@dual-os/sdk 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Runner.ts CHANGED
@@ -1,26 +1,20 @@
1
- import { NodeCrypto, NodeRuntime, NodeServices } from "@effect/platform-node";
1
+ import { NodeCrypto, NodeServices } from "@effect/platform-node";
2
2
 
3
3
  import {
4
- Array,
5
4
  Cause,
6
5
  ConfigProvider,
7
6
  Context,
8
- Deferred,
9
7
  Effect,
10
- Exit,
11
8
  Fiber,
12
- FiberMap,
13
9
  Formatter,
14
10
  Inspectable,
15
11
  Layer,
12
+ ManagedRuntime,
16
13
  Match,
17
- Option,
18
14
  Predicate,
19
15
  Redacted,
20
16
  Schema,
21
17
  Scope,
22
- Stdio,
23
- Stream,
24
18
  String,
25
19
  pipe,
26
20
  } from "effect";
@@ -57,193 +51,150 @@ function initializationError(cause: unknown) {
57
51
  });
58
52
  }
59
53
 
60
- // This executable runs only in the plugin's process, using its own SDK and Effect.
61
- pipe(
62
- Effect.gen(function* () {
63
- const guestServices = yield* Effect.context<
64
- NodeServices.NodeServices | Layer.Success<typeof NodeCrypto.layer>
65
- >();
66
- const scope = yield* Scope.Scope;
67
- const runtimeScope = yield* Scope.fork(scope, "sequential");
68
- const failed = yield* Deferred.make<never, PluginRuntime.PluginExecutionError>();
69
- const invocations = yield* FiberMap.make<
70
- string,
71
- RemoteRuntime.Response,
72
- PluginRuntime.PluginExecutionError
73
- >();
74
- const stdio = yield* Stdio.Stdio;
75
- const args = yield* Schema.decodeUnknownEffect(
76
- Schema.Tuple([
77
- Schema.NonEmptyString,
78
- Schema.NonEmptyString,
79
- Schema.Literals(["inspect", "execute"]),
80
- Schema.NonEmptyString,
81
- ]),
82
- )(yield* stdio.args);
83
- const load = yield* Effect.cached(
84
- Effect.forkIn(
85
- Effect.gen(function* () {
86
- const exports = yield* Schema.decodeUnknownEffect(
87
- Schema.Record(Schema.String, Schema.Unknown),
88
- )(yield* Effect.tryPromise({ try: () => import(args[0]), catch: initializationError }));
89
- const plugin = exports[args[1]];
90
- if (!Plugin.isPlugin(plugin)) {
91
- return yield* PluginRuntime.PluginExecutionError.make({
92
- category: "protocol",
93
- message: "The configured export is not an integration plugin",
54
+ export type Options = typeof Options.Type;
55
+ export const Options = Schema.Struct({
56
+ entrypoint: Schema.NonEmptyString,
57
+ exportName: Schema.NonEmptyString,
58
+ mode: Schema.Literals(["inspect", "execute"]),
59
+ version: Schema.NonEmptyString,
60
+ });
61
+
62
+ // The plugin's own SDK and Effect serve it for the life of the host process.
63
+ const runtime = ManagedRuntime.make(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer));
64
+
65
+ /**
66
+ * Load a plugin export into the calling process. `execute` takes and returns plain JSON; aborting
67
+ * its signal interrupts the invocation and settles the promise once its finalizers have run.
68
+ */
69
+ export function load(input: Options) {
70
+ return runtime.runPromise(
71
+ Effect.gen(function* () {
72
+ const options = yield* Schema.decodeUnknownEffect(Options)(input);
73
+ const guestServices = yield* Effect.context<
74
+ NodeServices.NodeServices | Layer.Success<typeof NodeCrypto.layer>
75
+ >();
76
+ const scope = yield* Scope.make("sequential");
77
+ const loaded = yield* Effect.cached(
78
+ Effect.forkIn(
79
+ Effect.gen(function* () {
80
+ const exports = yield* Schema.decodeUnknownEffect(
81
+ Schema.Record(Schema.String, Schema.Unknown),
82
+ )(
83
+ yield* Effect.tryPromise({
84
+ try: () => import(options.entrypoint),
85
+ catch: initializationError,
86
+ }),
87
+ );
88
+ const plugin = exports[options.exportName];
89
+ if (!Plugin.isPlugin(plugin)) {
90
+ return yield* PluginRuntime.PluginExecutionError.make({
91
+ category: "protocol",
92
+ message: "The configured export is not an integration plugin",
93
+ });
94
+ }
95
+ yield* Effect.try({
96
+ try: () => Plugin.make(plugin.identifier),
97
+ catch: initializationError,
94
98
  });
95
- }
96
- yield* Effect.try({
97
- try: () => Plugin.make(plugin.identifier),
98
- catch: initializationError,
99
- });
100
- const runtime = yield* Effect.cached(
101
- Effect.forkIn(
102
- pipe(
103
- Layer.buildWithScope(
104
- pipe(
105
- // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- Imported plugin requirements are erased; the guest supplies only its own services.
106
- DualRuntime.toLayer(DualRuntime.fromPlugin(plugin, args[3])),
107
- Layer.provideMerge(
108
- Layer.mergeAll(
109
- RemoteRuntime.filesUnavailable,
110
- FetchHttpClient.layer,
111
- guestOAuth,
99
+ const services = yield* Effect.cached(
100
+ Effect.forkIn(
101
+ pipe(
102
+ Layer.buildWithScope(
103
+ pipe(
104
+ // @effect-diagnostics-next-line anyUnknownInErrorContext:off -- Imported plugin requirements are erased; the guest supplies only its own services.
105
+ DualRuntime.toLayer(DualRuntime.fromPlugin(plugin, options.version)),
106
+ Layer.provideMerge(
107
+ Layer.mergeAll(
108
+ RemoteRuntime.filesUnavailable,
109
+ FetchHttpClient.layer,
110
+ guestOAuth,
111
+ ),
112
112
  ),
113
113
  ),
114
+ scope,
114
115
  ),
115
- runtimeScope,
116
+ Effect.provideContext(Context.makeUnsafe<unknown>(guestServices.mapUnsafe)),
116
117
  ),
117
- Effect.provideContext(Context.makeUnsafe<unknown>(guestServices.mapUnsafe)),
118
+ scope,
118
119
  ),
119
- runtimeScope,
120
- ),
121
- );
122
- return { plugin, runtime };
123
- }),
124
- runtimeScope,
125
- ),
126
- );
127
- const execute = Effect.fnUntraced(function* (request: PluginRuntime.Request) {
128
- return yield* pipe(
129
- Effect.gen(function* () {
130
- const { plugin, runtime } = yield* Fiber.join(yield* load);
131
- if (
132
- request.identity.pluginKey !== plugin.identifier &&
133
- !(args[2] === "inspect" && "_tag" in request && request._tag === "extract")
134
- ) {
135
- return yield* PluginRuntime.PluginExecutionError.make({
136
- category: "protocol",
137
- message: "Plugin identity does not match the request",
138
- });
139
- }
140
- if (request.identity.pluginVersion !== args[3])
141
- return yield* PluginRuntime.PluginExecutionError.make({
142
- category: "protocol",
143
- message: "Plugin release does not match the request",
144
- });
145
- if ("_tag" in request && request._tag === "extract") {
146
- return {
147
- _tag: "success",
148
- identity: request.identity,
149
- value: yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(
150
- yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown))(
151
- DualRegistry.materializePlugin(plugin, {
152
- version: request.identity.pluginVersion,
153
- }),
154
- ),
155
- ),
156
- } satisfies RemoteRuntime.Response;
157
- }
158
- return yield* pipe(
159
- PluginRuntime.execute(request),
160
- Effect.provideContext(yield* Fiber.join(yield* runtime)),
161
- );
162
- }),
163
- Effect.catchCauseIf(
164
- cause => !Cause.hasInterrupts(cause),
165
- cause =>
166
- args[2] === "inspect"
167
- ? Effect.fail(initializationError(Cause.squash(cause)))
168
- : Effect.succeed({
169
- _tag: "failure",
170
- identity: request.identity,
171
- error: {
172
- category: "initialization",
173
- code: "PluginInitializationFailed",
174
- message: "Cannot initialize the installed plugin",
175
- retryable: false,
176
- },
177
- } satisfies RemoteRuntime.Response),
120
+ );
121
+ return { plugin, services };
122
+ }),
123
+ scope,
178
124
  ),
179
- Effect.mapError(initializationError),
180
125
  );
181
- });
182
- yield* Effect.raceFirst(
183
- pipe(
184
- PluginRuntime.ipcMessages(process),
185
- Stream.runForEach(
186
- Effect.fnUntraced(function* (message) {
187
- const input = yield* PluginRuntime.decodeInput(message);
188
- const key = yield* Schema.encodeEffect(Schema.fromJsonString(RemoteRuntime.Identity))(
189
- input.identity,
190
- );
191
- if ("_tag" in input && input._tag === "cancel") {
192
- const fiber = Option.getOrUndefined(yield* FiberMap.get(invocations, key));
193
- if (fiber !== undefined) yield* pipe(Fiber.interrupt(fiber), Effect.forkIn(scope));
194
- return;
195
- }
126
+ const run = Effect.fnUntraced(function* (request: PluginRuntime.Request) {
127
+ return yield* pipe(
128
+ Effect.gen(function* () {
129
+ const { plugin, services } = yield* Fiber.join(yield* loaded);
196
130
  if (
197
- (yield* FiberMap.has(invocations, key)) ||
198
- (yield* FiberMap.size(invocations)) >= 16
131
+ request.identity.pluginKey !== plugin.identifier &&
132
+ !(options.mode === "inspect" && "_tag" in request && request._tag === "extract")
199
133
  ) {
200
134
  return yield* PluginRuntime.PluginExecutionError.make({
201
135
  category: "protocol",
202
- message: "Plugin invocation is duplicate or exceeds concurrency",
136
+ message: "Plugin identity does not match the request",
203
137
  });
204
138
  }
205
- const fiber = yield* FiberMap.run(invocations, key, Effect.scoped(execute(input)));
206
- yield* pipe(
207
- Effect.gen(function* () {
208
- const exit = yield* Fiber.await(fiber);
209
- const send = Effect.fnUntraced(function* (output: PluginRuntime.Output) {
210
- const encoded = yield* PluginRuntime.encodeOutput(
211
- output,
212
- PluginRuntime.responseLimit(input),
213
- );
214
- if (args[2] !== "inspect") return yield* PluginRuntime.sendIpc(process, encoded);
215
- // Bun can discard queued data on disconnect; wait for its native send callback.
216
- yield* Effect.callback<void, PluginRuntime.PluginExecutionError>(resume => {
217
- if (process.send === undefined) {
218
- resume(Effect.fail(initializationError("Plugin IPC channel is closed")));
219
- return;
220
- }
221
- process.send(encoded, error => {
222
- if (error !== null) resume(Effect.fail(initializationError(error)));
223
- else resume(Effect.void);
224
- });
225
- });
226
- if (process.connected) process.disconnect();
227
- });
228
- if (Exit.isSuccess(exit)) return yield* send(exit.value);
229
- if (Array.every(exit.cause.reasons, Cause.isInterruptReason)) {
230
- return yield* send({ _tag: "interrupted", identity: input.identity });
231
- }
232
- return yield* initializationError(Cause.squash(exit.cause));
233
- }),
234
- Effect.catchCause(cause =>
235
- Deferred.fail(failed, initializationError(Cause.squash(cause))),
236
- ),
237
- Effect.forkIn(scope),
139
+ if (request.identity.pluginVersion !== options.version)
140
+ return yield* PluginRuntime.PluginExecutionError.make({
141
+ category: "protocol",
142
+ message: "Plugin release does not match the request",
143
+ });
144
+ if ("_tag" in request && request._tag === "extract") {
145
+ return {
146
+ _tag: "success",
147
+ identity: request.identity,
148
+ value: yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Json))(
149
+ yield* Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown))(
150
+ DualRegistry.materializePlugin(plugin, {
151
+ version: request.identity.pluginVersion,
152
+ }),
153
+ ),
154
+ ),
155
+ } satisfies RemoteRuntime.Response;
156
+ }
157
+ return yield* pipe(
158
+ PluginRuntime.execute(request),
159
+ Effect.provideContext(yield* Fiber.join(yield* services)),
238
160
  );
239
161
  }),
240
- ),
241
- Effect.mapError(initializationError),
242
- ),
243
- Deferred.await(failed),
244
- );
245
- }),
246
- Effect.scoped,
247
- Effect.provide([NodeServices.layer, NodeCrypto.layer]),
248
- NodeRuntime.runMain({ disableErrorReporting: process.argv[4] !== "inspect" }),
249
- );
162
+ Effect.catchCauseIf(
163
+ cause => !Cause.hasInterrupts(cause),
164
+ cause =>
165
+ options.mode === "inspect"
166
+ ? Effect.fail(initializationError(Cause.squash(cause)))
167
+ : Effect.succeed({
168
+ _tag: "failure",
169
+ identity: request.identity,
170
+ error: {
171
+ category: "initialization",
172
+ code: "PluginInitializationFailed",
173
+ message: "Cannot initialize the installed plugin",
174
+ retryable: false,
175
+ },
176
+ } satisfies RemoteRuntime.Response),
177
+ ),
178
+ );
179
+ });
180
+ return {
181
+ execute: (message: unknown, signal?: AbortSignal) =>
182
+ runtime.runPromise(
183
+ pipe(
184
+ Effect.gen(function* () {
185
+ const request = yield* PluginRuntime.decodeInput(message);
186
+ return yield* PluginRuntime.encodeOutput(
187
+ yield* Effect.scoped(run(request)),
188
+ PluginRuntime.responseLimit(request),
189
+ );
190
+ }),
191
+ Effect.mapError(initializationError),
192
+ ),
193
+ { signal },
194
+ ),
195
+ };
196
+ }),
197
+ );
198
+ }
199
+
200
+ export * as Runner from "./Runner.ts";