Repository navigation
Expand file tree
/
Copy pathcapability-composition.test.ts
More file actions
390 lines (356 loc) · 19.8 KB
/
Copy pathcapability-composition.test.ts
File metadata and controls
390 lines (356 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* #22301 — the rule both `os serve` and `@objectstack/verify`'s `bootStack`
* read for which capability tokens a served boot mounts providers for, and
* what it constructs each provider with. One case per step of each rule, each
* against the answer the step changes, so a step that stops running turns a
* case red rather than leaving every case green.
*/
import { afterEach, describe, expect, it } from 'vitest';
import { composeStacks, defineStack } from '@objectstack/spec';
import { PLATFORM_ALWAYS_ON_CAPABILITIES, PLATFORM_CAPABILITY_PROVIDERS } from '@objectstack/spec/kernel';
import {
resolveCapabilityArgument,
resolveCapabilityExtras,
resolveKnowledgeStore,
resolveServedCapabilities,
stackItemCapabilities,
} from './capability-composition.js';
import { CAPABILITY_PROVIDERS, KNOWLEDGE_STORE_PROVIDERS } from './capability-providers.js';
import { stackDeclaredCapabilities } from './stack-collections.js';
const SLATE = [...PLATFORM_ALWAYS_ON_CAPABILITIES];
const svcManifest = { id: 'com.example.ccp.svc', name: 'CCP Service', namespace: 'ccp', version: '1.0.0', type: 'module' };
const appManifest = { id: 'com.example.ccp.app', name: 'CCP App', namespace: 'ccp', version: '1.0.0', type: 'app' };
const note = {
name: 'ccp_note', label: 'Note', pluralLabel: 'Notes', sharingModel: 'public_read_write',
fields: { name: { name: 'name', type: 'text', label: 'Name', required: true } },
};
const ticket = {
name: 'ccp_ticket', label: 'Ticket', pluralLabel: 'Tickets', sharingModel: 'public_read_write',
fields: { title: { name: 'title', type: 'text', label: 'Title', required: true } },
};
/** Two packages through the real producer: `svcExtra` lives only in the service package's body. */
const twoPackages = (svcExtra: Record<string, unknown>): Record<string, unknown> =>
composeStacks(
[
defineStack({ manifest: svcManifest, objects: [note], ...svcExtra } as never),
defineStack({ manifest: appManifest, objects: [ticket] } as never),
],
{ manifest: 'preserve' },
) as unknown as Record<string, unknown>;
describe('resolveServedCapabilities — which tokens a served boot mounts', () => {
it('an app that declares nothing gets the always-on slate, in the slate\'s order', () => {
const served = resolveServedCapabilities([]);
// Anti-vacuity: the slate is the spec's, and it is not empty.
expect(SLATE.length).toBeGreaterThan(0);
expect(served.tokens).toEqual(SLATE);
expect([...served.declared]).toEqual([]);
});
it('the declared tokens come first, deduplicated, and a slate member declared is not repeated', () => {
const served = resolveServedCapabilities(['automation', 'cache', 'automation']);
expect(served.tokens.slice(0, 2)).toEqual(['automation', 'cache']);
expect(served.tokens.filter((token) => token === 'cache')).toEqual(['cache']);
expect(served.tokens.slice(2)).toEqual(SLATE.filter((token) => token !== 'cache'));
expect([...served.declared]).toEqual(['automation', 'cache']);
});
it('`--preset minimal` mounts no slate — only what the stack declares', () => {
expect(resolveServedCapabilities(['automation'], { preset: 'minimal' }).tokens).toEqual(['automation']);
// Control: any other preset name keeps the slate.
expect(resolveServedCapabilities(['automation'], { preset: 'default' }).tokens).toEqual([
'automation',
...SLATE,
]);
});
it('a declared `auth` brings `email`, and `job` / `queue` move ahead of what schedules background work', () => {
const served = resolveServedCapabilities(['auth'], { preset: 'minimal' });
expect(served.tokens).toEqual(['job', 'queue', 'auth', 'email']);
// `email` was appended by the platform, not declared by the stack.
expect([...served.declared]).toEqual(['auth']);
// Control: nothing that schedules background work, nothing moved.
expect(resolveServedCapabilities(['automation'], { preset: 'minimal' }).tokens).toEqual(['automation']);
});
it('the host defaults land after the declared tokens and before the slate', () => {
const served = resolveServedCapabilities(['automation'], { hostDefaults: ['mcp', 'pinyin-search'] });
expect(served.tokens).toEqual(['automation', 'mcp', 'pinyin-search', ...SLATE]);
expect(served.declared.has('mcp')).toBe(false);
});
it('a package body\'s `requires`, as `stackDeclaredCapabilities` reads it for the boots, is what the rule mounts', () => {
const stack = twoPackages({ requires: ['approvals'] });
// Anti-vacuity: the producer really left `requires` out of the top level.
expect(stack.requires).toBeUndefined();
const served = resolveServedCapabilities(stackDeclaredCapabilities(stack), { preset: 'minimal' });
expect(served.tokens).toEqual(['job', 'queue', 'approvals']);
expect([...served.declared]).toEqual(['approvals']);
});
});
describe('resolveCapabilityArgument — what each provider is constructed with', () => {
it('`automation` is handed the app\'s root', () => {
expect(resolveCapabilityArgument('automation', { stack: {}, packageRoot: '/srv/app' }).argument).toEqual({
packageRoot: '/srv/app',
});
});
it('`analytics` is handed the stack\'s cubes: the top level first, then `cubes`, then the package bodies', () => {
const top = [{ name: 'top_cube' }];
const legacy = [{ name: 'legacy_cube' }];
const arg = (stack: unknown) => resolveCapabilityArgument('analytics', { stack, packageRoot: '/app' }).argument;
expect(arg({ analyticsCubes: top, cubes: legacy })).toEqual({ cubes: top });
expect(arg({ cubes: legacy })).toEqual({ cubes: legacy });
const bodyCube = {
name: 'ccp_note_cube', title: 'Notes', sql: 'ccp_note',
measures: { count: { label: 'Count', type: 'count', sql: '*' } },
dimensions: { name: { label: 'Name', type: 'string', sql: 'name' } },
};
const stack = twoPackages({ analyticsCubes: [bodyCube] });
expect(stack.analyticsCubes).toBeUndefined();
expect((arg(stack) as { cubes: Array<{ name: string }> }).cubes.map((cube) => cube.name)).toEqual(['ccp_note_cube']);
// Control: a stack with no cubes hands an empty list, never someone else's.
expect(arg({})).toEqual({ cubes: [] });
});
it('`email` and `sms` are built by the reader their provider module exports, from the stack and the env', () => {
const calls: unknown[][] = [];
const providerModule = {
resolveEmailCapabilityArg: (...args: unknown[]) => {
calls.push(['email', ...args]);
return { options: { built: 'email' } };
},
resolveSmsCapabilityArg: (...args: unknown[]) => {
calls.push(['sms', ...args]);
return { options: { built: 'sms' } };
},
};
const env = { OS_EMAIL_PROVIDER: 'log' };
const stack = { email: { persist: false }, sms: { provider: 'log' }, appName: 'Acme' };
expect(resolveCapabilityArgument('email', { stack, packageRoot: '/app', providerModule, env }).argument).toEqual({
built: 'email',
});
expect(resolveCapabilityArgument('sms', { stack, packageRoot: '/app', providerModule, env }).argument).toEqual({
built: 'sms',
});
expect(calls).toEqual([
['email', { persist: false }, env, 'Acme'],
['sms', { provider: 'log' }, env],
]);
// An absent block is read as `{}`, never skipped.
calls.length = 0;
resolveCapabilityArgument('email', { stack: {}, packageRoot: '/app', providerModule, env });
expect(calls).toEqual([['email', {}, env, undefined]]);
});
it('`push` is built by resolvePushCapabilityArg off its provider module, from the stack\'s push key alone', () => {
const calls: unknown[][] = [];
const providerModule = {
resolvePushCapabilityArg: (...args: unknown[]) => {
calls.push(args);
return { options: { config: { built: 'push' } } };
},
};
const push = { transport: 'direct', fcm: { projectId: 'p', credentialRef: 'FCM' } };
expect(resolveCapabilityArgument('push', { stack: { push }, packageRoot: '/app', providerModule, env: { OS_X: '1' } }).argument)
.toEqual({ config: { built: 'push' } });
// The stack's key only: no environment carries push configuration.
expect(calls).toEqual([[push]]);
// An absent key is read as `{}` — the reader decides (it refuses the relay that reads as), never skipped.
calls.length = 0;
resolveCapabilityArgument('push', { stack: {}, packageRoot: '/app', providerModule });
expect(calls).toEqual([[{}]]);
// A reader's refusal reaches the boot unchanged.
const refusing = { resolvePushCapabilityArg: () => { throw new Error('relay not served'); } };
expect(() => resolveCapabilityArgument('push', { stack: {}, packageRoot: '/app', providerModule: refusing }))
.toThrow('relay not served');
expect(() => resolveCapabilityArgument('push', { stack: {}, packageRoot: '/app', providerModule: {} })).toThrow(
/@objectstack\/service-push does not export resolvePushCapabilityArg/,
);
});
it('a provider module without its reader is refused by name, never built with defaults', () => {
expect(() => resolveCapabilityArgument('email', { stack: {}, packageRoot: '/app', providerModule: {} })).toThrow(
/does not export resolveEmailCapabilityArg/,
);
expect(() => resolveCapabilityArgument('sms', { stack: {}, packageRoot: '/app' })).toThrow(
/does not export resolveSmsCapabilityArg/,
);
});
describe('`storage` is handed its local root', () => {
const saved = { canonical: process.env.OS_STORAGE_LOCAL_ROOT, legacy: process.env.OS_STORAGE_ROOT };
afterEach(() => {
for (const [name, value] of [['OS_STORAGE_LOCAL_ROOT', saved.canonical], ['OS_STORAGE_ROOT', saved.legacy]] as const) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
});
it('the built-in root when the environment names none, and the environment\'s when it does', () => {
delete process.env.OS_STORAGE_LOCAL_ROOT;
delete process.env.OS_STORAGE_ROOT;
expect(resolveCapabilityArgument('storage', { stack: {}, packageRoot: '/app' })).toEqual({
argument: { adapter: 'local', local: { rootDir: '.objectstack/data/uploads' } },
localStorageRoot: '.objectstack/data/uploads',
});
process.env.OS_STORAGE_LOCAL_ROOT = '/srv/uploads';
expect(resolveCapabilityArgument('storage', { stack: {}, packageRoot: '/app' }).argument).toEqual({
adapter: 'local',
local: { rootDir: '/srv/uploads' },
});
});
});
it('any other token is constructed with no argument', () => {
for (const token of ['cache', 'queue', 'job', 'messaging', 'approvals', 'not-a-token']) {
expect(resolveCapabilityArgument(token, { stack: { analyticsCubes: [] }, packageRoot: '/app' }), token).toEqual({
argument: undefined,
});
}
});
});
/**
* ADR-0161 — `requires: ['knowledge']` mounts the knowledge service and ONE
* vector store, chosen by the platform database. One case per arm, each
* against the answer that arm changes.
*/
describe('resolveKnowledgeStore — which store the knowledge token mounts', () => {
const root = '/srv/app';
const PG = 'postgres://u:p@db:5432/app';
it('PostgreSQL by the resolved driver or URL: pgvector, handed the platform URL', () => {
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database: { driver: 'postgres', url: PG } })).toEqual({
store: KNOWLEDGE_STORE_PROVIDERS.pgvector,
argument: { url: PG },
});
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database: { url: 'postgresql://db/app' } }).store.adapterId).toBe('pgvector');
// A driver id alone, with a URL the store cannot read: the store reads its own env.
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database: { driver: 'postgres', url: 'pg://db/app' } })).toEqual({
store: KNOWLEDGE_STORE_PROVIDERS.pgvector,
argument: {},
});
});
it('any other database: turso on a file under the app root, its URL configurable in settings', () => {
for (const database of [
{ driver: 'sqlite', url: 'file:/srv/app/.objectstack/data/objectstack.db' },
{ driver: 'turso', url: 'libsql://x.turso.io' },
{ driver: 'mysql', url: 'mysql://db/app' },
{ driver: 'mongodb', url: 'mongodb://db/app' },
]) {
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: {}, database })).toEqual({
store: KNOWLEDGE_STORE_PROVIDERS.turso,
argument: { projectRoot: root, urlFromSettings: true },
});
}
});
it('OS_HOME moves the store with the platform database: the store is handed the state directory', () => {
// `os start --home` sets OS_HOME; the default database is `<OS_HOME>/data/objectstack.db`.
const database = { driver: 'sqlite', url: 'file:/var/lib/os/data/objectstack.db' };
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_HOME: ' /var/lib/os ' }, database })).toEqual({
store: KNOWLEDGE_STORE_PROVIDERS.turso,
argument: { projectRoot: root, stateDir: '/var/lib/os', urlFromSettings: true },
});
// Unset or empty: the app's own `.objectstack/`, as before.
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_HOME: ' ' }, database }).argument).toEqual({
projectRoot: root,
urlFromSettings: true,
});
// The other two arms take no directory.
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_HOME: '/h' }, database: { url: ':memory:' } }).argument).toEqual({ url: ':memory:' });
});
it('an in-memory platform database: an in-memory store', () => {
for (const database of [{ driver: 'sqlite-wasm', url: ':memory:' }, { driver: 'memory' }]) {
expect(resolveKnowledgeStore({ stack: {}, packageRoot: root, database })).toEqual({
store: KNOWLEDGE_STORE_PROVIDERS.turso,
argument: { url: ':memory:' },
});
}
});
it('no resolved database: OS_DATABASE_URL, else DATABASE_URL, decides', () => {
const pick = (env: Record<string, string | undefined>) =>
resolveKnowledgeStore({ stack: {}, packageRoot: root, env }).store.adapterId;
expect(pick({ OS_DATABASE_URL: PG })).toBe('pgvector');
expect(pick({ DATABASE_URL: PG })).toBe('pgvector');
expect(pick({ OS_DATABASE_URL: 'file:./x.db', DATABASE_URL: PG })).toBe('turso');
expect(pick({})).toBe('turso');
// A resolved database wins over the environment.
expect(
resolveKnowledgeStore({ stack: {}, packageRoot: root, env: { OS_DATABASE_URL: PG }, database: { driver: 'sqlite' } }).store.adapterId,
).toBe('turso');
});
});
describe('resolveCapabilityExtras — what a boot mounts after a main provider', () => {
it('knowledge: exactly one store, with its argument; never the in-memory one', () => {
const extras = resolveCapabilityExtras('knowledge', { stack: {}, packageRoot: '/a', database: { driver: 'postgres', url: 'postgres://h/d' } });
expect(extras).toEqual([
{
pkg: '@objectstack/knowledge-pgvector',
export: 'KnowledgePgvectorPlugin',
identities: ['com.objectstack.plugin.knowledge-pgvector', 'KnowledgePgvectorPlugin'],
argument: { url: 'postgres://h/d' },
},
]);
expect(Object.values(KNOWLEDGE_STORE_PROVIDERS).map((s) => s.pkg)).not.toContain('@objectstack/knowledge-memory');
});
it("any other token: its row's extras, each with no argument", () => {
const extras = resolveCapabilityExtras('triggers', { stack: {}, packageRoot: '/a' });
expect(extras.map((e) => e.export)).toEqual((CAPABILITY_PROVIDERS.triggers.extras ?? []).map((e) => e.export));
expect(extras.every((e) => e.argument === undefined)).toBe(true);
expect(resolveCapabilityExtras('cache', { stack: {}, packageRoot: '/a' })).toEqual([]);
});
it('the knowledge row names the service, never a store: the store is the database\'s choice', () => {
expect(CAPABILITY_PROVIDERS.knowledge).toMatchObject({ pkg: '@objectstack/service-knowledge', export: 'KnowledgeServicePlugin' });
expect(CAPABILITY_PROVIDERS.knowledge.extras).toBeUndefined();
});
});
/**
* [ADR-0161 K8 item 12] A `knowledge_source` item mounts the knowledge
* service and the deployment's store, through the token's own provider row;
* and [K4 ◆] the service is told which store is the deployment's.
*/
describe("stackItemCapabilities — a stack's items mount their reader", () => {
const SOURCE = { name: 'ccp_notes', label: 'Notes', source: { kind: 'object', object: 'ccp_note', content: ['name'] } };
it('a stack holding a knowledge source mounts `knowledge`, at the top level or in a package body; none, nothing', () => {
expect(stackItemCapabilities({ knowledgeSources: [SOURCE] })).toEqual(['knowledge']);
const multi = twoPackages({ knowledgeSources: [SOURCE] });
// Anti-vacuity: the producer really left the source out of the top level.
expect(multi.knowledgeSources).toBeUndefined();
expect(stackItemCapabilities(multi)).toEqual(['knowledge']);
expect(stackItemCapabilities(twoPackages({}))).toEqual([]);
expect(stackItemCapabilities({ knowledgeSources: [] })).toEqual([]);
expect(stackItemCapabilities({})).toEqual([]);
});
it('is read off the spec provider row — one row today, the knowledge one', () => {
const rows = Object.entries(PLATFORM_CAPABILITY_PROVIDERS).filter(([, row]) => row.mountedBy !== undefined);
expect(rows).toEqual([['knowledge', expect.objectContaining({ mountedBy: { collection: 'knowledgeSources' } })]]);
});
it('an item token is declared (required), mounted after the declared ones, and reported as the items\' own', () => {
const served = resolveServedCapabilities(['automation'], { itemTokens: ['knowledge'] });
expect(served.tokens.slice(0, 2)).toEqual(['automation', 'knowledge']);
expect(served.declared.has('knowledge')).toBe(true);
expect([...served.byItems]).toEqual(['knowledge']);
// Listed under `requires` as well: the requirement is the author's, not the items'.
const both = resolveServedCapabilities(['knowledge'], { itemTokens: ['knowledge'] });
expect(both.tokens.filter((token) => token === 'knowledge')).toEqual(['knowledge']);
expect([...both.byItems]).toEqual([]);
});
it("the knowledge service is constructed with the deployment's store: the adapter id of the store the extras mount", () => {
const pg = { stack: {}, packageRoot: '/app', database: { driver: 'postgres', url: 'postgres://db/app' } };
const file = { stack: {}, packageRoot: '/app', database: { driver: 'sqlite', url: 'file:/app/.objectstack/data/objectstack.db' } };
for (const input of [pg, file]) {
const { argument } = resolveCapabilityArgument('knowledge', input);
const [store] = resolveCapabilityExtras('knowledge', input);
expect(argument).toEqual({
deploymentAdapter: resolveKnowledgeStore(input).store.adapterId,
runtimeComposed: { declared: false },
});
expect(store?.pkg).toBe(resolveKnowledgeStore(input).store.pkg);
}
expect(resolveCapabilityArgument('knowledge', pg).argument).toEqual({
deploymentAdapter: 'pgvector',
runtimeComposed: { declared: false },
});
expect(resolveCapabilityArgument('knowledge', file).argument).toEqual({
deploymentAdapter: 'turso',
runtimeComposed: { declared: false },
});
});
it('[ADR-0161 K8, note on item 12] marks the service runtime-composed, declared only when the stack lists the token', () => {
const database = { driver: 'sqlite', url: 'file:/app/.objectstack/data/objectstack.db' };
const argumentOf = (stack: unknown) =>
resolveCapabilityArgument('knowledge', { stack, packageRoot: '/app', database }).argument as {
runtimeComposed: { declared: boolean };
};
// A shipped `knowledge_source` mounts the service (an item token), and is no request for it.
expect(argumentOf({ knowledgeSources: [{ name: 'faq' }] }).runtimeComposed).toEqual({ declared: false });
expect(argumentOf({ requires: ['knowledge'] }).runtimeComposed).toEqual({ declared: true });
});
});