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

runtime.ts

756 lines24.6 KB

1import { EnvironmentId, type EnvironmentId as EnvironmentIdType } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Effect from "effect/Effect";
4import * as Exit from "effect/Exit";
5import * as Option from "effect/Option";
6import * as Stream from "effect/Stream";
7import * as SubscriptionRef from "effect/SubscriptionRef";
8import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
9​
10import type { ConnectionAttemptError } from "../connection/model.ts";
11import * as EnvironmentRegistry from "../connection/registry.ts";
12import {
13 type EnvironmentRpcInput,
14 type EnvironmentRpcSuccess,
15 type EnvironmentRpcFailure,
16 type EnvironmentRpcStreamFailure,
17 type EnvironmentRpcStreamValue,
18 type EnvironmentSubscriptionRpcTag,
19 type EnvironmentUnaryRpcTag,
20 EnvironmentRpcUnavailableError,
21 request,
22 subscribe,
23} from "../rpc/client.ts";
24import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25​
26interface EnvironmentAtomOptions<Input, A, E, R> {
27 readonly label: string;
28 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
29 readonly scheduler?: AtomCommandScheduler;
30 readonly concurrency?: AtomCommandConcurrency<{
31 readonly environmentId: EnvironmentIdType;
32 readonly input: Input;
33 }>;
35​
36interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
37 EnvironmentAtomOptions<Input, A, E, R>,
38 "execute"
39> {
40 readonly execute: (
41 input: Input,
42 registry: AtomRegistry.AtomRegistry,
43 environmentId: EnvironmentIdType,
44 ) => Effect.Effect<A, E, R>;
46​
47interface EnvironmentQueryAtomOptions<Input, A, E, R> extends EnvironmentAtomOptions<
48 Input,
49 A,
50 E,
51 R
52> {
53 readonly staleTimeMs?: number;
54 readonly idleTtlMs?: number;
55 readonly refreshIntervalMs?: number;
56 readonly refreshTrigger?: (target: {
57 readonly environmentId: EnvironmentIdType;
58 readonly input: Input;
59 }) => Atom.Atom<unknown> | undefined;
61​
62interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
63 readonly sensitiveInput?: boolean;
64 readonly label: string;
65 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
66 readonly idleTtlMs?: number;
68​
69export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
70​
71export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
72​
73export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
74​
75export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
76​
77export interface AtomCommandOptions {
78 readonly label?: string;
79 readonly reportFailure?: boolean;
80 readonly reportDefect?: boolean;
82​
83export interface AtomCommandReporter {
84 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
85 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
87​
88export interface AtomCommand<W, A, E> {
89 readonly label: string;
90 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
92​
93export type AtomCommandConcurrency<W> =
94 /** Every invocation runs independently. */
95 | { readonly mode: "parallel" }
96 | {
97 /**
98 * `serial` preserves every invocation in FIFO order, `singleFlight` shares an active
99 * invocation, and `latest` coalesces queued invocations to the newest input.
100 */
101 readonly mode: "serial" | "singleFlight" | "latest";
102 readonly key: (input: W) => string;
103 };
104​
105interface AtomCommandSchedulerState {
106 readonly serial: Map<string, Promise<unknown>>;
107 readonly singleFlight: Map<string, Promise<unknown>>;
108 readonly latest: Map<string, AtomCommandLatestLane>;
110​
111interface AtomCommandLatestBatch {
112 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
113 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
115​
116interface AtomCommandLatestLane {
117 running: boolean;
118 pending: AtomCommandLatestBatch | undefined;
120​
121export interface AtomCommandScheduler {
122 readonly schedule: <W, A, E>(
123 registry: AtomRegistry.AtomRegistry,
124 concurrency: AtomCommandConcurrency<W>,
125 input: W,
126 execute: () => Promise<AtomCommandResult<A, E>>,
127 ) => Promise<AtomCommandResult<A, E>>;
129​
130async function settleAtomCommandResult<A, E>(
131 execute: () => Promise<AtomCommandResult<A, E>>,
132): Promise<AtomCommandResult<A, E>> {
133 try {
134 return await execute();
135 } catch (defect) {
136 return AsyncResult.failure(Cause.die(defect));
137 }
139​
140export function createAtomCommandScheduler(): AtomCommandScheduler {
141 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
142​
143 const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
144 const existing = registryStates.get(registry);
145 if (existing !== undefined) {
146 return existing;
147 }
148 const state: AtomCommandSchedulerState = {
149 serial: new Map(),
150 singleFlight: new Map(),
151 latest: new Map(),
152 };
153 registryStates.set(registry, state);
154 return state;
155 };
156​
157 return {
158 schedule: <W, A, E>(
159 registry: AtomRegistry.AtomRegistry,
160 concurrency: AtomCommandConcurrency<W>,
161 input: W,
162 execute: () => Promise<AtomCommandResult<A, E>>,
163 ): Promise<AtomCommandResult<A, E>> => {
164 if (concurrency.mode === "parallel") {
165 return execute();
166 }
167​
168 const key = concurrency.key(input);
169 const state = stateFor(registry);
170 if (concurrency.mode === "singleFlight") {
171 const existing = state.singleFlight.get(key) as
172 | Promise<AtomCommandResult<A, E>>
173 | undefined;
174 if (existing !== undefined) {
175 return existing;
176 }
177 const current = execute();
178 state.singleFlight.set(key, current);
179 void current.then(
180 () => {
181 if (state.singleFlight.get(key) === current) {
182 state.singleFlight.delete(key);
183 }
184 },
185 () => {
186 if (state.singleFlight.get(key) === current) {
187 state.singleFlight.delete(key);
188 }
189 },
190 );
191 return current;
192 }
193​
194 if (concurrency.mode === "serial") {
195 const previous = state.serial.get(key);
196 const current = previous === undefined ? execute() : previous.then(execute, execute);
197 state.serial.set(key, current);
198 void current.then(
199 () => {
200 if (state.serial.get(key) === current) {
201 state.serial.delete(key);
202 }
203 },
204 () => {
205 if (state.serial.get(key) === current) {
206 state.serial.delete(key);
207 }
208 },
209 );
210 return current;
211 }
212​
213 let lane = state.latest.get(key);
214 if (lane === undefined) {
215 lane = { running: false, pending: undefined };
216 state.latest.set(key, lane);
217 }
218 const activeLane = lane;
219​
220 const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
221 if (activeLane.pending === undefined) {
222 activeLane.pending = {
223 execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
224 resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
225 };
226 return;
227 }
228 activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
229 activeLane.pending.resolve.push(
230 resolve as (result: AtomCommandResult<unknown, unknown>) => void,
231 );
232 });
233​
234 if (!activeLane.running) {
235 activeLane.running = true;
236 void (async () => {
237 while (activeLane.pending !== undefined) {
238 const batch = activeLane.pending;
239 activeLane.pending = undefined;
240 let batchResult: AtomCommandResult<unknown, unknown>;
241 try {
242 batchResult = await batch.execute();
243 } catch (defect) {
244 batchResult = AsyncResult.failure(Cause.die(defect));
245 }
246 for (const resolve of batch.resolve) {
247 resolve(batchResult);
248 }
249 }
250 activeLane.running = false;
251 if (state.latest.get(key) === activeLane) {
252 state.latest.delete(key);
253 }
254 })();
255 }
256​
257 return result;
258 },
259 };
261​
262/** Runs one effect inside an existing command scheduler lane. */
263export function scheduleAtomCommandEffect<W, A, E, R>(
264 registry: AtomRegistry.AtomRegistry,
265 scheduler: AtomCommandScheduler,
266 concurrency: AtomCommandConcurrency<W>,
267 input: W,
268 effect: Effect.Effect<A, E, R>,
269): Effect.Effect<A, E, R> {
270 return Effect.gen(function* () {
271 const context = yield* Effect.context<R>();
272 const result = yield* Effect.promise((signal) =>
273 scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
274 const exit = await Effect.runPromiseExitWith(context)(effect, { signal });
275 return Exit.isSuccess(exit)
276 ? AsyncResult.success(exit.value)
277 : AsyncResult.failure(exit.cause);
278 }),
279 );
280 return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
281 });
283​
284export async function runAtomCommand<W, A, E>(
285 registry: AtomRegistry.AtomRegistry,
286 command: AtomCommand<W, A, E>,
287 input: W,
288 options: AtomCommandOptions = {},
289 reporter: AtomCommandReporter = console,
290): Promise<AtomCommandResult<A, E>> {
291 const result = await settleAtomCommandResult(() => command.run(registry, input));
292 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
293 return result;
295​
296export function mapAtomCommandResult<A, E, B>(
297 result: AtomCommandResult<A, E>,
298 map: (value: A) => B,
299): AtomCommandResult<B, E> {
300 return result._tag === "Success"
301 ? AsyncResult.success(map(result.value))
302 : AsyncResult.failure(result.cause);
304​
305export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
306 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
308​
309export function squashAtomCommandFailure(result: {
310 readonly cause: Cause.Cause<unknown>;
311}): unknown {
312 return Cause.squash(result.cause);
314​
315export async function settleAsyncResult<A, E>(
316 execute: () => Promise<Exit.Exit<A, E>>,
317): Promise<SettledAsyncResult<A, E>> {
318 try {
319 return AsyncResult.fromExit(await execute());
320 } catch (defect) {
321 return AsyncResult.failure(Cause.die(defect));
322 }
324​
325export async function executeAtomCommand<A, E>(
326 execute: () => Promise<Exit.Exit<A, E>>,
327 options: AtomCommandOptions = {},
328 reporter: AtomCommandReporter = console,
329): Promise<AtomCommandResult<A, E>> {
330 const result = await settleAsyncResult(execute);
331 reportAtomCommandResult(result, options, reporter);
332 return result;
334​
335export interface AtomQueryOptions extends AtomCommandOptions {
336 /**
337 * Force a fresh execution instead of accepting a value the atom already
338 * holds (e.g. an SWR-cached result within its stale window). Used by
339 * verification flows where a cached failure must not satisfy a retry.
340 */
341 readonly refresh?: boolean;
342 /** Interrupt the query wait when its caller no longer wants the result. */
343 readonly signal?: AbortSignal;
345​
346export async function executeAtomQuery<A, E>(
347 registry: AtomRegistry.AtomRegistry,
348 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
349 options: AtomQueryOptions = {},
350 reporter: AtomCommandReporter = console,
351): Promise<AtomCommandResult<A, E>> {
352 const query = Effect.scoped(
353 Effect.gen(function* () {
354 yield* AtomRegistry.mount(registry, atom);
355 if (options.refresh) {
356 yield* Effect.sync(() => {
357 // Only a settled value can be a leftover from an earlier read; a
358 // computation that mounting just started is already fresh.
359 const current = registry.get(atom);
360 if (current._tag !== "Initial" && !current.waiting) {
361 registry.refresh(atom);
362 }
363 });
364 }
365 return yield* AtomRegistry.getResult(registry, atom, {
366 suspendOnWaiting: true,
367 });
368 }),
369 );
370 return executeAtomCommand(
371 () => Effect.runPromiseExit(query, { signal: options.signal }),
372 options,
373 reporter,
374 );
376​
377export function createRuntimeCommand<R, ER, W, A, E>(
378 runtime: Atom.AtomRuntime<R, ER>,
379 options: {
380 readonly label: string;
381 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
382 readonly scheduler?: AtomCommandScheduler;
383 readonly concurrency?: AtomCommandConcurrency<W>;
384 },
385): AtomCommand<W, A, E | ER> {
386 const scheduler = options.scheduler ?? createAtomCommandScheduler();
387 const concurrency = options.concurrency ?? { mode: "parallel" as const };
388 return {
389 label: options.label,
390 run: (registry, input) =>
391 settleAtomCommandResult(() =>
392 scheduler.schedule(registry, concurrency, input, () => {
393 const atom = runtime
394 .atom(options.execute(input, registry))
395 .pipe(Atom.withLabel(options.label));
396 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
397 }),
398 ),
399 };
401​
402export function reportAtomCommandResult(
403 result: AtomCommandResult<unknown, unknown>,
404 options: AtomCommandOptions = {},
405 reporter: AtomCommandReporter = console,
406): void {
407 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
408 return;
409 }
410​
411 const label = options.label ?? "atom command";
412 if (Cause.hasDies(result.cause)) {
413 if (options.reportDefect ?? true) {
414 reporter.error(`[atom-command] ${label} defected`, result.cause);
415 }
416 } else if (options.reportFailure ?? true) {
417 reporter.warn(`[atom-command] ${label} failed`, result.cause);
418 }
420​
421export async function settlePromise<A>(
422 execute: () => Promise<A>,
423): Promise<AtomCommandResult<A, never>> {
424 try {
425 return AsyncResult.success(await execute());
426 } catch (defect) {
427 return AsyncResult.failure(Cause.die(defect));
428 }
430​
431export function environmentRpcKey<Input>(target: {
432 readonly environmentId: EnvironmentIdType;
433 readonly input: Input;
434}): string {
435 return JSON.stringify([target.environmentId, target.input]);
437​
438function parseEnvironmentRpcKey<Input>(key: string): {
439 readonly environmentId: EnvironmentIdType;
440 readonly input: Input;
441} {
442 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
443 return {
444 environmentId: EnvironmentId.make(decoded[0]),
445 input: decoded[1],
446 };
448​
449function runInEnvironment<A, E, R>(
450 environmentId: EnvironmentIdType,
451 effect: Effect.Effect<A, E, R>,
452): Effect.Effect<
453 A,
454 E | EnvironmentRegistry.EnvironmentNotRegisteredError,
455 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
456> {
457 return EnvironmentRegistry.EnvironmentRegistry.pipe(
458 Effect.flatMap((registry) => registry.run(environmentId, effect)),
459 );
461​
462export function runStreamInEnvironment<A, E, R>(
463 environmentId: EnvironmentIdType,
464 stream: Stream.Stream<A, E, R>,
465): Stream.Stream<
466 A,
467 E | EnvironmentRegistry.EnvironmentNotRegisteredError,
468 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
469> {
470 return Stream.unwrap(
471 EnvironmentRegistry.EnvironmentRegistry.pipe(
472 Effect.map((registry) => registry.runStream(environmentId, stream)),
473 ),
474 );
476​
477export function followStreamInEnvironment<A, E, R>(
478 environmentId: EnvironmentIdType,
479 stream: Stream.Stream<A, E, R>,
480): Stream.Stream<
481 A,
482 E,
483 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
484> {
485 return Stream.unwrap(
486 EnvironmentRegistry.EnvironmentRegistry.pipe(
487 Effect.map((registry) => registry.followStream(environmentId, stream)),
488 ),
489 );
491​
492export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
493 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
494 options: EnvironmentQueryAtomOptions<
495 Input,
496 A,
497 E,
498 | EnvironmentSupervisor.EnvironmentSupervisor
499 | EnvironmentRegistry.EnvironmentRegistry
500 | AtomRegistry.AtomRegistry
501 | R
502 >,
503): (target: {
504 readonly environmentId: EnvironmentIdType;
505 readonly input: Input;
506}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
507 const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
508 runtime.atom(
509 followStreamInEnvironment(
510 environmentId,
511 Stream.unwrap(
512 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
513 Effect.map((supervisor) =>
514 SubscriptionRef.changes(supervisor.state).pipe(
515 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
516 ),
517 ),
518 ),
519 ),
520 ),
521 { initialValue: null },
522 ),
523 );
524 const family = Atom.family((key: string) => {
525 const target = parseEnvironmentRpcKey<Input>(key);
526 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
527 const queryAtom = runtime
528 .atom<
529 A,
530 | E
531 | ConnectionAttemptError
532 | EnvironmentRegistry.EnvironmentNotRegisteredError
533 | EnvironmentRpcUnavailableError
534 >((get) => {
535 const connection = Option.getOrNull(
536 AsyncResult.value(get(connectionAtom(target.environmentId))),
537 );
538 if (connection === null) {
539 return Effect.never;
540 }
541 const [connectionState, session] = connection;
542 switch (connectionState.phase) {
543 case "connected":
544 return Option.isSome(session)
545 ? runInEnvironment(target.environmentId, options.execute(target.input))
546 : Effect.never;
547 case "connecting":
548 case "backoff":
549 return Effect.never;
550 case "available":
551 case "offline":
552 case "blocked":
553 if (connectionState.lastFailure !== null) {
554 return Effect.fail(connectionState.lastFailure);
555 }
556 return Effect.fail(
557 new EnvironmentRpcUnavailableError({
558 environmentId: target.environmentId,
559 message: `Environment ${target.environmentId} is ${
560 connectionState.phase === "available" ? "not connected" : connectionState.phase
561 }.`,
562 }),
563 );
564 }
565 })
566 .pipe(
567 Atom.swr({
568 staleTime: options.staleTimeMs ?? 30_000,
569 revalidateOnMount: true,
570 }),
571 Atom.setIdleTTL(idleTtlMs),
572 );
573 const intervalQuery =
574 options.refreshIntervalMs === undefined
575 ? queryAtom
576 : queryAtom.pipe(Atom.withRefresh(options.refreshIntervalMs));
577 const refreshTrigger = options.refreshTrigger?.(target);
578 return (
579 refreshTrigger === undefined
580 ? intervalQuery
581 : intervalQuery.pipe(Atom.makeRefreshOnSignal(refreshTrigger))
582 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
583 });
584 return (target) => family(environmentRpcKey(target));
586​
587export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
588 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
589 options: EnvironmentSubscriptionAtomOptions<
590 Input,
591 A,
592 E,
593 EnvironmentSupervisor.EnvironmentSupervisor | R
594 >,
595) {
596 const family = Atom.family((key: string) => {
597 const target = parseEnvironmentRpcKey<Input>(key);
598 return runtime
599 .atom(followStreamInEnvironment(target.environmentId, options.subscribe(target.input)))
600 .pipe(
601 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
602 Atom.withLabel(
603 options.sensitiveInput
604 ? `${options.label}:${target.environmentId}`
605 : `${options.label}:${key}`,
606 ),
607 );
608 });
609 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
610 family(environmentRpcKey(target));
612​
613export function createEnvironmentCommand<R, ER, Input, A, E>(
614 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
615 options: EnvironmentCommandAtomOptions<
616 Input,
617 A,
618 E,
619 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
620 >,
621) {
622 return createRuntimeCommand(runtime, {
623 label: options.label,
624 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
625 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
626 execute: (target, registry) =>
627 runInEnvironment(
628 target.environmentId,
629 options.execute(target.input, registry, target.environmentId),
630 ),
631 });
633​
634export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(
635 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
636 options: {
637 readonly label: string;
638 readonly tag: TTag;
639 readonly execute?: (
640 input: EnvironmentRpcInput<TTag>,
641 ) => Effect.Effect<
642 EnvironmentRpcSuccess<TTag>,
643 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
644 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
645 >;
646 readonly staleTimeMs?: number;
647 readonly idleTtlMs?: number;
648 readonly refreshIntervalMs?: number;
649 readonly refreshTrigger?: (target: {
650 readonly environmentId: EnvironmentIdType;
651 readonly input: EnvironmentRpcInput<TTag>;
652 }) => Atom.Atom<unknown> | undefined;
653 },
654) {
655 return createEnvironmentQueryAtomFamily(runtime, {
656 label: options.label,
657 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
658 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
659 ...(options.refreshIntervalMs === undefined
660 ? {}
661 : { refreshIntervalMs: options.refreshIntervalMs }),
662 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
663 execute: (input: EnvironmentRpcInput<TTag>) =>
664 options.execute?.(input) ?? request(options.tag, input),
665 });
667​
668export function createEnvironmentRpcSubscriptionAtomFamily<
669 R,
670 ER,
671 TTag extends EnvironmentSubscriptionRpcTag,
672 B = EnvironmentRpcStreamValue<TTag>,
673>(
674 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
675 options: {
676 readonly label: string;
677 readonly tag: TTag;
678 readonly idleTtlMs?: number;
679 readonly transform?: (
680 stream: Stream.Stream<
681 EnvironmentRpcStreamValue<TTag>,
682 EnvironmentRpcStreamFailure<TTag>,
683 EnvironmentSupervisor.EnvironmentSupervisor | R
684 >,
685 ) => Stream.Stream<
686 B,
687 EnvironmentRpcStreamFailure<TTag>,
688 EnvironmentSupervisor.EnvironmentSupervisor | R
689 >;
690 },
691) {
692 return createEnvironmentSubscriptionAtomFamily(runtime, {
693 label: options.label,
694 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
695 subscribe: (input: EnvironmentRpcInput<TTag>) => {
696 const stream = subscribe(options.tag, input);
697 return options.transform === undefined
698 ? (stream as Stream.Stream<
699 B,
700 EnvironmentRpcStreamFailure<TTag>,
701 EnvironmentSupervisor.EnvironmentSupervisor | R
702 >)
703 : options.transform(stream);
704 },
705 });
707​
708export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryRpcTag>(
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 ) => Effect.Effect<
716 EnvironmentRpcSuccess<TTag>,
717 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
718 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
719 >;
720 readonly scheduler?: AtomCommandScheduler;
721 readonly concurrency?: AtomCommandConcurrency<{
722 readonly environmentId: EnvironmentIdType;
723 readonly input: EnvironmentRpcInput<TTag>;
724 }>;
725 readonly onSuccess?: (
726 target: {
727 readonly environmentId: EnvironmentIdType;
728 readonly input: EnvironmentRpcInput<TTag>;
729 },
730 registry: AtomRegistry.AtomRegistry,
731 ) => Effect.Effect<void, never, R>;
732 readonly onSettled?: (
733 target: {
734 readonly environmentId: EnvironmentIdType;
735 readonly input: EnvironmentRpcInput<TTag>;
736 },
737 registry: AtomRegistry.AtomRegistry,
738 ) => Effect.Effect<void, never, R>;
739 },
740) {
741 return createEnvironmentCommand(runtime, {
742 label: options.label,
743 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
744 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
745 execute: (input: EnvironmentRpcInput<TTag>, registry, environmentId) => {
746 const target = {
747 environmentId,
748 input,
749 };
750 return (options.execute?.(input) ?? request(options.tag, input)).pipe(
751 Effect.tap(() => options.onSuccess?.(target, registry) ?? Effect.void),
752 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
753 );
754 },
755 });