Skip to content

Commit 7d39171

Browse files
committed
feat(plugin-webhooks): resolve declared webhook names through the package-scoped resolver
A declared webhook's name is answered by resolvePackageScopedName as a caller with no package; a name two packages hold is not dispatched and the by-name read throws a 409 naming every candidate. The booted pin on a clash held from before phase 1 moves from the first-registered package to that refusal. Claude-Session: https://claude.ai/code/session_01ADHkmR4astMzES5UkW47jW Co-authored-by: Claude <noreply@anthropic.com>
1 parent f2abd47 commit 7d39171

7 files changed

Lines changed: 307 additions & 18 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-webhooks': patch
3+
---
4+
5+
feat: a declared webhook's name resolves by (package, name) through the shared package-scoped resolver (ADR-0150 D3/D4)
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Which declared webhook a name dispatches is now answered by `resolvePackageScopedName` from `@objectstack/objectql`, never by list order. The dispatcher and the by-name reads (activation door, redelivery veto, name guard) read the whole environment's declaration, so each asks as a caller with no package: the environment's own item, else the unique package holder, else a refusal that names every candidate.
11+
12+
Who is affected: a deployment that held one declared webhook name in two packages from before phase 1's one-holder refusal (the cold boot warns about it as a "Bare-name conflict at boot"). That webhook was dispatched from whichever package registered first; it is now not dispatched, the refusal is logged once naming both packages, and the by-name reads answer a `409 RESOURCE_CONFLICT` naming them instead of "not declared". Rename one of the two (the boot warning names the rename). First-party count of such clashes: 0. Every other name resolves exactly as before, since phase 1 still refuses a new clash at install.
13+
14+
`@objectstack/plugin-webhooks` now depends on `@objectstack/objectql` at runtime (it was a dev dependency).

