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