From 17ac7146a5013e5a4d8c1141e8a09801d0d765ed Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 04:13:32 +0000 Subject: [PATCH 1/2] feat(service-automation): the automation engine holds a connector instance by its package and name, and a dispatch addresses the one its caller's name resolves to The engine's connectors are held by (package, name); a bare-name read answers the one instance, never one of two. connector_action resolves the instance for the calling flow's package and reads its handler, effect and inputSchema from it. The reconcile registers each declarative instance with its package and as the sole instance of its name, re-registers it when its package changes, and drops it by name. The OAuth2 grant handle asks its package on every read, and serves a token only for the connection row it was obtained for. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L9qibzKCovWpJoMZD6U3NT --- .../31699-connector-instance-by-package.md | 45 ++++++ .../src/builtin/connector-nodes.ts | 22 +-- .../src/connector-connection-door.test.ts | 66 ++++++++- .../src/connector-connection-package.test.ts | 4 +- .../src/connector-connections.ts | 9 +- .../src/connector-input-schema.ts | 10 ++ .../src/connector-instances.ts | 87 +++++++++++ .../services/service-automation/src/engine.ts | 135 ++++++++++++++---- .../flow-package-scoped-resolution.test.ts | 131 +++++++++++++++++ .../services/service-automation/src/index.ts | 6 + .../src/oauth2-grant/grant-handle.test.ts | 39 ++++- .../src/oauth2-grant/grant-handle.ts | 55 +++++-- .../src/plugin-extension-api.ts | 76 ++++++++-- .../services/service-automation/src/plugin.ts | 46 +++++- 14 files changed, 662 insertions(+), 69 deletions(-) create mode 100644 .changeset/31699-connector-instance-by-package.md create mode 100644 packages/services/service-automation/src/connector-instances.ts diff --git a/.changeset/31699-connector-instance-by-package.md b/.changeset/31699-connector-instance-by-package.md new file mode 100644 index 00000000000..5afb5e7c0c2 --- /dev/null +++ b/.changeset/31699-connector-instance-by-package.md @@ -0,0 +1,45 @@ +--- +'@objectstack/service-automation': patch +--- + +feat(service-automation): the automation engine holds a connector instance by its package and name, and a dispatch addresses the one instance its caller's name resolves to (ADR-0150 D4, #31699) + +Clause-②: yes (widening) — additive in-process surface only: `AutomationEngine` gains `resolveConnectorInstance`, `resolveConnectorInstanceFor` and `resolveConnectorActionInputSchema`; `registerConnector`, `registerDegradedConnector` and `unregisterConnector` take an optional instance (its package, and `soleOfName`); `resolveConnectorAction`, `resolveConnectorActionEffect`, `getConnectorOrigin`, `getConnectorDegradedReason` and `getConnectorDegradedHold` take an optional package; the barrel exports the types `ConnectorInstanceResolution` and `ConnectorInstanceOptions`. Dispatch answers change in one transitional state only (an unstamped entry whose name gains a second holder after boot), as an intended tightening (see "What answers differently" below). Every other dispatch, door and HTTP answer is as before: the declared-connector reconcile still keeps one instance per name (the one-holder backstop, its duplicate-name refusal, and `soleOfName` on every declarative registration), and a lookup by bare name answers that one instance. +Metadata-protocol: none +Skills-docs: none — nothing a skill or a docs page teaches changes while one instance per name is kept; the two-holder connector docs come with the PR that narrows the backstop. + +Part of #31699 (ADR-0150 child B, PR 3b). PR 3a-ii made the connection store, the connect door and the OAuth callback address an instance by package and name; this PR makes the engine hold and dispatch it so. + +**The engine's instances.** + +- The registered connectors are held by `(package, name)` (`ConnectorInstances`): a declarative instance by the package the connection door addresses it by (`connectorInstancePackage`: its real stamp; none for the environment's stored entry; the name's durable holder for an unstamped or compatibility-default entry), a plugin's connector by no package. +- A plugin's connector and a declarative instance still never share a name, whatever package the instance is of (ADR-0097 §4). With `soleOfName`, a declarative registration drops any other declarative instance of the name: the reconcile registers every instance so, and keeps one per name, until the backstop narrows. +- A read by bare name answers the one instance of the name, and none when there are two, never one of them. `getRegisteredConnectors` lists each name once; `getConnectorDescriptors` lists every instance. + +**Dispatch.** + +- `connector_action` resolves its `connectorId` for the calling flow's package (`resolveConnectorInstance`): a refused name is refused as before, naming every candidate; a resolved holder is dispatched to its own instance, and its action's `inputSchema` and `effect` are read from that instance. A caller with no package, a name no registry holds, or a resolved holder with no instance registered under it (a plugin's connector of a declared name) is answered by the one instance of the name, as the dispatch by name answered; two are not dispatched. `connectorNameRefusal` answers as before. +- The OAuth2 grant handle asks its instance's package on every read of the connection store, so an unstamped entry's connections are read under the package its name resolves to now, not when the handle was made. A cached access token is served only for the connection row it was obtained for (its row id, beside its revision): a read that now chooses another row (another package's connection of the organization) refreshes, never serves the other row's token. + +**The reconcile.** + +- The instance package is part of a provider-bound entry's desired signature, so an unstamped entry whose name's holder changes (installed, uninstalled, a second holder) is registered again under the package it resolves to now, on the next reconcile. The engine's instance and the connection the grant handle reads stay one package. +- An instance the reconcile drops (no longer declared, degraded and removed) is unregistered by name, every instance of it: the reconcile keeps one per name, whatever package it was registered under. +- Limit: the boot's second reconcile (packages registered during the boot) is skipped when the declared list's fingerprint is unchanged, and the fingerprint carries no package, so a holder that changes in that window without the declared list changing is followed on the next reload or restart. + +**What answers differently.** + +- An unstamped (or compatibility-default) declared entry whose name gains a second durable holder: its dispatch was answered with the connection of the package that held the name at boot (200) until a restart. It is now read under the package the name resolves to at that moment, which is no one package, so it is refused 503 (no connection of its own): under two holders a row is its own package's only (PR 3a-ii's store rule), as the connection door already refuses that name (409). It is recovered by stamping the entry or by uninstalling the second holder. A holder that is uninstalled or replaced, leaving one holder, changes no answer: every row of the name still answers the one instance, and the next reconcile registers the instance again under the package it resolves to now (any provider-bound instance is re-materialized on such a change). +- A dispatch that joins an access-token refresh already in flight for another connection row of the organization (the instance's package changed while the refresh was out) is refused 503, never served that row's token; the next dispatch refreshes its own row. +- The store's refusal of a row of a two-holder name that names none of the holders now names the remedy that works for it: `os migrate stored-references bind` for a row naming no package, and uninstalling one of the holders for a row already naming another package, which the bind refuses (PR 3a-ii contract review N4). +- On a change of holder, the instance is re-registered, so its name moves to the end of `getRegisteredConnectors()` and `GET /automation/connectors`. + +**Not in this PR (moved to the PR that narrows the backstop).** + +- The materializer's own bookkeeping (`desired`, the materialized, degraded and credential-refusal maps, `grantHandles`, retry and dematerialize) stays keyed by name: under the backstop the reconcile cannot hold two instances of one name, so re-keying it is observable only once the duplicate-name refusal is lifted, and lands with it and with a two-live-instance test. Its registrations and unregistrations already pass the instance package. +- The connector pull keeps reading its connector by bare name (the one instance): whether a mapping's connector is resolved for the job's package, and refused where that name is refused, changes an answer and is decided with the narrowing. +- The resolved-holder fallback above (a resolved holder with no registered instance answered by the one instance of the name) is right only while one instance per name is kept; with two instances alive the narrowing PR makes it `none`. +- `ConnectorDescriptor.packageId`, the addressed connection door (`?package=`), connector into the namespace-scoped type sets, and the backstop itself. +- `registerConnector(def, handlers, 'declarative', { packageId })` without `soleOfName` is public and keeps two instances of one name side by side (the engine tests use it). Nothing in-tree registers so outside the tests; the reconcile always passes `soleOfName`. + +**In-process APIs.** Listed under Clause-② above. All additive; every new parameter is optional and its absence answers as before. diff --git a/packages/services/service-automation/src/builtin/connector-nodes.ts b/packages/services/service-automation/src/builtin/connector-nodes.ts index 90f5f32a74b..b995d9673e7 100644 --- a/packages/services/service-automation/src/builtin/connector-nodes.ts +++ b/packages/services/service-automation/src/builtin/connector-nodes.ts @@ -65,13 +65,17 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont // [ADR-0150 D3, epic #31527 child E5] A packaged flow names its // connector from its package: refused (every candidate named) when // the name does not resolve for that package — never dispatched on - // a guess. - const nameRefusal = engine.connectorNameRefusal(cfg.connectorId, context); - if (nameRefusal) { - return refuseNode(`connector_action '${node.id}': ${nameRefusal.message}`); + // a guess. [ADR-0150 D4, #31699] Otherwise the step dispatches the + // one instance that answer addresses, by its package. + const instance = engine.resolveConnectorInstance(cfg.connectorId, context); + if (instance.status === 'refused') { + return refuseNode(`connector_action '${node.id}': ${instance.refusal.message}`); } + // `none`: an address no instance answers; every read below then + // finds nothing registered, as for a name never registered. + const packageId = instance.status === 'instance' ? instance.packageId : undefined; - const handler = engine.resolveConnectorAction(cfg.connectorId, cfg.actionId); + const handler = packageId === undefined ? undefined : engine.resolveConnectorAction(cfg.connectorId, cfg.actionId, packageId); if (!handler) { // A degraded declarative instance (#3017) is registered but has no // handlers — say WHY dispatch fails and what recovers it, instead @@ -80,9 +84,9 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont // was refused. [#28016] Recovery is automatic only on the backoff: // a held instance (a configuration fault met on a retry, a refused // credential the platform will not re-send) names its fix instead. - const degraded = engine.getConnectorDegradedReason(cfg.connectorId); + const degraded = packageId === undefined ? undefined : engine.getConnectorDegradedReason(cfg.connectorId, packageId); if (degraded) { - const hold = engine.getConnectorDegradedHold(cfg.connectorId); + const hold = engine.getConnectorDegradedHold(cfg.connectorId, packageId); // A reason that is a full sentence keeps one full stop. const reason = degraded.replace(/\.\s*$/, ''); return { @@ -123,7 +127,7 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont // #4395 lets the action declare `effect`, and this is where the // declaration is spent. Resolved BEFORE dispatch so both the // success and the failure path read one value. - const effect = engine.resolveConnectorActionEffect(cfg.connectorId, cfg.actionId); + const effect = engine.resolveConnectorActionEffect(cfg.connectorId, cfg.actionId, packageId); // #27327 — `input` is a value-slot map: a top-level CEL envelope is // evaluated in the run's scope, every other value handed on as a @@ -143,7 +147,7 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont // (#28040). A `runtime` failure, not a guard: the input can come // from run data, so a `fault` edge may handle it. const verdict = judgeConnectorInput( - findConnectorActionInputSchema(engine, cfg.connectorId, cfg.actionId), + findConnectorActionInputSchema(engine, cfg.connectorId, cfg.actionId, packageId), input, ); if (verdict) { diff --git a/packages/services/service-automation/src/connector-connection-door.test.ts b/packages/services/service-automation/src/connector-connection-door.test.ts index e5e535b7063..25be856028b 100644 --- a/packages/services/service-automation/src/connector-connection-door.test.ts +++ b/packages/services/service-automation/src/connector-connection-door.test.ts @@ -247,6 +247,7 @@ async function boot( ) { const ql = await dataEngine(); const provider = grantedProvider(); + let captured: any; const kernel = new LiteKernel({ logger: { level: 'debug', format: 'json' } } as never); kernels.push(kernel); kernel.use(new AutomationServicePlugin({ @@ -260,6 +261,7 @@ async function boot( version: '1.0.0', dependencies: ['com.objectstack.service-automation'], async init(ctx: any) { + captured = ctx; const listItems = (t: string) => (t === 'connector' ? declared : []); const registry = opts.registry ? Object.assign(Object.create(opts.registry), { listItems }) : { listItems }; ctx.registerService('objectql', { registry }); @@ -283,7 +285,9 @@ async function boot( const query = opts2.query ?? { code: opts2.code ?? GOOD_CODE, state }; return { begun, state, done: () => engine.completeConnectorConnection({ query: { state, ...query }, context: (opts2.as ?? context) as never }) }; }; - return { ql, engine, provider, call, connect, kernel }; + /** Fire the reload hook: the runtime reconcile, over `declared` as it stands now. */ + const reload = async () => { await captured.trigger('metadata:reloaded'); await flush(); }; + return { ql, engine, provider, call, connect, kernel, reload }; } const rowsOf = async (ql: ObjectQL) => (await ql.find(CONNECTOR_CONNECTION_OBJECT, { context: SYSTEM } as never)) as any[]; @@ -1105,6 +1109,66 @@ describe('ADR-0150 D4 [#31699] — the connection door connects one instance, by expect(await rowsOf(ql)).toHaveLength(0); }); + it('[3b] the materializer registers the instance by its package, and the dispatch handle reads the package as the name resolves now', async () => { + const registry = registryHolding('com.example.crm'); + const { connect, call, engine } = await boot([crm({ _packageId: undefined })], { registry }); + await (await connect()).done(); + expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: 'com.example.crm' }); + await expect(call('org_a')).resolves.toMatchObject({ status: 200 }); + // A second durable holder: the unstamped entry is no one package's any + // more, so its connection (the package's row) is not its own. + hold(registry, OTHER); + await expect(call('org_a')).rejects.toMatchObject({ status: 503 }); + }); + + it('[3b] the holder of an unstamped entry is replaced, leaving one holder: the dispatch keeps its connection', async () => { + const registry = registryHolding('com.example.crm'); + const { connect, call, engine } = await boot([crm({ _packageId: undefined })], { registry }); + await (await connect()).done(); + registry.uninstallPackage('com.example.crm'); + registry.unregisterItemsByPackage('com.example.crm'); + hold(registry, OTHER); + expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: 'com.example.crm' }); + await expect(call('org_a')).resolves.toMatchObject({ status: 200 }); + }); + + it('[3b, review M1] the package an unstamped entry is registered under follows the name\'s holder, and a removed entry leaves no instance behind', async () => { + // Not connected: the instance is the degraded husk. + const registry = registryHolding('com.example.crm'); + const declared: unknown[] = [crm({ _packageId: undefined })]; + const { engine, reload } = await boot(declared, { registry }); + expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: 'com.example.crm' }); + expect(engine.getConnectorDegradedReason('crm')).toBeDefined(); + // The holder is uninstalled; the declared list is unchanged. The + // reconcile registers the instance again, under no package. + registry.uninstallPackage('com.example.crm'); + registry.unregisterItemsByPackage('com.example.crm'); + await reload(); + expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: null }); + expect(engine.getConnectorDescriptors().filter((d) => d.name === 'crm')).toHaveLength(1); + // The entry is removed: no instance of the name is left, under any package. + declared.length = 0; + await reload(); + expect(engine.getRegisteredConnectors()).not.toContain('crm'); + expect(engine.getConnectorDegradedReason('crm')).toBeUndefined(); + }); + + it('[3b, review M1] an entry removed while its package holds the name: both the degraded and the live instance are dropped', async () => { + const declared: unknown[] = [crm({ _packageId: undefined })]; + const degraded = await boot(declared, { registry: registryHolding('com.example.crm') }); + declared.length = 0; + await degraded.reload(); + expect(degraded.engine.getRegisteredConnectors()).not.toContain('crm'); + + const declaredLive: unknown[] = [crm({ _packageId: undefined })]; + const live = await boot(declaredLive, { registry: registryHolding('com.example.crm') }); + await (await live.connect()).done(); + expect(live.engine.getConnectorDegradedReason('crm')).toBeUndefined(); + declaredLive.length = 0; + await live.reload(); + expect(live.engine.getRegisteredConnectors()).not.toContain('crm'); + }); + it('a resolved holder no declared entry is the instance of: the one declared entry is served, with its own package', async () => { const { connect, ql } = await boot([crm({ _packageId: OTHER })], { registry: registryHolding('com.example.crm') }); await expect((await connect()).done()).resolves.toMatchObject({ status: 'connected' }); diff --git a/packages/services/service-automation/src/connector-connection-package.test.ts b/packages/services/service-automation/src/connector-connection-package.test.ts index 830107bf2d5..97a79f2e759 100644 --- a/packages/services/service-automation/src/connector-connection-package.test.ts +++ b/packages/services/service-automation/src/connector-connection-package.test.ts @@ -175,7 +175,9 @@ describe('[#31699, contract review F1] a declaration that moves keeps its connec const store = storeOver(ql, twoHolders); const refusal = await store.read('org_a', 'crm', A).then(() => undefined, (e: unknown) => e); expect(refusal).toBeInstanceOf(ConnectorConnectionConflictError); - expect((refusal as Error).message).toMatch(/os migrate stored-references bind/); + // The bind never moves a row that already names a package: the remedy is to uninstall one holder. + expect((refusal as Error).message).toMatch(/Uninstall one of the packages/); + expect((refusal as Error).message).not.toMatch(/stored-references bind/); await expect(store.revoke('org_a', 'crm', undefined, A)).rejects.toBeInstanceOf(ConnectorConnectionConflictError); expect(await packages(ql)).toEqual(['com.acme.gone']); diff --git a/packages/services/service-automation/src/connector-connections.ts b/packages/services/service-automation/src/connector-connections.ts index b40a2cc3948..5ec7a208511 100644 --- a/packages/services/service-automation/src/connector-connections.ts +++ b/packages/services/service-automation/src/connector-connections.ts @@ -245,11 +245,14 @@ export class ConnectorConnectionStore { return named === null || !holders.has(named); }); if (unclaimed.length === 0) return own; + const remedy = unclaimed.some((r) => rowPackage(r) === null) + ? 'Bind a connection naming no package to its package with `os migrate stored-references bind --table ' + + 'sys_connector_connection`, or uninstall one of the packages, then read it again.' + // The bind never moves a row that already names a package. + : 'Uninstall one of the packages, then read it again: the one remaining instance reads it, and a revoke removes it.'; throw new ConnectorConnectionConflictError( `The connection of connector instance '${connectorName}' in this organization names no package that holds ` - + `that name, and ${holder.candidates.length} packages hold it, so it is no one package's connection. Bind it to ` - + 'its package with `os migrate stored-references bind --table sys_connector_connection`, or uninstall one of ' - + 'the packages, then read it again.', + + `that name, and ${holder.candidates.length} packages hold it, so it is no one package's connection. ${remedy}`, ); } diff --git a/packages/services/service-automation/src/connector-input-schema.ts b/packages/services/service-automation/src/connector-input-schema.ts index ff5952ddba5..6a55440ec2a 100644 --- a/packages/services/service-automation/src/connector-input-schema.ts +++ b/packages/services/service-automation/src/connector-input-schema.ts @@ -21,6 +21,12 @@ import type { ConnectorDescriptor } from '@objectstack/spec/integration'; /** Where a door reads an action's declared `inputSchema` — the automation engine's descriptor list. */ export interface ConnectorInputSchemaSource { getConnectorDescriptors(): ConnectorDescriptor[]; + /** + * [#31699] The schema of one instance's action, by its package: the + * engine's (`AutomationEngine.resolveConnectorActionInputSchema`). A + * source without it is read through its descriptor list, by name. + */ + resolveConnectorActionInputSchema?(connectorId: string, actionId: string, packageId?: string | null): unknown; } /** What one judgment found: the violations as one sentence, and whether any was text where a number or boolean is declared. */ @@ -46,7 +52,11 @@ export function findConnectorActionInputSchema( source: ConnectorInputSchemaSource, connectorId: string, actionId: string, + packageId?: string | null, ): unknown { + if (typeof source.resolveConnectorActionInputSchema === 'function') { + return source.resolveConnectorActionInputSchema(connectorId, actionId, packageId); + } return source .getConnectorDescriptors() .find((d) => d.name === connectorId) diff --git a/packages/services/service-automation/src/connector-instances.ts b/packages/services/service-automation/src/connector-instances.ts new file mode 100644 index 00000000000..a91e21cb135 --- /dev/null +++ b/packages/services/service-automation/src/connector-instances.ts @@ -0,0 +1,87 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0150 D4, #31699] The automation engine's registered connector + * instances, held by `(package, name)`. + * + * A connector instance is identified by its package and its name: a package's + * declared instance by that package, an instance the environment authored or a + * plugin registers in code by no package (`null`). Two packages' instances of + * one name are two instances. A caller that knows only the name is answered + * by the one instance of that name, never by one of two (ADR-0150 red line 2). + * + * Today the declared-connector reconcile still keeps one instance per name + * (the one-holder backstop and its duplicate-name refusal), and registers a + * declarative instance with `soleOfName`, which drops any other declarative + * instance of the name. The PR that narrows the backstop lifts that. + */ + +import type { RegisteredConnector } from './engine.js'; + +/** One registered instance and the package it is the instance of (`null`: none). */ +export interface ConnectorInstanceEntry { + readonly packageId: string | null; + readonly registered: RegisteredConnector; +} + +export class ConnectorInstances { + private readonly byName = new Map>(); + + /** The instance of `name` of exactly `packageId`, or `undefined`. */ + get(name: string, packageId: string | null): RegisteredConnector | undefined { + return this.byName.get(name)?.get(packageId); + } + + /** Every instance registered under `name`, in registration order. */ + ofName(name: string): ConnectorInstanceEntry[] { + return [...(this.byName.get(name) ?? new Map())] + .map(([packageId, registered]) => ({ packageId, registered })); + } + + /** The one instance of `name`, or `undefined` when there is none or more than one. */ + sole(name: string): ConnectorInstanceEntry | undefined { + const all = this.ofName(name); + return all.length === 1 ? all[0] : undefined; + } + + /** Register (or replace) the instance of `name` of `packageId`. */ + set(name: string, packageId: string | null, registered: RegisteredConnector): void { + let instances = this.byName.get(name); + if (!instances) { + instances = new Map(); + this.byName.set(name, instances); + } + instances.set(packageId, registered); + } + + /** + * Remove the instance of `name` of `packageId`, or, with `packageId` + * `undefined`, every instance of `name`. `true` when one was removed. + */ + delete(name: string, packageId?: string | null): boolean { + const instances = this.byName.get(name); + if (!instances) return false; + if (packageId === undefined) { + this.byName.delete(name); + return instances.size > 0; + } + const removed = instances.delete(packageId); + if (instances.size === 0) this.byName.delete(name); + return removed; + } + + /** Every registered name, once each. */ + names(): string[] { + return [...this.byName.keys()]; + } + + /** Every registered instance. */ + entries(): ConnectorInstanceEntry[] { + return this.names().flatMap((name) => this.ofName(name)); + } + + /** Every registered instance's registration. */ + values(): RegisteredConnector[] { + return this.entries().map((e) => e.registered); + } +} diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 5aa9bdaf19e..f7309f37d85 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -237,6 +237,8 @@ import { packageScopedRefusalMessage, PackageScopedNameRefusedError } from '@obj import { ENVIRONMENT_ADDRESS_SEGMENT } from '@objectstack/spec/kernel'; import { FlowSlotTable, flowRunKey, flowRunPackage, isSlotKeySpelling, qualifiedFlowKey, unfiledFlowKey, stampFlowRunSlot, type FlowKeyMove, type FlowSlot } from './flow-slots.js'; import { flowSlotRunStore } from './flow-slot-run-store.js'; +import { ConnectorInstances } from './connector-instances.js'; +import type { ConnectorInstanceOptions } from './plugin-extension-api.js'; import { describeRegionSuspendingCall, regionSuspendingCall } from './subflow-region-guard.js'; // [#25222] The consumed-suspension restore's bodies: journaling a consumed // suspension, resolving its witnesses, and restoring, peeking at or inspecting @@ -2697,6 +2699,17 @@ export type FlowNameResolver = ( * means the host serves no registry to ask. ⛔ Never a second implementation * of the rule. [#32183] `options` as {@link FlowNameResolver}'s. */ +/** + * [#31699] The answer of {@link AutomationEngine.resolveConnectorInstanceFor}: + * the registered instance a name addresses (its package, `null` for none), a + * refusal naming every candidate, or `none` (not registered, or two instances + * and nothing to choose by). + */ +export type ConnectorInstanceResolution = + | { readonly status: 'instance'; readonly packageId: string | null } + | { readonly status: 'refused'; readonly refusal: PackageScopedRefusal } + | { readonly status: 'none' }; + export type ConnectorNameResolver = ( name: string, callerPackageId: string | null, @@ -3166,8 +3179,12 @@ export class AutomationEngine implements IAutomationService { * {@link withdrawFlow}. */ private readonly subflowRegionDeclinedFlows = new Map(); - /** Connectors registered by integration plugins, keyed by connector name (ADR-0018 §Addendum). */ - private connectors = new Map(); + /** + * Registered connector instances (ADR-0018 §Addendum), by package and name + * ([#31699] ADR-0150 D4: a plugin's connector, or an instance the + * environment authored, is of no package). + */ + private connectors = new ConnectorInstances(); /** Connector provider factories keyed by provider name (ADR-0097 §2 — `openapi`/`mcp`/`rest`/…). */ private connectorProviders = new Map(); /** ADR-0143 D4 — provider keys registered with `credentialHandle: true`. */ @@ -4385,6 +4402,7 @@ export class AutomationEngine implements IAutomationService { def: Connector, handlers: Record, origin: ConnectorOrigin = 'plugin', + instance?: ConnectorInstanceOptions, ): void { // The body lives in ./plugin-extension-api.ts (#25222). const host: ThisParameterType = { @@ -4392,7 +4410,7 @@ export class AutomationEngine implements IAutomationService { connectors: this.connectors, logger: this.logger, }; - registerConnector.call(host, def, handlers, origin); + registerConnector.call(host, def, handlers, origin, instance); } /** @@ -4462,6 +4480,7 @@ export class AutomationEngine implements IAutomationService { origin: ConnectorOrigin = 'declarative', cause?: unknown, hold?: ConnectorHold, + instance?: ConnectorInstanceOptions, ): void { // The body lives in ./plugin-extension-api.ts (#25222). const host: ThisParameterType = { @@ -4469,36 +4488,60 @@ export class AutomationEngine implements IAutomationService { connectors: this.connectors, logger: this.logger, }; - registerDegradedConnector.call(host, def, reason, origin, cause, hold); + registerDegradedConnector.call(host, def, reason, origin, cause, hold, instance); } /** Enforce the ADR-0097 §4 two-sources-of-truth rule; warn on same-origin replace. */ - private assertSameOriginOrFree(name: string, origin: ConnectorOrigin): void { + private assertSameOriginOrFree(name: string, origin: ConnectorOrigin, packageId?: string | null, soleOfName?: boolean): void { // The body lives in ./plugin-extension-api.ts (#25222). const host: ThisParameterType = { connectors: this.connectors, logger: this.logger, }; - assertSameOriginOrFree.call(host, name, origin); + assertSameOriginOrFree.call(host, name, origin, packageId ?? null, soleOfName ?? false); } - /** Unregister a connector (hot-unplug). */ - unregisterConnector(name: string): void { + /** + * Unregister a connector (hot-unplug): [#31699] the instance of + * `packageId`, or every instance of `name` when `packageId` is absent. + */ + unregisterConnector(name: string, packageId?: string | null): void { // The body lives in ./plugin-extension-api.ts (#25222). const host: ThisParameterType = { connectors: this.connectors, logger: this.logger, }; - unregisterConnector.call(host, name); + unregisterConnector.call(host, name, packageId); + } + + /** + * [#31699] The registered instance `packageId` addresses: exactly that + * package's instance of `name` (`null`: the one of no package), or, with + * `packageId` absent, the one instance of the name, `undefined` when there + * are two (never one of them, ADR-0150 red line 2). + */ + private connectorInstance(name: string, packageId?: string | null): RegisteredConnector | undefined { + return packageId === undefined ? this.connectors.sole(name)?.registered : this.connectors.get(name, packageId); } /** * Resolve the handler for a connector action, used by the baseline * `connector_action` node. Returns `undefined` when the connector or action * is not registered, so the node can fail the step with a clear error. + * [#31699] `packageId` addresses the instance ({@link connectorInstance}). + */ + resolveConnectorAction(connectorId: string, actionId: string, packageId?: string | null): ConnectorActionHandler | undefined { + return this.connectorInstance(connectorId, packageId)?.handlers[actionId]; + } + + /** + * [#31699] The declared `inputSchema` of an action of the instance + * `packageId` addresses ({@link connectorInstance}), read from its stored + * def as {@link getConnectorDescriptors} projects it; `undefined` when it + * declares none or is not registered. */ - resolveConnectorAction(connectorId: string, actionId: string): ConnectorActionHandler | undefined { - return this.connectors.get(connectorId)?.handlers[actionId]; + resolveConnectorActionInputSchema(connectorId: string, actionId: string, packageId?: string | null): unknown { + return this.connectorInstance(connectorId, packageId)?.def.actions?.find((a) => a.key === actionId)?.inputSchema; } /** @@ -4514,8 +4557,8 @@ export class AutomationEngine implements IAutomationService { * ADR-0097 declarative materialization path store their def here, so one * lookup covers both origins. */ - resolveConnectorActionEffect(connectorId: string, actionId: string): ConnectorActionEffect | undefined { - return this.connectors.get(connectorId)?.def.actions?.find((a) => a.key === actionId)?.effect; + resolveConnectorActionEffect(connectorId: string, actionId: string, packageId?: string | null): ConnectorActionEffect | undefined { + return this.connectorInstance(connectorId, packageId)?.def.actions?.find((a) => a.key === actionId)?.effect; } /** @@ -4609,12 +4652,16 @@ export class AutomationEngine implements IAutomationService { /** Get all registered connector names. */ getRegisteredConnectors(): string[] { - return [...this.connectors.keys()]; + return this.connectors.names(); } - /** The origin a connector was registered under, or `undefined` if unregistered. */ - getConnectorOrigin(name: string): ConnectorOrigin | undefined { - return this.connectors.get(name)?.origin; + /** + * The origin a connector was registered under, or `undefined` if + * unregistered. [#31699] `packageId` addresses the instance + * ({@link connectorInstance}). + */ + getConnectorOrigin(name: string, packageId?: string | null): ConnectorOrigin | undefined { + return this.connectorInstance(name, packageId)?.origin; } /** @@ -4623,8 +4670,8 @@ export class AutomationEngine implements IAutomationService { * `connector_action` node distinguish "degraded, retrying" from "no such * connector/action" in its failure message (#3017). */ - getConnectorDegradedReason(name: string): string | undefined { - const reg = this.connectors.get(name); + getConnectorDegradedReason(name: string, packageId?: string | null): string | undefined { + const reg = this.connectorInstance(name, packageId); return reg?.state === 'degraded' ? (reg.degradedReason ?? 'upstream unavailable') : undefined; } @@ -4634,8 +4681,8 @@ export class AutomationEngine implements IAutomationService { * Lets the `connector_action` node say "retries automatically" only when * that is true. */ - getConnectorDegradedHold(name: string): ConnectorHold | undefined { - const reg = this.connectors.get(name); + getConnectorDegradedHold(name: string, packageId?: string | null): ConnectorHold | undefined { + const reg = this.connectorInstance(name, packageId); return reg?.state === 'degraded' ? reg.degradedHold : undefined; } @@ -4703,7 +4750,7 @@ export class AutomationEngine implements IAutomationService { * Handlers are omitted — they are runtime code, not metadata. */ getConnectorDescriptors(): ConnectorDescriptor[] { - return [...this.connectors.values()].map(({ def, origin, state, degradedReason }) => ({ + return this.connectors.values().map(({ def, origin, state, degradedReason }) => ({ name: def.name, label: def.label, type: def.type, @@ -5832,10 +5879,46 @@ export class AutomationEngine implements IAutomationService { * as before. Read-only. */ connectorNameRefusal(connectorId: string, context: AutomationContext | undefined): PackageScopedRefusal | undefined { - const callerPackageId = this.flowCallerPackage(context); - if (callerPackageId === null) return undefined; - const meant = this.connectorNameResolver?.(connectorId, callerPackageId); - return meant?.status === 'refused' ? meant : undefined; + const resolved = this.resolveConnectorInstanceFor(connectorId, this.flowCallerPackage(context)); + return resolved.status === 'refused' ? resolved.refusal : undefined; + } + + /** + * [ADR-0150 D3/D4, #31699] Which registered instance the bare name + * `connectorId` means for the run of `context`'s flow + * ({@link resolveConnectorInstanceFor} for {@link flowCallerPackage}). + */ + resolveConnectorInstance(connectorId: string, context: AutomationContext | undefined): ConnectorInstanceResolution { + return this.resolveConnectorInstanceFor(connectorId, this.flowCallerPackage(context)); + } + + /** + * [ADR-0150 D3/D4, #31699] Which registered instance the bare name + * `connectorId` means for a caller of package `callerPackageId`: + * + * - a package caller: the resolver's answer. `refused` is said with the + * resolver's own message (every candidate named, {@link connectorNameRefusal}); + * `resolved` addresses the holder's instance, when one is registered; + * - otherwise (no package, no resolver, a name no registry holds, a + * resolved holder with no instance registered under it): the one + * instance of the name, as a dispatch by name answered before; two are + * `none`, never one of them. + * + * The second arm is the connection door's rule + * (`AutomationServicePlugin.connectionDoorInstance`), so the door and the + * dispatch address one instance. Read-only. + */ + resolveConnectorInstanceFor(connectorId: string, callerPackageId: string | null): ConnectorInstanceResolution { + if (callerPackageId !== null) { + const meant = this.connectorNameResolver?.(connectorId, callerPackageId); + if (meant?.status === 'refused') return { status: 'refused', refusal: meant }; + if (meant?.status === 'resolved') { + const packageId = meant.holder.kind === 'package' ? meant.holder.packageId : null; + if (this.connectors.get(connectorId, packageId)) return { status: 'instance', packageId }; + } + } + const sole = this.connectors.sole(connectorId); + return sole ? { status: 'instance', packageId: sole.packageId } : { status: 'none' }; } /** diff --git a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts index 6c64f4ceb34..853472f62fb 100644 --- a/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts +++ b/packages/services/service-automation/src/flow-package-scoped-resolution.test.ts @@ -765,3 +765,134 @@ describe('ADR-0150 D3 — an environment override of a packaged flow names its r expect(engine.armedFlowPackage('never_registered')).toBeUndefined(); }); }); + +// ── [ADR-0150 D4, #31699] the engine holds a connector instance by package and name ── + +describe('ADR-0150 D4 — the engine holds a connector instance by (package, name) and dispatches the one a flow addresses (#31699)', () => { + const B = 'com.acme.beta'; + const P2 = 'com.acme.caller2'; + const def = (name: string, inputSchema: unknown = { type: 'object' }) => + ({ name, label: name, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'ping', label: 'Ping', inputSchema }] }) as never; + /** A declarative instance of `name` of package `packageId`; `pings` records `name@package` per dispatch. */ + const instance = (name: string, packageId: string | null, opts: { soleOfName?: boolean; inputSchema?: unknown } = {}) => + engine.registerConnector( + def(name, opts.inputSchema), + { ping: async () => { pings.push(`${name}@${packageId ?? '-'}`); return { ok: true }; } }, + 'declarative', + { packageId, ...(opts.soleOfName ? { soleOfName: true } : {}) }, + ); + + beforeEach(() => { + pings = []; + const ctx = { getService(name: string) { if (name === 'objectql') return { registry }; throw new Error(`no ${name}`); } }; + engine.setConnectorNameResolver(connectorNameResolver(ctx as never)); + }); + + it("two packages' instances of one name are both held; each package's flow dispatches the one its closure resolves to", async () => { + install(A); + install(B); + install(P, [A]); + install(P2, [B]); + declareConnector('billing', A); + declareConnector('billing', B); + instance('billing', A); + instance('billing', B); + expect(engine.getRegisteredConnectors()).toEqual(['billing']); + expect(engine.getConnectorDescriptors().filter((d) => d.name === 'billing')).toHaveLength(2); + ship(P, dispatcher('charge', 'billing')); + ship(P2, dispatcher('charge2', 'billing')); + expect((await engine.execute('charge')).success).toBe(true); + expect((await engine.execute('charge2')).success).toBe(true); + expect(pings).toEqual([`billing@${A}`, `billing@${B}`]); + }); + + it("each flow's input is judged against the inputSchema of the instance it dispatches, not another package's of the name", async () => { + install(A); + install(B); + install(P, [A]); + install(P2, [B]); + declareConnector('billing', A); + declareConnector('billing', B); + instance('billing', A); + instance('billing', B, { inputSchema: { type: 'object', required: ['amount'], properties: { amount: { type: 'number' } } } }); + ship(P, dispatcher('charge', 'billing')); + ship(P2, dispatcher('charge2', 'billing')); + expect((await engine.execute('charge')).success).toBe(true); + const refused = await engine.execute('charge2'); + expect(refused.success).toBe(false); + expect(String(refused.error)).toContain('amount'); + expect(pings).toEqual([`billing@${A}`]); + }); + + it('⛔ two instances and a caller with nothing to choose by: no dispatch, never one of them', async () => { + install(A); + install(B); + declareConnector('billing', A); + declareConnector('billing', B); + instance('billing', A); + instance('billing', B); + author(dispatcher('my_charge', 'billing')); + const result = await engine.execute('my_charge'); + expect(result.success).toBe(false); + expect(pings).toEqual([]); + // The bare-name reads answer no instance; the addressed ones answer each. + expect(engine.resolveConnectorAction('billing', 'ping')).toBeUndefined(); + expect(engine.getConnectorOrigin('billing')).toBeUndefined(); + expect(engine.resolveConnectorAction('billing', 'ping', A)).toBeTypeOf('function'); + expect(engine.resolveConnectorActionInputSchema('billing', 'ping', B)).toEqual({ type: 'object' }); + expect(engine.resolveConnectorInstanceFor('billing', null)).toEqual({ status: 'none' }); + }); + + it('a package caller whose closure holds two is refused with the resolver\'s message, naming both', () => { + install(A); + install(B); + install(P, [A, B]); + declareConnector('billing', A); + declareConnector('billing', B); + instance('billing', A); + instance('billing', B); + const answer = engine.resolveConnectorInstanceFor('billing', P); + expect(answer.status).toBe('refused'); + const message = answer.status === 'refused' ? answer.refusal.message : ''; + expect(message).toContain(A); + expect(message).toContain(B); + }); + + it('fallback (the connection door\'s rule, until the narrowing): a package caller whose holder has no instance registered is answered by the one instance of the name', async () => { + install(A); + install(P, [A]); + declareConnector('billing', A); + // The one instance is registered under no package (an unstamped entry + // whose holder could not be read when it was registered). + instance('billing', null); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'instance', packageId: null }); + ship(P, dispatcher('charge', 'billing')); + expect((await engine.execute('charge')).success).toBe(true); + expect(pings).toEqual(['billing@-']); + // A second instance: no sole one, so no fallback: none, never one of them. + instance('billing', B); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'none' }); + }); + + it('soleOfName (the reconcile today): a declarative registration drops the other declarative instance of the name', () => { + instance('billing', A, { soleOfName: true }); + instance('billing', B, { soleOfName: true }); + expect(engine.resolveConnectorInstanceFor('billing', null)).toEqual({ status: 'instance', packageId: B }); + expect(engine.resolveConnectorAction('billing', 'ping', A)).toBeUndefined(); + }); + + it('a plugin connector and a declarative instance never share a name, whatever package the instance is of', () => { + engine.registerConnector(def('slack'), { ping: async () => ({}) }); + expect(() => instance('slack', A)).toThrow(/Connector name conflict: 'slack'/); + }); + + it('unregister removes the addressed instance, or every instance of the name when none is addressed', () => { + instance('billing', A); + instance('billing', B); + engine.unregisterConnector('billing', A); + expect(engine.resolveConnectorInstanceFor('billing', null)).toEqual({ status: 'instance', packageId: B }); + instance('billing', A); + engine.unregisterConnector('billing'); + expect(engine.getRegisteredConnectors()).toEqual([]); + }); +}); diff --git a/packages/services/service-automation/src/index.ts b/packages/services/service-automation/src/index.ts index b0808df628f..96aa8405848 100644 --- a/packages/services/service-automation/src/index.ts +++ b/packages/services/service-automation/src/index.ts @@ -78,6 +78,10 @@ export type { // barrel-reachable through that method, for a host composing its own // registry over the one package-scoped resolver. FlowNameResolver, + // [#31699] What `AutomationEngine.resolveConnectorInstance` and + // `resolveConnectorInstanceFor` answer: the instance a connector name + // addresses, by package. + ConnectorInstanceResolution, // [#28405] The reader `AutomationEngine.setFlowHistorySource` takes — // barrel-reachable through that method, for a host composing its own // metadata history. @@ -98,6 +102,8 @@ export type { MissedScheduledRun, MissedRunOutcome, } from './engine.js'; +// [#31699] Which instance a registration is: `AutomationEngine.registerConnector`'s `instance` argument. +export type { ConnectorInstanceOptions } from './plugin-extension-api.js'; // [#11997] ADR-0005 overlay precedence for same-named flow definitions. The boot // pull applies this; exported so a host that assembles its own flow list (or a diff --git a/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts b/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts index 42a065c20a5..1ad4d19ab95 100644 --- a/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts +++ b/packages/services/service-automation/src/oauth2-grant/grant-handle.test.ts @@ -332,16 +332,51 @@ describe('ADR-0143 D4 — authorization_code: refresh', () => { const idp = tokenEndpoint(); const { store } = fakeConnections([{ org: 'org_a', refreshToken: 'dummy-rt-a' }]); const handle = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, fetch: idp.fetch, now: () => 0 }); - handle.seed('org_a', 1, { accessToken: 'dummy-at-seeded', expiresAt: 3_600_000 }); + handle.seed('org_a', 1, { accessToken: 'dummy-at-seeded', expiresAt: 3_600_000 }, 'row_org_a'); expect((await handle.get({ organizationId: 'org_a' })).auth).toEqual({ type: 'bearer', token: 'dummy-at-seeded' }); expect(idp.state.requests).toHaveLength(0); // A seed under a stale revision is not served. - handle.seed('org_a', 0, { accessToken: 'dummy-at-stale', expiresAt: 3_600_000 }); + handle.seed('org_a', 0, { accessToken: 'dummy-at-stale', expiresAt: 3_600_000 }, 'row_org_a'); expect((await handle.get({ organizationId: 'org_a' })).auth).toEqual({ type: 'bearer', token: 'dummy-at-1' }); handle.forget('org_a'); await handle.get({ organizationId: 'org_a' }); expect(idp.state.requests).toHaveLength(2); }); + it('[#31699] a cached token is served only for the connection row it was obtained for, never another row at the same revision', async () => { + const idp = tokenEndpoint(); + const { store, held } = fakeConnections([{ org: 'org_a', refreshToken: 'dummy-rt-a' }]); + const handle = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, fetch: idp.fetch, now: () => 0 }); + // A seed for another row of the organization (another package's connection) is not served. + handle.seed('org_a', 1, { accessToken: 'dummy-at-other-row', expiresAt: 3_600_000 }, 'row_other'); + const first = (await handle.get({ organizationId: 'org_a' })).auth; + expect(first).not.toEqual({ type: 'bearer', token: 'dummy-at-other-row' }); + expect(idp.state.requests).toHaveLength(1); + // Warm: the same row at the same revision is served from the cache. + expect((await handle.get({ organizationId: 'org_a' })).auth).toEqual(first); + expect(idp.state.requests).toHaveLength(1); + // The read now chooses another row whose revision matches the cached one: refreshed, not served. + const row = held.get('org_a')!; + held.set('org_a', { ...row, id: 'row_b' }); + expect((await handle.get({ organizationId: 'org_a' })).auth).not.toEqual(first); + expect(idp.state.requests).toHaveLength(2); + }); + + it('[#31699] a read that joins a refresh in flight for another row of the organization is refused, never served that row\'s token', async () => { + const idp = tokenEndpoint(); + const { store, held } = fakeConnections([{ org: 'org_a', refreshToken: 'dummy-rt-a' }]); + const handle = createOAuth2GrantHandle({ connector: 'crm', config: AUTH_CODE, connections: store, fetch: idp.fetch, now: () => 0 }); + let release!: () => void; + idp.state.gate = new Promise((r) => { release = r; }); + const first = handle.get({ organizationId: 'org_a' }); + while (idp.state.requests.length === 0) await new Promise((r) => setTimeout(r, 0)); + // While row_org_a's refresh is out, the read chooses another row. + held.set('org_a', { ...held.get('org_a')!, id: 'row_b' }); + const second = handle.get({ organizationId: 'org_a' }); + release(); + await expect(first).resolves.toMatchObject({ auth: { type: 'bearer' } }); + await expect(second).rejects.toMatchObject({ status: 503 }); + expect(idp.state.requests).toHaveLength(1); + }); }); describe('ADR-0143 D2.1 — an MCP instance whose connection keeps the client its authorization flow found', () => { diff --git a/packages/services/service-automation/src/oauth2-grant/grant-handle.ts b/packages/services/service-automation/src/oauth2-grant/grant-handle.ts index 518fd0917c9..75223eb2570 100644 --- a/packages/services/service-automation/src/oauth2-grant/grant-handle.ts +++ b/packages/services/service-automation/src/oauth2-grant/grant-handle.ts @@ -84,9 +84,12 @@ export interface OAuth2GrantHandleDeps { /** * [#31699] The instance's package (`null`: the environment's or the * platform's instance): its connections are read by `(package, name)`. - * Absent, every connection of the name answers, as before. + * Absent, every connection of the name answers, as before. A function is + * asked on every read, so a package the instance's name resolves to + * (an unstamped entry's) is read as it is now, never as it was when the + * handle was made. */ - readonly packageId?: string | null; + readonly packageId?: string | null | (() => string | null); readonly config: OAuth2GrantConfig; /** The connection store (`authorization_code` only). */ readonly connections: ConnectorConnectionStore; @@ -106,8 +109,11 @@ export interface OAuth2GrantHandleDeps { /** The handle, plus what the connect door needs to hand it a token it just obtained. */ export interface OAuth2GrantHandle extends ConnectorCredentialHandle { - /** Keep the access token a completed connect obtained for `organizationId`, under the connection's `revision`. */ - seed(organizationId: string, revision: number, token: OAuth2TokenResponse): void; + /** + * Keep the access token a completed connect obtained for `organizationId`, + * under the connection's `revision` and [#31699] its row id (`rowId`). + */ + seed(organizationId: string, revision: number, token: OAuth2TokenResponse, rowId: string): void; /** Drop every cached access token (a revoke, a reconnect, the instance torn down). */ forget(organizationId?: string): void; } @@ -117,6 +123,14 @@ export const OAUTH2_REFRESH_LOCK_TTL_MS = 30_000; interface CachedToken { readonly revision: number; + /** + * [#31699] The id of the connection row the token was obtained for. A + * revision is per row and every row starts at 1, so a token is served only + * for its own row: never for another package's connection of the + * organization that a later read chose. A client_credentials token has + * no row. + */ + readonly rowId?: string; readonly accessToken: string; readonly expiresAt?: number; } @@ -233,6 +247,9 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran // authorization_code const cache = new Map(); + /** [#31699] The instance's package as it is at this read ({@link OAuth2GrantHandleDeps.packageId}). */ + const packageNow = (): string | null | undefined => + typeof deps.packageId === 'function' ? deps.packageId() : deps.packageId; const inflight = new Map>(); /** The connection a request dispatches with (D4, Q1 = A). */ @@ -241,9 +258,9 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran let record: ConnectorConnectionRecord | undefined; try { if (organizationId !== undefined) { - record = await deps.connections.read(organizationId, connector, deps.packageId); + record = await deps.connections.read(organizationId, connector, packageNow()); } else { - const all = await deps.connections.listFor(connector, deps.packageId); + const all = await deps.connections.listFor(connector, packageNow()); if (all.length > 1) { throw connectorCredentialRefusal( `connector instance '${connector}' is connected for ${all.length} organizations, and this dispatch carries ` @@ -323,7 +340,7 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran const refreshOnce = async (organizationId: string): Promise => { let current: ConnectorConnectionRecord | undefined; try { - current = await deps.connections.read(organizationId, connector, deps.packageId); + current = await deps.connections.read(organizationId, connector, packageNow()); } catch (err) { // [#31699] As `select` says it: a conflict is no transient fault, never a 409 out of the dispatch. if (err instanceof ConnectorConnectionConflictError) throw unavailable(err.message.replace(/\.$/, '')); @@ -371,6 +388,7 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran } const cached: CachedToken = { revision: token.refreshToken === undefined ? current.revision : current.revision + 1, + rowId: current.id, accessToken: token.accessToken, ...(token.expiresAt === undefined ? {} : { expiresAt: token.expiresAt }), }; @@ -402,22 +420,37 @@ export function createOAuth2GrantHandle(deps: OAuth2GrantHandleDeps): OAuth2Gran return flight; }; + /** + * [#31699] A refresh already in flight for the organization may be of + * another row than the one this read chose (the instance's package changed + * while it was out): its token is not this row's, so the dispatch is + * refused and the next one refreshes the row it chooses. + */ + const ownRow = (token: CachedToken, record: ConnectorConnectionRecord): CachedToken => { + if (token.rowId === record.id) return token; + throw unavailable(`the connection of connector instance '${connector}' for organization '${record.organizationId}' ` + + 'changed while it was being refreshed; the next dispatch uses the new one'); + }; + return { connector, async get(request) { const record = await select(request); const held = cache.get(record.organizationId); - if (fresh(held) && held.revision === record.revision) return toCredential(held); - return toCredential(await refreshFor(record.organizationId)); + if (fresh(held) && held.revision === record.revision && held.rowId === record.id) { + return toCredential(held); + } + return toCredential(ownRow(await refreshFor(record.organizationId), record)); }, async refresh(request) { const record = await select(request); cache.delete(record.organizationId); - return toCredential(await refreshFor(record.organizationId)); + return toCredential(ownRow(await refreshFor(record.organizationId), record)); }, - seed(organizationId, revision, token) { + seed(organizationId, revision, token, rowId) { cache.set(organizationId, { revision, + rowId, accessToken: token.accessToken, ...(token.expiresAt === undefined ? {} : { expiresAt: token.expiresAt }), }); diff --git a/packages/services/service-automation/src/plugin-extension-api.ts b/packages/services/service-automation/src/plugin-extension-api.ts index 8036803ed9c..19350c41dba 100644 --- a/packages/services/service-automation/src/plugin-extension-api.ts +++ b/packages/services/service-automation/src/plugin-extension-api.ts @@ -33,7 +33,8 @@ import { FLOW_RESERVED_NODE_TYPES, defineActionDescriptor, resolveFlowTriggerKin import type { Connector, ConnectorOrigin } from '@objectstack/spec/integration'; import { ConnectorSchema, isConnectorUpstreamChanged } from '@objectstack/spec/integration'; import { describeThrownForLog } from './thrown-cause-diagnostics.js'; -import type { AutomationEngine, ConnectorActionHandler, ConnectorHold, FlowTrigger, FlowTriggerBinding, NodeExecutor } from './engine.js'; +import type { AutomationEngine, ConnectorActionHandler, ConnectorHold, FlowTrigger, FlowTriggerBinding, NodeExecutor, RegisteredConnector } from './engine.js'; +import type { ConnectorInstances } from './connector-instances.js'; /** * The `AutomationEngine` members the moved bodies read, each typed as the class @@ -343,6 +344,7 @@ export function registerConnector( def: Connector, handlers: Record, origin: ConnectorOrigin, + instance: ConnectorInstanceOptions = {}, ): void { const parsed = ConnectorSchema.parse(def); for (const action of parsed.actions ?? []) { @@ -352,8 +354,11 @@ export function registerConnector( ); } } - this.assertSameOriginOrFree(parsed.name, origin); - this.connectors.set(parsed.name, { def: parsed, handlers, origin, state: 'ready' }); + const packageId = instance.packageId ?? null; + this.assertSameOriginOrFree(parsed.name, origin, packageId, instance.soleOfName === true); + placeInstance(this.connectors, parsed.name, packageId, origin, instance.soleOfName === true, { + def: parsed, handlers, origin, state: 'ready', + }); this.logger.info( `Connector registered: ${parsed.name} (${Object.keys(handlers).length} action handlers, origin: ${origin})`, ); @@ -367,10 +372,12 @@ export function registerDegradedConnector( origin: ConnectorOrigin, cause?: unknown, hold?: ConnectorHold, + instance: ConnectorInstanceOptions = {}, ): void { const parsed = ConnectorSchema.parse(def); - this.assertSameOriginOrFree(parsed.name, origin); - this.connectors.set(parsed.name, { + const packageId = instance.packageId ?? null; + this.assertSameOriginOrFree(parsed.name, origin, packageId, instance.soleOfName === true); + placeInstance(this.connectors, parsed.name, packageId, origin, instance.soleOfName === true, { def: parsed, handlers: {}, origin, @@ -410,9 +417,19 @@ export function describeHold(hold: ConnectorHold): string { } /** The body of {@link AutomationEngine.assertSameOriginOrFree}, moved unedited; that method's docblock is its contract. */ -export function assertSameOriginOrFree(this: Pick, name: string, origin: ConnectorOrigin): void { - const existing = this.connectors.get(name); - if (!existing) return; +export function assertSameOriginOrFree( + this: Pick, + name: string, + origin: ConnectorOrigin, + packageId: string | null = null, + soleOfName = false, +): void { + // [#31699] Two sources of truth are judged by NAME, whatever package each + // instance is of: a plugin's connector and a declarative instance never + // share a name. Two declarative instances of one name are two packages'. + const instances = this.connectors.ofName(name); + if (instances.length === 0) return; + const existing = instances.find((i) => i.registered.origin !== origin)?.registered ?? instances[0]!.registered; if (existing.origin !== origin) { const describe = (o: ConnectorOrigin) => o === 'plugin' @@ -425,7 +442,39 @@ export function assertSameOriginOrFree(this: Pick i.packageId === packageId)) this.logger.warn(`Connector '${name}' replaced`); +} + +/** + * [#31699] Where a registration lands: the instance of `(packageId, name)`, + * replaced in place. With `soleOfName`, every other instance of `name` of the + * same origin is dropped first: the declared-connector reconcile keeps one + * instance per name until the one-holder backstop narrows. + */ +function placeInstance( + connectors: ConnectorInstances, + name: string, + packageId: string | null, + origin: ConnectorOrigin, + soleOfName: boolean, + registered: RegisteredConnector, +): void { + if (soleOfName) { + for (const other of connectors.ofName(name)) { + if (other.packageId !== packageId && other.registered.origin === origin) connectors.delete(name, other.packageId); + } + } + connectors.set(name, packageId, registered); +} + +/** + * [#31699] Which instance a registration is: its package (`null`, the + * default: a plugin's connector, or an instance the environment authored), + * and whether it is to be the one instance of its name ({@link placeInstance}). + */ +export interface ConnectorInstanceOptions { + readonly packageId?: string | null; + readonly soleOfName?: boolean; } /** The body of {@link AutomationEngine.unregisterNodeExecutor}, moved unedited; that method's docblock is its contract. */ @@ -472,7 +521,12 @@ export function unregisterTrigger(this: Pick, name: string): void { - this.connectors.delete(name); +export function unregisterConnector( + this: Pick, + name: string, + packageId?: string | null, +): void { + // [#31699] `packageId` absent: every instance of the name, as before. + this.connectors.delete(name, packageId); this.logger.info(`Connector unregistered: ${name}`); } diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 6c3f5eb545c..eca939d7423 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -3354,7 +3354,13 @@ export class AutomationServicePlugin implements Plugin { ); continue; } - desired.set(bound.name, { entry: bound, signature: connectorInstanceSignature(bound) }); + // [#31699] The instance package joins the signature: an entry whose + // package moves (an unstamped entry's durable holder changing) is + // registered again under the new one, never left under the old. + desired.set(bound.name, { + entry: bound, + signature: `${connectorInstanceSignature(bound)}|package:${this.declaredInstance(ctx, bound).packageId ?? ''}`, + }); } // [#27237] Where each instance's `credentialRef` resolves from joins its @@ -3455,6 +3461,7 @@ export class AutomationServicePlugin implements Plugin { for (const name of [...this.degradedInstances.keys()]) { if (desired.has(name)) continue; this.degradedInstances.delete(name); + // [#31699] By name, as {@link dematerializeConnector} says why. try { engine.unregisterConnector(name); } catch { /* ignore */ } ctx.logger.info(`[Automation] dropped degraded connector instance '${name}' (no longer declared)`); } @@ -3919,6 +3926,7 @@ export class AutomationServicePlugin implements Plugin { def, withFailureTextRewritten(handlers, connectorReadWithheldText(entry)), 'declarative', + this.declaredInstance(ctx, entry), ); this.materializedConnectors.set(name, tracked); if (credentialHandle) this.grantHandles.set(name, credentialHandle); @@ -4027,6 +4035,8 @@ export class AutomationServicePlugin implements Plugin { info.reason, 'declarative', info.cause, + undefined, + this.declaredInstance(ctx, info.entry), ); } catch (err) { // Can't even register the husk (e.g. the entry's def no longer @@ -4096,6 +4106,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', info.cause, { kind: 'declaration' }, + this.declaredInstance(ctx, info.entry), ); } catch (err) { ctx.logger.warn( @@ -4171,7 +4182,9 @@ export class AutomationServicePlugin implements Plugin { // the client its administrator entered (`clientSource: 'installer'`). return createOAuth2GrantHandle({ connector: name, - packageId: connectorInstancePackage(connectorNameResolver(ctx), entry), + // [#31699] Asked on every read: an unstamped entry's package is the + // one its name resolves to now (red-line r3 note on 3a-ii). + packageId: () => connectorInstancePackage(connectorNameResolver(ctx), entry), config: { grant: auth.grant, ...(takesInstallerClient(auth) ? { clientSource: 'installer' as const } : {}), @@ -4258,7 +4271,10 @@ export class AutomationServicePlugin implements Plugin { this.degradedInstances.set(name, { attempts: 1, signature: info.signature, reason, held: true }); if (!info.hasLive) { try { - engine.registerDegradedConnector(this.buildDegradedHuskDef(name, info.entry), reason, 'declarative', info.cause, { kind: 'connection' }); + engine.registerDegradedConnector( + this.buildDegradedHuskDef(name, info.entry), reason, 'declarative', info.cause, { kind: 'connection' }, + this.declaredInstance(ctx, info.entry), + ); } catch (err) { ctx.logger.warn( `[Automation] could not register degraded husk for '${name}' — the instance stays absent from the ` @@ -4304,6 +4320,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', undefined, { kind: 'connection' }, + this.declaredInstance(ctx, info.entry), ); } catch (err) { ctx.logger.warn( @@ -4481,6 +4498,17 @@ export class AutomationServicePlugin implements Plugin { return { name, entry, packageId, auth, organizationId, userId }; } + /** + * [ADR-0150 D4, #31699] Which engine instance a declared entry is + * registered as: its instance package ({@link connectorInstancePackage}), + * the one the connection door and the dispatch address it by, and the one + * instance of its name (`soleOfName`), as the reconcile keeps them until + * the one-holder backstop narrows. + */ + private declaredInstance(ctx: PluginContext, entry: unknown): { packageId: string | null; soleOfName: true } { + return { packageId: connectorInstancePackage(connectorNameResolver(ctx), entry), soleOfName: true }; + } + /** * [ADR-0150 D3/D4, #31699; design review M6] Which declared instance the * connection door's name means, and its package. The resolver decides @@ -4868,7 +4896,7 @@ export class AutomationServicePlugin implements Plugin { }); // The access token the exchange answered serves the next dispatch; it is // never stored (D3). - this.grantHandles.get(name)?.seed(organizationId, record.revision, token); + this.grantHandles.get(name)?.seed(organizationId, record.revision, token, record.id); return this.describeConnection(name, organizationId, record); } @@ -5006,7 +5034,10 @@ export class AutomationServicePlugin implements Plugin { if (repeat) return; if (!hasLive) { try { - engine.registerDegradedConnector(this.buildDegradedHuskDef(info.name, info.entry), reason, 'declarative'); + engine.registerDegradedConnector( + this.buildDegradedHuskDef(info.name, info.entry), reason, 'declarative', undefined, undefined, + this.declaredInstance(ctx, info.entry), + ); } catch (err) { ctx.logger.warn( `[Automation] could not register degraded husk for '${info.name}' — the instance stays absent from the ` + @@ -5409,6 +5440,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', info.cause, held ? (stored ? { kind: 'credential', ref: stored.ref } : { kind: 'declaration' }) : undefined, + this.declaredInstance(ctx, info.entry), ); } catch (err) { ctx.logger.warn( @@ -5642,6 +5674,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, why = 'no longer declared', ): Promise { + // [#31699] By name: every instance of it, which is the one the + // reconcile keeps ({@link declaredInstance}'s `soleOfName`) whatever + // package it was registered under. Addressed by package once the + // reconcile's bookkeeping is keyed by instance. try { engine.unregisterConnector(name); } catch { /* ignore */ } if (tracked.close) { try { await tracked.close(); } catch { /* best-effort */ } From e7bb20846c6cf8b4f631deeedb4854be0086483b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:40:18 +0000 Subject: [PATCH 2/2] docs(changeset): the 3b changeset names the declarative registration with no instance argument, the empty token cache after re-materialization, and every answer that moves Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01L9qibzKCovWpJoMZD6U3NT --- .changeset/31699-connector-instance-by-package.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.changeset/31699-connector-instance-by-package.md b/.changeset/31699-connector-instance-by-package.md index 5afb5e7c0c2..c39fce048a2 100644 --- a/.changeset/31699-connector-instance-by-package.md +++ b/.changeset/31699-connector-instance-by-package.md @@ -4,7 +4,7 @@ feat(service-automation): the automation engine holds a connector instance by its package and name, and a dispatch addresses the one instance its caller's name resolves to (ADR-0150 D4, #31699) -Clause-②: yes (widening) — additive in-process surface only: `AutomationEngine` gains `resolveConnectorInstance`, `resolveConnectorInstanceFor` and `resolveConnectorActionInputSchema`; `registerConnector`, `registerDegradedConnector` and `unregisterConnector` take an optional instance (its package, and `soleOfName`); `resolveConnectorAction`, `resolveConnectorActionEffect`, `getConnectorOrigin`, `getConnectorDegradedReason` and `getConnectorDegradedHold` take an optional package; the barrel exports the types `ConnectorInstanceResolution` and `ConnectorInstanceOptions`. Dispatch answers change in one transitional state only (an unstamped entry whose name gains a second holder after boot), as an intended tightening (see "What answers differently" below). Every other dispatch, door and HTTP answer is as before: the declared-connector reconcile still keeps one instance per name (the one-holder backstop, its duplicate-name refusal, and `soleOfName` on every declarative registration), and a lookup by bare name answers that one instance. +Clause-②: yes (widening) — additive in-process surface only: `AutomationEngine` gains `resolveConnectorInstance`, `resolveConnectorInstanceFor` and `resolveConnectorActionInputSchema`; `registerConnector`, `registerDegradedConnector` and `unregisterConnector` take an optional instance (its package, and `soleOfName`); `resolveConnectorAction`, `resolveConnectorActionEffect`, `getConnectorOrigin`, `getConnectorDegradedReason` and `getConnectorDegradedHold` take an optional package; the barrel exports the types `ConnectorInstanceResolution` and `ConnectorInstanceOptions`. Dispatch answers change in one transitional state (an unstamped entry whose name gains a second holder after boot), as an intended tightening; the phase-1 one-holder refusal keeps a supported install out of that state, since it refuses a second holder at install and at package registration. Three smaller answers move too, each listed under "What answers differently" below: a dispatch that joins a refresh in flight for another connection row is refused 503 once, the store's two-holder refusal names a different remedy, and a re-registered instance moves to the end of the connector list. Every other dispatch, door and HTTP answer is as before: the declared-connector reconcile still keeps one instance per name (the one-holder backstop, its duplicate-name refusal, and `soleOfName` on every declarative registration), and a lookup by bare name answers that one instance. Metadata-protocol: none Skills-docs: none — nothing a skill or a docs page teaches changes while one instance per name is kept; the two-holder connector docs come with the PR that narrows the backstop. @@ -29,7 +29,7 @@ Part of #31699 (ADR-0150 child B, PR 3b). PR 3a-ii made the connection store, th **What answers differently.** -- An unstamped (or compatibility-default) declared entry whose name gains a second durable holder: its dispatch was answered with the connection of the package that held the name at boot (200) until a restart. It is now read under the package the name resolves to at that moment, which is no one package, so it is refused 503 (no connection of its own): under two holders a row is its own package's only (PR 3a-ii's store rule), as the connection door already refuses that name (409). It is recovered by stamping the entry or by uninstalling the second holder. A holder that is uninstalled or replaced, leaving one holder, changes no answer: every row of the name still answers the one instance, and the next reconcile registers the instance again under the package it resolves to now (any provider-bound instance is re-materialized on such a change). +- An unstamped (or compatibility-default) declared entry whose name gains a second durable holder: its dispatch was answered with the connection of the package that held the name at boot (200) until a restart. It is now read under the package the name resolves to at that moment, which is no one package, so it is refused 503 (no connection of its own): under two holders a row is its own package's only (PR 3a-ii's store rule), as the connection door already refuses that name (409). It is recovered by stamping the entry or by uninstalling the second holder. A holder that is uninstalled or replaced, leaving one holder, changes no answer: every row of the name still answers the one instance, and the next reconcile registers the instance again under the package it resolves to now (any provider-bound instance is re-materialized on such a change). A re-materialized OAuth2 instance starts with a new grant handle whose access-token cache is empty, so a connection with no refresh token reads `reconnect_required` at its next dispatch, as after a restart. - A dispatch that joins an access-token refresh already in flight for another connection row of the organization (the instance's package changed while the refresh was out) is refused 503, never served that row's token; the next dispatch refreshes its own row. - The store's refusal of a row of a two-holder name that names none of the holders now names the remedy that works for it: `os migrate stored-references bind` for a row naming no package, and uninstalling one of the holders for a row already naming another package, which the bind refuses (PR 3a-ii contract review N4). - On a change of holder, the instance is re-registered, so its name moves to the end of `getRegisteredConnectors()` and `GET /automation/connectors`. @@ -40,6 +40,6 @@ Part of #31699 (ADR-0150 child B, PR 3b). PR 3a-ii made the connection store, th - The connector pull keeps reading its connector by bare name (the one instance): whether a mapping's connector is resolved for the job's package, and refused where that name is refused, changes an answer and is decided with the narrowing. - The resolved-holder fallback above (a resolved holder with no registered instance answered by the one instance of the name) is right only while one instance per name is kept; with two instances alive the narrowing PR makes it `none`. - `ConnectorDescriptor.packageId`, the addressed connection door (`?package=`), connector into the namespace-scoped type sets, and the backstop itself. -- `registerConnector(def, handlers, 'declarative', { packageId })` without `soleOfName` is public and keeps two instances of one name side by side (the engine tests use it). Nothing in-tree registers so outside the tests; the reconcile always passes `soleOfName`. +- `registerConnector(def, handlers, 'declarative', { packageId })` without `soleOfName` is public and keeps two instances of one name side by side (the engine tests use it). So does `registerConnector(def, handlers, 'declarative')` with no instance argument over a name the reconcile holds under a package: it is registered under no package beside that instance instead of replacing it, and a bare-name read answers neither until the next reconcile. Nothing in-tree registers either way outside the tests; the reconcile always passes the instance with `soleOfName`. -**In-process APIs.** Listed under Clause-② above. All additive; every new parameter is optional and its absence answers as before. +**In-process APIs.** Listed under Clause-② above. All additive; every new parameter is optional and its absence answers as before, except the declarative registration with no instance argument named in the list above.