-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathplugin.ts
More file actions
1598 lines (1499 loc) · 68.3 KB
/
Copy pathplugin.ts
File metadata and controls
1598 lines (1499 loc) · 68.3 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 { ObjectQL } from './engine.js';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
import { Plugin, PluginContext } from '@objectstack/core';
import { StorageNameMapping } from '@objectstack/spec/system';
import { SERVICE_SELF_INFO_KEY, type ServiceSelfInfo } from '@objectstack/spec/api';
import { LifecycleService } from './lifecycle/lifecycle-service.js';
import { lifecycleSettingsManifest } from './lifecycle/lifecycle-settings.js';
import {
SysMetadataObject,
SysMetadataHistoryObject,
SysMetadataCommitObject,
SysMetadataAuditObject,
SysViewDefinitionObject,
} from '@objectstack/metadata-core';
export type { Plugin, PluginContext };
/**
* Protocol extension for DB-based metadata hydration.
* `loadMetaFromDb` is implemented by ObjectStackProtocolImplementation but
* is NOT (yet) part of the canonical ObjectStackProtocol wire-contract in
* `@objectstack/spec`, since it is a server-side bootstrap concern only.
*/
interface ProtocolWithDbRestore {
loadMetaFromDb(): Promise<{ loaded: number; errors: number }>;
}
/** Type guard — checks whether the service exposes `loadMetaFromDb`. */
function hasLoadMetaFromDb(service: unknown): service is ProtocolWithDbRestore {
return (
typeof service === 'object' &&
service !== null &&
typeof (service as Record<string, unknown>)['loadMetaFromDb'] === 'function'
);
}
/**
* Options for ObjectQLPlugin.
*
* `environmentId` scopes all metadata writes + reads to a specific project.
* When set, `protocol.saveMetaItem` stamps `environment_id = <environmentId>` on
* new sys_metadata rows, and `protocol.loadMetaFromDb` filters by the same
* column. Leave undefined in single-kernel / self-hosted mode — rows land
* in the platform-global scope (environment_id IS NULL).
*/
export interface ObjectQLPluginOptions {
/** Optional pre-built engine. When absent, one is lazily created in init. */
ql?: ObjectQL;
/** Passed to `new ObjectQL(...)` when `ql` is not supplied. */
hostContext?: Record<string, any>;
/** Scope sys_metadata reads/writes to this project. */
environmentId?: string;
/**
* Override the kernel's default plugin-start timeout for this plugin.
* Defaults to 120000 (120s). Schema sync to a remote SQL backend
* (Neon/Postgres/Turso) is latency-bound — the SQL driver currently
* does NOT support `batchSchemaSync`, so it issues one round-trip per
* registered object × twice (Phase 1 + Phase 3 in `start()`). On a
* cold remote DB with N tables this can blow past the kernel's
* default 30s easily, even though everything is healthy.
*/
startupTimeout?: number;
/**
* Skip both `syncRegisteredSchemas()` calls inside `start()` and
* assume DDL is managed out-of-band (e.g. an `apps/cloud/scripts/migrate.ts`
* run before deploy that connects directly to the database and creates
* all `sys_*` + custom tables once).
*
* Use this on cold-start-sensitive runtimes (Cloudflare Containers,
* Lambda) where the platform's inbound-request budget is shorter than
* a fresh remote-DB schema sync. The plugin still hydrates the
* SchemaRegistry from `sys_metadata` (Phase 2), so custom user
* objects come up — they just aren't re-DDL'd on every cold boot.
*
* Falls back to `process.env.OS_SKIP_SCHEMA_SYNC === '1'` when the
* option is unset, so containers can flip it via their env without a
* code change.
*/
skipSchemaSync?: boolean;
/**
* Hydrate the SchemaRegistry from this kernel's local `sys_metadata`
* even when `environmentId` is set.
*
* By default Phase-2 hydration in `start()` is gated on
* `environmentId === undefined`, because the original multi-environment
* model assumed project kernels source metadata from a remote artifact /
* control-plane proxy and have NO local `sys_metadata` to read. That is
* NOT true for an isolated, proxy-free project kernel that persists its
* OWN `sys_metadata` locally (e.g. the cloud single-env tenant runtime on
* Turso): objects CREATED AT RUNTIME there — not present in the boot
* artifact manifest — would otherwise never re-enter the registry after a
* restart, so `registry.getObject(name)` returns nothing for them and any
* registry consumer (the unknown-`$select` guard, hooks, relationships)
* silently degrades.
*
* Set this ONLY when the kernel's registry is per-instance isolated AND
* `sys_metadata` lives on the kernel's own local driver (no control-plane
* proxy) — hydrating a proxied kernel would read the wrong database.
* Safe to leave unset: hydration tolerates a missing table.
*/
hydrateMetadataFromDb?: boolean;
/**
* ADR-0057 LifecycleService tuning. Lifecycle enforcement is a platform
* primitive and defaults ON — objects without a `lifecycle` declaration are
* never touched, so a kernel with no declarations sees zero deletes. Set
* `enabled: false` (or env `OS_LIFECYCLE_DISABLED=1`) to disable the
* periodic sweep entirely; the `lifecycle` service stays registered so
* tooling can still run `sweep()` explicitly.
*/
lifecycle?: {
enabled?: boolean;
sweepIntervalMs?: number;
initialDelayMs?: number;
};
}
export class ObjectQLPlugin implements Plugin {
name = 'com.objectstack.engine.objectql';
type = 'objectql';
version = '1.0.0';
/**
* Schema sync to remote SQL DBs is latency-bound (one round-trip per
* table × 2 phases). Default to 120s instead of the kernel's 30s so
* cold Neon/Turso starts don't get killed mid-sync.
*/
startupTimeout = 120_000;
private ql: ObjectQL | undefined;
private hostContext?: Record<string, any>;
private environmentId?: string;
private skipSchemaSync = false;
/** Serializes reload-time schema syncs so overlapping reloads can't race DDL. */
private reloadSchemaSync: Promise<void> = Promise.resolve();
private hydrateMetadataFromDb = false;
/** Unsubscribe handles for metadata-event subscriptions (ADR-0008 PR-7). */
private metadataUnsubscribes: Array<() => void> = [];
/** ADR-0057 lifecycle enforcement (Reaper/Rotator/Archiver). */
private lifecycleService: LifecycleService | undefined;
private lifecycleOptions: ObjectQLPluginOptions['lifecycle'];
constructor(qlOrOptions?: ObjectQL | ObjectQLPluginOptions, hostContext?: Record<string, any>) {
// Back-compat: legacy callers passed `(ObjectQL, hostContext)` positionally.
if (qlOrOptions instanceof ObjectQL) {
this.ql = qlOrOptions;
this.hostContext = hostContext;
return;
}
// New signature: options bag.
const opts = (qlOrOptions as ObjectQLPluginOptions | undefined) ?? {};
if (opts.ql) {
this.ql = opts.ql;
}
this.hostContext = opts.hostContext ?? hostContext;
this.environmentId = opts.environmentId;
if (typeof opts.startupTimeout === 'number' && opts.startupTimeout > 0) {
this.startupTimeout = opts.startupTimeout;
}
this.skipSchemaSync =
typeof opts.skipSchemaSync === 'boolean'
? opts.skipSchemaSync
: process.env.OS_SKIP_SCHEMA_SYNC === '1';
this.hydrateMetadataFromDb = opts.hydrateMetadataFromDb === true;
this.lifecycleOptions = opts.lifecycle;
}
init = async (ctx: PluginContext) => {
if (!this.ql) {
// Pass kernel logger to engine to avoid creating a separate logger instance
const hostCtx = { ...this.hostContext, logger: ctx.logger };
this.ql = new ObjectQL(hostCtx);
}
// Register as provider for Core Kernel Services
ctx.registerService('objectql', this.ql);
ctx.registerService('data', this.ql); // ObjectQL implements IDataEngine
// Register manifest service for direct app/package registration.
// Plugins call ctx.getService('manifest').register(manifestData)
// instead of the legacy ctx.registerService('app.<id>', manifestData) convention.
const ql = this.ql;
ctx.registerService('manifest', {
register: (manifest: any) => {
ql.registerApp(manifest);
ctx.logger.debug('Manifest registered via manifest service', {
id: manifest.id || manifest.name
});
}
});
ctx.logger.info('ObjectQL engine registered', {
services: ['objectql', 'data', 'manifest'],
});
// Register the metadata-storage objects this engine's own protocol reads
// and writes — `sys_metadata` (loadMetaFromDb / getMetaItems / saveMetaItem),
// its history/audit siblings, and `sys_view_definition`. Doing it here
// guarantees their tables get schema-synced in start() even when no
// MetadataPlugin is present (e.g. standalone "host config" apps, where the
// CLI auto-registers a bare ObjectQLPlugin and nothing else owns these
// tables → "no such table: sys_metadata" on every read).
//
// Gated on `environmentId === undefined` — the SAME condition that gates
// `restoreMetadataFromDb` below: platform / standalone kernels own their
// local sys_metadata, whereas per-project (cloud) kernels source metadata
// from the control plane and must NOT provision these tables locally.
// Definitions live in @objectstack/metadata-core (shared by this protocol
// and the metadata layer's DatabaseLoader). registerApp is idempotent, so
// a MetadataPlugin that also registers them is harmless.
if (this.environmentId === undefined) {
this.ql.registerApp({
id: 'com.objectstack.metadata-objects',
name: 'Metadata Platform Objects',
version: '1.0.0',
type: 'plugin',
scope: 'system',
objects: [
SysMetadataObject,
SysMetadataHistoryObject,
SysMetadataCommitObject,
SysMetadataAuditObject,
SysViewDefinitionObject,
],
});
}
// Register Protocol Implementation
const protocolShim = new ObjectStackProtocolImplementation(
this.ql,
() => ctx.getServices ? ctx.getServices() : new Map(),
this.environmentId,
);
ctx.registerService('protocol', protocolShim);
ctx.logger.info('Protocol service registered');
// ── Runtime-authored hook/action rebind on authoring (#2588, #2605) ──
// The protocol is the ONE choke point every metadata-authoring surface
// funnels through (rest-server PUT /meta, dispatcher, publish-drafts, AI
// builders). When a `hook` or `action` row lands (direct-active save,
// publish) or is deleted, re-sync the authored set so the change is live
// without a restart. Draft saves are skipped — drafts are not live by
// design. Fire-and-forget: a resync failure is logged, never fails the
// write.
if (typeof (protocolShim as any).onMetadataMutation === 'function') {
const unsubscribe = (protocolShim as any).onMetadataMutation(
(evt: { type: string; name: string; state: string }) => {
if (evt?.state === 'draft') return;
if (evt?.type === 'hook') {
void this.resyncAuthoredHooks(ctx).catch((e: any) => {
ctx.logger.warn('[ObjectQLPlugin] authored-hook rebind after mutation failed', {
hook: evt.name,
error: e?.message,
});
});
} else if (evt?.type === 'action' || evt?.type === 'object') {
// `object` rows carry embedded `actions[]`, so an object edit can
// add/remove an authored action too — re-sync on both.
void this.resyncAuthoredActions(ctx).catch((e: any) => {
ctx.logger.warn('[ObjectQLPlugin] authored-action rebind after mutation failed', {
item: evt.name,
error: e?.message,
});
});
}
},
);
this.metadataUnsubscribes.push(unsubscribe);
}
// Register an `analytics` service adapter that maps the dispatcher's
// expected interface (query / getMeta / generateSql) onto the
// protocol shim's `analyticsQuery`. Without this, HttpDispatcher's
// `handleAnalytics` cannot resolve a service and `/api/v1/analytics/*`
// returns ROUTE_NOT_FOUND, even though discovery advertises the route
// (objectql's getDiscovery hardcodes `analytics: enabled:true`). The
// adapter delegates `query` to the cube → engine.aggregate translator
// already implemented in protocol.ts; getMeta/generateSql return a
// structured "not implemented" payload so callers see something
// useful instead of a 500.
ctx.registerService('analytics', {
// Honest capabilities (ADR-0076 D12, #2462): this adapter is a
// deliberate lightweight fallback, not the full analytics engine —
// self-identify so discovery reports it as 'degraded' instead of
// 'available'. AnalyticsServicePlugin replaces this service (via
// ctx.replaceService) with the real engine, which carries no marker.
[SERVICE_SELF_INFO_KEY]: {
status: 'degraded',
handlerReady: true,
message: 'Lightweight ObjectQL analytics fallback — install @objectstack/service-analytics for the full engine',
} satisfies ServiceSelfInfo,
// HttpDispatcher passes the raw POST body (AnalyticsQuery shape:
// `{ cube, measures, dimensions, where?, filters?, ... }`). The
// protocol shim's `analyticsQuery` expects the wrapped envelope
// `{ cube, query }` and destructures `request.query` for dims /
// measures. Reshape here so the destructure resolves to the
// analytics query instead of `undefined` (which caused
// "Cannot read properties of undefined (reading 'dimensions')").
//
// `analyticsQuery` also returns its own `{ success, data: { rows,
// fields } }` envelope. HttpDispatcher wraps service responses
// again with `success(result)`, so without unwrapping here the
// client sees `{success, data:{success, data:{rows, fields}}}` —
// KPI widgets read `data.rows` and silently get nothing. Unwrap
// to the inner `{ rows, fields }` payload so a single wrap from
// the dispatcher yields the canonical shape.
query: async (body: any) => {
const envelope = body && typeof body === 'object' && 'query' in body && 'cube' in body
? body
: { cube: body?.cube, query: body };
const result = await protocolShim.analyticsQuery(envelope);
// Unwrap an inner `{ success, data }` envelope (one level only).
if (result && typeof result === 'object' && 'success' in result && 'data' in result) {
return (result as any).data;
}
return result;
},
getMeta: async () => ({
cubes: [],
message: 'Analytics meta endpoint not implemented by ObjectQL adapter',
}),
generateSql: async (_body: any) => ({
sql: null,
message: 'Analytics SQL generation not implemented by ObjectQL adapter',
}),
});
// ADR-0057: the platform-owned LifecycleService. Registered from the
// engine plugin (not an opt-in capability) so every kernel that has data
// also has lifecycle enforcement — a declared retention that drives no
// sweeper is dead surface (ADR-0049).
this.lifecycleService = new LifecycleService({
getEngine: () => this.ql,
logger: ctx.logger,
// P4 governance: overrides/quotas resolve from the 'lifecycle'
// settings namespace when a SettingsService is present. Lazy per
// sweep — plugin registration order doesn't matter.
getSettings: () => {
try {
return ctx.getService('settings') as never;
} catch {
return undefined;
}
},
...this.lifecycleOptions,
});
ctx.registerService('lifecycle', this.lifecycleService);
}
start = async (ctx: PluginContext) => {
ctx.logger.info('ObjectQL engine starting...');
// Sync from external metadata service (e.g. MetadataPlugin) if available
try {
const metadataService = ctx.getService('metadata') as any;
if (metadataService && typeof metadataService.loadMany === 'function' && this.ql) {
await this.loadMetadataFromService(metadataService, ctx);
}
// ── ADR-0008 PR-7: subscribe to object metadata events so the
// SchemaRegistry cache is invalidated on edits (Studio HMR).
// The metadata service bubbles repo events through its own
// `subscribe(type, cb)` API (PR-6 bridge), so we don't talk
// to the repo directly here — this keeps ObjectQL decoupled
// from the storage backend.
if (metadataService && typeof metadataService.subscribe === 'function' && this.ql) {
this.subscribeToMetadataEvents(metadataService, ctx);
}
} catch (e: any) {
ctx.logger.debug('No external metadata service to sync from');
}
// ── Runtime-authored hook bind (#2588) ───────────────────────────────
// Hooks authored in the Studio live as `sys_metadata` rows, which the
// metadata service's loadMany() above does NOT surface on env-scoped
// kernels (no DatabaseLoader there) — so the boot bind never sees them
// and their bodies never run, even after a restart. Re-bind from the
// rows themselves:
// • at `kernel:ready` — cold-boot coverage, once every plugin has
// registered its packages (so the artifact filter can classify);
// • on `metadata:reloaded` — publish-while-running coverage (the
// runtime dispatcher announces after publishPackageDrafts, #2576),
// mirroring service-automation's flow re-sync.
// Idempotent: the bind fully replaces the 'metadata-service' package
// set, so edited hooks re-bind and deleted hooks tear down.
ctx.hook('kernel:ready', async () => {
await this.resyncAuthoredHooks(ctx);
await this.resyncAuthoredActions(ctx);
// ADR-0057 P4: surface the lifecycle governance namespace in Settings
// (overrides / quotas / growth alerts) when a SettingsService exists.
try {
const settings = ctx.getService('settings') as { registerManifest?: (m: unknown) => void };
settings?.registerManifest?.(lifecycleSettingsManifest);
} catch {
// No settings service — governance stays at declared defaults.
}
});
ctx.hook('metadata:reloaded', async (payload?: unknown) => {
await this.resyncAuthoredHooks(ctx);
await this.resyncAuthoredActions(ctx);
// 15.1 third-party eval: an object added while `os dev` runs was
// invisible until a manual restart. Two gaps compounded:
// 1. MetadataPlugin's artifact reload ingests through
// `manager.register(…, { notify: false })` — one announcement per
// artifact, not per item (#3112) — so the bridge in
// `subscribeToMetadataEvents` never sees the new object and the
// SchemaRegistry never learns it ("Object … is not registered").
// This hook IS that announcement: ingest the reloaded object
// definitions straight off the `metadata:reloaded` payload
// (mirroring the subscribe handler's registerObject call,
// provenance included).
// 2. Tables were only ever created by the boot-time sync — re-run
// the idempotent schema sync after each reload so new objects
// get their DDL immediately. Honors the same opt-out as boot
// (`skipSchemaSync` / OS_SKIP_SCHEMA_SYNC) for deployments that
// manage DDL out-of-band, and serializes through
// `reloadSchemaSync` so overlapping reload events can't race DDL.
this.ingestReloadedObjects(ctx, payload);
if (!this.skipSchemaSync) {
this.reloadSchemaSync = this.reloadSchemaSync.then(async () => {
try {
await this.syncRegisteredSchemas(ctx);
} catch (e: any) {
ctx.logger.warn('[ObjectQLPlugin] reload-time schema sync failed', {
error: e?.message ?? String(e),
});
}
});
await this.reloadSchemaSync;
}
});
// Discover features from Kernel Services
if (ctx.getServices && this.ql) {
const services = ctx.getServices();
for (const [name, service] of services.entries()) {
if (name.startsWith('driver.')) {
// Register Driver
this.ql.registerDriver(service);
ctx.logger.debug('Discovered and registered driver service', { serviceName: name });
}
if (name.startsWith('app.')) {
// Legacy fallback: discover app.* services (DEPRECATED)
ctx.logger.warn(
`[DEPRECATED] Service "${name}" uses legacy app.* convention. ` +
`Migrate to ctx.getService('manifest').register(data).`
);
this.ql.registerApp(service); // service is Manifest
ctx.logger.debug('Discovered and registered app service (legacy)', { serviceName: name });
}
}
// Bridge realtime service from kernel service registry to ObjectQL.
// RealtimeServicePlugin registers as 'realtime' service during init().
// This enables ObjectQL to publish data change events.
try {
const realtimeService = ctx.getService('realtime');
if (realtimeService && typeof realtimeService === 'object' && 'publish' in realtimeService) {
ctx.logger.info('[ObjectQLPlugin] Bridging realtime service to ObjectQL for event publishing');
this.ql.setRealtimeService(realtimeService as any);
}
} catch (e: any) {
ctx.logger.debug('[ObjectQLPlugin] No realtime service found — data events will not be published', {
error: e.message,
});
}
}
// Initialize drivers (calls driver.connect() which sets up persistence)
await this.ql?.init();
// Phase 1: Sync built-in schemas so sys_metadata table exists before reading it.
//
// Cold-start-sensitive runtimes (Cloudflare Containers, Lambda) can
// opt out via `skipSchemaSync` / `OS_SKIP_SCHEMA_SYNC=1`. In that
// mode an out-of-band migration must have already created every
// table; we only assume the DDL is in place and skip straight to
// hydration. This avoids one round-trip per table × N objects on
// every cold boot.
if (this.skipSchemaSync) {
ctx.logger.info('Skipping schema sync (OS_SKIP_SCHEMA_SYNC=1) — assuming DDL is managed out-of-band');
} else {
await this.syncRegisteredSchemas(ctx);
}
// Phase 2: Hydrate SchemaRegistry from sys_metadata (loads custom/template objects).
// Project kernels (environmentId set) USUALLY source metadata from the
// artifact (MetadataPlugin) or a control-plane proxy and have no local
// sys_metadata, so hydration is skipped to avoid querying a table that
// does not exist (or, worse, a proxied remote one). EXCEPTION: an
// isolated, proxy-free project kernel that persists its OWN sys_metadata
// locally (the cloud single-env tenant runtime) opts in via
// `hydrateMetadataFromDb` so objects CREATED AT RUNTIME there re-enter the
// registry after a restart — otherwise registry.getObject() returns
// nothing for them and every registry consumer (the unknown-$select
// guard, hooks, relationships) silently degrades. Safe because each engine
// owns its registry (no cross-kernel leakage) and hydration tolerates a
// missing table.
if (this.environmentId === undefined || this.hydrateMetadataFromDb) {
await this.restoreMetadataFromDb(ctx);
} else {
ctx.logger.info('Project kernel — skipping sys_metadata hydration (metadata sourced from artifact)');
}
// Phase 3: Sync any new schemas that were just hydrated from the DB
// (e.g. CRM objects seeded via template — they must have tables before use).
if (!this.skipSchemaSync) {
await this.syncRegisteredSchemas(ctx);
}
// Bridge all SchemaRegistry objects to metadata service.
//
// `SchemaRegistry` is a process-wide singleton, so project kernels in a
// multi-environment server would otherwise inherit every object ever
// registered by any sibling project. When this plugin was constructed
// with a `environmentId`, the kernel is project-scoped — its
// metadata comes from the artifact (MetadataPlugin) or the
// control-plane proxy, not from local sys_metadata. The bridge would
// only pollute its metadata service with cross-project leakage, so
// skip it in that case.
if (this.environmentId === undefined) {
await this.bridgeObjectsToMetadataService(ctx);
}
// Register built-in audit hooks
this.registerAuditHooks(ctx);
// Tenant isolation is now handled by `@objectstack/plugin-security`
// via the `member_default` permission set's RLS rule
// (`organization_id = current_user.organization_id`, with
// field-existence guards). The legacy hard-coded `tenant_id` filter
// middleware was removed because it (a) collided with the
// SecurityPlugin RLS pipeline and (b) blindly filtered tables that
// don't have a `tenant_id` column (e.g. `sys_organization`),
// returning 0 rows instead of all rows.
ctx.logger.info('ObjectQL engine started', {
driversRegistered: this.ql?.['drivers']?.size || 0,
objectsRegistered: this.ql?.registry?.getAllObjects?.()?.length || 0
});
// ADR-0057: arm the periodic lifecycle sweep once the engine is live.
this.lifecycleService?.start();
}
stop = async (ctx: PluginContext) => {
// ADR-0057: disarm the lifecycle sweep timers.
this.lifecycleService?.stop();
// ADR-0008 PR-7: tear down metadata subscriptions on plugin stop so
// tests don't leak watchers and reloaded plugins don't double-subscribe.
for (const unsub of this.metadataUnsubscribes) {
try { unsub(); } catch (e: any) {
ctx.logger.debug('[ObjectQLPlugin] metadata-event unsubscribe failed', { error: e?.message });
}
}
this.metadataUnsubscribes = [];
}
/**
* Re-register every object definition carried on a `metadata:reloaded`
* payload into the SchemaRegistry. The artifact reload path registers
* items via `MetadataManager.register()`, which does not fire
* `subscribe()` watchers — without this ingest, an object added while the
* server runs never reaches the registry (and therefore can never get a
* table or answer a query). Mirrors `subscribeToMetadataEvents`'s
* registerObject call: provenance comes from the `_packageId` the
* MetadataPlugin stamped during registration (falling back to
* 'metadata-service'), so package attribution stays reload-stable.
* Removed objects are left registered until restart — same lifecycle as
* their tables, which managed drift deliberately never drops.
*/
private ingestReloadedObjects(ctx: PluginContext, payload: unknown): void {
if (!this.ql) return;
const objects = (payload as any)?.metadata?.objects;
if (!Array.isArray(objects) || objects.length === 0) return;
let ingested = 0;
for (const obj of objects) {
const name = (obj as any)?.name;
if (typeof name !== 'string' || name.length === 0) continue;
try {
this.ql.registry.invalidate(name);
this.ql.registry.registerObject(
obj as any,
(obj as any)._packageId ?? 'metadata-service',
(obj as any).namespace,
'own',
);
ingested++;
} catch (e: any) {
ctx.logger.warn('[ObjectQLPlugin] reload object ingest failed', {
name,
error: e?.message,
});
}
}
if (ingested > 0) {
ctx.logger.info('[ObjectQLPlugin] reload ingested object definitions into the registry', {
count: ingested,
});
}
}
/**
* Subscribe to `object` metadata events from the metadata service and
* invalidate the SchemaRegistry merge cache on each event (ADR-0008
* PR-7). For create/update we also re-load the affected object from
* the metadata service so subsequent reads see the new definition;
* for delete we unregister it from every contributing package.
*
* Events are filtered to the canonical `object` type — view/dashboard
* /flow edits go through their own consumers (Studio SSE, REST cache).
*
* Stored unsubscribe handle is invoked from {@link stop}.
*/
private subscribeToMetadataEvents(metadataService: any, ctx: PluginContext) {
const handler = async (evt: any) => {
if (!this.ql) return;
const name: string = evt?.name ?? '';
if (!name) return;
const eventType: 'added' | 'changed' | 'deleted' =
evt?.type === 'added' || evt?.type === 'changed' || evt?.type === 'deleted'
? evt.type
: 'changed';
try {
// Drop the merged-schema cache entry first so any in-flight
// resolveObject() races recompute against the new state.
this.ql.registry.invalidate(name);
if (eventType === 'deleted') {
ctx.logger.info('[ObjectQLPlugin] object metadata deleted — registry invalidated', { name });
return;
}
// Re-fetch the canonical definition from the metadata service.
// The metadata service goes through its loader chain (FS, DB,
// attached repository), so this picks up edits from any source.
const fresh = typeof metadataService.get === 'function'
? await metadataService.get('object', name)
: undefined;
if (fresh && typeof fresh === 'object') {
// Re-register with the original contributor metadata. We use
// 'metadata-service' as packageId to match how the initial
// load enrolls these objects (see `loadMetadataFromService`).
const packageId = (fresh as any)._packageId ?? 'metadata-service';
const namespace = (fresh as any).namespace;
this.ql.registry.registerObject(
fresh as any,
packageId,
namespace,
'own',
);
ctx.logger.info('[ObjectQLPlugin] object metadata updated — registry refreshed', {
name,
packageId,
});
} else {
ctx.logger.debug('[ObjectQLPlugin] object event received but metadata service has no fresh body', { name });
}
} catch (e: any) {
ctx.logger.warn('[ObjectQLPlugin] metadata event handler failed', {
name,
error: e?.message,
});
}
};
const unsub = metadataService.subscribe('object', handler);
if (typeof unsub === 'function') {
this.metadataUnsubscribes.push(unsub);
} else if (unsub && typeof unsub.unsubscribe === 'function') {
// Support `MetadataWatchHandle` style return shape.
this.metadataUnsubscribes.push(() => unsub.unsubscribe());
}
ctx.logger.info('[ObjectQLPlugin] subscribed to object metadata events (ADR-0008 PR-7)');
}
/**
* Register built-in audit hooks for auto-stamping created_by/updated_by
* and fetching previousData for update/delete operations. These are
* declared as canonical `Hook` metadata and bound through the same
* `bindHooksToEngine` path used by `defineStack({ hooks })`, so the
* engine's built-ins flow through the same rails as user code
* (dogfooding the protocol).
*/
private registerAuditHooks(ctx: PluginContext) {
if (!this.ql) return;
const stamp = () => new Date().toISOString();
/**
* Returns true when the resolved object schema declares a field with the
* given name. Audit fields (`created_by`, `updated_by`, `tenant_id`) are
* NOT auto-injected by the SQL driver, so we must only stamp values for
* fields the user has explicitly declared on the object — otherwise the
* driver will issue an INSERT against a column that does not exist in
* the physical table (e.g. `table lead has no column named created_by`).
*
* `created_at`/`updated_at` are unconditional because driver-sql creates
* them as built-in columns on every table.
*/
const hasField = (objectName: string, field: string): boolean => {
try {
const schema: any = this.ql?.getSchema?.(objectName);
if (!schema || typeof schema !== 'object') return false;
const fields = schema.fields;
if (!fields || typeof fields !== 'object') return false;
return Object.prototype.hasOwnProperty.call(fields, field);
} catch {
return false;
}
};
const applyToRecord = (
record: Record<string, any>,
objectName: string,
session: any,
isInsert: boolean,
) => {
const now = stamp();
if (isInsert) {
record.created_at = record.created_at ?? now;
}
record.updated_at = now;
if (session?.userId) {
if (isInsert && hasField(objectName, 'created_by')) {
record.created_by = record.created_by ?? session.userId;
}
if (hasField(objectName, 'updated_by')) {
record.updated_by = session.userId;
}
}
// Stamp the driver-layer `tenant_id` column from the caller's active org.
// The hook session exposes it as `organizationId` (the `session.tenantId`
// alias was removed in v11, #3290); the column name is a separate axis.
if (isInsert && session?.organizationId && hasField(objectName, 'tenant_id')) {
record.tenant_id = record.tenant_id ?? session.organizationId;
}
};
const stampData = (
data: unknown,
objectName: string,
session: any,
isInsert: boolean,
) => {
if (Array.isArray(data)) {
for (const row of data) {
if (row && typeof row === 'object') {
applyToRecord(row as Record<string, any>, objectName, session, isInsert);
}
}
} else if (data && typeof data === 'object') {
applyToRecord(data as Record<string, any>, objectName, session, isInsert);
}
};
const builtinHooks: any[] = [
{
name: 'sys_stamp_audit_insert',
object: '*',
events: ['beforeInsert'],
priority: 10,
description: 'Auto-stamp created_by / updated_by / created_at / updated_at / tenant_id on insert (only when the field exists on the object schema)',
handler: async (hookCtx: any) => {
if (hookCtx.input?.data) {
stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, true);
}
},
},
{
name: 'sys_stamp_audit_update',
object: '*',
events: ['beforeUpdate'],
priority: 10,
description: 'Auto-stamp updated_by / updated_at on update (only when the field exists on the object schema)',
handler: async (hookCtx: any) => {
if (hookCtx.input?.data) {
stampData(hookCtx.input.data, hookCtx.object, hookCtx.session, false);
}
},
},
{
name: 'sys_fetch_previous_update',
object: '*',
events: ['beforeUpdate'],
priority: 5,
description: 'Auto-fetch the previous record for update hooks',
handler: async (hookCtx: any) => {
if (hookCtx.input?.id && !hookCtx.previous) {
try {
const existing = await this.ql!.findOne(hookCtx.object, {
where: { id: hookCtx.input.id },
context: {
positions: [],
permissions: [],
isSystem: true,
...(hookCtx.transaction ? { transaction: hookCtx.transaction } : {}),
} as any,
});
if (existing) hookCtx.previous = existing;
} catch (_e) {
// Non-fatal: some objects may not support findOne
}
}
},
},
{
name: 'sys_fetch_previous_delete',
object: '*',
events: ['beforeDelete'],
priority: 5,
description: 'Auto-fetch the previous record for delete hooks',
handler: async (hookCtx: any) => {
if (hookCtx.input?.id && !hookCtx.previous) {
try {
const existing = await this.ql!.findOne(hookCtx.object, {
where: { id: hookCtx.input.id },
context: {
positions: [],
permissions: [],
isSystem: true,
...(hookCtx.transaction ? { transaction: hookCtx.transaction } : {}),
} as any,
});
if (existing) hookCtx.previous = existing;
} catch (_e) {
// Non-fatal
}
}
},
},
];
if (typeof (this.ql as any).bindHooks === 'function') {
(this.ql as any).bindHooks(builtinHooks, { packageId: 'sys:audit' });
} else {
// Defensive fallback if binder isn't available (older builds).
for (const h of builtinHooks) {
for (const event of h.events) {
this.ql.registerHook(event, h.handler, {
object: h.object,
priority: h.priority,
packageId: 'sys:audit',
});
}
}
}
ctx.logger.debug('Audit hooks registered via binder (created_by/updated_by, previousData)');
}
/**
* Tenant isolation moved to `@objectstack/plugin-security`'s
* `member_default` permission set RLS
* (`organization_id = current_user.organization_id`, with
* field-existence guards). The legacy `registerTenantMiddleware`
* method was removed because it (a) collided with SecurityPlugin's
* RLS pipeline and (b) blindly filtered tables that don't have a
* `tenant_id` column (e.g. `sys_organization`), returning 0 rows
* instead of all rows.
*/
/**
* Synchronize all registered object schemas to the database.
*
* Groups objects by their responsible driver, then:
* - If the driver advertises `supports.batchSchemaSync` and implements
* `syncSchemasBatch()`, submits all schemas in a single call (reducing
* network round-trips for remote drivers like Turso).
* - Otherwise falls back to sequential `syncSchema()` per object.
*
* This is idempotent — drivers must tolerate repeated calls without
* duplicating tables or erroring out.
*
* Drivers that do not implement `syncSchema` are silently skipped.
*/
private async syncRegisteredSchemas(ctx: PluginContext) {
if (!this.ql) return;
const allObjects = this.ql.registry?.getAllObjects?.() ?? [];
if (allObjects.length === 0) return;
let synced = 0;
let skipped = 0;
// Group objects by driver for potential batch optimization
const driverGroups = new Map<any, Array<{ obj: any; tableName: string }>>();
for (const obj of allObjects) {
const driver = this.ql.getDriverForObject(obj.name);
if (!driver) {
ctx.logger.debug('No driver available for object, skipping schema sync', {
object: obj.name,
});
skipped++;
continue;
}
// Federated (external) objects (ADR-0015): their schema is owned by the
// remote database, so DDL (syncSchema/initObjects) is forbidden and would
// throw. Register read metadata (physical remote table + coercion maps)
// without DDL so the query path resolves to the remote table, then skip
// the DDL grouping below.
if (obj.external != null) {
if (typeof driver.registerExternalObject === 'function') {
try {
await driver.registerExternalObject(obj);
synced++;
} catch (e: unknown) {
ctx.logger.warn('Failed to register external object metadata', {
object: obj.name,
driver: driver.name,
error: e instanceof Error ? e.message : String(e),
});
}
} else {
ctx.logger.debug('Driver does not support registerExternalObject, skipping external object', {
object: obj.name,
driver: driver.name,
});
skipped++;
}
continue;
}
if (typeof driver.syncSchema !== 'function') {
ctx.logger.debug('Driver does not support syncSchema, skipping', {
object: obj.name,
driver: driver.name,
});
skipped++;
continue;
}
const tableName = StorageNameMapping.resolveTableName(obj);
let group = driverGroups.get(driver);
if (!group) {
group = [];
driverGroups.set(driver, group);
}
group.push({ obj, tableName });
}
// Process each driver group
for (const [driver, entries] of driverGroups) {
// Batch path: driver supports batch schema sync
if (
driver.supports?.batchSchemaSync &&
typeof driver.syncSchemasBatch === 'function'
) {
const batchPayload = entries.map((e) => ({
object: e.tableName,
schema: e.obj,
}));
try {
await driver.syncSchemasBatch(batchPayload);
synced += entries.length;
ctx.logger.debug('Batch schema sync succeeded', {
driver: driver.name,
count: entries.length,
});
} catch (e: unknown) {
ctx.logger.warn('Batch schema sync failed, falling back to sequential', {
driver: driver.name,
error: e instanceof Error ? e.message : String(e),
});
// Fallback: sequential sync for this driver's objects
for (const { obj, tableName } of entries) {
try {
await driver.syncSchema(tableName, obj);
synced++;
} catch (seqErr: unknown) {
ctx.logger.warn('Failed to sync schema for object', {
object: obj.name,
tableName,
driver: driver.name,
error: seqErr instanceof Error ? seqErr.message : String(seqErr),
});
}
}
}
} else {
// Sequential path: no batch support
for (const { obj, tableName } of entries) {
try {
await driver.syncSchema(tableName, obj);
synced++;
} catch (e: unknown) {
ctx.logger.warn('Failed to sync schema for object', {
object: obj.name,
tableName,
driver: driver.name,
error: e instanceof Error ? e.message : String(e),
});
}
}
}