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

DesktopIpc.ts

274 lines7.6 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Schema from "effect/Schema";
5import * as Scope from "effect/Scope";
6​
7export interface DesktopIpcInvokeEvent {
8 readonly sender: { readonly id: number };
9}
10​
11export interface DesktopIpcSyncEvent {
12 returnValue: unknown;
14​
15export type DesktopIpcHandleListener = (
16 event: DesktopIpcInvokeEvent,
17 raw: unknown,
18) => unknown | Promise<unknown>;
19​
20export type DesktopIpcSyncListener = (event: DesktopIpcSyncEvent) => void;
21​
22export interface DesktopIpcMain {
23 removeHandler(channel: string): void;
24 handle(channel: string, listener: DesktopIpcHandleListener): void;
25 removeAllListeners(channel: string): void;
26 on(channel: string, listener: DesktopIpcSyncListener): void;
28​
29export class DesktopIpcRegistrationError extends Schema.TaggedError<DesktopIpcRegistrationError>()(
30 "DesktopIpcRegistrationError",
31 {
32 handlerKind: Schema.Literals(["invoke", "sync"]),
33 channel: Schema.String,
34 cause: Schema.Defect(),
35 },
36) {
37 override get message(): string {
38 return `Failed to register the ${this.handlerKind} IPC handler for ${this.channel}.`;
39 }
41​
42export class DesktopIpcUnregistrationError extends Schema.TaggedError<DesktopIpcUnregistrationError>()(
43 "DesktopIpcUnregistrationError",
44 {
45 handlerKind: Schema.Literals(["invoke", "sync"]),
46 channel: Schema.String,
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 return `Failed to unregister the ${this.handlerKind} IPC handler for ${this.channel}.`;
52 }
54​
55export const DesktopIpcError = Schema.Union([
56 DesktopIpcRegistrationError,
57 DesktopIpcUnregistrationError,
58]);
59export type DesktopIpcError = typeof DesktopIpcError.Type;
60​
61export interface DesktopIpcMethod<E, R> {
62 readonly channel: string;
63 readonly handler: (raw: unknown, event?: DesktopIpcInvokeEvent) => Effect.Effect<unknown, E, R>;
65​
66export interface DesktopSyncIpcMethod<E, R> {
67 readonly channel: string;
68 readonly handler: () => Effect.Effect<unknown, E, R>;
70​
71export class DesktopIpc extends Context.Service<
72 DesktopIpc,
73 {
74 readonly handle: <E, R>(
75 input: DesktopIpcMethod<E, R>,
76 ) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
77 readonly handleSync: <E, R>(
78 input: DesktopSyncIpcMethod<E, R>,
79 ) => Effect.Effect<void, DesktopIpcRegistrationError, R | Scope.Scope>;
80 }
81>()("@t3tools/desktop/ipc/DesktopIpc") {}
82​
83export const make = (ipcMain: DesktopIpcMain): DesktopIpc["Service"] =>
84 DesktopIpc.of({
85 handle: Effect.fn("desktop.ipc.registerInvoke")(function* <E, R>({
86 channel,
87 handler,
88 }: DesktopIpcMethod<E, R>) {
89 yield* Effect.annotateCurrentSpan({ channel });
90 const context = yield* Effect.context<R>();
91 const runPromise = Effect.runPromiseWith(context);
92​
93 yield* Effect.acquireRelease(
94 Effect.try({
95 try: () => {
96 ipcMain.removeHandler(channel);
97 ipcMain.handle(channel, (event, raw) =>
98 runPromise(
99 Effect.gen(function* () {
100 yield* Effect.annotateCurrentSpan({ channel });
101 return yield* handler(raw, event);
102 }).pipe(Effect.annotateLogs({ channel }), Effect.withSpan("desktop.ipc.invoke")),
103 ),
104 );
105 },
106 catch: (cause) =>
107 new DesktopIpcRegistrationError({ handlerKind: "invoke", channel, cause }),
108 }),
109 () =>
110 Effect.try({
111 try: () => ipcMain.removeHandler(channel),
112 catch: (cause) =>
113 new DesktopIpcUnregistrationError({ handlerKind: "invoke", channel, cause }),
114 }).pipe(Effect.orDie),
115 );
116 }),
117​
118 handleSync: Effect.fn("desktop.ipc.registerSync")(function* <E, R>({
119 channel,
120 handler,
121 }: DesktopSyncIpcMethod<E, R>) {
122 yield* Effect.annotateCurrentSpan({ channel });
123 const context = yield* Effect.context<R>();
124 const runSync = Effect.runSyncWith(context);
125​
126 yield* Effect.acquireRelease(
127 Effect.try({
128 try: () => {
129 ipcMain.removeAllListeners(channel);
130 ipcMain.on(channel, (event) => {
131 event.returnValue = runSync(
132 Effect.gen(function* () {
133 yield* Effect.annotateCurrentSpan({ channel });
134 return yield* handler();
135 }).pipe(
136 Effect.annotateLogs({ channel }),
137 Effect.withSpan("desktop.ipc.invokeSync"),
138 ),
139 );
140 });
141 },
142 catch: (cause) =>
143 new DesktopIpcRegistrationError({ handlerKind: "sync", channel, cause }),
144 }),
145 () =>
146 Effect.try({
147 try: () => ipcMain.removeAllListeners(channel),
148 catch: (cause) =>
149 new DesktopIpcUnregistrationError({ handlerKind: "sync", channel, cause }),
150 }).pipe(Effect.orDie),
151 );
152 }),
153 });
154​
155export const layer = (ipcMain: DesktopIpcMain) => Layer.succeed(DesktopIpc, make(ipcMain));
156​
157export interface DesktopIpcMethodRegistration<
158 Payload,
159 EncodedPayload,
160 Result,
161 EncodedResult,
162 E,
163 R,
164 PayloadDecodingServices = never,
165 PayloadEncodingServices = never,
166 ResultDecodingServices = never,
167 ResultEncodingServices = never,
168> {
169 readonly channel: string;
170 readonly payload: Schema.Codec<
171 Payload,
172 EncodedPayload,
173 PayloadDecodingServices,
174 PayloadEncodingServices
175 >;
176 readonly result: Schema.Codec<
177 Result,
178 EncodedResult,
179 ResultDecodingServices,
180 ResultEncodingServices
181 >;
182 readonly handler: (input: Payload, event?: DesktopIpcInvokeEvent) => Effect.Effect<Result, E, R>;
184​
185export const makeIpcMethod = <
186 Payload,
187 EncodedPayload,
188 Result,
189 EncodedResult,
190 E,
191 R,
192 PayloadDecodingServices = never,
193 PayloadEncodingServices = never,
194 ResultDecodingServices = never,
195 ResultEncodingServices = never,
196>(
197 method: DesktopIpcMethodRegistration<
198 Payload,
199 EncodedPayload,
200 Result,
201 EncodedResult,
202 E,
203 R,
204 PayloadDecodingServices,
205 PayloadEncodingServices,
206 ResultDecodingServices,
207 ResultEncodingServices
208 >,
209): DesktopIpcMethod<
210 E | Schema.SchemaError,
211 R | PayloadDecodingServices | ResultEncodingServices
212> => {
213 const decode = Schema.decodeUnknownEffect(method.payload);
214 const encode = Schema.encodeUnknownEffect(method.result);
215​
216 return {
217 channel: method.channel,
218 handler: (raw, event) =>
219 decode(raw).pipe(
220 Effect.flatMap((input) => method.handler(input, event)),
221 Effect.flatMap(encode),
222 Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
223 ),
224 };
225};
226​
227export interface DesktopSyncIpcMethodRegistration<
228 Result,
229 EncodedResult,
230 E,
231 R,
232 ResultDecodingServices = never,
233 ResultEncodingServices = never,
234> {
235 readonly channel: string;
236 readonly result: Schema.Codec<
237 Result,
238 EncodedResult,
239 ResultDecodingServices,
240 ResultEncodingServices
241 >;
242 readonly handler: () => Effect.Effect<Result, E, R>;
244​
245export const makeSyncIpcMethod = <
246 Result,
247 EncodedResult,
248 E,
249 R,
250 ResultDecodingServices = never,
251 ResultEncodingServices = never,
252>(
253 method: DesktopSyncIpcMethodRegistration<
254 Result,
255 EncodedResult,
256 E,
257 R,
258 ResultDecodingServices,
259 ResultEncodingServices
260 >,
261): DesktopSyncIpcMethod<E | Schema.SchemaError, R | ResultEncodingServices> => {
262 const encode = Schema.encodeUnknownEffect(method.result);
263​
264 return {
265 channel: method.channel,
266 handler: () =>
267 method
268 .handler()
269 .pipe(
270 Effect.flatMap(encode),
271 Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
272 ),
273 };
274};