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