From 7128495d1be140d64c09db9f8844efbf31154523 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 10 Nov 2026 16:58:41 -0600 Subject: [PATCH] feat(chat): hand Photon ingress to Cloud custody Keep provider transport and receipt ownership in the Photon modules. Preserve current audit and notification writes inside the actual transaction. Name the public SDK event return type and keep prepared replacement and attachment IDs stable across async client calls. Co-Authored-By: Paperclip --- package.json | 2 + patches/@grpc__grpc-js@1.14.5.patch | 3938 +++++++++++++++++ .../@photon-ai__advanced-imessage@2.2.0.patch | 30 + pnpm-workspace.yaml | 2 + .../__tests__/photon/external-owner.test.ts | 162 + server/src/__tests__/photon/photon.test.ts | 117 +- server/src/services/activity-log.ts | 17 +- server/src/services/chat-channels.ts | 57 +- .../chat-channels/imessage-photon/events.ts | 10 +- .../imessage-photon/external-contract.ts | 77 + .../imessage-photon/external-owner.ts | 177 + .../imessage-photon/external-runtime.ts | 255 ++ .../imessage-photon/external-store.ts | 92 + .../imessage-photon/runtime-callbacks.ts | 8 +- .../services/chat-channels/runtime-types.ts | 1 + .../runtime/receiver-schedule.ts | 8 +- .../src/services/chat-channels/sdk-state.ts | 2 +- server/src/services/chat-sdk-runtime.ts | 17 +- .../src/services/github-connection-events.ts | 14 + server/src/services/instance-settings.ts | 2 +- .../src/services/paperclip-cloud-connector.ts | 30 +- server/src/services/photon/adapter.ts | 105 +- server/src/services/photon/interactions.ts | 4 +- server/src/services/photon/owned-client.ts | 65 + server/src/services/photon/receiver.ts | 88 +- .../src/services/photon/recovery-transport.ts | 23 +- .../services/photon/transport-resources.ts | 76 + server/src/services/photon/useful-client.ts | 61 + 28 files changed, 5344 insertions(+), 96 deletions(-) create mode 100644 patches/@grpc__grpc-js@1.14.5.patch create mode 100644 patches/@photon-ai__advanced-imessage@2.2.0.patch create mode 100644 server/src/__tests__/photon/external-owner.test.ts create mode 100644 server/src/services/chat-channels/imessage-photon/external-contract.ts create mode 100644 server/src/services/chat-channels/imessage-photon/external-owner.ts create mode 100644 server/src/services/chat-channels/imessage-photon/external-runtime.ts create mode 100644 server/src/services/chat-channels/imessage-photon/external-store.ts create mode 100644 server/src/services/photon/owned-client.ts create mode 100644 server/src/services/photon/transport-resources.ts create mode 100644 server/src/services/photon/useful-client.ts diff --git a/package.json b/package.json index e670c9718e4..9bec6af681d 100644 --- a/package.json +++ b/package.json @@ -114,6 +114,8 @@ "packageManager": "pnpm@9.15.4", "pnpm": { "patchedDependencies": { + "@grpc/grpc-js@1.14.5": "patches/@grpc__grpc-js@1.14.5.patch", + "@photon-ai/advanced-imessage@2.2.0": "patches/@photon-ai__advanced-imessage@2.2.0.patch", "embedded-postgres@18.1.0-beta.16": "patches/embedded-postgres@18.1.0-beta.16.patch", "acpx@0.12.0": "patches/acpx@0.12.0.patch", "acpx@0.13.1": "patches/acpx@0.13.1.patch", diff --git a/patches/@grpc__grpc-js@1.14.5.patch b/patches/@grpc__grpc-js@1.14.5.patch new file mode 100644 index 00000000000..33b2f7bb0eb --- /dev/null +++ b/patches/@grpc__grpc-js@1.14.5.patch @@ -0,0 +1,3938 @@ +--- a/build/src/channel-credentials.js ++++ b/build/src/channel-credentials.js +@@ -166,7 +166,8 @@ + return connectionOptions; + } + class SecureConnectorImpl { +- constructor(connectionOptions, callCredentials) { ++ constructor(connectionOptions, callCredentials, transportOwner) { ++ this.transportOwner = transportOwner; + this.connectionOptions = connectionOptions; + this.callCredentials = callCredentials; + } +@@ -187,6 +188,10 @@ + tlsSocket.on('error', (error) => { + reject(error); + }); ++ if (this.transportOwner) { ++ tlsSocket.once('close', () => reject(new Error('Owned TLS socket closed before handshake completion'))); ++ this.transportOwner.socket(tlsSocket); ++ } + }); + } + waitForReady() { +@@ -221,7 +226,7 @@ + } + _createSecureConnector(channelTarget, options, callCredentials) { + const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); +- return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); ++ return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(), options['grpc-node.transport_owner']); + } + } + class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { +--- a/build/src/channel-options.d.ts ++++ b/build/src/channel-options.d.ts +@@ -2,7 +2,16 @@ + /** + * An interface that contains options used when initializing a Channel instance. + */ ++/** Opt-in ownership for a private channel pool. Default channels are unchanged. */ ++export interface TransportResourceOwner { ++ readonly signal: AbortSignal; ++ pending(operation: Promise): void; ++ socket(socket: import('net').Socket): void; ++ session(session: import('http2').ClientHttp2Session): void; ++ request(request: import('http').ClientRequest): void; ++} + export interface ChannelOptions { ++ 'grpc-node.transport_owner'?: TransportResourceOwner; + 'grpc.ssl_target_name_override'?: string; + 'grpc.primary_user_agent'?: string; + 'grpc.secondary_user_agent'?: string; +@@ -59,6 +68,7 @@ + 'grpc.initial_reconnect_backoff_ms': boolean; + 'grpc.max_reconnect_backoff_ms': boolean; + 'grpc.use_local_subchannel_pool': boolean; ++ 'grpc-node.transport_owner': boolean; + 'grpc.max_send_message_length': boolean; + 'grpc.max_receive_message_length': boolean; + 'grpc.enable_http_proxy': boolean; +--- a/build/src/channel-options.js ++++ b/build/src/channel-options.js +@@ -35,6 +35,7 @@ + 'grpc.initial_reconnect_backoff_ms': true, + 'grpc.max_reconnect_backoff_ms': true, + 'grpc.use_local_subchannel_pool': true, ++ 'grpc-node.transport_owner': true, + 'grpc.max_send_message_length': true, + 'grpc.max_receive_message_length': true, + 'grpc.enable_http_proxy': true, +--- a/build/src/http_proxy.js ++++ b/build/src/http_proxy.js +@@ -226,13 +226,26 @@ + Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'); + } + options.headers = headers; ++ if (channelOptions['grpc-node.transport_owner']) options.signal = channelOptions['grpc-node.transport_owner'].signal; + const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); + trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); + return new Promise((resolve, reject) => { + const request = http.request(options); ++ const owner = channelOptions['grpc-node.transport_owner']; ++ if (owner) { ++ request.once('socket', socket => owner.socket(socket)); ++ request.once('close', () => reject(new Error('Owned proxy request closed'))); ++ owner.request(request); ++ } + request.once('connect', (res, socket, head) => { + request.removeAllListeners(); + socket.removeAllListeners(); ++ if (owner) { ++ owner.request(request); ++ owner.socket(socket); ++ request.once('error', reject); ++ request.once('close', () => reject(new Error('Owned proxy request closed'))); ++ } + if (res.statusCode === 200) { + trace('Successfully connected to ' + + options.path + +@@ -262,6 +275,7 @@ + }); + request.once('error', err => { + request.removeAllListeners(); ++ if (owner) owner.request(request); + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' + + proxyAddressString + + ' with error ' + +--- a/build/src/transport.js ++++ b/build/src/transport.js +@@ -535,7 +535,8 @@ + if (this.isShutdown) { + return Promise.reject(); + } +- if (secureConnectResult.socket.closed) { ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ if (secureConnectResult.socket.closed) { + return Promise.reject('Connection closed before starting HTTP/2 handshake'); + } + return new Promise((resolve, reject) => { +@@ -613,6 +614,7 @@ + } + } + session.removeAllListeners(); ++ options['grpc-node.transport_owner']?.session(session); + secureConnectResult.socket.removeListener('close', closeHandler); + secureConnectResult.socket.removeListener('error', errorHandler); + resolve(new Http2Transport(session, address, options, remoteName)); +@@ -622,10 +624,13 @@ + session.once('error', errorHandler); + secureConnectResult.socket.once('close', closeHandler); + secureConnectResult.socket.once('error', errorHandler); ++ options['grpc-node.transport_owner']?.session(session); + }); + } + tcpConnect(address, options) { +- return (0, http_proxy_1.getProxiedConnection)(address, options).then(proxiedSocket => { ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ return (0, http_proxy_1.getProxiedConnection)(address, options).then(proxiedSocket => { ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); + if (proxiedSocket) { + return proxiedSocket; + } +@@ -644,11 +649,19 @@ + }); + socket.once('close', closeCallback); + socket.once('error', errorCallback); ++ options['grpc-node.transport_owner']?.socket(socket); + }); + } + }); + } +- async connect(address, secureConnector, options) { ++ connect(address, secureConnector, options) { ++ const owner = options['grpc-node.transport_owner']; ++ if (owner && options['grpc.use_local_subchannel_pool'] !== 1) return Promise.reject(new Error('Owned transport requires a private subchannel pool')); ++ const operation = this.connectOwned(address, secureConnector, options); ++ owner?.pending(operation); ++ return operation; ++ } ++ async connectOwned(address, secureConnector, options) { + if (this.isShutdown) { + return Promise.reject(); + } +@@ -659,16 +672,20 @@ + if (this.traceEnabled) { + this.trace(addressString + ' Waiting for secureConnector to be ready'); + } ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); + await secureConnector.waitForReady(); ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); + if (this.traceEnabled) { + this.trace(addressString + ' secureConnector is ready'); + } + tcpConnection = await this.tcpConnect(address, options); ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); + tcpConnection.setNoDelay(); + if (this.traceEnabled) { + this.trace(addressString + ' Established TCP connection'); + } + secureConnectResult = await secureConnector.connect(tcpConnection); ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); + if (this.traceEnabled) { + this.trace(addressString + ' Established secure connection'); + } +--- a/src/channel-credentials.ts ++++ b/src/channel-credentials.ts +@@ -1,523 +1,527 @@ +-/* +- * Copyright 2019 gRPC authors. +- * +- * Licensed under the Apache License, Version 2.0 (the "License"); +- * you may not use this file except in compliance with the License. +- * You may obtain a copy of the License at +- * +- * http://www.apache.org/licenses/LICENSE-2.0 +- * +- * Unless required by applicable law or agreed to in writing, software +- * distributed under the License is distributed on an "AS IS" BASIS, +- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +- * See the License for the specific language governing permissions and +- * limitations under the License. +- * +- */ +- +-import { +- ConnectionOptions, +- createSecureContext, +- PeerCertificate, +- SecureContext, +- checkServerIdentity, +- connect as tlsConnect +-} from 'tls'; +- +-import { CallCredentials } from './call-credentials'; +-import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers'; +-import { CaCertificateUpdate, CaCertificateUpdateListener, CertificateProvider, IdentityCertificateUpdate, IdentityCertificateUpdateListener } from './certificate-provider'; +-import { Socket } from 'net'; +-import { ChannelOptions } from './channel-options'; +-import { GrpcUri, parseUri, splitHostPort } from './uri-parser'; +-import { getDefaultAuthority } from './resolver'; +-import { log } from './logging'; +-import { LogVerbosity } from './constants'; +- +-// eslint-disable-next-line @typescript-eslint/no-explicit-any +-function verifyIsBufferOrNull(obj: any, friendlyName: string): void { +- if (obj && !(obj instanceof Buffer)) { +- throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); +- } +-} +- +-/** +- * A callback that will receive the expected hostname and presented peer +- * certificate as parameters. The callback should return an error to +- * indicate that the presented certificate is considered invalid and +- * otherwise returned undefined. +- */ +-export type CheckServerIdentityCallback = ( +- hostname: string, +- cert: PeerCertificate +-) => Error | undefined; +- +-/** +- * Additional peer verification options that can be set when creating +- * SSL credentials. +- */ +-export interface VerifyOptions { +- /** +- * If set, this callback will be invoked after the usual hostname verification +- * has been performed on the peer certificate. +- */ +- checkServerIdentity?: CheckServerIdentityCallback; +- rejectUnauthorized?: boolean; +-} +- +-export interface SecureConnectResult { +- socket: Socket; +- secure: boolean; +-} +- +-export interface SecureConnector { +- connect(socket: Socket): Promise; +- waitForReady(): Promise; +- getCallCredentials(): CallCredentials; +- destroy(): void; +-} +- +-/** +- * A class that contains credentials for communicating over a channel, as well +- * as a set of per-call credentials, which are applied to every method call made +- * over a channel initialized with an instance of this class. +- */ +-export abstract class ChannelCredentials { +- /** +- * Returns a copy of this object with the included set of per-call credentials +- * expanded to include callCredentials. +- * @param callCredentials A CallCredentials object to associate with this +- * instance. +- */ +- compose(callCredentials: CallCredentials): ChannelCredentials { +- return new ComposedChannelCredentialsImpl(this, callCredentials); +- } +- +- /** +- * Indicates whether this credentials object creates a secure channel. +- */ +- abstract _isSecure(): boolean; +- +- /** +- * Check whether two channel credentials objects are equal. Two secure +- * credentials are equal if they were constructed with the same parameters. +- * @param other The other ChannelCredentials Object +- */ +- abstract _equals(other: ChannelCredentials): boolean; +- +- abstract _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector; +- +- /** +- * Return a new ChannelCredentials instance with a given set of credentials. +- * The resulting instance can be used to construct a Channel that communicates +- * over TLS. +- * @param rootCerts The root certificate data. +- * @param privateKey The client certificate private key, if available. +- * @param certChain The client certificate key chain, if available. +- * @param verifyOptions Additional options to modify certificate verification +- */ +- static createSsl( +- rootCerts?: Buffer | null, +- privateKey?: Buffer | null, +- certChain?: Buffer | null, +- verifyOptions?: VerifyOptions +- ): ChannelCredentials { +- verifyIsBufferOrNull(rootCerts, 'Root certificate'); +- verifyIsBufferOrNull(privateKey, 'Private key'); +- verifyIsBufferOrNull(certChain, 'Certificate chain'); +- if (privateKey && !certChain) { +- throw new Error( +- 'Private key must be given with accompanying certificate chain' +- ); +- } +- if (!privateKey && certChain) { +- throw new Error( +- 'Certificate chain must be given with accompanying private key' +- ); +- } +- const secureContext = createSecureContext({ +- ca: rootCerts ?? getDefaultRootsData() ?? undefined, +- key: privateKey ?? undefined, +- cert: certChain ?? undefined, +- ciphers: CIPHER_SUITES, +- }); +- return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); +- } +- +- /** +- * Return a new ChannelCredentials instance with credentials created using +- * the provided secureContext. The resulting instances can be used to +- * construct a Channel that communicates over TLS. gRPC will not override +- * anything in the provided secureContext, so the environment variables +- * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will +- * not be applied. +- * @param secureContext The return value of tls.createSecureContext() +- * @param verifyOptions Additional options to modify certificate verification +- */ +- static createFromSecureContext( +- secureContext: SecureContext, +- verifyOptions?: VerifyOptions +- ): ChannelCredentials { +- return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); +- } +- +- /** +- * Return a new ChannelCredentials instance with no credentials. +- */ +- static createInsecure(): ChannelCredentials { +- return new InsecureChannelCredentialsImpl(); +- } +-} +- +-class InsecureChannelCredentialsImpl extends ChannelCredentials { +- constructor() { +- super(); +- } +- +- override compose(callCredentials: CallCredentials): never { +- throw new Error('Cannot compose insecure credentials'); +- } +- _isSecure(): boolean { +- return false; +- } +- _equals(other: ChannelCredentials): boolean { +- return other instanceof InsecureChannelCredentialsImpl; +- } +- _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { +- return { +- connect(socket) { +- return Promise.resolve({ +- socket, +- secure: false +- }); +- }, +- waitForReady: () => { +- return Promise.resolve(); +- }, +- getCallCredentials: () => { +- return callCredentials ?? CallCredentials.createEmpty(); +- }, +- destroy() {} +- } +- } +-} +- +-function getConnectionOptions(secureContext: SecureContext, verifyOptions: VerifyOptions, channelTarget: GrpcUri, options: ChannelOptions): ConnectionOptions { +- const connectionOptions: ConnectionOptions = { +- secureContext: secureContext +- }; +- let realTarget: GrpcUri = channelTarget; +- if ('grpc.http_connect_target' in options) { +- const parsedTarget = parseUri(options['grpc.http_connect_target']!); +- if (parsedTarget) { +- realTarget = parsedTarget; +- } +- } +- const targetPath = getDefaultAuthority(realTarget); +- const hostPort = splitHostPort(targetPath); +- const remoteHost = hostPort?.host ?? targetPath; +- connectionOptions.host = remoteHost; +- +- if (verifyOptions.checkServerIdentity) { +- connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; +- } +- if (verifyOptions.rejectUnauthorized !== undefined) { +- connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; +- } +- connectionOptions.ALPNProtocols = ['h2']; +- if (options['grpc.ssl_target_name_override']) { +- const sslTargetNameOverride = options['grpc.ssl_target_name_override']!; +- const originalCheckServerIdentity = +- connectionOptions.checkServerIdentity ?? checkServerIdentity; +- connectionOptions.checkServerIdentity = ( +- host: string, +- cert: PeerCertificate +- ): Error | undefined => { +- return originalCheckServerIdentity(sslTargetNameOverride, cert); +- }; +- connectionOptions.servername = sslTargetNameOverride; +- } else { +- connectionOptions.servername = remoteHost; +- } +- if (options['grpc-node.tls_enable_trace']) { +- connectionOptions.enableTrace = true; +- } +- return connectionOptions; +-} +- +-class SecureConnectorImpl implements SecureConnector { +- constructor(private connectionOptions: ConnectionOptions, private callCredentials: CallCredentials) { +- } +- connect(socket: Socket): Promise { +- const tlsConnectOptions: ConnectionOptions = { +- socket: socket, +- ...this.connectionOptions +- }; +- return new Promise((resolve, reject) => { +- const tlsSocket = tlsConnect(tlsConnectOptions, () => { +- if ((this.connectionOptions.rejectUnauthorized ?? true) && !tlsSocket.authorized) { +- reject(tlsSocket.authorizationError); +- return; +- } +- resolve({ +- socket: tlsSocket, +- secure: true +- }) +- }); +- tlsSocket.on('error', (error: Error) => { +- reject(error); +- }); +- }); +- } +- waitForReady(): Promise { +- return Promise.resolve(); +- } +- getCallCredentials(): CallCredentials { +- return this.callCredentials; +- } +- destroy() {} +-} +- +-class SecureChannelCredentialsImpl extends ChannelCredentials { +- constructor( +- private secureContext: SecureContext, +- private verifyOptions: VerifyOptions +- ) { +- super(); +- } +- +- _isSecure(): boolean { +- return true; +- } +- _equals(other: ChannelCredentials): boolean { +- if (this === other) { +- return true; +- } +- if (other instanceof SecureChannelCredentialsImpl) { +- return ( +- this.secureContext === other.secureContext && +- this.verifyOptions.checkServerIdentity === +- other.verifyOptions.checkServerIdentity +- ); +- } else { +- return false; +- } +- } +- _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { +- const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); +- return new SecureConnectorImpl(connectionOptions, callCredentials ?? CallCredentials.createEmpty()); +- } +-} +- +-class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { +- private refcount: number = 0; +- /** +- * `undefined` means that the certificates have not yet been loaded. `null` +- * means that an attempt to load them has completed, and has failed. +- */ +- private latestCaUpdate: CaCertificateUpdate | null | undefined = undefined; +- /** +- * `undefined` means that the certificates have not yet been loaded. `null` +- * means that an attempt to load them has completed, and has failed. +- */ +- private latestIdentityUpdate: IdentityCertificateUpdate | null | undefined = undefined; +- private caCertificateUpdateListener: CaCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); +- private identityCertificateUpdateListener: IdentityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); +- private secureContextWatchers: ((context: SecureContext | null) => void)[] = []; +- private static SecureConnectorImpl = class implements SecureConnector { +- constructor(private parent: CertificateProviderChannelCredentialsImpl, private channelTarget: GrpcUri, private options: ChannelOptions, private callCredentials: CallCredentials) {} +- +- connect(socket: Socket): Promise { +- return new Promise((resolve, reject) => { +- const secureContext = this.parent.getLatestSecureContext(); +- if (!secureContext) { +- reject(new Error('Failed to load credentials')); +- return; +- } +- if (socket.closed) { +- reject(new Error('Socket closed while loading credentials')); +- } +- const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); +- const tlsConnectOptions: ConnectionOptions = { +- socket: socket, +- ...connnectionOptions +- } +- const closeCallback = () => { +- reject(new Error('Socket closed')); +- }; +- const errorCallback = (error: Error) => { +- reject(error); +- } +- const tlsSocket = tlsConnect(tlsConnectOptions, () => { +- tlsSocket.removeListener('close', closeCallback); +- tlsSocket.removeListener('error', errorCallback); +- if ((this.parent.verifyOptions.rejectUnauthorized ?? true) && !tlsSocket.authorized) { +- reject(tlsSocket.authorizationError); +- return; +- } +- resolve({ +- socket: tlsSocket, +- secure: true +- }); +- }); +- tlsSocket.once('close', closeCallback); +- tlsSocket.once('error', errorCallback); +- }); +- } +- +- async waitForReady(): Promise { +- await this.parent.getSecureContext(); +- } +- +- getCallCredentials(): CallCredentials { +- return this.callCredentials; +- } +- +- destroy() { +- this.parent.unref(); +- } +- } +- constructor( +- private caCertificateProvider: CertificateProvider, +- private identityCertificateProvider: CertificateProvider | null, +- private verifyOptions: VerifyOptions +- ) { +- super(); +- } +- _isSecure(): boolean { +- return true; +- } +- _equals(other: ChannelCredentials): boolean { +- if (this === other) { +- return true; +- } +- if (other instanceof CertificateProviderChannelCredentialsImpl) { +- return this.caCertificateProvider === other.caCertificateProvider && +- this.identityCertificateProvider === other.identityCertificateProvider && +- this.verifyOptions?.checkServerIdentity === other.verifyOptions?.checkServerIdentity; +- } else { +- return false; +- } +- } +- private ref(): void { +- if (this.refcount === 0) { +- this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); +- this.identityCertificateProvider?.addIdentityCertificateListener(this.identityCertificateUpdateListener); +- } +- this.refcount += 1; +- } +- private unref(): void { +- this.refcount -= 1; +- if (this.refcount === 0) { +- this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); +- this.identityCertificateProvider?.removeIdentityCertificateListener(this.identityCertificateUpdateListener); +- } +- } +- _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { +- this.ref(); +- return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials ?? CallCredentials.createEmpty()); +- } +- +- private maybeUpdateWatchers() { +- if (this.hasReceivedUpdates()) { +- for (const watcher of this.secureContextWatchers) { +- watcher(this.getLatestSecureContext()); +- } +- this.secureContextWatchers = []; +- } +- } +- +- private handleCaCertificateUpdate(update: CaCertificateUpdate | null) { +- this.latestCaUpdate = update; +- this.maybeUpdateWatchers(); +- } +- +- private handleIdentityCertitificateUpdate(update: IdentityCertificateUpdate | null) { +- this.latestIdentityUpdate = update; +- this.maybeUpdateWatchers(); +- } +- +- private hasReceivedUpdates(): boolean { +- if (this.latestCaUpdate === undefined) { +- return false; +- } +- if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { +- return false; +- } +- return true; +- } +- +- private getSecureContext(): Promise { +- if (this.hasReceivedUpdates()) { +- return Promise.resolve(this.getLatestSecureContext()); +- } else { +- return new Promise(resolve => { +- this.secureContextWatchers.push(resolve); +- }); +- } +- } +- +- private getLatestSecureContext(): SecureContext | null { +- if (!this.latestCaUpdate) { +- return null; +- } +- if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { +- return null; +- } +- try { +- return createSecureContext({ +- ca: this.latestCaUpdate.caCertificate, +- key: this.latestIdentityUpdate?.privateKey, +- cert: this.latestIdentityUpdate?.certificate, +- ciphers: CIPHER_SUITES +- }); +- } catch (e) { +- log(LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + (e as Error).message); +- return null; +- } +- } +-} +- +-export function createCertificateProviderChannelCredentials(caCertificateProvider: CertificateProvider, identityCertificateProvider: CertificateProvider | null, verifyOptions?: VerifyOptions) { +- return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions ?? {}); +-} +- +-class ComposedChannelCredentialsImpl extends ChannelCredentials { +- constructor( +- private channelCredentials: ChannelCredentials, +- private callCredentials: CallCredentials +- ) { +- super(); +- if (!channelCredentials._isSecure()) { +- throw new Error('Cannot compose insecure credentials'); +- } +- } +- compose(callCredentials: CallCredentials) { +- const combinedCallCredentials = +- this.callCredentials.compose(callCredentials); +- return new ComposedChannelCredentialsImpl( +- this.channelCredentials, +- combinedCallCredentials +- ); +- } +- _isSecure(): boolean { +- return true; +- } +- _equals(other: ChannelCredentials): boolean { +- if (this === other) { +- return true; +- } +- if (other instanceof ComposedChannelCredentialsImpl) { +- return ( +- this.channelCredentials._equals(other.channelCredentials) && +- this.callCredentials._equals(other.callCredentials) +- ); +- } else { +- return false; +- } +- } +- _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { +- const combinedCallCredentials = this.callCredentials.compose(callCredentials ?? CallCredentials.createEmpty()); +- return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); +- } +-} ++/* ++ * Copyright 2019 gRPC authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ * ++ */ ++ ++import { ++ ConnectionOptions, ++ createSecureContext, ++ PeerCertificate, ++ SecureContext, ++ checkServerIdentity, ++ connect as tlsConnect ++} from 'tls'; ++ ++import { CallCredentials } from './call-credentials'; ++import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers'; ++import { CaCertificateUpdate, CaCertificateUpdateListener, CertificateProvider, IdentityCertificateUpdate, IdentityCertificateUpdateListener } from './certificate-provider'; ++import { Socket } from 'net'; ++import { ChannelOptions } from './channel-options'; ++import { GrpcUri, parseUri, splitHostPort } from './uri-parser'; ++import { getDefaultAuthority } from './resolver'; ++import { log } from './logging'; ++import { LogVerbosity } from './constants'; ++ ++// eslint-disable-next-line @typescript-eslint/no-explicit-any ++function verifyIsBufferOrNull(obj: any, friendlyName: string): void { ++ if (obj && !(obj instanceof Buffer)) { ++ throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); ++ } ++} ++ ++/** ++ * A callback that will receive the expected hostname and presented peer ++ * certificate as parameters. The callback should return an error to ++ * indicate that the presented certificate is considered invalid and ++ * otherwise returned undefined. ++ */ ++export type CheckServerIdentityCallback = ( ++ hostname: string, ++ cert: PeerCertificate ++) => Error | undefined; ++ ++/** ++ * Additional peer verification options that can be set when creating ++ * SSL credentials. ++ */ ++export interface VerifyOptions { ++ /** ++ * If set, this callback will be invoked after the usual hostname verification ++ * has been performed on the peer certificate. ++ */ ++ checkServerIdentity?: CheckServerIdentityCallback; ++ rejectUnauthorized?: boolean; ++} ++ ++export interface SecureConnectResult { ++ socket: Socket; ++ secure: boolean; ++} ++ ++export interface SecureConnector { ++ connect(socket: Socket): Promise; ++ waitForReady(): Promise; ++ getCallCredentials(): CallCredentials; ++ destroy(): void; ++} ++ ++/** ++ * A class that contains credentials for communicating over a channel, as well ++ * as a set of per-call credentials, which are applied to every method call made ++ * over a channel initialized with an instance of this class. ++ */ ++export abstract class ChannelCredentials { ++ /** ++ * Returns a copy of this object with the included set of per-call credentials ++ * expanded to include callCredentials. ++ * @param callCredentials A CallCredentials object to associate with this ++ * instance. ++ */ ++ compose(callCredentials: CallCredentials): ChannelCredentials { ++ return new ComposedChannelCredentialsImpl(this, callCredentials); ++ } ++ ++ /** ++ * Indicates whether this credentials object creates a secure channel. ++ */ ++ abstract _isSecure(): boolean; ++ ++ /** ++ * Check whether two channel credentials objects are equal. Two secure ++ * credentials are equal if they were constructed with the same parameters. ++ * @param other The other ChannelCredentials Object ++ */ ++ abstract _equals(other: ChannelCredentials): boolean; ++ ++ abstract _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector; ++ ++ /** ++ * Return a new ChannelCredentials instance with a given set of credentials. ++ * The resulting instance can be used to construct a Channel that communicates ++ * over TLS. ++ * @param rootCerts The root certificate data. ++ * @param privateKey The client certificate private key, if available. ++ * @param certChain The client certificate key chain, if available. ++ * @param verifyOptions Additional options to modify certificate verification ++ */ ++ static createSsl( ++ rootCerts?: Buffer | null, ++ privateKey?: Buffer | null, ++ certChain?: Buffer | null, ++ verifyOptions?: VerifyOptions ++ ): ChannelCredentials { ++ verifyIsBufferOrNull(rootCerts, 'Root certificate'); ++ verifyIsBufferOrNull(privateKey, 'Private key'); ++ verifyIsBufferOrNull(certChain, 'Certificate chain'); ++ if (privateKey && !certChain) { ++ throw new Error( ++ 'Private key must be given with accompanying certificate chain' ++ ); ++ } ++ if (!privateKey && certChain) { ++ throw new Error( ++ 'Certificate chain must be given with accompanying private key' ++ ); ++ } ++ const secureContext = createSecureContext({ ++ ca: rootCerts ?? getDefaultRootsData() ?? undefined, ++ key: privateKey ?? undefined, ++ cert: certChain ?? undefined, ++ ciphers: CIPHER_SUITES, ++ }); ++ return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); ++ } ++ ++ /** ++ * Return a new ChannelCredentials instance with credentials created using ++ * the provided secureContext. The resulting instances can be used to ++ * construct a Channel that communicates over TLS. gRPC will not override ++ * anything in the provided secureContext, so the environment variables ++ * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will ++ * not be applied. ++ * @param secureContext The return value of tls.createSecureContext() ++ * @param verifyOptions Additional options to modify certificate verification ++ */ ++ static createFromSecureContext( ++ secureContext: SecureContext, ++ verifyOptions?: VerifyOptions ++ ): ChannelCredentials { ++ return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); ++ } ++ ++ /** ++ * Return a new ChannelCredentials instance with no credentials. ++ */ ++ static createInsecure(): ChannelCredentials { ++ return new InsecureChannelCredentialsImpl(); ++ } ++} ++ ++class InsecureChannelCredentialsImpl extends ChannelCredentials { ++ constructor() { ++ super(); ++ } ++ ++ override compose(callCredentials: CallCredentials): never { ++ throw new Error('Cannot compose insecure credentials'); ++ } ++ _isSecure(): boolean { ++ return false; ++ } ++ _equals(other: ChannelCredentials): boolean { ++ return other instanceof InsecureChannelCredentialsImpl; ++ } ++ _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { ++ return { ++ connect(socket) { ++ return Promise.resolve({ ++ socket, ++ secure: false ++ }); ++ }, ++ waitForReady: () => { ++ return Promise.resolve(); ++ }, ++ getCallCredentials: () => { ++ return callCredentials ?? CallCredentials.createEmpty(); ++ }, ++ destroy() {} ++ } ++ } ++} ++ ++function getConnectionOptions(secureContext: SecureContext, verifyOptions: VerifyOptions, channelTarget: GrpcUri, options: ChannelOptions): ConnectionOptions { ++ const connectionOptions: ConnectionOptions = { ++ secureContext: secureContext ++ }; ++ let realTarget: GrpcUri = channelTarget; ++ if ('grpc.http_connect_target' in options) { ++ const parsedTarget = parseUri(options['grpc.http_connect_target']!); ++ if (parsedTarget) { ++ realTarget = parsedTarget; ++ } ++ } ++ const targetPath = getDefaultAuthority(realTarget); ++ const hostPort = splitHostPort(targetPath); ++ const remoteHost = hostPort?.host ?? targetPath; ++ connectionOptions.host = remoteHost; ++ ++ if (verifyOptions.checkServerIdentity) { ++ connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; ++ } ++ if (verifyOptions.rejectUnauthorized !== undefined) { ++ connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; ++ } ++ connectionOptions.ALPNProtocols = ['h2']; ++ if (options['grpc.ssl_target_name_override']) { ++ const sslTargetNameOverride = options['grpc.ssl_target_name_override']!; ++ const originalCheckServerIdentity = ++ connectionOptions.checkServerIdentity ?? checkServerIdentity; ++ connectionOptions.checkServerIdentity = ( ++ host: string, ++ cert: PeerCertificate ++ ): Error | undefined => { ++ return originalCheckServerIdentity(sslTargetNameOverride, cert); ++ }; ++ connectionOptions.servername = sslTargetNameOverride; ++ } else { ++ connectionOptions.servername = remoteHost; ++ } ++ if (options['grpc-node.tls_enable_trace']) { ++ connectionOptions.enableTrace = true; ++ } ++ return connectionOptions; ++} ++ ++class SecureConnectorImpl implements SecureConnector { ++ constructor(private connectionOptions: ConnectionOptions, private callCredentials: CallCredentials, private transportOwner?: ChannelOptions['grpc-node.transport_owner']) { ++ } ++ connect(socket: Socket): Promise { ++ const tlsConnectOptions: ConnectionOptions = { ++ socket: socket, ++ ...this.connectionOptions ++ }; ++ return new Promise((resolve, reject) => { ++ const tlsSocket = tlsConnect(tlsConnectOptions, () => { ++ if ((this.connectionOptions.rejectUnauthorized ?? true) && !tlsSocket.authorized) { ++ reject(tlsSocket.authorizationError); ++ return; ++ } ++ resolve({ ++ socket: tlsSocket, ++ secure: true ++ }) ++ }); ++ tlsSocket.on('error', (error: Error) => { ++ reject(error); ++ }); ++ if (this.transportOwner) { ++ tlsSocket.once('close', () => reject(new Error('Owned TLS socket closed before handshake completion'))); ++ this.transportOwner.socket(tlsSocket); ++ } ++ }); ++ } ++ waitForReady(): Promise { ++ return Promise.resolve(); ++ } ++ getCallCredentials(): CallCredentials { ++ return this.callCredentials; ++ } ++ destroy() {} ++} ++ ++class SecureChannelCredentialsImpl extends ChannelCredentials { ++ constructor( ++ private secureContext: SecureContext, ++ private verifyOptions: VerifyOptions ++ ) { ++ super(); ++ } ++ ++ _isSecure(): boolean { ++ return true; ++ } ++ _equals(other: ChannelCredentials): boolean { ++ if (this === other) { ++ return true; ++ } ++ if (other instanceof SecureChannelCredentialsImpl) { ++ return ( ++ this.secureContext === other.secureContext && ++ this.verifyOptions.checkServerIdentity === ++ other.verifyOptions.checkServerIdentity ++ ); ++ } else { ++ return false; ++ } ++ } ++ _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { ++ const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); ++ return new SecureConnectorImpl(connectionOptions, callCredentials ?? CallCredentials.createEmpty(), options['grpc-node.transport_owner']); ++ } ++} ++ ++class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { ++ private refcount: number = 0; ++ /** ++ * `undefined` means that the certificates have not yet been loaded. `null` ++ * means that an attempt to load them has completed, and has failed. ++ */ ++ private latestCaUpdate: CaCertificateUpdate | null | undefined = undefined; ++ /** ++ * `undefined` means that the certificates have not yet been loaded. `null` ++ * means that an attempt to load them has completed, and has failed. ++ */ ++ private latestIdentityUpdate: IdentityCertificateUpdate | null | undefined = undefined; ++ private caCertificateUpdateListener: CaCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); ++ private identityCertificateUpdateListener: IdentityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); ++ private secureContextWatchers: ((context: SecureContext | null) => void)[] = []; ++ private static SecureConnectorImpl = class implements SecureConnector { ++ constructor(private parent: CertificateProviderChannelCredentialsImpl, private channelTarget: GrpcUri, private options: ChannelOptions, private callCredentials: CallCredentials) {} ++ ++ connect(socket: Socket): Promise { ++ return new Promise((resolve, reject) => { ++ const secureContext = this.parent.getLatestSecureContext(); ++ if (!secureContext) { ++ reject(new Error('Failed to load credentials')); ++ return; ++ } ++ if (socket.closed) { ++ reject(new Error('Socket closed while loading credentials')); ++ } ++ const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); ++ const tlsConnectOptions: ConnectionOptions = { ++ socket: socket, ++ ...connnectionOptions ++ } ++ const closeCallback = () => { ++ reject(new Error('Socket closed')); ++ }; ++ const errorCallback = (error: Error) => { ++ reject(error); ++ } ++ const tlsSocket = tlsConnect(tlsConnectOptions, () => { ++ tlsSocket.removeListener('close', closeCallback); ++ tlsSocket.removeListener('error', errorCallback); ++ if ((this.parent.verifyOptions.rejectUnauthorized ?? true) && !tlsSocket.authorized) { ++ reject(tlsSocket.authorizationError); ++ return; ++ } ++ resolve({ ++ socket: tlsSocket, ++ secure: true ++ }); ++ }); ++ tlsSocket.once('close', closeCallback); ++ tlsSocket.once('error', errorCallback); ++ }); ++ } ++ ++ async waitForReady(): Promise { ++ await this.parent.getSecureContext(); ++ } ++ ++ getCallCredentials(): CallCredentials { ++ return this.callCredentials; ++ } ++ ++ destroy() { ++ this.parent.unref(); ++ } ++ } ++ constructor( ++ private caCertificateProvider: CertificateProvider, ++ private identityCertificateProvider: CertificateProvider | null, ++ private verifyOptions: VerifyOptions ++ ) { ++ super(); ++ } ++ _isSecure(): boolean { ++ return true; ++ } ++ _equals(other: ChannelCredentials): boolean { ++ if (this === other) { ++ return true; ++ } ++ if (other instanceof CertificateProviderChannelCredentialsImpl) { ++ return this.caCertificateProvider === other.caCertificateProvider && ++ this.identityCertificateProvider === other.identityCertificateProvider && ++ this.verifyOptions?.checkServerIdentity === other.verifyOptions?.checkServerIdentity; ++ } else { ++ return false; ++ } ++ } ++ private ref(): void { ++ if (this.refcount === 0) { ++ this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); ++ this.identityCertificateProvider?.addIdentityCertificateListener(this.identityCertificateUpdateListener); ++ } ++ this.refcount += 1; ++ } ++ private unref(): void { ++ this.refcount -= 1; ++ if (this.refcount === 0) { ++ this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); ++ this.identityCertificateProvider?.removeIdentityCertificateListener(this.identityCertificateUpdateListener); ++ } ++ } ++ _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { ++ this.ref(); ++ return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials ?? CallCredentials.createEmpty()); ++ } ++ ++ private maybeUpdateWatchers() { ++ if (this.hasReceivedUpdates()) { ++ for (const watcher of this.secureContextWatchers) { ++ watcher(this.getLatestSecureContext()); ++ } ++ this.secureContextWatchers = []; ++ } ++ } ++ ++ private handleCaCertificateUpdate(update: CaCertificateUpdate | null) { ++ this.latestCaUpdate = update; ++ this.maybeUpdateWatchers(); ++ } ++ ++ private handleIdentityCertitificateUpdate(update: IdentityCertificateUpdate | null) { ++ this.latestIdentityUpdate = update; ++ this.maybeUpdateWatchers(); ++ } ++ ++ private hasReceivedUpdates(): boolean { ++ if (this.latestCaUpdate === undefined) { ++ return false; ++ } ++ if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { ++ return false; ++ } ++ return true; ++ } ++ ++ private getSecureContext(): Promise { ++ if (this.hasReceivedUpdates()) { ++ return Promise.resolve(this.getLatestSecureContext()); ++ } else { ++ return new Promise(resolve => { ++ this.secureContextWatchers.push(resolve); ++ }); ++ } ++ } ++ ++ private getLatestSecureContext(): SecureContext | null { ++ if (!this.latestCaUpdate) { ++ return null; ++ } ++ if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { ++ return null; ++ } ++ try { ++ return createSecureContext({ ++ ca: this.latestCaUpdate.caCertificate, ++ key: this.latestIdentityUpdate?.privateKey, ++ cert: this.latestIdentityUpdate?.certificate, ++ ciphers: CIPHER_SUITES ++ }); ++ } catch (e) { ++ log(LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + (e as Error).message); ++ return null; ++ } ++ } ++} ++ ++export function createCertificateProviderChannelCredentials(caCertificateProvider: CertificateProvider, identityCertificateProvider: CertificateProvider | null, verifyOptions?: VerifyOptions) { ++ return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions ?? {}); ++} ++ ++class ComposedChannelCredentialsImpl extends ChannelCredentials { ++ constructor( ++ private channelCredentials: ChannelCredentials, ++ private callCredentials: CallCredentials ++ ) { ++ super(); ++ if (!channelCredentials._isSecure()) { ++ throw new Error('Cannot compose insecure credentials'); ++ } ++ } ++ compose(callCredentials: CallCredentials) { ++ const combinedCallCredentials = ++ this.callCredentials.compose(callCredentials); ++ return new ComposedChannelCredentialsImpl( ++ this.channelCredentials, ++ combinedCallCredentials ++ ); ++ } ++ _isSecure(): boolean { ++ return true; ++ } ++ _equals(other: ChannelCredentials): boolean { ++ if (this === other) { ++ return true; ++ } ++ if (other instanceof ComposedChannelCredentialsImpl) { ++ return ( ++ this.channelCredentials._equals(other.channelCredentials) && ++ this.callCredentials._equals(other.callCredentials) ++ ); ++ } else { ++ return false; ++ } ++ } ++ _createSecureConnector(channelTarget: GrpcUri, options: ChannelOptions, callCredentials?: CallCredentials): SecureConnector { ++ const combinedCallCredentials = this.callCredentials.compose(callCredentials ?? CallCredentials.createEmpty()); ++ return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); ++ } ++} +--- a/src/channel-options.ts ++++ b/src/channel-options.ts +@@ -1,128 +1,138 @@ +-/* +- * Copyright 2019 gRPC authors. +- * +- * Licensed under the Apache License, Version 2.0 (the "License"); +- * you may not use this file except in compliance with the License. +- * You may obtain a copy of the License at +- * +- * http://www.apache.org/licenses/LICENSE-2.0 +- * +- * Unless required by applicable law or agreed to in writing, software +- * distributed under the License is distributed on an "AS IS" BASIS, +- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +- * See the License for the specific language governing permissions and +- * limitations under the License. +- * +- */ +- +-import { CompressionAlgorithms } from './compression-algorithms'; +- +-/** +- * An interface that contains options used when initializing a Channel instance. +- */ +-export interface ChannelOptions { +- 'grpc.ssl_target_name_override'?: string; +- 'grpc.primary_user_agent'?: string; +- 'grpc.secondary_user_agent'?: string; +- 'grpc.default_authority'?: string; +- 'grpc.keepalive_time_ms'?: number; +- 'grpc.keepalive_timeout_ms'?: number; +- 'grpc.keepalive_permit_without_calls'?: number; +- 'grpc.service_config'?: string; +- 'grpc.max_concurrent_streams'?: number; +- 'grpc.initial_reconnect_backoff_ms'?: number; +- 'grpc.max_reconnect_backoff_ms'?: number; +- 'grpc.use_local_subchannel_pool'?: number; +- 'grpc.max_send_message_length'?: number; +- 'grpc.max_receive_message_length'?: number; +- 'grpc.enable_http_proxy'?: number; +- /* http_connect_target and http_connect_creds are used for passing data +- * around internally, and should not be documented as public-facing options +- */ +- 'grpc.http_connect_target'?: string; +- 'grpc.http_connect_creds'?: string; +- 'grpc.default_compression_algorithm'?: CompressionAlgorithms; +- 'grpc.enable_channelz'?: number; +- 'grpc.dns_min_time_between_resolutions_ms'?: number; +- 'grpc.enable_retries'?: number; +- 'grpc.per_rpc_retry_buffer_size'?: number; +- /* This option is pattered like a core option, but the core does not have +- * this option. It is closely related to the option +- * grpc.per_rpc_retry_buffer_size, which is in the core. The core will likely +- * implement this functionality using the ResourceQuota mechanism, so there +- * will probably not be any collision or other inconsistency. */ +- 'grpc.retry_buffer_size'?: number; +- 'grpc.max_connection_age_ms'?: number; +- 'grpc.max_connection_age_grace_ms'?: number; +- 'grpc.max_connection_idle_ms'?: number; +- 'grpc-node.max_session_memory'?: number; +- 'grpc.service_config_disable_resolution'?: number; +- 'grpc.client_idle_timeout_ms'?: number; +- /** +- * Set the enableTrace option in TLS clients and servers +- */ +- 'grpc-node.tls_enable_trace'?: number; +- 'grpc.lb.ring_hash.ring_size_cap'?: number; +- 'grpc-node.retry_max_attempts_limit'?: number; +- 'grpc-node.flow_control_window'?: number; +- 'grpc.server_call_metric_recording'?: number; +- // eslint-disable-next-line @typescript-eslint/no-explicit-any +- [key: string]: any; +-} +- +-/** +- * This is for checking provided options at runtime. This is an object for +- * easier membership checking. +- */ +-export const recognizedOptions = { +- 'grpc.ssl_target_name_override': true, +- 'grpc.primary_user_agent': true, +- 'grpc.secondary_user_agent': true, +- 'grpc.default_authority': true, +- 'grpc.keepalive_time_ms': true, +- 'grpc.keepalive_timeout_ms': true, +- 'grpc.keepalive_permit_without_calls': true, +- 'grpc.service_config': true, +- 'grpc.max_concurrent_streams': true, +- 'grpc.initial_reconnect_backoff_ms': true, +- 'grpc.max_reconnect_backoff_ms': true, +- 'grpc.use_local_subchannel_pool': true, +- 'grpc.max_send_message_length': true, +- 'grpc.max_receive_message_length': true, +- 'grpc.enable_http_proxy': true, +- 'grpc.enable_channelz': true, +- 'grpc.dns_min_time_between_resolutions_ms': true, +- 'grpc.enable_retries': true, +- 'grpc.per_rpc_retry_buffer_size': true, +- 'grpc.retry_buffer_size': true, +- 'grpc.max_connection_age_ms': true, +- 'grpc.max_connection_age_grace_ms': true, +- 'grpc-node.max_session_memory': true, +- 'grpc.service_config_disable_resolution': true, +- 'grpc.client_idle_timeout_ms': true, +- 'grpc-node.tls_enable_trace': true, +- 'grpc.lb.ring_hash.ring_size_cap': true, +- 'grpc-node.retry_max_attempts_limit': true, +- 'grpc-node.flow_control_window': true, +- 'grpc.server_call_metric_recording': true +-}; +- +-export function channelOptionsEqual( +- options1: ChannelOptions, +- options2: ChannelOptions +-) { +- const keys1 = Object.keys(options1).sort(); +- const keys2 = Object.keys(options2).sort(); +- if (keys1.length !== keys2.length) { +- return false; +- } +- for (let i = 0; i < keys1.length; i += 1) { +- if (keys1[i] !== keys2[i]) { +- return false; +- } +- if (options1[keys1[i]] !== options2[keys2[i]]) { +- return false; +- } +- } +- return true; +-} ++/* ++ * Copyright 2019 gRPC authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ * ++ */ ++ ++import { CompressionAlgorithms } from './compression-algorithms'; ++ ++/** ++ * An interface that contains options used when initializing a Channel instance. ++ */ ++/** Opt-in ownership for a private channel pool. Default channels are unchanged. */ ++export interface TransportResourceOwner { ++ readonly signal: AbortSignal; ++ pending(operation: Promise): void; ++ socket(socket: import('net').Socket): void; ++ session(session: import('http2').ClientHttp2Session): void; ++ request(request: import('http').ClientRequest): void; ++} ++export interface ChannelOptions { ++ 'grpc-node.transport_owner'?: TransportResourceOwner; ++ 'grpc.ssl_target_name_override'?: string; ++ 'grpc.primary_user_agent'?: string; ++ 'grpc.secondary_user_agent'?: string; ++ 'grpc.default_authority'?: string; ++ 'grpc.keepalive_time_ms'?: number; ++ 'grpc.keepalive_timeout_ms'?: number; ++ 'grpc.keepalive_permit_without_calls'?: number; ++ 'grpc.service_config'?: string; ++ 'grpc.max_concurrent_streams'?: number; ++ 'grpc.initial_reconnect_backoff_ms'?: number; ++ 'grpc.max_reconnect_backoff_ms'?: number; ++ 'grpc.use_local_subchannel_pool'?: number; ++ 'grpc.max_send_message_length'?: number; ++ 'grpc.max_receive_message_length'?: number; ++ 'grpc.enable_http_proxy'?: number; ++ /* http_connect_target and http_connect_creds are used for passing data ++ * around internally, and should not be documented as public-facing options ++ */ ++ 'grpc.http_connect_target'?: string; ++ 'grpc.http_connect_creds'?: string; ++ 'grpc.default_compression_algorithm'?: CompressionAlgorithms; ++ 'grpc.enable_channelz'?: number; ++ 'grpc.dns_min_time_between_resolutions_ms'?: number; ++ 'grpc.enable_retries'?: number; ++ 'grpc.per_rpc_retry_buffer_size'?: number; ++ /* This option is pattered like a core option, but the core does not have ++ * this option. It is closely related to the option ++ * grpc.per_rpc_retry_buffer_size, which is in the core. The core will likely ++ * implement this functionality using the ResourceQuota mechanism, so there ++ * will probably not be any collision or other inconsistency. */ ++ 'grpc.retry_buffer_size'?: number; ++ 'grpc.max_connection_age_ms'?: number; ++ 'grpc.max_connection_age_grace_ms'?: number; ++ 'grpc.max_connection_idle_ms'?: number; ++ 'grpc-node.max_session_memory'?: number; ++ 'grpc.service_config_disable_resolution'?: number; ++ 'grpc.client_idle_timeout_ms'?: number; ++ /** ++ * Set the enableTrace option in TLS clients and servers ++ */ ++ 'grpc-node.tls_enable_trace'?: number; ++ 'grpc.lb.ring_hash.ring_size_cap'?: number; ++ 'grpc-node.retry_max_attempts_limit'?: number; ++ 'grpc-node.flow_control_window'?: number; ++ 'grpc.server_call_metric_recording'?: number; ++ // eslint-disable-next-line @typescript-eslint/no-explicit-any ++ [key: string]: any; ++} ++ ++/** ++ * This is for checking provided options at runtime. This is an object for ++ * easier membership checking. ++ */ ++export const recognizedOptions = { ++ 'grpc.ssl_target_name_override': true, ++ 'grpc.primary_user_agent': true, ++ 'grpc.secondary_user_agent': true, ++ 'grpc.default_authority': true, ++ 'grpc.keepalive_time_ms': true, ++ 'grpc.keepalive_timeout_ms': true, ++ 'grpc.keepalive_permit_without_calls': true, ++ 'grpc.service_config': true, ++ 'grpc.max_concurrent_streams': true, ++ 'grpc.initial_reconnect_backoff_ms': true, ++ 'grpc.max_reconnect_backoff_ms': true, ++ 'grpc.use_local_subchannel_pool': true, ++ 'grpc-node.transport_owner': true, ++ 'grpc.max_send_message_length': true, ++ 'grpc.max_receive_message_length': true, ++ 'grpc.enable_http_proxy': true, ++ 'grpc.enable_channelz': true, ++ 'grpc.dns_min_time_between_resolutions_ms': true, ++ 'grpc.enable_retries': true, ++ 'grpc.per_rpc_retry_buffer_size': true, ++ 'grpc.retry_buffer_size': true, ++ 'grpc.max_connection_age_ms': true, ++ 'grpc.max_connection_age_grace_ms': true, ++ 'grpc-node.max_session_memory': true, ++ 'grpc.service_config_disable_resolution': true, ++ 'grpc.client_idle_timeout_ms': true, ++ 'grpc-node.tls_enable_trace': true, ++ 'grpc.lb.ring_hash.ring_size_cap': true, ++ 'grpc-node.retry_max_attempts_limit': true, ++ 'grpc-node.flow_control_window': true, ++ 'grpc.server_call_metric_recording': true ++}; ++ ++export function channelOptionsEqual( ++ options1: ChannelOptions, ++ options2: ChannelOptions ++) { ++ const keys1 = Object.keys(options1).sort(); ++ const keys2 = Object.keys(options2).sort(); ++ if (keys1.length !== keys2.length) { ++ return false; ++ } ++ for (let i = 0; i < keys1.length; i += 1) { ++ if (keys1[i] !== keys2[i]) { ++ return false; ++ } ++ if (options1[keys1[i]] !== options2[keys2[i]]) { ++ return false; ++ } ++ } ++ return true; ++} +--- a/src/http_proxy.ts ++++ b/src/http_proxy.ts +@@ -1,315 +1,329 @@ +-/* +- * Copyright 2019 gRPC authors. +- * +- * Licensed under the Apache License, Version 2.0 (the "License"); +- * you may not use this file except in compliance with the License. +- * You may obtain a copy of the License at +- * +- * http://www.apache.org/licenses/LICENSE-2.0 +- * +- * Unless required by applicable law or agreed to in writing, software +- * distributed under the License is distributed on an "AS IS" BASIS, +- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +- * See the License for the specific language governing permissions and +- * limitations under the License. +- * +- */ +- +-import { log } from './logging'; +-import { LogVerbosity } from './constants'; +-import { isIPv4, Socket } from 'net'; +-import * as http from 'http'; +-import * as logging from './logging'; +-import { +- SubchannelAddress, +- isTcpSubchannelAddress, +- subchannelAddressToString, +-} from './subchannel-address'; +-import { ChannelOptions } from './channel-options'; +-import { GrpcUri, parseUri, splitHostPort, uriToString } from './uri-parser'; +-import { URL } from 'url'; +-import { DEFAULT_PORT } from './resolver-dns'; +- +-const TRACER_NAME = 'proxy'; +- +-function trace(text: string): void { +- logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +-} +- +-interface ProxyInfo { +- address?: string; +- creds?: string; +-} +- +-function getProxyInfo(): ProxyInfo { +- let proxyEnv = ''; +- let envVar = ''; +- /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. +- * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The +- * fallback behavior can be removed if there's a demand for it. +- */ +- if (process.env.grpc_proxy) { +- envVar = 'grpc_proxy'; +- proxyEnv = process.env.grpc_proxy; +- } else if (process.env.https_proxy) { +- envVar = 'https_proxy'; +- proxyEnv = process.env.https_proxy; +- } else if (process.env.http_proxy) { +- envVar = 'http_proxy'; +- proxyEnv = process.env.http_proxy; +- } else { +- return {}; +- } +- let proxyUrl: URL; +- try { +- proxyUrl = new URL(proxyEnv); +- } catch (e) { +- log(LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); +- return {}; +- } +- if (proxyUrl.protocol !== 'http:') { +- log( +- LogVerbosity.ERROR, +- `"${proxyUrl.protocol}" scheme not supported in proxy URI` +- ); +- return {}; +- } +- let userCred: string | null = null; +- if (proxyUrl.username) { +- if (proxyUrl.password) { +- log(LogVerbosity.INFO, 'userinfo found in proxy URI'); +- userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); +- } else { +- userCred = proxyUrl.username; +- } +- } +- const hostname = proxyUrl.hostname; +- let port = proxyUrl.port; +- /* The proxy URL uses the scheme "http:", which has a default port number of +- * 80. We need to set that explicitly here if it is omitted because otherwise +- * it will use gRPC's default port 443. */ +- if (port === '') { +- port = '80'; +- } +- const result: ProxyInfo = { +- address: `${hostname}:${port}`, +- }; +- if (userCred) { +- result.creds = userCred; +- } +- trace( +- 'Proxy server ' + result.address + ' set by environment variable ' + envVar +- ); +- return result; +-} +- +-function getNoProxyHostList(): string[] { +- /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ +- let noProxyStr: string | undefined = process.env.no_grpc_proxy; +- let envVar = 'no_grpc_proxy'; +- if (!noProxyStr) { +- noProxyStr = process.env.no_proxy; +- envVar = 'no_proxy'; +- } +- if (noProxyStr) { +- trace('No proxy server list set by environment variable ' + envVar); +- return noProxyStr.split(','); +- } else { +- return []; +- } +-} +- +-interface CIDRNotation { +- ip: number; +- prefixLength: number; +-} +- +-/* +- * The groups correspond to CIDR parts as follows: +- * 1. ip +- * 2. prefixLength +- */ +- +-export function parseCIDR(cidrString: string): CIDRNotation | null { +- const splitRange = cidrString.split('/'); +- if (splitRange.length !== 2) { +- return null; +- } +- const prefixLength = parseInt(splitRange[1], 10); +- if (!isIPv4(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { +- return null; +- } +- return { +- ip: ipToInt(splitRange[0]), +- prefixLength: prefixLength +- }; +-} +- +-function ipToInt(ip: string) { +- return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); +-} +- +-function isIpInCIDR(cidr: CIDRNotation, serverHost: string) { +- const ip = cidr.ip; +- const mask = -1 << (32 - cidr.prefixLength); +- const hostIP = ipToInt(serverHost); +- +- return (hostIP & mask) === (ip & mask); +-} +- +-function hostMatchesNoProxyList(serverHost: string): boolean { +- for (const host of getNoProxyHostList()) { +- const parsedCIDR = parseCIDR(host); +- // host is a CIDR and serverHost is an IP address +- if (isIPv4(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { +- return true; +- } else if (serverHost.endsWith(host)) { +- // host is a single IP or a domain name suffix +- return true; +- } +- } +- return false; +-} +- +-export interface ProxyMapResult { +- target: GrpcUri; +- extraOptions: ChannelOptions; +-} +- +-export function mapProxyName( +- target: GrpcUri, +- options: ChannelOptions +-): ProxyMapResult { +- const noProxyResult: ProxyMapResult = { +- target: target, +- extraOptions: {}, +- }; +- if ((options['grpc.enable_http_proxy'] ?? 1) === 0) { +- return noProxyResult; +- } +- if (target.scheme === 'unix') { +- return noProxyResult; +- } +- const proxyInfo = getProxyInfo(); +- if (!proxyInfo.address) { +- return noProxyResult; +- } +- const hostPort = splitHostPort(target.path); +- if (!hostPort) { +- return noProxyResult; +- } +- const serverHost = hostPort.host; +- if (hostMatchesNoProxyList(serverHost)) { +- trace('Not using proxy for target in no_proxy list: ' + uriToString(target)); +- return noProxyResult; +- } +- const extraOptions: ChannelOptions = { +- 'grpc.http_connect_target': uriToString(target), +- }; +- if (proxyInfo.creds) { +- extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; +- } +- return { +- target: { +- scheme: 'dns', +- path: proxyInfo.address, +- }, +- extraOptions: extraOptions, +- }; +-} +- +-export function getProxiedConnection( +- address: SubchannelAddress, +- channelOptions: ChannelOptions +-): Promise { +- if (!('grpc.http_connect_target' in channelOptions)) { +- return Promise.resolve(null); +- } +- const realTarget = channelOptions['grpc.http_connect_target'] as string; +- const parsedTarget = parseUri(realTarget); +- if (parsedTarget === null) { +- return Promise.resolve(null); +- } +- const splitHostPost = splitHostPort(parsedTarget.path); +- if (splitHostPost === null) { +- return Promise.resolve(null); +- } +- const hostPort = `${splitHostPost.host}:${ +- splitHostPost.port ?? DEFAULT_PORT +- }`; +- const options: http.RequestOptions = { +- method: 'CONNECT', +- path: hostPort, +- }; +- const headers: http.OutgoingHttpHeaders = { +- Host: hostPort, +- }; +- // Connect to the subchannel address as a proxy +- if (isTcpSubchannelAddress(address)) { +- options.host = address.host; +- options.port = address.port; +- } else { +- options.socketPath = address.path; +- } +- if ('grpc.http_connect_creds' in channelOptions) { +- headers['Proxy-Authorization'] = +- 'Basic ' + +- Buffer.from(channelOptions['grpc.http_connect_creds'] as string).toString( +- 'base64' +- ); +- } +- options.headers = headers; +- const proxyAddressString = subchannelAddressToString(address); +- trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); +- return new Promise((resolve, reject) => { +- const request = http.request(options); +- request.once('connect', (res, socket, head) => { +- request.removeAllListeners(); +- socket.removeAllListeners(); +- if (res.statusCode === 200) { +- trace( +- 'Successfully connected to ' + +- options.path + +- ' through proxy ' + +- proxyAddressString +- ); +- // The HTTP client may have already read a few bytes of the proxied +- // connection. If that's the case, put them back into the socket. +- // See https://github.com/grpc/grpc-node/issues/2744. +- if (head.length > 0) { +- socket.unshift(head); +- } +- trace( +- 'Successfully established a plaintext connection to ' + +- options.path + +- ' through proxy ' + +- proxyAddressString +- ); +- resolve(socket); +- } else { +- log( +- LogVerbosity.ERROR, +- 'Failed to connect to ' + +- options.path + +- ' through proxy ' + +- proxyAddressString + +- ' with status ' + +- res.statusCode +- ); +- reject(); +- } +- }); +- request.once('error', err => { +- request.removeAllListeners(); +- log( +- LogVerbosity.ERROR, +- 'Failed to connect to proxy ' + +- proxyAddressString + +- ' with error ' + +- err.message +- ); +- reject(); +- }); +- request.end(); +- }); +-} ++/* ++ * Copyright 2019 gRPC authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ * ++ */ ++ ++import { log } from './logging'; ++import { LogVerbosity } from './constants'; ++import { isIPv4, Socket } from 'net'; ++import * as http from 'http'; ++import * as logging from './logging'; ++import { ++ SubchannelAddress, ++ isTcpSubchannelAddress, ++ subchannelAddressToString, ++} from './subchannel-address'; ++import { ChannelOptions } from './channel-options'; ++import { GrpcUri, parseUri, splitHostPort, uriToString } from './uri-parser'; ++import { URL } from 'url'; ++import { DEFAULT_PORT } from './resolver-dns'; ++ ++const TRACER_NAME = 'proxy'; ++ ++function trace(text: string): void { ++ logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); ++} ++ ++interface ProxyInfo { ++ address?: string; ++ creds?: string; ++} ++ ++function getProxyInfo(): ProxyInfo { ++ let proxyEnv = ''; ++ let envVar = ''; ++ /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. ++ * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The ++ * fallback behavior can be removed if there's a demand for it. ++ */ ++ if (process.env.grpc_proxy) { ++ envVar = 'grpc_proxy'; ++ proxyEnv = process.env.grpc_proxy; ++ } else if (process.env.https_proxy) { ++ envVar = 'https_proxy'; ++ proxyEnv = process.env.https_proxy; ++ } else if (process.env.http_proxy) { ++ envVar = 'http_proxy'; ++ proxyEnv = process.env.http_proxy; ++ } else { ++ return {}; ++ } ++ let proxyUrl: URL; ++ try { ++ proxyUrl = new URL(proxyEnv); ++ } catch (e) { ++ log(LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); ++ return {}; ++ } ++ if (proxyUrl.protocol !== 'http:') { ++ log( ++ LogVerbosity.ERROR, ++ `"${proxyUrl.protocol}" scheme not supported in proxy URI` ++ ); ++ return {}; ++ } ++ let userCred: string | null = null; ++ if (proxyUrl.username) { ++ if (proxyUrl.password) { ++ log(LogVerbosity.INFO, 'userinfo found in proxy URI'); ++ userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); ++ } else { ++ userCred = proxyUrl.username; ++ } ++ } ++ const hostname = proxyUrl.hostname; ++ let port = proxyUrl.port; ++ /* The proxy URL uses the scheme "http:", which has a default port number of ++ * 80. We need to set that explicitly here if it is omitted because otherwise ++ * it will use gRPC's default port 443. */ ++ if (port === '') { ++ port = '80'; ++ } ++ const result: ProxyInfo = { ++ address: `${hostname}:${port}`, ++ }; ++ if (userCred) { ++ result.creds = userCred; ++ } ++ trace( ++ 'Proxy server ' + result.address + ' set by environment variable ' + envVar ++ ); ++ return result; ++} ++ ++function getNoProxyHostList(): string[] { ++ /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ ++ let noProxyStr: string | undefined = process.env.no_grpc_proxy; ++ let envVar = 'no_grpc_proxy'; ++ if (!noProxyStr) { ++ noProxyStr = process.env.no_proxy; ++ envVar = 'no_proxy'; ++ } ++ if (noProxyStr) { ++ trace('No proxy server list set by environment variable ' + envVar); ++ return noProxyStr.split(','); ++ } else { ++ return []; ++ } ++} ++ ++interface CIDRNotation { ++ ip: number; ++ prefixLength: number; ++} ++ ++/* ++ * The groups correspond to CIDR parts as follows: ++ * 1. ip ++ * 2. prefixLength ++ */ ++ ++export function parseCIDR(cidrString: string): CIDRNotation | null { ++ const splitRange = cidrString.split('/'); ++ if (splitRange.length !== 2) { ++ return null; ++ } ++ const prefixLength = parseInt(splitRange[1], 10); ++ if (!isIPv4(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { ++ return null; ++ } ++ return { ++ ip: ipToInt(splitRange[0]), ++ prefixLength: prefixLength ++ }; ++} ++ ++function ipToInt(ip: string) { ++ return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); ++} ++ ++function isIpInCIDR(cidr: CIDRNotation, serverHost: string) { ++ const ip = cidr.ip; ++ const mask = -1 << (32 - cidr.prefixLength); ++ const hostIP = ipToInt(serverHost); ++ ++ return (hostIP & mask) === (ip & mask); ++} ++ ++function hostMatchesNoProxyList(serverHost: string): boolean { ++ for (const host of getNoProxyHostList()) { ++ const parsedCIDR = parseCIDR(host); ++ // host is a CIDR and serverHost is an IP address ++ if (isIPv4(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { ++ return true; ++ } else if (serverHost.endsWith(host)) { ++ // host is a single IP or a domain name suffix ++ return true; ++ } ++ } ++ return false; ++} ++ ++export interface ProxyMapResult { ++ target: GrpcUri; ++ extraOptions: ChannelOptions; ++} ++ ++export function mapProxyName( ++ target: GrpcUri, ++ options: ChannelOptions ++): ProxyMapResult { ++ const noProxyResult: ProxyMapResult = { ++ target: target, ++ extraOptions: {}, ++ }; ++ if ((options['grpc.enable_http_proxy'] ?? 1) === 0) { ++ return noProxyResult; ++ } ++ if (target.scheme === 'unix') { ++ return noProxyResult; ++ } ++ const proxyInfo = getProxyInfo(); ++ if (!proxyInfo.address) { ++ return noProxyResult; ++ } ++ const hostPort = splitHostPort(target.path); ++ if (!hostPort) { ++ return noProxyResult; ++ } ++ const serverHost = hostPort.host; ++ if (hostMatchesNoProxyList(serverHost)) { ++ trace('Not using proxy for target in no_proxy list: ' + uriToString(target)); ++ return noProxyResult; ++ } ++ const extraOptions: ChannelOptions = { ++ 'grpc.http_connect_target': uriToString(target), ++ }; ++ if (proxyInfo.creds) { ++ extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; ++ } ++ return { ++ target: { ++ scheme: 'dns', ++ path: proxyInfo.address, ++ }, ++ extraOptions: extraOptions, ++ }; ++} ++ ++export function getProxiedConnection( ++ address: SubchannelAddress, ++ channelOptions: ChannelOptions ++): Promise { ++ if (!('grpc.http_connect_target' in channelOptions)) { ++ return Promise.resolve(null); ++ } ++ const realTarget = channelOptions['grpc.http_connect_target'] as string; ++ const parsedTarget = parseUri(realTarget); ++ if (parsedTarget === null) { ++ return Promise.resolve(null); ++ } ++ const splitHostPost = splitHostPort(parsedTarget.path); ++ if (splitHostPost === null) { ++ return Promise.resolve(null); ++ } ++ const hostPort = `${splitHostPost.host}:${ ++ splitHostPost.port ?? DEFAULT_PORT ++ }`; ++ const options: http.RequestOptions = { ++ method: 'CONNECT', ++ path: hostPort, ++ }; ++ const headers: http.OutgoingHttpHeaders = { ++ Host: hostPort, ++ }; ++ // Connect to the subchannel address as a proxy ++ if (isTcpSubchannelAddress(address)) { ++ options.host = address.host; ++ options.port = address.port; ++ } else { ++ options.socketPath = address.path; ++ } ++ if ('grpc.http_connect_creds' in channelOptions) { ++ headers['Proxy-Authorization'] = ++ 'Basic ' + ++ Buffer.from(channelOptions['grpc.http_connect_creds'] as string).toString( ++ 'base64' ++ ); ++ } ++ options.headers = headers; ++ if (channelOptions['grpc-node.transport_owner']) options.signal = channelOptions['grpc-node.transport_owner'].signal; ++ const proxyAddressString = subchannelAddressToString(address); ++ trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); ++ return new Promise((resolve, reject) => { ++ const request = http.request(options); ++ const owner = channelOptions['grpc-node.transport_owner']; ++ if (owner) { ++ request.once('socket', socket => owner.socket(socket)); ++ request.once('close', () => reject(new Error('Owned proxy request closed'))); ++ owner.request(request); ++ } ++ request.once('connect', (res, socket, head) => { ++ request.removeAllListeners(); ++ socket.removeAllListeners(); ++ if (owner) { ++ owner.request(request); ++ owner.socket(socket); ++ request.once('error', reject); ++ request.once('close', () => reject(new Error('Owned proxy request closed'))); ++ } ++ if (res.statusCode === 200) { ++ trace( ++ 'Successfully connected to ' + ++ options.path + ++ ' through proxy ' + ++ proxyAddressString ++ ); ++ // The HTTP client may have already read a few bytes of the proxied ++ // connection. If that's the case, put them back into the socket. ++ // See https://github.com/grpc/grpc-node/issues/2744. ++ if (head.length > 0) { ++ socket.unshift(head); ++ } ++ trace( ++ 'Successfully established a plaintext connection to ' + ++ options.path + ++ ' through proxy ' + ++ proxyAddressString ++ ); ++ resolve(socket); ++ } else { ++ log( ++ LogVerbosity.ERROR, ++ 'Failed to connect to ' + ++ options.path + ++ ' through proxy ' + ++ proxyAddressString + ++ ' with status ' + ++ res.statusCode ++ ); ++ reject(); ++ } ++ }); ++ request.once('error', err => { ++ request.removeAllListeners(); ++ if (owner) owner.request(request); ++ log( ++ LogVerbosity.ERROR, ++ 'Failed to connect to proxy ' + ++ proxyAddressString + ++ ' with error ' + ++ err.message ++ ); ++ reject(); ++ }); ++ request.end(); ++ }); ++} +--- a/src/transport.ts ++++ b/src/transport.ts +@@ -1,883 +1,900 @@ +-/* +- * Copyright 2023 gRPC authors. +- * +- * Licensed under the Apache License, Version 2.0 (the "License"); +- * you may not use this file except in compliance with the License. +- * You may obtain a copy of the License at +- * +- * http://www.apache.org/licenses/LICENSE-2.0 +- * +- * Unless required by applicable law or agreed to in writing, software +- * distributed under the License is distributed on an "AS IS" BASIS, +- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +- * See the License for the specific language governing permissions and +- * limitations under the License. +- * +- */ +- +-import * as http2 from 'http2'; +-import { +- CipherNameAndProtocol, +- TLSSocket, +-} from 'tls'; +-import { PartialStatusObject } from './call-interface'; +-import { SecureConnector, SecureConnectResult } from './channel-credentials'; +-import { ChannelOptions } from './channel-options'; +-import { +- ChannelzCallTracker, +- ChannelzCallTrackerStub, +- registerChannelzSocket, +- SocketInfo, +- SocketRef, +- TlsInfo, +- unregisterChannelzRef, +-} from './channelz'; +-import { LogVerbosity } from './constants'; +-import { getProxiedConnection } from './http_proxy'; +-import * as logging from './logging'; +-import { getDefaultAuthority } from './resolver'; +-import { +- stringToSubchannelAddress, +- SubchannelAddress, +- subchannelAddressToString, +-} from './subchannel-address'; +-import { GrpcUri, parseUri, uriToString } from './uri-parser'; +-import * as net from 'net'; +-import { +- Http2SubchannelCall, +- SubchannelCall, +- SubchannelCallInterceptingListener, +-} from './subchannel-call'; +-import { Metadata } from './metadata'; +-import { getNextCallNumber } from './call-number'; +-import { Socket } from 'net'; +-import { AuthContext } from './auth-context'; +- +-const TRACER_NAME = 'transport'; +-const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; +- +-const clientVersion = require('../../package.json').version; +- +-const { +- HTTP2_HEADER_AUTHORITY, +- HTTP2_HEADER_CONTENT_TYPE, +- HTTP2_HEADER_METHOD, +- HTTP2_HEADER_PATH, +- HTTP2_HEADER_TE, +- HTTP2_HEADER_USER_AGENT, +-} = http2.constants; +- +-const KEEPALIVE_TIMEOUT_MS = 20000; +- +-export interface CallEventTracker { +- addMessageSent(): void; +- addMessageReceived(): void; +- onCallEnd(status: PartialStatusObject): void; +- onStreamEnd(success: boolean): void; +-} +- +-export interface TransportDisconnectListener { +- (tooManyPings: boolean): void; +-} +- +-export interface Transport { +- getChannelzRef(): SocketRef; +- getPeerName(): string; +- getOptions(): ChannelOptions; +- getAuthContext(): AuthContext; +- createCall( +- metadata: Metadata, +- host: string, +- method: string, +- listener: SubchannelCallInterceptingListener, +- subchannelCallStatsTracker: Partial, +- callId?: number +- ): SubchannelCall; +- addDisconnectListener(listener: TransportDisconnectListener): void; +- shutdown(): void; +-} +- +-const tooManyPingsData: Buffer = Buffer.from('too_many_pings', 'ascii'); +- +-class Http2Transport implements Transport { +- /** +- * The amount of time in between sending pings +- */ +- private readonly keepaliveTimeMs: number; +- /** +- * The amount of time to wait for an acknowledgement after sending a ping +- */ +- private readonly keepaliveTimeoutMs: number; +- /** +- * Indicates whether keepalive pings should be sent without any active calls +- */ +- private readonly keepaliveWithoutCalls: boolean; +- /** +- * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. +- */ +- private keepaliveTimer: NodeJS.Timeout | null = null; +- /** +- * Indicates that the keepalive timer ran out while there were no active +- * calls, and a ping should be sent the next time a call starts. +- */ +- private pendingSendKeepalivePing = false; +- +- private userAgent: string; +- +- private activeCalls: Set = new Set(); +- +- private subchannelAddressString: string; +- +- private disconnectListeners: TransportDisconnectListener[] = []; +- +- private disconnectHandled = false; +- +- private authContext: AuthContext; +- +- // Channelz info +- private channelzRef: SocketRef; +- private readonly channelzEnabled: boolean = true; +- private streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; +- private keepalivesSent = 0; +- private messagesSent = 0; +- private messagesReceived = 0; +- private lastMessageSentTimestamp: Date | null = null; +- private lastMessageReceivedTimestamp: Date | null = null; +- +- constructor( +- private session: http2.ClientHttp2Session, +- subchannelAddress: SubchannelAddress, +- private options: ChannelOptions, +- /** +- * Name of the remote server, if it is not the same as the subchannel +- * address, i.e. if connecting through an HTTP CONNECT proxy. +- */ +- private remoteName: string | null +- ) { +- /* Populate subchannelAddressString and channelzRef before doing anything +- * else, because they are used in the trace methods. */ +- this.subchannelAddressString = subchannelAddressToString(subchannelAddress); +- +- if (options['grpc.enable_channelz'] === 0) { +- this.channelzEnabled = false; +- this.streamTracker = new ChannelzCallTrackerStub(); +- } else { +- this.streamTracker = new ChannelzCallTracker(); +- } +- +- this.channelzRef = registerChannelzSocket( +- this.subchannelAddressString, +- () => this.getChannelzInfo(), +- this.channelzEnabled +- ); +- +- // Build user-agent string. +- this.userAgent = [ +- options['grpc.primary_user_agent'], +- `grpc-node-js/${clientVersion}`, +- options['grpc.secondary_user_agent'], +- ] +- .filter(e => e) +- .join(' '); // remove falsey values first +- +- if ('grpc.keepalive_time_ms' in options) { +- this.keepaliveTimeMs = options['grpc.keepalive_time_ms']!; +- } else { +- this.keepaliveTimeMs = -1; +- } +- if ('grpc.keepalive_timeout_ms' in options) { +- this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']!; +- } else { +- this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; +- } +- if ('grpc.keepalive_permit_without_calls' in options) { +- this.keepaliveWithoutCalls = +- options['grpc.keepalive_permit_without_calls'] === 1; +- } else { +- this.keepaliveWithoutCalls = false; +- } +- +- session.once('close', () => { +- this.trace('session closed'); +- this.handleDisconnect(); +- }); +- +- session.once( +- 'goaway', +- (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => { +- let tooManyPings = false; +- /* See the last paragraph of +- * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ +- if ( +- errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && +- opaqueData && +- opaqueData.equals(tooManyPingsData) +- ) { +- tooManyPings = true; +- } +- if (this.traceEnabled) { +- this.trace( +- 'connection closed by GOAWAY with code ' + +- errorCode + +- ' and data ' + +- opaqueData?.toString() +- ); +- } +- this.reportDisconnectToOwner(tooManyPings); +- } +- ); +- +- session.once('error', error => { +- if (this.traceEnabled) { +- this.trace('connection closed with error ' + (error as Error).message); +- } +- this.handleDisconnect(); +- }); +- +- session.socket.once('close', (hadError) => { +- if (this.traceEnabled) { +- this.trace('connection closed. hadError=' + hadError); +- } +- this.handleDisconnect(); +- }); +- +- if (this.traceEnabled) { +- session.on('remoteSettings', (settings: http2.Settings) => { +- this.trace( +- 'new settings received' + +- (this.session !== session ? ' on the old connection' : '') + +- ': ' + +- JSON.stringify(settings) +- ); +- }); +- session.on('localSettings', (settings: http2.Settings) => { +- this.trace( +- 'local settings acknowledged by remote' + +- (this.session !== session ? ' on the old connection' : '') + +- ': ' + +- JSON.stringify(settings) +- ); +- }); +- } +- +- /* Start the keepalive timer last, because this can trigger trace logs, +- * which should only happen after everything else is set up. */ +- if (this.keepaliveWithoutCalls) { +- this.maybeStartKeepalivePingTimer(); +- } +- +- if (session.socket instanceof TLSSocket && session.socket.authorized) { +- this.authContext = { +- transportSecurityType: 'ssl', +- sslPeerCertificate: session.socket.getPeerCertificate() +- }; +- } else { +- this.authContext = {}; +- } +- } +- +- private getChannelzInfo(): SocketInfo { +- const sessionSocket = this.session.socket; +- const remoteAddress = sessionSocket.remoteAddress +- ? stringToSubchannelAddress( +- sessionSocket.remoteAddress, +- sessionSocket.remotePort +- ) +- : null; +- const localAddress = sessionSocket.localAddress +- ? stringToSubchannelAddress( +- sessionSocket.localAddress, +- sessionSocket.localPort +- ) +- : null; +- let tlsInfo: TlsInfo | null; +- if (this.session.encrypted) { +- const tlsSocket: TLSSocket = sessionSocket as TLSSocket; +- const cipherInfo: CipherNameAndProtocol & { standardName?: string } = +- tlsSocket.getCipher(); +- const certificate = tlsSocket.getCertificate(); +- const peerCertificate = tlsSocket.getPeerCertificate(); +- tlsInfo = { +- cipherSuiteStandardName: cipherInfo.standardName ?? null, +- cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, +- localCertificate: +- certificate && 'raw' in certificate ? certificate.raw : null, +- remoteCertificate: +- peerCertificate && 'raw' in peerCertificate +- ? peerCertificate.raw +- : null, +- }; +- } else { +- tlsInfo = null; +- } +- const socketInfo: SocketInfo = { +- remoteAddress: remoteAddress, +- localAddress: localAddress, +- security: tlsInfo, +- remoteName: this.remoteName, +- streamsStarted: this.streamTracker.callsStarted, +- streamsSucceeded: this.streamTracker.callsSucceeded, +- streamsFailed: this.streamTracker.callsFailed, +- messagesSent: this.messagesSent, +- messagesReceived: this.messagesReceived, +- keepAlivesSent: this.keepalivesSent, +- lastLocalStreamCreatedTimestamp: +- this.streamTracker.lastCallStartedTimestamp, +- lastRemoteStreamCreatedTimestamp: null, +- lastMessageSentTimestamp: this.lastMessageSentTimestamp, +- lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, +- localFlowControlWindow: this.session.state.localWindowSize ?? null, +- remoteFlowControlWindow: this.session.state.remoteWindowSize ?? null, +- }; +- return socketInfo; +- } +- +- private get traceEnabled(): boolean { +- return logging.isTracerEnabled(TRACER_NAME); +- } +- +- private get keepaliveTraceEnabled(): boolean { +- return logging.isTracerEnabled('keepalive'); +- } +- +- private get flowControlTraceEnabled(): boolean { +- return logging.isTracerEnabled(FLOW_CONTROL_TRACER_NAME); +- } +- +- private get internalsTraceEnabled(): boolean { +- return logging.isTracerEnabled('transport_internals'); +- } +- +- private trace(text: string): void { +- if (this.traceEnabled) { +- logging.trace( +- LogVerbosity.DEBUG, +- TRACER_NAME, +- '(' + +- this.channelzRef.id + +- ') ' + +- this.subchannelAddressString + +- ' ' + +- text +- ); +- } +- } +- +- private keepaliveTrace(text: string): void { +- if (this.keepaliveTraceEnabled) { +- logging.trace( +- LogVerbosity.DEBUG, +- 'keepalive', +- '(' + +- this.channelzRef.id + +- ') ' + +- this.subchannelAddressString + +- ' ' + +- text +- ); +- } +- } +- +- private flowControlTrace(text: string): void { +- if (this.flowControlTraceEnabled) { +- logging.trace( +- LogVerbosity.DEBUG, +- FLOW_CONTROL_TRACER_NAME, +- '(' + +- this.channelzRef.id + +- ') ' + +- this.subchannelAddressString + +- ' ' + +- text +- ); +- } +- } +- +- private internalsTrace(text: string): void { +- if (this.internalsTraceEnabled) { +- logging.trace( +- LogVerbosity.DEBUG, +- 'transport_internals', +- '(' + +- this.channelzRef.id + +- ') ' + +- this.subchannelAddressString + +- ' ' + +- text +- ); +- } +- } +- +- /** +- * Indicate to the owner of this object that this transport should no longer +- * be used. That happens if the connection drops, or if the server sends a +- * GOAWAY. +- * @param tooManyPings If true, this was triggered by a GOAWAY with data +- * indicating that the session was closed becaues the client sent too many +- * pings. +- * @returns +- */ +- private reportDisconnectToOwner(tooManyPings: boolean) { +- if (this.disconnectHandled) { +- return; +- } +- this.disconnectHandled = true; +- this.disconnectListeners.forEach(listener => listener(tooManyPings)); +- } +- +- /** +- * Handle connection drops, but not GOAWAYs. +- */ +- private handleDisconnect() { +- this.clearKeepaliveTimeout(); +- this.reportDisconnectToOwner(false); +- for (const call of this.activeCalls) { +- call.onDisconnect(); +- } +- // Wait an event loop cycle before destroying the connection +- setImmediate(() => { +- this.session.destroy(); +- }); +- } +- +- addDisconnectListener(listener: TransportDisconnectListener): void { +- this.disconnectListeners.push(listener); +- } +- +- private canSendPing() { +- return ( +- !this.session.destroyed && +- this.keepaliveTimeMs > 0 && +- (this.keepaliveWithoutCalls || this.activeCalls.size > 0) +- ); +- } +- +- private maybeSendPing() { +- if (!this.canSendPing()) { +- this.pendingSendKeepalivePing = true; +- return; +- } +- if (this.keepaliveTimer) { +- console.error('keepaliveTimeout is not null'); +- return; +- } +- if (this.channelzEnabled) { +- this.keepalivesSent += 1; +- } +- 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'); +- this.handleDisconnect(); +- }, this.keepaliveTimeoutMs); +- this.keepaliveTimer.unref?.(); +- let pingSendError = ''; +- try { +- const pingSentSuccessfully = this.session.ping( +- (err: Error | null, duration: number, payload: Buffer) => { +- this.clearKeepaliveTimeout(); +- if (err) { +- if (this.keepaliveTraceEnabled) { +- this.keepaliveTrace('Ping failed with error ' + err.message); +- } +- this.handleDisconnect(); +- } else { +- this.keepaliveTrace('Received ping response'); +- this.maybeStartKeepalivePingTimer(); +- } +- } +- ); +- if (!pingSentSuccessfully) { +- pingSendError = 'Ping returned false'; +- } +- } catch (e) { +- // grpc/grpc-node#2139 +- pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; +- } +- if (pingSendError) { +- if (this.keepaliveTraceEnabled) { +- this.keepaliveTrace('Ping send failed: ' + pingSendError); +- } +- this.handleDisconnect(); +- } +- } +- +- /** +- * Starts the keepalive ping timer if appropriate. If the timer already ran +- * out while there were no active requests, instead send a ping immediately. +- * If the ping timer is already running or a ping is currently in flight, +- * instead do nothing and wait for them to resolve. +- */ +- private maybeStartKeepalivePingTimer() { +- if (!this.canSendPing()) { +- return; +- } +- if (this.pendingSendKeepalivePing) { +- this.pendingSendKeepalivePing = false; +- this.maybeSendPing(); +- } else if (!this.keepaliveTimer) { +- this.keepaliveTrace( +- 'Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms' +- ); +- this.keepaliveTimer = setTimeout(() => { +- this.keepaliveTimer = null; +- this.maybeSendPing(); +- }, this.keepaliveTimeMs); +- this.keepaliveTimer.unref?.(); +- } +- /* Otherwise, there is already either a keepalive timer or a ping pending, +- * wait for those to resolve. */ +- } +- +- /** +- * Clears whichever keepalive timeout is currently active, if any. +- */ +- private clearKeepaliveTimeout() { +- if (this.keepaliveTimer) { +- clearTimeout(this.keepaliveTimer); +- this.keepaliveTimer = null; +- } +- } +- +- private removeActiveCall(call: Http2SubchannelCall) { +- this.activeCalls.delete(call); +- if (this.activeCalls.size === 0) { +- this.session.unref(); +- } +- } +- +- private addActiveCall(call: Http2SubchannelCall) { +- this.activeCalls.add(call); +- if (this.activeCalls.size === 1) { +- this.session.ref(); +- if (!this.keepaliveWithoutCalls) { +- this.maybeStartKeepalivePingTimer(); +- } +- } +- } +- +- createCall( +- metadata: Metadata, +- host: string, +- method: string, +- listener: SubchannelCallInterceptingListener, +- subchannelCallStatsTracker: Partial, +- callId?: number +- ): Http2SubchannelCall { +- const headers = metadata.toHttp2Headers(); +- headers[HTTP2_HEADER_AUTHORITY] = host; +- headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; +- headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; +- headers[HTTP2_HEADER_METHOD] = 'POST'; +- headers[HTTP2_HEADER_PATH] = method; +- headers[HTTP2_HEADER_TE] = 'trailers'; +- let http2Stream: http2.ClientHttp2Stream; +- /* In theory, if an error is thrown by session.request because session has +- * become unusable (e.g. because it has received a goaway), this subchannel +- * should soon see the corresponding close or goaway event anyway and leave +- * READY. But we have seen reports that this does not happen +- * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) +- * so for defense in depth, we just discard the session when we see an +- * error here. +- */ +- try { +- http2Stream = this.session.request(headers); +- } catch (e) { +- this.handleDisconnect(); +- throw e; +- } +- 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: CallEventTracker; +- // eslint-disable-next-line prefer-const +- let call: Http2SubchannelCall; +- if (this.channelzEnabled) { +- this.streamTracker.addCallStarted(); +- eventTracker = { +- addMessageSent: () => { +- this.messagesSent += 1; +- this.lastMessageSentTimestamp = new Date(); +- subchannelCallStatsTracker.addMessageSent?.(); +- }, +- addMessageReceived: () => { +- this.messagesReceived += 1; +- this.lastMessageReceivedTimestamp = new Date(); +- subchannelCallStatsTracker.addMessageReceived?.(); +- }, +- onCallEnd: status => { +- subchannelCallStatsTracker.onCallEnd?.(status); +- this.removeActiveCall(call); +- }, +- onStreamEnd: success => { +- if (success) { +- this.streamTracker.addCallSucceeded(); +- } else { +- this.streamTracker.addCallFailed(); +- } +- subchannelCallStatsTracker.onStreamEnd?.(success); +- }, +- }; +- } else { +- eventTracker = { +- addMessageSent: () => { +- subchannelCallStatsTracker.addMessageSent?.(); +- }, +- addMessageReceived: () => { +- subchannelCallStatsTracker.addMessageReceived?.(); +- }, +- onCallEnd: status => { +- subchannelCallStatsTracker.onCallEnd?.(status); +- this.removeActiveCall(call); +- }, +- onStreamEnd: success => { +- subchannelCallStatsTracker.onStreamEnd?.(success); +- }, +- }; +- } +- call = new Http2SubchannelCall( +- http2Stream, +- eventTracker, +- listener, +- this, +- callId ?? getNextCallNumber() +- ); +- this.addActiveCall(call); +- return call; +- } +- +- getChannelzRef(): SocketRef { +- return this.channelzRef; +- } +- +- getPeerName() { +- return this.subchannelAddressString; +- } +- +- getOptions() { +- return this.options; +- } +- +- getAuthContext(): AuthContext { +- return this.authContext; +- } +- +- shutdown() { +- this.session.close(); +- unregisterChannelzRef(this.channelzRef); +- } +-} +- +-export interface SubchannelConnector { +- connect( +- address: SubchannelAddress, +- secureConnector: SecureConnector, +- options: ChannelOptions +- ): Promise; +- shutdown(): void; +-} +- +-export class Http2SubchannelConnector implements SubchannelConnector { +- private session: http2.ClientHttp2Session | null = null; +- private isShutdown = false; +- constructor(private channelTarget: GrpcUri) {} +- +- private get traceEnabled(): boolean { +- return logging.isTracerEnabled(TRACER_NAME); +- } +- +- private trace(text: string) { +- if (this.traceEnabled) { +- logging.trace( +- LogVerbosity.DEBUG, +- TRACER_NAME, +- uriToString(this.channelTarget) + ' ' + text +- ); +- } +- } +- +- private createSession( +- secureConnectResult: SecureConnectResult, +- address: SubchannelAddress, +- options: ChannelOptions +- ): Promise { +- if (this.isShutdown) { +- return Promise.reject(); +- } +- +- if (secureConnectResult.socket.closed) { +- return Promise.reject('Connection closed before starting HTTP/2 handshake'); +- } +- +- return new Promise((resolve, reject) => { +- let remoteName: string | null = null; +- let realTarget: GrpcUri = this.channelTarget; +- if ('grpc.http_connect_target' in options) { +- const parsedTarget = parseUri(options['grpc.http_connect_target']!); +- if (parsedTarget) { +- realTarget = parsedTarget; +- remoteName = uriToString(parsedTarget); +- } +- } +- const scheme = secureConnectResult.secure ? 'https' : 'http'; +- const targetPath = getDefaultAuthority(realTarget); +- const closeHandler = () => { +- this.session?.destroy(); +- this.session = null; +- // Leave time for error event to happen before rejecting +- setImmediate(() => { +- if (!reportedError) { +- reportedError = true; +- reject(`${errorMessage.trim()} (${new Date().toISOString()})`); +- } +- }); +- }; +- const errorHandler = (error: Error) => { +- this.session?.destroy(); +- errorMessage = (error as Error).message; +- if (this.traceEnabled) { +- this.trace('connection failed with error ' + errorMessage); +- } +- if (!reportedError) { +- reportedError = true; +- reject(`${errorMessage} (${new Date().toISOString()})`); +- } +- }; +- const sessionOptions: http2.ClientSessionOptions = { +- createConnection: (authority, option) => { +- return secureConnectResult.socket; +- }, +- settings: { +- initialWindowSize: +- options['grpc-node.flow_control_window'] ?? +- http2.getDefaultSettings?.()?.initialWindowSize ?? 65535, +- }, +- maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, +- /* By default, set a very large max session memory limit, to effectively +- * disable enforcement of the limit. Some testing indicates that Node's +- * behavior degrades badly when this limit is reached, so we solve that +- * by disabling the check entirely. */ +- maxSessionMemory: options['grpc-node.max_session_memory'] ?? Number.MAX_SAFE_INTEGER +- }; +- const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); +- // Prepare window size configuration for remoteSettings handler +- const defaultWin = http2.getDefaultSettings?.()?.initialWindowSize ?? 65535; // 65 535 B +- const connWin = options[ +- 'grpc-node.flow_control_window' +- ] as number | undefined; +- +- this.session = session; +- let errorMessage = 'Failed to connect'; +- let reportedError = false; +- session.unref(); +- session.once('remoteSettings', () => { +- // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. +- if (connWin && connWin > defaultWin) { +- try { +- // Node ≥ 14.18 +- (session as any).setLocalWindowSize(connWin); +- } catch { +- // Older Node: bump by the delta +- const delta = connWin - (session.state.localWindowSize ?? defaultWin); +- if (delta > 0) (session as any).incrementWindowSize(delta); +- } +- } +- +- session.removeAllListeners(); +- secureConnectResult.socket.removeListener('close', closeHandler); +- secureConnectResult.socket.removeListener('error', errorHandler); +- resolve(new Http2Transport(session, address, options, remoteName)); +- this.session = null; +- }); +- session.once('close', closeHandler); +- session.once('error', errorHandler); +- secureConnectResult.socket.once('close', closeHandler); +- secureConnectResult.socket.once('error', errorHandler); +- }); +- } +- +- private tcpConnect(address: SubchannelAddress, options: ChannelOptions): Promise { +- return getProxiedConnection(address, options).then(proxiedSocket => { +- if (proxiedSocket) { +- return proxiedSocket; +- } else { +- return new Promise((resolve, reject) => { +- const closeCallback = () => { +- reject(new Error('Socket closed')); +- }; +- const errorCallback = (error: Error) => { +- reject(error); +- } +- const socket = net.connect(address, () => { +- socket.removeListener('close', closeCallback); +- socket.removeListener('error', errorCallback); +- resolve(socket); +- }); +- socket.once('close', closeCallback); +- socket.once('error', errorCallback); +- }); +- } +- }); +- } +- +- async connect( +- address: SubchannelAddress, +- secureConnector: SecureConnector, +- options: ChannelOptions +- ): Promise { +- if (this.isShutdown) { +- return Promise.reject(); +- } +- let tcpConnection: net.Socket | null = null; +- let secureConnectResult: SecureConnectResult | null = null; +- const addressString = subchannelAddressToString(address); +- try { +- if (this.traceEnabled) { +- this.trace(addressString + ' Waiting for secureConnector to be ready'); +- } +- await secureConnector.waitForReady(); +- if (this.traceEnabled) { +- this.trace(addressString + ' secureConnector is ready'); +- } +- tcpConnection = await this.tcpConnect(address, options); +- tcpConnection.setNoDelay(); +- if (this.traceEnabled) { +- this.trace(addressString + ' Established TCP connection'); +- } +- secureConnectResult = await secureConnector.connect(tcpConnection); +- if (this.traceEnabled) { +- this.trace(addressString + ' Established secure connection'); +- } +- return this.createSession(secureConnectResult, address, options); +- } catch (e) { +- tcpConnection?.destroy(); +- secureConnectResult?.socket.destroy(); +- throw e; +- } +- } +- +- shutdown(): void { +- this.isShutdown = true; +- this.session?.close(); +- this.session = null; +- } +-} ++/* ++ * Copyright 2023 gRPC authors. ++ * ++ * Licensed under the Apache License, Version 2.0 (the "License"); ++ * you may not use this file except in compliance with the License. ++ * You may obtain a copy of the License at ++ * ++ * http://www.apache.org/licenses/LICENSE-2.0 ++ * ++ * Unless required by applicable law or agreed to in writing, software ++ * distributed under the License is distributed on an "AS IS" BASIS, ++ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++ * See the License for the specific language governing permissions and ++ * limitations under the License. ++ * ++ */ ++ ++import * as http2 from 'http2'; ++import { ++ CipherNameAndProtocol, ++ TLSSocket, ++} from 'tls'; ++import { PartialStatusObject } from './call-interface'; ++import { SecureConnector, SecureConnectResult } from './channel-credentials'; ++import { ChannelOptions } from './channel-options'; ++import { ++ ChannelzCallTracker, ++ ChannelzCallTrackerStub, ++ registerChannelzSocket, ++ SocketInfo, ++ SocketRef, ++ TlsInfo, ++ unregisterChannelzRef, ++} from './channelz'; ++import { LogVerbosity } from './constants'; ++import { getProxiedConnection } from './http_proxy'; ++import * as logging from './logging'; ++import { getDefaultAuthority } from './resolver'; ++import { ++ stringToSubchannelAddress, ++ SubchannelAddress, ++ subchannelAddressToString, ++} from './subchannel-address'; ++import { GrpcUri, parseUri, uriToString } from './uri-parser'; ++import * as net from 'net'; ++import { ++ Http2SubchannelCall, ++ SubchannelCall, ++ SubchannelCallInterceptingListener, ++} from './subchannel-call'; ++import { Metadata } from './metadata'; ++import { getNextCallNumber } from './call-number'; ++import { Socket } from 'net'; ++import { AuthContext } from './auth-context'; ++ ++const TRACER_NAME = 'transport'; ++const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; ++ ++const clientVersion = require('../../package.json').version; ++ ++const { ++ HTTP2_HEADER_AUTHORITY, ++ HTTP2_HEADER_CONTENT_TYPE, ++ HTTP2_HEADER_METHOD, ++ HTTP2_HEADER_PATH, ++ HTTP2_HEADER_TE, ++ HTTP2_HEADER_USER_AGENT, ++} = http2.constants; ++ ++const KEEPALIVE_TIMEOUT_MS = 20000; ++ ++export interface CallEventTracker { ++ addMessageSent(): void; ++ addMessageReceived(): void; ++ onCallEnd(status: PartialStatusObject): void; ++ onStreamEnd(success: boolean): void; ++} ++ ++export interface TransportDisconnectListener { ++ (tooManyPings: boolean): void; ++} ++ ++export interface Transport { ++ getChannelzRef(): SocketRef; ++ getPeerName(): string; ++ getOptions(): ChannelOptions; ++ getAuthContext(): AuthContext; ++ createCall( ++ metadata: Metadata, ++ host: string, ++ method: string, ++ listener: SubchannelCallInterceptingListener, ++ subchannelCallStatsTracker: Partial, ++ callId?: number ++ ): SubchannelCall; ++ addDisconnectListener(listener: TransportDisconnectListener): void; ++ shutdown(): void; ++} ++ ++const tooManyPingsData: Buffer = Buffer.from('too_many_pings', 'ascii'); ++ ++class Http2Transport implements Transport { ++ /** ++ * The amount of time in between sending pings ++ */ ++ private readonly keepaliveTimeMs: number; ++ /** ++ * The amount of time to wait for an acknowledgement after sending a ping ++ */ ++ private readonly keepaliveTimeoutMs: number; ++ /** ++ * Indicates whether keepalive pings should be sent without any active calls ++ */ ++ private readonly keepaliveWithoutCalls: boolean; ++ /** ++ * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. ++ */ ++ private keepaliveTimer: NodeJS.Timeout | null = null; ++ /** ++ * Indicates that the keepalive timer ran out while there were no active ++ * calls, and a ping should be sent the next time a call starts. ++ */ ++ private pendingSendKeepalivePing = false; ++ ++ private userAgent: string; ++ ++ private activeCalls: Set = new Set(); ++ ++ private subchannelAddressString: string; ++ ++ private disconnectListeners: TransportDisconnectListener[] = []; ++ ++ private disconnectHandled = false; ++ ++ private authContext: AuthContext; ++ ++ // Channelz info ++ private channelzRef: SocketRef; ++ private readonly channelzEnabled: boolean = true; ++ private streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; ++ private keepalivesSent = 0; ++ private messagesSent = 0; ++ private messagesReceived = 0; ++ private lastMessageSentTimestamp: Date | null = null; ++ private lastMessageReceivedTimestamp: Date | null = null; ++ ++ constructor( ++ private session: http2.ClientHttp2Session, ++ subchannelAddress: SubchannelAddress, ++ private options: ChannelOptions, ++ /** ++ * Name of the remote server, if it is not the same as the subchannel ++ * address, i.e. if connecting through an HTTP CONNECT proxy. ++ */ ++ private remoteName: string | null ++ ) { ++ /* Populate subchannelAddressString and channelzRef before doing anything ++ * else, because they are used in the trace methods. */ ++ this.subchannelAddressString = subchannelAddressToString(subchannelAddress); ++ ++ if (options['grpc.enable_channelz'] === 0) { ++ this.channelzEnabled = false; ++ this.streamTracker = new ChannelzCallTrackerStub(); ++ } else { ++ this.streamTracker = new ChannelzCallTracker(); ++ } ++ ++ this.channelzRef = registerChannelzSocket( ++ this.subchannelAddressString, ++ () => this.getChannelzInfo(), ++ this.channelzEnabled ++ ); ++ ++ // Build user-agent string. ++ this.userAgent = [ ++ options['grpc.primary_user_agent'], ++ `grpc-node-js/${clientVersion}`, ++ options['grpc.secondary_user_agent'], ++ ] ++ .filter(e => e) ++ .join(' '); // remove falsey values first ++ ++ if ('grpc.keepalive_time_ms' in options) { ++ this.keepaliveTimeMs = options['grpc.keepalive_time_ms']!; ++ } else { ++ this.keepaliveTimeMs = -1; ++ } ++ if ('grpc.keepalive_timeout_ms' in options) { ++ this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']!; ++ } else { ++ this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; ++ } ++ if ('grpc.keepalive_permit_without_calls' in options) { ++ this.keepaliveWithoutCalls = ++ options['grpc.keepalive_permit_without_calls'] === 1; ++ } else { ++ this.keepaliveWithoutCalls = false; ++ } ++ ++ session.once('close', () => { ++ this.trace('session closed'); ++ this.handleDisconnect(); ++ }); ++ ++ session.once( ++ 'goaway', ++ (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => { ++ let tooManyPings = false; ++ /* See the last paragraph of ++ * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ ++ if ( ++ errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && ++ opaqueData && ++ opaqueData.equals(tooManyPingsData) ++ ) { ++ tooManyPings = true; ++ } ++ if (this.traceEnabled) { ++ this.trace( ++ 'connection closed by GOAWAY with code ' + ++ errorCode + ++ ' and data ' + ++ opaqueData?.toString() ++ ); ++ } ++ this.reportDisconnectToOwner(tooManyPings); ++ } ++ ); ++ ++ session.once('error', error => { ++ if (this.traceEnabled) { ++ this.trace('connection closed with error ' + (error as Error).message); ++ } ++ this.handleDisconnect(); ++ }); ++ ++ session.socket.once('close', (hadError) => { ++ if (this.traceEnabled) { ++ this.trace('connection closed. hadError=' + hadError); ++ } ++ this.handleDisconnect(); ++ }); ++ ++ if (this.traceEnabled) { ++ session.on('remoteSettings', (settings: http2.Settings) => { ++ this.trace( ++ 'new settings received' + ++ (this.session !== session ? ' on the old connection' : '') + ++ ': ' + ++ JSON.stringify(settings) ++ ); ++ }); ++ session.on('localSettings', (settings: http2.Settings) => { ++ this.trace( ++ 'local settings acknowledged by remote' + ++ (this.session !== session ? ' on the old connection' : '') + ++ ': ' + ++ JSON.stringify(settings) ++ ); ++ }); ++ } ++ ++ /* Start the keepalive timer last, because this can trigger trace logs, ++ * which should only happen after everything else is set up. */ ++ if (this.keepaliveWithoutCalls) { ++ this.maybeStartKeepalivePingTimer(); ++ } ++ ++ if (session.socket instanceof TLSSocket && session.socket.authorized) { ++ this.authContext = { ++ transportSecurityType: 'ssl', ++ sslPeerCertificate: session.socket.getPeerCertificate() ++ }; ++ } else { ++ this.authContext = {}; ++ } ++ } ++ ++ private getChannelzInfo(): SocketInfo { ++ const sessionSocket = this.session.socket; ++ const remoteAddress = sessionSocket.remoteAddress ++ ? stringToSubchannelAddress( ++ sessionSocket.remoteAddress, ++ sessionSocket.remotePort ++ ) ++ : null; ++ const localAddress = sessionSocket.localAddress ++ ? stringToSubchannelAddress( ++ sessionSocket.localAddress, ++ sessionSocket.localPort ++ ) ++ : null; ++ let tlsInfo: TlsInfo | null; ++ if (this.session.encrypted) { ++ const tlsSocket: TLSSocket = sessionSocket as TLSSocket; ++ const cipherInfo: CipherNameAndProtocol & { standardName?: string } = ++ tlsSocket.getCipher(); ++ const certificate = tlsSocket.getCertificate(); ++ const peerCertificate = tlsSocket.getPeerCertificate(); ++ tlsInfo = { ++ cipherSuiteStandardName: cipherInfo.standardName ?? null, ++ cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, ++ localCertificate: ++ certificate && 'raw' in certificate ? certificate.raw : null, ++ remoteCertificate: ++ peerCertificate && 'raw' in peerCertificate ++ ? peerCertificate.raw ++ : null, ++ }; ++ } else { ++ tlsInfo = null; ++ } ++ const socketInfo: SocketInfo = { ++ remoteAddress: remoteAddress, ++ localAddress: localAddress, ++ security: tlsInfo, ++ remoteName: this.remoteName, ++ streamsStarted: this.streamTracker.callsStarted, ++ streamsSucceeded: this.streamTracker.callsSucceeded, ++ streamsFailed: this.streamTracker.callsFailed, ++ messagesSent: this.messagesSent, ++ messagesReceived: this.messagesReceived, ++ keepAlivesSent: this.keepalivesSent, ++ lastLocalStreamCreatedTimestamp: ++ this.streamTracker.lastCallStartedTimestamp, ++ lastRemoteStreamCreatedTimestamp: null, ++ lastMessageSentTimestamp: this.lastMessageSentTimestamp, ++ lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, ++ localFlowControlWindow: this.session.state.localWindowSize ?? null, ++ remoteFlowControlWindow: this.session.state.remoteWindowSize ?? null, ++ }; ++ return socketInfo; ++ } ++ ++ private get traceEnabled(): boolean { ++ return logging.isTracerEnabled(TRACER_NAME); ++ } ++ ++ private get keepaliveTraceEnabled(): boolean { ++ return logging.isTracerEnabled('keepalive'); ++ } ++ ++ private get flowControlTraceEnabled(): boolean { ++ return logging.isTracerEnabled(FLOW_CONTROL_TRACER_NAME); ++ } ++ ++ private get internalsTraceEnabled(): boolean { ++ return logging.isTracerEnabled('transport_internals'); ++ } ++ ++ private trace(text: string): void { ++ if (this.traceEnabled) { ++ logging.trace( ++ LogVerbosity.DEBUG, ++ TRACER_NAME, ++ '(' + ++ this.channelzRef.id + ++ ') ' + ++ this.subchannelAddressString + ++ ' ' + ++ text ++ ); ++ } ++ } ++ ++ private keepaliveTrace(text: string): void { ++ if (this.keepaliveTraceEnabled) { ++ logging.trace( ++ LogVerbosity.DEBUG, ++ 'keepalive', ++ '(' + ++ this.channelzRef.id + ++ ') ' + ++ this.subchannelAddressString + ++ ' ' + ++ text ++ ); ++ } ++ } ++ ++ private flowControlTrace(text: string): void { ++ if (this.flowControlTraceEnabled) { ++ logging.trace( ++ LogVerbosity.DEBUG, ++ FLOW_CONTROL_TRACER_NAME, ++ '(' + ++ this.channelzRef.id + ++ ') ' + ++ this.subchannelAddressString + ++ ' ' + ++ text ++ ); ++ } ++ } ++ ++ private internalsTrace(text: string): void { ++ if (this.internalsTraceEnabled) { ++ logging.trace( ++ LogVerbosity.DEBUG, ++ 'transport_internals', ++ '(' + ++ this.channelzRef.id + ++ ') ' + ++ this.subchannelAddressString + ++ ' ' + ++ text ++ ); ++ } ++ } ++ ++ /** ++ * Indicate to the owner of this object that this transport should no longer ++ * be used. That happens if the connection drops, or if the server sends a ++ * GOAWAY. ++ * @param tooManyPings If true, this was triggered by a GOAWAY with data ++ * indicating that the session was closed becaues the client sent too many ++ * pings. ++ * @returns ++ */ ++ private reportDisconnectToOwner(tooManyPings: boolean) { ++ if (this.disconnectHandled) { ++ return; ++ } ++ this.disconnectHandled = true; ++ this.disconnectListeners.forEach(listener => listener(tooManyPings)); ++ } ++ ++ /** ++ * Handle connection drops, but not GOAWAYs. ++ */ ++ private handleDisconnect() { ++ this.clearKeepaliveTimeout(); ++ this.reportDisconnectToOwner(false); ++ for (const call of this.activeCalls) { ++ call.onDisconnect(); ++ } ++ // Wait an event loop cycle before destroying the connection ++ setImmediate(() => { ++ this.session.destroy(); ++ }); ++ } ++ ++ addDisconnectListener(listener: TransportDisconnectListener): void { ++ this.disconnectListeners.push(listener); ++ } ++ ++ private canSendPing() { ++ return ( ++ !this.session.destroyed && ++ this.keepaliveTimeMs > 0 && ++ (this.keepaliveWithoutCalls || this.activeCalls.size > 0) ++ ); ++ } ++ ++ private maybeSendPing() { ++ if (!this.canSendPing()) { ++ this.pendingSendKeepalivePing = true; ++ return; ++ } ++ if (this.keepaliveTimer) { ++ console.error('keepaliveTimeout is not null'); ++ return; ++ } ++ if (this.channelzEnabled) { ++ this.keepalivesSent += 1; ++ } ++ 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'); ++ this.handleDisconnect(); ++ }, this.keepaliveTimeoutMs); ++ this.keepaliveTimer.unref?.(); ++ let pingSendError = ''; ++ try { ++ const pingSentSuccessfully = this.session.ping( ++ (err: Error | null, duration: number, payload: Buffer) => { ++ this.clearKeepaliveTimeout(); ++ if (err) { ++ if (this.keepaliveTraceEnabled) { ++ this.keepaliveTrace('Ping failed with error ' + err.message); ++ } ++ this.handleDisconnect(); ++ } else { ++ this.keepaliveTrace('Received ping response'); ++ this.maybeStartKeepalivePingTimer(); ++ } ++ } ++ ); ++ if (!pingSentSuccessfully) { ++ pingSendError = 'Ping returned false'; ++ } ++ } catch (e) { ++ // grpc/grpc-node#2139 ++ pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; ++ } ++ if (pingSendError) { ++ if (this.keepaliveTraceEnabled) { ++ this.keepaliveTrace('Ping send failed: ' + pingSendError); ++ } ++ this.handleDisconnect(); ++ } ++ } ++ ++ /** ++ * Starts the keepalive ping timer if appropriate. If the timer already ran ++ * out while there were no active requests, instead send a ping immediately. ++ * If the ping timer is already running or a ping is currently in flight, ++ * instead do nothing and wait for them to resolve. ++ */ ++ private maybeStartKeepalivePingTimer() { ++ if (!this.canSendPing()) { ++ return; ++ } ++ if (this.pendingSendKeepalivePing) { ++ this.pendingSendKeepalivePing = false; ++ this.maybeSendPing(); ++ } else if (!this.keepaliveTimer) { ++ this.keepaliveTrace( ++ 'Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms' ++ ); ++ this.keepaliveTimer = setTimeout(() => { ++ this.keepaliveTimer = null; ++ this.maybeSendPing(); ++ }, this.keepaliveTimeMs); ++ this.keepaliveTimer.unref?.(); ++ } ++ /* Otherwise, there is already either a keepalive timer or a ping pending, ++ * wait for those to resolve. */ ++ } ++ ++ /** ++ * Clears whichever keepalive timeout is currently active, if any. ++ */ ++ private clearKeepaliveTimeout() { ++ if (this.keepaliveTimer) { ++ clearTimeout(this.keepaliveTimer); ++ this.keepaliveTimer = null; ++ } ++ } ++ ++ private removeActiveCall(call: Http2SubchannelCall) { ++ this.activeCalls.delete(call); ++ if (this.activeCalls.size === 0) { ++ this.session.unref(); ++ } ++ } ++ ++ private addActiveCall(call: Http2SubchannelCall) { ++ this.activeCalls.add(call); ++ if (this.activeCalls.size === 1) { ++ this.session.ref(); ++ if (!this.keepaliveWithoutCalls) { ++ this.maybeStartKeepalivePingTimer(); ++ } ++ } ++ } ++ ++ createCall( ++ metadata: Metadata, ++ host: string, ++ method: string, ++ listener: SubchannelCallInterceptingListener, ++ subchannelCallStatsTracker: Partial, ++ callId?: number ++ ): Http2SubchannelCall { ++ const headers = metadata.toHttp2Headers(); ++ headers[HTTP2_HEADER_AUTHORITY] = host; ++ headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; ++ headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; ++ headers[HTTP2_HEADER_METHOD] = 'POST'; ++ headers[HTTP2_HEADER_PATH] = method; ++ headers[HTTP2_HEADER_TE] = 'trailers'; ++ let http2Stream: http2.ClientHttp2Stream; ++ /* In theory, if an error is thrown by session.request because session has ++ * become unusable (e.g. because it has received a goaway), this subchannel ++ * should soon see the corresponding close or goaway event anyway and leave ++ * READY. But we have seen reports that this does not happen ++ * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) ++ * so for defense in depth, we just discard the session when we see an ++ * error here. ++ */ ++ try { ++ http2Stream = this.session.request(headers); ++ } catch (e) { ++ this.handleDisconnect(); ++ throw e; ++ } ++ 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: CallEventTracker; ++ // eslint-disable-next-line prefer-const ++ let call: Http2SubchannelCall; ++ if (this.channelzEnabled) { ++ this.streamTracker.addCallStarted(); ++ eventTracker = { ++ addMessageSent: () => { ++ this.messagesSent += 1; ++ this.lastMessageSentTimestamp = new Date(); ++ subchannelCallStatsTracker.addMessageSent?.(); ++ }, ++ addMessageReceived: () => { ++ this.messagesReceived += 1; ++ this.lastMessageReceivedTimestamp = new Date(); ++ subchannelCallStatsTracker.addMessageReceived?.(); ++ }, ++ onCallEnd: status => { ++ subchannelCallStatsTracker.onCallEnd?.(status); ++ this.removeActiveCall(call); ++ }, ++ onStreamEnd: success => { ++ if (success) { ++ this.streamTracker.addCallSucceeded(); ++ } else { ++ this.streamTracker.addCallFailed(); ++ } ++ subchannelCallStatsTracker.onStreamEnd?.(success); ++ }, ++ }; ++ } else { ++ eventTracker = { ++ addMessageSent: () => { ++ subchannelCallStatsTracker.addMessageSent?.(); ++ }, ++ addMessageReceived: () => { ++ subchannelCallStatsTracker.addMessageReceived?.(); ++ }, ++ onCallEnd: status => { ++ subchannelCallStatsTracker.onCallEnd?.(status); ++ this.removeActiveCall(call); ++ }, ++ onStreamEnd: success => { ++ subchannelCallStatsTracker.onStreamEnd?.(success); ++ }, ++ }; ++ } ++ call = new Http2SubchannelCall( ++ http2Stream, ++ eventTracker, ++ listener, ++ this, ++ callId ?? getNextCallNumber() ++ ); ++ this.addActiveCall(call); ++ return call; ++ } ++ ++ getChannelzRef(): SocketRef { ++ return this.channelzRef; ++ } ++ ++ getPeerName() { ++ return this.subchannelAddressString; ++ } ++ ++ getOptions() { ++ return this.options; ++ } ++ ++ getAuthContext(): AuthContext { ++ return this.authContext; ++ } ++ ++ shutdown() { ++ this.session.close(); ++ unregisterChannelzRef(this.channelzRef); ++ } ++} ++ ++export interface SubchannelConnector { ++ connect( ++ address: SubchannelAddress, ++ secureConnector: SecureConnector, ++ options: ChannelOptions ++ ): Promise; ++ shutdown(): void; ++} ++ ++export class Http2SubchannelConnector implements SubchannelConnector { ++ private session: http2.ClientHttp2Session | null = null; ++ private isShutdown = false; ++ constructor(private channelTarget: GrpcUri) {} ++ ++ private get traceEnabled(): boolean { ++ return logging.isTracerEnabled(TRACER_NAME); ++ } ++ ++ private trace(text: string) { ++ if (this.traceEnabled) { ++ logging.trace( ++ LogVerbosity.DEBUG, ++ TRACER_NAME, ++ uriToString(this.channelTarget) + ' ' + text ++ ); ++ } ++ } ++ ++ private createSession( ++ secureConnectResult: SecureConnectResult, ++ address: SubchannelAddress, ++ options: ChannelOptions ++ ): Promise { ++ if (this.isShutdown) { ++ return Promise.reject(); ++ } ++ ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ if (secureConnectResult.socket.closed) { ++ return Promise.reject('Connection closed before starting HTTP/2 handshake'); ++ } ++ ++ return new Promise((resolve, reject) => { ++ let remoteName: string | null = null; ++ let realTarget: GrpcUri = this.channelTarget; ++ if ('grpc.http_connect_target' in options) { ++ const parsedTarget = parseUri(options['grpc.http_connect_target']!); ++ if (parsedTarget) { ++ realTarget = parsedTarget; ++ remoteName = uriToString(parsedTarget); ++ } ++ } ++ const scheme = secureConnectResult.secure ? 'https' : 'http'; ++ const targetPath = getDefaultAuthority(realTarget); ++ const closeHandler = () => { ++ this.session?.destroy(); ++ this.session = null; ++ // Leave time for error event to happen before rejecting ++ setImmediate(() => { ++ if (!reportedError) { ++ reportedError = true; ++ reject(`${errorMessage.trim()} (${new Date().toISOString()})`); ++ } ++ }); ++ }; ++ const errorHandler = (error: Error) => { ++ this.session?.destroy(); ++ errorMessage = (error as Error).message; ++ if (this.traceEnabled) { ++ this.trace('connection failed with error ' + errorMessage); ++ } ++ if (!reportedError) { ++ reportedError = true; ++ reject(`${errorMessage} (${new Date().toISOString()})`); ++ } ++ }; ++ const sessionOptions: http2.ClientSessionOptions = { ++ createConnection: (authority, option) => { ++ return secureConnectResult.socket; ++ }, ++ settings: { ++ initialWindowSize: ++ options['grpc-node.flow_control_window'] ?? ++ http2.getDefaultSettings?.()?.initialWindowSize ?? 65535, ++ }, ++ maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, ++ /* By default, set a very large max session memory limit, to effectively ++ * disable enforcement of the limit. Some testing indicates that Node's ++ * behavior degrades badly when this limit is reached, so we solve that ++ * by disabling the check entirely. */ ++ maxSessionMemory: options['grpc-node.max_session_memory'] ?? Number.MAX_SAFE_INTEGER ++ }; ++ const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); ++ // Prepare window size configuration for remoteSettings handler ++ const defaultWin = http2.getDefaultSettings?.()?.initialWindowSize ?? 65535; // 65 535 B ++ const connWin = options[ ++ 'grpc-node.flow_control_window' ++ ] as number | undefined; ++ ++ this.session = session; ++ let errorMessage = 'Failed to connect'; ++ let reportedError = false; ++ session.unref(); ++ session.once('remoteSettings', () => { ++ // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. ++ if (connWin && connWin > defaultWin) { ++ try { ++ // Node ≥ 14.18 ++ (session as any).setLocalWindowSize(connWin); ++ } catch { ++ // Older Node: bump by the delta ++ const delta = connWin - (session.state.localWindowSize ?? defaultWin); ++ if (delta > 0) (session as any).incrementWindowSize(delta); ++ } ++ } ++ ++ session.removeAllListeners(); ++ options['grpc-node.transport_owner']?.session(session); ++ secureConnectResult.socket.removeListener('close', closeHandler); ++ secureConnectResult.socket.removeListener('error', errorHandler); ++ resolve(new Http2Transport(session, address, options, remoteName)); ++ this.session = null; ++ }); ++ session.once('close', closeHandler); ++ session.once('error', errorHandler); ++ secureConnectResult.socket.once('close', closeHandler); ++ secureConnectResult.socket.once('error', errorHandler); ++ options['grpc-node.transport_owner']?.session(session); ++ }); ++ } ++ ++ private tcpConnect(address: SubchannelAddress, options: ChannelOptions): Promise { ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ return getProxiedConnection(address, options).then(proxiedSocket => { ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ if (proxiedSocket) { ++ return proxiedSocket; ++ } else { ++ return new Promise((resolve, reject) => { ++ const closeCallback = () => { ++ reject(new Error('Socket closed')); ++ }; ++ const errorCallback = (error: Error) => { ++ reject(error); ++ } ++ const socket = net.connect(address, () => { ++ socket.removeListener('close', closeCallback); ++ socket.removeListener('error', errorCallback); ++ resolve(socket); ++ }); ++ socket.once('close', closeCallback); ++ socket.once('error', errorCallback); ++ options['grpc-node.transport_owner']?.socket(socket); ++ }); ++ } ++ }); ++ } ++ ++ connect(address: SubchannelAddress, secureConnector: SecureConnector, options: ChannelOptions): Promise { ++ const owner = options['grpc-node.transport_owner']; ++ if (owner && options['grpc.use_local_subchannel_pool'] !== 1) return Promise.reject(new Error('Owned transport requires a private subchannel pool')); ++ const operation = this.connectOwned(address, secureConnector, options); ++ owner?.pending(operation); ++ return operation; ++ } ++ private async connectOwned( ++ address: SubchannelAddress, ++ secureConnector: SecureConnector, ++ options: ChannelOptions ++ ): Promise { ++ if (this.isShutdown) { ++ return Promise.reject(); ++ } ++ let tcpConnection: net.Socket | null = null; ++ let secureConnectResult: SecureConnectResult | null = null; ++ const addressString = subchannelAddressToString(address); ++ try { ++ if (this.traceEnabled) { ++ this.trace(addressString + ' Waiting for secureConnector to be ready'); ++ } ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ await secureConnector.waitForReady(); ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ if (this.traceEnabled) { ++ this.trace(addressString + ' secureConnector is ready'); ++ } ++ tcpConnection = await this.tcpConnect(address, options); ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ tcpConnection.setNoDelay(); ++ if (this.traceEnabled) { ++ this.trace(addressString + ' Established TCP connection'); ++ } ++ secureConnectResult = await secureConnector.connect(tcpConnection); ++ options['grpc-node.transport_owner']?.signal.throwIfAborted(); ++ if (this.traceEnabled) { ++ this.trace(addressString + ' Established secure connection'); ++ } ++ return this.createSession(secureConnectResult, address, options); ++ } catch (e) { ++ tcpConnection?.destroy(); ++ secureConnectResult?.socket.destroy(); ++ throw e; ++ } ++ } ++ ++ shutdown(): void { ++ this.isShutdown = true; ++ this.session?.close(); ++ this.session = null; ++ } ++} diff --git a/patches/@photon-ai__advanced-imessage@2.2.0.patch b/patches/@photon-ai__advanced-imessage@2.2.0.patch new file mode 100644 index 00000000000..aeaa13bb601 --- /dev/null +++ b/patches/@photon-ai__advanced-imessage@2.2.0.patch @@ -0,0 +1,30 @@ +--- a/dist/chunk-5WYZRCOS.js ++++ b/dist/chunk-5WYZRCOS.js +@@ -7246,15 +7246,20 @@ + // Lifecycle + // ------------------------------------------------------------------------- + /** Signal the stream is done. Interrupts any pending iteration. */ +- async close() { +- if (this._closed) { +- return; +- } ++ close() { ++ if (this._cleanupComplete) return Promise.resolve(); ++ if (this._closeAttempt) return this._closeAttempt; + this._closed = true; + this._cancelResolve?.(); +- if (this._cleanup) { +- await this._cleanup(); +- } ++ let resolveCleanup, rejectCleanup; ++ const attempt = new Promise((resolve, reject) => { resolveCleanup = resolve; rejectCleanup = reject; }); ++ this._closeAttempt = attempt; ++ try { Promise.resolve(this._cleanup?.()).then(resolveCleanup, rejectCleanup); } ++ catch (error) { rejectCleanup(error); } ++ void attempt.then(() => { this._cleanupComplete = true; }, () => { ++ if (this._closeAttempt === attempt) this._closeAttempt = undefined; ++ }); ++ return attempt; + } + /** `Symbol.asyncDispose` -- enables `await using`. */ + async [Symbol.asyncDispose]() { diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a20325bff3a..c4dd38caae7 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -16,6 +16,8 @@ packages: # Keep in sync with package.json#pnpm.patchedDependencies. Newer pnpm # versions read patch configuration only from the workspace manifest. patchedDependencies: + "@grpc/grpc-js@1.14.5": patches/@grpc__grpc-js@1.14.5.patch + "@photon-ai/advanced-imessage@2.2.0": patches/@photon-ai__advanced-imessage@2.2.0.patch postgres@3.4.9: patches/postgres@3.4.9.patch embedded-postgres@18.1.0-beta.16: patches/embedded-postgres@18.1.0-beta.16.patch acpx@0.12.0: patches/acpx@0.12.0.patch diff --git a/server/src/__tests__/photon/external-owner.test.ts b/server/src/__tests__/photon/external-owner.test.ts new file mode 100644 index 00000000000..f65c5691dfc --- /dev/null +++ b/server/src/__tests__/photon/external-owner.test.ts @@ -0,0 +1,162 @@ +import { isDeepStrictEqual } from "node:util"; +import { describe, expect, it } from "vitest"; +import type { ChatSdkStatePersistence, ChatSdkStateRecord } from "../../services/chat-sdk-state.js"; +import { PhotonState } from "../../services/photon/state.js"; +import { PhotonUsefulClient } from "../../services/photon/useful-client.js"; +import { createPhotonExternalOwner, PhotonLocalResources, handoffCheckpoint, recordPhotonCheckpointAuthority } from "../../services/chat-channels/imessage-photon/external-owner.js"; +import { photonHash, readPhotonExternalState, parsePhotonExternalDelivery, type PhotonExternalIdentity, type PhotonExternalState } from "../../services/chat-channels/imessage-photon/external-contract.js"; +import { PHOTON_EXTERNAL_STATE, type PhotonExternalStore } from "../../services/chat-channels/imessage-photon/external-store.js"; +import { writePhotonCheckpoint } from "../../services/photon/receiver.js"; + +const identity: PhotonExternalIdentity = { companyId: "company", endpointId: "endpoint", connectionId: "connection", runtimeGeneration: 1, + credentialReferences: "a".repeat(64), subject: "current-company-manager" }; +const config = { provider: "imessage-photon" as const, userName: "Photon", intakeAfter: 1, + credentials: { projectId: "project", projectSecret: "controlled-project-secret", lineId: "line", phoneNumber: "+15555550101", allocation: "dedicated" as const } }; +function fixture() { + let rows = new Map(), currentLease = "lease", currentGeneration = 1; + const persistence: ChatSdkStatePersistence = { + read: async (_scope, key) => structuredClone(rows.get(key) ?? null), + compareAndSet: async input => { + const current = rows.get(input.key); + if ((current?.version ?? null) !== input.expectedVersion) return false; + // Exercise JSON persistence rather than keeping shared reference identity. + rows.set(input.key, { value: JSON.parse(JSON.stringify(input.value)), version: (current?.version ?? 0) + 1, expiresAt: null }); return true; + }, + deleteIfVersion: async input => rows.get(input.key)?.version === input.expectedVersion && rows.delete(input.key), + }; + const state = new PhotonState(identity, persistence); + async function read() { return readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE)); } + const store: PhotonExternalStore = { + read: async () => read(), + inspect: async () => read(), + current: async (selected, lease, work) => { + if (selected.companyId !== identity.companyId || selected.runtimeGeneration !== currentGeneration || lease.token !== currentLease) throw new Error("current authority changed"); + const before = structuredClone(rows); + try { return await work(state, await read()); } catch (error) { rows = before; throw error; } + }, + retained: async (expected, update) => state.update(PHOTON_EXTERNAL_STATE, raw => { + const actual = readPhotonExternalState(raw); + if (!actual || !isDeepStrictEqual(actual, expected)) throw new Error("retained CAS failed"); + return update(actual); + }), + noEffect: async () => { throw new Error("no revocation in this owner-port fixture"); }, + }; + let lostEnrollment = false, retirement = "retiring", enrollments = 0, joins = 0; + const requests: Record[] = []; + const resources = new PhotonLocalResources(), resource = {}; + const resourceId = resources.capture(resource, async () => { + joins++; + await writePhotonCheckpoint(state, "line", 2); + await recordPhotonCheckpointAuthority(state, identity, 2); + }); + const broker = { instanceIdentity: () => ({ instanceId: "instance", environment: "test" as const }), + photonReceiverOperation: async ({ operation }: { operation: Record }) => { + requests.push(structuredClone(operation)); + const retained = await read(); if (!retained) throw new Error("missing durable intent"); + if (operation.kind === "enroll") { + enrollments++; + if (lostEnrollment) { lostEnrollment = false; throw new Error("lost enrollment reply"); } + return { binding: retained.binding }; + } + if (operation.kind === "retire") return { binding: retained.binding, pending: true }; + return { binding: retained.binding, handoffId: retained.handoffId, phase: retirement }; + } }; + const create = (selectedResources = resources) => createPhotonExternalOwner({ store, broker, resources: selectedResources, notify: () => {}, now: () => new Date("2099-01-01T00:00:00.000Z") }); + const reconcile = () => create().reconcile({ identity, config, lease: { token: currentLease }, localResourceId: resourceId }); + return { state, store, resources, resourceId, resource, requests, create, reconcile, read, + loseReply: () => { lostEnrollment = true; }, replaceGeneration: () => { currentGeneration++; }, replaceLease: () => { currentLease = "next-lease"; }, + finishRetirement: () => { retirement = "retired"; }, counts: () => ({ enrollments, joins }) }; +} +// Actual pinned protobuf: CatchUpEventsResponse.sequence=1/chat_changed=13; +// ChatChangeEvent.chat_guid=1/occurred_at=2/marked_read=12. The REAL SDK decoder +// owns interpretation; these controls do not mock or replace it. +function delivery(state: PhotonExternalState, sequence = 3, previousSequence: number | null = 2) { + const raw = Buffer.from([8, sequence, 106, 12, 10, 4, 99, 104, 97, 116, 18, 2, 8, 1, 98, 0]); + const createdAt = "2099-01-01T00:00:00.000Z"; + return { id: `photon_${photonHash([state.binding.bindingId, sequence])}`, event: "chat.markedRead", createdAt, installationId: state.binding.bindingId, bindingIds: [state.binding.bindingId], + payload: { version: 1, binding: state.binding, sequence, previousSequence, acceptedAt: createdAt, rawFrame: raw.toString("base64") } }; +} +describe("Photon normal external-owner handoff (controlled owner ports, not real SQL or gRPC)", () => { + it("stages the exact enrollment before broker use and joins before external placement", async () => { + const f = fixture(), accepted = await f.reconcile(); + expect(accepted.phase).toBe("external"); expect(accepted.joinedSequence).toBe(2); + expect(f.counts()).toEqual({ enrollments: 1, joins: 1 }); + expect(f.requests[0].enrollment).toMatchObject({ initialized: false, sequence: null, handoffId: accepted.handoffId }); + }); + it("lost enrollment reply retains the same input and retries without an early join", async () => { + const f = fixture(); f.loseReply(); await expect(f.reconcile()).rejects.toThrow("lost enrollment reply"); + const original = await f.read(); expect(original?.phase).toBe("enrolling"); expect(f.counts().joins).toBe(0); + const accepted = await f.reconcile(); expect(accepted.handoffId).toBe(original?.handoffId); + expect(f.requests[0]).toEqual(f.requests[1]); expect(f.counts().joins).toBe(1); + }); + it("a replacement process cannot use absent local resources as physical-close proof", async () => { + const f = fixture(); f.loseReply(); await expect(f.reconcile()).rejects.toThrow(); + await expect(f.create(new PhotonLocalResources()).reconcile({ identity, config, lease: { token: "lease" }, localResourceId: f.resourceId })).rejects.toThrow("closure is unknown"); + expect(await f.read()).toMatchObject({ phase: "joining", failure: { code: "local_join" } }); + }); + it("unknown initialized legacy checkpoint provenance remains attention", async () => { + const f = fixture(); await writePhotonCheckpoint(f.state, "line", 17); + await expect(handoffCheckpoint(f.state, identity, "line")).rejects.toThrow("provenance"); + await expect(f.reconcile()).rejects.toThrow("provenance"); expect(f.counts().enrollments).toBe(0); + }); + it("real SDK decoded event commits normal callback before checkpoint and normal ACK permission", async () => { + const f = fixture(), state = await f.reconcile(), event = delivery(state); let calls = 0; + await f.create().dispatch({ identity, lease: { token: "lease" }, delivery: event, admit: async decoded => { + expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 2 }); expect(decoded).toMatchObject({ type: "chat.markedRead", chatGuid: "chat", sequence: 3 }); calls++; + } }); + expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 3 }); + await f.create().dispatch({ identity, lease: { token: "lease" }, delivery: event, admit: async () => { calls++; } }); + expect(calls).toBe(1); expect(await f.read()).toMatchObject({ acceptedSequence: 3, pending: null }); + }); + it("out-of-order cross-batch delivery cannot advance an opaque admitted predecessor", async () => { + const f = fixture(), state = await f.reconcile(); let calls = 0; + await expect(f.create().dispatch({ identity, lease: { token: "lease" }, delivery: delivery(state, 5, 4), admit: async () => { calls++; } })).rejects.toThrow("predecessor"); + expect(calls).toBe(0); expect(await f.read()).toMatchObject({ acceptedSequence: 2, pending: null }); + }); + it("lease replacement after callback retains the same pending receipt and no cursor advance", async () => { + const f = fixture(), state = await f.reconcile(); const effects = new Set(); let calls = 0; + const admit = async () => { effects.add(3); calls++; if (calls === 1) f.replaceLease(); }; + await expect(f.create().dispatch({ identity, lease: { token: "lease" }, delivery: delivery(state), admit })).rejects.toThrow("authority"); + expect(await f.read()).toMatchObject({ acceptedSequence: 2, pending: { sequence: 3 } }); + expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 2 }); + await f.create().dispatch({ identity, lease: { token: "next-lease" }, delivery: delivery(state), admit }); + expect(calls).toBe(2); expect(effects.size).toBe(1); + }); + it("foreign company/environment/delivery and altered original frame fail before callback", async () => { + const f = fixture(), state = await f.reconcile(), event = delivery(state); + for (const binding of [{ ...state.binding, companyId: "foreign" }, { ...state.binding, environment: "production" }]) + expect(() => parsePhotonExternalDelivery({ ...event, payload: { ...event.payload, binding } }, state)).toThrow(); + expect(() => parsePhotonExternalDelivery({ ...event, id: "foreign" }, state)).toThrow(); + expect(() => parsePhotonExternalDelivery({ ...event, payload: { ...event.payload, rawFrame: event.payload.rawFrame + "=" } }, state)).toThrow(); + }); + it("retirement keeps the exact original fact until normal SQL acceptance", async () => { + const f = fixture(), state = await f.reconcile(); + await expect(f.create().retire(state)).rejects.toThrow("remains outstanding"); + const pending = await f.read(); expect(pending?.phase).toBe("retiring"); + f.finishRetirement(); if (!pending) throw new Error("missing retirement"); + await f.create().retire(pending); expect(await f.read()).toMatchObject({ phase: "retired", handoffId: state.handoffId, binding: state.binding }); + }); +}); +describe("Photon actual resource join and useful-channel owner", () => { + it("joins concurrent calls, retries only failed close and never confirms an unknown object", async () => { + const resources = new PhotonLocalResources(); let calls = 0, release = () => {}; + const gate = new Promise(resolve => { release = resolve; }); + const id = resources.capture({}, async () => { if (++calls === 1) throw new Error("close failed"); await gate; }); + await expect(resources.join(id)).rejects.toThrow("close failed"); + let closed = false; const second = resources.join(id).then(() => { closed = true; }), concurrent = resources.join(id); + await Promise.resolve(); expect(closed).toBe(false); expect(calls).toBe(2); release(); await Promise.all([second, concurrent]); + await resources.join(id); expect(calls).toBe(2); await expect(resources.join("unknown")).rejects.toThrow("unknown"); + }); + it("fresh useful work opens and physically closes its own channel every time", async () => { + let opens = 0, closes = 0; const owner = new PhotonUsefulClient(() => { opens++; return { close: async () => { closes++; } }; }); + await owner.run(async () => "first-useful-result"); await owner.run(async () => "second-useful-result"); + expect({ opens, closes }).toEqual({ opens: 2, closes: 2 }); await owner.close(); expect(closes).toBe(2); + }); + it("known provider receipt survives cleanup refusal and old physical resource retries before new send", async () => { + let opens = 0, closes = 0, sends = 0, debt = 0; + const owner = new PhotonUsefulClient(() => { opens++; return { close: async () => { if (++closes === 1) throw new Error("cleanup refused"); } }; }, undefined, async () => { debt++; }); + expect(await owner.run(async () => { sends++; return { messageId: "known-original" }; })).toEqual({ messageId: "known-original" }); + expect({ opens, closes, sends, debt }).toEqual({ opens: 1, closes: 1, sends: 1, debt: 1 }); + await owner.drain(); expect({ opens, closes, sends }).toEqual({ opens: 1, closes: 2, sends: 1 }); await owner.close(); + }); +}); diff --git a/server/src/__tests__/photon/photon.test.ts b/server/src/__tests__/photon/photon.test.ts index 90f1081783e..5f48b2f547c 100644 --- a/server/src/__tests__/photon/photon.test.ts +++ b/server/src/__tests__/photon/photon.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, vi } from "vitest"; import { Client, Server, ServerCredentials, credentials } from "@grpc/grpc-js"; -import { IMessageError, type LiveEvent } from "@photon-ai/advanced-imessage"; +import { IMessageError, TypedEventStream, type LiveEvent } from "@photon-ai/advanced-imessage"; import type { AskUserQuestionsInteraction } from "@paperclipai/shared"; import { PhotonCloudClient, @@ -64,6 +64,7 @@ const question = (id = "interaction"): AskUserQuestionsInteraction => }, }) as AskUserQuestionsInteraction; const guard = async () => {}; +const recordedFailure = async (): Promise<{ kind: "recorded" }> => ({ kind: "recorded" }); describe("Photon Cloud and fixed line identity", () => { it("uses Basic project auth, verifies dedicated allocation, and never exposes tokens", async () => { @@ -302,6 +303,108 @@ describe("Photon publication receipts", () => { }); describe("Photon durable event recovery", () => { + it("initial obsolete failure receipt cannot certify stopped responsibility", async () => { + const f = photonFixture(); let attempted!: () => void, releaseLive!: () => void; + const reported = new Promise(resolve => { attempted = resolve; }); + const live = new Promise(resolve => { releaseLive = resolve; }); + for (const resource of [f.client.messages, f.client.chats, f.client.groups, f.client.polls]) + resource.subscribeEvents.mockImplementation(() => new TypedEventStream((async function* () { await live; })(), async () => { releaseLive(); })); + const failure = vi.fn<() => Promise>(async () => { attempted(); return { kind: "obsolete" }; }); + const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0, + assertOwned: guard, admit: guard, failure, catchUp: () => new TypedEventStream((async function* () { throw new Error("controlled CatchUp failure"); })()) }); + try { + receiver.start(); await reported; await new Promise(resolve => setImmediate(resolve)); + await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed"); + expect(await f.state.read("checkpoint")).toBeNull(); + failure.mockResolvedValue({ kind: "recorded" }); await receiver.close(); + } finally { failure.mockResolvedValue({ kind: "recorded" }); await receiver.close(); } + }); + + it("retains completed request reporting debt until the same owner durably records it on close retry", async () => { + const f = photonFixture(), source = new Error("controlled catch-up failure"), reporting = new Error("controlled attention persistence failure"); + let attempted!: () => void; + const reported = new Promise(resolve => { attempted = resolve; }); + // Live subscriptions stay open; only the normal CatchUp request fails. + let releaseLive!: () => void; + const live = new Promise(resolve => { releaseLive = resolve; }); + for (const resource of [f.client.messages, f.client.chats, f.client.groups, f.client.polls]) + resource.subscribeEvents.mockImplementation(() => new TypedEventStream((async function* () { await live; })(), async () => { releaseLive(); })); + const failure = vi.fn<() => Promise>(async () => { attempted(); throw reporting; }); + const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0, + assertOwned: guard, admit: guard, failure, catchUp: () => new TypedEventStream((async function* () { throw source; })()) }); + try { + receiver.start(); await reported; + // The failure callback and request have completed BEFORE shutdown starts. + await new Promise(resolve => setImmediate(resolve)); + expect(failure).toHaveBeenCalledTimes(1); + await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed"); + expect(failure).toHaveBeenCalledTimes(2); + failure.mockImplementation(async () => ({ kind: "recorded" as const })); + const repaired = receiver.close(); expect(receiver.close()).toBe(repaired); + await repaired; expect(receiver.close()).toBe(repaired); + expect(failure).toHaveBeenCalledTimes(3); + expect(await f.state.read("checkpoint")).toBeNull(); + } finally { + failure.mockImplementation(async () => ({ kind: "recorded" as const })); + await receiver.close(); + } + }); + it("does not treat a stale or void reporting retry as current durable responsibility", async () => { + const f = photonFixture(); let attempted!: () => void; + const reported = new Promise(resolve => { attempted = resolve; }); + // Live subscriptions stay open; only the normal CatchUp request fails. + let releaseLive!: () => void; + const live = new Promise(resolve => { releaseLive = resolve; }); + for (const resource of [f.client.messages, f.client.chats, f.client.groups, f.client.polls]) + resource.subscribeEvents.mockImplementation(() => new TypedEventStream((async function* () { await live; })(), async () => { releaseLive(); })); + const failure = vi.fn<() => Promise>(async () => { attempted(); throw new Error("controlled persistence failure"); }); + const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0, + assertOwned: guard, admit: guard, failure, catchUp: () => new TypedEventStream((async function* () { throw new Error("controlled catch-up failure"); })()) }); + try { + receiver.start(); await reported; await new Promise(resolve => setImmediate(resolve)); + failure.mockResolvedValue({ kind: "obsolete" }); + await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed"); + failure.mockResolvedValue(undefined); + await expect(receiver.close()).rejects.toThrow("shutdown remains unconfirmed"); + } finally { + failure.mockResolvedValue({ kind: "recorded" }); await receiver.close(); + } + }); + it("joins in-flight durable admission before close completes and never admits new work after stop", async () => { + const f = photonFixture(); let release!: () => void, entered!: () => void, finished = false; + const pending = new Promise(resolve => { release = resolve; }), admitting = new Promise(resolve => { entered = resolve; }); + const admit = vi.fn(async () => { entered(); await pending; }); + const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0, + assertOwned: guard, admit, failure: recordedFailure, catchUp: () => stream([photonEvent(1), { type: "catchup.complete", headSequence: 1 }]) }); + receiver.start(); await admitting; + const closing = receiver.close(); expect(receiver.close()).toBe(closing); + void closing.then(() => { finished = true; }); await Promise.resolve(); expect(finished).toBe(false); + release(); await closing; expect(finished).toBe(true); expect(admit).toHaveBeenCalledTimes(1); + await receiver.catchUp(); expect(admit).toHaveBeenCalledTimes(1); expect(f.client.close).toHaveBeenCalledTimes(1); + expect(await f.state.read("checkpoint")).toMatchObject({ sequence: 1 }); + }); + it("retries the same client close after failure and memoizes only successful joined shutdown", async () => { + const f = photonFixture(), original = new Error("controlled actual client close failure"); + f.client.close.mockRejectedValueOnce(original); + const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0, + assertOwned: guard, admit: guard, failure: recordedFailure }); + const first = receiver.close(); expect(receiver.close()).toBe(first); + await expect(first).rejects.toMatchObject({ errors: [original] }); + const second = receiver.close(); expect(second).not.toBe(first); expect(receiver.close()).toBe(second); + await second; expect(receiver.close()).toBe(second); expect(f.client.close).toHaveBeenCalledTimes(2); + }); + it("never converts an unresolved SDK stream cleanup rejection into a successful repeated close", async () => { + const f = photonFixture(), original = new Error("controlled actual stream cleanup failure"); let unblock!: () => void; + const blocked = new Promise(resolve => { unblock = resolve; }); + f.client.messages.subscribeEvents.mockReturnValue(new TypedEventStream((async function* () { await blocked; })(), async () => { unblock(); throw original; })); + const receiver = new PhotonReceiver({ client: f.adapter.client, state: f.state, lineId: "line", intakeAfter: 0, + assertOwned: guard, admit: guard, failure: recordedFailure }); + receiver.start(); + await expect(receiver.close()).rejects.toMatchObject({ errors: expect.arrayContaining([original]) }); + await expect(receiver.close()).rejects.toMatchObject({ errors: expect.arrayContaining([original]) }); + expect(f.client.close).toHaveBeenCalledTimes(2); + }); + it("records preceding events, deduplicates, and does not checkpoint an unadmitted event", async () => { const f = photonFixture(); const events = [photonEvent(1), photonEvent(2)]; @@ -316,7 +419,7 @@ describe("Photon durable event recovery", () => { intakeAfter: 0, assertOwned: guard, admit: admitted, - failure: guard, + failure: recordedFailure, catchUp: () => stream([...events, { type: "catchup.complete", headSequence: 2 }]), }); @@ -339,7 +442,7 @@ describe("Photon durable event recovery", () => { intakeAfter: Date.now() + 1000, assertOwned: guard, admit, - failure: guard, + failure: recordedFailure, catchUp: () => stream([ photonEvent(10), @@ -357,7 +460,7 @@ describe("Photon durable event recovery", () => { intakeAfter: 0, assertOwned: guard, admit, - failure: guard, + failure: recordedFailure, catchUp: () => stream([ photonEvent(13), @@ -374,7 +477,7 @@ describe("Photon durable event recovery", () => { throw new Error("lease lost"); }, admit, - failure: guard, + failure: recordedFailure, }); await expect(lost.catchUp()).rejects.toThrow("lease lost"); expect(admit).not.toHaveBeenCalled(); @@ -384,7 +487,7 @@ describe("Photon durable event recovery", () => { const admit = vi.fn(guard); await f.state.update("checkpoint", () => ({schema:1, lineId:"line", sequence:0})); let events: any[] = [photonEvent(1_008_648_034), {type:"catchup.complete",headSequence:1_008_648_034}]; - const receiver = new PhotonReceiver({client:f.adapter.client,state:f.state,lineId:"line",allocation:"shared",intakeAfter:0,assertOwned:guard,admit,failure:guard,catchUp:()=>stream(events)}); + const receiver = new PhotonReceiver({client:f.adapter.client,state:f.state,lineId:"line",allocation:"shared",intakeAfter:0,assertOwned:guard,admit,failure:recordedFailure,catchUp:()=>stream(events)}); await receiver.catchUp(); expect(admit).toHaveBeenCalledTimes(1); expect(await f.state.read("checkpoint")).toMatchObject({sequence:1_008_648_034}); @@ -443,7 +546,7 @@ describe("Photon durable event recovery", () => { { type: "catchup.complete", headSequence: 3 }, ]); } finally { - transport.close(); + await transport.close(); server.forceShutdown(); } }); diff --git a/server/src/services/activity-log.ts b/server/src/services/activity-log.ts index de1940acd24..0734e6b954f 100644 --- a/server/src/services/activity-log.ts +++ b/server/src/services/activity-log.ts @@ -6,6 +6,9 @@ export type { ActivityPublication } from "../types/activity-publication.js"; import { randomUUID } from "node:crypto"; import { and, eq } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; + +/** Activity persistence needs query/transaction capability, not a pool client. */ +type ActivityDb = Pick; import { activityLog, agentApiKeys, companies, heartbeatRuns, issues } from "@paperclipai/db"; import { isUuidLike, PLUGIN_EVENT_TYPES, type PluginEventType } from "@paperclipai/shared"; import type { PluginEvent } from "@paperclipai/plugin-sdk"; @@ -73,7 +76,7 @@ export interface LogActivityInput { } -export async function createActivityDetailsRedactor(db: Db) { +export async function createActivityDetailsRedactor(db: ActivityDb) { const currentUserRedactionOptions = { enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs, }; @@ -82,7 +85,7 @@ export async function createActivityDetailsRedactor(db: Db) { ); } -export async function redactActivityDetails(db: Db, details: Record | null) { +export async function redactActivityDetails(db: ActivityDb, details: Record | null) { if (!details) return null; return (await createActivityDetailsRedactor(db))(details); } @@ -91,7 +94,7 @@ function readNonEmptyString(value: unknown) { return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; } -export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActivityInput) { +export async function resolveResponsibleUserIdForActivity(db: ActivityDb, input: LogActivityInput) { if (input.responsibleUserIdOverride !== undefined) { return readNonEmptyString(input.responsibleUserIdOverride); } @@ -164,10 +167,10 @@ export function publishActivity(publication: ActivityPublication) { } finally { finish(); } } -export async function persistActivity(db: Db, input: LogActivityInput, receipt?: { id: string }) { +export async function persistActivity(db: ActivityDb, input: LogActivityInput, receipt?: { id: string }) { const redactedDetails = await redactActivityDetails(db, input.authorization ? { ...input.details, permissionDecision: input.authorization, ...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}) } : input.details ?? null); const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input); - const insert = (runner: Db) => runner.insert(activityLog).values({ + const insert = (runner: Pick) => runner.insert(activityLog).values({ ...(receipt ? { id: receipt.id } : {}), companyId: input.companyId, actorType: input.actorType, @@ -185,7 +188,7 @@ export async function persistActivity(db: Db, input: LogActivityInput, receipt?: await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`); if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status))) await notifyActiveRunSilence(tx, { companyId: input.companyId, runId: input.runId }); - return insert(tx as unknown as Db); + return insert(tx); }) : await insert(db); @@ -232,7 +235,7 @@ export async function persistActivity(db: Db, input: LogActivityInput, receipt?: } export async function logActivity( - db: Db, + db: ActivityDb, input: LogActivityInput, postCommitPublications?: ActivityPublication[], ) { diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 55fb04afc3f..c8e3356d4e5 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -1,3 +1,5 @@ +import { createPhotonExternalRuntimeOwner, stagePhotonExternalConfiguration } from "./chat-channels/imessage-photon/external-runtime.js"; +import { createPaperclipCloudConnector, paperclipCloudConnectorConfigFromEnv } from "./paperclip-cloud-connector.js"; import { retrySlackFormAcknowledgement } from "./chat-channels/slack/form-retry.js"; import { createSlackFormConnectorAccess, registerSlackFormWorkOwner, reconcilePendingSlackFormWork, stageSlackFormOwnerConfiguration } from "./chat-channels/slack/form-owner.js"; import { createSlackFormDeliveryOwner } from "./chat-channels/slack/form-delivery.js"; @@ -830,8 +832,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { allowedStatuses: EndpointRow["status"][], ) { const record = await endpointRecord(endpointId); + const externalPhoton = record?.endpoint.provider === "imessage-photon" && context.discordGatewayOwned !== true + && await photonExternalRuntimeOwner.placement(record); if ( - record && leasedChatProvider(record.endpoint.provider) && + record && leasedChatProvider(record.endpoint.provider) && !externalPhoton && !(await ensureDiscordGatewayRuntimeIsCurrent(endpointId, context)) ) { return null; @@ -843,7 +847,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { credentialFingerprint(record.credentialSecretRefs) === context.credentialFingerprint && runtime.get(endpointId) === context.endpointRuntime && - (!leasedChatProvider(record.endpoint.provider) || + (!leasedChatProvider(record.endpoint.provider) || externalPhoton || discordGatewayRuntimeIsCurrent(endpointId, context)) ? record : null; @@ -905,6 +909,22 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { const { admitDiscordRootMention, discordRootThreadPending, reconcileDiscordRootThread, promoteDiscordRootReceipt } = createDiscordRootThreads(db, { ensureDiscordGatewayRuntimeIsCurrent, withCredentialMutationLease, runtimeCallbackEndpoint, lockCurrentPrincipalAuthorization, processMessage, redactError, scheduleConversationDrain, lifecycleRuntimeFence, runtimeFor, DISCORD_ROOT_THREAD_CONFIRMATION_DELAY_MS, discordRootThreadTransportBarrier: () => options.discordRootThreadTransportBarrier?.() ?? Promise.resolve() }); const { handleDiscordGatewayEvent } = createDiscordGatewayEvents(db, { ensureDiscordGatewayRuntimeIsCurrent, discordGatewayRuntimeIsCurrent, runtimeCallbackRecord, runtimeCallbackEndpoint, applyProviderLifecycleEffect, runtimeGeneration, discordGatewayEventBarrier: (event) => options.discordGatewayEventBarrier?.(event) ?? Promise.resolve() }); const { handlePhotonFailure, handlePhotonEvent } = createPhotonEvents(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, invalidateRuntime, ensurePrincipal, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications, questionResponses, redactError, renewDiscordGatewayOwnershipForMessageAdmission, handleSdkMessage }); + const photonConnectorConfig = paperclipCloudConnectorConfigFromEnv(); + const photonConnector = photonConnectorConfig ? createPaperclipCloudConnector({ config: photonConnectorConfig }) : undefined; + const photonExternalRuntimeOwner = createPhotonExternalRuntimeOwner(db, { + broker: () => photonConnector, + endpointRecord, runtimeFor, context: instance => runtimeContexts.get(instance), + ownership: id => discordGatewayOwnerships.get(id), currentRuntime: id => runtime.get(id), + release: ownership => stopDiscordGatewayOwnership(ownership, { removeRuntime: false, notifyStopped: false }), + removeRuntime: async id => { runtimeVersions.delete(id); return runtime.removeEndpoint(id); }, + config: async record => { + const config = runtimeConfig(record.endpoint, record.endpoint.botUsername ?? record.assignedAgentName, await resolveCredentials(record.endpoint)); + if (config.provider !== "imessage-photon") throw new Error("Photon external provider changed"); + return config; + }, + admit: handlePhotonEvent, + notify: id => { receiverWork?.changed(id); }, + }); const { handleTelegramGenerationStopped, reserveTelegramPublicationDraft } = createTelegramPublicationDrafts(db, { runtimeCallbackRecord, runtimeCallbackEndpoint, runtimeFor, runtime, runtimeContexts, credentialFingerprint, authorizeRetainedChatSourcePublication }); const { recordSlackFileUploadReceipt, stageSlackFilePublicationSuccess, processPendingSlackFileUploadReceipts, nextSlackReceiptAt } = createSlackFileReceipts(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runtimeFor, isExplicitOperatorPublication, recordExactOutboundPublicationLink }); const { processPendingSlackSessionSyncs } = createSlackSessionStatus(db, { endpointRecord, withCredentialMutationLease, runtimeCallbackEndpoint, nonDirectDestinationAllowed, runIdFromMilestonePublication, resolveCredentials, fetchImpl, redactError, get slackSessionSyncSelectionBarrier() { return options.slackSessionSyncSelectionBarrier; } }); @@ -967,6 +987,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { } const context = runtimeContextForRecord(record); const current = runtime.get(endpoint.id); + const photonPlacement = record.endpoint.provider === "imessage-photon" ? await photonExternalRuntimeOwner.placement(record) : null; const currentDiscordOwnership = discordGatewayOwnerships.get(endpoint.id); const currentOwnsDiscordGateway = currentDiscordOwnership !== undefined && @@ -974,6 +995,15 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { currentDiscordOwnership.context.version === context.version && currentDiscordOwnership.context.endpointRuntime === current && currentDiscordOwnership.expiresAt.getTime() > Date.now(); + if (current && photonPlacement && runtimeVersions.get(endpoint.id) === context.version + && optionsForRuntime.requireDiscordOwnership === true && !currentOwnsDiscordGateway) { + const exactContext = runtimeContexts.get(current); + if (!exactContext) throw new Error("Photon current sender context is unavailable"); + const owned = await acquireDiscordGatewayOwnership(record.endpoint, exactContext, optionsForRuntime.waitForDiscordOwnership === true); + if (!owned) throw discordGatewayNotOwnedError(); + exactContext.discordGatewayOwned = true; + return current; + } if ( current && runtimeVersions.get(endpoint.id) === context.version && @@ -1033,7 +1063,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { }; const promise = (async () => { const discordOwnership = - leasedChatProvider(record.endpoint.provider) + leasedChatProvider(record.endpoint.provider) && (!photonPlacement || optionsForRuntime.requireDiscordOwnership === true) ? await acquireDiscordGatewayOwnership( record.endpoint, context, @@ -1075,8 +1105,17 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { callbacks: { onMessage: (event) => handleSdkMessage(event, context), ...createPhotonRuntimeCallbacks(db, { endpointId: endpoint.id, connectionId: endpoint.connectionId, companyId: record.endpoint.companyId, assignedAgentId: record.endpoint.assignedAgentId, context, lineId: credentials.lineId, runtimeCallbackRecord, runtimeCallbackEndpoint, renewDiscordGatewayOwnershipForMessageAdmission }), + onPhotonUsefulClientDebt: () => photonExternalRuntimeOwner.senderDebt(endpoint.id), + onPhotonIntakePlacement: async () => { + const latest = await endpointRecord(endpoint.id); + const external = latest && await photonExternalRuntimeOwner.placement(latest); + return external ? { kind: "cloud", bindingId: external.binding.bindingId } : { kind: "local" }; + }, onPhotonEvent: (event) => handlePhotonEvent(endpoint.id, event, context), - onPhotonFailure: (error) => handlePhotonFailure(endpoint.id, error, context), + onPhotonFailure: async error => { + const result = await handlePhotonFailure(endpoint.id, error, context); + return result?.kind === "recorded" ? result : photonExternalRuntimeOwner.cleanupFailure(endpoint.id, context); + }, onDiscordRootMentionAdmission: record.endpoint.provider === "discord" ? (event) => @@ -1187,7 +1226,9 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { } const receiverSchedule = chatReceiverSchedule(db, { + retained: scope => photonExternalRuntimeOwner.retained(scope), stop: async id => { + await photonExternalRuntimeOwner.retire(id); const ownership = discordGatewayOwnerships.get(id); // Discovery already observed removal; only independent ownership loss needs another wake. if (ownership) await stopDiscordGatewayOwnership(ownership, { notifyStopped: false }); @@ -1196,6 +1237,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { const record = await endpointRecord(id); if (!record) return "owned"; try { + if (record.endpoint.provider === "imessage-photon" && photonConnector) { + await photonExternalRuntimeOwner.reconcile(id); + if (await photonExternalRuntimeOwner.placement(record)) return "owned"; + } const instance = await runtimeFor(record.endpoint, { requireDiscordOwnership: true }); await reconcileDiscordRuntime(id, instance); return "owned"; @@ -3458,6 +3503,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { const { configure, configureWithCredentialLease, runtimeConfig } = createChatConfiguration(db, { stageConfigurationEffects: async (tx, endpointId, actorUserId) => { await stageSlackCloudEnrollmentIntent(tx, endpointId, actorUserId); + await stagePhotonExternalConfiguration(tx, endpointId, actorUserId); const identity = slackForms.identity(); if (identity) await stageSlackFormOwnerConfiguration(tx, endpointId, false, actorUserId ?? "", identity); }, @@ -3602,6 +3648,8 @@ return { test, retrySlackFormReceipt: async (endpointId: string, actionId: string, management?: ConnectionManagementContext) => { if (!management) throw forbidden("Connection management authority is required"); + const retryRecord = await endpointRecord(endpointId); + if (retryRecord?.endpoint.provider === "imessage-photon") return photonExternalRuntimeOwner.retry(endpointId, actionId, management); return retrySlackFormAcknowledgement(db, { companyId: management.resource.companyId, endpointId, actionId, identity: slackForms.identity, management }); }, @@ -3676,6 +3724,7 @@ return { voice.unregisterAgentTools(); unregisterGitHubCloudIngress(); unregisterSlackCloudIngress(); + await photonExternalRuntimeOwner.close(); unregisterSlackFormWork(); unregisterSlackCloudEnrollment(); unregisterCommittedResponseAuthority(); diff --git a/server/src/services/chat-channels/imessage-photon/events.ts b/server/src/services/chat-channels/imessage-photon/events.ts index 882a57e7a7a..d82ce81ccc3 100644 --- a/server/src/services/chat-channels/imessage-photon/events.ts +++ b/server/src/services/chat-channels/imessage-photon/events.ts @@ -97,13 +97,13 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) { error instanceof PhotonError ? error.message : "Photon connection interrupted; reconnecting"; - await db.transaction(async (tx) => { + const responsibility = await db.transaction(async (tx) => { const endpoint = await runtimeCallbackEndpoint(tx, endpointId, context, [ "verifying", "active", "attention", ]); - if (!endpoint) return; + if (!endpoint) return { kind: "obsolete" as const }; await notifyChatReceiver(tx, endpoint); await tx .update(chatEndpoints) @@ -123,9 +123,11 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) { healthMessage: message, }) .where(eq(toolConnections.id, endpoint.connectionId)); + return { kind: "recorded" as const }; }); // Retirement is queued outside the receiver callback to avoid self-joining. void invalidateRuntime(endpointId).catch(() => undefined); + return responsibility; } async function processPhotonResponse( @@ -759,11 +761,11 @@ export function createPhotonEvents(db: Db, options: PhotonEventsOptions) { // Late events from a removed chat must still advance recovery without a // now-forbidden chat lookup holding every other conversation behind them. if (removedGroup?.metadata.photonRemoved === true && !readded) return; - const chat = await adapter.client.chats + const chat = await adapter.withClient(client => client.chats .get(event.chatGuid) .catch((error) => { throw photonFailure(error); - }); + })); if (chat.guid !== event.chatGuid || chat.service !== "iMessage" || (chat.isGroup && adapter.authentication.identity.allocation === "shared")) return; const threadId = photonThreadId({ lineId: adapter.authentication.identity.lineId, diff --git a/server/src/services/chat-channels/imessage-photon/external-contract.ts b/server/src/services/chat-channels/imessage-photon/external-contract.ts new file mode 100644 index 00000000000..a9f8e9989d8 --- /dev/null +++ b/server/src/services/chat-channels/imessage-photon/external-contract.ts @@ -0,0 +1,77 @@ +import type { LiveEvent } from "@photon-ai/advanced-imessage"; +import { isDeepStrictEqual } from "node:util"; +import { createHash } from "node:crypto"; +import { z } from "zod"; +import { decodePhotonRecoveryFrame } from "../../photon/recovery-transport.js"; + +const id = z.string().min(1).max(200); +const sequence = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER); +export const photonExternalBindingSchema = z.object({ + version: z.literal(1), instanceId: id, environment: z.enum(["development", "test", "staging", "production"]), + companyId: id, endpointId: id, connectionId: id, runtimeGeneration: sequence.positive(), + projectId: z.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/), lineId: id, phoneNumber: id, + allocation: z.enum(["dedicated", "shared"]), credentialFingerprint: z.string().regex(/^[a-f0-9]{64}$/), + bindingId: z.string().regex(/^photon-receiver:[a-f0-9]{64}$/), intakeAfter: z.string().datetime(), + maxFrameBytes: sequence.positive(), +}).strict(); +export type PhotonExternalBinding = z.infer; +export const photonHash = (value: string | readonly (string | number | boolean | null)[]) => createHash("sha256").update(JSON.stringify(value)).digest("hex"); +export const photonExternalIdentitySchema = z.object({ + companyId: id, endpointId: id, connectionId: id, runtimeGeneration: sequence.positive(), + credentialReferences: z.string().regex(/^[a-f0-9]{64}$/), subject: id, +}).strict(); +export type PhotonExternalIdentity = z.infer; +const identityKeys = ["companyId", "endpointId", "connectionId", "runtimeGeneration"] as const; +export function assertPhotonExternalBinding(identity: PhotonExternalIdentity, binding: PhotonExternalBinding): void { + if (identityKeys.some(key => identity[key] !== binding[key]) || binding.bindingId !== `photon-receiver:${photonHash([ + binding.instanceId, binding.companyId, binding.endpointId, binding.connectionId, binding.runtimeGeneration, binding.credentialFingerprint, + ])}`) throw new Error("Photon external owner identity changed"); +} +export const photonExternalStateSchema = z.object({ + version: z.literal(1), identity: photonExternalIdentitySchema, + handoffId: z.string().uuid(), localResourceId: z.string().uuid().nullable(), + phase: z.enum(["enrolling", "joining", "external", "retiring", "retired"]), + // The complete non-secret enrollment input survives an ambiguous broker reply. + binding: photonExternalBindingSchema, + acceptedRetirement: z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid() }).strict().nullable(), + initialSequence: sequence.nullable(), + joinedSequence: sequence.nullable(), acceptedSequence: sequence.nullable(), + pending: z.object({ deliveryId: id, sequence, previousSequence: sequence.nullable(), frameDigest: z.string().regex(/^[a-f0-9]{64}$/) }).strict().nullable(), + failure: z.object({ code: z.enum(["enrollment", "local_join", "dispatch", "authority", "retirement", "sender_close"]), attempts: sequence.positive(), nextAttemptAt: z.string().datetime().nullable() }).strict().nullable(), +}).strict(); +export type PhotonExternalState = z.infer; +export function readPhotonExternalState(value: unknown): PhotonExternalState | null { + if (value === null) return null; + const state = photonExternalStateSchema.parse(value); + assertPhotonExternalBinding(state.identity, state.binding); + if (state.phase === "external" && state.joinedSequence === null && state.initialSequence !== null + || state.pending && state.pending.sequence <= (state.acceptedSequence ?? -1)) throw new Error("Photon external custody invariant changed"); + return state; +} +export type PhotonExternalDeliveryPacket = { + version: 1; binding: PhotonExternalBinding; sequence: number; previousSequence: number | null; + acceptedAt: string; rawFrame: string; +}; +export type ParsedPhotonExternalDelivery = { + packet: PhotonExternalDeliveryPacket; + event: LiveEvent; + receipt: { deliveryId: string; sequence: number; previousSequence: number | null; frameDigest: string }; +}; +export function parsePhotonExternalDelivery(input: { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: unknown }, state: PhotonExternalState): ParsedPhotonExternalDelivery { + const packet = z.object({ version: z.literal(1), binding: photonExternalBindingSchema, sequence, + previousSequence: sequence.nullable(), acceptedAt: z.string().datetime(), rawFrame: z.string().min(4), + }).strict().parse(input.payload); + if (!isDeepStrictEqual(packet.binding, state.binding) || packet.acceptedAt !== input.createdAt + || input.installationId !== state.binding.bindingId || input.bindingIds.length !== 1 || input.bindingIds[0] !== state.binding.bindingId + || input.id !== `photon_${photonHash([state.binding.bindingId, packet.sequence])}` + || packet.previousSequence !== null && packet.previousSequence >= packet.sequence) + throw new Error("Photon external delivery binding changed"); + if (packet.rawFrame.length > Math.ceil(state.binding.maxFrameBytes / 3) * 4) throw new Error("Photon external encoded frame exceeds its bound"); + const bytes = Buffer.from(packet.rawFrame, "base64"); + if (bytes.toString("base64") !== packet.rawFrame || bytes.byteLength > state.binding.maxFrameBytes) throw new Error("Photon external frame bounds changed"); + const event = decodePhotonRecoveryFrame(bytes); + if (!event || event.type === "catchup.complete" || event.type === "photon.ignored" || event.sequence !== packet.sequence || event.type !== input.event) + throw new Error("Photon external recovery event changed"); + return { packet, event, receipt: { deliveryId: input.id, sequence: packet.sequence, + previousSequence: packet.previousSequence, frameDigest: photonHash(packet.rawFrame) } }; +} diff --git a/server/src/services/chat-channels/imessage-photon/external-owner.ts b/server/src/services/chat-channels/imessage-photon/external-owner.ts new file mode 100644 index 00000000000..cf3bacf0fd7 --- /dev/null +++ b/server/src/services/chat-channels/imessage-photon/external-owner.ts @@ -0,0 +1,177 @@ +import { isDeepStrictEqual } from "node:util"; +import { randomUUID } from "node:crypto"; +import { z } from "zod"; +import type { LiveEvent } from "@photon-ai/advanced-imessage"; +import { PhotonState } from "../../photon/state.js"; +import { writePhotonCheckpoint } from "../../photon/receiver.js"; +import type { ResolvedPhotonChatConfig } from "../../chat-sdk-runtime.js"; +import { MAX_ATTACHMENT_BYTES } from "../../../attachment-types.js"; +import { PHOTON_EXTERNAL_STATE, type PhotonExternalStore, type PhotonExternalLease } from "./external-store.js"; +import { assertPhotonExternalBinding, photonExternalBindingSchema, photonHash, readPhotonExternalState, + parsePhotonExternalDelivery, type PhotonExternalBinding, type PhotonExternalIdentity, type PhotonExternalState } from "./external-contract.js"; + +const CHECKPOINT_AUTHORITY = "checkpoint-authority"; +const checkpointIdentity = ({ subject: _subject, ...identity }: PhotonExternalIdentity) => identity; +type Checkpoint = { schema: 1; lineId: string; sequence: number }; +export type PhotonCheckpointAuthority = Omit & { sequence: number }; +/** Called INSIDE the ordinary checkpoint SQL transaction before writing it. + * Untagged initialized legacy history remains local-only attention for handoff; + * neither a newer generation nor one successful request proves its provenance. */ +export async function checkpointAuthorityMayAdvance(state: PhotonState, identity: PhotonExternalIdentity): Promise { + const checkpoint = await state.read("checkpoint"); + const authority = await state.read(CHECKPOINT_AUTHORITY); + if (!checkpoint) return !(await state.read("receiver-initialized")) && authority === null; + return authority !== null && isDeepStrictEqual(authority, { ...checkpointIdentity(identity), sequence: checkpoint.sequence }); +} +export async function recordPhotonCheckpointAuthority(state: PhotonState, identity: PhotonExternalIdentity, sequence: number): Promise { + await state.update(CHECKPOINT_AUTHORITY, () => ({ ...checkpointIdentity(identity), sequence })); +} +export async function handoffCheckpoint(state: PhotonState, identity: PhotonExternalIdentity, lineId: string): Promise { + const checkpoint = await state.read("checkpoint"); + if (!checkpoint) { + if (await state.read("receiver-initialized")) throw new Error("Photon initialized history has no checkpoint"); + return null; + } + if (checkpoint.schema !== 1 || checkpoint.lineId !== lineId || !Number.isSafeInteger(checkpoint.sequence) || checkpoint.sequence < 0 + || !await checkpointAuthorityMayAdvance(state, identity)) throw new Error("Photon legacy checkpoint provenance requires operator recovery"); + return checkpoint.sequence; +} +export interface PhotonExternalBroker { + instanceIdentity(): { instanceId: string; environment: PhotonExternalBinding["environment"] }; + photonReceiverOperation(input: { subject: string; companyId: string; operation: Record }): Promise; +} +/** Resource IDs identify a retained object; ONLY awaiting its real close confirms + * closure. An unknown object after restart is attention, never a lease-expiry proof. */ +export class PhotonLocalResources { + private readonly resources = new Map; closing?: Promise; closed: boolean }>(); + private readonly objects = new WeakMap(); + capture(object: object, close: () => Promise): string { + const existing = this.objects.get(object); if (existing) return existing; + const id = randomUUID(); this.objects.set(object, id); this.resources.set(id, { close, closed: false }); return id; + } + async join(id: string): Promise { + const resource = this.resources.get(id); + if (!resource) throw new Error("Photon original local resource closure is unknown"); + if (resource.closed) return; + resource.closing ??= resource.close().then(() => { resource.closed = true; }); + try { await resource.closing; } catch (error) { resource.closing = undefined; throw error; } + } + known(id: string): boolean { return this.resources.has(id); } + owns(id: string, object: object): boolean { return this.objects.get(object) === id && this.resources.has(id); } +} +export function createPhotonExternalOwner(options: { store: PhotonExternalStore; broker: PhotonExternalBroker; + resources: PhotonLocalResources; notify(identity: PhotonExternalIdentity): void; now?: () => Date }) { + const now = options.now ?? (() => new Date()); + async function failure(expected: PhotonExternalState, code: NonNullable["code"]) { + const attempts = (expected.failure?.attempts ?? 0) + 1; + // Existing receiver coordinator consumes this deadline/notification; no timer. + const nextAttemptAt = new Date(now().getTime() + Math.min(300_000, 30_000 * 2 ** Math.min(attempts - 1, 4))).toISOString(); + await options.store.retained(expected, value => ({ ...value, failure: { code, attempts, nextAttemptAt } })); + options.notify(expected.identity); + } + async function fail(expected: PhotonExternalState, code: NonNullable["code"], primary: unknown): Promise { + try { await failure(expected, code); } + catch (cleanup) { throw new AggregateError([primary, cleanup], "Photon operation and responsibility persistence failed"); } + throw primary; + } + async function reconcile(input: { identity: PhotonExternalIdentity; lease: PhotonExternalLease; config: ResolvedPhotonChatConfig; + localResourceId: string | null }): Promise { + const { identity, lease, config } = input; + const instance = options.broker.instanceIdentity(); + const fingerprint = photonHash([instance.instanceId, instance.environment, identity.companyId, identity.endpointId, identity.connectionId, + identity.runtimeGeneration, config.credentials.projectId, config.credentials.lineId, config.credentials.phoneNumber, + (config.credentials.allocation ?? "dedicated"), photonHash(config.credentials.projectSecret)]); + const binding = photonExternalBindingSchema.parse({ version: 1, ...instance, companyId: identity.companyId, endpointId: identity.endpointId, + connectionId: identity.connectionId, runtimeGeneration: identity.runtimeGeneration, projectId: config.credentials.projectId, + lineId: config.credentials.lineId, phoneNumber: config.credentials.phoneNumber, allocation: config.credentials.allocation ?? "dedicated", + credentialFingerprint: fingerprint, bindingId: `photon-receiver:${photonHash([instance.instanceId, identity.companyId, identity.endpointId, identity.connectionId, identity.runtimeGeneration, fingerprint])}`, + intakeAfter: new Date(config.intakeAfter).toISOString(), maxFrameBytes: MAX_ATTACHMENT_BYTES + 1024 * 1024 }); + let retained = await options.store.current(identity, lease, async (state, current) => { + if (current && current.phase !== "retired") { + if (!isDeepStrictEqual(current.binding, binding)) throw new Error("Photon original enrollment must finish retirement"); + return current; + } + const initialSequence = await handoffCheckpoint(state, identity, binding.lineId); + return state.update(PHOTON_EXTERNAL_STATE, raw => { + if (!isDeepStrictEqual(readPhotonExternalState(raw), current)) throw new Error("Photon external intent was installed concurrently"); + return { version: 1, identity, binding, handoffId: randomUUID(), localResourceId: input.localResourceId, + phase: "enrolling", acceptedRetirement: current ? { binding: current.binding, handoffId: current.handoffId } : null, initialSequence, joinedSequence: null, acceptedSequence: null, pending: null, failure: null }; + }); + }); + if (retained.phase === "external") return retained; + if (!["enrolling", "joining"].includes(retained.phase)) throw new Error("Photon receiver requires retirement reconciliation"); + if (retained.phase === "enrolling") { + try { + const reply = await options.broker.photonReceiverOperation({ subject: identity.subject, companyId: identity.companyId, + operation: { kind: "enroll", enrollment: { companyId: identity.companyId, endpointId: identity.endpointId, connectionId: identity.connectionId, + runtimeGeneration: identity.runtimeGeneration, projectId: binding.projectId, lineId: binding.lineId, phoneNumber: binding.phoneNumber, + allocation: binding.allocation, intakeAfter: binding.intakeAfter, maxFrameBytes: binding.maxFrameBytes, + ...(retained.acceptedRetirement ? { acceptedRetirement: retained.acceptedRetirement } : {}), + projectSecret: config.credentials.projectSecret, handoffId: retained.handoffId, initialized: retained.initialSequence !== null, sequence: retained.initialSequence } } }); + const response = z.object({ binding: photonExternalBindingSchema }).strict().parse(reply).binding; + assertPhotonExternalBinding(identity, response); + if (!isDeepStrictEqual(response, retained.binding)) throw new Error("Photon broker enrollment tuple changed"); + // Known external custody commits even if configure won after the request. + retained = await options.store.retained(retained, value => ({ ...value, phase: "joining", failure: null })); + } catch (error) { return fail(retained, "enrollment", error); } + } + try { + if (retained.localResourceId !== null) await options.resources.join(retained.localResourceId); + const expected = retained; + retained = await options.store.current(identity, lease, async (state, current) => { + if (!current || !isDeepStrictEqual(current, expected)) throw new Error("Photon handoff changed while joining"); + const joinedSequence = await handoffCheckpoint(state, identity, binding.lineId); + if (expected.initialSequence !== null && (joinedSequence === null || joinedSequence < expected.initialSequence)) throw new Error("Photon joined checkpoint regressed"); + return state.update(PHOTON_EXTERNAL_STATE, () => ({ ...expected, phase: "external", joinedSequence, acceptedSequence: joinedSequence, failure: null })); + }); + options.notify(identity); + return retained; + } catch (error) { return fail(retained, "local_join", error); } + } + async function dispatch(input: { identity: PhotonExternalIdentity; lease: PhotonExternalLease; + delivery: { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: unknown }; admit(event: LiveEvent): Promise }): Promise { + const retained = await options.store.read(input.identity); + if (!retained || retained.phase !== "external") throw new Error("Photon local join or retirement remains outstanding"); + const decoded = parsePhotonExternalDelivery(input.delivery, retained); + const pending = await options.store.current(input.identity, input.lease, async (state, current) => { + if (!current || current.phase !== "external" || !isDeepStrictEqual(current.binding, retained.binding)) throw new Error("Photon delivery owner changed"); + // The joined checkpoint already admitted the complete local prefix. + if (decoded.packet.sequence <= (current.joinedSequence ?? -1)) return false; + if (decoded.packet.sequence <= (current.acceptedSequence ?? -1)) return false; + if (current.pending && !isDeepStrictEqual(current.pending, decoded.receipt)) throw new Error("Photon earlier delivery admission remains outstanding"); + const previous = decoded.packet.previousSequence; + if (previous !== (current.acceptedSequence ?? null) + && !(current.acceptedSequence === current.joinedSequence && (previous ?? -1) <= (current.joinedSequence ?? -1))) + throw new Error("Photon durable predecessor has not been admitted"); + await state.update(PHOTON_EXTERNAL_STATE, () => ({ ...current, pending: decoded.receipt })); + return true; + }); + if (!pending) return; + // Actual normal Photon callback owns company authorization and idempotent + // task/interaction admission. It may perform provider I/O, never inside SQL. + await input.admit(decoded.event); + await options.store.current(input.identity, input.lease, async (state, current) => { + if (!current || current.phase !== "external" || !isDeepStrictEqual(current.pending, decoded.receipt)) throw new Error("Photon admission commit lost its current lease"); + await writePhotonCheckpoint(state, current.binding.lineId, decoded.packet.sequence); + await recordPhotonCheckpointAuthority(state, input.identity, decoded.packet.sequence); + await state.update(PHOTON_EXTERNAL_STATE, () => ({ ...current, pending: null, acceptedSequence: decoded.packet.sequence, failure: null })); + }); + // Caller can now use ONLY the ordinary authenticated delivery ACK. + } + async function retire(retained: PhotonExternalState): Promise { + if (retained.phase === "retired") return; + if (retained.phase !== "retiring") retained = await options.store.retained(retained, value => ({ ...value, phase: "retiring" })); + try { + if (retained.localResourceId !== null) await options.resources.join(retained.localResourceId); + const request = { subject: retained.identity.subject, companyId: retained.identity.companyId }; + await options.broker.photonReceiverOperation({ ...request, operation: { kind: "retire", binding: retained.binding } }); + const response = z.object({ binding: photonExternalBindingSchema, handoffId: z.string().uuid(), + phase: z.enum(["staged", "active", "retiring", "retired"]) }).strict().parse(await options.broker.photonReceiverOperation({ ...request, operation: { kind: "status", binding: retained.binding } })); + if (!isDeepStrictEqual(response.binding, retained.binding) || response.handoffId !== retained.handoffId) throw new Error("Photon retirement tuple changed"); + if (response.phase !== "retired") throw new Error("Photon original physical close or queue drain remains outstanding"); + await options.store.retained(retained, value => ({ ...value, phase: "retired", failure: null })); + options.notify(retained.identity); + } catch (error) { return fail(retained, "retirement", error); } + } + return { reconcile, dispatch, retire }; +} diff --git a/server/src/services/chat-channels/imessage-photon/external-runtime.ts b/server/src/services/chat-channels/imessage-photon/external-runtime.ts new file mode 100644 index 00000000000..33160c67ae3 --- /dev/null +++ b/server/src/services/chat-channels/imessage-photon/external-runtime.ts @@ -0,0 +1,255 @@ +import { isDeepStrictEqual } from "node:util"; +import type { ConnectionManagementContext } from "../../connection-management.js"; +import { logActivity } from "../../activity-log.js"; +import { forbidden, conflict, notFound } from "../../../errors.js"; +import { notifyChatReceiver } from "../runtime/receiver-work-notifications.js"; +import { PhotonChatAdapter } from "../../photon/adapter.js"; +import { and, eq, sql, gt, lte, desc } from "drizzle-orm"; +import { chatEndpoints, chatSdkState, type Db } from "@paperclipai/db"; +import type { LiveEvent } from "@photon-ai/advanced-imessage"; +import type { ChatEndpointRuntime } from "../../voice/voice-runtime.js"; +import type { ResolvedPhotonChatConfig } from "../../chat-sdk-runtime.js"; +import type { EndpointRecord, RuntimeContext, DiscordGatewayOwnership, InternalSetupState } from "../runtime-types.js"; +import { credentialFingerprint } from "../credential-fingerprint.js"; +import { createPhotonExternalStore, PHOTON_EXTERNAL_STATE } from "./external-store.js"; +import { createPhotonExternalOwner, PhotonLocalResources, type PhotonExternalBroker } from "./external-owner.js"; +import { readPhotonExternalState, parsePhotonExternalDelivery, type PhotonExternalIdentity } from "./external-contract.js"; +import { createHash } from "node:crypto"; + +export type PhotonCloudDelivery = { id: string; event: string; createdAt: string; installationId: string | null; bindingIds: readonly string[]; payload: Record }; +type Ingress = (event: PhotonCloudDelivery) => Promise; +const ingress = new WeakMap(); +export async function dispatchPhotonCloudEvent(db: Db, event: PhotonCloudDelivery) { + const owner = ingress.get(db); if (!owner) throw new Error("Photon normal authorized ingress is not ready"); + await owner(event); +} +const stateKey = `photon:${createHash("sha256").update(PHOTON_EXTERNAL_STATE).digest("hex")}`; +type PhotonReceiverScope = { kind: "endpoint" | "connection" | "company"; id: string }; +/** Same keyset reconstruction pattern as the normal receiver owner. The upper + * bound is captured once, so concurrent inserts cannot extend this scan forever; + * their ordinary durable endpoint notifications remain independently pending. + * Cost is 1 + ceil(snapshot rows / 100) reads, NOT a fixed SQL-lifetime bound. */ +async function* photonExternalRows(db: Db, scope?: PhotonReceiverScope) { + const filter = and(eq(chatSdkState.stateKey, stateKey), scope?.kind === "endpoint" ? eq(chatSdkState.endpointId, scope.id) : undefined, + scope?.kind === "company" ? eq(chatSdkState.companyId, scope.id) : undefined); + const [last] = await db.select({ id: chatSdkState.id }).from(chatSdkState).where(filter).orderBy(desc(chatSdkState.id)).limit(1); + if (!last) return; + let after: string | undefined; + while (true) { + const rows = await db.select({ id: chatSdkState.id, companyId: chatSdkState.companyId, endpointId: chatSdkState.endpointId, + connectionId: chatEndpoints.connectionId, value: chatSdkState.value }).from(chatSdkState).innerJoin(chatEndpoints, + and(eq(chatEndpoints.companyId, chatSdkState.companyId), eq(chatEndpoints.id, chatSdkState.endpointId))) + .where(and(filter, lte(chatSdkState.id, last.id), after ? gt(chatSdkState.id, after) : undefined)).orderBy(chatSdkState.id).limit(100); + for (const row of rows) if (scope?.kind !== "connection" || row.connectionId === scope.id) yield row; + if (rows.length < 100 || rows[rows.length - 1].id === last.id) return; + after = rows[rows.length - 1].id; + } +} +export async function readPhotonRetainedConsumer(db: Db, identity: { instanceId: string; environment: string }) { + // Settled history never hides an unfinished tail behind a LIMIT-before-filter. + const attention: string[] = []; + let owner: { subject: string; companyId: string } | null = null; + for await (const row of photonExternalRows(db)) { + try { + const retained = readPhotonExternalState(row.value); + if (!retained || retained.identity.companyId !== row.companyId || retained.identity.endpointId !== row.endpointId + || retained.binding.instanceId !== identity.instanceId || retained.binding.environment !== identity.environment) throw new Error("Photon retained identity changed"); + if (retained.phase !== "retired" && !owner) owner = { subject: retained.identity.subject, companyId: row.companyId }; + } catch { if (attention.length < 100) attention.push("photon_retained_identity_invalid"); } + } + return { owner, attention }; +} +export function createPhotonExternalRuntimeOwner(db: Db, options: { + broker(): PhotonExternalBroker | undefined; + endpointRecord(id: string): Promise; + runtimeFor(endpoint: EndpointRecord["endpoint"], input: { requireDiscordOwnership?: boolean }): Promise; + context(runtime: ChatEndpointRuntime): RuntimeContext | undefined; + ownership(id: string): DiscordGatewayOwnership | undefined; + release(ownership: DiscordGatewayOwnership): Promise; + currentRuntime(id: string): ChatEndpointRuntime | null; + removeRuntime(id: string): Promise; + config(record: EndpointRecord): Promise; + admit(id: string, event: LiveEvent, context: RuntimeContext): Promise; + notify(id: string): void; +}) { + const store = createPhotonExternalStore(db), resources = new PhotonLocalResources(); + const active = new Map>(); + async function selected(record: EndpointRecord) { + const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject; + if (!subject) return null; + const identity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: record.endpoint.id, + connectionId: record.endpoint.connectionId, runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), + credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject }; + const retained = await store.inspect(identity), connector = options.broker()?.instanceIdentity(); + if (!retained || retained.phase !== "external" || !isDeepStrictEqual(retained.identity, identity) + || !connector || retained.binding.instanceId !== connector.instanceId || retained.binding.environment !== connector.environment) return null; + return retained; + } + async function placement(record: EndpointRecord) { + if (record.endpoint.provider !== "imessage-photon") return null; + return selected(record); + } + async function reconcile(id: string): Promise { + const pending = active.get(id); if (pending) return pending; + const run = (async () => { + const record = await options.endpointRecord(id), broker = options.broker(); + if (!record || record.endpoint.provider !== "imessage-photon" || !(record.endpoint.setup as InternalSetupState).photonExternalSubject || !broker) return; + const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject; + if (!subject) return; + const identity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId, + runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject }; + const previous = await store.read(identity); + if (previous && previous.phase !== "retired" && (previous.phase === "retiring" + || !isDeepStrictEqual(previous.identity, identity) || !["active", "verifying", "attention"].includes(record.endpoint.status))) { + await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(previous); + return; + } + const external = await placement(record); + if (external) { + const adapter = options.currentRuntime(id)?.getProviderAdapter(); + if (adapter instanceof PhotonChatAdapter) await adapter.drainUsefulClient(); + else if (external.failure?.code === "sender_close" && !await options.removeRuntime(id)) throw new Error("Photon original sender physical closure is unknown"); + if (external.failure?.code === "sender_close") await store.retained(external, value => ({ ...value, failure: null })); + return; + } + const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true }); + const context = options.context(runtime), lease = options.ownership(id); + if (!context || !lease || lease.context !== context || context.endpointRuntime !== runtime || lease.stopping) throw new Error("Photon normal local resource lease changed"); + const currentIdentity: PhotonExternalIdentity = { companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId, + runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject }; + const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }); + // Keep the real runtime in the normal registry through shutdown. Its failure + // persistence callbacks still see the exact current object/lease; removing + // it first would turn cleanup debt into an obsolete-context no-op. + const resourceId = resources.capture(runtime, async () => { await runtime.shutdown(); }); + await owner.reconcile({ identity: currentIdentity, lease, config: await options.config(record), localResourceId: resourceId }); + await options.removeRuntime(id); + await options.release(lease); + context.discordGatewayOwned = false; + // The SDK client was physically closed. Normal runtimeFor builds a NEW + // useful sender, with placement verified from committed external state. + // No eager sender/client is created merely to be idle. The next genuine + // ordinary publication or Cloud admission calls normal runtimeFor. + })(); + active.set(id, run); + try { await run; } finally { if (active.get(id) === run) active.delete(id); } + } + const receive: Ingress = async event => { + const packet = event.payload.photonEvent; + if (!packet || typeof packet !== "object" || Array.isArray(packet)) throw new Error("Photon sealed packet is missing"); + const raw = Reflect.get(packet, "binding"); + if (!raw || typeof raw !== "object" || typeof Reflect.get(raw, "endpointId") !== "string") throw new Error("Photon sealed binding is invalid"); + const record = await options.endpointRecord(Reflect.get(raw, "endpointId")); + if (!record) throw new Error("Photon retained endpoint requires retirement attention"); + const retained = await placement(record), broker = options.broker(); + if (!retained) { + const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject; + if (!subject) throw new Error("Photon original subject is unavailable"); + const previous = await store.read({ companyId: record.endpoint.companyId, endpointId: record.endpoint.id, connectionId: record.endpoint.connectionId, + runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject }); + if (!previous || previous.phase !== "retiring" || !broker) throw new Error("Photon exact retired delivery owner is unavailable"); + const decoded = parsePhotonExternalDelivery({ ...event, payload: packet }, previous); + await store.noEffect(previous, decoded.packet.sequence); + options.notify(record.endpoint.id); + return; + } + if (!broker) throw new Error("Photon exact external owner is not currently dispatchable"); + const runtime = await options.runtimeFor(record.endpoint, { requireDiscordOwnership: true }); + const context = options.context(runtime), lease = options.ownership(record.endpoint.id); + if (!context || !lease || lease.context !== context || lease.stopping) throw new Error("Photon short admission lease is unavailable"); + try { + const owner = createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }); + await owner.dispatch({ identity: retained.identity, lease, delivery: { ...event, payload: packet }, + admit: value => options.admit(record.endpoint.id, value, context) }); + } finally { + // Keep the useful sender; retire ONLY the short receiver admission lease. + await options.release(lease); context.discordGatewayOwned = false; + } + }; + async function senderDebt(id: string) { + const record = await options.endpointRecord(id); + if (!record) throw new Error("Photon sender debt has no retained endpoint"); + const external = await placement(record); + if (!external) throw new Error("Photon sender debt has no exact retained owner"); + await store.retained(external, value => ({ ...value, failure: { code: "sender_close", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } })); + options.notify(id); + } + async function retire(id: string) { + const record = await options.endpointRecord(id), broker = options.broker(); + if (!record || !broker) return; + const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject; + if (!subject) return; + const retained = await store.read({ companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId, + runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject }); + if (retained && retained.phase !== "retired") await createPhotonExternalOwner({ store, broker, resources, notify: value => options.notify(value.endpointId) }).retire(retained); + } + async function retained(scope?: { kind: "endpoint" | "connection" | "company"; id: string }) { + const values = []; + for await (const row of photonExternalRows(db, scope)) { + let state; + try { + state = readPhotonExternalState(row.value); + if (!state || state.identity.companyId !== row.companyId || state.identity.endpointId !== row.endpointId) throw new Error("Photon retained receiver identity changed"); + } catch { + // Keep malformed debt on its own existing endpoint owner. The coordinator + // records/retries that failure while still visiting unrelated endpoints. + if (scope?.kind !== "connection" || row.connectionId === scope.id) values.push({ id: row.endpointId, companyId: row.companyId, connectionId: row.connectionId, dueAt: 0 }); + continue; + } + if (state.phase === "retired" || scope?.kind === "connection" && state.identity.connectionId !== scope.id) continue; + values.push({ id: row.endpointId, companyId: row.companyId, connectionId: state.identity.connectionId, + dueAt: state.phase === "external" && !state.failure ? null : state.failure?.nextAttemptAt ? Date.parse(state.failure.nextAttemptAt) : 0 }); + } + return values; + } + async function cleanupFailure(id: string, context: RuntimeContext): Promise<{ kind: "recorded" } | { kind: "obsolete" }> { + const record = await options.endpointRecord(id); + const subject = record && (record.endpoint.setup as InternalSetupState).photonExternalSubject; + if (!record || !subject || !context.endpointRuntime) return { kind: "obsolete" }; + const state = await store.read({ companyId: record.endpoint.companyId, endpointId: id, connectionId: record.endpoint.connectionId, + runtimeGeneration: context.generation, credentialReferences: context.credentialFingerprint, subject }); + if (!state?.localResourceId || !resources.owns(state.localResourceId, context.endpointRuntime) + || !["joining", "retiring"].includes(state.phase)) return { kind: "obsolete" }; + await store.retained(state, value => ({ ...value, failure: { code: "local_join", attempts: (value.failure?.attempts ?? 0) + 1, nextAttemptAt: new Date().toISOString() } })); + options.notify(id); + return { kind: "recorded" }; + } + async function retry(endpointId: string, actionId: string, management: ConnectionManagementContext) { + await management.reauthorize(); + const record = await options.endpointRecord(endpointId), broker = options.broker(); + if (!record || record.endpoint.provider !== "imessage-photon") throw notFound("Photon endpoint not found"); + const subject = (record.endpoint.setup as InternalSetupState).photonExternalSubject; + if (!subject || !broker || !management.responsibleUserId || !management.decision.allowed || management.decision.action !== "connections:configure" + || management.resource.companyId !== record.endpoint.companyId || management.resource.connectionId && management.resource.connectionId !== record.endpoint.connectionId) + throw forbidden("Current company connection authority is required"); + const state = await store.read({ companyId: record.endpoint.companyId, endpointId, connectionId: record.endpoint.connectionId, + runtimeGeneration: Number((record.endpoint.setup as InternalSetupState).runtimeGeneration ?? 0), credentialReferences: credentialFingerprint(record.credentialSecretRefs), subject }); + const connector = broker.instanceIdentity(); + if (!state || state.handoffId !== actionId || state.binding.instanceId !== connector.instanceId || state.binding.environment !== connector.environment) + throw conflict("Photon retained retry identity changed"); + if (state.phase === "retired") return { actionId, state: "complete" as const }; + if (state.localResourceId !== null && !resources.known(state.localResourceId) && ["joining", "retiring"].includes(state.phase)) + throw conflict("Photon original stream closure is unknown; restore its owning process or establish real resource closure before retry"); + if (state.phase === "external") await broker.photonReceiverOperation({ subject: management.responsibleUserId, companyId: state.identity.companyId, + operation: { kind: "retry", binding: state.binding } }); + await management.reauthorize(); + await store.retained(state, value => ({ ...value, failure: value.failure ? { ...value.failure, nextAttemptAt: new Date().toISOString() } : null }), async tx => { + await management.reauthorize(); + await logActivity(tx, { ...management.audit, companyId: state.identity.companyId, action: "chat.photon_external_owner.retry", + entityType: "chat_endpoint", entityId: endpointId, details: { handoffId: actionId, phase: state.phase } }); + await notifyChatReceiver(tx, { id: endpointId, provider: "imessage-photon" }); + }); + options.notify(endpointId); + return { actionId, state: "scheduled" as const }; + } + ingress.set(db, receive); + return { reconcile, placement, senderDebt, retire, retained, cleanupFailure, retry, close() { if (ingress.get(db) === receive) ingress.delete(db); return Promise.all([...active.values()]).then(() => undefined); } }; +} + +/** Called by normal configuration SQL with its actual authorized actor. Existing + * retained SDK state is deliberately untouched until its original owner retires. */ +export async function stagePhotonExternalConfiguration(db: Pick, endpointId: string, subject: string | null | undefined) { + if (!subject) return; + await db.update(chatEndpoints).set({ setup: sql`jsonb_set(${chatEndpoints.setup}, '{photonExternalSubject}', ${JSON.stringify(subject)}::jsonb)` }) + .where(and(eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "imessage-photon"))); +} diff --git a/server/src/services/chat-channels/imessage-photon/external-store.ts b/server/src/services/chat-channels/imessage-photon/external-store.ts new file mode 100644 index 00000000000..325e59d0b51 --- /dev/null +++ b/server/src/services/chat-channels/imessage-photon/external-store.ts @@ -0,0 +1,92 @@ +import { isDeepStrictEqual } from "node:util"; +import { and, eq, gt } from "drizzle-orm"; +import { chatEndpoints, chatEndpointLeases, toolConnections, type Db } from "@paperclipai/db"; +import type { InternalSetupState } from "../runtime-types.js"; +import { credentialFingerprint } from "../credential-fingerprint.js"; +import { PhotonState } from "../../photon/state.js"; +import { createChatSdkStatePersistence } from "../sdk-state.js"; +import { readPhotonExternalState, type PhotonExternalIdentity, type PhotonExternalState } from "./external-contract.js"; + +export const PHOTON_EXTERNAL_STATE = "external-owner"; +type Transaction = Parameters[0]>[0]; +export type PhotonExternalLease = { token: string }; +export function photonStateFor(db: Pick, identity: Pick) { + return new PhotonState(identity, createChatSdkStatePersistence(db)); +} +/** All callbacks are SQL-only. Provider I/O and resource joining happen outside. */ +export function createPhotonExternalStore(db: Db) { + async function lock(tx: Transaction, identity: PhotonExternalIdentity) { + const [endpoint] = await tx.select().from(chatEndpoints).where(and(eq(chatEndpoints.companyId, identity.companyId), eq(chatEndpoints.id, identity.endpointId))).for("no key update"); + if (!endpoint || endpoint.provider !== "imessage-photon") throw new Error("Photon external endpoint is unavailable"); + return endpoint; + } + return { + async read(identity: PhotonExternalIdentity) { + return readPhotonExternalState(await photonStateFor(db, identity).read(PHOTON_EXTERNAL_STATE)); + }, + async inspect(identity: PhotonExternalIdentity) { + return db.transaction(async tx => { + const endpoint = await lock(tx, identity); + const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.companyId, identity.companyId), eq(toolConnections.id, identity.connectionId))).for("share"); + if (!["active", "verifying", "attention"].includes(endpoint.status) || endpoint.connectionId !== identity.connectionId + || (endpoint.setup as InternalSetupState).runtimeGeneration !== identity.runtimeGeneration || !connection?.enabled + || connection.status !== "active" || connection.healthStatus === "failed" || credentialFingerprint(connection.credentialSecretRefs) !== identity.credentialReferences) return null; + return readPhotonExternalState(await photonStateFor(tx, identity).read(PHOTON_EXTERNAL_STATE)); + }); + }, + async current(identity: PhotonExternalIdentity, lease: PhotonExternalLease, work: (state: PhotonState, current: PhotonExternalState | null) => Promise): Promise { + return db.transaction(async tx => { + const endpoint = await lock(tx, identity); + const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.companyId, identity.companyId), eq(toolConnections.id, identity.connectionId))).for("share"); + const [owner] = await tx.select().from(chatEndpointLeases).where(and(eq(chatEndpointLeases.companyId, identity.companyId), + eq(chatEndpointLeases.endpointId, identity.endpointId), eq(chatEndpointLeases.leaseKey, "photon_receiver_runtime"), + eq(chatEndpointLeases.token, lease.token), gt(chatEndpointLeases.expiresAt, new Date()))).for("update"); + if (!owner || !["active", "verifying", "attention"].includes(endpoint.status) || endpoint.connectionId !== identity.connectionId + || (endpoint.setup as InternalSetupState).runtimeGeneration !== identity.runtimeGeneration || !connection?.enabled || connection.status !== "active" || connection.healthStatus === "failed" + || credentialFingerprint(connection.credentialSecretRefs) !== identity.credentialReferences) + throw new Error("Photon external current authority changed"); + const state = photonStateFor(tx, identity), current = readPhotonExternalState(await state.read(PHOTON_EXTERNAL_STATE)); + if (current && current.phase !== "retired" && !isDeepStrictEqual(current.identity, identity)) throw new Error("Photon prior owner must finish retirement"); + return work(state, current); + }); + }, + async noEffect(expected: PhotonExternalState, sequence: number) { + return db.transaction(async tx => { + const endpoint = await lock(tx, expected.identity); + const [connection] = await tx.select().from(toolConnections).where(and(eq(toolConnections.companyId, expected.identity.companyId), eq(toolConnections.id, endpoint.connectionId))).for("share"); + const superseded = !["active", "verifying", "attention"].includes(endpoint.status) + || endpoint.connectionId !== expected.identity.connectionId || (endpoint.setup as InternalSetupState).runtimeGeneration !== expected.identity.runtimeGeneration + || !connection?.enabled || connection.status !== "active" || connection.healthStatus === "failed" || credentialFingerprint(connection.credentialSecretRefs) !== expected.identity.credentialReferences; + if (!superseded || expected.phase !== "retiring") throw new Error("Photon no-effect requires actual current revocation"); + const updated = await photonStateFor(tx, expected.identity).update(PHOTON_EXTERNAL_STATE, raw => { + const current = readPhotonExternalState(raw); + if (!current || !isDeepStrictEqual(current.binding, expected.binding) || current.phase !== "retiring") throw new Error("Photon no-effect owner changed"); + return { ...current, acceptedSequence: Math.max(current.acceptedSequence ?? -1, sequence), pending: null }; + }); + return updated; + }); + }, + /** Preserve an already accepted broker/resource result even if configure won. + * This cannot activate or grant use: it only replaces the exact retained intent. */ + async retained(expected: PhotonExternalState, update: (state: PhotonExternalState) => PhotonExternalState, after?: (tx: Transaction) => Promise) { + return db.transaction(async tx => { + await lock(tx, expected.identity); + const updated = await photonStateFor(tx, expected.identity).update(PHOTON_EXTERNAL_STATE, raw => { + const current = readPhotonExternalState(raw); + if (!current || !isDeepStrictEqual(current, expected)) throw new Error("Photon retained intent changed concurrently"); + const next = update(current); + if (!isDeepStrictEqual(next.identity, current.identity) || !isDeepStrictEqual(next.binding, current.binding) + || next.handoffId !== current.handoffId || next.localResourceId !== current.localResourceId + || next.initialSequence !== current.initialSequence || next.phase === "external" && current.phase !== "external") + throw new Error("Photon retained update cannot change authority"); + const parsed = readPhotonExternalState(next); + if (!parsed) throw new Error("Photon retained result disappeared"); + return parsed; + }); + await after?.(tx); + return updated; + }); + }, + }; +} +export type PhotonExternalStore = ReturnType; diff --git a/server/src/services/chat-channels/imessage-photon/runtime-callbacks.ts b/server/src/services/chat-channels/imessage-photon/runtime-callbacks.ts index 414e070a844..8a83a98ed94 100644 --- a/server/src/services/chat-channels/imessage-photon/runtime-callbacks.ts +++ b/server/src/services/chat-channels/imessage-photon/runtime-callbacks.ts @@ -1,3 +1,4 @@ +import { checkpointAuthorityMayAdvance, recordPhotonCheckpointAuthority } from "./external-owner.js"; import { createChatSdkStatePersistence } from "../sdk-state.js"; import { notifyChatEndpointWork } from "../../chat-work-notifications.js"; import { writePhotonCheckpoint } from "../../photon/receiver.js"; @@ -39,7 +40,12 @@ export function createPhotonRuntimeCallbacks(db: Db, options: PhotonRuntimeOptio onPhotonCheckpoint: (sequence) => db.transaction(async (tx) => { if (!(await runtimeCallbackEndpoint(tx, endpointId, context, ["verifying", "active"]))) throw new Error("Photon receiver is no longer current"); if ((await renewDiscordGatewayOwnershipForMessageAdmission(tx, endpointId, context)).kind !== "owned") throw new Error("Photon receiver lease was replaced"); - await writePhotonCheckpoint(new PhotonState({ companyId: companyId, endpointId: endpointId }, createChatSdkStatePersistence(tx as unknown as Db)), lineId, sequence); + const state = new PhotonState({ companyId, endpointId }, createChatSdkStatePersistence(tx)); + const identity = { companyId, endpointId, connectionId, runtimeGeneration: context.generation, + credentialReferences: context.credentialFingerprint, subject: "checkpoint-only" }; + const provenance = await checkpointAuthorityMayAdvance(state, identity); + await writePhotonCheckpoint(state, lineId, sequence); + if (provenance) await recordPhotonCheckpointAuthority(state, identity, sequence); }) }; } diff --git a/server/src/services/chat-channels/runtime-types.ts b/server/src/services/chat-channels/runtime-types.ts index bae9a9221f4..42f1426b561 100644 --- a/server/src/services/chat-channels/runtime-types.ts +++ b/server/src/services/chat-channels/runtime-types.ts @@ -45,6 +45,7 @@ export type SlackCallbackObservation = { url: string; observedAt: string }; export type InternalSetupState = ChatEndpointSetupState & { photonIntakeAfter?: string; + photonExternalSubject?: string; runtimeGeneration?: number; /** Binds pre-install URL verification to the signing secret later configured. */ slackVerificationSigningFingerprint?: string; diff --git a/server/src/services/chat-channels/runtime/receiver-schedule.ts b/server/src/services/chat-channels/runtime/receiver-schedule.ts index 4e07ec7fb95..a4a5b76a7cd 100644 --- a/server/src/services/chat-channels/runtime/receiver-schedule.ts +++ b/server/src/services/chat-channels/runtime/receiver-schedule.ts @@ -9,6 +9,7 @@ export type ReceiverDeadline = { id: string; companyId: string; connectionId: st export function chatReceiverSchedule(db: Db, receiver: { reconcile: (id: string) => Promise<"owned" | "foreign">; stop: (id: string) => Promise; + retained?: (scope?: ReceiverScope) => Promise; }) { async function load(scope?: ReceiverScope, signal?: AbortSignal): Promise { const result: ReceiverDeadline[] = []; @@ -28,7 +29,12 @@ export function chatReceiverSchedule(db: Db, receiver: { cursor ? gt(chatEndpoints.id, cursor) : undefined, )).orderBy(chatEndpoints.id).limit(100); result.push(...rows.map(row => ({ ...row, dueAt: 0 }))); - if (rows.length < 100) return result; + if (rows.length < 100) { + const retained = await receiver.retained?.(scope) ?? []; + const merged = new Map(result.map(row => [row.id, row])); + for (const row of retained) merged.set(row.id, row); + return [...merged.values()]; + } cursor = rows[rows.length - 1].id; } } diff --git a/server/src/services/chat-channels/sdk-state.ts b/server/src/services/chat-channels/sdk-state.ts index 5fb2f86db91..4da473f029d 100644 --- a/server/src/services/chat-channels/sdk-state.ts +++ b/server/src/services/chat-channels/sdk-state.ts @@ -16,7 +16,7 @@ import type { ChatSdkStateScope, } from "../chat-sdk-state.js"; -export function createChatSdkStatePersistence(db: Db): ChatSdkStatePersistence { +export function createChatSdkStatePersistence(db: Pick): ChatSdkStatePersistence { return { async read(scope: ChatSdkStateScope, key: string) { return db diff --git a/server/src/services/chat-sdk-runtime.ts b/server/src/services/chat-sdk-runtime.ts index 602b77fff2d..6c69018e3e2 100644 --- a/server/src/services/chat-sdk-runtime.ts +++ b/server/src/services/chat-sdk-runtime.ts @@ -2,7 +2,7 @@ import { isPassiveSlackAction, normalizeSlackSelectionAction, slackSelectionValu import { PhotonChatAdapter, parsePhotonThreadId } from "./photon/adapter.js"; import { PhotonLineAuthentication } from "./photon/cloud.js"; import { PhotonState } from "./photon/state.js"; -import { PhotonReceiver } from "./photon/receiver.js"; +import { PhotonReceiver, type PhotonFailureResponsibility } from "./photon/receiver.js"; import { photonAttachmentLocator, photonAttachmentLocatorSchema, downloadPhotonAttachment, type PhotonAttachmentLocator } from "./photon/attachments.js"; import type { LiveEvent as PhotonEvent } from "@photon-ai/advanced-imessage"; import { @@ -469,10 +469,14 @@ export interface DiscordGatewayCallbackEvent extends ChatSdkCallbackEvent; + onPhotonIntakePlacement?(): Promise<{ kind: "local" } | { kind: "cloud"; bindingId: string }>; + onPhotonEvent?(event: PhotonEvent): Promise; onPhotonAssertOwned?(activeThreadId?: string): Promise; onPhotonCheckpoint?(sequence: number): Promise; - onPhotonFailure?(error: unknown): Promise; + onPhotonFailure?(error: unknown): Promise; onMessage(event: ChatSdkMessageCallbackEvent): Promise | void; onTelegramGenerationStopped?( event: ChatSdkCallbackEvent, @@ -2295,17 +2299,24 @@ export class ChatSdkEndpointRuntime { async initialize(): Promise { await this.initializeChat(); this.assertNotRetired(); - if (this.adapter instanceof PhotonChatAdapter && this.discordGatewayEnabled && !this.photonReceiver) { + if (this.adapter instanceof PhotonChatAdapter && !this.photonReceiver) { const options = this.runtimeOptions; const config = options.providerConfig as ResolvedPhotonChatConfig; if (!options.callbacks.onPhotonCheckpoint || !options.callbacks.onPhotonAssertOwned || !options.callbacks.onPhotonEvent || !options.callbacks.onPhotonFailure) throw new Error("Photon receiver requires durable admission callbacks"); this.adapter.typingGuard = async (activeThreadId) => { this.assertNotRetired(); await options.callbacks.onPhotonAssertOwned!(activeThreadId); }; + const placement = await options.callbacks.onPhotonIntakePlacement?.() ?? { kind: "local" }; + if (placement.kind === "cloud") { + this.adapter.onUsefulClientDebt = options.callbacks.onPhotonUsefulClientDebt; + await this.adapter.useExternalIntake(); + } + if (placement.kind === "local" && this.discordGatewayEnabled) { this.photonReceiver = new PhotonReceiver({ client: this.adapter.client, state: this.adapter.state, lineId: config.credentials.lineId, intakeAfter: config.intakeAfter, allocation: config.credentials.allocation, catchUp: (sequence) => (this.adapter as PhotonChatAdapter).recoveryStream(sequence), assertOwned: async () => { this.assertNotRetired(); await (this.adapter as PhotonChatAdapter).authentication.token(); await options.callbacks.onPhotonAssertOwned!(); }, commitCheckpoint: options.callbacks.onPhotonCheckpoint, admit: options.callbacks.onPhotonEvent, failure: options.callbacks.onPhotonFailure }); this.photonReceiver.start(); + } } if (this.provider === "discord" && this.discordGatewayEnabled) { this.startDiscordGateway(); diff --git a/server/src/services/github-connection-events.ts b/server/src/services/github-connection-events.ts index e095c52c1a0..00f180e4612 100644 --- a/server/src/services/github-connection-events.ts +++ b/server/src/services/github-connection-events.ts @@ -1,3 +1,4 @@ +import { dispatchPhotonCloudEvent, readPhotonRetainedConsumer } from "./chat-channels/imessage-photon/external-runtime.js"; import { parseSlackFormOperation } from "./chat-channels/slack/cloud-forms.js"; import { acknowledgeSlackFormDeliveries } from "./chat-channels/slack/form-normal-ack.js"; import { readSlackFormRetainedConsumer } from "./chat-channels/slack/cloud-consumer.js"; @@ -559,6 +560,14 @@ export function githubConnectionEventService( } } } + if (!identity && connector.instanceIdentity) { + try { + const retained = await readPhotonRetainedConsumer(db, connector.instanceIdentity()); + identity = retained.owner; + hasConsumer ||= retained.owner !== null; + if (retained.attention.length) logger.warn({ reason: "photon_retained_owner_invalid", count: retained.attention.length }, "Photon custody requires attention"); + } catch { logger.warn({ reason: "photon_retained_owner_unavailable" }, "Photon custody requires attention"); } + } if (!identity) { const [history] = await db.select({ grant: connectionGrants, connection: toolConnections }).from(connectionGrants) .innerJoin(toolConnections, and(eq(toolConnections.id, connectionGrants.connectionId), eq(toolConnections.companyId, connectionGrants.companyId))) @@ -596,6 +605,11 @@ export function githubConnectionEventService( const acknowledge: string[] = []; const formCompanies = new Map(); for (const event of lease.events) { + if (event.provider === "imessage-photon") { + try { await dispatchPhotonCloudEvent(db, event); acknowledge.push(event.id); result.processed += 1; } + catch { result.failed += 1; } + continue; + } if (event.provider === "slack") { try { await dispatchSlackCloudEvent(db, event); diff --git a/server/src/services/instance-settings.ts b/server/src/services/instance-settings.ts index 1719878f28a..cd314d369b6 100644 --- a/server/src/services/instance-settings.ts +++ b/server/src/services/instance-settings.ts @@ -469,7 +469,7 @@ export function stripCloudCatalogDefaultEchoes( return result as Partial; } -export function instanceSettingsService(db: Db, options: InstanceSettingsServiceOptions = {}) { +export function instanceSettingsService(db: Pick, options: InstanceSettingsServiceOptions = {}) { // Fail closed: a malformed PAPERCLIP_MANAGED_CONFIG throws here (and at // boot in index.ts) rather than silently running without the overlay. const managedConfig = getManagedInstanceConfig(options.runtimeEnv ?? process.env); diff --git a/server/src/services/paperclip-cloud-connector.ts b/server/src/services/paperclip-cloud-connector.ts index b1f9f087133..7085718c7b7 100644 --- a/server/src/services/paperclip-cloud-connector.ts +++ b/server/src/services/paperclip-cloud-connector.ts @@ -36,9 +36,9 @@ export const GMAIL_CONNECTOR_SCOPES = [ export { GOOGLE_WORKSPACE_CONNECTOR_PROFILES }; export type PaperclipCloudConnectorEnvironment = "development" | "test" | "staging" | "production"; -export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "mcp-client-mirror" | "mcp-revocation-index"; +export type PaperclipCloudConnectorOperation = "status" | "session" | "claim" | "refresh" | "revoke" | "webhook-bind" | "event-lease" | "event-ack" | "github-app" | "slack-events" | "slack-forms" | "photon-receiver" | "mcp-client-mirror" | "mcp-revocation-index"; export type PaperclipCloudConnectorProfileId = GoogleWorkspaceConnectorProfileId | GitHubConnectorProfileId | AsanaConnectorProfileId | "slack.manager" | "github.bot"; -export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack"; +export type PaperclipCloudConnectorProvider = "google" | "github" | "asana" | "slack" | "imessage-photon"; export type PaperclipCloudConnectorConfig = { baseUrl: string; @@ -76,7 +76,7 @@ export type SealedConnectorEvents = { leaseId: string; events: Array<{ id: string; - provider: "github" | "slack"; + provider: "github" | "slack" | "imessage-photon"; event: string; action: string | null; installationId: string | null; @@ -87,7 +87,7 @@ export type SealedConnectorEvents = { }>; }; -type SealedEnvelopeProfileId = PaperclipCloudConnectorProfileId | "slack.events.v1" | "slack.form-open.v1" | "slack.callbacks.v1"; +type SealedEnvelopeProfileId = PaperclipCloudConnectorProfileId | "slack.events.v1" | "slack.form-open.v1" | "slack.callbacks.v1" | "photon.events.v1"; type SealedEnvelope = { v: 1; @@ -121,12 +121,14 @@ type ConnectorResponse = { githubApps?: { version: number }; slackEvents?: { version: number }; slackForm?: unknown; + photonReceiver?: unknown; enrollment?: unknown; retirement?: unknown; eventWakeVersion?: unknown; }; const ENDPOINTS: Record = { + "photon-receiver": "/v1/connector/photon-receiver", "mcp-client-mirror": "/v1/connector/mcp-client-mirror", "mcp-revocation-index": "/v1/connector/mcp-revocation-index", "slack-events": "/v1/connector/slack-events", @@ -417,6 +419,11 @@ export function createPaperclipCloudConnector(input: { const response = await call("status", { subject: "instance-capabilities", companyId: "instance-capabilities" }); return response.active === true && response.slackEvents?.version === 1; }, + async photonReceiverOperation(values: { subject: string; companyId: string; operation: Record }): Promise { + const response = await call("photon-receiver", values, { field: "operation", value: JSON.stringify(values.operation) }); + if (!isRecord(response.photonReceiver)) throw badEnvelope(); + return response.photonReceiver; + }, async slackFormOperation(values: { subject: string; companyId: string; operation: Record }) { const response = await call("slack-forms", values, { field: "operation", value: JSON.stringify(values.operation) }); if (!isRecord(response.slackForm)) throw badEnvelope(); @@ -664,6 +671,16 @@ export function createPaperclipCloudConnector(input: { event.payload = { slackEvent: delivery }; } } + if (event.provider === "imessage-photon") { + const packet = event.payload.photonEvent; + if (!isRecord(packet) || typeof packet.bindingId !== "string" || packet.sealed === undefined) throw badEnvelope(); + const sealed = parseEnvelope(packet.sealed, "events", "imessage-photon", "photon.events.v1"); + const delivery = decryptEnvelope(sealed, sealKey, config.instanceId, config.environment, "imessage-photon", "photon.events.v1", []); + if (!isRecord(delivery) || delivery.version !== 1 || !isRecord(delivery.binding) + || delivery.binding.instanceId !== config.instanceId || delivery.binding.environment !== config.environment + || delivery.binding.bindingId !== packet.bindingId || delivery.acceptedAt !== event.createdAt) throw badEnvelope(); + event.payload = { photonEvent: delivery }; + } events.push(event); } catch { failedEventIds.push(event.id); @@ -716,8 +733,9 @@ function parseCloudHandoff(value: unknown): { kind: "paperclip_cloud"; session: return { kind: "paperclip_cloud", session }; } -export type PaperclipCloudConnector = Omit, "instanceIdentity" | "slackFormOperation"> & { +export type PaperclipCloudConnector = Omit, "instanceIdentity" | "slackFormOperation" | "photonReceiverOperation"> & { instanceIdentity?: () => Readonly<{ instanceId: string; environment: PaperclipCloudConnectorEnvironment }>; + photonReceiverOperation?: ReturnType["photonReceiverOperation"]; slackFormOperation?: ReturnType["slackFormOperation"]; }; export type PaperclipCloudGoogleWorkspaceConnector = PaperclipCloudConnector; @@ -867,7 +885,7 @@ function unsealEvents( if (parsed.v !== 1 || parsed.instanceId !== instanceId || parsed.environment !== environment || typeof parsed.leaseId !== "string" || !Array.isArray(parsed.events)) throw badEnvelope(); for (const event of parsed.events) { - if (!isRecord(event) || typeof event.id !== "string" || !["github", "slack"].includes(event.provider) + if (!isRecord(event) || typeof event.id !== "string" || !["github", "slack", "imessage-photon"].includes(event.provider) || typeof event.event !== "string" || !isRecord(event.payload) || !Array.isArray(event.bindingIds) || !event.bindingIds.every((id) => typeof id === "string")) throw badEnvelope(); } diff --git a/server/src/services/photon/adapter.ts b/server/src/services/photon/adapter.ts index 9285ea1b6e2..fd7354ffc27 100644 --- a/server/src/services/photon/adapter.ts +++ b/server/src/services/photon/adapter.ts @@ -1,7 +1,8 @@ +import { createOwnedPhotonClient } from "./owned-client.js"; +import { PhotonUsefulClient } from "./useful-client.js"; import { PhotonRecoveryTransport } from "./recovery-transport.js"; import { createHash } from "node:crypto"; import { - createGrpcClient, type GrpcAdvancedIMessage, type Message as PhotonMessage, type Chat as PhotonChat, @@ -101,7 +102,28 @@ export class PhotonChatAdapter implements Adapter { readonly name = "imessage-photon"; readonly lockScope = "channel" as const; readonly botUserId: string; - readonly client: GrpcAdvancedIMessage; + private localClient?: GrpcAdvancedIMessage; + private usefulClient?: PhotonUsefulClient; + onUsefulClientDebt?: () => Promise; + async drainUsefulClient(): Promise { await this.usefulClient?.drain(); } + private makeClient(): GrpcAdvancedIMessage { + return createOwnedPhotonClient({ address: this.authentication.address, token: () => this.authentication.token(), tls: true, + retry: false, autoIdempotency: false, timeout: 25_000, + channelOptions: { "grpc.max_receive_message_length": MAX_ATTACHMENT_BYTES + 1024 * 1024 } }); + } + get client(): GrpcAdvancedIMessage { + if (this.usefulClient) throw new Error("External Photon unary calls require their useful-operation owner"); + if (!this.localClient) throw new Error("Photon local client is closed"); + return this.localClient; + } + async useExternalIntake(): Promise { + this.usefulClient ??= new PhotonUsefulClient(() => this.makeClient(), this.localClient, async () => { if (!this.onUsefulClientDebt) throw new Error("Photon physical debt owner is unavailable"); await this.onUsefulClientDebt(); }); + this.localClient = undefined; + await this.usefulClient.drain(); + } + withClient(action: (client: GrpcAdvancedIMessage) => Promise): Promise { + return this.usefulClient ? this.usefulClient.run(action) : action(this.client); + } private closed = false; private recovery?: PhotonRecoveryTransport; private readonly typing = new Map>(); @@ -117,19 +139,7 @@ export class PhotonChatAdapter implements Adapter { client?: GrpcAdvancedIMessage, ) { this.botUserId = authentication.identity.phoneNumber; - this.client = - client ?? - createGrpcClient({ - address: authentication.address, - token: () => authentication.token(), - tls: true, - retry: false, - autoIdempotency: false, - timeout: 25_000, - channelOptions: { - "grpc.max_receive_message_length": MAX_ATTACHMENT_BYTES + 1024 * 1024, - }, - }); + this.localClient = client ?? this.makeClient(); } async initialize(_chat: ChatInstance): Promise { await this.authentication.token(); @@ -139,8 +149,13 @@ export class PhotonChatAdapter implements Adapter { for (const timer of this.typing.values()) clearTimeout(timer); this.typing.clear(); this.authentication.retire(); - this.recovery?.close(); - await this.client.close(); + const localClient = this.localClient; + const closed = await Promise.allSettled([ + ...(this.recovery ? [this.recovery.close()] : []), + ...(this.usefulClient ? [this.usefulClient.close()] : localClient ? [localClient.close().then(() => { if (this.localClient === localClient) this.localClient = undefined; })] : []), + ]); + const errors = closed.flatMap(result => result.status === "rejected" ? [result.reason] : []); + if (errors.length) throw new AggregateError(errors, "Photon receiver and useful sender shutdown remain incomplete"); } encodeThreadId(value: PhotonThread): string { if (value.isGroup && this.authentication.identity.allocation === "shared") @@ -167,11 +182,11 @@ export class PhotonChatAdapter implements Adapter { async chatInfo(id: string): Promise { if (this.closed) throw new Error("Photon runtime retired"); const identity = this.decodeThreadId(id); - const chat = await this.client.chats + const chat = await this.withClient(client => client.chats .get(identity.chatGuid) .catch((error) => { throw photonFailure(error); - }); + })); if ( chat.guid !== identity.chatGuid || chat.isGroup !== identity.isGroup || @@ -254,12 +269,12 @@ export class PhotonChatAdapter implements Adapter { attachmentGuid: locator.attachmentGuid, }, fetchData: () => - downloadPhotonAttachment( - this.client, + this.withClient(client => downloadPhotonAttachment( + client, this.authentication.identity.lineId, locator, this.authentication.identity.allocation, - ), + )), }; }); const text = raw.content.text ?? ""; @@ -301,22 +316,22 @@ export class PhotonChatAdapter implements Adapter { async fetchMessage(id: string, messageId: string) { const chat = await this.chatInfo(id); return this.normalize( - await this.client.messages.get(messageId).catch((error) => { + await this.withClient(client => client.messages.get(messageId).catch((error) => { throw photonFailure(error); - }), + })), chat, ); } async fetchMessages(id: string, options?: FetchOptions) { const chat = await this.chatInfo(id); - const page = await this.client.messages + const page = await this.withClient(client => client.messages .listInChat(chat.guid, { pageSize: Math.min(options?.limit ?? 50, 100), pageToken: options?.cursor, }) .catch((error) => { throw photonFailure(error); - }); + })); return { messages: page.messages .map((message) => this.normalize(message, chat)) @@ -348,11 +363,11 @@ export class PhotonChatAdapter implements Adapter { if (this.closed) return; if (this.typing.has(id)) clearTimeout(this.typing.get(id)); await this.typingGuard?.(refresh ? id : undefined); - await this.client.chats + await this.withClient(client => client.chats .setTyping(this.decodeThreadId(id).chatGuid, true) .catch((error) => { throw photonFailure(error); - }); + })); if (this.closed) return; // Refresh while work is running; final/prompt publication or runtime // retirement clears this timer. Every refresh checks endpoint ownership. @@ -367,9 +382,9 @@ export class PhotonChatAdapter implements Adapter { if (this.typing.has(id)) clearTimeout(this.typing.get(id)); this.typing.delete(id); if (!this.closed) - await this.client.chats + await this.withClient(client => client.chats .setTyping(this.decodeThreadId(id).chatGuid, false) - .catch(() => {}); + .catch(() => {})); } async postMessage( _id: string, @@ -506,10 +521,10 @@ export class PhotonChatAdapter implements Adapter { await options.assertCurrent(); await save({ phase: "uploading" }); try { - const uploaded = await this.client.attachments.upload({ + const uploaded = await this.withClient(client => client.attachments.upload({ fileName: file.filename, data: file.data as Buffer, - }); + })); if (!uploaded.attachment.guid) throw new PhotonError( "delivery_unknown", @@ -527,8 +542,9 @@ export class PhotonChatAdapter implements Adapter { } } await options.assertCurrent(); - if (payload.replaceMessageId) { - const original = await this.client.messages.get(payload.replaceMessageId); + const replaceMessageId = payload.replaceMessageId; + if (replaceMessageId) { + const original = await this.withClient(client => client.messages.get(replaceMessageId)); if ( !original.isFromMe || !original.chatGuids.includes(payload.chatGuid) || @@ -543,25 +559,26 @@ export class PhotonChatAdapter implements Adapter { const clientMessageId = createHash("sha256") .update(`${this.state.scope.endpointId}:${publicationId}:${part}`) .digest("hex"); + const attachmentGuid = record.attachmentGuid; try { - const result = record.attachmentGuid - ? await this.client.messages.sendAttachment( + const result = attachmentGuid + ? await this.withClient(client => client.messages.sendAttachment( payload.chatGuid, - record.attachmentGuid, + attachmentGuid, { clientMessageId, replyTo: payload.replyTo }, - ) - : payload.replaceMessageId - ? await this.client.messages.edit( + )) + : replaceMessageId + ? await this.withClient(client => client.messages.edit( payload.chatGuid, - payload.replaceMessageId, + replaceMessageId, payload.text!, { clientMessageId }, - ) - : await this.client.messages.sendText( + )) + : await this.withClient(client => client.messages.sendText( payload.chatGuid, payload.text!, { clientMessageId, replyTo: payload.replyTo }, - ); + )); if (!result.guid || !result.chatGuids.includes(payload.chatGuid)) throw new Error("Photon returned an invalid send receipt"); await save({ phase: "sent", messageGuid: result.guid }); diff --git a/server/src/services/photon/interactions.ts b/server/src/services/photon/interactions.ts index e190df5f7fb..4cc9d371ad7 100644 --- a/server/src/services/photon/interactions.ts +++ b/server/src/services/photon/interactions.ts @@ -291,7 +291,7 @@ export async function publishPhotonPrompt(input: { throw new PhotonAnswerValidationError("Photon poll already claimed"); return { schema: 1, phase: "creating" }; }); - const poll = await adapter.client.polls + const poll = await adapter.withClient(client => client.polls .create( adapter.decodeThreadId(input.threadId).chatGuid, title, @@ -310,7 +310,7 @@ export async function publishPhotonPrompt(input: { phase: "prepared", })); throw failure; - }); + })); if ( !poll.pollMessageGuid || poll.options.length !== choices.length || diff --git a/server/src/services/photon/owned-client.ts b/server/src/services/photon/owned-client.ts new file mode 100644 index 00000000000..a75494ab978 --- /dev/null +++ b/server/src/services/photon/owned-client.ts @@ -0,0 +1,65 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { createGrpcClient, type GrpcClientOptions, type GrpcAdvancedIMessage } from "@photon-ai/advanced-imessage"; +import { PhotonTransportResources } from "./transport-resources.js"; +const require = createRequire(import.meta.url); +const deliveredGrpc = { + "build/src/http_proxy.js": "56e1e38a2e933025212512edfebde611c80471e6b27b0570b29f1275fab46c85", + "build/src/transport.js": "9b142290b2bcdf9eb4e75e70adbe6301689ff31e8f2e8bc957d22a6590e4be8c", + "build/src/channel-options.js": "3d83c36164c8b0499ba39da0864b5a3e12a77c6f455ad7cfed55e942dbf8d4f0", + "build/src/channel-credentials.js": "553fff7957c883c85925fe8fec9d912e02ddc29d073419747ed1737a00b66bc0" +}; +const inspectedSdk = { + "dist/chunk-5WYZRCOS.js": "f26e3ed5d8a076f0bb214fe05680c317d7c1123fb29f7dc727e3dd1ac54a0c69", + "dist/chunk-EUYUM3KD.js": "1538679fbe4c509e80571c5096c7af9c5343975f6e171d9af89e4476eb951f2e", + "dist/client-UZMHAKPA.js": "dd078953c237ed11abb42856739f547ba952acb8a8a42e77aefb3f9d130f6c15" +}; +function installedRoot(name: string, version: string): string { + let path = dirname(require.resolve(name)); + for (let parents = 0; parents < 6; parents++, path = dirname(path)) { + let pkg: unknown; + try { pkg = JSON.parse(readFileSync(join(path, "package.json"), "utf8")); } catch { continue; } + if (pkg && typeof pkg === "object" && Reflect.get(pkg, "name") === name) { + if (Reflect.get(pkg, "version") !== version) throw new Error("Photon transport dependency version changed"); + return path; + } + } + throw new Error("Photon transport dependency ownership is unavailable"); +} +export function assertInstalledPhotonTransportJoin(): void { + for (const [root, files] of [[installedRoot("@grpc/grpc-js", "1.14.5"), deliveredGrpc], + [installedRoot("@photon-ai/advanced-imessage", "2.2.0"), inspectedSdk]] as const) { + for (const [path, expected] of Object.entries(files)) { + if (createHash("sha256").update(readFileSync(join(root, path))).digest("hex") !== expected) + throw new Error("Photon transport close-and-join delivery is incomplete"); + } + } +} +export function createOwnedPhotonClient(options: GrpcClientOptions): GrpcAdvancedIMessage { + // Check exact installed delivery BEFORE allocating either SDK channel. This + // prevents an unpatched dependency from silently turning no observations into + // a successful close receipt. + assertInstalledPhotonTransportJoin(); + const resources = new PhotonTransportResources(); + const client = createGrpcClient({ ...options, channelOptions: { ...options.channelOptions, + "grpc.use_local_subchannel_pool": 1, "grpc-node.transport_owner": resources } }); + const closeSdk = client.close.bind(client); + let closing: Promise | undefined, joined = false; + client.close = () => { + if (joined) return Promise.resolve(); + if (closing) return closing; + resources.beginClose(); + const attempt = (async () => { + const errors: unknown[] = []; + try { await closeSdk(); } catch (error) { errors.push(error); } + try { await resources.close(); } catch (error) { errors.push(error); } + if (errors.length) throw new AggregateError(errors, "Photon SDK and physical transport close remain incomplete"); + })(); + closing = attempt; + void attempt.then(() => { joined = true; }, () => { if (closing === attempt) closing = undefined; }); + return attempt; + }; + return client; +} diff --git a/server/src/services/photon/receiver.ts b/server/src/services/photon/receiver.ts index c7629b95b02..3e2dafabae0 100644 --- a/server/src/services/photon/receiver.ts +++ b/server/src/services/photon/receiver.ts @@ -7,6 +7,8 @@ import type { import { PhotonError } from "./cloud.js"; import { PhotonState } from "./state.js"; +export type PhotonFailureResponsibility = { kind: "recorded" } | { kind: "obsolete" }; + interface Checkpoint { schema: 1; lineId: string; @@ -22,7 +24,7 @@ export interface PhotonReceiverOptions { /** Renewal verifies both the selected identity and the current endpoint lease. */ assertOwned(): Promise; admit(event: LiveEvent): Promise; - failure(error: unknown): Promise; + failure(error: unknown): Promise; /** Production persists the cursor under the same transaction as its lease fence. */ commitCheckpoint?(sequence: number): Promise; } @@ -33,6 +35,11 @@ export class PhotonReceiver { private stopped = false; private streams: Array> = []; private running?: Promise; + private closing?: Promise; + private readonly consumers: Promise[] = []; + private readonly reads = new Set>(); + private readonly closeFailures = new Map(); + private readonly failureDebt = new Map(); private requested = false; private catchUpStream?: TypedEventStream; private timer?: ReturnType; @@ -47,20 +54,22 @@ export class PhotonReceiver { client.polls.subscribeEvents(), ]; for (const stream of this.streams) { - void (async () => { + const consumer = (async () => { try { for await (const _event of stream) { if (this.stopped) break; this.request(); } if (!this.stopped) - await this.options.failure( + await this.report( new PhotonError("network", "Photon event stream disconnected"), ); } catch (error) { - if (!this.stopped) await this.options.failure(error); + if (!this.stopped) await this.report(error); } - })().catch(() => {}); + })(); + this.consumers.push(consumer); + void consumer.catch(() => {}); } this.timer = setInterval(() => this.request(), 15_000); this.timer.unref(); @@ -77,14 +86,20 @@ export class PhotonReceiver { } })() .catch(async (error) => { - if (!this.stopped) await this.options.failure(error); + if (!this.stopped) await this.report(error); }) .finally(() => { this.running = undefined; }); } /** Exposed for deterministic recovery tests, never an external route. */ - async catchUp(): Promise { + catchUp(): Promise { + if (this.stopped) return Promise.resolve(); + const reading = this.catchUpOwned(); this.reads.add(reading); + void reading.finally(() => this.reads.delete(reading)).catch(() => {}); + return reading; + } + private async catchUpOwned(): Promise { const { state, lineId, client, assertOwned, admit, intakeAfter } = this.options; await assertOwned(); @@ -108,6 +123,7 @@ export class PhotonReceiver { const shared = this.options.allocation === "shared"; let sequence = original?.sequence; let batchEvents = 0; + if (this.stopped) return; const stream = this.options.catchUp?.(sequence) ?? client.events.catchUp(sequence); this.catchUpStream = stream; @@ -116,6 +132,7 @@ export class PhotonReceiver { for await (const event of stream) { if (this.stopped) return; await assertOwned(); + if (this.stopped) return; if (event.type === "catchup.complete") { if ( !Number.isSafeInteger(event.headSequence) || @@ -173,7 +190,7 @@ export class PhotonReceiver { "Photon catch-up ended before its checkpoint barrier", ); } finally { - await stream.close(); + await this.closeStream(stream); if (this.catchUpStream === stream) this.catchUpStream = undefined; } } @@ -188,12 +205,57 @@ export class PhotonReceiver { ); } - async close(): Promise { - this.stopped = true; + private async report(error: unknown): Promise { + try { + const receipt = await this.options.failure(error); + if (receipt?.kind !== "recorded") throw new Error("Photon failure responsibility was not recorded by the current owner"); + } + catch (reportingError) { + // Preserve responsibility after the request owner finishes. A stopped + // receiver may retry reporting during close, never restart intake. + this.failureDebt.set(error, reportingError); + this.stopped = true; + this.requested = false; + if (this.timer) clearInterval(this.timer); + } + } + private async retryFailureDebt(): Promise { + for (const [error] of this.failureDebt) { + try { + const receipt = await this.options.failure(error); + if (receipt?.kind === "recorded") this.failureDebt.delete(error); + // A void/stale callback is not proof that current responsibility was + // durably accepted. Keep the original debt for explicit owner repair. + } catch (reportingError) { this.failureDebt.set(error, reportingError); } + } + } + private async closeStream(stream: { close(): Promise }): Promise { + try { await stream.close(); this.closeFailures.delete(stream); } + catch (error) { this.closeFailures.set(stream, error); throw error; } + } + close(): Promise { + if (this.closing) return this.closing; + const closing = this.closeOwned(); this.closing = closing; + void closing.catch(() => { if (this.closing === closing) this.closing = undefined; }); + return closing; + } + private async closeOwned(): Promise { + this.stopped = true; this.requested = false; if (this.timer) clearInterval(this.timer); - await this.catchUpStream?.close(); - await Promise.allSettled(this.streams.map((stream) => stream.close())); - // client.close interrupts a blocked catch-up RPC during runtime shutdown. + const streams = [...this.streams, ...(this.catchUpStream ? [this.catchUpStream] : [])]; + const closed = await Promise.allSettled([ + ...streams.map(stream => this.closeStream(stream)), + Promise.resolve().then(() => this.options.client.close()), + ]); + const joined = await Promise.allSettled([...this.consumers, ...this.reads, ...(this.running ? [this.running] : [])]); + await this.retryFailureDebt(); + const errors = [...new Set([ + ...this.closeFailures.values(), + ...[...this.failureDebt].map(([error, reportingError]) => new AggregateError([error, reportingError], "Photon failure responsibility remains unconfirmed")), + ...closed.flatMap(result => result.status === "rejected" ? [result.reason] : []), + ...joined.flatMap(result => result.status === "rejected" ? [result.reason] : []), + ])]; + if (errors.length) throw new AggregateError(errors, "Photon receiver shutdown remains unconfirmed"); } } diff --git a/server/src/services/photon/recovery-transport.ts b/server/src/services/photon/recovery-transport.ts index 4692cb7a596..4cbf41f218a 100644 --- a/server/src/services/photon/recovery-transport.ts +++ b/server/src/services/photon/recovery-transport.ts @@ -1,3 +1,5 @@ +import { PhotonTransportResources } from "./transport-resources.js"; +import { assertInstalledPhotonTransportJoin } from "./owned-client.js"; import { Client, credentials, Metadata, status } from "@grpc/grpc-js"; import { decodeCatchUpEvent, @@ -111,13 +113,19 @@ export function decodePhotonRecoveryFrame( export class PhotonRecoveryTransport { private readonly client: Client; + private readonly resources = new PhotonTransportResources(); + private closing?: Promise; + private joined = false; constructor( private readonly authentication: PhotonLineAuthentication, client?: Client, ) { + if (!client) assertInstalledPhotonTransportJoin(); this.client = client ?? new Client(authentication.address, credentials.createSsl(), { + "grpc.use_local_subchannel_pool": 1, + "grpc-node.transport_owner": this.resources, "grpc.max_receive_message_length": MAX_ATTACHMENT_BYTES + 1024 * 1024, }); } @@ -172,7 +180,18 @@ export class PhotonRecoveryTransport { } return new TypedEventStream(receive(), async () => controller.abort()); } - close(): void { - this.client.close(); + close(): Promise { + if (this.joined) return Promise.resolve(); + if (this.closing) return this.closing; + this.resources.beginClose(); + const attempt = (async () => { + const errors: unknown[] = []; + try { this.client.close(); } catch (error) { errors.push(error); } + try { await this.resources.close(); } catch (error) { errors.push(error); } + if (errors.length) throw new AggregateError(errors, "Photon CatchUp client and physical transport close remain incomplete"); + })(); + this.closing = attempt; + void attempt.then(() => { this.joined = true; }, () => { if (this.closing === attempt) this.closing = undefined; }); + return attempt; } } diff --git a/server/src/services/photon/transport-resources.ts b/server/src/services/photon/transport-resources.ts new file mode 100644 index 00000000000..1c555456a83 --- /dev/null +++ b/server/src/services/photon/transport-resources.ts @@ -0,0 +1,76 @@ +import type { Socket } from "node:net"; +import type { ClientHttp2Session } from "node:http2"; +import type { ClientRequest } from "node:http"; + +// Exact resources reported by the opt-in grpc1.14.5 delivery patch. No global +// socket interception, recurring timer, activity inference or destroyed flag. +type Resource = Socket | ClientHttp2Session | ClientRequest; +type Entry = { closed: Promise; resolve(): void; onClose(): void; observed: boolean }; +export class PhotonTransportResources { + private readonly abort = new AbortController(); + private readonly entries = new WeakMap(); + private readonly resources = new Map(); + private readonly operations = new Set>(); + private readonly disposalErrors = new Map(); + private attempt?: Promise; + private joined = false; + readonly signal = this.abort.signal; + readonly pending = (operation: Promise): void => { + this.operations.add(operation); + void operation.then(() => this.operations.delete(operation), () => this.operations.delete(operation)); + }; + readonly socket = (socket: Socket): void => { this.observe(socket); }; + readonly session = (session: ClientHttp2Session): void => { this.observe(session); }; + readonly request = (request: ClientRequest): void => { this.observe(request); }; + private observe(resource: Resource): void { + let entry = this.entries.get(resource); + if (!entry) { + let resolve!: () => void; + const closed = new Promise(done => { resolve = done; }); + entry = { closed, resolve, observed: false, onClose: () => {} }; + const current = entry; + current.onClose = () => { + current.observed = true; + this.resources.delete(resource); + this.disposalErrors.delete(resource); + current.resolve(); + }; + this.entries.set(resource, current); + this.resources.set(resource, current); + } + // grpc's normal CONNECT/remoteSettings transitions remove listeners. The + // delivered hook reports that SAME object again in the same synchronous + // transition. Reinstall the same observer; do not replace its receipt. + if (!entry.observed && !resource.listeners("close").includes(entry.onClose)) resource.once("close", entry.onClose); + if (this.signal.aborted && !entry.observed) this.destroy(resource); + } + private destroy(resource: Resource): void { + try { resource.destroy(); this.disposalErrors.delete(resource); } + catch (error) { this.disposalErrors.set(resource, error); } + } + beginClose(): void { + this.abort.abort(); + } + close(): Promise { + if (this.joined) return Promise.resolve(); + if (this.attempt) return this.attempt; + const attempt = this.closeOwned(); this.attempt = attempt; + void attempt.then(() => { this.joined = true; }, () => { if (this.attempt === attempt) this.attempt = undefined; }); + return attempt; + } + private async closeOwned(): Promise { + this.beginClose(); + for (const [resource, entry] of this.resources) if (!entry.observed) this.destroy(resource); + // A synchronous destroy refusal is real retryable debt. Do not wait forever + // on the resource that refused disposal or discard any of its identity. + if (this.disposalErrors.size) throw new AggregateError([...this.disposalErrors.values()], "Photon transport disposal remains incomplete"); + // Every allocation after an await checks this same aborted signal. A late + // resource is observed and destroyed before its connect promise settles. + while (this.operations.size) { + await Promise.allSettled([...this.operations]); + if (this.disposalErrors.size) throw new AggregateError([...this.disposalErrors.values()], "Photon late transport disposal remains incomplete"); + } + await Promise.all([...this.resources.values()].map(entry => entry.closed)); + if (this.disposalErrors.size) throw new AggregateError([...this.disposalErrors.values()], "Photon transport join remains incomplete"); + } +} diff --git a/server/src/services/photon/useful-client.ts b/server/src/services/photon/useful-client.ts new file mode 100644 index 00000000000..9ca1e793721 --- /dev/null +++ b/server/src/services/photon/useful-client.ts @@ -0,0 +1,61 @@ +import { registerIdleLocalWorkProbe } from "../idle-local-work.js"; + +/** Unary useful work owns its actual channel until close resolves. There is no + * keepalive, idle timeout or new poller. Failed close retains the same resource + * and blocks the next operation until its normal retry actually closes it. */ +export class PhotonUsefulClient | void }> { + private client?: T; + private tail: Promise = Promise.resolve(); + private pending = 0; + private failed = false; + private unrecordedDebt = false; + private stopped = false; + private readonly unregister: () => void; + constructor(private readonly create: () => T, initial?: T, private readonly recordDebt: () => Promise = async () => {}) { + this.client = initial; + this.unregister = registerIdleLocalWorkProbe(() => this.failed || this.unrecordedDebt ? "unknown" : this.pending || this.client ? "present" : "none"); + } + private async closeCurrent() { + const client = this.client; + if (!client) { + if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; } + return; + } + try { await client.close(); this.client = undefined; this.failed = false; } + catch (error) { + this.failed = true; this.unrecordedDebt = true; + try { await this.recordDebt(); this.unrecordedDebt = false; } catch { /* Exact resource stays owned and the probe remains unknown. */ } + throw error; + } + if (this.unrecordedDebt) { await this.recordDebt(); this.unrecordedDebt = false; } + } + private enqueue(action: () => Promise): Promise { + this.pending += 1; + const result = this.tail.then(action); + this.tail = result.then(() => undefined, () => undefined); + void this.tail.then(() => { this.pending -= 1; }); + return result; + } + run(action: (client: T) => Promise): Promise { + return this.enqueue(async () => { + if (this.stopped) throw new Error("Photon useful client is stopped"); + await this.closeCurrent(); + const client = this.create(); this.client = client; + let value: R; + try { value = await action(client); } + catch (primary) { + try { await this.closeCurrent(); } catch (cleanup) { throw new AggregateError([primary, cleanup], "Photon useful operation and close failed"); } + throw primary; + } + // The provider result is already known. Preserve it for the caller's + // ordinary durable receipt commit; cleanup failure is separately owned. + try { await this.closeCurrent(); } catch { /* Retained exact resource/debt, never a second provider invocation. */ } + return value; + }); + } + drain(): Promise { return this.enqueue(() => this.closeCurrent()); } + close(): Promise { + this.stopped = true; + return this.enqueue(async () => { await this.closeCurrent(); this.unregister(); }); + } +}