Open History to see the last commit
1import {
2 WsPush,
3 type WsPushChannel,
4 type WsPushData,
5 type WsPushEnvelopeBase,
6} from "@t3tools/contracts";
7import { Deferred, Effect, Queue, Ref, Schema } from "effect";
8import type { Scope } from "effect";
9import type { WebSocket } from "ws";
10
11type PushTarget =
12 | { readonly kind: "all" }
13 | { readonly kind: "client"; readonly client: WebSocket };
14
15interface PushJob<C extends WsPushChannel = WsPushChannel> {
16 readonly channel: C;
17 readonly data: WsPushData<C>;
18 readonly target: PushTarget;
19 readonly delivered: Deferred.Deferred<boolean> | null;
20}
21
22export interface ServerPushBus {
23 readonly publishAll: <C extends WsPushChannel>(
24 channel: C,
25 data: WsPushData<C>,
26 ) => Effect.Effect<void>;
27 readonly publishClient: <C extends WsPushChannel>(
28 client: WebSocket,
29 channel: C,
30 data: WsPushData<C>,
31 ) => Effect.Effect<boolean>;
32}
33
34export const makeServerPushBus = (input: {
35 readonly clients: Ref.Ref<Set<WebSocket>>;
36 readonly logOutgoingPush: (push: WsPushEnvelopeBase, recipients: number) => void;
37}): Effect.Effect<ServerPushBus, never, Scope.Scope> =>
38 Effect.gen(function* () {
39 const nextSequence = yield* Ref.make(0);
40 const queue = yield* Queue.unbounded<PushJob>();
41 const encodePush = Schema.encodeUnknownEffect(Schema.fromJsonString(WsPush));
42
43 const settleDelivery = (job: PushJob, delivered: boolean) =>
44 job.delivered === null
45 ? Effect.void
46 : Deferred.succeed(job.delivered, delivered).pipe(Effect.orDie);
47
48 const send = Effect.fnUntraced(function* (job: PushJob) {
49 const sequence = yield* Ref.updateAndGet(nextSequence, (current) => current + 1);
50 const push: WsPushEnvelopeBase = {
51 type: "push",
52 sequence,
53 channel: job.channel,
54 data: job.data,
55 };
56 const recipients =
57 job.target.kind === "all" ? yield* Ref.get(input.clients) : new Set([job.target.client]);
58
59 return yield* encodePush(push).pipe(
60 Effect.map((message) => {
61 let recipientCount = 0;
62 for (const client of recipients) {
63 if (client.readyState !== client.OPEN) {
64 continue;
65 }
66 client.send(message);
67 recipientCount += 1;
68 }
69
70 input.logOutgoingPush(push, recipientCount);
71 return recipientCount > 0;
72 }),
73 );
74 });
75
76 yield* Effect.forkScoped(
77 Effect.forever(
78 Queue.take(queue).pipe(
79 Effect.flatMap((job) =>
80 send(job).pipe(
81 Effect.tap((delivered) => settleDelivery(job, delivered)),
82 Effect.tapCause(() => settleDelivery(job, false)),
83 Effect.ignoreCause({ log: true }),
84 ),
85 ),
86 ),
87 ),
88 );
89
90 const publish =
91 (target: PushTarget) =>
92 <C extends WsPushChannel>(channel: C, data: WsPushData<C>) =>
93 Queue.offer(queue, {
94 channel,
95 data,
96 target,
97 delivered: null,
98 }).pipe(Effect.asVoid);
99
100 return {
101 publishAll: publish({ kind: "all" }),
102 publishClient: (client, channel, data) =>
103 Effect.gen(function* () {
104 const delivered = yield* Deferred.make<boolean>();
105 yield* Queue.offer(queue, {
106 channel,
107 data,
108 target: { kind: "client", client },
109 delivered,
110 }).pipe(Effect.asVoid);
111 return yield* Deferred.await(delivered);
112 }),
113 } satisfies ServerPushBus;
114 });