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 readonly sender: { readonly id: number };
9}
10
11export interface DesktopIpcSyncEvent {
12 returnValue: unknown;
13}
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;
27}
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 }
40}
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 }
53}
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>;
64}
65
66export interface DesktopSyncIpcMethod<E, R> {
67 readonly channel: string;
68 readonly handler: () => Effect.Effect<unknown, E, R>;
69}
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
157/**
158 * Convenience helpers for creating IPC methods
159 */
160
161export interface DesktopIpcMethodRegistration<
162 Payload,
163 EncodedPayload,
164 Result,
165 EncodedResult,
166 E,
167 R,
168 PayloadDecodingServices = never,
169 PayloadEncodingServices = never,
170 ResultDecodingServices = never,
171 ResultEncodingServices = never,
172> {
173 readonly channel: string;
174 readonly payload: Schema.Codec<
175 Payload,
176 EncodedPayload,
177 PayloadDecodingServices,
178 PayloadEncodingServices
179 >;
180 readonly result: Schema.Codec<
181 Result,
182 EncodedResult,
183 ResultDecodingServices,
184 ResultEncodingServices
185 >;
186 readonly handler: (input: Payload, event?: DesktopIpcInvokeEvent) => Effect.Effect<Result, E, R>;
187}
188
189export const makeIpcMethod = <
190 Payload,
191 EncodedPayload,
192 Result,
193 EncodedResult,
194 E,
195 R,
196 PayloadDecodingServices = never,
197 PayloadEncodingServices = never,
198 ResultDecodingServices = never,
199 ResultEncodingServices = never,
200>(
201 method: DesktopIpcMethodRegistration<
202 Payload,
203 EncodedPayload,
204 Result,
205 EncodedResult,
206 E,
207 R,
208 PayloadDecodingServices,
209 PayloadEncodingServices,
210 ResultDecodingServices,
211 ResultEncodingServices
212 >,
213): DesktopIpcMethod<
214 E | Schema.SchemaError,
215 R | PayloadDecodingServices | ResultEncodingServices
216> => {
217 const decode = Schema.decodeUnknownEffect(method.payload);
218 const encode = Schema.encodeUnknownEffect(method.result);
219
220 return {
221 channel: method.channel,
222 handler: (raw, event) =>
223 decode(raw).pipe(
224 Effect.flatMap((input) => method.handler(input, event)),
225 Effect.flatMap(encode),
226 Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
227 ),
228 };
229};
230
231export interface DesktopSyncIpcMethodRegistration<
232 Result,
233 EncodedResult,
234 E,
235 R,
236 ResultDecodingServices = never,
237 ResultEncodingServices = never,
238> {
239 readonly channel: string;
240 readonly result: Schema.Codec<
241 Result,
242 EncodedResult,
243 ResultDecodingServices,
244 ResultEncodingServices
245 >;
246 readonly handler: () => Effect.Effect<Result, E, R>;
247}
248
249export const makeSyncIpcMethod = <
250 Result,
251 EncodedResult,
252 E,
253 R,
254 ResultDecodingServices = never,
255 ResultEncodingServices = never,
256>(
257 method: DesktopSyncIpcMethodRegistration<
258 Result,
259 EncodedResult,
260 E,
261 R,
262 ResultDecodingServices,
263 ResultEncodingServices
264 >,
265): DesktopSyncIpcMethod<E | Schema.SchemaError, R | ResultEncodingServices> => {
266 const encode = Schema.encodeUnknownEffect(method.result);
267
268 return {
269 channel: method.channel,
270 handler: () =>
271 method
272 .handler()
273 .pipe(
274 Effect.flatMap(encode),
275 Effect.withSpan("desktop.ipc.method", { attributes: { channel: method.channel } }),
276 ),
277 };
278};