@orieljs/cache 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1060 @@
1
+ // errors.ts
2
+ var LockTimeoutError = class extends Error {
3
+ constructor(lockName) {
4
+ super(`Unable to acquire lock [${lockName}].`);
5
+ this.lockName = lockName;
6
+ }
7
+ lockName;
8
+ kind = "Server";
9
+ status = 500;
10
+ name = "LockTimeoutError";
11
+ };
12
+ var TagsNotSupportedError = class extends Error {
13
+ kind = "Server";
14
+ status = 500;
15
+ name = "TagsNotSupportedError";
16
+ constructor(store) {
17
+ super(`The [${store}] cache store does not support tags. Only the redis store does.`);
18
+ }
19
+ };
20
+ var UnknownCacheStoreError = class extends Error {
21
+ kind = "Server";
22
+ status = 500;
23
+ name = "UnknownCacheStoreError";
24
+ constructor(name) {
25
+ super(`Cache store [${name}] is not configured. Add it to config('cache.stores').`);
26
+ }
27
+ };
28
+ var UnknownCacheDriverError = class extends Error {
29
+ kind = "Server";
30
+ status = 500;
31
+ name = "UnknownCacheDriverError";
32
+ constructor(driver) {
33
+ super(`Cache driver [${driver}] is not supported. Register it first with CacheManager.extend().`);
34
+ }
35
+ };
36
+ var InvalidCacheConfigError = class extends Error {
37
+ kind = "Server";
38
+ status = 500;
39
+ name = "InvalidCacheConfigError";
40
+ };
41
+
42
+ // serialize.ts
43
+ function serialize(value) {
44
+ return JSON.stringify(value) ?? "null";
45
+ }
46
+ function deserialize(raw) {
47
+ return JSON.parse(raw);
48
+ }
49
+ function roundTrip(value) {
50
+ return JSON.parse(serialize(value));
51
+ }
52
+
53
+ // locks/GenericLock.ts
54
+ import { setTimeout as sleep } from "timers/promises";
55
+ import { Str } from "@orieljs/support";
56
+ var GenericLock = class {
57
+ constructor(store, name, seconds, owner, pollMs = 50) {
58
+ this.store = store;
59
+ this.name = name;
60
+ this.seconds = seconds;
61
+ this.pollMs = pollMs;
62
+ this.ownerValue = owner ?? Str.random(20);
63
+ }
64
+ store;
65
+ name;
66
+ seconds;
67
+ pollMs;
68
+ ownerValue;
69
+ owner() {
70
+ return this.ownerValue;
71
+ }
72
+ async get(callback) {
73
+ const acquired = await this.store.add(this.name, this.ownerValue, this.seconds);
74
+ if (!acquired) return false;
75
+ if (!callback) return true;
76
+ try {
77
+ return await callback();
78
+ } finally {
79
+ await this.release();
80
+ }
81
+ }
82
+ async block(seconds, callback) {
83
+ const deadline = Date.now() + seconds * 1e3;
84
+ for (; ; ) {
85
+ if (await this.get()) break;
86
+ if (Date.now() >= deadline) throw new LockTimeoutError(this.name);
87
+ await sleep(this.pollMs);
88
+ }
89
+ if (!callback) return true;
90
+ try {
91
+ return await callback();
92
+ } finally {
93
+ await this.release();
94
+ }
95
+ }
96
+ async release() {
97
+ const current = await this.store.get(this.name);
98
+ if (current !== this.ownerValue) return false;
99
+ return this.store.forget(this.name);
100
+ }
101
+ async forceRelease() {
102
+ await this.store.forget(this.name);
103
+ }
104
+ };
105
+
106
+ // Repository.ts
107
+ var defaultLockFactory = (store, name, seconds, owner) => new GenericLock(store, name, seconds, owner);
108
+ var Repository = class {
109
+ constructor(store, lockFactory = defaultLockFactory) {
110
+ this.store = store;
111
+ this.lockFactory = lockFactory;
112
+ }
113
+ store;
114
+ lockFactory;
115
+ async get(key, defaultValue) {
116
+ const value = await this.store.get(key);
117
+ if (value !== void 0) return value;
118
+ return typeof defaultValue === "function" ? defaultValue() : defaultValue;
119
+ }
120
+ async many(keys) {
121
+ const found = await this.store.many(keys);
122
+ const result = {};
123
+ for (const key of keys) result[key] = found[key];
124
+ return result;
125
+ }
126
+ async has(key) {
127
+ return await this.store.get(key) !== void 0;
128
+ }
129
+ async missing(key) {
130
+ return !await this.has(key);
131
+ }
132
+ async put(key, value, ttlSeconds) {
133
+ if (ttlSeconds !== void 0 && ttlSeconds <= 0) {
134
+ await this.store.forget(key);
135
+ return true;
136
+ }
137
+ if (ttlSeconds === void 0) return this.store.putForever(key, value);
138
+ return this.store.put(key, value, ttlSeconds);
139
+ }
140
+ async add(key, value, ttlSeconds) {
141
+ if (ttlSeconds !== void 0 && ttlSeconds <= 0) return false;
142
+ return this.store.add(key, value, ttlSeconds);
143
+ }
144
+ increment(key, by = 1) {
145
+ return this.store.increment(key, by);
146
+ }
147
+ decrement(key, by = 1) {
148
+ return this.store.decrement(key, by);
149
+ }
150
+ forever(key, value) {
151
+ return this.store.putForever(key, value);
152
+ }
153
+ async pull(key, defaultValue) {
154
+ const value = await this.get(key);
155
+ await this.forget(key);
156
+ return value === void 0 ? defaultValue : value;
157
+ }
158
+ forget(key) {
159
+ return this.store.forget(key);
160
+ }
161
+ flush() {
162
+ return this.store.flush();
163
+ }
164
+ async remember(key, ttlSeconds, callback) {
165
+ const cached = await this.get(key);
166
+ if (cached !== void 0) return cached;
167
+ const value = await callback();
168
+ if (value !== void 0) await this.put(key, value, ttlSeconds);
169
+ return value;
170
+ }
171
+ async rememberForever(key, callback) {
172
+ const cached = await this.get(key);
173
+ if (cached !== void 0) return cached;
174
+ const value = await callback();
175
+ if (value !== void 0) await this.forever(key, value);
176
+ return value;
177
+ }
178
+ lock(name, seconds, owner) {
179
+ const normalizedSeconds = seconds !== void 0 && seconds <= 0 ? void 0 : seconds;
180
+ return this.lockFactory(this.store, name, normalizedSeconds, owner);
181
+ }
182
+ tags(_names) {
183
+ throw new TagsNotSupportedError(this.store.constructor.name);
184
+ }
185
+ };
186
+
187
+ // stores/MemoryStore.ts
188
+ var MemoryStore = class {
189
+ constructor(keyPrefix = "", maxItems) {
190
+ this.keyPrefix = keyPrefix;
191
+ this.maxItems = maxItems;
192
+ if (maxItems !== void 0 && !(maxItems >= 1)) {
193
+ throw new InvalidCacheConfigError(`Memory cache maxItems must be at least 1, got [${maxItems}].`);
194
+ }
195
+ }
196
+ keyPrefix;
197
+ maxItems;
198
+ entries = /* @__PURE__ */ new Map();
199
+ k(key) {
200
+ return this.keyPrefix + key;
201
+ }
202
+ /** Reads and, on a hit, re-inserts the entry so Map iteration order tracks recency (a simple LRU). */
203
+ read(key) {
204
+ const entry = this.entries.get(key);
205
+ if (!entry) return void 0;
206
+ if (entry.expiresAt !== void 0 && entry.expiresAt <= Date.now()) {
207
+ this.entries.delete(key);
208
+ return void 0;
209
+ }
210
+ this.entries.delete(key);
211
+ this.entries.set(key, entry);
212
+ return entry;
213
+ }
214
+ write(key, value, expiresAt) {
215
+ this.entries.delete(key);
216
+ this.entries.set(key, { value: roundTrip(value), expiresAt });
217
+ if (this.maxItems !== void 0) {
218
+ while (this.entries.size > this.maxItems) {
219
+ const oldest = this.entries.keys().next().value;
220
+ if (oldest === void 0) break;
221
+ this.entries.delete(oldest);
222
+ }
223
+ }
224
+ }
225
+ async get(key) {
226
+ return this.read(this.k(key))?.value;
227
+ }
228
+ async many(keys) {
229
+ const result = {};
230
+ for (const key of keys) {
231
+ const entry = this.read(this.k(key));
232
+ if (entry) result[key] = entry.value;
233
+ }
234
+ return result;
235
+ }
236
+ async put(key, value, seconds) {
237
+ this.write(this.k(key), value, Date.now() + seconds * 1e3);
238
+ return true;
239
+ }
240
+ async putForever(key, value) {
241
+ this.write(this.k(key), value, void 0);
242
+ return true;
243
+ }
244
+ async add(key, value, seconds) {
245
+ const k = this.k(key);
246
+ if (this.read(k) !== void 0) return false;
247
+ this.write(k, value, seconds === void 0 ? void 0 : Date.now() + seconds * 1e3);
248
+ return true;
249
+ }
250
+ async increment(key, by) {
251
+ const k = this.k(key);
252
+ const existing = this.read(k);
253
+ const current = typeof existing?.value === "number" ? existing.value : 0;
254
+ const next = current + by;
255
+ this.write(k, next, existing?.expiresAt);
256
+ return next;
257
+ }
258
+ async decrement(key, by) {
259
+ return this.increment(key, -by);
260
+ }
261
+ async forget(key) {
262
+ return this.entries.delete(this.k(key));
263
+ }
264
+ async flush() {
265
+ this.entries.clear();
266
+ return true;
267
+ }
268
+ };
269
+
270
+ // stores/FileStore.ts
271
+ import { createHash } from "crypto";
272
+ import { link, mkdir, readFile, rename, rm, stat, writeFile } from "fs/promises";
273
+ import { dirname, join } from "path";
274
+ var FOREVER = 9999999999999;
275
+ var MUTEX_STALE_MS = 1e4;
276
+ var now = () => Date.now();
277
+ var isLive = (payload) => payload !== void 0 && payload.expiresAt > now();
278
+ var errorCode = (error) => error.code;
279
+ var FileStore = class {
280
+ constructor(directory, keyPrefix = "") {
281
+ this.directory = directory;
282
+ this.keyPrefix = keyPrefix;
283
+ }
284
+ directory;
285
+ keyPrefix;
286
+ path(key) {
287
+ const hash = createHash("sha1").update(this.keyPrefix + key).digest("hex");
288
+ return join(this.directory, hash.slice(0, 2), hash.slice(2, 4), hash);
289
+ }
290
+ tempPath(path) {
291
+ return `${path}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`;
292
+ }
293
+ encode(value, expiresAt) {
294
+ return `${String(expiresAt).padStart(13, "0")}${serialize(roundTrip(value))}`;
295
+ }
296
+ /** Undefined for a missing or corrupt file; the payload (possibly expired) otherwise. */
297
+ async readPayload(path) {
298
+ let raw;
299
+ try {
300
+ raw = await readFile(path, "utf8");
301
+ } catch (error) {
302
+ if (errorCode(error) === "ENOENT") return void 0;
303
+ throw error;
304
+ }
305
+ const header = raw.slice(0, 13);
306
+ if (!/^\d{13}$/.test(header)) return void 0;
307
+ try {
308
+ return { expiresAt: Number(header), value: deserialize(raw.slice(13)) };
309
+ } catch {
310
+ return void 0;
311
+ }
312
+ }
313
+ async writeTemp(path, contents) {
314
+ await mkdir(dirname(path), { recursive: true });
315
+ const temp = this.tempPath(path);
316
+ await writeFile(temp, contents);
317
+ return temp;
318
+ }
319
+ async atomicWrite(path, contents) {
320
+ const temp = await this.writeTemp(path, contents);
321
+ try {
322
+ await rename(temp, path);
323
+ } catch (error) {
324
+ await rm(temp, { force: true });
325
+ throw error;
326
+ }
327
+ }
328
+ async get(key) {
329
+ const payload = await this.readPayload(this.path(key));
330
+ return isLive(payload) ? payload.value : void 0;
331
+ }
332
+ async many(keys) {
333
+ const result = {};
334
+ for (const key of keys) {
335
+ const payload = await this.readPayload(this.path(key));
336
+ if (isLive(payload)) result[key] = payload.value;
337
+ }
338
+ return result;
339
+ }
340
+ async put(key, value, seconds) {
341
+ await this.atomicWrite(this.path(key), this.encode(value, now() + seconds * 1e3));
342
+ return true;
343
+ }
344
+ async putForever(key, value) {
345
+ await this.atomicWrite(this.path(key), this.encode(value, FOREVER));
346
+ return true;
347
+ }
348
+ /**
349
+ * Exclusive create is the atomicity primitive, but the exclusive step is a hard link, not opening `path`
350
+ * directly with `wx`: the full payload is written to a temp file first, then `link()`'d into place. `link()`
351
+ * is atomic and fails `EEXIST` if the destination already exists, so no concurrent reader can ever observe a
352
+ * half-written file at `path` — unlike creating `path` itself with `wx` and writing to it afterwards, which
353
+ * leaves a window (between file creation and the write completing) where a concurrent `get()`/`add()` can read
354
+ * an empty or truncated file and throw a JSON parse error instead of losing the race cleanly.
355
+ *
356
+ * If the key holds an expired or corrupt entry, the takeover happens under a per-key mutex (see
357
+ * takeOverExpired), so two callers can never both replace it.
358
+ */
359
+ async add(key, value, seconds) {
360
+ const path = this.path(key);
361
+ const expiresAt = seconds === void 0 ? FOREVER : now() + seconds * 1e3;
362
+ const temp = await this.writeTemp(path, this.encode(value, expiresAt));
363
+ try {
364
+ if (await this.linkExclusive(temp, path)) return true;
365
+ if (isLive(await this.readPayload(path))) return false;
366
+ return await this.takeOverExpired(path, temp);
367
+ } finally {
368
+ await rm(temp, { force: true });
369
+ }
370
+ }
371
+ async linkExclusive(from, to) {
372
+ try {
373
+ await link(from, to);
374
+ return true;
375
+ } catch (error) {
376
+ if (errorCode(error) === "EEXIST") return false;
377
+ throw error;
378
+ }
379
+ }
380
+ /**
381
+ * Replaces an expired or corrupt entry, holding `path + '.lock'` (created with the same link() trick) so only
382
+ * one add() at a time can take it over. A caller that finds the mutex held loses without waiting: the holder
383
+ * is replacing the entry right now, so at that moment the key is taken either way. Inside the mutex the entry
384
+ * is re-read (it may have been replaced by a put() meanwhile), then removed and our file linked in: if anything
385
+ * else creates the key in between (a put(), or an add() after a forget()), the link fails and we lose cleanly.
386
+ */
387
+ async takeOverExpired(path, temp) {
388
+ const mutex = `${path}.lock`;
389
+ const token = await this.acquireMutex(mutex);
390
+ if (token === void 0) return false;
391
+ try {
392
+ if (isLive(await this.readPayload(path))) return false;
393
+ await rm(path, { force: true });
394
+ return await this.linkExclusive(temp, path);
395
+ } finally {
396
+ await this.releaseMutex(mutex, token);
397
+ }
398
+ }
399
+ /** Returns our token once the mutex is held, or undefined if another live holder has it. */
400
+ async acquireMutex(mutex, retried = false) {
401
+ const token = `${process.pid}-${Math.random().toString(36).slice(2)}`;
402
+ const temp = await this.writeTemp(mutex, token);
403
+ try {
404
+ if (await this.linkExclusive(temp, mutex)) return token;
405
+ } finally {
406
+ await rm(temp, { force: true });
407
+ }
408
+ if (retried) return void 0;
409
+ let modified;
410
+ try {
411
+ modified = (await stat(mutex)).mtimeMs;
412
+ } catch (error) {
413
+ if (errorCode(error) === "ENOENT") return this.acquireMutex(mutex, true);
414
+ throw error;
415
+ }
416
+ if (now() - modified < MUTEX_STALE_MS) return void 0;
417
+ await rm(mutex, { force: true });
418
+ return this.acquireMutex(mutex, true);
419
+ }
420
+ /** Only removes the mutex if it is still ours (a stalled holder's mutex may have been cleared as stale). */
421
+ async releaseMutex(mutex, token) {
422
+ try {
423
+ if (await readFile(mutex, "utf8") === token) await rm(mutex, { force: true });
424
+ } catch (error) {
425
+ if (errorCode(error) !== "ENOENT") throw error;
426
+ }
427
+ }
428
+ async increment(key, by) {
429
+ const path = this.path(key);
430
+ const payload = await this.readPayload(path);
431
+ const existing = isLive(payload) ? payload : void 0;
432
+ const current = existing && typeof existing.value === "number" ? existing.value : 0;
433
+ const next = current + by;
434
+ await this.atomicWrite(path, this.encode(next, existing?.expiresAt ?? FOREVER));
435
+ return next;
436
+ }
437
+ decrement(key, by) {
438
+ return this.increment(key, -by);
439
+ }
440
+ async forget(key) {
441
+ try {
442
+ await rm(this.path(key));
443
+ return true;
444
+ } catch (error) {
445
+ if (errorCode(error) === "ENOENT") return false;
446
+ throw error;
447
+ }
448
+ }
449
+ /** Clears the whole directory, regardless of prefix — matches Laravel's FileStore::flush(). */
450
+ async flush() {
451
+ await rm(this.directory, { recursive: true, force: true });
452
+ await mkdir(this.directory, { recursive: true });
453
+ return true;
454
+ }
455
+ };
456
+
457
+ // insertOrTakeOver.ts
458
+ async function insertOrTakeOver(connection, table, row) {
459
+ if (await connection.table(table).insertOrIgnore(row) === 1) return true;
460
+ const now4 = Math.floor(Date.now() / 1e3);
461
+ return await connection.table(table).where("key", row.key).where("expiration", "<=", now4).update(row) > 0;
462
+ }
463
+
464
+ // stores/DatabaseStore.ts
465
+ var FOREVER_SECONDS = 31536e4;
466
+ var now2 = () => Math.floor(Date.now() / 1e3);
467
+ var DatabaseStore = class {
468
+ constructor(connection, table, keyPrefix = "") {
469
+ this.connection = connection;
470
+ this.table = table;
471
+ this.keyPrefix = keyPrefix;
472
+ }
473
+ connection;
474
+ table;
475
+ keyPrefix;
476
+ k(key) {
477
+ return this.keyPrefix + key;
478
+ }
479
+ async get(key) {
480
+ const k = this.k(key);
481
+ const row = await this.connection.table(this.table).where("key", k).first();
482
+ if (!row) return void 0;
483
+ if (row.expiration <= now2()) {
484
+ await this.connection.table(this.table).where("key", k).where("expiration", "<=", now2()).delete();
485
+ return void 0;
486
+ }
487
+ return deserialize(row.value);
488
+ }
489
+ async many(keys) {
490
+ if (keys.length === 0) return {};
491
+ const prefixed = keys.map((key) => this.k(key));
492
+ const rows = await this.connection.table(this.table).whereIn("key", prefixed).get();
493
+ const byKey = new Map(rows.all().map((row) => [row.key, row]));
494
+ const time = now2();
495
+ const result = {};
496
+ keys.forEach((key, i) => {
497
+ const row = byKey.get(prefixed[i]);
498
+ if (row && row.expiration > time) result[key] = deserialize(row.value);
499
+ });
500
+ return result;
501
+ }
502
+ async put(key, value, seconds) {
503
+ return this.write(this.k(key), value, now2() + Math.ceil(seconds));
504
+ }
505
+ async putForever(key, value) {
506
+ return this.write(this.k(key), value, now2() + FOREVER_SECONDS);
507
+ }
508
+ async write(key, value, expiration) {
509
+ await this.connection.table(this.table).upsert({ key, value: serialize(roundTrip(value)), expiration }, ["key"]);
510
+ return true;
511
+ }
512
+ /**
513
+ * Laravel's DatabaseStore::add(): an insert that skips a taken key, and then a conditional update that only takes
514
+ * over an expired row (see insertOrTakeOver). Nothing fails on a taken key, so a caller's transaction stays usable.
515
+ */
516
+ async add(key, value, seconds) {
517
+ const k = this.k(key);
518
+ const expiration = seconds === void 0 ? now2() + FOREVER_SECONDS : now2() + Math.ceil(seconds);
519
+ const row = { key: k, value: serialize(roundTrip(value)), expiration };
520
+ return insertOrTakeOver(this.connection, this.table, row);
521
+ }
522
+ async increment(key, by, attempt = 0) {
523
+ const k = this.k(key);
524
+ try {
525
+ return await this.connection.transaction(async (trx) => {
526
+ const existing = await trx.table(this.table).where("key", k).lockForUpdate().first();
527
+ const unexpired = existing !== void 0 && existing.expiration > now2();
528
+ const current = unexpired ? Number(deserialize(existing.value)) : 0;
529
+ const next = current + by;
530
+ const expiration = unexpired ? existing.expiration : now2() + FOREVER_SECONDS;
531
+ const row = { key: k, value: serialize(next), expiration };
532
+ if (existing) await trx.table(this.table).where("key", k).update(row);
533
+ else await trx.table(this.table).insert(row);
534
+ return next;
535
+ });
536
+ } catch (error) {
537
+ if (attempt > 0) throw error;
538
+ return this.increment(key, by, attempt + 1);
539
+ }
540
+ }
541
+ decrement(key, by) {
542
+ return this.increment(key, -by);
543
+ }
544
+ async forget(key) {
545
+ const deleted = await this.connection.table(this.table).where("key", this.k(key)).delete();
546
+ return deleted > 0;
547
+ }
548
+ async flush() {
549
+ if (this.keyPrefix) await this.connection.table(this.table).where("key", "like", `${this.keyPrefix}%`).delete();
550
+ else await this.connection.table(this.table).delete();
551
+ return true;
552
+ }
553
+ };
554
+
555
+ // locks/DatabaseLock.ts
556
+ import { setTimeout as sleep2 } from "timers/promises";
557
+ import { Str as Str2 } from "@orieljs/support";
558
+ var FOREVER_SECONDS2 = 31536e4;
559
+ var now3 = () => Math.floor(Date.now() / 1e3);
560
+ var DatabaseLock = class {
561
+ constructor(connection, table, name, seconds, owner, pollMs = 50) {
562
+ this.connection = connection;
563
+ this.table = table;
564
+ this.name = name;
565
+ this.seconds = seconds;
566
+ this.pollMs = pollMs;
567
+ this.ownerValue = owner ?? Str2.random(20);
568
+ }
569
+ connection;
570
+ table;
571
+ name;
572
+ seconds;
573
+ pollMs;
574
+ ownerValue;
575
+ owner() {
576
+ return this.ownerValue;
577
+ }
578
+ async get(callback) {
579
+ const acquired = await this.acquire();
580
+ if (!acquired) return false;
581
+ if (!callback) return true;
582
+ try {
583
+ return await callback();
584
+ } finally {
585
+ await this.release();
586
+ }
587
+ }
588
+ async block(seconds, callback) {
589
+ const deadline = Date.now() + seconds * 1e3;
590
+ for (; ; ) {
591
+ if (await this.acquire()) break;
592
+ if (Date.now() >= deadline) throw new LockTimeoutError(this.name);
593
+ await sleep2(this.pollMs);
594
+ }
595
+ if (!callback) return true;
596
+ try {
597
+ return await callback();
598
+ } finally {
599
+ await this.release();
600
+ }
601
+ }
602
+ async release() {
603
+ return this.connection.transaction(async (trx) => {
604
+ const existing = await trx.table(this.table).where("key", this.name).lockForUpdate().first();
605
+ if (!existing || existing.owner !== this.ownerValue) return false;
606
+ await trx.table(this.table).where("key", this.name).delete();
607
+ return true;
608
+ });
609
+ }
610
+ async forceRelease() {
611
+ await this.connection.table(this.table).where("key", this.name).delete();
612
+ }
613
+ /**
614
+ * Laravel's DatabaseLock::acquire(): an insert that skips a taken key, and then a conditional update that only takes
615
+ * over an expired lock (no re-entry for the same owner, like RedisLock); see insertOrTakeOver.
616
+ */
617
+ async acquire() {
618
+ const expiration = this.seconds === void 0 ? now3() + FOREVER_SECONDS2 : now3() + Math.ceil(this.seconds);
619
+ const row = { key: this.name, owner: this.ownerValue, expiration };
620
+ return insertOrTakeOver(this.connection, this.table, row);
621
+ }
622
+ };
623
+
624
+ // migrations.ts
625
+ var CACHE_TABLE_MIGRATION = `import { Migration, Schema } from '@orieljs/framework'
626
+
627
+ export default class extends Migration {
628
+ async up() {
629
+ await Schema.create('cache', (t) => {
630
+ t.string('key').primary()
631
+ t.text('value')
632
+ t.integer('expiration')
633
+ })
634
+ await Schema.create('cache_locks', (t) => {
635
+ t.string('key').primary()
636
+ t.string('owner')
637
+ t.integer('expiration')
638
+ })
639
+ }
640
+
641
+ async down() {
642
+ await Schema.dropIfExists('cache_locks')
643
+ await Schema.dropIfExists('cache')
644
+ }
645
+ }
646
+ `;
647
+
648
+ // stores/RedisStore.ts
649
+ import { createHash as createHash2, randomUUID } from "crypto";
650
+ import Redis from "ioredis";
651
+ function makeRedisClient(config) {
652
+ if (typeof config.client === "object" && config.client !== null) return config.client;
653
+ const { client: _client, url, driver: _driver, prefix: _prefix, connection: _connection, ...options } = config;
654
+ if (typeof url === "string") return new Redis(url, options);
655
+ return new Redis(options);
656
+ }
657
+ var RedisPrimitives = class {
658
+ constructor(redis) {
659
+ this.redis = redis;
660
+ }
661
+ redis;
662
+ async rawGet(key) {
663
+ const raw = await this.redis.get(key);
664
+ return raw === null ? void 0 : deserialize(raw);
665
+ }
666
+ async rawMany(keys) {
667
+ if (keys.length === 0) return {};
668
+ const values = await this.redis.mget(...keys);
669
+ const result = {};
670
+ keys.forEach((key, i) => {
671
+ const raw = values[i];
672
+ if (raw !== null && raw !== void 0) result[key] = deserialize(raw);
673
+ });
674
+ return result;
675
+ }
676
+ async rawPut(key, value, ms) {
677
+ if (ms === void 0) await this.redis.set(key, serialize(roundTrip(value)));
678
+ else await this.redis.set(key, serialize(roundTrip(value)), "PX", Math.max(1, Math.round(ms)));
679
+ return true;
680
+ }
681
+ async rawAdd(key, value, ms) {
682
+ const result = ms === void 0 ? await this.redis.set(key, serialize(roundTrip(value)), "NX") : await this.redis.set(key, serialize(roundTrip(value)), "PX", Math.max(1, Math.round(ms)), "NX");
683
+ return result === "OK";
684
+ }
685
+ rawIncrement(key, by) {
686
+ return this.redis.incrby(key, by);
687
+ }
688
+ async rawForget(key) {
689
+ return await this.redis.del(key) > 0;
690
+ }
691
+ };
692
+ var RedisStore = class extends RedisPrimitives {
693
+ constructor(redis, keyPrefix = "") {
694
+ super(redis);
695
+ this.keyPrefix = keyPrefix;
696
+ }
697
+ keyPrefix;
698
+ k(key) {
699
+ return this.keyPrefix + key;
700
+ }
701
+ getPrefix() {
702
+ return this.keyPrefix;
703
+ }
704
+ get(key) {
705
+ return this.rawGet(this.k(key));
706
+ }
707
+ async many(keys) {
708
+ const prefixed = keys.map((key) => this.k(key));
709
+ const found = await this.rawMany(prefixed);
710
+ const result = {};
711
+ keys.forEach((key, i) => {
712
+ const p = prefixed[i];
713
+ if (p in found) result[key] = found[p];
714
+ });
715
+ return result;
716
+ }
717
+ put(key, value, seconds) {
718
+ return this.rawPut(this.k(key), value, seconds * 1e3);
719
+ }
720
+ putForever(key, value) {
721
+ return this.rawPut(this.k(key), value);
722
+ }
723
+ add(key, value, seconds) {
724
+ return this.rawAdd(this.k(key), value, seconds === void 0 ? void 0 : seconds * 1e3);
725
+ }
726
+ increment(key, by) {
727
+ return this.rawIncrement(this.k(key), by);
728
+ }
729
+ decrement(key, by) {
730
+ return this.rawIncrement(this.k(key), -by);
731
+ }
732
+ forget(key) {
733
+ return this.rawForget(this.k(key));
734
+ }
735
+ async flush() {
736
+ let cursor = "0";
737
+ do {
738
+ const [next, keys] = await this.redis.scan(cursor, "MATCH", `${this.keyPrefix}*`, "COUNT", 200);
739
+ cursor = next;
740
+ if (keys.length > 0) await this.redis.unlink(...keys);
741
+ } while (cursor !== "0");
742
+ return true;
743
+ }
744
+ tags(names) {
745
+ return new RedisTaggedStore(this.redis, this.keyPrefix, names);
746
+ }
747
+ };
748
+ var RedisTaggedStore = class extends RedisPrimitives {
749
+ constructor(redis, keyPrefix, tagNames) {
750
+ super(redis);
751
+ this.keyPrefix = keyPrefix;
752
+ this.tagNames = tagNames;
753
+ }
754
+ keyPrefix;
755
+ tagNames;
756
+ async tagVersion(name) {
757
+ const key = `${this.keyPrefix}tag:${name}:version`;
758
+ const existing = await this.redis.get(key);
759
+ if (existing !== null) return existing;
760
+ const version = randomUUID();
761
+ const set = await this.redis.set(key, version, "NX");
762
+ return set === "OK" ? version : await this.redis.get(key) ?? version;
763
+ }
764
+ async namespace() {
765
+ const versions = await Promise.all(this.tagNames.map((name) => this.tagVersion(name)));
766
+ const joined = this.tagNames.map((name, i) => `${name}=${versions[i]}`).sort().join("|");
767
+ return createHash2("sha1").update(joined).digest("hex").slice(0, 16);
768
+ }
769
+ async k(key) {
770
+ return `${this.keyPrefix}tags:${await this.namespace()}:${key}`;
771
+ }
772
+ async get(key) {
773
+ return this.rawGet(await this.k(key));
774
+ }
775
+ async many(keys) {
776
+ const prefixed = await Promise.all(keys.map((key) => this.k(key)));
777
+ const found = await this.rawMany(prefixed);
778
+ const result = {};
779
+ keys.forEach((key, i) => {
780
+ const p = prefixed[i];
781
+ if (p in found) result[key] = found[p];
782
+ });
783
+ return result;
784
+ }
785
+ async put(key, value, seconds) {
786
+ return this.rawPut(await this.k(key), value, seconds * 1e3);
787
+ }
788
+ async putForever(key, value) {
789
+ return this.rawPut(await this.k(key), value);
790
+ }
791
+ async add(key, value, seconds) {
792
+ return this.rawAdd(await this.k(key), value, seconds === void 0 ? void 0 : seconds * 1e3);
793
+ }
794
+ async increment(key, by) {
795
+ return this.rawIncrement(await this.k(key), by);
796
+ }
797
+ async decrement(key, by) {
798
+ return this.rawIncrement(await this.k(key), -by);
799
+ }
800
+ async forget(key) {
801
+ return this.rawForget(await this.k(key));
802
+ }
803
+ async flush() {
804
+ await Promise.all(this.tagNames.map((name) => this.redis.set(`${this.keyPrefix}tag:${name}:version`, randomUUID())));
805
+ return true;
806
+ }
807
+ };
808
+
809
+ // locks/RedisLock.ts
810
+ import { setTimeout as sleep3 } from "timers/promises";
811
+ import { Str as Str3 } from "@orieljs/support";
812
+ var RELEASE_SCRIPT = 'if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end';
813
+ var RedisLock = class {
814
+ constructor(redis, name, seconds, owner, pollMs = 50) {
815
+ this.redis = redis;
816
+ this.name = name;
817
+ this.seconds = seconds;
818
+ this.pollMs = pollMs;
819
+ this.ownerValue = owner ?? Str3.random(20);
820
+ }
821
+ redis;
822
+ name;
823
+ seconds;
824
+ pollMs;
825
+ ownerValue;
826
+ owner() {
827
+ return this.ownerValue;
828
+ }
829
+ async get(callback) {
830
+ const acquired = await this.acquire();
831
+ if (!acquired) return false;
832
+ if (!callback) return true;
833
+ try {
834
+ return await callback();
835
+ } finally {
836
+ await this.release();
837
+ }
838
+ }
839
+ async block(seconds, callback) {
840
+ const deadline = Date.now() + seconds * 1e3;
841
+ for (; ; ) {
842
+ if (await this.acquire()) break;
843
+ if (Date.now() >= deadline) throw new LockTimeoutError(this.name);
844
+ await sleep3(this.pollMs);
845
+ }
846
+ if (!callback) return true;
847
+ try {
848
+ return await callback();
849
+ } finally {
850
+ await this.release();
851
+ }
852
+ }
853
+ async release() {
854
+ const result = await this.redis.eval(RELEASE_SCRIPT, 1, this.name, this.ownerValue);
855
+ return result === 1;
856
+ }
857
+ async forceRelease() {
858
+ await this.redis.del(this.name);
859
+ }
860
+ async acquire() {
861
+ const result = this.seconds === void 0 ? await this.redis.set(this.name, this.ownerValue, "NX") : await this.redis.set(this.name, this.ownerValue, "PX", Math.max(1, Math.round(this.seconds * 1e3)), "NX");
862
+ return result === "OK";
863
+ }
864
+ };
865
+
866
+ // stores/RedisRepository.ts
867
+ var RedisRepository = class extends Repository {
868
+ constructor(redisStore, redis) {
869
+ super(redisStore, (_store, name, seconds, owner) => new RedisLock(redis, redisStore.getPrefix() + name, seconds, owner));
870
+ this.redisStore = redisStore;
871
+ this.redis = redis;
872
+ }
873
+ redisStore;
874
+ redis;
875
+ tags(names) {
876
+ const list = Array.isArray(names) ? names : [names];
877
+ const taggedStore = this.redisStore.tags(list);
878
+ const prefix = this.redisStore.getPrefix();
879
+ return new Repository(taggedStore, (_store, name, seconds, owner) => new RedisLock(this.redis, prefix + name, seconds, owner));
880
+ }
881
+ };
882
+
883
+ // CacheManager.ts
884
+ import { ConfigRepository, DatabaseManager } from "@orieljs/contracts";
885
+ function resolveRedisConfig(cfg, lookupDatabaseRedis) {
886
+ const hasClient = typeof cfg.client === "object" && cfg.client !== null;
887
+ if (cfg.url !== void 0 || hasClient) return cfg;
888
+ const connectionName = cfg.connection ?? "default";
889
+ return { ...lookupDatabaseRedis(connectionName), ...cfg };
890
+ }
891
+ var CacheManager = class {
892
+ constructor(container) {
893
+ this.container = container;
894
+ this.drivers.set("memory", (cfg) => new Repository(new MemoryStore(this.str(cfg.prefix), cfg.maxItems)));
895
+ this.drivers.set("array", (cfg) => new Repository(new MemoryStore(this.str(cfg.prefix))));
896
+ this.drivers.set("file", (cfg) => new Repository(new FileStore(cfg.path, this.str(cfg.prefix))));
897
+ this.drivers.set("database", (cfg) => this.buildDatabaseStore(cfg));
898
+ this.drivers.set("redis", (cfg) => this.buildRedisStore(cfg));
899
+ }
900
+ container;
901
+ stores = /* @__PURE__ */ new Map();
902
+ drivers = /* @__PURE__ */ new Map();
903
+ str(value) {
904
+ return typeof value === "string" ? value : "";
905
+ }
906
+ cacheConfig() {
907
+ return this.container.make(ConfigRepository).get("cache", { default: "database", stores: {} });
908
+ }
909
+ buildDatabaseStore(cfg) {
910
+ const connection = this.container.make(DatabaseManager).connection(cfg.connection);
911
+ const table = cfg.table ?? "cache";
912
+ const lockTable = cfg.lockTable ?? "cache_locks";
913
+ const prefix = this.str(cfg.prefix);
914
+ const store = new DatabaseStore(connection, table, prefix);
915
+ return new Repository(store, (_store, name, seconds, owner) => new DatabaseLock(connection, lockTable, prefix + name, seconds, owner));
916
+ }
917
+ buildRedisStore(cfg) {
918
+ const resolved = resolveRedisConfig(
919
+ cfg,
920
+ (connectionName) => this.container.make(ConfigRepository).get(`database.redis.${connectionName}`, {})
921
+ );
922
+ const redis = makeRedisClient(resolved);
923
+ const store = new RedisStore(redis, this.str(cfg.prefix));
924
+ return new RedisRepository(store, redis);
925
+ }
926
+ store(name) {
927
+ const cacheConfig = this.cacheConfig();
928
+ const storeName = name ?? cacheConfig.default;
929
+ let repository = this.stores.get(storeName);
930
+ if (!repository) {
931
+ const storeConfig = cacheConfig.stores[storeName];
932
+ if (!storeConfig) throw new UnknownCacheStoreError(storeName);
933
+ const driverName = storeConfig.driver;
934
+ const driver = driverName ? this.drivers.get(driverName) : void 0;
935
+ if (!driver) throw new UnknownCacheDriverError(String(driverName));
936
+ repository = driver({ ...storeConfig, prefix: storeConfig.prefix ?? cacheConfig.prefix ?? "" });
937
+ this.stores.set(storeName, repository);
938
+ }
939
+ return repository;
940
+ }
941
+ extend(driver, factory) {
942
+ this.drivers.set(driver, factory);
943
+ }
944
+ get(key, defaultValue) {
945
+ return defaultValue === void 0 ? this.store().get(key) : this.store().get(key, defaultValue);
946
+ }
947
+ many(keys) {
948
+ return this.store().many(keys);
949
+ }
950
+ has(key) {
951
+ return this.store().has(key);
952
+ }
953
+ missing(key) {
954
+ return this.store().missing(key);
955
+ }
956
+ put(key, value, ttlSeconds) {
957
+ return this.store().put(key, value, ttlSeconds);
958
+ }
959
+ add(key, value, ttlSeconds) {
960
+ return this.store().add(key, value, ttlSeconds);
961
+ }
962
+ increment(key, by) {
963
+ return this.store().increment(key, by);
964
+ }
965
+ decrement(key, by) {
966
+ return this.store().decrement(key, by);
967
+ }
968
+ forever(key, value) {
969
+ return this.store().forever(key, value);
970
+ }
971
+ pull(key, defaultValue) {
972
+ return this.store().pull(key, defaultValue);
973
+ }
974
+ forget(key) {
975
+ return this.store().forget(key);
976
+ }
977
+ flush() {
978
+ return this.store().flush();
979
+ }
980
+ remember(key, ttlSeconds, callback) {
981
+ return this.store().remember(key, ttlSeconds, callback);
982
+ }
983
+ rememberForever(key, callback) {
984
+ return this.store().rememberForever(key, callback);
985
+ }
986
+ lock(name, seconds, owner) {
987
+ return this.store().lock(name, seconds, owner);
988
+ }
989
+ tags(names) {
990
+ return this.store().tags(names);
991
+ }
992
+ };
993
+
994
+ // facade.ts
995
+ import { CacheManager as CacheManagerToken2 } from "@orieljs/contracts";
996
+ import { inject } from "@orieljs/container";
997
+ import { facade } from "@orieljs/support";
998
+ var Cache = facade(CacheManagerToken2);
999
+ function cache(arg, ttlSeconds) {
1000
+ const manager = inject(CacheManagerToken2);
1001
+ if (arg === void 0) return manager;
1002
+ if (typeof arg === "string") return manager.get(arg);
1003
+ return Promise.all(Object.entries(arg).map(([key, value]) => manager.put(key, value, ttlSeconds))).then(
1004
+ (results) => results.every(Boolean)
1005
+ );
1006
+ }
1007
+
1008
+ // CacheServiceProvider.ts
1009
+ import { CacheManager as CacheManagerToken3 } from "@orieljs/contracts";
1010
+ import { ServiceProvider } from "@orieljs/support";
1011
+ var CacheServiceProvider = class extends ServiceProvider {
1012
+ register() {
1013
+ this.mergeConfigFrom(
1014
+ {
1015
+ default: "database",
1016
+ prefix: "",
1017
+ stores: {
1018
+ array: { driver: "array" },
1019
+ memory: { driver: "memory" },
1020
+ file: { driver: "file", path: this.app.storagePath("framework/cache/data") },
1021
+ database: { driver: "database", table: "cache", lockTable: "cache_locks" },
1022
+ // Resolved from `database.redis.cache` (its own db), not `default`: flush() scans every key under the
1023
+ // prefix, so sharing a db with Queue or Session would wipe their keys too.
1024
+ redis: { driver: "redis", connection: "cache" }
1025
+ }
1026
+ },
1027
+ "cache"
1028
+ );
1029
+ this.app.singleton(CacheManagerToken3, (container) => new CacheManager(container));
1030
+ }
1031
+ };
1032
+ export {
1033
+ CACHE_TABLE_MIGRATION,
1034
+ Cache,
1035
+ CacheManager,
1036
+ CacheServiceProvider,
1037
+ DatabaseLock,
1038
+ DatabaseStore,
1039
+ FileStore,
1040
+ GenericLock,
1041
+ InvalidCacheConfigError,
1042
+ LockTimeoutError,
1043
+ MemoryStore,
1044
+ RedisLock,
1045
+ RedisRepository,
1046
+ RedisStore,
1047
+ RedisTaggedStore,
1048
+ Repository,
1049
+ TagsNotSupportedError,
1050
+ UnknownCacheDriverError,
1051
+ UnknownCacheStoreError,
1052
+ cache,
1053
+ defaultLockFactory,
1054
+ deserialize,
1055
+ makeRedisClient,
1056
+ resolveRedisConfig,
1057
+ roundTrip,
1058
+ serialize
1059
+ };
1060
+ //# sourceMappingURL=index.js.map