-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdatasource-admin-service.ts
More file actions
327 lines (295 loc) · 12.5 KB
/
Copy pathdatasource-admin-service.ts
File metadata and controls
327 lines (295 loc) · 12.5 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* DatasourceAdminService — implements {@link IDatasourceAdminService}
* (ADR-0015 Addendum) on top of injected persistence + secret + driver probe
* callbacks.
*
* Like its federation sibling `ExternalDatasourceService`, this service is
* intentionally decoupled from the kernel: every side effect (connection probe,
* metadata read/write, secret write, bound-object count, hot pool (de)register)
* is injected via {@link DatasourceAdminServiceConfig}, so the lifecycle rules
* (origin gating, secret indirection, removal safety) are pure and unit-testable.
*
* Invariants enforced here, independent of the wiring:
* - Code-defined datasources (`origin: 'code'`) are read-only — update/remove
* reject them, and create refuses a name a code datasource already owns.
* - A runtime datasource never shadows a code one (code wins on collision).
* - Credentials never persist in cleartext: the cleartext {@link SecretInput}
* transits create/update/test only; create/update write it to the secret
* store and persist only the returned `credentialsRef`.
* - Removal is refused while objects are still bound to the datasource.
*/
import type {
IDatasourceAdminService,
DatasourceDraft,
SecretInput,
TestConnectionResult,
DatasourceSummary,
} from './contracts/index.js';
import type { Logger } from './logger.js';
/** Datasource name rule (mirrors `DatasourceSchema.name`). */
const NAME_RE = /^[a-z_][a-z0-9_]*$/;
/**
* A persisted datasource record (subset of `Datasource`). `origin` distinguishes
* code-defined from runtime; `external.credentialsRef` is the opaque secret
* handle — never a cleartext credential.
*/
export interface StoredDatasource {
name: string;
label?: string;
driver: string;
schemaMode?: 'managed' | 'external' | 'validate-only';
config?: Record<string, unknown>;
external?: (Record<string, unknown> & { credentialsRef?: string }) | undefined;
pool?: Record<string, unknown>;
active?: boolean;
origin?: 'code' | 'runtime';
/** Package that defines a code-origin datasource, when known. */
definedIn?: string;
}
/** What a connection probe needs (cleartext secret is transient, never stored). */
export interface ProbeInput {
driver: string;
config: Record<string, unknown>;
/** Cleartext secret used for this probe only (e.g. password / DSN). */
secret?: string;
external?: Record<string, unknown>;
timeoutMs?: number;
}
/**
* Injected dependencies. The plugin supplies real implementations backed by the
* driver registry, `IMetadataService` (runtime store), and the secret store;
* tests supply fakes.
*/
export interface DatasourceAdminServiceConfig {
/** Probe a connection live (driver connect + cheap round-trip). */
probe: (input: ProbeInput) => Promise<TestConnectionResult>;
/** Read every datasource record (code + runtime). */
listDatasourceRecords: () => Promise<StoredDatasource[]>;
/** Read one datasource record by name. */
getDatasourceRecord: (name: string) => Promise<StoredDatasource | undefined>;
/** Persist a runtime datasource record into the runtime metadata store. */
putDatasourceRecord: (record: StoredDatasource) => Promise<void>;
/** Remove a runtime datasource record from the runtime metadata store. */
deleteDatasourceRecord: (name: string) => Promise<void>;
/** Encrypt + store a secret, returning an opaque `credentialsRef`. */
writeSecret: (input: SecretInput, hint: { name: string }) => Promise<string>;
/** Best-effort delete of a stored secret by ref (cleanup on remove/rewrap). */
removeSecret?: (credentialsRef: string) => Promise<void>;
/** Count objects bound to a datasource (removal blocked while > 0). */
countBoundObjects: (datasource: string) => Promise<number>;
/** Hot-(re)register a runtime datasource's connection pool after write. */
registerPool?: (record: StoredDatasource) => Promise<void> | void;
/** Tear down a runtime datasource's pool on remove. */
unregisterPool?: (name: string) => Promise<void> | void;
logger?: Logger;
}
export class DatasourceAdminService implements IDatasourceAdminService {
constructor(private readonly config: DatasourceAdminServiceConfig) {}
private get logger(): Logger | undefined {
return this.config.logger;
}
async listDatasources(): Promise<DatasourceSummary[]> {
const records = await this.config.listDatasourceRecords();
// Group by name; code wins on collision, and a shadowed runtime row marks
// the effective (code) entry as conflicting.
const byName = new Map<string, { code?: StoredDatasource; runtime?: StoredDatasource }>();
for (const rec of records) {
const slot = byName.get(rec.name) ?? {};
if (rec.origin === 'runtime') slot.runtime = rec;
else slot.code = rec;
byName.set(rec.name, slot);
}
const summaries: DatasourceSummary[] = [];
for (const [name, slot] of byName) {
const effective = slot.code ?? slot.runtime;
if (!effective) continue;
summaries.push({
name,
label: effective.label,
driver: effective.driver,
schemaMode: effective.schemaMode ?? 'managed',
origin: slot.code ? 'code' : 'runtime',
active: effective.active ?? true,
status: 'unvalidated',
...(slot.code?.definedIn ? { definedIn: slot.code.definedIn } : {}),
...(slot.code && slot.runtime ? { conflictsWithCode: true } : {}),
});
}
return summaries;
}
/**
* Read one datasource's full detail for editing, with the credential stripped.
* Returns `config` (non-sensitive — credentials live in `sys_secret`, never in
* config), `origin`, and a `hasSecret` flag so the UI can show "leave blank to
* keep" without ever receiving the `credentialsRef` or any cleartext. Returns
* `undefined` when the name is unknown.
*/
async getDatasource(name: string): Promise<
| (Pick<StoredDatasource, 'name' | 'label' | 'driver' | 'schemaMode' | 'config' | 'active' | 'definedIn'> & {
origin: 'code' | 'runtime';
hasSecret: boolean;
})
| undefined
> {
const rec = await this.config.getDatasourceRecord(name);
if (!rec) return undefined;
const hasSecret = Boolean(rec.external?.credentialsRef);
return {
name: rec.name,
label: rec.label,
driver: rec.driver,
schemaMode: rec.schemaMode ?? 'managed',
config: rec.config ?? {},
active: rec.active ?? true,
origin: rec.origin === 'runtime' ? 'runtime' : 'code',
hasSecret,
...(rec.definedIn ? { definedIn: rec.definedIn } : {}),
};
}
async testConnection(input: DatasourceDraft, secret?: SecretInput): Promise<TestConnectionResult> {
if (!input?.driver) {
return { ok: false, error: 'A driver is required to test a connection.' };
}
const queryTimeoutMs = (input.external as { queryTimeoutMs?: number } | undefined)?.queryTimeoutMs;
try {
return await this.config.probe({
driver: input.driver,
config: input.config ?? {},
secret: secret?.value,
external: input.external,
...(typeof queryTimeoutMs === 'number' ? { timeoutMs: queryTimeoutMs } : {}),
});
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
async createDatasource(input: DatasourceDraft, secret?: SecretInput): Promise<DatasourceSummary> {
this.assertValidName(input?.name);
if (!input.driver) throw new Error('A driver is required to create a datasource.');
const existing = await this.config.getDatasourceRecord(input.name);
if (existing) {
if (existing.origin === 'code' || existing.origin === undefined) {
throw new Error(
`Cannot create datasource '${input.name}': a code-defined datasource owns this name (read-only).`,
);
}
throw new Error(`Datasource '${input.name}' already exists.`);
}
const record: StoredDatasource = {
...this.toRecord(input),
origin: 'runtime',
};
if (secret) {
const credentialsRef = await this.config.writeSecret(secret, { name: input.name });
record.external = { ...(record.external ?? {}), credentialsRef };
}
await this.config.putDatasourceRecord(record);
await this.tryRegisterPool(record);
return this.toSummary(record);
}
async updateDatasource(
name: string,
patch: Partial<DatasourceDraft>,
secret?: SecretInput,
): Promise<DatasourceSummary> {
const existing = await this.config.getDatasourceRecord(name);
if (!existing) throw new Error(`Datasource '${name}' not found.`);
if (existing.origin !== 'runtime') {
throw new Error(`Datasource '${name}' is code-defined and cannot be edited at runtime.`);
}
// Merge patch over the existing record; `name`/`origin` are never patched.
const merged: StoredDatasource = {
...existing,
...(patch.label !== undefined ? { label: patch.label } : {}),
...(patch.driver !== undefined ? { driver: patch.driver } : {}),
...(patch.schemaMode !== undefined ? { schemaMode: patch.schemaMode } : {}),
...(patch.config !== undefined ? { config: patch.config } : {}),
...(patch.pool !== undefined ? { pool: patch.pool } : {}),
...(patch.active !== undefined ? { active: patch.active } : {}),
name: existing.name,
origin: 'runtime',
};
if (patch.external !== undefined) {
// Preserve the existing credentialsRef unless a new secret rewraps it.
merged.external = { ...patch.external, credentialsRef: existing.external?.credentialsRef };
}
if (secret) {
const prevRef = existing.external?.credentialsRef;
const credentialsRef = await this.config.writeSecret(secret, { name });
merged.external = { ...(merged.external ?? {}), credentialsRef };
if (prevRef && prevRef !== credentialsRef) await this.tryRemoveSecret(prevRef);
}
await this.config.putDatasourceRecord(merged);
await this.tryRegisterPool(merged);
return this.toSummary(merged);
}
async removeDatasource(name: string): Promise<void> {
const existing = await this.config.getDatasourceRecord(name);
if (!existing) throw new Error(`Datasource '${name}' not found.`);
if (existing.origin !== 'runtime') {
throw new Error(`Datasource '${name}' is code-defined and cannot be removed at runtime.`);
}
const bound = await this.config.countBoundObjects(name);
if (bound > 0) {
throw new Error(
`Cannot remove datasource '${name}': ${bound} object(s) are still bound to it.`,
);
}
await this.config.deleteDatasourceRecord(name);
if (existing.external?.credentialsRef) await this.tryRemoveSecret(existing.external.credentialsRef);
await this.tryUnregisterPool(name);
}
// --- internals -----------------------------------------------------------
private assertValidName(name: string | undefined): void {
if (!name || !NAME_RE.test(name)) {
throw new Error(
`Invalid datasource name '${name ?? ''}': must match /^[a-z_][a-z0-9_]*$/.`,
);
}
}
private toRecord(input: DatasourceDraft): StoredDatasource {
return {
name: input.name,
...(input.label !== undefined ? { label: input.label } : {}),
driver: input.driver,
...(input.schemaMode !== undefined ? { schemaMode: input.schemaMode } : {}),
...(input.config !== undefined ? { config: input.config } : {}),
...(input.external !== undefined ? { external: input.external } : {}),
...(input.pool !== undefined ? { pool: input.pool } : {}),
...(input.active !== undefined ? { active: input.active } : {}),
};
}
private toSummary(record: StoredDatasource): DatasourceSummary {
return {
name: record.name,
label: record.label,
driver: record.driver,
schemaMode: record.schemaMode ?? 'managed',
origin: record.origin ?? 'runtime',
active: record.active ?? true,
status: 'unvalidated',
};
}
private async tryRegisterPool(record: StoredDatasource): Promise<void> {
try {
await this.config.registerPool?.(record);
} catch (err) {
this.logger?.warn(`registerPool('${record.name}') failed`, err);
}
}
private async tryUnregisterPool(name: string): Promise<void> {
try {
await this.config.unregisterPool?.(name);
} catch (err) {
this.logger?.warn(`unregisterPool('${name}') failed`, err);
}
}
private async tryRemoveSecret(credentialsRef: string): Promise<void> {
try {
await this.config.removeSecret?.(credentialsRef);
} catch (err) {
this.logger?.warn(`removeSecret('${credentialsRef}') failed`, err);
}
}
}