@openfairygui/backend 0.5.0-alpha.4 → 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
|
@@ -18,11 +18,11 @@ import type {
|
|
|
18
18
|
ProjectRootNotAllowedError,
|
|
19
19
|
SessionIdConflictError,
|
|
20
20
|
SessionNotFoundError,
|
|
21
|
+
SessionCloseFailedError,
|
|
21
22
|
} from '../runtime.js';
|
|
22
23
|
import type { CacheService } from './cache-service.js';
|
|
23
24
|
import { type BackendContext, type BackendSessionState, failure, success } from './context.js';
|
|
24
25
|
import type { EventService } from './event-service.js';
|
|
25
|
-
import type { JobService } from './job-service.js';
|
|
26
26
|
import { createSessionNotFoundError, toSessionSnapshot } from './session-utils.js';
|
|
27
27
|
|
|
28
28
|
function randomId(): string {
|
|
@@ -54,6 +54,7 @@ function createProjectReaderFileSystem(
|
|
|
54
54
|
return operation();
|
|
55
55
|
};
|
|
56
56
|
return {
|
|
57
|
+
stat: (path) => contained(path, () => fileSystem.stat(path)),
|
|
57
58
|
readFile(filePath: string): Promise<string> {
|
|
58
59
|
return contained(filePath, () => fileSystem.readFile(filePath));
|
|
59
60
|
},
|
|
@@ -117,7 +118,6 @@ export class RuntimeService {
|
|
|
117
118
|
private readonly context: BackendContext,
|
|
118
119
|
private readonly cacheService: CacheService,
|
|
119
120
|
private readonly eventService: EventService,
|
|
120
|
-
private readonly jobService: JobService,
|
|
121
121
|
) {}
|
|
122
122
|
|
|
123
123
|
public async openSession(input: {
|
|
@@ -155,20 +155,11 @@ export class RuntimeService {
|
|
|
155
155
|
const resolved = await resolveCanonicalProjectRoot(fileSystem, input.projectPath);
|
|
156
156
|
const { fairyPath, canonicalProjectPath, canonicalPathKey } = resolved;
|
|
157
157
|
await fileSystem.validateProjectRoot?.(canonicalProjectPath);
|
|
158
|
-
const existingSessionId = this.context.sessionsByPath.get(canonicalPathKey);
|
|
159
158
|
const lockFilePath = fileSystem.getSessionLockPath?.(canonicalProjectPath)
|
|
160
159
|
?? fileSystem.join(canonicalProjectPath, '.openfairygui.backend.lock');
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
code: 'lock_conflict',
|
|
165
|
-
kind: 'in_process_session_exists',
|
|
166
|
-
message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
|
|
167
|
-
canonicalPathKey,
|
|
168
|
-
holderSessionId: existingSessionId,
|
|
169
|
-
lockFilePath,
|
|
170
|
-
});
|
|
171
|
-
}
|
|
160
|
+
const sessionId = randomId();
|
|
161
|
+
const reservation = this.context.sessions.reserve(sessionId, { canonicalPathKey, canonicalProjectPath, lockFilePath });
|
|
162
|
+
if ('code' in reservation) return failure('runtime', startedAt, reservation);
|
|
172
163
|
|
|
173
164
|
let sessionLock: BackendSessionLock | null = null;
|
|
174
165
|
try {
|
|
@@ -190,7 +181,6 @@ export class RuntimeService {
|
|
|
190
181
|
if (!read.document) throw new Error(read.diagnostics[0]?.message ?? `Unable to read project: ${fairyPath}`);
|
|
191
182
|
const document = read.document;
|
|
192
183
|
const project = liftDocumentToUamProject(document);
|
|
193
|
-
const sessionId = randomId();
|
|
194
184
|
const session: BackendSessionState = {
|
|
195
185
|
sessionId,
|
|
196
186
|
fairyPath,
|
|
@@ -202,7 +192,7 @@ export class RuntimeService {
|
|
|
202
192
|
project,
|
|
203
193
|
readDiagnostics: read.diagnostics,
|
|
204
194
|
readComplete: read.complete,
|
|
205
|
-
uamFidelity: (await hasFullUamFidelity(document, project)) ? 'full' : 'unsupported',
|
|
195
|
+
uamFidelity: read.complete && (await hasFullUamFidelity(document, project)) ? 'full' : 'unsupported',
|
|
206
196
|
revision: 0,
|
|
207
197
|
lastSavedRevision: 0,
|
|
208
198
|
pendingStaleSourceFiles: new Map(),
|
|
@@ -212,8 +202,7 @@ export class RuntimeService {
|
|
|
212
202
|
lockHeld: true,
|
|
213
203
|
closed: false,
|
|
214
204
|
};
|
|
215
|
-
|
|
216
|
-
this.context.sessionsByPath.set(canonicalPathKey, sessionId);
|
|
205
|
+
reservation.commit(session);
|
|
217
206
|
this.cacheService.refreshSession(session);
|
|
218
207
|
this.eventService.emit({ kind: 'session.opened', sessionId, canonicalPathKey, revision: session.revision });
|
|
219
208
|
|
|
@@ -239,6 +228,8 @@ export class RuntimeService {
|
|
|
239
228
|
});
|
|
240
229
|
}
|
|
241
230
|
throw error;
|
|
231
|
+
} finally {
|
|
232
|
+
reservation.release();
|
|
242
233
|
}
|
|
243
234
|
}
|
|
244
235
|
|
|
@@ -264,16 +255,10 @@ export class RuntimeService {
|
|
|
264
255
|
storage?.canonicalPathKey ??
|
|
265
256
|
input.canonicalPathKey ??
|
|
266
257
|
(storage ? normalizeComparablePath(canonicalProjectPath) : canonicalProjectPath.toLowerCase());
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
kind: 'in_process_session_exists',
|
|
272
|
-
message: `Project is already open in this backend runtime: ${canonicalProjectPath}`,
|
|
273
|
-
canonicalPathKey,
|
|
274
|
-
holderSessionId: existingSessionId,
|
|
275
|
-
});
|
|
276
|
-
}
|
|
258
|
+
// Normalize before claiming a path: malformed native input must not leave a reservation behind.
|
|
259
|
+
const project = normalizeUamProject(input.project);
|
|
260
|
+
const reservation = this.context.sessions.reserve(sessionId, { canonicalPathKey, canonicalProjectPath });
|
|
261
|
+
if ('code' in reservation) return failure('runtime', startedAt, reservation);
|
|
277
262
|
|
|
278
263
|
const session: BackendSessionState = {
|
|
279
264
|
sessionId,
|
|
@@ -283,7 +268,7 @@ export class RuntimeService {
|
|
|
283
268
|
lockFilePath: '',
|
|
284
269
|
sessionLock: null,
|
|
285
270
|
fileSystem: storage?.fileSystem,
|
|
286
|
-
project
|
|
271
|
+
project,
|
|
287
272
|
readDiagnostics: [],
|
|
288
273
|
readComplete: true,
|
|
289
274
|
uamFidelity: 'full',
|
|
@@ -296,8 +281,7 @@ export class RuntimeService {
|
|
|
296
281
|
lockHeld: false,
|
|
297
282
|
closed: false,
|
|
298
283
|
};
|
|
299
|
-
|
|
300
|
-
this.context.sessionsByPath.set(canonicalPathKey, sessionId);
|
|
284
|
+
reservation.commit(session);
|
|
301
285
|
this.cacheService.refreshSession(session);
|
|
302
286
|
this.eventService.emit({ kind: 'session.opened', sessionId, canonicalPathKey, revision: session.revision });
|
|
303
287
|
|
|
@@ -309,7 +293,7 @@ export class RuntimeService {
|
|
|
309
293
|
|
|
310
294
|
public async closeSession(input: {
|
|
311
295
|
sessionId: string;
|
|
312
|
-
}): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError>> {
|
|
296
|
+
}): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError | SessionCloseFailedError>> {
|
|
313
297
|
const startedAt = Date.now();
|
|
314
298
|
const session = this.context.sessions.get(input.sessionId);
|
|
315
299
|
if (!session || session.closed) {
|
|
@@ -322,14 +306,21 @@ export class RuntimeService {
|
|
|
322
306
|
canonicalPathKey: session.canonicalPathKey,
|
|
323
307
|
revision: session.revision,
|
|
324
308
|
});
|
|
325
|
-
|
|
309
|
+
try {
|
|
310
|
+
await session.sessionLock?.release();
|
|
311
|
+
} catch (error) {
|
|
312
|
+
return failure('runtime', startedAt, {
|
|
313
|
+
code: 'session_close_failed',
|
|
314
|
+
message: error instanceof Error ? error.message : String(error),
|
|
315
|
+
sessionId: session.sessionId,
|
|
316
|
+
lockFilePath: session.lockFilePath,
|
|
317
|
+
}, toSessionSnapshot(session, this.context.capabilities), { sessionId: session.sessionId, revision: session.revision });
|
|
318
|
+
}
|
|
326
319
|
session.sessionLock = null;
|
|
327
320
|
session.lockHeld = false;
|
|
328
321
|
session.closed = true;
|
|
329
|
-
this.context.sessions.
|
|
330
|
-
this.context.sessionsByPath.delete(session.canonicalPathKey);
|
|
322
|
+
this.context.sessions.remove(session);
|
|
331
323
|
this.cacheService.removeSession(session.sessionId);
|
|
332
|
-
this.jobService.removeSession(session.sessionId);
|
|
333
324
|
this.eventService.emit({
|
|
334
325
|
kind: 'session.closed',
|
|
335
326
|
sessionId: session.sessionId,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Serializes lifecycle and authoring operations for one session, without blocking other sessions. */
|
|
2
|
+
export class SessionOperationQueue {
|
|
3
|
+
private readonly operations = new Map<string, Promise<void>>();
|
|
4
|
+
|
|
5
|
+
public async run<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {
|
|
6
|
+
const previous = this.operations.get(sessionId) ?? Promise.resolve();
|
|
7
|
+
let release = (): void => undefined;
|
|
8
|
+
const current = new Promise<void>((resolve) => {
|
|
9
|
+
release = resolve;
|
|
10
|
+
});
|
|
11
|
+
const tail = previous.then(() => current);
|
|
12
|
+
this.operations.set(sessionId, tail);
|
|
13
|
+
await previous;
|
|
14
|
+
try {
|
|
15
|
+
return await operation();
|
|
16
|
+
} finally {
|
|
17
|
+
release();
|
|
18
|
+
if (this.operations.get(sessionId) === tail) this.operations.delete(sessionId);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Document } from '@openfairygui/core';
|
|
2
2
|
import { type FileSystem, type ProjectBranchDirectory, type ProjectSourceFile, ProjectWriter } from '@openfairygui/core/project-io';
|
|
3
3
|
import type { BackendFileSystem } from '../runtime.js';
|
|
4
|
+
import { ProjectWriteTransactionError } from '../runtime/contracts.js';
|
|
4
5
|
import { assertProjectPathContained } from '../path-policy.js';
|
|
5
6
|
|
|
6
7
|
function createWriterFileSystem(
|
|
@@ -25,6 +26,7 @@ function createWriterFileSystem(
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
return {
|
|
29
|
+
resolvePath: (path) => contained(path, () => fileSystem.resolvePath(path)),
|
|
28
30
|
readFile: (path) => contained(path, () => fileSystem.readFile(path)),
|
|
29
31
|
readFileRaw: (path) => contained(path, () => fileSystem.readFileRaw(path)),
|
|
30
32
|
writeFile: (path, content) =>
|
|
@@ -81,7 +83,7 @@ export async function writeSessionProject(input: {
|
|
|
81
83
|
try {
|
|
82
84
|
await input.fileSystem.runProjectWriteTransaction(projectRoot, write);
|
|
83
85
|
} catch (error) {
|
|
84
|
-
input.writtenPaths.length = 0;
|
|
86
|
+
if (ProjectWriteTransactionError.is(error) && !error.diskMayBePartiallyUpdated) input.writtenPaths.length = 0;
|
|
85
87
|
throw error;
|
|
86
88
|
}
|
|
87
89
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { InProcessLockConflictError } from '../runtime/contracts.js';
|
|
2
|
+
import type { BackendSessionState } from './context.js';
|
|
3
|
+
|
|
4
|
+
type SessionTarget = Pick<BackendSessionState, 'canonicalPathKey' | 'canonicalProjectPath'> &
|
|
5
|
+
Partial<Pick<BackendSessionState, 'fileSystem' | 'fairyPath' | 'lockFilePath'>>;
|
|
6
|
+
|
|
7
|
+
interface PathReservation {
|
|
8
|
+
commit(session: BackendSessionState): void;
|
|
9
|
+
release(): void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Owns live sessions and path claims, including claims made before asynchronous I/O. */
|
|
13
|
+
export class SessionRegistry {
|
|
14
|
+
private readonly sessions = new Map<string, BackendSessionState>();
|
|
15
|
+
private readonly paths = new Map<string, { sessionId: string }>();
|
|
16
|
+
private readonly opening = new Set<string>();
|
|
17
|
+
|
|
18
|
+
public get(sessionId: string): BackendSessionState | undefined {
|
|
19
|
+
return this.sessions.get(sessionId);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
public has(sessionId: string): boolean {
|
|
23
|
+
return this.sessions.has(sessionId) || this.opening.has(sessionId);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
public reserve(sessionId: string, target: SessionTarget): PathReservation | InProcessLockConflictError {
|
|
27
|
+
const key = target.canonicalPathKey;
|
|
28
|
+
const previous = this.paths.get(key);
|
|
29
|
+
if (previous && previous.sessionId !== sessionId) {
|
|
30
|
+
return {
|
|
31
|
+
code: 'lock_conflict',
|
|
32
|
+
kind: 'in_process_session_exists',
|
|
33
|
+
message: `Project is already open in this backend runtime: ${target.canonicalProjectPath}`,
|
|
34
|
+
canonicalPathKey: key,
|
|
35
|
+
holderSessionId: previous.sessionId,
|
|
36
|
+
lockFilePath: target.lockFilePath,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const claim = previous ?? { sessionId };
|
|
40
|
+
this.paths.set(key, claim);
|
|
41
|
+
if (!this.sessions.has(sessionId)) this.opening.add(sessionId);
|
|
42
|
+
let committed = false;
|
|
43
|
+
return {
|
|
44
|
+
commit: (session) => {
|
|
45
|
+
if (session.sessionId !== sessionId || this.paths.get(key) !== claim)
|
|
46
|
+
throw new Error('Session path reservation lost.');
|
|
47
|
+
if (session.canonicalPathKey !== key) this.releasePath(session.canonicalPathKey, sessionId);
|
|
48
|
+
Object.assign(session, target);
|
|
49
|
+
this.sessions.set(sessionId, session);
|
|
50
|
+
this.opening.delete(sessionId);
|
|
51
|
+
committed = true;
|
|
52
|
+
},
|
|
53
|
+
release: () => {
|
|
54
|
+
if (committed) return;
|
|
55
|
+
if (!previous && this.paths.get(key) === claim) this.paths.delete(key);
|
|
56
|
+
this.opening.delete(sessionId);
|
|
57
|
+
},
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public remove(session: BackendSessionState): void {
|
|
62
|
+
if (this.sessions.get(session.sessionId) !== session) return;
|
|
63
|
+
this.sessions.delete(session.sessionId);
|
|
64
|
+
this.releasePath(session.canonicalPathKey, session.sessionId);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private releasePath(key: string, sessionId: string): void {
|
|
68
|
+
if (this.paths.get(key)?.sessionId === sessionId) this.paths.delete(key);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -4,11 +4,11 @@ import type {
|
|
|
4
4
|
SessionNotFoundError,
|
|
5
5
|
SessionStaleWriteError,
|
|
6
6
|
} from '../runtime.js';
|
|
7
|
-
import type
|
|
7
|
+
import { cloneReadData, type ReadonlyData, type BackendSessionState, type SessionReadView } from './context.js';
|
|
8
8
|
|
|
9
9
|
export function toSessionSnapshot(
|
|
10
|
-
session:
|
|
11
|
-
capabilities: BackendCapabilities
|
|
10
|
+
session: Pick<SessionReadView, 'sessionId' | 'canonicalProjectPath' | 'revision' | 'lastSavedRevision' | 'dirty' | 'uamFidelity' | 'lockHeld'>,
|
|
11
|
+
capabilities: ReadonlyData<BackendCapabilities>,
|
|
12
12
|
): BackendSessionSnapshot {
|
|
13
13
|
return {
|
|
14
14
|
sessionId: session.sessionId,
|
|
@@ -18,7 +18,7 @@ export function toSessionSnapshot(
|
|
|
18
18
|
dirty: session.dirty,
|
|
19
19
|
uamFidelity: session.uamFidelity,
|
|
20
20
|
lockHeld: session.lockHeld,
|
|
21
|
-
capabilities:
|
|
21
|
+
capabilities: cloneReadData<BackendCapabilities>(capabilities),
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
24
|
|
|
@@ -1,238 +0,0 @@
|
|
|
1
|
-
import { failure, success, type BackendContext } from './context.js';
|
|
2
|
-
import type { CacheService } from './cache-service.js';
|
|
3
|
-
import type { EventService } from './event-service.js';
|
|
4
|
-
import { createSessionNotFoundError } from './session-utils.js';
|
|
5
|
-
import type {
|
|
6
|
-
BackendJobListSnapshot,
|
|
7
|
-
BackendJobNotCancellableError,
|
|
8
|
-
BackendJobNotFoundError,
|
|
9
|
-
BackendJobSnapshot,
|
|
10
|
-
BackendJobStatus,
|
|
11
|
-
BackendResult,
|
|
12
|
-
CancelJobInput,
|
|
13
|
-
GetJobInput,
|
|
14
|
-
ListJobsInput,
|
|
15
|
-
RefreshCacheInput,
|
|
16
|
-
SessionNotFoundError,
|
|
17
|
-
} from '../runtime.js';
|
|
18
|
-
|
|
19
|
-
const COMPLETED_JOB_RETENTION_LIMIT = 100;
|
|
20
|
-
const REFRESH_START_DELAY_MS = 0;
|
|
21
|
-
const REFRESH_COMPLETE_DELAY_MS = 50;
|
|
22
|
-
|
|
23
|
-
function isTerminal(status: BackendJobStatus): boolean {
|
|
24
|
-
return status === 'completed' || status === 'failed' || status === 'cancelled';
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export class JobService {
|
|
28
|
-
public constructor(
|
|
29
|
-
private readonly context: BackendContext,
|
|
30
|
-
private readonly cacheService: CacheService,
|
|
31
|
-
private readonly eventService: EventService,
|
|
32
|
-
) {}
|
|
33
|
-
private readonly cancellationRequests = new Set<string>();
|
|
34
|
-
|
|
35
|
-
private getJobs(sessionId: string): BackendJobSnapshot[] {
|
|
36
|
-
return this.context.jobsBySession.get(sessionId) ?? [];
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
private setJobs(sessionId: string, jobs: BackendJobSnapshot[]): void {
|
|
40
|
-
const retained: BackendJobSnapshot[] = [];
|
|
41
|
-
let terminalCount = 0;
|
|
42
|
-
for (let index = jobs.length - 1; index >= 0; index -= 1) {
|
|
43
|
-
const job = jobs[index];
|
|
44
|
-
if (isTerminal(job.status)) {
|
|
45
|
-
if (terminalCount >= COMPLETED_JOB_RETENTION_LIMIT) continue;
|
|
46
|
-
terminalCount += 1;
|
|
47
|
-
}
|
|
48
|
-
retained.push(job);
|
|
49
|
-
}
|
|
50
|
-
this.context.jobsBySession.set(sessionId, retained.reverse());
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
public refreshCache(input: RefreshCacheInput): BackendResult<BackendJobSnapshot, SessionNotFoundError> {
|
|
54
|
-
const startedAt = Date.now();
|
|
55
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
56
|
-
if (!session || session.closed) {
|
|
57
|
-
return failure('runtime', startedAt, createSessionNotFoundError(input.sessionId));
|
|
58
|
-
}
|
|
59
|
-
const jobId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
60
|
-
const createdAt = new Date().toISOString();
|
|
61
|
-
const job: BackendJobSnapshot = {
|
|
62
|
-
jobId,
|
|
63
|
-
kind: 'cache.refresh',
|
|
64
|
-
status: 'queued',
|
|
65
|
-
createdAt,
|
|
66
|
-
sessionId: session.sessionId,
|
|
67
|
-
canonicalPathKey: session.canonicalPathKey,
|
|
68
|
-
revision: session.revision,
|
|
69
|
-
diagnostics: [],
|
|
70
|
-
progress: { completed: 0, total: 1, message: input.reason ?? 'manual' },
|
|
71
|
-
};
|
|
72
|
-
const jobs = this.getJobs(session.sessionId);
|
|
73
|
-
jobs.push(job);
|
|
74
|
-
this.setJobs(session.sessionId, jobs);
|
|
75
|
-
this.eventService.emit({ kind: 'job.created', sessionId: session.sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, jobId });
|
|
76
|
-
this.scheduleRefreshJob(session.sessionId, jobId);
|
|
77
|
-
|
|
78
|
-
return success('runtime', startedAt, structuredClone(job), { sessionId: session.sessionId, revision: session.revision });
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
public getJob(input: GetJobInput): BackendResult<BackendJobSnapshot, SessionNotFoundError | BackendJobNotFoundError> {
|
|
82
|
-
const startedAt = Date.now();
|
|
83
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
84
|
-
if (!session || session.closed) return failure('runtime', startedAt, createSessionNotFoundError(input.sessionId));
|
|
85
|
-
const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
|
|
86
|
-
if (!job) {
|
|
87
|
-
return failure('runtime', startedAt, {
|
|
88
|
-
code: 'job_not_found',
|
|
89
|
-
message: `Job was not found: ${input.jobId}`,
|
|
90
|
-
sessionId: input.sessionId,
|
|
91
|
-
jobId: input.jobId,
|
|
92
|
-
}, undefined, { sessionId: session.sessionId, revision: session.revision });
|
|
93
|
-
}
|
|
94
|
-
return success('runtime', startedAt, structuredClone(job), { sessionId: session.sessionId, revision: session.revision });
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
public listJobs(input: ListJobsInput): BackendResult<BackendJobListSnapshot, SessionNotFoundError> {
|
|
98
|
-
const startedAt = Date.now();
|
|
99
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
100
|
-
if (!session || session.closed) return failure('runtime', startedAt, createSessionNotFoundError(input.sessionId));
|
|
101
|
-
let jobs = [...this.getJobs(input.sessionId)];
|
|
102
|
-
if (input.kind) jobs = jobs.filter((job) => job.kind === input.kind);
|
|
103
|
-
if (input.status) {
|
|
104
|
-
if (input.status === 'active') jobs = jobs.filter((job) => !isTerminal(job.status));
|
|
105
|
-
else if (input.status === 'terminal') jobs = jobs.filter((job) => isTerminal(job.status));
|
|
106
|
-
else jobs = jobs.filter((job) => job.status === input.status);
|
|
107
|
-
}
|
|
108
|
-
if (input.limit !== undefined) jobs = jobs.slice(0, Math.max(0, input.limit));
|
|
109
|
-
return success('runtime', startedAt, { jobs: jobs.map((job) => structuredClone(job)) }, { sessionId: session.sessionId, revision: session.revision });
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
public cancelJob(input: CancelJobInput): BackendResult<BackendJobSnapshot, SessionNotFoundError | BackendJobNotFoundError | BackendJobNotCancellableError> {
|
|
113
|
-
const startedAt = Date.now();
|
|
114
|
-
const session = this.context.sessions.get(input.sessionId);
|
|
115
|
-
if (!session || session.closed) return failure('runtime', startedAt, createSessionNotFoundError(input.sessionId));
|
|
116
|
-
const job = this.getJobs(input.sessionId).find((item) => item.jobId === input.jobId);
|
|
117
|
-
if (!job) {
|
|
118
|
-
return failure('runtime', startedAt, {
|
|
119
|
-
code: 'job_not_found',
|
|
120
|
-
message: `Job was not found: ${input.jobId}`,
|
|
121
|
-
sessionId: input.sessionId,
|
|
122
|
-
jobId: input.jobId,
|
|
123
|
-
}, undefined, { sessionId: session.sessionId, revision: session.revision });
|
|
124
|
-
}
|
|
125
|
-
if (isTerminal(job.status)) {
|
|
126
|
-
return failure('runtime', startedAt, {
|
|
127
|
-
code: 'job_not_cancellable',
|
|
128
|
-
message: `Job is already terminal: ${input.jobId}`,
|
|
129
|
-
sessionId: input.sessionId,
|
|
130
|
-
jobId: input.jobId,
|
|
131
|
-
status: job.status as 'completed' | 'failed' | 'cancelled',
|
|
132
|
-
}, undefined, { sessionId: session.sessionId, revision: session.revision });
|
|
133
|
-
}
|
|
134
|
-
this.cancellationRequests.add(job.jobId);
|
|
135
|
-
this.eventService.emit({ kind: 'job.cancelRequested', sessionId: input.sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, jobId: job.jobId });
|
|
136
|
-
const cancelled = this.cancelRefreshJob(session.sessionId, job);
|
|
137
|
-
return success('runtime', startedAt, structuredClone(cancelled), { sessionId: session.sessionId, revision: session.revision });
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
public removeSession(sessionId: string): void {
|
|
141
|
-
for (const job of this.getJobs(sessionId)) this.cancellationRequests.delete(job.jobId);
|
|
142
|
-
this.context.jobsBySession.delete(sessionId);
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
private replaceJob(sessionId: string, nextJob: BackendJobSnapshot): void {
|
|
146
|
-
const jobs = this.getJobs(sessionId).map((job) => job.jobId === nextJob.jobId ? nextJob : job);
|
|
147
|
-
this.setJobs(sessionId, jobs);
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
private scheduleRefreshJob(sessionId: string, jobId: string): void {
|
|
151
|
-
setTimeout(() => this.startRefreshJob(sessionId, jobId), REFRESH_START_DELAY_MS);
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
private startRefreshJob(sessionId: string, jobId: string): void {
|
|
155
|
-
const session = this.context.sessions.get(sessionId);
|
|
156
|
-
if (!session || session.closed) return;
|
|
157
|
-
const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
|
|
158
|
-
if (!job || isTerminal(job.status)) return;
|
|
159
|
-
if (this.cancellationRequests.has(jobId)) {
|
|
160
|
-
this.cancelRefreshJob(sessionId, job);
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
const running: BackendJobSnapshot = {
|
|
164
|
-
...job,
|
|
165
|
-
status: 'running',
|
|
166
|
-
startedAt: new Date().toISOString(),
|
|
167
|
-
progress: { completed: 0, total: 1, message: 'refreshing cache' },
|
|
168
|
-
};
|
|
169
|
-
this.replaceJob(sessionId, running);
|
|
170
|
-
this.eventService.emit({ kind: 'job.started', sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, jobId });
|
|
171
|
-
this.eventService.emit({ kind: 'job.progress', sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, jobId, payload: running.progress });
|
|
172
|
-
setTimeout(() => this.completeRefreshJob(sessionId, jobId), REFRESH_COMPLETE_DELAY_MS);
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
private completeRefreshJob(sessionId: string, jobId: string): void {
|
|
176
|
-
const session = this.context.sessions.get(sessionId);
|
|
177
|
-
if (!session || session.closed) return;
|
|
178
|
-
const job = this.getJobs(sessionId).find((item) => item.jobId === jobId);
|
|
179
|
-
if (!job || isTerminal(job.status)) return;
|
|
180
|
-
if (this.cancellationRequests.has(jobId)) {
|
|
181
|
-
this.cancelRefreshJob(sessionId, job);
|
|
182
|
-
return;
|
|
183
|
-
}
|
|
184
|
-
try {
|
|
185
|
-
const entry = this.cacheService.refreshSession(session);
|
|
186
|
-
const completed: BackendJobSnapshot = {
|
|
187
|
-
...job,
|
|
188
|
-
status: 'completed',
|
|
189
|
-
finishedAt: new Date().toISOString(),
|
|
190
|
-
cacheRevision: entry.revision,
|
|
191
|
-
progress: { completed: 1, total: 1, message: 'cache refreshed' },
|
|
192
|
-
result: { cacheRevision: entry.revision },
|
|
193
|
-
};
|
|
194
|
-
this.replaceJob(sessionId, completed);
|
|
195
|
-
this.eventService.emit({ kind: 'job.completed', sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, cacheRevision: entry.revision, jobId });
|
|
196
|
-
this.eventService.emit({ kind: 'cache.updated', sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, cacheRevision: entry.revision });
|
|
197
|
-
} catch (error) {
|
|
198
|
-
const failed: BackendJobSnapshot = {
|
|
199
|
-
...job,
|
|
200
|
-
status: 'failed',
|
|
201
|
-
finishedAt: new Date().toISOString(),
|
|
202
|
-
error: {
|
|
203
|
-
code: 'cache_refresh_failed',
|
|
204
|
-
message: error instanceof Error ? error.message : 'Cache refresh failed',
|
|
205
|
-
sessionId,
|
|
206
|
-
jobId,
|
|
207
|
-
},
|
|
208
|
-
};
|
|
209
|
-
this.replaceJob(sessionId, failed);
|
|
210
|
-
this.eventService.emit({ kind: 'job.failed', sessionId, canonicalPathKey: session.canonicalPathKey, revision: session.revision, jobId, diagnostics: failed.diagnostics });
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
private cancelRefreshJob(sessionId: string, job: BackendJobSnapshot): BackendJobSnapshot {
|
|
215
|
-
const session = this.context.sessions.get(sessionId);
|
|
216
|
-
const cancelled: BackendJobSnapshot = {
|
|
217
|
-
...job,
|
|
218
|
-
status: 'cancelled',
|
|
219
|
-
finishedAt: new Date().toISOString(),
|
|
220
|
-
error: {
|
|
221
|
-
code: 'job_cancelled',
|
|
222
|
-
message: `Job was cancelled: ${job.jobId}`,
|
|
223
|
-
sessionId,
|
|
224
|
-
jobId: job.jobId,
|
|
225
|
-
},
|
|
226
|
-
};
|
|
227
|
-
this.replaceJob(sessionId, cancelled);
|
|
228
|
-
this.cancellationRequests.delete(job.jobId);
|
|
229
|
-
this.eventService.emit({
|
|
230
|
-
kind: 'job.cancelled',
|
|
231
|
-
sessionId,
|
|
232
|
-
canonicalPathKey: session?.canonicalPathKey ?? job.canonicalPathKey,
|
|
233
|
-
revision: session?.revision ?? job.revision,
|
|
234
|
-
jobId: job.jobId,
|
|
235
|
-
});
|
|
236
|
-
return cancelled;
|
|
237
|
-
}
|
|
238
|
-
}
|