@agentproto/collect 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/README.md +642 -2
- package/dist/chunk-FQLYZIVI.mjs +405 -0
- package/dist/chunk-FQLYZIVI.mjs.map +1 -0
- package/dist/chunk-SOLT3HJH.mjs +213 -0
- package/dist/chunk-SOLT3HJH.mjs.map +1 -0
- package/dist/chunk-SYTQ6RN6.mjs +98 -0
- package/dist/chunk-SYTQ6RN6.mjs.map +1 -0
- package/dist/connector-DUNy3vSU.d.ts +981 -0
- package/dist/connectors.d.ts +104 -0
- package/dist/connectors.mjs +1197 -0
- package/dist/connectors.mjs.map +1 -0
- package/dist/engine-BRXHKg5A.d.ts +384 -0
- package/dist/index.d.ts +134 -0
- package/dist/index.mjs +1494 -0
- package/dist/index.mjs.map +1 -0
- package/dist/node.d.ts +526 -0
- package/dist/node.mjs +2322 -0
- package/dist/node.mjs.map +1 -0
- package/package.json +71 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1494 @@
|
|
|
1
|
+
import { createConnectorRegistry, CollectTask, listConnectors } from './chunk-SYTQ6RN6.mjs';
|
|
2
|
+
export { AccessDeclaration, Capability, CollectTask, ConnectorDeclaration, CounterDeclaration, Pace, SessionCheck, TransportNameSchema, createConnectorRegistry, defineConnector, getConnector, listConnectors, registerConnector } from './chunk-SYTQ6RN6.mjs';
|
|
3
|
+
import { assertSafeName, EventRecord, SamplingRecord, PlanEntry, makeReader, lastWins, TaskRecord, recipeHash, itemSeenKeys, dropRedone, pickupRedoKey, actorRedoKey, sourceOf, observationRedoKey, parseRawRef, sha256Bytes, rawRef, RawIndexEntry, STORE_SCHEMA_VERSION, readAll, StoreLockedError, seenKey, stableStringify } from './chunk-SOLT3HJH.mjs';
|
|
4
|
+
export { EventRecord, PlanEntry, RawIndexEntry, RunRecord, STORE_SCHEMA_VERSION, SamplingRecord, StoreLockedError, StoreVersionError, TaskRecord, TaskStatus, actorRedoKey, assertSafeName, dropRedone, itemSeenKeys, lastWins, makeReader, monthOf, observationRedoKey, parseRawRef, pickupRedoKey, rawRef, readAll, recipeHash, seenKey, sha256Bytes, sourceOf, stableStringify } from './chunk-SOLT3HJH.mjs';
|
|
5
|
+
import { RunReport, Recipe, Pickup, Actor, Observation, CollectItem, MissingSecretError, TransportError, canonicalUrl, itemIdFromUrl, textFingerprint, sha256Hex } from './chunk-FQLYZIVI.mjs';
|
|
6
|
+
export { Actor, AudienceKind, AudienceReading, AudienceUnknownReason, CollectItem, ConnectorReport, Coverage, CoverageCell, FailureCause, ItemKind, ItemLinks, ItemPart, MetricName, MissingReason, MissingSecretError, Observation, ObservationBase, Pickup, PickupBase, PickupKind, PickupMethod, Recipe, RunReport, SampledReport, Subject, TransportError, VERIFIED_PICKUP_METHODS, canonicalUrl, itemId, itemIdFromUrl, normalizeText, sha256Hex, textFingerprint } from './chunk-FQLYZIVI.mjs';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* @agentproto/collect
|
|
10
|
+
* Schemas, ids, URL canonicalisation and text fingerprints for collected public content.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// src/memory-store.ts
|
|
14
|
+
function listReader(rows) {
|
|
15
|
+
return makeReader(async function* () {
|
|
16
|
+
for (const r of rows()) yield structuredClone(r);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
function memoryStore(options = {}) {
|
|
20
|
+
const now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
|
|
21
|
+
const raws = /* @__PURE__ */ new Map();
|
|
22
|
+
const rawIndex = [];
|
|
23
|
+
const items = /* @__PURE__ */ new Map();
|
|
24
|
+
const observations = [];
|
|
25
|
+
const actors = [];
|
|
26
|
+
const pickups = [];
|
|
27
|
+
const seen = /* @__PURE__ */ new Map();
|
|
28
|
+
const runs = /* @__PURE__ */ new Map();
|
|
29
|
+
let locked = false;
|
|
30
|
+
const run = (runId) => {
|
|
31
|
+
const s = runs.get(assertSafeName("run id", runId));
|
|
32
|
+
if (!s) throw new Error(`unknown run ${runId}`);
|
|
33
|
+
return s;
|
|
34
|
+
};
|
|
35
|
+
const rows = (runId, pick) => {
|
|
36
|
+
const s = runs.get(assertSafeName("run id", runId));
|
|
37
|
+
return s ? pick(s) : [];
|
|
38
|
+
};
|
|
39
|
+
const bySource = (rows2, source, sourceFor) => source === void 0 ? rows2 : rows2.filter((r) => sourceFor(r) === source);
|
|
40
|
+
return {
|
|
41
|
+
async schemaVersion() {
|
|
42
|
+
return STORE_SCHEMA_VERSION;
|
|
43
|
+
},
|
|
44
|
+
async putRaw(input) {
|
|
45
|
+
const bytes = new Uint8Array(input.bytes);
|
|
46
|
+
const hash = await sha256Bytes(bytes);
|
|
47
|
+
const ref = rawRef(input.connector, input.fetchedAt, hash, input.ext);
|
|
48
|
+
const stored = !raws.has(ref);
|
|
49
|
+
if (stored) raws.set(ref, bytes);
|
|
50
|
+
rawIndex.push(
|
|
51
|
+
RawIndexEntry.parse({
|
|
52
|
+
ref,
|
|
53
|
+
connector: input.connector,
|
|
54
|
+
hash,
|
|
55
|
+
ext: input.ext,
|
|
56
|
+
bytes: bytes.byteLength,
|
|
57
|
+
url: input.url,
|
|
58
|
+
fetchedAt: input.fetchedAt,
|
|
59
|
+
httpStatus: input.httpStatus,
|
|
60
|
+
contentType: input.contentType,
|
|
61
|
+
transport: input.transport,
|
|
62
|
+
runId: input.runId,
|
|
63
|
+
taskId: input.taskId,
|
|
64
|
+
failure: input.failure
|
|
65
|
+
})
|
|
66
|
+
);
|
|
67
|
+
return { ref, hash, stored };
|
|
68
|
+
},
|
|
69
|
+
async getRaw(ref) {
|
|
70
|
+
parseRawRef(ref);
|
|
71
|
+
const b = raws.get(ref);
|
|
72
|
+
return b && new Uint8Array(b);
|
|
73
|
+
},
|
|
74
|
+
rawIndex: () => listReader(() => rawIndex),
|
|
75
|
+
async upsertItem(item) {
|
|
76
|
+
const parsed = CollectItem.parse(item);
|
|
77
|
+
sourceOf(parsed.id);
|
|
78
|
+
items.set(parsed.id, parsed);
|
|
79
|
+
},
|
|
80
|
+
async getItem(id) {
|
|
81
|
+
const i = items.get(id);
|
|
82
|
+
return i && structuredClone(i);
|
|
83
|
+
},
|
|
84
|
+
items: (source) => listReader(() => bySource([...items.values()], source, (i) => sourceOf(i.id))),
|
|
85
|
+
async appendObservation(o) {
|
|
86
|
+
const parsed = Observation.parse(o);
|
|
87
|
+
sourceOf(parsed.itemId);
|
|
88
|
+
observations.push(parsed);
|
|
89
|
+
},
|
|
90
|
+
observations: (source) => dropRedone(listReader(() => bySource(observations, source, (o) => sourceOf(o.itemId))), observationRedoKey),
|
|
91
|
+
async appendActor(a) {
|
|
92
|
+
const parsed = Actor.parse(a);
|
|
93
|
+
sourceOf(parsed.ref);
|
|
94
|
+
actors.push(parsed);
|
|
95
|
+
},
|
|
96
|
+
actors: (source) => dropRedone(listReader(() => bySource(actors, source, (a) => sourceOf(a.ref))), actorRedoKey),
|
|
97
|
+
async appendPickup(p) {
|
|
98
|
+
pickups.push(Pickup.parse(p));
|
|
99
|
+
},
|
|
100
|
+
pickups: () => dropRedone(listReader(() => pickups), pickupRedoKey),
|
|
101
|
+
async seenHas(key2) {
|
|
102
|
+
return seen.has(key2);
|
|
103
|
+
},
|
|
104
|
+
async seenGet(key2) {
|
|
105
|
+
return seen.get(key2);
|
|
106
|
+
},
|
|
107
|
+
async seenAdd(key2, itemId2) {
|
|
108
|
+
for (const v of itemId2 === void 0 ? [key2] : [key2, itemId2]) {
|
|
109
|
+
if (v.includes("\n") || v.includes(" ")) throw new Error("a seen key or item id cannot contain a newline or a tab");
|
|
110
|
+
}
|
|
111
|
+
if (!seen.has(key2) || seen.get(key2) === void 0 && itemId2 !== void 0) seen.set(key2, itemId2);
|
|
112
|
+
},
|
|
113
|
+
async seenKeys() {
|
|
114
|
+
return [...seen.keys()];
|
|
115
|
+
},
|
|
116
|
+
async rebuildSeenIndex() {
|
|
117
|
+
seen.clear();
|
|
118
|
+
for (const item of items.values()) for (const k of itemSeenKeys(item)) if (!seen.has(k)) seen.set(k, item.id);
|
|
119
|
+
},
|
|
120
|
+
async createRun(runId, recipe, extra) {
|
|
121
|
+
assertSafeName("run id", runId);
|
|
122
|
+
const parsed = Recipe.parse(recipe);
|
|
123
|
+
const hash = await recipeHash(parsed);
|
|
124
|
+
if (runs.has(runId)) throw new Error(`run ${runId} already exists`);
|
|
125
|
+
const record = { runId, createdAt: now(), recipeHash: hash, recipe: parsed, ...extra?.connectorModules ? { connectorModules: extra.connectorModules } : {}, ...extra?.origin ? { origin: extra.origin } : {} };
|
|
126
|
+
runs.set(runId, { record, tasks: [], sampling: [], events: [] });
|
|
127
|
+
return structuredClone(record);
|
|
128
|
+
},
|
|
129
|
+
async getRun(runId) {
|
|
130
|
+
const r = runs.get(assertSafeName("run id", runId));
|
|
131
|
+
return r && structuredClone(r.record);
|
|
132
|
+
},
|
|
133
|
+
async listRuns() {
|
|
134
|
+
return [...runs.keys()].sort();
|
|
135
|
+
},
|
|
136
|
+
async appendTask(runId, task) {
|
|
137
|
+
run(runId).tasks.push(TaskRecord.parse(task));
|
|
138
|
+
},
|
|
139
|
+
tasks: (runId) => makeReader(async function* () {
|
|
140
|
+
yield* lastWins(listReader(() => rows(runId, (s) => s.tasks)), (t) => t.taskId);
|
|
141
|
+
}),
|
|
142
|
+
async writePlan(runId, plan) {
|
|
143
|
+
run(runId).plan = plan.map((p) => PlanEntry.parse(p));
|
|
144
|
+
},
|
|
145
|
+
async readPlan(runId) {
|
|
146
|
+
const p = runs.get(assertSafeName("run id", runId))?.plan;
|
|
147
|
+
return p && structuredClone(p);
|
|
148
|
+
},
|
|
149
|
+
async appendSampling(runId, r) {
|
|
150
|
+
run(runId).sampling.push(SamplingRecord.parse(r));
|
|
151
|
+
},
|
|
152
|
+
async appendSamplingBatch(runId, rs) {
|
|
153
|
+
const parsed = rs.map((r) => SamplingRecord.parse(r));
|
|
154
|
+
run(runId).sampling.push(...parsed);
|
|
155
|
+
},
|
|
156
|
+
sampling: (runId) => listReader(() => rows(runId, (s) => s.sampling)),
|
|
157
|
+
async appendEvent(runId, e) {
|
|
158
|
+
run(runId).events.push(EventRecord.parse(e));
|
|
159
|
+
},
|
|
160
|
+
events: (runId) => listReader(() => rows(runId, (s) => s.events)),
|
|
161
|
+
async writeReport(runId, report) {
|
|
162
|
+
run(runId).report = RunReport.parse(report);
|
|
163
|
+
},
|
|
164
|
+
async readReport(runId) {
|
|
165
|
+
const r = runs.get(assertSafeName("run id", runId))?.report;
|
|
166
|
+
return r && structuredClone(r);
|
|
167
|
+
},
|
|
168
|
+
async acquireLock() {
|
|
169
|
+
if (locked) throw new StoreLockedError("store is locked by another writer");
|
|
170
|
+
locked = true;
|
|
171
|
+
let released = false;
|
|
172
|
+
return {
|
|
173
|
+
async release() {
|
|
174
|
+
if (released) return;
|
|
175
|
+
released = true;
|
|
176
|
+
locked = false;
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/redact.ts
|
|
184
|
+
var MARK = "[redacted]";
|
|
185
|
+
var MIN_LENGTH = 4;
|
|
186
|
+
function isSecretRecorder(port) {
|
|
187
|
+
return !!port && typeof port.redact === "function" && typeof port.redactJson === "function";
|
|
188
|
+
}
|
|
189
|
+
function recordSecrets(port) {
|
|
190
|
+
if (isSecretRecorder(port)) return port;
|
|
191
|
+
const forms = /* @__PURE__ */ new Set();
|
|
192
|
+
let ordered = [];
|
|
193
|
+
const add = (value) => {
|
|
194
|
+
if (value.length < MIN_LENGTH) return;
|
|
195
|
+
for (const f of [value, encodeURIComponent(value), encodeURIComponent(value).replace(/%20/g, "+"), JSON.stringify(value).slice(1, -1)]) {
|
|
196
|
+
if (f.length >= MIN_LENGTH) forms.add(f);
|
|
197
|
+
}
|
|
198
|
+
ordered = [...forms].sort((a, b) => b.length - a.length);
|
|
199
|
+
};
|
|
200
|
+
const redact = (text) => {
|
|
201
|
+
let out = text;
|
|
202
|
+
for (const f of ordered) if (out.includes(f)) out = out.split(f).join(MARK);
|
|
203
|
+
return out;
|
|
204
|
+
};
|
|
205
|
+
const walk = (v) => {
|
|
206
|
+
if (typeof v === "string") return redact(v);
|
|
207
|
+
if (Array.isArray(v)) return v.map(walk);
|
|
208
|
+
if (v && typeof v === "object") {
|
|
209
|
+
const o = {};
|
|
210
|
+
for (const [k, x] of Object.entries(v)) o[redact(k)] = walk(x);
|
|
211
|
+
return o;
|
|
212
|
+
}
|
|
213
|
+
return v;
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
async get(name) {
|
|
217
|
+
const value = await port.get(name);
|
|
218
|
+
if (value) add(value);
|
|
219
|
+
return value;
|
|
220
|
+
},
|
|
221
|
+
redact,
|
|
222
|
+
redactJson: (v) => ordered.length === 0 ? v : walk(v)
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// src/sampling.ts
|
|
227
|
+
function mulberry32(seed) {
|
|
228
|
+
let a = seed >>> 0;
|
|
229
|
+
return () => {
|
|
230
|
+
a = a + 1831565813 >>> 0;
|
|
231
|
+
let t = a;
|
|
232
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
233
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
234
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function hashString(s) {
|
|
238
|
+
let h = 2166136261;
|
|
239
|
+
for (let i = 0; i < s.length; i++) {
|
|
240
|
+
h ^= s.charCodeAt(i);
|
|
241
|
+
h = Math.imul(h, 16777619);
|
|
242
|
+
}
|
|
243
|
+
return h >>> 0;
|
|
244
|
+
}
|
|
245
|
+
function domainOf(url) {
|
|
246
|
+
if (!url) return void 0;
|
|
247
|
+
try {
|
|
248
|
+
const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "").replace(/^www\./, "");
|
|
249
|
+
return host || void 0;
|
|
250
|
+
} catch {
|
|
251
|
+
return void 0;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
function candidateDomain(c) {
|
|
255
|
+
if (c.kind === "submission") {
|
|
256
|
+
const t = domainOf(c.target) ?? domainOf(c.outboundLinks?.[0]);
|
|
257
|
+
if (t) return t;
|
|
258
|
+
}
|
|
259
|
+
return domainOf(c.url);
|
|
260
|
+
}
|
|
261
|
+
function seededOrder(items, seed, batchKey) {
|
|
262
|
+
const sorted = [...items].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
263
|
+
const rnd = mulberry32((seed ^ hashString(batchKey)) >>> 0);
|
|
264
|
+
for (let i = sorted.length - 1; i > 0; i--) {
|
|
265
|
+
const j = Math.floor(rnd() * (i + 1));
|
|
266
|
+
const tmp = sorted[i];
|
|
267
|
+
sorted[i] = sorted[j];
|
|
268
|
+
sorted[j] = tmp;
|
|
269
|
+
}
|
|
270
|
+
return sorted;
|
|
271
|
+
}
|
|
272
|
+
function createSampler(config, primary, prior) {
|
|
273
|
+
const bands = config.bands ?? [];
|
|
274
|
+
const seed = config.seed;
|
|
275
|
+
const decided = /* @__PURE__ */ new Map();
|
|
276
|
+
const decidedUrl = /* @__PURE__ */ new Map();
|
|
277
|
+
const bandKept = bands.map(() => 0);
|
|
278
|
+
const domainKept = /* @__PURE__ */ new Map();
|
|
279
|
+
function apply(lines) {
|
|
280
|
+
for (const d of lines) {
|
|
281
|
+
if (decided.has(d.candidate)) continue;
|
|
282
|
+
decided.set(d.candidate, d);
|
|
283
|
+
if (d.url && !decidedUrl.has(d.url)) decidedUrl.set(d.url, d);
|
|
284
|
+
if (d.decision !== "kept") continue;
|
|
285
|
+
if (d.band !== void 0 && d.band < bandKept.length) bandKept[d.band]++;
|
|
286
|
+
if (d.domain) domainKept.set(d.domain, (domainKept.get(d.domain) ?? 0) + 1);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
apply(prior);
|
|
290
|
+
const bandMetric = (i) => bands[i].metric ?? primary;
|
|
291
|
+
function rank(c) {
|
|
292
|
+
for (let i = 0; i < bands.length; i++) {
|
|
293
|
+
const m = bandMetric(i);
|
|
294
|
+
const v2 = m ? c.metrics[m] : void 0;
|
|
295
|
+
if (v2 !== void 0) return v2;
|
|
296
|
+
}
|
|
297
|
+
const v = primary ? c.metrics[primary] : void 0;
|
|
298
|
+
return v ?? Number.NEGATIVE_INFINITY;
|
|
299
|
+
}
|
|
300
|
+
function representative(g) {
|
|
301
|
+
return [...g.members].sort((a, b) => {
|
|
302
|
+
const d = rank(b) - rank(a);
|
|
303
|
+
if (d !== 0 && !Number.isNaN(d)) return d;
|
|
304
|
+
const ua = a.url ?? "\uFFFF";
|
|
305
|
+
const ub = b.url ?? "\uFFFF";
|
|
306
|
+
if (ua !== ub) return ua < ub ? -1 : 1;
|
|
307
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
308
|
+
})[0];
|
|
309
|
+
}
|
|
310
|
+
function plan(batchKey, candidates, known = /* @__PURE__ */ new Set()) {
|
|
311
|
+
const groups = [];
|
|
312
|
+
const byId = /* @__PURE__ */ new Map();
|
|
313
|
+
const byUrl = /* @__PURE__ */ new Map();
|
|
314
|
+
for (const c of candidates) {
|
|
315
|
+
let g = byId.get(c.id) ?? (c.url ? byUrl.get(c.url) : void 0);
|
|
316
|
+
if (!g) {
|
|
317
|
+
g = { members: [] };
|
|
318
|
+
groups.push(g);
|
|
319
|
+
}
|
|
320
|
+
const other = c.url ? byUrl.get(c.url) : void 0;
|
|
321
|
+
if (other && other !== g) {
|
|
322
|
+
for (const m of other.members) {
|
|
323
|
+
g.members.push(m);
|
|
324
|
+
byId.set(m.id, g);
|
|
325
|
+
if (m.url) byUrl.set(m.url, g);
|
|
326
|
+
}
|
|
327
|
+
groups.splice(groups.indexOf(other), 1);
|
|
328
|
+
}
|
|
329
|
+
g.members.push(c);
|
|
330
|
+
byId.set(c.id, g);
|
|
331
|
+
if (c.url) byUrl.set(c.url, g);
|
|
332
|
+
}
|
|
333
|
+
const dropped = /* @__PURE__ */ new Set();
|
|
334
|
+
const pool = [];
|
|
335
|
+
for (const g of groups) {
|
|
336
|
+
let earlier;
|
|
337
|
+
for (const m of g.members) earlier ??= decided.get(m.id) ?? (m.url ? decidedUrl.get(m.url) : void 0);
|
|
338
|
+
if (g.members.some((m) => known.has(m.id)) && earlier?.decision !== "kept") continue;
|
|
339
|
+
const rep = representative(g);
|
|
340
|
+
pool.push({ id: rep.id, g, rep, earlier });
|
|
341
|
+
}
|
|
342
|
+
const bandLocal = [...bandKept];
|
|
343
|
+
const domainLocal = /* @__PURE__ */ new Map();
|
|
344
|
+
const domainCount = (d) => (domainKept.get(d) ?? 0) + (domainLocal.get(d) ?? 0);
|
|
345
|
+
function decideOne(c) {
|
|
346
|
+
const domain = candidateDomain(c);
|
|
347
|
+
const base = {
|
|
348
|
+
candidate: c.id,
|
|
349
|
+
...c.url ? { url: c.url } : {},
|
|
350
|
+
...domain ? { domain } : {},
|
|
351
|
+
...seed !== void 0 ? { seed } : {}
|
|
352
|
+
};
|
|
353
|
+
const drop = (rule, band2) => ({
|
|
354
|
+
...base,
|
|
355
|
+
decision: "dropped",
|
|
356
|
+
rule,
|
|
357
|
+
...band2 !== void 0 ? { band: band2 } : {}
|
|
358
|
+
});
|
|
359
|
+
let band;
|
|
360
|
+
if (bands.length > 0) {
|
|
361
|
+
let missing = true;
|
|
362
|
+
for (let i = 0; i < bands.length; i++) {
|
|
363
|
+
const m = bandMetric(i);
|
|
364
|
+
const v = m ? c.metrics[m] : void 0;
|
|
365
|
+
if (v === void 0) continue;
|
|
366
|
+
missing = false;
|
|
367
|
+
const b = bands[i];
|
|
368
|
+
if ((b.min === void 0 || v >= b.min) && (b.max === void 0 || v <= b.max)) {
|
|
369
|
+
band = i;
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
if (band === void 0) {
|
|
374
|
+
if (!missing) return drop("out_of_bands");
|
|
375
|
+
if (!config.keepMissingMetric) return drop("no_metric");
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
if (band !== void 0) {
|
|
379
|
+
const quota = bands[band].quota;
|
|
380
|
+
if (quota !== void 0 && bandLocal[band] >= quota) return drop("band_quota", band);
|
|
381
|
+
}
|
|
382
|
+
if (domain && config.perDomainCap !== void 0 && domainCount(domain) >= config.perDomainCap) {
|
|
383
|
+
return drop("domain_cap", band);
|
|
384
|
+
}
|
|
385
|
+
if (band !== void 0) bandLocal[band]++;
|
|
386
|
+
if (domain) domainLocal.set(domain, (domainLocal.get(domain) ?? 0) + 1);
|
|
387
|
+
return { ...base, decision: "kept", ...band !== void 0 ? { band } : {} };
|
|
388
|
+
}
|
|
389
|
+
const ordered = seed !== void 0 ? seededOrder(pool, seed, batchKey) : pool;
|
|
390
|
+
const lines = [];
|
|
391
|
+
for (const { g, rep, earlier } of ordered) {
|
|
392
|
+
if (earlier) {
|
|
393
|
+
if (earlier.decision === "dropped") for (const m of g.members) dropped.add(m.id);
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
const d = decideOne(rep);
|
|
397
|
+
lines.push(d);
|
|
398
|
+
if (d.decision === "dropped") for (const m of g.members) dropped.add(m.id);
|
|
399
|
+
}
|
|
400
|
+
return { lines, dropped };
|
|
401
|
+
}
|
|
402
|
+
return { plan, apply };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// src/coverage.ts
|
|
406
|
+
var UNKNOWN = "unknown";
|
|
407
|
+
var NO_SUBJECT = "none";
|
|
408
|
+
async function computeCoverage(store, connectors = []) {
|
|
409
|
+
const primary = {};
|
|
410
|
+
const list = Array.isArray(connectors) ? [...connectors] : connectors.list();
|
|
411
|
+
for (const c of list) {
|
|
412
|
+
primary[c.id] = c.counters.find((k) => k.primary)?.name;
|
|
413
|
+
}
|
|
414
|
+
const metricsByItem = /* @__PURE__ */ new Map();
|
|
415
|
+
for await (const o of store.observations()) {
|
|
416
|
+
let set = metricsByItem.get(o.itemId);
|
|
417
|
+
if (!set) metricsByItem.set(o.itemId, set = /* @__PURE__ */ new Set());
|
|
418
|
+
for (const k of Object.keys(o.metrics)) set.add(k);
|
|
419
|
+
}
|
|
420
|
+
const audience = /* @__PURE__ */ new Set();
|
|
421
|
+
for await (const a of store.actors()) {
|
|
422
|
+
if (a.audience.some((r) => (r.kind === "followers" || r.kind === "subscribers") && r.value !== void 0)) {
|
|
423
|
+
audience.add(a.ref);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const items = [];
|
|
427
|
+
const contentCounts = /* @__PURE__ */ new Map();
|
|
428
|
+
for await (const item of store.items()) {
|
|
429
|
+
items.push(item);
|
|
430
|
+
if (item.contentId) contentCounts.set(item.contentId, (contentCounts.get(item.contentId) ?? 0) + 1);
|
|
431
|
+
}
|
|
432
|
+
const cells = /* @__PURE__ */ new Map();
|
|
433
|
+
for (const item of items) {
|
|
434
|
+
const seen = metricsByItem.get(item.id);
|
|
435
|
+
const main = primary[item.source];
|
|
436
|
+
const hasPrimary = seen !== void 0 && main !== void 0 && seen.has(main);
|
|
437
|
+
const hasAudience = item.authorRef !== void 0 && audience.has(item.authorRef);
|
|
438
|
+
const hasAge = item.postedAt !== void 0 && seen !== void 0;
|
|
439
|
+
const hasAuthorId = item.authorRef !== void 0;
|
|
440
|
+
const unique = item.contentId !== void 0 && contentCounts.get(item.contentId) === 1;
|
|
441
|
+
const eligible = hasAudience && hasPrimary && hasAge && hasAuthorId;
|
|
442
|
+
const subjects = [...new Set(item.subjects.map((s) => s.label))];
|
|
443
|
+
for (const subject of subjects.length ? subjects : [NO_SUBJECT]) {
|
|
444
|
+
const platform = item.source;
|
|
445
|
+
const format = item.format ?? UNKNOWN;
|
|
446
|
+
const language = item.language ?? UNKNOWN;
|
|
447
|
+
const key2 = JSON.stringify([platform, format, language, subject]);
|
|
448
|
+
let cell = cells.get(key2);
|
|
449
|
+
if (!cell) {
|
|
450
|
+
cell = {
|
|
451
|
+
platform,
|
|
452
|
+
format,
|
|
453
|
+
language,
|
|
454
|
+
subject,
|
|
455
|
+
items: 0,
|
|
456
|
+
withAuthorAudience: 0,
|
|
457
|
+
withPrimaryMetric: 0,
|
|
458
|
+
withAge: 0,
|
|
459
|
+
withAuthorId: 0,
|
|
460
|
+
withUniqueContent: 0,
|
|
461
|
+
eligible: 0
|
|
462
|
+
};
|
|
463
|
+
cells.set(key2, cell);
|
|
464
|
+
}
|
|
465
|
+
cell.items++;
|
|
466
|
+
if (hasAudience) cell.withAuthorAudience++;
|
|
467
|
+
if (hasPrimary) cell.withPrimaryMetric++;
|
|
468
|
+
if (hasAge) cell.withAge++;
|
|
469
|
+
if (hasAuthorId) cell.withAuthorId++;
|
|
470
|
+
if (unique) cell.withUniqueContent++;
|
|
471
|
+
if (eligible) cell.eligible++;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
cells: [...cells.values()].sort(
|
|
476
|
+
(a, b) => JSON.stringify([a.platform, a.format, a.language, a.subject]).localeCompare(
|
|
477
|
+
JSON.stringify([b.platform, b.format, b.language, b.subject])
|
|
478
|
+
)
|
|
479
|
+
)
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// src/engine.ts
|
|
484
|
+
var systemClock = {
|
|
485
|
+
now: () => Date.now(),
|
|
486
|
+
sleep: (ms, signal) => new Promise((resolve) => {
|
|
487
|
+
if (signal?.aborted) return resolve();
|
|
488
|
+
const t = setTimeout(done, ms);
|
|
489
|
+
const onAbort = () => {
|
|
490
|
+
clearTimeout(t);
|
|
491
|
+
done();
|
|
492
|
+
};
|
|
493
|
+
function done() {
|
|
494
|
+
signal?.removeEventListener("abort", onAbort);
|
|
495
|
+
resolve();
|
|
496
|
+
}
|
|
497
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
498
|
+
})
|
|
499
|
+
};
|
|
500
|
+
var CollectRunError = class extends Error {
|
|
501
|
+
constructor(runId, cause) {
|
|
502
|
+
super(`run ${runId} failed: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
503
|
+
this.runId = runId;
|
|
504
|
+
this.cause = cause;
|
|
505
|
+
this.name = "CollectRunError";
|
|
506
|
+
}
|
|
507
|
+
runId;
|
|
508
|
+
cause;
|
|
509
|
+
code = "RUN_ERROR";
|
|
510
|
+
};
|
|
511
|
+
var FALLBACK_STATUSES = /* @__PURE__ */ new Set([401, 403, 429]);
|
|
512
|
+
var DEFAULT_WORKERS = 8;
|
|
513
|
+
var key = (connector, taskId) => `${connector}/${taskId}`;
|
|
514
|
+
function challengeFailure(browser, message) {
|
|
515
|
+
return { fallback: !browser, challenge: browser, cause: "challenge", message };
|
|
516
|
+
}
|
|
517
|
+
function classifyError(e, browser) {
|
|
518
|
+
if (e instanceof TransportError) {
|
|
519
|
+
const message = e.message;
|
|
520
|
+
if (e.cause !== "challenge" && e.status !== void 0 && (e.status < 200 || e.status >= 300)) {
|
|
521
|
+
return FALLBACK_STATUSES.has(e.status) ? { fallback: true, challenge: false, cause: "blocked", message } : { fallback: false, challenge: false, cause: "http", message };
|
|
522
|
+
}
|
|
523
|
+
switch (e.cause) {
|
|
524
|
+
case "challenge":
|
|
525
|
+
return challengeFailure(browser, message);
|
|
526
|
+
case "blocked":
|
|
527
|
+
return { fallback: true, challenge: false, cause: "blocked", message };
|
|
528
|
+
case "empty":
|
|
529
|
+
return { fallback: true, challenge: false, cause: "empty", message };
|
|
530
|
+
case "network":
|
|
531
|
+
return { fallback: false, challenge: false, cause: "network", message };
|
|
532
|
+
case "http":
|
|
533
|
+
return e.status !== void 0 && FALLBACK_STATUSES.has(e.status) ? { fallback: true, challenge: false, cause: "blocked", message } : { fallback: false, challenge: false, cause: "http", message };
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
return { fallback: false, challenge: false, cause: "other", message: e instanceof Error ? e.message : String(e) };
|
|
537
|
+
}
|
|
538
|
+
function classifyRaw(raw, browser) {
|
|
539
|
+
if (raw.challenge) return challengeFailure(browser, "challenge page");
|
|
540
|
+
const s = raw.httpStatus;
|
|
541
|
+
if (s !== void 0) {
|
|
542
|
+
if (FALLBACK_STATUSES.has(s)) return { fallback: true, challenge: false, cause: "blocked", message: `HTTP ${s}` };
|
|
543
|
+
if (s < 200 || s >= 300) return { fallback: false, challenge: false, cause: "http", message: `HTTP ${s}` };
|
|
544
|
+
}
|
|
545
|
+
if (raw.bytes.byteLength === 0) return { fallback: true, challenge: false, cause: "empty", message: "empty content" };
|
|
546
|
+
return void 0;
|
|
547
|
+
}
|
|
548
|
+
function compareOrder(a, b) {
|
|
549
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
550
|
+
const x = a[i];
|
|
551
|
+
const y = b[i];
|
|
552
|
+
if (x === void 0) return -1;
|
|
553
|
+
if (y === void 0) return 1;
|
|
554
|
+
if (x !== y) return x - y;
|
|
555
|
+
}
|
|
556
|
+
return 0;
|
|
557
|
+
}
|
|
558
|
+
function insertSorted(queue, entry) {
|
|
559
|
+
let i = queue.length;
|
|
560
|
+
while (i > 0 && compareOrder(queue[i - 1].order, entry.order) > 0) i--;
|
|
561
|
+
queue.splice(i, 0, entry);
|
|
562
|
+
}
|
|
563
|
+
function serial() {
|
|
564
|
+
let tail = Promise.resolve();
|
|
565
|
+
return (fn) => {
|
|
566
|
+
const p = tail.then(fn);
|
|
567
|
+
tail = p.then(
|
|
568
|
+
() => void 0,
|
|
569
|
+
() => void 0
|
|
570
|
+
);
|
|
571
|
+
return p;
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
function sampledOf(rows) {
|
|
575
|
+
const dropped = {};
|
|
576
|
+
let kept = 0;
|
|
577
|
+
for (const r of rows) {
|
|
578
|
+
if (r.decision === "kept") kept++;
|
|
579
|
+
else dropped[r.rule ?? "unknown"] = (dropped[r.rule ?? "unknown"] ?? 0) + 1;
|
|
580
|
+
}
|
|
581
|
+
return { candidates: rows.length, kept, dropped };
|
|
582
|
+
}
|
|
583
|
+
function hostOf(url) {
|
|
584
|
+
try {
|
|
585
|
+
return new URL(url).host.toLowerCase();
|
|
586
|
+
} catch {
|
|
587
|
+
return "";
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
function randomId(random) {
|
|
591
|
+
let s = "";
|
|
592
|
+
for (let i = 0; i < 6; i++) s += Math.floor(random() * 36).toString(36);
|
|
593
|
+
return s;
|
|
594
|
+
}
|
|
595
|
+
function toError(e) {
|
|
596
|
+
if (e instanceof Error) return e;
|
|
597
|
+
let text;
|
|
598
|
+
try {
|
|
599
|
+
text = typeof e === "string" ? e : JSON.stringify(e) ?? String(e);
|
|
600
|
+
} catch {
|
|
601
|
+
text = String(e);
|
|
602
|
+
}
|
|
603
|
+
return new Error(`rejected with ${text}`);
|
|
604
|
+
}
|
|
605
|
+
function abortError() {
|
|
606
|
+
return Object.assign(new Error("aborted"), { name: "AbortError" });
|
|
607
|
+
}
|
|
608
|
+
function createCollector(options) {
|
|
609
|
+
const { transports } = options;
|
|
610
|
+
const clock = options.clock ?? systemClock;
|
|
611
|
+
const random = options.random ?? Math.random;
|
|
612
|
+
const secrets = recordSecrets(options.secrets ?? { get: async () => void 0 });
|
|
613
|
+
const abortGraceMs = options.abortGraceMs ?? 1e4;
|
|
614
|
+
const store = new Proxy(options.store, {
|
|
615
|
+
get(target, prop) {
|
|
616
|
+
const value = Reflect.get(target, prop, target);
|
|
617
|
+
if (typeof value !== "function") return value;
|
|
618
|
+
if (prop === "appendEvent" || prop === "appendTask" || prop === "writeReport" || prop === "writePlan") {
|
|
619
|
+
return (runId, record) => value.call(target, runId, secrets.redactJson(record));
|
|
620
|
+
}
|
|
621
|
+
return value.bind(target);
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
const scrubbed = (e) => {
|
|
625
|
+
if (!(e instanceof Error)) return e;
|
|
626
|
+
const message = secrets.redact(e.message);
|
|
627
|
+
if (message === e.message) return e;
|
|
628
|
+
const copy = new Error(message);
|
|
629
|
+
copy.name = e.name;
|
|
630
|
+
return copy;
|
|
631
|
+
};
|
|
632
|
+
const apiFactories = /* @__PURE__ */ new Map();
|
|
633
|
+
const apiFor = (connector) => {
|
|
634
|
+
const api = transports.api;
|
|
635
|
+
if (typeof api !== "function") return api;
|
|
636
|
+
let t = apiFactories.get(connector.id);
|
|
637
|
+
if (!t) apiFactories.set(connector.id, t = api(connector));
|
|
638
|
+
return t;
|
|
639
|
+
};
|
|
640
|
+
const registry = Array.isArray(options.connectors) ? createConnectorRegistry(options.connectors) : options.connectors ?? { register() {
|
|
641
|
+
}, get: (id) => listConnectors().find((c) => c.id === id), list: listConnectors };
|
|
642
|
+
const iso = () => new Date(clock.now()).toISOString();
|
|
643
|
+
const gates = /* @__PURE__ */ new Map();
|
|
644
|
+
async function gate(url, intervalMs, signal) {
|
|
645
|
+
const host = hostOf(url);
|
|
646
|
+
let g = gates.get(host);
|
|
647
|
+
if (!g) gates.set(host, g = { tail: Promise.resolve(), lastInterval: 0 });
|
|
648
|
+
const state = g;
|
|
649
|
+
const mine = state.tail.then(async () => {
|
|
650
|
+
for (; ; ) {
|
|
651
|
+
if (signal?.aborted) throw abortError();
|
|
652
|
+
const gap = Math.max(intervalMs, state.lastInterval);
|
|
653
|
+
const wait = state.lastStart === void 0 ? 0 : state.lastStart + gap - clock.now();
|
|
654
|
+
if (wait <= 0) break;
|
|
655
|
+
await clock.sleep(wait, signal);
|
|
656
|
+
}
|
|
657
|
+
state.lastStart = clock.now();
|
|
658
|
+
state.lastInterval = intervalMs;
|
|
659
|
+
});
|
|
660
|
+
state.tail = mine.then(
|
|
661
|
+
() => void 0,
|
|
662
|
+
() => void 0
|
|
663
|
+
);
|
|
664
|
+
await mine;
|
|
665
|
+
}
|
|
666
|
+
function both(a, b) {
|
|
667
|
+
return a && b ? AbortSignal.any([a, b]) : a ?? b;
|
|
668
|
+
}
|
|
669
|
+
function handleFor(name, connector, signal) {
|
|
670
|
+
const delay = connector.pace.delayMs;
|
|
671
|
+
if (name === "browser") {
|
|
672
|
+
const b = transports.browser;
|
|
673
|
+
return {
|
|
674
|
+
name,
|
|
675
|
+
browser: {
|
|
676
|
+
open: async (url) => {
|
|
677
|
+
await gate(url, delay, signal);
|
|
678
|
+
return b.open(url);
|
|
679
|
+
},
|
|
680
|
+
evaluate: (p, s) => b.evaluate(p, s),
|
|
681
|
+
fetchInPage: async (p, r) => {
|
|
682
|
+
const sig = both(r.signal, signal);
|
|
683
|
+
await gate(r.url, delay, sig);
|
|
684
|
+
return b.fetchInPage(p, { ...r, signal: sig });
|
|
685
|
+
},
|
|
686
|
+
scroll: (p, o) => b.scroll(p, o),
|
|
687
|
+
waitFor: (p, o) => b.waitFor(p, o),
|
|
688
|
+
close: (p) => b.close(p)
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
const h = name === "api" ? apiFor(connector) : transports[name];
|
|
693
|
+
return {
|
|
694
|
+
name,
|
|
695
|
+
http: {
|
|
696
|
+
request: async (req) => {
|
|
697
|
+
const sig = both(req.signal, signal);
|
|
698
|
+
await gate(req.url, delay, sig);
|
|
699
|
+
return h.request({ ...req, signal: sig });
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
async function connectorState(id, recipe) {
|
|
705
|
+
const connector = registry.get(id);
|
|
706
|
+
const state = { id, connector, transports: [], started: 0, stopped: false, controller: new AbortController() };
|
|
707
|
+
if (!connector) {
|
|
708
|
+
state.skipReason = `connector "${id}" is not registered`;
|
|
709
|
+
return state;
|
|
710
|
+
}
|
|
711
|
+
state.cap = recipe.caps?.perConnector ?? connector.pace.maxTasksPerRun;
|
|
712
|
+
state.transports = connector.transports.filter((t) => transports[t] !== void 0);
|
|
713
|
+
if (connector.access.level === "key") {
|
|
714
|
+
const secret = await secrets.get(connector.access.secret);
|
|
715
|
+
if (!secret) {
|
|
716
|
+
state.skipReason = `missing_secret:${connector.access.secret}`;
|
|
717
|
+
state.transports = [];
|
|
718
|
+
return state;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if (state.transports.length === 0) {
|
|
722
|
+
state.skipReason = `no usable transport (declared: ${connector.transports.join(", ")}; provided: ${["api", "http", "browser"].filter((t) => transports[t] !== void 0).join(", ") || "none"})`;
|
|
723
|
+
}
|
|
724
|
+
return state;
|
|
725
|
+
}
|
|
726
|
+
async function execute(runId, recipe, mode, opts) {
|
|
727
|
+
const { signal, onEvent } = opts;
|
|
728
|
+
const lock = await store.acquireLock();
|
|
729
|
+
const active = /* @__PURE__ */ new Set();
|
|
730
|
+
const grace = { expired: false, closing: false };
|
|
731
|
+
try {
|
|
732
|
+
return await executeLocked(runId, recipe, mode, signal, onEvent, active, grace, opts.connectorModules);
|
|
733
|
+
} catch (e) {
|
|
734
|
+
if (e instanceof CollectRunError) throw e;
|
|
735
|
+
throw new CollectRunError(runId, scrubbed(e));
|
|
736
|
+
} finally {
|
|
737
|
+
if (!grace.expired) await Promise.allSettled([...active]);
|
|
738
|
+
await lock.release();
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
async function executeLocked(runId, recipe, mode, signal, onEvent, active, grace, connectorModules) {
|
|
742
|
+
const startedAt = (mode === "resume" ? (await store.readReport(runId))?.startedAt : void 0) ?? iso();
|
|
743
|
+
const writeSerial = serial();
|
|
744
|
+
const write = (fn) => grace.expired && !grace.closing ? Promise.reject(new Error("the run was abandoned after the abort grace period")) : writeSerial(fn);
|
|
745
|
+
const emit = (type, data) => write(async () => {
|
|
746
|
+
const event = secrets.redactJson({ at: iso(), type, ...data ? { data } : {} });
|
|
747
|
+
await store.appendEvent(runId, event);
|
|
748
|
+
const report2 = (e) => {
|
|
749
|
+
const p = write(
|
|
750
|
+
() => store.appendEvent(runId, { at: iso(), type: "error", data: { source: "onEvent", message: toError(e).message } })
|
|
751
|
+
).then(
|
|
752
|
+
() => void 0,
|
|
753
|
+
() => void 0
|
|
754
|
+
);
|
|
755
|
+
active.add(p);
|
|
756
|
+
void p.finally(() => active.delete(p));
|
|
757
|
+
};
|
|
758
|
+
try {
|
|
759
|
+
void Promise.resolve(onEvent?.({ ...event, runId })).catch(report2);
|
|
760
|
+
} catch (e) {
|
|
761
|
+
report2(e);
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
const taskRecord = (r) => ({
|
|
765
|
+
...r,
|
|
766
|
+
...counted.has(r.taskId) || r.status === "started" ? { charged: true } : {},
|
|
767
|
+
updatedAt: iso()
|
|
768
|
+
});
|
|
769
|
+
const record = (r) => write(() => store.appendTask(runId, taskRecord(r)));
|
|
770
|
+
if (mode === "new") await store.createRun(runId, recipe, connectorModules ? { connectorModules } : void 0);
|
|
771
|
+
await emit("run.start", { mode, recipeName: recipe.name });
|
|
772
|
+
const samplers = /* @__PURE__ */ new Map();
|
|
773
|
+
const samplerFor = async (connector) => {
|
|
774
|
+
let s = samplers.get(connector.id);
|
|
775
|
+
if (!s) {
|
|
776
|
+
const prior = (await readAll(store.sampling(runId))).records.filter((r) => r.connector === connector.id);
|
|
777
|
+
const primary = connector.counters.find((c) => c.primary)?.name;
|
|
778
|
+
s = createSampler(recipe.sampling, primary, prior);
|
|
779
|
+
samplers.set(connector.id, s);
|
|
780
|
+
}
|
|
781
|
+
return s;
|
|
782
|
+
};
|
|
783
|
+
const connectorIds = [...new Set(recipe.sources.map((s) => s.connector))];
|
|
784
|
+
const states = /* @__PURE__ */ new Map();
|
|
785
|
+
for (const id of connectorIds) states.set(id, await connectorState(id, recipe));
|
|
786
|
+
const abortConnectors = () => {
|
|
787
|
+
for (const st of states.values()) st.controller.abort();
|
|
788
|
+
};
|
|
789
|
+
if (signal?.aborted) abortConnectors();
|
|
790
|
+
else signal?.addEventListener("abort", abortConnectors, { once: true });
|
|
791
|
+
const payloadOf = (t) => ({ id: t.id, ...t.kind ? { kind: t.kind } : {}, params: t.params });
|
|
792
|
+
const known = /* @__PURE__ */ new Set();
|
|
793
|
+
const entries = [];
|
|
794
|
+
const counted = /* @__PURE__ */ new Set();
|
|
795
|
+
const mkEntry = (state, k, task, order) => ({
|
|
796
|
+
key: k,
|
|
797
|
+
connector: state.connector,
|
|
798
|
+
task,
|
|
799
|
+
order,
|
|
800
|
+
attempt: 0,
|
|
801
|
+
started: false,
|
|
802
|
+
t0: 0,
|
|
803
|
+
escalations: []
|
|
804
|
+
});
|
|
805
|
+
const buildPlan = () => {
|
|
806
|
+
const plan2 = [];
|
|
807
|
+
const seen = /* @__PURE__ */ new Set();
|
|
808
|
+
connectorIds.forEach((id, ci) => {
|
|
809
|
+
const state = states.get(id);
|
|
810
|
+
if (!state.connector) return;
|
|
811
|
+
const sources = recipe.sources.filter((s) => s.connector === id);
|
|
812
|
+
let index = 0;
|
|
813
|
+
for (const t of state.connector.plan(recipe, sources)) {
|
|
814
|
+
const task = CollectTask.parse(t);
|
|
815
|
+
const k = key(id, task.id);
|
|
816
|
+
if (seen.has(k)) continue;
|
|
817
|
+
seen.add(k);
|
|
818
|
+
plan2.push({ taskId: k, connector: id, order: [ci, index++], payload: payloadOf(task) });
|
|
819
|
+
}
|
|
820
|
+
});
|
|
821
|
+
return plan2;
|
|
822
|
+
};
|
|
823
|
+
let plan = mode === "resume" ? await store.readPlan(runId) : void 0;
|
|
824
|
+
if (!plan) {
|
|
825
|
+
const built = buildPlan();
|
|
826
|
+
await write(() => store.writePlan(runId, built));
|
|
827
|
+
plan = built;
|
|
828
|
+
}
|
|
829
|
+
if (mode === "new") {
|
|
830
|
+
for (const p of plan) {
|
|
831
|
+
const st = states.get(p.connector);
|
|
832
|
+
if (st && !st.skipReason) {
|
|
833
|
+
await record({ taskId: p.taskId, connector: p.connector, status: "pending", order: p.order, payload: p.payload });
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
{
|
|
838
|
+
const { records } = await readAll(store.tasks(runId));
|
|
839
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
840
|
+
plan.forEach((p) => byKey.set(p.taskId, { connector: p.connector, order: p.order, payload: p.payload }));
|
|
841
|
+
records.forEach((r, i) => {
|
|
842
|
+
const prior = byKey.get(r.taskId);
|
|
843
|
+
const ci = Math.max(connectorIds.indexOf(r.connector), 0);
|
|
844
|
+
byKey.set(r.taskId, {
|
|
845
|
+
connector: r.connector,
|
|
846
|
+
order: r.order ?? prior?.order ?? [ci, Number.MAX_SAFE_INTEGER, i],
|
|
847
|
+
payload: r.payload ?? prior?.payload,
|
|
848
|
+
rec: r
|
|
849
|
+
});
|
|
850
|
+
});
|
|
851
|
+
for (const [k, v] of byKey) {
|
|
852
|
+
known.add(k);
|
|
853
|
+
const status = v.rec?.status ?? "pending";
|
|
854
|
+
const state = states.get(v.connector);
|
|
855
|
+
if (status === "done" || status === "failed" || status === "started" || v.rec?.charged) {
|
|
856
|
+
counted.add(k);
|
|
857
|
+
if (state) state.started++;
|
|
858
|
+
}
|
|
859
|
+
if (status === "done") continue;
|
|
860
|
+
const task = CollectTask.safeParse(v.payload);
|
|
861
|
+
if (!task.success) continue;
|
|
862
|
+
if (!state?.connector || state.skipReason) {
|
|
863
|
+
const reason = state?.skipReason ?? `connector "${v.connector}" is not registered`;
|
|
864
|
+
if (v.rec?.status !== "skipped" || v.rec.reason !== reason) {
|
|
865
|
+
await record({ taskId: k, connector: v.connector, status: "skipped", reason, order: v.order, payload: payloadOf(task.data) });
|
|
866
|
+
}
|
|
867
|
+
continue;
|
|
868
|
+
}
|
|
869
|
+
entries.push(mkEntry(state, k, task.data, v.order));
|
|
870
|
+
}
|
|
871
|
+
for (const st of states.values()) {
|
|
872
|
+
if (st.skipReason) await emit("connector.skipped", { connector: st.id, reason: st.skipReason });
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
for await (const item of store.items()) {
|
|
876
|
+
for (const k of itemSeenKeys(item)) if (await store.seenGet(k) === void 0) await store.seenAdd(k, item.id);
|
|
877
|
+
}
|
|
878
|
+
const workers = recipe.workers ?? DEFAULT_WORKERS;
|
|
879
|
+
const poolQueue = [];
|
|
880
|
+
const browserQueue = [];
|
|
881
|
+
const laneQueue = (e) => states.get(e.connector.id)?.transports[e.attempt] === "browser" ? browserQueue : poolQueue;
|
|
882
|
+
const enqueue = (e) => insertSorted(laneQueue(e), e);
|
|
883
|
+
let poolActive = 0;
|
|
884
|
+
let browserActive = 0;
|
|
885
|
+
let totalStarted = counted.size;
|
|
886
|
+
let commitsActive = 0;
|
|
887
|
+
const slots = [];
|
|
888
|
+
const waiters = /* @__PURE__ */ new Map();
|
|
889
|
+
const wakeHead = () => {
|
|
890
|
+
const head = slots[0];
|
|
891
|
+
const w = head && waiters.get(head);
|
|
892
|
+
if (w) {
|
|
893
|
+
waiters.delete(head);
|
|
894
|
+
w();
|
|
895
|
+
}
|
|
896
|
+
};
|
|
897
|
+
const lookahead = recipe.lookahead ?? 4 * workers;
|
|
898
|
+
const live = /* @__PURE__ */ new Set();
|
|
899
|
+
const resolveSlot = (e) => {
|
|
900
|
+
const i = slots.indexOf(e);
|
|
901
|
+
if (i >= 0) slots.splice(i, 1);
|
|
902
|
+
live.delete(e);
|
|
903
|
+
wakeHead();
|
|
904
|
+
pump();
|
|
905
|
+
};
|
|
906
|
+
const launchable = (e) => live.has(e) || slots[0] === e || !slots.includes(e) || live.size < lookahead && slots.indexOf(e) < lookahead;
|
|
907
|
+
const registerSlot = (e) => insertSorted(slots, e);
|
|
908
|
+
async function awaitTurn(e) {
|
|
909
|
+
while (slots.length > 0 && slots[0] !== e && slots.includes(e)) {
|
|
910
|
+
if (stopping()) return false;
|
|
911
|
+
await new Promise((resolve2) => waiters.set(e, resolve2));
|
|
912
|
+
}
|
|
913
|
+
return true;
|
|
914
|
+
}
|
|
915
|
+
for (const e of entries) {
|
|
916
|
+
registerSlot(e);
|
|
917
|
+
enqueue(e);
|
|
918
|
+
}
|
|
919
|
+
let fatal;
|
|
920
|
+
const aborted = () => signal?.aborted === true;
|
|
921
|
+
const stopping = () => aborted() || fatal !== void 0;
|
|
922
|
+
let finish = () => {
|
|
923
|
+
};
|
|
924
|
+
const finished = new Promise((resolve2) => {
|
|
925
|
+
finish = resolve2;
|
|
926
|
+
});
|
|
927
|
+
const check = () => {
|
|
928
|
+
if (stopping()) for (const [e, w] of [...waiters]) waiters.delete(e), w();
|
|
929
|
+
if (poolActive === 0 && browserActive === 0 && commitsActive === 0 && (stopping() || !poolQueue.length && !browserQueue.length)) finish();
|
|
930
|
+
};
|
|
931
|
+
const pump = () => {
|
|
932
|
+
if (!stopping()) {
|
|
933
|
+
while (poolActive < workers && poolQueue.length && launchable(poolQueue[0])) launch(poolQueue.shift(), "pool");
|
|
934
|
+
if (browserActive === 0 && browserQueue.length && launchable(browserQueue[0])) launch(browserQueue.shift(), "browser");
|
|
935
|
+
if (poolActive === 0 && browserActive === 0 && commitsActive === 0) {
|
|
936
|
+
const first = [poolQueue[0], browserQueue[0]].filter((e) => e !== void 0).sort((a, b) => compareOrder(a.order, b.order))[0];
|
|
937
|
+
if (first) launch((first === poolQueue[0] ? poolQueue : browserQueue).shift(), first === poolQueue[0] ? "pool" : "browser");
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
check();
|
|
941
|
+
};
|
|
942
|
+
const launch = (entry, lane) => {
|
|
943
|
+
live.add(entry);
|
|
944
|
+
if (lane === "pool") poolActive++;
|
|
945
|
+
else browserActive++;
|
|
946
|
+
const p = attempt(entry).catch((e) => {
|
|
947
|
+
if (stopping() && e?.name === "AbortError") return;
|
|
948
|
+
fatal ??= toError(e);
|
|
949
|
+
}).finally(() => {
|
|
950
|
+
active.delete(p);
|
|
951
|
+
if (lane === "pool") poolActive--;
|
|
952
|
+
else browserActive--;
|
|
953
|
+
pump();
|
|
954
|
+
});
|
|
955
|
+
active.add(p);
|
|
956
|
+
};
|
|
957
|
+
signal?.addEventListener("abort", check, { once: true });
|
|
958
|
+
const writtenActors = /* @__PURE__ */ new Set();
|
|
959
|
+
async function skip(entry, reason, why) {
|
|
960
|
+
await record({
|
|
961
|
+
taskId: entry.key,
|
|
962
|
+
connector: entry.connector.id,
|
|
963
|
+
status: "skipped",
|
|
964
|
+
reason,
|
|
965
|
+
order: entry.order,
|
|
966
|
+
payload: payloadOf(entry.task),
|
|
967
|
+
escalations: entry.escalations
|
|
968
|
+
});
|
|
969
|
+
await emit("task.skipped", { connector: entry.connector.id, taskId: entry.task.id, reason: why });
|
|
970
|
+
resolveSlot(entry);
|
|
971
|
+
}
|
|
972
|
+
function haltConnector(state) {
|
|
973
|
+
state.stopped = true;
|
|
974
|
+
state.controller.abort();
|
|
975
|
+
const removed = [];
|
|
976
|
+
for (const q of [poolQueue, browserQueue]) {
|
|
977
|
+
for (let i = q.length - 1; i >= 0; i--) {
|
|
978
|
+
if (q[i].connector.id === state.id) removed.unshift(...q.splice(i, 1));
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
return removed.sort((x, y) => compareOrder(x.order, y.order));
|
|
982
|
+
}
|
|
983
|
+
async function skipHalted(state, removed, first) {
|
|
984
|
+
if (first) await emit("connector.stopped", { connector: state.id, reason: "challenge" });
|
|
985
|
+
for (const e of removed) await skip(e, "challenge", "challenge");
|
|
986
|
+
}
|
|
987
|
+
async function prepare(entry, parsed, ref, rawHash, fetchedAt, transport) {
|
|
988
|
+
const keyOf = (kind, index) => sha256Hex(JSON.stringify([runId, entry.key, rawHash, kind, index]));
|
|
989
|
+
const items = [];
|
|
990
|
+
for (const p of parsed.items ?? []) {
|
|
991
|
+
const canonical = p.canonicalUrl ?? (p.url ? canonicalUrl(p.url) : void 0);
|
|
992
|
+
const id = p.id ?? (canonical ? await itemIdFromUrl(p.source, canonical) : void 0);
|
|
993
|
+
if (!id) throw new Error("an item needs an id or a url");
|
|
994
|
+
const contentId = p.contentId ?? (p.text ? await textFingerprint(p.text) : void 0);
|
|
995
|
+
const item = CollectItem.parse({
|
|
996
|
+
...p,
|
|
997
|
+
id,
|
|
998
|
+
canonicalUrl: canonical,
|
|
999
|
+
contentId,
|
|
1000
|
+
firstSeenAt: p.firstSeenAt ?? fetchedAt,
|
|
1001
|
+
runId,
|
|
1002
|
+
rawRefs: [.../* @__PURE__ */ new Set([...p.rawRefs ?? [], ref])]
|
|
1003
|
+
});
|
|
1004
|
+
if (entry.connector.ext && item.ext !== void 0) entry.connector.ext.parse(item.ext);
|
|
1005
|
+
items.push(item);
|
|
1006
|
+
}
|
|
1007
|
+
const observations = [];
|
|
1008
|
+
for (const [i, o] of (parsed.observations ?? []).entries()) {
|
|
1009
|
+
observations.push(
|
|
1010
|
+
Observation.parse({ measuredAt: fetchedAt, transport, rawRef: ref, ...o, runId, taskId: entry.key, recordKey: await keyOf("observation", i) })
|
|
1011
|
+
);
|
|
1012
|
+
}
|
|
1013
|
+
const pickups = [];
|
|
1014
|
+
for (const [i, p] of (parsed.pickups ?? []).entries()) {
|
|
1015
|
+
pickups.push(
|
|
1016
|
+
Pickup.parse({
|
|
1017
|
+
firstSeenAt: fetchedAt,
|
|
1018
|
+
measuredAt: fetchedAt,
|
|
1019
|
+
...p,
|
|
1020
|
+
runId,
|
|
1021
|
+
taskId: entry.key,
|
|
1022
|
+
recordKey: await keyOf("pickup", i),
|
|
1023
|
+
evidence: { rawRef: ref, ...p.evidence }
|
|
1024
|
+
})
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
const actors = [];
|
|
1028
|
+
for (const [i, a] of (parsed.actors ?? []).entries()) {
|
|
1029
|
+
actors.push(Actor.parse({ ...a, recordKey: await keyOf("actor", i) }));
|
|
1030
|
+
}
|
|
1031
|
+
return { ref, items, observations, actors, pickups };
|
|
1032
|
+
}
|
|
1033
|
+
async function sample(entry, prepared) {
|
|
1034
|
+
if (recipe.sampling === void 0 || entry.task.kind === "read") return prepared;
|
|
1035
|
+
const known2 = /* @__PURE__ */ new Set();
|
|
1036
|
+
const candidates = [];
|
|
1037
|
+
for (const p of prepared) {
|
|
1038
|
+
for (const item of p.items) {
|
|
1039
|
+
const metrics = {};
|
|
1040
|
+
for (const o of p.observations) {
|
|
1041
|
+
if (o.itemId !== item.id) continue;
|
|
1042
|
+
for (const [name, v] of Object.entries(o.metrics)) {
|
|
1043
|
+
if (typeof v === "number" && metrics[name] === void 0) metrics[name] = v;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
const url = item.canonicalUrl ?? item.url;
|
|
1047
|
+
const idKey = seenKey("id", item.id);
|
|
1048
|
+
if (await store.seenGet(idKey) !== void 0 || await store.seenHas(idKey) || item.canonicalUrl !== void 0 && await store.seenGet(seenKey("url", item.canonicalUrl)) !== void 0) {
|
|
1049
|
+
known2.add(item.id);
|
|
1050
|
+
}
|
|
1051
|
+
candidates.push({ id: item.id, kind: item.kind, metrics, url, target: item.links?.target, outboundLinks: item.outboundLinks });
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
const sampler = await samplerFor(entry.connector);
|
|
1055
|
+
const { lines, dropped } = sampler.plan(entry.key, candidates, known2);
|
|
1056
|
+
if (lines.length > 0) {
|
|
1057
|
+
const at = iso();
|
|
1058
|
+
await store.appendSamplingBatch(
|
|
1059
|
+
runId,
|
|
1060
|
+
lines.map((d) => ({ ...d, connector: entry.connector.id, taskId: entry.key, at }))
|
|
1061
|
+
);
|
|
1062
|
+
sampler.apply(lines);
|
|
1063
|
+
}
|
|
1064
|
+
if (dropped.size === 0) return prepared;
|
|
1065
|
+
const refsOf = (i) => [i.authorRef, i.submitterRef, ...(i.parts ?? []).map((part) => part.authorRef)];
|
|
1066
|
+
const keptRefs = new Set(prepared.flatMap((p) => p.items.filter((i) => !dropped.has(i.id))).flatMap(refsOf));
|
|
1067
|
+
const droppedRefs = new Set(prepared.flatMap((p) => p.items.filter((i) => dropped.has(i.id))).flatMap(refsOf));
|
|
1068
|
+
return prepared.map((p) => ({
|
|
1069
|
+
...p,
|
|
1070
|
+
items: p.items.filter((i) => !dropped.has(i.id)),
|
|
1071
|
+
observations: p.observations.filter((o) => !dropped.has(o.itemId)),
|
|
1072
|
+
pickups: p.pickups.filter((k) => !dropped.has(k.itemId) && !(k.pickupItemId && dropped.has(k.pickupItemId))),
|
|
1073
|
+
actors: p.actors.filter((a) => !droppedRefs.has(a.ref) || keptRefs.has(a.ref))
|
|
1074
|
+
}));
|
|
1075
|
+
}
|
|
1076
|
+
async function resolve(idMap, id) {
|
|
1077
|
+
return idMap.get(id) ?? await store.seenGet(seenKey("id", id)) ?? id;
|
|
1078
|
+
}
|
|
1079
|
+
async function ingest(prepared, counters) {
|
|
1080
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
1081
|
+
const created = [];
|
|
1082
|
+
for (const { ref, items } of prepared) {
|
|
1083
|
+
counters.items += items.length;
|
|
1084
|
+
for (const item of items) {
|
|
1085
|
+
const idKey = seenKey("id", item.id);
|
|
1086
|
+
let owner = await store.seenGet(idKey);
|
|
1087
|
+
if (owner === void 0 && await store.seenHas(idKey)) owner = item.id;
|
|
1088
|
+
let level = owner ? 1 : 0;
|
|
1089
|
+
if (!owner && item.canonicalUrl) {
|
|
1090
|
+
owner = await store.seenGet(seenKey("url", item.canonicalUrl));
|
|
1091
|
+
if (owner) level = 2;
|
|
1092
|
+
}
|
|
1093
|
+
if (owner) {
|
|
1094
|
+
idMap.set(item.id, owner);
|
|
1095
|
+
if (level === 2) await store.seenAdd(idKey, owner);
|
|
1096
|
+
const existing = mode === "resume" ? await store.getItem(owner) : void 0;
|
|
1097
|
+
if (existing?.runId === runId && existing.rawRefs?.includes(ref)) counters.newItems++;
|
|
1098
|
+
else counters.duplicates++;
|
|
1099
|
+
continue;
|
|
1100
|
+
}
|
|
1101
|
+
await store.upsertItem(item);
|
|
1102
|
+
for (const k of itemSeenKeys(item)) await store.seenAdd(k, item.id);
|
|
1103
|
+
created.push(item);
|
|
1104
|
+
counters.newItems++;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
for (const item of created) {
|
|
1108
|
+
if (!item.links) continue;
|
|
1109
|
+
const links = { ...item.links };
|
|
1110
|
+
let changed = false;
|
|
1111
|
+
for (const name of ["target", "parent", "root", "quoted"]) {
|
|
1112
|
+
const v = links[name];
|
|
1113
|
+
if (v === void 0) continue;
|
|
1114
|
+
const r = await resolve(idMap, v);
|
|
1115
|
+
if (r !== v) {
|
|
1116
|
+
links[name] = r;
|
|
1117
|
+
changed = true;
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
if (changed) await store.upsertItem({ ...item, links });
|
|
1121
|
+
}
|
|
1122
|
+
for (const { observations, actors, pickups } of prepared) {
|
|
1123
|
+
for (const o of observations) {
|
|
1124
|
+
await store.appendObservation({ ...o, itemId: await resolve(idMap, o.itemId) });
|
|
1125
|
+
counters.observations++;
|
|
1126
|
+
counters.metricValues += Object.keys(o.metrics).length;
|
|
1127
|
+
}
|
|
1128
|
+
for (const a of actors) {
|
|
1129
|
+
const { recordKey: _key, ...bare } = a;
|
|
1130
|
+
const k = stableStringify(bare);
|
|
1131
|
+
if (writtenActors.has(k)) continue;
|
|
1132
|
+
writtenActors.add(k);
|
|
1133
|
+
await store.appendActor(a);
|
|
1134
|
+
}
|
|
1135
|
+
for (const p of pickups) {
|
|
1136
|
+
await store.appendPickup({
|
|
1137
|
+
...p,
|
|
1138
|
+
itemId: await resolve(idMap, p.itemId),
|
|
1139
|
+
...p.pickupItemId ? { pickupItemId: await resolve(idMap, p.pickupItemId) } : {}
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
async function finishFailed(entry, failure) {
|
|
1145
|
+
const durationMs = clock.now() - entry.t0;
|
|
1146
|
+
await record({
|
|
1147
|
+
taskId: entry.key,
|
|
1148
|
+
connector: entry.connector.id,
|
|
1149
|
+
status: "failed",
|
|
1150
|
+
transport: entry.lastTransport,
|
|
1151
|
+
cause: failure.cause,
|
|
1152
|
+
reason: failure.challenge ? "challenge" : failure.message,
|
|
1153
|
+
order: entry.order,
|
|
1154
|
+
payload: payloadOf(entry.task),
|
|
1155
|
+
escalations: entry.escalations,
|
|
1156
|
+
counters: { items: 0, newItems: 0, duplicates: 0, observations: 0, metricValues: 0, durationMs }
|
|
1157
|
+
});
|
|
1158
|
+
await emit("task.end", {
|
|
1159
|
+
connector: entry.connector.id,
|
|
1160
|
+
taskId: entry.task.id,
|
|
1161
|
+
status: "failed",
|
|
1162
|
+
cause: failure.cause,
|
|
1163
|
+
message: failure.message,
|
|
1164
|
+
durationMs
|
|
1165
|
+
});
|
|
1166
|
+
resolveSlot(entry);
|
|
1167
|
+
}
|
|
1168
|
+
async function attempt(entry) {
|
|
1169
|
+
const connector = entry.connector;
|
|
1170
|
+
const state = states.get(connector.id);
|
|
1171
|
+
if (stopping()) return;
|
|
1172
|
+
if (state.stopped) return skip(entry, "challenge", "challenge");
|
|
1173
|
+
if (!entry.started) {
|
|
1174
|
+
if (!counted.has(entry.key)) {
|
|
1175
|
+
if (state.cap !== void 0 && state.started >= state.cap) {
|
|
1176
|
+
return skip(entry, `per-connector cap reached (${state.cap})`, "cap");
|
|
1177
|
+
}
|
|
1178
|
+
if (recipe.caps?.total !== void 0 && totalStarted >= recipe.caps.total) {
|
|
1179
|
+
return skip(entry, `total cap reached (${recipe.caps.total})`, "total cap");
|
|
1180
|
+
}
|
|
1181
|
+
state.started++;
|
|
1182
|
+
totalStarted++;
|
|
1183
|
+
counted.add(entry.key);
|
|
1184
|
+
await record({
|
|
1185
|
+
taskId: entry.key,
|
|
1186
|
+
connector: connector.id,
|
|
1187
|
+
status: "started",
|
|
1188
|
+
order: entry.order,
|
|
1189
|
+
payload: payloadOf(entry.task)
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
entry.started = true;
|
|
1193
|
+
entry.t0 = clock.now();
|
|
1194
|
+
await emit("task.start", { connector: connector.id, taskId: entry.task.id });
|
|
1195
|
+
}
|
|
1196
|
+
const name = state.transports[entry.attempt];
|
|
1197
|
+
entry.lastTransport = name;
|
|
1198
|
+
let result;
|
|
1199
|
+
let failure;
|
|
1200
|
+
let failedRaws = [];
|
|
1201
|
+
let thrown = false;
|
|
1202
|
+
try {
|
|
1203
|
+
const sig = state.controller.signal;
|
|
1204
|
+
result = await connector.fetch(entry.task, handleFor(name, connector, sig), { secrets, signal: sig, now: iso() });
|
|
1205
|
+
failedRaws = result.raws;
|
|
1206
|
+
const found = result.raws.map((r) => classifyRaw(r, name === "browser")).filter((f) => f !== void 0);
|
|
1207
|
+
failure = found.find((f) => f.challenge) ?? found.find((f) => f.cause === "challenge") ?? found[0];
|
|
1208
|
+
if (!failure && result.raws.length === 0) {
|
|
1209
|
+
failure = { fallback: true, challenge: false, cause: "empty", message: "no content" };
|
|
1210
|
+
}
|
|
1211
|
+
} catch (e) {
|
|
1212
|
+
if (aborted()) return;
|
|
1213
|
+
if (e instanceof MissingSecretError) {
|
|
1214
|
+
const next = state.transports[entry.attempt + 1];
|
|
1215
|
+
if (!next) return skip(entry, `missing_secret:${e.secret}`, "missing secret");
|
|
1216
|
+
entry.escalations.push({ from: name, to: next });
|
|
1217
|
+
await emit("escalation", { connector: connector.id, taskId: entry.task.id, from: name, to: next, cause: "missing_secret" });
|
|
1218
|
+
entry.attempt++;
|
|
1219
|
+
enqueue(entry);
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
failure = classifyError(e, name === "browser");
|
|
1223
|
+
if (state.stopped && !failure.challenge) return skip(entry, "challenge", "challenge");
|
|
1224
|
+
thrown = true;
|
|
1225
|
+
if (e instanceof TransportError && e.url) {
|
|
1226
|
+
failedRaws = [{ url: e.url, ext: e.ext ?? "bin", bytes: e.body ?? new Uint8Array(), httpStatus: e.status, contentType: e.contentType }];
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
const fetchedAt = iso();
|
|
1230
|
+
const firstHalt = failure?.challenge === true && !state.stopped;
|
|
1231
|
+
const halted = failure?.challenge ? haltConnector(state) : [];
|
|
1232
|
+
if (failure) {
|
|
1233
|
+
const f = failure;
|
|
1234
|
+
await write(async () => {
|
|
1235
|
+
for (const raw of failedRaws) {
|
|
1236
|
+
await store.putRaw({
|
|
1237
|
+
connector: connector.id,
|
|
1238
|
+
ext: raw.ext,
|
|
1239
|
+
bytes: raw.bytes,
|
|
1240
|
+
url: raw.url,
|
|
1241
|
+
fetchedAt,
|
|
1242
|
+
httpStatus: raw.httpStatus,
|
|
1243
|
+
contentType: raw.contentType,
|
|
1244
|
+
transport: name,
|
|
1245
|
+
runId,
|
|
1246
|
+
taskId: entry.key,
|
|
1247
|
+
failure: thrown ? f.cause : classifyRaw(raw, name === "browser")?.cause ?? f.cause
|
|
1248
|
+
});
|
|
1249
|
+
}
|
|
1250
|
+
});
|
|
1251
|
+
if (f.challenge) {
|
|
1252
|
+
await finishFailed(entry, f);
|
|
1253
|
+
await skipHalted(state, halted, firstHalt);
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
const next = state.transports[entry.attempt + 1];
|
|
1257
|
+
if (f.fallback && next) {
|
|
1258
|
+
entry.escalations.push({ from: name, to: next });
|
|
1259
|
+
await emit("escalation", { connector: connector.id, taskId: entry.task.id, from: name, to: next, cause: f.cause });
|
|
1260
|
+
entry.attempt++;
|
|
1261
|
+
enqueue(entry);
|
|
1262
|
+
return;
|
|
1263
|
+
}
|
|
1264
|
+
return finishFailed(entry, f);
|
|
1265
|
+
}
|
|
1266
|
+
const prepared = [];
|
|
1267
|
+
const tasks = [];
|
|
1268
|
+
const stored = await write(async () => {
|
|
1269
|
+
const out = [];
|
|
1270
|
+
for (const raw of result.raws) {
|
|
1271
|
+
const put = await store.putRaw({
|
|
1272
|
+
connector: connector.id,
|
|
1273
|
+
ext: raw.ext,
|
|
1274
|
+
bytes: raw.bytes,
|
|
1275
|
+
url: raw.url,
|
|
1276
|
+
fetchedAt,
|
|
1277
|
+
httpStatus: raw.httpStatus,
|
|
1278
|
+
contentType: raw.contentType,
|
|
1279
|
+
transport: name,
|
|
1280
|
+
runId,
|
|
1281
|
+
taskId: entry.key
|
|
1282
|
+
});
|
|
1283
|
+
out.push({ raw, ref: put.ref, hash: put.hash });
|
|
1284
|
+
}
|
|
1285
|
+
return out;
|
|
1286
|
+
});
|
|
1287
|
+
let parseError;
|
|
1288
|
+
try {
|
|
1289
|
+
for (const { raw, ref, hash } of stored) {
|
|
1290
|
+
const parsed = await connector.parse({
|
|
1291
|
+
connector: connector.id,
|
|
1292
|
+
task: entry.task,
|
|
1293
|
+
raw: { ref, url: raw.url, ext: raw.ext, bytes: raw.bytes, httpStatus: raw.httpStatus, contentType: raw.contentType, fetchedAt, transport: name }
|
|
1294
|
+
});
|
|
1295
|
+
prepared.push(await prepare(entry, parsed, ref, hash, fetchedAt, name));
|
|
1296
|
+
}
|
|
1297
|
+
for (const t of result.tasks ?? []) tasks.push(CollectTask.parse(t));
|
|
1298
|
+
} catch (e) {
|
|
1299
|
+
parseError = e instanceof Error ? e.message : String(e);
|
|
1300
|
+
}
|
|
1301
|
+
if (parseError !== void 0) {
|
|
1302
|
+
return finishFailed(entry, { challenge: false, cause: "parse", message: parseError });
|
|
1303
|
+
}
|
|
1304
|
+
if (slots[0] === entry || !slots.includes(entry)) return commit(entry, prepared, tasks, name);
|
|
1305
|
+
commitsActive++;
|
|
1306
|
+
const p = commit(entry, prepared, tasks, name).catch((e) => {
|
|
1307
|
+
if (stopping() && e?.name === "AbortError") return;
|
|
1308
|
+
fatal ??= toError(e);
|
|
1309
|
+
}).finally(() => {
|
|
1310
|
+
active.delete(p);
|
|
1311
|
+
commitsActive--;
|
|
1312
|
+
pump();
|
|
1313
|
+
});
|
|
1314
|
+
active.add(p);
|
|
1315
|
+
}
|
|
1316
|
+
async function commit(entry, prepared, tasks, name) {
|
|
1317
|
+
const connector = entry.connector;
|
|
1318
|
+
const state = states.get(connector.id);
|
|
1319
|
+
const wasHead = slots[0] === entry || !slots.includes(entry);
|
|
1320
|
+
if (!await awaitTurn(entry)) return;
|
|
1321
|
+
const counters = { items: 0, newItems: 0, duplicates: 0, observations: 0, metricValues: 0 };
|
|
1322
|
+
const followUps = [];
|
|
1323
|
+
const outcome = { v: "done" };
|
|
1324
|
+
await write(async () => {
|
|
1325
|
+
if (fatal !== void 0 || aborted() && !wasHead) {
|
|
1326
|
+
outcome.v = "bail";
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
if (state.stopped) {
|
|
1330
|
+
outcome.v = "stopped";
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
await ingest(await sample(entry, prepared), counters);
|
|
1334
|
+
tasks.forEach((task, j) => {
|
|
1335
|
+
const k = key(connector.id, task.id);
|
|
1336
|
+
if (known.has(k)) return;
|
|
1337
|
+
known.add(k);
|
|
1338
|
+
followUps.push(mkEntry(state, k, task, [...entry.order, j]));
|
|
1339
|
+
});
|
|
1340
|
+
for (const f of followUps) {
|
|
1341
|
+
registerSlot(f);
|
|
1342
|
+
await store.appendTask(runId, taskRecord({
|
|
1343
|
+
taskId: f.key,
|
|
1344
|
+
connector: connector.id,
|
|
1345
|
+
status: "pending",
|
|
1346
|
+
order: f.order,
|
|
1347
|
+
payload: payloadOf(f.task)
|
|
1348
|
+
}));
|
|
1349
|
+
}
|
|
1350
|
+
await store.appendTask(runId, taskRecord({
|
|
1351
|
+
taskId: entry.key,
|
|
1352
|
+
connector: connector.id,
|
|
1353
|
+
status: "done",
|
|
1354
|
+
transport: name,
|
|
1355
|
+
order: entry.order,
|
|
1356
|
+
payload: payloadOf(entry.task),
|
|
1357
|
+
escalations: entry.escalations,
|
|
1358
|
+
counters: { ...counters, durationMs: clock.now() - entry.t0 }
|
|
1359
|
+
}));
|
|
1360
|
+
});
|
|
1361
|
+
if (outcome.v === "bail") return;
|
|
1362
|
+
if (outcome.v === "stopped") return skip(entry, "challenge", "challenge");
|
|
1363
|
+
resolveSlot(entry);
|
|
1364
|
+
for (const f of followUps) enqueue(f);
|
|
1365
|
+
await emit("task.end", {
|
|
1366
|
+
connector: connector.id,
|
|
1367
|
+
taskId: entry.task.id,
|
|
1368
|
+
status: "done",
|
|
1369
|
+
transport: name,
|
|
1370
|
+
durationMs: clock.now() - entry.t0,
|
|
1371
|
+
...counters
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
pump();
|
|
1375
|
+
if (signal) {
|
|
1376
|
+
let timer;
|
|
1377
|
+
const gaveUp = new Promise((resolve2) => {
|
|
1378
|
+
const arm = () => {
|
|
1379
|
+
timer = setTimeout(() => resolve2("gaveUp"), abortGraceMs);
|
|
1380
|
+
};
|
|
1381
|
+
if (signal.aborted) arm();
|
|
1382
|
+
else signal.addEventListener("abort", arm, { once: true });
|
|
1383
|
+
});
|
|
1384
|
+
const first = await Promise.race([finished.then(() => "done"), gaveUp]);
|
|
1385
|
+
clearTimeout(timer);
|
|
1386
|
+
if (first === "gaveUp") {
|
|
1387
|
+
grace.expired = true;
|
|
1388
|
+
grace.closing = true;
|
|
1389
|
+
await writeSerial(() => store.appendEvent(runId, { at: iso(), type: "warning", data: { message: `abort grace period (${abortGraceMs} ms) expired with tasks still running; they stay started and are not written` } }));
|
|
1390
|
+
}
|
|
1391
|
+
} else await finished;
|
|
1392
|
+
if (!grace.expired) await Promise.allSettled([...active]);
|
|
1393
|
+
if (fatal !== void 0) {
|
|
1394
|
+
try {
|
|
1395
|
+
await write(async () => store.writeReport(runId, await buildReport(runId, recipe, startedAt, states)));
|
|
1396
|
+
} catch {
|
|
1397
|
+
}
|
|
1398
|
+
throw new CollectRunError(runId, fatal);
|
|
1399
|
+
}
|
|
1400
|
+
if (aborted()) await emit("cancelled", {});
|
|
1401
|
+
const report = await buildReport(runId, recipe, startedAt, states);
|
|
1402
|
+
await emit("run.end", { connectors: report.connectors.map((c) => ({ connector: c.connector, status: c.status })) });
|
|
1403
|
+
await write(() => store.writeReport(runId, report));
|
|
1404
|
+
grace.closing = false;
|
|
1405
|
+
return report;
|
|
1406
|
+
}
|
|
1407
|
+
async function buildReport(runId, recipe, startedAt, states) {
|
|
1408
|
+
const { records: tasks } = await readAll(store.tasks(runId));
|
|
1409
|
+
const samplingRows = recipe.sampling !== void 0 ? (await readAll(store.sampling(runId))).records : [];
|
|
1410
|
+
const coverage = await computeCoverage(
|
|
1411
|
+
store,
|
|
1412
|
+
[...states.values()].flatMap((s) => s.connector ? [s.connector] : [])
|
|
1413
|
+
);
|
|
1414
|
+
const connectors = [];
|
|
1415
|
+
for (const s of states.values()) {
|
|
1416
|
+
const mine = tasks.filter((t) => t.connector === s.id);
|
|
1417
|
+
const count = (status2) => mine.filter((t) => t.status === status2).length;
|
|
1418
|
+
const done = count("done");
|
|
1419
|
+
const failedTasks = mine.filter((t) => t.status === "failed");
|
|
1420
|
+
const skipped = count("skipped");
|
|
1421
|
+
const pending = count("pending") + count("started");
|
|
1422
|
+
const failures = {};
|
|
1423
|
+
for (const t of failedTasks) failures[t.cause ?? "other"] = (failures[t.cause ?? "other"] ?? 0) + 1;
|
|
1424
|
+
const sum = { items: 0, newItems: 0, duplicates: 0, observations: 0, metricValues: 0, durationMs: 0 };
|
|
1425
|
+
const escalations = /* @__PURE__ */ new Map();
|
|
1426
|
+
for (const t of mine) {
|
|
1427
|
+
for (const k of Object.keys(sum)) sum[k] += t.counters?.[k] ?? 0;
|
|
1428
|
+
for (const e of t.escalations ?? []) {
|
|
1429
|
+
const ek = `${e.from}>${e.to}`;
|
|
1430
|
+
const cur = escalations.get(ek) ?? { from: e.from, to: e.to, count: 0 };
|
|
1431
|
+
cur.count++;
|
|
1432
|
+
escalations.set(ek, cur);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
const challenged = mine.some((t) => t.reason === "challenge");
|
|
1436
|
+
const missing = mine.find((t) => t.status === "skipped" && t.reason?.startsWith("missing_secret:"));
|
|
1437
|
+
let status = "ok";
|
|
1438
|
+
let reason;
|
|
1439
|
+
let skippedReason = s.skipReason;
|
|
1440
|
+
if (!skippedReason && missing && done === 0 && failedTasks.length === 0 && skipped === mine.length) skippedReason = missing.reason;
|
|
1441
|
+
if (skippedReason) status = "skipped";
|
|
1442
|
+
else if (challenged) {
|
|
1443
|
+
status = done > 0 ? "partial" : "failed";
|
|
1444
|
+
reason = "challenge: the connector was stopped and its remaining tasks skipped";
|
|
1445
|
+
} else if (done === 0 && failedTasks.length > 0) {
|
|
1446
|
+
status = "failed";
|
|
1447
|
+
reason = "every task failed";
|
|
1448
|
+
} else if (done > 0 && sum.items === 0) {
|
|
1449
|
+
status = "failed";
|
|
1450
|
+
reason = "shape check: the run returned no items";
|
|
1451
|
+
} else if (done > 0 && (s.connector?.counters.length ?? 0) > 0 && sum.metricValues === 0) {
|
|
1452
|
+
status = "failed";
|
|
1453
|
+
reason = "shape check: every counter is missing";
|
|
1454
|
+
} else if (failedTasks.length > 0 || skipped > 0 || pending > 0) {
|
|
1455
|
+
status = "partial";
|
|
1456
|
+
reason = pending > 0 ? "pending tasks remain" : failedTasks.length > 0 ? `${failedTasks.length} task(s) failed` : `${skipped} task(s) skipped`;
|
|
1457
|
+
}
|
|
1458
|
+
connectors.push({
|
|
1459
|
+
connector: s.id,
|
|
1460
|
+
status,
|
|
1461
|
+
...skippedReason ? { skippedReason } : {},
|
|
1462
|
+
...reason ? { reason } : {},
|
|
1463
|
+
tasks: { planned: mine.length, done, failed: failedTasks.length, skipped },
|
|
1464
|
+
newItems: sum.newItems,
|
|
1465
|
+
observations: sum.observations,
|
|
1466
|
+
duplicates: sum.duplicates,
|
|
1467
|
+
failures,
|
|
1468
|
+
escalations: [...escalations.values()],
|
|
1469
|
+
durationMs: sum.durationMs,
|
|
1470
|
+
...recipe.sampling !== void 0 ? { sampled: sampledOf(samplingRows.filter((r) => r.connector === s.id)) } : {},
|
|
1471
|
+
coverage: { cells: coverage.cells.filter((c) => c.platform === s.id) }
|
|
1472
|
+
});
|
|
1473
|
+
}
|
|
1474
|
+
return { runId, startedAt, finishedAt: iso(), connectors, coverage };
|
|
1475
|
+
}
|
|
1476
|
+
return {
|
|
1477
|
+
async run(recipeInput, runOptions = {}) {
|
|
1478
|
+
const recipe = Recipe.parse(recipeInput);
|
|
1479
|
+
const runId = runOptions.runId ?? `${iso().replace(/[-:]/g, "").replace(/\..*$/, "")}-${randomId(random)}`;
|
|
1480
|
+
const { runId: _ignored, ...rest } = runOptions;
|
|
1481
|
+
return execute(runId, recipe, "new", rest);
|
|
1482
|
+
},
|
|
1483
|
+
async resume(runId, runOptions = {}) {
|
|
1484
|
+
const run = await store.getRun(runId);
|
|
1485
|
+
if (!run) throw new Error(`unknown run ${runId}`);
|
|
1486
|
+
if (run.origin === "reparse") throw new Error(`run ${runId} is a copy kept by reparse and cannot be resumed; run its recipe again instead`);
|
|
1487
|
+
return execute(runId, run.recipe, "resume", runOptions);
|
|
1488
|
+
}
|
|
1489
|
+
};
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
export { CollectRunError, candidateDomain, computeCoverage, createCollector, createSampler, domainOf, isSecretRecorder, memoryStore, mulberry32, recordSecrets };
|
|
1493
|
+
//# sourceMappingURL=index.mjs.map
|
|
1494
|
+
//# sourceMappingURL=index.mjs.map
|