Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalSessionState.ts

605 lines17.9 KB

1import type {
2 TerminalAttachStreamEvent,
3 TerminalMetadataStreamEvent,
4 TerminalSessionSnapshot,
5 TerminalSummary,
6 EnvironmentId,
7} from "@t3tools/contracts";
8import { ThreadId, type TerminalAttachInput } from "@t3tools/contracts";
9import * as Arr from "effect/Array";
10import { pipe } from "effect/Function";
11import * as Order from "effect/Order";
12import * as Result from "effect/Result";
13import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
14​
15export interface TerminalSessionState {
16 readonly summary: TerminalSummary | null;
17 readonly buffer: string;
18 readonly status: TerminalSessionSnapshot["status"] | "closed";
19 readonly error: string | null;
20 readonly hasRunningSubprocess: boolean;
21 readonly updatedAt: string | null;
22 readonly version: number;
24​
25export interface TerminalBufferState {
26 readonly buffer: string;
27 readonly status: TerminalSessionSnapshot["status"] | "closed";
28 readonly error: string | null;
29 readonly updatedAt: string | null;
30 readonly version: number;
32​
33export interface TerminalSessionTarget {
34 readonly environmentId: EnvironmentId | null;
35 readonly threadId: ThreadId | null;
36 readonly terminalId: string | null;
38​
39export interface KnownTerminalSessionTarget {
40 readonly environmentId: EnvironmentId;
41 readonly threadId: ThreadId;
42 readonly terminalId: string;
44​
45export interface KnownTerminalSession {
46 readonly target: KnownTerminalSessionTarget;
47 readonly state: TerminalSessionState;
49​
50export interface KnownTerminalMetadata {
51 readonly target: KnownTerminalSessionTarget;
52 readonly summary: TerminalSummary;
54​
55export interface TerminalSessionListFilter {
56 readonly environmentId: EnvironmentId | null;
57 readonly threadId?: ThreadId | null;
58 readonly terminalId?: string | null;
60​
61export interface KnownTerminalSessionListFilter {
62 readonly environmentId: EnvironmentId;
63 readonly threadId: ThreadId | null;
64 readonly terminalId: string | null;
66​
67export interface TerminalSessionManagerConfig {
68 readonly getRegistry: () => AtomRegistry.AtomRegistry;
69 readonly maxBufferBytes?: number;
71​
72export interface TerminalMetadataClient {
73 readonly terminal: {
74 readonly onMetadata: (
75 listener: (event: TerminalMetadataStreamEvent) => void,
76 options?: { readonly onResubscribe?: () => void },
77 ) => () => void;
78 };
80​
81export interface TerminalAttachClient {
82 readonly terminal: {
83 readonly attach: (
84 input: TerminalAttachInput,
85 listener: (event: TerminalAttachStreamEvent) => void,
86 options?: { readonly onResubscribe?: () => void },
87 ) => () => void;
88 };
90​
91export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({
92 buffer: "",
93 status: "closed",
94 error: null,
95 updatedAt: null,
96 version: 0,
97});
98​
99export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>({
100 summary: null,
101 buffer: "",
102 status: "closed",
103 error: null,
104 hasRunningSubprocess: false,
105 updatedAt: null,
106 version: 0,
107});
108​
109const EMPTY_KNOWN_TERMINAL_SESSIONS = Object.freeze<Array<KnownTerminalSession>>([]);
110const EMPTY_TERMINAL_ID_LIST = Object.freeze<Array<string>>([]);
111const DEFAULT_MAX_BUFFER_BYTES = 512 * 1024;
112const knownTerminalMetadataEnvironmentIds = new Set<EnvironmentId>();
113const knownTerminalBufferTargets = new Map<string, KnownTerminalSessionTarget>();
114const textEncoder = new TextEncoder();
115const textDecoder = new TextDecoder();
116const terminalIdOrder = Order.make<string>(
117 (left, right) => left.localeCompare(right, undefined, { numeric: true }) as -1 | 0 | 1,
118);
119const knownTerminalSessionOrder = Order.mapInput(
120 terminalIdOrder,
121 (session: KnownTerminalSession) => session.target.terminalId,
122);
123​
124export const terminalSessionMetadataAtom = Atom.family((environmentId: EnvironmentId) => {
125 knownTerminalMetadataEnvironmentIds.add(environmentId);
126 return Atom.make<Record<string, KnownTerminalMetadata>>({}).pipe(
127 Atom.keepAlive,
128 Atom.withLabel(`terminal-session:metadata:${environmentId}`),
129 );
130});
131​
132export const terminalSessionBufferAtom = Atom.family((target: KnownTerminalSessionTarget) => {
133 const key = keyFromKnownTarget(target);
134 knownTerminalBufferTargets.set(key, target);
135 return Atom.make(EMPTY_TERMINAL_BUFFER_STATE).pipe(
136 Atom.keepAlive,
137 Atom.withLabel(`terminal-session:buffer:${key}`),
138 );
139});
140​
141export const EMPTY_TERMINAL_BUFFER_ATOM = Atom.make(EMPTY_TERMINAL_BUFFER_STATE).pipe(
142 Atom.keepAlive,
143 Atom.withLabel("terminal-session:buffer:null"),
144);
145​
146export const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe(
147 Atom.keepAlive,
148 Atom.withLabel("terminal-session:state:null"),
149);
150​
151export const EMPTY_KNOWN_TERMINAL_SESSIONS_ATOM = Atom.make(EMPTY_KNOWN_TERMINAL_SESSIONS).pipe(
152 Atom.keepAlive,
153 Atom.withLabel("terminal-session:known:null"),
154);
155​
156export const EMPTY_TERMINAL_ID_LIST_ATOM = Atom.make(EMPTY_TERMINAL_ID_LIST).pipe(
157 Atom.keepAlive,
158 Atom.withLabel("terminal-session:running-terminal-ids:null"),
159);
160​
161export function getKnownTerminalSessionTarget(
162 target: TerminalSessionTarget,
163): KnownTerminalSessionTarget | null {
164 if (target.environmentId === null || target.threadId === null || target.terminalId === null) {
165 return null;
166 }
167​
168 return {
169 environmentId: target.environmentId,
170 threadId: target.threadId,
171 terminalId: target.terminalId,
172 };
174​
175export function getKnownTerminalSessionListFilter(
176 filter: TerminalSessionListFilter,
177): KnownTerminalSessionListFilter | null {
178 if (filter.environmentId === null) {
179 return null;
180 }
181​
182 return {
183 environmentId: filter.environmentId,
184 threadId: filter.threadId ?? null,
185 terminalId: filter.terminalId ?? null,
186 };
188​
189function knownTargetFromSummary(
190 environmentId: EnvironmentId,
191 summary: TerminalSummary,
192): KnownTerminalSessionTarget {
193 return {
194 environmentId,
195 threadId: ThreadId.make(summary.threadId),
196 terminalId: summary.terminalId,
197 };
199​
200function keyFromKnownTarget(target: KnownTerminalSessionTarget): string {
201 return `${target.environmentId}:${target.threadId}:${target.terminalId}`;
203​
204function trimBufferToBytes(buffer: string, maxBufferBytes: number): string {
205 if (maxBufferBytes <= 0) {
206 return "";
207 }
208​
209 const encoded = textEncoder.encode(buffer);
210 if (encoded.byteLength <= maxBufferBytes) {
211 return buffer;
212 }
213​
214 let start = encoded.byteLength - maxBufferBytes;
215 while (start < encoded.length) {
216 const byte = encoded[start];
217 if (byte === undefined || (byte & 0b1100_0000) !== 0b1000_0000) {
218 break;
219 }
220 start += 1;
221 }
222​
223 return textDecoder.decode(encoded.subarray(start));
225​
226function bufferFromSnapshot(
227 snapshot: TerminalSessionSnapshot,
228 maxBufferBytes: number,
229): TerminalBufferState {
230 return {
231 buffer: trimBufferToBytes(snapshot.history, maxBufferBytes),
232 status: snapshot.status,
233 error: null,
234 updatedAt: snapshot.updatedAt,
235 version: 1,
236 };
238​
239function latestTimestamp(left: string | null, right: string | null): string | null {
240 if (left === null) return right;
241 if (right === null) return left;
242 return Date.parse(left) >= Date.parse(right) ? left : right;
244​
245function combineSessionState(
246 summary: TerminalSummary | null,
247 buffer: TerminalBufferState,
248): TerminalSessionState {
249 return {
250 summary,
251 buffer: buffer.buffer,
252 status: summary?.status ?? buffer.status,
253 error: buffer.error,
254 hasRunningSubprocess: summary?.hasRunningSubprocess ?? false,
255 updatedAt: latestTimestamp(summary?.updatedAt ?? null, buffer.updatedAt),
256 version: buffer.version,
257 };
259​
260function listKnownSessionsFromMetadata(
261 metadata: Record<string, KnownTerminalMetadata>,
262 getBuffer: (target: KnownTerminalSessionTarget) => TerminalBufferState,
263 filter?: Partial<KnownTerminalSessionTarget>,
264): ReadonlyArray<KnownTerminalSession> {
265 return pipe(
266 Object.values(metadata),
267 Arr.filterMap(({ target, summary }) => {
268 if (filter?.environmentId && target.environmentId !== filter.environmentId) {
269 return Result.failVoid;
270 }
271 if (filter?.threadId && target.threadId !== filter.threadId) {
272 return Result.failVoid;
273 }
274 if (filter?.terminalId && target.terminalId !== filter.terminalId) {
275 return Result.failVoid;
276 }
277 return Result.succeed({
278 target,
279 state: combineSessionState(summary, getBuffer(target)),
280 });
281 }),
282 Arr.sort(knownTerminalSessionOrder),
283 );
285​
286export const terminalSessionStateAtom = Atom.family((target: KnownTerminalSessionTarget) =>
287 Atom.make((get) => {
288 const targetKey = keyFromKnownTarget(target);
289 return combineSessionState(
290 get(terminalSessionMetadataAtom(target.environmentId))[targetKey]?.summary ?? null,
291 get(terminalSessionBufferAtom(target)),
292 );
293 }).pipe(Atom.keepAlive, Atom.withLabel(`terminal-session:state:${keyFromKnownTarget(target)}`)),
294);
295​
296export const knownTerminalSessionsAtom = Atom.family((filter: KnownTerminalSessionListFilter) =>
297 Atom.make((get) =>
298 listKnownSessionsFromMetadata(
299 get(terminalSessionMetadataAtom(filter.environmentId)),
300 (target) => get(terminalSessionBufferAtom(target)),
301 {
302 environmentId: filter.environmentId,
303 ...(filter.threadId !== null ? { threadId: filter.threadId } : {}),
304 ...(filter.terminalId !== null ? { terminalId: filter.terminalId } : {}),
305 },
306 ),
307 ).pipe(Atom.keepAlive, Atom.withLabel(`terminal-session:known:${JSON.stringify(filter)}`)),
308);
309​
310export const runningTerminalIdsAtom = Atom.family((filter: KnownTerminalSessionListFilter) =>
311 Atom.make((get) => {
312 return pipe(
313 Object.values(get(terminalSessionMetadataAtom(filter.environmentId))),
314 Arr.filterMap((entry) =>
315 entry.target.environmentId === filter.environmentId &&
316 (filter.threadId === null || entry.target.threadId === filter.threadId) &&
317 (filter.terminalId === null || entry.target.terminalId === filter.terminalId) &&
318 entry.summary.hasRunningSubprocess
319 ? Result.succeed(entry.target.terminalId)
320 : Result.failVoid,
321 ),
322 Arr.sort(Order.String),
323 );
324 }).pipe(
325 Atom.keepAlive,
326 Atom.withLabel(`terminal-session:running-terminal-ids:${JSON.stringify(filter)}`),
327 ),
328);
329​
330export function createTerminalSessionManager(config: TerminalSessionManagerConfig) {
331 const maxBufferBytes = config.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
332​
333 function getMetadata(environmentId: EnvironmentId): Record<string, KnownTerminalMetadata> {
334 return config.getRegistry().get(terminalSessionMetadataAtom(environmentId));
335 }
336​
337 function setMetadata(
338 environmentId: EnvironmentId,
339 next: Record<string, KnownTerminalMetadata>,
340 ): void {
341 config.getRegistry().set(terminalSessionMetadataAtom(environmentId), next);
342 }
343​
344 function getBuffer(target: KnownTerminalSessionTarget): TerminalBufferState {
345 return config.getRegistry().get(terminalSessionBufferAtom(target));
346 }
347​
348 function setBuffer(target: KnownTerminalSessionTarget, next: TerminalBufferState): void {
349 config.getRegistry().set(terminalSessionBufferAtom(target), next);
350 }
351​
352 function getSnapshot(target: TerminalSessionTarget): TerminalSessionState {
353 const knownTarget = getKnownTerminalSessionTarget(target);
354 if (knownTarget === null) {
355 return EMPTY_TERMINAL_SESSION_STATE;
356 }
357​
358 return combineSessionState(
359 getMetadata(knownTarget.environmentId)[keyFromKnownTarget(knownTarget)]?.summary ?? null,
360 getBuffer(knownTarget),
361 );
362 }
363​
364 function syncSnapshot(
365 target: Pick<TerminalSessionTarget, "environmentId">,
366 snapshot: TerminalSessionSnapshot,
367 ): void {
368 const knownTarget = getKnownTerminalSessionTarget({
369 environmentId: target.environmentId,
370 threadId: ThreadId.make(snapshot.threadId),
371 terminalId: snapshot.terminalId,
372 });
373 if (knownTarget === null) {
374 return;
375 }
376​
377 setBuffer(knownTarget, bufferFromSnapshot(snapshot, maxBufferBytes));
378 }
379​
380 function applyMetadataEvent(
381 target: Pick<TerminalSessionTarget, "environmentId">,
382 event: TerminalMetadataStreamEvent,
383 ): void {
384 const environmentId = target.environmentId;
385 if (environmentId === null) {
386 return;
387 }
388​
389 if (event.type === "snapshot") {
390 const retainedKeys = new Set<string>();
391 const next = { ...getMetadata(environmentId) };
392​
393 for (const terminal of event.terminals) {
394 const knownTarget = knownTargetFromSummary(environmentId, terminal);
395 const targetKey = keyFromKnownTarget(knownTarget);
396 retainedKeys.add(targetKey);
397 next[targetKey] = {
398 target: knownTarget,
399 summary: terminal,
400 };
401 }
402​
403 for (const key of Object.keys(next)) {
404 if (!retainedKeys.has(key)) {
405 delete next[key];
406 }
407 }
408​
409 setMetadata(environmentId, next);
410 return;
411 }
412​
413 if (event.type === "upsert") {
414 const knownTarget = knownTargetFromSummary(environmentId, event.terminal);
415 const targetKey = keyFromKnownTarget(knownTarget);
416 setMetadata(environmentId, {
417 ...getMetadata(environmentId),
418 [targetKey]: {
419 target: knownTarget,
420 summary: event.terminal,
421 },
422 });
423 return;
424 }
425​
426 const knownTarget = getKnownTerminalSessionTarget({
427 environmentId,
428 threadId: ThreadId.make(event.threadId),
429 terminalId: event.terminalId,
430 });
431 if (knownTarget === null) {
432 return;
433 }
434​
435 const next = { ...getMetadata(environmentId) };
436 delete next[keyFromKnownTarget(knownTarget)];
437 setMetadata(environmentId, next);
438 }
439​
440 function applyAttachEvent(
441 target: Pick<TerminalSessionTarget, "environmentId">,
442 event: TerminalAttachStreamEvent,
443 ): void {
444 if (event.type === "snapshot") {
445 syncSnapshot(target, event.snapshot);
446 return;
447 }
448​
449 const knownTarget = getKnownTerminalSessionTarget({
450 environmentId: target.environmentId,
451 threadId: ThreadId.make(event.threadId),
452 terminalId: event.terminalId,
453 });
454 if (knownTarget === null) {
455 return;
456 }
457​
458 const current = getBuffer(knownTarget);
459 switch (event.type) {
460 case "restarted":
461 setBuffer(knownTarget, bufferFromSnapshot(event.snapshot, maxBufferBytes));
462 return;
463 case "output":
464 setBuffer(knownTarget, {
465 ...current,
466 buffer: trimBufferToBytes(`${current.buffer}${event.data}`, maxBufferBytes),
467 status: current.status === "closed" ? "running" : current.status,
468 error: null,
469 version: current.version + 1,
470 });
471 return;
472 case "cleared":
473 setBuffer(knownTarget, {
474 ...current,
475 buffer: "",
476 error: null,
477 version: current.version + 1,
478 });
479 return;
480 case "exited":
481 setBuffer(knownTarget, {
482 ...current,
483 status: "exited",
484 error: null,
485 version: current.version + 1,
486 });
487 return;
488 case "closed":
489 setBuffer(knownTarget, {
490 ...current,
491 status: "closed",
492 error: null,
493 version: current.version + 1,
494 });
495 return;
496 case "error":
497 setBuffer(knownTarget, {
498 ...current,
499 status: "error",
500 error: event.message,
501 version: current.version + 1,
502 });
503 return;
504 case "activity":
505 return;
506 }
507 }
508​
509 function invalidate(target?: TerminalSessionTarget): void {
510 if (target) {
511 const knownTarget = getKnownTerminalSessionTarget(target);
512 if (knownTarget !== null) {
513 const targetKey = keyFromKnownTarget(knownTarget);
514 const next = { ...getMetadata(knownTarget.environmentId) };
515 delete next[targetKey];
516 setMetadata(knownTarget.environmentId, next);
517 setBuffer(knownTarget, EMPTY_TERMINAL_BUFFER_STATE);
518 }
519 return;
520 }
521​
522 for (const environmentId of knownTerminalMetadataEnvironmentIds) {
523 setMetadata(environmentId, {});
524 }
525 knownTerminalMetadataEnvironmentIds.clear();
526 for (const target of knownTerminalBufferTargets.values()) {
527 setBuffer(target, EMPTY_TERMINAL_BUFFER_STATE);
528 }
529 knownTerminalBufferTargets.clear();
530 }
531​
532 function invalidateEnvironment(environmentId: EnvironmentId): void {
533 setMetadata(environmentId, {});
534 knownTerminalMetadataEnvironmentIds.delete(environmentId);
535​
536 const prefix = `${environmentId}:`;
537 for (const [key, target] of knownTerminalBufferTargets) {
538 if (key.startsWith(prefix)) {
539 setBuffer(target, EMPTY_TERMINAL_BUFFER_STATE);
540 }
541 }
542 }
543​
544 function reset(): void {
545 invalidate();
546 }
547​
548 function listSessions(
549 filter?: Partial<KnownTerminalSessionTarget>,
550 ): ReadonlyArray<KnownTerminalSession> {
551 if (filter?.environmentId) {
552 return listKnownSessionsFromMetadata(getMetadata(filter.environmentId), getBuffer, filter);
553 }
554​
555 return pipe(
556 knownTerminalMetadataEnvironmentIds,
557 Arr.fromIterable,
558 Arr.flatMap((environmentId) =>
559 listKnownSessionsFromMetadata(getMetadata(environmentId), getBuffer, filter),
560 ),
561 );
562 }
563​
564 function subscribeMetadata(input: {
565 readonly environmentId: EnvironmentId;
566 readonly client: TerminalMetadataClient;
567 readonly options?: { readonly onResubscribe?: () => void };
568 }): () => void {
569 return input.client.terminal.onMetadata(
570 (event) => applyMetadataEvent({ environmentId: input.environmentId }, event),
571 input.options,
572 );
573 }
574​
575 function attach(input: {
576 readonly environmentId: EnvironmentId;
577 readonly client: TerminalAttachClient;
578 readonly terminal: TerminalAttachInput;
579 readonly onSnapshot?: (snapshot: TerminalSessionSnapshot) => void;
580 readonly onEvent?: (event: TerminalAttachStreamEvent) => void;
581 readonly options?: { readonly onResubscribe?: () => void };
582 }): () => void {
583 return input.client.terminal.attach(
584 input.terminal,
585 (event) => {
586 applyAttachEvent({ environmentId: input.environmentId }, event);
587 input.onEvent?.(event);
588 if (event.type === "snapshot") {
589 input.onSnapshot?.(event.snapshot);
590 }
591 },
592 input.options,
593 );
594 }
595​
596 return {
597 attach,
598 getSnapshot,
599 invalidate,
600 invalidateEnvironment,
601 listSessions,
602 subscribeMetadata,
603 reset,
604 };