‎packages/plugins/plugin-webhooks/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
},
3838
"dependencies": {
3939
"@objectstack/core": "workspace:*",
40+
"@objectstack/objectql": "workspace:*",
4041
"@objectstack/platform-objects": "workspace:*",
4142
"@objectstack/service-messaging": "workspace:*",
4243
"@objectstack/spec": "workspace:*",
@@ -45,7 +46,6 @@
4546
"devDependencies": {
4647
"@objectstack/driver-sql": "workspace:*",
4748
"@objectstack/metadata-core": "workspace:*",
48-
"@objectstack/objectql": "workspace:*",
4949
"@types/node": "^26.6.5",
5050
"hono": "^4.13.9",
5151
"tsx": "^4.23.15",

‎packages/plugins/plugin-webhooks/src/declared-webhooks.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,12 @@
2727
import { describe, expect, it, vi } from 'vitest';
2828
import { AutoEnqueuer, type HttpEnqueueFn } from './auto-enqueuer.js';
2929
import {
30+
DeclaredWebhookAmbiguousError,
3031
DeclaredWebhookSource,
3132
WEBHOOK_ACTIVATION_TYPE,
3233
declaredWebhookRefId,
3334
} from './declared-webhooks.js';
35+
import { SchemaRegistry } from '@objectstack/objectql';
3436
import { createWebhookRedeliverGuard } from './redeliver-guard.js';
3537
import { bindWebhookProvenanceStamp } from './webhook-provenance.js';
3638
import { WebhookOutboxPlugin } from './webhook-outbox-plugin.js';
@@ -609,3 +611,93 @@ describe('declared webhooks — the redelivery veto', () => {
609611
expect(await guardFor(engine)({ source: 'webhook', refId: 'whk_seeded' })).toBeUndefined();
610612
});
611613
});
614+
615+
// ---------------------------------------------------------------------------
616+
// 4. One declaration per name, by (package, name) — ADR-0150 D3 (epic #31527 child E5)
617+
// ---------------------------------------------------------------------------
618+
619+
describe('declared webhooks — a name resolves by (package, name) (ADR-0150 D3)', () => {
620+
const A = 'com.acme.alpha';
621+
const B = 'com.acme.beta';
622+
623+
/** A real registry with each id installed as a code package shipping `wh` in its own composite slot. */
624+
function registryShipping(packages: Array<[string, any]>): SchemaRegistry {
625+
const registry = new SchemaRegistry();
626+
registry.logLevel = 'silent';
627+
for (const [id, wh] of packages) {
628+
if (!registry.getPackage(id)) {
629+
registry.installPackage({ id, name: id, version: '1.0.0', type: 'app', namespace: id.split('.').pop() } as never, 'code');
630+
}
631+
registry.registerItem('webhook', { ...wh }, 'name' as never, id);
632+
}
633+
return registry;
634+
}
635+
636+
/** The fake engine, its `_registry` the real one. */
637+
function engineOver(registry: SchemaRegistry, seed?: { rows?: Record<string, any[]> }): FakeEngine {
638+
const engine = newEngine(seed);
639+
Object.defineProperty(engine, '_registry', { get: () => registry });
640+
return engine;
641+
}
642+
643+
it('one package holder: the declaration dispatches, carrying its package', async () => {
644+
const engine = engineOver(registryShipping([[A, declaredWebhook()]]));
645+
const source = new DeclaredWebhookSource(engine, undefined);
646+
expect((await source.list()).map((d) => [d.webhook.name, d.packageId])).toEqual([['task_changed', A]]);
647+
expect((await source.declaredWebhookNamed('task_changed'))?.packageId).toBe(A);
648+
649+
const { enqueuer, realtime, calls } = await startEnqueuer(engine);
650+
await realtime.publish(taskCreated());
651+
await flush();
652+
expect(calls).toHaveLength(1);
653+
await enqueuer.stop();
654+
});
655+
656+
it('two package holders: neither is dispatched, and the refusal names both, once', async () => {
657+
const engine = engineOver(registryShipping([
658+
[A, declaredWebhook({ url: 'https://hooks.example/alpha' })],
659+
[B, declaredWebhook({ url: 'https://hooks.example/beta' })],
660+
]));
661+
const warn = vi.fn();
662+
const { enqueuer, realtime, calls, declaredWebhooks } = await startEnqueuer(engine, { warn, info: vi.fn(), error: vi.fn(), debug: vi.fn() });
663+
await realtime.publish(taskCreated());
664+
await flush();
665+
expect(calls).toEqual([]);
666+
expect(await declaredWebhooks.list()).toEqual([]);
667+
await enqueuer.stop();
668+
669+
const refusals = warn.mock.calls.filter(([msg]) => String(msg).includes(`declared webhook 'task_changed' is not dispatched`));
670+
expect(refusals).toHaveLength(1);
671+
expect(refusals[0][0]).toContain(`"${A}"`);
672+
expect(refusals[0][0]).toContain(`"${B}"`);
673+
});
674+
675+
it('two package holders: the by-name read throws the 409 conflict naming both, never "not declared"', async () => {
676+
const engine = engineOver(registryShipping([[A, declaredWebhook()], [B, declaredWebhook()]]));
677+
const source = new DeclaredWebhookSource(engine, undefined);
678+
const err = await source.declaredWebhookNamed('task_changed').then(() => undefined, (e: unknown) => e);
679+
expect(err).toBeInstanceOf(DeclaredWebhookAmbiguousError);
680+
expect(err).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409, webhook: 'task_changed' });
681+
expect((err as DeclaredWebhookAmbiguousError).candidates).toEqual([
682+
{ kind: 'package', packageId: A },
683+
{ kind: 'package', packageId: B },
684+
]);
685+
686+
// The redelivery veto propagates it: "we could not check" never reads as "allowed".
687+
const guard = createWebhookRedeliverGuard(engine as any, 'sys_webhook', source);
688+
await expect(guard({ source: 'webhook', refId: declaredWebhookRefId('task_changed') }))
689+
.rejects.toBeInstanceOf(DeclaredWebhookAmbiguousError);
690+
});
691+
692+
it('with no registry to resolve against, a name the metadata service lists twice is refused, never first-picked', async () => {
693+
const engine = newEngine();
694+
const metadata = {
695+
list: (type: string) => (type === 'webhook'
696+
? [{ ...declaredWebhook(), _packageId: A }, { ...declaredWebhook({ url: 'https://hooks.example/beta' }), _packageId: B }]
697+
: []),
698+
};
699+
const source = new DeclaredWebhookSource(engine, metadata);
700+
expect(await source.list()).toEqual([]);
701+
await expect(source.declaredWebhookNamed('task_changed')).rejects.toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 });
702+
});
703+
});

