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

server.ts

1,264 lines46.4 KB

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 Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as Fiber from "effect/Fiber";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Ref from "effect/Ref";
20import * as Result from "effect/Result";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import * as SubscriptionRef from "effect/SubscriptionRef";
24import { AsyncResult, Atom } from "effect/unstable/reactivity";
25​
26import {
27 createAtomCommandScheduler,
28 createEnvironmentRpcCommand,
29 createEnvironmentQueryAtomFamily,
30 createEnvironmentRpcQueryAtomFamily,
31 createEnvironmentRpcSubscriptionAtomFamily,
32 createRuntimeCommand,
33 scheduleAtomCommandEffect,
34} from "./runtime.ts";
35import { EnvironmentRegistry } from "../connection/registry.ts";
36import { EnvironmentSupervisor } from "../connection/supervisor.ts";
37import { safeErrorLogAttributes } from "../errors/safeLog.ts";
38import { EnvironmentCacheStore } from "../platform/persistence.ts";
39import {
40 isRpcClientError,
41 request,
42 runStream,
43 subscribe,
44 subscribeDynamicWithSession,
45 type EnvironmentRpcInput,
46} from "../rpc/client.ts";
47import type { RpcSession } from "../rpc/session.ts";
48import { followStreamInEnvironment } from "./runtime.ts";
49import {
50 applyServerConfigProjection,
51 type ServerConfigProjection,
52 withoutEnvironmentThemes,
53} from "./serverConfigProjection.ts";
54​
55// Exported server state includes this type in its inferred public return type.
56export type { ServerConfigProjection } from "./serverConfigProjection.ts";
57​
58export type ServerUpdateStage = "downloading" | "installing" | "resuming";
59​
60export type ServerUpdateState =
61 | { readonly status: "idle" }
62 | {
63 readonly status: "running";
64 readonly stage: ServerUpdateStage;
65 readonly fromVersion: string;
66 readonly targetVersion: string;
67 }
68 | {
69 readonly status: "failed";
70 readonly stage: ServerUpdateStage;
71 readonly fromVersion: string;
72 readonly targetVersion: string;
73 readonly message: string;
74 };
75​
76export interface ServerUpdateTarget {
77 readonly environmentId: EnvironmentId;
78 readonly input: EnvironmentRpcInput<typeof WS_METHODS.serverUpdateServer>;
80​
81const IDLE_SERVER_UPDATE_STATE: ServerUpdateState = { status: "idle" };
82const EMPTY_SERVER_UPDATE_STATE_ATOM = Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
83 Atom.withLabel("environment-data:server:update-state:empty"),
84);
85const serverUpdateStateAtom = Atom.family((environmentId: EnvironmentId) =>
86 Atom.make<ServerUpdateState>(IDLE_SERVER_UPDATE_STATE).pipe(
87 Atom.withLabel(`environment-data:server:update-state:${environmentId}`),
88 ),
89);
90​
91export class ServerUpdateResumeTimeoutError extends Schema.TaggedError<ServerUpdateResumeTimeoutError>()(
92 "ServerUpdateResumeTimeoutError",
93 {
94 environmentId: Schema.String,
95 targetVersion: Schema.String,
96 },
97) {
98 override get message(): string {
99 return `The server did not resume on t3@${this.targetVersion}.`;
100 }
102​
103export class ServerUpdateProgressIncompleteError extends Schema.TaggedError<ServerUpdateProgressIncompleteError>()(
104 "ServerUpdateProgressIncompleteError",
105 {
106 targetVersion: Schema.String,
107 },
108) {
109 override get message(): string {
110 return `The t3@${this.targetVersion} update ended before the server accepted the restart.`;
111 }
113​
114export class ServerUpdateTerminalError extends Schema.TaggedError<ServerUpdateTerminalError>()(
115 "ServerUpdateTerminalError",
116 {
117 targetVersion: Schema.String,
118 status: Schema.Literals(["committed", "rolled-back", "failed"]),
119 reason: Schema.optional(Schema.String),
120 },
121) {
122 override get message(): string {
123 return this.reason ?? `The t3@${this.targetVersion} update ${this.status}.`;
124 }
126​
127// Covers the 120-second trial deadline and a final restart of the previous
128// version when the trial rolls back.
129const SERVER_UPDATE_RESUME_TIMEOUT = Duration.minutes(4);
130​
131export function matchesServerUpdateReadyEvent(
132 result: ServerSelfUpdateResult,
133 event: ServerLifecycleStreamReadyEvent,
134): boolean {
135 return result.updateId === undefined
136 ? event.payload.environment.serverVersion === result.targetVersion
137 : event.payload.updateOutcome?.id === result.updateId;
139​
140export function matchesServerUpdateResumeEvent(
141 result: ServerSelfUpdateResult,
142 event: ServerLifecycleStreamReadyEvent,
143): boolean {
144 return (
145 (result.method === "desktop-app" && result.desktopUpdateToken !== undefined) ||
146 matchesServerUpdateReadyEvent(result, event)
147 );
149​
150export function validateServerUpdateReadyEvent(
151 result: ServerSelfUpdateResult,
152 event: ServerLifecycleStreamReadyEvent,
153): Effect.Effect<void, ServerUpdateTerminalError> {
154 if (result.updateId === undefined) return Effect.void;
155 const outcome = event.payload.updateOutcome;
156 if (
157 outcome?.id === result.updateId &&
158 outcome.status === "committed" &&
159 outcome.targetVersion === result.targetVersion &&
160 event.payload.environment.serverVersion === result.targetVersion
161 ) {
162 return Effect.void;
163 }
164 return Effect.fail(
165 new ServerUpdateTerminalError({
166 targetVersion: result.targetVersion,
167 status: outcome?.status ?? "failed",
168 reason:
169 outcome?.reason ??
170 "The service launcher resumed without committing the requested server version.",
171 }),
172 );
174​
175/**
176 * Keeps reconnect attempts ~1s apart for the whole update restart.
177 *
178 * A restart takes the server down for ~15 seconds, but the supervisor's normal
179 * backoff ladder (1/2/4/8/16s) assumes an unexpected failure and lands attempts
180 * at ~3, 5, 9, 17 and 33 seconds — so a 15-second restart is observed as a
181 * 33-second "Resuming". Nudging on every backoff entry (not just the first)
182 * holds the retry cadence flat until the server answers again. The sleep before
183 * each nudge is the pacer: a connection that fails instantly re-enters backoff
184 * immediately and would otherwise spin a tight retry loop.
185 *
186 * A newly restarted server can also reject the first environment credential.
187 * Authentication blocks need the same paced retry during this known restart;
188 * permission and configuration failures remain blocked.
189 *
190 * Callers fork this as a child of the update command so it is interrupted as
191 * soon as the update settles, whether it succeeds, fails, or times out.
192 */
193export function nudgeReconnectDuringUpdateRestart(input: {
194 readonly stateChanges: Stream.Stream<
195 {
196 readonly phase: string;
197 readonly lastFailure?: { readonly reason: string } | null;
198 },
199 unknown
200 >;
201 readonly retryNow: Effect.Effect<void>;
202 readonly interval?: Duration.Duration;
203}): Effect.Effect<void> {
204 return input.stateChanges.pipe(
205 Stream.filter(
206 (state) =>
207 state.phase === "backoff" ||
208 (state.phase === "blocked" && state.lastFailure?.reason === "authentication"),
209 ),
210 Stream.runForEach(() =>
211 Effect.sleep(input.interval ?? Duration.seconds(1)).pipe(Effect.andThen(input.retryNow)),
212 ),
213 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
214 Effect.ignore,
215 );
217​
218export function waitForNextEnvironmentReconnect<E>(
219 stateChanges: Stream.Stream<{ readonly phase: string }, E>,
220): Effect.Effect<void, E> {
221 return stateChanges.pipe(
222 Stream.dropWhile((state) => state.phase === "connected"),
223 Stream.filter((state) => state.phase === "connected"),
224 Stream.runHead,
225 Effect.asVoid,
226 );
228​
229export const runDesktopCommitWithReconnectObserver = Effect.fn(
230 "runDesktopCommitWithReconnectObserver",
231)(function* <EState, ECommit>(
232 stateChanges: Stream.Stream<{ readonly phase: string }, EState>,
233 commit: Effect.Effect<void, ECommit>,
234) {
235 const armed = yield* Deferred.make<void>();
236 const reconnected = yield* Deferred.make<void>();
237 const observer = yield* stateChanges.pipe(
238 Stream.tap(() => Deferred.succeed(armed, undefined)),
239 waitForNextEnvironmentReconnect,
240 Effect.andThen(Deferred.succeed(reconnected, undefined)),
241 Effect.forkChild,
242 );
243 yield* Deferred.await(armed);
244 const commitExit = yield* commit.pipe(Effect.exit);
245 if (Exit.isSuccess(commitExit)) {
246 yield* Fiber.interrupt(observer);
247 return;
248 }
249 if (!isLegacyUpdateHandoffLoss(commitExit.cause)) {
250 yield* Fiber.interrupt(observer);
251 return yield* Effect.failCause(commitExit.cause);
252 }
253 yield* Deferred.await(reconnected).pipe(Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT));
254 return yield* Effect.failCause(commitExit.cause);
255});
256​
257export const waitForDesktopUpdateTarget = Effect.fn("waitForDesktopUpdateTarget")(function* <
258 EReady,
259 ECommit,
260>(
261 targetVersion: string,
262 nextReady: Effect.Effect<ServerLifecycleStreamReadyEvent, EReady>,
263 retryCommit: Effect.Effect<void, ECommit>,
264 maxCommitAttempts = 3,
265): Effect.fn.Return<ServerLifecycleStreamReadyEvent, EReady | ECommit | ServerUpdateTerminalError> {
266 for (let attempt = 1; attempt <= maxCommitAttempts; attempt += 1) {
267 const ready = yield* nextReady;
268 if (ready.payload.environment.serverVersion === targetVersion) return ready;
269 if (attempt === maxCommitAttempts) break;
270 const retryExit = yield* retryCommit.pipe(Effect.exit);
271 if (Exit.isSuccess(retryExit)) break;
272 if (!isLegacyUpdateHandoffLoss(retryExit.cause)) {
273 return yield* Effect.failCause(retryExit.cause);
274 }
275 }
276 return yield* new ServerUpdateTerminalError({
277 targetVersion,
278 status: "failed",
279 reason: "The desktop app resumed without installing the prepared update.",
280 });
281});
282​
283export function serverUpdateStateForProgressEvent(
284 fromVersion: string,
285 targetVersion: string,
286 event: ServerSelfUpdateProgressEvent,
287): Extract<ServerUpdateState, { status: "running" }> {
288 return {
289 status: "running",
290 stage: event.type === "complete" ? "resuming" : event.stage,
291 fromVersion,
292 targetVersion,
293 };
295​
296export function serverUpdateStateForServerVersion(
297 state: ServerUpdateState,
298 serverVersion: string | null,
299): ServerUpdateState {
300 return state.status === "idle" ||
301 state.status === "running" ||
302 serverVersion === null ||
303 state.fromVersion === serverVersion
304 ? state
305 : IDLE_SERVER_UPDATE_STATE;
307​
308function serverUpdateFailureMessage(error: unknown): string {
309 return error instanceof Error ? error.message : "Server update failed.";
311​
312function isRpcSocketError(error: unknown): boolean {
313 if (!isRpcClientError(error)) {
314 return false;
315 }
316 switch (error.reason._tag) {
317 case "SocketReadError":
318 case "SocketWriteError":
319 case "SocketCloseError":
320 return true;
321 default:
322 return false;
323 }
325​
326export function isLegacyUpdateHandoffLoss(cause: Cause.Cause<unknown>): boolean {
327 if (Cause.hasInterruptsOnly(cause)) {
328 return true;
329 }
330 return (
331 cause.reasons.length > 0 &&
332 cause.reasons.every((reason) => Cause.isFailReason(reason) && isRpcSocketError(reason.error))
333 );
335​
336export function resolveServerUpdateProgressResult<E>(
337 targetVersion: string,
338 terminal: Option.Option<ServerSelfUpdateResult>,
339 streamExit: Exit.Exit<void, E>,
340): Effect.Effect<ServerSelfUpdateResult, E | ServerUpdateProgressIncompleteError> {
341 if (
342 Option.isSome(terminal) &&
343 (Exit.isSuccess(streamExit) || isLegacyUpdateHandoffLoss(streamExit.cause))
344 ) {
345 return Effect.succeed(terminal.value);
346 }
347 if (Exit.isFailure(streamExit)) {
348 return Effect.failCause(streamExit.cause);
349 }
350 return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
352​
353const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({
354 version: 1,
355 type: "snapshot",
356 config,
357});
358​
359export interface ServerConfigSubscriptionOptions {
360 readonly environmentThemes?: boolean;
361 readonly usageLimitSources?: boolean;
362 readonly usageLimitsCommand?: boolean;
364​
365export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
366 function* (subscription: ServerConfigSubscriptionOptions) {
367 const supervisor = yield* EnvironmentSupervisor;
368 const cache = yield* EnvironmentCacheStore;
369 const environmentId = supervisor.target.environmentId;
370 const cachedConfig = yield* cache.loadServerConfig(environmentId).pipe(
371 Effect.catch((error) =>
372 Effect.logWarning("Could not load cached server configuration.").pipe(
373 Effect.annotateLogs({
374 environmentId,
375 ...safeErrorLogAttributes(error),
376 }),
377 Effect.as(Option.none<ServerConfig>()),
378 ),
379 ),
380 );
381 const state = yield* SubscriptionRef.make<Option.Option<ServerConfigProjection>>(
382 // Stripped on load as well as on save: a cache written by an earlier
383 // build can still carry published themes.
384 Option.map(cachedConfig, (cached) => ({
385 config: withoutEnvironmentThemes(cached),
386 latestEvent: cachedConfigSnapshotEvent(withoutEnvironmentThemes(cached)),
387 source: "cache" as const,
388 })),
389 );
390 const persistence = yield* Queue.sliding<ServerConfig>(1);
391 const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());
392​
393 const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (
394 config: ServerConfig,
395 ) {
396 return yield* cache.saveServerConfig(environmentId, withoutEnvironmentThemes(config)).pipe(
397 Effect.as(true),
398 Effect.catch((error) =>
399 Effect.logWarning("Could not persist cached server configuration.").pipe(
400 Effect.annotateLogs({
401 environmentId,
402 ...safeErrorLogAttributes(error),
403 }),
404 Effect.as(false),
405 ),
406 ),
407 );
408 });
409​
410 const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (
411 config: ServerConfig,
412 ) {
413 if (!(yield* persist(config))) {
414 return;
415 }
416 yield* Ref.update(pendingPersistence, (pending) =>
417 Option.isSome(pending) && pending.value === config ? Option.none() : pending,
418 );
419 });
420​
421 yield* Stream.fromQueue(persistence).pipe(
422 Stream.debounce("500 millis"),
423 Stream.runForEach(persistPending),
424 Effect.forkScoped,
425 );
426​
427 yield* subscribe(WS_METHODS.subscribeServerConfig, {
428 ...(subscription.environmentThemes === true ? { environmentThemes: true } : {}),
429 ...(subscription.usageLimitSources === true ? { usageLimitSources: true } : {}),
430 ...(subscription.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
431 }).pipe(
432 Stream.runForEach((event) =>
433 Effect.gen(function* () {
434 const next = applyServerConfigProjection(yield* SubscriptionRef.get(state), event);
435 if (Option.isNone(next)) {
436 return;
437 }
438 yield* Ref.set(pendingPersistence, Option.some(next.value.config));
439 yield* SubscriptionRef.set(state, next);
440 yield* Queue.offer(persistence, next.value.config);
441 }),
442 ),
443 Effect.forkScoped,
444 );
445​
446 yield* Effect.addFinalizer(() =>
447 Ref.get(pendingPersistence).pipe(
448 Effect.flatMap(
449 Option.match({
450 onNone: () => Effect.void,
451 onSome: (config) => persist(config).pipe(Effect.asVoid),
452 }),
453 ),
454 ),
455 );
456​
457 return state;
458 },
459);
460​
461function serverConfigStateChanges(
462 environmentId: EnvironmentId,
463 subscription: ServerConfigSubscriptionOptions,
464) {
465 return followStreamInEnvironment(
466 environmentId,
467 Stream.unwrap(
468 makeEnvironmentServerConfigState(subscription).pipe(
469 Effect.map((state) =>
470 SubscriptionRef.changes(state).pipe(
471 Stream.filterMap((projection) =>
472 Option.match(projection, {
473 onNone: () => Result.failVoid,
474 onSome: (value) => Result.succeed(value),
475 }),
476 ),
477 ),
478 ),
479 ),
480 ),
481 );
483​
484export function applyServerWelcomeEvent(
485 current: EnvironmentServerWelcomeState,
486 session: RpcSession,
487 event: {
488 readonly type: "welcome" | "ready" | "legacyThreadMigration";
489 readonly payload: unknown;
490 },
491): EnvironmentServerWelcomeState {
492 return event.type === "welcome" && current.currentSession === session
493 ? {
494 ...current,
495 welcomeSession: session,
496 welcome: event.payload as ServerLifecycleWelcomePayload,
497 }
498 : current;
500​
501export interface EnvironmentServerWelcomeState {
502 readonly currentSession: RpcSession | null;
503 readonly welcomeSession: RpcSession | null;
504 readonly welcome: ServerLifecycleWelcomePayload | null;
506​
507export function resolveServerWelcomeState(
508 state: EnvironmentServerWelcomeState,
509): ServerLifecycleWelcomePayload | null {
510 return state.currentSession === state.welcomeSession ? state.welcome : null;
512​
513export const makeEnvironmentServerWelcomeState = Effect.fn("EnvironmentServerWelcomeState.make")(
514 function* () {
515 const supervisor = yield* EnvironmentSupervisor;
516 const initialSession = Option.getOrNull(yield* SubscriptionRef.get(supervisor.session));
517 const state = yield* SubscriptionRef.make<EnvironmentServerWelcomeState>({
518 currentSession: initialSession,
519 welcomeSession: null,
520 welcome: null,
521 });
522​
523 const updateWithCurrentSession = Effect.fn(
524 "EnvironmentServerWelcomeState.updateWithCurrentSession",
525 )(function* (
526 update: (
527 current: EnvironmentServerWelcomeState,
528 currentSession: RpcSession | null,
529 ) => EnvironmentServerWelcomeState,
530 ) {
531 return yield* SubscriptionRef.modifyEffect(state, (current) =>
532 SubscriptionRef.get(supervisor.session).pipe(
533 Effect.map(
534 (latestSession) =>
535 [undefined, update(current, Option.getOrNull(latestSession))] as const,
536 ),
537 ),
538 );
539 });
540​
541 yield* SubscriptionRef.changes(supervisor.session).pipe(
542 Stream.runForEach(() =>
543 updateWithCurrentSession((current, currentSession) => ({
544 ...current,
545 currentSession,
546 })),
547 ),
548 Effect.forkScoped,
549 );
550​
551 yield* subscribeDynamicWithSession(
552 WS_METHODS.subscribeServerLifecycle,
553 Effect.fn("EnvironmentServerWelcomeState.makeSubscribeInput")(function* (session) {
554 yield* updateWithCurrentSession((current, currentSession) =>
555 currentSession === session
556 ? {
557 ...current,
558 currentSession,
559 welcomeSession: session,
560 welcome: null,
561 }
562 : { ...current, currentSession },
563 );
564 return {};
565 }),
566 ).pipe(
567 Stream.runForEach(([session, event]) =>
568 updateWithCurrentSession((current, currentSession) =>
569 applyServerWelcomeEvent(
570 {
571 ...current,
572 currentSession,
573 },
574 session,
575 event,
576 ),
577 ),
578 ),
579 Effect.forkScoped,
580 );
581​
582 return state;
583 },
584);
585​
586function serverWelcomeStateChanges(environmentId: EnvironmentId) {
587 return followStreamInEnvironment(
588 environmentId,
589 Stream.unwrap(
590 makeEnvironmentServerWelcomeState().pipe(
591 Effect.map((state) =>
592 SubscriptionRef.changes(state).pipe(Stream.map(resolveServerWelcomeState)),
593 ),
594 ),
595 ),
596 );
598​
599export function resolveServerConfigValue(
600 projection: ServerConfigProjection | null,
601 initialConfig: ServerConfig | null,
602): ServerConfig | null {
603 if (
604 projection?.source === "live" &&
605 (initialConfig === null ||
606 projection.config.environment.serverVersion === initialConfig.environment.serverVersion)
607 ) {
608 return projection.config;
609 }
610 return initialConfig ?? projection?.config ?? null;
612​
613export function createServerEnvironmentAtoms<R, E>(
614 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
615 options: {
616 readonly initialConfigValueAtom: (
617 environmentId: EnvironmentId,
618 ) => Atom.Atom<ServerConfig | null>;
619 /**
620 * Whether this surface renders themes the environment publishes. Mobile
621 * keeps its own appearance settings, so it neither asks for the stream nor
622 * receives the payload.
623 */
624 readonly environmentThemes?: boolean;
625 /** Whether this surface renders quota from configured usage-limit sources. */
626 readonly usageLimitSources?: boolean;
627 readonly usageLimitsCommand?: boolean;
628 },
629) {
630 const configScheduler = createAtomCommandScheduler();
631 // Updates stay serial end-to-end, but only their handoff phase occupies the config lane.
632 const updateScheduler = createAtomCommandScheduler();
633 const configConcurrency = {
634 mode: "serial" as const,
635 key: ({ environmentId }: { readonly environmentId: string }) => environmentId,
636 };
637 const configProjectionFamily = Atom.family((environmentId: EnvironmentId) =>
638 runtime
639 .atom(
640 serverConfigStateChanges(environmentId, {
641 ...(options.environmentThemes === true ? { environmentThemes: true } : {}),
642 ...(options.usageLimitSources === true ? { usageLimitSources: true } : {}),
643 ...(options.usageLimitsCommand === true ? { usageLimitsCommand: true } : {}),
644 }),
645 )
646 .pipe(
647 Atom.setIdleTTL(5 * 60_000),
648 Atom.withLabel(`environment-data:server:config-projection:${environmentId}`),
649 ),
650 );
651 const configProjection = (target: {
652 readonly environmentId: EnvironmentId;
653 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerConfig>;
654 }) => configProjectionFamily(target.environmentId);
655 const emptyConfigAtom = Atom.make<ServerConfig | null>(null).pipe(
656 Atom.withLabel("environment-data:server:config:empty"),
657 );
658 const configValueAtom = Atom.family((environmentId: EnvironmentId | null) => {
659 if (environmentId === null) {
660 return emptyConfigAtom;
661 }
662 return Atom.make((get): ServerConfig | null => {
663 const projection = Option.getOrNull(
664 AsyncResult.value(get(configProjection({ environmentId, input: {} }))),
665 );
666 return resolveServerConfigValue(
667 projection,
668 get(options.initialConfigValueAtom(environmentId)),
669 );
670 }).pipe(Atom.withLabel(`environment-data:server:config:${environmentId}`));
671 });
672 const updateStateValueAtom = Atom.family((environmentId: EnvironmentId) =>
673 Atom.make((get) =>
674 serverUpdateStateForServerVersion(
675 get(serverUpdateStateAtom(environmentId)),
676 get(configValueAtom(environmentId))?.environment.serverVersion ?? null,
677 ),
678 ).pipe(Atom.withLabel(`environment-data:server:update-state-value:${environmentId}`)),
679 );
680 const updateStateAtom = (environmentId: EnvironmentId | null) =>
681 environmentId === null ? EMPTY_SERVER_UPDATE_STATE_ATOM : updateStateValueAtom(environmentId);
682 const updateServer = createRuntimeCommand<
683 EnvironmentRegistry | EnvironmentCacheStore | R,
684 E,
685 ServerUpdateTarget,
686 ServerSelfUpdateResult,
687 unknown
688 >(runtime, {
689 label: "environment-data:server:update-server",
690 scheduler: updateScheduler,
691 concurrency: configConcurrency,
692 execute: (target, atomRegistry) => {
693 const stateAtom = serverUpdateStateAtom(target.environmentId);
694 let targetVersion = target.input.targetVersion;
695 let fromVersion =
696 atomRegistry.get(configValueAtom(target.environmentId))?.environment.serverVersion ??
697 targetVersion;
698 let currentStage: ServerUpdateStage = "downloading";
699 let desktopCommitLostTransport = false;
700 atomRegistry.set(stateAtom, {
701 status: "running",
702 stage: currentStage,
703 fromVersion,
704 targetVersion,
705 });
706​
707 return Effect.gen(function* () {
708 const environmentRegistry = yield* EnvironmentRegistry;
709 const desktopCommitStarting = yield* Deferred.make<void>();
710 const desktopReconnectObserverArmed = yield* Deferred.make<void>();
711 const desktopReconnected = yield* Deferred.make<void>();
712 yield* Deferred.await(desktopCommitStarting).pipe(
713 Effect.andThen(
714 environmentRegistry.stateChanges(target.environmentId).pipe(
715 Stream.tap(() => Deferred.succeed(desktopReconnectObserverArmed, undefined)),
716 Stream.dropWhile((state) => state.phase === "connected"),
717 Stream.filter((state) => state.phase === "connected"),
718 Stream.runHead,
719 ),
720 ),
721 Effect.andThen(Deferred.succeed(desktopReconnected, undefined)),
722 Effect.forkChild,
723 );
724 const result = yield* scheduleAtomCommandEffect(
725 atomRegistry,
726 configScheduler,
727 configConcurrency,
728 target,
729 Effect.gen(function* () {
730 const currentConfig = atomRegistry.get(configValueAtom(target.environmentId));
731 fromVersion = currentConfig?.environment.serverVersion ?? targetVersion;
732 atomRegistry.set(stateAtom, {
733 status: "running",
734 stage: currentStage,
735 fromVersion,
736 targetVersion,
737 });
738​
739 const supportsProgress =
740 currentConfig?.environment.capabilities.serverSelfUpdateProgress === true;
741 const updateResult: ServerSelfUpdateResult = supportsProgress
742 ? yield* Effect.gen(function* () {
743 const terminal = yield* Ref.make<Option.Option<ServerSelfUpdateResult>>(
744 Option.none(),
745 );
746 const streamExit = yield* environmentRegistry
747 .runStream(
748 target.environmentId,
749 runStream(WS_METHODS.serverUpdateServerWithProgress, target.input),
750 )
751 .pipe(
752 Stream.runForEach((event) =>
753 Effect.sync(() => {
754 currentStage = event.type === "complete" ? "resuming" : event.stage;
755 atomRegistry.set(
756 stateAtom,
757 serverUpdateStateForProgressEvent(fromVersion, targetVersion, event),
758 );
759 }).pipe(
760 Effect.andThen(
761 event.type === "complete"
762 ? Ref.set(terminal, Option.some(event.result))
763 : Effect.void,
764 ),
765 ),
766 ),
767 Effect.exit,
768 );
769 return yield* resolveServerUpdateProgressResult(
770 targetVersion,
771 yield* Ref.get(terminal),
772 streamExit,
773 );
774 })
775 : yield* Effect.gen(function* () {
776 const selfUpdateMethod = currentConfig?.environment.capabilities.serverSelfUpdate;
777 const exit = yield* environmentRegistry
778 .run(target.environmentId, request(WS_METHODS.serverUpdateServer, target.input))
779 .pipe(Effect.exit);
780 if (Exit.isSuccess(exit)) {
781 return exit.value;
782 }
783 if (
784 (selfUpdateMethod === "boot-service" || selfUpdateMethod === "respawn") &&
785 isLegacyUpdateHandoffLoss(exit.cause)
786 ) {
787 // Older servers can tear down the transport before their
788 // unary acknowledgement arrives. Treat only that transport
789 // loss as a handoff, then prove it by waiting for target ready.
790 return { targetVersion, method: selfUpdateMethod };
791 }
792 return yield* Effect.failCause(exit.cause);
793 });
794​
795 if (
796 updateResult.method === "desktop-app" &&
797 updateResult.desktopUpdateToken !== undefined
798 ) {
799 yield* Deferred.succeed(desktopCommitStarting, undefined);
800 yield* Deferred.await(desktopReconnectObserverArmed);
801 const commitExit = yield* environmentRegistry
802 .run(
803 target.environmentId,
804 request(WS_METHODS.serverCommitDesktopUpdate, {
805 requestId: updateResult.desktopUpdateToken,
806 }),
807 )
808 .pipe(Effect.exit);
809 if (Exit.isFailure(commitExit) && !isLegacyUpdateHandoffLoss(commitExit.cause)) {
810 return yield* Effect.failCause(commitExit.cause);
811 }
812 desktopCommitLostTransport = Exit.isFailure(commitExit);
813 }
814​
815 targetVersion = updateResult.targetVersion;
816​
817 currentStage = "resuming";
818 atomRegistry.set(stateAtom, {
819 status: "running",
820 stage: currentStage,
821 fromVersion,
822 targetVersion,
823 });
824 return updateResult;
825 }),
826 );
827​
828 // The update restart is intentional and the server stays unreachable
829 // for the whole restart, so hold the retry cadence flat instead of
830 // letting the supervisor climb its backoff ladder.
831 yield* nudgeReconnectDuringUpdateRestart({
832 stateChanges: environmentRegistry.stateChanges(target.environmentId),
833 retryNow: environmentRegistry.retryNow(target.environmentId),
834 }).pipe(Effect.forkChild);
835​
836 if (result.method === "desktop-app" && desktopCommitLostTransport) {
837 yield* Deferred.await(desktopReconnected).pipe(
838 Effect.timeout(SERVER_UPDATE_RESUME_TIMEOUT),
839 );
840 }
841​
842 const waitForReady = environmentRegistry
843 .followStream(target.environmentId, subscribe(WS_METHODS.subscribeServerLifecycle, {}))
844 .pipe(
845 Stream.filter(
846 (event): event is ServerLifecycleStreamReadyEvent =>
847 event.type === "ready" && matchesServerUpdateResumeEvent(result, event),
848 ),
849 Stream.runHead,
850 Effect.timeoutOption(SERVER_UPDATE_RESUME_TIMEOUT),
851 Effect.map(Option.flatten),
852 );
853 const nextReady = waitForReady.pipe(
854 Effect.flatMap(
855 Option.match({
856 onNone: () =>
857 new ServerUpdateResumeTimeoutError({
858 environmentId: target.environmentId,
859 targetVersion,
860 }),
861 onSome: Effect.succeed,
862 }),
863 ),
864 );
865 const desktopUpdateToken = result.desktopUpdateToken;
866 const resumed =
867 result.method === "desktop-app" && desktopUpdateToken !== undefined
868 ? yield* waitForDesktopUpdateTarget(
869 result.targetVersion,
870 nextReady,
871 runDesktopCommitWithReconnectObserver(
872 environmentRegistry.stateChanges(target.environmentId),
873 environmentRegistry
874 .run(
875 target.environmentId,
876 request(WS_METHODS.serverCommitDesktopUpdate, {
877 requestId: desktopUpdateToken,
878 }),
879 )
880 .pipe(Effect.asVoid),
881 ),
882 )
883 : yield* nextReady;
884 yield* validateServerUpdateReadyEvent(result, resumed);
885​
886 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
887 return result;
888 }).pipe(
889 Effect.onExit((exit) =>
890 Effect.sync(() => {
891 if (Exit.isSuccess(exit)) {
892 return;
893 }
894 if (Cause.hasInterruptsOnly(exit.cause)) {
895 atomRegistry.set(stateAtom, IDLE_SERVER_UPDATE_STATE);
896 return;
897 }
898 atomRegistry.set(stateAtom, {
899 status: "failed",
900 stage: currentStage,
901 fromVersion,
902 targetVersion,
903 message: serverUpdateFailureMessage(Cause.squash(exit.cause)),
904 });
905 }),
906 ),
907 );
908 },
909 });
910 const settingsValueAtom = Atom.family((environmentId: EnvironmentId) =>
911 Atom.make((get) => get(configValueAtom(environmentId))?.settings ?? null).pipe(
912 Atom.withLabel(`environment-data:server:settings:${environmentId}`),
913 ),
914 );
915 const usagePricesAtom = Atom.family((environmentId: EnvironmentId) =>
916 Atom.make((get) => {
917 const overrides = get(settingsValueAtom(environmentId))?.usagePriceOverrides ?? {};
918 // Only changed prices should trigger another transcript scan. Settings
919 // snapshots can recreate the same mapping in a different property order.
920 return JSON.stringify(
921 Object.keys(overrides)
922 .sort()
923 .map((model) => {
924 const price = overrides[model]!;
925 return [
926 model,
927 price.inputCostPerMillionTokens,
928 price.outputCostPerMillionTokens,
929 price.cacheReadCostPerMillionTokens,
930 price.cacheWriteCostPerMillionTokens,
931 ];
932 }),
933 );
934 }).pipe(Atom.withLabel(`environment-data:server:usage-prices:${environmentId}`)),
935 );
936 const providersValueAtom = Atom.family((environmentId: EnvironmentId) =>
937 Atom.make((get) => get(configValueAtom(environmentId))?.providers ?? null).pipe(
938 Atom.withLabel(`environment-data:server:providers:${environmentId}`),
939 ),
940 );
941 const welcomeStateFamily = Atom.family((environmentId: EnvironmentId) =>
942 runtime
943 .atom(serverWelcomeStateChanges(environmentId), { initialValue: null })
944 .pipe(
945 Atom.setIdleTTL(5 * 60_000),
946 Atom.withLabel(`environment-data:server:welcome-state:${environmentId}`),
947 ),
948 );
949 const welcomeFamily = Atom.family((environmentId: EnvironmentId) =>
950 Atom.make((get) => {
951 const result = get(welcomeStateFamily(environmentId));
952 if (result._tag !== "Success") return result;
953 return result.value === null
954 ? AsyncResult.initial<ServerLifecycleWelcomePayload, never>(result.waiting)
955 : AsyncResult.success(result.value, result);
956 }).pipe(Atom.withLabel(`environment-data:server:welcome:${environmentId}`)),
957 );
958 const welcome = (target: {
959 readonly environmentId: EnvironmentId;
960 readonly input: EnvironmentRpcInput<typeof WS_METHODS.subscribeServerLifecycle>;
961 }) => welcomeFamily(target.environmentId);
962 const updateSettings = createEnvironmentRpcCommand(runtime, {
963 label: "environment-data:server:update-settings",
964 tag: WS_METHODS.serverUpdateSettings,
965 scheduler: configScheduler,
966 concurrency: configConcurrency,
967 });
968​
969 return {
970 configValueAtom,
971 updateStateAtom,
972 settingsValueAtom,
973 providersValueAtom,
974 providerAuthState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
975 label: "environment-data:provider:auth-state",
976 tag: WS_METHODS.providerAuthSubscribe,
977 idleTtlMs: 0,
978 }),
979 startProviderAuth: createEnvironmentRpcCommand(runtime, {
980 label: "environment-data:provider:auth-start",
981 tag: WS_METHODS.providerAuthStart,
982 concurrency: {
983 mode: "singleFlight",
984 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
985 },
986 }),
987 completeProviderAuth: createEnvironmentRpcCommand(runtime, {
988 label: "environment-data:provider:auth-complete",
989 tag: WS_METHODS.providerAuthComplete,
990 }),
991 cancelProviderAuth: createEnvironmentRpcCommand(runtime, {
992 label: "environment-data:provider:auth-cancel",
993 tag: WS_METHODS.providerAuthCancel,
994 }),
995 logoutProviderAuth: createEnvironmentRpcCommand(runtime, {
996 label: "environment-data:provider:auth-logout",
997 tag: WS_METHODS.providerAuthLogout,
998 }),
999 providerInstallState: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1000 label: "environment-data:provider:install-state",
1001 tag: WS_METHODS.providerInstallSubscribe,
1002 idleTtlMs: 0,
1003 }),
1004 startProviderInstall: createEnvironmentRpcCommand(runtime, {
1005 label: "environment-data:provider:install-start",
1006 tag: WS_METHODS.providerInstallStart,
1007 concurrency: {
1008 mode: "singleFlight",
1009 key: ({ environmentId }) => environmentId,
1010 },
1011 }),
1012 cancelProviderInstall: createEnvironmentRpcCommand(runtime, {
1013 label: "environment-data:provider:install-cancel",
1014 tag: WS_METHODS.providerInstallCancel,
1015 }),
1016 removeProviderInstallation: createEnvironmentRpcCommand(runtime, {
1017 label: "environment-data:provider:install-remove",
1018 tag: WS_METHODS.providerInstallRemove,
1019 }),
1020 traceDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1021 label: "environment-data:server:trace-diagnostics",
1022 tag: WS_METHODS.serverGetTraceDiagnostics,
1023 }),
1024 processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1025 label: "environment-data:server:process-diagnostics",
1026 tag: WS_METHODS.serverGetProcessDiagnostics,
1027 }),
1028 hostResources: createEnvironmentQueryAtomFamily(runtime, {
1029 label: "environment-data:server:host-resources",
1030 idleTtlMs: 0,
1031 staleTimeMs: 5_000,
1032 execute: (input: EnvironmentRpcInput<typeof WS_METHODS.serverGetHostResources>) =>
1033 request(WS_METHODS.serverGetHostResources, input).pipe(Effect.timeout("5 seconds")),
1034 }),
1035 processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1036 label: "environment-data:server:process-resource-history",
1037 tag: WS_METHODS.serverGetProcessResourceHistory,
1038 }),
1039 /** Live scheduled-task list: snapshot on subscribe, fresh list after every server-side change. */
1040 scheduledTasksLive: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1041 label: "environment-data:server:scheduled-tasks:live",
1042 tag: WS_METHODS.scheduledTasksSubscribe,
1043 }),
1044 // A cold transcript scan is measured in seconds, so keep the result around
1045 // long enough that switching windows or re-rendering does not rescan.
1046 usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
1047 label: "environment-data:server:usage-summary",
1048 tag: WS_METHODS.serverGetUsageSummary,
1049 staleTimeMs: 60_000,
1050 refreshTrigger: ({ environmentId }) => usagePricesAtom(environmentId),
1051 }),
1052 resourceTelemetry: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1053 label: "environment-data:server:resource-telemetry",
1054 tag: WS_METHODS.subscribeResourceTelemetry,
1055 idleTtlMs: 0,
1056 }),
1057 resourceTelemetryHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
1058 label: "environment-data:server:resource-telemetry-history",
1059 tag: WS_METHODS.serverGetResourceTelemetryHistory,
1060 staleTimeMs: 5_000,
1061 }),
1062 searchAcpRegistry: createEnvironmentRpcQueryAtomFamily(runtime, {
1063 label: "environment-data:server:acp-registry:search",
1064 tag: WS_METHODS.serverSearchAcpRegistry,
1065 // Each submitted search refreshes the server-side registry. Dropping an
1066 // abandoned query immediately also interrupts stale in-flight requests.
1067 staleTimeMs: 0,
1068 idleTtlMs: 0,
1069 }),
1070 configProjection,
1071 welcome,
1072 legacyThreadMigration: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
1073 label: "environment-data:server:legacy-thread-migration",
1074 tag: WS_METHODS.subscribeServerLifecycle,
1075 transform: (stream) =>
1076 stream.pipe(
1077 Stream.filterMap((event) =>
1078 event.type === "legacyThreadMigration"
1079 ? Result.succeed(event.payload)
1080 : Result.failVoid,
1081 ),
1082 ),
1083 }),
1084 consumeResetCredit: createEnvironmentRpcCommand(runtime, {
1085 label: "environment-data:server:consume-reset-credit",
1086 tag: WS_METHODS.providerConsumeResetCredit,
1087 concurrency: {
1088 mode: "singleFlight",
1089 // Both ids are free-form strings; a delimiter could collide.
1090 key: ({ environmentId, input }) => JSON.stringify([environmentId, input]),
1091 },
1092 }),
1093 refreshProviders: createEnvironmentRpcCommand(runtime, {
1094 label: "environment-data:server:refresh-providers",
1095 tag: WS_METHODS.serverRefreshProviders,
1096 concurrency: {
1097 mode: "singleFlight",
1098 key: ({ environmentId, input }) =>
1099 JSON.stringify([
1100 environmentId,
1101 input.instanceId ?? null,
1102 input.cwd ?? null,
1103 input.refreshModels ?? false,
1104 ]),
1105 },
1106 }),
1107 updateProvider: createEnvironmentRpcCommand(runtime, {
1108 label: "environment-data:server:update-provider",
1109 tag: WS_METHODS.serverUpdateProvider,
1110 scheduler: configScheduler,
1111 concurrency: configConcurrency,
1112 }),
1113 updateServer,
1114 upsertKeybinding: createEnvironmentRpcCommand(runtime, {
1115 label: "environment-data:server:upsert-keybinding",
1116 tag: WS_METHODS.serverUpsertKeybinding,
1117 scheduler: configScheduler,
1118 concurrency: configConcurrency,
1119 }),
1120 removeKeybinding: createEnvironmentRpcCommand(runtime, {
1121 label: "environment-data:server:remove-keybinding",
1122 tag: WS_METHODS.serverRemoveKeybinding,
1123 scheduler: configScheduler,
1124 concurrency: configConcurrency,
1125 }),
1126 updateSettings,
1127 // Provider-instance mutations share the settings command and its
1128 // environment-serial scheduler. The named boundary keeps clients on the
1129 // atomic map-entry payload instead of rebuilding a stale whole map.
1130 mutateProviderInstance: updateSettings,
1131 prepareAcpRegistryAgent: createEnvironmentRpcCommand(runtime, {
1132 label: "environment-data:server:acp-registry:prepare",
1133 tag: WS_METHODS.serverPrepareAcpRegistryAgent,
1134 concurrency: {
1135 mode: "singleFlight",
1136 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1137 },
1138 }),
1139 uninstallAcpRegistryManagedBinary: createEnvironmentRpcCommand(runtime, {
1140 label: "environment-data:server:acp-registry:uninstall-managed-binary",
1141 tag: WS_METHODS.serverUninstallAcpRegistryManagedBinary,
1142 concurrency: {
1143 mode: "singleFlight",
1144 key: ({ environmentId, input }) => `${environmentId}:${input.agentId}`,
1145 },
1146 }),
1147 acceptAcpRegistryUrlAuth: createEnvironmentRpcCommand(runtime, {
1148 label: "environment-data:server:acp-registry:accept-url-auth",
1149 tag: WS_METHODS.serverAcceptAcpRegistryUrlAuth,
1150 concurrency: {
1151 mode: "singleFlight",
1152 key: ({ environmentId, input }) =>
1153 `${environmentId}:${input.instanceId}:${input.elicitationId}`,
1154 },
1155 }),
1156 listAcpRegistrySessions: createEnvironmentRpcCommand(runtime, {
1157 label: "environment-data:server:acp-registry:list-sessions",
1158 tag: WS_METHODS.serverListAcpRegistrySessions,
1159 concurrency: {
1160 mode: "singleFlight",
1161 key: ({ environmentId, input }) =>
1162 `${environmentId}:${input.instanceId}:${input.projectId}:${input.cursor ?? "first"}`,
1163 },
1164 }),
1165 importAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1166 label: "environment-data:server:acp-registry:import-session",
1167 tag: WS_METHODS.serverImportAcpRegistrySession,
1168 concurrency: {
1169 mode: "singleFlight",
1170 key: ({ environmentId, input }) =>
1171 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1172 },
1173 }),
1174 deleteAcpRegistrySession: createEnvironmentRpcCommand(runtime, {
1175 label: "environment-data:server:acp-registry:delete-session",
1176 tag: WS_METHODS.serverDeleteAcpRegistrySession,
1177 concurrency: {
1178 mode: "singleFlight",
1179 key: ({ environmentId, input }) =>
1180 `${environmentId}:${input.instanceId}:${input.projectId}:${input.sessionId}`,
1181 },
1182 }),
1183 listAcpRegistryProviders: createEnvironmentRpcCommand(runtime, {
1184 label: "environment-data:server:acp-registry:list-providers",
1185 tag: WS_METHODS.serverListAcpRegistryProviders,
1186 concurrency: {
1187 mode: "singleFlight",
1188 key: ({ environmentId, input }) =>
1189 `${environmentId}:${input.instanceId}:${input.projectId}`,
1190 },
1191 }),
1192 setAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1193 label: "environment-data:server:acp-registry:set-provider",
1194 tag: WS_METHODS.serverSetAcpRegistryProvider,
1195 concurrency: {
1196 mode: "singleFlight",
1197 key: ({ environmentId, input }) =>
1198 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1199 },
1200 }),
1201 disableAcpRegistryProvider: createEnvironmentRpcCommand(runtime, {
1202 label: "environment-data:server:acp-registry:disable-provider",
1203 tag: WS_METHODS.serverDisableAcpRegistryProvider,
1204 concurrency: {
1205 mode: "singleFlight",
1206 key: ({ environmentId, input }) =>
1207 `${environmentId}:${input.instanceId}:${input.projectId}:${input.providerId}`,
1208 },
1209 }),
1210 logoutAcpRegistry: createEnvironmentRpcCommand(runtime, {
1211 label: "environment-data:server:acp-registry:logout",
1212 tag: WS_METHODS.serverLogoutAcpRegistry,
1213 concurrency: {
1214 mode: "singleFlight",
1215 key: ({ environmentId, input }) => `${environmentId}:${input.instanceId}`,
1216 },
1217 }),
1218 signalProcess: createEnvironmentRpcCommand(runtime, {
1219 label: "environment-data:server:signal-process",
1220 tag: WS_METHODS.serverSignalProcess,
1221 }),
1222 upsertScheduledTask: createEnvironmentRpcCommand(runtime, {
1223 label: "environment-data:server:scheduled-task:upsert",
1224 tag: WS_METHODS.scheduledTasksUpsert,
1225 scheduler: configScheduler,
1226 concurrency: configConcurrency,
1227 }),
1228 setScheduledTaskEnabled: createEnvironmentRpcCommand(runtime, {
1229 label: "environment-data:server:scheduled-task:set-enabled",
1230 tag: WS_METHODS.scheduledTasksSetEnabled,
1231 scheduler: configScheduler,
1232 concurrency: configConcurrency,
1233 }),
1234 deleteScheduledTask: createEnvironmentRpcCommand(runtime, {
1235 label: "environment-data:server:scheduled-task:delete",
1236 tag: WS_METHODS.scheduledTasksDelete,
1237 scheduler: configScheduler,
1238 concurrency: configConcurrency,
1239 }),
1240 // Deliberately not on the config lane: run-now blocks until the run is
1241 // dispatched, and a slow run must not stall settings/keybinding/provider
1242 // mutations (or other scheduled-task edits) queued behind it.
1243 runScheduledTaskNow: createEnvironmentRpcCommand(runtime, {
1244 label: "environment-data:server:scheduled-task:run-now",
1245 tag: WS_METHODS.scheduledTasksRunNow,
1246 }),
1247 refreshUsageRates: createEnvironmentRpcCommand(runtime, {
1248 label: "environment-data:server:refresh-usage-rates",
1249 tag: WS_METHODS.serverRefreshUsageRates,
1250 concurrency: {
1251 mode: "singleFlight",
1252 key: ({ environmentId }) => environmentId,
1253 },
1254 }),
1255 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1256 label: "environment-data:server:retry-resource-telemetry",
1257 tag: WS_METHODS.serverRetryResourceTelemetry,
1258 concurrency: {
1259 mode: "singleFlight",
1260 key: ({ environmentId }) => environmentId,
1261 },
1262 }),
1263 };