@memberjunction/schema-engine 6.2.0-edge.6 → 6.2.0-edge.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/GitHubAppAuth.d.ts +45 -0
- package/dist/GitHubAppAuth.d.ts.map +1 -0
- package/dist/GitHubAppAuth.js +104 -0
- package/dist/GitHubAppAuth.js.map +1 -0
- package/dist/RuntimeSchemaManager.d.ts +162 -5
- package/dist/RuntimeSchemaManager.d.ts.map +1 -1
- package/dist/RuntimeSchemaManager.js +350 -39
- package/dist/RuntimeSchemaManager.js.map +1 -1
- package/package.json +6 -6
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { BaseSingleton } from '@memberjunction/global';
|
|
12
12
|
import { LogError, Metadata, RunView, } from '@memberjunction/core';
|
|
13
13
|
import { Octokit } from '@octokit/rest';
|
|
14
|
+
import { MintInstallationToken, ReadGitHubAppCredentials } from './GitHubAppAuth.js';
|
|
14
15
|
import { RSUMetrics } from './RSUMetrics.js';
|
|
15
16
|
import { GetDialect } from './DDLGenerator.js';
|
|
16
17
|
import * as nodePath from 'node:path';
|
|
@@ -100,6 +101,29 @@ class RSUConfig {
|
|
|
100
101
|
get CompileCommand() {
|
|
101
102
|
return process.env.RSU_COMPILE_COMMAND;
|
|
102
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* How many packages the compile builds at once. ONE by default, deliberately.
|
|
106
|
+
*
|
|
107
|
+
* `turbo build` with no `--concurrency` fans out one `tsc` per filtered package — three of them on
|
|
108
|
+
* a 2 vCPU / 4 GB instance that is also serving the API, beside a heap that has just finished
|
|
109
|
+
* CodeGen. On the sandbox that took the whole workspace off the air for the duration of the compile
|
|
110
|
+
* (MJ-RUN-33). A slower compile that leaves the API answering beats a faster one that does not.
|
|
111
|
+
*/
|
|
112
|
+
get CompileConcurrency() {
|
|
113
|
+
return process.env.RSU_COMPILE_CONCURRENCY || '1';
|
|
114
|
+
}
|
|
115
|
+
/** How often the compile reports that it is still alive. */
|
|
116
|
+
get CompileHeartbeatMs() {
|
|
117
|
+
return parseInt(process.env.RSU_COMPILE_HEARTBEAT_MS || '30000', 10);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Grace between SIGTERM and SIGKILL when a command has to be killed for exceeding its timeout.
|
|
121
|
+
* Small on purpose: the command is already over budget, and the point of the kill is that the box
|
|
122
|
+
* gets its CPU back.
|
|
123
|
+
*/
|
|
124
|
+
get CommandKillGraceMs() {
|
|
125
|
+
return parseInt(process.env.RSU_COMMAND_KILL_GRACE_MS || '5000', 10);
|
|
126
|
+
}
|
|
103
127
|
get CompilePackages() {
|
|
104
128
|
return process.env.RSU_COMPILE_PACKAGES;
|
|
105
129
|
}
|
|
@@ -210,6 +234,16 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
210
234
|
super();
|
|
211
235
|
// ─── State ───────────────────────────────────────────────────────
|
|
212
236
|
this._isRunning = false;
|
|
237
|
+
/**
|
|
238
|
+
* True from the moment RunPipelineBatch begins until its outer `finally` — the whole pipeline,
|
|
239
|
+
* not just the DB-mutation window. `_isRunning` is the concurrency MUTEX and is deliberately
|
|
240
|
+
* released right after ExecuteMigration (the database is consistent from then on), which means
|
|
241
|
+
* it is false for WriteAdditionalSchemaInfo, RunCodeGen, CompileTypeScript, GitCommitAndPR and
|
|
242
|
+
* RestartMJAPI — roughly 95% of the pipeline's wall clock. Reporting the mutex as "running" made
|
|
243
|
+
* the API say no RSU was running while CodeGen was ten minutes in (sandbox, 2026-09-11), and every
|
|
244
|
+
* consumer that trusted it misjudged the build. Status reports THIS flag; the mutex stays a mutex.
|
|
245
|
+
*/
|
|
246
|
+
this._pipelineActive = false;
|
|
213
247
|
this._ddlProvider = null;
|
|
214
248
|
this._codeGenRunner = null;
|
|
215
249
|
this._codeGenOutputPaths = [];
|
|
@@ -541,7 +575,8 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
541
575
|
GetStatus() {
|
|
542
576
|
return {
|
|
543
577
|
Enabled: this.IsEnabled,
|
|
544
|
-
|
|
578
|
+
// The pipeline, not the mutex — see _pipelineActive. Either is enough to be "running".
|
|
579
|
+
Running: this.IsRunning || this._pipelineActive,
|
|
545
580
|
OutOfSync: this.IsOutOfSync,
|
|
546
581
|
OutOfSyncSince: this._outOfSyncSince,
|
|
547
582
|
LastRunAt: this._lastRunAt,
|
|
@@ -560,15 +595,51 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
560
595
|
*/
|
|
561
596
|
static { this.EXPECTED_STEPS_SHARED_PRE = ['ValidateEnvironment', 'ValidateSQL', 'AcquireLock']; }
|
|
562
597
|
static { this.EXPECTED_STEPS_PER_ITEM = ['WriteMigrationFile', 'ExecuteMigration']; }
|
|
563
|
-
static { this.EXPECTED_STEPS_SHARED_POST = [
|
|
598
|
+
static { this.EXPECTED_STEPS_SHARED_POST = [
|
|
599
|
+
'WriteAdditionalSchemaInfo',
|
|
600
|
+
'RunCodeGen',
|
|
601
|
+
'CompileTypeScript',
|
|
602
|
+
'GitCommitAndPR',
|
|
603
|
+
'RestartMJAPI',
|
|
604
|
+
]; }
|
|
605
|
+
/**
|
|
606
|
+
* The steps that run AFTER the pipeline restarts the API on itself, in order.
|
|
607
|
+
*
|
|
608
|
+
* They belong to the same run — the setup journey the user is watching is not finished until the
|
|
609
|
+
* sync starts — but they execute in a DIFFERENT PROCESS, so nothing in this class ever runs them.
|
|
610
|
+
* They are declared here because this is where the run's shape is defined: they count towards
|
|
611
|
+
* {@link ExpectedStepTotal}, so the determinate progress bar does not reach 100% and then sit
|
|
612
|
+
* there while the connector is still not live, and they are named here so the post-restart
|
|
613
|
+
* consumer and this pipeline cannot drift apart on what the remaining steps are called.
|
|
614
|
+
*/
|
|
615
|
+
static { this.EXPECTED_STEPS_POST_RESTART = ['CreateEntityMaps', 'StartSync']; }
|
|
616
|
+
/**
|
|
617
|
+
* The full expected step sequence for a batch of `itemCount` migrations, in execution order —
|
|
618
|
+
* including the two that run after the restart.
|
|
619
|
+
*
|
|
620
|
+
* Public and static so the arithmetic is directly assertable without a live pipeline; the number
|
|
621
|
+
* it produces is the denominator every progress UI divides by.
|
|
622
|
+
*/
|
|
623
|
+
static ExpectedSteps(itemCount) {
|
|
624
|
+
const perItem = [];
|
|
625
|
+
for (let i = 0; i < itemCount; i++)
|
|
626
|
+
perItem.push(...RuntimeSchemaManager.EXPECTED_STEPS_PER_ITEM);
|
|
627
|
+
return [
|
|
628
|
+
...RuntimeSchemaManager.EXPECTED_STEPS_SHARED_PRE,
|
|
629
|
+
...perItem,
|
|
630
|
+
...RuntimeSchemaManager.EXPECTED_STEPS_SHARED_POST,
|
|
631
|
+
...RuntimeSchemaManager.EXPECTED_STEPS_POST_RESTART,
|
|
632
|
+
];
|
|
633
|
+
}
|
|
634
|
+
/** Expected total steps for a batch of `itemCount` migrations. See {@link ExpectedSteps}. */
|
|
635
|
+
static ExpectedStepTotal(itemCount) {
|
|
636
|
+
return RuntimeSchemaManager.ExpectedSteps(itemCount).length;
|
|
637
|
+
}
|
|
564
638
|
/** Arms the U11 step counter for a run of `itemCount` migrations. */
|
|
565
639
|
beginStepTracking(itemCount) {
|
|
566
640
|
this._currentStepIndex = 0;
|
|
567
641
|
this._currentStepName = null;
|
|
568
|
-
this._stepTotal =
|
|
569
|
-
RuntimeSchemaManager.EXPECTED_STEPS_SHARED_PRE.length +
|
|
570
|
-
itemCount * RuntimeSchemaManager.EXPECTED_STEPS_PER_ITEM.length +
|
|
571
|
-
RuntimeSchemaManager.EXPECTED_STEPS_SHARED_POST.length;
|
|
642
|
+
this._stepTotal = RuntimeSchemaManager.ExpectedStepTotal(itemCount);
|
|
572
643
|
}
|
|
573
644
|
/** Clears the U11 step counter when the run finishes (status returns to idle). */
|
|
574
645
|
endStepTracking() {
|
|
@@ -576,19 +647,102 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
576
647
|
this._currentStepIndex = null;
|
|
577
648
|
this._stepTotal = null;
|
|
578
649
|
}
|
|
650
|
+
/**
|
|
651
|
+
* How long the pipeline will wait for an observer to make a `restart.pending` event durable.
|
|
652
|
+
*
|
|
653
|
+
* Bounded on purpose. The wait exists because the process is seconds from being killed, but an
|
|
654
|
+
* observer that hangs must not wedge a schema migration — the invariant "progress reporting can
|
|
655
|
+
* never break a migration" outranks the checkpoint. Five seconds is orders of magnitude more than
|
|
656
|
+
* appending a few lines to a local file needs, and far less than the restart path's own timeouts.
|
|
657
|
+
*/
|
|
658
|
+
static { this.OBSERVER_DURABLE_TIMEOUT_MS = 5_000; }
|
|
579
659
|
/** Delivers an event to {@link PipelineObserver}, swallowing (but logging) any throw. */
|
|
580
660
|
notifyObserver(event) {
|
|
581
661
|
const observer = this.PipelineObserver;
|
|
582
662
|
if (!observer)
|
|
583
663
|
return;
|
|
584
664
|
try {
|
|
585
|
-
observer(event);
|
|
665
|
+
const maybePromise = observer(event);
|
|
666
|
+
// An observer may return a promise; for every event but `restart.pending` we do not wait on
|
|
667
|
+
// it. Attach a catch so a rejection is logged rather than surfacing as an unhandled rejection
|
|
668
|
+
// (which, depending on the Node flags, can take the process down mid-migration).
|
|
669
|
+
if (maybePromise && typeof maybePromise.then === 'function') {
|
|
670
|
+
void maybePromise.catch((error) => this.rsuLog(`Pipeline observer rejected on ${event.Kind} (ignored): ${error instanceof Error ? error.message : String(error)}`));
|
|
671
|
+
}
|
|
586
672
|
}
|
|
587
673
|
catch (error) {
|
|
588
674
|
// Progress reporting must never break a schema migration.
|
|
589
675
|
this.rsuLog(`Pipeline observer threw on ${event.Kind} (ignored): ${error instanceof Error ? error.message : String(error)}`);
|
|
590
676
|
}
|
|
591
677
|
}
|
|
678
|
+
/**
|
|
679
|
+
* Delivers an event and WAITS for the observer to finish with it, bounded by
|
|
680
|
+
* {@link OBSERVER_DURABLE_TIMEOUT_MS}. Used for exactly one event: `restart.pending`.
|
|
681
|
+
*
|
|
682
|
+
* The ordinary fire-and-forget path is wrong there. The observer's durable write is asynchronous,
|
|
683
|
+
* and the very next thing the pipeline does is issue a command that kills this process — so a
|
|
684
|
+
* queued-but-unflushed checkpoint is simply lost, and the whole point of the checkpoint is that it
|
|
685
|
+
* survives the kill. Errors and timeouts are swallowed exactly as they are on the sync path.
|
|
686
|
+
*/
|
|
687
|
+
async notifyObserverDurable(event) {
|
|
688
|
+
const observer = this.PipelineObserver;
|
|
689
|
+
if (!observer)
|
|
690
|
+
return;
|
|
691
|
+
try {
|
|
692
|
+
const maybePromise = observer(event);
|
|
693
|
+
if (!maybePromise || typeof maybePromise.then !== 'function')
|
|
694
|
+
return;
|
|
695
|
+
let timer;
|
|
696
|
+
const timeout = new Promise((resolve) => {
|
|
697
|
+
timer = setTimeout(() => {
|
|
698
|
+
this.rsuLog(`Pipeline observer did not settle ${event.Kind} within ${RuntimeSchemaManager.OBSERVER_DURABLE_TIMEOUT_MS}ms — continuing`);
|
|
699
|
+
resolve();
|
|
700
|
+
}, RuntimeSchemaManager.OBSERVER_DURABLE_TIMEOUT_MS);
|
|
701
|
+
timer.unref?.();
|
|
702
|
+
});
|
|
703
|
+
try {
|
|
704
|
+
await Promise.race([maybePromise, timeout]);
|
|
705
|
+
}
|
|
706
|
+
finally {
|
|
707
|
+
if (timer)
|
|
708
|
+
clearTimeout(timer);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
catch (error) {
|
|
712
|
+
this.rsuLog(`Pipeline observer failed on ${event.Kind} (ignored): ${error instanceof Error ? error.message : String(error)}`);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* The de-duplicated set of connections a batch touches, in input order.
|
|
717
|
+
*
|
|
718
|
+
* Resolution order per input: the explicit {@link RSUPipelineInput.CompanyIntegrationID} first,
|
|
719
|
+
* then the `CompanyIntegrationID` of any {@link RSUPipelineInput.PendingWork} entry. The fallback
|
|
720
|
+
* is not a convenience — it is the compatibility path that gives EVERY production caller today an
|
|
721
|
+
* identity without changing a single call site, because every one of them registers post-restart
|
|
722
|
+
* work against a connection. An input with neither contributes nothing, and a batch where no
|
|
723
|
+
* input has either yields an empty set: that run stays unreadable through the per-connection
|
|
724
|
+
* endpoints, which is the conservative answer, not a bug.
|
|
725
|
+
*
|
|
726
|
+
* Public and static so the identity rule is assertable on its own.
|
|
727
|
+
*/
|
|
728
|
+
static CollectCompanyIntegrationIDs(inputs) {
|
|
729
|
+
const seen = new Set();
|
|
730
|
+
const ordered = [];
|
|
731
|
+
const add = (id) => {
|
|
732
|
+
if (!id)
|
|
733
|
+
return;
|
|
734
|
+
if (seen.has(id))
|
|
735
|
+
return;
|
|
736
|
+
seen.add(id);
|
|
737
|
+
ordered.push(id);
|
|
738
|
+
};
|
|
739
|
+
for (const input of inputs) {
|
|
740
|
+
add(input.CompanyIntegrationID);
|
|
741
|
+
for (const work of input.PendingWork ?? [])
|
|
742
|
+
add(work.CompanyIntegrationID);
|
|
743
|
+
}
|
|
744
|
+
return ordered;
|
|
745
|
+
}
|
|
592
746
|
/**
|
|
593
747
|
* Records a completed step onto `steps` AND publishes it to the observer, so a step is never
|
|
594
748
|
* visible in the result but absent from the event stream. Every step recording goes through
|
|
@@ -678,12 +832,14 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
678
832
|
const sharedSteps = [];
|
|
679
833
|
// U11 — arm the determinate step counter (index of expected total) for this run.
|
|
680
834
|
this.beginStepTracking(inputs.length);
|
|
835
|
+
this._pipelineActive = true;
|
|
681
836
|
this.notifyObserver({
|
|
682
837
|
Kind: 'run.start',
|
|
683
838
|
ItemCount: inputs.length,
|
|
684
839
|
Descriptions: inputs.map((i) => i.Description),
|
|
685
840
|
AffectedTables: [...new Set(inputs.flatMap((i) => i.AffectedTables))],
|
|
686
841
|
StepTotal: this._stepTotal ?? 0,
|
|
842
|
+
CompanyIntegrationIDs: RuntimeSchemaManager.CollectCompanyIntegrationIDs(inputs),
|
|
687
843
|
});
|
|
688
844
|
// Captured so the `finally` can publish the terminal run boundary on EVERY exit path —
|
|
689
845
|
// early validation failure, normal completion, or a throw (which leaves it undefined).
|
|
@@ -706,6 +862,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
706
862
|
}
|
|
707
863
|
finally {
|
|
708
864
|
this.endStepTracking();
|
|
865
|
+
this._pipelineActive = false;
|
|
709
866
|
this.notifyRunEnd(batchResult, inputs.length);
|
|
710
867
|
}
|
|
711
868
|
}
|
|
@@ -811,9 +968,26 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
811
968
|
}
|
|
812
969
|
if (codegenOk) {
|
|
813
970
|
const compileOk = await this.runStep('CompileTypeScript', () => this.compileTypeScript(), sharedSteps);
|
|
971
|
+
result.CompileSucceeded = !!compileOk;
|
|
814
972
|
if (compileOk) {
|
|
815
973
|
this.ClearOutOfSync();
|
|
816
974
|
}
|
|
975
|
+
else {
|
|
976
|
+
// STOP HERE. Everything below assumes the tree on disk matches the migrated database, and a
|
|
977
|
+
// failed compile is exactly the case where it does not:
|
|
978
|
+
// - GitCommitAndPR would publish a migration whose generated code never built (its only
|
|
979
|
+
// guard was SkipGitCommit, so it ran regardless);
|
|
980
|
+
// - RestartMJAPI would bring the API back up on an UNCOMPILED tree.
|
|
981
|
+
// On the sandbox that combination presented as a 40-minute outage behind a pipeline that
|
|
982
|
+
// reported itself complete (MJ-RUN-33). The API stays flagged out-of-sync, the pending work
|
|
983
|
+
// registered above stays Pending (visible and resumable, not consumed until a restart onto a
|
|
984
|
+
// tree that built), and the caller's result names the step.
|
|
985
|
+
result.CompileError =
|
|
986
|
+
sharedSteps.find((s) => s.Name === 'CompileTypeScript' && s.Status === 'failed')?.Message ??
|
|
987
|
+
'TypeScript compile failed after CodeGen — the API code on disk does not match the migrated database';
|
|
988
|
+
this.rsuLog(`Compile failed — NOT committing and NOT restarting: ${result.CompileError}`);
|
|
989
|
+
return result;
|
|
990
|
+
}
|
|
817
991
|
}
|
|
818
992
|
// Git commit + PR before restart — PM2 restart kills this process
|
|
819
993
|
if (!inputs.every((i) => i.SkipGitCommit)) {
|
|
@@ -831,6 +1005,22 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
831
1005
|
await this.writePostRestartFiles(successfulInputs);
|
|
832
1006
|
// Restart LAST — PM2 restart kills this process, nothing runs after this
|
|
833
1007
|
if (!inputs.every((i) => i.SkipRestart)) {
|
|
1008
|
+
// Publish the restart boundary BEFORE issuing it. `runStep('RestartMJAPI', ...)` will emit a
|
|
1009
|
+
// step.start and then never emit a step.end, because pm2 kills us inside restartMJAPI() — so
|
|
1010
|
+
// this is the last chance to tell an observer that the pipeline reached the restart in good
|
|
1011
|
+
// order, and to hand the process on the other side what it needs to pick the run back up.
|
|
1012
|
+
// Awaited (not fire-and-forget) precisely because we are about to be killed.
|
|
1013
|
+
await this.notifyObserverDurable({
|
|
1014
|
+
Kind: 'restart.pending',
|
|
1015
|
+
RemainingSteps: [...RuntimeSchemaManager.EXPECTED_STEPS_POST_RESTART],
|
|
1016
|
+
// +1: the RestartMJAPI step is issued next and its own increment happens inside runStep.
|
|
1017
|
+
StepIndex: this._currentStepIndex === null ? undefined : this._currentStepIndex + 1,
|
|
1018
|
+
StepTotal: this._stepTotal ?? undefined,
|
|
1019
|
+
CompanyIntegrationIDs: RuntimeSchemaManager.CollectCompanyIntegrationIDs(successfulInputs),
|
|
1020
|
+
PendingWorkIDs: [...new Set([...(result.PendingWorkIDs?.values() ?? [])].flat())],
|
|
1021
|
+
TotalCount: inputs.length,
|
|
1022
|
+
SuccessCount: successfulItems.length,
|
|
1023
|
+
});
|
|
834
1024
|
const restartOk = await this.runStep('RestartMJAPI', () => this.restartMJAPI(), sharedSteps);
|
|
835
1025
|
if (restartOk)
|
|
836
1026
|
result.ApiRestarted = true;
|
|
@@ -843,19 +1033,23 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
843
1033
|
// A run-wide CodeGen failure means the migrations applied but the entities may have
|
|
844
1034
|
// no stored procedures — treat the run as failed, not success.
|
|
845
1035
|
const codeGenFailed = postResult.CodeGenSucceeded === false;
|
|
846
|
-
|
|
1036
|
+
// A failed compile is the same class of failure one step later: the DDL is committed, the entity
|
|
1037
|
+
// classes were generated, and nothing built them — so the running API cannot use them.
|
|
1038
|
+
const compileFailed = postResult.CompileSucceeded === false;
|
|
1039
|
+
this._lastRunResult = successfulItems.length > 0 && !codeGenFailed && !compileFailed ? 'success' : 'failed';
|
|
847
1040
|
const results = itemResults.map((item) => {
|
|
848
1041
|
const allSteps = [...sharedSteps, ...item.Steps];
|
|
849
1042
|
// A migration that executed but whose run-wide CodeGen failed is NOT a success —
|
|
850
1043
|
// the entity may have no spCreate/spUpdate procs and would silently skip on sync.
|
|
851
1044
|
const codeGenFailedThisCaller = codeGenFailed && item.Success;
|
|
1045
|
+
const compileFailedThisCaller = compileFailed && item.Success;
|
|
852
1046
|
// Same reasoning as the CodeGen case above: the migration ran, but work the caller
|
|
853
1047
|
// asked to happen after the restart was never persisted, so the restart drops it.
|
|
854
1048
|
// Reporting success here would tell the caller their sync is coming when it is not.
|
|
855
1049
|
const pendingWorkErrors = postResult.PendingWorkErrors?.get(item.Input) ?? [];
|
|
856
1050
|
const pendingWorkFailedThisCaller = pendingWorkErrors.length > 0 && item.Success;
|
|
857
1051
|
const result = {
|
|
858
|
-
Success: item.Success && successfulItems.length > 0 && !codeGenFailed && !pendingWorkFailedThisCaller,
|
|
1052
|
+
Success: item.Success && successfulItems.length > 0 && !codeGenFailed && !compileFailed && !pendingWorkFailedThisCaller,
|
|
859
1053
|
MigrationFilePath: item.FilePath,
|
|
860
1054
|
APIRestarted: postResult.ApiRestarted,
|
|
861
1055
|
GitCommitSuccess: postResult.GitCommitSuccess,
|
|
@@ -863,16 +1057,20 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
863
1057
|
Steps: allSteps,
|
|
864
1058
|
ErrorMessage: codeGenFailedThisCaller
|
|
865
1059
|
? postResult.CodeGenError ?? item.Error
|
|
866
|
-
:
|
|
867
|
-
?
|
|
868
|
-
:
|
|
1060
|
+
: compileFailedThisCaller
|
|
1061
|
+
? postResult.CompileError ?? item.Error
|
|
1062
|
+
: pendingWorkFailedThisCaller
|
|
1063
|
+
? pendingWorkErrors.join('; ')
|
|
1064
|
+
: item.Error,
|
|
869
1065
|
ErrorStep: codeGenFailedThisCaller
|
|
870
1066
|
? 'RunCodeGen'
|
|
871
|
-
:
|
|
872
|
-
? '
|
|
873
|
-
:
|
|
874
|
-
?
|
|
875
|
-
:
|
|
1067
|
+
: compileFailedThisCaller
|
|
1068
|
+
? 'CompileTypeScript'
|
|
1069
|
+
: pendingWorkFailedThisCaller
|
|
1070
|
+
? 'RegisterPendingWork'
|
|
1071
|
+
: item.Error
|
|
1072
|
+
? item.Steps.find((s) => s.Status === 'failed')?.Name
|
|
1073
|
+
: undefined,
|
|
876
1074
|
PendingWorkIDs: postResult.PendingWorkIDs?.get(item.Input),
|
|
877
1075
|
};
|
|
878
1076
|
this.writeAuditLog(item.Input, result).catch((err) => LogError(`[RSU] Audit log failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
@@ -1395,30 +1593,129 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
1395
1593
|
return { ...process.env, NODE_OPTIONS: nodeOptions };
|
|
1396
1594
|
}
|
|
1397
1595
|
async compileTypeScript() {
|
|
1398
|
-
const { execAsync } = await this.getExecAsync();
|
|
1399
1596
|
const codegenDir = rsuConfig.CodeGenDir;
|
|
1400
1597
|
const timeoutMs = rsuConfig.CompileTimeoutMs;
|
|
1401
|
-
|
|
1402
|
-
const
|
|
1403
|
-
|
|
1404
|
-
|
|
1598
|
+
const startedAt = Date.now();
|
|
1599
|
+
const elapsedSec = () => Math.round((Date.now() - startedAt) / 1000);
|
|
1600
|
+
// A compile is minutes of silence from a process that is also the API. Say so, with the elapsed
|
|
1601
|
+
// time against the budget, so the pm2 log an incident gets read from can distinguish "compiling"
|
|
1602
|
+
// from "hung" — on the sandbox the only record of a 40-minute compile was its failure line.
|
|
1603
|
+
const heartbeat = setInterval(() => this.rsuLog(`CompileTypeScript still running — ${elapsedSec()}s elapsed of a ${Math.round(timeoutMs / 1000)}s budget`), rsuConfig.CompileHeartbeatMs);
|
|
1604
|
+
heartbeat.unref?.();
|
|
1605
|
+
try {
|
|
1606
|
+
// A full-command override is honoured as-is, but it goes through the same killable runner: the
|
|
1607
|
+
// override exists precisely because the default command was starving small boxes, and the
|
|
1608
|
+
// replacement must be no harder to stop.
|
|
1609
|
+
const compileCmd = rsuConfig.CompileCommand ?? this.defaultCompileCommand();
|
|
1610
|
+
await this.runCommandInOwnProcessGroup(`cd "${codegenDir}" && ${compileCmd}`, { timeoutMs, env: this.buildChildEnv() });
|
|
1611
|
+
this.rsuLog(`CompileTypeScript completed in ${elapsedSec()}s`);
|
|
1405
1612
|
return true;
|
|
1406
1613
|
}
|
|
1407
|
-
|
|
1614
|
+
finally {
|
|
1615
|
+
clearInterval(heartbeat);
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
/**
|
|
1619
|
+
* The turbo invocation the compile step uses when nothing overrides it.
|
|
1620
|
+
*
|
|
1621
|
+
* `--concurrency` is the load-bearing part: without it turbo builds every filtered package at once,
|
|
1622
|
+
* which is three `tsc` processes on a 2 vCPU / 4 GB instance that is simultaneously serving the API.
|
|
1623
|
+
* See {@link RSUConfig.CompileConcurrency}.
|
|
1624
|
+
*/
|
|
1625
|
+
defaultCompileCommand() {
|
|
1408
1626
|
const defaultPackages = '@memberjunction/core-entities,@memberjunction/server,mj_api';
|
|
1409
1627
|
const envPackages = rsuConfig.CompilePackages;
|
|
1410
1628
|
const rawPackages = envPackages !== undefined ? envPackages : defaultPackages;
|
|
1411
|
-
const
|
|
1629
|
+
const filterArgs = rawPackages
|
|
1412
1630
|
.split(',')
|
|
1413
|
-
.map((
|
|
1414
|
-
.filter((
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1631
|
+
.map((pkg) => pkg.trim())
|
|
1632
|
+
.filter((pkg) => pkg.length > 0)
|
|
1633
|
+
.map((pkg) => `--filter="${pkg}"`)
|
|
1634
|
+
.join(' ');
|
|
1635
|
+
return `npx turbo build ${filterArgs} --concurrency=${rsuConfig.CompileConcurrency}`;
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* Runs a shell command in its OWN process group, and kills the whole group if it exceeds its
|
|
1639
|
+
* timeout.
|
|
1640
|
+
*
|
|
1641
|
+
* Why this exists rather than `execAsync(cmd, { timeout })`: `promisify(exec)`'s timeout signals the
|
|
1642
|
+
* `/bin/sh` it spawned, NOT the process tree beneath it, and the promise it returns does not settle
|
|
1643
|
+
* until every pipe closes. A `turbo build` that outran its timeout therefore kept its `tsc` children
|
|
1644
|
+
* alive AND left the pipeline awaiting a promise that would never resolve — a 300-second budget that
|
|
1645
|
+
* ran for 40 minutes and ended only when a deploy replaced the release directory underneath it
|
|
1646
|
+
* (MJ-RUN-33). The timeout was decorative.
|
|
1647
|
+
*
|
|
1648
|
+
* Three properties make it real:
|
|
1649
|
+
* - `detached: true` puts the child in a new process group whose id IS the child's pid, so
|
|
1650
|
+
* `process.kill(-pid, …)` reaches every descendant — the shell, turbo, and each `tsc`.
|
|
1651
|
+
* - SIGTERM first, SIGKILL after {@link RSUConfig.CommandKillGraceMs}, so a child that ignores the
|
|
1652
|
+
* polite signal still loses the CPU.
|
|
1653
|
+
* - the promise REJECTS as soon as the kill is issued, rather than waiting for pipes that a wedged
|
|
1654
|
+
* child may never close. Not settling was half the defect.
|
|
1655
|
+
*
|
|
1656
|
+
* Windows has no process groups in this sense; there the child is killed directly.
|
|
1657
|
+
*/
|
|
1658
|
+
runCommandInOwnProcessGroup(command, opts) {
|
|
1659
|
+
const maxBuffer = opts.maxBuffer ?? 50 * 1024 * 1024; // 50 MB — build output is verbose
|
|
1660
|
+
const posix = process.platform !== 'win32';
|
|
1661
|
+
return new Promise((resolve, reject) => {
|
|
1662
|
+
const child = childProcess.spawn(command, {
|
|
1663
|
+
shell: true,
|
|
1664
|
+
detached: posix,
|
|
1665
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1666
|
+
// The per-child heap ceiling (buildChildEnv) — a compile run through this runner must not lose it.
|
|
1667
|
+
env: opts.env ?? process.env,
|
|
1668
|
+
});
|
|
1669
|
+
let stdout = '';
|
|
1670
|
+
let stderr = '';
|
|
1671
|
+
let settled = false;
|
|
1672
|
+
child.stdout?.on('data', (chunk) => {
|
|
1673
|
+
if (stdout.length < maxBuffer)
|
|
1674
|
+
stdout += String(chunk);
|
|
1675
|
+
});
|
|
1676
|
+
child.stderr?.on('data', (chunk) => {
|
|
1677
|
+
if (stderr.length < maxBuffer)
|
|
1678
|
+
stderr += String(chunk);
|
|
1679
|
+
});
|
|
1680
|
+
const killGroup = (signal) => {
|
|
1681
|
+
try {
|
|
1682
|
+
if (posix && child.pid !== undefined)
|
|
1683
|
+
process.kill(-child.pid, signal);
|
|
1684
|
+
else
|
|
1685
|
+
child.kill(signal);
|
|
1686
|
+
}
|
|
1687
|
+
catch {
|
|
1688
|
+
/* already gone — nothing to signal */
|
|
1689
|
+
}
|
|
1690
|
+
};
|
|
1691
|
+
const settle = (fn) => {
|
|
1692
|
+
if (settled)
|
|
1693
|
+
return;
|
|
1694
|
+
settled = true;
|
|
1695
|
+
clearTimeout(timer);
|
|
1696
|
+
fn();
|
|
1697
|
+
};
|
|
1698
|
+
// The SIGKILL escalation, armed only when the timeout fires; cleared once the child has
|
|
1699
|
+
// actually closed so it never fires at a process group that is already gone.
|
|
1700
|
+
let hardKill;
|
|
1701
|
+
const timer = setTimeout(() => {
|
|
1702
|
+
killGroup('SIGTERM');
|
|
1703
|
+
hardKill = setTimeout(() => killGroup('SIGKILL'), rsuConfig.CommandKillGraceMs);
|
|
1704
|
+
hardKill.unref?.();
|
|
1705
|
+
settle(() => reject(new RSUError('COMMAND_TIMEOUT', `Command exceeded its ${opts.timeoutMs}ms timeout and its process group was killed: ${command}` +
|
|
1706
|
+
(stderr ? ` — last stderr: ${stderr.slice(-500)}` : ''))));
|
|
1707
|
+
}, opts.timeoutMs);
|
|
1708
|
+
timer.unref?.();
|
|
1709
|
+
child.on('error', (err) => settle(() => reject(err)));
|
|
1710
|
+
child.on('close', (code, signal) => {
|
|
1711
|
+
if (hardKill)
|
|
1712
|
+
clearTimeout(hardKill);
|
|
1713
|
+
if (code === 0)
|
|
1714
|
+
settle(() => resolve({ stdout, stderr }));
|
|
1715
|
+
else
|
|
1716
|
+
settle(() => reject(new RSUError('COMMAND_FAILED', `Command failed (exit ${code ?? signal}): ${command}\n${stderr.slice(-2000)}`)));
|
|
1717
|
+
});
|
|
1718
|
+
});
|
|
1422
1719
|
}
|
|
1423
1720
|
/**
|
|
1424
1721
|
* Restart MJAPI via PM2.
|
|
@@ -1532,7 +1829,7 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
1532
1829
|
* For Docker/CI environments without a local `.git` directory.
|
|
1533
1830
|
*/
|
|
1534
1831
|
async gitCommitAndPRViaAPI(migrationFilePaths, affectedTables, description) {
|
|
1535
|
-
const octokit = this.createOctokit();
|
|
1832
|
+
const octokit = await this.createOctokit();
|
|
1536
1833
|
const { owner, repo } = this.resolveGitHubOwnerRepo();
|
|
1537
1834
|
const branchName = this.generateBranchName(affectedTables);
|
|
1538
1835
|
const baseBranch = rsuConfig.GitTargetBranch;
|
|
@@ -1730,13 +2027,27 @@ export class RuntimeSchemaManager extends BaseSingleton {
|
|
|
1730
2027
|
'Runtime Schema Update (RSU) pipeline — auto-generated PR.',
|
|
1731
2028
|
].join('\n');
|
|
1732
2029
|
}
|
|
1733
|
-
/**
|
|
1734
|
-
|
|
2030
|
+
/**
|
|
2031
|
+
* An authenticated Octokit instance: a plain token when one is set, otherwise a token minted from
|
|
2032
|
+
* the GitHub App the process was deployed with (GITHUB_APP_ID / _INSTALLATION_ID / _PRIVATE_KEY —
|
|
2033
|
+
* the same names the feedback resolver reads), scoped to the one repository this pipeline commits
|
|
2034
|
+
* to. Until this fallback existed every App-deployed workspace ended this step with "GitHub token
|
|
2035
|
+
* not found", and because the step is non-fatal the migration and generated code it had just
|
|
2036
|
+
* produced lived only on the box, where the next deploy discarded them.
|
|
2037
|
+
*/
|
|
2038
|
+
async createOctokit() {
|
|
1735
2039
|
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
|
1736
|
-
if (
|
|
1737
|
-
|
|
2040
|
+
if (token) {
|
|
2041
|
+
return new Octokit({ auth: token });
|
|
2042
|
+
}
|
|
2043
|
+
const app = ReadGitHubAppCredentials();
|
|
2044
|
+
if (!app) {
|
|
2045
|
+
throw new RSUError('GIT', 'GitHub credentials not found. Set GITHUB_TOKEN/GH_TOKEN, or GITHUB_APP_ID + GITHUB_APP_INSTALLATION_ID + GITHUB_APP_PRIVATE_KEY (the App the deploy installs) for PR creation.');
|
|
1738
2046
|
}
|
|
1739
|
-
|
|
2047
|
+
const { repo } = this.resolveGitHubOwnerRepo();
|
|
2048
|
+
const installationToken = await MintInstallationToken(new Octokit(), app, repo);
|
|
2049
|
+
this.rsuLog(`GitHub App ${app.AppId}: minted an installation token scoped to "${repo}"`);
|
|
2050
|
+
return new Octokit({ auth: installationToken });
|
|
1740
2051
|
}
|
|
1741
2052
|
/**
|
|
1742
2053
|
* Generate a branch name from affected table names.
|