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

runtime.ts

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