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

server.ts

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