Open History to see the last commit
1import type { ServerProvider } from "@t3tools/contracts";
2import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
3import * as Semaphore from "effect/Semaphore";
4
5import type { ServerProviderShape } from "./Services/ServerProvider";
6import { ServerSettingsError } from "../serverSettings";
7
8export function makeManagedServerProvider<Settings>(input: {
9 readonly getSettings: Effect.Effect<Settings>;
10 readonly streamSettings: Stream.Stream<Settings>;
11 readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
12 readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
13 readonly refreshInterval?: Duration.Input;
14}): Effect.Effect<ServerProviderShape, ServerSettingsError, Scope.Scope> {
15 return Effect.gen(function* () {
16 const refreshSemaphore = yield* Semaphore.make(1);
17 const changesPubSub = yield* Effect.acquireRelease(
18 PubSub.unbounded<ServerProvider>(),
19 PubSub.shutdown,
20 );
21 const initialSettings = yield* input.getSettings;
22 const initialSnapshot = yield* input.checkProvider;
23 const snapshotRef = yield* Ref.make(initialSnapshot);
24 const settingsRef = yield* Ref.make(initialSettings);
25
26 const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
27 refreshSemaphore.withPermits(1)(
28 Effect.gen(function* () {
29 const forceRefresh = options?.forceRefresh === true;
30 const previousSettings = yield* Ref.get(settingsRef);
31 if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
32 yield* Ref.set(settingsRef, nextSettings);
33 return yield* Ref.get(snapshotRef);
34 }
35
36 const nextSnapshot = yield* input.checkProvider;
37 yield* Ref.set(settingsRef, nextSettings);
38 yield* Ref.set(snapshotRef, nextSnapshot);
39 yield* PubSub.publish(changesPubSub, nextSnapshot);
40 return nextSnapshot;
41 }),
42 );
43
44 const refreshSnapshot = Effect.gen(function* () {
45 const nextSettings = yield* input.getSettings;
46 return yield* applySnapshot(nextSettings, { forceRefresh: true });
47 });
48
49 yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
50 Effect.asVoid(applySnapshot(nextSettings)),
51 ).pipe(Effect.forkScoped);
52
53 yield* Effect.forever(
54 Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
55 Effect.flatMap(() => refreshSnapshot),
56 Effect.ignoreCause({ log: true }),
57 ),
58 ).pipe(Effect.forkScoped);
59
60 return {
61 getSnapshot: input.getSettings.pipe(
62 Effect.flatMap(applySnapshot),
63 Effect.tapError(Effect.logError),
64 Effect.orDie,
65 ),
66 refresh: refreshSnapshot.pipe(Effect.tapError(Effect.logError), Effect.orDie),
67 get streamChanges() {
68 return Stream.fromPubSub(changesPubSub);
69 },
70 } satisfies ServerProviderShape;
71 });
72}