@c9up/echo 0.2.3 → 0.2.5

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.
Files changed (109) hide show
  1. package/README.md +1 -1
  2. package/dist/CacheManager.d.ts +13 -2
  3. package/dist/CacheManager.d.ts.map +1 -1
  4. package/dist/CacheManager.js +309 -56
  5. package/dist/CacheManager.js.map +1 -1
  6. package/dist/EchoProvider.d.ts.map +1 -1
  7. package/dist/EchoProvider.js +32 -3
  8. package/dist/EchoProvider.js.map +1 -1
  9. package/dist/StoreManager.d.ts +38 -11
  10. package/dist/StoreManager.d.ts.map +1 -1
  11. package/dist/StoreManager.js +80 -22
  12. package/dist/StoreManager.js.map +1 -1
  13. package/dist/bytes.d.ts +13 -0
  14. package/dist/bytes.d.ts.map +1 -0
  15. package/dist/bytes.js +35 -0
  16. package/dist/bytes.js.map +1 -0
  17. package/dist/claim.d.ts +15 -0
  18. package/dist/claim.d.ts.map +1 -0
  19. package/dist/claim.js +10 -0
  20. package/dist/claim.js.map +1 -0
  21. package/dist/configure.d.ts +1 -0
  22. package/dist/configure.d.ts.map +1 -1
  23. package/dist/configure.js +3 -0
  24. package/dist/configure.js.map +1 -1
  25. package/dist/console/cacheClear.d.ts +13 -0
  26. package/dist/console/cacheClear.d.ts.map +1 -0
  27. package/dist/console/cacheClear.js +69 -0
  28. package/dist/console/cacheClear.js.map +1 -0
  29. package/dist/console/cacheDelete.d.ts +11 -0
  30. package/dist/console/cacheDelete.d.ts.map +1 -0
  31. package/dist/console/cacheDelete.js +42 -0
  32. package/dist/console/cacheDelete.js.map +1 -0
  33. package/dist/console/cachePrune.d.ts +9 -0
  34. package/dist/console/cachePrune.d.ts.map +1 -0
  35. package/dist/console/cachePrune.js +35 -0
  36. package/dist/console/cachePrune.js.map +1 -0
  37. package/dist/console/contract.d.ts +64 -0
  38. package/dist/console/contract.d.ts.map +1 -0
  39. package/dist/console/contract.js +32 -0
  40. package/dist/console/contract.js.map +1 -0
  41. package/dist/console/index.d.ts +25 -0
  42. package/dist/console/index.d.ts.map +1 -0
  43. package/dist/console/index.js +38 -0
  44. package/dist/console/index.js.map +1 -0
  45. package/dist/console/store.d.ts +14 -0
  46. package/dist/console/store.d.ts.map +1 -0
  47. package/dist/console/store.js +35 -0
  48. package/dist/console/store.js.map +1 -0
  49. package/dist/drivers/MemoryDriver.d.ts +37 -1
  50. package/dist/drivers/MemoryDriver.d.ts.map +1 -1
  51. package/dist/drivers/MemoryDriver.js +170 -72
  52. package/dist/drivers/MemoryDriver.js.map +1 -1
  53. package/dist/drivers/RedisDriver.d.ts +15 -8
  54. package/dist/drivers/RedisDriver.d.ts.map +1 -1
  55. package/dist/drivers/RedisDriver.js +198 -97
  56. package/dist/drivers/RedisDriver.js.map +1 -1
  57. package/dist/drivers/TieredDriver.d.ts +42 -0
  58. package/dist/drivers/TieredDriver.d.ts.map +1 -1
  59. package/dist/drivers/TieredDriver.js +114 -9
  60. package/dist/drivers/TieredDriver.js.map +1 -1
  61. package/dist/duration.d.ts +13 -3
  62. package/dist/duration.d.ts.map +1 -1
  63. package/dist/duration.js +22 -7
  64. package/dist/duration.js.map +1 -1
  65. package/dist/errors.d.ts +60 -2
  66. package/dist/errors.d.ts.map +1 -1
  67. package/dist/errors.js +81 -6
  68. package/dist/errors.js.map +1 -1
  69. package/dist/index.d.ts +4 -4
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +3 -3
  72. package/dist/index.js.map +1 -1
  73. package/dist/quasar.d.ts +1 -1
  74. package/dist/quasar.d.ts.map +1 -1
  75. package/dist/quasar.js +106 -19
  76. package/dist/quasar.js.map +1 -1
  77. package/dist/services/main.d.ts +1 -1
  78. package/dist/services/main.d.ts.map +1 -1
  79. package/dist/services/main.js +22 -5
  80. package/dist/services/main.js.map +1 -1
  81. package/dist/types.d.ts +44 -2
  82. package/dist/types.d.ts.map +1 -1
  83. package/dist/vendor/quasarConnection.d.ts +44 -3
  84. package/dist/vendor/quasarConnection.d.ts.map +1 -1
  85. package/dist/vendor/quasarConnection.js +64 -23
  86. package/dist/vendor/quasarConnection.js.map +1 -1
  87. package/package.json +5 -1
  88. package/src/CacheManager.ts +367 -69
  89. package/src/EchoProvider.ts +45 -4
  90. package/src/StoreManager.ts +131 -35
  91. package/src/bytes.ts +38 -0
  92. package/src/claim.ts +22 -0
  93. package/src/configure.ts +4 -0
  94. package/src/console/cacheClear.ts +96 -0
  95. package/src/console/cacheDelete.ts +65 -0
  96. package/src/console/cachePrune.ts +57 -0
  97. package/src/console/contract.ts +93 -0
  98. package/src/console/index.ts +61 -0
  99. package/src/console/store.ts +47 -0
  100. package/src/drivers/MemoryDriver.ts +221 -69
  101. package/src/drivers/RedisDriver.ts +234 -104
  102. package/src/drivers/TieredDriver.ts +169 -9
  103. package/src/duration.ts +28 -7
  104. package/src/errors.ts +103 -6
  105. package/src/index.ts +17 -3
  106. package/src/quasar.ts +145 -30
  107. package/src/services/main.ts +26 -8
  108. package/src/types.ts +46 -7
  109. package/src/vendor/quasarConnection.ts +105 -22
