From de76cce9636ee5bc88a9aee6531a32e0c9fcb3c7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:04:01 +0000 Subject: [PATCH 1/2] Bump @grpc/grpc-js from 1.14.4 to 1.14.6 Bumps [@grpc/grpc-js](https://github.com/grpc/grpc-node) from 1.14.4 to 1.14.6. - [Release notes](https://github.com/grpc/grpc-node/releases) - [Commits](https://github.com/grpc/grpc-node/compare/@grpc/grpc-js@1.14.4...@grpc/grpc-js@1.14.6) --- updated-dependencies: - dependency-name: "@grpc/grpc-js" dependency-version: 1.14.6 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- package-lock.json | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/package-lock.json b/package-lock.json index 00b6e1795..f051851e8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1359,9 +1359,10 @@ "dev": true }, "node_modules/@grpc/grpc-js": { - "version": "1.14.4", - "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz", - "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==", + "version": "1.14.6", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.6.tgz", + "integrity": "sha512-SgC/B3/VZ8lTyOZ4Cwk6f1skWhmkNAaVfiX90qd5u1rRXGKk1//8FTUEN9GvOUq7rfWIqAYkA3CoyumYVpOS6g==", + "license": "Apache-2.0", "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" @@ -12694,9 +12695,9 @@ "dev": true }, "@grpc/grpc-js": { - "version": "1.14.4", - "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz", - "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==", + "version": "1.14.6", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.6.tgz", + "integrity": "sha512-SgC/B3/VZ8lTyOZ4Cwk6f1skWhmkNAaVfiX90qd5u1rRXGKk1//8FTUEN9GvOUq7rfWIqAYkA3CoyumYVpOS6g==", "requires": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" From 8051bd6f64c77d285c243725331b5dda82332db8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:05:03 +0000 Subject: [PATCH 2/2] [dependabot skip] Update dist/ with build changes --- dist/cleanup.js | 777 ++++++++++++++++++++++++++++++++++-------------- dist/main.js | 777 ++++++++++++++++++++++++++++++++++-------------- 2 files changed, 1124 insertions(+), 430 deletions(-) diff --git a/dist/cleanup.js b/dist/cleanup.js index f5379175f..278fdffc7 100644 --- a/dist/cleanup.js +++ b/dist/cleanup.js @@ -47536,7 +47536,7 @@ var require_package2 = __commonJS({ "node_modules/@grpc/grpc-js/package.json"(exports2, module2) { module2.exports = { name: "@grpc/grpc-js", - version: "1.14.4", + version: "1.14.6", description: "gRPC Library for Node - pure JS implementation", homepage: "https://grpc.io/", repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", @@ -47709,6 +47709,9 @@ var require_logging = __commonJS({ var enabledTracers = /* @__PURE__ */ new Set(); var disabledTracers = /* @__PURE__ */ new Set(); for (const tracerName of tracersString.split(",")) { + if (tracerName.length === 0) { + continue; + } if (tracerName.startsWith("-")) { disabledTracers.add(tracerName.substring(1)); } else { @@ -47716,12 +47719,16 @@ var require_logging = __commonJS({ } } var allEnabled = enabledTracers.has("all"); + var anyTracerEnabled = allEnabled || enabledTracers.size > 0; function trace(severity, tracer, text) { if (isTracerEnabled(tracer)) { (0, exports2.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text); } } function isTracerEnabled(tracer) { + if (!anyTracerEnabled) { + return false; + } return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)); } } @@ -47799,7 +47806,6 @@ var require_metadata = __commonJS({ var Metadata = class _Metadata { constructor(options = {}) { this.internalRepr = /* @__PURE__ */ new Map(); - this.opaqueData = /* @__PURE__ */ new Map(); this.options = options; } /** @@ -47910,7 +47916,11 @@ var require_metadata = __commonJS({ if (key.startsWith(":")) { continue; } - result[key] = values.map(bufToString); + if (values.length === 1) { + result[key] = bufToString(values[0]); + } else { + result[key] = values.map(bufToString); + } } return result; } @@ -47934,6 +47944,9 @@ var require_metadata = __commonJS({ * @param value */ setOpaque(key, value) { + if (!this.opaqueData) { + this.opaqueData = /* @__PURE__ */ new Map(); + } this.opaqueData.set(key, value); } /** @@ -47942,7 +47955,8 @@ var require_metadata = __commonJS({ * @returns */ getOpaque(key) { - return this.opaqueData.get(key); + var _a; + return (_a = this.opaqueData) === null || _a === void 0 ? void 0 : _a.get(key); } /** * Returns a new Metadata object based fields in a given IncomingHttpHeaders @@ -48001,6 +48015,7 @@ var require_call_credentials = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CallCredentials = void 0; + exports2.isEmptyCallCredentials = isEmptyCallCredentials; var metadata_1 = require_metadata(); function isCurrentOauth2Client(client) { return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function"; @@ -48071,6 +48086,9 @@ var require_call_credentials = __commonJS({ return base; } compose(other) { + if (other instanceof EmptyCallCredentials) { + return this; + } return new _ComposedCallCredentials(this.creds.concat([other])); } _equals(other) { @@ -48101,6 +48119,9 @@ var require_call_credentials = __commonJS({ }); } compose(other) { + if (other instanceof EmptyCallCredentials) { + return this; + } return new ComposedCallCredentials([this, other]); } _equals(other) { @@ -48125,6 +48146,9 @@ var require_call_credentials = __commonJS({ return other instanceof _EmptyCallCredentials; } }; + function isEmptyCallCredentials(callCredentials) { + return callCredentials instanceof EmptyCallCredentials; + } } }); @@ -48160,6 +48184,8 @@ var require_uri_parser = __commonJS({ exports2.splitHostPort = splitHostPort; exports2.combineHostPort = combineHostPort; exports2.uriToString = uriToString; + exports2.extractServiceName = extractServiceName; + exports2.computeServiceUrl = computeServiceUrl; var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; function parseUri(uriString) { const parsedUri = URI_REGEX.exec(uriString); @@ -48242,6 +48268,23 @@ var require_uri_parser = __commonJS({ result += uri.path; return result; } + function extractServiceName(methodName) { + const firstSlashIndex = methodName.indexOf("/"); + if (firstSlashIndex === -1) { + return ""; + } + const secondSlashIndex = methodName.indexOf("/", firstSlashIndex + 1); + if (secondSlashIndex === -1) { + return methodName.substring(firstSlashIndex + 1); + } + return methodName.substring(firstSlashIndex + 1, secondSlashIndex); + } + function computeServiceUrl(host, methodName) { + var _a, _b; + const serviceName = extractServiceName(methodName); + const hostname = (_b = (_a = splitHostPort(host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; + return `https://${hostname}/${serviceName}`; + } } }); @@ -48389,6 +48432,7 @@ var require_channel_credentials = __commonJS({ return other instanceof _InsecureChannelCredentialsImpl; } _createSecureConnector(channelTarget, options, callCredentials) { + const credentials = callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); return { connect(socket) { return Promise.resolve({ @@ -48400,7 +48444,7 @@ var require_channel_credentials = __commonJS({ return Promise.resolve(); }, getCallCredentials: () => { - return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); + return credentials; }, destroy() { } @@ -49247,7 +49291,9 @@ var require_backoff_timeout = __commonJS({ this.maxDelay = options.maxDelay; } } - this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); + if (this.traceEnabled) { + this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); + } this.nextDelay = this.initialDelay; this.timerId = setTimeout(() => { }, 0); @@ -49256,12 +49302,19 @@ var require_backoff_timeout = __commonJS({ static getNextId() { return this.nextId++; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); + } } runTimer(delay) { var _a, _b; - this.trace("runTimer(delay=" + delay + ")"); + if (this.traceEnabled) { + this.trace("runTimer(delay=" + delay + ")"); + } this.endTime = this.startTime; this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); clearTimeout(this.timerId); @@ -49300,7 +49353,9 @@ var require_backoff_timeout = __commonJS({ * retroactively apply that reset to the current timer. */ reset() { - this.trace("reset() running=" + this.running); + if (this.traceEnabled) { + this.trace("reset() running=" + this.running); + } this.nextDelay = this.initialDelay; if (this.running) { const now = /* @__PURE__ */ new Date(); @@ -49487,6 +49542,7 @@ var require_resolving_load_balancer = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ResolvingLoadBalancer = void 0; + exports2.getDefaultConfigSelector = getDefaultConfigSelector; var load_balancer_1 = require_load_balancer(); var service_config_1 = require_service_config(); var connectivity_state_1 = require_connectivity_state(); @@ -49537,34 +49593,40 @@ var require_resolving_load_balancer = __commonJS({ } return null; } + var MAX_CACHED_METHOD_CONFIGS = 100; function getDefaultConfigSelector(serviceConfig) { + const methodConfigCache = /* @__PURE__ */ new Map(); return { - invoke(methodName, metadata) { + invoke(methodName, metadata, channelId) { var _a, _b; - const splitName = methodName.split("/").filter((x) => x.length > 0); - const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ""; - const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ""; - if (serviceConfig && serviceConfig.methodConfig) { - for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { - const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); - if (matchingConfig) { - return { - methodConfig: matchingConfig, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [] - }; + let matchingConfig = methodConfigCache.get(methodName); + if (matchingConfig === void 0) { + const splitName = methodName.split("/").filter((x) => x.length > 0); + const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ""; + const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ""; + matchingConfig = { name: [] }; + if (serviceConfig && serviceConfig.methodConfig) { + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const foundConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); + if (foundConfig) { + matchingConfig = foundConfig; + break; + } } } + if (methodConfigCache.size < MAX_CACHED_METHOD_CONFIGS) { + methodConfigCache.set(methodName, matchingConfig); + } } return { - methodConfig: { name: [] }, + methodConfig: matchingConfig, pickInformation: {}, status: constants_1.Status.OK, dynamicFilterFactories: [] }; }, unref() { + methodConfigCache.clear(); } }; } @@ -61374,6 +61436,7 @@ var require_channelz = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.registerChannelzSocket = exports2.registerChannelzServer = exports2.registerChannelzSubchannel = exports2.registerChannelzChannel = exports2.ChannelzCallTrackerStub = exports2.ChannelzCallTracker = exports2.ChannelzChildrenTrackerStub = exports2.ChannelzChildrenTracker = exports2.ChannelzTrace = exports2.ChannelzTraceStub = void 0; exports2.unregisterChannelzRef = unregisterChannelzRef; + exports2.dateToProtoTimestamp = dateToProtoTimestamp; exports2.getChannelzHandlers = getChannelzHandlers; exports2.getChannelzServiceDefinition = getChannelzServiceDefinition; exports2.setup = setup; @@ -61530,7 +61593,7 @@ var require_channelz = __commonJS({ } addCallStarted() { this.callsStarted += 1; - this.lastCallStartedTimestamp = /* @__PURE__ */ new Date(); + this.lastCallStartedTimestamp = Date.now(); } addCallSucceeded() { this.callsSucceeded += 1; @@ -61672,12 +61735,12 @@ var require_channelz = __commonJS({ } } function dateToProtoTimestamp(date) { - if (!date) { + if (date === null || date === void 0) { return null; } - const millisSinceEpoch = date.getTime(); + const millisSinceEpoch = typeof date === "number" ? date : date.getTime(); return { - seconds: millisSinceEpoch / 1e3 | 0, + seconds: Math.floor(millisSinceEpoch / 1e3), nanos: millisSinceEpoch % 1e3 * 1e6 }; } @@ -62332,7 +62395,7 @@ var require_deadline = __commonJS({ ["H", 60 * 60 * 1e3] ]; function getDeadlineTimeoutString(deadline) { - const now = (/* @__PURE__ */ new Date()).getTime(); + const now = Date.now(); if (deadline instanceof Date) { deadline = deadline.getTime(); } @@ -62348,7 +62411,7 @@ var require_deadline = __commonJS({ var MAX_TIMEOUT_TIME = 2147483647; function getRelativeTimeout(deadline) { const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; - const now = (/* @__PURE__ */ new Date()).getTime(); + const now = Date.now(); const timeout = deadlineMs - now; if (timeout < 0) { return 0; @@ -62371,7 +62434,9 @@ var require_deadline = __commonJS({ } } function formatDateDifference(startDate, endDate) { - return ((endDate.getTime() - startDate.getTime()) / 1e3).toFixed(3) + "s"; + const startMs = typeof startDate === "number" ? startDate : startDate.getTime(); + const endMs = typeof endDate === "number" ? endDate : endDate.getTime(); + return ((endMs - startMs) / 1e3).toFixed(3) + "s"; } } }); @@ -62466,7 +62531,6 @@ var require_single_subchannel_channel = __commonJS({ var uri_parser_1 = require_uri_parser(); var SubchannelCallWrapper = class { constructor(subchannel, method, filterStackFactory, options, callNumber) { - var _a, _b; this.subchannel = subchannel; this.method = method; this.options = options; @@ -62478,13 +62542,7 @@ var require_single_subchannel_channel = __commonJS({ this.pendingStatus = null; this.readFilterPending = false; this.writeFilterPending = false; - const splitPath = this.method.split("/"); - let serviceName = ""; - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; - this.serviceUrl = `https://${hostname}/${serviceName}`; + this.serviceUrl = (0, uri_parser_1.computeServiceUrl)(this.options.host, this.method); const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); if (timeout !== Infinity) { if (timeout <= 0) { @@ -62562,7 +62620,7 @@ var require_single_subchannel_channel = __commonJS({ } } }; - this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); + this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener, this.callNumber); if (this.readPending) { this.childCall.startRead(); } @@ -62732,7 +62790,9 @@ var require_subchannel = __commonJS({ } this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); this.channelzTrace.addTrace("CT_INFO", "Subchannel created"); - this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2)); + if (this.traceEnabled) { + this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2)); + } this.secureConnector = credentials._createSecureConnector(channelTarget, options); } getChannelzInfo() { @@ -62744,11 +62804,21 @@ var require_subchannel = __commonJS({ target: this.subchannelAddressString }; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } + get refTraceEnabled() { + return logging.isTracerEnabled("subchannel_refcount"); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } refTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.refTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } handleBackoffTimer() { if (this.continueConnecting) { @@ -62805,10 +62875,12 @@ var require_subchannel = __commonJS({ if (oldStates.indexOf(this.connectivityState) === -1) { return false; } - if (errorMessage) { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); - } else { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + if (this.traceEnabled) { + if (errorMessage) { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); + } else { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + } } if (this.channelzEnabled) { this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); @@ -62852,11 +62924,15 @@ var require_subchannel = __commonJS({ return true; } ref() { - this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); + if (this.refTraceEnabled) { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); + } this.refcount += 1; } unref() { - this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); + if (this.refTraceEnabled) { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); + } this.refcount -= 1; if (this.refcount === 0) { this.channelzTrace.addTrace("CT_INFO", "Shutting down"); @@ -62874,7 +62950,7 @@ var require_subchannel = __commonJS({ } return false; } - createCall(metadata, host, method, listener) { + createCall(metadata, host, method, listener, callId) { if (!this.transport) { throw new Error("Cannot create call, subchannel not READY"); } @@ -62894,7 +62970,7 @@ var require_subchannel = __commonJS({ } else { statsTracker = {}; } - return this.transport.createCall(metadata, host, method, listener, statsTracker); + return this.transport.createCall(metadata, host, method, listener, statsTracker, callId); } /** * If the subchannel is currently IDLE, start connecting and switch to the @@ -63000,9 +63076,11 @@ var require_environment = __commonJS({ "node_modules/@grpc/grpc-js/build/src/environment.js"(exports2) { "use strict"; var _a; + var _b; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; + exports2.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS = exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : "false") === "true"; + exports2.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS = ((_b = process.env.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) !== null && _b !== void 0 ? _b : "false") === "true"; } }); @@ -63673,11 +63751,13 @@ var require_subchannel_call = __commonJS({ const maxReceiveMessageLength = (_a = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); http2Stream.on("response", (headers, flags) => { - let headersString = ""; - for (const header of Object.keys(headers)) { - headersString += " " + header + ": " + headers[header] + "\n"; + if (this.traceEnabled) { + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += " " + header + ": " + headers[header] + "\n"; + } + this.trace("Received server headers:\n" + headersString); } - this.trace("Received server headers:\n" + headersString); this.httpStatusCode = headers[":status"]; if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { this.handleTrailers(headers); @@ -63703,7 +63783,9 @@ var require_subchannel_call = __commonJS({ if (this.statusOutput) { return; } - this.trace("receive HTTP/2 data frame of length " + data.length); + if (this.traceEnabled) { + this.trace("receive HTTP/2 data frame of length " + data.length); + } let messages; try { messages = this.decoder.write(data); @@ -63717,7 +63799,9 @@ var require_subchannel_call = __commonJS({ return; } for (const message of messages) { - this.trace("parsed message of length " + message.length); + if (this.traceEnabled) { + this.trace("parsed message of length " + message.length); + } this.callEventTracker.addMessageReceived(); this.tryPush(message); } @@ -63730,7 +63814,9 @@ var require_subchannel_call = __commonJS({ this.serverEndedCall = true; process.nextTick(() => { var _a2; - this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); + if (this.traceEnabled) { + this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); + } if (((_a2 = this.finalStatus) === null || _a2 === void 0 ? void 0 : _a2.code) === constants_1.Status.OK) { return; } @@ -63798,7 +63884,9 @@ var require_subchannel_call = __commonJS({ }); http2Stream.on("error", (err) => { if (err.code !== "ERR_HTTP2_STREAM_ERROR") { - this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); + if (this.traceEnabled) { + this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); + } this.internalError = err; } this.callEventTracker.onStreamEnd(false); @@ -63820,7 +63908,9 @@ var require_subchannel_call = __commonJS({ outputStatus() { if (!this.statusOutput) { this.statusOutput = true; - this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); + if (this.traceEnabled) { + this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); + } this.callEventTracker.onCallEnd(this.finalStatus); process.nextTick(() => { this.listener.onReceiveStatus(this.finalStatus); @@ -63828,8 +63918,13 @@ var require_subchannel_call = __commonJS({ this.http2Stream.resume(); } } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); + } } /** * On first call, emits a 'status' event with the given StatusObject. @@ -63851,7 +63946,9 @@ var require_subchannel_call = __commonJS({ } } push(message) { - this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); + if (this.traceEnabled) { + this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); + } this.canPush = false; this.isPushPending = true; process.nextTick(() => { @@ -63868,39 +63965,49 @@ var require_subchannel_call = __commonJS({ this.http2Stream.pause(); this.push(messageBytes); } else { - this.trace("unpushedReadMessages.push message of length " + messageBytes.length); + if (this.traceEnabled) { + this.trace("unpushedReadMessages.push message of length " + messageBytes.length); + } this.unpushedReadMessages.push(messageBytes); } } handleTrailers(headers) { this.serverEndedCall = true; this.callEventTracker.onStreamEnd(true); - let headersString = ""; - for (const header of Object.keys(headers)) { - headersString += " " + header + ": " + headers[header] + "\n"; + if (this.traceEnabled) { + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += " " + header + ": " + headers[header] + "\n"; + } + this.trace("Received server trailers:\n" + headersString); } - this.trace("Received server trailers:\n" + headersString); let metadata; try { metadata = metadata_1.Metadata.fromHttp2Headers(headers); } catch (e) { metadata = new metadata_1.Metadata(); } - const metadataMap = metadata.getMap(); + const statusValues = metadata.get("grpc-status"); let status; - if (typeof metadataMap["grpc-status"] === "string") { - const receivedStatus = Number(metadataMap["grpc-status"]); - this.trace("received status code " + receivedStatus + " from server"); + if (statusValues.length > 0 && typeof statusValues[0] === "string") { + const receivedStatus = Number(statusValues[0]); + if (this.traceEnabled) { + this.trace("received status code " + receivedStatus + " from server"); + } metadata.remove("grpc-status"); let details = ""; - if (typeof metadataMap["grpc-message"] === "string") { + const messageValues = metadata.get("grpc-message"); + if (messageValues.length > 0 && typeof messageValues[0] === "string") { + const messageString = messageValues[0]; try { - details = decodeURI(metadataMap["grpc-message"]); - } catch (e) { - details = metadataMap["grpc-message"]; + details = decodeURI(messageString); + } catch (error2) { + details = messageString; } metadata.remove("grpc-message"); - this.trace('received status details string "' + details + '" from server'); + if (this.traceEnabled) { + this.trace('received status details string "' + details + '" from server'); + } } status = { code: receivedStatus, @@ -63925,7 +64032,9 @@ var require_subchannel_call = __commonJS({ return; } if (this.serverEndedCall) { - this.http2Stream.end(); + if (!this.http2Stream.writableEnded) { + this.http2Stream.end(); + } } else { let code; if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { @@ -63933,12 +64042,16 @@ var require_subchannel_call = __commonJS({ } else { code = http2.constants.NGHTTP2_CANCEL; } - this.trace("close http2 stream with code " + code); + if (this.traceEnabled) { + this.trace("close http2 stream with code " + code); + } this.http2Stream.close(code); } } cancelWithStatus(status, details) { - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); } getStatus() { @@ -63968,7 +64081,9 @@ var require_subchannel_call = __commonJS({ this.http2Stream.resume(); } sendMessageWithContext(context, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } const cb = (error2) => { process.nextTick(() => { var _a; @@ -63982,7 +64097,9 @@ var require_subchannel_call = __commonJS({ (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); }); }; - this.trace("sending data chunk of length " + message.length); + if (this.traceEnabled) { + this.trace("sending data chunk of length " + message.length); + } this.callEventTracker.addMessageSent(); try { this.http2Stream.write(message, cb); @@ -63996,6 +64113,9 @@ var require_subchannel_call = __commonJS({ } halfClose() { this.trace("end() called"); + if (this.http2Stream.destroyed || this.http2Stream.writableEnded) { + return; + } this.trace("calling end() on HTTP/2 stream"); this.http2Stream.end(); } @@ -64081,18 +64201,24 @@ var require_transport = __commonJS({ if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) { tooManyPings = true; } - this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + if (this.traceEnabled) { + this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + } this.reportDisconnectToOwner(tooManyPings); }); session.once("error", (error2) => { - this.trace("connection closed with error " + error2.message); + if (this.traceEnabled) { + this.trace("connection closed with error " + error2.message); + } this.handleDisconnect(); }); session.socket.once("close", (hadError) => { - this.trace("connection closed. hadError=" + hadError); + if (this.traceEnabled) { + this.trace("connection closed. hadError=" + hadError); + } this.handleDisconnect(); }); - if (logging.isTracerEnabled(TRACER_NAME)) { + if (this.traceEnabled) { session.on("remoteSettings", (settings) => { this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); }); @@ -64103,7 +64229,7 @@ var require_transport = __commonJS({ if (this.keepaliveWithoutCalls) { this.maybeStartKeepalivePingTimer(); } - if (session.socket instanceof tls_1.TLSSocket) { + if (session.socket instanceof tls_1.TLSSocket && session.socket.authorized) { this.authContext = { transportSecurityType: "ssl", sslPeerCertificate: session.socket.getPeerCertificate() @@ -64152,17 +64278,37 @@ var require_transport = __commonJS({ }; return socketInfo; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } + get keepaliveTraceEnabled() { + return logging.isTracerEnabled("keepalive"); + } + get flowControlTraceEnabled() { + return logging.isTracerEnabled(FLOW_CONTROL_TRACER_NAME); + } + get internalsTraceEnabled() { + return logging.isTracerEnabled("transport_internals"); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.keepaliveTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } flowControlTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.flowControlTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } internalsTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.internalsTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } /** * Indicate to the owner of this object that this transport should no longer @@ -64212,7 +64358,9 @@ var require_transport = __commonJS({ if (this.channelzEnabled) { this.keepalivesSent += 1; } - this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + if (this.keepaliveTraceEnabled) { + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + } this.keepaliveTimer = setTimeout(() => { this.keepaliveTimer = null; this.keepaliveTrace("Ping timeout passed without response"); @@ -64224,7 +64372,9 @@ var require_transport = __commonJS({ const pingSentSuccessfully = this.session.ping((err, duration, payload) => { this.clearKeepaliveTimeout(); if (err) { - this.keepaliveTrace("Ping failed with error " + err.message); + if (this.keepaliveTraceEnabled) { + this.keepaliveTrace("Ping failed with error " + err.message); + } this.handleDisconnect(); } else { this.keepaliveTrace("Received ping response"); @@ -64238,7 +64388,9 @@ var require_transport = __commonJS({ pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; } if (pingSendError) { - this.keepaliveTrace("Ping send failed: " + pingSendError); + if (this.keepaliveTraceEnabled) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + } this.handleDisconnect(); } } @@ -64289,7 +64441,7 @@ var require_transport = __commonJS({ } } } - createCall(metadata, host, method, listener, subchannelCallStatsTracker) { + createCall(metadata, host, method, listener, subchannelCallStatsTracker, callId) { const headers = metadata.toHttp2Headers(); headers[HTTP2_HEADER_AUTHORITY] = host; headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; @@ -64304,8 +64456,12 @@ var require_transport = __commonJS({ this.handleDisconnect(); throw e; } - this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); - this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); + if (this.flowControlTraceEnabled) { + this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); + } + if (this.internalsTraceEnabled) { + this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); + } let eventTracker; let call; if (this.channelzEnabled) { @@ -64314,13 +64470,13 @@ var require_transport = __commonJS({ addMessageSent: () => { var _a; this.messagesSent += 1; - this.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); + this.lastMessageSentTimestamp = Date.now(); (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); }, addMessageReceived: () => { var _a; this.messagesReceived += 1; - this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); + this.lastMessageReceivedTimestamp = Date.now(); (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); }, onCallEnd: (status) => { @@ -64359,7 +64515,7 @@ var require_transport = __commonJS({ } }; } - call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); + call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, callId !== null && callId !== void 0 ? callId : (0, call_number_1.getNextCallNumber)()); this.addActiveCall(call); return call; } @@ -64386,8 +64542,13 @@ var require_transport = __commonJS({ this.session = null; this.isShutdown = false; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); + } } createSession(secureConnectResult, address, options) { if (this.isShutdown) { @@ -64424,7 +64585,9 @@ var require_transport = __commonJS({ var _a2; (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy(); errorMessage = error2.message; - this.trace("connection failed with error " + errorMessage); + if (this.traceEnabled) { + this.trace("connection failed with error " + errorMessage); + } if (!reportedError) { reportedError = true; reject(`${errorMessage} (${(/* @__PURE__ */ new Date()).toISOString()})`); @@ -64505,14 +64668,22 @@ var require_transport = __commonJS({ let secureConnectResult = null; const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); try { - this.trace(addressString + " Waiting for secureConnector to be ready"); + if (this.traceEnabled) { + this.trace(addressString + " Waiting for secureConnector to be ready"); + } await secureConnector.waitForReady(); - this.trace(addressString + " secureConnector is ready"); + if (this.traceEnabled) { + this.trace(addressString + " secureConnector is ready"); + } tcpConnection = await this.tcpConnect(address, options); tcpConnection.setNoDelay(); - this.trace(addressString + " Established TCP connection"); + if (this.traceEnabled) { + this.trace(addressString + " Established TCP connection"); + } secureConnectResult = await secureConnector.connect(tcpConnection); - this.trace(addressString + " Established secure connection"); + if (this.traceEnabled) { + this.trace(addressString + " Established secure connection"); + } return this.createSession(secureConnectResult, address, options); } catch (e) { tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); @@ -64635,19 +64806,19 @@ var require_load_balancing_call = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LoadBalancingCall = void 0; + var call_credentials_1 = require_call_credentials(); var connectivity_state_1 = require_connectivity_state(); var constants_1 = require_constants7(); var deadline_1 = require_deadline(); var metadata_1 = require_metadata(); var picker_1 = require_picker(); - var uri_parser_1 = require_uri_parser(); var logging = require_logging(); var control_plane_status_1 = require_control_plane_status(); var http2 = require("http2"); var TRACER_NAME = "load_balancing_call"; + var RESOLVED_EMPTY_METADATA = Promise.resolve(void 0); var LoadBalancingCall = class { constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { - var _a, _b; this.channel = channel; this.callConfig = callConfig; this.methodName = methodName; @@ -64664,19 +64835,13 @@ var require_load_balancing_call = __commonJS({ this.listener = null; this.onCallEnded = null; this.childStartTime = null; - const splitPath = this.methodName.split("/"); - let serviceName = ""; - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; - this.serviceUrl = `https://${hostname}/${serviceName}`; - this.startTime = /* @__PURE__ */ new Date(); + this.serviceUrl = this.channel.getServiceUrl(this.host, this.methodName); + this.startTime = Date.now(); } getDeadlineInfo() { var _a, _b; const deadlineInfo = []; - if (this.childStartTime) { + if (this.childStartTime !== null) { if (this.childStartTime > this.startTime) { if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { deadlineInfo.push("wait_for_ready"); @@ -64693,19 +64858,36 @@ var require_load_balancing_call = __commonJS({ } return deadlineInfo; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + } + getSubchannelString(subchannel) { + return subchannel ? "(" + subchannel.getChannelzRef().id + ") " + subchannel.getAddress() : "" + subchannel; } outputStatus(status, progress) { var _a, _b; if (!this.ended) { this.ended = true; - this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString()); + if (this.traceEnabled) { + this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + new Date(this.startTime).toISOString()); + } const finalStatus = Object.assign(Object.assign({}, status), { progress }); (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); + this.channel.removeCallFromPickQueue(this); } } + generateCallCredentialsMetadata(callCredentials) { + return (0, call_credentials_1.isEmptyCallCredentials)(callCredentials) ? RESOLVED_EMPTY_METADATA : callCredentials.generateMetadata({ + method_name: this.methodName, + service_url: this.serviceUrl + }); + } doPick() { var _a, _b; if (this.ended) { @@ -64717,18 +64899,20 @@ var require_load_balancing_call = __commonJS({ this.trace("Pick called"); const finalMetadata = this.metadata.clone(); const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); - const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel; - this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + if (this.traceEnabled) { + this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + this.getSubchannelString(pickResult.subchannel) + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + } switch (pickResult.pickResultType) { case picker_1.PickResultType.COMPLETE: - const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); - combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => { + this.generateCallCredentialsMetadata(this.credentials.compose(pickResult.subchannel.getCallCredentials())).then((credsMetadata) => { var _a2; if (this.ended) { this.trace("Credentials metadata generation finished after call ended"); return; } - finalMetadata.merge(credsMetadata); + if (credsMetadata) { + finalMetadata.merge(credsMetadata); + } if (finalMetadata.get("authorization").length > 1) { this.outputStatus({ code: constants_1.Status.INTERNAL, @@ -64737,7 +64921,9 @@ var require_load_balancing_call = __commonJS({ }, "PROCESSED"); } if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); + if (this.traceEnabled) { + this.trace("Picked subchannel " + this.getSubchannelString(pickResult.subchannel) + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); + } this.doPick(); return; } @@ -64762,10 +64948,12 @@ var require_load_balancing_call = __commonJS({ this.outputStatus(status, "PROCESSED"); } } - }); - this.childStartTime = /* @__PURE__ */ new Date(); + }, this.callNumber); + this.childStartTime = Date.now(); } catch (error2) { - this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error2.message); + if (this.traceEnabled) { + this.trace("Failed to start call on picked subchannel " + this.getSubchannelString(pickResult.subchannel) + " with error " + error2.message); + } this.outputStatus({ code: constants_1.Status.INTERNAL, details: "Failed to start HTTP/2 stream with error " + error2.message, @@ -64775,7 +64963,9 @@ var require_load_balancing_call = __commonJS({ } (_a2 = pickResult.onCallStarted) === null || _a2 === void 0 ? void 0 : _a2.call(pickResult); this.onCallEnded = pickResult.onCallEnded; - this.trace("Created child call [" + this.child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Created child call [" + this.child.getCallNumber() + "]"); + } if (this.readPending) { this.child.startRead(); } @@ -64816,7 +65006,9 @@ var require_load_balancing_call = __commonJS({ } cancelWithStatus(status, details) { var _a; - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED"); } @@ -64831,7 +65023,9 @@ var require_load_balancing_call = __commonJS({ this.doPick(); } sendMessageWithContext(context, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } if (this.child) { this.child.sendMessageWithContext(context, message); } else { @@ -64902,8 +65096,7 @@ var require_resolving_call = __commonJS({ this.metadata = null; this.listener = null; this.statusWatchers = []; - this.deadlineTimer = setTimeout(() => { - }, 0); + this.deadlineTimer = null; this.filterStack = null; this.deadlineStartTime = null; this.configReceivedTime = null; @@ -64918,36 +65111,51 @@ var require_resolving_call = __commonJS({ }); } if (options.flags & constants_1.Propagate.DEADLINE) { - this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); + if (this.traceEnabled) { + this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); + } this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); } } this.trace("Created"); this.runDeadlineTimer(); } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } } runDeadlineTimer() { - clearTimeout(this.deadlineTimer); - this.deadlineStartTime = /* @__PURE__ */ new Date(); - this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + this.deadlineTimer = null; + } + this.deadlineStartTime = Date.now(); + if (this.traceEnabled) { + this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); + } const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); if (timeout !== Infinity) { - this.trace("Deadline will be reached in " + timeout + "ms"); + if (this.traceEnabled) { + this.trace("Deadline will be reached in " + timeout + "ms"); + } const handleDeadline = () => { - if (!this.deadlineStartTime) { + this.deadlineTimer = null; + if (this.deadlineStartTime === null) { this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); return; } const deadlineInfo = []; - const deadlineEndTime = /* @__PURE__ */ new Date(); + const deadlineEndTime = Date.now(); deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); - if (this.configReceivedTime) { + if (this.configReceivedTime !== null) { if (this.configReceivedTime > this.deadlineStartTime) { deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); } - if (this.childStartTime) { + if (this.childStartTime !== null) { if (this.childStartTime > this.configReceivedTime) { deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); } @@ -64975,9 +65183,14 @@ var require_resolving_call = __commonJS({ if (!this.filterStack) { this.filterStack = this.filterStackFactory.createFilter(); } - clearTimeout(this.deadlineTimer); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + this.deadlineTimer = null; + } const filteredStatus = this.filterStack.receiveTrailers(status); - this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); + if (this.traceEnabled) { + this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); + } this.statusWatchers.forEach((watcher) => watcher(filteredStatus)); process.nextTick(() => { var _a; @@ -64998,7 +65211,8 @@ var require_resolving_call = __commonJS({ child.halfClose(); } }, (status) => { - this.cancelWithStatus(status.code, status.details); + var _a, _b; + this.cancelWithStatus((_a = status.code) !== null && _a !== void 0 ? _a : constants_1.Status.INTERNAL, (_b = status.details) !== null && _b !== void 0 ? _b : "Failed to write message"); }); } getConfig() { @@ -65020,7 +65234,7 @@ var require_resolving_call = __commonJS({ } return; } - this.configReceivedTime = /* @__PURE__ */ new Date(); + this.configReceivedTime = Date.now(); const config = configResult.config; if (config.status !== constants_1.Status.OK) { const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method); @@ -65032,18 +65246,19 @@ var require_resolving_call = __commonJS({ return; } if (config.methodConfig.timeout) { - const configDeadline = /* @__PURE__ */ new Date(); - configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); - configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6); + const timeoutMs = Math.floor(config.methodConfig.timeout.seconds * 1e3 + config.methodConfig.timeout.nanos / 1e6); + const configDeadline = Date.now() + timeoutMs; this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); this.runDeadlineTimer(); } this.filterStackFactory.push(config.dynamicFilterFactories); this.filterStack = this.filterStackFactory.createFilter(); this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => { - this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); - this.trace("Created child [" + this.child.getCallNumber() + "]"); - this.childStartTime = /* @__PURE__ */ new Date(); + this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline, this.callNumber); + if (this.traceEnabled) { + this.trace("Created child [" + this.child.getCallNumber() + "]"); + } + this.childStartTime = Date.now(); this.child.start(filteredMetadata, { onReceiveMetadata: (metadata) => { this.trace("Received metadata"); @@ -65094,7 +65309,9 @@ var require_resolving_call = __commonJS({ } cancelWithStatus(status, details) { var _a; - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); this.outputStatus({ code: status, @@ -65113,7 +65330,9 @@ var require_resolving_call = __commonJS({ this.getConfig(); } sendMessageWithContext(context, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } if (this.child) { this.sendMessageOnChild(context, message); } else { @@ -65167,6 +65386,7 @@ var require_retrying_call = __commonJS({ var deadline_1 = require_deadline(); var metadata_1 = require_metadata(); var logging = require_logging(); + var call_number_1 = require_call_number(); var TRACER_NAME = "retrying_call"; var RetryThrottler = class { constructor(maxTokens, tokenRatio, previousRetryThrottler) { @@ -65271,7 +65491,7 @@ var require_retrying_call = __commonJS({ this.state = "TRANSPARENT_ONLY"; this.maxAttempts = 1; } - this.startTime = /* @__PURE__ */ new Date(); + this.startTime = Date.now(); } getDeadlineInfo() { if (this.underlyingCalls.length === 0) { @@ -65291,11 +65511,18 @@ var require_retrying_call = __commonJS({ getCallNumber() { return this.callNumber; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } } reportStatus(statusObject) { - this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString()); + if (this.traceEnabled) { + this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + new Date(this.startTime).toISOString()); + } this.bufferTracker.freeAll(this.callNumber); this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; this.writeBuffer = []; @@ -65309,7 +65536,9 @@ var require_retrying_call = __commonJS({ }); } cancelWithStatus(status, details) { - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); for (const { call } of this.underlyingCalls) { call.cancelWithStatus(status, details); @@ -65356,7 +65585,9 @@ var require_retrying_call = __commonJS({ if (this.state === "COMMITTED") { return; } - this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); + if (this.traceEnabled) { + this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); + } this.state = "COMMITTED"; (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); this.committedCallIndex = index; @@ -65523,7 +65754,9 @@ var require_retrying_call = __commonJS({ if (this.underlyingCalls[callIndex].state === "COMPLETED") { return; } - this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); + if (this.traceEnabled) { + this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); + } this.underlyingCalls[callIndex].state = "COMPLETED"; if (status.code === constants_1.Status.OK) { (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); @@ -65599,24 +65832,30 @@ var require_retrying_call = __commonJS({ (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); } startNewAttempt() { - const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); - this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); + const childCallNumber = this.underlyingCalls.length > 0 ? (0, call_number_1.getNextCallNumber)() : this.callNumber; + const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline, childCallNumber); + if (this.traceEnabled) { + this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); + } const index = this.underlyingCalls.length; this.underlyingCalls.push({ state: "ACTIVE", call: child, nextMessageToSend: 0, - startTime: /* @__PURE__ */ new Date() + startTime: Date.now() }); const previousAttempts = this.attempts - 1; - const initialMetadata = this.initialMetadata.clone(); + let initialMetadata = this.initialMetadata; if (previousAttempts > 0) { + initialMetadata = initialMetadata.clone(); initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); } let receivedMetadata = false; child.start(initialMetadata, { onReceiveMetadata: (metadata) => { - this.trace("Received metadata from child [" + child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Received metadata from child [" + child.getCallNumber() + "]"); + } this.commitCall(index); receivedMetadata = true; if (previousAttempts > 0) { @@ -65627,14 +65866,18 @@ var require_retrying_call = __commonJS({ } }, onReceiveMessage: (message) => { - this.trace("Received message from child [" + child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Received message from child [" + child.getCallNumber() + "]"); + } this.commitCall(index); if (this.underlyingCalls[index].state === "ACTIVE") { this.listener.onReceiveMessage(message); } }, onReceiveStatus: (status) => { - this.trace("Received status from child [" + child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Received status from child [" + child.getCallNumber() + "]"); + } if (!receivedMetadata && previousAttempts > 0) { status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); } @@ -65679,7 +65922,9 @@ var require_retrying_call = __commonJS({ }, bufferEntry.message.message); const nextEntry = this.getBufferEntry(messageIndex + 1); if (nextEntry.entryType === "HALF_CLOSE") { - this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); + if (this.traceEnabled) { + this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); + } childCall.nextMessageToSend += 1; childCall.call.halfClose(); } @@ -65694,7 +65939,9 @@ var require_retrying_call = __commonJS({ } } sendMessageWithContext(context, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } const writeObj = { message, flags: context.flags @@ -65755,7 +66002,9 @@ var require_retrying_call = __commonJS({ for (const call of this.underlyingCalls) { if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") { if (call.nextMessageToSend === halfCloseIndex || call.nextMessageToSend === halfCloseIndex - 1) { - this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); + if (this.traceEnabled) { + this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); + } call.nextMessageToSend += 1; call.call.halfClose(); } @@ -65977,7 +66226,7 @@ var require_internal_channel = __commonJS({ }; } }; - var InternalChannel = class { + var InternalChannel = class _InternalChannel { constructor(target, credentials, options) { var _a, _b, _c, _d, _e, _f; this.credentials = credentials; @@ -65985,7 +66234,7 @@ var require_internal_channel = __commonJS({ this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; this.currentPicker = new picker_1.UnavailablePicker(); this.configSelectionQueue = []; - this.pickQueue = []; + this.pickQueue = /* @__PURE__ */ new Set(); this.connectivityStateWatchers = []; this.callRefTimer = null; this.configSelector = null; @@ -65995,6 +66244,7 @@ var require_internal_channel = __commonJS({ this.idleTimer = null; this.channelzEnabled = true; this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + this.serviceUrlCache = /* @__PURE__ */ new Map(); if (typeof target !== "string") { throw new TypeError("Channel target must be a string"); } @@ -66052,9 +66302,9 @@ var require_internal_channel = __commonJS({ }, updateState: (connectivityState, picker) => { this.currentPicker = picker; - const queueCopy = this.pickQueue.slice(); - this.pickQueue = []; - if (queueCopy.length > 0) { + const queueCopy = this.pickQueue; + this.pickQueue = /* @__PURE__ */ new Set(); + if (queueCopy.size > 0) { this.callRefTimerUnref(); } for (const call of queueCopy) { @@ -66121,15 +66371,22 @@ var require_internal_channel = __commonJS({ this.filterStackFactory = new filter_stack_1.FilterStackFactory([ new compression_filter_1.CompressionFilterFactory(this, this.options) ]); - this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2)); - const error2 = new Error(); + if (this.traceEnabled) { + this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2)); + } if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) { + const error2 = new Error(); (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") Channel constructed \n" + ((_f = error2.stack) === null || _f === void 0 ? void 0 : _f.substring(error2.stack.indexOf("\n") + 1))); } - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.lastActivityTimestamp = Date.now(); + } + get traceEnabled() { + return (0, logging_1.isTracerEnabled)("channel"); } trace(text, verbosityOverride) { - (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); + if (this.traceEnabled) { + (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); + } } callRefTimerRef() { var _a, _b, _c, _d; @@ -66138,14 +66395,18 @@ var require_internal_channel = __commonJS({ }, MAX_TIMEOUT_TIME); } if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { - this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + if (this.traceEnabled) { + this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.size); + } (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); } } callRefTimerUnref() { var _a, _b, _c; if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { - this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + if (this.traceEnabled) { + this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.size); + } (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); } } @@ -66197,9 +66458,15 @@ var require_internal_channel = __commonJS({ }); } queueCallForPick(call) { - this.pickQueue.push(call); + this.pickQueue.add(call); this.callRefTimerRef(); } + removeCallFromPickQueue(call) { + this.pickQueue.delete(call); + if (this.pickQueue.size === 0) { + this.callRefTimerUnref(); + } + } getConfig(method, metadata) { if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { this.resolvingLoadBalancer.exitIdle(); @@ -66246,8 +66513,8 @@ var require_internal_channel = __commonJS({ this.startIdleTimeout(this.idleTimeoutMs); return; } - const now = /* @__PURE__ */ new Date(); - const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); + const now = Date.now(); + const timeSinceLastActivity = now - this.lastActivityTimestamp; if (timeSinceLastActivity >= this.idleTimeoutMs) { this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity"); this.enterIdle(); @@ -66277,22 +66544,54 @@ var require_internal_channel = __commonJS({ } } this.callCount -= 1; - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.lastActivityTimestamp = Date.now(); this.maybeStartIdleTimer(); } - createLoadBalancingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"'); - return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); + /** + * Returns the precomputed service URL (`https://${hostname}/${serviceName}`) + * for the given host and method, using a bounded cache to avoid parsing on + * every RPC. + */ + getServiceUrl(host, methodName) { + let methodMap = this.serviceUrlCache.get(host); + if (methodMap === void 0) { + if (this.serviceUrlCache.size < _InternalChannel.MAX_CACHED_HOSTS) { + methodMap = /* @__PURE__ */ new Map(); + this.serviceUrlCache.set(host, methodMap); + } + } + if (methodMap !== void 0) { + const serviceUrl = methodMap.get(methodName); + if (serviceUrl !== void 0) { + return serviceUrl; + } + const computedServiceUrl = (0, uri_parser_1.computeServiceUrl)(host, methodName); + if (methodMap.size < _InternalChannel.MAX_METHODS_PER_HOST) { + methodMap.set(methodName, computedServiceUrl); + } + return computedServiceUrl; + } + return (0, uri_parser_1.computeServiceUrl)(host, methodName); } - createRetryingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"'); - return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); + createLoadBalancingCall(callConfig, method, host, credentials, deadline, callNumber) { + const finalCallNumber = callNumber !== null && callNumber !== void 0 ? callNumber : (0, call_number_1.getNextCallNumber)(); + if (this.traceEnabled) { + this.trace("createLoadBalancingCall [" + finalCallNumber + '] method="' + method + '"'); + } + return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, finalCallNumber); + } + createRetryingCall(callConfig, method, host, credentials, deadline, callNumber) { + const finalCallNumber = callNumber !== null && callNumber !== void 0 ? callNumber : (0, call_number_1.getNextCallNumber)(); + if (this.traceEnabled) { + this.trace("createRetryingCall [" + finalCallNumber + '] method="' + method + '"'); + } + return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, finalCallNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); } createResolvingCall(method, deadline, host, parentCall, propagateFlags) { const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); + if (this.traceEnabled) { + this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); + } const finalOptions = { deadline, flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, @@ -66318,7 +66617,7 @@ var require_internal_channel = __commonJS({ for (const call of this.pickQueue) { call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); } - this.pickQueue = []; + this.pickQueue.clear(); if (this.callRefTimer) { clearInterval(this.callRefTimer); } @@ -66331,6 +66630,7 @@ var require_internal_channel = __commonJS({ this.subchannelPool.unrefUnusedSubchannels(); (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); this.configSelector = null; + this.serviceUrlCache.clear(); } getTarget() { return (0, uri_parser_1.uriToString)(this.target); @@ -66339,7 +66639,7 @@ var require_internal_channel = __commonJS({ const connectivityState = this.connectivityState; if (tryToConnect) { this.resolvingLoadBalancer.exitIdle(); - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.lastActivityTimestamp = Date.now(); this.maybeStartIdleTimer(); } return connectivityState; @@ -66393,6 +66693,8 @@ var require_internal_channel = __commonJS({ } }; exports2.InternalChannel = InternalChannel; + InternalChannel.MAX_CACHED_HOSTS = 5; + InternalChannel.MAX_METHODS_PER_HOST = 100; } }); @@ -67325,6 +67627,7 @@ var require_server_interceptors = __commonJS({ var logging = require_logging(); var tls_1 = require("tls"); var orca_1 = require_orca(); + var environment_1 = require_environment(); var TRACER_NAME = "server_call"; function trace(text) { logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); @@ -67723,8 +68026,7 @@ var require_server_interceptors = __commonJS({ return; } const timeout = +match[1] * deadlineUnitsToMs[match[2]] | 0; - const now = /* @__PURE__ */ new Date(); - this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadline = Date.now() + timeout; this.deadlineTimer = setTimeout(() => { const status = { code: constants_1.Status.DEADLINE_EXCEEDED, @@ -67840,9 +68142,15 @@ var require_server_interceptors = __commonJS({ try { queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Error deserializing request: ${err.message}`; + } else { + details = "Error deserializing request"; + } this.sendStatus({ code: constants_1.Status.INTERNAL, - details: `Error deserializing request: ${err.message}` + details }); return; } @@ -67922,9 +68230,15 @@ var require_server_interceptors = __commonJS({ try { response = this.serializeMessage(message); } catch (e) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`; + } else { + details = "Error serializing response"; + } this.sendStatus({ code: constants_1.Status.INTERNAL, - details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, + details, metadata: null }); return; @@ -67942,9 +68256,15 @@ var require_server_interceptors = __commonJS({ this.stream.write(response, (error2) => { var _a; if (error2) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Error writing message: ${(0, error_1.getErrorMessage)(error2)}`; + } else { + details = "Internal server error"; + } this.sendStatus({ code: constants_1.Status.INTERNAL, - details: `Error writing message: ${(0, error_1.getErrorMessage)(error2)}`, + details, metadata: null }); return; @@ -68026,15 +68346,17 @@ var require_server_interceptors = __commonJS({ } getAuthContext() { var _a; - if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { - const peerCertificate = this.stream.session.socket.getPeerCertificate(); - return { - transportSecurityType: "ssl", - sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0 - }; - } else { + if (!(((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket)) { + return {}; + } + if (!this.stream.session.socket.authorized) { return {}; } + const peerCertificate = this.stream.session.socket.getPeerCertificate(); + return { + transportSecurityType: "ssl", + sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0 + }; } getConnectionInfo() { return this.connectionInfo; @@ -68116,6 +68438,7 @@ var require_server2 = __commonJS({ var uri_parser_1 = require_uri_parser(); var channelz_1 = require_channelz(); var server_interceptors_1 = require_server_interceptors(); + var environment_1 = require_environment(); var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); var KEEPALIVE_TIMEOUT_MS = 2e4; @@ -68922,13 +69245,13 @@ var require_server2 = __commonJS({ addMessageSent: () => { if (channelzSessionInfo) { channelzSessionInfo.messagesSent += 1; - channelzSessionInfo.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); + channelzSessionInfo.lastMessageSentTimestamp = Date.now(); } }, addMessageReceived: () => { if (channelzSessionInfo) { channelzSessionInfo.messagesReceived += 1; - channelzSessionInfo.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); + channelzSessionInfo.lastMessageReceivedTimestamp = Date.now(); } }, onCallEnd: (status) => { @@ -69369,9 +69692,15 @@ var require_server2 = __commonJS({ try { handler.func(stream, respond); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } @@ -69405,9 +69734,15 @@ var require_server2 = __commonJS({ try { handler.func(stream, respond); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } @@ -69461,9 +69796,15 @@ var require_server2 = __commonJS({ try { handler.func(stream); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } @@ -69485,9 +69826,15 @@ var require_server2 = __commonJS({ try { handler.func(stream); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } diff --git a/dist/main.js b/dist/main.js index eb8e392a8..df6f068c3 100644 --- a/dist/main.js +++ b/dist/main.js @@ -48308,7 +48308,7 @@ var require_package2 = __commonJS({ "node_modules/@grpc/grpc-js/package.json"(exports2, module2) { module2.exports = { name: "@grpc/grpc-js", - version: "1.14.4", + version: "1.14.6", description: "gRPC Library for Node - pure JS implementation", homepage: "https://grpc.io/", repository: "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", @@ -48481,6 +48481,9 @@ var require_logging = __commonJS({ var enabledTracers = /* @__PURE__ */ new Set(); var disabledTracers = /* @__PURE__ */ new Set(); for (const tracerName of tracersString.split(",")) { + if (tracerName.length === 0) { + continue; + } if (tracerName.startsWith("-")) { disabledTracers.add(tracerName.substring(1)); } else { @@ -48488,12 +48491,16 @@ var require_logging = __commonJS({ } } var allEnabled = enabledTracers.has("all"); + var anyTracerEnabled = allEnabled || enabledTracers.size > 0; function trace(severity, tracer, text) { if (isTracerEnabled(tracer)) { (0, exports2.log)(severity, (/* @__PURE__ */ new Date()).toISOString() + " | v" + clientVersion + " " + process_1.pid + " | " + tracer + " | " + text); } } function isTracerEnabled(tracer) { + if (!anyTracerEnabled) { + return false; + } return !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)); } } @@ -48571,7 +48578,6 @@ var require_metadata = __commonJS({ var Metadata = class _Metadata { constructor(options = {}) { this.internalRepr = /* @__PURE__ */ new Map(); - this.opaqueData = /* @__PURE__ */ new Map(); this.options = options; } /** @@ -48682,7 +48688,11 @@ var require_metadata = __commonJS({ if (key.startsWith(":")) { continue; } - result[key] = values.map(bufToString); + if (values.length === 1) { + result[key] = bufToString(values[0]); + } else { + result[key] = values.map(bufToString); + } } return result; } @@ -48706,6 +48716,9 @@ var require_metadata = __commonJS({ * @param value */ setOpaque(key, value) { + if (!this.opaqueData) { + this.opaqueData = /* @__PURE__ */ new Map(); + } this.opaqueData.set(key, value); } /** @@ -48714,7 +48727,8 @@ var require_metadata = __commonJS({ * @returns */ getOpaque(key) { - return this.opaqueData.get(key); + var _a; + return (_a = this.opaqueData) === null || _a === void 0 ? void 0 : _a.get(key); } /** * Returns a new Metadata object based fields in a given IncomingHttpHeaders @@ -48773,6 +48787,7 @@ var require_call_credentials = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.CallCredentials = void 0; + exports2.isEmptyCallCredentials = isEmptyCallCredentials; var metadata_1 = require_metadata(); function isCurrentOauth2Client(client) { return "getRequestHeaders" in client && typeof client.getRequestHeaders === "function"; @@ -48843,6 +48858,9 @@ var require_call_credentials = __commonJS({ return base; } compose(other) { + if (other instanceof EmptyCallCredentials) { + return this; + } return new _ComposedCallCredentials(this.creds.concat([other])); } _equals(other) { @@ -48873,6 +48891,9 @@ var require_call_credentials = __commonJS({ }); } compose(other) { + if (other instanceof EmptyCallCredentials) { + return this; + } return new ComposedCallCredentials([this, other]); } _equals(other) { @@ -48897,6 +48918,9 @@ var require_call_credentials = __commonJS({ return other instanceof _EmptyCallCredentials; } }; + function isEmptyCallCredentials(callCredentials) { + return callCredentials instanceof EmptyCallCredentials; + } } }); @@ -48932,6 +48956,8 @@ var require_uri_parser = __commonJS({ exports2.splitHostPort = splitHostPort; exports2.combineHostPort = combineHostPort; exports2.uriToString = uriToString; + exports2.extractServiceName = extractServiceName; + exports2.computeServiceUrl = computeServiceUrl; var URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; function parseUri(uriString) { const parsedUri = URI_REGEX.exec(uriString); @@ -49014,6 +49040,23 @@ var require_uri_parser = __commonJS({ result += uri.path; return result; } + function extractServiceName(methodName) { + const firstSlashIndex = methodName.indexOf("/"); + if (firstSlashIndex === -1) { + return ""; + } + const secondSlashIndex = methodName.indexOf("/", firstSlashIndex + 1); + if (secondSlashIndex === -1) { + return methodName.substring(firstSlashIndex + 1); + } + return methodName.substring(firstSlashIndex + 1, secondSlashIndex); + } + function computeServiceUrl(host, methodName) { + var _a, _b; + const serviceName = extractServiceName(methodName); + const hostname = (_b = (_a = splitHostPort(host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; + return `https://${hostname}/${serviceName}`; + } } }); @@ -49161,6 +49204,7 @@ var require_channel_credentials = __commonJS({ return other instanceof _InsecureChannelCredentialsImpl; } _createSecureConnector(channelTarget, options, callCredentials) { + const credentials = callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); return { connect(socket) { return Promise.resolve({ @@ -49172,7 +49216,7 @@ var require_channel_credentials = __commonJS({ return Promise.resolve(); }, getCallCredentials: () => { - return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); + return credentials; }, destroy() { } @@ -50019,7 +50063,9 @@ var require_backoff_timeout = __commonJS({ this.maxDelay = options.maxDelay; } } - this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); + if (this.traceEnabled) { + this.trace("constructed initialDelay=" + this.initialDelay + " multiplier=" + this.multiplier + " jitter=" + this.jitter + " maxDelay=" + this.maxDelay); + } this.nextDelay = this.initialDelay; this.timerId = setTimeout(() => { }, 0); @@ -50028,12 +50074,19 @@ var require_backoff_timeout = __commonJS({ static getNextId() { return this.nextId++; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "{" + this.id + "} " + text); + } } runTimer(delay) { var _a, _b; - this.trace("runTimer(delay=" + delay + ")"); + if (this.traceEnabled) { + this.trace("runTimer(delay=" + delay + ")"); + } this.endTime = this.startTime; this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); clearTimeout(this.timerId); @@ -50072,7 +50125,9 @@ var require_backoff_timeout = __commonJS({ * retroactively apply that reset to the current timer. */ reset() { - this.trace("reset() running=" + this.running); + if (this.traceEnabled) { + this.trace("reset() running=" + this.running); + } this.nextDelay = this.initialDelay; if (this.running) { const now = /* @__PURE__ */ new Date(); @@ -50259,6 +50314,7 @@ var require_resolving_load_balancer = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.ResolvingLoadBalancer = void 0; + exports2.getDefaultConfigSelector = getDefaultConfigSelector; var load_balancer_1 = require_load_balancer(); var service_config_1 = require_service_config(); var connectivity_state_1 = require_connectivity_state(); @@ -50309,34 +50365,40 @@ var require_resolving_load_balancer = __commonJS({ } return null; } + var MAX_CACHED_METHOD_CONFIGS = 100; function getDefaultConfigSelector(serviceConfig) { + const methodConfigCache = /* @__PURE__ */ new Map(); return { - invoke(methodName, metadata) { + invoke(methodName, metadata, channelId) { var _a, _b; - const splitName = methodName.split("/").filter((x) => x.length > 0); - const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ""; - const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ""; - if (serviceConfig && serviceConfig.methodConfig) { - for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { - const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); - if (matchingConfig) { - return { - methodConfig: matchingConfig, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [] - }; + let matchingConfig = methodConfigCache.get(methodName); + if (matchingConfig === void 0) { + const splitName = methodName.split("/").filter((x) => x.length > 0); + const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ""; + const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ""; + matchingConfig = { name: [] }; + if (serviceConfig && serviceConfig.methodConfig) { + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const foundConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); + if (foundConfig) { + matchingConfig = foundConfig; + break; + } } } + if (methodConfigCache.size < MAX_CACHED_METHOD_CONFIGS) { + methodConfigCache.set(methodName, matchingConfig); + } } return { - methodConfig: { name: [] }, + methodConfig: matchingConfig, pickInformation: {}, status: constants_1.Status.OK, dynamicFilterFactories: [] }; }, unref() { + methodConfigCache.clear(); } }; } @@ -62146,6 +62208,7 @@ var require_channelz = __commonJS({ Object.defineProperty(exports2, "__esModule", { value: true }); exports2.registerChannelzSocket = exports2.registerChannelzServer = exports2.registerChannelzSubchannel = exports2.registerChannelzChannel = exports2.ChannelzCallTrackerStub = exports2.ChannelzCallTracker = exports2.ChannelzChildrenTrackerStub = exports2.ChannelzChildrenTracker = exports2.ChannelzTrace = exports2.ChannelzTraceStub = void 0; exports2.unregisterChannelzRef = unregisterChannelzRef; + exports2.dateToProtoTimestamp = dateToProtoTimestamp; exports2.getChannelzHandlers = getChannelzHandlers; exports2.getChannelzServiceDefinition = getChannelzServiceDefinition; exports2.setup = setup; @@ -62302,7 +62365,7 @@ var require_channelz = __commonJS({ } addCallStarted() { this.callsStarted += 1; - this.lastCallStartedTimestamp = /* @__PURE__ */ new Date(); + this.lastCallStartedTimestamp = Date.now(); } addCallSucceeded() { this.callsSucceeded += 1; @@ -62444,12 +62507,12 @@ var require_channelz = __commonJS({ } } function dateToProtoTimestamp(date) { - if (!date) { + if (date === null || date === void 0) { return null; } - const millisSinceEpoch = date.getTime(); + const millisSinceEpoch = typeof date === "number" ? date : date.getTime(); return { - seconds: millisSinceEpoch / 1e3 | 0, + seconds: Math.floor(millisSinceEpoch / 1e3), nanos: millisSinceEpoch % 1e3 * 1e6 }; } @@ -63104,7 +63167,7 @@ var require_deadline = __commonJS({ ["H", 60 * 60 * 1e3] ]; function getDeadlineTimeoutString(deadline) { - const now = (/* @__PURE__ */ new Date()).getTime(); + const now = Date.now(); if (deadline instanceof Date) { deadline = deadline.getTime(); } @@ -63120,7 +63183,7 @@ var require_deadline = __commonJS({ var MAX_TIMEOUT_TIME = 2147483647; function getRelativeTimeout(deadline) { const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; - const now = (/* @__PURE__ */ new Date()).getTime(); + const now = Date.now(); const timeout = deadlineMs - now; if (timeout < 0) { return 0; @@ -63143,7 +63206,9 @@ var require_deadline = __commonJS({ } } function formatDateDifference(startDate, endDate) { - return ((endDate.getTime() - startDate.getTime()) / 1e3).toFixed(3) + "s"; + const startMs = typeof startDate === "number" ? startDate : startDate.getTime(); + const endMs = typeof endDate === "number" ? endDate : endDate.getTime(); + return ((endMs - startMs) / 1e3).toFixed(3) + "s"; } } }); @@ -63238,7 +63303,6 @@ var require_single_subchannel_channel = __commonJS({ var uri_parser_1 = require_uri_parser(); var SubchannelCallWrapper = class { constructor(subchannel, method, filterStackFactory, options, callNumber) { - var _a, _b; this.subchannel = subchannel; this.method = method; this.options = options; @@ -63250,13 +63314,7 @@ var require_single_subchannel_channel = __commonJS({ this.pendingStatus = null; this.readFilterPending = false; this.writeFilterPending = false; - const splitPath = this.method.split("/"); - let serviceName = ""; - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; - this.serviceUrl = `https://${hostname}/${serviceName}`; + this.serviceUrl = (0, uri_parser_1.computeServiceUrl)(this.options.host, this.method); const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); if (timeout !== Infinity) { if (timeout <= 0) { @@ -63334,7 +63392,7 @@ var require_single_subchannel_channel = __commonJS({ } } }; - this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); + this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener, this.callNumber); if (this.readPending) { this.childCall.startRead(); } @@ -63504,7 +63562,9 @@ var require_subchannel = __commonJS({ } this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); this.channelzTrace.addTrace("CT_INFO", "Subchannel created"); - this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2)); + if (this.traceEnabled) { + this.trace("Subchannel constructed with options " + JSON.stringify(options, void 0, 2)); + } this.secureConnector = credentials._createSecureConnector(channelTarget, options); } getChannelzInfo() { @@ -63516,11 +63576,21 @@ var require_subchannel = __commonJS({ target: this.subchannelAddressString }; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } + get refTraceEnabled() { + return logging.isTracerEnabled("subchannel_refcount"); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } refTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.refTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, "subchannel_refcount", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } handleBackoffTimer() { if (this.continueConnecting) { @@ -63577,10 +63647,12 @@ var require_subchannel = __commonJS({ if (oldStates.indexOf(this.connectivityState) === -1) { return false; } - if (errorMessage) { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); - } else { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + if (this.traceEnabled) { + if (errorMessage) { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState] + ' with error "' + errorMessage + '"'); + } else { + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + " -> " + connectivity_state_1.ConnectivityState[newState]); + } } if (this.channelzEnabled) { this.channelzTrace.addTrace("CT_INFO", "Connectivity state change to " + connectivity_state_1.ConnectivityState[newState]); @@ -63624,11 +63696,15 @@ var require_subchannel = __commonJS({ return true; } ref() { - this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); + if (this.refTraceEnabled) { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount + 1)); + } this.refcount += 1; } unref() { - this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); + if (this.refTraceEnabled) { + this.refTrace("refcount " + this.refcount + " -> " + (this.refcount - 1)); + } this.refcount -= 1; if (this.refcount === 0) { this.channelzTrace.addTrace("CT_INFO", "Shutting down"); @@ -63646,7 +63722,7 @@ var require_subchannel = __commonJS({ } return false; } - createCall(metadata, host, method, listener) { + createCall(metadata, host, method, listener, callId) { if (!this.transport) { throw new Error("Cannot create call, subchannel not READY"); } @@ -63666,7 +63742,7 @@ var require_subchannel = __commonJS({ } else { statsTracker = {}; } - return this.transport.createCall(metadata, host, method, listener, statsTracker); + return this.transport.createCall(metadata, host, method, listener, statsTracker, callId); } /** * If the subchannel is currently IDLE, start connecting and switch to the @@ -63772,9 +63848,11 @@ var require_environment = __commonJS({ "node_modules/@grpc/grpc-js/build/src/environment.js"(exports2) { "use strict"; var _a; + var _b; Object.defineProperty(exports2, "__esModule", { value: true }); - exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; + exports2.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS = exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; exports2.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : "false") === "true"; + exports2.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS = ((_b = process.env.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) !== null && _b !== void 0 ? _b : "false") === "true"; } }); @@ -64445,11 +64523,13 @@ var require_subchannel_call = __commonJS({ const maxReceiveMessageLength = (_a = transport.getOptions()["grpc.max_receive_message_length"]) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); http2Stream.on("response", (headers, flags) => { - let headersString = ""; - for (const header of Object.keys(headers)) { - headersString += " " + header + ": " + headers[header] + "\n"; + if (this.traceEnabled) { + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += " " + header + ": " + headers[header] + "\n"; + } + this.trace("Received server headers:\n" + headersString); } - this.trace("Received server headers:\n" + headersString); this.httpStatusCode = headers[":status"]; if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { this.handleTrailers(headers); @@ -64475,7 +64555,9 @@ var require_subchannel_call = __commonJS({ if (this.statusOutput) { return; } - this.trace("receive HTTP/2 data frame of length " + data.length); + if (this.traceEnabled) { + this.trace("receive HTTP/2 data frame of length " + data.length); + } let messages; try { messages = this.decoder.write(data); @@ -64489,7 +64571,9 @@ var require_subchannel_call = __commonJS({ return; } for (const message of messages) { - this.trace("parsed message of length " + message.length); + if (this.traceEnabled) { + this.trace("parsed message of length " + message.length); + } this.callEventTracker.addMessageReceived(); this.tryPush(message); } @@ -64502,7 +64586,9 @@ var require_subchannel_call = __commonJS({ this.serverEndedCall = true; process.nextTick(() => { var _a2; - this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); + if (this.traceEnabled) { + this.trace("HTTP/2 stream closed with code " + http2Stream.rstCode); + } if (((_a2 = this.finalStatus) === null || _a2 === void 0 ? void 0 : _a2.code) === constants_1.Status.OK) { return; } @@ -64570,7 +64656,9 @@ var require_subchannel_call = __commonJS({ }); http2Stream.on("error", (err) => { if (err.code !== "ERR_HTTP2_STREAM_ERROR") { - this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); + if (this.traceEnabled) { + this.trace("Node error event: message=" + err.message + " code=" + err.code + " errno=" + getSystemErrorName(err.errno) + " syscall=" + err.syscall); + } this.internalError = err; } this.callEventTracker.onStreamEnd(false); @@ -64592,7 +64680,9 @@ var require_subchannel_call = __commonJS({ outputStatus() { if (!this.statusOutput) { this.statusOutput = true; - this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); + if (this.traceEnabled) { + this.trace("ended with status: code=" + this.finalStatus.code + ' details="' + this.finalStatus.details + '"'); + } this.callEventTracker.onCallEnd(this.finalStatus); process.nextTick(() => { this.listener.onReceiveStatus(this.finalStatus); @@ -64600,8 +64690,13 @@ var require_subchannel_call = __commonJS({ this.http2Stream.resume(); } } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callId + "] " + text); + } } /** * On first call, emits a 'status' event with the given StatusObject. @@ -64623,7 +64718,9 @@ var require_subchannel_call = __commonJS({ } } push(message) { - this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); + if (this.traceEnabled) { + this.trace("pushing to reader message of length " + (message instanceof Buffer ? message.length : null)); + } this.canPush = false; this.isPushPending = true; process.nextTick(() => { @@ -64640,39 +64737,49 @@ var require_subchannel_call = __commonJS({ this.http2Stream.pause(); this.push(messageBytes); } else { - this.trace("unpushedReadMessages.push message of length " + messageBytes.length); + if (this.traceEnabled) { + this.trace("unpushedReadMessages.push message of length " + messageBytes.length); + } this.unpushedReadMessages.push(messageBytes); } } handleTrailers(headers) { this.serverEndedCall = true; this.callEventTracker.onStreamEnd(true); - let headersString = ""; - for (const header of Object.keys(headers)) { - headersString += " " + header + ": " + headers[header] + "\n"; + if (this.traceEnabled) { + let headersString = ""; + for (const header of Object.keys(headers)) { + headersString += " " + header + ": " + headers[header] + "\n"; + } + this.trace("Received server trailers:\n" + headersString); } - this.trace("Received server trailers:\n" + headersString); let metadata; try { metadata = metadata_1.Metadata.fromHttp2Headers(headers); } catch (e) { metadata = new metadata_1.Metadata(); } - const metadataMap = metadata.getMap(); + const statusValues = metadata.get("grpc-status"); let status; - if (typeof metadataMap["grpc-status"] === "string") { - const receivedStatus = Number(metadataMap["grpc-status"]); - this.trace("received status code " + receivedStatus + " from server"); + if (statusValues.length > 0 && typeof statusValues[0] === "string") { + const receivedStatus = Number(statusValues[0]); + if (this.traceEnabled) { + this.trace("received status code " + receivedStatus + " from server"); + } metadata.remove("grpc-status"); let details = ""; - if (typeof metadataMap["grpc-message"] === "string") { + const messageValues = metadata.get("grpc-message"); + if (messageValues.length > 0 && typeof messageValues[0] === "string") { + const messageString = messageValues[0]; try { - details = decodeURI(metadataMap["grpc-message"]); - } catch (e) { - details = metadataMap["grpc-message"]; + details = decodeURI(messageString); + } catch (error2) { + details = messageString; } metadata.remove("grpc-message"); - this.trace('received status details string "' + details + '" from server'); + if (this.traceEnabled) { + this.trace('received status details string "' + details + '" from server'); + } } status = { code: receivedStatus, @@ -64697,7 +64804,9 @@ var require_subchannel_call = __commonJS({ return; } if (this.serverEndedCall) { - this.http2Stream.end(); + if (!this.http2Stream.writableEnded) { + this.http2Stream.end(); + } } else { let code; if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { @@ -64705,12 +64814,16 @@ var require_subchannel_call = __commonJS({ } else { code = http2.constants.NGHTTP2_CANCEL; } - this.trace("close http2 stream with code " + code); + if (this.traceEnabled) { + this.trace("close http2 stream with code " + code); + } this.http2Stream.close(code); } } cancelWithStatus(status, details) { - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); } getStatus() { @@ -64740,7 +64853,9 @@ var require_subchannel_call = __commonJS({ this.http2Stream.resume(); } sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } const cb = (error2) => { process.nextTick(() => { var _a; @@ -64754,7 +64869,9 @@ var require_subchannel_call = __commonJS({ (_a = context3.callback) === null || _a === void 0 ? void 0 : _a.call(context3); }); }; - this.trace("sending data chunk of length " + message.length); + if (this.traceEnabled) { + this.trace("sending data chunk of length " + message.length); + } this.callEventTracker.addMessageSent(); try { this.http2Stream.write(message, cb); @@ -64768,6 +64885,9 @@ var require_subchannel_call = __commonJS({ } halfClose() { this.trace("end() called"); + if (this.http2Stream.destroyed || this.http2Stream.writableEnded) { + return; + } this.trace("calling end() on HTTP/2 stream"); this.http2Stream.end(); } @@ -64853,18 +64973,24 @@ var require_transport = __commonJS({ if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && opaqueData && opaqueData.equals(tooManyPingsData)) { tooManyPings = true; } - this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + if (this.traceEnabled) { + this.trace("connection closed by GOAWAY with code " + errorCode + " and data " + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + } this.reportDisconnectToOwner(tooManyPings); }); session.once("error", (error2) => { - this.trace("connection closed with error " + error2.message); + if (this.traceEnabled) { + this.trace("connection closed with error " + error2.message); + } this.handleDisconnect(); }); session.socket.once("close", (hadError) => { - this.trace("connection closed. hadError=" + hadError); + if (this.traceEnabled) { + this.trace("connection closed. hadError=" + hadError); + } this.handleDisconnect(); }); - if (logging.isTracerEnabled(TRACER_NAME)) { + if (this.traceEnabled) { session.on("remoteSettings", (settings) => { this.trace("new settings received" + (this.session !== session ? " on the old connection" : "") + ": " + JSON.stringify(settings)); }); @@ -64875,7 +65001,7 @@ var require_transport = __commonJS({ if (this.keepaliveWithoutCalls) { this.maybeStartKeepalivePingTimer(); } - if (session.socket instanceof tls_1.TLSSocket) { + if (session.socket instanceof tls_1.TLSSocket && session.socket.authorized) { this.authContext = { transportSecurityType: "ssl", sslPeerCertificate: session.socket.getPeerCertificate() @@ -64924,17 +65050,37 @@ var require_transport = __commonJS({ }; return socketInfo; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } + get keepaliveTraceEnabled() { + return logging.isTracerEnabled("keepalive"); + } + get flowControlTraceEnabled() { + return logging.isTracerEnabled(FLOW_CONTROL_TRACER_NAME); + } + get internalsTraceEnabled() { + return logging.isTracerEnabled("transport_internals"); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.keepaliveTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, "keepalive", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } flowControlTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.flowControlTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } internalsTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + if (this.internalsTraceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, "transport_internals", "(" + this.channelzRef.id + ") " + this.subchannelAddressString + " " + text); + } } /** * Indicate to the owner of this object that this transport should no longer @@ -64984,7 +65130,9 @@ var require_transport = __commonJS({ if (this.channelzEnabled) { this.keepalivesSent += 1; } - this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + if (this.keepaliveTraceEnabled) { + this.keepaliveTrace("Sending ping with timeout " + this.keepaliveTimeoutMs + "ms"); + } this.keepaliveTimer = setTimeout(() => { this.keepaliveTimer = null; this.keepaliveTrace("Ping timeout passed without response"); @@ -64996,7 +65144,9 @@ var require_transport = __commonJS({ const pingSentSuccessfully = this.session.ping((err, duration, payload) => { this.clearKeepaliveTimeout(); if (err) { - this.keepaliveTrace("Ping failed with error " + err.message); + if (this.keepaliveTraceEnabled) { + this.keepaliveTrace("Ping failed with error " + err.message); + } this.handleDisconnect(); } else { this.keepaliveTrace("Received ping response"); @@ -65010,7 +65160,9 @@ var require_transport = __commonJS({ pingSendError = (e instanceof Error ? e.message : "") || "Unknown error"; } if (pingSendError) { - this.keepaliveTrace("Ping send failed: " + pingSendError); + if (this.keepaliveTraceEnabled) { + this.keepaliveTrace("Ping send failed: " + pingSendError); + } this.handleDisconnect(); } } @@ -65061,7 +65213,7 @@ var require_transport = __commonJS({ } } } - createCall(metadata, host, method, listener, subchannelCallStatsTracker) { + createCall(metadata, host, method, listener, subchannelCallStatsTracker, callId) { const headers = metadata.toHttp2Headers(); headers[HTTP2_HEADER_AUTHORITY] = host; headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; @@ -65076,8 +65228,12 @@ var require_transport = __commonJS({ this.handleDisconnect(); throw e; } - this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); - this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); + if (this.flowControlTraceEnabled) { + this.flowControlTrace("local window size: " + this.session.state.localWindowSize + " remote window size: " + this.session.state.remoteWindowSize); + } + if (this.internalsTraceEnabled) { + this.internalsTrace("session.closed=" + this.session.closed + " session.destroyed=" + this.session.destroyed + " session.socket.destroyed=" + this.session.socket.destroyed); + } let eventTracker; let call; if (this.channelzEnabled) { @@ -65086,13 +65242,13 @@ var require_transport = __commonJS({ addMessageSent: () => { var _a; this.messagesSent += 1; - this.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); + this.lastMessageSentTimestamp = Date.now(); (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); }, addMessageReceived: () => { var _a; this.messagesReceived += 1; - this.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); + this.lastMessageReceivedTimestamp = Date.now(); (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); }, onCallEnd: (status) => { @@ -65131,7 +65287,7 @@ var require_transport = __commonJS({ } }; } - call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); + call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, callId !== null && callId !== void 0 ? callId : (0, call_number_1.getNextCallNumber)()); this.addActiveCall(call); return call; } @@ -65158,8 +65314,13 @@ var require_transport = __commonJS({ this.session = null; this.isShutdown = false; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + " " + text); + } } createSession(secureConnectResult, address, options) { if (this.isShutdown) { @@ -65196,7 +65357,9 @@ var require_transport = __commonJS({ var _a2; (_a2 = this.session) === null || _a2 === void 0 ? void 0 : _a2.destroy(); errorMessage = error2.message; - this.trace("connection failed with error " + errorMessage); + if (this.traceEnabled) { + this.trace("connection failed with error " + errorMessage); + } if (!reportedError) { reportedError = true; reject(`${errorMessage} (${(/* @__PURE__ */ new Date()).toISOString()})`); @@ -65277,14 +65440,22 @@ var require_transport = __commonJS({ let secureConnectResult = null; const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); try { - this.trace(addressString + " Waiting for secureConnector to be ready"); + if (this.traceEnabled) { + this.trace(addressString + " Waiting for secureConnector to be ready"); + } await secureConnector.waitForReady(); - this.trace(addressString + " secureConnector is ready"); + if (this.traceEnabled) { + this.trace(addressString + " secureConnector is ready"); + } tcpConnection = await this.tcpConnect(address, options); tcpConnection.setNoDelay(); - this.trace(addressString + " Established TCP connection"); + if (this.traceEnabled) { + this.trace(addressString + " Established TCP connection"); + } secureConnectResult = await secureConnector.connect(tcpConnection); - this.trace(addressString + " Established secure connection"); + if (this.traceEnabled) { + this.trace(addressString + " Established secure connection"); + } return this.createSession(secureConnectResult, address, options); } catch (e) { tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); @@ -65407,19 +65578,19 @@ var require_load_balancing_call = __commonJS({ "use strict"; Object.defineProperty(exports2, "__esModule", { value: true }); exports2.LoadBalancingCall = void 0; + var call_credentials_1 = require_call_credentials(); var connectivity_state_1 = require_connectivity_state(); var constants_1 = require_constants7(); var deadline_1 = require_deadline(); var metadata_1 = require_metadata(); var picker_1 = require_picker(); - var uri_parser_1 = require_uri_parser(); var logging = require_logging(); var control_plane_status_1 = require_control_plane_status(); var http2 = require("http2"); var TRACER_NAME = "load_balancing_call"; + var RESOLVED_EMPTY_METADATA = Promise.resolve(void 0); var LoadBalancingCall = class { constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { - var _a, _b; this.channel = channel; this.callConfig = callConfig; this.methodName = methodName; @@ -65436,19 +65607,13 @@ var require_load_balancing_call = __commonJS({ this.listener = null; this.onCallEnded = null; this.childStartTime = null; - const splitPath = this.methodName.split("/"); - let serviceName = ""; - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : "localhost"; - this.serviceUrl = `https://${hostname}/${serviceName}`; - this.startTime = /* @__PURE__ */ new Date(); + this.serviceUrl = this.channel.getServiceUrl(this.host, this.methodName); + this.startTime = Date.now(); } getDeadlineInfo() { var _a, _b; const deadlineInfo = []; - if (this.childStartTime) { + if (this.childStartTime !== null) { if (this.childStartTime > this.startTime) { if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { deadlineInfo.push("wait_for_ready"); @@ -65465,19 +65630,36 @@ var require_load_balancing_call = __commonJS({ } return deadlineInfo; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } + } + getSubchannelString(subchannel) { + return subchannel ? "(" + subchannel.getChannelzRef().id + ") " + subchannel.getAddress() : "" + subchannel; } outputStatus(status, progress) { var _a, _b; if (!this.ended) { this.ended = true; - this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + this.startTime.toISOString()); + if (this.traceEnabled) { + this.trace("ended with status: code=" + status.code + ' details="' + status.details + '" start time=' + new Date(this.startTime).toISOString()); + } const finalStatus = Object.assign(Object.assign({}, status), { progress }); (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); + this.channel.removeCallFromPickQueue(this); } } + generateCallCredentialsMetadata(callCredentials) { + return (0, call_credentials_1.isEmptyCallCredentials)(callCredentials) ? RESOLVED_EMPTY_METADATA : callCredentials.generateMetadata({ + method_name: this.methodName, + service_url: this.serviceUrl + }); + } doPick() { var _a, _b; if (this.ended) { @@ -65489,18 +65671,20 @@ var require_load_balancing_call = __commonJS({ this.trace("Pick called"); const finalMetadata = this.metadata.clone(); const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); - const subchannelString = pickResult.subchannel ? "(" + pickResult.subchannel.getChannelzRef().id + ") " + pickResult.subchannel.getAddress() : "" + pickResult.subchannel; - this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + subchannelString + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + if (this.traceEnabled) { + this.trace("Pick result: " + picker_1.PickResultType[pickResult.pickResultType] + " subchannel: " + this.getSubchannelString(pickResult.subchannel) + " status: " + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + " " + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + } switch (pickResult.pickResultType) { case picker_1.PickResultType.COMPLETE: - const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); - combinedCallCredentials.generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }).then((credsMetadata) => { + this.generateCallCredentialsMetadata(this.credentials.compose(pickResult.subchannel.getCallCredentials())).then((credsMetadata) => { var _a2; if (this.ended) { this.trace("Credentials metadata generation finished after call ended"); return; } - finalMetadata.merge(credsMetadata); + if (credsMetadata) { + finalMetadata.merge(credsMetadata); + } if (finalMetadata.get("authorization").length > 1) { this.outputStatus({ code: constants_1.Status.INTERNAL, @@ -65509,7 +65693,9 @@ var require_load_balancing_call = __commonJS({ }, "PROCESSED"); } if (pickResult.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - this.trace("Picked subchannel " + subchannelString + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); + if (this.traceEnabled) { + this.trace("Picked subchannel " + this.getSubchannelString(pickResult.subchannel) + " has state " + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + " after getting credentials metadata. Retrying pick"); + } this.doPick(); return; } @@ -65534,10 +65720,12 @@ var require_load_balancing_call = __commonJS({ this.outputStatus(status, "PROCESSED"); } } - }); - this.childStartTime = /* @__PURE__ */ new Date(); + }, this.callNumber); + this.childStartTime = Date.now(); } catch (error2) { - this.trace("Failed to start call on picked subchannel " + subchannelString + " with error " + error2.message); + if (this.traceEnabled) { + this.trace("Failed to start call on picked subchannel " + this.getSubchannelString(pickResult.subchannel) + " with error " + error2.message); + } this.outputStatus({ code: constants_1.Status.INTERNAL, details: "Failed to start HTTP/2 stream with error " + error2.message, @@ -65547,7 +65735,9 @@ var require_load_balancing_call = __commonJS({ } (_a2 = pickResult.onCallStarted) === null || _a2 === void 0 ? void 0 : _a2.call(pickResult); this.onCallEnded = pickResult.onCallEnded; - this.trace("Created child call [" + this.child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Created child call [" + this.child.getCallNumber() + "]"); + } if (this.readPending) { this.child.startRead(); } @@ -65588,7 +65778,9 @@ var require_load_balancing_call = __commonJS({ } cancelWithStatus(status, details) { var _a; - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); this.outputStatus({ code: status, details, metadata: new metadata_1.Metadata() }, "PROCESSED"); } @@ -65603,7 +65795,9 @@ var require_load_balancing_call = __commonJS({ this.doPick(); } sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } if (this.child) { this.child.sendMessageWithContext(context3, message); } else { @@ -65674,8 +65868,7 @@ var require_resolving_call = __commonJS({ this.metadata = null; this.listener = null; this.statusWatchers = []; - this.deadlineTimer = setTimeout(() => { - }, 0); + this.deadlineTimer = null; this.filterStack = null; this.deadlineStartTime = null; this.configReceivedTime = null; @@ -65690,36 +65883,51 @@ var require_resolving_call = __commonJS({ }); } if (options.flags & constants_1.Propagate.DEADLINE) { - this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); + if (this.traceEnabled) { + this.trace("Propagating deadline from parent: " + options.parentCall.getDeadline()); + } this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); } } this.trace("Created"); this.runDeadlineTimer(); } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } } runDeadlineTimer() { - clearTimeout(this.deadlineTimer); - this.deadlineStartTime = /* @__PURE__ */ new Date(); - this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + this.deadlineTimer = null; + } + this.deadlineStartTime = Date.now(); + if (this.traceEnabled) { + this.trace("Deadline: " + (0, deadline_1.deadlineToString)(this.deadline)); + } const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); if (timeout !== Infinity) { - this.trace("Deadline will be reached in " + timeout + "ms"); + if (this.traceEnabled) { + this.trace("Deadline will be reached in " + timeout + "ms"); + } const handleDeadline = () => { - if (!this.deadlineStartTime) { + this.deadlineTimer = null; + if (this.deadlineStartTime === null) { this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, "Deadline exceeded"); return; } const deadlineInfo = []; - const deadlineEndTime = /* @__PURE__ */ new Date(); + const deadlineEndTime = Date.now(); deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); - if (this.configReceivedTime) { + if (this.configReceivedTime !== null) { if (this.configReceivedTime > this.deadlineStartTime) { deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); } - if (this.childStartTime) { + if (this.childStartTime !== null) { if (this.childStartTime > this.configReceivedTime) { deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); } @@ -65747,9 +65955,14 @@ var require_resolving_call = __commonJS({ if (!this.filterStack) { this.filterStack = this.filterStackFactory.createFilter(); } - clearTimeout(this.deadlineTimer); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + this.deadlineTimer = null; + } const filteredStatus = this.filterStack.receiveTrailers(status); - this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); + if (this.traceEnabled) { + this.trace("ended with status: code=" + filteredStatus.code + ' details="' + filteredStatus.details + '"'); + } this.statusWatchers.forEach((watcher) => watcher(filteredStatus)); process.nextTick(() => { var _a; @@ -65770,7 +65983,8 @@ var require_resolving_call = __commonJS({ child.halfClose(); } }, (status) => { - this.cancelWithStatus(status.code, status.details); + var _a, _b; + this.cancelWithStatus((_a = status.code) !== null && _a !== void 0 ? _a : constants_1.Status.INTERNAL, (_b = status.details) !== null && _b !== void 0 ? _b : "Failed to write message"); }); } getConfig() { @@ -65792,7 +66006,7 @@ var require_resolving_call = __commonJS({ } return; } - this.configReceivedTime = /* @__PURE__ */ new Date(); + this.configReceivedTime = Date.now(); const config = configResult.config; if (config.status !== constants_1.Status.OK) { const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, "Failed to route call to method " + this.method); @@ -65804,18 +66018,19 @@ var require_resolving_call = __commonJS({ return; } if (config.methodConfig.timeout) { - const configDeadline = /* @__PURE__ */ new Date(); - configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); - configDeadline.setMilliseconds(configDeadline.getMilliseconds() + config.methodConfig.timeout.nanos / 1e6); + const timeoutMs = Math.floor(config.methodConfig.timeout.seconds * 1e3 + config.methodConfig.timeout.nanos / 1e6); + const configDeadline = Date.now() + timeoutMs; this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); this.runDeadlineTimer(); } this.filterStackFactory.push(config.dynamicFilterFactories); this.filterStack = this.filterStackFactory.createFilter(); this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then((filteredMetadata) => { - this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); - this.trace("Created child [" + this.child.getCallNumber() + "]"); - this.childStartTime = /* @__PURE__ */ new Date(); + this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline, this.callNumber); + if (this.traceEnabled) { + this.trace("Created child [" + this.child.getCallNumber() + "]"); + } + this.childStartTime = Date.now(); this.child.start(filteredMetadata, { onReceiveMetadata: (metadata) => { this.trace("Received metadata"); @@ -65866,7 +66081,9 @@ var require_resolving_call = __commonJS({ } cancelWithStatus(status, details) { var _a; - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); this.outputStatus({ code: status, @@ -65885,7 +66102,9 @@ var require_resolving_call = __commonJS({ this.getConfig(); } sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } if (this.child) { this.sendMessageOnChild(context3, message); } else { @@ -65939,6 +66158,7 @@ var require_retrying_call = __commonJS({ var deadline_1 = require_deadline(); var metadata_1 = require_metadata(); var logging = require_logging(); + var call_number_1 = require_call_number(); var TRACER_NAME = "retrying_call"; var RetryThrottler = class { constructor(maxTokens, tokenRatio, previousRetryThrottler) { @@ -66043,7 +66263,7 @@ var require_retrying_call = __commonJS({ this.state = "TRANSPARENT_ONLY"; this.maxAttempts = 1; } - this.startTime = /* @__PURE__ */ new Date(); + this.startTime = Date.now(); } getDeadlineInfo() { if (this.underlyingCalls.length === 0) { @@ -66063,11 +66283,18 @@ var require_retrying_call = __commonJS({ getCallNumber() { return this.callNumber; } + get traceEnabled() { + return logging.isTracerEnabled(TRACER_NAME); + } trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + if (this.traceEnabled) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, "[" + this.callNumber + "] " + text); + } } reportStatus(statusObject) { - this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + this.startTime.toISOString()); + if (this.traceEnabled) { + this.trace("ended with status: code=" + statusObject.code + ' details="' + statusObject.details + '" start time=' + new Date(this.startTime).toISOString()); + } this.bufferTracker.freeAll(this.callNumber); this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; this.writeBuffer = []; @@ -66081,7 +66308,9 @@ var require_retrying_call = __commonJS({ }); } cancelWithStatus(status, details) { - this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + if (this.traceEnabled) { + this.trace("cancelWithStatus code: " + status + ' details: "' + details + '"'); + } this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); for (const { call } of this.underlyingCalls) { call.cancelWithStatus(status, details); @@ -66128,7 +66357,9 @@ var require_retrying_call = __commonJS({ if (this.state === "COMMITTED") { return; } - this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); + if (this.traceEnabled) { + this.trace("Committing call [" + this.underlyingCalls[index].call.getCallNumber() + "] at index " + index); + } this.state = "COMMITTED"; (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); this.committedCallIndex = index; @@ -66295,7 +66526,9 @@ var require_retrying_call = __commonJS({ if (this.underlyingCalls[callIndex].state === "COMPLETED") { return; } - this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); + if (this.traceEnabled) { + this.trace("state=" + this.state + " handling status with progress " + status.progress + " from child [" + this.underlyingCalls[callIndex].call.getCallNumber() + "] in state " + this.underlyingCalls[callIndex].state); + } this.underlyingCalls[callIndex].state = "COMPLETED"; if (status.code === constants_1.Status.OK) { (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); @@ -66371,24 +66604,30 @@ var require_retrying_call = __commonJS({ (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); } startNewAttempt() { - const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); - this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); + const childCallNumber = this.underlyingCalls.length > 0 ? (0, call_number_1.getNextCallNumber)() : this.callNumber; + const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline, childCallNumber); + if (this.traceEnabled) { + this.trace("Created child call [" + child.getCallNumber() + "] for attempt " + this.attempts); + } const index = this.underlyingCalls.length; this.underlyingCalls.push({ state: "ACTIVE", call: child, nextMessageToSend: 0, - startTime: /* @__PURE__ */ new Date() + startTime: Date.now() }); const previousAttempts = this.attempts - 1; - const initialMetadata = this.initialMetadata.clone(); + let initialMetadata = this.initialMetadata; if (previousAttempts > 0) { + initialMetadata = initialMetadata.clone(); initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); } let receivedMetadata = false; child.start(initialMetadata, { onReceiveMetadata: (metadata) => { - this.trace("Received metadata from child [" + child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Received metadata from child [" + child.getCallNumber() + "]"); + } this.commitCall(index); receivedMetadata = true; if (previousAttempts > 0) { @@ -66399,14 +66638,18 @@ var require_retrying_call = __commonJS({ } }, onReceiveMessage: (message) => { - this.trace("Received message from child [" + child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Received message from child [" + child.getCallNumber() + "]"); + } this.commitCall(index); if (this.underlyingCalls[index].state === "ACTIVE") { this.listener.onReceiveMessage(message); } }, onReceiveStatus: (status) => { - this.trace("Received status from child [" + child.getCallNumber() + "]"); + if (this.traceEnabled) { + this.trace("Received status from child [" + child.getCallNumber() + "]"); + } if (!receivedMetadata && previousAttempts > 0) { status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); } @@ -66451,7 +66694,9 @@ var require_retrying_call = __commonJS({ }, bufferEntry.message.message); const nextEntry = this.getBufferEntry(messageIndex + 1); if (nextEntry.entryType === "HALF_CLOSE") { - this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); + if (this.traceEnabled) { + this.trace("Sending halfClose immediately after message to child [" + childCall.call.getCallNumber() + "] - optimizing for unary/final message"); + } childCall.nextMessageToSend += 1; childCall.call.halfClose(); } @@ -66466,7 +66711,9 @@ var require_retrying_call = __commonJS({ } } sendMessageWithContext(context3, message) { - this.trace("write() called with message of length " + message.length); + if (this.traceEnabled) { + this.trace("write() called with message of length " + message.length); + } const writeObj = { message, flags: context3.flags @@ -66527,7 +66774,9 @@ var require_retrying_call = __commonJS({ for (const call of this.underlyingCalls) { if ((call === null || call === void 0 ? void 0 : call.state) === "ACTIVE") { if (call.nextMessageToSend === halfCloseIndex || call.nextMessageToSend === halfCloseIndex - 1) { - this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); + if (this.traceEnabled) { + this.trace("Sending halfClose immediately to child [" + call.call.getCallNumber() + "] - all messages already sent"); + } call.nextMessageToSend += 1; call.call.halfClose(); } @@ -66749,7 +66998,7 @@ var require_internal_channel = __commonJS({ }; } }; - var InternalChannel = class { + var InternalChannel = class _InternalChannel { constructor(target, credentials, options) { var _a, _b, _c, _d, _e, _f; this.credentials = credentials; @@ -66757,7 +67006,7 @@ var require_internal_channel = __commonJS({ this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; this.currentPicker = new picker_1.UnavailablePicker(); this.configSelectionQueue = []; - this.pickQueue = []; + this.pickQueue = /* @__PURE__ */ new Set(); this.connectivityStateWatchers = []; this.callRefTimer = null; this.configSelector = null; @@ -66767,6 +67016,7 @@ var require_internal_channel = __commonJS({ this.idleTimer = null; this.channelzEnabled = true; this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + this.serviceUrlCache = /* @__PURE__ */ new Map(); if (typeof target !== "string") { throw new TypeError("Channel target must be a string"); } @@ -66824,9 +67074,9 @@ var require_internal_channel = __commonJS({ }, updateState: (connectivityState, picker) => { this.currentPicker = picker; - const queueCopy = this.pickQueue.slice(); - this.pickQueue = []; - if (queueCopy.length > 0) { + const queueCopy = this.pickQueue; + this.pickQueue = /* @__PURE__ */ new Set(); + if (queueCopy.size > 0) { this.callRefTimerUnref(); } for (const call of queueCopy) { @@ -66893,15 +67143,22 @@ var require_internal_channel = __commonJS({ this.filterStackFactory = new filter_stack_1.FilterStackFactory([ new compression_filter_1.CompressionFilterFactory(this, this.options) ]); - this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2)); - const error2 = new Error(); + if (this.traceEnabled) { + this.trace("Channel constructed with options " + JSON.stringify(options, void 0, 2)); + } if ((0, logging_1.isTracerEnabled)("channel_stacktrace")) { + const error2 = new Error(); (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, "channel_stacktrace", "(" + this.channelzRef.id + ") Channel constructed \n" + ((_f = error2.stack) === null || _f === void 0 ? void 0 : _f.substring(error2.stack.indexOf("\n") + 1))); } - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.lastActivityTimestamp = Date.now(); + } + get traceEnabled() { + return (0, logging_1.isTracerEnabled)("channel"); } trace(text, verbosityOverride) { - (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); + if (this.traceEnabled) { + (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, "channel", "(" + this.channelzRef.id + ") " + (0, uri_parser_1.uriToString)(this.target) + " " + text); + } } callRefTimerRef() { var _a, _b, _c, _d; @@ -66910,14 +67167,18 @@ var require_internal_channel = __commonJS({ }, MAX_TIMEOUT_TIME); } if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { - this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + if (this.traceEnabled) { + this.trace("callRefTimer.ref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.size); + } (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); } } callRefTimerUnref() { var _a, _b, _c; if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { - this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.length); + if (this.traceEnabled) { + this.trace("callRefTimer.unref | configSelectionQueue.length=" + this.configSelectionQueue.length + " pickQueue.length=" + this.pickQueue.size); + } (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); } } @@ -66969,9 +67230,15 @@ var require_internal_channel = __commonJS({ }); } queueCallForPick(call) { - this.pickQueue.push(call); + this.pickQueue.add(call); this.callRefTimerRef(); } + removeCallFromPickQueue(call) { + this.pickQueue.delete(call); + if (this.pickQueue.size === 0) { + this.callRefTimerUnref(); + } + } getConfig(method, metadata) { if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { this.resolvingLoadBalancer.exitIdle(); @@ -67018,8 +67285,8 @@ var require_internal_channel = __commonJS({ this.startIdleTimeout(this.idleTimeoutMs); return; } - const now = /* @__PURE__ */ new Date(); - const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); + const now = Date.now(); + const timeSinceLastActivity = now - this.lastActivityTimestamp; if (timeSinceLastActivity >= this.idleTimeoutMs) { this.trace("Idle timer triggered after " + this.idleTimeoutMs + "ms of inactivity"); this.enterIdle(); @@ -67049,22 +67316,54 @@ var require_internal_channel = __commonJS({ } } this.callCount -= 1; - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.lastActivityTimestamp = Date.now(); this.maybeStartIdleTimer(); } - createLoadBalancingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createLoadBalancingCall [" + callNumber + '] method="' + method + '"'); - return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); + /** + * Returns the precomputed service URL (`https://${hostname}/${serviceName}`) + * for the given host and method, using a bounded cache to avoid parsing on + * every RPC. + */ + getServiceUrl(host, methodName) { + let methodMap = this.serviceUrlCache.get(host); + if (methodMap === void 0) { + if (this.serviceUrlCache.size < _InternalChannel.MAX_CACHED_HOSTS) { + methodMap = /* @__PURE__ */ new Map(); + this.serviceUrlCache.set(host, methodMap); + } + } + if (methodMap !== void 0) { + const serviceUrl = methodMap.get(methodName); + if (serviceUrl !== void 0) { + return serviceUrl; + } + const computedServiceUrl = (0, uri_parser_1.computeServiceUrl)(host, methodName); + if (methodMap.size < _InternalChannel.MAX_METHODS_PER_HOST) { + methodMap.set(methodName, computedServiceUrl); + } + return computedServiceUrl; + } + return (0, uri_parser_1.computeServiceUrl)(host, methodName); } - createRetryingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createRetryingCall [" + callNumber + '] method="' + method + '"'); - return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); + createLoadBalancingCall(callConfig, method, host, credentials, deadline, callNumber) { + const finalCallNumber = callNumber !== null && callNumber !== void 0 ? callNumber : (0, call_number_1.getNextCallNumber)(); + if (this.traceEnabled) { + this.trace("createLoadBalancingCall [" + finalCallNumber + '] method="' + method + '"'); + } + return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, finalCallNumber); + } + createRetryingCall(callConfig, method, host, credentials, deadline, callNumber) { + const finalCallNumber = callNumber !== null && callNumber !== void 0 ? callNumber : (0, call_number_1.getNextCallNumber)(); + if (this.traceEnabled) { + this.trace("createRetryingCall [" + finalCallNumber + '] method="' + method + '"'); + } + return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, finalCallNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); } createResolvingCall(method, deadline, host, parentCall, propagateFlags) { const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); + if (this.traceEnabled) { + this.trace("createResolvingCall [" + callNumber + '] method="' + method + '", deadline=' + (0, deadline_1.deadlineToString)(deadline)); + } const finalOptions = { deadline, flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, @@ -67090,7 +67389,7 @@ var require_internal_channel = __commonJS({ for (const call of this.pickQueue) { call.cancelWithStatus(constants_1.Status.UNAVAILABLE, "Channel closed before call started"); } - this.pickQueue = []; + this.pickQueue.clear(); if (this.callRefTimer) { clearInterval(this.callRefTimer); } @@ -67103,6 +67402,7 @@ var require_internal_channel = __commonJS({ this.subchannelPool.unrefUnusedSubchannels(); (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); this.configSelector = null; + this.serviceUrlCache.clear(); } getTarget() { return (0, uri_parser_1.uriToString)(this.target); @@ -67111,7 +67411,7 @@ var require_internal_channel = __commonJS({ const connectivityState = this.connectivityState; if (tryToConnect) { this.resolvingLoadBalancer.exitIdle(); - this.lastActivityTimestamp = /* @__PURE__ */ new Date(); + this.lastActivityTimestamp = Date.now(); this.maybeStartIdleTimer(); } return connectivityState; @@ -67165,6 +67465,8 @@ var require_internal_channel = __commonJS({ } }; exports2.InternalChannel = InternalChannel; + InternalChannel.MAX_CACHED_HOSTS = 5; + InternalChannel.MAX_METHODS_PER_HOST = 100; } }); @@ -68097,6 +68399,7 @@ var require_server_interceptors = __commonJS({ var logging = require_logging(); var tls_1 = require("tls"); var orca_1 = require_orca(); + var environment_1 = require_environment(); var TRACER_NAME = "server_call"; function trace(text) { logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); @@ -68495,8 +68798,7 @@ var require_server_interceptors = __commonJS({ return; } const timeout = +match[1] * deadlineUnitsToMs[match[2]] | 0; - const now = /* @__PURE__ */ new Date(); - this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadline = Date.now() + timeout; this.deadlineTimer = setTimeout(() => { const status = { code: constants_1.Status.DEADLINE_EXCEEDED, @@ -68612,9 +68914,15 @@ var require_server_interceptors = __commonJS({ try { queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Error deserializing request: ${err.message}`; + } else { + details = "Error deserializing request"; + } this.sendStatus({ code: constants_1.Status.INTERNAL, - details: `Error deserializing request: ${err.message}` + details }); return; } @@ -68694,9 +69002,15 @@ var require_server_interceptors = __commonJS({ try { response = this.serializeMessage(message); } catch (e) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`; + } else { + details = "Error serializing response"; + } this.sendStatus({ code: constants_1.Status.INTERNAL, - details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, + details, metadata: null }); return; @@ -68714,9 +69028,15 @@ var require_server_interceptors = __commonJS({ this.stream.write(response, (error2) => { var _a; if (error2) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Error writing message: ${(0, error_1.getErrorMessage)(error2)}`; + } else { + details = "Internal server error"; + } this.sendStatus({ code: constants_1.Status.INTERNAL, - details: `Error writing message: ${(0, error_1.getErrorMessage)(error2)}`, + details, metadata: null }); return; @@ -68798,15 +69118,17 @@ var require_server_interceptors = __commonJS({ } getAuthContext() { var _a; - if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { - const peerCertificate = this.stream.session.socket.getPeerCertificate(); - return { - transportSecurityType: "ssl", - sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0 - }; - } else { + if (!(((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket)) { + return {}; + } + if (!this.stream.session.socket.authorized) { return {}; } + const peerCertificate = this.stream.session.socket.getPeerCertificate(); + return { + transportSecurityType: "ssl", + sslPeerCertificate: peerCertificate.raw ? peerCertificate : void 0 + }; } getConnectionInfo() { return this.connectionInfo; @@ -68888,6 +69210,7 @@ var require_server2 = __commonJS({ var uri_parser_1 = require_uri_parser(); var channelz_1 = require_channelz(); var server_interceptors_1 = require_server_interceptors(); + var environment_1 = require_environment(); var UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); var KEEPALIVE_MAX_TIME_MS = ~(1 << 31); var KEEPALIVE_TIMEOUT_MS = 2e4; @@ -69694,13 +70017,13 @@ var require_server2 = __commonJS({ addMessageSent: () => { if (channelzSessionInfo) { channelzSessionInfo.messagesSent += 1; - channelzSessionInfo.lastMessageSentTimestamp = /* @__PURE__ */ new Date(); + channelzSessionInfo.lastMessageSentTimestamp = Date.now(); } }, addMessageReceived: () => { if (channelzSessionInfo) { channelzSessionInfo.messagesReceived += 1; - channelzSessionInfo.lastMessageReceivedTimestamp = /* @__PURE__ */ new Date(); + channelzSessionInfo.lastMessageReceivedTimestamp = Date.now(); } }, onCallEnd: (status) => { @@ -70141,9 +70464,15 @@ var require_server2 = __commonJS({ try { handler2.func(stream2, respond); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } @@ -70177,9 +70506,15 @@ var require_server2 = __commonJS({ try { handler2.func(stream2, respond); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } @@ -70233,9 +70568,15 @@ var require_server2 = __commonJS({ try { handler2.func(stream2); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); } @@ -70257,9 +70598,15 @@ var require_server2 = __commonJS({ try { handler2.func(stream2); } catch (err) { + let details; + if (environment_1.GRPC_NODE_DEBUG_SEND_ERROR_DETAILS) { + details = `Server method handler threw error ${err.message}`; + } else { + details = "Unknown error"; + } call.sendStatus({ code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, + details, metadata: null }); }