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

runtime.ts

858 lines29.2 KB

1import type { QueryPersistence } from "./queryPersistence.ts";
2import { createCommandPermissions } from "./commandPermissions.ts";
3import { followStreamInEnvironment } from "./environmentStreams.ts";
4export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
5import {
6 type ClientGuardedRpcTag,
7 EnvironmentId,
8 type EnvironmentId as EnvironmentIdType,
9} from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Option from "effect/Option";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
17​
18import type { ConnectionAttemptError } from "../connection/model.ts";
19import * as EnvironmentRegistry from "../connection/registry.ts";
20import {
21 type EnvironmentRpcInput,
22 type EnvironmentRpcSuccess,
23 type EnvironmentRpcFailure,
24 type EnvironmentRpcStreamFailure,
25 type EnvironmentRpcStreamValue,
26 type EnvironmentSubscriptionRpcTag,
27 type EnvironmentUnaryRpcTag,
28 EnvironmentRpcUnavailableError,
29 request,
30 requestGuarded,
31 RpcPermissionGuard,
32 subscribe,
33} from "../rpc/client.ts";
34import * as EnvironmentSupervisor from "../connection/supervisor.ts";
35​
36interface EnvironmentAtomOptions<Input, A, E, R> {
37 readonly label: string;
38 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
39 readonly scheduler?: AtomCommandScheduler;
40 readonly concurrency?: AtomCommandConcurrency<{
41 readonly environmentId: EnvironmentIdType;
42 readonly input: Input;
43 }>;
45​
46interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
47 EnvironmentAtomOptions<Input, A, E, R>,
48 "execute"
49> {
50 readonly execute: (
51 input: Input,
52 registry: AtomRegistry.AtomRegistry,
53 environmentId: EnvironmentIdType,
54 ) => Effect.Effect<A, E, R>;
56​
57interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
58 EnvironmentAtomOptions<Input, A, E, R>,
59 "execute"
60> {
61 /**
62 * `emit` shows a provisional value while the query keeps waiting. The settled
63 * result replaces it, so catch failures that should keep it on screen.
64 */
65 readonly execute: (
66 input: Input,
67 emit: (value: A) => Effect.Effect<void>,
68 ) => Effect.Effect<A, E, R>;
69 readonly persistence?: QueryPersistence<A>;
70 readonly staleTimeMs?: number;
71 readonly idleTtlMs?: number;
72 readonly refreshIntervalMs?: number;
73 readonly refreshTrigger?: (target: {
74 readonly environmentId: EnvironmentIdType;
75 readonly input: Input;
76 }) => Atom.Atom<unknown> | undefined;
77 readonly isFinal?: (value: A) => boolean;
79​
80interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
81 readonly sensitiveInput?: boolean;
82 readonly label: string;
83 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
84 readonly completeWhen?: (value: A) => boolean;
85 readonly idleTtlMs?: number;
87​
88export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
89​
90export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
91​
92export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
93​
94export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
95​
96export interface AtomCommandOptions {
97 readonly label?: string;
98 readonly reportFailure?: boolean;
99 readonly reportDefect?: boolean;
101​
102export interface AtomCommandReporter {
103 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
104 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
106​
107export interface AtomCommand<W, A, E> {
108 readonly label: string;
109 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
111​
112export type AtomCommandConcurrency<W> =
113 | { readonly mode: "parallel" }
114 | {
115 readonly mode: "serial" | "singleFlight" | "latest";
116 readonly key: (input: W) => string;
117 };
118​
119interface AtomCommandSchedulerState {
120 readonly serial: Map<string, Promise<unknown>>;
121 readonly singleFlight: Map<string, Promise<unknown>>;
122 readonly latest: Map<string, AtomCommandLatestLane>;
124​
125interface AtomCommandLatestBatch {
126 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
127 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
129​
130interface AtomCommandLatestLane {
131 running: boolean;
132 pending: AtomCommandLatestBatch | undefined;
134​
135export interface AtomCommandScheduler {
136 readonly schedule: <W, A, E>(
137 registry: AtomRegistry.AtomRegistry,
138 concurrency: AtomCommandConcurrency<W>,
139 input: W,
140 execute: () => Promise<AtomCommandResult<A, E>>,
141 ) => Promise<AtomCommandResult<A, E>>;
143​
144async function settleAtomCommandResult<A, E>(
145 execute: () => Promise<AtomCommandResult<A, E>>,
146): Promise<AtomCommandResult<A, E>> {
147 try {
148 return await execute();
149 } catch (defect) {
150 return AsyncResult.failure(Cause.die(defect));
151 }
153​
154export function createAtomCommandScheduler(): AtomCommandScheduler {
155 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
156​
157 const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
158 const existing = registryStates.get(registry);
159 if (existing !== undefined) {
160 return existing;
161 }
162 const state: AtomCommandSchedulerState = {
163 serial: new Map(),
164 singleFlight: new Map(),
165 latest: new Map(),
166 };
167 registryStates.set(registry, state);
168 return state;
169 };
170​
171 return {
172 schedule: <W, A, E>(
173 registry: AtomRegistry.AtomRegistry,
174 concurrency: AtomCommandConcurrency<W>,
175 input: W,
176 execute: () => Promise<AtomCommandResult<A, E>>,
177 ): Promise<AtomCommandResult<A, E>> => {
178 if (concurrency.mode === "parallel") {
179 return execute();
180 }
181​
182 const key = concurrency.key(input);
183 const state = stateFor(registry);
184 if (concurrency.mode === "singleFlight") {
185 const existing = state.singleFlight.get(key) as
186 | Promise<AtomCommandResult<A, E>>
187 | undefined;
188 if (existing !== undefined) {
189 return existing;
190 }
191 const current = execute();
192 state.singleFlight.set(key, current);
193 void current.then(
194 () => {
195 if (state.singleFlight.get(key) === current) {
196 state.singleFlight.delete(key);
197 }
198 },
199 () => {
200 if (state.singleFlight.get(key) === current) {
201 state.singleFlight.delete(key);
202 }
203 },
204 );
205 return current;
206 }
207​
208 if (concurrency.mode === "serial") {
209 const previous = state.serial.get(key);
210 const current = previous === undefined ? execute() : previous.then(execute, execute);
211 state.serial.set(key, current);
212 void current.then(
213 () => {
214 if (state.serial.get(key) === current) {
215 state.serial.delete(key);
216 }
217 },
218 () => {
219 if (state.serial.get(key) === current) {
220 state.serial.delete(key);
221 }
222 },
223 );
224 return current;
225 }
226​
227 let lane = state.latest.get(key);
228 if (lane === undefined) {
229 lane = { running: false, pending: undefined };
230 state.latest.set(key, lane);
231 }
232 const activeLane = lane;
233​
234 const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
235 if (activeLane.pending === undefined) {
236 activeLane.pending = {
237 execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
238 resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
239 };
240 return;
241 }
242 activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
243 activeLane.pending.resolve.push(
244 resolve as (result: AtomCommandResult<unknown, unknown>) => void,
245 );
246 });
247​
248 if (!activeLane.running) {
249 activeLane.running = true;
250 void (async () => {
251 while (activeLane.pending !== undefined) {
252 const batch = activeLane.pending;
253 activeLane.pending = undefined;
254 let batchResult: AtomCommandResult<unknown, unknown>;
255 try {
256 batchResult = await batch.execute();
257 } catch (defect) {
258 batchResult = AsyncResult.failure(Cause.die(defect));
259 }
260 for (const resolve of batch.resolve) {
261 resolve(batchResult);
262 }
263 }
264 activeLane.running = false;
265 if (state.latest.get(key) === activeLane) {
266 state.latest.delete(key);
267 }
268 })();
269 }
270​
271 return result;
272 },
273 };
275​
276export function scheduleAtomCommandEffect<W, A, E, R>(
277 registry: AtomRegistry.AtomRegistry,
278 scheduler: AtomCommandScheduler,
279 concurrency: AtomCommandConcurrency<W>,
280 input: W,
281 effect: Effect.Effect<A, E, R>,
282): Effect.Effect<A, E, R> {
283 return Effect.gen(function* () {
284 const context = yield* Effect.context<R>();
285 const result = yield* Effect.promise((signal) =>
286 scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
287 const exit = await Effect.runPromiseExitWith(context)(effect, { signal });
288 return Exit.isSuccess(exit)
289 ? AsyncResult.success(exit.value)
290 : AsyncResult.failure(exit.cause);
291 }),
292 );
293 return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
294 });
296​
297export async function runAtomCommand<W, A, E>(
298 registry: AtomRegistry.AtomRegistry,
299 command: AtomCommand<W, A, E>,
300 input: W,
301 options: AtomCommandOptions = {},
302 reporter: AtomCommandReporter = console,
303): Promise<AtomCommandResult<A, E>> {
304 const result = await settleAtomCommandResult(() => command.run(registry, input));
305 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
306 return result;
308​
309export function mapAtomCommandResult<A, E, B>(
310 result: AtomCommandResult<A, E>,
311 map: (value: A) => B,
312): AtomCommandResult<B, E> {
313 return result._tag === "Success"
314 ? AsyncResult.success(map(result.value))
315 : AsyncResult.failure(result.cause);
317​
318export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
319 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
321​
322export function squashAtomCommandFailure(result: {
323 readonly cause: Cause.Cause<unknown>;
324}): unknown {
325 return Cause.squash(result.cause);
327​
328export async function settleAsyncResult<A, E>(
329 execute: () => Promise<Exit.Exit<A, E>>,
330): Promise<SettledAsyncResult<A, E>> {
331 try {
332 return AsyncResult.fromExit(await execute());
333 } catch (defect) {
334 return AsyncResult.failure(Cause.die(defect));
335 }
337​
338export async function executeAtomCommand<A, E>(
339 execute: () => Promise<Exit.Exit<A, E>>,
340 options: AtomCommandOptions = {},
341 reporter: AtomCommandReporter = console,
342): Promise<AtomCommandResult<A, E>> {
343 const result = await settleAsyncResult(execute);
344 reportAtomCommandResult(result, options, reporter);
345 return result;
347​
348export interface AtomQueryOptions extends AtomCommandOptions {
349 /**
350 * Force a fresh execution instead of accepting a value the atom already
351 * holds (e.g. an SWR-cached result within its stale window). Used by
352 * verification flows where a cached failure must not satisfy a retry.
353 */
354 readonly refresh?: boolean;
355 readonly signal?: AbortSignal;
357​
358export async function executeAtomQuery<A, E>(
359 registry: AtomRegistry.AtomRegistry,
360 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
361 options: AtomQueryOptions = {},
362 reporter: AtomCommandReporter = console,
363): Promise<AtomCommandResult<A, E>> {
364 const query = Effect.scoped(
365 Effect.gen(function* () {
366 yield* AtomRegistry.mount(registry, atom);
367 if (options.refresh) {
368 yield* Effect.sync(() => {
369 const current = registry.get(atom);
370 if (current._tag !== "Initial" && !current.waiting) {
371 registry.refresh(atom);
372 }
373 });
374 }
375 return yield* AtomRegistry.getResult(registry, atom, {
376 suspendOnWaiting: true,
377 });
378 }),
379 );
380 return executeAtomCommand(
381 () => Effect.runPromiseExit(query, { signal: options.signal }),
382 options,
383 reporter,
384 );
386​
387export function createRuntimeCommand<R, ER, W, A, E>(
388 runtime: Atom.AtomRuntime<R, ER>,
389 options: {
390 readonly label: string;
391 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
392 readonly scheduler?: AtomCommandScheduler;
393 readonly concurrency?: AtomCommandConcurrency<W>;
394 },
395): AtomCommand<W, A, E | ER> {
396 const scheduler = options.scheduler ?? createAtomCommandScheduler();
397 const concurrency = options.concurrency ?? { mode: "parallel" as const };
398 return {
399 label: options.label,
400 run: (registry, input) =>
401 settleAtomCommandResult(() =>
402 scheduler.schedule(registry, concurrency, input, () => {
403 const atom = runtime
404 .atom(options.execute(input, registry))
405 .pipe(Atom.withLabel(options.label));
406 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
407 }),
408 ),
409 };
411​
412export function reportAtomCommandResult(
413 result: AtomCommandResult<unknown, unknown>,
414 options: AtomCommandOptions = {},
415 reporter: AtomCommandReporter = console,
416): void {
417 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
418 return;
419 }
420​
421 const label = options.label ?? "atom command";
422 if (Cause.hasDies(result.cause)) {
423 if (options.reportDefect ?? true) {
424 reporter.error(`[atom-command] ${label} defected`, result.cause);
425 }
426 } else if (options.reportFailure ?? true) {
427 reporter.warn(`[atom-command] ${label} failed`, result.cause);
428 }
430​
431export async function settlePromise<A>(
432 execute: () => Promise<A>,
433): Promise<AtomCommandResult<A, never>> {
434 try {
435 return AsyncResult.success(await execute());
436 } catch (defect) {
437 return AsyncResult.failure(Cause.die(defect));
438 }
440​
441export function environmentRpcKey<Input>(target: {
442 readonly environmentId: EnvironmentIdType;
443 readonly input: Input;
444}): string {
445 return JSON.stringify([target.environmentId, target.input]);
447​
448function parseEnvironmentRpcKey<Input>(key: string): {
449 readonly environmentId: EnvironmentIdType;
450 readonly input: Input;
451} {
452 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
453 return {
454 environmentId: EnvironmentId.make(decoded[0]),
455 input: decoded[1],
456 };
458​
459function runInEnvironment<A, E, R>(
460 environmentId: EnvironmentIdType,
461 effect: Effect.Effect<A, E, R>,
462): Effect.Effect<
463 A,
464 E | EnvironmentRegistry.EnvironmentNotRegisteredError,
465 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
466> {
467 return EnvironmentRegistry.EnvironmentRegistry.pipe(
468 Effect.flatMap((registry) => registry.run(environmentId, effect)),
469 );
471​
472/**
473 * `Atom.makeRefreshOnSignal` subscribes to the signal, so a query that outlives its view on an
474 * idle TTL still re-runs on every change. Reading the signal as a dependency instead lets the
475 * registry re-run a mounted query right away and only mark an idle one stale, which then
476 * refreshes on its next read.
477 */
478const refreshOnSignalWhileRead =
479 <V>(signal: Atom.Atom<unknown>, isFinal: (value: V) => boolean) =>
480 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> => {
481 // The signal value each registry's data was read under. Held outside the node because the
482 // registry can sweep this node while `self` keeps the data, and the rebuilt node must still
483 // see a change it missed.
484 const readUnder = new WeakMap<AtomRegistry.AtomRegistry, unknown>();
485 return Atom.transform(
486 self,
487 (get) => {
488 const current = get(signal);
489 get.subscribe(self, (value) => get.setSelf(value));
490 const changed =
491 readUnder.has(get.registry) && !Object.is(readUnder.get(get.registry), current);
492 readUnder.set(get.registry, current);
493 if (changed && !isFinal(get.once(self))) get.refresh(self);
494 return get.once(self);
495 },
496 { initialValueTarget: self },
497 );
498 };
499​
500const refreshEveryUntilFinal =
501 <V>(intervalMs: number, isFinal: (value: V) => boolean) =>
502 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> =>
503 Atom.transform(
504 self,
505 (get) => {
506 const value = get(self);
507 if (!isFinal(value)) {
508 // @effect-diagnostics-next-line globalTimers:off - Mirrors `Atom.withRefresh`, outside an Effect runtime.
509 const handle = setTimeout(() => get.refresh(self), intervalMs);
510 get.addFinalizer(() => clearTimeout(handle));
511 }
512 return value;
513 },
514 { initialValueTarget: self },
515 );
516​
517export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
518 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
519 options: EnvironmentQueryAtomOptions<
520 Input,
521 A,
522 E,
523 | EnvironmentSupervisor.EnvironmentSupervisor
524 | EnvironmentRegistry.EnvironmentRegistry
525 | AtomRegistry.AtomRegistry
526 | R
527 >,
528): (target: {
529 readonly environmentId: EnvironmentIdType;
530 readonly input: Input;
531}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
532 const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
533 runtime.atom(
534 followStreamInEnvironment(
535 environmentId,
536 Stream.unwrap(
537 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
538 Effect.map((supervisor) =>
539 SubscriptionRef.changes(supervisor.state).pipe(
540 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
541 ),
542 ),
543 ),
544 ),
545 ),
546 { initialValue: null },
547 ),
548 );
549 const family = Atom.family((key: string) => {
550 const target = parseEnvironmentRpcKey<Input>(key);
551 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
552 const queryAtom = runtime
553 .atom<
554 A,
555 | E
556 | ConnectionAttemptError
557 | EnvironmentRegistry.EnvironmentNotRegisteredError
558 | EnvironmentRpcUnavailableError
559 >((get) => {
560 const connection = Option.getOrNull(
561 AsyncResult.value(get(connectionAtom(target.environmentId))),
562 );
563 const emit = (value: A) =>
564 Effect.sync(() => get.setSelf(AsyncResult.success(value, { waiting: true }))).pipe(
565 // A value set while the atom builds wins over the build's own
566 // result, so a query that then settled synchronously would stay
567 // waiting forever. Suspend on a promise (`yieldNow` is drained
568 // inside the build) so the settled result arrives asynchronously.
569 Effect.andThen(Effect.promise(() => Promise.resolve())),
570 );
571 const execute = (): Effect.Effect<
572 A,
573 | E
574 | ConnectionAttemptError
575 | EnvironmentRegistry.EnvironmentNotRegisteredError
576 | EnvironmentRpcUnavailableError,
577 | EnvironmentRegistry.EnvironmentRegistry
578 | AtomRegistry.AtomRegistry
579 | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
580 > => {
581 if (connection === null) return Effect.never;
582 const [connectionState, session] = connection;
583 switch (connectionState.phase) {
584 case "connected":
585 return Option.isSome(session)
586 ? runInEnvironment(target.environmentId, options.execute(target.input, emit))
587 : Effect.never;
588 case "connecting":
589 case "backoff":
590 return Effect.never;
591 case "available":
592 case "offline":
593 case "blocked":
594 if (connectionState.lastFailure !== null) {
595 return Effect.fail(connectionState.lastFailure);
596 }
597 return Effect.fail(
598 new EnvironmentRpcUnavailableError({
599 environmentId: target.environmentId,
600 message: `Environment ${target.environmentId} is ${
601 connectionState.phase === "available" ? "not connected" : connectionState.phase
602 }.`,
603 }),
604 );
605 }
606 };
607 if (!options.persistence) return execute();
608 const persistence = options.persistence;
609 const cacheKey = JSON.stringify([options.label, target.input]);
610 const previous = Option.flatMap(
611 get.self<AsyncResult.AsyncResult<A, unknown>>(),
612 AsyncResult.value,
613 );
614 return Effect.gen(function* () {
615 const cached = Option.isSome(previous)
616 ? previous
617 : yield* persistence.load(target.environmentId, cacheKey);
618 if (
619 Option.isSome(cached) &&
620 (connection === null || connection[0].phase !== "connected")
621 ) {
622 return cached.value;
623 }
624 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
625 return yield* execute().pipe(
626 Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
627 );
628 });
629 })
630 .pipe(
631 Atom.swr({
632 staleTime: options.staleTimeMs ?? 30_000,
633 revalidateOnMount: true,
634 }),
635 Atom.setIdleTTL(idleTtlMs),
636 );
637 const isFinal = (result: AsyncResult.AsyncResult<A, unknown>) =>
638 options.isFinal !== undefined && Option.exists(AsyncResult.value(result), options.isFinal);
639 const intervalQuery =
640 options.refreshIntervalMs === undefined
641 ? queryAtom
642 : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal));
643 const refreshTrigger = options.refreshTrigger?.(target);
644 return (
645 refreshTrigger === undefined
646 ? intervalQuery
647 : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal))
648 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
649 });
650 return (target) => family(environmentRpcKey(target));
652​
653export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
654 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
655 options: EnvironmentSubscriptionAtomOptions<
656 Input,
657 A,
658 E,
659 EnvironmentSupervisor.EnvironmentSupervisor | R
660 >,
661) {
662 const family = Atom.family((key: string) => {
663 const target = parseEnvironmentRpcKey<Input>(key);
664 return runtime
665 .atom(
666 followStreamInEnvironment(target.environmentId, options.subscribe(target.input)).pipe(
667 options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream,
668 ),
669 )
670 .pipe(
671 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
672 Atom.withLabel(
673 options.sensitiveInput
674 ? `${options.label}:${target.environmentId}`
675 : `${options.label}:${key}`,
676 ),
677 );
678 });
679 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
680 family(environmentRpcKey(target));
682​
683export function createEnvironmentCommand<R, ER, Input, A, E>(
684 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
685 options: EnvironmentCommandAtomOptions<
686 Input,
687 A,
688 E,
689 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
690 >,
691) {
692 return createRuntimeCommand(runtime, {
693 label: options.label,
694 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
695 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
696 execute: (target, registry) =>
697 runInEnvironment(
698 target.environmentId,
699 options.execute(target.input, registry, target.environmentId),
700 ),
701 });
703​
704export function createEnvironmentRpcQueryAtomFamily<
705 R,
706 ER,
707 TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,
708>(
709 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
710 options: {
711 readonly label: string;
712 readonly tag: TTag;
713 readonly execute?: (
714 input: EnvironmentRpcInput<TTag>,
715 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
716 ) => Effect.Effect<
717 EnvironmentRpcSuccess<TTag>,
718 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
719 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
720 >;
721 readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;
722 readonly staleTimeMs?: number;
723 readonly idleTtlMs?: number;
724 readonly refreshIntervalMs?: number;
725 readonly refreshTrigger?: (target: {
726 readonly environmentId: EnvironmentIdType;
727 readonly input: EnvironmentRpcInput<TTag>;
728 }) => Atom.Atom<unknown> | undefined;
729 readonly isFinal?: (value: EnvironmentRpcSuccess<TTag>) => boolean;
730 },
731) {
732 return createEnvironmentQueryAtomFamily(runtime, {
733 label: options.label,
734 ...(options.persistence === undefined ? {} : { persistence: options.persistence }),
735 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
736 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
737 ...(options.refreshIntervalMs === undefined
738 ? {}
739 : { refreshIntervalMs: options.refreshIntervalMs }),
740 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
741 ...(options.isFinal === undefined ? {} : { isFinal: options.isFinal }),
742 execute: (
743 input: EnvironmentRpcInput<TTag>,
744 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
745 ) => options.execute?.(input, emit) ?? request(options.tag, input),
746 });
748​
749export function createEnvironmentRpcSubscriptionAtomFamily<
750 R,
751 ER,
752 TTag extends EnvironmentSubscriptionRpcTag,
753 B = EnvironmentRpcStreamValue<TTag>,
754>(
755 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
756 options: {
757 readonly label: string;
758 readonly tag: TTag;
759 readonly idleTtlMs?: number;
760 readonly completeWhen?: (value: B) => boolean;
761 readonly transform?: (
762 stream: Stream.Stream<
763 EnvironmentRpcStreamValue<TTag>,
764 EnvironmentRpcStreamFailure<TTag>,
765 EnvironmentSupervisor.EnvironmentSupervisor | R
766 >,
767 ) => Stream.Stream<
768 B,
769 EnvironmentRpcStreamFailure<TTag>,
770 EnvironmentSupervisor.EnvironmentSupervisor | R
771 >;
772 },
773) {
774 return createEnvironmentSubscriptionAtomFamily(runtime, {
775 label: options.label,
776 ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),
777 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
778 subscribe: (input: EnvironmentRpcInput<TTag>) => {
779 const stream = subscribe(options.tag, input);
780 return options.transform === undefined
781 ? (stream as Stream.Stream<
782 B,
783 EnvironmentRpcStreamFailure<TTag>,
784 EnvironmentSupervisor.EnvironmentSupervisor | R
785 >)
786 : options.transform(stream);
787 },
788 });
790​
791export function createEnvironmentRpcCommand<
792 R,
793 ER,
794 TTag extends EnvironmentUnaryRpcTag,
795 Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
796>(
797 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
798 options: {
799 readonly label: string;
800 readonly tag: TTag;
801 readonly execute?: (
802 input: Input,
803 ) => Effect.Effect<
804 EnvironmentRpcSuccess<TTag>,
805 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
806 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
807 >;
808 readonly scheduler?: AtomCommandScheduler;
809 readonly concurrency?: AtomCommandConcurrency<{
810 readonly environmentId: EnvironmentIdType;
811 readonly input: NoInfer<Input>;
812 }>;
813 readonly onSuccess?: (
814 target: {
815 readonly environmentId: EnvironmentIdType;
816 readonly input: NoInfer<Input>;
817 },
818 registry: AtomRegistry.AtomRegistry,
819 result: EnvironmentRpcSuccess<TTag>,
820 ) => Effect.Effect<void, never, R>;
821 readonly onSettled?: (
822 target: {
823 readonly environmentId: EnvironmentIdType;
824 readonly input: NoInfer<Input>;
825 },
826 registry: AtomRegistry.AtomRegistry,
827 ) => Effect.Effect<void, never, R>;
828 },
829) {
830 const permissions = createCommandPermissions(runtime, options.tag);
831 const command = createEnvironmentCommand(runtime, {
832 label: options.label,
833 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
834 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
835 execute: (input: Input, registry, environmentId) => {
836 const target = {
837 environmentId,
838 input,
839 };
840 // Routing requires consent on the origin as well as the actual destination.
841 // The transport check below deliberately checks the destination again.
842 return permissions.authorize(registry, environmentId, input).pipe(
843 Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),
844 Effect.provideService(RpcPermissionGuard, {
845 authorize: (id, method, payload) =>
846 createCommandPermissions(runtime, method).authorize(registry, id, payload),
847 }),
848 Effect.tap((result) => options.onSuccess?.(target, registry, result) ?? Effect.void),
849 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
850 );
851 },
852 });
853 return {
854 ...command,
855 requiredScopes: permissions.requiredScopes,
856 permissionAtom: permissions.permissionAtom,
857 };