@c9up/echo 0.1.15 → 0.2.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.
Files changed (44) hide show
  1. package/dist/CacheManager.d.ts +52 -6
  2. package/dist/CacheManager.d.ts.map +1 -1
  3. package/dist/CacheManager.js +146 -6
  4. package/dist/CacheManager.js.map +1 -1
  5. package/dist/EchoProvider.d.ts +27 -1
  6. package/dist/EchoProvider.d.ts.map +1 -1
  7. package/dist/EchoProvider.js +31 -3
  8. package/dist/EchoProvider.js.map +1 -1
  9. package/dist/StoreManager.d.ts +25 -2
  10. package/dist/StoreManager.d.ts.map +1 -1
  11. package/dist/StoreManager.js +35 -1
  12. package/dist/StoreManager.js.map +1 -1
  13. package/dist/drivers/MemoryDriver.d.ts +1 -1
  14. package/dist/drivers/MemoryDriver.d.ts.map +1 -1
  15. package/dist/drivers/MemoryDriver.js +19 -3
  16. package/dist/drivers/MemoryDriver.js.map +1 -1
  17. package/dist/drivers/RedisDriver.d.ts +1 -1
  18. package/dist/drivers/RedisDriver.d.ts.map +1 -1
  19. package/dist/drivers/RedisDriver.js +5 -2
  20. package/dist/drivers/RedisDriver.js.map +1 -1
  21. package/dist/drivers/TieredDriver.d.ts +45 -3
  22. package/dist/drivers/TieredDriver.d.ts.map +1 -1
  23. package/dist/drivers/TieredDriver.js +77 -10
  24. package/dist/drivers/TieredDriver.js.map +1 -1
  25. package/dist/quasar.d.ts +7 -6
  26. package/dist/quasar.d.ts.map +1 -1
  27. package/dist/quasar.js +96 -68
  28. package/dist/quasar.js.map +1 -1
  29. package/dist/types.d.ts +26 -1
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/vendor/quasarConnection.d.ts +35 -0
  32. package/dist/vendor/quasarConnection.d.ts.map +1 -0
  33. package/dist/vendor/quasarConnection.js +62 -0
  34. package/dist/vendor/quasarConnection.js.map +1 -0
  35. package/package.json +1 -1
  36. package/src/CacheManager.ts +163 -12
  37. package/src/EchoProvider.ts +32 -3
  38. package/src/StoreManager.ts +52 -3
  39. package/src/drivers/MemoryDriver.ts +16 -3
  40. package/src/drivers/RedisDriver.ts +5 -2
  41. package/src/drivers/TieredDriver.ts +108 -11
  42. package/src/quasar.ts +123 -87
  43. package/src/types.ts +26 -1
  44. package/src/vendor/quasarConnection.ts +129 -0
package/src/quasar.ts CHANGED
@@ -1,17 +1,55 @@
1
1
  /**
2
2
  * Resolving a Redis connection by name, from `@c9up/quasar`.
3
3
  *
4
- * Echo does not depend on quasar: it is an optional peer, and this module
5
- * never imports it statically. The specifier is built at runtime so the
6
- * TypeScript build stays free of it too — a hard type import would make echo
7
- * unbuildable for anyone who caches in memory.
4
+ * Echo does not depend on quasar: it is an optional peer, and neither this
5
+ * module nor the vendored loader it calls imports it statically. The specifier
6
+ * is built at runtime so the TypeScript build stays free of it too.
8
7
  *
9
- * The shape is checked before use rather than asserted, the same way echo
10
- * duck-types its host framework.
8
+ * The loading, the shape check and the messages are the same in every package
9
+ * that offers a Redis-backed option, so they are vendored rather than written
10
+ * again: `src/vendor/quasarConnection.ts`, generated from one source. The bus
11
+ * below is echo's alone and stays here.
11
12
  */
12
13
 
13
14
  import type { RedisClient } from "./drivers/RedisDriver.js";
14
15
  import type { BusMessage, CacheBus } from "./drivers/TieredDriver.js";
