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

makeManagedServerProvider.ts

165 lines6.0 KB

1import type { ServerProvider } from "@t3tools/contracts";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Equal from "effect/Equal";
5import * as Fiber from "effect/Fiber";
6import * as PubSub from "effect/PubSub";
7import * as Ref from "effect/Ref";
8import * as Scope from "effect/Scope";
9import * as Stream from "effect/Stream";
10import * as Semaphore from "effect/Semaphore";
11​
12import type { ServerProviderShape } from "./Services/ServerProvider.ts";
13import { ServerSettingsError } from "@t3tools/contracts";
14​
15interface ProviderSnapshotState {
16 readonly snapshot: ServerProvider;
17 readonly enrichmentGeneration: number;
19​
20export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
21 Settings,
22>(input: {
23 readonly maintenanceCapabilities: ServerProviderShape["maintenanceCapabilities"];
24 readonly getSettings: Effect.Effect<Settings>;
25 readonly streamSettings: Stream.Stream<Settings>;
26 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
27 readonly initialSnapshot: (settings: Settings) => Effect.Effect<ServerProvider>;
28 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
29 readonly enrichSnapshot?: (input: {
30 readonly settings: Settings;
31 readonly snapshot: ServerProvider;
32 readonly getSnapshot: Effect.Effect<ServerProvider>;
33 readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
34 }) => Effect.Effect<void>;
35 readonly refreshInterval?: Duration.Input;
36}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
37 const refreshSemaphore = yield* Semaphore.make(1);
38 const changesPubSub = yield* Effect.acquireRelease(
39 PubSub.unbounded<ServerProvider>(),
40 PubSub.shutdown,
41 );
42 const initialSettings = yield* input.getSettings;
43 const initialSnapshot = yield* input.initialSnapshot(initialSettings);
44 const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
45 snapshot: initialSnapshot,
46 enrichmentGeneration: 0,
47 });
48 const settingsRef = yield* Ref.make(initialSettings);
49 const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
50 const scope = yield* Effect.scope;
51​
52 const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
53 generation: number,
54 nextSnapshot: ServerProvider,
55 ) {
56 const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
57 if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
58 return [null, state] as const;
59 }
60 return [
61 nextSnapshot,
62 {
63 ...state,
64 snapshot: nextSnapshot,
65 },
66 ] as const;
67 });
68 if (snapshotToPublish === null) {
69 return;
70 }
71 yield* PubSub.publish(changesPubSub, snapshotToPublish);
72 });
73​
74 const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
75 settings: Settings,
76 snapshot: ServerProvider,
77 generation: number,
78 ) {
79 const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
80 if (previousFiber) {
81 yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
82 }
83​
84 if (!input.enrichSnapshot) {
85 return;
86 }
87​
88 const fiber = yield* input
89 .enrichSnapshot({
90 settings,
91 snapshot,
92 getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
93 publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
94 })
95 .pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
96​
97 yield* Ref.set(enrichmentFiberRef, fiber);
98 });
99​
100 const applySnapshotBase = Effect.fn("applySnapshot")(function* (
101 nextSettings: Settings,
102 options?: { readonly forceRefresh?: boolean },
103 ) {
104 const forceRefresh = options?.forceRefresh === true;
105 const previousSettings = yield* Ref.get(settingsRef);
106 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
107 yield* Ref.set(settingsRef, nextSettings);
108 return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
109 }
110​
111 const nextSnapshot = yield* input.checkProvider;
112 const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
113 const generation = input.enrichSnapshot
114 ? state.enrichmentGeneration + 1
115 : state.enrichmentGeneration;
116 return [
117 generation,
118 {
119 snapshot: nextSnapshot,
120 enrichmentGeneration: generation,
121 },
122 ] as const;
123 });
124 yield* Ref.set(settingsRef, nextSettings);
125 yield* PubSub.publish(changesPubSub, nextSnapshot);
126 yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
127 return nextSnapshot;
128 });
129 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
130 refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
131​
132 const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
133 const nextSettings = yield* input.getSettings;
134 return yield* applySnapshot(nextSettings, { forceRefresh: true });
135 });
136​
137 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
138 Effect.asVoid(applySnapshot(nextSettings)),
139 ).pipe(Effect.forkScoped);
140​
141 yield* Effect.forever(
142 Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
143 Effect.flatMap(() => refreshSnapshot()),
144 Effect.ignoreCause({ log: true }),
145 ),
146 ).pipe(Effect.forkScoped);
147​
148 yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
149 Effect.ignoreCause({ log: true }),
150 Effect.forkScoped,
151 );
152​
153 return {
154 maintenanceCapabilities: input.maintenanceCapabilities,
155 getSnapshot: input.getSettings.pipe(
156 Effect.flatMap(applySnapshot),
157 Effect.tapError(Effect.logError),
158 Effect.orDie,
159 ),
160 refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
161 get streamChanges() {
162 return Stream.fromPubSub(changesPubSub);
163 },
164 } satisfies ServerProviderShape;
165});