slashbin-kit-core 1.2.0-next.1 → 1.3.0-next.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/README.md CHANGED
@@ -18,7 +18,7 @@ npm install slashbin-kit-core ioredis
18
18
 
19
19
  ```ts
20
20
  import { Redis } from "ioredis";
21
- import { DurableQueueClaim, RedisQueueStore } from "slashbin-kit-core";
21
+ import { DurableQueueClaim, RedisQueueStore, deadLetterEntry } from "slashbin-kit-core";
22
22
 
23
23
  const client = new Redis();
24
24
  const blockingClient = new Redis({ maxRetriesPerRequest: null });
@@ -28,7 +28,7 @@ const claim = new DurableQueueClaim(store, {
28
28
  queue: "events",
29
29
  processing: "events:processing",
30
30
  maxAttempts: 8,
31
- deadLetter: (item, reason) => store.deadLetterPush("events:dead", `${reason}:${item}`),
31
+ deadLetter: (item, reason) => store.deadLetterPush("events:dead", deadLetterEntry(item, reason)),
32
32
  });
33
33
 
34
34
  async function handle(item: string): Promise<void> {
@@ -50,7 +50,9 @@ export async function run(): Promise<void> {
50
50
  }
51
51
  ```
52
52
 
53
- Items are UTF-8 JSON object strings. The kit reads and writes only the top-level `attempts` member.
53
+ Items are UTF-8 JSON object strings. The kit reads and writes only the top-level `attempts` member, as text, so your other values are never re-encoded.
54
+
55
+ `deadLetterEntry(item, reason)` builds the dead-letter text for your sink. An object keeps every byte and gains a top-level `last_error`. An item that is not a JSON object (invalid JSON, or valid JSON of another type) is stored as `[reason, item]` with the exact original text at index 1; `replayDeadLetters` and its dry run refuse it and leave it in place. Do not `JSON.parse` and `JSON.stringify` an item in your sink: that rewrites large and exponent numbers.
54
56
 
55
57
  ## What to know
56
58
 
