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

runtime.ts

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