Skip to content

Commit 6328a07

Browse files
fix(plugin-security): metadata-derived caches invalidate on a runtime metadata publish (#26878)
Fixes #26596 Fixes #26698 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:安全插件(plugin-security)把从对象元数据推导出的鉴权输入缓存起来复用;现在每次运行时元数据发布(保存、发布、回滚、删除、制品重载)之后,这些缓存会立即失效,下一次请求按新发布的声明判定,无需重启。 - **为什么改**:管理员上线后调整对象的访问声明(Studio 的组织默认值面板、元数据保存、AI 作者、包发布)需要即时生效;原来的失效订阅挂在元数据服务一个并不存在的 `watch` 接口上,从未触发(具体现象见两张卡片)。 - **风险与回滚**:低。缓存内容与清除逻辑不变,只改了“何时清除”的订阅点;代价是元数据变更后各对象缓存重建一次。回滚即 revert 本 PR。 - **先看**:① `packages/plugins/plugin-security/src/metadata-change-invalidation.ts`(订阅哪两个信号、为什么不订阅元数据服务的 watcher);② `security-plugin.ts` 中 `start()` 的订阅处与 `invalidateMetadataDerivedCaches()`;③ dogfood pin `security-verdict-follows-runtime-metadata-change.dogfood.test.ts`。 - **两分钟验证**:建好 dogfood 依赖闭包后运行 `pnpm --filter @objectstack/dogfood exec vitest run test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts`,预期 6/6 通过;同一命令在修复前的构建上 6 个用例中 5 个失败。 - **需要你做的**:无,席位落地。 ## What changes The security plugin's metadata-derived caches now invalidate on a runtime metadata publish. Symptom detail stays on the cards (#26596, #26698). - **`packages/plugins/plugin-security/src/metadata-change-invalidation.ts` (new).** `subscribeMetadataChangeInvalidation(ctx, invalidate)` wires one clearing body to two signals: 1. the protocol's post-persistence `onMetadataMutation` notification, skipping drafts. Every metadata authoring door emits it (`saveMetaItem`, `publishMetaItem` and the package publish, `revertCommit`, `rollbackMetaItem`, `deleteMetaItem`) after the engine registry write-through, so the cache refill reads the new definition. A cluster peer's mutation is replayed into the same listeners after that replica's registry converges; 2. the `metadata:reloaded` kernel hook (artifact reload, batch publish announce). The plugin already declares `dependencies: ['com.objectstack.engine.objectql']`, so its handler runs after ObjectQL's ingest on the same hook. A protocol service without `onMetadataMutation` is reported once at `warn` (a functional degradation). A kernel with no protocol has no authoring door, so nothing is reported. - **`security-plugin.ts`.** The `md.watch('*', …)` probe is replaced by that subscription. The clearing body moved verbatim into `invalidateMetadataDerivedCaches()`. `destroy()` releases the protocol subscription. The stale "schemas are immutable, no invalidation" docblock on `fieldNamesCache` is corrected. - **Landing site.** The fix lands only in `plugin-security`. `packages/metadata/src/**` is untouched, because measurement showed the metadata service is not the producer (Verification › seam). The protocol's `onMetadataMutation` is a seam plugin-security already consumes for the `everyone` re-derivation. - **Changeset.** `.changeset/26596-security-cache-invalidation.md`, a `patch` for `@objectstack/plugin-security`. ## Tests All readings are on head `8dcb3e2a`. Its tree is `f87a2d44`, the same tree as the pre-restructure merge head `8b4f335d` where the post-merge runs were taken. - **New HTTP pin.** `packages/qa/dogfood/test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts` uses `orgContext: true` and `assertArmed`. It covers five objects, each created at runtime through `PUT /meta/object/:name`, used by a member first, then changed through the same door, with the verdict read before and after. Each case is its own control, and the cases are listed in the file's header. It ran red on the pre-fix build (5 of 6) and green after (6 of 6). - **New unit file.** `metadata-change-invalidation.test.ts`: - drafts are skipped; - `metadata:reloaded` invalidates; - the disposer stops delivery; - the older-protocol `warn`; - the no-protocol silence; - through the plugin's own lifecycle: every cache is cleared, the epoch advances, the metadata service's `subscribe`/`watchService` are not used, and `destroy()` stops listening. - **Fixture triage.** - `security-plugin.test.ts` › "metadata-change cache invalidation" and `controlled-by-parent-reference-alias.test.ts` › `boot()` both mocked a `watch` member that no shipped metadata service has. Both pinned the removed branch, so they were **replaced** to drive the protocol seam. - `everyone-rederivation-on-permission-mutation.test.ts` counted every protocol listener. It now reads the listeners the bootstrap adds after `start()`'s own. ## Acceptance notes - **Cluster (H3).** The `onMetadataMutation` path receives cluster-replayed events: `applyRemoteMetadataMutation` replays into the same listeners after convergence. This is already pinned by `packages/metadata-protocol/src/protocol.cluster-mutation-fanout.test.ts` ("the peer's onMetadataMutation listeners receive the remote event, once, after convergence") and was not re-measured here. The old comment's `metadata.changed` channel is the metadata service's channel, which runtime authoring never publishes on. - **Other `md.watch` probes (H4).** None. `git grep` over `packages/plugins` and `packages/services` (and the rest of `packages/`) finds plugin-security as the only probe of a metadata-service `watch`. The other `.watch(` hits are `MetadataRepository.watch` (metadata-core / metadata-fs / metadata-protocol / MetadataManager's repo loop), chokidar, and the Redis client. All are live, and none is this seam. - **Not subscribed: the metadata service's own watchers.** No runtime registration of an object announces there (every `register('object', …)` at runtime passes `notify: false`). The watchers' remaining producers are the dev FileSystemRepository watch and its `metadata.changed` replay. A clear on those events would also land before ObjectQL's asynchronous registry refresh for the same event. No reproduction, so this is noted rather than filed. - **`IMetadataService.watch?`.** It is declared in `packages/spec/src/contracts/metadata-service.ts`, and after this PR it has no implementer and no consumer. That is declared surface with no pull; carrier: none. - **Wall time.** The new dogfood file measured 24.9 s of file wall (tests 6.65 s) on a shared box, over the 10 s file line like every stack-booting dogfood file. No `test-budget` class fits, so none is declared. - **Commit layout.** There is one commit per card: `9864bb92` (#26596: fix, unit tests, changeset, `sharingModel` cases) and `8dcb3e2a` (#26698: the remaining pin cases). The branch was re-laid onto `3c2187f4` before this PR opened (no reviewer, sole author), tree-identical to the tested head. ## Verification <details><summary>Seam measurement: which subscription hears a runtime object save</summary> A throwaway probe (not committed) booted a stack and subscribed before two `PUT /meta/object/zzp_thing` saves (both 200): ``` metadata service class NodeMetadataManager, has watch: undefined seen {"subscribeObject":0,"subscribeStar":0,"watchServiceObject":0,"watchServiceStar":0,"protocolMutation":2} ``` The old `typeof md?.watch === 'function'` probe was a no-op. The metadata service's watchers, exact-type or `'*'`, never fire for a runtime save. The protocol's `onMetadataMutation` fires once per save. </details> <details><summary>Red on the pre-fix build, green after</summary> - Pre-fix, on base `43731031` with the closure built from it: `Tests 5 failed | 1 passed (6)`, VERDICT command-exit 1. - After the fix: `Tests 6 passed (6)`, VERDICT command-exit 0. - After merging `origin/main` (`3c2187f4`) and rebuilding the dogfood closure (`Tasks: 67 successful, 67 total`): the pin plus `owd-public-read-write-write-floor.dogfood.test.ts` gave `Test Files 2 passed (2)` and `Tests 16 passed (16)`, VERDICT command-exit 0. </details> <details><summary>Ablation: the protocol listener carries the fix</summary> `node scripts/ablation-replace.mjs` replaced the listener's draft guard with one that returns for every event, leaving the `metadata:reloaded` hook wired: anchor x1 to x0, blob `677b3111` to `df2e7be4`. - Mutated leg: `pnpm --filter @objectstack/plugin-security build` exit 0, then `ablation-dist-preflight` found the marker present in `dist/index.js` and `dist/index.mjs`. The pin gave `Tests 5 failed | 1 passed (6)`. - Restore leg: blob back to `677b3111`, the same as HEAD, and `git diff HEAD` empty. The rebuild exited 0, `--absent` reported the marker absent from all 6 built files, and the pin gave `Tests 6 passed (6)`. </details> <details><summary>Unit, typecheck, lint</summary> All runs are on head `8dcb3e2a`. Every `os-verify-lock` VERDICT was command-exit 0, read from the lock's own line. - `pnpm --filter @objectstack/plugin-security typecheck`: green (tsc, scripts tsconfig, `check:test-typecheck OK — 0 file(s) / 0 error(s)`). - `pnpm --filter @objectstack/dogfood typecheck`: green. - `pnpm --filter @objectstack/plugin-security test`: `Test Files 232 passed (232)`, `Tests 5040 passed | 45 skipped (5085)`. - `eslint --no-inline-config` over the eight changed TypeScript files: exit 0, no output. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derived 66 commands from merge base `3c2187f4`, and all were run, each exit code captured before any pipe. Three first answered exit 3 (PREREQUISITE NOT MET) and were re-run to a reading: - `check-plugin-teardown-shape --self-test`: its pinned fixture commit was fetched, then exit 0, 48 cases. - `check:dual-build-cjs-loads`: the seven packages lacking `dist/` were built, then exit 0. - `check:type-check-debt`: run under the verify lock, then exit 0, "0 raw tsc error(s)". - `dispatch-gates --ran`: "66 derived, 66 run, 0 NOT-MEASURED, 0 UNRUN". - Not run locally, because CI owns them: `pnpm lint`, and the `test:repo` project (this diff touches none of its tests). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01J8VVAkZns5rNnK2rtszzbQ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3271a08 commit 6328a07

9 files changed

Lines changed: 720 additions & 62 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-security': patch
3+
---
4+
5+
fix(plugin-security): the security plugin's metadata-derived caches now invalidate on a runtime metadata publish
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The security plugin keeps the per-object inputs it derives from metadata for reuse across requests. Those caches are now dropped whenever metadata changes at runtime, so the next request is judged by the published declaration without a restart (#26596, #26698):
11+
12+
- **The signal.** The plugin listens to the protocol's post-persistence `onMetadataMutation` notification, which every metadata authoring door emits (save, per-item and package publish, revert, rollback, delete) after the engine registry holds the new definition, and which a cluster peer replays after converging its own registry. Drafts are ignored. It also listens to the `metadata:reloaded` announcement that an artifact reload fires.
13+
- **What it replaces.** The previous subscription probed an optional `watch` member on the metadata service, which `MetadataManager` does not implement, and the runtime authoring path does not announce to the metadata service's watchers in any case.
14+
- **Composition note.** A protocol service that offers no `onMetadataMutation` is reported once at `warn` when the plugin starts.

‎packages/plugins/plugin-security/src/controlled-by-parent-reference-alias.test.ts‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,26 +62,32 @@ function detailSchema(field: string, value: unknown, extra: Record<string, unkno
6262
* Boot a real `SecurityPlugin` over a fake registry, through the plugin's OWN
6363
* lifecycle — `start()` is what binds `this.logger` to the host sink and what
6464
* subscribes the cache invalidation, so both facts under test here are only
65-
* true of a started plugin. Returns the metadata `watch` callback so a test can
66-
* drive a real metadata-change invalidation rather than reaching into the cache.
65+
* true of a started plugin. Returns the protocol's `onMetadataMutation` listener
66+
* the plugin subscribed, so a test can drive a real metadata-change
67+
* invalidation rather than reaching into the cache.
6768
*/
6869
async function boot(schemas: Record<string, any>) {
6970
const warn = vi.fn();
70-
let onMetadataChange: (() => void) | undefined;
71+
// Every listener the plugin subscribes, fired together as the protocol does:
72+
// `start()` wires more than one (the `everyone` re-derivation listens too).
73+
const mutationListeners: Array<(evt: { type: string; name: string; state: string }) => void> = [];
7174
const ql: any = {
7275
getSchema: (object: string) => schemas[object],
7376
registerMiddleware: () => {},
7477
};
7578
const metadata: any = {
76-
watch: (_pattern: string, cb: () => void) => {
77-
onMetadataChange = cb;
79+
list: async () => [],
80+
};
81+
const protocol: any = {
82+
onMetadataMutation: (listener: (typeof mutationListeners)[number]) => {
83+
mutationListeners.push(listener);
7884
return () => {};
7985
},
80-
list: async () => [],
8186
};
8287
const services: Record<string, any> = {
8388
objectql: ql,
8489
metadata,
90+
protocol,
8591
manifest: { register: () => {} },
8692
};
8793
const ctx: any = {
@@ -99,10 +105,10 @@ async function boot(schemas: Record<string, any>) {
99105
plugin,
100106
warn,
101107
resolve: (object: string) => (plugin as any).resolveCbpRelation(object),
102-
/** Fire the real `metadata.watch('*')` subscription `start()` installed. */
108+
/** Fire the real metadata-mutation subscription `start()` installed. */
103109
changeMetadata: () => {
104-
if (!onMetadataChange) throw new Error('plugin did not subscribe to metadata changes');
105-
onMetadataChange();
110+
if (mutationListeners.length === 0) throw new Error('plugin did not subscribe to metadata changes');
111+
for (const listener of mutationListeners) listener({ type: 'object', name: 'crm_contact', state: 'active' });
106112
},
107113
};
108114
}
@@ -238,7 +244,7 @@ describe('resolveCbpRelation — the tolerance is LOUD (#13250)', () => {
238244
resolve('crm_contact');
239245
expect(aliasWarns(warn)).toHaveLength(1);
240246

241-
// Studio / AI authoring edited metadata: `start()`'s `metadata.watch('*')`
247+
// Studio / AI authoring edited metadata: `start()`'s metadata-mutation
242248
// subscription clears `cbpRelCache`, and the report rides that same
243249
// lifecycle deliberately — a process-lifetime "already warned" set would
244250
// stay silent here, which is the one moment the author is listening.

‎packages/plugins/plugin-security/src/everyone-rederivation-on-permission-mutation.test.ts‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,27 +75,33 @@ async function boot() {
7575
const plugin = new SecurityPlugin();
7676
await plugin.init(ctx);
7777
await plugin.start(ctx);
78+
// [#26596, #26698] `start()` itself subscribes the metadata-derived cache
79+
// invalidation; the listeners this suite pins are the ones the bootstrap
80+
// adds after it, at `kernel:ready`.
81+
const atStart = listeners.length;
82+
const bootstrapListeners = () => listeners.slice(atStart);
7883
const fire = async (event: string) => {
7984
for (const [, cb] of hook.mock.calls.filter((c: any[]) => c[0] === event)) await cb();
8085
};
8186
const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((r) => setTimeout(r, 0)); };
82-
return { ctx, fire, settle, listeners, derive };
87+
return { ctx, fire, settle, bootstrapListeners, derive };
8388
}
8489

8590
describe('[#22801 → A] a landed permission mutation re-derives everyone', () => {
8691
it('registers ONE listener, and a bootstrap re-run never adds a second', async () => {
87-
const { ctx, fire, listeners } = await boot();
92+
const { ctx, fire, bootstrapListeners } = await boot();
8893
await fire('kernel:ready');
8994
// Positive control: the bootstrap really completed.
9095
expect(ctx.logger.info.mock.calls.filter((c: any[]) => String(c[0]).includes('platform bootstrap complete'))).toHaveLength(1);
91-
expect(listeners).toHaveLength(1);
96+
expect(bootstrapListeners()).toHaveLength(1);
9297
await fire('kernel:ready');
93-
expect(listeners).toHaveLength(1);
98+
expect(bootstrapListeners()).toHaveLength(1);
9499
});
95100

96101
it('a published or deleted permission derives everyone again — whatever the body said', async () => {
97-
const { fire, settle, listeners, derive } = await boot();
102+
const { fire, settle, bootstrapListeners, derive } = await boot();
98103
await fire('kernel:ready');
104+
const listeners = bootstrapListeners();
99105
const before = derive.mock.calls.length;
100106

101107
listeners[0]!({ type: 'permission', name: 'crm_sales_user', state: 'active' });
@@ -108,8 +114,9 @@ describe('[#22801 → A] a landed permission mutation re-derives everyone', () =
108114
});
109115

110116
it('a draft, or a mutation of another type, derives nothing', async () => {
111-
const { fire, settle, listeners, derive } = await boot();
117+
const { fire, settle, bootstrapListeners, derive } = await boot();
112118
await fire('kernel:ready');
119+
const listeners = bootstrapListeners();
113120
const before = derive.mock.calls.length;
114121

115122
listeners[0]!({ type: 'permission', name: 'crm_sales_user', state: 'draft' });
Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26596, #26698] The metadata-change subscription contract: which signals
5+
* drop the security plugin's metadata-derived caches, and which do not.
6+
*
7+
* The HTTP-level proof that a member's verdict follows a runtime change is
8+
* `packages/qa/dogfood/test/security-verdict-follows-runtime-metadata-change.dogfood.test.ts`;
9+
* this file pins the seam it rests on.
10+
*/
11+
12+
import { describe, it, expect, vi } from 'vitest';
13+
import { subscribeMetadataChangeInvalidation } from './metadata-change-invalidation.js';
14+
import { SecurityPlugin } from './security-plugin.js';
15+
16+
type MutationEvent = { type: string; name: string; state: string };
17+
18+
/** A protocol double carrying the one member the module subscribes through. */
19+
function fakeProtocol() {
20+
const listeners = new Set<(evt: MutationEvent) => void>();
21+
return {
22+
listeners,
23+
onMetadataMutation(listener: (evt: MutationEvent) => void) {
24+
listeners.add(listener);
25+
return () => { listeners.delete(listener); };
26+
},
27+
emit(evt: MutationEvent) {
28+
for (const l of [...listeners]) l(evt);
29+
},
30+
};
31+
}
32+
33+
function fakeCtx(services: Record<string, unknown>) {
34+
const hooks = new Map<string, Array<() => void>>();
35+
return {
36+
hooks,
37+
logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },
38+
registerService: vi.fn(),
39+
getService: (name: string) => {
40+
if (!(name in services)) throw new Error(`service not registered: ${name}`);
41+
return services[name];
42+
},
43+
hook: (name: string, handler: () => void) => {
44+
hooks.set(name, [...(hooks.get(name) ?? []), handler]);
45+
},
46+
fire(name: string) {
47+
for (const h of hooks.get(name) ?? []) h();
48+
},
49+
};
50+
}
51+
52+
describe('subscribeMetadataChangeInvalidation', () => {
53+
it('a landed (non-draft) metadata mutation invalidates; a draft does not', () => {
54+
const protocol = fakeProtocol();
55+
const ctx = fakeCtx({ protocol });
56+
const invalidate = vi.fn();
57+
subscribeMetadataChangeInvalidation(ctx, invalidate);
58+
59+
protocol.emit({ type: 'object', name: 'crm_account', state: 'draft' });
60+
expect(invalidate, 'a draft never enters the registry').not.toHaveBeenCalled();
61+
62+
protocol.emit({ type: 'object', name: 'crm_account', state: 'active' });
63+
protocol.emit({ type: 'permission', name: 'crm_rep', state: 'deleted' });
64+
expect(invalidate).toHaveBeenCalledTimes(2);
65+
});
66+
67+
it('the `metadata:reloaded` announcement invalidates', () => {
68+
const ctx = fakeCtx({ protocol: fakeProtocol() });
69+
const invalidate = vi.fn();
70+
subscribeMetadataChangeInvalidation(ctx, invalidate);
71+
72+
ctx.fire('metadata:reloaded');
73+
expect(invalidate).toHaveBeenCalledTimes(1);
74+
});
75+
76+
it('returns the protocol subscription disposer, which stops delivery', () => {
77+
const protocol = fakeProtocol();
78+
const invalidate = vi.fn();
79+
const disposers = subscribeMetadataChangeInvalidation(fakeCtx({ protocol }), invalidate);
80+
expect(disposers).toHaveLength(1);
81+
82+
disposers[0]!();
83+
protocol.emit({ type: 'object', name: 'crm_account', state: 'active' });
84+
expect(invalidate).not.toHaveBeenCalled();
85+
});
86+
87+
it('a protocol older than the seam is reported once, at `warn`; the reload hook is still wired', () => {
88+
const ctx = fakeCtx({ protocol: {} });
89+
const invalidate = vi.fn();
90+
const disposers = subscribeMetadataChangeInvalidation(ctx, invalidate);
91+
92+
expect(disposers).toEqual([]);
93+
expect(ctx.logger.warn).toHaveBeenCalledTimes(1);
94+
expect(String(ctx.logger.warn.mock.calls[0]![0])).toContain('onMetadataMutation');
95+
96+
ctx.fire('metadata:reloaded');
97+
expect(invalidate).toHaveBeenCalledTimes(1);
98+
});
99+
100+
it('a kernel with no protocol has no authoring door to hear from: nothing to report', () => {
101+
const ctx = fakeCtx({});
102+
const disposers = subscribeMetadataChangeInvalidation(ctx, vi.fn());
103+
expect(disposers).toEqual([]);
104+
expect(ctx.logger.warn).not.toHaveBeenCalled();
105+
});
106+
});
107+
108+
describe('SecurityPlugin — metadata-change invalidation through its own lifecycle', () => {
109+
/**
110+
* The metadata service here carries exactly the watch API `MetadataManager`
111+
* exposes (`subscribe`, `watchService`) and no `watch` member: the
112+
* invalidation must not depend on the metadata service's watchers at all,
113+
* because the runtime authoring path never announces to them.
114+
*/
115+
async function boot() {
116+
const protocol = fakeProtocol();
117+
const metadata = { subscribe: vi.fn(() => () => {}), watchService: vi.fn(() => ({ unsubscribe() {} })) };
118+
const ctx = fakeCtx({
119+
protocol,
120+
metadata,
121+
manifest: { register: vi.fn() },
122+
objectql: { registerMiddleware: vi.fn(), getSchema: () => undefined },
123+
});
124+
const plugin = new SecurityPlugin();
125+
await plugin.init(ctx as any);
126+
await plugin.start(ctx as any);
127+
return { plugin: plugin as any, protocol, ctx, metadata };
128+
}
129+
130+
const seed = (plugin: any) => {
131+
plugin.fieldNamesCache.set('crm_account', new Set(['name']));
132+
plugin.datetimeFieldNamesCache.set('crm_account', new Set());
133+
plugin.numberComparandFieldsCache.set('crm_account', new Map());
134+
plugin.tenancyDisabledCache.set('crm_account', false);
135+
plugin.cbpRelCache.set('crm_account', null);
136+
plugin.objectSecurityMetaCache.set('crm_account', { owdOpensRowWrites: false });
137+
};
138+
const sizes = (plugin: any) => [
139+
plugin.fieldNamesCache.size,
140+
plugin.datetimeFieldNamesCache.size,
141+
plugin.numberComparandFieldsCache.size,
142+
plugin.tenancyDisabledCache.size,
143+
plugin.cbpRelCache.size,
144+
plugin.objectSecurityMetaCache.size,
145+
];
146+
147+
it('a mutation clears every metadata-derived cache and advances the epoch', async () => {
148+
const { plugin, protocol, metadata } = await boot();
149+
seed(plugin);
150+
const epochBefore = plugin.epoch.current;
151+
152+
protocol.emit({ type: 'object', name: 'crm_account', state: 'active' });
153+
154+
expect(sizes(plugin)).toEqual([0, 0, 0, 0, 0, 0]);
155+
expect(plugin.epoch.current, 'the per-context permission-set memo is retired too').toBeGreaterThan(epochBefore);
156+
expect(metadata.subscribe, 'not the metadata service watchers').not.toHaveBeenCalled();
157+
expect(metadata.watchService).not.toHaveBeenCalled();
158+
});
159+
160+
it('`metadata:reloaded` clears them as well', async () => {
161+
const { plugin, ctx } = await boot();
162+
seed(plugin);
163+
ctx.fire('metadata:reloaded');
164+
expect(sizes(plugin)).toEqual([0, 0, 0, 0, 0, 0]);
165+
});
166+
167+
it('destroy() releases the protocol subscription', async () => {
168+
const { plugin, protocol } = await boot();
169+
const subscribed = protocol.listeners.size;
170+
expect(subscribed).toBeGreaterThan(0);
171+
await plugin.destroy();
172+
seed(plugin);
173+
protocol.emit({ type: 'object', name: 'crm_account', state: 'active' });
174+
expect(sizes(plugin), 'a destroyed plugin no longer listens').toEqual([1, 1, 1, 1, 1, 1]);
175+
});
176+
});

0 commit comments

Comments
 (0)