16
+ import { quasarConnection as loadQuasarConnection } from "./vendor/quasarConnection.js";
17
+
18
+ /**
19
+ * The commands this driver actually issues.
20
+ *
21
+ * `keys` and `exists` are deliberately absent: `RedisClient` declares them, but
22
+ * nothing here calls them — `flush()` walks a SCAN cursor because it considers
23
+ * KEYS unsafe in production, so demanding `keys` would reject a client that
24
+ * omits it on exactly the grounds this driver agrees with. `scan` is optional
25
+ * on the interface, and `flush()` reports its absence with a message of its
26
+ * own.
27
+ */
28
+ const REQUIRED = [
29
+ "get",
30
+ "set",
31
+ "del",
32
+ "sadd",
33
+ "srem",
34
+ "smembers",
35
+ "expire",
36
+ "ttl",
37
+ ] as const;
38
+
39
+ /**
40
+ * A resolver for `drivers.redis({ connection })` — quasar is loaded on the
41
+ * first cache command, not at config time.
42
+ */
43
+ export function quasarConnection(name?: string): () => Promise<RedisClient> {
44
+ return async () =>
45
+ loadQuasarConnection<RedisClient>({
46
+ pkg: "echo",
47
+ name,
48
+ required: REQUIRED,
49
+ what: "the cache store",
50
+ raise: (_reason, message, cause) => new Error(message, { cause }),
51
+ });
52
+ }
15
53
 
16
54
  /** The slice of quasar's manager this needs: a connection, by name. */
