-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathsessionManagerService.ts
More file actions
273 lines (248 loc) · 11.4 KB
/
Copy pathsessionManagerService.ts
File metadata and controls
273 lines (248 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
* `sessionManager` domain — the App-scope session lifecycle facade.
*
* Owns the global live-session registry across per-workspace controllers and
* routes create / resume / restore / close / archive / delete / fork /
* createChild to the owning controller; per-session work (resume / restore /
* close / delete / fork / createChild and the batch archive critical
* section) queues on one serialization chain per session. Cold
* id→workspace lookups go through `sessionIndex`; workspace
* materialization through `workspaces`. App scope.
*/
import { DisposableStore } from '#/_base/di/lifecycle';
import { Emitter, type Event, type IWaitUntil } from '#/_base/event';
import { ScopeActivation, registerScopedService, type ISessionScopeHandle } from '#/_base/di/scope';
import { LifecycleScope } from '#/app/scopes';
import { Error2, ErrorCodes } from '#/errors';
import { ISessionIndex } from '#/app/sessionIndex/sessionIndex';
import {
type CreateChildSessionOptions,
type ForkSessionOptions,
type ResumeSessionOptions,
type SessionArchivedEvent,
type SessionClosedEvent,
type SessionCreatedEvent,
type SessionForkedEvent,
type SessionWillCloseEvent,
type SessionWillCreateEvent,
} from '#/workspace/sessionLifecycle/sessionLifecycle';
import type { SessionLifecycleService } from '#/workspace/sessionLifecycle/sessionLifecycleService';
import { IWorkspaceInstanceManager } from '#/workspace/workspaceInstance/workspaceInstanceManager';
import {
ISessionManager,
type CreateManagedSessionOptions,
type UnguardedSessionLifecycle,
} from './sessionManager';
interface SessionControllerEntry {
readonly generation: string;
readonly controller: SessionLifecycleService;
readonly subscriptions: DisposableStore;
sessionCount: number;
}
export class SessionManager implements ISessionManager {
declare readonly _serviceBrand: undefined;
private readonly sessions = new Map<string, ISessionScopeHandle>();
private readonly owners = new Map<string, SessionLifecycleService>();
private readonly pendingResumes = new Map<string, Promise<ISessionScopeHandle | undefined>>();
private readonly resumeFailures = new Map<string, unknown>();
private readonly lifecycleChains = new Map<string, Promise<void>>();
private readonly controllers = new Map<string, SessionControllerEntry>();
private readonly controllerEntries = new Set<SessionControllerEntry>();
private readonly willCreateEmitter = new Emitter<SessionWillCreateEvent>();
readonly onWillCreateSession: Event<SessionWillCreateEvent> = this.willCreateEmitter.event;
private readonly didCreateEmitter = new Emitter<SessionCreatedEvent & IWaitUntil>();
readonly onDidCreateSession = this.didCreateEmitter.event;
private readonly willCloseEmitter = new Emitter<SessionWillCloseEvent & IWaitUntil>();
readonly onWillCloseSession = this.willCloseEmitter.event;
private readonly didCloseEmitter = new Emitter<SessionClosedEvent>();
readonly onDidCloseSession = this.didCloseEmitter.event;
private readonly didArchiveEmitter = new Emitter<SessionArchivedEvent>();
readonly onDidArchiveSession = this.didArchiveEmitter.event;
private readonly didForkEmitter = new Emitter<SessionForkedEvent>();
readonly onDidForkSession = this.didForkEmitter.event;
constructor(
@IWorkspaceInstanceManager private readonly workspaces: IWorkspaceInstanceManager,
@ISessionIndex private readonly index: ISessionIndex,
) {}
async create(options: CreateManagedSessionOptions): Promise<ISessionScopeHandle> {
const workspace = await this.workspaces.getOrCreate(
options.workspaceId === undefined
? { root: options.workDir }
: { workspaceId: options.workspaceId, root: options.workDir },
);
return this.controllerForWorkspace(workspace.id).create(options);
}
async resume(sessionId: string, options?: ResumeSessionOptions): Promise<ISessionScopeHandle | undefined> {
const inflight = this.pendingResumes.get(sessionId);
if (inflight !== undefined) return inflight;
// A fresh attempt supersedes any earlier failure record.
this.resumeFailures.delete(sessionId);
const promise = this.serializeLifecycle(sessionId, async () =>
(await this.controllerForSession(sessionId))?.resume(sessionId, options),
).finally(() => this.pendingResumes.delete(sessionId));
this.pendingResumes.set(sessionId, promise);
// Keep the rejection observable past the registry cleanup: a resume that
// fails mid-materialization leaves no trace in the live registry, and a
// later settle must still see it instead of treating the session as cold.
void promise.catch((error: unknown) => {
this.resumeFailures.set(sessionId, error);
});
return promise;
}
get(sessionId: string): ISessionScopeHandle | undefined {
return this.sessions.get(sessionId);
}
async whenResumeSettled(sessionId: string): Promise<void> {
await this.pendingResumes.get(sessionId);
const failure = this.resumeFailures.get(sessionId);
if (failure !== undefined) throw failure;
await this.owners.get(sessionId)?.whenResumeSettled(sessionId);
}
private serializeLifecycle<T>(sessionId: string, work: () => Promise<T>): Promise<T> {
const prev = this.lifecycleChains.get(sessionId) ?? Promise.resolve();
const run = prev.then(work, work);
const next = run.then(
() => undefined,
() => undefined,
);
this.lifecycleChains.set(sessionId, next);
void next.finally(() => {
if (this.lifecycleChains.get(sessionId) === next) this.lifecycleChains.delete(sessionId);
});
return run;
}
withLifecycleSerialization<T>(
sessionId: string,
work: (unguarded: UnguardedSessionLifecycle) => Promise<T>,
): Promise<T> {
return this.serializeLifecycle(sessionId, () =>
work({
archive: () => this.archiveInner(sessionId),
restore: () => this.restoreInner(sessionId),
}),
);
}
list(): readonly ISessionScopeHandle[] {
return [...this.sessions.values()];
}
async close(sessionId: string): Promise<void> {
await this.serializeLifecycle(sessionId, async () => this.owners.get(sessionId)?.close(sessionId));
}
private async archiveInner(sessionId: string): Promise<void> {
await (await this.controllerForSession(sessionId))?.archive(sessionId);
}
async archive(sessionId: string): Promise<void> {
await this.serializeLifecycle(sessionId, () => this.archiveInner(sessionId));
}
private async restoreInner(
sessionId: string,
options?: ResumeSessionOptions,
): Promise<ISessionScopeHandle | undefined> {
return (await this.controllerForSession(sessionId))?.restore(sessionId, options);
}
async restore(sessionId: string, options?: ResumeSessionOptions): Promise<ISessionScopeHandle | undefined> {
return this.serializeLifecycle(sessionId, () => this.restoreInner(sessionId, options));
}
async delete(sessionId: string): Promise<void> {
await this.serializeLifecycle(sessionId, async () => {
const controller = await this.controllerForSession(sessionId);
if (controller === undefined) {
throw new Error2(ErrorCodes.SESSION_NOT_FOUND, `session ${sessionId} does not exist`);
}
await controller.delete(sessionId);
});
}
async fork(options: ForkSessionOptions): Promise<ISessionScopeHandle> {
return this.serializeLifecycle(options.sourceSessionId, async () => {
const controller = await this.controllerForSession(options.sourceSessionId);
if (controller === undefined) {
throw new Error2(
ErrorCodes.SESSION_NOT_FOUND,
`session ${options.sourceSessionId} does not exist`,
);
}
return controller.fork(options);
});
}
async createChild(options: CreateChildSessionOptions): Promise<ISessionScopeHandle> {
return this.serializeLifecycle(options.sourceSessionId, async () => {
const controller = await this.controllerForSession(options.sourceSessionId);
if (controller === undefined) {
throw new Error2(
ErrorCodes.SESSION_NOT_FOUND,
`session ${options.sourceSessionId} does not exist`,
);
}
return controller.createChild(options);
});
}
dispose(): void {
for (const { controller, subscriptions } of [...this.controllerEntries].reverse()) {
subscriptions.dispose();
controller.dispose();
}
this.controllerEntries.clear();
this.controllers.clear();
this.sessions.clear();
this.owners.clear();
this.willCreateEmitter.dispose();
this.didCreateEmitter.dispose();
this.willCloseEmitter.dispose();
this.didCloseEmitter.dispose();
this.didArchiveEmitter.dispose();
this.didForkEmitter.dispose();
}
private controllerForWorkspace(workspaceId: string): SessionLifecycleService {
const workspace = this.workspaces.get(workspaceId);
if (workspace === undefined) throw new Error(`workspace ${workspaceId} is not materialized`);
const generation = workspace.program.sessionControllerGeneration;
const existing = this.controllers.get(workspaceId);
if (existing?.generation === generation) return existing.controller;
const controller = workspace.program.createSessionController();
const subscriptions = new DisposableStore();
const entry: SessionControllerEntry = { generation, controller, subscriptions, sessionCount: 0 };
subscriptions.add(controller.onWillCreateSession((event) => this.willCreateEmitter.fire(event)));
subscriptions.add(controller.onDidCreateSession((event) => {
entry.sessionCount += 1;
this.sessions.set(event.sessionId, event.handle);
this.owners.set(event.sessionId, controller);
this.didCreateEmitter.fire(event);
}));
subscriptions.add(controller.onWillCloseSession((event) => this.willCloseEmitter.fire(event)));
subscriptions.add(controller.onDidCloseSession((event) => {
entry.sessionCount -= 1;
this.sessions.delete(event.sessionId);
this.owners.delete(event.sessionId);
this.didCloseEmitter.fire(event);
this.retireEntryIfIdle(workspaceId, entry);
}));
subscriptions.add(controller.onDidArchiveSession((event) => {
entry.sessionCount -= 1;
this.sessions.delete(event.sessionId);
this.owners.delete(event.sessionId);
this.didArchiveEmitter.fire(event);
this.retireEntryIfIdle(workspaceId, entry);
}));
subscriptions.add(controller.onDidForkSession((event) => this.didForkEmitter.fire(event)));
this.controllerEntries.add(entry);
this.controllers.set(workspaceId, entry);
if (existing !== undefined) this.retireEntryIfIdle(workspaceId, existing);
return controller;
}
private retireEntryIfIdle(workspaceId: string, entry: SessionControllerEntry): void {
if (entry.sessionCount !== 0 || !this.controllerEntries.has(entry)) return;
this.controllerEntries.delete(entry);
if (this.controllers.get(workspaceId) === entry) this.controllers.delete(workspaceId);
entry.subscriptions.dispose();
entry.controller.dispose();
}
private async controllerForSession(sessionId: string): Promise<SessionLifecycleService | undefined> {
const live = this.owners.get(sessionId);
if (live !== undefined) return live;
const summary = await this.index.get(sessionId);
if (summary === undefined) return undefined;
const workspace = await this.workspaces.getOrCreate({ workspaceId: summary.workspaceId, root: summary.cwd });
return this.controllerForWorkspace(workspace.id);
}
}
registerScopedService(LifecycleScope.App, ISessionManager, SessionManager, ScopeActivation.OnScopeCreated, 'sessionManager');