diff --git a/.changeset/31699-connector-names-per-namespace.md b/.changeset/31699-connector-names-per-namespace.md new file mode 100644 index 00000000000..1686e02517a --- /dev/null +++ b/.changeset/31699-connector-names-per-namespace.md @@ -0,0 +1,29 @@ +--- +'@objectstack/core': minor +'@objectstack/objectql': minor +'@objectstack/metadata': minor +'@objectstack/metadata-protocol': patch +'@objectstack/spec': minor +'@objectstack/service-automation': minor +'@objectstack/runtime': minor +--- + +feat(service-automation)!: two packages of two namespaces may each declare a connector of the same name, each is materialized, connected and dispatched as its own instance, and a flow, a pull and the connection door address one by package (ADR-0150 child B, connector, the narrowing) + +Clause-②: yes (narrowing) — ten answers move for a caller that worked before. (1) The install door, `registerItem` and the cold-boot seal admit a package declaring a connector name a package of another namespace holds, FROM `422 PLUGIN_REGISTER_FAILED` naming both (a sealed boot clash warned) TO admitted; `os migrate stored-references` lists no sealed clash for it. (2) The boot of two packages' provider-bound instances of one name (the sealed clash), FROM refused naming both (`connector instance 'NAME' is not materialized`, fatal for the host's boot) TO each materialized under its package, whatever their namespaces: a pair the install door still refuses (one namespace, or a package with no namespace), which a code boot only warns about, is materialized too, and is connectable only in process (`ConnectorConnectionRequest.package`), since the namespace door answers `409` for both. (3) The bare `GET /meta/connector/NAME` of a name two packages hold is refused `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, naming both), where it served the first registered package's declaration, and `MetadataManager` keeps a slot per `(package, name)` for a connector (`PACKAGE_SLOTTED_STORE_TYPES`), so its bare read of such a name is refused and its unscoped plural reads answer both, where the second package's item overwrote the first's. The history and rollback doors (#33193) read the same list (`PACKAGE_SLOTTED_METADATA_TYPES`, `@objectstack/spec`, which `connector` joins): a connector's `?package=` there, FROM refused `400`, TO the addressed holder's versions; a bare connector name two packages hold, or one package's row beside the environment's (the rule every per-package type keeps), FROM served, TO refused `409` naming both. (4) A bare connector read on a metadata engine that cannot read by package is refused `501` (the protocol's fail-closed read for a narrowed type), where it served the engine's `getItem`. (5) A `connector_action` in a flow with no package (an environment-authored flow) naming a connector two packages hold, FROM not dispatched as "not registered" (`none`), or, where each holder declares only a catalog entry beside a connector a plugin registers in code under the name, dispatched to the plugin's connector, TO refused naming both. (6) A flow whose connector name resolves to a package with no live instance of it (a catalog entry, or an instance the reconcile has not registered yet), FROM dispatched to the one instance of the name (3b's fallback arm) TO not dispatched, unless the one instance is a connector a plugin registers in code, which is served as before. (7) A name only disabled packages hold, whose instance is still registered, FROM dispatched to it TO not dispatched for a caller outside those packages (a flow of the disabled package itself still reads its own instance, as before). A disabled package's own entry is removed by the next reconcile; an entry with no package of its own over such a name stays that package's instance, and is not dispatched until the package is enabled again. (8) A connector pull resolves `connectorSource.connector` from the package that holds the mapping: a name that resolves to no single instance, FROM `400 connector_not_registered` (two instances) TO `409 connector_name_refused` naming every candidate; a name that resolves to a package with no instance, FROM pulled through the one instance of the name TO `400 connector_not_registered`. (9) A declared entry with no package of its own (unstamped, or the environment's stored row) under a name two packages hold, FROM the whole name refused TO this entry alone refused naming both, and each package's own instance materialized. (10) Two declared entries of one name in a composition with no package-scoped registry are refused with a sentence that says why (one instance per name where nothing can tell two packages apart), where the duplicate sentence named the package of one of them. Widened beside them: `ConnectorConnectionRequest.package` and `ConnectorDescriptor.packageId` (`@objectstack/spec`, both optional); the namespace connection door `/api/v1/automation/connectors/:ns/:name/connection`, which answered `409` naming both for a name two packages hold, connects, reads and revokes the instance of the addressed namespace's package; `GET /api/v1/automation/connectors` lists every instance, each with its `packageId`; the connector credential listing names each package's instance with its own state. +Metadata-protocol: added + + + +**BREAKING** for the callers in (3) to (8). A deployment that held one connector name under two packages (sealed at boot with a warning, its boot refused) now boots both: read each declaration by its package (`?package=ID`, or `/meta/connector/NS/NAME`), connect each at its namespace address, and have an environment-authored flow name a connector one package holds. A flow that dispatched through 3b's fallback arm (6) dispatches once its own package's instance is materialized. A pull whose mapping no package holds, naming a connector two packages hold, names a mapping in one of the packages. Nothing in the workspace dispatches through (6) or (7) in a supported state: the reconcile registers a package's instance under its package, and drops a disabled package's own entry on its next run. An entry with no package of its own over a name only a disabled package holds is not dispatched while that package is disabled (7). + +The bare-name one-holder rule (`bare-name-one-holder.ts`) has narrowed for `connector`, the last covered type, from one package holder per deployment to one per namespace (ADR-0150 D2, D9): `connector` joins `NAMESPACE_SCOPED_BARE_NAME_TYPES` (`@objectstack/core`), `PACKAGE_SCOPED_READ_TYPES` (`@objectstack/objectql`) and `PACKAGE_SLOTTED_STORE_TYPES` (`@objectstack/metadata`). Still refused, with the same envelope and sentence: a co-owner of the holder's namespace, a package that declares no namespace beside any other holder, and two packages of one shareable namespace. + +- **The reconcile** (`plugin.ts`): the one-holder backstop (`refusedDeclaredConnectorNames`, and `refusedConnectorNames` in `connector-package-scope.ts`) is gone. Each provider-bound entry is the instance of its own package; an entry with no package of its own is the instance of the package its name resolves to over every holder, a disabled one included (the durable judgment), and under two holders it is refused naming both, never registered as either. Its bookkeeping (desired, materialized, degraded, credential-refusal, retry, dematerialize) and the OAuth2 grant handles are keyed by instance (`connectorInstanceKey`: the name, or `PACKAGE/NAME`), so two packages' instances of one name are materialized, degraded, retried and connected each on its own. A name repeated within one package is refused as a duplicate, naming the package. A composition with no package-scoped registry keeps one instance per name (red line 1: nothing there can tell two packages apart). A reloaded artifact supersedes the registry's entries by `(package, name)` (an unstamped item is its manifest's), so a reload of one package leaves another package's instance of the name live (an artifact with no manifest id, or a composition with no package-scoped registry, still supersedes by name, as before); the inert-descriptor audit and the credential listing judge each entry by its own instance. +- **Dispatch** (`engine.ts`, `resolveConnectorInstanceFor`): every caller asks the resolver over the served holders, a caller with no package included. `refused` is said with the resolver's message; `resolved` addresses exactly the holder's instance, and with none registered under it, the connector a plugin registers in code under the name (ADR-0097 §4: a plugin's connector and a declarative instance never share a name), else nothing. A name only disabled packages hold answers the same way (#31699 notes 6816295828 and 6820178514: resolve and count over the served set; a disabled package's instance is never served). A name the registry holds nothing under, or a host with no resolver, is answered by the one instance of the name, as before. +- **The pull** (`connector-pull.ts`): the mapping's connector is resolved from the mapping's holder package (an environment mapping: as a caller with no package) through the registry's `resolveConnectorInstanceFor`, and its origin, degraded state, provider, action and `inputSchema` are read from that instance. A registry without the member is read by the bare name, as before. New refusal reason `connector_name_refused`. +- **The connection door**: `ConnectorConnectionRequest.package` names the instance; the runtime's namespace address admits a connector name two packages hold to the addressed holder (`admitAutomationAddress` answers a slot for a connector as it does for a flow) and passes the package. The bare door keeps its `409` naming both. A callback completes the package its begin recorded, as before. +- **Descriptors**: `ConnectorDescriptor.packageId` is set for an instance a package holds; the credential listing matches each declaring entry to its own instance. +- **#33218 review N6** (judged, pinned): a connection row a moved declaration left stamped with its old package, once that package declares the name again beside the new holder, is that package's own again and the new holder has none. The row is not restamped: its token was obtained for the old package's connect. + +One holder: every answer is as before except (6), (7), and an unstamped entry whose holder is replaced, which is not dispatched between the change and the next reconcile (FROM the instance registered under the replaced package). diff --git a/content/docs/automation/connectors.mdx b/content/docs/automation/connectors.mdx index a726ee031cd..8aa55d776c4 100644 --- a/content/docs/automation/connectors.mdx +++ b/content/docs/automation/connectors.mdx @@ -759,8 +759,10 @@ a rotating refresh token is never spent twice. an instance the environment authored or a plugin registers); it is not a sign-in account, and signing in never touches it. A callback completes the instance its connect was begun for, never the name read - again, and the connect door refuses with `409` a name two packages hold - rather than pick one. A run dispatches + again, and the bare connect door refuses with `409` a name two packages hold + rather than pick one: connect each package's instance at its namespace + address, `/api/v1/automation/connectors/NS/NAME/connection` (see + [Two packages, one connector name](#two-packages-one-connector-name)). A run dispatches with its own organization's connection; a run with no organization uses the instance's only connection, and is refused when there are several. When the grant stops working, the connection is marked **reconnect required** and the @@ -935,6 +937,45 @@ A materialized instance is dispatched exactly like any other connector — by See [Flows](/docs/automation/flows) for the node reference and how outputs flow into downstream nodes. +### Two packages, one connector name + +Two packages that declare **different namespaces** may each declare a +connector of the same `name`. Each is its own instance, held by its package +and name: each is materialized, connected, credentialed and listed on its own +(`GET /api/v1/automation/connectors` lists both, each descriptor carrying its +`packageId`). Two packages of **one** namespace still may not, nor a package +that declares no namespace beside another holder: the install is refused, +naming both, as before. A deployment that already holds such a pair (code +packages a boot only warns about) materializes each instance under its +package, but no HTTP address tells them apart: the namespace door answers +`409` for both. Give one of them its own namespace. + +A bare name is resolved for whoever names it, and never picked between two +holders: + +| Who names the connector | Which instance it means | +|:---|:---| +| A flow's `connector_action` (`connectorId`) | The flow's own package's instance, else the one holder in the package's declared dependencies; refused, naming every candidate, when its reach holds two or holds it only outside | +| A flow the environment authored | The environment's own instance, else the one package holder; refused, naming both, when two packages hold it | +| A connector pull (`mapping.connectorSource.connector`) | Resolved as a flow is, from the package that holds the mapping (an environment mapping: as the environment's flow). A refused name fails the pull `409` (`connector_name_refused`); a name that resolves to a package with no live instance is `connector_not_registered`, never another package's instance | +| The connection door, `/api/v1/automation/connectors/NAME/connection` | The one holder of the name; `409` naming both when two packages hold it | +| The connection door at the namespace address, `/api/v1/automation/connectors/NS/NAME/connection` | The instance of the package of namespace `NS`: connect, read and revoke each package's connection there | +| `GET /api/v1/meta/connector/NAME` | `409` naming both when two packages hold it; read each with `?package=ID` or `/meta/connector/NS/NAME` | + +Each package's instance has its own connection per organization: connecting +one leaves the other's untouched, and revoking one leaves the other serving. + +A connector a plugin registers in code is no package's: it is dispatched by +its name as before. A package may still declare a catalog descriptor of that +name (an entry without a `provider`); the package's flows are then served the +plugin's connector. + +A disabled package holds no name for anyone else: its instance is not served +to a caller outside the package, even before the next reconcile removes it. A +flow of the disabled package itself still reads its own instance. An entry +with no package of its own over a name only a disabled package holds is that +package's instance, and is not dispatched until the package is enabled again. + ## Failure modes at a glance Boot distinguishes **configuration faults** (your entry is wrong — fail loud, @@ -954,6 +995,8 @@ retry): | A response to an `alipay-v3` call is unsigned (below status 400) or its signature does not verify | The dispatch **fails** naming the instance and the status; the response's body is never returned | | The upstream refuses the credential (`401` / `403`), or an `mcp` server sent a static credential does not list a tool the instance's `include` names | **Not fatal**: the instance registers **degraded**. A stored credential is marked `rejected` and waits until it is set again (or a restart); an environment or vault credential is retried on the backoff | | Instance `name` collides with a plugin-registered connector | **Hard boot error** — there is no silent precedence between the two worlds | +| Two entries of one package share a `name` | **Hard boot error** naming the name and the package (a stored entry is logged and skipped): a name is unique within a package | +| An entry with no package of its own (one the environment stored, or an unstamped one) shares a `name` two packages hold | **Not materialized**, refused naming both holders, since which package's instance it would be cannot be told: a host's own entry fails the boot, a stored or installed one is logged and skipped. Declare it in one of the packages, or under another name | | stdio transport without host opt-in | **Hard boot error** with the `declarativeStdio` fix inline — a security rejection is never retried | | An entry of an **installed** package (`os package install`, `POST /api/v1/marketplace/install-local`) names a package-relative file — an `openapi` `spec` path — or needs a location inside its package, as a stdio `mcp` transport's working directory does | Configuration fault, **never resolved against the host's directory**: an installed package has no directory on the runtime it was installed into, and the host's is not its own. The instance is not materialized, and the reconcile's error names the entry, its package and the ref. Rebuild the package with a current `os build`, which carries an `openapi` spec file into the artifact, or inline the document; reach an MCP server from an installed package over `http`. Whether an entry is the host's is read from what the install recorded, never from the package's own words: an entry carrying a `_packageId` other than its own package's is refused at the install, every member of a `packages[]` bundle is recorded as installed whatever its `source` says, and an entry naming a package no registration records is refused its ref too. The host's own entries keep reading their files | | A **stored** entry — one saved in this environment through the metadata door (`PUT /api/v1/meta/connector/:name`, Studio), environment-wide or in a package created here (`POST /api/v1/packages`) — names a package-relative file or needs a location inside a package | Configuration fault, **never resolved against the host's directory**: a stored definition is no package's declaration and has no directory on disk. The instance is not materialized, and the reconcile's error names the entry, its package if it has one, and the ref. This one is never fatal, even at boot: a stored row at rest is logged and skipped, and the platform starts. Carry the document inline in the definition, or name it by an `http(s)` URL; reach an MCP server from a stored entry over `http`. Only what the host's own stack declares reads its files: a stored row is never read as the host's, whatever `_packageId` its body carries | diff --git a/packages/cli/src/commands/migrate/stored-references.integration.test.ts b/packages/cli/src/commands/migrate/stored-references.integration.test.ts index b4ae84406ba..054858d2277 100644 --- a/packages/cli/src/commands/migrate/stored-references.integration.test.ts +++ b/packages/cli/src/commands/migrate/stored-references.integration.test.ts @@ -23,8 +23,9 @@ * and one tool name, which the one-holder rule no longer calls a clash * (#31701, #31697, #31699, #31985; ADR-0150 D2/D9), so the sealed-clash * section never lists them; nor the picklist `m31693_tone` they both declare - * (#31700). The clash the seal still records is the connector `m31693_link` - * both declare: a connector name is held once per deployment. + * (#31700); nor, since the connector narrowed last (#31699 PR 3), the + * connector `m31693_link` both declare. Two holders of different namespaces + * are no clash for any covered type now, so the section is empty. * * Over a database an older release left: two managed `sys_sharing_rule` rows * naming `m31693_share` (two holders: ambiguous) and `m31693_only_a` (one @@ -95,7 +96,7 @@ const rule = (name: string) => ({ accessLevel: 'read', sharedWith: { type: 'user', value: 'u1' }, active: true, }); const list = (name: string) => ({ name, label: name, options: [{ label: 'One', value: 'one' }] }); -/** The connector A and B both declare: a connector name is still held once per deployment, the sealed clash. */ +/** The connector A and B both declare, in their own namespaces: no clash since #31699 PR 3 (it was the sealed clash). */ const link = (tag: string) => ({ name: 'm31693_link', label: `${tag} link`, type: 'api', description: `${tag} link`, enabled: false }); /** The agent, the skill (#31701), the object-less action (#31697), the email template (#31699) and the tool (#31985) A and B both declare, in their own namespaces. */ const ai = (tag: string) => ({ @@ -341,10 +342,11 @@ describe('os migrate stored-references (the report)', () => { d8: 'R17', object: 'm31693a_task', field: 'hue', packageId: A, name: 'm31693_hue', reason: 'outside-closure', candidates: [{ holder: 'package', packageId: C, address: 'm31693c/m31693_hue' }], }]); - // [#31701, #31697, #31699, #31700, #31985] Only the connector: never the - // agent, the skill, the object-less action, the email template, the - // picklist and the tool A and B hold in two namespaces. - expect(payload.sealedClashes).toEqual([{ type: 'connector', name: 'm31693_link', candidates: [`package "${A}"`, `package "${B}"`] }]); + // [#31701, #31697, #31699, #31700, #31985] Never the agent, the skill, the + // object-less action, the email template, the picklist and the tool A and + // B hold in two namespaces; [#31699 PR 3] nor the connector (FROM: the + // one sealed clash, naming both). + expect(payload.sealedClashes).toEqual([]); // The served platform carries no automation or approvals table here: named, not silently skipped. expect(payload.tablesNotCarried).toEqual(expect.arrayContaining(['sys_automation_run', 'sys_flow_credential', 'sys_approval_request'])); }, CASE_TIMEOUT_MS); diff --git a/packages/cloud-connection/src/marketplace-install-local-bare-name-conflict.test.ts b/packages/cloud-connection/src/marketplace-install-local-bare-name-conflict.test.ts index 485514c7a83..a090fa0f2c0 100644 --- a/packages/cloud-connection/src/marketplace-install-local-bare-name-conflict.test.ts +++ b/packages/cloud-connection/src/marketplace-install-local-bare-name-conflict.test.ts @@ -32,12 +32,18 @@ * ## What these cases pin * * - a fresh cloud-fetched install and a cloud-fetched upgrade, each declaring - * a connector name another package holds: `422 PLUGIN_REGISTER_FAILED` in - * the declared envelope, both holders and the rename named, the registry - * and the ledger exactly as before the call, the holder's items still the - * holder's. [#31696] These cases declared a flow name until the flow's - * one-holder rule narrowed to the namespace (ADR-0150 D9); the connector - * keeps one package holder per name, so it carries the refusal now; + * a connector name another package of the SAME namespace holds (a + * co-owner, admitted to the namespace by its dependency on the holder): + * `422 PLUGIN_REGISTER_FAILED` in the declared envelope, both holders and + * the rename named, the registry and the ledger exactly as before the + * call, the holder's items still the holder's. [#31696] These cases + * declared a flow name until the flow's one-holder rule narrowed to the + * namespace (ADR-0150 D9); [#31699] the connector, the last covered type, + * narrowed too, so the refusal is now a co-owner's; + * - [#31699] the same move for a connector (Clause-② yes (narrowing)): a + * cloud-fetched install declaring a connector name another namespace's + * package holds now installs, each package's connector its own, and a + * by-name read that names no package refused naming both; * - [#31696] the answer that moved, FROM → TO (Clause-② yes (narrowing)): a * cloud-fetched install declaring a flow name another namespace's package * holds was refused `422` naming both; it now installs, `200` and @@ -90,7 +96,7 @@ const CLOUD_URL = 'http://cloud.test'; const HOLDER_ID = 'com.acme.dispatch'; /** The package the cloud-fetched install asks for. */ const INCOMING_ID = 'com.acme.routing'; -/** The connector name both declare: one package holder per name (#30803). */ +/** The connector name both declare: one holder per namespace since #31699 (one per deployment under #30803). */ const HELD_CONN = 'technician_api'; /** [#31696] The flow name both declare: scoped to the namespace, so each package holds its own. */ const SHARED_FLOW = 'assign_technician'; @@ -256,14 +262,23 @@ function expectBareNameRefusal(res: any) { expect(res.payload.error.message).toContain(`package "${INCOMING_ID}"`); expect(res.payload.error.message).toContain(`package "${HOLDER_ID}"`); expect(res.payload.error.message).toContain(`"${HELD_CONN}"`); - expect(res.payload.error.message).toContain(`"routing_${HELD_CONN}"`); + // [#31699] The co-owner's namespace is the holder's, so the rename carries it. + expect(res.payload.error.message).toContain(`"dispatch_${HELD_CONN}"`); } +/** [#31699] The holder's namespace, shared through a dependency on the holder: a co-owner. */ +const CO_OWNER: Bag = { namespace: 'dispatch', dependencies: { [HOLDER_ID]: '^1.0.0' } }; + describe('install-local cloud branch refuses a package declaring a bare name another package holds, before any write', () => { const versions = { 'v1-free': packageVersion(INCOMING_ID, '1.0.0', [FREE_FLOW]), - 'v1-held': packageVersion(INCOMING_ID, '1.0.0', [FREE_FLOW], { connectors: [connector(HELD_CONN, 'routing')] }), - 'v2-held': packageVersion(INCOMING_ID, '2.0.0', [FREE_FLOW], { connectors: [connector(HELD_CONN, 'routing')] }), + // [#31699] Every covered type has narrowed to the namespace, so the + // refusal is a co-owner's: the incoming package shares the holder's + // namespace (allowed by its dependency on the holder) and declares the + // holder's connector name. + 'v1-held': packageVersion(INCOMING_ID, '1.0.0', [FREE_FLOW], { ...CO_OWNER, connectors: [connector(HELD_CONN, 'routing')] }), + 'v2-held': packageVersion(INCOMING_ID, '2.0.0', [FREE_FLOW], { ...CO_OWNER, connectors: [connector(HELD_CONN, 'routing')] }), + 'v1-other-ns-conn': packageVersion(INCOMING_ID, '1.0.0', [FREE_FLOW], { connectors: [connector(HELD_CONN, 'routing')] }), 'v1-shared-flow': packageVersion(INCOMING_ID, '1.0.0', [SHARED_FLOW]), }; @@ -358,6 +373,26 @@ describe('install-local cloud branch refuses a package declaring a bare name ano expect(String((refusal as Error | undefined)?.message)).toContain(INCOMING_ID); expect(ql.registry.getItem('connector', HELD_CONN)?.label).toBe('dispatch connector'); }); + + it('[#31699] a connector name another namespace\'s package holds installs: 200, hot-loaded, each holder\'s connector its own, a bare read refused naming both', async () => { + serveVersions(versions); + const { ql, installFromCloud, installHolder } = await bootPlugin(); + await installHolder(); + + const res = await installFromCloud('v1-other-ns-conn'); + + // FROM `422 PLUGIN_REGISTER_FAILED` naming both holders, TO installed. + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(res.payload.data.hotLoaded).toBe(true); + expect(res.payload.data.hotLoadError).toBeUndefined(); + expect(ledger().incoming?.version).toBe('1.0.0'); + expect(ql.registry.resolveItem('connector', HELD_CONN, HOLDER_ID)?.label).toBe('dispatch connector'); + expect(ql.registry.resolveItem('connector', HELD_CONN, INCOMING_ID)?.label).toBe('routing connector'); + let refusal: unknown; + try { ql.registry.resolveItem('connector', HELD_CONN); } catch (e) { refusal = e; } + expect(String((refusal as Error | undefined)?.message)).toContain(HOLDER_ID); + expect(String((refusal as Error | undefined)?.message)).toContain(INCOMING_ID); + }); }); describe('install-local cloud branch refuses a package whose namespace another package owns, before any write (#31392)', () => { diff --git a/packages/core/src/package-scoped-resolution.test.ts b/packages/core/src/package-scoped-resolution.test.ts index 08798c20757..9e09580383b 100644 --- a/packages/core/src/package-scoped-resolution.test.ts +++ b/packages/core/src/package-scoped-resolution.test.ts @@ -277,10 +277,10 @@ describe('the types narrowed to the namespace (ADR-0150 D2/D9)', () => { expect(isPackageScopedType(type), type).toBe(type !== ENGINE_FUNCTION_TYPE); expect(isNamespaceScopedBareNameType(type), type).toBe(true); } - // [#31696, #31699 PR 2] The flow and the webhook have narrowed (they are in the set above); a connector has not. + // [#31696, #31699 PR 2, #31699 PR 3] The flow, the webhook and the connector have narrowed (they are in the set above). expect(isNamespaceScopedBareNameType('flow')).toBe(true); expect(isNamespaceScopedBareNameType('webhook')).toBe(true); - expect(isNamespaceScopedBareNameType('connector')).toBe(false); + expect(isNamespaceScopedBareNameType('connector')).toBe(true); expect(isNamespaceScopedBareNameType(undefined)).toBe(false); }); diff --git a/packages/core/src/package-scoped-resolution.ts b/packages/core/src/package-scoped-resolution.ts index 535cc91c77f..d15d2ffdb46 100644 --- a/packages/core/src/package-scoped-resolution.ts +++ b/packages/core/src/package-scoped-resolution.ts @@ -138,8 +138,12 @@ export function isBareNameOneHolderType(type: unknown): type is BareNameOneHolde * name by package), then the picklist family (#31700): `picklist`, * `mapping` and `dataset`, the `api` and the engine's `function` registry, * then `webhook` (#31699 PR 2), and `tool` beside the AI family (#31985), - * whose one by-name reader (`/meta/tool/NAME`) resolves by package. A type - * not listed here keeps one package holder per deployment. + * whose one by-name reader (`/meta/tool/NAME`) resolves by package, and + * last `connector` (#31699 PR 3: the automation engine holds an instance per + * `(package, name)`, and a flow, a connector pull and the connection door + * address one by package). Every covered type is listed now; a type joining + * {@link BARE_NAME_ONE_HOLDER_TYPES} later keeps one package holder per + * deployment until its own narrowing lists it here. * * Every member but {@link ENGINE_FUNCTION_TYPE} is a metadata type ADR-0150 * addresses by package ({@link PACKAGE_SCOPED_TYPES}). The function registry @@ -169,6 +173,8 @@ export const NAMESPACE_SCOPED_BARE_NAME_TYPES: readonly BareNameOneHolderType[] 'function', // #31699 PR 2 'webhook', + // #31699 PR 3 (the narrowing PR) + 'connector', ]); /** Has `type`'s one-holder rule narrowed to the namespace ({@link NAMESPACE_SCOPED_BARE_NAME_TYPES})? */ diff --git a/packages/metadata-protocol/src/no-package-scoped-reads.testkit.ts b/packages/metadata-protocol/src/no-package-scoped-reads.testkit.ts index ea11dee0ab0..9779452787b 100644 --- a/packages/metadata-protocol/src/no-package-scoped-reads.testkit.ts +++ b/packages/metadata-protocol/src/no-package-scoped-reads.testkit.ts @@ -23,9 +23,13 @@ * (`readsByPackage`): its bare read goes through `resolveItem`, which here is * the double's own `getItem` read (nothing, for a double with none), as the * registry's resolver answers a name one holder (or none) holds. + * + * [#31699 PR 3] `connector` is read the same way once its one-holder rule + * narrows to the namespace: `SchemaRegistry` reads it by package too, so a + * double that pins a connector read answers it through its own `getItem`. */ export const NO_PACKAGE_SCOPED_READS = Object.freeze({ - readsByPackage: (type: string): boolean => type === 'flow', + readsByPackage: (type: string): boolean => type === 'flow' || type === 'connector', resolveItem(this: { getItem?(type: string, name: string, packageId?: string, member?: string): unknown }, type: string, name: string, callerPackageId?: string | null, member?: string): unknown { return typeof this.getItem === 'function' ? this.getItem(type, name, callerPackageId ?? undefined, member) : undefined; diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index afa7b7724b8..dd3ae9cf72c 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -2124,7 +2124,7 @@ describe('[#32791] a stored package-less row the boot pass files under the host\ const BETA = 'com.beta.app'; const HOST = 'com.host.app'; const UNBUNDLED = [...PACKAGE_SLOTTED_STORE_TYPES].filter((type) => !isBundledStoreType(type)); - /** [#31699 PR 2] The unbundled slotted types the boot pass reads: every one but `webhook`, which the registry the pass walks does not list. */ + /** [#31699 PR 2, PR 3] The unbundled slotted types the boot pass reads: every one but `webhook` and `connector`, which the registry the pass walks does not list. */ const BOOT_PASS_READS = UNBUNDLED.filter((type) => DEFAULT_METADATA_TYPE_REGISTRY.some((entry) => entry.type === type)); let driver: IDataDriver; @@ -2488,28 +2488,29 @@ describe('[#32791] a stored package-less row the boot pass files under the host\ /** * [#31699 PR 2] `webhook` is slotted, but the pass registers none of its - * rows (`DEFAULT_METADATA_TYPE_REGISTRY` lists no `webhook`), so the case + * rows (`DEFAULT_METADATA_TYPE_REGISTRY` lists no `webhook`; nor any + * `connector`, slotted since #31699 PR 3), so the case * above, which asks for the row the pass registered, does not hold for it. * Its bare read is the loader's own: the package's row, in either save * order, on every host. FROM (`webhook` out of `PACKAGE_SLOTTED_STORE_TYPES`, * as on main): the row saved first, so `ALPHA` when the package-less row * was saved last and the package-less row when it was saved first. */ - it('CONTROL webhook, slotted but not a type the pass reads, one package\'s row and a package-less row: the pass registers neither, and the bare read answers the package\'s row in either save order on every host (FROM the row saved first)', async () => { - expect(BOOT_PASS_READS).toEqual(UNBUNDLED.filter((type) => type !== 'webhook')); + it.each(['webhook', 'connector'] as const)('CONTROL %s, slotted but not a type the pass reads, one package\'s row and a package-less row: the pass registers neither, and the bare read answers the package\'s row in either save order on every host (FROM the row saved first)', async (slotted) => { + expect(BOOT_PASS_READS).toEqual(UNBUNDLED.filter((type) => type !== 'webhook' && type !== 'connector')); const seen: unknown[] = []; for (const order of ['package-less row saved last', 'package-less row saved first'] as const) { for (const hostPackage of [undefined, ALPHA, HOST]) { driver = createMockDriver(); if (order === 'package-less row saved last') { - await seed('webhook', ALPHA, 1); - await seed('webhook', null, 2); + await seed(slotted, ALPHA, 1); + await seed(slotted, null, 2); } else { - await seed('webhook', null, 1); - await seed('webhook', ALPHA, 2); + await seed(slotted, null, 1); + await seed(slotted, ALPHA, 2); } const m = await bootPass(hostPackage); - seen.push([order, hostPackage ?? 'no host package', registryKeys(m, 'webhook'), await answer(m, 'webhook')]); + seen.push([order, hostPackage ?? 'no host package', registryKeys(m, slotted), await answer(m, slotted)]); } } expect(seen).toEqual(['package-less row saved last', 'package-less row saved first'].flatMap((order) => @@ -2801,9 +2802,9 @@ describe('[#32458] an unbundled slotted type\'s rows bound by the column only', }); it('the types are taken from the tree', () => { - expect(UNBUNDLED).toEqual(expect.arrayContaining(['api', 'agent', 'skill', 'action', 'permission', 'webhook'])); + expect(UNBUNDLED).toEqual(expect.arrayContaining(['api', 'agent', 'skill', 'action', 'permission', 'webhook', 'connector'])); expect(UNBUNDLED).not.toContain('email_template'); - expect(BOOT_PASS_READS).toEqual(UNBUNDLED.filter((type) => type !== 'webhook')); + expect(BOOT_PASS_READS).toEqual(UNBUNDLED.filter((type) => type !== 'webhook' && type !== 'connector')); }); it('CONTROL — webhook: the boot pass registers none of its rows, so a read stays the loader\'s, as before it was slotted', async () => { diff --git a/packages/metadata/src/metadata-manager-action-slots.test.ts b/packages/metadata/src/metadata-manager-action-slots.test.ts index 09598671e80..65a17965051 100644 --- a/packages/metadata/src/metadata-manager-action-slots.test.ts +++ b/packages/metadata/src/metadata-manager-action-slots.test.ts @@ -149,13 +149,13 @@ describe('[#31697] the in-memory action store keeps one slot per (package, name) it('CONTROL — a type outside the slotted set is unchanged: the later write replaces the earlier', async () => { const manager = new MetadataManager({ formats: ['json'], loaders: [] }); - // A connector: `flow` (#31696) and `webhook` (#31699 PR 2) joined the slotted set. - manager.registerInMemory('connector', 'digest', { name: 'digest', _packageId: ALPHA }); + // A job: `flow` (#31696), `webhook` (#31699 PR 2) and `connector` (#31699 PR 3) joined the slotted set. + manager.registerInMemory('job', 'digest', { name: 'digest', _packageId: ALPHA }); const later = { name: 'digest', _packageId: BETA }; - manager.registerInMemory('connector', 'digest', later); - expect(await manager.get('connector', 'digest')).toBe(later); - expect(await manager.get('connector', 'digest', ALPHA)).toBe(later); - expect(await manager.list('connector')).toEqual([later]); + manager.registerInMemory('job', 'digest', later); + expect(await manager.get('job', 'digest')).toBe(later); + expect(await manager.get('job', 'digest', ALPHA)).toBe(later); + expect(await manager.list('job')).toEqual([later]); }); }); diff --git a/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts b/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts index 4339e041301..ccf195a5e46 100644 --- a/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts +++ b/packages/metadata/src/metadata-manager-keyed-plural-read.test.ts @@ -402,8 +402,8 @@ describe('[#32517] the unscoped plural reads answer every package\'s item of an const A = 'com.acme.alpha'; const B = 'com.acme.beta'; // [#31699 PR 2] `webhook` joins the slotted set, and so these plural reads; - // [#31985] `tool` joins with its narrowing. - const UNBUNDLED = ['api', 'agent', 'skill', 'action', 'flow', 'permission', 'picklist', 'mapping', 'dataset', 'webhook', 'tool']; + // [#31985] `tool` joins with its narrowing; [#31699 PR 3] `connector` with its. + const UNBUNDLED = ['api', 'agent', 'skill', 'action', 'flow', 'permission', 'picklist', 'mapping', 'dataset', 'webhook', 'tool', 'connector']; const NAME = 'shared_item'; const item = (packageId: string | undefined, extra: Record = {}) => ({ name: NAME, diff --git a/packages/metadata/src/metadata-manager-match-endpoint.test.ts b/packages/metadata/src/metadata-manager-match-endpoint.test.ts index 2dee41fc7fc..457ac4c3be8 100644 --- a/packages/metadata/src/metadata-manager-match-endpoint.test.ts +++ b/packages/metadata/src/metadata-manager-match-endpoint.test.ts @@ -451,12 +451,12 @@ describe('the in-memory api store keeps one slot per (package, name) (ADR-0150 D it('a type outside the slotted set keeps one item per name: the later write replaces the earlier', async () => { const manager = new MetadataManager({ formats: ['json'], loaders: [] }); - // A connector: `flow` (#31696) and `webhook` (#31699 PR 2) joined the slotted set. - manager.registerInMemory('connector', 'f', { name: 'f', _packageId: 'com.acme.alpha' }); + // A job: `flow` (#31696), `webhook` (#31699 PR 2) and `connector` (#31699 PR 3) joined the slotted set. + manager.registerInMemory('job', 'f', { name: 'f', _packageId: 'com.acme.alpha' }); const later = { name: 'f', _packageId: 'com.acme.beta' }; - manager.registerInMemory('connector', 'f', later); - expect(await manager.get('connector', 'f')).toBe(later); - expect(await manager.list('connector')).toEqual([later]); + manager.registerInMemory('job', 'f', later); + expect(await manager.get('job', 'f')).toBe(later); + expect(await manager.list('job')).toEqual([later]); }); }); diff --git a/packages/metadata/src/package-slotted-store.ts b/packages/metadata/src/package-slotted-store.ts index 6453d0cb3cc..18e9869e6db 100644 --- a/packages/metadata/src/package-slotted-store.ts +++ b/packages/metadata/src/package-slotted-store.ts @@ -139,7 +139,8 @@ import { PACKAGE_SLOTTED_METADATA_TYPES } from '@objectstack/spec/api'; * picklist family's `picklist`, `mapping` and `dataset` (#31700); then * `webhook` (#31699 PR 2), so a host with no registry lists each package's * declaration of one name; then `tool` (#31985, ADR-0150 child B), likewise - * in the change that narrows it. The list itself is `@objectstack/spec`'s + * in the change that narrows it; and last `connector` (#31699 PR 3), in the + * change that narrows it. The list itself is `@objectstack/spec`'s * `PACKAGE_SLOTTED_METADATA_TYPES` (#32905), so a client that names a package * on the history and rollback doors reads the same one; a type joins there. */ diff --git a/packages/objectql/src/bare-name-one-holder.ts b/packages/objectql/src/bare-name-one-holder.ts index 4dbbc0387ae..be5b1964005 100644 --- a/packages/objectql/src/bare-name-one-holder.ts +++ b/packages/objectql/src/bare-name-one-holder.ts @@ -55,9 +55,12 @@ * the other, and `/meta/webhook/NAME` served the same one (both since * narrowed to the namespace: "The narrowing"); * - `connector` — `/meta/connector/NAME` (the by-name door the designer's - * connector picker reads) serves the FIRST-registered package's - * declaration; a provider-bound instance is the engine's one connector - * per name, and a second one at boot already refuses the boot (ADR-0097); + * connector picker reads) served the FIRST-registered package's + * declaration, and a provider-bound instance was the engine's one + * connector per name, a second one at boot refusing the boot (ADR-0097) + * (since narrowed to the namespace: "The narrowing", #31699 — the engine + * holds an instance per `(package, name)`, and a flow, a pull and the + * connection door address one by package); * - `email_template` — a send's `template: NAME` resolved the * FIRST-registered package's bundle, and `/meta/email_template/NAME` * served the same one (both since narrowed to the namespace: "The @@ -207,6 +210,18 @@ * D3) and refuses two holders, naming them (`packages/spec/liveness/tool.json` * records that precondition). * + * `connector` followed last (#31699 PR 3), so every covered type has now + * narrowed. The automation engine holds a connector instance per + * `(package, name)`, and the declared-connector reconcile materializes each + * package's entry under its package; an entry with no package of its own + * is the instance of the package the name resolves to, and under two holders + * it is refused naming both, never materialized as either. A flow's + * `connector_action` resolves its connector from the flow's package, a + * connector pull from the package that holds its mapping, and the + * connection door connects the instance its namespace address names + * (`/automation/connectors/NS/NAME/connection`); `/meta/connector/NAME` and + * the bare connection door refuse a name two packages hold, naming both. + * * Two holdings still meet under a narrowed type, whatever the namespaces: * * - a name the platform requests by its bare spelling @@ -239,8 +254,10 @@ * (ADR-0146 D9): a stored row bound to its pair, hydrated into the bare * slot — the environment catalog, never a package holder. * - A provider-bound connector instance two packages of ONE boot declare: - * the automation service's own duplicate refusal (ADR-0097) stops that boot - * before the seal; the doors here judge the install that follows a boot. + * the automation service materializes each package's under its package + * (ADR-0150 D9, #31699), and refuses an entry with no package of its own + * under such a name, and a name declared twice within one package + * (ADR-0097); the doors here judge the install that follows a boot. * - Every type not in {@link BARE_NAME_ONE_HOLDER_TYPES}: §3.4's coexistence * stands for them (package-scoped resolution, a key that carries the object, * the job key `appId:jobName`). diff --git a/packages/objectql/src/package-scoped-e8-readers.test.ts b/packages/objectql/src/package-scoped-e8-readers.test.ts index 0fd3f3f0ccf..240625c9843 100644 --- a/packages/objectql/src/package-scoped-e8-readers.test.ts +++ b/packages/objectql/src/package-scoped-e8-readers.test.ts @@ -50,7 +50,7 @@ const P = 'com.acme.caller'; /** The nine types this card wires, as the registry spells them. */ const E8_TYPES = ['app', 'page', 'dashboard', 'report', 'book', 'analytics_cube', 'tool', 'skill', 'agent'] as const; /** The types wired since, each by its own card: `api` (#32069), the email template (#31699), the picklist's bare read (#32070), `mapping` (#32071), `dataset` (#32072), `permission` (#32162), `flow` (#31696) and `webhook` (#31699 PR 2). */ -const WIRED_SINCE = ['api', 'email_template', 'picklist', 'mapping', 'dataset', 'permission', 'flow', 'webhook'] as const; +const WIRED_SINCE = ['api', 'email_template', 'picklist', 'mapping', 'dataset', 'permission', 'flow', 'webhook', 'connector'] as const; /** Of them, the ones phase 1's one-holder refusal does not cover: two package holders can exist today. */ const UNCOVERED = E8_TYPES.filter((t) => !(BARE_NAME_REGISTRY_TYPES as readonly string[]).includes(t)); @@ -387,10 +387,31 @@ describe('webhook joins the readers (ADR-0150 D9, #31699 PR 2): `/meta/webhook/N }); }); -describe('the types E8 does not wire keep the legacy read', () => { - it('a view (bucket 1) and a connector (not wired; the flow and the webhook are, #31696 and #31699 PR 2) are read by getItem, untouched', async () => { +describe('connector joins the readers (ADR-0150 D9, #31699 PR 3): `/meta/connector/NAME`', () => { + it('[FROM first-registered TO 409] a caller with no package is refused a name two packages ship, naming both; each package\'s address serves its own', async () => { + ship('connector', 'crm', A); + ship('connector', 'crm', B); + await expectRefusal(() => protocol.getMetaItem({ type: 'connector', name: 'crm' }), 'ambiguous-in-environment', [A, B]); + await expectRefusal(() => facade.get('connector', 'crm'), 'ambiguous-in-environment', [A, B]); + expect(labelOf((await protocol.getMetaItem({ type: 'connector', name: 'crm', packageId: A }))?.item)).toBe('alpha connector'); + expect(labelOf((await protocol.getMetaItem({ type: 'connector', name: 'crm', packageId: B }))?.item)).toBe('beta connector'); + }); + + it('CONTROL — one holder is served to a caller with no package, as before', async () => { ship('connector', 'onboard', A); - expect(labelOf(await facade.get('connector', 'onboard', P))).toBe('alpha connector'); + expect(labelOf((await protocol.getMetaItem({ type: 'connector', name: 'onboard' }))?.item)).toBe('alpha connector'); + expect(labelOf(await facade.get('connector', 'onboard'))).toBe('alpha connector'); + }); + + it('one enabled and one disabled holder: a caller with no package reads the enabled one\'s; re-enabled, 409 naming both', async () => { + for (const order of [[A, B], [B, A]] as const) { + const name = `twin_${order[0].split('.').pop()}`; + for (const id of order) ship('connector', name, id); + registry.disablePackage(B); + expect(labelOf((await protocol.getMetaItem({ type: 'connector', name }))?.item), order.join(',')).toBe('alpha connector'); + registry.enablePackage(B); + await expectRefusal(() => protocol.getMetaItem({ type: 'connector', name }), 'ambiguous-in-environment', [A, B]); + } }); }); diff --git a/packages/objectql/src/package-scoped-read.ts b/packages/objectql/src/package-scoped-read.ts index de775e77fb2..e0cd885c265 100644 --- a/packages/objectql/src/package-scoped-read.ts +++ b/packages/objectql/src/package-scoped-read.ts @@ -118,6 +118,9 @@ export const PACKAGE_SCOPED_READ_TYPES = Object.freeze([ // redelivery veto and the activation door read by `(package, name)` in // plugin-webhooks' `declared-webhooks.ts`. 'webhook', + // [ADR-0150 D9, #31699 PR 3] `/meta/connector/NAME`; the automation engine + // holds and dispatches a connector instance by `(package, name)`. + 'connector', ] as const); /** A type whose by-name readers consult `(package, name)` ({@link PACKAGE_SCOPED_READ_TYPES}). */ diff --git a/packages/objectql/src/package-scoped-resolver.test.ts b/packages/objectql/src/package-scoped-resolver.test.ts index 95d9396d0d1..bb8154dd8e5 100644 --- a/packages/objectql/src/package-scoped-resolver.test.ts +++ b/packages/objectql/src/package-scoped-resolver.test.ts @@ -820,11 +820,15 @@ describe('phase 1 parity — under the one-holder rule the resolver answers as ` } }); - it('a second package holder is still refused by phase 1, so no reader can meet two', () => { + it('a second package holder of the same namespace is still refused by phase 1, so no reader can meet two there', () => { sealedWithHolder(false); - install(B); - // A type whose rule has not narrowed to the namespace (`flow` has, #31696; `webhook` too, #31699 PR 2). - expect(() => ship('connector', NAME, B)).toThrow(); + // [#31699 PR 3] Every covered type has narrowed to the namespace (the + // connector last), so the refusal that stands is the one inside a + // namespace: B co-owns A's namespace (a declared dependency, ADR-0141 D5). + install(B, [A], A.split('.').pop()!); + for (const type of ['connector', 'flow', 'webhook'] as const) { + expect(() => ship(type, NAME, B), type).toThrow(); + } }); }); diff --git a/packages/objectql/src/registry-bare-name-one-holder-ai-family.test.ts b/packages/objectql/src/registry-bare-name-one-holder-ai-family.test.ts index 9964cb074b9..f327a4986ed 100644 --- a/packages/objectql/src/registry-bare-name-one-holder-ai-family.test.ts +++ b/packages/objectql/src/registry-bare-name-one-holder-ai-family.test.ts @@ -343,7 +343,8 @@ describe('the narrowing — agent, skill and tool hold one name per namespace (A it('the switch holds agent, skill and tool, the later families\' narrowed types, and no other covered type', () => { // Later child B cards append their own type, each pinned in its family's file. - const SWITCHED: readonly string[] = [...NARROWED, 'action', 'email_template', 'flow', 'picklist', 'mapping', 'dataset', 'api', 'function', 'webhook']; + // [#31699 PR 3] The connector is the last: every covered type has narrowed. + const SWITCHED: readonly string[] = [...NARROWED, 'action', 'email_template', 'flow', 'picklist', 'mapping', 'dataset', 'api', 'function', 'webhook', 'connector']; expect(NAMESPACE_SCOPED_BARE_NAME_TYPES).toEqual(SWITCHED); for (const type of BARE_NAME_ONE_HOLDER_TYPES) { // A type that has not narrowed meets every holder, namespaces or not. diff --git a/packages/objectql/src/registry-bare-name-one-holder-flow-family.test.ts b/packages/objectql/src/registry-bare-name-one-holder-flow-family.test.ts index 53bb1df6e67..24e7ec168cd 100644 --- a/packages/objectql/src/registry-bare-name-one-holder-flow-family.test.ts +++ b/packages/objectql/src/registry-bare-name-one-holder-flow-family.test.ts @@ -329,10 +329,10 @@ describe('the narrowing — a flow holds one name per namespace (ADR-0150 D2/D9, const type = 'flow' as const; const name = 'shared_flow'; - it('the switch holds flow (and the webhook, #31699 PR 2), and not the connector', () => { + it('the switch holds flow, the webhook (#31699 PR 2) and the connector (#31699 PR 3)', () => { expect(NAMESPACE_SCOPED_BARE_NAME_TYPES).toContain('flow'); expect(NAMESPACE_SCOPED_BARE_NAME_TYPES).toContain('webhook'); - expect(narrowed('connector'), 'connector').toBe(false); + expect(narrowed('connector'), 'connector').toBe(true); }); it('two packages of two namespaces each install the name after the seal, and each holds its own flow', async () => { @@ -407,31 +407,75 @@ describe('the narrowing — a flow holds one name per namespace (ADR-0150 D2/D9, } }); - it.each(['connector'] as const)('CONTROL — a %s has not narrowed: a package of another namespace is still refused its name', async (other) => { +}); + +describe('the narrowing — a connector holds one name per namespace (ADR-0150 D2/D9, child B, #31699 PR 3)', () => { + const type = 'connector' as const; + const name = 'shared_connector'; + + it('[FROM refused TO admitted] two packages of two namespaces each install the name after the seal, and each holds its own connector', async () => { + const { registry, register } = await boot(); + expect(await register(pkg('com.acme.alpha', { [type]: [name] }))).toBeUndefined(); + expect(await register(pkg('com.acme.beta', { [type]: [name] }))).toBeUndefined(); + const held = registry.listItems<{ _packageId?: string; label?: string; name?: string }>(type) + .filter((item) => item.name === name) + .map((item) => [item._packageId, marker(item)]); + expect(held).toEqual([['com.acme.alpha', 'alpha connector'], ['com.acme.beta', 'beta connector']]); + }); + + it('the by-name read resolves by package: each holder reads its own connector, and a read naming no package is refused 409 naming both', async () => { + const { registry, register } = await boot(); + expect(await register(pkg('com.acme.alpha', { [type]: [name] }))).toBeUndefined(); + expect(await register(pkg('com.acme.beta', { [type]: [name] }))).toBeUndefined(); + expect(marker(registry.resolveItem(type, name, 'com.acme.alpha'))).toBe('alpha connector'); + expect(marker(registry.resolveItem(type, name, 'com.acme.beta'))).toBe('beta connector'); + const err = await caught(() => registry.resolveItem(type, name)) as (Refusal & { refusal?: { candidates?: Holder[] } }) | undefined; + expect([err?.code, err?.status]).toEqual(['RESOURCE_CONFLICT', 409]); + expect(err!.refusal!.candidates).toEqual([ + { kind: 'package', packageId: 'com.acme.alpha' }, + { kind: 'package', packageId: 'com.acme.beta' }, + ]); + }); + + it('a co-owner of the holder\'s namespace is still refused, and so is a package with no namespace', async () => { const { register } = await boot(); - expect(await register(pkg('com.acme.alpha', { [other]: [`shared_${other}`] }))).toBeUndefined(); - expectRefusal( - await register(pkg('com.acme.beta', { [other]: [`shared_${other}`] })), - 'com.acme.beta', { kind: 'package', packageId: 'com.acme.alpha' }, `beta_shared_${other}`, - ); + expect(await register(pkg('com.acme.alpha', { [type]: [name] }))).toBeUndefined(); + expectRefusal(await register(rival(type, 'com.acme.gamma', { [type]: [name] })), 'com.acme.gamma', { kind: 'package', packageId: 'com.acme.alpha' }, `alpha_${name}`); + const bare = pkg('com.acme.plain', { [type]: [name] }); + delete bare.namespace; + expectRefusal(await register(bare), 'com.acme.plain', { kind: 'package', packageId: 'com.acme.alpha' }); + }); + + it('the cold boot of two namespaces\' holders boots with no bare-name warning, and the seal reports no clash', async () => { + const { registry, bareNameWarnings } = await boot([pkg('com.acme.alpha', { [type]: [name] }), pkg('com.acme.beta', { [type]: [name] })]); + expect(bareNameWarnings()).toEqual([]); + expect(registry.sealBareNameHolders().filter((c) => c.type === type)).toEqual([]); }); }); describe('connector — a descriptor and a provider-bound instance hold the name alike', () => { - it('a second package\'s provider-bound instance under a held descriptor name is refused, and the reverse', async () => { + const instance = (tag: string, n: string) => body('connector', n, tag, { provider: 'rest', providerConfig: { baseUrl: `https://${tag}.example` }, auth: { type: 'none' }, enabled: true }); + + it('a co-owner\'s provider-bound instance under a held descriptor name is refused, and the reverse', async () => { const { register } = await boot(); - const instance = (tag: string) => body('connector', 'shared_conn', tag, { provider: 'rest', providerConfig: { baseUrl: `https://${tag}.example` }, auth: { type: 'none' }, enabled: true }); - expect(await register(pkg('com.acme.alpha', { connector: ['shared_conn'] }))).toBeUndefined(); + expect(await register(pkg('com.acme.alpha', { connector: ['shared_conn', 'live_conn'] }))).toBeUndefined(); expectRefusal( - await register(pkg('com.acme.beta', {}, { connectors: [instance('beta')] })), - 'com.acme.beta', { kind: 'package', packageId: 'com.acme.alpha' }, 'beta_shared_conn', + await register(rival('connector', 'com.acme.beta', {}, { connectors: [instance('beta', 'shared_conn')] })), + 'com.acme.beta', { kind: 'package', packageId: 'com.acme.alpha' }, 'alpha_shared_conn', ); - expect(await register(pkg('com.acme.gamma', {}, { connectors: [{ ...instance('gamma'), name: 'live_conn' }] }))).toBeUndefined(); + const other = await boot(); + expect(await other.register(pkg('com.acme.alpha', {}, { connectors: [instance('alpha', 'live_conn')] }))).toBeUndefined(); expectRefusal( - await register(pkg('com.acme.delta', { connector: ['live_conn'] })), - 'com.acme.delta', { kind: 'package', packageId: 'com.acme.gamma' }, 'delta_live_conn', + await other.register(rival('connector', 'com.acme.delta', { connector: ['live_conn'] })), + 'com.acme.delta', { kind: 'package', packageId: 'com.acme.alpha' }, 'alpha_live_conn', ); }); + + it('[#31699 PR 3] a package of another namespace holds the name beside a descriptor or an instance', async () => { + const { register } = await boot(); + expect(await register(pkg('com.acme.alpha', { connector: ['shared_conn'] }))).toBeUndefined(); + expect(await register(pkg('com.acme.beta', {}, { connectors: [instance('beta', 'shared_conn')] }))).toBeUndefined(); + }); }); describe('email_template — the name holds the bundle, and the built-in templates are an overridable baseline', () => { @@ -562,11 +606,11 @@ describe('the narrowing — an email template holds one name per namespace (ADR- const member = (tag: string, n: string, locale: string) => body('email_template', n, tag, { locale }); const ofBeta = (decl: Record) => pkg('com.acme.beta', {}, decl); - it('the switch holds email_template, the flow (#31696) and webhook (#31699 PR 2), and not the connector', () => { + it('the switch holds email_template, the flow (#31696), the webhook (#31699 PR 2) and the connector (#31699 PR 3)', () => { expect(NAMESPACE_SCOPED_BARE_NAME_TYPES).toContain('email_template'); expect(NAMESPACE_SCOPED_BARE_NAME_TYPES).toContain('flow'); expect(NAMESPACE_SCOPED_BARE_NAME_TYPES).toContain('webhook'); - expect(narrowed('connector'), 'connector').toBe(false); + expect(narrowed('connector'), 'connector').toBe(true); }); it('two packages of two namespaces each install the name after the seal, and each holds its own bundle', async () => { @@ -727,14 +771,6 @@ describe('the narrowing — an email template holds one name per namespace (ADR- ); }); - it.each(['connector'] as const)('CONTROL — a %s has not narrowed: a package of another namespace is still refused its name', async (other) => { - const { register } = await boot(); - expect(await register(pkg('com.acme.alpha', { [other]: [`shared_${other}`] }))).toBeUndefined(); - expectRefusal( - await register(pkg('com.acme.beta', { [other]: [`shared_${other}`] })), - 'com.acme.beta', { kind: 'package', packageId: 'com.acme.alpha' }, `beta_shared_${other}`, - ); - }); }); describe('the refusal\'s reason names the consumers of the types it lists', () => { diff --git a/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts b/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts index 2d85febd333..d7551048367 100644 --- a/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts +++ b/packages/qa/dogfood/test/bare-name-one-holder-flow-family.dogfood.test.ts @@ -14,10 +14,9 @@ // - the cold boot of a deployment that already holds the clash — two // `AppPlugin` packages, `alpha` and `beta`, shipping one flow, one webhook, // one connector and one email template under the same names — boots, and -// logs ONE bare-name warning line naming the connector alone, both -// packages and its rename (the flow's, the email template's and the -// webhook's rules narrowed to the namespace, ADR-0150 D9 #31696 and -// #31699: two namespaces' flows, templates or webhooks are no clash, and a +// logs NO bare-name warning line (every one of the four rules narrowed to +// the namespace, ADR-0150 D9 #31696 and #31699, the connector last: two +// namespaces' flows, templates, webhooks or connectors are no clash, and a // send of the template name is refused naming both); the automation engine // arms EACH flow in its own slot and refuses the bare name naming both, and // the declared webhook's by-name read refuses the held name naming both @@ -26,12 +25,15 @@ // - `POST /marketplace/install-local` of a third namespace's package // declaring the held flow name installs (#31696), and the engine arms its // flow in a third slot beside the two; the bare name stays refused; -// - the same door refusing a package that declares the held connector and -// webhook names and the showcase's own flow and email template names, for -// the connector alone, naming its holders — and no longer the held webhook -// name or the showcase's flow or template name, which another namespace may -// now ship (`flow-name-per-namespace.dogfood.test.ts` pins the flow's -// narrowing at every door); +// - the same door admitting a package that declares the held connector name +// and the showcase's own flow and email template names, which another +// namespace may now ship (#31699: the connector, the last; the refusal it +// answered before is gone; `flow-name-per-namespace.dogfood.test.ts` pins +// the flow's narrowing at every door); +// - the connector's narrowing (#31699, the narrowing PR): the bare +// `/meta/connector/NAME` refuses the name naming every holder, the +// namespace address reads one holder's own declaration, and a co-owner of +// `alpha`'s namespace is still refused; // - the webhook's narrowing (#31699 PR 2): each holder is its own slot, the // activation door's bare address refuses the name naming both while its // namespace address switches one holder's own row, that holder alone is @@ -65,7 +67,6 @@ import { defineStack } from '@objectstack/spec'; import { PROTOCOL_MAJOR } from '@objectstack/spec/kernel'; import { bootShowcase } from './showcase-boot.js'; -const SHOWCASE_PKG = 'com.example.showcase'; const SHOWCASE_FLOW = 'showcase_task_completed'; const SHOWCASE_TEMPLATE = 'showcase_task_done_email'; const FLOW = 'qa_shared_flow'; @@ -134,11 +135,6 @@ async function captureOutput(run: () => Promise): Promise<{ value: T; line } } -/** The level of one kernel-logger line (` …`), or `undefined`. */ -function levelOf(line: string): string | undefined { - return /^(?:\S+Z\s+)?(DEBUG|INFO|WARN|ERROR|FATAL)\b/.exec(line.trim())?.[1]; -} - const codeOf = (body: any) => (body?.error && typeof body.error === 'object' ? body.error.code : undefined) ?? body?.code ?? null; @@ -228,25 +224,13 @@ describe('one package holder per flow, webhook, connector and email template nam if (storageDir) rmSync(storageDir, { recursive: true, force: true }); }); - it('the cold boot of a deployment holding the clash boots, and warns once naming the one unnarrowed name (the connector), both packages and its rename', async () => { + it('[FROM one warning naming the connector TO none] the cold boot of a deployment holding the four names in two namespaces boots with no bare-name warning', async () => { + // [ADR-0150 D9, #31696, #31699] Two namespaces' flows, email templates, + // webhooks (PR 2) and connectors (the narrowing, the last) are no clash. const warnings = bootLines.filter((l) => l.includes('Bare-name conflict at boot')); - expect(warnings, 'one warning line').toHaveLength(1); - const line = warnings[0]!; - expect(levelOf(line)).toBe('WARN'); - // [ADR-0150 D9, #31696] Two namespaces' flows are no clash. - expect(line).not.toContain(`the flow "${FLOW}"`); - expect(line).toContain(`the connector "${CONN}"`); - // [ADR-0150 D9, #31699] Two namespaces' email templates, and webhooks (PR 2), are no clash. - expect(line).not.toContain(`the email template "${TPL}"`); - expect(line).not.toContain(`the webhook "${HOOK}"`); - expect(line, `the rename of ${CONN}`).toContain(`"beta_${CONN}"`); - expect(line).toContain('package "com.qa.bare.alpha"'); - expect(line).toContain('package "com.qa.bare.beta"'); - // The platform's built-in templates are the overridable baseline: never named by the warning. - const baseline = builtInTemplatePackage(); - expect(baseline, 'the built-in templates are registered under a package').toBeDefined(); - expect(line).not.toContain(BUILT_IN_TPL); - expect(line).not.toContain(baseline!); + expect(warnings, 'no warning line').toEqual([]); + // The platform's built-in templates are the overridable baseline, registered under a package. + expect(builtInTemplatePackage(), 'the built-in templates are registered under a package').toBeDefined(); expect(await packageIds(), 'both packages booted').toEqual(expect.arrayContaining(['com.qa.bare.alpha', 'com.qa.bare.beta'])); // [ADR-0150 D4, #31696] The engine arms each flow (it had refused the arming). expect(bootLines.some((l) => l.includes('failed to register flow') && l.includes(`"${FLOW}"`))).toBe(false); @@ -265,26 +249,17 @@ describe('one package holder per flow, webhook, connector and email template nam await expectEachSlotArmedAndBareRefused(); }); - it('install-local of a package declaring the held connector and webhook names and the showcase\'s own flow and email template names is refused for the connector alone, naming its holders and never the showcase', async () => { - const before = await packageIds(); + it('[FROM 422 TO admitted] install-local of a third namespace\'s package declaring the held connector name and the showcase\'s own flow and email template names installs', async () => { + // [#31696, #31699] Another namespace may ship the showcase's flow and + // template names, and (the narrowing, the last) the held connector name. + // The held webhook name's admission is pinned in its own block below. const { status, body } = await installLocal(inline('delta', { flows: [flow('delta', SHOWCASE_FLOW)], - webhooks: [webhook('delta')], connectors: [connector('delta')], emailTemplates: [template('delta', SHOWCASE_TEMPLATE)], })); - expect([status, codeOf(body)], JSON.stringify(body)).toEqual([422, 'PLUGIN_REGISTER_FAILED']); - const message = String(body?.error?.message ?? ''); - // [#31696, #31699] Another namespace may ship the showcase's flow and template names. - expect(message).not.toContain(`the flow "${SHOWCASE_FLOW}"`); - expect(message).not.toContain(`the email template "${SHOWCASE_TEMPLATE}"`); - // [#31699 PR 2] Another namespace may declare the held webhook name. - expect(message).not.toContain(`the webhook "${HOOK}"`); - expect(message).not.toContain(SHOWCASE_PKG); - expect(message).toContain(`the connector "${CONN}"`); - expect(message).toContain('com.qa.bare.alpha'); - expect(message).toContain(`"delta_${CONN}"`); - expect(await packageIds(), 'the package list is unchanged').toEqual(before); + expect(status, JSON.stringify(body)).toBeLessThan(300); + expect(await packageIds()).toContain('com.qa.bare.delta'); await expectHeldWebhookRefused(); }); @@ -373,6 +348,48 @@ describe('one package holder per flow, webhook, connector and email template nam expect(await packageIds()).toEqual(before); }); }); + describe('the connector\'s rule narrowed to the namespace (ADR-0150 D3/D5/D9, #31699, the narrowing)', () => { + const HOLDERS = ['com.qa.bare.alpha', 'com.qa.bare.beta', 'com.qa.bare.delta']; + + it('[FROM the first registered declaration TO 409] the bare /meta/connector/NAME of the held name refuses it, naming every holder', async () => { + const res = await stack.apiAs(admin, 'GET', `/meta/connector/${CONN}`); + const body = (await res.json()) as any; + expect([res.status, codeOf(body)], JSON.stringify(body)).toEqual([409, 'RESOURCE_CONFLICT']); + for (const holder of HOLDERS) expect(JSON.stringify(body)).toContain(holder); + }); + + it('each holder\'s namespace address reads that holder\'s own declaration', async () => { + for (const ns of ['alpha', 'beta', 'delta']) { + const res = await stack.apiAs(admin, 'GET', `/meta/connector/${ns}/${CONN}`); + const body = (await res.json()) as any; + expect(res.status, JSON.stringify(body)).toBe(200); + expect(JSON.stringify(body)).toContain(`${ns} connector body`); + } + }); + + it('CONTROL — install-local of a co-owner of alpha\'s namespace declaring the held connector name is refused, naming alpha only; nothing is installed', async () => { + // Unlike the email template, a connector is not override-gated, so the + // bare-name rule answers the co-owner itself: one holder per namespace. + const before = await packageIds(); + const { status, body } = await installLocal({ + manifest: { + id: 'com.qa.bare.alphaconn', namespace: 'alpha', name: 'alphaconn', version: '1.0.0', type: 'app', scope: 'project', + engines: { protocol: `^${PROTOCOL_MAJOR}` }, + dependencies: { 'com.qa.bare.alpha': '^1.0.0' }, + objects: [item('alpha_alphaconn')], + connectors: [connector('alphaconn')], + }, + }); + expect([status, codeOf(body)], JSON.stringify(body)).toEqual([422, 'PLUGIN_REGISTER_FAILED']); + const message = String(body?.error?.message ?? ''); + expect(message).toContain(`the connector "${CONN}"`); + expect(message).toContain('already held by package "com.qa.bare.alpha"'); + expect(message).not.toContain('com.qa.bare.beta'); + expect(message).not.toContain('com.qa.bare.delta'); + expect(await packageIds()).toEqual(before); + }); + }); + describe('the webhook\'s rule narrowed to the namespace (ADR-0150 D3/D4/D5/D9, #31699 PR 2)', () => { const declared = () => (stack.kernel as any).getService('declaredWebhooks'); const slotsOf = async (name: string) => ((await declared().list()) as Array<{ webhook: { name: string }; packageId?: string; active: boolean }>) diff --git a/packages/runtime/src/domains/automation-address.ts b/packages/runtime/src/domains/automation-address.ts index a1377e0bdbc..8774bf04c12 100644 --- a/packages/runtime/src/domains/automation-address.ts +++ b/packages/runtime/src/domains/automation-address.ts @@ -196,8 +196,8 @@ export type AutomationAddressRefusal = | { readonly status: 409; readonly refusal: PackageScopedRefusal }; /** - * [ADR-0150 D4/D9, #31696] An address admitted to one holder's slot: the flow - * name is one two packages hold, which the bare doors refuse (`refusal`), and + * [ADR-0150 D4/D9, #31696; #31699] An address admitted to one holder's slot: the flow + * (or connector) name is one two packages hold, which the bare doors refuse (`refusal`), and * the address names `packageId`, one of them. The domain serves it from that * package's slot, or answers `refusal` where it cannot (a door that writes the * definition, an engine with no slot entries). @@ -263,7 +263,7 @@ export function bareNameRefusal( * Judge an addressed path's qualifier (see the module note). `undefined` * admits it: the path is then served as its bare path, whose item is the * address's. An {@link AutomationAddressSlot} admits it to one holder's slot - * of a flow name two packages hold. A registry that cannot answer admits + * of a flow or connector name two packages hold. A registry that cannot answer admits * nothing it could not judge: a namespace was read through it, so it answers; * `_env` with no registry is the bare path. */ @@ -311,8 +311,10 @@ export function admitAutomationAddress( }); if (bare.status === 'refused') { // [#31696] A flow name two packages hold: each holder's flow is its own - // slot, and the address names one holder of it. - return type === 'flow' && holder.kind === 'package' + // slot, and the address names one holder of it. [ADR-0150 D9, #31699] + // So is a connector name: each holder's instance is its own, and the + // connection door connects the addressed one. + return (type === 'flow' || type === 'connector') && holder.kind === 'package' ? { status: 'slot', packageId: holder.packageId, refusal: bare } : { status: 409, refusal: bare }; } diff --git a/packages/runtime/src/domains/automation-addressed-route.test.ts b/packages/runtime/src/domains/automation-addressed-route.test.ts index fe4b8e5e9d7..67d5ae388b3 100644 --- a/packages/runtime/src/domains/automation-addressed-route.test.ts +++ b/packages/runtime/src/domains/automation-addressed-route.test.ts @@ -473,6 +473,18 @@ describe('/automation/connectors/:ns/:name/connection — a connector instance b expect(automation.getConnectorConnection).not.toHaveBeenCalled(); }); + it('[ADR-0150 D9, #31699] a name two packages hold: each namespace\'s address reads, connects and revokes its own package\'s instance (FROM: 409 naming both)', async () => { + const { call, automation } = dispatcherWith(connectors); + for (const [ns, pkg] of [['crm', CRM], ['hr', HR]] as const) { + const read = await call(`/connectors/${ns}/mail/connection`, 'GET'); + expect(read.status, JSON.stringify(read.body)).toBe(200); + expect(automation.getConnectorConnection.mock.calls.at(-1)?.[0]).toMatchObject({ connector: 'mail', package: pkg }); + } + // CONTROL: the one-holder address names no package; the bare door names none. + await call('/connectors/crm/stripe/connection', 'GET'); + expect(automation.getConnectorConnection.mock.calls.at(-1)?.[0]).not.toHaveProperty('package'); + }); + it('CONTROL — the literal segments keep their routes: `oauth` and `credential-refs` are never read as a namespace', async () => { // A package booted under `oauth` (held before the install refusal) holds `stripe`. const { call, automation } = dispatcherWith({ packages: { 'connector:stripe': [HR] }, namespaces: { [HR]: 'oauth' } }); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index f8f81b8738e..cb06136162b 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -1173,6 +1173,12 @@ async function respondToConnectorConnectionDoor( body: unknown, context: HttpProtocolContext, query: unknown, + /** + * [ADR-0150 D9, #31699] The package the namespace address admitted the + * door to, for a connector name two packages hold: that package's + * instance is the one connected, read or revoked. + */ + connectorPackage?: string, ): Promise { const isCallback = parts[1] === CONNECTOR_OAUTH_SEGMENT && parts[2] === CONNECTOR_OAUTH_CALLBACK_SEGMENT; const queryRefusal = unknownQueryParamRefusalMessage( @@ -1219,7 +1225,12 @@ async function respondToConnectorConnectionDoor( if ('refusal' in read) return { handled: true, response: deps.error(read.refusal, 400, { code: 'VALIDATION_ERROR' }) }; client = read.client; } - const answer = await call.call(svc, { connector, context: executionContext, ...(client ? { client } : {}) }); + const answer = await call.call(svc, { + connector, + ...(connectorPackage !== undefined ? { package: connectorPackage } : {}), + context: executionContext, + ...(client ? { client } : {}), + }); return { handled: true, response: deps.success(answer) }; } catch (err) { const refusal = connectorCredentialRefusal(deps, err); @@ -3846,11 +3857,18 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // the run carries its slot key, so it is no guess at a name. A run of // another flow, or one whose key no one holder's slot is filed under, // keeps the `409`. + // + // [ADR-0150 D9, #31699] A connector name two packages hold, addressed by + // the namespace of one of them: the connection door connects, reads and + // revokes that holder's instance (`ConnectorConnectionRequest.package`). + let connectorPackage: string | undefined; { const admission = address.qualifier && address.item ? admitAutomationAddress(addressRegistry, address.qualifier, address.item) : bareByNameRefusal(addressRegistry, parts, m); - if (admission?.status === 'slot') { + if (admission?.status === 'slot' && address.item?.type === 'connector' && bareByNameItem(parts, m)?.type === 'connector') { + connectorPackage = admission.packageId; + } else if (admission?.status === 'slot') { const slotted = bareByNameItem(parts, m)?.type === 'flow' && address.item ? flowSlotView(automationService, admission.packageId, address.item.name) : undefined; @@ -4060,7 +4078,7 @@ export async function handleAutomationRequest(deps: DomainHandlerDeps, path: str // ADR-0143 D5 — the connector connection door, ahead of `/:name` for the // reason `/connectors` is. if (isConnectorConnectionDoor(parts, m)) { - return respondToConnectorConnectionDoor(deps, automationService, parts, m, body, context, query); + return respondToConnectorConnectionDoor(deps, automationService, parts, m, body, context, query, connectorPackage); } if (parts[0] === 'connectors' && parts.length === 1 && m === 'GET') { 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 25be856028b..5a557b2af1f 100644 --- a/packages/services/service-automation/src/connector-connection-door.test.ts +++ b/packages/services/service-automation/src/connector-connection-door.test.ts @@ -659,7 +659,7 @@ describe('ADR-0143 D3/D6 — what a grant leaves behind', () => { } } // The logs did record the connect — the pin is not passing on silence. - expect(out.text()).toContain("connector instance 'crm' connected for organization 'org_a' by user 'usr_admin'"); + expect(out.text()).toContain("connector instance 'crm' of package 'com.example.crm' connected for organization 'org_a' by user 'usr_admin'"); expect(out.text()).toContain( "[Automation] connector instance 'crm' needs to be reconnected for organization 'org_a': its authorization server refused the grant", ); @@ -922,7 +922,7 @@ describe("ADR-0143 D2.1 — an instance that takes the installer's OAuth client" expect(text.includes(INSTALLER_SECRET), `${where} carries the installer's secret`).toBe(false); } // Not passing on silence: the connect was logged and the read named the client. - expect(out.text()).toContain("connector instance 'crm' connected for organization 'org_a' by user 'usr_admin'"); + expect(out.text()).toContain("connector instance 'crm' of package 'com.example.crm' connected for organization 'org_a' by user 'usr_admin'"); expect(surfaces.answers).toContain(INSTALLER_ID); }); @@ -1109,26 +1109,41 @@ 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 () => { + it('[3b; the narrowing, review nit] the materializer registers the instance by its package, and its handle reads that package\'s connection; a second holder refuses the bare name until the reconcile drops the entry', async () => { const registry = registryHolding('com.example.crm'); - const { connect, call, engine } = await boot([crm({ _packageId: undefined })], { registry }); + const { connect, call, engine, reload } = 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. + // more. The bare name is refused at resolution, naming both (no flow + // dispatches it). The registered instance is still com.example.crm's + // until the reconcile, and its handle reads that package's row, fixed + // (FROM: re-resolved on every read, answering no package's row). hold(registry, OTHER); - await expect(call('org_a')).rejects.toMatchObject({ status: 503 }); + expect(engine.resolveConnectorInstanceFor('crm', null).status).toBe('refused'); + await expect(engine.resolveConnectorAction('crm', 'request', 'com.example.crm')!({}, { automation: { tenantId: 'org_a' } } as never)) + .resolves.toMatchObject({ status: 200 }); + // The reconcile refuses the entry: it is materialized as neither holder's. + await reload(); + expect(engine.resolveConnectorAction('crm', 'request', 'com.example.crm')).toBeUndefined(); + expect(engine.resolveConnectorAction('crm', 'request', OTHER)).toBeUndefined(); }); - it('[3b] the holder of an unstamped entry is replaced, leaving one holder: the dispatch keeps its connection', async () => { + it('[3b; the narrowing] the holder of an unstamped entry is replaced, leaving one holder: once the reconcile re-registers it, the dispatch keeps its connection', async () => { const registry = registryHolding('com.example.crm'); - const { connect, call, engine } = await boot([crm({ _packageId: undefined })], { registry }); + const { connect, call, engine, reload } = 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' }); + // Before the reconcile: the name resolves to OTHER, which has no + // instance yet. FROM (3b's fallback arm) the one instance of the name, + // registered under the uninstalled package; TO none, never another + // package's instance. + expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'none' }); + await reload(); + expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: OTHER }); await expect(call('org_a')).resolves.toMatchObject({ status: 200 }); }); @@ -1198,3 +1213,139 @@ describe('ADR-0150 D4 [#31699] — the connection door connects one instance, by expect(rows.map((r) => [r.id, r.connector_package])).toEqual([[row.id, 'com.example.crm']]); }); }); + +// ─── ADR-0150 D9 [#31699, the narrowing] two live instances of one name ─── + +describe('ADR-0150 D9 [#31699] — two packages of different namespaces each hold an instance of one name', () => { + const CRM = 'com.example.crm'; + const OTHER = 'com.example.other'; + function hold(r: SchemaRegistry, id: string): SchemaRegistry { + r.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + r.registerItem('connector', crm({ _packageId: id }) as never, 'name' as never, id); + return r; + } + const registryHoldingBoth = () => hold(hold(new SchemaRegistry({ multiTenant: false }), CRM), OTHER); + const both = () => [crm({ _packageId: CRM }), crm({ _packageId: OTHER })]; + const connectAt = async (engine: AutomationEngine, pkg: string | undefined, context = ADMIN_A) => { + const begun = await engine.beginConnectorConnection({ connector: 'crm', context: context as never, ...(pkg ? { package: pkg } : {}) }); + const state = new URL(begun.authorizationUrl).searchParams.get('state')!; + return engine.completeConnectorConnection({ query: { state, code: GOOD_CODE }, context: context as never }); + }; + const dispatchAt = (engine: AutomationEngine, pkg: string, organizationId = 'org_a') => + engine.resolveConnectorAction('crm', 'request', pkg)!({}, { automation: { tenantId: organizationId } } as never); + + it('both instances materialize, each under its package (FROM: the boot refused the name, naming both)', async () => { + const { engine } = await boot(both(), { registry: registryHoldingBoth() }); + expect(engine.getConnectorDescriptors().filter((d) => d.name === 'crm').map((d) => d.packageId).sort()).toEqual([CRM, OTHER]); + expect(engine.getConnectorDegradedReason('crm', CRM)).toBeDefined(); + expect(engine.getConnectorDegradedReason('crm', OTHER)).toBeDefined(); + }); + + it('the bare connection door is refused 409 naming both; the addressed door connects each package\'s instance, each with its own row and token', async () => { + const { engine, ql, provider } = await boot(both(), { registry: registryHoldingBoth() }); + await expect(engine.beginConnectorConnection({ connector: 'crm', context: ADMIN_A as never })) + .rejects.toMatchObject({ status: 409, message: expect.stringContaining(OTHER) }); + await expect(connectAt(engine, CRM)).resolves.toMatchObject({ status: 'connected' }); + // Connecting one leaves the other unconnected. + expect(await engine.getConnectorConnection({ connector: 'crm', package: OTHER, context: ADMIN_A as never })) + .toMatchObject({ status: 'not_connected' }); + await expect(connectAt(engine, OTHER)).resolves.toMatchObject({ status: 'connected' }); + const rows = await rowsOf(ql); + expect(rows.map((r) => r.connector_package).sort()).toEqual([CRM, OTHER]); + // Each dispatch presents its own instance's token (two live grant handles). + await expect(dispatchAt(engine, CRM)).resolves.toMatchObject({ status: 200 }); + await expect(dispatchAt(engine, OTHER)).resolves.toMatchObject({ status: 200 }); + expect(provider.state.sent).toHaveLength(2); + expect(new Set(provider.state.sent).size).toBe(2); + // The bare read is ambiguous: 409, never one of them. + await expect(engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never })) + .rejects.toMatchObject({ status: 409 }); + }); + + it('revoking one package\'s connection leaves the other\'s connection and token serving', async () => { + const { engine, ql, provider } = await boot(both(), { registry: registryHoldingBoth() }); + await connectAt(engine, CRM); + await connectAt(engine, OTHER); + await dispatchAt(engine, OTHER); + const otherToken = provider.state.sent[provider.state.sent.length - 1]; + await engine.revokeConnectorConnection({ connector: 'crm', package: CRM, context: ADMIN_A as never }); + expect((await rowsOf(ql)).map((r) => r.connector_package)).toEqual([OTHER]); + // CRM's instance is held degraded, with no connection to present: nothing of it dispatches. + expect(engine.getConnectorDegradedReason('crm', CRM)).toBeDefined(); + expect(engine.resolveConnectorAction('crm', 'request', CRM)).toBeUndefined(); + expect(engine.getConnectorDegradedReason('crm', OTHER)).toBeUndefined(); + await expect(dispatchAt(engine, OTHER)).resolves.toMatchObject({ status: 200 }); + expect(provider.state.sent[provider.state.sent.length - 1]).toBe(otherToken); + }); + + // [review S5] One of the two holders disabled, in both registration + // orders. The registry lists no item of a disabled package, so the + // declaration the reconcile and the door read is the enabled holder's. + for (const order of ['crm first', 'other first'] as const) { + const oneDisabled = () => { + const r = new SchemaRegistry({ multiTenant: false }); + for (const id of order === 'crm first' ? [CRM, OTHER] : [OTHER, CRM]) hold(r, id); + r.disablePackage(CRM); + return r; + }; + + it(`[${order}] CRM disabled: the bare door connects OTHER's instance, the one served holder`, async () => { + const { engine, ql } = await boot([crm({ _packageId: OTHER })], { registry: oneDisabled() }); + await expect(connectAt(engine, undefined)).resolves.toMatchObject({ status: 'connected' }); + expect((await rowsOf(ql)).map((r) => r.connector_package)).toEqual([OTHER]); + }); + + it(`[${order}] CRM disabled: the door addressed to CRM finds no declared instance (404) and writes nothing`, async () => { + const { engine, ql } = await boot([crm({ _packageId: OTHER })], { registry: oneDisabled() }); + await expect(engine.getConnectorConnection({ connector: 'crm', package: CRM, context: ADMIN_A as never })) + .rejects.toMatchObject({ status: 404 }); + await expect(engine.beginConnectorConnection({ connector: 'crm', package: CRM, context: ADMIN_A as never })) + .rejects.toMatchObject({ status: 404 }); + expect(await rowsOf(ql)).toEqual([]); + }); + } + + it('an entry with no package of its own under the two holders is refused, naming both, and materialized as neither', async () => { + const logged = captureOutput(); + const { engine } = await boot([...both(), crm({ _packageId: undefined, label: 'unowned' })], { registry: registryHoldingBoth() }); + expect(engine.getConnectorDescriptors().filter((d) => d.name === 'crm').map((d) => d.packageId).sort()).toEqual([CRM, OTHER]); + expect(engine.getConnectorDescriptors().some((d) => d.label === 'unowned')).toBe(false); + expect(logged.text()).toContain(`connector instance 'crm' is not materialized`); + }); + + it('two entries of one package with one name are a duplicate within the package: the boot fails loudly, as a duplicate name did', async () => { + await expect(boot([...both(), crm({ _packageId: CRM, label: 'second' })], { registry: registryHoldingBoth() })) + .rejects.toThrow(`duplicate declarative connector instance name 'crm' in package '${CRM}'`); + }); + + it('[#33218 review N6] a row a moved declaration left stamped with its old package is that package\'s again once it declares the name beside the new holder', async () => { + // CRM connects; the declaration moves to OTHER (one holder throughout): + // the row keeps CRM's stamp and serves OTHER's instance (#33218 F1). + const registry = hold(new SchemaRegistry({ multiTenant: false }), CRM); + const declared: unknown[] = [crm({ _packageId: CRM })]; + const { engine, ql, reload } = await boot(declared, { registry }); + await connectAt(engine, undefined); + registry.uninstallPackage(CRM); + registry.unregisterItemsByPackage(CRM); + hold(registry, OTHER); + declared.splice(0, 1, crm({ _packageId: OTHER })); + await reload(); + expect(await engine.getConnectorConnection({ connector: 'crm', context: ADMIN_A as never })).toMatchObject({ status: 'connected' }); + expect((await rowsOf(ql)).map((r) => r.connector_package)).toEqual([CRM]); + // CRM declares the name again, beside OTHER: two holders. The row + // names a holder, so it is that holder's own; OTHER has none. The + // stamp is judged, not rewritten: the token was got for CRM's connect. + hold(registry, CRM); + declared.push(crm({ _packageId: CRM })); + await reload(); + expect(await engine.getConnectorConnection({ connector: 'crm', package: CRM, context: ADMIN_A as never })) + .toMatchObject({ status: 'connected' }); + expect(await engine.getConnectorConnection({ connector: 'crm', package: OTHER, context: ADMIN_A as never })) + .toMatchObject({ status: 'not_connected' }); + expect((await rowsOf(ql)).map((r) => r.connector_package)).toEqual([CRM]); + }); + + it('CONTROL: with no registry to judge by, one instance per name, as before the narrowing (red line 1): the second is a duplicate', async () => { + await expect(boot(both())).rejects.toThrow(/duplicate declarative connector instance name 'crm' — .*serves none/); + }); +}); diff --git a/packages/services/service-automation/src/connector-descriptor-audit.test.ts b/packages/services/service-automation/src/connector-descriptor-audit.test.ts index f3bce826135..9c2b4ce0df9 100644 --- a/packages/services/service-automation/src/connector-descriptor-audit.test.ts +++ b/packages/services/service-automation/src/connector-descriptor-audit.test.ts @@ -12,6 +12,8 @@ import { describe, it, expect, vi } from 'vitest'; import { LiteKernel } from '@objectstack/core'; +import { SchemaRegistry } from '@objectstack/objectql'; +import type { ConnectorProviderFactory } from '@objectstack/spec/integration'; import { AutomationServicePlugin, findInertDeclaredConnectors } from './plugin.js'; const flush = () => new Promise((r) => setTimeout(r, 0)); @@ -39,7 +41,7 @@ function declaredConnector(name: string, opts: { actions?: number; enabled?: boo */ async function bootWithConnectors( declared: unknown[], - opts: { registerLive?: string[] } = {}, + opts: { registerLive?: string[]; registry?: SchemaRegistry; provider?: ConnectorProviderFactory } = {}, ) { const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); kernel.use(new AutomationServicePlugin()); @@ -54,10 +56,11 @@ async function bootWithConnectors( // so spying here observes the automation plugin's warn calls too. warnSpy = vi.spyOn(ctx.logger, 'warn'); ctx.registerService('objectql', { - registry: { + registry: opts.registry ?? { listItems: (type: string) => (type === 'connector' ? declared : []), }, }); + if (opts.provider) ctx.getService('automation').registerConnectorProvider('fake', opts.provider); for (const name of opts.registerLive ?? []) { ctx.getService('automation').registerConnector( { @@ -151,6 +154,27 @@ describe('kernel:ready audit (wiring)', () => { await kernel.shutdown(); }); + it('[#31699 PR 3] a package\'s catalog entry is not silenced by another package\'s live instance of its name', async () => { + const A = 'com.acme.catalog_a'; + const B = 'com.acme.instance_b'; + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const id of [A, B]) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + } + registry.registerItem('connector', declaredConnector('billing') as never, 'name' as never, A); + registry.registerItem('connector', { ...declaredConnector('billing'), provider: 'fake', providerConfig: {} } as never, 'name' as never, B); + const provider: ConnectorProviderFactory = (ctx) => ({ + def: { name: ctx.name, label: ctx.label, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'action_0', label: 'A' }] } as never, + handlers: { action_0: async () => ({}) }, + }); + const { kernel, warnSpy } = await bootWithConnectors([], { registry, provider }); + const warnings = auditWarnings(warnSpy); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain('billing'); + await kernel.shutdown(); + }); + it('stays silent when nothing is declared', async () => { const { kernel, warnSpy } = await bootWithConnectors([]); expect(auditWarnings(warnSpy)).toHaveLength(0); diff --git a/packages/services/service-automation/src/connector-instances.ts b/packages/services/service-automation/src/connector-instances.ts index a91e21cb135..029b1fecc86 100644 --- a/packages/services/service-automation/src/connector-instances.ts +++ b/packages/services/service-automation/src/connector-instances.ts @@ -10,10 +10,12 @@ * 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. + * The declared-connector reconcile registers each package's instance under + * its package (ADR-0150 D9: two packages of different namespaces may each + * declare one name), so two instances of a name can be live at once. + * `soleOfName` (drop any other declarative instance of the name) is kept on + * the engine's registration for a caller that wants one instance per name; + * the reconcile no longer asks for it. */ import type { RegisteredConnector } from './engine.js'; diff --git a/packages/services/service-automation/src/connector-materialization.test.ts b/packages/services/service-automation/src/connector-materialization.test.ts index 45a3fb631cd..43f089f7c1c 100644 --- a/packages/services/service-automation/src/connector-materialization.test.ts +++ b/packages/services/service-automation/src/connector-materialization.test.ts @@ -225,6 +225,8 @@ async function bootReloadable( residualOwners?: Record; /** The connectors a package registration filed, as `getArtifactItem` answers them (#28594). */ registered?: unknown[]; + /** A real `SchemaRegistry` served instead of the double over the mutable set (#31699: two holders). */ + schemaRegistry?: SchemaRegistry; }, ) { const state = { declared: initial }; @@ -239,7 +241,7 @@ async function bootReloadable( async init(ctx: any) { captured = ctx; ctx.registerService('objectql', { - registry: { + registry: opts.schemaRegistry ?? { listItems: (type: string) => (type === 'connector' ? state.declared : []), getPackage: (id: string) => opts.packages?.[id], getArtifactItem: artifactReader(opts.registered), @@ -445,16 +447,80 @@ describe('ADR-0150 D3 — a declared connector name resolves by (package, name) expect(calls.map((c) => c.label)).toEqual([`billing from ${A}`]); }); - it('two package holders: the boot refuses, naming both — no instance is picked by list order', async () => { + it('[ADR-0150 D9, the narrowing] two package holders of different namespaces: each instance materializes under its package (FROM: the boot refused, naming both)', async () => { const { factory, calls } = makeFakeProvider(); - const err = await boot([], { providerFactory: factory, schemaRegistry: registryShipping(A, B) }).then( - () => undefined, - (e: Error) => e, - ); - expect(err?.message).toContain(`connector instance 'billing' is not materialized`); - expect(err?.message).toContain(`"${A}"`); - expect(err?.message).toContain(`"${B}"`); - expect(calls).toEqual([]); + const kernel = await boot([], { providerFactory: factory, schemaRegistry: registryShipping(A, B) }); + const engine = automationOf(kernel); + expect(calls.map((c) => c.label).sort()).toEqual([`billing from ${A}`, `billing from ${B}`]); + expect(engine.getConnectorDescriptors().filter((d) => d.name === 'billing').map((d) => d.packageId).sort()).toEqual([A, B]); + expect(engine.getConnectorOrigin('billing', A)).toBe('declarative'); + expect(engine.getConnectorOrigin('billing', B)).toBe('declarative'); + // The bare name reads no instance: two, never one of them. + expect(engine.getConnectorOrigin('billing')).toBeUndefined(); + await kernel.shutdown(); + }); + + describe('[#31699 review M1] the credential listing reads each declaring entry\'s own instance', () => { + const REF = 'OS_TEST_31699_LISTING_REF'; + const auth = { type: 'bearer', credentialRef: REF } as ConnectorInstanceAuth; + afterEach(() => { delete process.env[REF]; }); + /** A's instance reaches its upstream; B's cannot (degraded). */ + const factory: ConnectorProviderFactory = (ctx) => { + if (ctx.label === `billing from ${B}`) throw new ConnectorUpstreamUnavailableError(`connector '${ctx.name}' could not reach its server: connect ECONNREFUSED`); + return { + def: { name: ctx.name, label: ctx.label, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'ping', label: 'Ping' }] } as unknown as Connector, + handlers: { ping: async () => ({ ok: true }) }, + }; + }; + + it('two packages\' instances of one name, one ready and one degraded: each entry reports its own state', async () => { + process.env[REF] = 'dummy-31699'; + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + for (const id of [A, B]) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + registry.registerItem('connector', providerConnector('billing', { label: `billing from ${id}`, auth }), 'name' as never, id); + } + const kernel = await boot([], { providerFactory: factory, schemaRegistry: registry }); + const [entry] = await automationOf(kernel).listConnectorCredentialRefs(); + expect(entry?.connectors.map((c) => [c.packageId, c.state]).sort()).toEqual([[A, 'ready'], [B, 'degraded']]); + await kernel.shutdown(); + }); + + it.each(['sys_metadata', '__runtime__'])('an entry stamped %s (no package of its own) over a one-holder name reports the holder\'s instance state', async (stamp) => { + process.env[REF] = 'dummy-31699'; + const registry = new SchemaRegistry(); + registry.logLevel = 'silent'; + registry.installPackage({ id: A, name: A, version: '1.0.0', type: 'app', namespace: 'billing_a' } as never, 'code'); + registry.registerItem('connector', providerConnector('billing', { label: `billing from ${A}` }), 'name' as never, A); + // The declaration the reconcile reads is the environment's stored row; the holder is A's. + const row = { ...providerConnector('billing', { label: `billing from ${A}`, auth }), _packageId: stamp }; + const served = Object.assign(Object.create(registry) as SchemaRegistry, { + listItems: (type: string) => (type === 'connector' ? [row] : registry.listItems(type as never)), + }); + const kernel = await boot([], { providerFactory: factory, schemaRegistry: served }); + const engine = automationOf(kernel); + expect(engine.getConnectorDescriptors().find((d) => d.name === 'billing')?.packageId).toBe(A); + const [entry] = await engine.listConnectorCredentialRefs(); + expect(entry?.connectors).toEqual([expect.objectContaining({ name: 'billing', state: 'ready' })]); + await kernel.shutdown(); + }); + }); + + it('[#31699 review M2] a reload of one holder\'s artifact re-materializes that holder\'s instance and leaves the other\'s live', async () => { + const { factory, calls, closed } = makeClosableProvider(); + const { engine, reload, kernel } = await bootReloadable([], { providerFactory: factory, schemaRegistry: registryShipping(A, B) }); + expect(calls.map((c) => c.label).sort()).toEqual([`billing from ${A}`, `billing from ${B}`]); + // A's artifact, its item unstamped as a compiled artifact carries it: it is A's, by the manifest. + await reload([], { metadata: { manifest: { id: A }, connectors: [providerConnector('billing', { label: 'billing from A, edited' })] } }); + expect(calls.map((c) => c.label)).toContain('billing from A, edited'); + // One teardown: A's superseded instance. B's was never touched. + expect(closed).toEqual(['billing']); + expect(calls.filter((c) => c.label === `billing from ${B}`)).toHaveLength(1); + expect(engine.getConnectorOrigin('billing', A)).toBe('declarative'); + expect(engine.getConnectorOrigin('billing', B)).toBe('declarative'); + expect(engine.getConnectorDescriptors().filter((d) => d.name === 'billing').map((d) => d.packageId).sort()).toEqual([A, B]); + await kernel.shutdown(); }); }); diff --git a/packages/services/service-automation/src/connector-package-scope.ts b/packages/services/service-automation/src/connector-package-scope.ts index ca77d351edf..25ca2d60b65 100644 --- a/packages/services/service-automation/src/connector-package-scope.ts +++ b/packages/services/service-automation/src/connector-package-scope.ts @@ -7,20 +7,15 @@ * package-scoped resolver (`resolvePackageScopedName`, `@objectstack/objectql`), * never by list order. * - * A connector is addressed by `(package, name)`. The engine keeps one live - * instance per name, and the reconcile that materializes declared instances - * is context-free: it reads the whole environment's declaration, so it asks - * as a caller with no package — the environment's own item, else the unique - * package holder, else a refusal naming every candidate. A refused name is not - * materialized: the reconcile reports the refusal (the boot fails loudly on a - * host-declared entry, as it does for a duplicate name) and tears down what - * it materialized before, so no flow dispatches to one of the candidates on a - * guess. Every other answer leaves the name to the reconcile as it stood. - * - * While phase 1's one-holder refusal stands (`connector` is one of its types) - * no two packages hold a connector name, so this refuses nothing on a booted - * deployment; it is the reader the type's trailing backstop child (ADR-0150 - * D9) narrows that refusal behind. + * A connector is addressed by `(package, name)` (ADR-0150 D4). Two packages + * of different namespaces may each declare an instance of one name (ADR-0150 + * D9, the narrowing of phase 1's one-holder refusal for this type, #31699): + * the engine holds both, and a bare name is resolved for its caller's package + * — the flow that dispatches, the mapping a pull reads, the connection door's + * address — to exactly one of them, or refused naming every candidate. A + * declared entry with no package of its own is the instance of the package + * the name resolves to; under two holders it is no instance at all, and the + * reconcile reports it instead of materializing it as either. * * A connector a plugin registers in code (`engine.registerConnector`) is no * registry item: the resolver answers not-found for it, and it keeps the @@ -30,7 +25,6 @@ import { resolvePackageScopedName, type PackageScopedHolder, - type PackageScopedRefusal, type PackageScopedRegistry, type PackageScopedResolution, } from '@objectstack/objectql'; @@ -47,23 +41,6 @@ export function packageScopedRegistryOf(registry: unknown): PackageScopedRegistr : undefined; } -/** - * The refusal of every declared connector name in `names` that resolves to no - * single holder (ADR-0150 D3, a caller with no package), keyed by name. A name - * the resolver answers — or does not hold at all — is absent. - */ -export function refusedConnectorNames( - registry: PackageScopedRegistry, - names: Iterable, -): Map { - const refused = new Map(); - for (const name of new Set(names)) { - const resolved = resolvePackageScopedName(registry, { type: 'connector', name }); - if (resolved.status === 'refused') refused.set(name, resolved); - } - return refused; -} - /** * [ADR-0150 D3] The engine's reader over the one package-scoped resolver for * the `connector` type (`AutomationEngine.setConnectorNameResolver`): which diff --git a/packages/services/service-automation/src/connector-pull-service-door.test.ts b/packages/services/service-automation/src/connector-pull-service-door.test.ts index b951d2b436c..f31117eab1d 100644 --- a/packages/services/service-automation/src/connector-pull-service-door.test.ts +++ b/packages/services/service-automation/src/connector-pull-service-door.test.ts @@ -74,3 +74,19 @@ describe('#20281 stage ③: IAutomationService.pullConnectorSource, served by th } }); }); + +describe('[#31699] the provider a pull reads is the instance the pull resolved', () => { + it('by package; with no package addressed, the one materialized instance of the name, never one of two', () => { + const plugin = new AutomationServicePlugin({ suspendedRunStore: 'memory' }); + const materialized = (plugin as any).materializedConnectors as Map; + const providerOf = (name: string, packageId?: string | null) => (plugin as any).materializedProviderOf(name, packageId); + materialized.set('com.acme.alpha/crm_api', { name: 'crm_api', packageId: 'com.acme.alpha', signature: '', provider: 'rest' }); + materialized.set('com.acme.beta/crm_api', { name: 'crm_api', packageId: 'com.acme.beta', signature: '', provider: 'openapi' }); + expect(providerOf('crm_api', 'com.acme.alpha')).toBe('rest'); + expect(providerOf('crm_api', 'com.acme.beta')).toBe('openapi'); + expect(providerOf('crm_api', null)).toBeUndefined(); + expect(providerOf('crm_api')).toBeUndefined(); + materialized.delete('com.acme.beta/crm_api'); + expect(providerOf('crm_api')).toBe('rest'); + }); +}); diff --git a/packages/services/service-automation/src/connector-pull.test.ts b/packages/services/service-automation/src/connector-pull.test.ts index ac7c151d941..91b6595bc3a 100644 --- a/packages/services/service-automation/src/connector-pull.test.ts +++ b/packages/services/service-automation/src/connector-pull.test.ts @@ -15,7 +15,8 @@ import { describe, it, expect, vi } from 'vitest'; import { buildFieldMetaMap, runImport } from '@objectstack/core'; import { PackageScopedNameRefusedError } from '@objectstack/core'; import { SchemaRegistry } from '@objectstack/objectql'; -import { mappingNameResolver } from './connector-package-scope.js'; +import { connectorNameResolver, mappingNameResolver } from './connector-package-scope.js'; +import { AutomationEngine } from './engine.js'; import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { pullConnectorSource, @@ -801,3 +802,89 @@ describe('[#32071] connector pull — a package caller reads the mapping from it expect(pathPulled(h), 'no registry: the protocol read, as before').toBe('beta'); }); }); + +/** + * [ADR-0150 D9, #31699 — the narrowing] Two packages of different namespaces + * may each declare a connector of one name. A pull resolves the mapping's + * `connectorSource.connector` from the package that holds the mapping, as a + * flow's `connector_action` resolves from the flow's package, and reads + * exactly that instance: its origin, state, provider, action and inputSchema. + */ +describe('[#31699] connector pull — the connector resolves from the mapping\'s package', () => { + const ALPHA = 'com.acme.alpha'; + const BETA = 'com.acme.beta'; + const silentEngineLogger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } } as never; + + function overTwoInstances(opts: { instances?: string[]; providers?: Record } = {}) { + const h = harness(); + const registry = new SchemaRegistry({ multiTenant: false }); + registry.logLevel = 'silent'; + const pulled: string[] = []; + const engine = new AutomationEngine(silentEngineLogger); + for (const id of [ALPHA, BETA]) { + registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code'); + registry.registerItem('connector', { name: 'crm_api', label: 'CRM', type: 'api' } as never, 'name' as never, id); + registry.registerItem('mapping', baseMapping({ label: id }) as never, 'name' as never, id); + } + for (const id of opts.instances ?? [ALPHA, BETA]) { + engine.registerConnector( + { name: 'crm_api', label: 'CRM', type: 'api', authentication: { type: 'none' }, actions: [{ key: 'request', label: 'HTTP Request' }] } as never, + { request: async () => { pulled.push(id); return { status: 200, ok: true, body: [] }; } }, + 'declarative', + { packageId: id }, + ); + } + const ctx = { getService: () => ({ registry }) as T }; + engine.setConnectorNameResolver(connectorNameResolver(ctx as never)); + h.deps.registry = engine; + h.deps.mappingByPackage = mappingNameResolver(ctx); + const providers = opts.providers ?? { [ALPHA]: 'rest', [BETA]: 'rest' }; + h.deps.providerOf = (name, packageId) => (name === 'crm_api' && typeof packageId === 'string' ? providers[packageId] : undefined); + return { h, pulled, registry }; + } + + it('each package\'s mapping pulls through its own package\'s instance of the name', async () => { + const { h, pulled } = overTwoInstances(); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', callerPackageId: ALPHA }); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', callerPackageId: BETA }); + expect(pulled).toEqual([ALPHA, BETA]); + }); + + it('the provider read is the resolved instance\'s: BETA\'s non-rest provider refuses BETA\'s pull only', async () => { + const { h, pulled } = overTwoInstances({ providers: { [ALPHA]: 'rest', [BETA]: 'mcp' } }); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', callerPackageId: ALPHA }); + const err = await pullConnectorSource(h.deps, { mapping: 'crm_contacts', callerPackageId: BETA }).then(() => undefined, (e: unknown) => e); + expect((err as ConnectorPullError).reason).toBe('connector_provider_unsupported'); + expect(pulled).toEqual([ALPHA]); + }); + + it('⛔ the mapping\'s holder has no instance of the name: not registered, never pulled through the other package\'s instance', async () => { + const { h, pulled } = overTwoInstances({ instances: [BETA] }); + const err = await pullConnectorSource(h.deps, { mapping: 'crm_contacts', callerPackageId: ALPHA }).then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(ConnectorPullError); + expect((err as ConnectorPullError).reason).toBe('connector_not_registered'); + expect(pulled).toEqual([]); + }); + + it('a mapping no package holds names a connector two packages hold: refused 409 naming both, nothing pulled', async () => { + const { h, pulled } = overTwoInstances(); + h.deps.mappingByPackage = undefined; + // The fake protocol answers the environment's mapping, with no holder. + const err = await pullConnectorSource(h.deps, { mapping: 'crm_contacts' }).then(() => undefined, (e: unknown) => e); + expect(err).toBeInstanceOf(ConnectorPullError); + expect((err as ConnectorPullError).reason).toBe('connector_name_refused'); + expect((err as ConnectorPullError).status).toBe(409); + expect(String((err as Error).message)).toContain(ALPHA); + expect(String((err as Error).message)).toContain(BETA); + expect(pulled).toEqual([]); + }); + + it('[review S5] one of the two holders disabled: the environment\'s mapping pulls through the one served holder\'s instance, the enabled package\'s through its own', async () => { + const { h, pulled, registry } = overTwoInstances(); + registry.disablePackage(ALPHA); + await pullConnectorSource(h.deps, { mapping: 'crm_contacts', callerPackageId: BETA }); + h.deps.mappingByPackage = undefined; + await pullConnectorSource(h.deps, { mapping: 'crm_contacts' }); + expect(pulled).toEqual([BETA, BETA]); + }); +}); diff --git a/packages/services/service-automation/src/connector-pull.ts b/packages/services/service-automation/src/connector-pull.ts index 7e85bc91a45..bfb7bad3167 100644 --- a/packages/services/service-automation/src/connector-pull.ts +++ b/packages/services/service-automation/src/connector-pull.ts @@ -71,7 +71,7 @@ import { import type { AutomationContext, Logger } from '@objectstack/spec/contracts'; import { SystemObjectName } from '@objectstack/spec/system'; import type { ConnectorOrigin } from '@objectstack/spec/integration'; -import type { ConnectorActionHandler } from './engine.js'; +import type { ConnectorActionHandler, ConnectorInstanceResolution } from './engine.js'; import { findConnectorActionInputSchema, judgeConnectorInput, @@ -109,9 +109,17 @@ export interface ConnectorPullProtocol extends ImportProtocolLike { * (#28040), the read the `connector_action` node makes. */ export interface ConnectorPullRegistry extends ConnectorInputSchemaSource { - resolveConnectorAction(connectorId: string, actionId: string): ConnectorActionHandler | undefined; - getConnectorOrigin(name: string): ConnectorOrigin | undefined; - getConnectorDegradedReason(name: string): string | undefined; + /** [#31699] `packageId` addresses one instance; absent, the one instance of the name. */ + resolveConnectorAction(connectorId: string, actionId: string, packageId?: string | null): ConnectorActionHandler | undefined; + getConnectorOrigin(name: string, packageId?: string | null): ConnectorOrigin | undefined; + getConnectorDegradedReason(name: string, packageId?: string | null): string | undefined; + /** + * [ADR-0150 D9, #31699] Which instance the bare name means for a caller of + * a package (`null`: none): the engine's + * (`AutomationEngine.resolveConnectorInstanceFor`). A registry without it + * is read by the bare name. + */ + resolveConnectorInstanceFor?(connectorId: string, callerPackageId: string | null): ConnectorInstanceResolution; } export interface ConnectorPullDeps { @@ -123,7 +131,7 @@ export interface ConnectorPullDeps { * registered connector definition carries no provider key, so this is the * one place the answer lives. */ - providerOf(connector: string): string | undefined; + providerOf(connector: string, packageId?: string | null): string | undefined; logger: Logger; /** * [ADR-0150 D3, #32071] The mapping read for a caller of a package @@ -623,7 +631,30 @@ async function pullOnce( const objectName = artifact.targetObject; // 2. The connector: a DECLARED rest/openapi instance, and its action. - const origin = registry.getConnectorOrigin(connector); + // + // [ADR-0150 D9, #31699] `connectorSource.connector` is a bare name the + // mapping writes, so it resolves from the package that holds the mapping + // (a mapping no package holds: as a caller with no package), as a flow's + // `connector_action` resolves from the flow's package. Two packages may + // each declare an instance of one name: the pull reads exactly the + // instance the name resolves to, and a name that resolves to no single + // instance is refused naming every candidate, never pulled through one. + let instancePackage: string | null | undefined; + let noInstance = false; + if (typeof registry.resolveConnectorInstanceFor === 'function') { + const meant = registry.resolveConnectorInstanceFor(connector, holderPackage ?? null); + if (meant.status === 'refused') { + const refused = new PackageScopedNameRefusedError(meant.refusal); + return refuse( + refused.code, refused.status, 'connector_name_refused', + `Mapping "${mappingName}" pulls from connector "${connector}": ${refused.message}`, + ); + } + // `none` reads as not registered below. + if (meant.status === 'instance') instancePackage = meant.packageId; + else noInstance = true; + } + const origin = noInstance ? undefined : registry.getConnectorOrigin(connector, instancePackage); if (origin === undefined) { return refuse( 'VALIDATION_ERROR', 400, 'connector_not_registered', @@ -638,7 +669,7 @@ async function pullOnce( + 'not a `connectors[]` entry; a pull reads only a declared rest or openapi instance', ); } - const degraded = registry.getConnectorDegradedReason(connector); + const degraded = registry.getConnectorDegradedReason(connector, instancePackage); if (degraded !== undefined) { return refuse( 'SERVICE_UNAVAILABLE', 503, 'connector_degraded', @@ -646,7 +677,7 @@ async function pullOnce( + 'nothing was pulled', ); } - const provider = deps.providerOf(connector); + const provider = deps.providerOf(connector, instancePackage); if (provider === undefined || !CONNECTOR_PULL_PROVIDERS.includes(provider)) { return refuse( 'VALIDATION_ERROR', 400, 'connector_provider_unsupported', @@ -654,7 +685,7 @@ async function pullOnce( + `${provider === undefined ? 'unknown' : `"${provider}"`}; a pull reads only a rest or openapi connector`, ); } - const handler = registry.resolveConnectorAction(connector, action); + const handler = registry.resolveConnectorAction(connector, action, instancePackage); if (!handler) { return refuse( 'VALIDATION_ERROR', 400, 'connector_action_unknown', @@ -755,7 +786,7 @@ async function pullOnce( // hint is the pull door's own: `connectorSource.input` is JSON spread as // written and the watermark is the stored value, so no CEL envelope runs // here and the node's `int()` / `double()` / `bool()` advice cannot apply. - const verdict = judgeConnectorInput(findConnectorActionInputSchema(registry, connector, action), input); + const verdict = judgeConnectorInput(findConnectorActionInputSchema(registry, connector, action, instancePackage), input); if (verdict) { return refuse( 'VALIDATION_ERROR', 400, 'input_schema_mismatch', diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index 43c586524a6..59a9a010ed1 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -2703,8 +2703,9 @@ export type FlowNameResolver = ( /** * [#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). + * refusal naming every candidate, or `none` (not registered, none registered + * under the holder the name resolves to, or two instances and nothing to + * choose by). */ export type ConnectorInstanceResolution = | { readonly status: 'instance'; readonly packageId: string | null } @@ -4769,8 +4770,11 @@ 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.entries().map(({ packageId, registered: { def, origin, state, degradedReason } }) => ({ name: def.name, + // [ADR-0150 D9, #31699] two packages' instances of one name are two + // descriptors: the package tells them apart. + ...(packageId === null ? {} : { packageId }), label: def.label, type: def.type, description: def.description, @@ -5887,17 +5891,13 @@ export class AutomationEngine implements IAutomationService { * The name is resolved for the package that ships the calling flow * ({@link flowCallerPackage}: a packaged flow names it from its package; an * environment-authored flow, or a call outside a run, names it with no - * package). The engine holds ONE instance per name, materialized for the - * answer a caller with no package gets (the declared-connector reconcile, - * which already refuses a name two packages hold). So a package caller - * whose answer is a refusal — two holders in its closure, or holders only - * outside it, an environment-only instance included (ADR-0150 D3 (a)) — is - * refused with the resolver's own message, naming every candidate. Any - * other answer is the instance the engine serves: an environment item - * exists only for a name no package holds, so a package caller that - * resolves at all resolves to the one package holder the reconcile - * materialized. A name the registry holds nothing under (a connector a - * plugin registers in code), or a host with no resolver, dispatches by name + * package). A refusal — two holders in the caller's closure, holders only + * outside it, an environment-only instance included (ADR-0150 D3 (a)), or, + * for a caller with no package, two package holders of different + * namespaces (ADR-0150 D9) — is answered with the resolver's own message, + * naming every candidate ({@link resolveConnectorInstanceFor}). A name the + * registry holds nothing under (a connector a plugin registers in code), or + * a host with no resolver, dispatches by name * as before. Read-only. */ connectorNameRefusal(connectorId: string, context: AutomationContext | undefined): PackageScopedRefusal | undefined { @@ -5915,34 +5915,62 @@ export class AutomationEngine implements IAutomationService { } /** - * [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. + * [ADR-0150 D3/D4/D9, #31699] Which registered instance the bare name + * `connectorId` means for a caller of package `callerPackageId` (`null`: + * no package), over the served holders (a disabled package holds no name, + * #32183): + * + * - the resolver's `refused` is said with its own message, every + * candidate named ({@link connectorNameRefusal}); + * - `resolved` addresses exactly the holder's instance (`null`: the + * environment's). When none is registered under that holder (a catalog + * entry, whose runtime a plugin registers in code; or one the reconcile + * has not reached), the instance a plugin registered in code under the + * name answers, as it did before (ADR-0097 §4: a plugin connector and a + * declarative instance never share a name); otherwise `none`. ⛔ Never + * another package's declarative instance, nor the environment's: two + * packages may each hold the name now (ADR-0150 D9), and the one other + * instance is not the caller's (red line 2; the narrowing removed 3b's + * fallback to the one instance of the name); + * - a name only disabled packages hold (served: `not-found`; every + * holder: held) is answered as a resolved holder with no instance: a + * disabled package's instance is not served to a caller outside it, + * even before the reconcile drops it (#31699 notes 6816295828 and + * 6820178514). A caller of the disabled package itself is answered its + * own instance, as before: the resolver keeps a caller's own holding in + * its served set; + * - a name the registry holds nothing under (a connector a plugin + * registers in code), or a host with no resolver: the one instance of + * the name, as a dispatch by name answered before; two are `none`, + * never one of them. + * + * 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 resolver = this.connectorNameResolver; + const meant = resolver?.(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; + return this.connectors.get(connectorId, packageId) ? { status: 'instance', packageId } : this.codeRegisteredInstance(connectorId); + } + if (meant?.status === 'not-found' + && resolver?.(connectorId, callerPackageId, { includeDisabledPackages: true })?.status !== 'not-found') { + return this.codeRegisteredInstance(connectorId); } const sole = this.connectors.sole(connectorId); return sole ? { status: 'instance', packageId: sole.packageId } : { status: 'none' }; } + /** + * [#31699] The instance a plugin registered in code under `connectorId` + * (package `null`, origin `plugin`), or `none`: what a name answers when + * the holder it resolves to has no instance of its own. + */ + private codeRegisteredInstance(connectorId: string): ConnectorInstanceResolution { + return this.connectors.get(connectorId, null)?.origin === 'plugin' ? { status: 'instance', packageId: null } : { status: 'none' }; + } + /** * [ADR-0150 D3] The package a call of {@link execute} comes from: the * package that ships the flow whose run made the call — `context.flowName`, 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 853472f62fb..7be36be1630 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 @@ -513,11 +513,16 @@ function declareConnector(name: string, packageId?: string) { /** The engine's one live instance under `name`; `pings` records each dispatch to it. */ let pings: string[]; -function liveConnector(name: string) { - engine.registerConnector( - { name, label: name, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'ping', label: 'Ping' }] } as never, - { ping: async () => { pings.push(name); return { ok: true }; } }, - ); +/** + * A live instance of `name`: as a plugin registers one in code (no package), + * or, given `packageId`, as the declared-connector reconcile registers a + * package's instance (ADR-0150 D9: under its package). + */ +function liveConnector(name: string, packageId?: string) { + const def = { name, label: name, type: 'api', authentication: { type: 'none' }, actions: [{ key: 'ping', label: 'Ping' }] } as never; + const handlers = { ping: async () => { pings.push(name); return { ok: true }; } }; + if (packageId === undefined) engine.registerConnector(def, handlers); + else engine.registerConnector(def, handlers, 'declarative', { packageId }); } /** start → connector_action(connectorId.ping) → end. */ @@ -548,7 +553,7 @@ describe('ADR-0150 D3 — a connector_action names its connector from the callin it("dispatches to the caller package's own instance, as before", async () => { install(P); declareConnector('billing', P); - liveConnector('billing'); + liveConnector('billing', P); ship(P, dispatcher('charge', 'billing')); const result = await engine.execute('charge'); expect(result.success, String(result.error)).toBe(true); @@ -559,7 +564,7 @@ describe('ADR-0150 D3 — a connector_action names its connector from the callin install(A); install(P, [A]); declareConnector('billing', A); - liveConnector('billing'); + liveConnector('billing', A); ship(P, dispatcher('charge', 'billing')); const result = await engine.execute('charge'); expect(result.success, String(result.error)).toBe(true); @@ -569,7 +574,7 @@ describe('ADR-0150 D3 — a connector_action names its connector from the callin it('an environment-authored flow dispatches to the one package holder (a caller with no package)', async () => { install(A); declareConnector('billing', A); - liveConnector('billing'); + liveConnector('billing', A); author(dispatcher('my_charge', 'billing')); const result = await engine.execute('my_charge'); expect(result.success, String(result.error)).toBe(true); @@ -589,7 +594,7 @@ describe('ADR-0150 D3 — a connector_action names its connector from the callin install(Q); install(P); declareConnector('billing', Q); - liveConnector('billing'); + liveConnector('billing', Q); ship(P, dispatcher('charge', 'billing')); const result = await engine.execute('charge'); expect(result.success).toBe(false); @@ -840,7 +845,23 @@ describe('ADR-0150 D4 — the engine holds a connector instance by (package, nam expect(engine.getConnectorOrigin('billing')).toBeUndefined(); expect(engine.resolveConnectorAction('billing', 'ping', A)).toBeTypeOf('function'); expect(engine.resolveConnectorActionInputSchema('billing', 'ping', B)).toEqual({ type: 'object' }); + // [the narrowing] A caller with no package asks the resolver too: two + // package holders are its refusal, naming both (FROM `none`, a + // dispatch answered "not registered", TO refused naming both). + const answer = engine.resolveConnectorInstanceFor('billing', null); + expect(answer.status).toBe('refused'); + expect(answer.status === 'refused' ? answer.refusal.message : '').toContain(A); + expect(answer.status === 'refused' ? answer.refusal.message : '').toContain(B); + expect(String(result.error)).toContain(A); + expect(String(result.error)).toContain(B); + }); + + it('CONTROL: two instances with no registry to ask: a caller with nothing to choose by is answered none, never one of them', () => { + engine.setConnectorNameResolver(undefined); + instance('billing', A); + instance('billing', B); expect(engine.resolveConnectorInstanceFor('billing', null)).toEqual({ status: 'none' }); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'none' }); }); it('a package caller whose closure holds two is refused with the resolver\'s message, naming both', () => { @@ -858,23 +879,121 @@ describe('ADR-0150 D4 — the engine holds a connector instance by (package, nam 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 () => { + it('⛔ [the narrowing] a holder with no instance registered under it is answered none: never another package\'s, or no package\'s, instance of the name', async () => { install(A); + install(B); 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 }); + declareConnector('billing', B); + // P resolves the name to A, whose instance is not registered (a + // catalog entry, or one the reconcile has not reached); B's is. + instance('billing', B); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'none' }); ship(P, dispatcher('charge', 'billing')); + const result = await engine.execute('charge'); + expect(result.success).toBe(false); + expect(pings).toEqual([]); + // FROM (3b's fallback arm): the one instance of the name, B's. TO: none. + // Nor the instance of no package: + engine.unregisterConnector('billing'); + instance('billing', null); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'none' }); + // CONTROL: A's instance registered, it is the one P dispatches. + instance('billing', A); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'instance', packageId: A }); 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(pings).toEqual([`billing@${A}`]); + }); + + it('CONTROL: a package\'s catalog entry and the connector a plugin registers in code under its name: the package\'s flow dispatches the plugin\'s', async () => { + install(A); + install(P, [A]); + declareConnector('slack', A); + liveConnector('slack'); + expect(engine.resolveConnectorInstanceFor('slack', P)).toEqual({ status: 'instance', packageId: null }); + ship(P, dispatcher('notify', 'slack')); + expect((await engine.execute('notify')).success).toBe(true); + expect(pings).toEqual(['slack']); + }); + + it('[the narrowing, review S2] two packages\' catalog entries beside the connector a plugin registers in code: each package\'s caller is served the plugin\'s; a caller with no package is refused naming both (FROM: the plugin\'s)', () => { + install(A); + install(B); + declareConnector('slack', A); + declareConnector('slack', B); + liveConnector('slack'); + expect(engine.resolveConnectorInstanceFor('slack', A)).toEqual({ status: 'instance', packageId: null }); + expect(engine.resolveConnectorInstanceFor('slack', B)).toEqual({ status: 'instance', packageId: null }); + const bare = engine.resolveConnectorInstanceFor('slack', null); + expect(bare.status).toBe('refused'); + expect(bare.status === 'refused' ? bare.refusal.message : '').toContain(A); + expect(bare.status === 'refused' ? bare.refusal.message : '').toContain(B); + }); + + // [#31699 notes 6816295828, 6820178514] A disabled holder: resolve and + // count over one holder set, the served one. Pinned in both registration + // orders, since a name's holders are listed in the order they registered. + for (const order of ['alpha first', 'beta first'] as const) { + const both = () => { + for (const id of order === 'alpha first' ? [A, B] : [B, A]) { + install(id); + declareConnector('billing', id); + instance('billing', id); + } + install(P, [A]); + }; + + it(`[${order}] A disabled: A's own caller is never served B's instance, nor A's (FROM: the one other instance)`, async () => { + both(); + registry.disablePackage(A); + const answer = engine.resolveConnectorInstanceFor('billing', P); + expect(answer.status).not.toBe('instance'); + ship(P, dispatcher('charge', 'billing')); + expect((await engine.execute('charge')).success).toBe(false); + expect(pings).toEqual([]); + }); + + it(`[${order}] A disabled: a caller of A itself is still served A's own instance (the resolver keeps a caller's own holding), never B's`, async () => { + both(); + registry.disablePackage(A); + expect(engine.resolveConnectorInstanceFor('billing', A)).toEqual({ status: 'instance', packageId: A }); + }); + + it(`[${order}] A disabled: a caller with no package is served B, the one served holder`, async () => { + both(); + registry.disablePackage(A); + expect(engine.resolveConnectorInstanceFor('billing', null)).toEqual({ status: 'instance', packageId: B }); + author(dispatcher('my_charge', 'billing')); + expect((await engine.execute('my_charge')).success).toBe(true); + expect(pings).toEqual([`billing@${B}`]); + }); + + it(`[${order}] CONTROL both enabled: A's caller is served A; a caller with no package is refused naming both`, async () => { + both(); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'instance', packageId: A }); + const bare = engine.resolveConnectorInstanceFor('billing', null); + expect(bare.status).toBe('refused'); + expect(bare.status === 'refused' ? bare.refusal.message : '').toContain(A); + expect(bare.status === 'refused' ? bare.refusal.message : '').toContain(B); + }); + } + + it('a lone disabled holder whose instance is still registered (the reconcile has not dropped it): served to no caller outside it', async () => { + install(A); + install(P, [A]); + declareConnector('billing', A); + instance('billing', A); + registry.disablePackage(A); expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'none' }); + expect(engine.resolveConnectorInstanceFor('billing', null)).toEqual({ status: 'none' }); + // A caller of A itself reads its own instance, as before the narrowing. + expect(engine.resolveConnectorInstanceFor('billing', A)).toEqual({ status: 'instance', packageId: A }); + // CONTROL: enabled again, served again. + registry.enablePackage(A); + expect(engine.resolveConnectorInstanceFor('billing', P)).toEqual({ status: 'instance', packageId: A }); }); - it('soleOfName (the reconcile today): a declarative registration drops the other declarative instance of the name', () => { + it('soleOfName (an engine option the reconcile no longer asks for): 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 }); diff --git a/packages/services/service-automation/src/plugin-extension-api.ts b/packages/services/service-automation/src/plugin-extension-api.ts index 19350c41dba..c6867491dc2 100644 --- a/packages/services/service-automation/src/plugin-extension-api.ts +++ b/packages/services/service-automation/src/plugin-extension-api.ts @@ -448,8 +448,9 @@ export function assertSameOriginOrFree( /** * [#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. + * same origin is dropped first, for a caller that wants one instance per + * name (the declared-connector reconcile no longer asks for it: ADR-0150 D9, + * each package's instance is kept beside the other's). */ function placeInstance( connectors: ConnectorInstances, diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index eca939d7423..f4a6dc3fa75 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -80,7 +80,7 @@ import { import { connectorReadWithheldText, type ConnectorFailureTextRewrite } from './connector-read-withheld-text.js'; import { CONNECTOR_CREDENTIAL_SOURCE_SERVICE } from '@objectstack/types'; import { createConnectorCredentialSource } from './connector-credential-source.js'; -import { connectorNameResolver, mappingNameResolver, packageScopedRegistryOf, refusedConnectorNames } from './connector-package-scope.js'; +import { connectorNameResolver, mappingNameResolver, packageScopedRegistryOf } from './connector-package-scope.js'; import { functionResolverOf, packageScopedFunctionEngineOf } from './function-package-scope.js'; import type { PackageScopedRefusal, PackageScopedRegistry } from '@objectstack/objectql'; import { createConnectorRequestSigner } from './request-signing/index.js'; @@ -1195,13 +1195,19 @@ function declaredEntryPackage(entry: unknown): string | null { } /** - * [#31699] The package a declared connector instance's connections are read - * and written by. An entry stamped with a real package is that package's; the - * environment's stored entry (`sys_metadata`) is no package's. An entry with - * no stamp, or the compatibility API's default, is the name's durable holder's + * [#31699] The package a declared connector instance is: the engine instance + * it is registered as, and the package its connections are read and written + * by. An entry stamped with a real package is that package's. An entry with + * no package of its own (no stamp, the compatibility API's default, or the + * environment's stored row, `sys_metadata`) is the name's durable holder's * when that is a package: the package the boot backfill binds a package-less * row of the name to, so a row the instance connected is still its row once - * bound. With no registry to ask, or no package holder, it is no package's. + * bound, and the holder whose item a stored row over its name customizes + * (ADR-0005; the registry reads such a row as that holder's, never as a + * second item). With no registry to ask, or no package holder, it is no + * package's. [#31699 PR 3] A name two packages hold gives such an entry no + * package: {@link connectorInstanceRefusal} refuses it, and the reconcile + * materializes nothing for it. */ function connectorInstancePackage( resolve: ReturnType, @@ -1209,14 +1215,58 @@ function connectorInstancePackage( ): string | null { const own = declaredEntryPackage(entry); if (own !== null) return own; - const stamp = (entry as { _packageId?: unknown } | null | undefined)?._packageId; - if (stamp === 'sys_metadata') return null; const name = (entry as { name?: unknown } | null | undefined)?.name; if (typeof name !== 'string' || name.length === 0) return null; const holder = resolve(name, null, { includeDisabledPackages: true }); return holder?.status === 'resolved' && holder.holder.kind === 'package' ? holder.holder.packageId : null; } +/** + * [ADR-0150 D3, #31699 PR 3] Why a declared entry is no instance it can be + * addressed as: an entry with no package of its own + * ({@link connectorInstancePackage}) whose name two packages hold. Which of + * them it is cannot be told, so it is refused, naming every candidate, and + * never registered as either (ADR-0150 red line 2). `undefined` for every + * other entry: one stamped with a package is that package's instance. + */ +function connectorInstanceRefusal( + resolve: ReturnType, + entry: unknown, +): PackageScopedRefusal | undefined { + if (declaredEntryPackage(entry) !== null) return undefined; + const name = (entry as { name?: unknown } | null | undefined)?.name; + if (typeof name !== 'string' || name.length === 0) return undefined; + const holder = resolve(name, null, { includeDisabledPackages: true }); + return holder?.status === 'refused' ? holder : undefined; +} + +/** + * [ADR-0150 D4, #31699 PR 3] The key the materializer keeps an instance's + * state by (live, degraded, retry, grant handle): its name for the instance + * of no package, else its package and name. A connector name is snake_case + * (`ConnectorSchema`), so it never contains the separator. + */ +function connectorInstanceKey(name: string, packageId: string | null): string { + return packageId === null ? name : `${packageId}/${name}`; +} + +/** [#31699 PR 3] How a log record names an instance's package, after its name: nothing for the instance of none. */ +function inPackage(packageId: string | null): string { + return packageId === null ? '' : ` of package '${packageId}'`; +} + +/** + * [#27237] One declared entry naming a credential reference: its name, its + * stamp as the listing reports it, and [#31699 PR 3] the package of the + * instance it is (`null`: the instance of no package; `false`: refused, no + * instance). + */ +interface DeclaredCredentialUser { + name: string; + packageId?: string; + instance: string | null | false; +} + interface DeclaredConnectorItem { name?: string; label?: string; @@ -1263,7 +1313,13 @@ interface DeclaredConnectorItem { * * - a registry entry whose name the artifact re-declares is superseded by the * artifact's (an edit re-materializes; an unchanged one still hashes to the - * same signature and is left alone); + * same signature and is left alone) — unless the two are entries of two + * different packages. [#31699 PR 3] Two packages may each declare a + * connector of one name, so a reload of one package's artifact supersedes + * that package's entry of the name, and the other package's entry is kept + * (its instance is not torn down). An artifact item with no stamp of its own + * arrives stamped with its manifest's id (the capture stamps it, as + * `MetadataPlugin._parseAndRegisterArtifact` stamps it in the registry); * - a registry entry owned by one of the artifact's own packages but ABSENT * from it was deleted from the stack — dropped, so the reconcile tears it * down; @@ -1276,26 +1332,40 @@ interface DeclaredConnectorItem { * — an artifact with no manifest id, whose items were never stamped — the * middle rule cannot fire and the fold degrades to name-wise replacement: an * edited or added connector is still picked up, a deleted one waits for the - * restart it always waited for. + * restart it always waited for. An artifact item that still has no package + * (no stamp, no manifest id) supersedes every registry entry of its name, as + * before: nothing tells which package's entry it edits. So does every item + * where the registry offers no package-scoped reads (`byPackage` false): the + * reconcile keeps one instance per name there (ADR-0150 red line 1). */ export function mergeDeclaredConnectorSources( registryItems: readonly unknown[], artifact: { items: readonly unknown[]; owners: ReadonlySet } | undefined, + opts: { byPackage?: boolean } = {}, ): unknown[] { if (!artifact) return [...registryItems]; - const declaredNames = new Set( - artifact.items - .map((item) => (item as DeclaredConnectorItem)?.name) - .filter((name): name is string => typeof name === 'string' && name.length > 0), - ); + const items = artifact.items; + /** name → the packages the artifact re-declares it under (`null`: an item of no package). */ + const declared = new Map>(); + for (const item of items) { + const name = (item as DeclaredConnectorItem)?.name; + if (typeof name !== 'string' || name.length === 0) continue; + const under = declared.get(name) ?? new Set(); + under.add(declaredEntryPackage(item)); + declared.set(name, under); + } const kept = registryItems.filter((item) => { + const own = declaredEntryPackage(item); + if (own !== null && artifact.owners.has(own)) return false; const name = (item as DeclaredConnectorItem)?.name; - if (typeof name === 'string' && declaredNames.has(name)) return false; - const owner = (item as { _packageId?: unknown })?._packageId; - if (typeof owner === 'string' && artifact.owners.has(owner)) return false; - return true; + const under = typeof name === 'string' ? declared.get(name) : undefined; + if (!under) return true; + // Superseded unless every re-declaration is another package's entry, + // and only where a package-scoped registry tells two packages' + // instances apart; elsewhere one instance per name, as before. + return opts.byPackage === true && own !== null && !under.has(null) && !under.has(own); }); - return [...kept, ...artifact.items]; + return [...kept, ...items]; } /** @@ -1559,7 +1629,8 @@ export class AutomationServicePlugin implements Plugin { private bootFlowViewFingerprint: string | undefined; /** * Provider-bound declarative connectors this plugin has materialized - * (ADR-0097), keyed by connector name. `signature` is a stable hash of the + * (ADR-0097), keyed by instance ({@link connectorInstanceKey}: the name, or + * `package/name` for a package's instance, ADR-0150 D9). `signature` is a stable hash of the * entry's materialization inputs so a `metadata:reloaded` reconcile can tell * an unchanged instance (skip — don't re-open its MCP connection) from a * changed one (re-materialize). `close` is the optional teardown (e.g. an MCP @@ -1568,10 +1639,17 @@ export class AutomationServicePlugin implements Plugin { * the registered def carries none, and the connector sync executor reads * only a `rest` / `openapi` instance, so the answer is recorded here. */ - private materializedConnectors = new Map void | Promise }>(); + private materializedConnectors = new Map void | Promise; + }>(); /** * Degraded declarative instances (#3017): provider-bound entries whose - * upstream was unreachable at materialization. Keyed by connector name; + * upstream was unreachable at materialization. Keyed by instance, as + * {@link materializedConnectors} is; * `attempts` drives the retry backoff, `signature` detects a config edit * (which resets the backoff), `reason` is what the registered husk surfaces. * Disjoint from {@link materializedConnectors} EXCEPT when a *changed* @@ -1591,7 +1669,14 @@ export class AutomationServicePlugin implements Plugin { * fault is held the same way, with the configuration reason: only a change * of its declaration or a restart re-attempts it. */ - private degradedInstances = new Map(); + private degradedInstances = new Map(); /** * [#27237] References whose upstream refused a value the credential door * does not hold — an environment variable or the host's resolver — keyed @@ -1762,6 +1847,18 @@ export class AutomationServicePlugin implements Plugin { * registry, and supplies the execution context (`opts.context`) built from * the job's `organization`. */ + /** + * [#20919, #31699] The provider a materialized declarative instance was + * built by: the instance of `packageId` (`null`: of no package), or, with + * `packageId` absent, the one materialized instance of `name` (`undefined` + * when there are two, never one of them). + */ + private materializedProviderOf(name: string, packageId?: string | null): string | undefined { + if (packageId !== undefined) return this.materializedConnectors.get(connectorInstanceKey(name, packageId))?.provider; + const ofName = [...this.materializedConnectors.values()].filter((tracked) => tracked.name === name); + return ofName.length === 1 ? ofName[0].provider : undefined; + } + async pullConnectorSource(opts: ConnectorPullOptions): Promise { const ctx = this.ctx; const engine = this.engine; @@ -1782,7 +1879,9 @@ export class AutomationServicePlugin implements Plugin { { protocol, registry: engine, - providerOf: (connector) => this.materializedConnectors.get(connector)?.provider, + // [#31699] The instance the pull resolved, by its package; with none + // addressed, the one materialized instance of the name. + providerOf: (connector, packageId) => this.materializedProviderOf(connector, packageId), logger: ctx.logger, // [ADR-0150 D3, #32071] A pull naming the package that declares // its job reads the mapping from that package. @@ -2974,13 +3073,24 @@ export class AutomationServicePlugin implements Plugin { */ private captureReloadedConnectors(payload: unknown): void { const metadata = (payload as { metadata?: Record } | undefined)?.metadata; - const items = metadata?.connectors; - if (!Array.isArray(items)) return; + const carried = metadata?.connectors; + if (!Array.isArray(carried)) return; const owners = new Set(); const manifestId = (metadata as { manifest?: { id?: unknown } } | undefined)?.manifest?.id ?? (metadata as { id?: unknown } | undefined)?.id; - if (typeof manifestId === 'string' && manifestId.length > 0) owners.add(manifestId); + const packageId = typeof manifestId === 'string' && manifestId.length > 0 ? manifestId : undefined; + if (packageId) owners.add(packageId); + // [#31699 PR 3] An item with no stamp is its manifest's, as + // `_parseAndRegisterArtifact` stamps it in the registry: two packages + // may each declare the name, and the merge supersedes by (package, name). + // Stamped here, once, so the merge and the host-entry judgment + // (`declaringPackageReadersOrNone`, by identity) see the same object. + const items = carried.map((item) => + packageId && item && typeof item === 'object' && (item as { _packageId?: unknown })._packageId === undefined + ? { ...item, _packageId: packageId } + : item, + ); for (const item of items) { const owner = (item as { _packageId?: unknown })?._packageId; if (typeof owner === 'string' && owner.length > 0) owners.add(owner); @@ -2988,31 +3098,6 @@ export class AutomationServicePlugin implements Plugin { this.reloadedConnectors = { items, owners }; } - /** - * [ADR-0150 D3] The refusal of every enabled provider-bound declared - * connector name that resolves to no single holder, read over the ObjectQL - * registry ({@link refusedConnectorNames}). A composition with no registry - * has no package coordinate to resolve against, and refuses nothing here. - */ - private refusedDeclaredConnectorNames(ctx: PluginContext, declared: readonly unknown[]): Map { - let registry: PackageScopedRegistry | undefined; - try { - registry = packageScopedRegistryOf(ctx.getService<{ registry?: unknown }>('objectql')?.registry); - } catch { - registry = undefined; // no registry service - } - if (!registry) return new Map(); - const names: string[] = []; - for (const raw of declared) { - const entry = raw as DeclaredConnectorItem; - if (typeof entry?.name !== 'string' || entry.name.length === 0) continue; - if (typeof entry.provider !== 'string' || entry.provider.length === 0) continue; - if (entry.enabled === false) continue; - names.push(entry.name); - } - return refusedConnectorNames(registry, names); - } - /** * [#28534] The readers {@link nonHostDeclaringPackageOf} judges a * connector entry's origin with, off the `objectql` engine the declared @@ -3089,11 +3174,13 @@ export class AutomationServicePlugin implements Plugin { opts: { post: boolean }, ): Promise { let registryItems: unknown[] | undefined; + let byPackage = false; try { const ql = ctx.getService<{ registry?: { listItems?: (type: string) => unknown[] }; }>('objectql'); registryItems = ql?.registry?.listItems?.('connector') ?? []; + byPackage = packageScopedRegistryOf(ql?.registry) !== undefined; } catch { registryItems = undefined; // no registry service } @@ -3116,7 +3203,7 @@ export class AutomationServicePlugin implements Plugin { if (!this.reloadedConnectors) return undefined; base = []; } - return mergeDeclaredConnectorSources(base, this.reloadedConnectors); + return mergeDeclaredConnectorSources(base, this.reloadedConnectors, { byPackage }); } /** @@ -3132,8 +3219,19 @@ export class AutomationServicePlugin implements Plugin { // Both call sites are post-boot hooks (`kernel:ready`, `metadata:reloaded`). const declared = await this.readDeclaredConnectorItems(ctx, { post: true }); if (!declared || declared.length === 0) return; - const live = new Set(this.engine.getConnectorDescriptors().map((d) => d.name)); - const inert = findInertDeclaredConnectors(declared, live); + // [#31699 PR 3] Live is judged per entry, as a dispatch would read it: + // the entry's own package's caller is served an instance (a plugin's + // connector of the name, or the package's own). Two packages may each + // declare the name, so another package's live instance serves nothing + // of this entry's and does not silence it. + const engine = this.engine; + const resolve = connectorNameResolver(ctx); + const unserved = declared.filter((entry) => { + const name = (entry as DeclaredConnectorItem)?.name; + if (typeof name !== 'string' || name.length === 0) return true; + return engine.resolveConnectorInstanceFor(name, connectorInstancePackage(resolve, entry)).status !== 'instance'; + }); + const inert = findInertDeclaredConnectors(unserved, new Set()); if (inert.length === 0) return; ctx.logger.warn( `[Automation] ${inert.length} declarative connector(s) declare actions but are not registered ` + @@ -3320,35 +3418,65 @@ export class AutomationServicePlugin implements Plugin { ctx.logger.error(msg, undefined, cause === undefined ? undefined : describeThrownForLog(cause)); }; - // [ADR-0150 D3, epic #31527 child E5] A declared name that resolves to - // no single holder (two packages declare it) is refused, naming every - // candidate, and never materialized: no instance is picked by list - // order ({@link refusedConnectorNames}). - const refusedNames = this.refusedDeclaredConnectorNames(ctx, declared); - for (const [name, refusal] of refusedNames) { - const stored = declared.some((raw) => (raw as DeclaredConnectorItem)?.name === name && storedEntry(raw)); - fail(`[Automation] connector instance '${name}' is not materialized: ${refusal.message}`, undefined, stored); - } - - // Build the desired set: enabled provider-bound instances, keyed by name. - // A descriptor (no `provider`) or an `enabled: false` instance is not - // desired — if we materialized it before, it is torn down below. - const desired = new Map(); + // Build the desired set: enabled provider-bound instances, keyed by + // instance ([ADR-0150 D4, #31699 PR 3] package and name: two packages' + // instances of one name are two instances, each materialized as its + // own). A descriptor (no `provider`) or an `enabled: false` instance is + // not desired — if we materialized it before, it is torn down below. + const resolveName = connectorNameResolver(ctx); + // [ADR-0150 D9, #31699] Two packages' instances of one name live side + // by side only where the package-scoped registry can judge them (the + // install door admits a second holder of a name only from another + // namespace). A composition with no registry to ask keeps one instance + // per name, as before the narrowing: red line 1, never loosened where + // it cannot be judged. + let judgedByPackage = false; + try { + judgedByPackage = packageScopedRegistryOf(ctx.getService<{ registry?: unknown }>('objectql')?.registry) !== undefined; + } catch { /* no ObjectQL: nothing to judge by */ } + const desired = new Map(); for (const raw of declared) { const entry = raw as DeclaredConnectorItem; if (typeof entry?.name !== 'string' || entry.name.length === 0) continue; if (typeof entry.provider !== 'string' || entry.provider.length === 0) continue; const bound = entry as DeclaredConnectorItem & { name: string; provider: string }; if (bound.enabled === false) continue; - if (refusedNames.has(bound.name)) continue; // [#28713] Held until every plugin has started ({@link holdStoredEntries}). if (this.holdStoredEntries && storedEntry(bound)) { this.storedEntriesHeld = true; continue; } - if (desired.has(bound.name)) { + // [ADR-0150 D3, #31699 PR 3] An entry with no package of its own, + // under a name two packages hold, is no instance anyone can address: + // refused, naming every candidate, and never materialized as one of + // them ({@link connectorInstanceRefusal}). Each package's own entry + // is its own instance, materialized beside the other's. + const refusal = connectorInstanceRefusal(resolveName, bound); + if (refusal !== undefined) { + fail(`[Automation] connector instance '${bound.name}' is not materialized: ${refusal.message}`, undefined, storedEntry(bound)); + continue; + } + const packageId = connectorInstancePackage(resolveName, bound); + const key = connectorInstanceKey(bound.name, packageId); + if (desired.has(key)) { fail( - `[Automation] duplicate declarative connector instance name '${bound.name}' — connector names must be unique (ADR-0097).`, + `[Automation] duplicate declarative connector instance name '${bound.name}'` + + `${packageId === null ? '' : ` in package '${packageId}'`} — connector names must be unique ` + + '(ADR-0097), within a package (ADR-0150 D4).', + undefined, + storedEntry(bound), + ); + continue; + } + if (!judgedByPackage && [...desired.values()].some((d) => d.entry.name === bound.name)) { + fail( + `[Automation] duplicate declarative connector instance name '${bound.name}' — connector names must be ` + + 'unique (ADR-0097); two packages may each declare one only where the package-scoped registry ' + + 'tells their instances apart (ADR-0150 D9), and this composition serves none.', undefined, storedEntry(bound), ); @@ -3357,9 +3485,10 @@ export class AutomationServicePlugin implements Plugin { // [#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, { + desired.set(key, { entry: bound, - signature: `${connectorInstanceSignature(bound)}|package:${this.declaredInstance(ctx, bound).packageId ?? ''}`, + packageId, + signature: `${connectorInstanceSignature(bound)}|package:${packageId ?? ''}`, }); } @@ -3402,13 +3531,14 @@ export class AutomationServicePlugin implements Plugin { // the other organizations keep their cached tokens), and neither does // a refresh that rotates the token. const connectionStates = new Map(); - for (const [name, d] of desired) { + for (const [key, d] of desired) { + const name = d.entry.name; const auth = d.entry.auth; if (auth?.type !== 'oauth2' || auth.grant !== 'authorization_code') continue; let state: ConnectionStateOfInstance; try { // [#31699] An organization whose read is refused has no connection to materialize with. - const rows = (await this.connectorConnectionStoreOrNone().listFor(name, connectorInstancePackage(connectorNameResolver(ctx), d.entry))) + const rows = (await this.connectorConnectionStoreOrNone().listFor(name, d.packageId)) .filter((r) => r.conflict === undefined); const reconnectRequired = rows.filter((r) => r.status === 'reconnect_required').map((r) => r.organizationId).sort(); const discovery = discoveryOrganizationOf(rows); @@ -3425,11 +3555,11 @@ export class AutomationServicePlugin implements Plugin { } catch (err) { state = { kind: 'unreadable' }; ctx.logger.warn( - `[Automation] the connections of connector instance '${name}' could not be read; it retries.`, + `[Automation] the connections of connector instance '${name}'${inPackage(d.packageId)} could not be read; it retries.`, describeThrownForLog(err), ); } - connectionStates.set(name, state); + connectionStates.set(key, state); d.signature += state.kind === 'unreadable' ? '|connections:unreadable' : state.connected.length > 0 @@ -3451,35 +3581,37 @@ export class AutomationServicePlugin implements Plugin { // 1. Remove connectors we previously materialized that are no longer // desired (deleted from the stack, or newly `enabled: false`). - for (const [name, tracked] of [...this.materializedConnectors]) { - if (desired.has(name)) continue; - await this.dematerializeConnector(engine, name, tracked, ctx); + for (const [key, tracked] of [...this.materializedConnectors]) { + if (desired.has(key)) continue; + await this.dematerializeConnector(engine, { key, name: tracked.name, packageId: tracked.packageId }, tracked, ctx); } // Degraded instances (#3017) whose entry vanished / was disabled are // dropped too: unregister the husk (idempotent — a kept-serving old // connector was already torn down above) and forget the retry. - 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)`); + for (const [key, degraded] of [...this.degradedInstances]) { + if (desired.has(key)) continue; + this.degradedInstances.delete(key); + // [#31699 PR 3] The instance itself: another package's of the name stays. + try { engine.unregisterConnector(degraded.name, degraded.packageId); } catch { /* ignore */ } + ctx.logger.info(`[Automation] dropped degraded connector instance '${degraded.name}'${inPackage(degraded.packageId)} (no longer declared)`); } - for (const name of [...this.credentialRefusalAttempts.keys()]) { - if (!desired.has(name)) this.credentialRefusalAttempts.delete(name); + for (const key of [...this.credentialRefusalAttempts.keys()]) { + if (!desired.has(key)) this.credentialRefusalAttempts.delete(key); } // 2. Add new instances and re-materialize changed ones (signature diff). let changed = 0; - for (const [name, { entry, signature }] of desired) { - const existing = this.materializedConnectors.get(name); + for (const [key, { entry, packageId, signature }] of desired) { + const name = entry.name; + const instance = { key, name, packageId }; + const existing = this.materializedConnectors.get(key); if (existing && existing.signature === signature) { // Unchanged — leave the live connector as-is. If a retry was // pending for a *changed* config that has since been reverted, // the live connector is already the desired one: cancel it. - if (this.degradedInstances.delete(name)) { + if (this.degradedInstances.delete(key)) { ctx.logger.info( - `[Automation] connector instance '${name}' reverted to its live configuration; pending retry cancelled`, + `[Automation] connector instance '${name}'${inPackage(packageId)} reverted to its live configuration; pending retry cancelled`, ); } continue; @@ -3488,7 +3620,7 @@ export class AutomationServicePlugin implements Plugin { // [#27237] Held: its upstream refused this very stored value. The // next attempt is the next change of the credential or the entry, // or a restart. - const held = this.degradedInstances.get(name); + const held = this.degradedInstances.get(key); if (held?.held && held.signature === signature) continue; const provider = entry.provider; @@ -3533,10 +3665,10 @@ export class AutomationServicePlugin implements Plugin { ? oauth2NotServableReason(name, { ...entry, provider }, entry.auth, engine.providerAppliesCredentialHandle(provider)) : undefined; if (grantRefusal !== undefined) { - if (existing) await this.dematerializeConnector(engine, name, existing, ctx, 'no longer servable'); - this.grantHandles.delete(name); + if (existing) await this.dematerializeConnector(engine, instance, existing, ctx, 'no longer servable'); + this.grantHandles.delete(key); this.failDegradedConnectorInstance(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3575,7 +3707,7 @@ export class AutomationServicePlugin implements Plugin { } if (resolution.kind !== 'resolved') { await this.degradeConnectorForCredential(engine, ctx, { - name, entry, provider, signature, existing, ref, resolution, + ...instance, entry, provider, signature, existing, ref, resolution, }); continue; } @@ -3601,7 +3733,7 @@ export class AutomationServicePlugin implements Plugin { } if (resolution.kind !== 'resolved') { await this.degradeConnectorForCredential(engine, ctx, { - name, entry, provider, signature, existing, ref: vendorRef, resolution, + ...instance, entry, provider, signature, existing, ref: vendorRef, resolution, }); continue; } @@ -3641,10 +3773,10 @@ export class AutomationServicePlugin implements Plugin { // fault and never fails a boot: it is held degraded, "not // connected" or "reconnect required", until a connect. if (entry.auth.grant === 'authorization_code') { - const state = connectionStates.get(name); + const state = connectionStates.get(key); if (state?.kind === 'unreadable') { this.degradeConnectorInstance(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3656,7 +3788,7 @@ export class AutomationServicePlugin implements Plugin { } if (state === undefined || state.connected.length === 0) { await this.holdConnectorUntilConnected(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3668,8 +3800,8 @@ export class AutomationServicePlugin implements Plugin { continue; } } - credentialHandle = this.createGrantHandle(ctx, name, entry, entry.auth, credential?.value); - const state = entry.auth.grant === 'authorization_code' && provider === 'mcp' ? connectionStates.get(name) : undefined; + credentialHandle = this.createGrantHandle(ctx, name, packageId, entry, entry.auth, credential?.value); + const state = entry.auth.grant === 'authorization_code' && provider === 'mcp' ? connectionStates.get(key) : undefined; if (state?.kind === 'read' && state.discovery !== undefined) { materializingHandle = askingDuringMaterializationAs(credentialHandle, state.discovery); discoveryConnection = { @@ -3788,7 +3920,7 @@ export class AutomationServicePlugin implements Plugin { // and the secret left alone (#26702). if (isConnectorCredentialRejected(thrown) && discoveryConnection !== undefined) { await this.holdConnectorForRefusedConnection(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3805,7 +3937,7 @@ export class AutomationServicePlugin implements Plugin { // retry loop against the same value. if (isConnectorCredentialRejected(thrown)) { await this.holdConnectorForRejectedCredential(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3826,7 +3958,7 @@ export class AutomationServicePlugin implements Plugin { // the instance at once. if (isConnectorUpstreamChanged(thrown)) { this.degradeConnectorInstance(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3839,7 +3971,7 @@ export class AutomationServicePlugin implements Plugin { } if (isConnectorUpstreamUnavailable(thrown)) { this.degradeConnectorInstance(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3862,9 +3994,9 @@ export class AutomationServicePlugin implements Plugin { // [#27992] A configuration fault met by an instance that is // degraded — its backoff retry, or a reload — ends the retry: // ADR-0097 does not retry a configuration fault. - if (!opts.fatal && this.degradedInstances.has(name)) { + if (!opts.fatal && this.degradedInstances.has(key)) { this.failDegradedConnectorInstance(engine, ctx, { - name, + ...instance, entry, provider, signature, @@ -3899,7 +4031,7 @@ export class AutomationServicePlugin implements Plugin { // what the factory named its def, so discovery, dispatch, and the // conflict rule all agree with the metadata the author wrote. const def = { ...materialization.def, name }; - const tracked = { signature, provider, close: materialization.close }; + const tracked = { name, packageId, signature, provider, close: materialization.close }; // [#27237] A credentialed instance's calls are watched for the // upstream's 401 / 403 (rest and openapi answer them as a result), // and — unless the provider proved the credential while @@ -3914,7 +4046,7 @@ export class AutomationServicePlugin implements Plugin { // that answer too; the provider's own covers a `401`. const handlers = credential && ref !== undefined && credentialHandle === undefined ? this.watchForCredentialRejection(engine, ctx, { - name, entry, provider, signature, ref, credential, tracked, proven, + ...instance, entry, provider, signature, ref, credential, tracked, proven, }, materialization.handlers) : credentialHandle && entry.auth?.type === 'app-credential' ? retryOnVendorTokenRefusal(name, entry.auth.vendor, credentialHandle, materialization.handlers) @@ -3926,18 +4058,18 @@ export class AutomationServicePlugin implements Plugin { def, withFailureTextRewritten(handlers, connectorReadWithheldText(entry)), 'declarative', - this.declaredInstance(ctx, entry), + { packageId }, ); - this.materializedConnectors.set(name, tracked); - if (credentialHandle) this.grantHandles.set(name, credentialHandle); - else this.grantHandles.delete(name); + this.materializedConnectors.set(key, tracked); + if (credentialHandle) this.grantHandles.set(key, credentialHandle); + else this.grantHandles.delete(key); // Success clears any pending degraded retry — including replacing a // registered husk (registerConnector above overwrote it). - const recovered = this.degradedInstances.delete(name); + const recovered = this.degradedInstances.delete(key); changed++; ctx.logger.info( `[Automation] ${recovered ? 'recovered' : existing ? 're-materialized' : 'materialized'} ` + - `connector instance '${name}' via provider '${provider}' (${def.actions?.length ?? 0} action(s))`, + `connector instance '${name}'${inPackage(packageId)} via provider '${provider}' (${def.actions?.length ?? 0} action(s))`, ); // [#27237] Only a provider that proved the credential while // materializing (`credentialVerified` — mcp's handshake) says the @@ -3945,7 +4077,7 @@ export class AutomationServicePlugin implements Plugin { // where a `2xx` only stamps a `set` row's time; neither that nor a // materialization alone turns a `rejected` row back to `set`. if (credential && ref !== undefined && proven && credentialHandle === undefined) { - await this.recordCredentialProven(ctx, name, ref, credential); + await this.recordCredentialProven(ctx, instance, ref, credential); } } @@ -3993,6 +4125,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -4018,9 +4154,9 @@ export class AutomationServicePlugin implements Plugin { fault?: 'unavailable' | 'changed'; }, ): void { - const prior = this.degradedInstances.get(info.name); + const prior = this.degradedInstances.get(info.key); const attempts = prior && prior.signature === info.signature ? prior.attempts + 1 : 1; - this.degradedInstances.set(info.name, { attempts, signature: info.signature, reason: info.reason }); + this.degradedInstances.set(info.key, { name: info.name, packageId: info.packageId, attempts, signature: info.signature, reason: info.reason }); if (!info.hasLive) { try { @@ -4036,7 +4172,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', info.cause, undefined, - this.declaredInstance(ctx, info.entry), + { packageId: info.packageId }, ); } catch (err) { // Can't even register the husk (e.g. the entry's def no longer @@ -4058,7 +4194,7 @@ export class AutomationServicePlugin implements Plugin { // which would ship the thrown value's stack on every retry (#5575). const changed = info.fault === 'changed'; ctx.logger.error( - `[Automation] connector instance '${info.name}' (provider '${info.provider}') ` + + `[Automation] connector instance '${info.name}'${inPackage(info.packageId)} (provider '${info.provider}') ` + (changed ? 'serves a tool definition that differs from its toolsSnapshot — ' : 'upstream unavailable — ') + @@ -4088,6 +4224,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -4096,7 +4236,7 @@ export class AutomationServicePlugin implements Plugin { cause: unknown; }, ): void { - this.degradedInstances.set(info.name, { attempts: 1, signature: info.signature, reason: info.reason, held: true }); + this.degradedInstances.set(info.key, { name: info.name, packageId: info.packageId, attempts: 1, signature: info.signature, reason: info.reason, held: true }); if (!info.hasLive) { try { // [#28016] Held: the husk says so, and a dispatch names the edit. @@ -4106,7 +4246,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', info.cause, { kind: 'declaration' }, - this.declaredInstance(ctx, info.entry), + { packageId: info.packageId }, ); } catch (err) { ctx.logger.warn( @@ -4121,7 +4261,7 @@ export class AutomationServicePlugin implements Plugin { // no thrown value: its reason rides `meta` instead, so the record never // renders `describeThrownForLog(undefined)`, the string "undefined". ctx.logger.error( - `[Automation] failed to materialize connector instance '${info.name}' via provider '${info.provider}' (ADR-0097): ` + + `[Automation] failed to materialize connector instance '${info.name}'${inPackage(info.packageId)} via provider '${info.provider}' (ADR-0097): ` + 'a configuration fault, so the instance is no longer retried. ' + (info.hasLive ? 'The previously-materialized connector keeps serving. ' : '') + 'Fix its declaration; an edit or a restart re-attempts it.', @@ -4173,6 +4313,7 @@ export class AutomationServicePlugin implements Plugin { private createGrantHandle( ctx: PluginContext, name: string, + packageId: string | null, entry: DeclaredConnectorItem, auth: OAuth2InstanceAuth, clientSecret: string | undefined, @@ -4182,9 +4323,13 @@ export class AutomationServicePlugin implements Plugin { // the client its administrator entered (`clientSource: 'installer'`). return createOAuth2GrantHandle({ connector: name, - // [#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), + // [#31699 PR 3] The instance's own package, fixed: the handle is + // the instance's, and an instance whose package moves (an unstamped + // entry's holder replaced) is re-materialized under the new one — + // its signature carries the package — with a handle of its own. + // Asked on every read it could name another instance's connections + // between a second holder's arrival and the next reconcile. + packageId, config: { grant: auth.grant, ...(takesInstallerClient(auth) ? { clientSource: 'installer' as const } : {}), @@ -4229,6 +4374,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -4243,14 +4392,14 @@ export class AutomationServicePlugin implements Plugin { let marked = false; try { const store = this.connectorConnectionStoreOrNone(); - const record = await store.read(connection.organizationId, name, connectorInstancePackage(connectorNameResolver(ctx), info.entry)); + const record = await store.read(connection.organizationId, name, info.packageId); if (record && record.status === 'connected' && record.connectedAt === connection.connectedAt) { await store.markReconnectRequired(record, reason); marked = true; } } catch (err) { ctx.logger.warn( - `[Automation] connector instance '${name}': the connection of organization '${connection.organizationId}' ` + `[Automation] connector instance '${name}'${inPackage(info.packageId)}: the connection of organization '${connection.organizationId}' ` + 'could not be marked to be reconnected; the instance retries.', describeThrownForLog(err), ); @@ -4258,6 +4407,8 @@ export class AutomationServicePlugin implements Plugin { if (!marked) { this.degradeConnectorInstance(engine, ctx, { name, + key: info.key, + packageId: info.packageId, entry: info.entry, provider: info.provider, signature: info.signature, @@ -4268,12 +4419,12 @@ export class AutomationServicePlugin implements Plugin { }); return; } - this.degradedInstances.set(name, { attempts: 1, signature: info.signature, reason, held: true }); + this.degradedInstances.set(info.key, { name, packageId: info.packageId, 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' }, - this.declaredInstance(ctx, info.entry), + { packageId: info.packageId }, ); } catch (err) { ctx.logger.warn( @@ -4284,7 +4435,7 @@ export class AutomationServicePlugin implements Plugin { } } ctx.logger.warn( - `[Automation] connector instance '${name}' (provider '${info.provider}'): its MCP server refused the token of ` + `[Automation] connector instance '${name}'${inPackage(info.packageId)} (provider '${info.provider}'): its MCP server refused the token of ` + `organization '${connection.organizationId}' while it listed its tools (HTTP ${info.status}); that connection ` + 'needs to be reconnected (ADR-0143 D4).', ); @@ -4304,6 +4455,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -4311,8 +4466,8 @@ export class AutomationServicePlugin implements Plugin { reason: string; }, ): Promise { - if (info.existing) await this.dematerializeConnector(engine, info.name, info.existing, ctx, 'no working connection'); - this.degradedInstances.set(info.name, { attempts: 1, signature: info.signature, reason: info.reason, held: true }); + if (info.existing) await this.dematerializeConnector(engine, info, info.existing, ctx, 'no working connection'); + this.degradedInstances.set(info.key, { name: info.name, packageId: info.packageId, attempts: 1, signature: info.signature, reason: info.reason, held: true }); try { engine.registerDegradedConnector( this.buildDegradedHuskDef(info.name, info.entry), @@ -4320,7 +4475,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', undefined, { kind: 'connection' }, - this.declaredInstance(ctx, info.entry), + { packageId: info.packageId }, ); } catch (err) { ctx.logger.warn( @@ -4329,7 +4484,7 @@ export class AutomationServicePlugin implements Plugin { describeThrownForLog(err), ); } - ctx.logger.warn(`[Automation] connector instance '${info.name}' (provider '${info.provider}') is degraded: ${info.reason}.`); + ctx.logger.warn(`[Automation] connector instance '${info.name}'${inPackage(info.packageId)} (provider '${info.provider}') is degraded: ${info.reason}.`); } /** ADR-0143 D5 — where begun connects wait: the cluster KV, or this process on a single node. */ @@ -4393,7 +4548,8 @@ export class AutomationServicePlugin implements Plugin { const serverUrl = mcpDiscoveryServerUrl(entry, auth); if (serverUrl === undefined) return undefined; const store = this.connectorConnectionStoreOrNone(); - const existing = installerClient ? undefined : await store.readOrRefuse(organizationId, name, connectorInstancePackage(connectorNameResolver(ctx), entry)); + const packageId = connectorInstancePackage(connectorNameResolver(ctx), entry); + const existing = installerClient ? undefined : await store.readOrRefuse(organizationId, name, packageId); if (existing?.hasRegisteredClient) { let kept: McpAuthorizationClient | undefined; try { @@ -4422,7 +4578,7 @@ export class AutomationServicePlugin implements Plugin { ...(typeof entry.requestTimeoutMs === 'number' ? { timeoutMs: entry.requestTimeoutMs } : {}), }); ctx.logger.info( - `[Automation] connector instance '${name}': the MCP authorization flow found its authorization server` + `[Automation] connector instance '${name}'${inPackage(packageId)}: the MCP authorization flow found its authorization server` + `${client.registered ? ' and registered a client' : ''} for organization '${organizationId}'.`, ); return client; @@ -4464,7 +4620,12 @@ export class AutomationServicePlugin implements Plugin { throw credentialDoorRefusal('A connector instance name is required.', 'VALIDATION_ERROR', 400); } const declared = await this.readDeclaredConnectorItems(ctx, { post: true }); - const { entry, packageId } = this.connectionDoorInstance(ctx, name, declared ?? [], recordedPackage); + // [ADR-0150 D5, #31699 PR 3] The addressed door + // (`/automation/connectors/:ns/:name/connection`) names the package + // the domain admitted the address to: that package's instance, read + // exactly, as a recorded package is. + const addressed = typeof request?.package === 'string' && request.package.length > 0 ? request.package : undefined; + const { entry, packageId } = this.connectionDoorInstance(ctx, name, declared ?? [], recordedPackage !== undefined ? recordedPackage : addressed); if (!entry || typeof entry.provider !== 'string' || entry.provider.length === 0) { throw credentialDoorRefusal( `No installed package declares a provider-bound connector instance '${name}'.`, @@ -4498,17 +4659,6 @@ 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 @@ -4727,7 +4877,7 @@ export class AutomationServicePlugin implements Plugin { ...(client ? { client } : {}), ...(installerClient ? { installerClient } : {}), }); - ctx.logger.info(`[Automation] connect of connector instance '${name}' begun for organization '${organizationId}' by user '${userId}'.`); + ctx.logger.info(`[Automation] connect of connector instance '${name}'${inPackage(packageId)} begun for organization '${organizationId}' by user '${userId}'.`); const resource = auth.resource ?? client?.resource; return { connector: name, @@ -4888,7 +5038,7 @@ export class AutomationServicePlugin implements Plugin { : {}), }); ctx.logger.info( - `[Automation] connector instance '${name}' connected for organization '${organizationId}'` + `[Automation] connector instance '${name}'${inPackage(packageId)} connected for organization '${organizationId}'` + `${userId ? ` by user '${userId}'` : ''}; reconciling it.`, ); await this.reconcileDeclaredConnectors(ctx, { fatal: false }); @@ -4896,7 +5046,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, record.id); + this.grantHandles.get(connectorInstanceKey(name, packageId))?.seed(organizationId, record.revision, token, record.id); return this.describeConnection(name, organizationId, record); } @@ -4907,9 +5057,9 @@ export class AutomationServicePlugin implements Plugin { const removed = await this.onReconcileQueue(async () => { const gone = await this.connectorConnectionStoreOrNone().revoke(organizationId, name, userId, packageId); if (!gone) return false; - this.grantHandles.get(name)?.forget(organizationId); + this.grantHandles.get(connectorInstanceKey(name, packageId))?.forget(organizationId); ctx.logger.info( - `[Automation] connection of connector instance '${name}' revoked for organization '${organizationId}'` + `[Automation] connection of connector instance '${name}'${inPackage(packageId)} revoked for organization '${organizationId}'` + `${userId ? ` by user '${userId}'` : ''}; reconciling it.`, ); await this.reconcileDeclaredConnectors(ctx, { fatal: false }); @@ -5007,6 +5157,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -5020,12 +5174,12 @@ export class AutomationServicePlugin implements Plugin { : info.resolution.reason; let hasLive = info.existing !== undefined; if (info.resolution.kind === 'missing' && info.existing) { - await this.dematerializeConnector(engine, info.name, info.existing, ctx, `its credential '${info.ref}' is no longer set`); + await this.dematerializeConnector(engine, info, info.existing, ctx, `its credential '${info.ref}' is no longer set`); hasLive = false; } - const prior = this.degradedInstances.get(info.name); + const prior = this.degradedInstances.get(info.key); const repeat = prior !== undefined && prior.signature === info.signature && prior.reason === reason; - this.degradedInstances.set(info.name, { + this.degradedInstances.set(info.key, { name: info.name, packageId: info.packageId, attempts: repeat ? prior.attempts + 1 : 1, signature: info.signature, reason, @@ -5036,7 +5190,7 @@ export class AutomationServicePlugin implements Plugin { try { engine.registerDegradedConnector( this.buildDegradedHuskDef(info.name, info.entry), reason, 'declarative', undefined, undefined, - this.declaredInstance(ctx, info.entry), + { packageId: info.packageId }, ); } catch (err) { ctx.logger.warn( @@ -5047,7 +5201,7 @@ export class AutomationServicePlugin implements Plugin { } } ctx.logger.warn( - `[Automation] connector instance '${info.name}' (provider '${info.provider}') is degraded: ${reason}.` + + `[Automation] connector instance '${info.name}'${inPackage(info.packageId)} (provider '${info.provider}') is degraded: ${reason}.` + (hasLive ? ' The previously-materialized connector keeps serving.' : ''), ); } @@ -5059,17 +5213,24 @@ export class AutomationServicePlugin implements Plugin { * `enabled: false` is listed too: an administrator may fill its credential * before enabling it. */ - private async declaredCredentialRefs(ctx: PluginContext): Promise>> { + private async declaredCredentialRefs(ctx: PluginContext): Promise> { const declared = (await this.readDeclaredConnectorItems(ctx, { post: true })) ?? []; - const out = new Map>(); + const resolve = connectorNameResolver(ctx); + const out = new Map(); for (const raw of declared) { const entry = raw as DeclaredConnectorItem & { _packageId?: unknown }; if (typeof entry?.name !== 'string' || entry.name.length === 0) continue; if (typeof entry.provider !== 'string' || entry.provider.length === 0) continue; const packageId = typeof entry._packageId === 'string' && entry._packageId.length > 0 ? entry._packageId : undefined; + // [#31699 PR 3] The instance this entry is (its own package, else + // the name's holder's), or none when it is refused: the listing + // reads that instance's state, and names each instance once. + const instance = connectorInstanceRefusal(resolve, entry) ? false : connectorInstancePackage(resolve, entry); for (const ref of credentialRefsOf(entry.auth)) { const list = out.get(ref) ?? []; - if (!list.some((c) => c.name === entry.name)) list.push({ name: entry.name, ...(packageId ? { packageId } : {}) }); + if (!list.some((c) => c.name === entry.name && c.instance === instance)) { + list.push({ name: entry.name, ...(packageId ? { packageId } : {}), instance }); + } out.set(ref, list); } } @@ -5092,12 +5253,20 @@ export class AutomationServicePlugin implements Plugin { private async describeCredentialRef( chain: ConnectorCredentialChain, ref: string, - declaredBy: Array<{ name: string; packageId?: string }> | undefined, + declaredBy: DeclaredCredentialUser[] | undefined, rows: ReadonlyMap, ): Promise { const probe = await probeConnectorCredential(chain, ref, rows); const record = chain.store ? rows.get(ref) : undefined; - const descriptors = new Map((this.engine?.getConnectorDescriptors() ?? []).map((d) => [d.name, d])); + const descriptors = this.engine?.getConnectorDescriptors() ?? []; + // [ADR-0150 D9, #31699] Two packages' instances of one name are two + // descriptors: an entry reads its own instance's (by the instance's + // package, not its stamp: an environment row or a compatibility entry + // is the holder's instance), and a refused entry reads none. + const descriptorOf = (c: DeclaredCredentialUser) => + c.instance === false + ? undefined + : descriptors.find((d) => d.name === c.name && (d.packageId ?? null) === c.instance); // A refused value the door does not hold has no row: its refusal is // kept in memory, and reported while the reference still resolves from there. const refusal = this.credentialRefusals.get(ref); @@ -5110,7 +5279,7 @@ export class AutomationServicePlugin implements Plugin { writable: probe.source !== 'env' && chain.store !== undefined, declared: declaredBy !== undefined, connectors: (declaredBy ?? []).map((c) => { - const d = descriptors.get(c.name); + const d = descriptorOf(c); return { name: c.name, ...(c.packageId ? { packageId: c.packageId } : {}), @@ -5398,6 +5567,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -5411,19 +5584,19 @@ export class AutomationServicePlugin implements Plugin { ): Promise { let hasLive = info.live !== undefined; if (info.takeDown && info.live) { - await this.dematerializeConnector(engine, info.name, info.live, ctx, 'its upstream refused its credential'); + await this.dematerializeConnector(engine, info, info.live, ctx, 'its upstream refused its credential'); hasLive = false; } const stored = info.credential?.source === 'object' ? info.credential.record : undefined; const held = info.credential === undefined || stored !== undefined; let attempts = 1; if (held) { - this.degradedInstances.set(info.name, { attempts, signature: info.signature, reason: info.reason, held: true }); + this.degradedInstances.set(info.key, { name: info.name, packageId: info.packageId, attempts, signature: info.signature, reason: info.reason, held: true }); } else { - const prior = this.credentialRefusalAttempts.get(info.name); + const prior = this.credentialRefusalAttempts.get(info.key); attempts = prior && prior.signature === info.signature ? prior.attempts + 1 : 1; - this.credentialRefusalAttempts.set(info.name, { signature: info.signature, attempts }); - this.degradedInstances.set(info.name, { attempts, signature: info.signature, reason: info.reason }); + this.credentialRefusalAttempts.set(info.key, { signature: info.signature, attempts }); + this.degradedInstances.set(info.key, { name: info.name, packageId: info.packageId, attempts, signature: info.signature, reason: info.reason }); const source = info.credential?.source; if (info.ref !== undefined && (source === 'env' || source === 'vault')) { this.credentialRefusals.set(info.ref, { source, reason: info.reason }); @@ -5440,7 +5613,7 @@ export class AutomationServicePlugin implements Plugin { 'declarative', info.cause, held ? (stored ? { kind: 'credential', ref: stored.ref } : { kind: 'declaration' }) : undefined, - this.declaredInstance(ctx, info.entry), + { packageId: info.packageId }, ); } catch (err) { ctx.logger.warn( @@ -5462,7 +5635,7 @@ export class AutomationServicePlugin implements Plugin { } // #5575 — the reason quotes the upstream, foreign text: it rides `meta`. ctx.logger.warn( - `[Automation] connector instance '${info.name}' (provider '${info.provider}') is degraded: its upstream refused ` + + `[Automation] connector instance '${info.name}'${inPackage(info.packageId)} (provider '${info.provider}') is degraded: its upstream refused ` + `its credential. ` + (hasLive ? 'The previously-materialized connector keeps serving' + (held ? '.' : `; retrying with backoff, attempt ${attempts}.`) @@ -5482,11 +5655,11 @@ export class AutomationServicePlugin implements Plugin { */ private async recordCredentialProven( ctx: PluginContext, - name: string, + { key, name }: { key: string; name: string }, ref: string, credential: Extract, ): Promise { - this.credentialRefusalAttempts.delete(name); + this.credentialRefusalAttempts.delete(key); if (credential.source !== 'object') { if (this.credentialRefusals.get(ref)?.source === credential.source) this.credentialRefusals.delete(ref); return; @@ -5543,6 +5716,10 @@ export class AutomationServicePlugin implements Plugin { ctx: PluginContext, info: { name: string; + /** [#31699 PR 3] The materializer's key of the instance ({@link connectorInstanceKey}). */ + key: string; + /** [#31699 PR 3] The instance's package (`null`: none). */ + packageId: string | null; entry: DeclaredConnectorItem; provider: string; signature: string; @@ -5555,7 +5732,7 @@ export class AutomationServicePlugin implements Plugin { ): Record { let refused = false; let accepted = info.proven; - const current = () => !this.destroyed && this.materializedConnectors.get(info.name) === info.tracked; + const current = () => !this.destroyed && this.materializedConnectors.get(info.key) === info.tracked; const watched: Record = {}; for (const [key, handler] of Object.entries(handlers)) { watched[key] = async (input, callCtx) => { @@ -5586,6 +5763,8 @@ export class AutomationServicePlugin implements Plugin { if (!current()) return; await this.holdConnectorForRejectedCredential(engine, ctx, { name: info.name, + key: info.key, + packageId: info.packageId, entry: info.entry, provider: info.provider, signature: info.signature, @@ -5669,22 +5848,20 @@ export class AutomationServicePlugin implements Plugin { /** Unregister and tear down one materialized declarative connector (ADR-0097). */ private async dematerializeConnector( engine: AutomationEngine, - name: string, + instance: { key: string; name: string; packageId: string | null }, tracked: { close?: () => void | Promise }, 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 */ } + // [#31699 PR 3] The instance itself, by its package and name: another + // package's instance of the name stays registered. + try { engine.unregisterConnector(instance.name, instance.packageId); } catch { /* ignore */ } if (tracked.close) { try { await tracked.close(); } catch { /* best-effort */ } } - this.materializedConnectors.delete(name); - this.grantHandles.delete(name); - ctx.logger.info(`[Automation] unregistered declarative connector instance '${name}' (${why})`); + this.materializedConnectors.delete(instance.key); + this.grantHandles.delete(instance.key); + ctx.logger.info(`[Automation] unregistered declarative connector instance '${instance.name}'${inPackage(instance.packageId)} (${why})`); } /** diff --git a/packages/services/service-automation/src/pull-refusal.ts b/packages/services/service-automation/src/pull-refusal.ts index 8be7ab8b652..f822fc7d4a6 100644 --- a/packages/services/service-automation/src/pull-refusal.ts +++ b/packages/services/service-automation/src/pull-refusal.ts @@ -20,6 +20,14 @@ export type ConnectorPullRefusalReason = */ | 'mapping_name_refused' | 'no_connector_source' + /** + * [ADR-0150 D9, #31699] The mapping's `connectorSource.connector` + * resolves, from the mapping's package, to no single connector instance: + * two holders in the package's closure, or, for a mapping no package + * holds, two packages' instances of the name. The message names every + * candidate. + */ + | 'connector_name_refused' | 'connector_not_registered' | 'connector_plugin_origin' | 'connector_degraded' diff --git a/packages/spec/src/api/protocol.zod.ts b/packages/spec/src/api/protocol.zod.ts index 1a1fcbf5c23..604cb7e5d94 100644 --- a/packages/spec/src/api/protocol.zod.ts +++ b/packages/spec/src/api/protocol.zod.ts @@ -2359,7 +2359,7 @@ const HISTORY_PACKAGE_SELECTOR_DESCRIPTION = */ export const PACKAGE_SLOTTED_METADATA_TYPES: readonly string[] = Object.freeze([ 'api', 'agent', 'skill', 'action', 'email_template', 'permission', 'flow', 'picklist', 'mapping', 'dataset', - 'webhook', 'tool', + 'webhook', 'tool', 'connector', ]); /** diff --git a/packages/spec/src/contracts/automation-service.ts b/packages/spec/src/contracts/automation-service.ts index 47d14266c0e..1b02f1d3920 100644 --- a/packages/spec/src/contracts/automation-service.ts +++ b/packages/spec/src/contracts/automation-service.ts @@ -1381,6 +1381,16 @@ export interface ConnectorConnectionState { export interface ConnectorConnectionRequest { /** The declarative connector instance, by name. */ connector: string; + /** + * ADR-0150 D9 (#31699) — the package whose instance of `connector` is + * meant, when two packages of different namespaces each declare one of the + * name. The namespace-addressed connection door + * (`/automation/connectors/:ns/:name/connection`) fills it from the address; + * left out, the bare name must resolve to one instance or the call is + * refused `409` (ambiguity is reported, never guessed). A connect that + * already recorded a connection keeps that connection's package. + */ + package?: string; /** The caller — its organization selects the connection, its user stamps the row. */ context?: ExecutionContext; /** diff --git a/packages/spec/src/integration/connector-descriptor.ts b/packages/spec/src/integration/connector-descriptor.ts index bae1cfc02db..ebab6275483 100644 --- a/packages/spec/src/integration/connector-descriptor.ts +++ b/packages/spec/src/integration/connector-descriptor.ts @@ -75,6 +75,14 @@ export interface ConnectorActionDescriptor { */ export interface ConnectorDescriptor { readonly name: string; + /** + * ADR-0150 D9 (#31699) — the package that holds this instance, when one does. + * Two packages of different namespaces may each declare a connector of the + * same name, so `name` alone no longer identifies one instance; the pair does. + * Absent for a connector registered with no package (a plugin connector, or a + * declarative entry no package holds). + */ + readonly packageId?: string; readonly label: string; /** * The connector's category (`saas`, `database`, `rest`, …) — the same `type`