Open History to see the last commit
1import {
2 type EnvironmentId,
3 type ServerConfig,
4 type ServerConfigStreamEvent,
5 type ServerLifecycleWelcomePayload,
6 type ServerLifecycleStreamReadyEvent,
7 type ServerSelfUpdateProgressEvent,
8 type ServerSelfUpdateResult,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Option from "effect/Option";
16import * as Queue from "effect/Queue";
17import * as Ref from "effect/Ref";
18import * as Result from "effect/Result";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21import * as SubscriptionRef from "effect/SubscriptionRef";
22import { AsyncResult, Atom } from "effect/unstable/reactivity";
23
24import {
25 createAtomCommandScheduler,
26 createEnvironmentRpcCommand,
27 createEnvironmentRpcQueryAtomFamily,
28 createEnvironmentRpcSubscriptionAtomFamily,
29 createRuntimeCommand,
30 scheduleAtomCommandEffect,
31} from "./runtime.ts";
32import { EnvironmentRegistry } from "../connection/registry.ts";
33import { EnvironmentSupervisor } from "../connection/supervisor.ts";
34import { safeErrorLogAttributes } from "../errors/safeLog.ts";
35import { EnvironmentCacheStore } from "../platform/persistence.ts";
36import {
37 isRpcClientError,
38 request,
39 runStream,
40 subscribe,
41 type EnvironmentRpcInput,
42} from "../rpc/client.ts";
43import { followStreamInEnvironment } from "./runtime.ts";
44
45export type ServerUpdateStage = "downloading" | "installing" | "resuming";
46
47export type ServerUpdateState =
48 | { readonly status: "idle" }
49 | {
50 readonly status: "running";
51 readonly stage: ServerUpdateStage;
52 readonly fromVersion: string;
53 readonly targetVersion: string;
54 }
55 | {
56 readonly status: "failed";
57 readonly stage: ServerUpdateStage;
58 readonly fromVersion: string;
59 readonly targetVersion: string;
60 readonly message: string;
61 };
62
63export interface ServerUpdateTarget {
64 readonly environmentId: EnvironmentId;
65 readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;
66}
67
68const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" };
69const EMPTY_SERVER_UPDATE_STATE_ATOM = Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
70 Atom.withLabel("environment-data:server:update-state:empty"),
71);
72const serverUpdateStateAtom = Atom.family((environmentId: EnvironmentId) =>
73 Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
74 Atom.withLabel(`environment-data:server:update-state:${environmentId}`),
75 ),
76);
77
78export class ServerUpdateResumeTimeoutError extends Schema.TaggedErrorClass<ServerUpdateResumeTimeoutError>()(
79 "ServerUpdateResumeTimeoutError",
80 {
81 environmentId: Schema.String,
82 targetVersion: Schema.String,
83 },
84) {
85 override get message(): string {
86 return `The server did not resume on t3@${this.targetVersion}.`;
87 }
88}
89
90export class ServerUpdateProgressIncompleteError extends Schema.TaggedErrorClass<ServerUpdateProgressIncompleteError>()(
91 "ServerUpdateProgressIncompleteError",
92 {
93 targetVersion: Schema.String,
94 },
95) {
96 override get message(): string {
97 return `The t3@${this.targetVersion} update ended before the server accepted the restart.`;
98 }
99}
100
101export class ServerUpdateTerminalError extends Schema.TaggedErrorClass<ServerUpdateTerminalError>()(
102 "ServerUpdateTerminalError",
103 {
104 targetVersion: Schema.String,
105 status: Schema.Literals(["committed", "rolled-back", "failed"]),
106 reason: Schema.optional(Schema.String),
107 },
108) {
109 override get message(): string {
110 return this.reason ?? `The t3@${this.targetVersion} update ${this.status}.`;
111 }
112}
113
114// Covers the 120-second trial deadline and a final restart of the previous
115// version when the trial rolls back.
116const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(4);
117
118export function matchesServerUpdateReadyEvent(
119 result: ServerSelfUpdateResult,
120 event: ServerLifecycleStreamReadyEvent,
121): boolean {
122 return result.updateId === undefined
123 ? event.payload.environment.serverVersion === result.targetVersion
124 : event.payload.updateOutcome?.id === result.updateId;
125}
126
127export function validateServerUpdateReadyEvent(
128 result: ServerSelfUpdateResult,
129 event: ServerLifecycleStreamReadyEvent,
130): Effect.Effect<void, ServerUpdateTerminalError> {
131 if (result.updateId === undefined) return Effect.void;
132 const outcome = event.payload.updateOutcome;
133 if (
134 outcome?.id === result.updateId &&
135 outcome.status === "committed" &&
136 outcome.targetVersion === result.targetVersion &&
137 event.payload.environment.serverVersion === result.targetVersion
138 ) {
139 return Effect.void;
140 }
141 return Effect.fail(
142 new ServerUpdateTerminalError({
143 targetVersion: result.targetVersion,
144 status: outcome?.status ?? "failed",
145 reason:
146 outcome?.reason ??
147 "The service launcher resumed without committing the requested server version.",
148 }),
149 );
150}
151
152/**
153 * Keeps reconnect attempts ~1s apart for the whole update restart.
154 *
155 * A restart takes the server down for ~15 seconds, but the supervisor's normal
156 * backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
157 * at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
158 * 33-second "Resuming". Nudging on every backoff entry (not just the first)
159 * holds the retry cadence flat until the server answers again. The sleep before
160 * each nudge is the pacer: a connection that fails instantly re-enters backoff
161 * immediately and would otherwise spin a tight retry loop.
162 *
163 * Callers fork this as a child of the update command so it is interrupted as
164 * soon as the update settles, whether it succeeds, fails, or times out.
165 */
166export function nudgeReconnectDuringUpdateRestart(input: {
167 readonly stateChanges: Stream.Stream<{ readonly phase: string }, unknown>;
168 readonly retryNow: Effect.Effect<void>;
169 readonly interval?: Duration.Duration;
170}): Effect.Effect<void> {
171 return input.stateChanges.pipe(
172 Stream.filter((state) => state.phase === "backoff"),
173 Stream.runForEach(() =>
174 Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
175 ),
176 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
177 Effect.ignore,
178 );
179}
180
181export function serverUpdateStateForProgressEvent(
182 fromVersion: string,
183 targetVersion: string,
184 event: ServerSelfUpdateProgressEvent,
185): Extract<ServerUpdateState, { status: "running" }> {
186 return {
187 status: "running",
188 stage: event.type === "complete" ? "resuming" : event.stage,
189 fromVersion,
190 targetVersion,
191 };
192}
193
194export function serverUpdateStateForServerVersion(
195 state: ServerUpdateState,
196 serverVersion: string | null,
197): ServerUpdateState {
198 return state.status === "idle" ||
199 state.status === "running" ||
200 serverVersion === null ||
201 state.fromVersion === serverVersion
202 ? state
203 : IDLE_SERVER_UPDATE_STATE;
204}
205
206function serverUpdateFailureMessage(error: unknown): string {
207 return error instanceof Error ? error.message : "Server update failed.";
208}
209
210function isRpcSocketError(error: unknown): boolean {
211 if (!isRpcClientError(error)) {
212 return false;
213 }
214 switch (error.reason._tag) {
215 case "SocketReadError":
216 case "SocketWriteError":
217 case "SocketCloseError":
218 return true;
219 default:
220 return false;
221 }
222}
223
224export function isLegacyUpdateHandoffLoss(cause: Cause.Cause<unknown>): boolean {
225 if (Cause.hasInterruptsOnly(cause)) {
226 return true;
227 }
228 return (
229 cause.reasons.length > 0 &&
230 cause.reasons.every((reason) => Cause.isFailReason(reason) && isRpcSocketError(reason.error))
231 );
232}
233
234export function resolveServerUpdateProgressResult<E>(
235 targetVersion: string,
236 terminal: Option.Option<ServerSelfUpdateResult>,
237 streamExit: Exit.Exit<void, E>,
238): Effect.Effect<ServerSelfUpdateResult, E | ServerUpdateProgressIncompleteError> {
239 if (
240 Option.isSome(terminal) &&
241 (Exit.isSuccess(streamExit) || isLegacyUpdateHandoffLoss(streamExit.cause))
242 ) {
243 return Effect.succeed(terminal.value);
244 }
245 if (Exit.isFailure(streamExit)) {
246 return Effect.failCause(streamExit.cause);
247 }
248 return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
249}
250
251export interface ServerConfigProjection {
252 readonly config: ServerConfig;
253 readonly latestEvent: ServerConfigStreamEvent;
254 readonly source: "cache" | "live";
255}
256
257export function applyServerConfigProjection(
258 current: Option.Option<ServerConfigProjection>,
259 event: ServerConfigStreamEvent,
260): Option.Option<ServerConfigProjection> {
261 switch (event.type) {
262 case "snapshot":
263 return Option.some({
264 config: event.config,
265 latestEvent: event,
266 source: "live",
267 });
268 case "keybindingsUpdated":
269 return Option.map(current, (projection) => ({
270 config: {
271 ...projection.config,
272 keybindings: event.payload.keybindings,
273 issues: event.payload.issues,
274 },
275 latestEvent: event,
276 source: "live",
277 }));
278 case "providerStatuses":
279 return Option.map(current, (projection) => ({
280 config: {
281 ...projection.config,
282 providers: event.payload.providers,
283 },
284 latestEvent: event,
285 source: "live",
286 }));
287 case "settingsUpdated":
288 return Option.map(current, (projection) => ({
289 config: {
290 ...projection.config,
291 settings: event.payload.settings,
292 },
293 latestEvent: event,
294 source: "live",
295 }));
296 }
297}
298
299export function projectServerConfig(
300 current: Option.Option<ServerConfigProjection>,
301 event: ServerConfigStreamEvent,
302): readonly [Option.Option<ServerConfigProjection>, ReadonlyArray<ServerConfigProjection>] {
303 const next = applyServerConfigProjection(current, event);
304 return [next, Option.toArray(next)];
305}
306
307const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
308 version: 1,
309 type: "snapshot",
310 config,
311});
312
313/**
314 * Keeps a complete server configuration available during reconnects. Server
315 * config carries the provider/model catalogue used by task creation, so it is
316 * useful—and safe—to retain after a transport session ends.
317 */
318export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
319 function* () {
320 const supervisor = yield* EnvironmentSupervisor;
321 const cache = yield* EnvironmentCacheStore;
322 const environmentId = supervisor.target.environmentId;
323 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
324 Effect.catch((error) =>
325 Effect.logWarning("Could not load cached server configuration.").pipe(
326 Effect.annotateLogs({
327 environmentId,
328 ...safeErrorLogAttributes(error),
329 }),
330 Effect.as(Option.none<ServerConfig>()),
331 ),
332 ),
333 );
334 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
335 Option.map(cachedConfig, (config) => ({
336 config,
337 latestEvent: cachedConfigSnapshotEvent(config),
338 source: "cache" as const,
339 })),
340 );
341 const persistence = yield* Queue.sliding<ServerConfig>(1);
342 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
343
344 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
345 config: ServerConfig,
346 ) {
347 return yield* cache.saveServerConfig(environmentId, config).pipe(
348 Effect.as(true),
349 Effect.catch((error) =>
350 Effect.logWarning("Could not persist cached server configuration.").pipe(
351 Effect.annotateLogs({
352 environmentId,
353 ...safeErrorLogAttributes(error),
354 }),
355 Effect.as(false),
356 ),
357 ),
358 );
359 });
360
361 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
362 config: ServerConfig,
363 ) {
364 if (!(yield* persist(config))) {
365 return;
366 }
367 yield* Ref.update(pendingPersistence, (pending) =>
368 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
369 );
370 });
371
372 yield* Stream.fromQueue(persistence).pipe(
373 Stream.debounce("500 millis"),
374 Stream.runForEach(persistPending),
375 Effect.forkScoped,
376 );
377
378 yield* subscribe(WS_METHODS.subscribeServerConfig, {}).pipe(
379 Stream.runForEach((event) =>
380 Effect.gen(function* () {
381 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
382 if (Option.isNone(next)) {
383 return;
384 }
385 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
386 yield* SubscriptionRef.set(state, next);
387 yield* Queue.offer(persistence, next.value.config);
388 }),
389 ),
390 Effect.forkScoped,
391 );
392
393 yield* Effect.addFinalizer(() =>
394 Ref.get(pendingPersistence).pipe(
395 Effect.flatMap(
396 Option.match({
397 onNone: () => Effect.void,
398 onSome: (config) => persist(config).pipe(Effect.asVoid),
399 }),
400 ),
401 ),
402 );
403
404 return state;
405 },
406);
407
408export function serverConfigStateChanges(environmentId: EnvironmentId) {
409 return followStreamInEnvironment(
410 environmentId,
411 Stream.unwrap(
412 makeEnvironmentServerConfigState().pipe(
413 Effect.map((state) =>
414 SubscriptionRef.changes(state).pipe(
415 Stream.filterMap((projection) =>
416 Option.match(projection, {
417 onNone: () => Result.failVoid,
418 onSome: (value) => Result.succeed(value),
419 }),
420 ),
421 ),
422 ),
423 ),
424 ),
425 );
426}
427
428export function projectServerWelcome(
429 current: Option.Option<ServerLifecycleWelcomePayload>,
430 event: {
431 readonly type: "welcome" | "ready";
432 readonly payload: unknown;
433 },
434): readonly [
435 Option.Option<ServerLifecycleWelcomePayload>,
436 ReadonlyArray<ServerLifecycleWelcomePayload>,
437] {
438 if (event.type !== "welcome") {
439 return [current, []];
440 }
441 const welcome = event.payload as ServerLifecycleWelcomePayload;
442 return [Option.some(welcome), [welcome]];
443}
444
445export function resolveServerConfigValue(
446 projection: ServerConfigProjection | null,
447 initialConfig: ServerConfig | null,
448): ServerConfig | null {
449 if (
450 projection?.source === "live" &&
451 (initialConfig === null ||
452 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
453 ) {
454 return projection.config;
455 }
456 return initialConfig ?? projection?.config ?? null;
457}
458
459export function createServerEnvironmentAtoms<R, E>(
460 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
461 options: {
462 readonly initialConfigValueAtom: (
463 environmentId: EnvironmentId,
464 ) => Atom.Atom<ServerConfig | null>;
465 },
466) {
467 const configScheduler = createAtomCommandScheduler();
468 // Updates stay serial end-to-end, but only their handoff phase occupies the config lane.
469 const updateScheduler = createAtomCommandScheduler();
470 const configConcurrency = {
471 mode: "serial" as const,
472 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
473 };
474 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
475 runtime
476 .atom(serverConfigStateChanges(environmentId))
477 .pipe(
478 Atom.setIdleTTL(5 * 60_000),
479 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
480 ),
481 );
482 const configProjection = (target: {
483 readonly environmentId: EnvironmentId;
484 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
485 }) => configProjectionFamily(target.environmentId);
486 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
487 Atom.withLabel("environment-data:server:config:empty"),
488 );
489 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
490 if (environmentId === null) {
491 return emptyConfigAtom;
492 }
493 return Atom.make((get): ServerConfig | null => {
494 const projection = Option.getOrNull(
495 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
496 );
497 return resolveServerConfigValue(
498 projection,
499 get(options.initialConfigValueAtom(environmentId)),
500 );
501 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
502 });
503 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
504 Atom.make((get) =>
505 serverUpdateStateForServerVersion(
506 get(serverUpdateStateAtom(environmentId)),
507 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
508 ),
509 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
510 );
511 const updateStateAtom = (environmentId: EnvironmentId | null) =>
512 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
513 const updateServer = createRuntimeCommand<
514 EnvironmentRegistry | EnvironmentCacheStore | R,
515 E,
516 ServerUpdateTarget,
517 ServerSelfUpdateResult,
518 unknown
519 >(runtime, {
520 label: "environment-data:server:update-server",
521 scheduler: updateScheduler,
522 concurrency: configConcurrency,
523 execute: (target, atomRegistry) => {
524 const stateAtom = serverUpdateStateAtom(target.environmentId);
525 const targetVersion = target.input.targetVersion;
526 let fromVersion =
527 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
528 targetVersion;
529 let currentStage: ServerUpdateStage = "downloading";
530 atomRegistry.set(stateAtom, {
531 status: "running",
532 stage: currentStage,
533 fromVersion,
534 targetVersion,
535 });
536
537 return Effect.gen(function* () {
538 const environmentRegistry = yield* EnvironmentRegistry;
539 const result = yield* scheduleAtomCommandEffect(
540 atomRegistry,
541 configScheduler,
542 configConcurrency,
543 target,
544 Effect.gen(function* () {
545 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
546 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
547 atomRegistry.set(stateAtom, {
548 status: "running",
549 stage: currentStage,
550 fromVersion,
551 targetVersion,
552 });
553
554 const supportsProgress =
555 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
556 const updateResult: ServerSelfUpdateResult = supportsProgress
557 ? yield* Effect.gen(function* () {
558 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
559 Option.none(),
560 );
561 const streamExit = yield* environmentRegistry
562 .runStream(
563 target.environmentId,
564 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
565 )
566 .pipe(
567 Stream.runForEach((event) =>
568 Effect.sync(() => {
569 currentStage = event.type === "complete" ? "resuming" : event.stage;
570 atomRegistry.set(
571 stateAtom,
572 serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
573 );
574 }).pipe(
575 Effect.andThen(
576 event.type === "complete"
577 ? Ref.set(terminal, Option.some(event.result))
578 : Effect.void,
579 ),
580 ),
581 ),
582 Effect.exit,
583 );
584 return yield* resolveServerUpdateProgressResult(
585 targetVersion,
586 yield* Ref.get(terminal),
587 streamExit,
588 );
589 })
590 : yield* Effect.gen(function* () {
591 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
592 const exit = yield* environmentRegistry
593 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
594 .pipe(Effect.exit);
595 if (Exit.isSuccess(exit)) {
596 return exit.value;
597 }
598 if (
599 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
600 isLegacyUpdateHandoffLoss(exit.cause)
601 ) {
602 // Older servers can tear down the transport before their
603 // unary acknowledgement arrives. Treat only that transport
604 // loss as a handoff, then prove it by waiting for target ready.
605 return { targetVersion, method: selfUpdateMethod };
606 }
607 return yield* Effect.failCause(exit.cause);
608 });
609
610 currentStage = "resuming";
611 atomRegistry.set(stateAtom, {
612 status: "running",
613 stage: currentStage,
614 fromVersion,
615 targetVersion,
616 });
617 return updateResult;
618 }),
619 );
620
621 // The update restart is intentional and the server stays unreachable
622 // for the whole restart, so hold the retry cadence flat instead of
623 // letting the supervisor climb its backoff ladder.
624 yield* nudgeReconnectDuringUpdateRestart({
625 stateChanges: environmentRegistry.stateChanges(target.environmentId),
626 retryNow: environmentRegistry.retryNow(target.environmentId),
627 }).pipe(Effect.forkChild);
628
629 const resumed = yield* environmentRegistry
630 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
631 .pipe(
632 Stream.filter(
633 (event): event is ServerLifecycleStreamReadyEvent =>
634 event.type === "ready" && matchesServerUpdateReadyEvent(result, event),
635 ),
636 Stream.runHead,
637 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
638 Effect.map(Option.flatten),
639 );
640 if (Option.isNone(resumed)) {
641 return yield* new ServerUpdateResumeTimeoutError({
642 environmentId: target.environmentId,
643 targetVersion,
644 });
645 }
646 yield* validateServerUpdateReadyEvent(result, resumed.value);
647
648 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
649 return result;
650 }).pipe(
651 Effect.onExit((exit) =>
652 Effect.sync(() => {
653 if (Exit.isSuccess(exit)) {
654 return;
655 }
656 if (Cause.hasInterruptsOnly(exit.cause)) {
657 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
658 return;
659 }
660 atomRegistry.set(stateAtom, {
661 status: "failed",
662 stage: currentStage,
663 fromVersion,
664 targetVersion,
665 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
666 });
667 }),
668 ),
669 );
670 },
671 });
672 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
673 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
674 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
675 ),
676 );
677 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
678 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
679 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
680 ),
681 );
682
683 return {
684 configValueAtom,
685 updateStateAtom,
686 settingsValueAtom,
687 providersValueAtom,
688 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
689 label: "environment-data:server:trace-diagnostics",
690 tag: WS_METHODS.serverGetTraceDiagnostics,
691 }),
692 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
693 label: "environment-data:server:process-diagnostics",
694 tag: WS_METHODS.serverGetProcessDiagnostics,
695 }),
696 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
697 label: "environment-data:server:process-resource-history",
698 tag: WS_METHODS.serverGetProcessResourceHistory,
699 }),
700 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
701 label: "environment-data:server:resource-telemetry",
702 tag: WS_METHODS.subscribeResourceTelemetry,
703 idleTtlMs: 0,
704 }),
705 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
706 label: "environment-data:server:resource-telemetry-history",
707 tag: WS_METHODS.serverGetResourceTelemetryHistory,
708 staleTimeMs: 5_000,
709 }),
710 // A cold transcript scan is measured in seconds, so keep the result around
711 // long enough that switching windows or re-rendering does not rescan.
712 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
713 label: "environment-data:server:usage-summary",
714 tag: WS_METHODS.serverGetUsageSummary,
715 staleTimeMs: 60_000,
716 }),
717 configProjection,
718 welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
719 label: "environment-data:server:welcome",
720 tag: WS_METHODS.subscribeServerLifecycle,
721 transform: (stream) =>
722 stream.pipe(
723 Stream.mapAccum(Option.none<ServerLifecycleWelcomePayload>, projectServerWelcome),
724 ),
725 }),
726 refreshProviders: createEnvironmentRpcCommand(runtime, {
727 label: "environment-data:server:refresh-providers",
728 tag: WS_METHODS.serverRefreshProviders,
729 concurrency: {
730 mode: "singleFlight",
731 key: ({ environmentId }) => environmentId,
732 },
733 }),
734 updateProvider: createEnvironmentRpcCommand(runtime, {
735 label: "environment-data:server:update-provider",
736 tag: WS_METHODS.serverUpdateProvider,
737 scheduler: configScheduler,
738 concurrency: configConcurrency,
739 }),
740 updateServer,
741 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
742 label: "environment-data:server:upsert-keybinding",
743 tag: WS_METHODS.serverUpsertKeybinding,
744 scheduler: configScheduler,
745 concurrency: configConcurrency,
746 }),
747 removeKeybinding: createEnvironmentRpcCommand(runtime, {
748 label: "environment-data:server:remove-keybinding",
749 tag: WS_METHODS.serverRemoveKeybinding,
750 scheduler: configScheduler,
751 concurrency: configConcurrency,
752 }),
753 updateSettings: createEnvironmentRpcCommand(runtime, {
754 label: "environment-data:server:update-settings",
755 tag: WS_METHODS.serverUpdateSettings,
756 scheduler: configScheduler,
757 concurrency: configConcurrency,
758 }),
759 signalProcess: createEnvironmentRpcCommand(runtime, {
760 label: "environment-data:server:signal-process",
761 tag: WS_METHODS.serverSignalProcess,
762 }),
763 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
764 label: "environment-data:server:retry-resource-telemetry",
765 tag: WS_METHODS.serverRetryResourceTelemetry,
766 concurrency: {
767 mode: "singleFlight",
768 key: ({ environmentId }) => environmentId,
769 },
770 }),
771 };
772}