-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathapp-plugin.ts
More file actions
1264 lines (1196 loc) · 62.3 KB
/
Copy pathapp-plugin.ts
File metadata and controls
1264 lines (1196 loc) · 62.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 { Plugin, PluginContext, wireAuthoredTranslationSync } from '@objectstack/core';
import { assertProtocolCompat } from '@objectstack/metadata-core';
import { resolveMultiOrgEnabled } from '@objectstack/types';
import { SeedLoaderService } from './seed-loader.js';
import { loadDisabledPackageIds } from './package-state-store.js';
import type { IMetadataService, II18nService } from '@objectstack/spec/contracts';
import { QuickJSScriptRunner } from './sandbox/quickjs-runner.js';
import { hookBodyRunnerFactory, actionBodyRunnerFactory } from './sandbox/body-runner.js';
import { countServerTiming } from '@objectstack/observability';
/**
* Optional per-project context attached when AppPlugin is instantiated by the
* project kernel factory. Required for the `app:registered` / `app:unregistered`
* hooks that drive the org-scoped `sys_app` catalog. Standalone (single-tenant)
* usages may omit this — no catalog hooks are emitted in that case.
*/
export interface AppPluginProjectContext {
environmentId: string;
organizationId: string;
projectName?: string;
/** When the app comes from a package installation, the source package id. */
packageId?: string;
/** Defaults to 'package' when packageId is set, otherwise 'user'. */
source?: 'package' | 'user';
}
/**
* AppPlugin
*
* Adapts a generic App Bundle (Manifest + Runtime Code) into a Kernel Plugin.
*
* Responsibilities:
* 1. Register App Manifest as a service (for ObjectQL discovery)
* 2. Execute Runtime `onEnable` hook (for code logic)
* 3. Auto-load i18n translation bundles into the kernel's i18n service
*/
export class AppPlugin implements Plugin {
name: string;
type = 'app';
version?: string;
private bundle: any;
private projectContext?: AppPluginProjectContext;
/** When true, init/start become no-ops — env has no app payload. */
private readonly empty: boolean = false;
constructor(bundle: any, projectContext?: AppPluginProjectContext) {
this.bundle = bundle;
this.projectContext = projectContext;
// Support both direct manifest (legacy) and Stack Definition (nested manifest)
const sys = bundle?.manifest || bundle;
const appId = sys?.id || sys?.name;
if (!appId) {
// No app id at all. Two scenarios:
// (a) Empty environment — the artifact only ships the bootstrap
// envelope ({ manifest: { plugins, drivers, engines }, functions: [] })
// with no app categories. We must NOT crash kernel boot
// here, otherwise every brand-new env returns 500.
// (b) Malformed envelope where an app payload exists but the
// caller forgot to pass `manifest`. We throw loudly with
// diagnostics so the bug surfaces immediately.
// App-category keys that indicate "this bundle was supposed to
// register an app". `manifest`/`functions` are envelope-level
// wrappers and don't count.
const APP_CATEGORY_KEYS = [
'objects', 'views', 'apps', 'pages', 'dashboards', 'reports',
'flows', 'workflows', 'triggers', 'agents', 'tools', 'skills',
'actions', 'permissions', 'positions', 'translations',
'sharingRules', 'ragPipelines', 'data', 'emailTemplates',
'docs', 'books',
];
const hasAppPayload = APP_CATEGORY_KEYS.some((k) => {
const v = (bundle && bundle[k]) ?? (sys && sys[k]);
return Array.isArray(v) && v.length > 0;
});
if (!hasAppPayload) {
// Empty env — degrade to a no-op plugin so kernel boot
// succeeds. Auth / data routes will still work; there's
// simply nothing to register.
this.empty = true;
const envSlug = projectContext?.environmentId
? projectContext.environmentId.slice(0, 8)
: 'empty';
this.name = `plugin.app.empty-${envSlug}`;
return;
}
// Has app payload but no id — genuine malformed envelope.
const bundleKeys = bundle && typeof bundle === 'object'
? Object.keys(bundle).slice(0, 20).join(',')
: typeof bundle;
const sysKeys = sys && typeof sys === 'object'
? Object.keys(sys).slice(0, 20).join(',')
: typeof sys;
const ctxHint = projectContext
? ` projectContext=${JSON.stringify({
environmentId: projectContext.environmentId,
packageId: projectContext.packageId,
source: projectContext.source,
})}`
: '';
throw new Error(
`[AppPlugin] bundle has app payload but no manifest.id / manifest.name — `
+ `cannot register as a plugin. bundleKeys=[${bundleKeys}] `
+ `sysKeys=[${sysKeys}]${ctxHint}`,
);
}
this.name = `plugin.app.${appId}`;
this.version = sys?.version;
}
init = async (ctx: PluginContext) => {
// Install the engine-wide default hook body runner FIRST — even for
// empty envs (an empty env is exactly where a user will author their
// first Studio hook). Runs in init (Phase 1) so it is in place before
// ObjectQLPlugin.start binds metadata-service hooks in Phase 2 (#2588).
this.installDefaultHookBodyRunner(ctx);
// Same for the action runner — authored actions register in Phase 2's
// authored-action re-sync and need the sandbox bridge in place (#2605).
this.installDefaultActionBodyRunner(ctx);
// Feed per-hook execution time into the request-scoped perf collector
// so the `Server-Timing` header can split "hook time" from "DB time".
// Same boot point as the runners so it is in place before Phase 2 binds
// metadata-service hooks; a no-op unless perf-tuning is on.
this.installHookMetricsTiming(ctx);
// Wire the authored-translation sync (#2591) — also BEFORE the empty-env
// return: an empty env is exactly where a user authors their first
// Studio translation. Covers whatever `i18n` service this kernel ends
// up with (the core in-memory fallback included); idempotent across
// multiple wirers via the ownership marker in core.
wireAuthoredTranslationSync(ctx as any);
if (this.empty) {
ctx.logger.debug('[AppPlugin] empty env — no app payload, skipping init', {
pluginName: this.name,
});
return;
}
const sys = this.bundle.manifest || this.bundle;
const appId = sys.id || sys.name;
// ADR-0087 D1 — protocol handshake on the code-defined-stack LOAD seam,
// BEFORE the manifest is decomposed into the registry. A bundle whose
// declared `engines.protocol` excludes this runtime's major fails boot
// fast with the structured OS_PROTOCOL_INCOMPATIBLE diagnostic (naming
// the `migrate meta` command) instead of crashing later in a schema
// `.parse()` or renderer contract. Absent/unparsable ranges are admitted
// with a warning (grandfathering; never a false rejection).
assertProtocolCompat(sys, undefined, (m) => ctx.logger.warn(`[AppPlugin] ${m}`));
ctx.logger.info('Registering App Service', {
appId,
pluginName: this.name,
version: this.version
});
// Register the app manifest directly via the manifest service.
// This immediately decomposes the manifest into SchemaRegistry entries.
const servicePayload = this.bundle.manifest
? { ...this.bundle.manifest, ...this.bundle }
: this.bundle;
// Seed persisted package disable-state into the registry BEFORE the
// manifest is decomposed, so disabled packages are installed disabled
// and stay hidden after restart. Honors every later registration path
// (boot artifact, marketplace rehydrate, import) via the registry's
// initial-disabled set. Best-effort — never block boot on this.
try {
const ql = ctx.getService<{ registry?: { setInitialDisabledPackageIds?: (ids: Iterable<string>) => void } }>('objectql');
const setter = ql?.registry?.setInitialDisabledPackageIds;
if (typeof setter === 'function') {
const disabled = loadDisabledPackageIds(this.projectContext?.environmentId);
if (disabled.size > 0) {
setter.call(ql!.registry, disabled);
ctx.logger.info('[AppPlugin] seeded persisted disabled packages', {
environmentId: this.projectContext?.environmentId,
disabled: Array.from(disabled),
});
}
}
} catch (err) {
ctx.logger.warn('[AppPlugin] failed to seed persisted package state', {
error: (err as Error)?.message ?? String(err),
});
}
ctx.getService<{ register(m: any): void }>('manifest').register(servicePayload);
}
/**
* Install the engine's DEFAULT hook body runner (`engine.setDefaultBodyRunner`).
*
* Hooks authored at runtime (Studio → `protocol.saveMetaItem` → publish)
* bind through paths that pass no explicit `bodyRunner` — notably
* ObjectQLPlugin's metadata-service bind — so without this default their
* L1/L2 `body` is silently dropped by `bindHooksToEngine` and the hook
* never runs (#2588). The runtime owns the sandbox bridge (objectql stays
* sandbox-free), so this is the boot point that wires it: same
* QuickJS-sandboxed, capability-gated runner the `defineStack({ hooks })`
* bind already uses.
*
* `OS_DISABLE_AUTHORED_HOOKS=1` opts out for deployments that want
* runtime-authored (DB-stored, non-code-reviewed) hook bodies to stay
* inert; code-shipped hooks are unaffected (AppPlugin passes its own
* runner explicitly).
*
* Idempotent: the first AppPlugin to run installs it; the runner is
* bundle-agnostic (it only closes over the engine + logger).
*/
private installDefaultHookBodyRunner(ctx: PluginContext): void {
if (process.env.OS_DISABLE_AUTHORED_HOOKS === '1') {
ctx.logger.info('[AppPlugin] OS_DISABLE_AUTHORED_HOOKS=1 — runtime-authored hook bodies will not execute');
return;
}
let ql: any;
try {
ql = ctx.getService('objectql');
} catch {
return; // no engine on this kernel — nothing to wire
}
if (!ql || typeof ql.setDefaultBodyRunner !== 'function') return;
if (ql._defaultBodyRunner) return; // another AppPlugin already installed one
ql.setDefaultBodyRunner(hookBodyRunnerFactory(new QuickJSScriptRunner(), {
ql,
logger: ctx.logger,
appId: 'runtime-authored',
}));
ctx.logger.info('[AppPlugin] Installed default hook body runner (runtime-authored hooks can execute)');
}
/**
* Install the engine's DEFAULT action body runner (`engine.setDefaultActionRunner`).
*
* The exact action-path parallel of {@link installDefaultHookBodyRunner}
* (#2605 item 1): actions authored at runtime (Studio → `action` metadata →
* publish) are registered by ObjectQLPlugin's authored-action re-sync,
* which lives in `objectql` and therefore has no sandbox of its own. This
* boot point hands it the same QuickJS-sandboxed runner that
* `defineStack({ actions })` bundles already execute through, so an
* authored `body` becomes a real `executeAction` handler instead of a
* silent "Action not found".
*
* `OS_DISABLE_AUTHORED_ACTIONS=1` opts out for deployments that want
* runtime-authored (DB-stored, non-code-reviewed) action bodies to stay
* inert; code-shipped actions are unaffected (AppPlugin registers those
* itself with its own runner).
*/
private installDefaultActionBodyRunner(ctx: PluginContext): void {
if (process.env.OS_DISABLE_AUTHORED_ACTIONS === '1') {
ctx.logger.info('[AppPlugin] OS_DISABLE_AUTHORED_ACTIONS=1 — runtime-authored action bodies will not execute');
return;
}
let ql: any;
try {
ql = ctx.getService('objectql');
} catch {
return; // no engine on this kernel — nothing to wire
}
if (!ql || typeof ql.setDefaultActionRunner !== 'function') return;
if (ql._defaultActionRunner) return; // another AppPlugin already installed one
ql.setDefaultActionRunner(actionBodyRunnerFactory(new QuickJSScriptRunner(), {
ql,
logger: ctx.logger,
appId: 'runtime-authored',
}));
ctx.logger.info('[AppPlugin] Installed default action body runner (runtime-authored actions can execute)');
}
/**
* Install an engine-wide {@link HookMetricsRecorder} that folds every
* hook's execution time into the request-scoped `Server-Timing` collector
* (the `hooks;dur=…;desc="N hooks"` span). This is the framework's ONLY
* caller of `setHookMetricsRecorder`, so it owns the engine's recorder;
* objectql stays observability-free (the lean `core` tier, ADR-0076) — the
* timing lives here in the runtime, which already depends on it.
*
* `countServerTiming` is a no-op unless a request opened a perf collector
* (perf-tuning mode), so this costs nothing when the feature is off. It
* composes with any recorder a host wired earlier (chains to it), and is
* idempotent across the multiple AppPlugins a multi-app env installs.
*/
private installHookMetricsTiming(ctx: PluginContext): void {
let ql: any;
try {
ql = ctx.getService('objectql');
} catch {
return; // no engine on this kernel — nothing to wire
}
if (!ql || typeof ql.setHookMetricsRecorder !== 'function') return;
const existing = typeof ql.getHookMetricsRecorder === 'function'
? ql.getHookMetricsRecorder()
: undefined;
if (existing?.__perfTimingFeed) return; // already installed by a sibling AppPlugin
ql.setHookMetricsRecorder({
__perfTimingFeed: true,
recordExecution(label: any, outcome: any, durationMs: number) {
try { existing?.recordExecution?.(label, outcome, durationMs); } catch { /* keep timing isolated */ }
countServerTiming('hooks', durationMs, 'hooks');
},
recordSkip(label: any, reason: any) {
try { existing?.recordSkip?.(label, reason); } catch { /* noop */ }
},
recordRetry(label: any, attempt: number) {
try { existing?.recordRetry?.(label, attempt); } catch { /* noop */ }
},
});
ctx.logger.debug('[AppPlugin] Installed hook-metrics Server-Timing feed');
}
start = async (ctx: PluginContext) => {
if (this.empty) {
ctx.logger.debug('[AppPlugin] empty env — no app payload, skipping start', {
pluginName: this.name,
});
return;
}
const sys = this.bundle.manifest || this.bundle;
const appId = sys.id || sys.name;
// Execute Runtime Step
// Retrieve ObjectQL engine from services
// ctx.getService throws when a service is not registered, so we
// must use try/catch instead of a null-check.
let ql: any;
try {
ql = ctx.getService('objectql');
} catch {
// Service not registered — handled below
}
if (!ql) {
ctx.logger.warn('ObjectQL engine service not found', {
appName: this.name,
appId
});
return;
}
ctx.logger.debug('Retrieved ObjectQL engine service', { appId });
// Configure datasourceMapping if provided in the stack definition
if (this.bundle.datasourceMapping && Array.isArray(this.bundle.datasourceMapping)) {
ctx.logger.info('Configuring datasource mapping rules', {
appId,
ruleCount: this.bundle.datasourceMapping.length
});
ql.setDatasourceMapping(this.bundle.datasourceMapping);
}
// Surface code-defined datasources (ADR-0015 Addendum) in the metadata
// registry so the datasource-admin list returns them alongside any
// UI-created (`origin:'runtime'`) ones. These are GitOps-managed
// (declared in `*.datasource.ts`), so they are registered IN MEMORY
// ONLY — never persisted to the runtime DB store — and stamped
// `origin:'code'` so the admin service enforces them as read-only.
// The engine already indexed them for the write gate via registerApp().
try {
const dsDefs = this.bundle.datasources;
const dsList = Array.isArray(dsDefs)
? dsDefs
: dsDefs && typeof dsDefs === 'object'
? Object.entries(dsDefs).map(([name, def]) => ({ name, ...(def as any) }))
: [];
if (dsList.length > 0) {
const metadata = ctx.getService('metadata') as
| { registerInMemory?: (t: string, n: string, d: unknown) => void }
| undefined;
if (typeof metadata?.registerInMemory === 'function') {
for (const ds of dsList) {
if (!ds?.name) continue;
metadata.registerInMemory('datasource', ds.name, { ...ds, origin: 'code' });
}
ctx.logger.info('Registered code-defined datasources in metadata registry', {
appId,
count: dsList.length,
});
}
}
} catch (err) {
ctx.logger.warn('[AppPlugin] failed to register code-defined datasources', {
error: (err as Error)?.message ?? String(err),
});
}
// Auto-connect declared datasources (ADR-0062 D1/D2/D5). The metadata
// registration above only makes a datasource *visible*; to make its
// federated objects *queryable* with zero app boilerplate, build + open
// + register a live driver via the shared `'datasource-connection'`
// service (when present — wired by the datasource-admin plugin). The
// service applies the D2 gate (connect only when `external`, an object
// explicitly binds via `object.datasource`, or `autoConnect:true`) and
// the host connect policy, so managed+unrouted datasources stay
// metadata-only (e.g. app-crm's `:memory:` datasources — byte-for-byte
// unchanged). Idempotent vs. a legacy `onEnable` driver registration.
//
// Runs in `start()` (before the `kernel:ready` external-validation gate)
// so the kernel's init-all-then-start-all ordering guarantees the
// connection service was already registered during init.
try {
const dsDefs = this.bundle.datasources;
const dsList: any[] = Array.isArray(dsDefs)
? dsDefs
: dsDefs && typeof dsDefs === 'object'
? Object.entries(dsDefs).map(([name, def]) => ({ name, ...(def as any) }))
: [];
if (dsList.length > 0) {
// `ctx.getService` throws when a service is absent, so resolve
// defensively — a runtime without the datasource-admin plugin
// simply has no connection service, and declared datasources
// stay metadata-only (the legacy `onEnable` escape hatch still
// works). This must NOT fall into the fail-fast catch below.
let connection:
| {
connectDeclared?: (input: {
datasources: any[];
objects?: Array<{ name?: string; datasource?: string }>;
}) => Promise<Array<{ name: string; status: string }>>;
}
| undefined;
try {
connection = ctx.getService('datasource-connection');
} catch {
connection = undefined;
}
if (typeof connection?.connectDeclared === 'function') {
const objects = Array.isArray(this.bundle.objects) ? this.bundle.objects : [];
const results = await connection.connectDeclared({ datasources: dsList, objects });
const connected = results.filter((r) => r.status === 'connected');
if (connected.length > 0) {
ctx.logger.info('Auto-connected declared datasources', {
appId,
connected: connected.map((r) => r.name),
});
}
} else {
ctx.logger.debug('No datasource-connection service — declared datasources stay metadata-only', { appId });
}
}
} catch (err) {
// A fail-fast (external + onMismatch:'fail') connect error propagates
// to brick boot as intended (ADR-0062 D5); other errors are already
// degraded inside the connection service. Re-throw so the kernel
// surfaces the real cause. (Single-string message: the context
// logger types `error(message, error?)`, not a meta object.)
ctx.logger.error(
`[AppPlugin] declared-datasource auto-connect failed for app '${appId}': ${(err as Error)?.message ?? String(err)}`,
);
throw err;
}
// [ADR-0057 / #2077] Surface stack-declared SECURITY metadata
// (positions, permission sets, sharing rules, policies) in the
// metadata registry so the boot seeders (plugin-security /
// plugin-sharing) and runtime resolvers can read them via
// `list('position'|'permission'|'sharing_rule')`.
// Without this, bootStack's metadata service holds only objects (the
// artifact loader that registers these runs only in compiled serve.ts),
// leaving the declarations decorative.
try {
const metadata = ctx.getService('metadata') as
| { registerInMemory?: (t: string, n: string, d: unknown) => void }
| undefined;
if (typeof metadata?.registerInMemory === 'function') {
const securityBundle: any = this.bundle.manifest
? { ...this.bundle.manifest, ...this.bundle }
: this.bundle;
const SECURITY_FIELDS: Array<[string, string]> = [
['positions', 'position'],
['permissions', 'permission'],
// [ADR-0066 D1] Package-declared authorization capabilities —
// read back by bootstrapDeclaredCapabilities to seed
// sys_capability with package provenance.
['capabilities', 'capability'],
['sharingRules', 'sharing_rule'],
['policies', 'policy'],
];
let count = 0;
for (const [field, type] of SECURITY_FIELDS) {
const arr = securityBundle?.[field];
if (!Array.isArray(arr)) continue;
for (const item of arr) {
if (!item?.name) continue;
metadata.registerInMemory(type, item.name, item);
count += 1;
}
}
if (count > 0) {
ctx.logger.info('Registered stack-declared security metadata', { appId, count });
}
}
} catch (err) {
ctx.logger.warn('[AppPlugin] failed to register security metadata', {
error: (err as Error)?.message ?? String(err),
});
}
// Resolve the runtime hook owner. Modules that declare both a
// `default` (defineStack(...)) export and a named `onEnable` export
// hide the named export from `bundle.default`, so we fall back to the
// top-level bundle when the default doesn't carry the hook.
const stackBundle = this.bundle.default || this.bundle;
const runtime: any = (stackBundle && typeof stackBundle.onEnable === 'function')
? stackBundle
: this.bundle;
if (runtime && typeof runtime.onEnable === 'function') {
ctx.logger.info('Executing runtime.onEnable', {
appName: this.name,
appId
});
// Construct the Host Context (mirroring old ObjectQL.use logic)
const hostContext = {
...ctx,
ql,
logger: ctx.logger,
drivers: {
register: (driver: any) => {
ctx.logger.debug('Registering driver via app runtime', {
driverName: driver.name,
appId
});
ql.registerDriver(driver);
}
},
};
await runtime.onEnable(hostContext);
ctx.logger.debug('Runtime.onEnable completed', { appId });
} else {
ctx.logger.debug('No runtime.onEnable function found', { appId });
}
// ── Auto-bind declarative Hook metadata ─────────────────────────
// Hooks declared via `defineStack({ hooks })` (or attached to the
// bundle by other tooling) are wired into the ObjectQL execution
// pipeline here, with no boilerplate from user code. Inline
// function handlers are resolved directly; string-named handlers
// are looked up in `bundle.functions` (also auto-registered) or in
// any function previously registered on the engine.
//
// Runs AFTER `runtime.onEnable` so user code may still
// imperatively register additional hooks/functions for advanced
// cases — both will coexist on the engine.
try {
const hooks = collectBundleHooks(this.bundle);
const functions = collectBundleFunctions(this.bundle);
if (hooks.length > 0 || Object.keys(functions).length > 0) {
if (typeof ql.bindHooks === 'function') {
ql.bindHooks(hooks, {
packageId: `app:${appId}`,
functions,
bodyRunner: hookBodyRunnerFactory(new QuickJSScriptRunner(), {
ql,
logger: ctx.logger,
appId,
}),
});
ctx.logger.info('[AppPlugin] Bound declarative hooks', {
appId,
hookCount: hooks.length,
functionCount: Object.keys(functions).length,
});
} else {
ctx.logger.warn('[AppPlugin] ql.bindHooks unavailable; declarative hooks ignored', {
appId,
hookCount: hooks.length,
});
}
}
} catch (err: any) {
ctx.logger.error('[AppPlugin] Failed to bind declarative hooks', err as Error, {
appId,
});
}
// ── Auto-register declarative Action handlers ───────────────────
// Actions with an inline `handler` (or extracted `body`) are wired
// to the engine here so HTTP `POST /api/v1/actions/<obj>/<name>`
// can invoke them. Actions without a body are left for legacy
// imperative `engine.registerAction(...)` registration in user code.
try {
const actions = collectBundleActions(this.bundle);
const actionBodyRunner = actionBodyRunnerFactory(new QuickJSScriptRunner(), {
ql,
logger: ctx.logger,
appId,
});
let registered = 0;
if (actions.length > 0 && typeof ql.registerAction === 'function') {
for (const action of actions) {
const handler = actionBodyRunner(action);
if (!handler) continue;
const objectKey =
typeof action.object === 'string' && action.object.length > 0
? action.object
: 'global';
try {
ql.registerAction(objectKey, action.name, handler, `app:${appId}`);
registered++;
} catch (err: any) {
ctx.logger.warn('[AppPlugin] Failed to register action body', {
appId,
action: action.name,
object: objectKey,
error: err?.message ?? String(err),
});
}
}
}
if (registered > 0) {
ctx.logger.info('[AppPlugin] Bound declarative actions', {
appId,
actionCount: registered,
});
}
} catch (err: any) {
ctx.logger.error('[AppPlugin] Failed to bind declarative actions', err as Error, {
appId,
});
}
// ── Auto-register declarative Background Jobs ────────────────────
// Jobs declared via `defineStack({ jobs })` are scheduled against the
// running `IJobService` on `kernel:ready` (so the service plugin and
// ObjectQL engine have had a chance to register). Handler strings are
// resolved through `collectBundleFunctions(bundle)` — the same
// registry used by hooks/actions, keeping the surface uniform.
try {
const jobs: any[] = Array.isArray(this.bundle.jobs)
? this.bundle.jobs
: Array.isArray((this.bundle.manifest || {}).jobs)
? (this.bundle.manifest as any).jobs
: [];
if (jobs.length > 0) {
ctx.hook('kernel:ready', async () => {
let svc: any;
try { svc = ctx.getService('job'); } catch { /* not installed */ }
if (!svc || typeof svc.schedule !== 'function') {
ctx.logger.warn('[AppPlugin] job service not registered — skipping declarative jobs', {
appId, jobCount: jobs.length,
});
return;
}
const fnMap = collectBundleFunctions(this.bundle);
let ok = 0;
for (const job of jobs) {
const jobName: string = job?.name;
if (!jobName) {
ctx.logger.warn('[AppPlugin] skipping job without name', { appId, job });
continue;
}
if (job.enabled === false) {
ctx.logger.debug('[AppPlugin] job disabled — skipping', { appId, job: jobName });
continue;
}
const handler = fnMap[job.handler];
if (typeof handler !== 'function') {
ctx.logger.warn('[AppPlugin] job handler not found in bundle.functions — skipping', {
appId, job: jobName, handler: job.handler,
});
continue;
}
try {
await svc.schedule(
jobName,
job.schedule,
async (jobCtx: any) => {
await handler({ ...jobCtx, jobId: jobName, bundle: this.bundle });
},
);
ok++;
} catch (err: any) {
ctx.logger.warn('[AppPlugin] Failed to schedule job', {
appId, job: jobName, error: err?.message ?? String(err),
});
}
}
ctx.logger.info('[AppPlugin] Scheduled background jobs', { appId, count: ok });
});
}
} catch (err: any) {
ctx.logger.error('[AppPlugin] Failed to schedule background-job registration', err as Error, { appId });
}
// ── Org-Scoped App Catalog Sync ──────────────────────────────────
// Emit `app:registered` so AppCatalogService (running on the
// control-plane kernel) can mirror this app into `sys_app`. Skipped
// for standalone (single-tenant) usages where no project context is
// attached.
this.emitCatalogEvent(ctx, 'app:registered', sys);
// ── i18n Translation Loading ─────────────────────────────────────
// Auto-load translation bundles from the app config into the
// kernel's i18n service, so discovery and handlers stay consistent.
await this.loadTranslations(ctx, appId);
// Data Seeding
// Collect seed data from multiple locations (top-level `data` preferred, `manifest.data` for backward compat)
const seedDatasets: any[] = [];
// 1. Top-level `data` field (new standard location on ObjectStackDefinition)
if (Array.isArray(this.bundle.data)) {
seedDatasets.push(...this.bundle.data);
}
// 2. Legacy: `manifest.data` (backward compatibility)
const manifest = this.bundle.manifest || this.bundle;
if (manifest && Array.isArray(manifest.data)) {
seedDatasets.push(...manifest.data);
}
// Object names in seed data are used as-is — no FQN expansion.
// Under the current naming convention, the object's short name IS
// the canonical name and the physical table name.
if (seedDatasets.length > 0) {
ctx.logger.info(`[AppPlugin] Found ${seedDatasets.length} seed datasets for ${appId}`);
// Pass seed datasets through unchanged — object names are canonical
const normalizedDatasets = seedDatasets
.filter((d: any) => d.object && Array.isArray(d.records))
.map((d: any) => ({
...d,
object: d.object,
}));
// No seed identity is provisioned. The platform never mints a
// placeholder `usr_system`: seeds leave `owner_id` unset (or use
// `cel`os.user.id``, which the loader resolves to NULL since the
// owning admin does not exist yet), and the first-admin handoff
// (`claimSeedOwnership`) re-owns those NULL rows to the promoted
// admin. `os.org` is still derived from `organizationId` inside the
// loader, independent of this.
const seedIdentity = undefined;
// Stash datasets on a kernel service so SecurityPlugin's
// sys_organization insert hook can replay them per-tenant
// (Salesforce-sandbox style: every new org gets its own
// private copy of the artifact's demo data).
//
// We also register a `seed-replayer` callable so the
// SecurityPlugin doesn't need to import @objectstack/runtime
// (would create a circular workspace dep). The replayer
// captures the SeedLoaderService closure and exposes a
// narrow `(orgId) => Promise<summary>` surface.
try {
const kernel: any = (ctx as any).kernel;
const existing = (() => {
try { return kernel?.getService?.('seed-datasets'); } catch { return undefined; }
})();
const merged = Array.isArray(existing)
? [...existing, ...normalizedDatasets]
: normalizedDatasets;
const registerSvc = (name: string, value: any) => {
if (kernel?.registerService) kernel.registerService(name, value);
else if (typeof (ctx as any).registerService === 'function') (ctx as any).registerService(name, value);
};
registerSvc('seed-datasets', merged);
const metadataNow = ctx.getService('metadata') as IMetadataService | undefined;
const loggerRef = ctx.logger;
const replayer = async (organizationId: string) => {
if (!organizationId) return { inserted: 0, updated: 0, skipped: 0, errors: [] as any[] };
const md = metadataNow ?? (ctx.getService('metadata') as IMetadataService | undefined);
if (!md) {
loggerRef.warn('[seed-replayer] metadata service unavailable');
return { inserted: 0, updated: 0, skipped: 0, errors: [] as any[] };
}
const datasetsNow = (() => {
try { return kernel?.getService?.('seed-datasets'); } catch { return merged; }
})() ?? merged;
if (!Array.isArray(datasetsNow) || datasetsNow.length === 0) {
return { inserted: 0, updated: 0, skipped: 0, errors: [] as any[] };
}
const seedLoader = new SeedLoaderService(ql, md, loggerRef);
const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');
const request = SeedLoaderRequestSchema.parse({
seeds: datasetsNow,
config: {
defaultMode: 'upsert',
multiPass: true,
organizationId,
// `os.org` is derived from organizationId inside
// the loader. `seedIdentity` (os.user) is undefined
// unless a seed embeds `cel`os.user.id`` — see the
// lazy guard where it is resolved.
identity: seedIdentity,
},
});
const result = await seedLoader.load(request);
return {
inserted: result.summary.totalInserted,
updated: result.summary.totalUpdated,
// `skipped` lets a cloud host distinguish an all-skip
// replay (data already present) from the zero-summary
// early-returns above (which never ran the loader), so
// it can stamp its seed-once record on progress rather
// than re-replaying every cold boot (cloud#853).
skipped: result.summary.totalSkipped,
errors: result.errors,
};
};
registerSvc('seed-replayer', replayer);
ctx.logger.info(`[Seeder] Registered ${normalizedDatasets.length} datasets + replayer on kernel (total seeds: ${merged.length})`);
} catch (e: any) {
ctx.logger.warn('[Seeder] Failed to register seed-datasets/seed-replayer service', { error: e?.message });
}
// Decide whether to also run the seed inline at AppPlugin
// start. In multi-tenant mode, the per-org replay (driven
// by OrgScopingPlugin's sys_organization middleware) is the
// source of truth — running it here too would create NULL-
// org rows that pollute reads and need a separate claim
// step. So we skip it. Single-tenant deployments keep the
// legacy behaviour: seed immediately at boot so there's
// always demo data without needing an org insert.
const multiTenant = resolveMultiOrgEnabled();
if (multiTenant) {
ctx.logger.info('[Seeder] multi-tenant mode — skipping inline seed; per-org replay will run on sys_organization insert');
} else {
// Inline seed budget: large bundles (e.g. CRM Starter's 10
// datasets) can easily exceed the kernel's plugin-start
// timeout. We MUST NOT let seed work tear the kernel down —
// a 500 on /auth and /data is far worse than a delayed seed.
// Race the actual seed work against a soft budget; if we run
// out of time, log loudly and let the kernel proceed.
const seedBudgetMs = Number(process.env.OS_INLINE_SEED_BUDGET_MS ?? 8000);
const seedPromise = (async () => {
try {
const metadata = ctx.getService('metadata') as IMetadataService | undefined;
if (metadata) {
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger);
const { SeedLoaderRequestSchema } = await import('@objectstack/spec/data');
const request = SeedLoaderRequestSchema.parse({
seeds: normalizedDatasets,
config: { defaultMode: 'upsert', multiPass: true, identity: seedIdentity },
});
const result = await seedLoader.load(request);
const { totalInserted, totalUpdated, totalSkipped, totalErrored } = result.summary;
if (result.success) {
ctx.logger.info('[Seeder] Seed loading complete', {
inserted: totalInserted,
updated: totalUpdated,
skipped: totalSkipped,
errored: totalErrored,
});
} else {
// LOUD FAILURE: dropped records were previously
// invisible (the summary only logged errors.length and
// omitted totalErrored). Report the count AND each
// actionable reason so broken seeds can't pass silently.
ctx.logger.warn(
`[Seeder] Seed loading completed with ${totalErrored} dropped record(s) and ${result.errors.length} error(s) for ${appId}`,
{
inserted: totalInserted,
updated: totalUpdated,
skipped: totalSkipped,
errored: totalErrored,
},
);
for (const e of result.errors.slice(0, 20)) {
ctx.logger.warn(`[Seeder] ✗ ${e.message}`);
}
if (result.errors.length > 20) {
ctx.logger.warn(`[Seeder] …and ${result.errors.length - 20} more error(s)`);
}
}
} else {
// Fallback: basic insert when metadata service is not available
ctx.logger.debug('[Seeder] No metadata service; using basic insert fallback');
for (const dataset of normalizedDatasets) {
ctx.logger.info(`[Seeder] Seeding ${dataset.records.length} records for ${dataset.object}`);
for (const record of dataset.records) {
try {
await ql.insert(dataset.object, record, { context: { isSystem: true } } as any);
} catch (err: any) {
ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: err.message });
}
}
}
ctx.logger.info('[Seeder] Data seeding complete.');
}
} catch (err: any) {
// If SeedLoaderService fails (e.g., metadata not available), fall back to basic insert
ctx.logger.warn('[Seeder] SeedLoaderService failed, falling back to basic insert', { error: err.message });
for (const dataset of normalizedDatasets) {
for (const record of dataset.records) {
try {
await ql.insert(dataset.object, record, { context: { isSystem: true } } as any);
} catch (insertErr: any) {
ctx.logger.warn(`[Seeder] Failed to insert ${dataset.object} record:`, { error: insertErr.message });
}
}
}
ctx.logger.info('[Seeder] Data seeding complete (fallback).');
}
})();
let timer: ReturnType<typeof setTimeout> | undefined;
const budget = new Promise<'budget'>((resolve) => {
timer = setTimeout(() => resolve('budget'), seedBudgetMs);
});
// Signal seed settle so reconcilers that read seeded rows can
// re-run past this point. plugin-auth's ADR-0093 D6 membership
// backfill runs once on `kernel:ready`, but seeded users are raw
// `engine.insert` into `sys_user` (bypassing better-auth's
// `user.create.after` reconciler). If this seed overruns the
// budget below and finishes in the background — AFTER
// `kernel:ready` — those users would stay member-less until the
// next restart. Emitting on settle lets the backfill re-run (#2996).
const emitSeedSettled = (overBudget: boolean) => {
const trigger = (ctx as any).trigger;
if (typeof trigger !== 'function') return;
try {
const p = trigger.call(ctx, 'app:seeded', { appId, overBudget });
if (p && typeof p.catch === 'function') {
p.catch((err: any) => ctx.logger.debug('[Seeder] app:seeded trigger failed', { appId, error: err?.message ?? String(err) }));
}
} catch (err: any) {
ctx.logger.debug('[Seeder] app:seeded trigger failed', { appId, error: err?.message ?? String(err) });
}
};
const winner = await Promise.race([seedPromise.then(() => 'done' as const), budget]);
if (timer) clearTimeout(timer);
if (winner === 'budget') {
ctx.logger.warn(
`[Seeder] Inline seed exceeded ${seedBudgetMs}ms budget for ${appId}; continuing in background to avoid blocking kernel start.`,
);
// Don't leave the promise unobserved; emit the settle signal
// once the background seed finishes (fires past kernel:ready).
seedPromise
.catch((err: any) => {
ctx.logger.warn('[Seeder] Background seed failed after budget', { appId, error: err?.message ?? String(err) });
})
.then(() => emitSeedSettled(true));
} else {
emitSeedSettled(false);
}
}
}
this.registerHotReloadSeeder(ctx, ql);
}
/**
* 15.1 third-party eval — dev hot-reload of a NEW object registered its
* metadata (and, via ObjectQL's `metadata:reloaded` hook, created its
* table) but its seeds never ran: the seed pipeline in `start()` only
* reads the boot-time bundle, so `os dev` users had to restart the
* server to get seed rows. Subscribe to `metadata:reloaded` (fired by
* MetadataPlugin for both the artifact-file watcher and the HMR POST
* endpoint; its payload carries the freshly parsed artifact, because
* seeds have no `name` and never enter the MetadataManager) and load the
* seeds of objects that did not exist before the reload.
*
* Scoped STRICTLY to first-seen objects: an already-loaded (and possibly
* user-edited) dataset is never re-upserted mid-run — edits to existing
* seeds still apply on restart, as before. Dev-only (production publish
* flows own their seeding), single-tenant only (multi-tenant replays
* per-org on sys_organization insert). Runs AFTER ObjectQL's reload
* schema sync because kernel hooks fire in registration order and
* ObjectQLPlugin starts first.
*/
private registerHotReloadSeeder(ctx: PluginContext, ql: any): void {
const hook = (ctx as any).hook;
if (typeof hook !== 'function') return;
if (process.env.NODE_ENV !== 'development') return;
if (resolveMultiOrgEnabled()) return;
const knownObjects = new Set<string>(
(Array.isArray(this.bundle.objects) ? this.bundle.objects : [])
.map((o: any) => o?.name)
.filter((n: any): n is string => typeof n === 'string'),
);
hook.call(ctx, 'metadata:reloaded', async (payload: any) => {
try {
const meta = payload?.metadata;
const objectsNow: any[] = Array.isArray(meta?.objects) ? meta.objects : [];
const fresh = objectsNow
.map((o: any) => o?.name)
.filter((n: any): n is string => typeof n === 'string' && !knownObjects.has(n));
for (const n of fresh) knownObjects.add(n);
if (fresh.length === 0) return;
const seeds = (Array.isArray(meta?.data) ? meta.data : []).filter(
(d: any) => d?.object && fresh.includes(d.object) && Array.isArray(d.records),
);
if (seeds.length === 0) return;
const metadata = ctx.getService('metadata') as IMetadataService | undefined;
if (!metadata) {
ctx.logger.warn('[Seeder] hot-reload seed skipped — metadata service unavailable');
return;
}
const seedLoader = new SeedLoaderService(ql, metadata, ctx.logger);