-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdatasource-admin-plugin.test.ts
More file actions
290 lines (263 loc) · 11.6 KB
/
Copy pathdatasource-admin-plugin.test.ts
File metadata and controls
290 lines (263 loc) · 11.6 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect } from 'vitest';
import type { IDatasourceAdminService, IDatasourceDriverFactory } from '../contracts/index.js';
import {
DatasourceAdminServicePlugin,
type DatasourceAdminServicePluginOptions,
} from '../datasource-admin-plugin.js';
/**
* Minimal PluginContext + in-memory metadata service. Boots the plugin and
* returns the registered `datasource-admin` service so we can exercise the
* plugin's glue (probe via factory, fail-closed secret) end to end.
*/
async function boot(opts: DatasourceAdminServicePluginOptions & {
services?: Record<string, unknown>;
} = {}) {
const registry = new Map<string, Map<string, unknown>>();
const metadata = {
get: async (t: string, n: string) => registry.get(t)?.get(n),
list: async (t: string) => [...(registry.get(t)?.values() ?? [])],
register: async (t: string, n: string, d: unknown) => {
if (!registry.has(t)) registry.set(t, new Map());
registry.get(t)!.set(n, d);
},
unregister: async (t: string, n: string) => {
registry.get(t)?.delete(n);
},
listObjects: async () => [...(registry.get('object')?.values() ?? [])],
};
const services: Record<string, unknown> = { metadata, ...(opts.services ?? {}) };
let registered: IDatasourceAdminService | undefined;
const ctx: any = {
getService: (name: string) => {
if (name in services) return services[name];
throw new Error(`no service ${name}`);
},
registerService: (name: string, svc: unknown) => {
if (name === 'datasource-admin') registered = svc as IDatasourceAdminService;
},
trigger: async () => {},
logger: { warn() {}, info() {} },
};
const { services: _omit, ...pluginOpts } = opts;
const plugin = new DatasourceAdminServicePlugin(pluginOpts);
await plugin.init(ctx);
return { service: registered!, registry, metadata, plugin, ctx };
}
/** A driver factory whose handle records connect/ping/disconnect calls. */
function fakeFactory(over?: Partial<IDatasourceDriverFactory> & { onProbe?: () => void }): IDatasourceDriverFactory {
return {
supports: (id: string) => id === 'postgres',
create: async (spec) => ({
connect: async () => {},
ping: async () => {
over?.onProbe?.();
// expose the secret the factory received for assertions
(globalThis as any).__lastProbeSecret = spec.secret;
},
disconnect: async () => {},
serverVersion: async () => 'PostgreSQL 16.1',
}),
...over,
};
}
describe('DatasourceAdminServicePlugin: probe', () => {
it('tests a connection through the driver factory (latency + version)', async () => {
const { service } = await boot({
driverFactory: fakeFactory(),
});
const res = await service.testConnection(
{ name: 'reporting', driver: 'postgres', config: { host: 'db' } },
{ value: 's3cret' },
);
expect(res.ok).toBe(true);
expect(res.serverVersion).toBe('PostgreSQL 16.1');
expect(typeof res.latencyMs).toBe('number');
expect((globalThis as any).__lastProbeSecret).toBe('s3cret');
});
it('returns ok:false when no factory supports the driver', async () => {
const { service } = await boot({ driverFactory: fakeFactory() });
const res = await service.testConnection({ name: 'x', driver: 'oracle', config: {} });
expect(res.ok).toBe(false);
expect(res.error).toMatch(/no driver factory supports/i);
});
it('returns ok:false when no factory is registered at all', async () => {
const { service } = await boot();
const res = await service.testConnection({ name: 'x', driver: 'postgres', config: {} });
expect(res.ok).toBe(false);
expect(res.error).toMatch(/no driver factory is registered/i);
});
});
describe('DatasourceAdminServicePlugin: secret fail-closed', () => {
it('refuses to create a secret-bearing datasource without a secret binder', async () => {
const { service, registry } = await boot({ driverFactory: fakeFactory() });
await expect(
service.createDatasource({ name: 'reporting', driver: 'postgres', config: {} }, { value: 'pw' }),
).rejects.toThrow(/no secret store configured/i);
// nothing persisted
expect(registry.get('datasource')?.size ?? 0).toBe(0);
});
it('persists a credentialsRef (not cleartext) when a binder is wired', async () => {
const bound: string[] = [];
const { service, registry } = await boot({
driverFactory: fakeFactory(),
secrets: {
bind: async (input, hint) => {
bound.push(input.value);
return `sys_secret://datasource/${hint.name}#1`;
},
},
});
await service.createDatasource({ name: 'reporting', driver: 'postgres', config: {} }, { value: 'pw' });
const rec = registry.get('datasource')?.get('reporting') as any;
expect(rec.origin).toBe('runtime');
expect(rec.external?.credentialsRef).toBe('sys_secret://datasource/reporting#1');
expect(JSON.stringify(rec)).not.toContain('pw');
expect(bound).toEqual(['pw']);
});
});
describe('DatasourceAdminServicePlugin: boot rehydration', () => {
/** Fake engine ('data') that records hot-registered drivers. */
function fakeEngine() {
const drivers: any[] = [];
return {
drivers,
registerDriver: (d: any) => drivers.push(d),
registerDatasourceDef: () => {},
getDriverByName: (n: string) => drivers.find((d) => d.name === n),
};
}
/** Factory that records the spec (incl. resolved secret) of each create(). */
function recordingFactory() {
const specs: any[] = [];
const factory: IDatasourceDriverFactory = {
supports: (id: string) => id === 'postgres',
create: async (spec) => {
specs.push(spec);
return { connect: async () => {}, disconnect: async () => {} };
},
};
return { factory, specs };
}
it('rebuilds runtime pools at start(), decrypting the credentialsRef', async () => {
const engine = fakeEngine();
const { factory, specs } = recordingFactory();
const resolved: string[] = [];
const { plugin, ctx, registry } = await boot({
driverFactory: factory,
services: { data: engine },
secrets: {
bind: async () => 'sys_secret:abc',
resolve: async (ref) => {
resolved.push(ref);
return ref === 'sys_secret:abc' ? 'super-secret-pw' : undefined;
},
},
});
// Simulate a persisted (DB-backed) runtime datasource that survived a restart.
registry.set(
'datasource',
new Map<string, unknown>([
['crm_primary', { name: 'crm_primary', driver: 'sqlite', origin: 'code' }],
[
'reporting',
{
name: 'reporting',
driver: 'postgres',
origin: 'runtime',
active: true,
config: { host: 'db' },
external: { credentialsRef: 'sys_secret:abc' },
},
],
[
'archived',
{ name: 'archived', driver: 'postgres', origin: 'runtime', active: false },
],
]),
);
await plugin.start(ctx);
// Only the active runtime datasource is rehydrated — not the code one, not the inactive one.
expect(engine.drivers.map((d) => d.name)).toEqual(['reporting']);
// The credentialsRef was dereferenced and the cleartext handed to the factory.
expect(resolved).toEqual(['sys_secret:abc']);
expect(specs).toHaveLength(1);
expect(specs[0].secret).toBe('super-secret-pw');
expect(specs[0].name).toBe('reporting');
});
it('does not block boot when nothing is persisted (dev: in-memory store)', async () => {
const engine = fakeEngine();
const { factory } = recordingFactory();
const { plugin, ctx } = await boot({ driverFactory: factory, services: { data: engine } });
await expect(plugin.start(ctx)).resolves.toBeUndefined();
expect(engine.drivers).toHaveLength(0);
});
});
describe('DatasourceAdminServicePlugin: persistence + bound count', () => {
it('lists code (artefact) + runtime records with origin, blocks remove while bound', async () => {
const { service, registry } = await boot({ driverFactory: fakeFactory() });
// seed an artefact (code) datasource lacking explicit origin
registry.set('datasource', new Map([['crm_primary', { name: 'crm_primary', driver: 'sqlite' }]]));
// seed an object bound to a runtime datasource
registry.set('object', new Map([['lead', { name: 'lead', datasource: 'reporting' }]]));
await service.createDatasource({ name: 'reporting', driver: 'postgres', config: {} });
const list = await service.listDatasources();
expect(list.find((d) => d.name === 'crm_primary')?.origin).toBe('code');
expect(list.find((d) => d.name === 'reporting')?.origin).toBe('runtime');
await expect(service.removeDatasource('reporting')).rejects.toThrow(/1 object\(s\)/);
});
});
describe('DatasourceAdminServicePlugin: runtime datasource durability', () => {
/** In-memory `sys_metadata` engine shared across two boots (a "restart"). */
function fakeSysMetadataEngine() {
const rows: Array<Record<string, unknown>> = [];
return {
rows,
registerDriver() {},
registerDatasourceDef() {},
getDriverByName() { return undefined; },
findOne: async (_o: string, q: { where?: Record<string, unknown> }) => {
const w = q.where ?? {};
return rows.find((r) => Object.entries(w).every(([k, v]) => r[k] === v));
},
find: async (_o: string, q: { where?: Record<string, unknown> }) => {
const w = q.where ?? {};
return rows.filter((r) => Object.entries(w).every(([k, v]) => r[k] === v));
},
insert: async (_o: string, row: Record<string, unknown>) => { rows.push({ ...row }); },
update: async (_o: string, row: Record<string, unknown>, opts: { where: Record<string, unknown> }) => {
const i = rows.findIndex((r) => r.id === opts.where.id);
if (i >= 0) rows[i] = { ...rows[i], ...row };
},
delete: async (_o: string, opts: { where: Record<string, unknown> }) => {
const i = rows.findIndex((r) => r.id === opts.where.id);
if (i >= 0) rows.splice(i, 1);
},
};
}
it('persists a UI-created datasource to sys_metadata and restores it after a restart', async () => {
const data = fakeSysMetadataEngine();
// Boot #1: create a runtime sqlite datasource (no secret needed).
const b1 = await boot({ services: { data } });
await b1.service.createDatasource({ name: 'demo_ext', driver: 'sqlite', config: { filename: '/tmp/x.db' } });
// It is durably written to sys_metadata (not just the in-memory registry).
expect(data.rows.filter((r) => r.type === 'datasource' && r.name === 'demo_ext')).toHaveLength(1);
// Boot #2 = "restart": fresh in-memory registry, SAME sys_metadata engine.
const b2 = await boot({ services: { data } });
// Before restore, the fresh registry is empty.
expect(await b2.service.listDatasources()).toHaveLength(0);
// start() restores runtime rows from sys_metadata into the registry.
await b2.plugin.start(b2.ctx);
const after = await b2.service.listDatasources();
expect(after.map((d) => d.name)).toContain('demo_ext');
expect(after.find((d) => d.name === 'demo_ext')?.origin).toBe('runtime');
});
it('removes the durable sys_metadata row when a datasource is deleted', async () => {
const data = fakeSysMetadataEngine();
const b = await boot({ services: { data } });
await b.service.createDatasource({ name: 'gone', driver: 'sqlite', config: { filename: '/tmp/y.db' } });
expect(data.rows.some((r) => r.name === 'gone')).toBe(true);
await b.service.removeDatasource('gone');
expect(data.rows.some((r) => r.name === 'gone')).toBe(false);
});
});