@@ -0,0 +1,11 @@
1
+ import type { DeadLetterReason } from "./durable-queue-claim.js";
2
+ /**
3
+ * The text to store in a dead-letter list for `item`. Built for the adopter's `deadLetter` sink.
4
+ *
5
+ * A JSON object keeps every byte it had; only its top-level `last_error` is set to `reason`, so
6
+ * `replayDeadLetters` can move it back unchanged. Anything else (invalid JSON, or valid JSON that is
7
+ * not an object) is stored as the JSON array `[reason, item]`: `item` is the exact original text, read
8
+ * back with `JSON.parse(entry)[1]`, and replay and preview refuse the entry and leave it in place.
9
+ * Never throws.
10
+ */
11
+ export declare function deadLetterEntry(item: string, reason: DeadLetterReason): string;
@@ -0,0 +1,13 @@
1
+ import { isJsonObject, withLastError } from "./item-text.js";
2
+ /**
3
+ * The text to store in a dead-letter list for `item`. Built for the adopter's `deadLetter` sink.
4
+ *
5
+ * A JSON object keeps every byte it had; only its top-level `last_error` is set to `reason`, so
6
+ * `replayDeadLetters` can move it back unchanged. Anything else (invalid JSON, or valid JSON that is
7
+ * not an object) is stored as the JSON array `[reason, item]`: `item` is the exact original text, read
8
+ * back with `JSON.parse(entry)[1]`, and replay and preview refuse the entry and leave it in place.
9
+ * Never throws.
10
+ */
11
+ export function deadLetterEntry(item, reason) {
12
+ return isJsonObject(item) ? withLastError(item, reason) : JSON.stringify([reason, item]);
13
+ }
@@ -0,0 +1,31 @@
1
+ import type { QueueStore } from "./queue-store.js";
2
+ export interface ReplayOptions {
3
+ /** The live queue to replay into. */
4
+ queue: string;
5
+ /** The Redis dead-letter list, e.g. "taste_tester:forward:deadletter". */
6
+ deadLetterKey: string;
7
+ /** Integer >= 1. Default 1. */
8
+ limit?: number;
9
+ /** Default false. When true, reads the oldest `limit` items and writes nothing. */
10
+ dryRun?: boolean;
11
+ }
12
+ export interface ReplayResult {
13
+ /** Items replayed (or, on a dry run, items that would be). 0 when the dead-letter list is empty; not an error. */
14
+ replayed: number;
15
+ /** The item strings with attempts = 0, last_error kept; [] when replayed = 0. */
16
+ items: string[];
17
+ }
18
+ /** Rejection of a replay that stopped part way; `replayed` lists the items already moved and still replayed. */
19
+ export declare class ReplayError extends Error {
20
+ readonly replayed: string[];
21
+ constructor(message: string, replayed: string[], options: {
22
+ cause: unknown;
23
+ });
24
+ }
25
+ /**
26
+ * Moves the oldest `limit` dead letters back to `queue`, one atomic `replayOldest` per item, resetting
27
+ * `attempts` to 0 and keeping every other byte (including `last_error`). Stops early when the list is
28
+ * empty. A dead letter that is not a JSON object is refused: the call rejects with a ReplayError, the
29
+ * entry stays in place, and `replayed` carries the items already moved. A Redis failure rejects the same way.
30
+ */
31
+ export declare function replayDeadLetters(store: QueueStore, opts: ReplayOptions): Promise<ReplayResult>;
@@ -0,0 +1,52 @@
1
+ import { isJsonObject, withAttempts } from "./item-text.js";
2
+ /** Rejection of a replay that stopped part way; `replayed` lists the items already moved and still replayed. */
3
+ export class ReplayError extends Error {
4
+ replayed;
5
+ constructor(message, replayed, options) {
6
+ super(message, options);
7
+ this.replayed = replayed;
8
+ this.name = "ReplayError";
9
+ }
10
+ }
11
+ /**
12
+ * Moves the oldest `limit` dead letters back to `queue`, one atomic `replayOldest` per item, resetting
13
+ * `attempts` to 0 and keeping every other byte (including `last_error`). Stops early when the list is
14
+ * empty. A dead letter that is not a JSON object is refused: the call rejects with a ReplayError, the
15
+ * entry stays in place, and `replayed` carries the items already moved. A Redis failure rejects the same way.
16
+ */
17
+ export async function replayDeadLetters(store, opts) {
18
+ const limit = opts.limit ?? 1;
19
+ if (!Number.isInteger(limit) || limit < 1) {
20
+ throw new Error(`replayDeadLetters: limit must be an integer >= 1, got ${String(opts.limit)}`);
21
+ }
22
+ return opts.dryRun === true ? previewOldest(store, opts.deadLetterKey, limit) : moveOldest(store, opts, limit);
23
+ }
24
+ async function previewOldest(store, deadLetterKey, limit) {
25
+ const oldest = await store.peekOldest(deadLetterKey, limit);
26
+ const items = [];
27
+ for (const entry of oldest) {
28
+ if (!isJsonObject(entry)) {
29
+ throw new ReplayError(`replayDeadLetters: oldest entry of "${deadLetterKey}" is not a JSON object; left in place`, [], {
30
+ cause: entry,
31
+ });
32
+ }
33
+ items.push(withAttempts(entry, 0));
34
+ }
35
+ return { replayed: items.length, items };
36
+ }
37
+ async function moveOldest(store, opts, limit) {
38
+ const items = [];
39
+ try {
40
+ while (items.length < limit) {
41
+ const item = await store.replayOldest(opts.deadLetterKey, opts.queue);
42
+ if (item === null)
43
+ break;
44
+ items.push(item);
45
+ }
46
+ }
47
+ catch (cause) {
48
+ const reason = cause instanceof Error ? cause.message : String(cause);
49
+ throw new ReplayError(`replayDeadLetters: stopped after ${items.length} item(s): ${reason}`, items, { cause });
50
+ }
51
+ return { replayed: items.length, items };
52
+ }
package/dist/index.d.ts CHANGED
@@ -2,3 +2,6 @@ export { DurableQueueClaim } from "./durable-queue-claim.js";
2
2
  export type { DurableQueueClaimOptions, FailOutcome, DeadLetterReason } from "./durable-queue-claim.js";
3
3
  export { RedisQueueStore } from "./queue-store.js";
4
4
  export type { QueueStore } from "./queue-store.js";
5
+ export { replayDeadLetters, ReplayError } from "./dead-letter-replay.js";
6
+ export type { ReplayOptions, ReplayResult } from "./dead-letter-replay.js";
7
+ export { deadLetterEntry } from "./dead-letter-entry.js";
package/dist/index.js CHANGED
@@ -1,2 +1,4 @@
1
1
  export { DurableQueueClaim } from "./durable-queue-claim.js";
2
2
  export { RedisQueueStore } from "./queue-store.js";
3
+ export { replayDeadLetters, ReplayError } from "./dead-letter-replay.js";
4
+ export { deadLetterEntry } from "./dead-letter-entry.js";
@@ -9,5 +9,7 @@
9
9
  export declare function readAttempts(raw: string): number;
10
10
  /** The item with its top-level `attempts` set to `attempts`; every other byte is unchanged. */
