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

runtime.ts

651 lines21.3 KB

1import { EnvironmentId, type EnvironmentId as EnvironmentIdType } from "@v12/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 Result from "effect/Result";
7import * as Stream from "effect/Stream";
8import * as SubscriptionRef from "effect/SubscriptionRef";
9import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
10​
11import { EnvironmentNotRegisteredError, EnvironmentRegistry } from "../connection/registry.ts";
12import {
13 type EnvironmentRpcInput,
14 type EnvironmentRpcStreamFailure,
15 type EnvironmentRpcStreamValue,
16 type EnvironmentStreamCommandRpcTag,
17 type EnvironmentSubscriptionRpcTag,
18 type EnvironmentUnaryRpcTag,
19 request,
20 runStream,
21 subscribe,
22} from "../rpc/client.ts";
23import { EnvironmentSupervisor } from "../connection/supervisor.ts";
24​
25interface EnvironmentAtomOptions<Input, A, E, R> {
26 readonly label: string;
27 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
28 readonly scheduler?: AtomCommandScheduler;
29 readonly concurrency?: AtomCommandConcurrency<{
30 readonly environmentId: EnvironmentIdType;
31 readonly input: Input;
32 }>;
34​
35interface EnvironmentQueryAtomOptions<Input, A, E, R> extends EnvironmentAtomOptions<
36 Input,
37 A,
38 E,
39 R
40> {
41 readonly staleTimeMs?: number;
42 readonly idleTtlMs?: number;
43 readonly refreshIntervalMs?: number;
45​
46interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
47 readonly label: string;
48 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
49 readonly idleTtlMs?: number;
51​
52export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
53​
54export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
55​
56export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
57​
58export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
59​
60export interface AtomCommandOptions {
61 readonly label?: string;
62 readonly reportFailure?: boolean;
63 readonly reportDefect?: boolean;
65​
66export interface AtomCommandReporter {
67 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
68 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
70​
71export interface AtomCommand<W, A, E> {
72 readonly label: string;
73 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
75​
76export type AtomCommandConcurrency<W> =
77 /** Every invocation runs independently. */
78 | { readonly mode: "parallel" }
79 | {
80 /**
81 * `serial` preserves every invocation in FIFO order, `singleFlight` shares an active
82 * invocation, and `latest` coalesces queued invocations to the newest input.
83 */
84 readonly mode: "serial" | "singleFlight" | "latest";
85 readonly key: (input: W) => string;
86 };
87​
88interface AtomCommandSchedulerState {
89 readonly serial: Map<string, Promise<unknown>>;
90 readonly singleFlight: Map<string, Promise<unknown>>;
91 readonly latest: Map<string, AtomCommandLatestLane>;
93​
94interface AtomCommandLatestBatch {
95 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
96 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
98​
99interface AtomCommandLatestLane {
100 running: boolean;
101 pending: AtomCommandLatestBatch | undefined;
103​
104export interface AtomCommandScheduler {
105 readonly schedule: <W, A, E>(
106 registry: AtomRegistry.AtomRegistry,
107 concurrency: AtomCommandConcurrency<W>,
108 input: W,
109 execute: () => Promise<AtomCommandResult<A, E>>,
110 ) => Promise<AtomCommandResult<A, E>>;
112​
113async function settleAtomCommandResult<A, E>(
114 execute: () => Promise<AtomCommandResult<A, E>>,
115): Promise<AtomCommandResult<A, E>> {
116 try {
117 return await execute();
118 } catch (defect) {
119 return AsyncResult.failure(Cause.die(defect));
120 }
122​
123export function createAtomCommandScheduler(): AtomCommandScheduler {
124 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
125​
126 const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
127 const existing = registryStates.get(registry);
128 if (existing !== undefined) {
129 return existing;
130 }
131 const state: AtomCommandSchedulerState = {
132 serial: new Map(),
133 singleFlight: new Map(),
134 latest: new Map(),
135 };
136 registryStates.set(registry, state);
137 return state;
138 };
139​
140 return {
141 schedule: <W, A, E>(
142 registry: AtomRegistry.AtomRegistry,
143 concurrency: AtomCommandConcurrency<W>,
144 input: W,
145 execute: () => Promise<AtomCommandResult<A, E>>,
146 ): Promise<AtomCommandResult<A, E>> => {
147 if (concurrency.mode === "parallel") {
148 return execute();
149 }
150​
151 const key = concurrency.key(input);
152 const state = stateFor(registry);
153 if (concurrency.mode === "singleFlight") {
154 const existing = state.singleFlight.get(key) as
155 | Promise<AtomCommandResult<A, E>>
156 | undefined;
157 if (existing !== undefined) {
158 return existing;
159 }
160 const current = execute();
161 state.singleFlight.set(key, current);
162 void current.then(
163 () => {
164 if (state.singleFlight.get(key) === current) {
165 state.singleFlight.delete(key);
166 }
167 },
168 () => {
169 if (state.singleFlight.get(key) === current) {
170 state.singleFlight.delete(key);
171 }
172 },
173 );
174 return current;
175 }
176​
177 if (concurrency.mode === "serial") {
178 const previous = state.serial.get(key);
179 const current = previous === undefined ? execute() : previous.then(execute, execute);
180 state.serial.set(key, current);
181 void current.then(
182 () => {
183 if (state.serial.get(key) === current) {
184 state.serial.delete(key);
185 }
186 },
187 () => {
188 if (state.serial.get(key) === current) {
189 state.serial.delete(key);
190 }
191 },
192 );
193 return current;
194 }
195​
196 let lane = state.latest.get(key);
197 if (lane === undefined) {
198 lane = { running: false, pending: undefined };
199 state.latest.set(key, lane);
200 }
201 const activeLane = lane;
202​
203 const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
204 if (activeLane.pending === undefined) {
205 activeLane.pending = {
206 execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
207 resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
208 };
209 return;
210 }
211 activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
212 activeLane.pending.resolve.push(
213 resolve as (result: AtomCommandResult<unknown, unknown>) => void,
214 );
215 });
216​
217 if (!activeLane.running) {
218 activeLane.running = true;
219 void (async () => {
220 while (activeLane.pending !== undefined) {
221 const batch = activeLane.pending;
222 activeLane.pending = undefined;
223 let batchResult: AtomCommandResult<unknown, unknown>;
224 try {
225 batchResult = await batch.execute();
226 } catch (defect) {
227 batchResult = AsyncResult.failure(Cause.die(defect));
228 }
229 for (const resolve of batch.resolve) {
230 resolve(batchResult);
231 }
232 }
233 activeLane.running = false;
234 if (state.latest.get(key) === activeLane) {
235 state.latest.delete(key);
236 }
237 })();
238 }
239​
240 return result;
241 },
242 };
244​
245export async function runAtomCommand<W, A, E>(
246 registry: AtomRegistry.AtomRegistry,
247 command: AtomCommand<W, A, E>,
248 input: W,
249 options: AtomCommandOptions = {},
250 reporter: AtomCommandReporter = console,
251): Promise<AtomCommandResult<A, E>> {
252 const result = await settleAtomCommandResult(() => command.run(registry, input));
253 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
254 return result;
256​
257export function mapAtomCommandResult<A, E, B>(
258 result: AtomCommandResult<A, E>,
259 map: (value: A) => B,
260): AtomCommandResult<B, E> {
261 return result._tag === "Success"
262 ? AsyncResult.success(map(result.value))
263 : AsyncResult.failure(result.cause);
265​
266export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
267 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
269​
270export function squashAtomCommandFailure(result: {
271 readonly cause: Cause.Cause<unknown>;
272}): unknown {
273 return Cause.squash(result.cause);
275​
276export async function settleAsyncResult<A, E>(
277 execute: () => Promise<Exit.Exit<A, E>>,
278): Promise<SettledAsyncResult<A, E>> {
279 try {
280 return AsyncResult.fromExit(await execute());
281 } catch (defect) {
282 return AsyncResult.failure(Cause.die(defect));
283 }
285​
286export async function executeAtomCommand<A, E>(
287 execute: () => Promise<Exit.Exit<A, E>>,
288 options: AtomCommandOptions = {},
289 reporter: AtomCommandReporter = console,
290): Promise<AtomCommandResult<A, E>> {
291 const result = await settleAsyncResult(execute);
292 reportAtomCommandResult(result, options, reporter);
293 return result;
295​
296export async function executeAtomQuery<A, E>(
297 registry: AtomRegistry.AtomRegistry,
298 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
299 options: AtomCommandOptions = {},
300 reporter: AtomCommandReporter = console,
301): Promise<AtomCommandResult<A, E>> {
302 const query = Effect.scoped(
303 Effect.gen(function* () {
304 yield* AtomRegistry.mount(registry, atom);
305 return yield* AtomRegistry.getResult(registry, atom, {
306 suspendOnWaiting: true,
307 });
308 }),
309 );
310 return executeAtomCommand(() => Effect.runPromiseExit(query), options, reporter);
312​
313export function createRuntimeCommand<R, ER, W, A, E>(
314 runtime: Atom.AtomRuntime<R, ER>,
315 options: {
316 readonly label: string;
317 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
318 readonly scheduler?: AtomCommandScheduler;
319 readonly concurrency?: AtomCommandConcurrency<W>;
320 },
321): AtomCommand<W, A, E | ER> {
322 const scheduler = options.scheduler ?? createAtomCommandScheduler();
323 const concurrency = options.concurrency ?? { mode: "parallel" as const };
324 return {
325 label: options.label,
326 run: (registry, input) =>
327 settleAtomCommandResult(() =>
328 scheduler.schedule(registry, concurrency, input, () => {
329 const atom = runtime
330 .atom(options.execute(input, registry))
331 .pipe(Atom.withLabel(options.label));
332 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
333 }),
334 ),
335 };
337​
338export function createRuntimeStreamCommand<R, ER, W, A, E>(
339 runtime: Atom.AtomRuntime<R, ER>,
340 options: {
341 readonly label: string;
342 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Stream.Stream<A, E, R>;
343 readonly scheduler?: AtomCommandScheduler;
344 readonly concurrency?: AtomCommandConcurrency<W>;
345 },
346): AtomCommand<W, A, E | ER | Cause.NoSuchElementError> {
347 const scheduler = options.scheduler ?? createAtomCommandScheduler();
348 const concurrency = options.concurrency ?? { mode: "parallel" as const };
349 return {
350 label: options.label,
351 run: (registry, input) =>
352 settleAtomCommandResult(() =>
353 scheduler.schedule(registry, concurrency, input, () => {
354 const atom = runtime
355 .atom(options.execute(input, registry))
356 .pipe(Atom.withLabel(options.label));
357 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
358 }),
359 ),
360 };
362​
363export function reportAtomCommandResult(
364 result: AtomCommandResult<unknown, unknown>,
365 options: AtomCommandOptions = {},
366 reporter: AtomCommandReporter = console,
367): void {
368 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
369 return;
370 }
371​
372 const label = options.label ?? "atom command";
373 if (Cause.hasDies(result.cause)) {
374 if (options.reportDefect ?? true) {
375 reporter.error(`[atom-command] ${label} defected`, result.cause);
376 }
377 } else if (options.reportFailure ?? true) {
378 reporter.warn(`[atom-command] ${label} failed`, result.cause);
379 }
381​
382export async function settlePromise<A>(
383 execute: () => Promise<A>,
384): Promise<AtomCommandResult<A, never>> {
385 try {
386 return AsyncResult.success(await execute());
387 } catch (defect) {
388 return AsyncResult.failure(Cause.die(defect));
389 }
391​
392export function environmentRpcKey<Input>(target: {
393 readonly environmentId: EnvironmentIdType;
394 readonly input: Input;
395}): string {
396 return JSON.stringify([target.environmentId, target.input]);
398​
399function parseEnvironmentRpcKey<Input>(key: string): {
400 readonly environmentId: EnvironmentIdType;
401 readonly input: Input;
402} {
403 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
404 return {
405 environmentId: EnvironmentId.make(decoded[0]),
406 input: decoded[1],
407 };
409​
410export function runInEnvironment<A, E, R>(
411 environmentId: EnvironmentIdType,
412 effect: Effect.Effect<A, E, R>,
413): Effect.Effect<
414 A,
415 E | EnvironmentNotRegisteredError,
416 EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>
417> {
418 return EnvironmentRegistry.pipe(
419 Effect.flatMap((registry) => registry.run(environmentId, effect)),
420 );
422​
423export function runStreamInEnvironment<A, E, R>(
424 environmentId: EnvironmentIdType,
425 stream: Stream.Stream<A, E, R>,
426): Stream.Stream<
427 A,
428 E | EnvironmentNotRegisteredError,
429 EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>
430> {
431 return Stream.unwrap(
432 EnvironmentRegistry.pipe(Effect.map((registry) => registry.runStream(environmentId, stream))),
433 );
435​
436export function followStreamInEnvironment<A, E, R>(
437 environmentId: EnvironmentIdType,
438 stream: Stream.Stream<A, E, R>,
439): Stream.Stream<A, E, EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>> {
440 return Stream.unwrap(
441 EnvironmentRegistry.pipe(
442 Effect.map((registry) => registry.followStream(environmentId, stream)),
443 ),
444 );
446​
447function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
448 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
449 options: EnvironmentQueryAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
450): (target: {
451 readonly environmentId: EnvironmentIdType;
452 readonly input: Input;
453}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
454 const rpcGenerationAtom = Atom.family((environmentId: EnvironmentIdType) =>
455 runtime.atom(
456 followStreamInEnvironment(
457 environmentId,
458 Stream.unwrap(
459 EnvironmentSupervisor.pipe(
460 Effect.map((supervisor) =>
461 SubscriptionRef.changes(supervisor.state).pipe(
462 Stream.filterMap((state) =>
463 state.phase === "connected" ? Result.succeed(state.generation) : Result.failVoid,
464 ),
465 Stream.changes,
466 Stream.map<number, number | null>((generation) => generation),
467 ),
468 ),
469 ),
470 ),
471 ),
472 { initialValue: null },
473 ),
474 );
475 const family = Atom.family((key: string) => {
476 const target = parseEnvironmentRpcKey<Input>(key);
477 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
478 const queryAtom = runtime
479 .atom((get) => {
480 const generation = Option.getOrNull(
481 AsyncResult.value(get(rpcGenerationAtom(target.environmentId))),
482 );
483 if (generation === null) {
484 return Effect.never;
485 }
486 return runInEnvironment(target.environmentId, options.execute(target.input));
487 })
488 .pipe(
489 Atom.swr({
490 staleTime: options.staleTimeMs ?? 30_000,
491 revalidateOnMount: true,
492 }),
493 Atom.setIdleTTL(idleTtlMs),
494 );
495 return (
496 options.refreshIntervalMs === undefined
497 ? queryAtom
498 : queryAtom.pipe(Atom.withRefresh(options.refreshIntervalMs))
499 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
500 });
501 return (target) => family(environmentRpcKey(target));
503​
504export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
505 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
506 options: EnvironmentSubscriptionAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
507) {
508 const family = Atom.family((key: string) => {
509 const target = parseEnvironmentRpcKey<Input>(key);
510 return runtime
511 .atom(followStreamInEnvironment(target.environmentId, options.subscribe(target.input)))
512 .pipe(
513 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
514 Atom.withLabel(`${options.label}:${key}`),
515 );
516 });
517 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
518 family(environmentRpcKey(target));
520​
521export function createEnvironmentCommand<R, ER, Input, A, E>(
522 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
523 options: EnvironmentAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
524) {
525 return createRuntimeCommand(runtime, {
526 label: options.label,
527 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
528 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
529 execute: (target) => runInEnvironment(target.environmentId, options.execute(target.input)),
530 });
532​
533function createEnvironmentStreamCommand<R, ER, Input, A, E>(
534 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
535 options: {
536 readonly label: string;
537 readonly execute: (input: Input) => Stream.Stream<A, E, EnvironmentSupervisor | R>;
538 readonly scheduler?: AtomCommandScheduler;
539 readonly concurrency?: AtomCommandConcurrency<{
540 readonly environmentId: EnvironmentIdType;
541 readonly input: Input;
542 }>;
543 },
544) {
545 return createRuntimeStreamCommand(runtime, {
546 label: options.label,
547 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
548 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
549 execute: (target) =>
550 runStreamInEnvironment(target.environmentId, options.execute(target.input)).pipe(
551 Stream.withSpan(options.label),
552 ),
553 });
555​
556export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(
557 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
558 options: {
559 readonly label: string;
560 readonly tag: TTag;
561 readonly staleTimeMs?: number;
562 readonly idleTtlMs?: number;
563 readonly refreshIntervalMs?: number;
564 },
565) {
566 return createEnvironmentQueryAtomFamily(runtime, {
567 label: options.label,
568 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
569 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
570 ...(options.refreshIntervalMs === undefined
571 ? {}
572 : { refreshIntervalMs: options.refreshIntervalMs }),
573 execute: (input: EnvironmentRpcInput<TTag>) => request(options.tag, input),
574 });
576​
577export function createEnvironmentRpcSubscriptionAtomFamily<
578 R,
579 ER,
580 TTag extends EnvironmentSubscriptionRpcTag,
581 B = EnvironmentRpcStreamValue<TTag>,
582>(
583 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
584 options: {
585 readonly label: string;
586 readonly tag: TTag;
587 readonly idleTtlMs?: number;
588 readonly transform?: (
589 stream: Stream.Stream<
590 EnvironmentRpcStreamValue<TTag>,
591 EnvironmentRpcStreamFailure<TTag>,
592 EnvironmentSupervisor | R
593 >,
594 ) => Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>;
595 },
596) {
597 return createEnvironmentSubscriptionAtomFamily(runtime, {
598 label: options.label,
599 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
600 subscribe: (input: EnvironmentRpcInput<TTag>) => {
601 const stream = subscribe(options.tag, input);
602 return options.transform === undefined
603 ? (stream as Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>)
604 : options.transform(stream);
605 },
606 });
608​
609export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryRpcTag>(
610 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
611 options: {
612 readonly label: string;
613 readonly tag: TTag;
614 readonly scheduler?: AtomCommandScheduler;
615 readonly concurrency?: AtomCommandConcurrency<{
616 readonly environmentId: EnvironmentIdType;
617 readonly input: EnvironmentRpcInput<TTag>;
618 }>;
619 },
620) {
621 return createEnvironmentCommand(runtime, {
622 label: options.label,
623 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
624 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
625 execute: (input: EnvironmentRpcInput<TTag>) => request(options.tag, input),
626 });
628​
629export function createEnvironmentRpcStreamCommand<
630 R,
631 ER,
632 TTag extends EnvironmentStreamCommandRpcTag,
633>(
634 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
635 options: {
636 readonly label: string;
637 readonly tag: TTag;
638 readonly scheduler?: AtomCommandScheduler;
639 readonly concurrency?: AtomCommandConcurrency<{
640 readonly environmentId: EnvironmentIdType;
641 readonly input: EnvironmentRpcInput<TTag>;
642 }>;
643 },
644) {
645 return createEnvironmentStreamCommand(runtime, {
646 label: options.label,
647 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
648 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
649 execute: (input: EnvironmentRpcInput<TTag>) => runStream(options.tag, input),
650 });