Skip to content

Commit 17ac714

Browse files
committed
feat(service-automation): the automation engine holds a connector instance by its package and name, and a dispatch addresses the one its caller's name resolves to
The engine's connectors are held by (package, name); a bare-name read answers the one instance, never one of two. connector_action resolves the instance for the calling flow's package and reads its handler, effect and inputSchema from it. The reconcile registers each declarative instance with its package and as the sole instance of its name, re-registers it when its package changes, and drops it by name. The OAuth2 grant handle asks its package on every read, and serves a token only for the connection row it was obtained for. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibzKCovWpJoMZD6U3NT
1 parent 199e362 commit 17ac714

14 files changed

Lines changed: 662 additions & 69 deletions
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
'@objectstack/service-automation': patch
3+
---
4+
5+
feat(service-automation): the automation engine holds a connector instance by its package and name, and a dispatch addresses the one instance its caller's name resolves to (ADR-0150 D4, #31699)
6+
7+
Clause-②: yes (widening) — additive in-process surface only: `AutomationEngine` gains `resolveConnectorInstance`, `resolveConnectorInstanceFor` and `resolveConnectorActionInputSchema`; `registerConnector`, `registerDegradedConnector` and `unregisterConnector` take an optional instance (its package, and `soleOfName`); `resolveConnectorAction`, `resolveConnectorActionEffect`, `getConnectorOrigin`, `getConnectorDegradedReason` and `getConnectorDegradedHold` take an optional package; the barrel exports the types `ConnectorInstanceResolution` and `ConnectorInstanceOptions`. Dispatch answers change in one transitional state only (an unstamped entry whose name gains a second holder after boot), as an intended tightening (see "What answers differently" below). Every other dispatch, door and HTTP answer is as before: the declared-connector reconcile still keeps one instance per name (the one-holder backstop, its duplicate-name refusal, and `soleOfName` on every declarative registration), and a lookup by bare name answers that one instance.
8+
Metadata-protocol: none
9+
Skills-docs: none — nothing a skill or a docs page teaches changes while one instance per name is kept; the two-holder connector docs come with the PR that narrows the backstop.
10+
11+
Part of #31699 (ADR-0150 child B, PR 3b). PR 3a-ii made the connection store, the connect door and the OAuth callback address an instance by package and name; this PR makes the engine hold and dispatch it so.
12+
13+
**The engine's instances.**
14+
15+
- The registered connectors are held by `(package, name)` (`ConnectorInstances`): a declarative instance by the package the connection door addresses it by (`connectorInstancePackage`: its real stamp; none for the environment's stored entry; the name's durable holder for an unstamped or compatibility-default entry), a plugin's connector by no package.
16+
- A plugin's connector and a declarative instance still never share a name, whatever package the instance is of (ADR-0097 §4). With `soleOfName`, a declarative registration drops any other declarative instance of the name: the reconcile registers every instance so, and keeps one per name, until the backstop narrows.
17+
- A read by bare name answers the one instance of the name, and none when there are two, never one of them. `getRegisteredConnectors` lists each name once; `getConnectorDescriptors` lists every instance.
18+
19+
**Dispatch.**
20+
21+
- `connector_action` resolves its `connectorId` for the calling flow's package (`resolveConnectorInstance`): a refused name is refused as before, naming every candidate; a resolved holder is dispatched to its own instance, and its action's `inputSchema` and `effect` are read from that instance. A caller with no package, a name no registry holds, or a resolved holder with no instance registered under it (a plugin's connector of a declared name) is answered by the one instance of the name, as the dispatch by name answered; two are not dispatched. `connectorNameRefusal` answers as before.
22+
- The OAuth2 grant handle asks its instance's package on every read of the connection store, so an unstamped entry's connections are read under the package its name resolves to now, not when the handle was made. A cached access token is served only for the connection row it was obtained for (its row id, beside its revision): a read that now chooses another row (another package's connection of the organization) refreshes, never serves the other row's token.
23+
24+
**The reconcile.**
25+
26+
- The instance package is part of a provider-bound entry's desired signature, so an unstamped entry whose name's holder changes (installed, uninstalled, a second holder) is registered again under the package it resolves to now, on the next reconcile. The engine's instance and the connection the grant handle reads stay one package.
27+
- An instance the reconcile drops (no longer declared, degraded and removed) is unregistered by name, every instance of it: the reconcile keeps one per name, whatever package it was registered under.
28+
- Limit: the boot's second reconcile (packages registered during the boot) is skipped when the declared list's fingerprint is unchanged, and the fingerprint carries no package, so a holder that changes in that window without the declared list changing is followed on the next reload or restart.
29+
30+
**What answers differently.**
31+
32+
- An unstamped (or compatibility-default) declared entry whose name gains a second durable holder: its dispatch was answered with the connection of the package that held the name at boot (200) until a restart. It is now read under the package the name resolves to at that moment, which is no one package, so it is refused 503 (no connection of its own): under two holders a row is its own package's only (PR 3a-ii's store rule), as the connection door already refuses that name (409). It is recovered by stamping the entry or by uninstalling the second holder. A holder that is uninstalled or replaced, leaving one holder, changes no answer: every row of the name still answers the one instance, and the next reconcile registers the instance again under the package it resolves to now (any provider-bound instance is re-materialized on such a change).
33+
- A dispatch that joins an access-token refresh already in flight for another connection row of the organization (the instance's package changed while the refresh was out) is refused 503, never served that row's token; the next dispatch refreshes its own row.
34+
- The store's refusal of a row of a two-holder name that names none of the holders now names the remedy that works for it: `os migrate stored-references bind` for a row naming no package, and uninstalling one of the holders for a row already naming another package, which the bind refuses (PR 3a-ii contract review N4).
35+
- On a change of holder, the instance is re-registered, so its name moves to the end of `getRegisteredConnectors()` and `GET /automation/connectors`.
36+
37+
**Not in this PR (moved to the PR that narrows the backstop).**
38+
39+
- The materializer's own bookkeeping (`desired`, the materialized, degraded and credential-refusal maps, `grantHandles`, retry and dematerialize) stays keyed by name: under the backstop the reconcile cannot hold two instances of one name, so re-keying it is observable only once the duplicate-name refusal is lifted, and lands with it and with a two-live-instance test. Its registrations and unregistrations already pass the instance package.
40+
- The connector pull keeps reading its connector by bare name (the one instance): whether a mapping's connector is resolved for the job's package, and refused where that name is refused, changes an answer and is decided with the narrowing.
41+
- The resolved-holder fallback above (a resolved holder with no registered instance answered by the one instance of the name) is right only while one instance per name is kept; with two instances alive the narrowing PR makes it `none`.
42+
- `ConnectorDescriptor.packageId`, the addressed connection door (`?package=`), connector into the namespace-scoped type sets, and the backstop itself.
43+
- `registerConnector(def, handlers, 'declarative', { packageId })` without `soleOfName` is public and keeps two instances of one name side by side (the engine tests use it). Nothing in-tree registers so outside the tests; the reconcile always passes `soleOfName`.
44+
45+
**In-process APIs.** Listed under Clause-② above. All additive; every new parameter is optional and its absence answers as before.

‎packages/services/service-automation/src/builtin/connector-nodes.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,17 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont
6565
// [ADR-0150 D3, epic #31527 child E5] A packaged flow names its
6666
// connector from its package: refused (every candidate named) when
6767
// the name does not resolve for that package — never dispatched on
68-
// a guess.
69-
const nameRefusal = engine.connectorNameRefusal(cfg.connectorId, context);
70-
if (nameRefusal) {
71-
return refuseNode(`connector_action '${node.id}': ${nameRefusal.message}`);
68+
// a guess. [ADR-0150 D4, #31699] Otherwise the step dispatches the
69+
// one instance that answer addresses, by its package.
70+
const instance = engine.resolveConnectorInstance(cfg.connectorId, context);
71+
if (instance.status === 'refused') {
72+
return refuseNode(`connector_action '${node.id}': ${instance.refusal.message}`);
7273
}
74+
// `none`: an address no instance answers; every read below then
75+
// finds nothing registered, as for a name never registered.
76+
const packageId = instance.status === 'instance' ? instance.packageId : undefined;
7377

74-
const handler = engine.resolveConnectorAction(cfg.connectorId, cfg.actionId);
78+
const handler = packageId === undefined ? undefined : engine.resolveConnectorAction(cfg.connectorId, cfg.actionId, packageId);
7579
if (!handler) {
7680
// A degraded declarative instance (#3017) is registered but has no
7781
// handlers — say WHY dispatch fails and what recovers it, instead
@@ -80,9 +84,9 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont
8084
// was refused. [#28016] Recovery is automatic only on the backoff:
8185
// a held instance (a configuration fault met on a retry, a refused
8286
// credential the platform will not re-send) names its fix instead.
83-
const degraded = engine.getConnectorDegradedReason(cfg.connectorId);
87+
const degraded = packageId === undefined ? undefined : engine.getConnectorDegradedReason(cfg.connectorId, packageId);
8488
if (degraded) {
85-
const hold = engine.getConnectorDegradedHold(cfg.connectorId);
89+
const hold = engine.getConnectorDegradedHold(cfg.connectorId, packageId);
8690
// A reason that is a full sentence keeps one full stop.
8791
const reason = degraded.replace(/\.\s*$/, '');
8892
return {
@@ -123,7 +127,7 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont
123127
// #4395 lets the action declare `effect`, and this is where the
124128
// declaration is spent. Resolved BEFORE dispatch so both the
125129
// success and the failure path read one value.
126-
const effect = engine.resolveConnectorActionEffect(cfg.connectorId, cfg.actionId);
130+
const effect = engine.resolveConnectorActionEffect(cfg.connectorId, cfg.actionId, packageId);
127131

128132
// #27327 — `input` is a value-slot map: a top-level CEL envelope is
129133
// evaluated in the run's scope, every other value handed on as a
@@ -143,7 +147,7 @@ export function registerConnectorNodes(engine: AutomationEngine, ctx: PluginCont
143147
// (#28040). A `runtime` failure, not a guard: the input can come
144148
// from run data, so a `fault` edge may handle it.
145149
const verdict = judgeConnectorInput(
146-
findConnectorActionInputSchema(engine, cfg.connectorId, cfg.actionId),
150+
findConnectorActionInputSchema(engine, cfg.connectorId, cfg.actionId, packageId),
147151
input,
148152
);
149153
if (verdict) {

‎packages/services/service-automation/src/connector-connection-door.test.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ async function boot(
247247
) {
248248
const ql = await dataEngine();
249249
const provider = grantedProvider();
250+
let captured: any;
250251
const kernel = new LiteKernel({ logger: { level: 'debug', format: 'json' } } as never);
251252
kernels.push(kernel);
252253
kernel.use(new AutomationServicePlugin({
@@ -260,6 +261,7 @@ async function boot(
260261
version: '1.0.0',
261262
dependencies: ['com.objectstack.service-automation'],
262263
async init(ctx: any) {
264+
captured = ctx;
263265
const listItems = (t: string) => (t === 'connector' ? declared : []);
264266
const registry = opts.registry ? Object.assign(Object.create(opts.registry), { listItems }) : { listItems };
265267
ctx.registerService('objectql', { registry });
@@ -283,7 +285,9 @@ async function boot(
283285
const query = opts2.query ?? { code: opts2.code ?? GOOD_CODE, state };
284286
return { begun, state, done: () => engine.completeConnectorConnection({ query: { state, ...query }, context: (opts2.as ?? context) as never }) };
285287
};
286-
return { ql, engine, provider, call, connect, kernel };
288+
/** Fire the reload hook: the runtime reconcile, over `declared` as it stands now. */
289+
const reload = async () => { await captured.trigger('metadata:reloaded'); await flush(); };
290+
return { ql, engine, provider, call, connect, kernel, reload };
287291
}
288292

289293
const rowsOf = async (ql: ObjectQL) => (await ql.find(CONNECTOR_CONNECTION_OBJECT, { context: SYSTEM } as never)) as any[];
@@ -1105,6 +1109,66 @@ describe('ADR-0150 D4 [#31699] — the connection door connects one instance, by
11051109
expect(await rowsOf(ql)).toHaveLength(0);
11061110
});
11071111

1112+
it('[3b] the materializer registers the instance by its package, and the dispatch handle reads the package as the name resolves now', async () => {
1113+
const registry = registryHolding('com.example.crm');
1114+
const { connect, call, engine } = await boot([crm({ _packageId: undefined })], { registry });
1115+
await (await connect()).done();
1116+
expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: 'com.example.crm' });
1117+
await expect(call('org_a')).resolves.toMatchObject({ status: 200 });
1118+
// A second durable holder: the unstamped entry is no one package's any
1119+
// more, so its connection (the package's row) is not its own.
1120+
hold(registry, OTHER);
1121+
await expect(call('org_a')).rejects.toMatchObject({ status: 503 });
1122+
});
1123+
1124+
it('[3b] the holder of an unstamped entry is replaced, leaving one holder: the dispatch keeps its connection', async () => {
1125+
const registry = registryHolding('com.example.crm');
1126+
const { connect, call, engine } = await boot([crm({ _packageId: undefined })], { registry });
1127+
await (await connect()).done();
1128+
registry.uninstallPackage('com.example.crm');
1129+
registry.unregisterItemsByPackage('com.example.crm');
1130+
hold(registry, OTHER);
1131+
expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: 'com.example.crm' });
1132+
await expect(call('org_a')).resolves.toMatchObject({ status: 200 });
1133+
});
1134+
1135+
it('[3b, review M1] the package an unstamped entry is registered under follows the name\'s holder, and a removed entry leaves no instance behind', async () => {
1136+
// Not connected: the instance is the degraded husk.
1137+
const registry = registryHolding('com.example.crm');
1138+
const declared: unknown[] = [crm({ _packageId: undefined })];
1139+
const { engine, reload } = await boot(declared, { registry });
1140+
expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: 'com.example.crm' });
1141+
expect(engine.getConnectorDegradedReason('crm')).toBeDefined();
1142+
// The holder is uninstalled; the declared list is unchanged. The
1143+
// reconcile registers the instance again, under no package.
1144+
registry.uninstallPackage('com.example.crm');
1145+
registry.unregisterItemsByPackage('com.example.crm');
1146+
await reload();
1147+
expect(engine.resolveConnectorInstanceFor('crm', null)).toEqual({ status: 'instance', packageId: null });
1148+
expect(engine.getConnectorDescriptors().filter((d) => d.name === 'crm')).toHaveLength(1);
1149+
// The entry is removed: no instance of the name is left, under any package.
1150+
declared.length = 0;
1151+
await reload();
1152+
expect(engine.getRegisteredConnectors()).not.toContain('crm');
1153+
expect(engine.getConnectorDegradedReason('crm')).toBeUndefined();
1154+
});
1155+
1156+
it('[3b, review M1] an entry removed while its package holds the name: both the degraded and the live instance are dropped', async () => {
1157+
const declared: unknown[] = [crm({ _packageId: undefined })];
1158+
const degraded = await boot(declared, { registry: registryHolding('com.example.crm') });
1159+
declared.length = 0;
1160+
await degraded.reload();
1161+
expect(degraded.engine.getRegisteredConnectors()).not.toContain('crm');
1162+
1163+
const declaredLive: unknown[] = [crm({ _packageId: undefined })];
1164+
const live = await boot(declaredLive, { registry: registryHolding('com.example.crm') });
1165+
await (await live.connect()).done();
1166+
expect(live.engine.getConnectorDegradedReason('crm')).toBeUndefined();
1167+
declaredLive.length = 0;
1168+
await live.reload();
1169+
expect(live.engine.getRegisteredConnectors()).not.toContain('crm');
1170+
});
1171+
11081172
it('a resolved holder no declared entry is the instance of: the one declared entry is served, with its own package', async () => {
11091173
const { connect, ql } = await boot([crm({ _packageId: OTHER })], { registry: registryHolding('com.example.crm') });
11101174
await expect((await connect()).done()).resolves.toMatchObject({ status: 'connected' });

‎packages/services/service-automation/src/connector-connection-package.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,9 @@ describe('[#31699, contract review F1] a declaration that moves keeps its connec
175175
const store = storeOver(ql, twoHolders);
176176
const refusal = await store.read('org_a', 'crm', A).then(() => undefined, (e: unknown) => e);
177177
expect(refusal).toBeInstanceOf(ConnectorConnectionConflictError);
178-
expect((refusal as Error).message).toMatch(/os migrate stored-references bind/);
178+
// The bind never moves a row that already names a package: the remedy is to uninstall one holder.
179+
expect((refusal as Error).message).toMatch(/Uninstall one of the packages/);
180+
expect((refusal as Error).message).not.toMatch(/stored-references bind/);
179181
await expect(store.revoke('org_a', 'crm', undefined, A)).rejects.toBeInstanceOf(ConnectorConnectionConflictError);
180182
expect(await packages(ql)).toEqual(['com.acme.gone']);
181183

‎packages/services/service-automation/src/connector-connections.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -245,11 +245,14 @@ export class ConnectorConnectionStore {
245245
return named === null || !holders.has(named);
246246
});
247247
if (unclaimed.length === 0) return own;
248+
const remedy = unclaimed.some((r) => rowPackage(r) === null)
249+
? 'Bind a connection naming no package to its package with `os migrate stored-references bind --table '
250+
+ 'sys_connector_connection`, or uninstall one of the packages, then read it again.'
251+
// The bind never moves a row that already names a package.
252+
: 'Uninstall one of the packages, then read it again: the one remaining instance reads it, and a revoke removes it.';
248253
throw new ConnectorConnectionConflictError(
249254
`The connection of connector instance '${connectorName}' in this organization names no package that holds `
250-
+ `that name, and ${holder.candidates.length} packages hold it, so it is no one package's connection. Bind it to `
251-
+ 'its package with `os migrate stored-references bind --table sys_connector_connection`, or uninstall one of '
252-
+ 'the packages, then read it again.',
255+
+ `that name, and ${holder.candidates.length} packages hold it, so it is no one package's connection. ${remedy}`,
253256
);
254257
}
255258

0 commit comments

Comments
 (0)