@openfairygui/backend 0.5.0 → 0.6.0
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/README.md +3 -3
- package/dist/docs.cjs +190 -611
- package/dist/docs.d.cts +9 -27
- package/dist/docs.d.mts +9 -27
- package/dist/docs.mjs +190 -611
- package/dist/index.cjs +445 -635
- package/dist/index.d.cts +46 -160
- package/dist/index.d.mts +46 -160
- package/dist/index.mjs +445 -636
- package/dist/node.cjs +476 -664
- package/dist/node.d.cts +20 -94
- package/dist/node.d.mts +20 -94
- package/dist/node.mjs +476 -664
- package/package.json +3 -3
- package/src/contracts.ts +2 -2
- package/src/diagnostics.ts +4 -5
- package/src/generated/contracts.ts +208 -837
- package/src/generated/docs.ts +3 -3
- package/src/index.ts +2 -13
- package/src/node.ts +36 -30
- package/src/runtime/capabilities.ts +2 -12
- package/src/runtime/contracts.ts +33 -107
- package/src/runtime.ts +22 -57
- package/src/services/authoring-service.ts +9 -572
- package/src/services/cache-service.ts +32 -10
- package/src/services/context.ts +27 -14
- package/src/services/event-service.ts +10 -8
- package/src/services/persistence-service.ts +550 -0
- package/src/services/read-service.ts +18 -18
- package/src/services/runtime-service.ts +27 -36
- package/src/services/session-operation-queue.ts +21 -0
- package/src/services/session-project-writer.ts +3 -1
- package/src/services/session-registry.ts +70 -0
- package/src/services/session-utils.ts +4 -4
- package/src/services/job-service.ts +0 -238
package/dist/index.mjs
CHANGED
|
@@ -3,8 +3,8 @@ import { applyUamTransactionAppAsync } from "@openfairygui/functions/uam";
|
|
|
3
3
|
import { ProjectReader, ProjectWriter } from "@openfairygui/core/project-io";
|
|
4
4
|
import { validateProject } from "@openfairygui/functions";
|
|
5
5
|
//#region src/contracts.ts
|
|
6
|
-
const BACKEND_CONTRACT_VERSION = "
|
|
7
|
-
const BACKEND_CAPABILITY_SCHEMA_VERSION =
|
|
6
|
+
const BACKEND_CONTRACT_VERSION = "3.0.0";
|
|
7
|
+
const BACKEND_CAPABILITY_SCHEMA_VERSION = 12;
|
|
8
8
|
const BACKEND_COMPATIBILITY_POLICY = {
|
|
9
9
|
incompatibleChange: "requires contractVersion bump",
|
|
10
10
|
capabilitySchemaChange: "requires capabilitySchemaVersion bump",
|
|
@@ -56,14 +56,6 @@ const write = {
|
|
|
56
56
|
kind: "host-action",
|
|
57
57
|
message: "Preserve the dirty session and inspect the error, actual target files and permissions with the host. Partial writes may have changed files: verify or recover them before a newly authorized save. Do not clear dirty state, discard memory or blindly retry."
|
|
58
58
|
};
|
|
59
|
-
const execution = {
|
|
60
|
-
kind: "host-action",
|
|
61
|
-
message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit."
|
|
62
|
-
};
|
|
63
|
-
const job = {
|
|
64
|
-
kind: "host-action",
|
|
65
|
-
message: "Inspect the job ID and status with getJob/listJobs. Do not fabricate, restart or force-cancel a missing, terminal or non-cancellable job. Ask the host before scheduling new work; cancellation is not success."
|
|
66
|
-
};
|
|
67
59
|
/** Exhaustiveness and exact ownership are checked against the canonical unions. */
|
|
68
60
|
const BACKEND_DIAGNOSTIC_GUIDES = [
|
|
69
61
|
{
|
|
@@ -114,6 +106,14 @@ const BACKEND_DIAGNOSTIC_GUIDES = [
|
|
|
114
106
|
message: "Ask the host to confirm the runtime and project, recover any unsaved state, then explicitly open a new session if appropriate. Session IDs are runtime-local. Read its new revision and replan; never reuse an expired session or assume disk contains unsaved changes."
|
|
115
107
|
}
|
|
116
108
|
},
|
|
109
|
+
{
|
|
110
|
+
code: "session_close_failed",
|
|
111
|
+
owners: ["backend"],
|
|
112
|
+
remediation: {
|
|
113
|
+
kind: "host-action",
|
|
114
|
+
message: "The session and lock ownership remain registered. Inspect the reported lock release failure, correct the storage problem, then retry closeSession with the same session ID. Do not remove the lock file or open a replacement session to bypass the owner."
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
117
|
{
|
|
118
118
|
code: "path_policy_violation",
|
|
119
119
|
owners: ["backend"],
|
|
@@ -594,27 +594,10 @@ const BACKEND_DIAGNOSTIC_GUIDES = [
|
|
|
594
594
|
{
|
|
595
595
|
code: "execution_failure",
|
|
596
596
|
owners: ["core.transaction"],
|
|
597
|
-
remediation:
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
owners: ["backend"],
|
|
602
|
-
remediation: execution
|
|
603
|
-
},
|
|
604
|
-
{
|
|
605
|
-
code: "job_not_found",
|
|
606
|
-
owners: ["backend"],
|
|
607
|
-
remediation: job
|
|
608
|
-
},
|
|
609
|
-
{
|
|
610
|
-
code: "job_not_cancellable",
|
|
611
|
-
owners: ["backend"],
|
|
612
|
-
remediation: job
|
|
613
|
-
},
|
|
614
|
-
{
|
|
615
|
-
code: "job_cancelled",
|
|
616
|
-
owners: ["backend"],
|
|
617
|
-
remediation: job
|
|
597
|
+
remediation: {
|
|
598
|
+
kind: "host-action",
|
|
599
|
+
message: "Inspect the execution/cache failure and current session/revision. Preserve sources and unsaved work and report the cause to the host. Replan after resolution; failed execution or cache work is not a completed edit."
|
|
600
|
+
}
|
|
618
601
|
}
|
|
619
602
|
];
|
|
620
603
|
const BACKEND_DIAGNOSTICS_URI = "openfairygui://docs/diagnostics";
|
|
@@ -647,82 +630,15 @@ function enrichBackendDiagnostic(diagnostic, sessionId) {
|
|
|
647
630
|
};
|
|
648
631
|
}
|
|
649
632
|
//#endregion
|
|
650
|
-
//#region src/
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
|
|
655
|
-
const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
|
|
656
|
-
const hasRoot = driveMatch ? true : remainder.startsWith("/");
|
|
657
|
-
const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
|
|
658
|
-
const segments = [];
|
|
659
|
-
for (const segment of rawSegments) {
|
|
660
|
-
if (segment === ".") continue;
|
|
661
|
-
if (segment === "..") {
|
|
662
|
-
if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
|
|
663
|
-
else if (!hasRoot) segments.push("..");
|
|
664
|
-
continue;
|
|
665
|
-
}
|
|
666
|
-
segments.push(segment);
|
|
667
|
-
}
|
|
668
|
-
const joined = segments.join("/");
|
|
669
|
-
return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
|
|
670
|
-
}
|
|
671
|
-
function createRuntimePathPolicy() {
|
|
672
|
-
return {
|
|
673
|
-
canonicalization: "realpath+normalized-casefold",
|
|
674
|
-
sessionIdentity: "project-root",
|
|
675
|
-
saveTarget: "opened-project-only",
|
|
676
|
-
outputTargets: "deferred",
|
|
677
|
-
workspaceBoundary: "project-root-only"
|
|
678
|
-
};
|
|
679
|
-
}
|
|
680
|
-
async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
|
|
681
|
-
const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
|
|
682
|
-
const root = normalizeComparablePath(resolvedRoot);
|
|
683
|
-
const target = normalizeComparablePath(resolvedTarget);
|
|
684
|
-
if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
|
|
685
|
-
if (target === root || target.startsWith(`${root}/`)) return;
|
|
686
|
-
const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
|
|
687
|
-
error.code = "EACCES";
|
|
688
|
-
throw error;
|
|
689
|
-
}
|
|
690
|
-
async function resolveFairyPath(fileSystem, input) {
|
|
691
|
-
const resolvedInput = fileSystem.resolve(input);
|
|
692
|
-
const stat = await fileSystem.stat(resolvedInput);
|
|
693
|
-
if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
|
|
694
|
-
if (stat.isDirectory()) {
|
|
695
|
-
const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
|
|
696
|
-
if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
|
|
697
|
-
if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
|
|
698
|
-
throw new Error(`No .fairy file found in ${resolvedInput}`);
|
|
699
|
-
}
|
|
700
|
-
throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
|
|
701
|
-
}
|
|
702
|
-
async function resolveCanonicalProjectRoot(fileSystem, input) {
|
|
703
|
-
const fairyPath = await resolveFairyPath(fileSystem, input);
|
|
704
|
-
const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
|
|
705
|
-
return {
|
|
706
|
-
fairyPath,
|
|
707
|
-
canonicalProjectPath,
|
|
708
|
-
canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
|
|
709
|
-
};
|
|
633
|
+
//#region src/services/context.ts
|
|
634
|
+
/** Borrow without copying the entire project before a read has checked its response budget. */
|
|
635
|
+
function readView(value) {
|
|
636
|
+
return value;
|
|
710
637
|
}
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
const allowedPath = await fileSystem.resolvePath(openedFairyPath);
|
|
715
|
-
if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
|
|
716
|
-
return {
|
|
717
|
-
code: "path_policy_violation",
|
|
718
|
-
message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
|
|
719
|
-
policy: "save_target",
|
|
720
|
-
attemptedPath,
|
|
721
|
-
allowedPath
|
|
722
|
-
};
|
|
638
|
+
/** A detached copy is writable again; this is the only conversion from a borrowed read view. */
|
|
639
|
+
function cloneReadData(value) {
|
|
640
|
+
return structuredClone(value);
|
|
723
641
|
}
|
|
724
|
-
//#endregion
|
|
725
|
-
//#region src/services/context.ts
|
|
726
642
|
function diagnosticFromError(error) {
|
|
727
643
|
return {
|
|
728
644
|
code: error.code,
|
|
@@ -743,7 +659,7 @@ function createMeta(stage, startedAt, options) {
|
|
|
743
659
|
diagnostics: (options?.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, options?.sessionId)),
|
|
744
660
|
stage,
|
|
745
661
|
contractVersion: BACKEND_CONTRACT_VERSION,
|
|
746
|
-
capabilitySchemaVersion:
|
|
662
|
+
capabilitySchemaVersion: 12
|
|
747
663
|
};
|
|
748
664
|
}
|
|
749
665
|
function success(stage, startedAt, data, options) {
|
|
@@ -766,68 +682,6 @@ function failure(stage, startedAt, error, session, options) {
|
|
|
766
682
|
};
|
|
767
683
|
}
|
|
768
684
|
//#endregion
|
|
769
|
-
//#region src/services/session-project-writer.ts
|
|
770
|
-
function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
|
|
771
|
-
const contained = async (targetPath, operation) => {
|
|
772
|
-
await assertProjectPathContained(fileSystem, projectRoot, targetPath);
|
|
773
|
-
return operation();
|
|
774
|
-
};
|
|
775
|
-
async function trackWrite(targetPath, write) {
|
|
776
|
-
try {
|
|
777
|
-
const result = await contained(targetPath, write);
|
|
778
|
-
writtenPaths.push(targetPath);
|
|
779
|
-
return result;
|
|
780
|
-
} catch (error) {
|
|
781
|
-
failedPaths.push(targetPath);
|
|
782
|
-
throw error;
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
return {
|
|
786
|
-
readFile: (path) => contained(path, () => fileSystem.readFile(path)),
|
|
787
|
-
readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
|
|
788
|
-
writeFile: (path, content) => trackWrite(path, async () => {
|
|
789
|
-
await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
|
|
790
|
-
await fileSystem.writeFile(path, content);
|
|
791
|
-
}),
|
|
792
|
-
writeFileRaw: (path, data) => trackWrite(path, async () => {
|
|
793
|
-
await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
|
|
794
|
-
await fileSystem.writeFileRaw(path, data);
|
|
795
|
-
}),
|
|
796
|
-
mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
|
|
797
|
-
readdir: (path) => contained(path, () => fileSystem.readdir(path)),
|
|
798
|
-
async exists(path) {
|
|
799
|
-
await assertProjectPathContained(fileSystem, projectRoot, path);
|
|
800
|
-
try {
|
|
801
|
-
await fileSystem.stat(path);
|
|
802
|
-
return true;
|
|
803
|
-
} catch {
|
|
804
|
-
return false;
|
|
805
|
-
}
|
|
806
|
-
},
|
|
807
|
-
join: (...paths) => fileSystem.join(...paths),
|
|
808
|
-
dirname: (path) => fileSystem.dirname(path),
|
|
809
|
-
unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
|
|
810
|
-
rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
|
|
811
|
-
};
|
|
812
|
-
}
|
|
813
|
-
async function writeSessionProject(input) {
|
|
814
|
-
const projectRoot = input.fileSystem.dirname(input.fairyPath);
|
|
815
|
-
const write = async (fileSystem) => {
|
|
816
|
-
await new ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
|
|
817
|
-
staleSourceFiles: input.staleSourceFiles,
|
|
818
|
-
staleResourceFolders: input.staleResourceFolders,
|
|
819
|
-
staleBranchDirectories: input.staleBranchDirectories
|
|
820
|
-
});
|
|
821
|
-
};
|
|
822
|
-
if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
|
|
823
|
-
try {
|
|
824
|
-
await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
|
|
825
|
-
} catch (error) {
|
|
826
|
-
input.writtenPaths.length = 0;
|
|
827
|
-
throw error;
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
//#endregion
|
|
831
685
|
//#region src/services/session-utils.ts
|
|
832
686
|
function toSessionSnapshot(session, capabilities) {
|
|
833
687
|
return {
|
|
@@ -838,7 +692,7 @@ function toSessionSnapshot(session, capabilities) {
|
|
|
838
692
|
dirty: session.dirty,
|
|
839
693
|
uamFidelity: session.uamFidelity,
|
|
840
694
|
lockHeld: session.lockHeld,
|
|
841
|
-
capabilities:
|
|
695
|
+
capabilities: cloneReadData(capabilities)
|
|
842
696
|
};
|
|
843
697
|
}
|
|
844
698
|
function createSessionNotFoundError(sessionId) {
|
|
@@ -893,6 +747,22 @@ const BACKEND_RESOURCE_QUERY_FIELDS = [
|
|
|
893
747
|
"image",
|
|
894
748
|
"movieClip"
|
|
895
749
|
];
|
|
750
|
+
/** A failed staged write with an explicit outcome for the original project. */
|
|
751
|
+
var ProjectWriteTransactionError = class extends Error {
|
|
752
|
+
code = "project_write_transaction_failed";
|
|
753
|
+
/** Recognizes the same contract across separately bundled Node/root or ESM/CJS entries. */
|
|
754
|
+
static is(error) {
|
|
755
|
+
if (typeof error !== "object" || error === null) return false;
|
|
756
|
+
const value = error;
|
|
757
|
+
return value.code === "project_write_transaction_failed" && typeof value.message === "string" && typeof value.diskMayBePartiallyUpdated === "boolean" && Array.isArray(value.recoveryPaths) && value.recoveryPaths.every((path) => typeof path === "string");
|
|
758
|
+
}
|
|
759
|
+
constructor(cause, diskMayBePartiallyUpdated, recoveryPaths = []) {
|
|
760
|
+
super(cause instanceof Error ? cause.message : String(cause), { cause });
|
|
761
|
+
this.diskMayBePartiallyUpdated = diskMayBePartiallyUpdated;
|
|
762
|
+
this.recoveryPaths = recoveryPaths;
|
|
763
|
+
this.name = "ProjectWriteTransactionError";
|
|
764
|
+
}
|
|
765
|
+
};
|
|
896
766
|
//#endregion
|
|
897
767
|
//#region src/services/capture-project.ts
|
|
898
768
|
function createCaptureFileSystem(files, directories) {
|
|
@@ -1163,52 +1033,6 @@ function toBackendDiagnostics(error) {
|
|
|
1163
1033
|
opId: error.opId
|
|
1164
1034
|
}];
|
|
1165
1035
|
}
|
|
1166
|
-
function createCapabilityUnavailableError$1(message) {
|
|
1167
|
-
return {
|
|
1168
|
-
code: "capability_unavailable",
|
|
1169
|
-
message,
|
|
1170
|
-
capability: "fileSystem",
|
|
1171
|
-
requiredAdapter: "BackendFileSystem"
|
|
1172
|
-
};
|
|
1173
|
-
}
|
|
1174
|
-
function createUamFidelityUnsupportedError(session) {
|
|
1175
|
-
return {
|
|
1176
|
-
code: "uam_fidelity_unsupported",
|
|
1177
|
-
message: "The source project contains formal properties that the current UAM cannot preserve.",
|
|
1178
|
-
sessionId: session.sessionId,
|
|
1179
|
-
canonicalPathKey: session.canonicalPathKey
|
|
1180
|
-
};
|
|
1181
|
-
}
|
|
1182
|
-
function validationDiagnostics(sessionProject) {
|
|
1183
|
-
return validateUamProject(sessionProject).map((issue) => ({
|
|
1184
|
-
code: "materialize_validation_failed",
|
|
1185
|
-
message: issue.message,
|
|
1186
|
-
severity: "error",
|
|
1187
|
-
path: issue.path,
|
|
1188
|
-
operationKind: "materializeSession"
|
|
1189
|
-
}));
|
|
1190
|
-
}
|
|
1191
|
-
function toMaterializeSnapshot(session, capabilities, input) {
|
|
1192
|
-
return {
|
|
1193
|
-
...toSessionSnapshot(session, capabilities),
|
|
1194
|
-
mode: "fullProject",
|
|
1195
|
-
reason: input.reason,
|
|
1196
|
-
materializeRevision: session.revision,
|
|
1197
|
-
saveRevision: session.lastSavedRevision,
|
|
1198
|
-
writtenPaths: [...input.writtenPaths],
|
|
1199
|
-
skippedPaths: [...input.skippedPaths],
|
|
1200
|
-
diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
|
|
1201
|
-
};
|
|
1202
|
-
}
|
|
1203
|
-
function storageCanonicalTarget(input) {
|
|
1204
|
-
const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
|
|
1205
|
-
return {
|
|
1206
|
-
fileSystem: input.fileSystem,
|
|
1207
|
-
fairyPath: input.fairyPath,
|
|
1208
|
-
canonicalProjectPath,
|
|
1209
|
-
canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
|
|
1210
|
-
};
|
|
1211
|
-
}
|
|
1212
1036
|
function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
1213
1037
|
if (!value || typeof value !== "object" || seen.has(value)) return;
|
|
1214
1038
|
seen.add(value);
|
|
@@ -1221,32 +1045,16 @@ function detachSharedByteViews(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
|
1221
1045
|
}
|
|
1222
1046
|
}
|
|
1223
1047
|
var AuthoringService = class {
|
|
1224
|
-
|
|
1225
|
-
constructor(context, cacheService, eventService) {
|
|
1048
|
+
constructor(context, cacheService, eventService, sessionOperations) {
|
|
1226
1049
|
this.context = context;
|
|
1227
1050
|
this.cacheService = cacheService;
|
|
1228
1051
|
this.eventService = eventService;
|
|
1229
|
-
|
|
1230
|
-
async runSessionExclusive(sessionId, operation) {
|
|
1231
|
-
const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
|
|
1232
|
-
let release = () => void 0;
|
|
1233
|
-
const current = new Promise((resolve) => {
|
|
1234
|
-
release = resolve;
|
|
1235
|
-
});
|
|
1236
|
-
const tail = previous.then(() => current);
|
|
1237
|
-
this.sessionOperations.set(sessionId, tail);
|
|
1238
|
-
await previous;
|
|
1239
|
-
try {
|
|
1240
|
-
return await operation();
|
|
1241
|
-
} finally {
|
|
1242
|
-
release();
|
|
1243
|
-
if (this.sessionOperations.get(sessionId) === tail) this.sessionOperations.delete(sessionId);
|
|
1244
|
-
}
|
|
1052
|
+
this.sessionOperations = sessionOperations;
|
|
1245
1053
|
}
|
|
1246
1054
|
async preflightTransaction(input) {
|
|
1247
1055
|
const queuedInput = structuredClone(input);
|
|
1248
1056
|
detachSharedByteViews(queuedInput);
|
|
1249
|
-
return this.
|
|
1057
|
+
return this.sessionOperations.run(queuedInput.sessionId, async () => {
|
|
1250
1058
|
const startedAt = Date.now();
|
|
1251
1059
|
const session = this.context.sessions.get(queuedInput.sessionId);
|
|
1252
1060
|
if (!session || session.closed) return failure("authoring", startedAt, createSessionNotFoundError(queuedInput.sessionId));
|
|
@@ -1286,7 +1094,7 @@ var AuthoringService = class {
|
|
|
1286
1094
|
async applyTransaction(input) {
|
|
1287
1095
|
const queuedInput = structuredClone(input);
|
|
1288
1096
|
detachSharedByteViews(queuedInput);
|
|
1289
|
-
return this.
|
|
1097
|
+
return this.sessionOperations.run(queuedInput.sessionId, () => this.applyTransactionExclusive(queuedInput));
|
|
1290
1098
|
}
|
|
1291
1099
|
async applyTransactionExclusive(input) {
|
|
1292
1100
|
const startedAt = Date.now();
|
|
@@ -1347,6 +1155,200 @@ var AuthoringService = class {
|
|
|
1347
1155
|
revision: session.revision
|
|
1348
1156
|
});
|
|
1349
1157
|
}
|
|
1158
|
+
};
|
|
1159
|
+
//#endregion
|
|
1160
|
+
//#region src/path-policy.ts
|
|
1161
|
+
function normalizeComparablePath(value) {
|
|
1162
|
+
const normalized = value.replace(/[/\\]+$/, "").replace(/\\/g, "/");
|
|
1163
|
+
const driveMatch = normalized.match(/^([a-z]:)(?:\/(.*))?$/i);
|
|
1164
|
+
const drivePrefix = driveMatch?.[1].toLowerCase() ?? "";
|
|
1165
|
+
const remainder = driveMatch ? driveMatch[2] ?? "" : normalized;
|
|
1166
|
+
const hasRoot = driveMatch ? true : remainder.startsWith("/");
|
|
1167
|
+
const rawSegments = remainder.split("/").filter((segment) => segment.length > 0);
|
|
1168
|
+
const segments = [];
|
|
1169
|
+
for (const segment of rawSegments) {
|
|
1170
|
+
if (segment === ".") continue;
|
|
1171
|
+
if (segment === "..") {
|
|
1172
|
+
if (segments.length > 0 && segments[segments.length - 1] !== "..") segments.pop();
|
|
1173
|
+
else if (!hasRoot) segments.push("..");
|
|
1174
|
+
continue;
|
|
1175
|
+
}
|
|
1176
|
+
segments.push(segment);
|
|
1177
|
+
}
|
|
1178
|
+
const joined = segments.join("/");
|
|
1179
|
+
return (drivePrefix ? `${drivePrefix}/${joined}`.replace(/\/$/, "") : hasRoot ? `/${joined}`.replace(/\/$/, "") : joined || ".").toLowerCase();
|
|
1180
|
+
}
|
|
1181
|
+
function createRuntimePathPolicy() {
|
|
1182
|
+
return {
|
|
1183
|
+
canonicalization: "realpath+normalized-casefold",
|
|
1184
|
+
sessionIdentity: "project-root",
|
|
1185
|
+
saveTarget: "opened-project-only",
|
|
1186
|
+
outputTargets: "deferred",
|
|
1187
|
+
workspaceBoundary: "project-root-only"
|
|
1188
|
+
};
|
|
1189
|
+
}
|
|
1190
|
+
async function assertProjectPathContained(fileSystem, projectRoot, targetPath) {
|
|
1191
|
+
const [resolvedRoot, resolvedTarget] = await Promise.all([fileSystem.resolvePath(projectRoot), fileSystem.resolvePath(targetPath)]);
|
|
1192
|
+
const root = normalizeComparablePath(resolvedRoot);
|
|
1193
|
+
const target = normalizeComparablePath(resolvedTarget);
|
|
1194
|
+
if (root === "." && !target.startsWith("/") && !/^[a-z]:\//i.test(target)) return;
|
|
1195
|
+
if (target === root || target.startsWith(`${root}/`)) return;
|
|
1196
|
+
const error = /* @__PURE__ */ new Error(`Project path escapes the opened root: ${targetPath}`);
|
|
1197
|
+
error.code = "EACCES";
|
|
1198
|
+
throw error;
|
|
1199
|
+
}
|
|
1200
|
+
async function resolveFairyPath(fileSystem, input) {
|
|
1201
|
+
const resolvedInput = fileSystem.resolve(input);
|
|
1202
|
+
const stat = await fileSystem.stat(resolvedInput);
|
|
1203
|
+
if (stat.isFile() && resolvedInput.endsWith(".fairy")) return await fileSystem.resolvePath(resolvedInput);
|
|
1204
|
+
if (stat.isDirectory()) {
|
|
1205
|
+
const fairyFiles = (await fileSystem.readdir(resolvedInput)).filter((entry) => entry.endsWith(".fairy"));
|
|
1206
|
+
if (fairyFiles.length === 1) return await fileSystem.resolvePath(fileSystem.join(resolvedInput, fairyFiles[0]));
|
|
1207
|
+
if (fairyFiles.length > 1) throw new Error(`Multiple .fairy files found in ${resolvedInput}: ${fairyFiles.join(", ")}`);
|
|
1208
|
+
throw new Error(`No .fairy file found in ${resolvedInput}`);
|
|
1209
|
+
}
|
|
1210
|
+
throw new Error(`Input is not a .fairy file or directory: ${resolvedInput}`);
|
|
1211
|
+
}
|
|
1212
|
+
async function resolveCanonicalProjectRoot(fileSystem, input) {
|
|
1213
|
+
const fairyPath = await resolveFairyPath(fileSystem, input);
|
|
1214
|
+
const canonicalProjectPath = await fileSystem.resolvePath(fileSystem.dirname(fairyPath));
|
|
1215
|
+
return {
|
|
1216
|
+
fairyPath,
|
|
1217
|
+
canonicalProjectPath,
|
|
1218
|
+
canonicalPathKey: normalizeComparablePath(canonicalProjectPath)
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
async function validateSaveTarget(fileSystem, openedFairyPath, targetPath) {
|
|
1222
|
+
if (!targetPath) return null;
|
|
1223
|
+
const attemptedPath = await fileSystem.resolvePath(fileSystem.resolve(targetPath));
|
|
1224
|
+
const allowedPath = await fileSystem.resolvePath(openedFairyPath);
|
|
1225
|
+
if (normalizeComparablePath(attemptedPath) === normalizeComparablePath(allowedPath)) return null;
|
|
1226
|
+
return {
|
|
1227
|
+
code: "path_policy_violation",
|
|
1228
|
+
message: `Save target is restricted to the originally opened project file: ${allowedPath}`,
|
|
1229
|
+
policy: "save_target",
|
|
1230
|
+
attemptedPath,
|
|
1231
|
+
allowedPath
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
//#endregion
|
|
1235
|
+
//#region src/services/session-project-writer.ts
|
|
1236
|
+
function createWriterFileSystem(fileSystem, projectRoot, writtenPaths, failedPaths) {
|
|
1237
|
+
const contained = async (targetPath, operation) => {
|
|
1238
|
+
await assertProjectPathContained(fileSystem, projectRoot, targetPath);
|
|
1239
|
+
return operation();
|
|
1240
|
+
};
|
|
1241
|
+
async function trackWrite(targetPath, write) {
|
|
1242
|
+
try {
|
|
1243
|
+
const result = await contained(targetPath, write);
|
|
1244
|
+
writtenPaths.push(targetPath);
|
|
1245
|
+
return result;
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
failedPaths.push(targetPath);
|
|
1248
|
+
throw error;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
return {
|
|
1252
|
+
resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
|
|
1253
|
+
readFile: (path) => contained(path, () => fileSystem.readFile(path)),
|
|
1254
|
+
readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
|
|
1255
|
+
writeFile: (path, content) => trackWrite(path, async () => {
|
|
1256
|
+
await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
|
|
1257
|
+
await fileSystem.writeFile(path, content);
|
|
1258
|
+
}),
|
|
1259
|
+
writeFileRaw: (path, data) => trackWrite(path, async () => {
|
|
1260
|
+
await fileSystem.mkdir(fileSystem.dirname(path), { recursive: true });
|
|
1261
|
+
await fileSystem.writeFileRaw(path, data);
|
|
1262
|
+
}),
|
|
1263
|
+
mkdir: (path) => contained(path, () => fileSystem.mkdir(path, { recursive: true })),
|
|
1264
|
+
readdir: (path) => contained(path, () => fileSystem.readdir(path)),
|
|
1265
|
+
async exists(path) {
|
|
1266
|
+
await assertProjectPathContained(fileSystem, projectRoot, path);
|
|
1267
|
+
try {
|
|
1268
|
+
await fileSystem.stat(path);
|
|
1269
|
+
return true;
|
|
1270
|
+
} catch {
|
|
1271
|
+
return false;
|
|
1272
|
+
}
|
|
1273
|
+
},
|
|
1274
|
+
join: (...paths) => fileSystem.join(...paths),
|
|
1275
|
+
dirname: (path) => fileSystem.dirname(path),
|
|
1276
|
+
unlink: (path) => trackWrite(path, () => fileSystem.unlink(path)),
|
|
1277
|
+
rmdir: (path) => trackWrite(path, () => fileSystem.rmdir(path))
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
async function writeSessionProject(input) {
|
|
1281
|
+
const projectRoot = input.fileSystem.dirname(input.fairyPath);
|
|
1282
|
+
const write = async (fileSystem) => {
|
|
1283
|
+
await new ProjectWriter(createWriterFileSystem(fileSystem, projectRoot, input.writtenPaths, input.failedPaths)).write(input.document, input.fairyPath, {
|
|
1284
|
+
staleSourceFiles: input.staleSourceFiles,
|
|
1285
|
+
staleResourceFolders: input.staleResourceFolders,
|
|
1286
|
+
staleBranchDirectories: input.staleBranchDirectories
|
|
1287
|
+
});
|
|
1288
|
+
};
|
|
1289
|
+
if (!input.fileSystem.runProjectWriteTransaction) return write(input.fileSystem);
|
|
1290
|
+
try {
|
|
1291
|
+
await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
|
|
1292
|
+
} catch (error) {
|
|
1293
|
+
if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
|
|
1294
|
+
throw error;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
//#endregion
|
|
1298
|
+
//#region src/services/persistence-service.ts
|
|
1299
|
+
function createCapabilityUnavailableError$1(message) {
|
|
1300
|
+
return {
|
|
1301
|
+
code: "capability_unavailable",
|
|
1302
|
+
message,
|
|
1303
|
+
capability: "fileSystem",
|
|
1304
|
+
requiredAdapter: "BackendFileSystem"
|
|
1305
|
+
};
|
|
1306
|
+
}
|
|
1307
|
+
function createUamFidelityUnsupportedError(session) {
|
|
1308
|
+
return {
|
|
1309
|
+
code: "uam_fidelity_unsupported",
|
|
1310
|
+
message: "The source project contains formal properties that the current UAM cannot preserve.",
|
|
1311
|
+
sessionId: session.sessionId,
|
|
1312
|
+
canonicalPathKey: session.canonicalPathKey
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
function validationDiagnostics(sessionProject) {
|
|
1316
|
+
return validateUamProject(sessionProject).map((issue) => ({
|
|
1317
|
+
code: "materialize_validation_failed",
|
|
1318
|
+
message: issue.message,
|
|
1319
|
+
severity: "error",
|
|
1320
|
+
path: issue.path,
|
|
1321
|
+
operationKind: "materializeSession"
|
|
1322
|
+
}));
|
|
1323
|
+
}
|
|
1324
|
+
function toMaterializeSnapshot(session, capabilities, input) {
|
|
1325
|
+
return {
|
|
1326
|
+
...toSessionSnapshot(session, capabilities),
|
|
1327
|
+
mode: "fullProject",
|
|
1328
|
+
reason: input.reason,
|
|
1329
|
+
materializeRevision: session.revision,
|
|
1330
|
+
saveRevision: session.lastSavedRevision,
|
|
1331
|
+
writtenPaths: [...input.writtenPaths],
|
|
1332
|
+
skippedPaths: [...input.skippedPaths],
|
|
1333
|
+
diagnostics: input.diagnostics.map((diagnostic) => ({ ...diagnostic }))
|
|
1334
|
+
};
|
|
1335
|
+
}
|
|
1336
|
+
function storageCanonicalTarget(input) {
|
|
1337
|
+
const canonicalProjectPath = input.canonicalProjectPath ?? (input.fileSystem.dirname(input.fairyPath) || ".");
|
|
1338
|
+
return {
|
|
1339
|
+
fileSystem: input.fileSystem,
|
|
1340
|
+
fairyPath: input.fairyPath,
|
|
1341
|
+
canonicalProjectPath,
|
|
1342
|
+
canonicalPathKey: input.canonicalPathKey ?? normalizeComparablePath(canonicalProjectPath)
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
var PersistenceService = class {
|
|
1346
|
+
constructor(context, cacheService, eventService, sessionOperations) {
|
|
1347
|
+
this.context = context;
|
|
1348
|
+
this.cacheService = cacheService;
|
|
1349
|
+
this.eventService = eventService;
|
|
1350
|
+
this.sessionOperations = sessionOperations;
|
|
1351
|
+
}
|
|
1350
1352
|
async saveSession(input) {
|
|
1351
1353
|
if (input.force === true || input.mode === "materializeCleanSession") return this.materializeSession({
|
|
1352
1354
|
sessionId: input.sessionId,
|
|
@@ -1356,7 +1358,8 @@ var AuthoringService = class {
|
|
|
1356
1358
|
mode: "fullProject",
|
|
1357
1359
|
reason: "force_save"
|
|
1358
1360
|
});
|
|
1359
|
-
|
|
1361
|
+
const captured = { ...input };
|
|
1362
|
+
return this.sessionOperations.run(captured.sessionId, () => this.saveSessionExclusive(captured));
|
|
1360
1363
|
}
|
|
1361
1364
|
finishSuccessfulSave(session) {
|
|
1362
1365
|
session.lastSavedRevision = session.revision;
|
|
@@ -1448,7 +1451,8 @@ var AuthoringService = class {
|
|
|
1448
1451
|
lastSavedRevision: session.lastSavedRevision,
|
|
1449
1452
|
committedPaths,
|
|
1450
1453
|
failedPaths,
|
|
1451
|
-
diskMayBePartiallyUpdated: !
|
|
1454
|
+
diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
|
|
1455
|
+
...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
|
|
1452
1456
|
}, toSessionSnapshot(session, this.context.capabilities), {
|
|
1453
1457
|
sessionId: session.sessionId,
|
|
1454
1458
|
revision: session.revision
|
|
@@ -1456,7 +1460,11 @@ var AuthoringService = class {
|
|
|
1456
1460
|
}
|
|
1457
1461
|
}
|
|
1458
1462
|
async materializeSession(input) {
|
|
1459
|
-
|
|
1463
|
+
const captured = {
|
|
1464
|
+
...input,
|
|
1465
|
+
storage: input.storage && { ...input.storage }
|
|
1466
|
+
};
|
|
1467
|
+
return this.sessionOperations.run(captured.sessionId, () => this.materializeSessionExclusive(captured));
|
|
1460
1468
|
}
|
|
1461
1469
|
async materializeSessionExclusive(input) {
|
|
1462
1470
|
const startedAt = Date.now();
|
|
@@ -1473,24 +1481,21 @@ var AuthoringService = class {
|
|
|
1473
1481
|
revision: session.revision
|
|
1474
1482
|
});
|
|
1475
1483
|
const fairyPath = storageTarget?.fairyPath ?? session.fairyPath;
|
|
1484
|
+
if (session.lockHeld && (fileSystem !== session.fileSystem || fairyPath !== session.fairyPath || storageTarget && (storageTarget.canonicalPathKey !== session.canonicalPathKey || storageTarget.canonicalProjectPath !== session.canonicalProjectPath))) return failure("authoring", startedAt, {
|
|
1485
|
+
code: "path_policy_violation",
|
|
1486
|
+
message: "A locked file-backed session must keep its opened storage binding.",
|
|
1487
|
+
policy: "save_target",
|
|
1488
|
+
attemptedPath: fairyPath,
|
|
1489
|
+
allowedPath: session.fairyPath
|
|
1490
|
+
}, toSessionSnapshot(session, this.context.capabilities), {
|
|
1491
|
+
sessionId: session.sessionId,
|
|
1492
|
+
revision: session.revision
|
|
1493
|
+
});
|
|
1476
1494
|
const targetViolation = await validateSaveTarget(fileSystem, fairyPath, input.targetPath);
|
|
1477
1495
|
if (targetViolation) return failure("authoring", startedAt, targetViolation, toSessionSnapshot(session, this.context.capabilities), {
|
|
1478
1496
|
sessionId: session.sessionId,
|
|
1479
1497
|
revision: session.revision
|
|
1480
1498
|
});
|
|
1481
|
-
if (storageTarget) {
|
|
1482
|
-
const holderSessionId = this.context.sessionsByPath.get(storageTarget.canonicalPathKey);
|
|
1483
|
-
if (holderSessionId && holderSessionId !== session.sessionId) return failure("authoring", startedAt, {
|
|
1484
|
-
code: "lock_conflict",
|
|
1485
|
-
kind: "in_process_session_exists",
|
|
1486
|
-
message: `Project is already open in this backend runtime: ${storageTarget.canonicalProjectPath}`,
|
|
1487
|
-
canonicalPathKey: storageTarget.canonicalPathKey,
|
|
1488
|
-
holderSessionId
|
|
1489
|
-
}, toSessionSnapshot(session, this.context.capabilities), {
|
|
1490
|
-
sessionId: session.sessionId,
|
|
1491
|
-
revision: session.revision
|
|
1492
|
-
});
|
|
1493
|
-
}
|
|
1494
1499
|
if (session.uamFidelity === "unsupported") return failure("authoring", startedAt, createUamFidelityUnsupportedError(session), toSessionSnapshot(session, this.context.capabilities), {
|
|
1495
1500
|
sessionId: session.sessionId,
|
|
1496
1501
|
revision: session.revision
|
|
@@ -1534,6 +1539,11 @@ var AuthoringService = class {
|
|
|
1534
1539
|
const writtenPaths = [];
|
|
1535
1540
|
const failedPaths = [];
|
|
1536
1541
|
const skippedPaths = [];
|
|
1542
|
+
const reservation = storageTarget ? this.context.sessions.reserve(session.sessionId, storageTarget) : null;
|
|
1543
|
+
if (reservation && "code" in reservation) return failure("authoring", startedAt, reservation, toSessionSnapshot(session, this.context.capabilities), {
|
|
1544
|
+
sessionId: session.sessionId,
|
|
1545
|
+
revision: session.revision
|
|
1546
|
+
});
|
|
1537
1547
|
this.eventService.emit({
|
|
1538
1548
|
kind: "save.started",
|
|
1539
1549
|
sessionId: session.sessionId,
|
|
@@ -1563,14 +1573,7 @@ var AuthoringService = class {
|
|
|
1563
1573
|
session.pendingStaleBranchDirectories.clear();
|
|
1564
1574
|
}
|
|
1565
1575
|
if (isSessionStorageTarget || storageTarget) commitUamProjectSourcePaths(session.project);
|
|
1566
|
-
|
|
1567
|
-
this.context.sessionsByPath.delete(session.canonicalPathKey);
|
|
1568
|
-
session.fileSystem = storageTarget.fileSystem;
|
|
1569
|
-
session.fairyPath = storageTarget.fairyPath;
|
|
1570
|
-
session.canonicalProjectPath = storageTarget.canonicalProjectPath;
|
|
1571
|
-
session.canonicalPathKey = storageTarget.canonicalPathKey;
|
|
1572
|
-
this.context.sessionsByPath.set(session.canonicalPathKey, session.sessionId);
|
|
1573
|
-
}
|
|
1576
|
+
reservation?.commit(session);
|
|
1574
1577
|
this.finishSuccessfulSave(session);
|
|
1575
1578
|
return success("authoring", startedAt, toMaterializeSnapshot(session, this.context.capabilities, {
|
|
1576
1579
|
reason: input.reason,
|
|
@@ -1608,12 +1611,15 @@ var AuthoringService = class {
|
|
|
1608
1611
|
failedPaths,
|
|
1609
1612
|
skippedPaths,
|
|
1610
1613
|
diagnostics: diagnosticsFromError,
|
|
1611
|
-
diskMayBePartiallyUpdated: !
|
|
1614
|
+
diskMayBePartiallyUpdated: !ProjectWriteTransactionError.is(error) || error.diskMayBePartiallyUpdated,
|
|
1615
|
+
...ProjectWriteTransactionError.is(error) && error.recoveryPaths.length ? { recoveryPaths: error.recoveryPaths } : {}
|
|
1612
1616
|
}, toSessionSnapshot(session, this.context.capabilities), {
|
|
1613
1617
|
sessionId: session.sessionId,
|
|
1614
1618
|
revision: session.revision,
|
|
1615
1619
|
diagnostics: diagnosticsFromError
|
|
1616
1620
|
});
|
|
1621
|
+
} finally {
|
|
1622
|
+
reservation?.release();
|
|
1617
1623
|
}
|
|
1618
1624
|
}
|
|
1619
1625
|
};
|
|
@@ -1636,14 +1642,16 @@ function createCacheEntry(session, valid) {
|
|
|
1636
1642
|
};
|
|
1637
1643
|
}
|
|
1638
1644
|
var CacheService = class {
|
|
1639
|
-
|
|
1640
|
-
|
|
1645
|
+
cacheBySession = /* @__PURE__ */ new Map();
|
|
1646
|
+
constructor(getSession, events) {
|
|
1647
|
+
this.getSession = getSession;
|
|
1648
|
+
this.events = events;
|
|
1641
1649
|
}
|
|
1642
1650
|
getCacheSnapshot(input) {
|
|
1643
1651
|
const startedAt = Date.now();
|
|
1644
|
-
const session = this.
|
|
1652
|
+
const session = this.getSession(input.sessionId);
|
|
1645
1653
|
if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1646
|
-
const entry = this.
|
|
1654
|
+
const entry = this.cacheBySession.get(input.sessionId);
|
|
1647
1655
|
return success("read", startedAt, {
|
|
1648
1656
|
cacheRevision: entry?.revision ?? session.revision,
|
|
1649
1657
|
entries: entry ? [structuredClone(entry)] : []
|
|
@@ -1652,47 +1660,145 @@ var CacheService = class {
|
|
|
1652
1660
|
revision: session.revision
|
|
1653
1661
|
});
|
|
1654
1662
|
}
|
|
1663
|
+
refreshCache(input) {
|
|
1664
|
+
const startedAt = Date.now();
|
|
1665
|
+
const session = this.getSession(input.sessionId);
|
|
1666
|
+
if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1667
|
+
const entry = this.refreshSession(session);
|
|
1668
|
+
this.events.emit({
|
|
1669
|
+
kind: "cache.updated",
|
|
1670
|
+
sessionId: session.sessionId,
|
|
1671
|
+
canonicalPathKey: session.canonicalPathKey,
|
|
1672
|
+
revision: session.revision,
|
|
1673
|
+
cacheRevision: entry.revision,
|
|
1674
|
+
payload: { reason: input.reason ?? "manual" }
|
|
1675
|
+
});
|
|
1676
|
+
return success("runtime", startedAt, {
|
|
1677
|
+
cacheRevision: entry.revision,
|
|
1678
|
+
entries: [structuredClone(entry)]
|
|
1679
|
+
}, {
|
|
1680
|
+
sessionId: session.sessionId,
|
|
1681
|
+
revision: session.revision
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1655
1684
|
refreshSession(session) {
|
|
1656
1685
|
const entry = createCacheEntry(session, true);
|
|
1657
|
-
this.
|
|
1686
|
+
this.cacheBySession.set(session.sessionId, entry);
|
|
1658
1687
|
return entry;
|
|
1659
1688
|
}
|
|
1660
1689
|
invalidateSession(session) {
|
|
1661
1690
|
const entry = createCacheEntry(session, false);
|
|
1662
|
-
this.
|
|
1691
|
+
this.cacheBySession.set(session.sessionId, entry);
|
|
1663
1692
|
return entry;
|
|
1664
1693
|
}
|
|
1665
1694
|
removeSession(sessionId) {
|
|
1666
|
-
this.
|
|
1695
|
+
this.cacheBySession.delete(sessionId);
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1698
|
+
//#endregion
|
|
1699
|
+
//#region src/services/session-registry.ts
|
|
1700
|
+
/** Owns live sessions and path claims, including claims made before asynchronous I/O. */
|
|
1701
|
+
var SessionRegistry = class {
|
|
1702
|
+
sessions = /* @__PURE__ */ new Map();
|
|
1703
|
+
paths = /* @__PURE__ */ new Map();
|
|
1704
|
+
opening = /* @__PURE__ */ new Set();
|
|
1705
|
+
get(sessionId) {
|
|
1706
|
+
return this.sessions.get(sessionId);
|
|
1707
|
+
}
|
|
1708
|
+
has(sessionId) {
|
|
1709
|
+
return this.sessions.has(sessionId) || this.opening.has(sessionId);
|
|
1710
|
+
}
|
|
1711
|
+
reserve(sessionId, target) {
|
|
1712
|
+
const key = target.canonicalPathKey;
|
|
1713
|
+
const previous = this.paths.get(key);
|
|
1714
|
+
if (previous && previous.sessionId !== sessionId) return {
|
|
1715
|
+
code: "lock_conflict",
|
|
1716
|
+
kind: "in_process_session_exists",
|
|
1717
|
+
message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
|
|
1718
|
+
canonicalPathKey: key,
|
|
1719
|
+
holderSessionId: previous.sessionId,
|
|
1720
|
+
lockFilePath: target.lockFilePath
|
|
1721
|
+
};
|
|
1722
|
+
const claim = previous ?? { sessionId };
|
|
1723
|
+
this.paths.set(key, claim);
|
|
1724
|
+
if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
|
|
1725
|
+
let committed = false;
|
|
1726
|
+
return {
|
|
1727
|
+
commit: (session) => {
|
|
1728
|
+
if (session.sessionId !== sessionId || this.paths.get(key) !== claim) throw new Error("Session path reservation lost.");
|
|
1729
|
+
if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
|
|
1730
|
+
Object.assign(session, target);
|
|
1731
|
+
this.sessions.set(sessionId, session);
|
|
1732
|
+
this.opening.delete(sessionId);
|
|
1733
|
+
committed = true;
|
|
1734
|
+
},
|
|
1735
|
+
release: () => {
|
|
1736
|
+
if (committed) return;
|
|
1737
|
+
if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
|
|
1738
|
+
this.opening.delete(sessionId);
|
|
1739
|
+
}
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
remove(session) {
|
|
1743
|
+
if (this.sessions.get(session.sessionId) !== session) return;
|
|
1744
|
+
this.sessions.delete(session.sessionId);
|
|
1745
|
+
this.releasePath(session.canonicalPathKey, session.sessionId);
|
|
1746
|
+
}
|
|
1747
|
+
releasePath(key, sessionId) {
|
|
1748
|
+
if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
|
|
1749
|
+
}
|
|
1750
|
+
};
|
|
1751
|
+
//#endregion
|
|
1752
|
+
//#region src/services/session-operation-queue.ts
|
|
1753
|
+
/** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
|
|
1754
|
+
var SessionOperationQueue = class {
|
|
1755
|
+
operations = /* @__PURE__ */ new Map();
|
|
1756
|
+
async run(sessionId, operation) {
|
|
1757
|
+
const previous = this.operations.get(sessionId) ?? Promise.resolve();
|
|
1758
|
+
let release = () => void 0;
|
|
1759
|
+
const current = new Promise((resolve) => {
|
|
1760
|
+
release = resolve;
|
|
1761
|
+
});
|
|
1762
|
+
const tail = previous.then(() => current);
|
|
1763
|
+
this.operations.set(sessionId, tail);
|
|
1764
|
+
await previous;
|
|
1765
|
+
try {
|
|
1766
|
+
return await operation();
|
|
1767
|
+
} finally {
|
|
1768
|
+
release();
|
|
1769
|
+
if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
|
|
1770
|
+
}
|
|
1667
1771
|
}
|
|
1668
1772
|
};
|
|
1669
1773
|
//#endregion
|
|
1670
1774
|
//#region src/services/event-service.ts
|
|
1671
1775
|
const DEFAULT_EVENT_RETENTION_LIMIT = 1e3;
|
|
1672
1776
|
var EventService = class {
|
|
1673
|
-
|
|
1674
|
-
|
|
1777
|
+
eventsBySession = /* @__PURE__ */ new Map();
|
|
1778
|
+
sequence = 0;
|
|
1779
|
+
constructor(getSession) {
|
|
1780
|
+
this.getSession = getSession;
|
|
1675
1781
|
}
|
|
1676
1782
|
emit(event) {
|
|
1677
1783
|
const emitted = {
|
|
1678
1784
|
...event,
|
|
1679
|
-
sequence: this.
|
|
1785
|
+
sequence: ++this.sequence,
|
|
1680
1786
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1681
1787
|
diagnostics: (event.diagnostics ?? []).map((entry) => enrichBackendDiagnostic(entry, event.sessionId))
|
|
1682
1788
|
};
|
|
1683
1789
|
const sessionId = event.sessionId;
|
|
1684
1790
|
if (!sessionId) return emitted;
|
|
1685
|
-
const events = this.
|
|
1791
|
+
const events = this.eventsBySession.get(sessionId) ?? [];
|
|
1686
1792
|
events.push(emitted);
|
|
1687
1793
|
while (events.length > DEFAULT_EVENT_RETENTION_LIMIT) events.shift();
|
|
1688
|
-
this.
|
|
1794
|
+
this.eventsBySession.set(sessionId, events);
|
|
1689
1795
|
return emitted;
|
|
1690
1796
|
}
|
|
1691
1797
|
getEvents(input) {
|
|
1692
1798
|
const startedAt = Date.now();
|
|
1693
|
-
const session = this.
|
|
1799
|
+
const session = this.getSession(input.sessionId);
|
|
1694
1800
|
if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1695
|
-
const events = this.
|
|
1801
|
+
const events = this.eventsBySession.get(input.sessionId) ?? [];
|
|
1696
1802
|
const oldestSequence = events[0]?.sequence ?? (events.length === 0 ? 1 : 0);
|
|
1697
1803
|
const currentSequence = events.at(-1)?.sequence ?? 0;
|
|
1698
1804
|
const after = input.after === void 0 ? 0 : Number(input.after);
|
|
@@ -1727,281 +1833,7 @@ var EventService = class {
|
|
|
1727
1833
|
});
|
|
1728
1834
|
}
|
|
1729
1835
|
removeSession(sessionId) {
|
|
1730
|
-
this.
|
|
1731
|
-
}
|
|
1732
|
-
};
|
|
1733
|
-
//#endregion
|
|
1734
|
-
//#region src/services/job-service.ts
|
|
1735
|
-
const COMPLETED_JOB_RETENTION_LIMIT = 100;
|
|
1736
|
-
const REFRESH_START_DELAY_MS = 0;
|
|
1737
|
-
const REFRESH_COMPLETE_DELAY_MS = 50;
|
|
1738
|
-
function isTerminal(status) {
|
|
1739
|
-
return status === "completed" || status === "failed" || status === "cancelled";
|
|
1740
|
-
}
|
|
1741
|
-
var JobService = class {
|
|
1742
|
-
constructor(context, cacheService, eventService) {
|
|
1743
|
-
this.context = context;
|
|
1744
|
-
this.cacheService = cacheService;
|
|
1745
|
-
this.eventService = eventService;
|
|
1746
|
-
}
|
|
1747
|
-
cancellationRequests = /* @__PURE__ */ new Set();
|
|
1748
|
-
getJobs(sessionId) {
|
|
1749
|
-
return this.context.jobsBySession.get(sessionId) ?? [];
|
|
1750
|
-
}
|
|
1751
|
-
setJobs(sessionId, jobs) {
|
|
1752
|
-
const retained = [];
|
|
1753
|
-
let terminalCount = 0;
|
|
1754
|
-
for (let index = jobs.length - 1; index >= 0; index -= 1) {
|
|
1755
|
-
const job = jobs[index];
|
|
1756
|
-
if (isTerminal(job.status)) {
|
|
1757
|
-
if (terminalCount >= COMPLETED_JOB_RETENTION_LIMIT) continue;
|
|
1758
|
-
terminalCount += 1;
|
|
1759
|
-
}
|
|
1760
|
-
retained.push(job);
|
|
1761
|
-
}
|
|
1762
|
-
this.context.jobsBySession.set(sessionId, retained.reverse());
|
|
1763
|
-
}
|
|
1764
|
-
refreshCache(input) {
|
|
1765
|
-
const startedAt = Date.now();
|
|
1766
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
1767
|
-
if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1768
|
-
const jobId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
1769
|
-
const job = {
|
|
1770
|
-
jobId,
|
|
1771
|
-
kind: "cache.refresh",
|
|
1772
|
-
status: "queued",
|
|
1773
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1774
|
-
sessionId: session.sessionId,
|
|
1775
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1776
|
-
revision: session.revision,
|
|
1777
|
-
diagnostics: [],
|
|
1778
|
-
progress: {
|
|
1779
|
-
completed: 0,
|
|
1780
|
-
total: 1,
|
|
1781
|
-
message: input.reason ?? "manual"
|
|
1782
|
-
}
|
|
1783
|
-
};
|
|
1784
|
-
const jobs = this.getJobs(session.sessionId);
|
|
1785
|
-
jobs.push(job);
|
|
1786
|
-
this.setJobs(session.sessionId, jobs);
|
|
1787
|
-
this.eventService.emit({
|
|
1788
|
-
kind: "job.created",
|
|
1789
|
-
sessionId: session.sessionId,
|
|
1790
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1791
|
-
revision: session.revision,
|
|
1792
|
-
jobId
|
|
1793
|
-
});
|
|
1794
|
-
this.scheduleRefreshJob(session.sessionId, jobId);
|
|
1795
|
-
return success("runtime", startedAt, structuredClone(job), {
|
|
1796
|
-
sessionId: session.sessionId,
|
|
1797
|
-
revision: session.revision
|
|
1798
|
-
});
|
|
1799
|
-
}
|
|
1800
|
-
getJob(input) {
|
|
1801
|
-
const startedAt = Date.now();
|
|
1802
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
1803
|
-
if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1804
|
-
const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
|
|
1805
|
-
if (!job) return failure("runtime", startedAt, {
|
|
1806
|
-
code: "job_not_found",
|
|
1807
|
-
message: `Job was not found: ${input.jobId}`,
|
|
1808
|
-
sessionId: input.sessionId,
|
|
1809
|
-
jobId: input.jobId
|
|
1810
|
-
}, void 0, {
|
|
1811
|
-
sessionId: session.sessionId,
|
|
1812
|
-
revision: session.revision
|
|
1813
|
-
});
|
|
1814
|
-
return success("runtime", startedAt, structuredClone(job), {
|
|
1815
|
-
sessionId: session.sessionId,
|
|
1816
|
-
revision: session.revision
|
|
1817
|
-
});
|
|
1818
|
-
}
|
|
1819
|
-
listJobs(input) {
|
|
1820
|
-
const startedAt = Date.now();
|
|
1821
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
1822
|
-
if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1823
|
-
let jobs = [...this.getJobs(input.sessionId)];
|
|
1824
|
-
if (input.kind) jobs = jobs.filter((job) => job.kind === input.kind);
|
|
1825
|
-
if (input.status) if (input.status === "active") jobs = jobs.filter((job) => !isTerminal(job.status));
|
|
1826
|
-
else if (input.status === "terminal") jobs = jobs.filter((job) => isTerminal(job.status));
|
|
1827
|
-
else jobs = jobs.filter((job) => job.status === input.status);
|
|
1828
|
-
if (input.limit !== void 0) jobs = jobs.slice(0, Math.max(0, input.limit));
|
|
1829
|
-
return success("runtime", startedAt, { jobs: jobs.map((job) => structuredClone(job)) }, {
|
|
1830
|
-
sessionId: session.sessionId,
|
|
1831
|
-
revision: session.revision
|
|
1832
|
-
});
|
|
1833
|
-
}
|
|
1834
|
-
cancelJob(input) {
|
|
1835
|
-
const startedAt = Date.now();
|
|
1836
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
1837
|
-
if (!session || session.closed) return failure("runtime", startedAt, createSessionNotFoundError(input.sessionId));
|
|
1838
|
-
const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
|
|
1839
|
-
if (!job) return failure("runtime", startedAt, {
|
|
1840
|
-
code: "job_not_found",
|
|
1841
|
-
message: `Job was not found: ${input.jobId}`,
|
|
1842
|
-
sessionId: input.sessionId,
|
|
1843
|
-
jobId: input.jobId
|
|
1844
|
-
}, void 0, {
|
|
1845
|
-
sessionId: session.sessionId,
|
|
1846
|
-
revision: session.revision
|
|
1847
|
-
});
|
|
1848
|
-
if (isTerminal(job.status)) return failure("runtime", startedAt, {
|
|
1849
|
-
code: "job_not_cancellable",
|
|
1850
|
-
message: `Job is already terminal: ${input.jobId}`,
|
|
1851
|
-
sessionId: input.sessionId,
|
|
1852
|
-
jobId: input.jobId,
|
|
1853
|
-
status: job.status
|
|
1854
|
-
}, void 0, {
|
|
1855
|
-
sessionId: session.sessionId,
|
|
1856
|
-
revision: session.revision
|
|
1857
|
-
});
|
|
1858
|
-
this.cancellationRequests.add(job.jobId);
|
|
1859
|
-
this.eventService.emit({
|
|
1860
|
-
kind: "job.cancelRequested",
|
|
1861
|
-
sessionId: input.sessionId,
|
|
1862
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1863
|
-
revision: session.revision,
|
|
1864
|
-
jobId: job.jobId
|
|
1865
|
-
});
|
|
1866
|
-
const cancelled = this.cancelRefreshJob(session.sessionId, job);
|
|
1867
|
-
return success("runtime", startedAt, structuredClone(cancelled), {
|
|
1868
|
-
sessionId: session.sessionId,
|
|
1869
|
-
revision: session.revision
|
|
1870
|
-
});
|
|
1871
|
-
}
|
|
1872
|
-
removeSession(sessionId) {
|
|
1873
|
-
for (const job of this.getJobs(sessionId)) this.cancellationRequests.delete(job.jobId);
|
|
1874
|
-
this.context.jobsBySession.delete(sessionId);
|
|
1875
|
-
}
|
|
1876
|
-
replaceJob(sessionId, nextJob) {
|
|
1877
|
-
const jobs = this.getJobs(sessionId).map((job) => job.jobId === nextJob.jobId ? nextJob : job);
|
|
1878
|
-
this.setJobs(sessionId, jobs);
|
|
1879
|
-
}
|
|
1880
|
-
scheduleRefreshJob(sessionId, jobId) {
|
|
1881
|
-
setTimeout(() => this.startRefreshJob(sessionId, jobId), REFRESH_START_DELAY_MS);
|
|
1882
|
-
}
|
|
1883
|
-
startRefreshJob(sessionId, jobId) {
|
|
1884
|
-
const session = this.context.sessions.get(sessionId);
|
|
1885
|
-
if (!session || session.closed) return;
|
|
1886
|
-
const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
|
|
1887
|
-
if (!job || isTerminal(job.status)) return;
|
|
1888
|
-
if (this.cancellationRequests.has(jobId)) {
|
|
1889
|
-
this.cancelRefreshJob(sessionId, job);
|
|
1890
|
-
return;
|
|
1891
|
-
}
|
|
1892
|
-
const running = {
|
|
1893
|
-
...job,
|
|
1894
|
-
status: "running",
|
|
1895
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1896
|
-
progress: {
|
|
1897
|
-
completed: 0,
|
|
1898
|
-
total: 1,
|
|
1899
|
-
message: "refreshing cache"
|
|
1900
|
-
}
|
|
1901
|
-
};
|
|
1902
|
-
this.replaceJob(sessionId, running);
|
|
1903
|
-
this.eventService.emit({
|
|
1904
|
-
kind: "job.started",
|
|
1905
|
-
sessionId,
|
|
1906
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1907
|
-
revision: session.revision,
|
|
1908
|
-
jobId
|
|
1909
|
-
});
|
|
1910
|
-
this.eventService.emit({
|
|
1911
|
-
kind: "job.progress",
|
|
1912
|
-
sessionId,
|
|
1913
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1914
|
-
revision: session.revision,
|
|
1915
|
-
jobId,
|
|
1916
|
-
payload: running.progress
|
|
1917
|
-
});
|
|
1918
|
-
setTimeout(() => this.completeRefreshJob(sessionId, jobId), REFRESH_COMPLETE_DELAY_MS);
|
|
1919
|
-
}
|
|
1920
|
-
completeRefreshJob(sessionId, jobId) {
|
|
1921
|
-
const session = this.context.sessions.get(sessionId);
|
|
1922
|
-
if (!session || session.closed) return;
|
|
1923
|
-
const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
|
|
1924
|
-
if (!job || isTerminal(job.status)) return;
|
|
1925
|
-
if (this.cancellationRequests.has(jobId)) {
|
|
1926
|
-
this.cancelRefreshJob(sessionId, job);
|
|
1927
|
-
return;
|
|
1928
|
-
}
|
|
1929
|
-
try {
|
|
1930
|
-
const entry = this.cacheService.refreshSession(session);
|
|
1931
|
-
const completed = {
|
|
1932
|
-
...job,
|
|
1933
|
-
status: "completed",
|
|
1934
|
-
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1935
|
-
cacheRevision: entry.revision,
|
|
1936
|
-
progress: {
|
|
1937
|
-
completed: 1,
|
|
1938
|
-
total: 1,
|
|
1939
|
-
message: "cache refreshed"
|
|
1940
|
-
},
|
|
1941
|
-
result: { cacheRevision: entry.revision }
|
|
1942
|
-
};
|
|
1943
|
-
this.replaceJob(sessionId, completed);
|
|
1944
|
-
this.eventService.emit({
|
|
1945
|
-
kind: "job.completed",
|
|
1946
|
-
sessionId,
|
|
1947
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1948
|
-
revision: session.revision,
|
|
1949
|
-
cacheRevision: entry.revision,
|
|
1950
|
-
jobId
|
|
1951
|
-
});
|
|
1952
|
-
this.eventService.emit({
|
|
1953
|
-
kind: "cache.updated",
|
|
1954
|
-
sessionId,
|
|
1955
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1956
|
-
revision: session.revision,
|
|
1957
|
-
cacheRevision: entry.revision
|
|
1958
|
-
});
|
|
1959
|
-
} catch (error) {
|
|
1960
|
-
const failed = {
|
|
1961
|
-
...job,
|
|
1962
|
-
status: "failed",
|
|
1963
|
-
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1964
|
-
error: {
|
|
1965
|
-
code: "cache_refresh_failed",
|
|
1966
|
-
message: error instanceof Error ? error.message : "Cache refresh failed",
|
|
1967
|
-
sessionId,
|
|
1968
|
-
jobId
|
|
1969
|
-
}
|
|
1970
|
-
};
|
|
1971
|
-
this.replaceJob(sessionId, failed);
|
|
1972
|
-
this.eventService.emit({
|
|
1973
|
-
kind: "job.failed",
|
|
1974
|
-
sessionId,
|
|
1975
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
1976
|
-
revision: session.revision,
|
|
1977
|
-
jobId,
|
|
1978
|
-
diagnostics: failed.diagnostics
|
|
1979
|
-
});
|
|
1980
|
-
}
|
|
1981
|
-
}
|
|
1982
|
-
cancelRefreshJob(sessionId, job) {
|
|
1983
|
-
const session = this.context.sessions.get(sessionId);
|
|
1984
|
-
const cancelled = {
|
|
1985
|
-
...job,
|
|
1986
|
-
status: "cancelled",
|
|
1987
|
-
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1988
|
-
error: {
|
|
1989
|
-
code: "job_cancelled",
|
|
1990
|
-
message: `Job was cancelled: ${job.jobId}`,
|
|
1991
|
-
sessionId,
|
|
1992
|
-
jobId: job.jobId
|
|
1993
|
-
}
|
|
1994
|
-
};
|
|
1995
|
-
this.replaceJob(sessionId, cancelled);
|
|
1996
|
-
this.cancellationRequests.delete(job.jobId);
|
|
1997
|
-
this.eventService.emit({
|
|
1998
|
-
kind: "job.cancelled",
|
|
1999
|
-
sessionId,
|
|
2000
|
-
canonicalPathKey: session?.canonicalPathKey ?? job.canonicalPathKey,
|
|
2001
|
-
revision: session?.revision ?? job.revision,
|
|
2002
|
-
jobId: job.jobId
|
|
2003
|
-
});
|
|
2004
|
-
return cancelled;
|
|
1836
|
+
this.eventsBySession.delete(sessionId);
|
|
2005
1837
|
}
|
|
2006
1838
|
};
|
|
2007
1839
|
//#endregion
|
|
@@ -2091,24 +1923,25 @@ function toProjectOutline(session) {
|
|
|
2091
1923
|
};
|
|
2092
1924
|
}
|
|
2093
1925
|
var ReadService = class {
|
|
2094
|
-
constructor(
|
|
2095
|
-
this.
|
|
1926
|
+
constructor(getSessionState, capabilities) {
|
|
1927
|
+
this.getSessionState = getSessionState;
|
|
1928
|
+
this.capabilities = capabilities;
|
|
2096
1929
|
}
|
|
2097
1930
|
getCapabilities() {
|
|
2098
|
-
return success("read", Date.now(),
|
|
1931
|
+
return success("read", Date.now(), cloneReadData(this.capabilities));
|
|
2099
1932
|
}
|
|
2100
1933
|
getSession(input) {
|
|
2101
1934
|
const startedAt = Date.now();
|
|
2102
|
-
const session = this.
|
|
1935
|
+
const session = this.getSessionState(input.sessionId);
|
|
2103
1936
|
if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
|
|
2104
|
-
return success("read", startedAt, toSessionSnapshot(session, this.
|
|
1937
|
+
return success("read", startedAt, toSessionSnapshot(session, this.capabilities), {
|
|
2105
1938
|
sessionId: session.sessionId,
|
|
2106
1939
|
revision: session.revision
|
|
2107
1940
|
});
|
|
2108
1941
|
}
|
|
2109
1942
|
getProjectOutline(input) {
|
|
2110
1943
|
const startedAt = Date.now();
|
|
2111
|
-
const session = this.
|
|
1944
|
+
const session = this.getSessionState(input.sessionId);
|
|
2112
1945
|
if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
|
|
2113
1946
|
return success("read", startedAt, toProjectOutline(session), {
|
|
2114
1947
|
sessionId: session.sessionId,
|
|
@@ -2117,7 +1950,7 @@ var ReadService = class {
|
|
|
2117
1950
|
}
|
|
2118
1951
|
queryEntity(input) {
|
|
2119
1952
|
const startedAt = Date.now();
|
|
2120
|
-
const session = this.
|
|
1953
|
+
const session = this.getSessionState(input.sessionId);
|
|
2121
1954
|
if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
|
|
2122
1955
|
const meta = {
|
|
2123
1956
|
sessionId: session.sessionId,
|
|
@@ -2138,7 +1971,7 @@ var ReadService = class {
|
|
|
2138
1971
|
entity
|
|
2139
1972
|
};
|
|
2140
1973
|
const problem = queryResponseProblem(data);
|
|
2141
|
-
return problem ? reject(problem) : success("read", startedAt,
|
|
1974
|
+
return problem ? reject(problem) : success("read", startedAt, cloneReadData(data), meta);
|
|
2142
1975
|
};
|
|
2143
1976
|
if (target.kind === "project") {
|
|
2144
1977
|
if (Object.hasOwn(target, "selector")) return reject("invalid_query");
|
|
@@ -2232,7 +2065,7 @@ var ReadService = class {
|
|
|
2232
2065
|
}
|
|
2233
2066
|
resolveReadSession(input, startedAt) {
|
|
2234
2067
|
if (!input || typeof input.sessionId !== "string" || !input.sessionId.length || input.sessionId.length > 256 || input.expectedRevision !== void 0 && (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0)) return readFailure(startedAt, typeof input?.sessionId === "string" ? input.sessionId : "", "invalid_query");
|
|
2235
|
-
const session = this.
|
|
2068
|
+
const session = this.getSessionState(input.sessionId);
|
|
2236
2069
|
if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
|
|
2237
2070
|
const meta = {
|
|
2238
2071
|
sessionId: session.sessionId,
|
|
@@ -2276,7 +2109,7 @@ var ReadService = class {
|
|
|
2276
2109
|
}
|
|
2277
2110
|
};
|
|
2278
2111
|
const problem = queryResponseProblem(data, BACKEND_SESSION_READ_LIMITS.model);
|
|
2279
|
-
return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt,
|
|
2112
|
+
return problem ? readFailure(startedAt, session.sessionId, problem, session.revision) : success("read", startedAt, cloneReadData(data), meta);
|
|
2280
2113
|
}
|
|
2281
2114
|
readResourceBytes(input) {
|
|
2282
2115
|
const startedAt = Date.now();
|
|
@@ -2306,10 +2139,10 @@ var ReadService = class {
|
|
|
2306
2139
|
}
|
|
2307
2140
|
validateSession(input) {
|
|
2308
2141
|
const startedAt = Date.now();
|
|
2309
|
-
const session = this.
|
|
2142
|
+
const session = this.getSessionState(input.sessionId);
|
|
2310
2143
|
if (!session || session.closed) return failure("read", startedAt, createSessionNotFoundError(input.sessionId));
|
|
2311
|
-
const report = validateProject(session.project, {
|
|
2312
|
-
readDiagnostics: session.readDiagnostics,
|
|
2144
|
+
const report = validateProject(cloneReadData(session.project), {
|
|
2145
|
+
readDiagnostics: cloneReadData(session.readDiagnostics),
|
|
2313
2146
|
complete: session.readComplete,
|
|
2314
2147
|
validateSources: true
|
|
2315
2148
|
});
|
|
@@ -2348,6 +2181,7 @@ function createProjectReaderFileSystem(fileSystem, projectRoot) {
|
|
|
2348
2181
|
return operation();
|
|
2349
2182
|
};
|
|
2350
2183
|
return {
|
|
2184
|
+
stat: (path) => contained(path, () => fileSystem.stat(path)),
|
|
2351
2185
|
readFile(filePath) {
|
|
2352
2186
|
return contained(filePath, () => fileSystem.readFile(filePath));
|
|
2353
2187
|
},
|
|
@@ -2395,11 +2229,10 @@ async function hasFullUamFidelity(document, project) {
|
|
|
2395
2229
|
return capturedFilesEqual(sourceFiles, materializedFiles) && capturedDirectoriesEqual(sourceDirectories, materializedDirectories);
|
|
2396
2230
|
}
|
|
2397
2231
|
var RuntimeService = class {
|
|
2398
|
-
constructor(context, cacheService, eventService
|
|
2232
|
+
constructor(context, cacheService, eventService) {
|
|
2399
2233
|
this.context = context;
|
|
2400
2234
|
this.cacheService = cacheService;
|
|
2401
2235
|
this.eventService = eventService;
|
|
2402
|
-
this.jobService = jobService;
|
|
2403
2236
|
}
|
|
2404
2237
|
async openSession(input) {
|
|
2405
2238
|
const startedAt = Date.now();
|
|
@@ -2422,16 +2255,14 @@ var RuntimeService = class {
|
|
|
2422
2255
|
}
|
|
2423
2256
|
const { fairyPath, canonicalProjectPath, canonicalPathKey } = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
|
|
2424
2257
|
await fileSystem.validateProjectRoot?.(canonicalProjectPath);
|
|
2425
|
-
const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
|
|
2426
2258
|
const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath) ?? fileSystem.join(canonicalProjectPath, ".openfairygui.backend.lock");
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
kind: "in_process_session_exists",
|
|
2430
|
-
message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
|
|
2259
|
+
const sessionId = randomId();
|
|
2260
|
+
const reservation = this.context.sessions.reserve(sessionId, {
|
|
2431
2261
|
canonicalPathKey,
|
|
2432
|
-
|
|
2262
|
+
canonicalProjectPath,
|
|
2433
2263
|
lockFilePath
|
|
2434
2264
|
});
|
|
2265
|
+
if ("code" in reservation) return failure("runtime", startedAt, reservation);
|
|
2435
2266
|
let sessionLock = null;
|
|
2436
2267
|
try {
|
|
2437
2268
|
sessionLock = await fileSystem.acquireSessionLock(lockFilePath);
|
|
@@ -2447,7 +2278,6 @@ var RuntimeService = class {
|
|
|
2447
2278
|
if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
|
|
2448
2279
|
const document = read.document;
|
|
2449
2280
|
const project = liftDocumentToUamProject(document);
|
|
2450
|
-
const sessionId = randomId();
|
|
2451
2281
|
const session = {
|
|
2452
2282
|
sessionId,
|
|
2453
2283
|
fairyPath,
|
|
@@ -2459,7 +2289,7 @@ var RuntimeService = class {
|
|
|
2459
2289
|
project,
|
|
2460
2290
|
readDiagnostics: read.diagnostics,
|
|
2461
2291
|
readComplete: read.complete,
|
|
2462
|
-
uamFidelity: await hasFullUamFidelity(document, project) ? "full" : "unsupported",
|
|
2292
|
+
uamFidelity: read.complete && await hasFullUamFidelity(document, project) ? "full" : "unsupported",
|
|
2463
2293
|
revision: 0,
|
|
2464
2294
|
lastSavedRevision: 0,
|
|
2465
2295
|
pendingStaleSourceFiles: /* @__PURE__ */ new Map(),
|
|
@@ -2469,8 +2299,7 @@ var RuntimeService = class {
|
|
|
2469
2299
|
lockHeld: true,
|
|
2470
2300
|
closed: false
|
|
2471
2301
|
};
|
|
2472
|
-
|
|
2473
|
-
this.context.sessionsByPath.set(canonicalPathKey, sessionId);
|
|
2302
|
+
reservation.commit(session);
|
|
2474
2303
|
this.cacheService.refreshSession(session);
|
|
2475
2304
|
this.eventService.emit({
|
|
2476
2305
|
kind: "session.opened",
|
|
@@ -2496,6 +2325,8 @@ var RuntimeService = class {
|
|
|
2496
2325
|
message: error instanceof Error ? error.message : String(error)
|
|
2497
2326
|
});
|
|
2498
2327
|
throw error;
|
|
2328
|
+
} finally {
|
|
2329
|
+
reservation.release();
|
|
2499
2330
|
}
|
|
2500
2331
|
}
|
|
2501
2332
|
openProjectSession(input) {
|
|
@@ -2510,14 +2341,12 @@ var RuntimeService = class {
|
|
|
2510
2341
|
const memoryProjectPath = `memory://${sessionId}`;
|
|
2511
2342
|
const canonicalProjectPath = storage?.canonicalProjectPath ?? input.canonicalProjectPath ?? (storage ? storage.fileSystem.dirname(storage.fairyPath) || "." : memoryProjectPath);
|
|
2512
2343
|
const canonicalPathKey = storage?.canonicalPathKey ?? input.canonicalPathKey ?? (storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
|
|
2513
|
-
const
|
|
2514
|
-
|
|
2515
|
-
code: "lock_conflict",
|
|
2516
|
-
kind: "in_process_session_exists",
|
|
2517
|
-
message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
|
|
2344
|
+
const project = normalizeUamProject(input.project);
|
|
2345
|
+
const reservation = this.context.sessions.reserve(sessionId, {
|
|
2518
2346
|
canonicalPathKey,
|
|
2519
|
-
|
|
2347
|
+
canonicalProjectPath
|
|
2520
2348
|
});
|
|
2349
|
+
if ("code" in reservation) return failure("runtime", startedAt, reservation);
|
|
2521
2350
|
const session = {
|
|
2522
2351
|
sessionId,
|
|
2523
2352
|
fairyPath: storage?.fairyPath ?? canonicalProjectPath,
|
|
@@ -2526,7 +2355,7 @@ var RuntimeService = class {
|
|
|
2526
2355
|
lockFilePath: "",
|
|
2527
2356
|
sessionLock: null,
|
|
2528
2357
|
fileSystem: storage?.fileSystem,
|
|
2529
|
-
project
|
|
2358
|
+
project,
|
|
2530
2359
|
readDiagnostics: [],
|
|
2531
2360
|
readComplete: true,
|
|
2532
2361
|
uamFidelity: "full",
|
|
@@ -2539,8 +2368,7 @@ var RuntimeService = class {
|
|
|
2539
2368
|
lockHeld: false,
|
|
2540
2369
|
closed: false
|
|
2541
2370
|
};
|
|
2542
|
-
|
|
2543
|
-
this.context.sessionsByPath.set(canonicalPathKey, sessionId);
|
|
2371
|
+
reservation.commit(session);
|
|
2544
2372
|
this.cacheService.refreshSession(session);
|
|
2545
2373
|
this.eventService.emit({
|
|
2546
2374
|
kind: "session.opened",
|
|
@@ -2563,14 +2391,24 @@ var RuntimeService = class {
|
|
|
2563
2391
|
canonicalPathKey: session.canonicalPathKey,
|
|
2564
2392
|
revision: session.revision
|
|
2565
2393
|
});
|
|
2566
|
-
|
|
2394
|
+
try {
|
|
2395
|
+
await session.sessionLock?.release();
|
|
2396
|
+
} catch (error) {
|
|
2397
|
+
return failure("runtime", startedAt, {
|
|
2398
|
+
code: "session_close_failed",
|
|
2399
|
+
message: error instanceof Error ? error.message : String(error),
|
|
2400
|
+
sessionId: session.sessionId,
|
|
2401
|
+
lockFilePath: session.lockFilePath
|
|
2402
|
+
}, toSessionSnapshot(session, this.context.capabilities), {
|
|
2403
|
+
sessionId: session.sessionId,
|
|
2404
|
+
revision: session.revision
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2567
2407
|
session.sessionLock = null;
|
|
2568
2408
|
session.lockHeld = false;
|
|
2569
2409
|
session.closed = true;
|
|
2570
|
-
this.context.sessions.
|
|
2571
|
-
this.context.sessionsByPath.delete(session.canonicalPathKey);
|
|
2410
|
+
this.context.sessions.remove(session);
|
|
2572
2411
|
this.cacheService.removeSession(session.sessionId);
|
|
2573
|
-
this.jobService.removeSession(session.sessionId);
|
|
2574
2412
|
this.eventService.emit({
|
|
2575
2413
|
kind: "session.closed",
|
|
2576
2414
|
sessionId: session.sessionId,
|
|
@@ -2623,9 +2461,6 @@ const BACKEND_METHODS = [
|
|
|
2623
2461
|
"materializeSession",
|
|
2624
2462
|
"closeSession",
|
|
2625
2463
|
"getEvents",
|
|
2626
|
-
"getJob",
|
|
2627
|
-
"listJobs",
|
|
2628
|
-
"cancelJob",
|
|
2629
2464
|
"getCacheSnapshot",
|
|
2630
2465
|
"refreshCache"
|
|
2631
2466
|
];
|
|
@@ -2639,7 +2474,7 @@ const ARTIFACT_BRIDGE_CAPABILITY = {
|
|
|
2639
2474
|
function createCapabilities(atomicSave = false) {
|
|
2640
2475
|
return {
|
|
2641
2476
|
contractVersion: BACKEND_CONTRACT_VERSION,
|
|
2642
|
-
capabilitySchemaVersion:
|
|
2477
|
+
capabilitySchemaVersion: 12,
|
|
2643
2478
|
transactionKernelOwner: "@openfairygui/core",
|
|
2644
2479
|
appSeamOwner: "@openfairygui/functions",
|
|
2645
2480
|
runtimeOwner: "@openfairygui/backend",
|
|
@@ -2748,17 +2583,10 @@ function createCapabilities(atomicSave = false) {
|
|
|
2748
2583
|
retentionLimit: 1e3,
|
|
2749
2584
|
sequenceScope: "runtime"
|
|
2750
2585
|
},
|
|
2751
|
-
jobs: {
|
|
2752
|
-
inMemory: true,
|
|
2753
|
-
cooperativeCancel: true,
|
|
2754
|
-
persistent: false,
|
|
2755
|
-
supportedKinds: ["cache.refresh"],
|
|
2756
|
-
artifactJobs: false,
|
|
2757
|
-
completedRetentionLimit: 100
|
|
2758
|
-
},
|
|
2759
2586
|
cache: {
|
|
2760
2587
|
derivedReadOnly: true,
|
|
2761
|
-
keyedBy: "
|
|
2588
|
+
keyedBy: "sessionId",
|
|
2589
|
+
refreshMode: "synchronous",
|
|
2762
2590
|
sourceOfTruth: false,
|
|
2763
2591
|
refreshMethod: "refreshCache"
|
|
2764
2592
|
}
|
|
@@ -2770,19 +2598,15 @@ function createCapabilities(atomicSave = false) {
|
|
|
2770
2598
|
var BackendRuntime = class {
|
|
2771
2599
|
fileSystem;
|
|
2772
2600
|
capabilities;
|
|
2773
|
-
sessions =
|
|
2774
|
-
|
|
2775
|
-
eventsBySession = /* @__PURE__ */ new Map();
|
|
2776
|
-
jobsBySession = /* @__PURE__ */ new Map();
|
|
2777
|
-
cacheBySession = /* @__PURE__ */ new Map();
|
|
2778
|
-
eventSequence = 0;
|
|
2601
|
+
sessions = new SessionRegistry();
|
|
2602
|
+
sessionOperations = new SessionOperationQueue();
|
|
2779
2603
|
context;
|
|
2780
2604
|
readService;
|
|
2781
2605
|
runtimeService;
|
|
2782
2606
|
authoringService;
|
|
2607
|
+
persistenceService;
|
|
2783
2608
|
cacheService;
|
|
2784
2609
|
eventService;
|
|
2785
|
-
jobService;
|
|
2786
2610
|
constructor(options = {}) {
|
|
2787
2611
|
this.fileSystem = options.fileSystem;
|
|
2788
2612
|
this.capabilities = createCapabilities(Boolean(options.fileSystem?.runProjectWriteTransaction));
|
|
@@ -2791,22 +2615,15 @@ var BackendRuntime = class {
|
|
|
2791
2615
|
host: options.host,
|
|
2792
2616
|
allowedProjectRoots: options.allowedProjectRoots,
|
|
2793
2617
|
capabilities: this.capabilities,
|
|
2794
|
-
sessions: this.sessions
|
|
2795
|
-
sessionsByPath: this.sessionsByPath,
|
|
2796
|
-
eventsBySession: this.eventsBySession,
|
|
2797
|
-
jobsBySession: this.jobsBySession,
|
|
2798
|
-
cacheBySession: this.cacheBySession,
|
|
2799
|
-
nextEventSequence: () => {
|
|
2800
|
-
this.eventSequence += 1;
|
|
2801
|
-
return this.eventSequence;
|
|
2802
|
-
}
|
|
2618
|
+
sessions: this.sessions
|
|
2803
2619
|
};
|
|
2804
|
-
|
|
2805
|
-
this.
|
|
2806
|
-
this.
|
|
2807
|
-
this.
|
|
2808
|
-
this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService
|
|
2809
|
-
this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService);
|
|
2620
|
+
const getSession = (sessionId) => this.sessions.get(sessionId);
|
|
2621
|
+
this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
|
|
2622
|
+
this.eventService = new EventService(getSession);
|
|
2623
|
+
this.cacheService = new CacheService(getSession, this.eventService);
|
|
2624
|
+
this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService);
|
|
2625
|
+
this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
|
|
2626
|
+
this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
|
|
2810
2627
|
}
|
|
2811
2628
|
getCapabilities() {
|
|
2812
2629
|
return this.readService.getCapabilities();
|
|
@@ -2851,31 +2668,23 @@ var BackendRuntime = class {
|
|
|
2851
2668
|
return this.authoringService.applyTransaction(input);
|
|
2852
2669
|
}
|
|
2853
2670
|
async saveSession(input) {
|
|
2854
|
-
return this.
|
|
2671
|
+
return this.persistenceService.saveSession(input);
|
|
2855
2672
|
}
|
|
2856
2673
|
async materializeSession(input) {
|
|
2857
|
-
return this.
|
|
2674
|
+
return this.persistenceService.materializeSession(input);
|
|
2858
2675
|
}
|
|
2859
2676
|
async closeSession(input) {
|
|
2860
|
-
|
|
2677
|
+
const captured = { ...input };
|
|
2678
|
+
return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
|
|
2861
2679
|
}
|
|
2862
2680
|
getEvents(input) {
|
|
2863
2681
|
return this.eventService.getEvents(input);
|
|
2864
2682
|
}
|
|
2865
|
-
getJob(input) {
|
|
2866
|
-
return this.jobService.getJob(input);
|
|
2867
|
-
}
|
|
2868
|
-
listJobs(input) {
|
|
2869
|
-
return this.jobService.listJobs(input);
|
|
2870
|
-
}
|
|
2871
|
-
cancelJob(input) {
|
|
2872
|
-
return this.jobService.cancelJob(input);
|
|
2873
|
-
}
|
|
2874
2683
|
getCacheSnapshot(input) {
|
|
2875
2684
|
return this.cacheService.getCacheSnapshot(input);
|
|
2876
2685
|
}
|
|
2877
2686
|
refreshCache(input) {
|
|
2878
|
-
return this.
|
|
2687
|
+
return this.cacheService.refreshCache(input);
|
|
2879
2688
|
}
|
|
2880
2689
|
};
|
|
2881
2690
|
//#endregion
|
|
@@ -3049,4 +2858,4 @@ function createBackendStorageFileSystem(storage) {
|
|
|
3049
2858
|
return fileSystem;
|
|
3050
2859
|
}
|
|
3051
2860
|
//#endregion
|
|
3052
|
-
export { BACKEND_CAPABILITY_SCHEMA_VERSION, BACKEND_COMPATIBILITY_POLICY, BACKEND_CONTRACT_VERSION, BACKEND_DIAGNOSTICS_URI, BACKEND_DIAGNOSTIC_TEMPLATE, BACKEND_ENTITY_QUERY_LIMITS, BACKEND_SESSION_READ_LIMITS, BACKEND_TRANSACTION_PREVIEW_LIMITS, BackendRuntime, createBackendStorageFileSystem, getBackendDiagnosticCatalog, getBackendDiagnosticGuide };
|
|
2861
|
+
export { BACKEND_CAPABILITY_SCHEMA_VERSION, BACKEND_COMPATIBILITY_POLICY, BACKEND_CONTRACT_VERSION, BACKEND_DIAGNOSTICS_URI, BACKEND_DIAGNOSTIC_TEMPLATE, BACKEND_ENTITY_QUERY_LIMITS, BACKEND_SESSION_READ_LIMITS, BACKEND_TRANSACTION_PREVIEW_LIMITS, BackendRuntime, ProjectWriteTransactionError, createBackendStorageFileSystem, getBackendDiagnosticCatalog, getBackendDiagnosticGuide };
|