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

runtime.ts

793 lines26.2 KB

1import { createCommandPermissions } from "./commandPermissions.ts";
2import { followStreamInEnvironment } from "./environmentStreams.ts";
3export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
4import {
5 type ClientGuardedRpcTag,
6 EnvironmentId,
7 type EnvironmentId as EnvironmentIdType,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Effect from "effect/Effect";
11import * as Exit from "effect/Exit";
12import * as Option from "effect/Option";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
16​
17import type { ConnectionAttemptError } from "../connection/model.ts";
18import * as EnvironmentRegistry from "../connection/registry.ts";
19import {
20 type EnvironmentRpcInput,
21 type EnvironmentRpcSuccess,
22 type EnvironmentRpcFailure,
23 type EnvironmentRpcStreamFailure,
24 type EnvironmentRpcStreamValue,
25 type EnvironmentSubscriptionRpcTag,
26 type EnvironmentUnaryRpcTag,
27 EnvironmentRpcUnavailableError,
28 request,
29 requestGuarded,
30 RpcPermissionGuard,
31 subscribe,
32} from "../rpc/client.ts";
33import * as EnvironmentSupervisor from "../connection/supervisor.ts";
34​
35interface EnvironmentAtomOptions<Input, A, E, R> {
36 readonly label: string;
37 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
38 readonly scheduler?: AtomCommandScheduler;
39 readonly concurrency?: AtomCommandConcurrency<{
40 readonly environmentId: EnvironmentIdType;
41 readonly input: Input;
42 }>;
44​
45interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
46 EnvironmentAtomOptions<Input, A, E, R>,
47 "execute"
48> {
49 readonly execute: (
50 input: Input,
51 registry: AtomRegistry.AtomRegistry,
52 environmentId: EnvironmentIdType,
53 ) => Effect.Effect<A, E, R>;
55​
56interface EnvironmentQueryAtomOptions<Input, A, E, R> extends EnvironmentAtomOptions<
57 Input,
58 A,
59 E,
60 R
61> {
62 readonly staleTimeMs?: number;
63 readonly idleTtlMs?: number;
64 readonly refreshIntervalMs?: number;
65 readonly refreshTrigger?: (target: {
66 readonly environmentId: EnvironmentIdType;
67 readonly input: Input;
68 }) => Atom.Atom<unknown> | undefined;
70​
71interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
72 readonly sensitiveInput?: boolean;
73 readonly label: string;
74 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
75 readonly completeWhen?: (value: A) => boolean;
76 readonly idleTtlMs?: number;
78​
79export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
80​
81export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
82​
83export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
84​
85export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
86​
87export interface AtomCommandOptions {
88 readonly label?: string;
89 readonly reportFailure?: boolean;
90 readonly reportDefect?: boolean;
92​
93export interface AtomCommandReporter {
94 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
95 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
97​
98export interface AtomCommand<W, A, E> {
99 readonly label: string;
100 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
102​
103export type AtomCommandConcurrency<W> =
104 /** Every invocation runs independently. */
105 | { readonly mode: "parallel" }
106 | {
107 /**
108 * `serial` preserves every invocation in FIFO order, `singleFlight` shares an active
109 * invocation, and `latest` coalesces queued invocations to the newest input.
110 */
111 readonly mode: "serial" | "singleFlight" | "latest";
112 readonly key: (input: W) => string;
113 };
114​
115interface AtomCommandSchedulerState {
116 readonly serial: Map<string, Promise<unknown>>;
117 readonly singleFlight: Map<string, Promise<unknown>>;
118 readonly latest: Map<string, AtomCommandLatestLane>;
120​
121interface AtomCommandLatestBatch {
122 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
123 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
125​
126interface AtomCommandLatestLane {
127 running: boolean;
128 pending: AtomCommandLatestBatch | undefined;
130​
131export interface AtomCommandScheduler {
132 readonly schedule: <W, A, E>(
133 registry: AtomRegistry.AtomRegistry,
134 concurrency: AtomCommandConcurrency<W>,
135 input: W,
136 execute: () => Promise<AtomCommandResult<A, E>>,
137 ) => Promise<AtomCommandResult<A, E>>;
139​
140async function settleAtomCommandResult<A, E>(
141 execute: () => Promise<AtomCommandResult<A, E>>,
142): Promise<AtomCommandResult<A, E>> {
143 try {
144 return await execute();
145 } catch (defect) {
146 return AsyncResult.failure(Cause.die(defect));
147 }
149​
150export function createAtomCommandScheduler(): AtomCommandScheduler {
151 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
152​
153 const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
154 const existing = registryStates.get(registry);
155 if (existing !== undefined) {
156 return existing;
157 }
158 const state: AtomCommandSchedulerState = {
159 serial: new Map(),
160 singleFlight: new Map(),
161 latest: new Map(),
162 };
163 registryStates.set(registry, state);
164 return state;
165 };
166​
167 return {
168 schedule: <W, A, E>(
169 registry: AtomRegistry.AtomRegistry,
170 concurrency: AtomCommandConcurrency<W>,
171 input: W,
172 execute: () => Promise<AtomCommandResult<A, E>>,
173 ): Promise<AtomCommandResult<A, E>> => {
174 if (concurrency.mode === "parallel") {
175 return execute();
176 }
177​
178 const key = concurrency.key(input);
179 const state = stateFor(registry);
180 if (concurrency.mode === "singleFlight") {
181 const existing = state.singleFlight.get(key) as
182 | Promise<AtomCommandResult<A, E>>
183 | undefined;
184 if (existing !== undefined) {
185 return existing;
186 }
187 const current = execute();
188 state.singleFlight.set(key, current);
189 void current.then(
190 () => {
191 if (state.singleFlight.get(key) === current) {
192 state.singleFlight.delete(key);
193 }
194 },
195 () => {
196 if (state.singleFlight.get(key) === current) {
197 state.singleFlight.delete(key);
198 }
199 },
200 );
201 return current;
202 }
203​
204 if (concurrency.mode === "serial") {
205 const previous = state.serial.get(key);
206 const current = previous === undefined ? execute() : previous.then(execute, execute);
207 state.serial.set(key, current);
208 void current.then(
209 () => {
210 if (state.serial.get(key) === current) {
211 state.serial.delete(key);
212 }
213 },
214 () => {
215 if (state.serial.get(key) === current) {
216 state.serial.delete(key);
217 }
218 },
219 );
220 return current;
221 }
222​
223 let lane = state.latest.get(key);
224 if (lane === undefined) {
225 lane = { running: false, pending: undefined };
226 state.latest.set(key, lane);
227 }
228 const activeLane = lane;
229​
230 const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
231 if (activeLane.pending === undefined) {
232 activeLane.pending = {
233 execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
234 resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
235 };
236 return;
237 }
238 activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
239 activeLane.pending.resolve.push(
240 resolve as (result: AtomCommandResult<unknown, unknown>) => void,
241 );
242 });
243​
244 if (!activeLane.running) {
245 activeLane.running = true;
246 void (async () => {
247 while (activeLane.pending !== undefined) {
248 const batch = activeLane.pending;
249 activeLane.pending = undefined;
250 let batchResult: AtomCommandResult<unknown, unknown>;
251 try {
252 batchResult = await batch.execute();
253 } catch (defect) {
254 batchResult = AsyncResult.failure(Cause.die(defect));
255 }
256 for (const resolve of batch.resolve) {
257 resolve(batchResult);
258 }
259 }
260 activeLane.running = false;
261 if (state.latest.get(key) === activeLane) {
262 state.latest.delete(key);
263 }
264 })();
265 }
266​
267 return result;
268 },
269 };
271​
272/** Runs one effect inside an existing command scheduler lane. */
273export function scheduleAtomCommandEffect<W, A, E, R>(
274 registry: AtomRegistry.AtomRegistry,
275 scheduler: AtomCommandScheduler,
276 concurrency: AtomCommandConcurrency<W>,
277 input: W,
278 effect: Effect.Effect<A, E, R>,
279): Effect.Effect<A, E, R> {
280 return Effect.gen(function* () {
281 const context = yield* Effect.context<R>();
282 const result = yield* Effect.promise((signal) =>
283 scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
284 const exit = await Effect.runPromiseExitWith(context)(effect, { signal });
285 return Exit.isSuccess(exit)
286 ? AsyncResult.success(exit.value)
287 : AsyncResult.failure(exit.cause);
288 }),
289 );
290 return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
291 });
293​
294export async function runAtomCommand<W, A, E>(
295 registry: AtomRegistry.AtomRegistry,
296 command: AtomCommand<W, A, E>,
297 input: W,
298 options: AtomCommandOptions = {},
299 reporter: AtomCommandReporter = console,
300): Promise<AtomCommandResult<A, E>> {
301 const result = await settleAtomCommandResult(() => command.run(registry, input));
302 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
303 return result;
305​
306export function mapAtomCommandResult<A, E, B>(
307 result: AtomCommandResult<A, E>,
308 map: (value: A) => B,
309): AtomCommandResult<B, E> {
310 return result._tag === "Success"
311 ? AsyncResult.success(map(result.value))
312 : AsyncResult.failure(result.cause);
314​
315export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
316 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
318​
319export function squashAtomCommandFailure(result: {
320 readonly cause: Cause.Cause<unknown>;
321}): unknown {
322 return Cause.squash(result.cause);
324​
325export async function settleAsyncResult<A, E>(
326 execute: () => Promise<Exit.Exit<A, E>>,
327): Promise<SettledAsyncResult<A, E>> {
328 try {
329 return AsyncResult.fromExit(await execute());
330 } catch (defect) {
331 return AsyncResult.failure(Cause.die(defect));
332 }
334​
335export async function executeAtomCommand<A, E>(
336 execute: () => Promise<Exit.Exit<A, E>>,
337 options: AtomCommandOptions = {},
338 reporter: AtomCommandReporter = console,
339): Promise<AtomCommandResult<A, E>> {
340 const result = await settleAsyncResult(execute);
341 reportAtomCommandResult(result, options, reporter);
342 return result;
344​
345export interface AtomQueryOptions extends AtomCommandOptions {
346 /**
347 * Force a fresh execution instead of accepting a value the atom already
348 * holds (e.g. an SWR-cached result within its stale window). Used by
349 * verification flows where a cached failure must not satisfy a retry.
350 */
351 readonly refresh?: boolean;
352 /** Interrupt the query wait when its caller no longer wants the result. */
353 readonly signal?: AbortSignal;
355​
356export async function executeAtomQuery<A, E>(
357 registry: AtomRegistry.AtomRegistry,
358 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
359 options: AtomQueryOptions = {},
360 reporter: AtomCommandReporter = console,
361): Promise<AtomCommandResult<A, E>> {
362 const query = Effect.scoped(
363 Effect.gen(function* () {
364 yield* AtomRegistry.mount(registry, atom);
365 if (options.refresh) {
366 yield* Effect.sync(() => {
367 // Only a settled value can be a leftover from an earlier read; a
368 // computation that mounting just started is already fresh.
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 * Refreshes a query when `signal` changes, but only while something reads it.
474 * `Atom.makeRefreshOnSignal` subscribes to the signal, so a query that outlives its view on an
475 * idle TTL still re-runs on every change. Reading the signal as a dependency instead lets the
476 * registry re-run a mounted query right away and only mark an idle one stale, which then
477 * refreshes on its next read.
478 */
479const refreshOnSignalWhileRead =
480 (signal: Atom.Atom<unknown>) =>
481 <A>(self: Atom.Atom<A>): Atom.Atom<A> => {
482 // The signal value each registry's data was read under. Held outside the node because the
483 // registry can sweep this node while `self` keeps the data, and the rebuilt node must still
484 // see a change it missed.
485 const readUnder = new WeakMap<AtomRegistry.AtomRegistry, unknown>();
486 return Atom.transform(
487 self,
488 (get) => {
489 const current = get(signal);
490 get.subscribe(self, (value) => get.setSelf(value));
491 const changed =
492 readUnder.has(get.registry) && !Object.is(readUnder.get(get.registry), current);
493 readUnder.set(get.registry, current);
494 if (changed) get.refresh(self);
495 return get.once(self);
496 },
497 { initialValueTarget: self },
498 );
499 };
500​
501export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
502 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
503 options: EnvironmentQueryAtomOptions<
504 Input,
505 A,
506 E,
507 | EnvironmentSupervisor.EnvironmentSupervisor
508 | EnvironmentRegistry.EnvironmentRegistry
509 | AtomRegistry.AtomRegistry
510 | R
511 >,
512): (target: {
513 readonly environmentId: EnvironmentIdType;
514 readonly input: Input;
515}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
516 const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
517 runtime.atom(
518 followStreamInEnvironment(
519 environmentId,
520 Stream.unwrap(
521 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
522 Effect.map((supervisor) =>
523 SubscriptionRef.changes(supervisor.state).pipe(
524 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
525 ),
526 ),
527 ),
528 ),
529 ),
530 { initialValue: null },
531 ),
532 );
533 const family = Atom.family((key: string) => {
534 const target = parseEnvironmentRpcKey<Input>(key);
535 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
536 const queryAtom = runtime
537 .atom<
538 A,
539 | E
540 | ConnectionAttemptError
541 | EnvironmentRegistry.EnvironmentNotRegisteredError
542 | EnvironmentRpcUnavailableError
543 >((get) => {
544 const connection = Option.getOrNull(
545 AsyncResult.value(get(connectionAtom(target.environmentId))),
546 );
547 if (connection === null) {
548 return Effect.never;
549 }
550 const [connectionState, session] = connection;
551 switch (connectionState.phase) {
552 case "connected":
553 return Option.isSome(session)
554 ? runInEnvironment(target.environmentId, options.execute(target.input))
555 : Effect.never;
556 case "connecting":
557 case "backoff":
558 return Effect.never;
559 case "available":
560 case "offline":
561 case "blocked":
562 if (connectionState.lastFailure !== null) {
563 return Effect.fail(connectionState.lastFailure);
564 }
565 return Effect.fail(
566 new EnvironmentRpcUnavailableError({
567 environmentId: target.environmentId,
568 message: `Environment ${target.environmentId} is ${
569 connectionState.phase === "available" ? "not connected" : connectionState.phase
570 }.`,
571 }),
572 );
573 }
574 })
575 .pipe(
576 Atom.swr({
577 staleTime: options.staleTimeMs ?? 30_000,
578 revalidateOnMount: true,
579 }),
580 Atom.setIdleTTL(idleTtlMs),
581 );
582 const intervalQuery =
583 options.refreshIntervalMs === undefined
584 ? queryAtom
585 : queryAtom.pipe(Atom.withRefresh(options.refreshIntervalMs));
586 const refreshTrigger = options.refreshTrigger?.(target);
587 return (
588 refreshTrigger === undefined
589 ? intervalQuery
590 : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger))
591 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
592 });
593 return (target) => family(environmentRpcKey(target));
595​
596export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
597 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
598 options: EnvironmentSubscriptionAtomOptions<
599 Input,
600 A,
601 E,
602 EnvironmentSupervisor.EnvironmentSupervisor | R
603 >,
604) {
605 const family = Atom.family((key: string) => {
606 const target = parseEnvironmentRpcKey<Input>(key);
607 return runtime
608 .atom(
609 followStreamInEnvironment(target.environmentId, options.subscribe(target.input)).pipe(
610 options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream,
611 ),
612 )
613 .pipe(
614 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
615 Atom.withLabel(
616 options.sensitiveInput
617 ? `${options.label}:${target.environmentId}`
618 : `${options.label}:${key}`,
619 ),
620 );
621 });
622 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
623 family(environmentRpcKey(target));
625​
626export function createEnvironmentCommand<R, ER, Input, A, E>(
627 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
628 options: EnvironmentCommandAtomOptions<
629 Input,
630 A,
631 E,
632 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
633 >,
634) {
635 return createRuntimeCommand(runtime, {
636 label: options.label,
637 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
638 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
639 execute: (target, registry) =>
640 runInEnvironment(
641 target.environmentId,
642 options.execute(target.input, registry, target.environmentId),
643 ),
644 });
646​
647export function createEnvironmentRpcQueryAtomFamily<
648 R,
649 ER,
650 TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,
651>(
652 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
653 options: {
654 readonly label: string;
655 readonly tag: TTag;
656 readonly execute?: (
657 input: EnvironmentRpcInput<TTag>,
658 ) => Effect.Effect<
659 EnvironmentRpcSuccess<TTag>,
660 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
661 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
662 >;
663 readonly staleTimeMs?: number;
664 readonly idleTtlMs?: number;
665 readonly refreshIntervalMs?: number;
666 readonly refreshTrigger?: (target: {
667 readonly environmentId: EnvironmentIdType;
668 readonly input: EnvironmentRpcInput<TTag>;
669 }) => Atom.Atom<unknown> | undefined;
670 },
671) {
672 return createEnvironmentQueryAtomFamily(runtime, {
673 label: options.label,
674 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
675 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
676 ...(options.refreshIntervalMs === undefined
677 ? {}
678 : { refreshIntervalMs: options.refreshIntervalMs }),
679 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
680 execute: (input: EnvironmentRpcInput<TTag>) =>
681 options.execute?.(input) ?? request(options.tag, input),
682 });
684​
685export function createEnvironmentRpcSubscriptionAtomFamily<
686 R,
687 ER,
688 TTag extends EnvironmentSubscriptionRpcTag,
689 B = EnvironmentRpcStreamValue<TTag>,
690>(
691 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
692 options: {
693 readonly label: string;
694 readonly tag: TTag;
695 readonly idleTtlMs?: number;
696 readonly completeWhen?: (value: B) => boolean;
697 readonly transform?: (
698 stream: Stream.Stream<
699 EnvironmentRpcStreamValue<TTag>,
700 EnvironmentRpcStreamFailure<TTag>,
701 EnvironmentSupervisor.EnvironmentSupervisor | R
702 >,
703 ) => Stream.Stream<
704 B,
705 EnvironmentRpcStreamFailure<TTag>,
706 EnvironmentSupervisor.EnvironmentSupervisor | R
707 >;
708 },
709) {
710 return createEnvironmentSubscriptionAtomFamily(runtime, {
711 label: options.label,
712 ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),
713 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
714 subscribe: (input: EnvironmentRpcInput<TTag>) => {
715 const stream = subscribe(options.tag, input);
716 return options.transform === undefined
717 ? (stream as Stream.Stream<
718 B,
719 EnvironmentRpcStreamFailure<TTag>,
720 EnvironmentSupervisor.EnvironmentSupervisor | R
721 >)
722 : options.transform(stream);
723 },
724 });
726​
727export function createEnvironmentRpcCommand<
728 R,
729 ER,
730 TTag extends EnvironmentUnaryRpcTag,
731 Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
732>(
733 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
734 options: {
735 readonly label: string;
736 readonly tag: TTag;
737 readonly execute?: (
738 input: Input,
739 ) => Effect.Effect<
740 EnvironmentRpcSuccess<TTag>,
741 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
742 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
743 >;
744 readonly scheduler?: AtomCommandScheduler;
745 readonly concurrency?: AtomCommandConcurrency<{
746 readonly environmentId: EnvironmentIdType;
747 readonly input: NoInfer<Input>;
748 }>;
749 readonly onSuccess?: (
750 target: {
751 readonly environmentId: EnvironmentIdType;
752 readonly input: NoInfer<Input>;
753 },
754 registry: AtomRegistry.AtomRegistry,
755 ) => Effect.Effect<void, never, R>;
756 readonly onSettled?: (
757 target: {
758 readonly environmentId: EnvironmentIdType;
759 readonly input: NoInfer<Input>;
760 },
761 registry: AtomRegistry.AtomRegistry,
762 ) => Effect.Effect<void, never, R>;
763 },
764) {
765 const permissions = createCommandPermissions(runtime, options.tag);
766 const command = createEnvironmentCommand(runtime, {
767 label: options.label,
768 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
769 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
770 execute: (input: Input, registry, environmentId) => {
771 const target = {
772 environmentId,
773 input,
774 };
775 // Routing requires consent on the origin as well as the actual destination.
776 // The transport check below deliberately checks the destination again.
777 return permissions.authorize(registry, environmentId, input).pipe(
778 Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),
779 Effect.provideService(RpcPermissionGuard, {
780 authorize: (id, method, payload) =>
781 createCommandPermissions(runtime, method).authorize(registry, id, payload),
782 }),
783 Effect.tap(() => options.onSuccess?.(target, registry) ?? Effect.void),
784 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
785 );
786 },
787 });
788 return {
789 ...command,
790 requiredScopes: permissions.requiredScopes,
791 permissionAtom: permissions.permissionAtom,
792 };