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

makeManagedServerProvider.ts

158 lines5.7 KB

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