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