-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathengine.ts
More file actions
5781 lines (5413 loc) · 264 KB
/
Copy pathengine.ts
File metadata and controls
5781 lines (5413 loc) · 264 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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { AsyncLocalStorage } from 'node:async_hooks';
import { QueryAST, HookContext, ServiceObject } from '@objectstack/spec/data';
import {
EngineQueryOptions,
DataEngineInsertOptions,
EngineUpdateOptions,
EngineDeleteOptions,
EngineAggregateOptions,
EngineCountOptions,
RPC_QUERY_ALIAS_SLOTS,
foldQueryAliasSlots,
QUERY_CURSOR_REMOVED,
QUERY_DISTINCT_REMOVED,
type QueryAliasSlot,
type DroppedFieldsEvent
} from '@objectstack/spec/data';
import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
import { parseAutonumberFormat, renderAutonumber, missingFieldValues, isTenancyDisabled, FILE_REFERENCE_TYPES, REFERENCE_VALUE_TYPES, referenceTargetOf, isFileIdToken, RAW_FILE_VALUES_CONTEXT_KEY, isCurrentUserDefaultToken } from '@objectstack/spec/data';
import {
DATA_MIGRATION_FLAG_OBJECT,
FILE_REFERENCES_MIGRATION_ID,
VALUE_SHAPES_MIGRATION_ID,
isDataMigrationFlagVerified,
} from '@objectstack/spec/system';
import { ExecutionContext, ExecutionContextInput, ExecutionContextSchema } from '@objectstack/spec/kernel';
import type { FlowFunctionEffect } from '@objectstack/spec/automation';
import {
IDataDriver,
IDataEngine,
type IObjectQLEngine,
Logger,
createLogger,
withTransientRetry,
type RetryOptions,
filterTokenContextFrom,
resolveFilterTokens,
} from '@objectstack/core';
import { SummaryRecomputeError, type SummaryRecomputeFailure } from './summary-errors.js';
import {
DriverConnectError,
DatasourceUnavailableError,
emitDegradedBootBanner,
type DriverConnectFailure,
type DriverHealth,
type DatasourceUnavailableInfo,
type DatasourceUnavailableKind,
} from './driver-connect-errors.js';
import { resolveAllowDriverConnectFailure } from '@objectstack/types';
/**
* Per-row outcome of {@link ObjectQL.insertMany} (framework#3172). One entry
* per input row, in input order: written rows carry the after-hook record,
* failed rows carry the per-row error (validation / autonumber / encryption).
*/
export type InsertManyRowOutcome =
| { ok: true; record: any }
| { ok: false; error: unknown };
import { CoreServiceName, StorageNameMapping } from '@objectstack/spec/system';
import { IRealtimeService, RealtimeEventPayload } from '@objectstack/spec/contracts';
import {
BulkDataEventSchema,
DataEventSchema,
type BulkDataEvent,
type DataEvent,
} from '@objectstack/spec/api';
import type { ICryptoProvider, CryptoHandle } from '@objectstack/spec/contracts';
import {
collectSecretFields,
collectMaskedReadFields,
collectCredentialFields,
makeSecretRef,
parseSecretRef,
isSecretRef,
SECRET_MASK,
} from './secret-fields.js';
import { pluralToSingular, ExternalWriteForbiddenError } from '@objectstack/spec/shared';
import { SchemaRegistry, computeFQN } from './registry.js';
import { expandSearchToFilter } from './search-filter.js';
import { ExpressionEngine } from '@objectstack/formula';
import type { Expression } from '@objectstack/spec';
import { isAggregatedViewContainer, expandViewContainer } from '@objectstack/spec';
import { bindHooksToEngine } from './hook-binder.js';
import { validateRecord, normalizeMultiValueFields, coerceBooleanFields, ValidationError, buildFieldError, valueShapePostureSetByEnv, mediaPostureSetByEnv, isScannableValueShapeField } from './validation/record-validator.js';
import { evaluateValidationRules, needsPriorRecord, stripReadonlyWhenFields, stripReadonlyWhenFieldsMulti, hasReadonlyWhenInPayload, stripReadonlyFields } from './validation/rule-validator.js';
import { applyInMemoryAggregation } from './in-memory-aggregation.js';
import { applyHaving } from './having-filter.js';
import {
auditDanglingReferences,
type AuditableObject,
type DanglingReferenceAuditOptions,
type DanglingReferenceReport,
} from './integrity/dangling-reference-audit.js';
/**
* The lifecycle events the engine actually dispatches via `triggerHooks`. This
* is the single source of truth for what a hook can subscribe to — kept in
* lockstep with the `triggerHooks(...)` call sites and with `HookEvent` in the
* spec. `beforeFind`/`afterFind` cover both `find` and `findOne`; the write
* events cover both single-id and bulk (`multi: true`) writes (#3195). A hook
* subscribing to anything outside this set would silently never fire, so
* `registerHook` warns rather than accepting it blindly.
*/
const DISPATCHABLE_HOOK_EVENTS: ReadonlySet<string> = new Set([
'beforeFind', 'afterFind',
'beforeInsert', 'afterInsert',
'beforeUpdate', 'afterUpdate',
'beforeDelete', 'afterDelete',
]);
/**
* [#4346] The alias slots the ENGINE option bags still admit, cut from the
* spec's own table (#3795) so the engine never re-declares a mapping.
*
* The deprecated `DataEngine{Query,Update,Delete,Count,Aggregate}Options`
* contracts declare `filter` on every read AND write method, but only `find`
* folded it — `findOne`/`count`/`update`/`delete`/`aggregate` passed the bag
* through with `where === undefined`, which every driver reads as "no
* predicate": a caller filtering with `{ filter }` silently matched EVERY row
* (an over-grant on the reads, an unbounded write on `update`/`delete`).
*
* `where` is the slot every method folds; `limit` additionally applies to the
* find-shaped bags, which declare `top` (OData) as its alias. The other four
* pairs in the table are RPC/wire spellings folded at parse by
* `RpcQueryOptionsSchema` / the protocol normalizer — their values need shape
* lowering (`sort` records, `populate` lists) that belongs to those layers, so
* the engine deliberately does not fold them.
*/
const ENGINE_WHERE_SLOTS: readonly QueryAliasSlot[] =
RPC_QUERY_ALIAS_SLOTS.filter((slot) => slot.canonical === 'where');
const ENGINE_QUERY_SLOTS: readonly QueryAliasSlot[] =
RPC_QUERY_ALIAS_SLOTS.filter((slot) => slot.canonical === 'where' || slot.canonical === 'limit');
/**
* [#4371] The slots the engine does NOT fold — the wire-only pairs
* (`select`→`fields`, `sort`→`orderBy`, `skip`→`offset`, `populate`→`expand`),
* derived as the complement of {@link ENGINE_QUERY_SLOTS} so a seventh pair
* added to the spec table lands on exactly one side of the split.
*
* Their values need shape lowering (`sort`'s `{field: 'asc'}` record form,
* `populate`'s name list) that belongs to the RPC/protocol layers, so folding
* here would re-implement the lowering per reader — the #3795 condition. But a
* DIRECT engine call never crosses those layers: the alias key used to ride
* the AST verbatim, drivers read only the canonical name, and the parameter
* was silently dropped — three shipped "latest N in arbitrary order" bugs
* (#4370) plus the engine's own `seedAutonumber`. Declared ≠ enforced
* (AGENTS.md PD #10): the find-shaped entry points now REJECT these spellings,
* naming the canonical key and shape, so the mistake throws at the call site
* instead of degrading the result.
*
* Deliberately NOT applied to the where-only methods
* (`update`/`delete`/`count`/`aggregate`): their contracts honour no
* sort/projection/pagination at all, so "pass `orderBy` instead" would
* redirect the caller to a key those methods silently ignore too. Unknown-key
* enforcement for those bags is #4371's option (2), scoped separately.
*/
const ENGINE_WIRE_ONLY_SLOTS: readonly QueryAliasSlot[] =
RPC_QUERY_ALIAS_SLOTS.filter((slot) => !ENGINE_QUERY_SLOTS.includes(slot));
/**
* Canonical shape each wire-only slot's value must be rewritten into — quoted
* by the rejection so the error carries the full migration, not just the key
* rename (the value shapes differ; that is WHY the engine cannot fold them).
*/
const WIRE_ONLY_CANONICAL_SHAPES: Record<string, string> = {
fields: "a string[] of field names",
orderBy: "SortNode[]: [{ field, order: 'asc' | 'desc' }]",
offset: 'a number of rows to skip',
expand: 'a record of { relationName: QueryAST }',
};
/**
* [#4371 option 2] The driver-option keys the engine forwards verbatim: on
* `find`/`findOne`/`update`/`delete` the option bag IS the base of the driver
* options (`buildDriverOptions(object, ctx, bag)`), which is how a caller's
* explicit `tenantId` / `bypassTenantAudit` reaches the driver (pinned in
* engine.test.ts). `count`/`aggregate` never forward the bag, so these keys
* are deliberately NOT legal there — accepting them would be the exact
* silently-ignored contract this gate exists to close.
*/
const ENGINE_DRIVER_PASSTHROUGH_KEYS = [
'transaction', 'tenantId', 'tenantIds', 'timezone', 'bypassTenantAudit', 'preserveAudit',
] as const;
/**
* [#4371 option 2] Per-method legal option keys. An option bag key outside
* the method's set is REJECTED at the entry point: the engine executes none
* of them, so the call would otherwise succeed with the option silently
* ignored — the `declared ≠ enforced` shape (PD #10) one layer below the
* wire-alias rejection above.
*
* Sources, in order: the method's `Engine*OptionsSchema` declared keys (minus
* the `retiredKey` tombstones `cursor`/`distinct`, which get their tombstone
* quoted instead of a generic rejection — the schema keeps them ONLY to carry
* that message, and this runtime path never parses); `searchFields` (read by
* `find` at the `$search` expansion, sent by the protocol layer);
* `onFieldsDropped` (`WriteObservabilityOptions` — contract-declared,
* unrepresentable in the serializable Zod schema); and the driver
* pass-through keys above. The alias spellings (`filter`/`top`) are folded
* and deleted BEFORE this check runs, so they never reach it.
*
* A drift pin in engine-unknown-option.test.ts asserts each set equals its
* schema's shape (minus tombstones, plus the documented extras) so a key
* added to the spec cannot be silently rejected here.
*/
const ENGINE_FIND_OPTION_KEYS: ReadonlySet<string> = new Set([
'context', 'where', 'fields', 'orderBy', 'limit', 'offset',
'search', 'searchFields', 'expand',
...ENGINE_DRIVER_PASSTHROUGH_KEYS,
]);
const ENGINE_UPDATE_OPTION_KEYS: ReadonlySet<string> = new Set([
'context', 'where', 'upsert', 'multi', 'returning', 'onFieldsDropped',
...ENGINE_DRIVER_PASSTHROUGH_KEYS,
]);
const ENGINE_DELETE_OPTION_KEYS: ReadonlySet<string> = new Set([
'context', 'where', 'multi',
...ENGINE_DRIVER_PASSTHROUGH_KEYS,
]);
const ENGINE_COUNT_OPTION_KEYS: ReadonlySet<string> = new Set(['context', 'where']);
const ENGINE_AGGREGATE_OPTION_KEYS: ReadonlySet<string> = new Set([
'context', 'where', 'groupBy', 'aggregations', 'having', 'timezone',
]);
/** Tombstoned option keys: rejected with the spec's own removal notice. */
const ENGINE_RETIRED_OPTION_MESSAGES: Record<string, string> = {
cursor: QUERY_CURSOR_REMOVED,
distinct: QUERY_DISTINCT_REMOVED,
};
/**
* The per-method legal key sets, exported for the drift pin ONLY
* (engine-unknown-option.test.ts asserts each set against its schema's shape,
* so a key added to the spec cannot be silently rejected here). Not a public
* API surface — consumers pass options, they do not read this table.
*/
export const ENGINE_OPTION_KEY_SETS: Readonly<Record<string, ReadonlySet<string>>> = {
find: ENGINE_FIND_OPTION_KEYS,
findOne: ENGINE_FIND_OPTION_KEYS,
update: ENGINE_UPDATE_OPTION_KEYS,
delete: ENGINE_DELETE_OPTION_KEYS,
count: ENGINE_COUNT_OPTION_KEYS,
aggregate: ENGINE_AGGREGATE_OPTION_KEYS,
};
/**
* Reject option-bag keys the engine does not execute (#4371 option 2).
*
* Runs AFTER `foldEngineOptionAliases`, so alias spellings are already folded
* away (or thrown on). `null`-valued keys pass — a `null` is a withdrawal
* carrying no intent a drop could lose, same rule as the fold. Retired keys
* (`cursor`/`distinct`) quote their tombstone. Everything else gets the legal
* key set, so the error carries the fix.
*/
function rejectUnknownEngineOptions(
object: string,
operation: string,
bag: object | undefined,
legal: ReadonlySet<string>,
): void {
if (!bag) return;
let unknown: string[] | undefined;
for (const [key, value] of Object.entries(bag)) {
if (value == null || legal.has(key)) continue;
(unknown ??= []).push(key);
}
if (!unknown) return;
const details = unknown.map((k) =>
ENGINE_RETIRED_OPTION_MESSAGES[k] ? `'${k}': ${ENGINE_RETIRED_OPTION_MESSAGES[k]}` : `'${k}'`,
);
throw new Error(
`${operation}('${object}') does not recognise option${unknown.length > 1 ? 's' : ''} ` +
`${details.join('; ')}. The engine executes none of ${unknown.length > 1 ? 'them' : 'it'}, ` +
`so the call would succeed with the option silently ignored (#4371). ` +
`Legal keys for ${operation}: ${[...legal].sort().join(', ')}.`,
);
}
/**
* Fold the deprecated alias spellings of an engine option bag into their
* canonical QueryAST keys, under the #3795/#4181 rule: an alias alone moves to
* the canonical key, redundant identical spellings collapse, DIFFERENT values
* for one slot are irreconcilable and throw (picking a winner IS the silent
* drop), and an explicit `null` alias is a withdrawal.
*
* `rejectSlots` ({@link ENGINE_WIRE_ONLY_SLOTS}) names the slots whose alias
* spellings the engine can neither fold nor honour: a non-null value under one
* throws, quoting the canonical key and shape (#4371). `null` stays a
* withdrawal here too — it carries no intent a drop could lose — and rides
* through for drivers to ignore, exactly as before.
*
* Returns the SAME reference when no alias spelling is present (the common
* path allocates nothing — `withResolvedWhere` discipline); otherwise folds a
* shallow copy, because the bag belongs to the caller and may be reused (view
* metadata, flow node config).
*/
function foldEngineOptionAliases<T extends object | undefined>(
object: string,
operation: string,
bag: T,
slots: readonly QueryAliasSlot[],
rejectSlots?: readonly QueryAliasSlot[],
): T {
if (!bag) return bag;
if (rejectSlots) {
const refused = rejectSlots.flatMap((slot) =>
slot.aliases
.filter((alias) => (bag as Record<string, unknown>)[alias] != null)
.map((alias) => ({ alias, canonical: slot.canonical })),
);
if (refused.length > 0) {
throw new Error(
`${operation}('${object}') does not accept ` +
`${refused.map((r) => `'${r.alias}'`).join(', ')}: ` +
refused
.map(
(r) =>
`'${r.alias}' is a wire spelling of '${r.canonical}', folded by the RPC/protocol ` +
`layer — a direct engine call bypasses that fold, so the value would be silently ` +
`dropped, not applied. Pass '${r.canonical}' ` +
`(${WIRE_ONLY_CANONICAL_SHAPES[r.canonical] ?? 'the canonical QueryAST shape'}) instead.`,
)
.join(' '),
);
}
}
if (!slots.some((slot) => slot.aliases.some((alias) => alias in bag))) return bag;
const folded: Record<string, unknown> = { ...bag };
foldQueryAliasSlots(folded, slots, (conflict) => {
throw new Error(
`Conflicting options on ${operation}('${object}'): ` +
`${conflict.spellings.map((s) => `'${s}'`).join(', ')} are spellings of the same ` +
`parameter (canonical '${conflict.canonical}') and were given different values. ` +
'Send exactly one.',
);
});
return folded as T;
}
interface FormulaPlanEntry { name: string; expression: Expression; }
function planFormulaProjection(
schema: any,
requestedFields: string[] | undefined
): { plan: FormulaPlanEntry[]; projected?: string[] } {
if (!schema?.fields) return { plan: [] };
const allFieldNames = Object.keys(schema.fields);
// When no explicit projection, evaluate every formula field on the schema —
// matches REST default of "return everything". Explicit projection still
// honours the caller's selection.
const targets = (Array.isArray(requestedFields) && requestedFields.length > 0)
? requestedFields
: allFieldNames;
const plan: FormulaPlanEntry[] = [];
const projected = new Set<string>();
for (const f of targets) {
const def = (schema.fields as any)[f];
if (def?.type === 'formula' && def.expression) {
// Normalize string-shorthand → Expression envelope (M9 transition).
const expr: Expression = typeof def.expression === 'string'
? { dialect: 'cel', source: def.expression }
: def.expression;
plan.push({ name: f, expression: expr });
// Pre-compile to surface syntax errors at planning stage rather than
// per-row eval. Dependency discovery (which fields the formula reads)
// is no longer used — CEL uses dynamic projection via `record.<field>`.
ExpressionEngine.compile(expr);
} else if (Array.isArray(requestedFields) && requestedFields.length > 0) {
projected.add(f);
}
}
if (plan.length === 0) return { plan: [] };
// For formulas: project all schema fields so CEL `record.<field>` lookups
// see complete data. Static dependency analysis on AST is M9.7 work.
if (Array.isArray(requestedFields) && requestedFields.length > 0) {
if (!projected.has('id')) projected.add('id');
for (const fname of allFieldNames) {
// Skip formula fields themselves — they are virtual and not
// projectable by the underlying driver. Without this guard the
// SQL driver emits `SELECT response_rate ...` which fails as
// "no such column" and the driver returns [] (silently).
const fdef = (schema.fields as any)[fname];
if (fdef?.type === 'formula') continue;
projected.add(fname);
}
return { plan, projected: Array.from(projected) };
}
// Implicit/full projection — leave projected undefined so the driver
// returns its default columns (typically *).
return { plan };
}
/**
* Evaluate read-time formula virtual fields against the raw rows.
*
* The eval context mirrors `applyFieldDefaults` so formula and default
* expressions see the same shape: a `now` pinned ONCE per operation (every row
* and every formula field in one `find()` observes the same instant —
* determinism, and no per-eval `new Date()` drift), plus `os.user` / `os.org`
* resolved from the execution context (so a computed field can reference the
* caller, e.g. `os.user.id`). Previously this passed only `{ record }`, so
* `now()`/`today()` ran against live wall-clock and user/org were unreachable.
*
* (ADR-0053 Phase 2 will additionally thread `timezone` here once
* `ExecutionContext.timezone` exists — see #1980; this change is independent
* of timezone.)
*/
function applyFormulaPlan(
plan: FormulaPlanEntry[],
records: any[],
execCtx?: ExecutionContextInput,
nowSnapshot?: Date,
): void {
if (!plan.length) return;
const now = nowSnapshot ?? new Date();
const timezone = execCtx?.timezone;
const user = execCtx?.userId ? { id: String(execCtx.userId), positions: execCtx?.positions ?? [] } : undefined;
const org = execCtx?.tenantId ? { id: String(execCtx.tenantId) } : undefined;
for (const rec of records) {
if (rec == null) continue;
for (const fp of plan) {
const r = ExpressionEngine.evaluate(fp.expression, { now, timezone, user, org, record: rec });
rec[fp.name] = r.ok ? r.value : null;
}
}
}
export type HookHandler = (context: HookContext) => Promise<void> | void;
/**
* Per-object hook entry with priority support
*/
export interface HookEntry {
handler: HookHandler;
object?: string | string[]; // undefined = global hook
priority: number;
packageId?: string;
/**
* Original metadata-form `Hook` definition this entry was bound from
* (when registered via `bindHooksToEngine`). Pure code-paths that call
* `engine.registerHook` directly leave this undefined.
*/
meta?: any;
/** Hook `name` from metadata; used for diagnostics & deduplication. */
hookName?: string;
}
/** Function registry entry — see `registerFunction`. */
export interface FunctionEntry {
handler: HookHandler;
packageId?: string;
/**
* What this function does to data, as DECLARED at registration (#4396).
* Only a `script`-node caller reads it: a flow function is contractually
* pure, and the run summary counts on that, so a function that legitimately
* writes declares `'writes'` and its step is reported as an effect the
* platform cannot count rather than as none. Absent ⇒ `'pure'`.
*
* Carried on the registry entry rather than beside it because this IS part of
* the registration — one registry, and what a caller needs to know about a
* function travels with the function.
*/
effect?: FlowFunctionEffect;
}
/**
* Declarations that may accompany a `registerFunction` call. The bare
* `packageId` string is still accepted in that position (every existing caller
* passes one), so this widens the signature without a migration.
*/
export interface FunctionRegistrationOptions {
/** Owning package — the unit `unregisterFunctionsByPackage` removes. */
packageId?: string;
/** Declared data effect (#4396); omit for the pure default. */
effect?: FlowFunctionEffect;
}
/**
* Operation Context for Middleware Chain
*/
export interface OperationContext {
object: string;
operation: 'find' | 'findOne' | 'insert' | 'update' | 'delete' | 'count' | 'aggregate';
ast?: QueryAST;
data?: any;
options?: any;
context?: ExecutionContextInput;
result?: any;
}
/**
* Trailing options for the READ methods (find / findOne / count / aggregate).
*
* Historically the read methods took their execution context INSIDE the query
* (`query.context`), while the WRITE methods (insert / update) took it in a
* trailing `options.context`. That split was a footgun: the same `{ context }`
* object is correct as the 3rd arg to `insert` but was SILENTLY DROPPED as the
* 3rd arg to `find` — a class of bugs where an intended `isSystem` bypass just
* vanished (e.g. control-plane reads coming back empty once org-scoping hooks
* were added). We now ALSO accept `context` via this trailing options arg on the
* read methods, so "execution context goes in the trailing options argument" is
* one rule across reads and writes. `query.context` remains supported; when both
* are given, `options.context` wins (it is the explicit channel).
*/
export interface EngineReadOptions {
context?: ExecutionContextInput;
}
/** Merge read-path execution context from the query and the trailing options. */
function mergeReadContext(
fromQuery?: ExecutionContextInput,
fromOptions?: ExecutionContextInput,
): ExecutionContextInput | undefined {
if (fromOptions == null) return fromQuery;
if (fromQuery == null) return fromOptions;
return { ...fromQuery, ...fromOptions };
}
/**
* True when this write is exempt from the `state_machine` validation rule —
* both the insert `initialStates` entry check and the update `transitions`
* check are skipped for it. Either the seed-specific `seedReplay` flag (#3433)
* or the general `skipStateMachine` flag (#3479, set by the REST import runner
* for a "historical" import) turns it off. Both are server-set, never
* client-supplied.
*/
function shouldSkipStateMachine(ctx?: ExecutionContextInput): boolean {
return ctx?.seedReplay === true || ctx?.skipStateMachine === true;
}
/**
* Engine Middleware (Onion model)
*/
export type EngineMiddleware = (
ctx: OperationContext,
next: () => Promise<void>
) => Promise<void>;
/**
* Derive the registry key for a metadata item.
*
* Most metadata items expose a top-level `name` (or `id`). The `View`
* container defined by `@objectstack/spec/ui` is special: it aggregates
* `list / form / listViews / formViews` for a single object and is
* keyed implicitly by its target object name (see `data.object`).
*
* Per spec, `ViewSchema` does NOT have a top-level `name` field
* (view.zod.ts), so we resolve it from the inner data source. This
* matches the server-side metadata API contract (`/api/v1/meta/views/:object`).
*/
function resolveMetadataItemName(key: string, item: any): string | undefined {
if (!item) return undefined;
if (item.name) return item.name;
if (item.id) return item.id;
if (key === 'views') {
// Independent ViewItems ("Object has-many View") carry a top-level `name`
// (handled above) and bind to their object via `object`. The aggregated
// container has no top-level name/object, so fall back to its inner data
// source — matching the loader's expansion key.
return (
item?.object ||
item?.list?.data?.object ||
item?.form?.data?.object ||
undefined
);
}
return undefined;
}
/**
* ObjectQL Engine
*
* Implements the IDataEngine interface for data persistence.
* Acts as the reference implementation for:
* - CoreServiceName.data (CRUD)
* - CoreServiceName.metadata (Schema Registry)
*/
/** A roll-up `summary` field on a parent object that aggregates a child. */
interface SummaryDescriptor {
parentObject: string;
summaryField: string;
/** FK field on the child pointing back to the parent. */
fkField: string;
fn: 'count' | 'sum' | 'min' | 'max' | 'avg';
/** Child field aggregated (unused for count). */
sourceField: string;
/**
* Optional predicate (a query `where` FilterCondition) restricting which child
* rows are aggregated. ANDed with the parent-FK match when the aggregate runs.
* Undefined ⇒ aggregate every child of the parent.
*/
filter?: Record<string, unknown>;
}
// `implements IObjectQLEngine` is the verification step of #4251 B3: every
// member the `objectql` slot's contract declares is checked against this class
// on every build, so the seven consumer-local surface declarations the contract
// replaced can never silently drift from the engine again. IObjectQLEngine
// extends IDataEngine, so the old claim rides along.
/**
* [#4441] "The caller did not name a record here."
*
* `null` / `undefined` / `''` mean NO LINK — exactly what
* `deleteBehavior: 'set_null'` writes — and an empty array is the multi-value
* spelling of the same thing. None of them is an id to resolve.
*/
function isEmptyReferenceValue(v: unknown): boolean {
if (v === null || v === undefined || v === '') return true;
if (Array.isArray(v)) return v.length === 0 || v.every((e) => e === null || e === undefined || e === '');
return false;
}
/**
* RFC-4122 v4 uuid for the realtime `DataEvent.id` (#4626).
*
* The twin of the generator `MetadataManager` uses for `MetadataEvent.id`
* (#4602/#4628) — same shape, same fallback, kept local rather than shared so
* the engine's `core` import closure gains nothing (ADR-0076 D2 ratchet).
* Prefers `crypto.randomUUID`; the fallback keeps browser-compatible (Pure)
* environments without WebCrypto working while still satisfying
* `DataEventSchema`'s `z.string().uuid()`.
*/
function generateEventUuid(): string {
const c = globalThis.crypto;
if (c && typeof c.randomUUID === 'function') {
return c.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
const r = (Math.random() * 16) | 0;
const v = ch === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
/**
* Coerce a driver-returned primary key into `DataEvent.recordId` (a required
* `string`). Returns `undefined` when the write has no single record identity
* — a bulk `updateMany`/`deleteMany` returns only a count — so the caller can
* decline to publish rather than fabricate one (#4626).
*/
function eventRecordId(value: unknown): string | undefined {
if (typeof value === 'string') return value === '' ? undefined : value;
if (typeof value === 'number' || typeof value === 'bigint') return String(value);
return undefined;
}
/** `DataEvent.changes`/`before`/`after` are `z.record(...)` — only a plain object qualifies. */
function eventRecordBody(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
/** `DataEvent.userId` — the acting user, when the execution context names one. */
function eventUserId(execCtx?: ExecutionContextInput): string | undefined {
const userId = execCtx?.userId;
if (userId == null) return undefined;
const asString = String(userId);
return asString === '' ? undefined : asString;
}
/**
* Coerce a multi-row driver result into `BulkDataEvent.matched` (#4639).
*
* `IDataDriver.updateMany`/`deleteMany` are contracted to resolve the affected
* row count (`Promise<number>`). A driver that resolves something else has not
* met that contract, and the count is the ONLY substantive thing a bulk event
* says — so this returns `undefined` and the caller declines to publish rather
* than inventing a `matched: 0` that reads as "nothing was affected" when rows
* very likely were.
*/
function eventMatchedCount(value: unknown): number | undefined {
if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) return undefined;
return value;
}
export class ObjectQL implements IObjectQLEngine {
/**
* Ambient transaction store (ADR-0034). While a `transaction()` callback
* runs, the active transaction handle lives here so that EVERY data
* operation — including internal reads done during a write (reference
* checks, hooks, expand) — automatically binds to the same connection
* instead of asking the pool for another one and deadlocking on the
* single-connection SQLite pool.
*/
private readonly txStore = new AsyncLocalStorage<{ transaction: unknown }>();
private drivers = new Map<string, IDataDriver>();
private defaultDriver: string | null = null;
private logger: Logger;
// Datasource mapping rules (imported from defineStack)
private datasourceMapping: Array<{
namespace?: string;
package?: string;
objectPattern?: string;
default?: boolean;
datasource: string;
priority?: number;
}> = [];
// Package manifests registry (for defaultDatasource lookup)
private manifests = new Map<string, any>();
// Datasource definitions by name (ADR-0015): carries schemaMode +
// external.allowWrites so the write gate (Gate 3) can enforce federation
// ownership. Populated from manifests in registerApp and via
// registerDatasourceDef. Absent entry ⇒ treated as managed (default DB).
private datasourceDefs = new Map<string, { schemaMode?: string; external?: { allowWrites?: boolean } }>();
// Declared-but-unusable datasources, keyed by name (framework#3828). Written
// by the datasource connection layer via markDatasourceUnavailable; read only
// by getDriver, to explain a missing driver instead of blaming a typo. Empty
// is the normal state — an entry here means a connect was refused or failed.
private unavailableDatasources = new Map<string, DatasourceUnavailableInfo>();
// Per-object hooks with priority support
private hooks: Map<string, HookEntry[]> = new Map([
['beforeFind', []], ['afterFind', []],
['beforeInsert', []], ['afterInsert', []],
['beforeUpdate', []], ['afterUpdate', []],
['beforeDelete', []], ['afterDelete', []],
]);
// Middleware chain (onion model)
private middlewares: Array<{
fn: EngineMiddleware;
object?: string;
}> = [];
// Action registry: key = "objectName:actionName"
private actions = new Map<string, { handler: (ctx: any) => Promise<any> | any; package?: string }>();
// Function registry: name → handler. Used by `bindHooksToEngine` to
// resolve string-named hook handlers (the JSON-safe form). Populated by
// `defineStack({ functions })` via `AppPlugin`, or directly via
// `engine.registerFunction(...)`.
private functions = new Map<string, FunctionEntry>();
// Realtime service for event publishing
private realtimeService?: IRealtimeService;
// i18n service backing validation-message + field-label localization (#3957).
// Optional: without it, messages render from the built-in catalog against the
// declared labels.
private i18nService?: { t?: (key: string, locale: string, params?: Record<string, unknown>) => string };
// Crypto provider backing `secret`-typed fields. Optional: when absent,
// writing an object that declares a secret field fails closed (never
// persists cleartext). Injected by the host via setCryptoProvider().
private cryptoProvider?: ICryptoProvider;
// [ADR-0105 D2 / #3623] Posture accessor for driver-scope widening under the
// `group` posture. Injected by SecurityPlugin via setTenancyPostureProvider();
// absent = equality scoping (fail toward isolation).
private tenancyPostureProvider?: () => string | undefined;
// Per-engine SchemaRegistry instance.
//
// Historically SchemaRegistry was a process-wide singleton of static state,
// which broke multi-environment servers: a project kernel would inherit every
// object registered by the control plane (e.g. sys_metadata), and
// getDriver()'s owner lookup would route CRUD to the wrong database. Each
// engine now owns its registry so kernels are fully isolated.
private _registry: SchemaRegistry = new SchemaRegistry();
constructor(hostContext: Record<string, any> = {}) {
// Use provided logger or create a new one
this.logger = hostContext.logger || createLogger({ level: 'info', format: 'pretty' });
// Pick up production hardening switches from env so deployers can
// enforce strict-body without code changes:
// OBJECTQL_STRICT_HOOKS=1 → unresolved hooks throw at bind time
// OBJECTQL_WARN_LEGACY_HANDLER=1 → log a deprecation per legacy bind
if (process?.env?.OBJECTQL_STRICT_HOOKS === '1') {
(this as any)._strictHookBinding = true;
}
if (process?.env?.OBJECTQL_WARN_LEGACY_HANDLER === '1') {
(this as any)._warnLegacyHandler = true;
}
this.logger.info('ObjectQL Engine Instance Created');
}
/**
* Service Status Report
* Used by Kernel to verify health and capabilities.
*/
getStatus() {
return {
name: CoreServiceName.enum.data,
status: 'running',
version: '0.9.0',
features: ['crud', 'query', 'aggregate', 'transactions', 'metadata']
};
}
/**
* Expose the SchemaRegistry for plugins to register metadata.
*
* Returns the per-engine instance, NOT the class. Each ObjectQL engine
* owns its registry so multi-environment kernels remain isolated.
*/
get registry(): SchemaRegistry {
return this._registry;
}
/**
* Register a hook
* @param event The event name (e.g. 'beforeFind', 'afterInsert')
* @param handler The handler function
* @param options Optional: target object(s) and priority
*/
registerHook(event: string, handler: HookHandler, options?: {
object?: string | string[];
priority?: number;
packageId?: string;
/** Original metadata Hook definition (set by `bindHooksToEngine`). */
meta?: any;
/** Stable name from metadata (set by `bindHooksToEngine`). */
hookName?: string;
}) {
// [#3195] Guard against enum-vs-dispatch drift: a hook on an event the
// engine never triggers would register "successfully" and then silently
// never fire. Warn loudly rather than swallow it. Not a hard reject — a
// custom driver/plugin may dispatch its own events via `triggerHooks`.
if (!DISPATCHABLE_HOOK_EVENTS.has(event)) {
this.logger.warn(
`Hook registered for '${event}', which the engine never dispatches — it will never fire. ` +
`Dispatchable events: ${[...DISPATCHABLE_HOOK_EVENTS].join(', ')}. ` +
`(Read filtering → RLS/permissions; field masking → field metadata; delete guards → beforeDelete.)`,
{ event, object: options?.object, hookName: options?.hookName },
);
}
if (!this.hooks.has(event)) {
this.hooks.set(event, []);
}
const entries = this.hooks.get(event)!;
entries.push({
handler,
object: options?.object,
priority: options?.priority ?? 100,
packageId: options?.packageId,
meta: options?.meta,
hookName: options?.hookName,
});
// Sort by priority (lower runs first)
entries.sort((a, b) => a.priority - b.priority);
this.logger.debug('Registered hook', { event, object: options?.object, priority: options?.priority ?? 100, totalHandlers: entries.length });
}
/**
* Remove all hooks registered under a given `packageId`. Used by
* `bindHooksToEngine` to make re-binding (hot reload, app reinstall)
* idempotent, and by app uninstall flows.
*/
unregisterHooksByPackage(packageId: string): number {
if (!packageId) return 0;
let removed = 0;
for (const [event, entries] of this.hooks.entries()) {
const before = entries.length;
const kept = entries.filter((e) => e.packageId !== packageId);
if (kept.length !== before) {
this.hooks.set(event, kept);
removed += before - kept.length;
}
}
if (removed > 0) {
this.logger.debug('Unregistered hooks by package', { packageId, removed });
}
return removed;
}
/**
* Register a named function handler that can later be referenced by
* string from a `Hook.handler` field, an `Action.target`, or a flow
* `script` node's `config.function`. This is the JSON-safe form of
* handler binding — declarative metadata persisted to disk or shipped
* over the wire only carries the name.
*
* The third parameter accepts either the owning `packageId` (its original
* shape, unchanged for every existing caller) or a
* {@link FunctionRegistrationOptions} record that also carries what the
* function DECLARES about itself — today its data `effect` (#4396).
*/
registerFunction(
name: string,
handler: HookHandler,
packageIdOrOptions?: string | FunctionRegistrationOptions,
): void {
if (!name || typeof handler !== 'function') return;
const opts: FunctionRegistrationOptions =
typeof packageIdOrOptions === 'string' ? { packageId: packageIdOrOptions } : (packageIdOrOptions ?? {});
const { packageId, effect } = opts;
this.functions.set(name, { handler, packageId, ...(effect ? { effect } : {}) });
this.logger.debug('Registered function', { name, packageId, effect });
}
/** Look up a registered function by name. */
resolveFunction(name: string): HookHandler | undefined {
return this.functions.get(name)?.handler;
}
/**
* Look up a registered function's FULL entry — the handler plus whatever it
* declared about itself (#4396). `resolveFunction` above answers "can I call
* it"; a caller that must also report what the call did (the automation
* engine's `script` node, feeding the #4354 run summary) needs the
* declaration, and reading it off the same registry keeps the two from
* drifting.
*/
resolveFunctionEntry(name: string): Readonly<FunctionEntry> | undefined {
return this.functions.get(name);
}
/** Remove all functions registered under a given `packageId`. */
unregisterFunctionsByPackage(packageId: string): number {
if (!packageId) return 0;
let removed = 0;
for (const [name, entry] of this.functions.entries()) {
if (entry.packageId === packageId) {
this.functions.delete(name);
removed += 1;
}
}
if (removed > 0) {
this.logger.debug('Unregistered functions by package', { packageId, removed });
}
return removed;
}
/**
* Bind a list of declarative `Hook` metadata definitions to this engine.
*
* Convenience proxy to the canonical `bindHooksToEngine` so callers do
* not need a separate import. Use `import { bindHooksToEngine } from
* '@objectstack/objectql'` directly when you want the result object.
*/
bindHooks(hooks: any[] | undefined, opts?: {
packageId?: string;
functions?: Record<string, HookHandler>;
bodyRunner?: any;
strict?: boolean;
warnLegacyHandler?: boolean;
metrics?: any;
}): void {
const merged = { ...(opts ?? {}), logger: this.logger } as any;
if (!merged.bodyRunner && this._defaultBodyRunner) {
merged.bodyRunner = this._defaultBodyRunner;
}
if (merged.strict === undefined && (this as any)._strictHookBinding) {
merged.strict = true;
}
if (merged.warnLegacyHandler === undefined && (this as any)._warnLegacyHandler) {
merged.warnLegacyHandler = true;
}
if (!merged.metrics && (this as any)._hookMetricsRecorder) {
merged.metrics = (this as any)._hookMetricsRecorder;
}
bindHooksToEngine(this, hooks, merged);
}
/** Default hook body-runner — see {@link setDefaultBodyRunner}. */
private _defaultBodyRunner?: any;
/** Default action body-runner factory — see {@link setDefaultActionRunner}. */
private _defaultActionRunner?: (actionDef: any) => ((ctx: any) => Promise<unknown>) | undefined;
/**
* Install a default body-runner used when `bindHooks` is called without
* an explicit one. The runtime layer sets this once on each per-project
* engine so every binding path (template seed, metadata sync, AppPlugin)
* can execute hook `body.source` consistently.
*
* FIRST-WINS (#4251): "set once per engine" is this method's own contract,
* so the method enforces it — a second call is ignored and returns `false`.
* Callers used to implement the guard themselves by probing the private
* `_defaultBodyRunner` field through `any` (multiple AppPlugin instances on
* one kernel must not clobber each other's runner), which meant the
* invariant lived in every caller and belonged to none. Nobody replaces a
* runner on a live engine: every setter call site either owns a fresh
* engine or wants exactly this keep-the-first behaviour.
*
* @returns `true` when this call installed the runner, `false` when one was
* already present (kept unchanged).
*/
setDefaultBodyRunner(runner: any): boolean {
if (this._defaultBodyRunner) {
this.logger.debug('Default body runner already installed — keeping the first');
return false;
}
this._defaultBodyRunner = runner;
return true;
}
/** The installed default body-runner, if any — the public read the first-wins guard implies. */
getDefaultBodyRunner(): any {
return this._defaultBodyRunner;
}
/**
* Install a default ACTION body-runner factory: `(actionDef) => handler |
* undefined`. The runtime layer sets this once per engine (same boot point