@@ -1,6 +1,7 @@
1
1
  import "./augmentations.js";
2
2
  import { type CacheConfig, CacheManager } from "./CacheManager.js";
3
3
  import { MemoryDriver } from "./drivers/MemoryDriver.js";
4
+ import { EchoError } from "./errors.js";
4
5
  import { CacheStoreManager, type MultiStoreConfig } from "./StoreManager.js";
5
6
  import { clearCache, getCache, setCache } from "./services/main.js";
6
7
  import type { CacheEmitter } from "./types.js";
@@ -43,6 +44,34 @@ function isEmitter(value: unknown): value is CacheEmitter {
43
44
  );
44
45
  }
45
46
 
47
+ function isDuration(value: unknown): boolean {
48
+ return (
49
+ value === undefined ||
50
+ value === null ||
51
+ typeof value === "number" ||
52
+ typeof value === "string"
53
+ );
54
+ }
55
+
56
+ /** A single-store config, field by field. */
57
+ function isSingleStoreConfig(value: unknown): value is EchoProviderConfig {
58
+ if (typeof value !== "object" || value === null) return false;
59
+ const read = (name: string): unknown => Reflect.get(value, name);
60
+ const driver = read("driver");
61
+ const prefix = read("prefix");
62
+ const name = read("name");
63
+ const emitter = read("emitter");
64
+ return (
65
+ (driver === undefined || driver === "memory") &&
66
+ (prefix === undefined || typeof prefix === "string") &&
67
+ (name === undefined || typeof name === "string") &&
68
+ (emitter === undefined || isEmitter(emitter)) &&
69
+ ["ttl", "grace", "timeout", "hardTimeout", "lockTimeout"].every((field) =>
70
+ isDuration(read(field)),
71
+ )
72
+ );
73
+ }
74
+
46
75
  function isMultiStoreConfig(value: unknown): value is MultiStoreConfig {
47
76
  return (
48
77
  typeof value === "object" &&
@@ -94,15 +123,27 @@ export default class EchoProvider {
94
123
  return manager.use();
95
124
  }
96
125
 
97
- const config = (raw ?? {}) as EchoProviderConfig;
98
- const driver = config.driver ?? "memory";
126
+ const config: unknown = raw ?? {};
127
+ const driver =
128
+ typeof config === "object" && config !== null
129
+ ? (Reflect.get(config, "driver") ?? "memory")
130
+ : "memory";
99
131
  if (driver !== "memory") {
100
- throw new Error(
101
- `[echo] Unsupported driver '${driver}' for default provider — ` +
132
+ throw new EchoError(
133
+ "E_ECHO_UNSUPPORTED_DRIVER",
134
+ `[echo] Unsupported driver '${String(driver)}' for default provider — ` +
102
135
  "wire CacheManager yourself for non-memory drivers, or use the " +
103
136
  "multi-store `{ default, stores }` config.",
104
137
  );
105
138
  }
139
+ // Checked, not asserted: a config file is the application's, and
140
+ // a prefix that is not a string would otherwise reach every key.
141
+ if (!isSingleStoreConfig(config)) {
142
+ throw new EchoError(
143
+ "E_ECHO_INVALID_CONFIG",
144
+ "[echo] config/cache.ts must export an object — `{ prefix, ttl, … }` for one store, or `{ default, stores }` for several.",
145
+ );
146
+ }
106
147
  return new CacheManager(new MemoryDriver(), { ...config, emitter });
107
148
  });
108
149
  // Namespaced by the package that owns it, the way upstream namespaces
@@ -16,15 +16,33 @@
16
16
  */
17
17
 
18
18
  import { CacheManager } from "./CacheManager.js";
19
- import { MemoryDriver } from "./drivers/MemoryDriver.js";
19
+ import {
20
+ MemoryDriver,
21
+ type MemoryDriverOptions,
22
+ } from "./drivers/MemoryDriver.js";
20
23
  import { type RedisClient, RedisDriver } from "./drivers/RedisDriver.js";
21
- import { type CacheBus, TieredDriver } from "./drivers/TieredDriver.js";
24
+ import {
25
+ type CacheBus,
26
+ TieredDriver,
27
+ type TieredDriverOptions,
28
+ } from "./drivers/TieredDriver.js";
22
29
  import type { Duration } from "./duration.js";
30
+ import { EchoError } from "./errors.js";
23
31
  import { quasarBus, quasarConnection } from "./quasar.js";
24
32
  import type { CacheDriver, CacheEmitter, CacheEventMap } from "./types.js";
25
33
 
26
- /** A lazily-instantiated driver (built once per store, on first `use`). */
27
- export type DriverFactory = () => CacheDriver;
34
+ /**
35
+ * A lazily-instantiated driver (built once per store, on first `use`). The
36
+ * store manager passes the store's name, which a tiered driver stamps on its
37
+ * bus messages so stores sharing a channel leave each other alone.
38
+ */
39
+ export type DriverFactory = (context?: DriverContext) => CacheDriver;
40
+
41
+ /** What the store manager tells a driver factory about the store it builds. */
42
+ export interface DriverContext {
43
+ /** The store's key in the config. */
44
+ store: string;
45
+ }
28
46
 
29
47
  export interface StoreConfig {
30
48
  driver: DriverFactory;
@@ -39,9 +57,19 @@ export interface StoreConfig {
39
57
  */
40
58
  ttl?: Duration;
41
59
  grace?: Duration;
60
+ /** How long a stale value stands in after its factory failed (default `'10s'`). */
61
+ graceBackoff?: Duration;
42
62
  timeout?: Duration;
43
63
  hardTimeout?: Duration;
44
64
  lockTimeout?: Duration;
65
+ /**
66
+ * For a two-layer store: serve from L1 and the factory when the L2 fails,
67
+ * rather than failing the call. Default `true` (see
68
+ * {@link TieredDriverOptions.suppressL2Errors}).
69
+ */
70
+ suppressL2Errors?: boolean;
71
+ /** For a two-layer store: how long to skip a failing L2. Off by default. */
72
+ l2CircuitBreakerDuration?: Duration;
45
73
  }
46
74
 
47
75
  export interface MultiStoreConfig {
@@ -109,20 +137,28 @@ export class Store {
109
137
  entry(): StoreConfig {
110
138
  const l1 = this.#l1;
111
139
  const l2 = this.#l2;
112
- if (!l1 && !l2) {
113
- throw new Error(
114
- "Echo: a store needs a layer — call useL1Layer() or useL2Layer() on it.",
115
- );
116
- }
117
140
  if (l1 && l2) {
118
141
  return {
119
142
  ...this.#options,
120
- driver: drivers.tiered({ l1, l2, bus: this.#bus }),
143
+ driver: drivers.tiered({
144
+ l1,
145
+ l2,
146
+ bus: this.#bus,
147
+ suppressL2Errors: this.#options.suppressL2Errors,
148
+ l2CircuitBreakerDuration: this.#options.l2CircuitBreakerDuration,
149
+ }),
121
150
  };
122
151
  }
123
- const only = (l1 ?? l2) as DriverFactory;
152
+ const only = l1 ?? l2;
153
+ if (only === undefined) {
154
+ throw new EchoError(
155
+ "E_ECHO_INVALID_CONFIG",
156
+ "Echo: a store needs a layer — call useL1Layer() or useL2Layer() on it.",
157
+ );
158
+ }
124
159
  if (this.#bus) {
125
- throw new Error(
160
+ throw new EchoError(
161
+ "E_ECHO_INVALID_CONFIG",
126
162
  "Echo: a bus only means something with two layers — it keeps each instance's L1 in step. Add useL2Layer(), or drop useBus().",
127
163
  );
128
164
  }
@@ -135,6 +171,16 @@ export function store(options?: Omit<StoreConfig, "driver">): Store {
135
171
  return new Store(options);
136
172
  }
137
173
 
174
+ /** Either accepted form of a store: a {@link Store} builder, or `{ driver, … }`. */
175
+ function isStoreDeclaration(value: unknown): value is StoreConfig | Store {
176
+ if (value instanceof Store) return true;
177
+ return (
178
+ typeof value === "object" &&
179
+ value !== null &&
180
+ typeof Reflect.get(value, "driver") === "function"
181
+ );
182
+ }
183
+
138
184
  /** Normalise either accepted form to the one the manager reads. */
139
185
  function entryOf(config: StoreConfig | Store): StoreConfig {
140
186
  return config instanceof Store ? config.entry() : config;
@@ -146,12 +192,12 @@ export const drivers = {
146
192
  * `maxItems` bounds the store by COUNT, which a TTL cannot: a cache keyed by
147
193
  * a user id or a search term grows until the process runs out of memory,
148
194
  * however short each entry's life. Omit it for no ceiling.
195
+ *
196
+ * Values are stored as JSON and read back as copies; `serialize: false`
197
+ * keeps references instead (see {@link MemoryDriverOptions.serialize}).
149
198
  */
150
- memory(options?: {
151
- sweepIntervalMs?: number;
152
- maxItems?: number;
153
- }): DriverFactory {
154
- return () => new MemoryDriver(options?.sweepIntervalMs, options?.maxItems);
199
+ memory(options?: MemoryDriverOptions): DriverFactory {
200
+ return () => new MemoryDriver({ ...options });
155
201
  },
156
202
  /**
157
203
  * Either hand it a client, or name a quasar connection — the AdonisJS shape,
@@ -181,16 +227,18 @@ export const drivers = {
181
227
  redisBus(options?: { connection?: string; channel?: string }): CacheBus {
182
228
  return quasarBus(options);
183
229
  },
184
- tiered(options: {
185
- l1: DriverFactory;
186
- l2: DriverFactory;
187
- bus?: CacheBus;
188
- }): DriverFactory {
189
- return () =>
230
+ tiered(
231
+ options: {
232
+ l1: DriverFactory;
233
+ l2: DriverFactory;
234
+ } & Omit<TieredDriverOptions, "l1" | "l2">,
235
+ ): DriverFactory {
236
+ return (context) =>
190
237
  new TieredDriver({
191
- l1: options.l1(),
192
- l2: options.l2(),
193
- bus: options.bus,
238
+ ...options,
239
+ l1: options.l1(context),
240
+ l2: options.l2(context),
241
+ store: options.store ?? context?.store,
194
242
  });
195
243
  },
196
244
  };
@@ -215,33 +263,65 @@ export class CacheStoreManager {
215
263
  "cache:written": new Set(),
216
264
  "cache:deleted": new Set(),
217
265
  "cache:cleared": new Set(),
266
+ "cache:expire": new Set(),
218
267
  };
219
268
 
220
269
  constructor(config: MultiStoreConfig) {
221
270
  this.#config = config;
222
- if (!config.stores[config.default]) {
223
- throw new Error(
271
+ if (!this.#declared(config.default)) {
272
+ throw new EchoError(
273
+ "E_ECHO_UNKNOWN_STORE",
224
274
  `Echo: default store "${config.default}" is not defined in stores`,
225
275
  );
226
276
  }
227
277
  }
228
278
 
279
+ /**
280
+ * A store declared under `name` in the config's OWN keys: a plain lookup
281
+ * would answer `toString` or `constructor` with an Object.prototype member.
282
+ *
283
+ * And one that IS a store. A config is read at runtime, from a file the
284
+ * type checker may never have seen: an own key holding `{}` or `null`
285
+ * passed the lookup, then failed on `cfg.driver(...)` with a bare
286
+ * TypeError, far from the line at fault.
287
+ */
288
+ #declared(name: string): MultiStoreConfig["stores"][string] | undefined {
289
+ if (!Object.hasOwn(this.#config.stores, name)) return undefined;
290
+ const declared: unknown = this.#config.stores[name];
291
+ if (!isStoreDeclaration(declared)) {
292
+ throw new EchoError(
293
+ "E_ECHO_INVALID_CONFIG",
294
+ `Echo: cache store "${name}" is not a store — declare it with store().useL1Layer(…) or as { driver: drivers.memory() }`,
295
+ );
296
+ }
297
+ return declared;
298
+ }
299
+
300
+ /** The store `use()` answers with no name (upstream `defaultStoreName`). */
301
+ get defaultStoreName(): string {
302
+ return this.#config.default;
303
+ }
304
+
229
305
  /** Resolve a store by name (or the default). Instances are built once and cached. */
230
306
  use(name?: string): CacheManager {
231
307
  const store = name ?? this.#config.default;
232
308
  const existing = this.#built.get(store);
233
309
  if (existing) return existing;
234
310
 
235
- const declared = this.#config.stores[store];
311
+ const declared = this.#declared(store);
236
312
  if (!declared) {
237
- throw new Error(`Echo: unknown cache store "${store}"`);
313
+ throw new EchoError(
314
+ "E_ECHO_UNKNOWN_STORE",
315
+ `Echo: unknown cache store "${store}"`,
316
+ );
238
317
  }
239
318
  const cfg = entryOf(declared);
240
- const manager = new CacheManager(cfg.driver(), {
319
+ const manager = new CacheManager(cfg.driver({ store }), {
241
320
  prefix: cfg.prefix,
242
321
  // The store's own, or the one every store inherits.
243
322
  ttl: cfg.ttl ?? this.#config.ttl,
244
323
  grace: cfg.grace,
324
+ graceBackoff: cfg.graceBackoff,
245
325
  timeout: cfg.timeout,
246
326
  hardTimeout: cfg.hardTimeout,
247
327
  lockTimeout: cfg.lockTimeout,
@@ -261,6 +341,7 @@ export class CacheStoreManager {
261
341
  replay("cache:written");
262
342
  replay("cache:deleted");
263
343
  replay("cache:cleared");
344
+ replay("cache:expire");
264
345
  // So `cache.use('other')` works on whichever store the provider
265
346
  // published — upstream's manager is one object that both operates on
266
347
  // the default store and reaches the named ones.
@@ -312,14 +393,29 @@ export class CacheStoreManager {
312
393
  return this;
313
394
  }
314
395
 
315
- /** Clear every store that has been built (bentocache `clearAll`). */
396
+ /**
397
+ * Every store the config declares, built here if this process has not
398
+ * used it yet. Walking only the built ones skipped a store another
399
+ * process writes to: a maintenance script's `clearAll` left its keys.
400
+ */
401
+ #everyStore(): CacheManager[] {
402
+ return Object.keys(this.#config.stores).map((name) => this.use(name));
403
+ }
404
+
405
+ /** Clear every configured store (bentocache `clearAll`). */
316
406
  async clearAll(): Promise<void> {
317
- await Promise.all([...this.#built.values()].map((m) => m.clear()));
407
+ await Promise.all(this.#everyStore().map((m) => m.clear()));
318
408
  }
319
409
 
320
- /** Prune expired entries in every built store (bentocache `prune`). */
410
+ /**
411
+ * Prune expired entries in every configured store (bentocache `prune`).
412
+ *
413
+ * NAMED DEVIATION: upstream's manager prunes the default store only; a
414
+ * store that needs pruning is no less in need of it for not being the
415
+ * default, so every configured one is reached, as `clearAll` does.
416
+ */
321
417
  async prune(): Promise<void> {
322
- await Promise.all([...this.#built.values()].map((m) => m.prune()));
418
+ await Promise.all(this.#everyStore().map((m) => m.prune()));
323
419
  }
324
420
 
325
421
  /**
package/src/bytes.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Byte sizes for the memory driver's bounds — upstream takes a number of bytes
3
+ * or a human string (`'10mb'`), in powers of 1024.
4
+ */
5
+
6
+ import { EchoError } from "./errors.js";
7
+
8
+ const UNIT_BYTES: Record<string, number> = {
9
+ b: 1,
10
+ kb: 1024,
11
+ mb: 1024 ** 2,
12
+ gb: 1024 ** 3,
13
+ tb: 1024 ** 4,
14
+ pb: 1024 ** 5,
15
+ };
16
+
17
+ const BYTES_RE = /^\s*(\d+(?:\.\d+)?)\s*([a-z]+)?\s*$/i;
18
+
19
+ /**
20
+ * A size in bytes, from a number of bytes or a string like `'512kb'`.
21
+ *
22
+ * @throws {EchoError} `E_ECHO_INVALID_CONFIG` for anything that is not a
23
+ * finite, non-negative size: a bound that cannot be read would otherwise
24
+ * leave the store silently unbounded.
25
+ */
26
+ export function parseBytes(value: number | string, option: string): number {
27
+ if (typeof value === "number") {
28
+ if (Number.isFinite(value) && value >= 0) return value;
29
+ } else {
30
+ const match = BYTES_RE.exec(value);
31
+ const factor = UNIT_BYTES[(match?.[2] ?? "b").toLowerCase()];
32
+ if (match && factor !== undefined) return Number(match[1]) * factor;
33
+ }
34
+ throw new EchoError(
35
+ "E_ECHO_INVALID_CONFIG",
36
+ `Echo: ${option} must be a number of bytes or a size like '10mb' — got ${String(value)}`,
37
+ );
38
+ }
package/src/claim.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The one place a cached value becomes the caller's `T`.
3
+ *
4
+ * A cache hands back what was written under a key. The type parameter of
5
+ * `get<T>()` is the caller's statement of what that was — nothing the cache
6
+ * can check, and upstream's `get<T>()` makes the same claim. It lives in this
7
+ * one named function rather than as an assertion at every read site, so the
8
+ * boundary is visible and there is exactly one of it.
9
+ */
10
+ export function claimed<T>(value: unknown): T;
11
+ export function claimed(value: unknown): unknown {
12
+ return value;
13
+ }
14
+
15
+ /** A timer handle that can be unreferenced — Node's, not the browser's. */
16
+ export function hasUnref(timer: unknown): timer is { unref(): void } {
17
+ return (
18
+ typeof timer === "object" &&
19
+ timer !== null &&
20
+ typeof Reflect.get(timer, "unref") === "function"
21
+ );
22
+ }
package/src/configure.ts CHANGED
@@ -11,6 +11,7 @@ import { stubsRoot } from "./stubs.js";
11
11
 
12
12
  interface Codemods {
13
13
  addProvider(importPath: string): Promise<void>;
14
+ registerCommand(importPath: string): Promise<void>;
14
15
  addEnvVars(vars: Record<string, string>): Promise<void>;
15
16
  writeFile(
16
17
  filePath: string,
@@ -34,5 +35,8 @@ export async function configure(codemods: Codemods): Promise<void> {
34
35
  });
35
36
 
36
37
  await codemods.addProvider("@c9up/echo/provider");
38
+ // `cache:clear`, `cache:delete` and `cache:prune` are the package's, not the
39
+ // binary's: a project reaches them by listing the module.
40
+ await codemods.registerCommand("@c9up/echo/commands");
37
41
  await codemods.makeUsingStub(stubsRoot, "config/cache.stub");
38
42
  }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * `cache:clear` — empty a store, one of its namespaces, or its entries under
3
+ * some tags.
4
+ *
5
+ * ream cache:clear
6
+ * ream cache:clear redis --namespace=users
7
+ * ream cache:clear --tags=products --tags=shop
8
+ *
9
+ * In production it asks first, unless `--force`.
10
+ */
11
+
12
+ import {
13
+ argument,
14
+ type CommandApp,
15
+ type CommandLogger,
16
+ type CommandPrompt,
17
+ type EchoCommandClass,
18
+ flag,
19
+ } from "./contract.js";
20
+ import { consent, resolveStore } from "./store.js";
21
+
22
+ export function cacheClearCommand(): EchoCommandClass {
23
+ return class CacheClear {
24
+ static commandName = "cache:clear";
25
+ static description = "Clear the application cache";
26
+ static options = { startApp: true };
27
+ static args = [
28
+ argument("store", {
29
+ description: "Define a custom cache store to clear",
30
+ required: false,
31
+ }),
32
+ ];
33
+ static flags = [
34
+ flag("namespace", "string", {
35
+ description: "Select a cache namespace to clear",
36
+ alias: ["n"],
37
+ }),
38
+ flag("tags", "array", {
39
+ description: "Specify tags to invalidate",
40
+ alias: ["t"],
41
+ }),
42
+ flag("force", "boolean", {
43
+ description: "Explicitly force to clear cache in production",
44
+ }),
45
+ ];
46
+
47
+ declare store?: string;
48
+ declare namespace?: string;
49
+ declare tags?: string[];
50
+ declare force?: boolean;
51
+ declare logger: CommandLogger;
52
+ declare prompt: CommandPrompt;
53
+ declare app: CommandApp;
54
+ declare exitCode?: number;
55
+
56
+ async run(): Promise<void> {
57
+ const cache = resolveStore(this.store, this.logger);
58
+ if (cache === undefined) {
59
+ this.exitCode = 1;
60
+ return;
61
+ }
62
+ const tags = this.tags ?? [];
63
+ if (this.namespace && tags.length > 0) {
64
+ this.logger.error(
65
+ "Cannot use --namespace and --tags options together. Please choose one or the other.",
66
+ );
67
+ this.exitCode = 1;
68
+ return;
69
+ }
70
+ if (
71
+ this.app.inProduction &&
72
+ !this.force &&
73
+ !(await consent(
74
+ this.prompt,
75
+ "You are in production environment. Want to continue clearing the cache?",
76
+ ))
77
+ ) {
78
+ return;
79
+ }
80
+ if (tags.length > 0) {
81
+ await cache.deleteByTag({ tags });
82
+ this.logger.success(
83
+ `Invalidated tags [${tags.join(", ")}] for "${cache.name}" cache successfully`,
84
+ );
85
+ } else if (this.namespace) {
86
+ await cache.namespace(this.namespace).clear();
87
+ this.logger.success(
88
+ `Cleared namespace "${this.namespace}" for "${cache.name}" cache successfully`,
89
+ );
90
+ } else {
91
+ await cache.clear();
92
+ this.logger.success(`Cleared "${cache.name}" cache successfully`);
93
+ }
94
+ }
95
+ };
96
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `cache:delete` — remove one key from a store.
3
+ *
4
+ * ream cache:delete user:42
5
+ * ream cache:delete user:42 redis
6
+ *
7
+ * In production it asks first.
8
+ */
9
+
10
+ import {
11
+ argument,
12
+ type CommandApp,
13
+ type CommandLogger,
14
+ type CommandPrompt,
15
+ type EchoCommandClass,
16
+ } from "./contract.js";
17
+ import { consent, resolveStore } from "./store.js";
18
+
19
+ export function cacheDeleteCommand(): EchoCommandClass {
20
+ return class CacheDelete {
21
+ static commandName = "cache:delete";
22
+ static description = "Delete a specific cache entry by key";
23
+ static options = { startApp: true };
24
+ static args = [
25
+ argument("key", { description: "The cache key to delete" }),
26
+ argument("store", {
27
+ description: "Define a custom cache store to delete from",
28
+ required: false,
29
+ }),
30
+ ];
31
+
32
+ declare key: string;
33
+ declare store?: string;
34
+ declare logger: CommandLogger;
35
+ declare prompt: CommandPrompt;
36
+ declare app: CommandApp;
37
+ declare exitCode?: number;
38
+
39
+ async run(): Promise<void> {
40
+ const cache = resolveStore(this.store, this.logger);
41
+ if (cache === undefined) {
42
+ this.exitCode = 1;
43
+ return;
44
+ }
45
+ if (
46
+ this.app.inProduction &&
47
+ !(await consent(
48
+ this.prompt,
49
+ `You are in production environment. Want to continue deleting cache key "${this.key}"?`,
50
+ ))
51
+ ) {
52
+ return;
53
+ }
54
+ if (await cache.delete({ key: this.key })) {
55
+ this.logger.success(
56
+ `Deleted cache key "${this.key}" from "${cache.name}" cache successfully`,
57
+ );
58
+ } else {
59
+ this.logger.warning(
60
+ `Cache key "${this.key}" not found in "${cache.name}" cache`,
61
+ );
62
+ }
63
+ }
64
+ };
65
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `cache:prune` — drop the entries a store knows to be expired. Only useful
3
+ * for stores that do not expire on their own; Redis does.
4
+ *
5
+ * In production it asks first.
6
+ */
7
+
8
+ import {
9
+ argument,
10
+ type CommandApp,
11
+ type CommandLogger,
12
+ type CommandPrompt,
13
+ type EchoCommandClass,
14
+ } from "./contract.js";
15
+ import { consent, resolveStore } from "./store.js";
16
+
17
+ export function cachePruneCommand(): EchoCommandClass {
18
+ return class CachePrune {
19
+ static commandName = "cache:prune";
20
+ static description =
21
+ "Remove expired cache entries from the selected store. This command is only useful for stores without native TTL support.";
22
+ static options = { startApp: true };
23
+ static args = [
24
+ argument("store", {
25
+ description: "Define a custom cache store to prune",
26
+ required: false,
27
+ }),
28
+ ];
29
+
30
+ declare store?: string;
31
+ declare logger: CommandLogger;
32
+ declare prompt: CommandPrompt;
33
+ declare app: CommandApp;
34
+ declare exitCode?: number;
35
+
36
+ async run(): Promise<void> {
37
+ const cache = resolveStore(this.store, this.logger);
38
+ if (cache === undefined) {
39
+ this.exitCode = 1;
40
+ return;
41
+ }
42
+ if (
43
+ this.app.inProduction &&
44
+ !(await consent(
45
+ this.prompt,
46
+ "You are in production environment. Want to continue pruning expired cache entries?",
47
+ ))
48
+ ) {
49
+ return;
50
+ }
51
+ await cache.prune();
52
+ this.logger.success(
53
+ `Pruned expired entries from "${cache.name}" cache successfully`,
54
+ );
55
+ }
56
+ };
57
+ }