‎packages/plugins/plugin-webhooks/src/declared-webhooks.ts‎

Lines changed: 153 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,24 @@
3333
* applied, a malformed item skipped with one warning per name per process,
3434
* never a crashed refresh.
3535
*
36+
* ## One declaration per name, by `(package, name)` (ADR-0150 D3/D4)
37+
*
38+
* A webhook is addressed by `(package, name)`. Which declaration a name
39+
* serves is answered by the ONE package-scoped resolver
40+
* (`resolvePackageScopedName`, `@objectstack/objectql`), never by list order:
41+
* every reader here (the dispatcher, the redelivery veto, the activation door,
42+
* the name guard) is context-free, so it asks as a caller with no package —
43+
* the environment's own item, else the unique package holder, else a refusal
44+
* naming every candidate. A refused name is not dispatched (reported once per
45+
* name per process), and {@link DeclaredWebhookReader.declaredWebhookNamed}
46+
* throws {@link DeclaredWebhookAmbiguousError} for it, so no door reads "not
47+
* declared" for a name two packages declare. While phase 1's one-holder
48+
* refusal stands (`webhook` is one of its types) no two packages hold a name,
49+
* so this answers every name as before. Items the registry does not hold (the
50+
* metadata service's, on a host whose registry holds no webhook) have no
51+
* package coordinate to resolve: one item per name serves, and a name listed
52+
* twice is refused the same way, never first-picked.
53+
*
3654
* ## The switch: regime C (ADR-0131 D6)
3755
*
3856
* A declared webhook is read-only. It is switched on or off for the deployment
@@ -78,6 +96,13 @@
7896

7997
import { WebhookSchema, type WebhookParsed } from '@objectstack/spec/automation';
8098
import { METADATA_ACTIVATION_TABLE } from '@objectstack/core';
99+
import {
100+
packageScopedRefusalMessage,
101+
resolvePackageScopedName,
102+
type PackageScopedHolder,
103+
type PackageScopedRefusal,
104+
type PackageScopedRegistry,
105+
} from '@objectstack/objectql';
81106

82107
/** System read context — the dispatcher reads its own configuration. */
83108
const SYSTEM_CTX = { isSystem: true } as const;
@@ -132,10 +157,94 @@ export interface DeclaredWebhook {
132157
export interface DeclaredWebhookReader {
133158
/** Every valid declaration, each with its switch resolved. */
134159
list(): Promise<DeclaredWebhook[]>;
135-
/** The declaration named `name`, switched on or off, or `null` when nothing declares it. */
160+
/**
161+
* The declaration named `name`, switched on or off, or `null` when nothing
162+
* declares it. Throws {@link DeclaredWebhookAmbiguousError} when the name
163+
* resolves to no single declaration (ADR-0150 D3).
164+
*/
136165
declaredWebhookNamed(name: string): Promise<DeclaredWebhook | null>;
137166
}
138167

168+
/**
169+
* [ADR-0150 D3, epic #31527 red line 2] A declared webhook name that resolves
170+
* to no single declaration: two packages declare it, and nothing picks one.
171+
* `code` + `status` are the conflict envelope (409 `RESOURCE_CONFLICT`, the
172+
* catalogue's code for a 409, the status ADR-0150 D5 gives an ambiguous bare
173+
* name); `candidates` names every holder, and so does the message.
174+
*/
175+
export class DeclaredWebhookAmbiguousError extends Error {
176+
readonly code = 'RESOURCE_CONFLICT';
177+
readonly status = 409;
178+
/** The declared webhook name. */
179+
readonly webhook: string;
180+
/** Every holder of the name, in the resolver's order. */
181+
readonly candidates: readonly PackageScopedHolder[];
182+
constructor(refusal: PackageScopedRefusal) {
183+
super(refusal.message);
184+
this.name = 'DeclaredWebhookAmbiguousError';
185+
this.webhook = refusal.name;
186+
this.candidates = refusal.candidates;
187+
}
188+
}
189+
190+
/** The engine's `SchemaRegistry`, when it carries the slice the package-scoped resolver reads. */
191+
function packageScopedRegistryOf(engine: unknown): PackageScopedRegistry | undefined {
192+
let reg: unknown;
193+
try {
194+
reg = (engine as { _registry?: unknown } | undefined)?._registry;
195+
} catch {
196+
return undefined;
197+
}
198+
const r = reg as Partial<Record<keyof PackageScopedRegistry, unknown>> | undefined;
199+
return typeof r?.packageScopedHoldersOf === 'function'
200+
&& typeof r.getPackageScopedItem === 'function'
201+
&& typeof r.getEnvironmentScopedItem === 'function'
202+
&& typeof r.getPackage === 'function'
203+
&& typeof r.getAllPackages === 'function'
204+
? (reg as PackageScopedRegistry)
205+
: undefined;
206+
}
207+
208+
/**
209+
* Which raw declaration serves `name` (ADR-0150 D3, a caller with no
210+
* package): the resolver's answer when the registry holds the name; else the
211+
* one listed item; else a refusal naming every listed holder.
212+
*/
213+
function chooseDeclaration(
214+
name: string,
215+
listed: readonly unknown[],
216+
registry: PackageScopedRegistry | undefined,
217+
): { item: unknown } | { refusal: PackageScopedRefusal } {
218+
if (registry) {
219+
const resolved = resolvePackageScopedName(registry, { type: 'webhook', name });
220+
if (resolved.status === 'resolved') return { item: resolved.item };
221+
if (resolved.status === 'refused') return { refusal: resolved };
222+
// not-found: the listed items are not the registry's (the metadata service's).
223+
}
224+
if (listed.length === 1) return { item: listed[0] };
225+
const candidates: PackageScopedHolder[] = [];
226+
const seen = new Set<string>();
227+
for (const item of listed) {
228+
const pkg = (item as { _packageId?: unknown })?._packageId;
229+
const holder: PackageScopedHolder = typeof pkg === 'string' && pkg !== '' && pkg !== 'sys_metadata'
230+
? { kind: 'package', packageId: pkg }
231+
: { kind: 'environment' };
232+
const key = holder.kind === 'package' ? holder.packageId : '';
233+
if (seen.has(key)) continue;
234+
seen.add(key);
235+
candidates.push(holder);
236+
}
237+
const refusal = {
238+
status: 'refused' as const,
239+
reason: 'ambiguous-in-environment' as const,
240+
type: 'webhook' as const,
241+
name,
242+
callerPackageId: null,
243+
candidates,
244+
};
245+
return { refusal: { ...refusal, message: packageScopedRefusalMessage(refusal) } };
246+
}
247+
139248
/**
140249
* The raw declared `webhook` items, registry first, metadata service second.
141250
* Never throws: a reader that cannot answer yields nothing from that reader.
@@ -181,6 +290,10 @@ export function readDeclaredWebhookNames(engine: unknown, metadataService: unkno
181290
export class DeclaredWebhookSource implements DeclaredWebhookReader {
182291
/** Names already reported as failing validation — said once per process. */
183292
private readonly invalidReported = new Set<string>();
293+
/** Names already reported as resolving to no single declaration — said once per process. */
294+
private readonly refusalReported = new Set<string>();
295+
/** The names the last read refused (ADR-0150 D3), each with its refusal. */
296+
private refusals = new Map<string, PackageScopedRefusal>();
184297

185298
constructor(
186299
private readonly engine: unknown,
@@ -201,13 +314,48 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader {
201314

202315
async declaredWebhookNamed(name: string): Promise<DeclaredWebhook | null> {
203316
if (!name) return null;
204-
return (await this.list()).find((d) => d.webhook.name === name) ?? null;
317+
const declared = await this.list();
318+
const refusal = this.refusals.get(name);
319+
if (refusal) throw new DeclaredWebhookAmbiguousError(refusal);
320+
return declared.find((d) => d.webhook.name === name) ?? null;
205321
}
206322

207323
private parseDeclared(): Array<{ webhook: WebhookParsed; packageId?: string }> {
208324
const out: Array<{ webhook: WebhookParsed; packageId?: string }> = [];
209-
const seen = new Set<string>();
210-
for (const raw of readDeclaredWebhookItems(this.engine, this.metadataService)) {
325+
const raws = readDeclaredWebhookItems(this.engine, this.metadataService);
326+
const listedByName = new Map<string, unknown[]>();
327+
for (const raw of raws) {
328+
const name = (raw as { name?: unknown })?.name;
329+
if (typeof name !== 'string' || name === '') continue;
330+
const listed = listedByName.get(name);
331+
if (listed) listed.push(raw);
332+
else listedByName.set(name, [raw]);
333+
}
334+
const registry = packageScopedRegistryOf(this.engine);
335+
const refusals = new Map<string, PackageScopedRefusal>();
336+
const answered = new Set<string>();
337+
for (const listedRaw of raws) {
338+
let raw = listedRaw;
339+
const listedName = (listedRaw as { name?: unknown })?.name;
340+
// A name serves ONE declaration (ADR-0150 D3): asked once, at its
341+
// first listing; a nameless item goes on to fail validation below.
342+
if (typeof listedName === 'string' && listedName !== '') {
343+
if (answered.has(listedName)) continue;
344+
answered.add(listedName);
345+
const chosen = chooseDeclaration(listedName, listedByName.get(listedName) ?? [listedRaw], registry);
346+
if ('refusal' in chosen) {
347+
refusals.set(listedName, chosen.refusal);
348+
if (!this.refusalReported.has(listedName)) {
349+
this.refusalReported.add(listedName);
350+
this.logger?.warn?.(
351+
`[webhook] declared webhook '${listedName}' is not dispatched: ${chosen.refusal.message}`,
352+
{ name: listedName, candidates: chosen.refusal.candidates },
353+
);
354+
}
355+
continue;
356+
}
357+
raw = chosen.item;
358+
}
211359
let webhook: WebhookParsed;
212360
try {
213361
webhook = WebhookSchema.parse(raw);
@@ -222,13 +370,10 @@ export class DeclaredWebhookSource implements DeclaredWebhookReader {
222370
}
223371
continue;
224372
}
225-
// Two registrations of one name: the first wins, as the seeder's
226-
// name-keyed upsert let the first one hold the row.
227-
if (seen.has(webhook.name)) continue;
228-
seen.add(webhook.name);
229373
const pkg = (raw as { _packageId?: unknown })._packageId;
230374
out.push({ webhook, ...(typeof pkg === 'string' && pkg ? { packageId: pkg } : {}) });
231375
}
376+
this.refusals = refusals;
232377
return out;
233378
}
234379
}

‎packages/plugins/plugin-webhooks/vitest.config.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,13 @@ export default defineConfig({
3737
// Mechanism + measured costs: examples/app-showcase/vitest.config.ts.
3838
// Enforced repo-wide by scripts/check-console-intercept-disarm.mjs.
3939
disableConsoleIntercept: true,
40+
// #13517: quiet the registry's per-item registration chatter — the
41+
// engine's own `OS_REGISTRY_LOG` seam, not a change to its shipped
42+
// default. Enforced by scripts/check-registry-log-declared.mjs, which
43+
// reads this suite as engine-booting since `declared-webhooks.test.ts`
44+
// resolves declared webhook names through a real `SchemaRegistry`
45+
// (ADR-0150 D3).
46+
env: { OS_REGISTRY_LOG: 'warn' },
4047
},
4148
resolve: {
4249
alias: [

0 commit comments

Comments
 (0)