11
11
  export declare function withAttempts(raw: string, attempts: number): string;
12
+ /** The item with its top-level `last_error` set to `reason`; every other byte is unchanged. */
13
+ export declare function withLastError(raw: string, reason: string): string;
12
14
  /** True when `raw` parses as a JSON object (not null, an array or a scalar). */
13
15
  export declare function isJsonObject(raw: string): boolean;
package/dist/item-text.js CHANGED
@@ -78,22 +78,30 @@ export function readAttempts(raw) {
78
78
  const value = JSON.parse(raw.slice(last.valueStart, last.valueEnd));
79
79
  return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : 0;
80
80
  }
81
- /** The item with its top-level `attempts` set to `attempts`; every other byte is unchanged. */
82
- export function withAttempts(raw, attempts) {
81
+ /** The item with every top-level member named `key` set to `valueText` (JSON text), or appended when absent; every other byte is unchanged. */
82
+ function withMember(raw, key, valueText) {
83
83
  const { members, insertAt } = scanObject(raw);
84
- const existing = members.filter((m) => m.key === "attempts");
84
+ const existing = members.filter((m) => m.key === key);
85
85
  if (existing.length === 0) {
86
- const member = `"attempts":${attempts}`;
86
+ const member = `${JSON.stringify(key)}:${valueText}`;
87
87
  return `${raw.slice(0, insertAt)}${members.length > 0 ? "," : ""}${member}${raw.slice(insertAt)}`;
88
88
  }
89
89
  let out = "";
90
90
  let from = 0;
91
91
  for (const m of existing) {
92
- out += raw.slice(from, m.valueStart) + String(attempts);
92
+ out += raw.slice(from, m.valueStart) + valueText;
93
93
  from = m.valueEnd;
94
94
  }
95
95
  return out + raw.slice(from);
96
96
  }
97
+ /** The item with its top-level `attempts` set to `attempts`; every other byte is unchanged. */
98
+ export function withAttempts(raw, attempts) {
99
+ return withMember(raw, "attempts", String(attempts));
100
+ }
101
+ /** The item with its top-level `last_error` set to `reason`; every other byte is unchanged. */
102
+ export function withLastError(raw, reason) {
103
+ return withMember(raw, "last_error", JSON.stringify(reason));
104
+ }
97
105
  /** True when `raw` parses as a JSON object (not null, an array or a scalar). */
98
106
  export function isJsonObject(raw) {
99
107
  try {
@@ -11,6 +11,8 @@ export interface QueueStore {
11
11
  requeueAll(processing: string, queue: string): Promise<number>;
12
12
  /** LPUSH deadKey item. The OLDEST dead letter is at the tail. */
13
13
  deadLetterPush(deadKey: string, item: string): Promise<void>;
14
+ /** LRANGE deadKey: up to `limit` entries, oldest first. Writes nothing. */
15
+ peekOldest(deadKey: string, limit: number): Promise<string[]>;
14
16
  /**
15
17
  * Replays the OLDEST dead letter: sets its top-level attempts to 0 as text (every other byte unchanged),
16
18
  * then moves it with one Lua EVAL that checks the destination is a list and the entry is still the oldest.
@@ -32,5 +34,6 @@ export declare class RedisQueueStore implements QueueStore {
32
34
  remove(processing: string, item: string): Promise<number>;
33
35
  requeueAll(processing: string, queue: string): Promise<number>;
34
36
  deadLetterPush(deadKey: string, item: string): Promise<void>;
37
+ peekOldest(deadKey: string, limit: number): Promise<string[]>;
35
38
  replayOldest(deadKey: string, queue: string): Promise<string | null>;
36
39
  }
@@ -45,6 +45,10 @@ export class RedisQueueStore {
45
45
  async deadLetterPush(deadKey, item) {
46
46
  await this.client.lpush(deadKey, item);
47
47
  }
48
+ async peekOldest(deadKey, limit) {
49
+ const tailFirst = await this.client.lrange(deadKey, -limit, -1);
50
+ return tailFirst.reverse();
51
+ }
48
52
  async replayOldest(deadKey, queue) {
49
53
  for (let attempt = 0; attempt < REPLAY_ATTEMPTS; attempt++) {
50
54
  const oldest = await this.client.lindex(deadKey, -1);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slashbin-kit-core",
3
- "version": "1.2.0-next.1",
3
+ "version": "1.3.0-next.1",
4
4
  "description": "Shared queue-claim primitives for Slashbin receiver and ingest kits: at-least-once claim, ack, retry and boot reconcile over Redis lists.",
5
5
  "license": "MIT",
6
6
  "repository": {