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

runtime.ts

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