actorctl 0.1.0 → 0.1.2
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/dist/actorctl.js +49 -9
- package/dist/user-worker.js +119 -132
- package/package.json +1 -1
package/dist/actorctl.js
CHANGED
|
@@ -36518,6 +36518,7 @@ var ActorArtifact = exports_Schema.Struct({
|
|
|
36518
36518
|
schema: exports_Schema.Literal(4),
|
|
36519
36519
|
platform: exports_Schema.optionalKey(exports_Schema.Literals(["bun", "cloudflare"])),
|
|
36520
36520
|
kind: exports_Schema.optionalKey(exports_Schema.Literal("worker")),
|
|
36521
|
+
services: exports_Schema.optionalKey(exports_Schema.Record(exports_Schema.String.check(exports_Schema.isPattern(/^[A-Z][A-Z0-9_]{0,63}$/)), exports_Schema.String.check(exports_Schema.isPattern(/^[a-z0-9][a-z0-9-]{0,62}$/)))),
|
|
36521
36522
|
name: exports_Schema.NonEmptyString,
|
|
36522
36523
|
module: exports_Schema.NonEmptyString,
|
|
36523
36524
|
digest: exports_Schema.NonEmptyString
|
|
@@ -36673,6 +36674,10 @@ var Runtime2 = exports_HttpApiGroup.make("runtime").add(exports_HttpApiEndpoint.
|
|
|
36673
36674
|
params: { ...actorParams, thread: Identifier, id: Identifier },
|
|
36674
36675
|
success: Call,
|
|
36675
36676
|
error: errors
|
|
36677
|
+
}), exports_HttpApiEndpoint.get("getMethodCall", `${actorPath}/threads/:thread/methods/:method/calls/:id`, {
|
|
36678
|
+
params: { ...actorParams, thread: Identifier, method: Identifier, id: Identifier },
|
|
36679
|
+
success: Call,
|
|
36680
|
+
error: errors
|
|
36676
36681
|
}), exports_HttpApiEndpoint.post("cancelCall", `${actorPath}/threads/:thread/calls/:id/cancel`, {
|
|
36677
36682
|
params: { ...actorParams, thread: Identifier, id: Identifier },
|
|
36678
36683
|
payload: exports_Schema.Struct({ reason: exports_Schema.String }),
|
|
@@ -36777,7 +36782,8 @@ var Config = exports_Schema.Struct({
|
|
|
36777
36782
|
url: exports_Schema.optionalKey(exports_Schema.NonEmptyString),
|
|
36778
36783
|
description: exports_Schema.optionalKey(exports_Schema.String),
|
|
36779
36784
|
platform: exports_Schema.optionalKey(exports_Schema.Literals(["bun", "cloudflare"])),
|
|
36780
|
-
kind: exports_Schema.optionalKey(exports_Schema.Literal("worker"))
|
|
36785
|
+
kind: exports_Schema.optionalKey(exports_Schema.Literal("worker")),
|
|
36786
|
+
services: exports_Schema.optionalKey(exports_Schema.Record(exports_Schema.String, exports_Schema.String))
|
|
36781
36787
|
});
|
|
36782
36788
|
var resolveConfig = (flags) => exports_Effect.gen(function* () {
|
|
36783
36789
|
const fs = yield* exports_FileSystem.FileSystem;
|
|
@@ -36802,6 +36808,7 @@ var resolveConfig = (flags) => exports_Effect.gen(function* () {
|
|
|
36802
36808
|
entry: config.entry === undefined ? undefined : path.resolve(path.dirname(filename), config.entry),
|
|
36803
36809
|
description: config.description,
|
|
36804
36810
|
kind: config.kind,
|
|
36811
|
+
services: config.services,
|
|
36805
36812
|
platform: (flags.platform === undefined ? undefined : exports_Option.getOrUndefined(flags.platform)) ?? config.platform ?? (local ? "bun" : "cloudflare")
|
|
36806
36813
|
};
|
|
36807
36814
|
});
|
|
@@ -36886,7 +36893,8 @@ var call = exports_Command.make("call", {
|
|
|
36886
36893
|
method: exports_Argument.String("method"),
|
|
36887
36894
|
thread: nonempty("thread"),
|
|
36888
36895
|
input: exports_Flag.String("input").pipe(exports_Flag.withDescription("Method input as JSON.")),
|
|
36889
|
-
key: optional6("key", "Idempotency key; generated when omitted. Reuse it to retry a call.")
|
|
36896
|
+
key: optional6("key", "Idempotency key; generated when omitted. Reuse it to retry a call."),
|
|
36897
|
+
wait: exports_Flag.Boolean("wait").pipe(exports_Flag.withDefault(false), exports_Flag.withDescription("Wait for the call to finish and print its result."))
|
|
36890
36898
|
}, (flags) => exports_Effect.gen(function* () {
|
|
36891
36899
|
const config = yield* resolveConfig(flags);
|
|
36892
36900
|
const name = yield* requireActor(config);
|
|
@@ -36898,8 +36906,20 @@ var call = exports_Command.make("call", {
|
|
|
36898
36906
|
headers: { "idempotency-key": key },
|
|
36899
36907
|
payload
|
|
36900
36908
|
}).pipe(exports_Effect.mapError((error2) => new Error(`Call ${key}: ${userError(error2).userMessage} Retry with --key ${key} and the same input.`)));
|
|
36901
|
-
|
|
36902
|
-
|
|
36909
|
+
if (!flags.wait)
|
|
36910
|
+
return yield* print(flags.json, result3, [`${result3.id} accepted${result3.position === undefined ? "" : ` at ${result3.position}`}`]);
|
|
36911
|
+
const params = { account: config.account, name, thread: flags.thread, method: flags.method, id: result3.id };
|
|
36912
|
+
let state = yield* client.runtime.getMethodCall({ params });
|
|
36913
|
+
while (state.status === "pending") {
|
|
36914
|
+
yield* exports_Effect.sleep(DEFAULT_EVENT_POLL_INTERVAL_MS);
|
|
36915
|
+
state = yield* client.runtime.getMethodCall({ params });
|
|
36916
|
+
}
|
|
36917
|
+
if (flags.json)
|
|
36918
|
+
return yield* exports_Console.log(JSON.stringify(state));
|
|
36919
|
+
if (state.status === "completed")
|
|
36920
|
+
return yield* exports_Console.log(JSON.stringify(state.output, null, 2));
|
|
36921
|
+
return yield* exports_Effect.fail(new Error(`Call ${result3.id} ${state.status}: ${state.status === "failed" ? state.error : state.reason}`));
|
|
36922
|
+
}).pipe(exports_Effect.mapError(userError))).pipe(exports_Command.withDescription("Invoke an actor method and print its receipt, or its result with --wait."));
|
|
36903
36923
|
var sequenceFlag = (name, description) => exports_Flag.Int(name).pipe(exports_Flag.withSchema(exports_Schema.Int.check(exports_Schema.isGreaterThanOrEqualTo(0))), exports_Flag.optional, exports_Flag.withDescription(description));
|
|
36904
36924
|
var countFlag = (name, description) => exports_Flag.Int(name).pipe(exports_Flag.withSchema(exports_Schema.Int.check(exports_Schema.isGreaterThan(0))), exports_Flag.optional, exports_Flag.withDescription(description));
|
|
36905
36925
|
var PAGE_LIMIT = 1000;
|
|
@@ -37004,7 +37024,7 @@ import { resolve as resolve5 } from "path";
|
|
|
37004
37024
|
import { build as build2 } from "esbuild";
|
|
37005
37025
|
var bundledShim = resolve5(import.meta.dir, "user-worker.js");
|
|
37006
37026
|
var userWorker = existsSync(bundledShim) ? bundledShim : resolve5(import.meta.dir, "../../../src/platform/cloudflare/user-worker.ts");
|
|
37007
|
-
var buildWorkerArtifact = (entry, actor) => exports_Effect.tryPromise({
|
|
37027
|
+
var buildWorkerArtifact = (entry, actor, services) => exports_Effect.tryPromise({
|
|
37008
37028
|
try: async () => {
|
|
37009
37029
|
const result3 = await build2({
|
|
37010
37030
|
entryPoints: [resolve5(entry)],
|
|
@@ -37024,7 +37044,7 @@ var buildWorkerArtifact = (entry, actor) => exports_Effect.tryPromise({
|
|
|
37024
37044
|
if (!/export\s*\{[^}]*\bActorDO\b/.test(module) && !/export\s+class\s+ActorDO\b/.test(module))
|
|
37025
37045
|
throw new Error("The Worker entry must export an ActorDO Durable Object class.");
|
|
37026
37046
|
return {
|
|
37027
|
-
manifest: { schema: 4, name: actor, module: "worker.js", platform: "cloudflare", kind: "worker", digest: `sha256:${createHash2("sha256").update(module).digest("hex")}` },
|
|
37047
|
+
manifest: { schema: 4, name: actor, module: "worker.js", platform: "cloudflare", kind: "worker", ...services && Object.keys(services).length ? { services } : {}, digest: `sha256:${createHash2("sha256").update(module).digest("hex")}` },
|
|
37028
37048
|
module
|
|
37029
37049
|
};
|
|
37030
37050
|
},
|
|
@@ -37323,7 +37343,7 @@ var deploy = exports_Command.make("deploy", { ...scoped4, entry, platform }, (fl
|
|
|
37323
37343
|
const source = exports_Option.getOrUndefined(flags.entry) ?? config.entry;
|
|
37324
37344
|
if (!source)
|
|
37325
37345
|
return yield* exports_Effect.fail(new Error("Provide an entry file or set entry in tardigrade.cloud.json."));
|
|
37326
|
-
const artifact = yield* config.kind === "worker" ? buildWorkerArtifact(source, actor) : buildArtifact(source, actor, config.platform);
|
|
37346
|
+
const artifact = yield* config.kind === "worker" ? buildWorkerArtifact(source, actor, config.services) : buildArtifact(source, actor, config.platform);
|
|
37327
37347
|
const client = yield* cloudClient(config.url);
|
|
37328
37348
|
const params = { account: config.account, name: actor };
|
|
37329
37349
|
yield* client.actors.putActor({ params, payload: config.description === undefined ? {} : { description: config.description } });
|
|
@@ -37342,6 +37362,25 @@ var actorsDelete = exports_Command.make("delete", {
|
|
|
37342
37362
|
yield* client.actors.deleteActor({ params: { account: config.account, name: flags.name } });
|
|
37343
37363
|
yield* print(flags.json, { deleted: flags.name }, [`Deleted ${flags.name}.`]);
|
|
37344
37364
|
}).pipe(exports_Effect.mapError(userError))).pipe(exports_Command.withDescription("Delete an actor's runtime, threads, and secrets."));
|
|
37365
|
+
var secretsPut = exports_Command.make("put", { ...scoped4, key: exports_Argument.String("key") }, (flags) => exports_Effect.gen(function* () {
|
|
37366
|
+
const config = yield* resolveConfig(flags);
|
|
37367
|
+
const name = yield* requireActor(config);
|
|
37368
|
+
if (process.stdin.isTTY)
|
|
37369
|
+
return yield* exports_Effect.fail(new Error(`Pipe the value on stdin, for example: printf %s "$VALUE" | actorctl secrets put ${flags.key}`));
|
|
37370
|
+
const value3 = (yield* exports_Effect.promise(() => Bun.stdin.text())).replace(/\r?\n$/, "");
|
|
37371
|
+
if (!value3)
|
|
37372
|
+
return yield* exports_Effect.fail(new Error("The secret value on stdin is empty."));
|
|
37373
|
+
const client = yield* cloudClient(config.url);
|
|
37374
|
+
yield* client.secrets.putSecret({ params: { account: config.account, name, key: flags.key }, payload: { value: value3 } });
|
|
37375
|
+
yield* print(flags.json, { key: flags.key, actor: name }, [`Set ${flags.key} on ${name}. Redeploy the actor to apply it.`]);
|
|
37376
|
+
}).pipe(exports_Effect.mapError(userError))).pipe(exports_Command.withDescription("Set an actor secret from stdin; it applies on the next deploy."));
|
|
37377
|
+
var secretsDelete = exports_Command.make("delete", { ...scoped4, key: exports_Argument.String("key") }, (flags) => exports_Effect.gen(function* () {
|
|
37378
|
+
const config = yield* resolveConfig(flags);
|
|
37379
|
+
const name = yield* requireActor(config);
|
|
37380
|
+
const client = yield* cloudClient(config.url);
|
|
37381
|
+
yield* client.secrets.deleteSecret({ params: { account: config.account, name, key: flags.key } });
|
|
37382
|
+
yield* print(flags.json, { deleted: flags.key, actor: name }, [`Deleted ${flags.key} from ${name}. Redeploy the actor to apply it.`]);
|
|
37383
|
+
}).pipe(exports_Effect.mapError(userError))).pipe(exports_Command.withDescription("Delete an actor secret; it applies on the next deploy."));
|
|
37345
37384
|
var init = exports_Command.make("init", {
|
|
37346
37385
|
name: exports_Argument.String("name").pipe(exports_Argument.withDescription("Actor name: lowercase letters, digits, and dashes.")),
|
|
37347
37386
|
dir: optional6("dir", "Directory to create; defaults to the actor name."),
|
|
@@ -37403,10 +37442,11 @@ var actorctl = exports_Command.make("actorctl").pipe(exports_Command.withDescrip
|
|
|
37403
37442
|
sql,
|
|
37404
37443
|
exports_Command.make("actors").pipe(exports_Command.withSubcommands([actorsList, actorsInfo, actorsDelete])),
|
|
37405
37444
|
exports_Command.make("versions").pipe(exports_Command.withSubcommands([versionsList, versionsView])),
|
|
37406
|
-
exports_Command.make("deployments").pipe(exports_Command.withSubcommands([deploymentsList]))
|
|
37445
|
+
exports_Command.make("deployments").pipe(exports_Command.withSubcommands([deploymentsList])),
|
|
37446
|
+
exports_Command.make("secrets").pipe(exports_Command.withSubcommands([secretsPut, secretsDelete]))
|
|
37407
37447
|
]));
|
|
37408
37448
|
// package.json
|
|
37409
|
-
var version2 = "0.1.
|
|
37449
|
+
var version2 = "0.1.2";
|
|
37410
37450
|
|
|
37411
37451
|
// src/main.ts
|
|
37412
37452
|
exports_Command.run(actorctl, { version: version2 }).pipe(exports_Effect.provide(exports_Layer.mergeAll(exports_BunServices.layer, exports_FetchHttpClient.layer)), exports_BunRuntime.runMain);
|
package/dist/user-worker.js
CHANGED
|
@@ -17,7 +17,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
17
|
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
18
18
|
|
|
19
19
|
// ../../src/platform/cloudflare/user-worker.ts
|
|
20
|
-
import { ConfigProvider, Layer as
|
|
20
|
+
import { ConfigProvider, Layer as Layer9 } from "effect";
|
|
21
21
|
|
|
22
22
|
// ../../src/platform/cloudflare/analytics.ts
|
|
23
23
|
import { Effect as Effect2, Layer } from "effect";
|
|
@@ -42,39 +42,27 @@ var cloudflareAnalytics = (accountId, binding) => Layer.succeed(Analytics, Analy
|
|
|
42
42
|
})
|
|
43
43
|
}));
|
|
44
44
|
|
|
45
|
-
// ../../src/services/container.ts
|
|
46
|
-
import { Context as Context2, Effect as Effect3, Layer as Layer2 } from "effect";
|
|
47
|
-
var ContainerService = class extends Context2.Service()("tardigrade-cloud/ContainerService") {
|
|
48
|
-
};
|
|
49
|
-
var boundContainerService = (binding, thread) => Layer2.succeed(ContainerService, {
|
|
50
|
-
execute: (taskId, command, timeoutMs) => Effect3.tryPromise(async () => {
|
|
51
|
-
if (!binding) throw new Error("Container service is unavailable");
|
|
52
|
-
if (thread !== `task-${taskId}`) throw new Error("Command task must match the agent thread");
|
|
53
|
-
return binding.execute(taskId, command, timeoutMs);
|
|
54
|
-
})
|
|
55
|
-
});
|
|
56
|
-
|
|
57
45
|
// ../../src/platform/cloudflare/inference.ts
|
|
58
|
-
import { Effect as
|
|
46
|
+
import { Effect as Effect4, Layer as Layer2 } from "effect";
|
|
59
47
|
|
|
60
48
|
// ../../src/services/ai-gateway.ts
|
|
61
|
-
import { Context as
|
|
49
|
+
import { Context as Context2, Data as Data2 } from "effect";
|
|
62
50
|
var AiGatewayError = class extends Data2.TaggedError("AiGatewayError") {
|
|
63
51
|
};
|
|
64
|
-
var AiGateway = class extends
|
|
52
|
+
var AiGateway = class extends Context2.Service()("tardigrade-cloud/AiGateway") {
|
|
65
53
|
};
|
|
66
54
|
|
|
67
55
|
// ../../src/platform/cloudflare/inference.ts
|
|
68
|
-
var boundAiGateway = (accountId, binding) =>
|
|
56
|
+
var boundAiGateway = (accountId, binding) => Layer2.succeed(AiGateway, AiGateway.of({
|
|
69
57
|
accountId,
|
|
70
|
-
complete: (request) =>
|
|
58
|
+
complete: (request) => Effect4.tryPromise({
|
|
71
59
|
try: () => binding.complete(request),
|
|
72
60
|
catch: () => new AiGatewayError({ reason: "unavailable", message: "Inference service unavailable." })
|
|
73
|
-
}).pipe(
|
|
61
|
+
}).pipe(Effect4.flatMap((result) => result.ok ? Effect4.succeed(result.value) : Effect4.fail(new AiGatewayError(result.error))))
|
|
74
62
|
}));
|
|
75
63
|
|
|
76
64
|
// ../../src/platform/cloudflare/runtime.ts
|
|
77
|
-
import { Effect as
|
|
65
|
+
import { Effect as Effect16 } from "effect";
|
|
78
66
|
|
|
79
67
|
// ../../node_modules/.bun/@effect+sql-sqlite-do@4.0.0-rc.115+4452d4a4fc6c5fd5/node_modules/@effect/sql-sqlite-do/dist/SqliteClient.js
|
|
80
68
|
var SqliteClient_exports = {};
|
|
@@ -87,12 +75,12 @@ __export(SqliteClient_exports, {
|
|
|
87
75
|
});
|
|
88
76
|
import * as Cause from "effect/Cause";
|
|
89
77
|
import * as Config from "effect/Config";
|
|
90
|
-
import * as
|
|
91
|
-
import * as
|
|
78
|
+
import * as Context3 from "effect/Context";
|
|
79
|
+
import * as Effect5 from "effect/Effect";
|
|
92
80
|
import * as Exit from "effect/Exit";
|
|
93
81
|
import * as Fiber from "effect/Fiber";
|
|
94
82
|
import { identity } from "effect/Function";
|
|
95
|
-
import * as
|
|
83
|
+
import * as Layer3 from "effect/Layer";
|
|
96
84
|
import * as Rec from "effect/Record";
|
|
97
85
|
import * as Scope from "effect/Scope";
|
|
98
86
|
import * as Semaphore from "effect/Semaphore";
|
|
@@ -107,8 +95,8 @@ var classifyError = (cause, message, operation) => classifySqliteError(cause, {
|
|
|
107
95
|
operation
|
|
108
96
|
});
|
|
109
97
|
var TypeId = "~@effect/sql-sqlite-do/SqliteClient";
|
|
110
|
-
var SqliteClient = /* @__PURE__ */
|
|
111
|
-
var SqliteTransaction = /* @__PURE__ */
|
|
98
|
+
var SqliteClient = /* @__PURE__ */ Context3.Service("@effect/sql-sqlite-do/SqliteClient");
|
|
99
|
+
var SqliteTransaction = /* @__PURE__ */ Context3.Service("@effect/sql-sqlite-do/SqliteClient/SqliteTransaction");
|
|
112
100
|
var unsupportedTransaction = (message, operation) => new SqlError({
|
|
113
101
|
reason: new UnknownError({
|
|
114
102
|
cause: new Error(message),
|
|
@@ -116,43 +104,43 @@ var unsupportedTransaction = (message, operation) => new SqlError({
|
|
|
116
104
|
operation
|
|
117
105
|
})
|
|
118
106
|
});
|
|
119
|
-
var makeUnsupportedWithTransaction = (message) => (_effect) =>
|
|
120
|
-
var makeStorageBackedWithTransaction = (storage, connection, semaphore) => (effect) =>
|
|
107
|
+
var makeUnsupportedWithTransaction = (message) => (_effect) => Effect5.fail(unsupportedTransaction(message, "transaction"));
|
|
108
|
+
var makeStorageBackedWithTransaction = (storage, connection, semaphore) => (effect) => Effect5.withFiber((fiber) => {
|
|
121
109
|
const services = fiber.context;
|
|
122
|
-
const connOption =
|
|
110
|
+
const connOption = Context3.getOption(services, SqliteTransaction);
|
|
123
111
|
if (connOption._tag === "Some") {
|
|
124
|
-
return
|
|
112
|
+
return Effect5.fail(unsupportedTransaction("Nested transactions are not supported by Cloudflare Durable Object SQLite storage", "transaction"));
|
|
125
113
|
}
|
|
126
|
-
const effectWithTxn =
|
|
127
|
-
return semaphore.withPermits(1)(
|
|
114
|
+
const effectWithTxn = Effect5.provideContext(effect, Context3.add(services, SqliteTransaction, [connection, 0]));
|
|
115
|
+
return semaphore.withPermits(1)(Effect5.callback((resume) => {
|
|
128
116
|
let interrupted = false;
|
|
129
117
|
const promise2 = storage.transaction((txn) => new Promise((resolve) => {
|
|
130
118
|
if (interrupted) return resolve();
|
|
131
|
-
resume(
|
|
119
|
+
resume(Effect5.onExit(effectWithTxn, (exit) => {
|
|
132
120
|
if (Exit.isFailure(exit)) {
|
|
133
121
|
txn.rollback();
|
|
134
122
|
}
|
|
135
123
|
resolve();
|
|
136
|
-
return
|
|
124
|
+
return Effect5.promise(() => promise2);
|
|
137
125
|
}));
|
|
138
|
-
})).catch((cause) => resume(
|
|
126
|
+
})).catch((cause) => resume(Effect5.fail(new SqlError({
|
|
139
127
|
reason: classifyError(cause, "Failed transaction", "transaction")
|
|
140
128
|
}))));
|
|
141
|
-
return
|
|
129
|
+
return Effect5.suspend(() => {
|
|
142
130
|
interrupted = true;
|
|
143
|
-
return
|
|
131
|
+
return Effect5.promise(() => promise2);
|
|
144
132
|
});
|
|
145
133
|
}));
|
|
146
134
|
});
|
|
147
|
-
var make4 = (options) =>
|
|
135
|
+
var make4 = (options) => Effect5.gen(function* () {
|
|
148
136
|
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
|
|
149
137
|
const transformRows = options.transformResultNames ? Statement.defaultTransforms(options.transformResultNames).array : void 0;
|
|
150
138
|
const db = options.storage?.sql ?? options.db;
|
|
151
139
|
if (db === void 0) {
|
|
152
|
-
return yield*
|
|
140
|
+
return yield* Effect5.die("SqliteClient.make requires either a Durable Object storage or sql storage");
|
|
153
141
|
}
|
|
154
142
|
const sqlStorage = db;
|
|
155
|
-
const makeConnection =
|
|
143
|
+
const makeConnection = Effect5.gen(function* () {
|
|
156
144
|
function* runIterator(sql, params = []) {
|
|
157
145
|
const cursor = sqlStorage.exec(sql, ...params);
|
|
158
146
|
const columns = cursor.columnNames;
|
|
@@ -165,13 +153,13 @@ var make4 = (options) => Effect6.gen(function* () {
|
|
|
165
153
|
yield obj;
|
|
166
154
|
}
|
|
167
155
|
}
|
|
168
|
-
const runStatement = (sql, params = []) =>
|
|
156
|
+
const runStatement = (sql, params = []) => Effect5.try({
|
|
169
157
|
try: () => Array.from(runIterator(sql, params)),
|
|
170
158
|
catch: (cause) => new SqlError({
|
|
171
159
|
reason: classifyError(cause, "Failed to execute statement", "execute")
|
|
172
160
|
})
|
|
173
161
|
});
|
|
174
|
-
const runValues = (sql, params = []) =>
|
|
162
|
+
const runValues = (sql, params = []) => Effect5.try({
|
|
175
163
|
try: () => Array.from(sqlStorage.exec(sql, ...params).raw(), (row) => {
|
|
176
164
|
for (let i = 0; i < row.length; i++) {
|
|
177
165
|
const value = row[i];
|
|
@@ -187,7 +175,7 @@ var make4 = (options) => Effect6.gen(function* () {
|
|
|
187
175
|
});
|
|
188
176
|
return identity({
|
|
189
177
|
execute(sql, params, transformRows2) {
|
|
190
|
-
return transformRows2 ?
|
|
178
|
+
return transformRows2 ? Effect5.map(runStatement(sql, params), transformRows2) : runStatement(sql, params);
|
|
191
179
|
},
|
|
192
180
|
executeRaw(sql, params) {
|
|
193
181
|
return runStatement(sql, params);
|
|
@@ -199,7 +187,7 @@ var make4 = (options) => Effect6.gen(function* () {
|
|
|
199
187
|
return runValues(sql, params);
|
|
200
188
|
},
|
|
201
189
|
executeUnprepared(sql, params, transformRows2) {
|
|
202
|
-
return transformRows2 ?
|
|
190
|
+
return transformRows2 ? Effect5.map(runStatement(sql, params), transformRows2) : runStatement(sql, params);
|
|
203
191
|
},
|
|
204
192
|
executeStream(sql, params, transformRows2) {
|
|
205
193
|
return Stream.suspend(() => {
|
|
@@ -213,11 +201,11 @@ var make4 = (options) => Effect6.gen(function* () {
|
|
|
213
201
|
});
|
|
214
202
|
const semaphore = yield* Semaphore.make(1);
|
|
215
203
|
const connection = yield* makeConnection;
|
|
216
|
-
const acquirer = semaphore.withPermits(1)(
|
|
217
|
-
const transactionAcquirer =
|
|
204
|
+
const acquirer = semaphore.withPermits(1)(Effect5.succeed(connection));
|
|
205
|
+
const transactionAcquirer = Effect5.uninterruptibleMask((restore) => {
|
|
218
206
|
const fiber = Fiber.getCurrent();
|
|
219
|
-
const scope =
|
|
220
|
-
return
|
|
207
|
+
const scope = Context3.getUnsafe(fiber.context, Scope.Scope);
|
|
208
|
+
return Effect5.as(Effect5.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))), connection);
|
|
221
209
|
});
|
|
222
210
|
const client = yield* Client.make({
|
|
223
211
|
acquirer,
|
|
@@ -233,8 +221,8 @@ var make4 = (options) => Effect6.gen(function* () {
|
|
|
233
221
|
withTransaction: options.storage ? makeStorageBackedWithTransaction(options.storage, connection, semaphore) : makeUnsupportedWithTransaction("Transactions require Durable Object storage; pass ctx.storage as the storage option")
|
|
234
222
|
});
|
|
235
223
|
});
|
|
236
|
-
var layerConfig = (config) =>
|
|
237
|
-
var layer2 = (config) =>
|
|
224
|
+
var layerConfig = (config) => Layer3.effectContext(Config.unwrap(config).pipe(Effect5.flatMap(make4), Effect5.map((client) => Context3.make(SqliteClient, client).pipe(Context3.add(Client.SqlClient, client))))).pipe(Layer3.provide(Reactivity.layer));
|
|
225
|
+
var layer2 = (config) => Layer3.effectContext(Effect5.map(make4(config), (client) => Context3.make(SqliteClient, client).pipe(Context3.add(Client.SqlClient, client)))).pipe(Layer3.provide(Reactivity.layer));
|
|
238
226
|
|
|
239
227
|
// ../../node_modules/.bun/@effect+sql-sqlite-do@4.0.0-rc.115+4452d4a4fc6c5fd5/node_modules/@effect/sql-sqlite-do/dist/SqliteMigrator.js
|
|
240
228
|
var SqliteMigrator_exports = {};
|
|
@@ -243,59 +231,59 @@ __export(SqliteMigrator_exports, {
|
|
|
243
231
|
run: () => run
|
|
244
232
|
});
|
|
245
233
|
__reExport(SqliteMigrator_exports, Migrator_star);
|
|
246
|
-
import * as
|
|
234
|
+
import * as Layer4 from "effect/Layer";
|
|
247
235
|
import * as Migrator from "effect/unstable/sql/Migrator";
|
|
248
236
|
import * as Migrator_star from "effect/unstable/sql/Migrator";
|
|
249
237
|
var run = /* @__PURE__ */ Migrator.make({});
|
|
250
|
-
var layer3 = (options) =>
|
|
238
|
+
var layer3 = (options) => Layer4.effectDiscard(run(options));
|
|
251
239
|
|
|
252
240
|
// ../../src/platform/cloudflare/runtime.ts
|
|
253
241
|
import { cloudflareHandler } from "tardie/experimental/cloudflare";
|
|
254
242
|
|
|
255
243
|
// ../../src/platform/exporting-host.ts
|
|
256
|
-
import { Context as
|
|
244
|
+
import { Context as Context6, Effect as Effect10, Fiber as Fiber2, Layer as Layer7, ManagedRuntime, Queue, Semaphore as Semaphore3, Schema as Schema2 } from "effect";
|
|
257
245
|
import { SqlClient as SqlClient3 } from "effect/unstable/sql";
|
|
258
246
|
import { createThreadHost, InvalidMessage, MessageConflict } from "tardie/experimental";
|
|
259
247
|
import { sqlJournal } from "tardie/experimental/cloudflare";
|
|
260
248
|
|
|
261
249
|
// ../../src/services/event-exporter.ts
|
|
262
|
-
import { Context as
|
|
250
|
+
import { Context as Context4, Data as Data3 } from "effect";
|
|
263
251
|
var ExportError = class extends Data3.TaggedError("ExportError") {
|
|
264
252
|
};
|
|
265
|
-
var EventExporter = class extends
|
|
253
|
+
var EventExporter = class extends Context4.Service()("tardigrade-cloud/EventExporter") {
|
|
266
254
|
};
|
|
267
255
|
|
|
268
256
|
// ../../src/platform/export-source.ts
|
|
269
|
-
import { Effect as
|
|
257
|
+
import { Effect as Effect7 } from "effect";
|
|
270
258
|
import { SqlClient as SqlClient2 } from "effect/unstable/sql";
|
|
271
|
-
var journalExportSource = (options) =>
|
|
259
|
+
var journalExportSource = (options) => Effect7.gen(function* () {
|
|
272
260
|
if (!options.journal || !options.cursorKey) return yield* new ExportError({ operation: "config", message: "Journal and destination cursor key are required." });
|
|
273
261
|
const sql = yield* SqlClient2.SqlClient;
|
|
274
262
|
const error = (operation) => () => new ExportError({ operation, message: `Journal export ${operation} failed.` });
|
|
275
|
-
yield* sql`CREATE TABLE IF NOT EXISTS event_export_cursors (id TEXT PRIMARY KEY, position INTEGER NOT NULL CHECK (position >= 0))`.pipe(
|
|
276
|
-
yield* sql`INSERT INTO event_export_cursors (id, position) VALUES (${options.cursorKey}, 0) ON CONFLICT (id) DO NOTHING`.pipe(
|
|
277
|
-
const cursor =
|
|
278
|
-
const rows = yield* sql`SELECT position FROM event_export_cursors WHERE id = ${options.cursorKey}`.pipe(
|
|
263
|
+
yield* sql`CREATE TABLE IF NOT EXISTS event_export_cursors (id TEXT PRIMARY KEY, position INTEGER NOT NULL CHECK (position >= 0))`.pipe(Effect7.mapError(error("cursor")));
|
|
264
|
+
yield* sql`INSERT INTO event_export_cursors (id, position) VALUES (${options.cursorKey}, 0) ON CONFLICT (id) DO NOTHING`.pipe(Effect7.mapError(error("cursor")));
|
|
265
|
+
const cursor = Effect7.gen(function* () {
|
|
266
|
+
const rows = yield* sql`SELECT position FROM event_export_cursors WHERE id = ${options.cursorKey}`.pipe(Effect7.mapError(error("cursor")));
|
|
279
267
|
if (!rows[0]) return yield* new ExportError({ operation: "cursor", message: "Export cursor is missing." });
|
|
280
268
|
return rows[0].position;
|
|
281
269
|
});
|
|
282
270
|
return {
|
|
283
271
|
cursor,
|
|
284
|
-
read: (from, limit) => sql`SELECT seq AS position, event AS payload FROM experimental_events WHERE actor = ${options.journal} AND seq >= ${from} ORDER BY seq LIMIT ${limit}`.pipe(
|
|
285
|
-
advance: (expected, next) =>
|
|
272
|
+
read: (from, limit) => sql`SELECT seq AS position, event AS payload FROM experimental_events WHERE actor = ${options.journal} AND seq >= ${from} ORDER BY seq LIMIT ${limit}`.pipe(Effect7.mapError(error("read"))),
|
|
273
|
+
advance: (expected, next) => Effect7.gen(function* () {
|
|
286
274
|
if (!Number.isSafeInteger(expected) || !Number.isSafeInteger(next) || expected < 0 || next <= expected) {
|
|
287
275
|
return yield* new ExportError({ operation: "cursor", message: "Invalid cursor advancement." });
|
|
288
276
|
}
|
|
289
|
-
const rows = yield* sql`UPDATE event_export_cursors SET position = ${next} WHERE id = ${options.cursorKey} AND position = ${expected} RETURNING position`.pipe(
|
|
277
|
+
const rows = yield* sql`UPDATE event_export_cursors SET position = ${next} WHERE id = ${options.cursorKey} AND position = ${expected} RETURNING position`.pipe(Effect7.mapError(error("cursor")));
|
|
290
278
|
if (rows.length !== 1) return yield* new ExportError({ operation: "cursor", message: "Export cursor changed concurrently; retry the flush." });
|
|
291
279
|
})
|
|
292
280
|
};
|
|
293
281
|
});
|
|
294
282
|
|
|
295
283
|
// ../../src/platform/exporter.ts
|
|
296
|
-
import { Effect as
|
|
284
|
+
import { Effect as Effect8, Layer as Layer5, Semaphore as Semaphore2 } from "effect";
|
|
297
285
|
var DEFAULT_EXPORT_BATCH_SIZE = 100;
|
|
298
|
-
var eventExporter = (options) =>
|
|
286
|
+
var eventExporter = (options) => Layer5.effect(EventExporter, Effect8.gen(function* () {
|
|
299
287
|
const analytics = yield* Analytics;
|
|
300
288
|
const batchSize = options.batchSize ?? DEFAULT_EXPORT_BATCH_SIZE;
|
|
301
289
|
if (![options.accountId, options.actor, options.sourceId].every(Boolean) || analytics.accountId !== options.accountId) {
|
|
@@ -309,10 +297,10 @@ var eventExporter = (options) => Layer6.effect(EventExporter, Effect9.gen(functi
|
|
|
309
297
|
account_id VARCHAR NOT NULL, actor VARCHAR NOT NULL, source_id VARCHAR NOT NULL,
|
|
310
298
|
position BIGINT NOT NULL, payload JSON NOT NULL,
|
|
311
299
|
PRIMARY KEY (account_id, source_id, position)
|
|
312
|
-
)`).pipe(
|
|
300
|
+
)`).pipe(Effect8.mapError(writeError));
|
|
313
301
|
const lock = yield* Semaphore2.make(1);
|
|
314
302
|
return EventExporter.of({
|
|
315
|
-
flush: () => lock.withPermits(1)(
|
|
303
|
+
flush: () => lock.withPermits(1)(Effect8.gen(function* () {
|
|
316
304
|
const cursor = yield* options.source.cursor;
|
|
317
305
|
if (!Number.isSafeInteger(cursor) || cursor < 0) return yield* new ExportError({ operation: "cursor", message: "Invalid export cursor." });
|
|
318
306
|
const rows = yield* options.source.read(cursor, batchSize + 1);
|
|
@@ -328,13 +316,13 @@ var eventExporter = (options) => Layer6.effect(EventExporter, Effect9.gen(functi
|
|
|
328
316
|
yield* analytics.execute(
|
|
329
317
|
`INSERT INTO actor_events (account_id, actor, source_id, position, payload) VALUES ${values} ON CONFLICT (account_id, source_id, position) DO NOTHING`,
|
|
330
318
|
parameters
|
|
331
|
-
).pipe(
|
|
319
|
+
).pipe(Effect8.mapError(writeError));
|
|
332
320
|
yield* options.source.advance(cursor, next);
|
|
333
321
|
return { exported: batch.length, cursor: next, hasMore: rows.length > batchSize, batchSize };
|
|
334
322
|
}))
|
|
335
323
|
});
|
|
336
324
|
}));
|
|
337
|
-
var sqlEventExporter = (options) =>
|
|
325
|
+
var sqlEventExporter = (options) => Layer5.unwrap(Effect8.gen(function* () {
|
|
338
326
|
if (!options.destinationId) return yield* new ExportError({ operation: "config", message: "Analytics destination identity is required." });
|
|
339
327
|
const source = yield* journalExportSource({
|
|
340
328
|
journal: options.journal,
|
|
@@ -344,7 +332,7 @@ var sqlEventExporter = (options) => Layer6.unwrap(Effect9.gen(function* () {
|
|
|
344
332
|
}));
|
|
345
333
|
|
|
346
334
|
// ../../src/platform/actor-mcp.ts
|
|
347
|
-
import { Context as
|
|
335
|
+
import { Context as Context5, Effect as Effect9, Layer as Layer6, Schema } from "effect";
|
|
348
336
|
import { McpProtocol, McpSchema, McpServer, Tool } from "effect/unstable/ai";
|
|
349
337
|
import { HttpRouter } from "effect/unstable/http";
|
|
350
338
|
var ACTOR_MCP_PROTOCOLS = [McpProtocol.v2025_11_25, McpProtocol.v2025_06_18];
|
|
@@ -353,28 +341,28 @@ var receipt = Schema.Struct({ id: Schema.String, position: Schema.optionalKey(Sc
|
|
|
353
341
|
function actorMcp(host, instance, options = {}) {
|
|
354
342
|
const path = `/v1/actors/${encodeURIComponent(instance)}/mcp`;
|
|
355
343
|
let app;
|
|
356
|
-
const open = () => app ??=
|
|
357
|
-
const register =
|
|
344
|
+
const open = () => app ??= Effect9.runPromise(host.describe(instance)).then((contracts) => {
|
|
345
|
+
const register = Layer6.effectDiscard(Effect9.gen(function* () {
|
|
358
346
|
const server = yield* McpServer.McpServer;
|
|
359
347
|
const add2 = (name, description, input, output, run2) => server.addTool({
|
|
360
348
|
tool: new McpSchema.Tool({ name, description, inputSchema: Tool.getJsonSchemaFromSchema(input), outputSchema: Tool.getJsonSchemaFromSchema(output) }),
|
|
361
|
-
annotations:
|
|
349
|
+
annotations: Context5.empty(),
|
|
362
350
|
handle: (payload) => Schema.decodeUnknownEffect(Schema.toType(input), { onExcessProperty: "error" })(payload).pipe(
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
351
|
+
Effect9.mapError((error) => new McpSchema.InvalidParams({ message: error.message })),
|
|
352
|
+
Effect9.flatMap((value) => run2(value).pipe(
|
|
353
|
+
Effect9.map((result) => new McpSchema.CallToolResult({ content: [{ type: "text", text: JSON.stringify(result) }], structuredContent: result })),
|
|
354
|
+
Effect9.catch((error) => Effect9.succeed(new McpSchema.CallToolResult({ isError: true, content: [{ type: "text", text: error.message }] })))
|
|
367
355
|
))
|
|
368
356
|
)
|
|
369
357
|
});
|
|
370
|
-
const thread = (name) => host.getThread({ instance, thread: name }).pipe(
|
|
358
|
+
const thread = (name) => host.getThread({ instance, thread: name }).pipe(Effect9.flatMap((value) => value ? Effect9.succeed(value) : Effect9.fail(new Error("Unknown thread"))));
|
|
371
359
|
for (const [name, method] of Object.entries(contracts)) {
|
|
372
360
|
yield* add2(
|
|
373
361
|
`invoke_${name}`,
|
|
374
362
|
`Accept ${name}. Returns a durable call receipt; use call_get for the final result. Reuse id and input on retries.`,
|
|
375
363
|
Schema.Struct({ ...identity2, input: method.inputSchema }),
|
|
376
364
|
receipt,
|
|
377
|
-
(input) => thread(input.thread).pipe(
|
|
365
|
+
(input) => thread(input.thread).pipe(Effect9.flatMap((current) => current.invoke(name, input.input, { id: input.id })))
|
|
378
366
|
);
|
|
379
367
|
}
|
|
380
368
|
yield* add2(
|
|
@@ -382,16 +370,16 @@ function actorMcp(host, instance, options = {}) {
|
|
|
382
370
|
"Read a call's current status and final result.",
|
|
383
371
|
Schema.Struct(identity2),
|
|
384
372
|
Schema.Struct({ id: Schema.String, method: Schema.String, status: Schema.String, output: Schema.optionalKey(Schema.Json), error: Schema.optionalKey(Schema.String), reason: Schema.optionalKey(Schema.String) }),
|
|
385
|
-
(input) => thread(input.thread).pipe(
|
|
373
|
+
(input) => thread(input.thread).pipe(Effect9.flatMap((current) => current.call(input.id)), Effect9.flatMap((value) => value ? Effect9.succeed(value) : Effect9.fail(new Error("Unknown call"))))
|
|
386
374
|
);
|
|
387
375
|
yield* add2(
|
|
388
376
|
"call_cancel",
|
|
389
377
|
"Request cancellation of an accepted call. Returns acceptance, not cancellation completion.",
|
|
390
378
|
Schema.Struct({ ...identity2, reason: Schema.String }),
|
|
391
379
|
receipt,
|
|
392
|
-
(input) => thread(input.thread).pipe(
|
|
380
|
+
(input) => thread(input.thread).pipe(Effect9.flatMap((current) => current.call(input.id).pipe(Effect9.flatMap((call) => call ? current.cancel(call.method, input.id, input.reason) : Effect9.fail(new Error("Unknown call"))))))
|
|
393
381
|
);
|
|
394
|
-
})).pipe(
|
|
382
|
+
})).pipe(Layer6.provide(McpServer.layerHttp({ name: host.actor, version: "1.0.0", path, protocols: ACTOR_MCP_PROTOCOLS, ...options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {} })));
|
|
395
383
|
return HttpRouter.toWebHandler(register, { disableLogger: true });
|
|
396
384
|
}).catch((error) => {
|
|
397
385
|
app = void 0;
|
|
@@ -423,13 +411,13 @@ async function createSqlExportingHost(options) {
|
|
|
423
411
|
const runtime = ManagedRuntime.make(options.sql);
|
|
424
412
|
const connections = /* @__PURE__ */ new Set();
|
|
425
413
|
try {
|
|
426
|
-
const state = await runtime.runPromise(
|
|
414
|
+
const state = await runtime.runPromise(Effect10.gen(function* () {
|
|
427
415
|
const sql = yield* SqlClient3.SqlClient;
|
|
428
416
|
yield* sql`CREATE TABLE IF NOT EXISTS event_export_identity (id INTEGER PRIMARY KEY CHECK (id = 1), account TEXT NOT NULL, actor TEXT NOT NULL, generation TEXT NOT NULL)`;
|
|
429
417
|
yield* sql`INSERT INTO event_export_identity VALUES (1, ${options.accountId}, ${options.actor.actorName}, ${crypto.randomUUID()}) ON CONFLICT (id) DO NOTHING`;
|
|
430
418
|
const rows = yield* sql`SELECT account, actor, generation FROM event_export_identity WHERE id = 1`;
|
|
431
419
|
const identity3 = rows[0];
|
|
432
|
-
if (identity3.account !== options.accountId || identity3.actor !== options.actor.actorName) return yield*
|
|
420
|
+
if (identity3.account !== options.accountId || identity3.actor !== options.actor.actorName) return yield* Effect10.fail(new Error("Journal database belongs to a different account or actor."));
|
|
433
421
|
const signals = yield* Queue.make({ capacity: 1, strategy: "sliding" });
|
|
434
422
|
const lock = yield* Semaphore3.make(1);
|
|
435
423
|
return { sql, identity: identity3, signals, lock };
|
|
@@ -440,16 +428,16 @@ async function createSqlExportingHost(options) {
|
|
|
440
428
|
};
|
|
441
429
|
const journal = (parts, exportEvents = false) => {
|
|
442
430
|
const key = JSON.stringify(parts);
|
|
443
|
-
const opened = sqlJournal({ actor: key, layer:
|
|
431
|
+
const opened = sqlJournal({ actor: key, layer: Layer7.succeed(SqlClient3.SqlClient, state.sql) });
|
|
444
432
|
connections.add(opened.close);
|
|
445
|
-
const afterCommit =
|
|
446
|
-
if (options.sync) yield*
|
|
433
|
+
const afterCommit = Effect10.gen(function* () {
|
|
434
|
+
if (options.sync) yield* Effect10.tryPromise(() => options.sync());
|
|
447
435
|
if (exportEvents) signal();
|
|
448
436
|
});
|
|
449
437
|
return {
|
|
450
438
|
...opened,
|
|
451
|
-
append: (...args) => opened.append(...args).pipe(
|
|
452
|
-
appendWithCheckpoint: (...args) => opened.appendWithCheckpoint(...args).pipe(
|
|
439
|
+
append: (...args) => opened.append(...args).pipe(Effect10.andThen(afterCommit)),
|
|
440
|
+
appendWithCheckpoint: (...args) => opened.appendWithCheckpoint(...args).pipe(Effect10.andThen(afterCommit))
|
|
453
441
|
};
|
|
454
442
|
};
|
|
455
443
|
const checkAccount = (instance) => {
|
|
@@ -464,44 +452,44 @@ async function createSqlExportingHost(options) {
|
|
|
464
452
|
checkAccount(coordinate.instance);
|
|
465
453
|
return journal([coordinate.actor, coordinate.instance, "thread", coordinate.thread, "events"], true);
|
|
466
454
|
},
|
|
467
|
-
close:
|
|
455
|
+
close: Effect10.gen(function* () {
|
|
468
456
|
for (const close of connections) yield* close;
|
|
469
457
|
connections.clear();
|
|
470
458
|
})
|
|
471
459
|
};
|
|
472
460
|
const allocations = Semaphore3.makeUnsafe(1);
|
|
473
|
-
const host = createThreadHost({ ...options, services: (coordinate, current) => options.services(coordinate, current).pipe(
|
|
474
|
-
const bootstrap = sqlJournal({ actor: "bootstrap", layer:
|
|
475
|
-
await
|
|
476
|
-
await
|
|
477
|
-
const flush = state.lock.withPermits(1)(
|
|
461
|
+
const host = createThreadHost({ ...options, services: (coordinate, current) => options.services(coordinate, current).pipe(Layer7.provideMerge(Layer7.succeed(SqlClient3.SqlClient, state.sql))), storage, actorContext: options.actorContext ?? ((context) => context) });
|
|
462
|
+
const bootstrap = sqlJournal({ actor: "bootstrap", layer: Layer7.succeed(SqlClient3.SqlClient, state.sql) });
|
|
463
|
+
await Effect10.runPromise(bootstrap.read);
|
|
464
|
+
await Effect10.runPromise(bootstrap.close);
|
|
465
|
+
const flush = state.lock.withPermits(1)(Effect10.scoped(Effect10.gen(function* () {
|
|
478
466
|
const rows = yield* state.sql`SELECT DISTINCT actor FROM experimental_events ORDER BY actor`;
|
|
479
467
|
const journals = rows.filter((row) => isThreadEventJournal(row.actor, options.actor.actorName, options.accountId));
|
|
480
468
|
const results = [];
|
|
481
469
|
if (journals.length === 0) return results;
|
|
482
|
-
const analytics =
|
|
470
|
+
const analytics = Context6.get(yield* Layer7.build(options.analytics), Analytics);
|
|
483
471
|
for (const row of journals) {
|
|
484
|
-
const result = yield*
|
|
472
|
+
const result = yield* Effect10.gen(function* () {
|
|
485
473
|
return yield* (yield* EventExporter).flush();
|
|
486
|
-
}).pipe(
|
|
474
|
+
}).pipe(Effect10.provide(sqlEventExporter({
|
|
487
475
|
accountId: options.accountId,
|
|
488
476
|
actor: options.actor.actorName,
|
|
489
477
|
sourceId: JSON.stringify([state.identity.generation, row.actor]),
|
|
490
478
|
destinationId: options.destinationId,
|
|
491
479
|
journal: row.actor,
|
|
492
480
|
...options.batchSize === void 0 ? {} : { batchSize: options.batchSize }
|
|
493
|
-
}).pipe(
|
|
481
|
+
}).pipe(Layer7.provide(Layer7.succeed(Analytics, analytics)))));
|
|
494
482
|
results.push(result);
|
|
495
483
|
}
|
|
496
484
|
return results;
|
|
497
|
-
})).pipe(
|
|
498
|
-
const worker = runtime.runFork(
|
|
485
|
+
})).pipe(Effect10.timeout(flushTimeoutMs)));
|
|
486
|
+
const worker = runtime.runFork(Effect10.forever(Effect10.gen(function* () {
|
|
499
487
|
yield* Queue.take(state.signals);
|
|
500
488
|
yield* flush.pipe(
|
|
501
|
-
|
|
489
|
+
Effect10.tap((results) => Effect10.sync(() => {
|
|
502
490
|
if (results.some((result) => result.hasMore)) signal();
|
|
503
491
|
})),
|
|
504
|
-
|
|
492
|
+
Effect10.catch((error) => Effect10.logWarning("Actor analytics export failed; the cursor is retained for the next flush.", { operation: error instanceof ExportError ? error.operation : "connection", flushTimeoutMs }))
|
|
505
493
|
);
|
|
506
494
|
})));
|
|
507
495
|
signal();
|
|
@@ -515,21 +503,21 @@ async function createSqlExportingHost(options) {
|
|
|
515
503
|
if (request.method !== "POST" || parts.length !== 5 || parts[1] !== "v1" || parts[2] !== "actors" || parts[4] !== "threads") return void 0;
|
|
516
504
|
const input = await request.json().catch(() => void 0);
|
|
517
505
|
const schema = Schema2.Struct({ name: Schema2.optionalKey(Schema2.NonEmptyString), parent: Schema2.optionalKey(Schema2.NonEmptyString) });
|
|
518
|
-
const work = allocations.withPermit(
|
|
519
|
-
const body = yield* Schema2.decodeUnknownEffect(schema)(input).pipe(
|
|
506
|
+
const work = allocations.withPermit(Effect10.gen(function* () {
|
|
507
|
+
const body = yield* Schema2.decodeUnknownEffect(schema)(input).pipe(Effect10.mapError(InvalidMessage.from));
|
|
520
508
|
const instance = decodeURIComponent(parts[3]);
|
|
521
509
|
if (body.name && (yield* host.getThread({ instance, thread: body.name }))) return Response.json({ code: "thread_exists", message: "Thread already exists." }, { status: 409 });
|
|
522
510
|
const name = body.name === void 0 ? {} : { name: body.name };
|
|
523
511
|
const thread = yield* body.parent === void 0 ? host.allocateRootThread({ instance, ...name }) : host.allocateChildThread({ parent: { actor: host.actor, instance, thread: body.parent }, ...name });
|
|
524
512
|
return Response.json(thread.coordinate);
|
|
525
513
|
}));
|
|
526
|
-
return
|
|
514
|
+
return Effect10.runPromise(work.pipe(Effect10.catch((error) => Effect10.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage ? 400 : 500 })))));
|
|
527
515
|
},
|
|
528
516
|
methodRequest: async (request) => {
|
|
529
517
|
const parts = new URL(request.url).pathname.split("/");
|
|
530
518
|
if (parts[1] !== "v1" || parts[2] !== "actors" || decodeURIComponent(parts[3] ?? "") !== options.accountId) return void 0;
|
|
531
519
|
if (request.method === "GET" && parts.length === 5 && parts[4] === "methods") {
|
|
532
|
-
const contracts = await
|
|
520
|
+
const contracts = await Effect10.runPromise(host.describe(options.accountId));
|
|
533
521
|
return Response.json({ items: Object.entries(contracts).map(([name, method]) => ({
|
|
534
522
|
name,
|
|
535
523
|
inputSchema: Tool2.getJsonSchemaFromSchema(method.inputSchema),
|
|
@@ -538,33 +526,33 @@ async function createSqlExportingHost(options) {
|
|
|
538
526
|
})) });
|
|
539
527
|
}
|
|
540
528
|
if (parts[4] === "threads" && parts[6] === "calls" && (request.method === "GET" && parts.length === 8 || request.method === "POST" && parts.length === 9 && parts[8] === "cancel")) {
|
|
541
|
-
const work2 =
|
|
529
|
+
const work2 = Effect10.gen(function* () {
|
|
542
530
|
const thread = yield* host.getThread({ instance: options.accountId, thread: decodeURIComponent(parts[5]) });
|
|
543
531
|
if (!thread) return new Response(null, { status: 404 });
|
|
544
532
|
const id2 = decodeURIComponent(parts[7]);
|
|
545
533
|
const call = yield* thread.call(id2);
|
|
546
534
|
if (!call) return new Response(null, { status: 404 });
|
|
547
535
|
if (request.method === "GET") return Response.json(call);
|
|
548
|
-
const input2 = yield*
|
|
549
|
-
const body = yield* Schema2.decodeUnknownEffect(Schema2.Struct({ reason: Schema2.String }), { onExcessProperty: "error" })(input2).pipe(
|
|
536
|
+
const input2 = yield* Effect10.tryPromise(() => request.json()).pipe(Effect10.mapError(InvalidMessage.from));
|
|
537
|
+
const body = yield* Schema2.decodeUnknownEffect(Schema2.Struct({ reason: Schema2.String }), { onExcessProperty: "error" })(input2).pipe(Effect10.mapError(InvalidMessage.from));
|
|
550
538
|
const receipt2 = yield* thread.cancel(call.method, id2, body.reason);
|
|
551
539
|
return Response.json(receipt2, { status: 202 });
|
|
552
540
|
});
|
|
553
|
-
return
|
|
541
|
+
return Effect10.runPromise(work2.pipe(Effect10.catch((error) => Effect10.succeed(Response.json({ error: error.message }, { status: error instanceof InvalidMessage ? 400 : error instanceof MessageConflict ? 409 : 500 })))));
|
|
554
542
|
}
|
|
555
543
|
if (request.method !== "POST" || parts.length !== 8 || parts[4] !== "threads" || parts[6] !== "methods") return void 0;
|
|
556
544
|
const id = request.headers.get("idempotency-key");
|
|
557
545
|
if (!id?.trim()) return Response.json({ error: "Idempotency-Key is required" }, { status: 400 });
|
|
558
546
|
const input = await request.json().catch(() => void 0);
|
|
559
|
-
const work =
|
|
547
|
+
const work = Effect10.gen(function* () {
|
|
560
548
|
const thread = yield* host.getThread({ instance: decodeURIComponent(parts[3]), thread: decodeURIComponent(parts[5]) });
|
|
561
549
|
const method = decodeURIComponent(parts[7]);
|
|
562
550
|
if (!thread || !Object.hasOwn(thread.methods, method)) return new Response(null, { status: 404 });
|
|
563
|
-
const body = yield* Schema2.decodeUnknownEffect(Schema2.Json)(input).pipe(
|
|
551
|
+
const body = yield* Schema2.decodeUnknownEffect(Schema2.Json)(input).pipe(Effect10.mapError(InvalidMessage.from));
|
|
564
552
|
const receipt2 = yield* thread.invoke(method, body, { id });
|
|
565
553
|
return Response.json(receipt2, { status: 202 });
|
|
566
554
|
});
|
|
567
|
-
return
|
|
555
|
+
return Effect10.runPromise(work.pipe(Effect10.catch((error) => Effect10.succeed(Response.json({ error: error.message }, { status: error instanceof MessageConflict ? 409 : error instanceof InvalidMessage ? 400 : 500 })))));
|
|
568
556
|
},
|
|
569
557
|
flushEvents: () => {
|
|
570
558
|
if (closed) return Promise.reject(new Error("Actor host is closed."));
|
|
@@ -576,16 +564,16 @@ async function createSqlExportingHost(options) {
|
|
|
576
564
|
try {
|
|
577
565
|
await mcp.close();
|
|
578
566
|
} finally {
|
|
579
|
-
await
|
|
567
|
+
await Effect10.runPromise(host.close);
|
|
580
568
|
}
|
|
581
569
|
} finally {
|
|
582
|
-
await
|
|
570
|
+
await Effect10.runPromise(Fiber2.interrupt(worker));
|
|
583
571
|
await runtime.dispose();
|
|
584
572
|
}
|
|
585
573
|
})()
|
|
586
574
|
};
|
|
587
575
|
} catch (error) {
|
|
588
|
-
for (const close of connections) await
|
|
576
|
+
for (const close of connections) await Effect10.runPromise(close);
|
|
589
577
|
await runtime.dispose();
|
|
590
578
|
throw error;
|
|
591
579
|
}
|
|
@@ -629,24 +617,24 @@ var eventsPage = (rows, query) => ({
|
|
|
629
617
|
});
|
|
630
618
|
|
|
631
619
|
// ../../src/platform/cloudflare/router.ts
|
|
632
|
-
import { Effect as
|
|
620
|
+
import { Effect as Effect15, Layer as Layer8 } from "effect";
|
|
633
621
|
|
|
634
622
|
// ../../src/services/actor-router.ts
|
|
635
|
-
import { Context as
|
|
623
|
+
import { Context as Context7, Data as Data4 } from "effect";
|
|
636
624
|
var ActorRouterError = class extends Data4.TaggedError("ActorRouterError") {
|
|
637
625
|
};
|
|
638
|
-
var ActorRouter = class extends
|
|
626
|
+
var ActorRouter = class extends Context7.Service()("tardigrade-cloud/ActorRouter") {
|
|
639
627
|
};
|
|
640
628
|
|
|
641
629
|
// ../../src/services/actor-runtime.ts
|
|
642
|
-
import { Context as
|
|
630
|
+
import { Context as Context8, Data as Data5 } from "effect";
|
|
643
631
|
var ActorRuntimeError = class extends Data5.TaggedError("ActorRuntimeError") {
|
|
644
632
|
};
|
|
645
|
-
var ActorRuntime = class extends
|
|
633
|
+
var ActorRuntime = class extends Context8.Service()("tardigrade-cloud/ActorRuntime") {
|
|
646
634
|
};
|
|
647
635
|
|
|
648
636
|
// ../../src/services/metadata-store.ts
|
|
649
|
-
import { Context as
|
|
637
|
+
import { Context as Context9, Data as Data6, Schema as Schema3 } from "effect";
|
|
650
638
|
var Actor = Schema3.Struct({
|
|
651
639
|
name: Schema3.NonEmptyString,
|
|
652
640
|
description: Schema3.String
|
|
@@ -666,11 +654,11 @@ var VersionRecord = Schema3.Struct({
|
|
|
666
654
|
}).annotate({ identifier: "VersionRecord" });
|
|
667
655
|
var MetadataStoreError = class extends Data6.TaggedError("MetadataStoreError") {
|
|
668
656
|
};
|
|
669
|
-
var MetadataStore = class extends
|
|
657
|
+
var MetadataStore = class extends Context9.Service()("tardigrade-cloud/MetadataStore") {
|
|
670
658
|
};
|
|
671
659
|
|
|
672
660
|
// ../../src/platform/router.ts
|
|
673
|
-
import { Effect as
|
|
661
|
+
import { Effect as Effect14, Option as Option2 } from "effect";
|
|
674
662
|
|
|
675
663
|
// ../../src/platform/cloudflare/router.ts
|
|
676
664
|
var actorObjectName = (address) => JSON.stringify([address.accountId, address.actorName]);
|
|
@@ -732,7 +720,7 @@ var cloudflareActorObject = (options) => class {
|
|
|
732
720
|
if (!Number.isSafeInteger(pageSize) || pageSize < 1) throw new Error("Event page size must be a positive integer.");
|
|
733
721
|
if (request.method === "GET" && parts.length === 7 && parts[6] === "events") {
|
|
734
722
|
const thread = decodeURIComponent(parts[5]);
|
|
735
|
-
if (!await
|
|
723
|
+
if (!await Effect16.runPromise(this.active.host.getThread({ instance: accountId, thread }))) return new Response(null, { status: 404 });
|
|
736
724
|
const query = parseEventsQuery(url.searchParams, pageSize);
|
|
737
725
|
if (!query) return new Response(null, { status: 400 });
|
|
738
726
|
const statement = eventsStatement(JSON.stringify([actorName, accountId, "thread", thread, "events"]), query);
|
|
@@ -741,13 +729,13 @@ var cloudflareActorObject = (options) => class {
|
|
|
741
729
|
if (request.method === "GET" && parts.length === 5 && parts[4] === "threads") {
|
|
742
730
|
const cursor = Number(url.searchParams.get("cursor") ?? 0);
|
|
743
731
|
if (!Number.isSafeInteger(cursor) || cursor < 0) return new Response(null, { status: 400 });
|
|
744
|
-
const store = await
|
|
732
|
+
const store = await Effect16.runPromise(this.active.host.supervisorStore(accountId));
|
|
745
733
|
const threads = store.threads.get().filter((thread) => thread.status === "registered");
|
|
746
734
|
return Response.json({ items: threads.slice(cursor, cursor + pageSize).map((thread) => ({ id: thread.coordinate.thread, ...thread.parent ? { parent: thread.parent } : {} })), ...cursor + pageSize < threads.length ? { cursor: String(cursor + pageSize) } : {} });
|
|
747
735
|
}
|
|
748
736
|
if (request.method === "POST" && parts.length === 5 && parts[4] === "threads") {
|
|
749
737
|
const input = await request.clone().json().catch(() => null);
|
|
750
|
-
if (typeof input?.name === "string" && await
|
|
738
|
+
if (typeof input?.name === "string" && await Effect16.runPromise(this.active.host.getThread({ instance: accountId, thread: input.name }))) return Response.json({ code: "thread_exists", message: "Thread already exists." }, { status: 409 });
|
|
751
739
|
}
|
|
752
740
|
return await this.active.host.allocationRequest(request.clone()) ?? await this.active.host.methodRequest(request.clone()) ?? await this.active.host.mcpRequest(request.clone()) ?? this.active.app.handler(request);
|
|
753
741
|
}
|
|
@@ -768,12 +756,11 @@ var createActorWorker = (actor, DurableObject, services, actorContext) => {
|
|
|
768
756
|
actor,
|
|
769
757
|
...actorContext ? { actorContext } : {},
|
|
770
758
|
services: (coordinate, runtime) => {
|
|
771
|
-
const platform =
|
|
759
|
+
const platform = Layer9.mergeAll(
|
|
772
760
|
ConfigProvider.layer(ConfigProvider.fromUnknown(secrets(env.SECRETS))),
|
|
773
|
-
boundAiGateway(deployment.accountId, env.INFERENCE)
|
|
774
|
-
boundContainerService(env.WORKSPACE, coordinate.thread)
|
|
761
|
+
boundAiGateway(deployment.accountId, env.INFERENCE)
|
|
775
762
|
);
|
|
776
|
-
return services ? services(runtime, coordinate).pipe(
|
|
763
|
+
return services ? services(runtime, coordinate).pipe(Layer9.provideMerge(platform)) : platform;
|
|
777
764
|
},
|
|
778
765
|
analytics: cloudflareAnalytics(deployment.accountId, env.ANALYTICS),
|
|
779
766
|
destinationId: "aurora",
|