17
55
  interface ConnectionSource {
@@ -22,77 +60,31 @@ function isConnectionSource(value: unknown): value is ConnectionSource {
22
60
  return (
23
61
  typeof value === "object" &&
24
62
  value !== null &&
63
+ "connection" in value &&
25
64
  typeof Reflect.get(value, "connection") === "function"
26
65
  );
27
66
  }
28
67
 
29
- function isRedisClient(value: unknown): value is RedisClient {
30
- if (typeof value !== "object" || value === null) return false;
31
- // The commands this driver actually issues. A connection missing one would
32
- // fail on the first cache write, far from the cause.
33
- //
34
- // `keys` and `exists` are deliberately NOT required: `RedisClient` declares
35
- // them, but nothing here calls them — `flush()` walks a SCAN cursor because
36
- // it considers KEYS unsafe in production. Demanding `keys` would reject a
37
- // client that omits it on exactly the grounds this driver agrees with.
38
- // `scan` is optional on the interface, and `flush()` reports its absence
39
- // with a precise message of its own.
40
- const required = [
41
- "get",
42
- "set",
43
- "del",
44
- "sadd",
45
- "srem",
46
- "smembers",
47
- "expire",
48
- "ttl",
49
- ];
50
- return required.every(
51
- (name) => typeof Reflect.get(value, name) === "function",
52
- );
53
- }
54
-
55
- /**
56
- * A resolver for `drivers.redis({ connection })` — quasar is loaded on the
57
- * first cache command, not at config time.
58
- */
59
- export function quasarConnection(name?: string): () => Promise<RedisClient> {
60
- return async () => {
61
- const specifier = "@c9up/quasar/services/main";
62
- let loaded: unknown;
63
- try {
64
- loaded = await import(/* @vite-ignore */ specifier);
65
- } catch (cause) {
66
- throw new Error(
67
- `Echo: the "${name ?? "default"}" cache store asks for a quasar connection, but @c9up/quasar is not installed.\n` +
68
- " pnpm add @c9up/quasar",
69
- { cause },
70
- );
71
- }
72
-
73
- const manager = isConnectionSource(loaded)
74
- ? loaded
75
- : Reflect.get(Object(loaded), "default");
76
- if (!isConnectionSource(manager)) {
77
- throw new Error(
78
- "Echo: @c9up/quasar/services/main did not expose a connection() manager",
79
- );
80
- }
81
-
82
- const connection = manager.connection(name);
83
- if (!isRedisClient(connection)) {
84
- throw new Error(
85
- `Echo: quasar connection "${name ?? "default"}" does not carry the commands this cache needs`,
86
- );
87
- }
88
- return connection;
89
- };
90
- }
91
-
92
68
  /** The slice of quasar's manager a pub/sub bus needs. */
93
69
  interface PubSubSource {
94
70
  publish(channel: string, message: string): unknown;
95
- subscribe(channel: string, handler: (message: string) => void): unknown;
71
+ subscribe(
72
+ channel: string,
73
+ handler: (message: string) => void,
74
+ /**
75
+ * How a failure is REPORTED. Quasar catches the Redis error, calls this
76
+ * and resolves normally — so awaiting the call proves nothing, and
77
+ * without it the tier believed it was subscribed while no handler was
78
+ * installed.
79
+ */
80
+ options?: { onError?: (error: unknown) => void },
81
+ ): unknown;
82
+ /**
83
+ * Optional, and NAMED when it is there: quasar stacks handlers per channel,
84
+ * so dropping them all would silence whatever else the application listens
85
+ * to on the connection echo borrows.
86
+ */
87
+ unsubscribe?(channel: string, handler?: (message: string) => void): unknown;
96
88
  }
97
89
 
98
90
  function isPubSubSource(value: unknown): value is PubSubSource {
@@ -144,6 +136,11 @@ export function quasarBus(options?: {
144
136
  }): CacheBus {
145
137
  const channel = options?.channel ?? "echo::invalidate";
146
138
  let ready: Promise<PubSubSource> | undefined;
139
+ /** Per subscriber, the wrapper actually registered — once it has been. */
140
+ const opened = new Map<
141
+ (message: BusMessage) => void,
142
+ Promise<(raw: string) => void>
143
+ >();
147
144
 
148
145
  const manager = (): Promise<PubSubSource> => {
149
146
  ready ??= loadQuasar(
@@ -167,24 +164,63 @@ export function quasarBus(options?: {
167
164
  const source = await manager();
168
165
  await source.publish(channel, JSON.stringify(message));
169
166
  },
170
- subscribe(handler: (message: BusMessage) => void): void {
171
- // Not awaited: `subscribe` is synchronous in the bus contract, and the
172
- // socket opens on quasar's own schedule. A failure to reach Redis must
173
- // not take down the store — a bus that is down costs staleness, and
174
- // throwing here would cost every cache read.
175
- void manager()
176
- .then((source) =>
177
- source.subscribe(channel, (raw: string) => {
178
- try {
179
- handler(JSON.parse(raw) as BusMessage);
180
- } catch {
181
- /* a malformed frame is not a reason to stop listening */
182
- }
183
- }),
184
- )
185
- .catch(() => {
186
- /* reported by the first publish, which does surface its error */
167
+ async subscribe(handler: (message: BusMessage) => void): Promise<void> {
168
+ const wrapper = (raw: string): void => {
169
+ try {
170
+ handler(JSON.parse(raw) as BusMessage);
171
+ } catch {
172
+ /* a malformed frame is not a reason to stop listening */
173
+ }
174
+ };
175
+ // AWAITED, and a reported failure becomes a rejection.
176
+ //
177
+ // This used to be fire-and-forget with the rejection swallowed, and
178
+ // quasar catches the Redis error itself and resolves — so the tier
179
+ // believed it was subscribed while no handler was installed. Every
180
+ // instance then served its own stale L1 until the TTL ran out, with
181
+ // nothing anywhere to say the bus was down.
182
+ //
183
+ // The provider awaits this in `ready()`, so an unreachable bus is a
184
+ // failed boot rather than a deployment that looks healthy and is
185
+ // quietly incoherent.
186
+ const attempt = (async (): Promise<(raw: string) => void> => {
187
+ const source = await manager();
188
+ let reported: unknown;
189
+ await source.subscribe(channel, wrapper, {
190
+ onError: (error) => {
191
+ reported = error;
192
+ },
187
193
  });
194
+ if (reported !== undefined) {
195
+ opened.delete(handler);
196
+ throw reported instanceof Error
197
+ ? reported
198
+ : new Error(String(reported));
199
+ }
200
+ return wrapper;
201
+ })();
202
+ opened.set(handler, attempt);
203
+ // Forgotten on a direct rejection too, so a retry is not refused by
204
+ // bookkeeping for a subscription that never happened.
205
+ attempt.catch(() => opened.delete(handler));
206
+ await attempt;
207
+ },
208
+ async unsubscribe(handler: (message: BusMessage) => void): Promise<void> {
209
+ // The subscribe may still be opening the socket. Removing ahead of it
210
+ // takes nothing off and leaves the handler to land afterwards, on a
211
+ // bus nobody is tracking any more.
212
+ const pending = opened.get(handler);
213
+ if (pending === undefined) return;
214
+ const wrapper = await pending;
215
+ const source = await manager();
216
+ // NAMED. Quasar keeps a `Set` of handlers per channel, so an unnamed
217
+ // unsubscribe drops every listener on a connection the application
218
+ // shares with the cache.
219
+ await source.unsubscribe?.(channel, wrapper);
220
+ // Forgotten LAST. Dropped before the call, a refusal left a live
221
+ // listener nothing could name again — neither to retry it nor to
222
+ // remove it at a second shutdown.
223
+ opened.delete(handler);
188
224
  },
189
225
  };
190
226
  }
package/src/types.ts CHANGED
@@ -53,7 +53,19 @@ export interface CacheDriver {
53
53
  get<T = unknown>(key: string): Promise<T | null>;
54
54
  set(key: string, value: unknown, ttlSeconds?: number): Promise<void>;
55
55
  delete(key: string): Promise<boolean>;
56
- flush(): Promise<void>;
56
+ /**
57
+ * Remove everything — or, when `prefix` is given, only the keys under it.
58
+ *
59
+ * A namespaced view shares this driver, so a `clear()` on one had to be
60
+ * able to say WHICH subtree it meant. Without that it flushed the whole
61
+ * store, and a namespace per tenant is the documented use: one tenant
62
+ * clearing its own cache emptied everyone else's.
63
+ *
64
+ * A driver that cannot scope the removal must REFUSE when a prefix is
65
+ * given. Flushing everything instead is the failure this parameter exists
66
+ * to prevent, and it is silent.
67
+ */
68
+ flush(prefix?: string): Promise<void>;
57
69
  has(key: string): Promise<boolean>;
58
70
  /** Grace-aware read: returns the entry even if stale, or `null` if physically gone. */
59
71
  getEntry?<T = unknown>(key: string): Promise<CacheEntry<T> | null>;
@@ -63,6 +75,19 @@ export interface CacheDriver {
63
75
  value: unknown,
64
76
  options: DriverSetOptions,
65
77
  ): Promise<void>;
78
+ /**
79
+ * Open whatever this driver needs OUTSIDE the process — a bus subscription,
80
+ * a connection it owns.
81
+ *
82
+ * Separate from the constructor on purpose. Building a store is what
83
+ * publishing the cache service does, and that happens while the application
84
+ * boots, including under `ream inspect` — which never shuts anything down.
85
+ * A driver that opened a socket to exist left one behind every time someone
86
+ * listed the routes. This is called once the application is ready, and its
87
+ * failure is the application's to refuse: a tiered store that never
88
+ * subscribed serves stale L1 copies to everyone until their TTL.
89
+ */
90
+ connect?(): Promise<void>;
66
91
  /**
67
92
  * Drop entries this driver knows to be expired (bentocache `prune`). Only
68
93
  * stores that do not evict on their own need it.
@@ -0,0 +1,129 @@
1
+ // Generated from scripts/vendor/quasarConnection.ts — do not edit.
2
+ //
3
+ // This package is published and built from its own repository, so the file
4
+ // has to exist here rather than be imported. `pnpm vendor:sync` rewrites it,
5
+ // and `pnpm vendor:check` fails if this copy has drifted from the original.
6
+
7
+ /**
8
+ * Resolving a Redis connection by name, from `@c9up/quasar`.
9
+ *
10
+ * No package here depends on quasar: it is an optional peer, and this module
11
+ * never imports it statically — the specifier is built at runtime so the
12
+ * TypeScript build stays free of it too. A host that never names a connection
13
+ * neither installs it nor pays for it.
14
+ *
15
+ * What varies between callers is passed in rather than copied: which commands
16
+ * they will issue, and what they are doing with them. Both end up in the
17
+ * message, because "the connection is missing lpop" is only useful next to
18
+ * "which the queue's atomic pop issues".
19
+ */
20
+
21
+ /** The slice of quasar's manager this needs: a connection, by name. */
22
+ interface ConnectionSource {
23
+ connection(name?: string): unknown;
24
+ }
25
+
26
+ /**
27
+ * Read a member without assuming how the object answers.
28
+ *
29
+ * Two shapes have to work, and they disagree about `in`. Quasar's accessor is
30
+ * a Proxy over an empty null-prototype object with only a `get` trap, so
31
+ * `"connection" in manager` is FALSE while reading it returns the function —
32
+ * gating on `in` rejected the real manager. And a module namespace under a
33
+ * test double RAISES for an export it does not have, rather than answering
34
+ * undefined, so a bare read fails on the mock. Reading through a catch is what
35
+ * satisfies both.
36
+ */
37
+ function readMember(value: unknown, name: string): unknown {
38
+ if (typeof value !== "object" || value === null) return undefined;
39
+ try {
40
+ return Reflect.get(value, name);
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ function isConnectionSource(value: unknown): value is ConnectionSource {
47
+ return typeof readMember(value, "connection") === "function";
48
+ }
49
+
50
+ export interface QuasarConnectionRequest {
51
+ /** The package asking. It prefixes every message this can raise. */
52
+ pkg: string;
53
+ /**
54
+ * How this package builds an error.
55
+ *
56
+ * Not optional, and not `new Error` by default: a package with its own
57
+ * error type carries codes (`E_<PKG>_<REASON>`) that a caller catches on,
58
+ * and a shared helper throwing a bare Error would silently drop them. The
59
+ * two reasons are distinguished so the codes can be too.
60
+ */
61
+ raise: (
62
+ reason: "quasar-missing" | "incomplete-connection",
63
+ message: string,
64
+ cause?: unknown,
65
+ ) => Error;
66
+ /** Connection name, or `undefined` for quasar's default. */
67
+ name?: string;
68
+ /** The commands the caller will actually issue. */
69
+ required: readonly string[];
70
+ /** What the caller does with them, for the message that names a gap. */
71
+ what: string;
72
+ /**
73
+ * A second way out, when this package has one.
74
+ *
75
+ * Several of them accept a client object directly, so "pass a client
76
+ * instead of a connection name" is actionable — and it was in each
77
+ * package's own message before this was shared. Dropping it to unify the
78
+ * wording would have made the error strictly less useful.
79
+ */
80
+ alternative?: string;
81
+ }
82
+
83
+ /**
84
+ * The named connection, checked for the commands the caller needs BEFORE it is
85
+ * handed over — a connection missing one would otherwise fail on the first
86
+ * command, far from the line that asked for it.
87
+ */
88
+ export async function quasarConnection<T>(
89
+ request: QuasarConnectionRequest,
90
+ ): Promise<T> {
91
+ const { pkg, name, required, what, raise, alternative } = request;
92
+ const specifier = "@c9up/quasar/services/main";
93
+ let loaded: unknown;
94
+ try {
95
+ loaded = await import(/* @vite-ignore */ specifier);
96
+ } catch (cause) {
97
+ throw raise(
98
+ "quasar-missing",
99
+ `[${pkg}] ${what} asks for the quasar connection "${name ?? "default"}", but @c9up/quasar is not installed.\n` +
100
+ ` pnpm add @c9up/quasar${alternative ? `, ${alternative}` : ""}`,
101
+ cause,
102
+ );
103
+ }
104
+
105
+ const manager = isConnectionSource(loaded)
106
+ ? loaded
107
+ : Reflect.get(Object(loaded), "default");
108
+ if (!isConnectionSource(manager)) {
109
+ throw raise(
110
+ "quasar-missing",
111
+ `[${pkg}] @c9up/quasar/services/main did not expose a connection() manager`,
112
+ );
113
+ }
114
+
115
+ const connection = manager.connection(name);
116
+ const missing = required.filter(
117
+ (command) => typeof readMember(connection, command) !== "function",
118
+ );
119
+ if (missing.length > 0) {
120
+ throw raise(
121
+ "incomplete-connection",
122
+ `[${pkg}] the quasar connection${name ? ` '${name}'` : ""} is missing ${missing.join(", ")}, which ${what} issues`,
123
+ );
124
+ }
125
+ // Load-bearing: every member of `required` has just been checked to be a
126
+ // function on this object. The caller names the type it needs because only
127
+ // the caller knows which commands it asked for.
128
+ return connection as T;
129
+ }