apps 1.0.0-beta.3 → 2.0.0-next.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/README.md +10 -48
- package/check-publish.mjs +7 -0
- package/package.json +27 -56
- package/src/Access.ts +37 -0
- package/src/Accounts.ts +468 -0
- package/src/App.ts +11 -0
- package/src/Ask.ts +156 -0
- package/src/Changes.ts +13 -0
- package/src/Http.ts +30 -0
- package/src/Provider.ts +146 -0
- package/src/Session.ts +52 -0
- package/src/Settings.ts +164 -0
- package/src/contract.ts +852 -0
- package/src/css-modules.d.ts +2 -0
- package/src/desktop/Desktop.ts +192 -0
- package/src/desktop/bridge.ts +62 -0
- package/src/desktop/errors.ts +88 -0
- package/src/desktop/index.ts +15 -0
- package/src/entry.ts +48 -0
- package/src/index.ts +16 -4
- package/src/internal/defects.ts +62 -0
- package/src/internal/files.ts +369 -0
- package/src/internal/host.ts +17 -0
- package/src/internal/query.ts +114 -0
- package/src/internal/records.ts +838 -0
- package/src/internal/retention.ts +87 -0
- package/src/internal/retries.ts +185 -0
- package/src/internal/telemetry.ts +167 -0
- package/src/migrations.ts +110 -0
- package/src/page/Accounts.ts +27 -0
- package/src/page/Changes.ts +126 -0
- package/src/page/Session.ts +46 -0
- package/src/page/client.ts +107 -0
- package/src/page/errors.ts +15 -0
- package/src/page/http.ts +21 -0
- package/src/page/index.ts +18 -0
- package/src/page/paths.ts +22 -0
- package/src/providers/anthropic.ts +26 -0
- package/src/providers/github.ts +49 -0
- package/src/providers/google.ts +67 -0
- package/src/providers/openai.ts +62 -0
- package/src/providers/slack.ts +81 -0
- package/src/runtime.ts +1540 -0
- package/src/testing.ts +660 -0
- package/src/text-modules.d.ts +5 -0
- package/src/theme.css +50 -0
- package/dist/authoring/index.d.ts +0 -393
- package/dist/authoring/index.js +0 -36
- package/dist/chunk-4OZFMCTT.js +0 -17
- package/dist/chunk-A3H32P2J.js +0 -143
- package/dist/chunk-B7NEUIJL.js +0 -14
- package/dist/chunk-F7GZYEAC.js +0 -41
- package/dist/chunk-MUFMJRXR.js +0 -308
- package/dist/chunk-S5KFP4JQ.js +0 -20
- package/dist/chunk-Y6LLTN7W.js +0 -99
- package/dist/chunk-YUZ4TXOY.js +0 -27
- package/dist/http/index.d.ts +0 -9
- package/dist/http/index.js +0 -6
- package/dist/index.d.ts +0 -4
- package/dist/index.js +0 -48
- package/dist/manifest/contract.d.ts +0 -63
- package/dist/manifest/contract.js +0 -8
- package/dist/manifest/index.d.ts +0 -20
- package/dist/manifest/index.js +0 -16
- package/dist/mcp/client.d.ts +0 -9
- package/dist/mcp/index.d.ts +0 -11
- package/dist/mcp/index.js +0 -7
- package/dist/openapi/index.d.ts +0 -14
- package/dist/openapi/index.js +0 -7
- package/dist/openapi/mapper.d.ts +0 -7
- package/dist/runner/index.d.ts +0 -4
- package/dist/runner/index.js +0 -66
- package/dist/runner/protocol.d.ts +0 -33
- package/dist/runner/protocol.js +0 -8
- package/dist/runtime/index.d.ts +0 -83
- package/dist/runtime/index.js +0 -12
- package/dist/workerd/index.d.ts +0 -7
- package/dist/workerd/index.js +0 -10
- package/src/authoring/index.ts +0 -658
- package/src/http/index.ts +0 -26
- package/src/manifest/contract.ts +0 -64
- package/src/manifest/index.ts +0 -156
- package/src/mcp/client.ts +0 -59
- package/src/mcp/index.ts +0 -42
- package/src/openapi/index.ts +0 -70
- package/src/openapi/mapper.ts +0 -25
- package/src/runner/index.ts +0 -80
- package/src/runner/protocol.ts +0 -54
- package/src/runtime/index.ts +0 -550
- package/src/workerd/index.ts +0 -17
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Retention of ended runs in the app's own database, through Effect's own
|
|
3
|
+
* `MessageStorage`. Without it every scheduled run and every workflow
|
|
4
|
+
* execution stays in `cluster_messages` and `cluster_replies` for good.
|
|
5
|
+
*
|
|
6
|
+
* - A scheduled run (`ClusterCron`) completed longer ago than
|
|
7
|
+
* {@link SCHEDULED_RUN_RETENTION}: `MessageStorage.deleteProcessed`.
|
|
8
|
+
* - A workflow run that ended longer ago than {@link WORKFLOW_RUN_RETENTION}:
|
|
9
|
+
* `MessageStorage.clearAddress` for the workflow and its clock. A run that
|
|
10
|
+
* is asleep, waiting or retrying has not ended and is never touched.
|
|
11
|
+
*
|
|
12
|
+
* When a workflow run ended is the `ended_at` of its row in `apps_runs`, which
|
|
13
|
+
* the records recorder keeps with the run's payload. Once Effect's rows for a
|
|
14
|
+
* run are cleared its `apps_runs` row goes too, so "run again" is offered for
|
|
15
|
+
* exactly as long as it can work. Pruning is a bounded step inside `wake()`,
|
|
16
|
+
* never a timer.
|
|
17
|
+
*/
|
|
18
|
+
import { Clock, Duration, Effect } from "effect";
|
|
19
|
+
import { EntityAddress, EntityId, EntityType, MessageStorage, ShardId } from "effect/cluster";
|
|
20
|
+
import { SqlClient } from "effect/sql";
|
|
21
|
+
import { RUNS_TABLE } from "./records.ts";
|
|
22
|
+
|
|
23
|
+
/** How long a completed scheduled run is kept. */
|
|
24
|
+
export const SCHEDULED_RUN_RETENTION = Duration.days(1);
|
|
25
|
+
/** How long a workflow run is kept after it ended. */
|
|
26
|
+
export const WORKFLOW_RUN_RETENTION = Duration.days(30);
|
|
27
|
+
/** At most this many of each kind are pruned per wake. */
|
|
28
|
+
export const PRUNE_LIMIT = 100;
|
|
29
|
+
|
|
30
|
+
const CLOCK_ENTITY = "Workflow/-/DurableClock";
|
|
31
|
+
|
|
32
|
+
export interface Periods {
|
|
33
|
+
readonly scheduledMs: number;
|
|
34
|
+
readonly workflowMs: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const defaultPeriods: Periods = {
|
|
38
|
+
scheduledMs: Duration.toMillis(SCHEDULED_RUN_RETENTION),
|
|
39
|
+
workflowMs: Duration.toMillis(WORKFLOW_RUN_RETENTION),
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** One bounded pruning step. Returns how many runs of each kind it removed, and which workflow runs. */
|
|
43
|
+
export const prune = (periods: Periods = defaultPeriods) =>
|
|
44
|
+
Effect.gen(function* () {
|
|
45
|
+
const sql = yield* SqlClient.SqlClient;
|
|
46
|
+
const storage = yield* MessageStorage.MessageStorage;
|
|
47
|
+
const now = yield* Clock.currentTimeMillis;
|
|
48
|
+
let scheduled = 0;
|
|
49
|
+
const jobs = yield* sql<{ entity_type: string }>`
|
|
50
|
+
SELECT DISTINCT entity_type FROM cluster_messages WHERE entity_type LIKE 'ClusterCron/%'`;
|
|
51
|
+
for (const { entity_type } of jobs) {
|
|
52
|
+
scheduled += yield* storage.deleteProcessed({
|
|
53
|
+
entityType: entity_type,
|
|
54
|
+
completedBefore: now - periods.scheduledMs,
|
|
55
|
+
limit: PRUNE_LIMIT,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
const tables = yield* sql<{ n: number }>`
|
|
59
|
+
SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = ${RUNS_TABLE}`;
|
|
60
|
+
const ended =
|
|
61
|
+
tables[0]!.n === 0
|
|
62
|
+
? []
|
|
63
|
+
: yield* sql<{ workflow: string; execution_id: string }>`
|
|
64
|
+
SELECT workflow, execution_id FROM ${sql(RUNS_TABLE)}
|
|
65
|
+
WHERE ended_at IS NOT NULL AND ended_at < ${now - periods.workflowMs} LIMIT ${PRUNE_LIMIT}`;
|
|
66
|
+
for (const { workflow, execution_id } of ended) {
|
|
67
|
+
const entityId = EntityId.make(execution_id);
|
|
68
|
+
for (const type of [`Workflow/${workflow}`, CLOCK_ENTITY]) {
|
|
69
|
+
const shards = yield* sql<{ shard_id: string }>`
|
|
70
|
+
SELECT DISTINCT shard_id FROM cluster_messages WHERE entity_type = ${type} AND entity_id = ${execution_id}`;
|
|
71
|
+
for (const { shard_id } of shards)
|
|
72
|
+
yield* storage.clearAddress(
|
|
73
|
+
EntityAddress.make({
|
|
74
|
+
entityType: EntityType.make(type),
|
|
75
|
+
entityId,
|
|
76
|
+
shardId: ShardId.fromString(shard_id),
|
|
77
|
+
}),
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
yield* sql`DELETE FROM ${sql(RUNS_TABLE)} WHERE workflow = ${workflow} AND execution_id = ${execution_id}`;
|
|
81
|
+
}
|
|
82
|
+
return {
|
|
83
|
+
scheduled,
|
|
84
|
+
workflows: ended.length,
|
|
85
|
+
removed: ended.map(({ workflow, execution_id }) => ({ workflow, executionId: execution_id })),
|
|
86
|
+
};
|
|
87
|
+
});
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A record of entity requests that failed with a defect and that Effect will
|
|
3
|
+
* run again, so the app can go idle in between and a new copy of it behaves
|
|
4
|
+
* like one that was never stopped.
|
|
5
|
+
*
|
|
6
|
+
* Effect retries a request that dies (a scheduled job whose body fails, for
|
|
7
|
+
* one) by restarting its entity after `min(exponential(500 ms, 1.5), 10 s)`, a
|
|
8
|
+
* delay it keeps only in memory. While it restarts, the entity takes nothing
|
|
9
|
+
* else from its mailbox. This record keeps that in the app's database:
|
|
10
|
+
*
|
|
11
|
+
* - the failed request's delay, so it is not due work, its retry time is the
|
|
12
|
+
* next wake, and a new copy waits it out instead of running it at once;
|
|
13
|
+
* - the attempt count, so a new copy's restart delay continues Effect's
|
|
14
|
+
* backoff instead of starting it over (`restartPolicy`);
|
|
15
|
+
* - that the entity is busy, so its other requests (a job's next slot) wait
|
|
16
|
+
* behind the failed one, as they do in its mailbox.
|
|
17
|
+
*
|
|
18
|
+
* What Effect does is not changed: the delays are its own, read back.
|
|
19
|
+
*/
|
|
20
|
+
import { Cause, Duration, Effect, Exit, Schedule } from "effect";
|
|
21
|
+
|
|
22
|
+
const TABLE = "apps_retry_delays";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The SQL condition, on a record `r`, that its request is still waiting: a request that was
|
|
26
|
+
* cancelled, or ended some other way, leaves its record behind and must not hold anything.
|
|
27
|
+
*/
|
|
28
|
+
const LIVE = `EXISTS (SELECT 1 FROM cluster_messages m WHERE m.request_id = CAST(r.request_id AS INTEGER) AND m.processed = 0)`;
|
|
29
|
+
|
|
30
|
+
/** Effect's default entity restart delay after `attempts` failures in a row. */
|
|
31
|
+
export const delayAfter = (attempts: number): number =>
|
|
32
|
+
Math.min(500 * 1.5 ** Math.max(0, attempts - 1), 10_000);
|
|
33
|
+
|
|
34
|
+
export const ensureTable = (sql: SqlStorage) =>
|
|
35
|
+
sql.exec(
|
|
36
|
+
`CREATE TABLE IF NOT EXISTS ${TABLE} (entity_type TEXT NOT NULL, entity_id TEXT NOT NULL, request_id TEXT NOT NULL, attempts INTEGER NOT NULL, retry_at INTEGER NOT NULL, PRIMARY KEY (entity_type, entity_id, request_id))`,
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Requests that failed in this copy: Effect restarts their entity and runs them again from
|
|
41
|
+
* memory, so a storage read must not deliver them too. A new copy starts with none, and its read
|
|
42
|
+
* is what delivers them again.
|
|
43
|
+
*/
|
|
44
|
+
const failedHere = new WeakMap<SqlStorage, Set<string>>();
|
|
45
|
+
/** The retry time of the failure this copy recorded last, by entity type: the next restart's. */
|
|
46
|
+
const lastRetryAt = new WeakMap<SqlStorage, Map<string, number>>();
|
|
47
|
+
const requestKey = (type: string, id: string, request: string) =>
|
|
48
|
+
`${type}\u0000${id}\u0000${request}`;
|
|
49
|
+
|
|
50
|
+
const recordFailure = (sql: SqlStorage, type: string, id: string, request: string, now: number) => {
|
|
51
|
+
const here = failedHere.get(sql) ?? new Set<string>();
|
|
52
|
+
here.add(requestKey(type, id, request));
|
|
53
|
+
failedHere.set(sql, here);
|
|
54
|
+
const previous = sql
|
|
55
|
+
.exec<{ attempts: number }>(
|
|
56
|
+
`SELECT attempts FROM ${TABLE} WHERE entity_type = ? AND entity_id = ? AND request_id = ?`,
|
|
57
|
+
type,
|
|
58
|
+
id,
|
|
59
|
+
request,
|
|
60
|
+
)
|
|
61
|
+
.toArray()[0]?.attempts;
|
|
62
|
+
const attempts = (previous ?? 0) + 1;
|
|
63
|
+
const retryAt = now + delayAfter(attempts);
|
|
64
|
+
const last = lastRetryAt.get(sql) ?? new Map<string, number>();
|
|
65
|
+
last.set(type, retryAt);
|
|
66
|
+
lastRetryAt.set(sql, last);
|
|
67
|
+
sql.exec(
|
|
68
|
+
`INSERT OR REPLACE INTO ${TABLE} (entity_type, entity_id, request_id, attempts, retry_at) VALUES (?, ?, ?, ?, ?)`,
|
|
69
|
+
type,
|
|
70
|
+
id,
|
|
71
|
+
request,
|
|
72
|
+
attempts,
|
|
73
|
+
retryAt,
|
|
74
|
+
);
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const clear = (sql: SqlStorage, type: string, id: string, request: string) => {
|
|
78
|
+
failedHere.get(sql)?.delete(requestKey(type, id, request));
|
|
79
|
+
sql.exec(
|
|
80
|
+
`DELETE FROM ${TABLE} WHERE entity_type = ? AND entity_id = ? AND request_id = ?`,
|
|
81
|
+
type,
|
|
82
|
+
id,
|
|
83
|
+
request,
|
|
84
|
+
);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Why a stored request must not be delivered now, if it must not:
|
|
89
|
+
* - `here`: it failed in this copy, which runs it again itself;
|
|
90
|
+
* - `later`: it failed and its delay has not run out, or it waits behind its entity's failed
|
|
91
|
+
* request. A later read must see it again, so its claim is released.
|
|
92
|
+
*/
|
|
93
|
+
export const hold = (
|
|
94
|
+
sql: SqlStorage,
|
|
95
|
+
type: string,
|
|
96
|
+
id: string,
|
|
97
|
+
request: string,
|
|
98
|
+
now: number,
|
|
99
|
+
): "here" | "later" | undefined => {
|
|
100
|
+
if (failedHere.get(sql)?.has(requestKey(type, id, request)) === true) return "here";
|
|
101
|
+
const failed = sql
|
|
102
|
+
.exec<{ request_id: string; retry_at: number }>(
|
|
103
|
+
`SELECT r.request_id, r.retry_at FROM ${TABLE} r WHERE r.entity_type = ? AND r.entity_id = ? AND ${LIVE}`,
|
|
104
|
+
type,
|
|
105
|
+
id,
|
|
106
|
+
)
|
|
107
|
+
.toArray();
|
|
108
|
+
if (failed.length === 0) return undefined;
|
|
109
|
+
const own = failed.find((row) => row.request_id === request);
|
|
110
|
+
if (own === undefined) return "later";
|
|
111
|
+
return Number(own.retry_at) > now ? "later" : undefined;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The SQL condition, on `cluster_messages`, for a message that is not due because of a failure:
|
|
116
|
+
* its own delay has not run out (`?`, now), or it waits behind its entity's failed request.
|
|
117
|
+
*/
|
|
118
|
+
export const retryingWhere = `EXISTS (SELECT 1 FROM ${TABLE} r WHERE r.entity_type = cluster_messages.entity_type AND r.entity_id = cluster_messages.entity_id AND ${LIVE} AND (r.retry_at > ? OR r.request_id <> CAST(cluster_messages.request_id AS TEXT)))`;
|
|
119
|
+
|
|
120
|
+
/** The earliest pending retry, in epoch milliseconds. */
|
|
121
|
+
export const nextRetry = (sql: SqlStorage, now: number): number | null => {
|
|
122
|
+
const at = sql
|
|
123
|
+
.exec<{ at: number | null }>(
|
|
124
|
+
`SELECT min(r.retry_at) AS at FROM ${TABLE} r WHERE r.retry_at > ? AND ${LIVE}`,
|
|
125
|
+
now,
|
|
126
|
+
)
|
|
127
|
+
.one().at;
|
|
128
|
+
return at === null ? null : Number(at);
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Wrap an entity's handlers so each request's outcome is recorded: a defect counts an attempt,
|
|
133
|
+
* anything but an interruption clears the record.
|
|
134
|
+
*/
|
|
135
|
+
export const observe = (
|
|
136
|
+
sql: SqlStorage,
|
|
137
|
+
entityType: string,
|
|
138
|
+
entityId: string,
|
|
139
|
+
handlers: Record<string, unknown>,
|
|
140
|
+
): Record<string, unknown> => {
|
|
141
|
+
const wrapped: Record<string, unknown> = {};
|
|
142
|
+
for (const [tag, handler] of Object.entries(handlers)) {
|
|
143
|
+
wrapped[tag] =
|
|
144
|
+
typeof handler !== "function"
|
|
145
|
+
? handler
|
|
146
|
+
: (
|
|
147
|
+
payload: unknown,
|
|
148
|
+
metadata: { readonly requestId: unknown },
|
|
149
|
+
...rest: Array<unknown>
|
|
150
|
+
) => {
|
|
151
|
+
const result: unknown = handler(payload, metadata, ...rest);
|
|
152
|
+
if (!Effect.isEffect(result)) return result;
|
|
153
|
+
const request = String(metadata.requestId);
|
|
154
|
+
return Effect.onExit(result, (exit) =>
|
|
155
|
+
Effect.sync(() => {
|
|
156
|
+
if (Exit.isFailure(exit) && Cause.hasDies(exit.cause)) {
|
|
157
|
+
recordFailure(sql, entityType, entityId, request, Date.now());
|
|
158
|
+
} else if (Exit.isSuccess(exit) || !Cause.hasInterruptsOnly(exit.cause)) {
|
|
159
|
+
clear(sql, entityType, entityId, request);
|
|
160
|
+
}
|
|
161
|
+
}),
|
|
162
|
+
);
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
return wrapped;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Effect's entity restart policy, continued from the record instead of from the start: the delay
|
|
170
|
+
* before restarting an entity of `type` after a defect is what is left of the delay this copy
|
|
171
|
+
* just recorded for it (whose attempt count carries over from earlier copies), so a new copy does
|
|
172
|
+
* not retry sooner than one left running would. With none (a handler that failed to build), it
|
|
173
|
+
* is Effect's own delay for that attempt.
|
|
174
|
+
*/
|
|
175
|
+
export const restartPolicy = (sql: SqlStorage, type: string) =>
|
|
176
|
+
Schedule.forever.pipe(
|
|
177
|
+
Schedule.modifyDelay(({ attempt }) =>
|
|
178
|
+
Effect.sync(() => {
|
|
179
|
+
const at = lastRetryAt.get(sql)?.get(type);
|
|
180
|
+
return Duration.millis(
|
|
181
|
+
at === undefined ? delayAfter(attempt) : Math.max(0, at - Date.now()),
|
|
182
|
+
);
|
|
183
|
+
}),
|
|
184
|
+
),
|
|
185
|
+
);
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Tracer` and `Logger` that batch to the host's `telemetry` capability.
|
|
3
|
+
* Spans are recorded by Effect's own native tracer and copied out when they end.
|
|
4
|
+
* The runtime flushes after each entry point and when it closes.
|
|
5
|
+
*/
|
|
6
|
+
import { Cause, Context, Exit, Layer, Logger, Option, Tracer } from "effect";
|
|
7
|
+
import * as References from "effect/References";
|
|
8
|
+
import type { HostTelemetry, LogRecord, SpanRecord, TelemetryBatch } from "../contract.ts";
|
|
9
|
+
|
|
10
|
+
const plain = (value: unknown): unknown => {
|
|
11
|
+
if (
|
|
12
|
+
value === null ||
|
|
13
|
+
typeof value === "string" ||
|
|
14
|
+
typeof value === "number" ||
|
|
15
|
+
typeof value === "boolean"
|
|
16
|
+
)
|
|
17
|
+
return value;
|
|
18
|
+
if (typeof value === "bigint") return value.toString();
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(JSON.stringify(value));
|
|
21
|
+
} catch {
|
|
22
|
+
return String(value);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const record = (map: Iterable<readonly [string, unknown]>) => {
|
|
27
|
+
const out: Record<string, unknown> = {};
|
|
28
|
+
for (const [k, v] of map) out[k] = plain(v);
|
|
29
|
+
return out;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const MAX_ERROR_MESSAGE = 2_000;
|
|
33
|
+
|
|
34
|
+
/** OpenTelemetry's `error.type` and `exception.message` for a span that failed, so its trace says why. */
|
|
35
|
+
const failureAttributes = (exit: Exit.Exit<unknown, unknown>): Record<string, string> => {
|
|
36
|
+
if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return {};
|
|
37
|
+
const failure = Cause.squash(exit.cause);
|
|
38
|
+
const tagged = failure as {
|
|
39
|
+
readonly _tag?: unknown;
|
|
40
|
+
readonly name?: unknown;
|
|
41
|
+
readonly message?: unknown;
|
|
42
|
+
};
|
|
43
|
+
const type =
|
|
44
|
+
typeof tagged?._tag === "string"
|
|
45
|
+
? tagged._tag
|
|
46
|
+
: typeof tagged?.name === "string"
|
|
47
|
+
? tagged.name
|
|
48
|
+
: typeof failure;
|
|
49
|
+
const message = typeof tagged?.message === "string" ? tagged.message : String(plain(failure));
|
|
50
|
+
return { "error.type": type, "exception.message": message.slice(0, MAX_ERROR_MESSAGE) };
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export interface TelemetryBuffer {
|
|
54
|
+
readonly layer: Layer.Layer<never>;
|
|
55
|
+
readonly take: () => TelemetryBatch | undefined;
|
|
56
|
+
/** A log line from the runtime itself (the runner started or closed). */
|
|
57
|
+
readonly note: (message: string, annotations?: Record<string, unknown>) => void;
|
|
58
|
+
readonly flush: (sink: HostTelemetry | undefined) => Promise<void>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** At most this many spans, and this many log lines, wait for the host; past it the oldest are dropped and counted: the end of a burst is what usually explains a failure. */
|
|
62
|
+
export const MAX_BUFFERED = 2_000;
|
|
63
|
+
|
|
64
|
+
export const makeTelemetry = (options: { readonly maxBuffered?: number } = {}): TelemetryBuffer => {
|
|
65
|
+
const max = options.maxBuffered ?? MAX_BUFFERED;
|
|
66
|
+
let spans: Array<SpanRecord> = [];
|
|
67
|
+
let logs: Array<LogRecord> = [];
|
|
68
|
+
let dropped = 0;
|
|
69
|
+
|
|
70
|
+
const tracer = Tracer.make({
|
|
71
|
+
span(options) {
|
|
72
|
+
const span = Tracer.nativeTracer.span(options);
|
|
73
|
+
const events: Array<SpanRecord["events"][number]> = [];
|
|
74
|
+
const event = span.event.bind(span);
|
|
75
|
+
const end = span.end.bind(span);
|
|
76
|
+
span.event = (name, time, attributes) => {
|
|
77
|
+
events.push({
|
|
78
|
+
name,
|
|
79
|
+
time: time.toString(),
|
|
80
|
+
attributes: record(Object.entries(attributes ?? {})),
|
|
81
|
+
});
|
|
82
|
+
event(name, time, attributes);
|
|
83
|
+
};
|
|
84
|
+
span.end = (endTime, exit) => {
|
|
85
|
+
end(endTime, exit);
|
|
86
|
+
if (spans.length >= max) {
|
|
87
|
+
spans.shift();
|
|
88
|
+
dropped += 1;
|
|
89
|
+
}
|
|
90
|
+
const parent = Option.getOrUndefined(span.parent);
|
|
91
|
+
spans.push({
|
|
92
|
+
traceId: span.traceId,
|
|
93
|
+
spanId: span.spanId,
|
|
94
|
+
parentSpanId: parent?.spanId ?? null,
|
|
95
|
+
name: span.name,
|
|
96
|
+
kind: span.kind,
|
|
97
|
+
startTime: options.startTime.toString(),
|
|
98
|
+
endTime: endTime.toString(),
|
|
99
|
+
status: Exit.isSuccess(exit)
|
|
100
|
+
? "ok"
|
|
101
|
+
: Cause.hasInterruptsOnly(exit.cause)
|
|
102
|
+
? "interrupted"
|
|
103
|
+
: "error",
|
|
104
|
+
attributes: { ...record(span.attributes), ...failureAttributes(exit) },
|
|
105
|
+
events,
|
|
106
|
+
});
|
|
107
|
+
};
|
|
108
|
+
return span;
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const logger = Logger.make((options) => {
|
|
113
|
+
if (logs.length >= max) {
|
|
114
|
+
logs.shift();
|
|
115
|
+
dropped += 1;
|
|
116
|
+
}
|
|
117
|
+
const span = Option.getOrUndefined(Context.getOption(options.fiber.context, Tracer.ParentSpan));
|
|
118
|
+
const message = Array.isArray(options.message) ? options.message : [options.message];
|
|
119
|
+
logs.push({
|
|
120
|
+
time: options.date.getTime(),
|
|
121
|
+
level: options.logLevel === "All" || options.logLevel === "None" ? "Info" : options.logLevel,
|
|
122
|
+
message: message
|
|
123
|
+
.map(plain)
|
|
124
|
+
.concat(options.cause.reasons.length === 0 ? [] : [Cause.pretty(options.cause)]),
|
|
125
|
+
annotations: record(Object.entries(options.fiber.getRef(References.CurrentLogAnnotations))),
|
|
126
|
+
traceId: span?.traceId ?? null,
|
|
127
|
+
spanId: span?.spanId ?? null,
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
const take = () => {
|
|
132
|
+
if (spans.length === 0 && logs.length === 0 && dropped === 0) return undefined;
|
|
133
|
+
const batch = { spans, logs, dropped };
|
|
134
|
+
spans = [];
|
|
135
|
+
logs = [];
|
|
136
|
+
dropped = 0;
|
|
137
|
+
return batch;
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const note = (message: string, annotations: Record<string, unknown> = {}) => {
|
|
141
|
+
if (logs.length >= max) {
|
|
142
|
+
logs.shift();
|
|
143
|
+
dropped += 1;
|
|
144
|
+
}
|
|
145
|
+
logs.push({
|
|
146
|
+
time: Date.now(),
|
|
147
|
+
level: "Info",
|
|
148
|
+
message: [message],
|
|
149
|
+
annotations: { "apps.runtime": true, ...annotations },
|
|
150
|
+
traceId: null,
|
|
151
|
+
spanId: null,
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
note,
|
|
157
|
+
layer: Layer.mergeAll(
|
|
158
|
+
Layer.succeed(Tracer.Tracer, tracer),
|
|
159
|
+
Logger.layer([logger, Logger.consolePretty()]),
|
|
160
|
+
),
|
|
161
|
+
take,
|
|
162
|
+
flush: async (sink) => {
|
|
163
|
+
const batch = take();
|
|
164
|
+
if (batch !== undefined && sink !== undefined) await sink.export(batch);
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
};
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/** Migrations as the build step and `apps/testing` load them. No runtime imports. */
|
|
2
|
+
import { Effect } from "effect";
|
|
3
|
+
import { SqlClient } from "effect/sql";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A `.sql` migration file, run as one script. On Executor the app's database is a Durable
|
|
7
|
+
* Object's SQLite, whose `exec` runs every statement in the text.
|
|
8
|
+
*/
|
|
9
|
+
export const sqlMigration = (text: string): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
|
10
|
+
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => Effect.asVoid(sql.unsafe(text).raw));
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The statements of a SQL script, split where SQLite itself would end each one
|
|
14
|
+
* (`sqlite3_complete`'s rule): at a semicolon outside quotes, identifiers and comments, and,
|
|
15
|
+
* inside `CREATE TRIGGER`, only at `; END ;`. Comments and blank text between statements are
|
|
16
|
+
* dropped.
|
|
17
|
+
*/
|
|
18
|
+
export const sqlStatements = (text: string): Array<string> => {
|
|
19
|
+
const statements: Array<string> = [];
|
|
20
|
+
let start = 0;
|
|
21
|
+
let i = 0;
|
|
22
|
+
let words: Array<string> = [];
|
|
23
|
+
let trigger = false;
|
|
24
|
+
let afterSemicolon = false;
|
|
25
|
+
let afterEnd = false;
|
|
26
|
+
const end = (at: number) => {
|
|
27
|
+
const statement = text.slice(start, at).trim();
|
|
28
|
+
if (statement.replace(/;\s*$/u, "").trim() !== "") statements.push(statement);
|
|
29
|
+
start = at;
|
|
30
|
+
words = [];
|
|
31
|
+
trigger = false;
|
|
32
|
+
afterSemicolon = false;
|
|
33
|
+
afterEnd = false;
|
|
34
|
+
};
|
|
35
|
+
while (i < text.length) {
|
|
36
|
+
const c = text[i]!;
|
|
37
|
+
if (c === "-" && text[i + 1] === "-") {
|
|
38
|
+
const newline = text.indexOf("\n", i);
|
|
39
|
+
i = newline === -1 ? text.length : newline + 1;
|
|
40
|
+
if (words.length === 0) start = i;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (c === "/" && text[i + 1] === "*") {
|
|
44
|
+
const close = text.indexOf("*/", i + 2);
|
|
45
|
+
i = close === -1 ? text.length : close + 2;
|
|
46
|
+
if (words.length === 0) start = i;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (c === "'" || c === '"' || c === "`" || c === "[") {
|
|
50
|
+
const close = c === "[" ? "]" : c;
|
|
51
|
+
let j = i + 1;
|
|
52
|
+
while (j < text.length) {
|
|
53
|
+
if (text[j] === close) {
|
|
54
|
+
if (close !== "]" && text[j + 1] === close) j += 2;
|
|
55
|
+
else break;
|
|
56
|
+
} else j += 1;
|
|
57
|
+
}
|
|
58
|
+
i = j + 1;
|
|
59
|
+
words.push("");
|
|
60
|
+
afterSemicolon = false;
|
|
61
|
+
afterEnd = false;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (c === ";") {
|
|
65
|
+
i += 1;
|
|
66
|
+
if (!trigger || afterEnd) end(i);
|
|
67
|
+
else {
|
|
68
|
+
afterSemicolon = true;
|
|
69
|
+
afterEnd = false;
|
|
70
|
+
}
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (/[A-Za-z_]/u.test(c)) {
|
|
74
|
+
let j = i;
|
|
75
|
+
while (j < text.length && /[\w$]/u.test(text[j]!)) j += 1;
|
|
76
|
+
const word = text.slice(i, j).toUpperCase();
|
|
77
|
+
words.push(word);
|
|
78
|
+
if (words.length <= 4 && words[0] === "CREATE" && word === "TRIGGER") trigger = true;
|
|
79
|
+
afterEnd = trigger && afterSemicolon && word === "END";
|
|
80
|
+
afterSemicolon = false;
|
|
81
|
+
i = j;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (!/\s/u.test(c)) {
|
|
85
|
+
words.push(c);
|
|
86
|
+
afterSemicolon = false;
|
|
87
|
+
afterEnd = false;
|
|
88
|
+
}
|
|
89
|
+
i += 1;
|
|
90
|
+
}
|
|
91
|
+
end(text.length);
|
|
92
|
+
return statements;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* A `.sql` migration for a SQLite driver that runs one statement per call (Node's, under
|
|
97
|
+
* `apps/testing`): every statement, in order, in the migration's own transaction.
|
|
98
|
+
*/
|
|
99
|
+
export const sqlMigrationByStatement = (
|
|
100
|
+
text: string,
|
|
101
|
+
): Effect.Effect<void, unknown, SqlClient.SqlClient> =>
|
|
102
|
+
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) =>
|
|
103
|
+
Effect.forEach(sqlStatements(text), (statement) => sql.unsafe(statement).raw, {
|
|
104
|
+
discard: true,
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
/** A migration file's key for `Migrator.fromRecord`, or `undefined` when the file is not one. */
|
|
109
|
+
export const migrationKey = (file: string): string | undefined =>
|
|
110
|
+
/^\d+_[\w-]+\.(sql|ts)$/u.test(file) ? file.replace(/\.(sql|ts)$/u, "") : undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Linking an account from a page. Linking happens on Executor's own pages,
|
|
3
|
+
* never in the app's: the page sends the person there, and Executor sends them
|
|
4
|
+
* back to `returnTo` once the account is linked or they gave up.
|
|
5
|
+
*/
|
|
6
|
+
import { Context, Effect } from "effect";
|
|
7
|
+
import { LINK_ACCOUNT_PATH } from "./paths.ts";
|
|
8
|
+
|
|
9
|
+
/** Where the page goes. Set it only in tests. */
|
|
10
|
+
export const Navigate = Context.Reference<(url: string) => void>("apps/page/Navigate", {
|
|
11
|
+
defaultValue: () => (url) => globalThis.location?.assign(url),
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
/** The address that starts linking the account the app declared as `name`. */
|
|
15
|
+
export const linkUrl = (name: string, returnTo?: string): string => {
|
|
16
|
+
const back =
|
|
17
|
+
returnTo ??
|
|
18
|
+
(globalThis.location === undefined ? "/" : `${location.pathname}${location.search}`);
|
|
19
|
+
return `${LINK_ACCOUNT_PATH}?${new URLSearchParams({ name, return: back })}`;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** Leave the page to link the account the app declared as `name`, then come back. */
|
|
23
|
+
export const link = (name: string, options?: { readonly returnTo?: string }): Effect.Effect<void> =>
|
|
24
|
+
Effect.gen(function* () {
|
|
25
|
+
const navigate = yield* Navigate;
|
|
26
|
+
navigate(linkUrl(name, options?.returnTo));
|
|
27
|
+
});
|