-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathclient.ts
More file actions
768 lines (686 loc) · 24 KB
/
Copy pathclient.ts
File metadata and controls
768 lines (686 loc) · 24 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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
import type {
Contract,
ContractMarkerRecord,
LedgerEntryRecord,
} from '@prisma-next/contract/types';
import { emit as emitContractArtifacts } from '@prisma-next/emitter';
import type { AuthoringPslBlockDescriptorNamespace } from '@prisma-next/framework-components/authoring';
import type { TargetBoundComponentDescriptor } from '@prisma-next/framework-components/components';
import type {
ControlAdapterInstance,
ControlDriverInstance,
ControlFamilyInstance,
ControlStack,
CoreSchemaView,
MigrationPlanOperation,
OperationPreview,
SignDatabaseResult,
VerifyDatabaseResult,
VerifyDatabaseSchemaResult,
} from '@prisma-next/framework-components/control';
import {
APP_SPACE_ID,
createControlStack,
hasMigrations,
hasOperationPreview,
hasPslContractInfer,
hasSchemaView,
} from '@prisma-next/framework-components/control';
import type { PslDocumentAst } from '@prisma-next/framework-components/psl-ast';
import { blindCast } from '@prisma-next/utils/casts';
import { ifDefined } from '@prisma-next/utils/defined';
import { notOk, ok } from '@prisma-next/utils/result';
import { toExtensionInputs } from '../utils/extension-pack-inputs';
import { assertFrameworkComponentsCompatible } from '../utils/framework-components';
import { enrichContract } from './contract-enrichment';
import { ContractValidationError } from './errors';
import { executeDbInit } from './operations/db-init';
import { executeDbUpdate } from './operations/db-update';
import { type ExecuteDbVerifyResult, executeDbVerify } from './operations/db-verify';
import { executeMigrate } from './operations/migrate';
import type {
ControlActionName,
ControlClient,
ControlClientOptions,
DbInitOptions,
DbInitResult,
DbUpdateOptions,
DbUpdateResult,
DbVerifyOptions,
EmitOptions,
EmitResult,
IntrospectOptions,
MigrateOptions,
MigrateResult,
OnControlProgress,
SchemaVerifyOptions,
SignOptions,
VerifyOptions,
} from './types';
/**
* Creates a programmatic control client for Prisma Next operations.
*
* The client accepts framework component descriptors at creation time,
* manages driver lifecycle via connect()/close(), and exposes domain
* operations that delegate to the existing family instance methods.
*
* @see {@link ControlClient} for the client interface
* @see README.md "Programmatic Control API" section for usage examples
*/
export function createControlClient(options: ControlClientOptions): ControlClient {
return new ControlClientImpl(options);
}
/**
* Implementation of ControlClient.
* Manages initialization and connection state, delegates operations to family instance.
*/
class ControlClientImpl implements ControlClient {
private readonly options: ControlClientOptions;
private stack: ControlStack | null = null;
private driver: ControlDriverInstance<string, string> | null = null;
private familyInstance: ControlFamilyInstance<string, unknown> | null = null;
private frameworkComponents: ReadonlyArray<
TargetBoundComponentDescriptor<string, string>
> | null = null;
private initialized = false;
private readonly defaultConnection: unknown;
constructor(options: ControlClientOptions) {
this.options = options;
this.defaultConnection = options.connection;
}
init(): void {
if (this.initialized) {
return; // Idempotent
}
this.stack = createControlStack({
family: this.options.family,
target: this.options.target,
adapter: this.options.adapter,
driver: this.options.driver,
extensionPacks: this.options.extensionPacks,
});
this.familyInstance = this.options.family.create(this.stack);
// Validate and type-narrow framework components
const rawComponents = [
this.options.target,
this.options.adapter,
...(this.options.extensionPacks ?? []),
];
this.frameworkComponents = assertFrameworkComponentsCompatible(
this.options.family.familyId,
this.options.target.targetId,
rawComponents,
);
this.initialized = true;
}
async connect(connection?: unknown): Promise<void> {
// Auto-init if needed
this.init();
if (this.driver) {
throw new Error('Already connected. Call close() before reconnecting.');
}
// Resolve connection: argument > default from options
const resolvedConnection = connection ?? this.defaultConnection;
if (resolvedConnection === undefined) {
throw new Error(
'No connection provided. Pass a connection to connect() or provide a default connection when creating the client.',
);
}
// Check for driver descriptor
if (!this.stack?.driver) {
throw new Error(
'Driver is not configured. Pass a driver descriptor when creating the control client to enable database operations.',
);
}
// biome-ignore lint/suspicious/noExplicitAny: required for runtime connection type flexibility
this.driver = await this.stack.driver.create(resolvedConnection as any);
}
async close(): Promise<void> {
if (this.driver) {
await this.driver.close();
this.driver = null;
}
}
/**
* Construct the control adapter once for a migration operation and return
* it, mirroring how the runtime plane builds the execution adapter once in
* `createExecutionStack`. Only `dbInit` / `dbUpdate` need it (it lowers the
* planner's DDL); read-only operations never build it. The descriptor is
* optional on the stack — targets without migrations omit it.
*/
private buildControlAdapter(): ControlAdapterInstance<string, string> {
this.init();
if (!this.stack?.adapter) {
throw new Error(
`Target "${this.options.target.targetId}" requires an adapter for migrations`,
);
}
return this.stack.adapter.create(this.stack);
}
private async ensureConnected(): Promise<{
driver: ControlDriverInstance<string, string>;
familyInstance: ControlFamilyInstance<string, unknown>;
frameworkComponents: ReadonlyArray<TargetBoundComponentDescriptor<string, string>>;
}> {
// Auto-init if needed
this.init();
// Auto-connect if not connected and default connection is available
if (!this.driver && this.defaultConnection !== undefined) {
await this.connect(this.defaultConnection);
}
if (!this.driver || !this.familyInstance || !this.frameworkComponents) {
throw new Error('Not connected. Call connect(connection) first.');
}
return {
driver: this.driver,
familyInstance: this.familyInstance,
frameworkComponents: this.frameworkComponents,
};
}
private async connectWithProgress(
connection: unknown | undefined,
action: ControlActionName,
onProgress?: OnControlProgress,
): Promise<void> {
if (connection === undefined) return;
onProgress?.({
action,
kind: 'spanStart',
spanId: 'connect',
label: 'Connecting to database...',
});
try {
await this.connect(connection);
onProgress?.({ action, kind: 'spanEnd', spanId: 'connect', outcome: 'ok' });
} catch (error) {
onProgress?.({ action, kind: 'spanEnd', spanId: 'connect', outcome: 'error' });
throw error;
}
}
async verify(options: VerifyOptions): Promise<VerifyDatabaseResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'verify', onProgress);
const { driver, familyInstance } = await this.ensureConnected();
// Validate contract using family instance
let contract: Contract;
try {
contract = familyInstance.deserializeContract(options.contract);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ContractValidationError(message, error);
}
// Emit verify span
onProgress?.({
action: 'verify',
kind: 'spanStart',
spanId: 'verify',
label: 'Verifying database marker...',
});
try {
// Delegate to family instance verify method
// Note: We pass empty strings for contractPath/configPath since the programmatic
// API doesn't deal with file paths. The family instance accepts these as optional
// metadata for error reporting.
const result = await familyInstance.verify({
driver,
contract,
expectedTargetId: this.options.target.targetId,
contractPath: '',
});
onProgress?.({
action: 'verify',
kind: 'spanEnd',
spanId: 'verify',
outcome: result.ok ? 'ok' : 'error',
});
return result;
} catch (error) {
onProgress?.({
action: 'verify',
kind: 'spanEnd',
spanId: 'verify',
outcome: 'error',
});
throw error;
}
}
async schemaVerify(options: SchemaVerifyOptions): Promise<VerifyDatabaseSchemaResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'schemaVerify', onProgress);
const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
// Validate contract using family instance
let contract: Contract;
try {
contract = familyInstance.deserializeContract(options.contract);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ContractValidationError(message, error);
}
// Emit schemaVerify span
onProgress?.({
action: 'schemaVerify',
kind: 'spanStart',
spanId: 'schemaVerify',
label: 'Verifying database schema...',
});
try {
// Introspect the live schema, then verify the contract against
// it. Composing the two primitives here keeps the family
// interface a single synchronous verifier and gives callers
// (and tests) explicit control over the introspected schema.
const schema = await familyInstance.introspect({ driver, contract });
const result = familyInstance.verifySchema({
contract,
schema,
strict: options.strict ?? false,
frameworkComponents,
});
onProgress?.({
action: 'schemaVerify',
kind: 'spanEnd',
spanId: 'schemaVerify',
outcome: result.ok ? 'ok' : 'error',
});
return result;
} catch (error) {
onProgress?.({
action: 'schemaVerify',
kind: 'spanEnd',
spanId: 'schemaVerify',
outcome: 'error',
});
throw error;
}
}
async sign(options: SignOptions): Promise<SignDatabaseResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'sign', onProgress);
const { driver, familyInstance } = await this.ensureConnected();
// Validate contract using family instance
let contract: Contract;
try {
contract = familyInstance.deserializeContract(options.contract);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ContractValidationError(message, error);
}
// Emit sign span
onProgress?.({
action: 'sign',
kind: 'spanStart',
spanId: 'sign',
label: 'Signing database...',
});
try {
// Delegate to family instance sign method
const result = await familyInstance.sign({
driver,
contract,
contractPath: options.contractPath ?? '',
...ifDefined('configPath', options.configPath),
});
onProgress?.({
action: 'sign',
kind: 'spanEnd',
spanId: 'sign',
outcome: 'ok',
});
return result;
} catch (error) {
onProgress?.({
action: 'sign',
kind: 'spanEnd',
spanId: 'sign',
outcome: 'error',
});
throw error;
}
}
async dbInit(options: DbInitOptions): Promise<DbInitResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'dbInit', onProgress);
const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
if (!hasMigrations(this.options.target)) {
throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
}
const adapter = this.buildControlAdapter();
let contract: Contract;
try {
contract = familyInstance.deserializeContract(options.contract);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ContractValidationError(message, error);
}
return executeDbInit({
driver,
adapter,
familyInstance,
contract,
mode: options.mode,
migrations: this.options.target.migrations,
frameworkComponents,
migrationsDir: options.migrationsDir,
targetId: this.options.target.targetId,
extensionPacks: this.options.extensionPacks ?? [],
...ifDefined('onProgress', onProgress),
});
}
async dbUpdate(options: DbUpdateOptions): Promise<DbUpdateResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'dbUpdate', onProgress);
const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
if (!hasMigrations(this.options.target)) {
throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
}
const adapter = this.buildControlAdapter();
let contract: Contract;
try {
contract = familyInstance.deserializeContract(options.contract);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ContractValidationError(message, error);
}
return executeDbUpdate({
driver,
adapter,
familyInstance,
contract,
mode: options.mode,
migrations: this.options.target.migrations,
frameworkComponents,
migrationsDir: options.migrationsDir,
targetId: this.options.target.targetId,
extensionPacks: this.options.extensionPacks ?? [],
...ifDefined('acceptDataLoss', options.acceptDataLoss),
...ifDefined('onProgress', onProgress),
});
}
async dbVerify(options: DbVerifyOptions): Promise<ExecuteDbVerifyResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'dbVerify', onProgress);
const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
return executeDbVerify({
driver,
familyInstance,
contract: options.contract,
migrationsDir: options.migrationsDir,
targetId: this.options.target.targetId,
extensionPacks: this.options.extensionPacks ?? [],
frameworkComponents,
mode: options.strict ? 'strict' : 'lenient',
skipSchema: options.skipSchema,
skipMarker: options.skipMarker,
...ifDefined('onProgress', onProgress),
});
}
async readMarker(): Promise<ContractMarkerRecord | null> {
const { driver, familyInstance } = await this.ensureConnected();
// The CLI client's readMarker reads the app's marker. Per-extension
// readers go through the orchestrator's per-space planner / runner
// boundary, which threads the extension's space id through the
// family interface explicitly.
return familyInstance.readMarker({ driver, space: APP_SPACE_ID });
}
async readAllMarkers(): Promise<ReadonlyMap<string, ContractMarkerRecord>> {
const { driver, familyInstance } = await this.ensureConnected();
return familyInstance.readAllMarkers({ driver });
}
/** Reads the per-migration journal; omit `space` to return every space. */
async readLedger(space?: string): Promise<readonly LedgerEntryRecord[]> {
const { driver, familyInstance } = await this.ensureConnected();
return familyInstance.readLedger({ driver, ...ifDefined('space', space) });
}
async migrate(options: MigrateOptions): Promise<MigrateResult> {
const { onProgress } = options;
await this.connectWithProgress(options.connection, 'migrate', onProgress);
const { driver, familyInstance, frameworkComponents } = await this.ensureConnected();
if (!hasMigrations(this.options.target)) {
throw new Error(`Target "${this.options.target.targetId}" does not support migrations`);
}
let contract: Contract;
try {
contract = familyInstance.deserializeContract(options.contract);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new ContractValidationError(message, error);
}
return executeMigrate({
driver,
familyInstance,
contract,
migrations: this.options.target.migrations,
frameworkComponents,
migrationsDir: options.migrationsDir,
extensionPacks: this.options.extensionPacks ?? [],
targetId: this.options.target.targetId,
...ifDefined('refHash', options.refHash),
...ifDefined('refInvariants', options.refInvariants),
...ifDefined('refName', options.refName),
...ifDefined('onProgress', onProgress),
});
}
async introspect(options?: IntrospectOptions): Promise<unknown> {
const onProgress = options?.onProgress;
await this.connectWithProgress(options?.connection, 'introspect', onProgress);
const { driver, familyInstance } = await this.ensureConnected();
// TODO: Pass schema option to familyInstance.introspect when schema filtering is implemented
const _schema = options?.schema;
void _schema;
// Emit introspect span
onProgress?.({
action: 'introspect',
kind: 'spanStart',
spanId: 'introspect',
label: 'Introspecting database schema...',
});
try {
const result = await familyInstance.introspect({ driver });
onProgress?.({
action: 'introspect',
kind: 'spanEnd',
spanId: 'introspect',
outcome: 'ok',
});
return result;
} catch (error) {
onProgress?.({
action: 'introspect',
kind: 'spanEnd',
spanId: 'introspect',
outcome: 'error',
});
throw error;
}
}
toSchemaView(schemaIR: unknown): CoreSchemaView | undefined {
this.init();
if (this.familyInstance && hasSchemaView(this.familyInstance)) {
return this.familyInstance.toSchemaView(schemaIR);
}
return undefined;
}
inferPslContract(schemaIR: unknown): PslDocumentAst | undefined {
this.init();
if (this.familyInstance && hasPslContractInfer(this.familyInstance)) {
return this.familyInstance.inferPslContract(schemaIR);
}
return undefined;
}
getPslBlockDescriptors(): AuthoringPslBlockDescriptorNamespace {
this.init();
return this.stack!.authoringContributions.pslBlockDescriptors;
}
toOperationPreview(operations: readonly MigrationPlanOperation[]): OperationPreview | undefined {
this.init();
if (this.familyInstance && hasOperationPreview(this.familyInstance)) {
return this.familyInstance.toOperationPreview(operations);
}
return undefined;
}
async emit(options: EmitOptions): Promise<EmitResult> {
const { onProgress, contractConfig } = options;
// Ensure initialized (creates stack and family instance)
// emit() does NOT require a database connection
this.init();
if (!this.familyInstance) {
throw new Error('Family instance was not initialized. This is a bug.');
}
let contractRaw: unknown;
onProgress?.({
action: 'emit',
kind: 'spanStart',
spanId: 'resolveSource',
label: 'Resolving contract source...',
});
try {
const stack = this.stack!;
const extensionInputs = toExtensionInputs(
blindCast<
readonly unknown[],
'toExtensionInputs accepts readonly unknown[] per its documented structural cast boundary'
>(stack.extensionPacks),
);
const composedExtensionContracts = new Map<string, Contract>(
extensionInputs
.filter((p) => p.contractSpace !== undefined)
.map((p) => [
p.id,
blindCast<
Contract,
'contractSpace.contractJson is the typed contract for this extension space'
>(p.contractSpace!.contractJson),
]),
);
const sourceContext = {
composedExtensionPacks: stack.extensionPacks.map((p) => p.id),
composedExtensionContracts,
scalarTypeDescriptors: stack.scalarTypeDescriptors,
authoringContributions: stack.authoringContributions,
codecLookup: stack.codecLookup,
controlMutationDefaults: stack.controlMutationDefaults,
resolvedInputs: contractConfig.source.inputs ?? [],
capabilities: stack.capabilities,
};
const providerResult = await contractConfig.source.load(sourceContext);
if (!providerResult.ok) {
onProgress?.({
action: 'emit',
kind: 'spanEnd',
spanId: 'resolveSource',
outcome: 'error',
});
return notOk({
code: 'CONTRACT_SOURCE_INVALID',
summary: providerResult.failure.summary,
why: providerResult.failure.summary,
meta: providerResult.failure.meta,
diagnostics: providerResult.failure,
});
}
contractRaw = providerResult.value;
onProgress?.({
action: 'emit',
kind: 'spanEnd',
spanId: 'resolveSource',
outcome: 'ok',
});
} catch (error) {
onProgress?.({
action: 'emit',
kind: 'spanEnd',
spanId: 'resolveSource',
outcome: 'error',
});
const message = error instanceof Error ? error.message : String(error);
return notOk({
code: 'CONTRACT_SOURCE_INVALID',
summary: 'Failed to resolve contract source',
why: message,
diagnostics: {
summary: 'Contract source provider threw an exception',
diagnostics: [
{
code: 'PROVIDER_THROW',
message,
},
],
},
meta: undefined,
});
}
// Emit contract
onProgress?.({
action: 'emit',
kind: 'spanStart',
spanId: 'emit',
label: 'Emitting contract...',
});
try {
// Blind cast: `contractRaw` is the unverified provider
// payload — `enrichContract` only adds capability + extension
// metadata onto whatever shape it receives. The structural
// check happens immediately afterwards via
// `familyInstance.deserializeContract`, which is the
// seam-of-record and the only thing that may surface
// structural errors to the caller.
const enrichedIR = enrichContract(
contractRaw as unknown as Contract,
this.frameworkComponents ?? [],
);
const rawContractJson = this.options.target.contractSerializer.serializeContract(enrichedIR);
let deserializedContract: Contract;
try {
deserializedContract = this.familyInstance.deserializeContract(rawContractJson);
} catch (error) {
onProgress?.({
action: 'emit',
kind: 'spanEnd',
spanId: 'emit',
outcome: 'error',
});
const message = error instanceof Error ? error.message : String(error);
return notOk({
code: 'CONTRACT_VALIDATION_FAILED',
summary: 'Contract validation failed',
why: message,
meta: undefined,
});
}
const result = await emitContractArtifacts(
deserializedContract,
this.stack!,
this.options.family.emission,
{
serializeContract: (contract) =>
this.options.target.contractSerializer.serializeContract(contract),
},
);
onProgress?.({
action: 'emit',
kind: 'spanEnd',
spanId: 'emit',
outcome: 'ok',
});
return ok({
storageHash: result.storageHash,
...ifDefined('executionHash', result.executionHash),
profileHash: result.profileHash,
contractJson: result.contractJson,
contractDts: result.contractDts,
});
} catch (error) {
onProgress?.({
action: 'emit',
kind: 'spanEnd',
spanId: 'emit',
outcome: 'error',
});
return notOk({
code: 'EMIT_FAILED',
summary: 'Failed to emit contract',
why: error instanceof Error ? error.message : String(error),
meta: undefined,
});
}
}
}