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

DesktopIpc.ts

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