@apocaliss92/addon-series-scraper 0.0.0-stage → 0.1.21

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.
@@ -0,0 +1,46 @@
1
+ import { createRequire as __scraperCreateRequire, createRequire } from "node:module";
2
+ __scraperCreateRequire(import.meta.url);
3
+ // \0rolldown/runtime.js
4
+ var __create = Object.create;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __esmMin = (fn, res, err) => () => {
11
+ if (err) throw err[0];
12
+ try {
13
+ return fn && (res = fn(fn = 0)), res;
14
+ } catch (e) {
15
+ throw err = [e], e;
16
+ }
17
+ };
18
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
19
+ var __exportAll = (all, flags) => {
20
+ let target = Object.setPrototypeOf({}, null);
21
+ for (var name in all) __defProp(target, name, {
22
+ get: all[name],
23
+ enumerable: true
24
+ });
25
+ if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
26
+ return flags & 2 ? target : Object.preventExtensions(target);
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) {
31
+ desc = __getOwnPropDesc(from, key);
32
+ __defProp(to, key, {
33
+ get: desc && desc.get && !desc.configurable ? desc.get : () => from[key],
34
+ enumerable: !desc || desc.enumerable
35
+ });
36
+ }
37
+ }
38
+ return to;
39
+ };
40
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
41
+ value: mod,
42
+ enumerable: true
43
+ }) : target, mod));
44
+ var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
45
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
46
+ export { __toCommonJS as a, __require as i, __esmMin as n, __toESM as o, __exportAll as r, __commonJSMin as t };
@@ -0,0 +1,420 @@
1
+ import { createRequire as __scraperCreateRequire } from "node:module";
2
+ __scraperCreateRequire(import.meta.url);
3
+ import { a as errorText, i as HOST_LOG_TAGS, v as require_dist } from "./proxy-Btrb1iBN.js";
4
+ import { z } from "zod";
5
+ import { defineRecordKinds } from "@dominevo/types";
6
+ // src/embedded/record-kinds.ts
7
+ var import_dist = require_dist();
8
+ /** One stored part of a collection: its name and its JSON value (see `collection-parts.ts`). */
9
+ var CollectionPartSchema = z.object({
10
+ part: z.string(),
11
+ value: z.unknown()
12
+ });
13
+ /** A secret the core stores under a name the addon cannot list in advance (an egress id, a webhook id). */
14
+ var NamedSecretSchema = z.object({
15
+ name: z.string(),
16
+ value: z.string().meta({ secret: true })
17
+ });
18
+ /** The record kind of a collection: `table` -> `scraper-table`. One kind per collection. */
19
+ function kindNameOf(collection) {
20
+ return `scraper-${collection}`;
21
+ }
22
+ /** A part of a row is at most this big; the engine's own ceiling is 1 MiB per row. */
23
+ var COLLECTION_ROW_BYTES = 1048576;
24
+ function collectionKind(collection) {
25
+ return {
26
+ schema: CollectionPartSchema,
27
+ class: "config",
28
+ writeTrigger: `the scraper changes its "${collection}" collection (an operator edit or a download finishing)`,
29
+ device: "none",
30
+ at: "none",
31
+ retention: { none: "the scraper owns this state; nothing ages out" },
32
+ maxDataBytes: COLLECTION_ROW_BYTES
33
+ };
34
+ }
35
+ /** The collection kinds, by kind name (`scraper-<collection>`). */
36
+ var COLLECTION_RECORD_KINDS = defineRecordKinds(Object.fromEntries(import_dist.STATE_COLLECTIONS.map((name) => [kindNameOf(name), collectionKind(name)])));
37
+ /** The declared kind of one collection. */
38
+ function collectionKindOf(collection) {
39
+ const kind = COLLECTION_RECORD_KINDS[kindNameOf(collection)];
40
+ if (kind === void 0) throw new Error(`series-scraper: no record kind for the "${collection}" collection`);
41
+ return kind;
42
+ }
43
+ /** The kind of the credentials the core mints under names the addon cannot list in advance. */
44
+ var SECRET_RECORD_KINDS = defineRecordKinds({ "scraper-secrets": {
45
+ schema: NamedSecretSchema,
46
+ class: "config",
47
+ writeTrigger: "the scraper stores a credential under a name it minted (a network exit, a webhook)",
48
+ device: "none",
49
+ at: "none",
50
+ retention: { none: "the scraper owns its credentials; they are released when it deletes one" }
51
+ } });
52
+ /** Every record kind the embedded host declares. */
53
+ var SCRAPER_RECORD_KINDS = {
54
+ ...COLLECTION_RECORD_KINDS,
55
+ ...SECRET_RECORD_KINDS
56
+ };
57
+ var SECRETS_KIND = "scraper-secrets";
58
+ // src/embedded/write-behind.ts
59
+ var DEFAULT_DEBOUNCE_MS = 750;
60
+ var DEFAULT_RETRY_DELAYS_MS = [
61
+ 2e3,
62
+ 5e3,
63
+ 15e3,
64
+ 3e4
65
+ ];
66
+ var DEFAULT_MAX_FAST_RETRIES = 10;
67
+ var DEFAULT_SLOW_RETRY_MS = 3e5;
68
+ /**
69
+ * Write-behind for keyed state: `mark(key)` says "this key changed", the key is written after a
70
+ * quiet period, and a failed write is logged with the key's name and retried — never dropped.
71
+ * `flush()` writes every pending key at once (shutdown) and answers the keys that still failed.
72
+ */
73
+ var WriteBehind = class {
74
+ options;
75
+ dirty = /* @__PURE__ */ new Set();
76
+ timers = /* @__PURE__ */ new Map();
77
+ running = /* @__PURE__ */ new Map();
78
+ failures = /* @__PURE__ */ new Map();
79
+ closed = false;
80
+ constructor(options) {
81
+ this.options = options;
82
+ }
83
+ mark(key) {
84
+ this.dirty.add(key);
85
+ if (!this.running.has(key)) this.schedule(key, this.options.debounceMs ?? DEFAULT_DEBOUNCE_MS);
86
+ }
87
+ /** True while a key waits for its write or for a retry. */
88
+ pending() {
89
+ return [...this.dirty];
90
+ }
91
+ /** True while a key is dirty or its write is in flight: its in-memory value is the newer one. */
92
+ busy(key) {
93
+ return this.dirty.has(key) || this.running.has(key);
94
+ }
95
+ /** Write everything pending now, once. The keys whose write failed stay pending and are returned. */
96
+ async flush() {
97
+ this.closed = true;
98
+ for (const timer of this.timers.values()) clearTimeout(timer);
99
+ this.timers.clear();
100
+ await Promise.all([...this.running.values()]);
101
+ await Promise.all([...this.dirty].map((key) => this.run(key)));
102
+ return [...this.dirty];
103
+ }
104
+ schedule(key, delayMs) {
105
+ if (this.closed) return;
106
+ const existing = this.timers.get(key);
107
+ if (existing !== void 0) clearTimeout(existing);
108
+ const timer = setTimeout(() => {
109
+ this.timers.delete(key);
110
+ this.run(key);
111
+ }, delayMs);
112
+ timer.unref();
113
+ this.timers.set(key, timer);
114
+ }
115
+ run(key) {
116
+ const inFlight = this.running.get(key);
117
+ if (inFlight !== void 0) return inFlight;
118
+ const job = this.attempt(key).finally(() => {
119
+ this.running.delete(key);
120
+ });
121
+ this.running.set(key, job);
122
+ return job;
123
+ }
124
+ async attempt(key) {
125
+ this.dirty.delete(key);
126
+ try {
127
+ await this.options.write(key);
128
+ this.failures.delete(key);
129
+ } catch (error) {
130
+ this.dirty.add(key);
131
+ const failed = (this.failures.get(key) ?? 0) + 1;
132
+ this.failures.set(key, failed);
133
+ const maxFast = this.options.maxFastRetries ?? DEFAULT_MAX_FAST_RETRIES;
134
+ const meta = {
135
+ [this.options.noun]: key,
136
+ attempt: failed,
137
+ reason: errorText(error)
138
+ };
139
+ if (failed < maxFast) this.options.logger.warn(`series-scraper: writing ${this.options.noun} "${key}" failed, will retry`, {
140
+ tags: HOST_LOG_TAGS,
141
+ meta
142
+ });
143
+ else if (failed === maxFast) this.options.logger.error(`series-scraper: writing ${this.options.noun} "${key}" keeps failing, retrying slowly and logging no more`, {
144
+ tags: HOST_LOG_TAGS,
145
+ meta
146
+ });
147
+ this.schedule(key, this.retryDelay(failed));
148
+ return;
149
+ }
150
+ if (this.dirty.has(key)) this.schedule(key, this.options.debounceMs ?? DEFAULT_DEBOUNCE_MS);
151
+ }
152
+ retryDelay(failed) {
153
+ if (failed >= (this.options.maxFastRetries ?? DEFAULT_MAX_FAST_RETRIES)) return this.options.slowRetryMs ?? DEFAULT_SLOW_RETRY_MS;
154
+ const delays = this.options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
155
+ return delays[Math.min(failed, delays.length) - 1] ?? 3e4;
156
+ }
157
+ };
158
+ // src/embedded/secret-store.ts
159
+ /** The secrets the core stores under a fixed name: `password` fields of the cluster settings. */
160
+ var FIXED_SECRETS = [
161
+ "sonarrApiKey",
162
+ "radarrApiKey",
163
+ "plexToken"
164
+ ];
165
+ function isFixed(name) {
166
+ return FIXED_SECRETS.some((fixed) => fixed === name);
167
+ }
168
+ /** A record id the core's secret names (`egress.<id>.privateKey`) map onto 1:1. */
169
+ function recordIdOf(name) {
170
+ return name;
171
+ }
172
+ /**
173
+ * The core's credentials in the keychain, in two places that are both the keychain:
174
+ * the three fixed ones are `password` fields of the addon's cluster settings (they show on the
175
+ * settings page as "set"), the ones the core mints per network exit or webhook are rows of a record
176
+ * kind whose `value` is a secret field. Both are read once at boot (`hydrate`) and served from memory.
177
+ * A `set` answers at once and is written through the settings API / the records behind it.
178
+ */
179
+ var SettingsSecretStore = class {
180
+ options;
181
+ values = /* @__PURE__ */ new Map();
182
+ handle;
183
+ behind;
184
+ constructor(options) {
185
+ this.options = options;
186
+ this.handle = options.records.kind(SECRET_RECORD_KINDS[SECRETS_KIND]);
187
+ this.behind = new WriteBehind({
188
+ write: (name) => this.persist(name),
189
+ logger: options.logger,
190
+ noun: "secret",
191
+ ...options.writeBehind
192
+ });
193
+ }
194
+ /** Read every credential. Call once, before the core module is created (the kinds are declared by the state store). */
195
+ async hydrate() {
196
+ const fixed = await this.options.settings.get();
197
+ for (const name of FIXED_SECRETS) {
198
+ const value = fixed[name];
199
+ if (typeof value === "string" && value !== "") this.values.set(name, value);
200
+ }
201
+ let cursor;
202
+ do {
203
+ const page = await this.handle.query({
204
+ limit: 1e3,
205
+ ...cursor === void 0 ? {} : { cursor }
206
+ }, { resolveSecrets: true });
207
+ for (const row of page.records) if (typeof row.data.value === "string" && row.data.value !== "") this.values.set(row.data.name, row.data.value);
208
+ cursor = page.nextCursor ?? void 0;
209
+ } while (cursor !== void 0);
210
+ }
211
+ /** A fixed secret changed on the settings page: take the new value. */
212
+ async refreshFixed() {
213
+ const fixed = await this.options.settings.get();
214
+ for (const name of FIXED_SECRETS) {
215
+ const value = fixed[name];
216
+ if (this.behind.busy(name)) continue;
217
+ if (typeof value === "string" && value !== "") this.values.set(name, value);
218
+ else this.values.delete(name);
219
+ }
220
+ }
221
+ get(name) {
222
+ return this.values.get(name);
223
+ }
224
+ set(name, value) {
225
+ if (value === "") {
226
+ this.delete(name);
227
+ return;
228
+ }
229
+ this.values.set(name, value);
230
+ this.behind.mark(name);
231
+ }
232
+ delete(name) {
233
+ this.values.delete(name);
234
+ this.behind.mark(name);
235
+ }
236
+ flush() {
237
+ return this.behind.flush();
238
+ }
239
+ /** The settings API merges and validates the whole document: two fixed secrets never write at once. */
240
+ settingsQueue = Promise.resolve();
241
+ persistFixed(name) {
242
+ const run = async () => {
243
+ const value = this.values.get(name);
244
+ if (value === void 0) await this.options.settings.unset([name]);
245
+ else await this.options.settings.patch({ [name]: value });
246
+ };
247
+ const next = this.settingsQueue.then(run, run);
248
+ this.settingsQueue = next.catch(() => void 0);
249
+ return next;
250
+ }
251
+ async persist(name) {
252
+ const value = this.values.get(name);
253
+ if (isFixed(name)) return this.persistFixed(name);
254
+ if (value === void 0) await this.handle.delete(recordIdOf(name));
255
+ else await this.handle.put({
256
+ id: recordIdOf(name),
257
+ data: {
258
+ name,
259
+ value
260
+ }
261
+ });
262
+ }
263
+ };
264
+ // src/embedded/collection-parts.ts
265
+ var SHAPE_ID = "shape";
266
+ var ELEMENT_PREFIX = "a:";
267
+ var KEY_PREFIX = "k:";
268
+ var SCALAR_ID = "value";
269
+ var ELEMENT_DIGITS = 8;
270
+ function isObject(value) {
271
+ return typeof value === "object" && value !== null && !Array.isArray(value);
272
+ }
273
+ /** The parts of a value, shape row included. Throws when a key cannot be a record id. */
274
+ function partsOf(value) {
275
+ if (value === void 0) return [{
276
+ id: SHAPE_ID,
277
+ part: SHAPE_ID,
278
+ value: "unset"
279
+ }];
280
+ if (Array.isArray(value)) return [{
281
+ id: SHAPE_ID,
282
+ part: SHAPE_ID,
283
+ value: "array"
284
+ }, ...value.map((element, index) => {
285
+ const id = `${ELEMENT_PREFIX}${String(index).padStart(ELEMENT_DIGITS, "0")}`;
286
+ return {
287
+ id,
288
+ part: id,
289
+ value: element
290
+ };
291
+ })];
292
+ if (isObject(value)) return [{
293
+ id: SHAPE_ID,
294
+ part: SHAPE_ID,
295
+ value: "object"
296
+ }, ...Object.entries(value).map(([key, entry]) => {
297
+ const id = `${KEY_PREFIX}${key}`;
298
+ if (id.length > 256) throw new Error(`the key "${key.slice(0, 40)}…" is too long to store`);
299
+ return {
300
+ id,
301
+ part: id,
302
+ value: entry
303
+ };
304
+ })];
305
+ return [{
306
+ id: SHAPE_ID,
307
+ part: SHAPE_ID,
308
+ value: "scalar"
309
+ }, {
310
+ id: SCALAR_ID,
311
+ part: SCALAR_ID,
312
+ value
313
+ }];
314
+ }
315
+ /** The value the parts describe; `undefined` when there is no shape row (nothing was ever saved). */
316
+ function valueOf(rows) {
317
+ const shape = rows.find((row) => row.id === SHAPE_ID)?.value;
318
+ const body = rows.filter((row) => row.id !== SHAPE_ID);
319
+ if (shape === "array") return body.filter((row) => row.id.startsWith(ELEMENT_PREFIX)).sort((a, b) => a.id.localeCompare(b.id)).map((row) => row.value);
320
+ if (shape === "object") return Object.fromEntries(body.filter((row) => row.id.startsWith(KEY_PREFIX)).map((row) => [row.id.slice(2), row.value]));
321
+ if (shape === "scalar") return body.find((row) => row.id === SCALAR_ID)?.value;
322
+ }
323
+ // src/embedded/state-store.ts
324
+ /** Ops per batch: the engine takes 1000 and 4 MiB; a table of long rows stays well inside both. */
325
+ var WRITE_CHUNK = 200;
326
+ var READ_PAGE = 1e3;
327
+ function isCollection(name) {
328
+ return import_dist.STATE_COLLECTIONS.some((known) => known === name);
329
+ }
330
+ /**
331
+ * The scraper's collections on `ctx.records`, one record kind per collection.
332
+ *
333
+ * The core reads state synchronously, so `hydrate()` loads every collection into memory BEFORE the
334
+ * Nest module exists and `load` answers from that cache. `save` updates the cache at once and the
335
+ * collection is written behind it (debounced, only the parts that changed); `flush()` is the
336
+ * shutdown path. A failed write is logged with the collection's name and retried.
337
+ */
338
+ var RecordsStateStore = class {
339
+ options;
340
+ cache = /* @__PURE__ */ new Map();
341
+ /** The serialised parts the records hold, per collection: the base a write is diffed against. */
342
+ persisted = /* @__PURE__ */ new Map();
343
+ handles = /* @__PURE__ */ new Map();
344
+ behind;
345
+ constructor(options) {
346
+ this.options = options;
347
+ this.behind = new WriteBehind({
348
+ write: (collection) => this.persist(collection),
349
+ logger: options.logger,
350
+ noun: "collection",
351
+ ...options.writeBehind
352
+ });
353
+ }
354
+ /** Declare the kinds and read every collection. Call once, before the core module is created. */
355
+ async hydrate() {
356
+ await this.options.records.declare(SCRAPER_RECORD_KINDS);
357
+ for (const collection of import_dist.STATE_COLLECTIONS) {
358
+ const handle = this.options.records.kind(collectionKindOf(collection));
359
+ this.handles.set(collection, handle);
360
+ const rows = await this.readAll(handle);
361
+ this.cache.set(collection, valueOf(rows));
362
+ this.persisted.set(collection, new Map(rows.map((row) => [row.id, JSON.stringify(row.value)])));
363
+ }
364
+ }
365
+ load(name) {
366
+ return this.cache.get(name);
367
+ }
368
+ save(name, value) {
369
+ if (!isCollection(name)) throw new Error(`series-scraper: "${name}" is not a collection the scraper stores`);
370
+ partsOf(value);
371
+ this.cache.set(name, value);
372
+ this.behind.mark(name);
373
+ }
374
+ /** Write everything pending; resolves with the collections that could not be written. */
375
+ flush() {
376
+ return this.behind.flush();
377
+ }
378
+ async readAll(handle) {
379
+ const rows = [];
380
+ let cursor;
381
+ do {
382
+ const page = await handle.query({
383
+ limit: READ_PAGE,
384
+ ...cursor === void 0 ? {} : { cursor }
385
+ });
386
+ for (const row of page.records) rows.push({
387
+ id: row.id,
388
+ part: row.data.part,
389
+ value: row.data.value
390
+ });
391
+ cursor = page.nextCursor ?? void 0;
392
+ } while (cursor !== void 0);
393
+ return rows;
394
+ }
395
+ async persist(collection) {
396
+ const handle = this.handles.get(collection);
397
+ const known = this.persisted.get(collection);
398
+ if (handle === void 0 || known === void 0) throw new Error(`collection "${collection}" was not hydrated`);
399
+ const wanted = new Map(partsOf(this.cache.get(collection)).map((row) => [row.id, row]));
400
+ const puts = [...wanted.values()].filter((row) => known.get(row.id) !== JSON.stringify(row.value));
401
+ const removes = [...known.keys()].filter((id) => !wanted.has(id));
402
+ for (let at = 0; at < puts.length; at += WRITE_CHUNK) {
403
+ const chunk = puts.slice(at, at + WRITE_CHUNK);
404
+ await handle.putMany(chunk.map((row) => ({
405
+ id: row.id,
406
+ data: {
407
+ part: row.part,
408
+ value: row.value
409
+ }
410
+ })));
411
+ for (const row of chunk) known.set(row.id, JSON.stringify(row.value));
412
+ }
413
+ for (let at = 0; at < removes.length; at += WRITE_CHUNK) {
414
+ const chunk = removes.slice(at, at + WRITE_CHUNK);
415
+ await handle.deleteMany(chunk);
416
+ for (const id of chunk) known.delete(id);
417
+ }
418
+ }
419
+ };
420
+ export { SettingsSecretStore as n, RecordsStateStore as t };