@zintrust/redis-rpc 2.4.3 → 2.4.6

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  `@zintrust/redis-rpc` provides an HTTP RPC boundary for Redis-backed BullMQ operations. It is designed for runtimes that cannot safely create direct Redis or BullMQ connections, such as Cloudflare Workers, queue dashboards, remote worker controllers, and thin application processes.
4
4
 
5
- Instead of asking every package to emulate Redis commands or BullMQ Lua scripts, the caller sends a typed intent to a backend-owned RPC server. The RPC server owns the real Redis connection, BullMQ queues, queue events, and worker instances.
5
+ Instead of asking every package to emulate Redis commands or BullMQ Lua scripts, the caller sends a typed intent to a backend-owned RPC server. The RPC server owns the real Redis connection, BullMQ queues, queue events, and worker lifecycle state. Application job execution stays in the runtime that has the application processors.
6
6
 
7
7
  ## When to use it
8
8
 
@@ -11,7 +11,7 @@ Use Redis RPC when:
11
11
  - `USE_REDIS_PROXY=true` and `REDIS_RPC_URL` are both configured.
12
12
  - Queue producers run in an environment where direct TCP Redis is unavailable.
13
13
  - Queue monitor or worker dashboard code needs queue state without constructing local BullMQ clients.
14
- - You want a single backend process to own Redis credentials and BullMQ execution details.
14
+ - You want a single backend process to own Redis credentials and BullMQ coordination details.
15
15
 
16
16
  Use direct BullMQ/Redis when your process can safely connect to Redis and does not need a proxy boundary.
17
17
 
@@ -186,6 +186,7 @@ Supported methods:
186
186
  - `add` / `enqueue`
187
187
  - `dequeue`
188
188
  - `ack`
189
+ - `fail` / `nack`
189
190
  - `get` / `getJob`
190
191
  - `getJobs`
191
192
  - `getJobCounts` / `counts`
@@ -202,15 +203,22 @@ Supported methods:
202
203
 
203
204
  Queue requests identify the queue with `payload.target`, `payload.queueName`, or `payload.queue`.
204
205
 
206
+ `dequeue` is for pull-based runtimes. It uses BullMQ's own atomic waiting-to-active transition and returns `{ id, name, payload, attempts }`. The caller must report the result with `ack` or `fail` / `nack`. `ack` accepts an optional return value as `payload.returnValue`, `payload.returnvalue`, or the second positional arg. `fail` / `nack` accepts an optional failure reason as `payload.reason` or the second positional arg.
207
+
205
208
  ### `worker`
206
209
 
207
210
  Supported methods:
208
211
 
209
- - `startWorker`
210
- - `stopWorker`
212
+ - `start` / `startWorker` / `startAppWorker`
213
+ - `restart` / `restartWorker` / `restartAppWorker`
214
+ - `stop` / `stopWorker`
211
215
  - `list`
212
216
 
213
- The default backend processors are intentionally small (`echo`, `sum`, and `fail`) so smoke tests and simple remote workers can run without loading application code. Register custom backend services or extend the backend process when production worker processors need application-specific behavior.
217
+ The Redis RPC backend does not import application processor modules and does not create BullMQ `Worker` consumers. Worker lifecycle calls persist desired state in Redis under `<BULLMQ_PREFIX>:__rpc_workers`. The record includes worker name, queue name, optional processor spec, concurrency, status, and update time.
218
+
219
+ This keeps Redis RPC as a coordination service. A Node worker process, Cloudflare Worker, container, or other runtime that already has the application code should pull jobs with `queue.dequeue`, execute the processor locally, then complete the job with `queue.ack` or `queue.fail`.
220
+
221
+ `worker.list` returns the persisted lifecycle records plus queue-discovery placeholders for BullMQ queues that have no registered worker record. Placeholders use `source: "bullmq-discovery"` and names like `<queueName>:redis-rpc`; persisted records use `source: "redis-rpc-registry"`.
214
222
 
215
223
  ### `queue-monitor`
216
224
 
@@ -291,4 +299,4 @@ Run the BullMQ smoke test when a Redis instance is available:
291
299
  npm --prefix packages/redis-rpc run test
292
300
  ```
293
301
 
294
- The smoke test starts the RPC server, verifies Redis `PING`, adds normal and delayed jobs, starts backend-owned workers, checks completed and failed job states, reads queue monitor snapshots, removes jobs, drains, cleans, and obliterates the temporary queue.
302
+ The smoke test starts the RPC server, verifies Redis `PING`, adds jobs, exercises queue lifecycle calls, reads queue monitor snapshots, removes jobs, drains, cleans, and obliterates the temporary queue.
@@ -3,7 +3,9 @@ type QueueRpcMethods = Readonly<{
3
3
  add: (name: string, data?: unknown, opts?: Record<string, unknown>) => Promise<unknown>;
4
4
  enqueue: (name: string, data?: unknown, opts?: Record<string, unknown>) => Promise<unknown>;
5
5
  dequeue: (visibilityTimeoutMs?: number) => Promise<unknown>;
6
- ack: (jobId: string) => Promise<unknown>;
6
+ ack: (jobId: string, returnValue?: unknown) => Promise<unknown>;
7
+ fail: (jobId: string, reason?: string) => Promise<unknown>;
8
+ nack: (jobId: string, reason?: string) => Promise<unknown>;
7
9
  get: (data?: Record<string, unknown>) => Promise<unknown>;
8
10
  getJob: (jobId: string) => Promise<unknown>;
9
11
  getJobs: (states?: string[], start?: number, end?: number, asc?: boolean) => Promise<unknown>;
package/dist/adapters.js CHANGED
@@ -9,6 +9,8 @@ export const createBullMqRpcQueue = (queueName, options = {}) => {
9
9
  enqueue: (...args) => client.queue('add', { target: queueName, args }),
10
10
  dequeue: (visibilityTimeoutMs) => client.queue('dequeue', { target: queueName, visibilityTimeoutMs }),
11
11
  ack: (...args) => client.queue('ack', { target: queueName, args }),
12
+ fail: (...args) => client.queue('fail', { target: queueName, args }),
13
+ nack: (...args) => client.queue('nack', { target: queueName, args }),
12
14
  get: (data = {}) => client.queue('getJob', { target: queueName, ...data }),
13
15
  getJob: (...args) => client.queue('getJob', { target: queueName, args }),
14
16
  getJobs: (...args) => client.queue('getJobs', { target: queueName, args }),
package/dist/backend.js CHANGED
@@ -2,7 +2,7 @@ import { ErrorFactory } from '@zintrust/core/errors';
2
2
  import { isArray, isNonEmptyString, isObject, isUndefinedOrNull } from '@zintrust/core/helper';
3
3
  import { Logger } from '@zintrust/core/logger';
4
4
  import { Sanitizer } from '@zintrust/core/security';
5
- import { Queue, QueueEvents, Worker, } from 'bullmq';
5
+ import { Job, Queue, QueueEvents, } from 'bullmq';
6
6
  import IORedis from 'ioredis';
7
7
  import { redisConnectionOptions, rpcServerOptions } from './env.js';
8
8
  import { createRpcValidationError } from './errors.js';
@@ -253,16 +253,32 @@ const getQueueJobById = async (state, queueName, payload) => {
253
253
  const args = asArgs(payload);
254
254
  return getJob(state, queueName, firstDefined(args[0], payload.jobId, payload.id));
255
255
  };
256
+ const normalizedPrefix = (state) => state.prefix.replace(/:+$/u, '');
257
+ const claimLockKey = (state, queueName, jobId) => `${normalizedPrefix(state)}:${queueName}:__pull_claim:${jobId}`;
258
+ const releaseClaim = async (state, queueName, jobId) => {
259
+ const connection = createConnection(state, { maxRetriesPerRequest: 1 });
260
+ try {
261
+ await connection.del(claimLockKey(state, queueName, jobId));
262
+ }
263
+ finally {
264
+ connection.disconnect();
265
+ }
266
+ };
256
267
  const dequeueQueueJob = async (state, queueName, payload) => {
257
268
  const queue = getQueue(state, queueName);
258
- const jobs = await queue.getJobs(['waiting'], 0, 0);
259
- const job = jobs[0];
260
- if (!job)
269
+ queue.opts.lockDuration = Math.max(1, numberFrom(payload.visibilityTimeoutMs, 30_000));
270
+ const scripts = queue.scripts;
271
+ if (scripts === undefined)
261
272
  return undefined;
262
- const visibilityTimeoutMs = numberFrom(payload.visibilityTimeoutMs, 30_000);
263
- await job.moveToDelayed(Date.now() + Math.max(1, visibilityTimeoutMs), PULL_WORKER_TOKEN);
273
+ const client = await queue.client;
274
+ const [jobData, jobId] = await scripts.moveToActive(client, PULL_WORKER_TOKEN, '');
275
+ if (!jobData || isUndefinedOrNull(jobId))
276
+ return undefined;
277
+ const job = Job.fromJSON(queue, jobData, String(jobId));
278
+ job.token = PULL_WORKER_TOKEN;
264
279
  return {
265
- id: isUndefinedOrNull(job.id) ? undefined : String(job.id),
280
+ id: String(job.id),
281
+ name: job.name,
266
282
  payload: job.data,
267
283
  attempts: job.attemptsMade || 0,
268
284
  };
@@ -271,7 +287,26 @@ const ackQueueJob = async (state, queueName, payload) => {
271
287
  const job = await getQueueJobById(state, queueName, payload);
272
288
  if (!job)
273
289
  return false;
274
- await job.moveToCompleted('acknowledged', PULL_WORKER_TOKEN, false);
290
+ const args = asArgs(payload);
291
+ const returnValue = firstDefined(args[1], payload.returnValue, payload.returnvalue, 'acknowledged');
292
+ await job.moveToCompleted(returnValue, PULL_WORKER_TOKEN, false);
293
+ if (!isUndefinedOrNull(job.id)) {
294
+ await releaseClaim(state, queueName, String(job.id));
295
+ }
296
+ return true;
297
+ };
298
+ const failQueueJob = async (state, queueName, payload) => {
299
+ const job = await getQueueJobById(state, queueName, payload);
300
+ if (!job)
301
+ return false;
302
+ const args = asArgs(payload);
303
+ const reason = isNonEmptyString(firstDefined(args[1], payload.reason))
304
+ ? String(firstDefined(args[1], payload.reason))
305
+ : 'failed by pull worker';
306
+ await job.moveToFailed(new Error(reason), PULL_WORKER_TOKEN, false);
307
+ if (!isUndefinedOrNull(job.id)) {
308
+ await releaseClaim(state, queueName, String(job.id));
309
+ }
275
310
  return true;
276
311
  };
277
312
  const removeQueueJob = async (state, queueName, payload) => {
@@ -318,6 +353,9 @@ const dispatchQueue = async (state, method, payload) => {
318
353
  return dequeueQueueJob(state, queueName, payload);
319
354
  case 'ack':
320
355
  return ackQueueJob(state, queueName, payload);
356
+ case 'fail':
357
+ case 'nack':
358
+ return failQueueJob(state, queueName, payload);
321
359
  case 'pause':
322
360
  await getQueue(state, queueName).pause();
323
361
  return true;
@@ -348,61 +386,147 @@ const dispatchQueue = async (state, method, payload) => {
348
386
  }
349
387
  };
350
388
  /* eslint-enable complexity */
351
- const createProcessor = (kind) => {
352
- switch (kind) {
353
- case 'echo':
354
- case undefined:
355
- case null:
356
- return async (job) => ({ echo: job.data, jobId: job.id, name: job.name });
357
- case 'sum':
358
- return async (job) => {
359
- const data = job.data;
360
- const values = isArray(data.values) ? data.values : [];
361
- return values.reduce((total, value) => total + Number(value || 0), 0);
362
- };
363
- case 'fail':
364
- return async () => {
365
- throw ErrorFactory.createWorkerError('redis-rpc test processor failure');
366
- };
367
- default:
368
- throw createRpcValidationError(`Unsupported worker processor: ${String(kind)}`);
389
+ const workerRegistryKey = (state) => `${normalizedPrefix(state)}:__rpc_workers`;
390
+ const buildWorkerRecord = (payload, status) => {
391
+ const args = asArgs(payload);
392
+ const queueName = requireString(firstDefined(args[0], payload.queueName, payload.queue), 'queueName');
393
+ const workerName = requireString(firstDefined(args[1], payload.workerName, payload.name, `${queueName}:worker`), 'workerName');
394
+ const processorSpec = firstDefined(payload.processorSpec, payload.spec, payload.processor);
395
+ return {
396
+ workerName,
397
+ queueName,
398
+ processorSpec: isNonEmptyString(processorSpec) ? String(processorSpec) : null,
399
+ concurrency: Math.max(1, numberFrom(payload.concurrency, 1)),
400
+ status,
401
+ updatedAt: new Date().toISOString(),
402
+ source: 'redis-rpc-registry',
403
+ };
404
+ };
405
+ const parseWorkerRecord = (raw) => {
406
+ try {
407
+ const parsed = JSON.parse(raw);
408
+ if (!isNonEmptyString(parsed.workerName) || !isNonEmptyString(parsed.queueName))
409
+ return null;
410
+ return {
411
+ workerName: parsed.workerName,
412
+ queueName: parsed.queueName,
413
+ processorSpec: isNonEmptyString(parsed.processorSpec) ? parsed.processorSpec : null,
414
+ concurrency: Math.max(1, numberFrom(parsed.concurrency, 1)),
415
+ status: parsed.status === 'running' ? 'running' : 'stopped',
416
+ updatedAt: isNonEmptyString(parsed.updatedAt) ? parsed.updatedAt : new Date().toISOString(),
417
+ source: 'redis-rpc-registry',
418
+ };
419
+ }
420
+ catch {
421
+ return null;
369
422
  }
370
423
  };
424
+ const saveWorkerRecord = async (state, record) => {
425
+ const connection = createConnection(state, { maxRetriesPerRequest: 1 });
426
+ try {
427
+ await connection.hset(workerRegistryKey(state), record.workerName, JSON.stringify(record));
428
+ }
429
+ finally {
430
+ connection.disconnect();
431
+ }
432
+ return record;
433
+ };
434
+ const getWorkerRecord = async (state, workerName) => {
435
+ const connection = createConnection(state, { maxRetriesPerRequest: 1 });
436
+ try {
437
+ const raw = await connection.hget(workerRegistryKey(state), workerName);
438
+ return raw ? parseWorkerRecord(raw) : null;
439
+ }
440
+ finally {
441
+ connection.disconnect();
442
+ }
443
+ };
444
+ const listWorkerRecords = async (state) => {
445
+ const connection = createConnection(state, { maxRetriesPerRequest: 1 });
446
+ try {
447
+ const records = Object.values(await connection.hgetall(workerRegistryKey(state)))
448
+ .map((raw) => parseWorkerRecord(raw))
449
+ .filter((record) => record !== null);
450
+ return records.sort((left, right) => left.workerName.localeCompare(right.workerName));
451
+ }
452
+ finally {
453
+ connection.disconnect();
454
+ }
455
+ };
456
+ const QUEUE_DISCOVERY_EVENT_KEYS = new Set([
457
+ 'wait',
458
+ 'waiting',
459
+ 'active',
460
+ 'completed',
461
+ 'failed',
462
+ 'delayed',
463
+ 'paused',
464
+ 'meta',
465
+ ]);
466
+ const discoverQueueNames = async (state) => {
467
+ const discovered = new Set(state.queues.keys());
468
+ const connection = createConnection(state, { maxRetriesPerRequest: 1 });
469
+ const prefix = normalizedPrefix(state);
470
+ const marker = `${prefix}:`;
471
+ let cursor = '0';
472
+ try {
473
+ do {
474
+ // eslint-disable-next-line no-await-in-loop
475
+ const [nextCursor, keys] = await connection.scan(cursor, 'MATCH', `${prefix}:*`, 'COUNT', '500');
476
+ cursor = String(nextCursor ?? '0');
477
+ for (const key of Array.isArray(keys) ? keys : []) {
478
+ if (typeof key !== 'string' || !key.startsWith(marker))
479
+ continue;
480
+ const [queueName, keyKind] = key.slice(marker.length).split(':');
481
+ if (queueName && QUEUE_DISCOVERY_EVENT_KEYS.has(keyKind ?? '')) {
482
+ discovered.add(queueName);
483
+ }
484
+ }
485
+ } while (cursor !== '0');
486
+ }
487
+ finally {
488
+ connection.disconnect();
489
+ }
490
+ return Array.from(discovered).sort((left, right) => left.localeCompare(right));
491
+ };
371
492
  const dispatchWorker = async (state, method, payload) => {
372
493
  const args = asArgs(payload);
373
494
  switch (method) {
374
495
  case 'start':
375
- case 'startWorker': {
376
- const queueName = requireString(firstDefined(args[0], payload.queueName, payload.queue), 'queueName');
377
- const defaultWorkerName = `${queueName}:${String(payload.processor || 'echo')}`;
378
- const workerName = requireString(firstDefined(args[1], payload.workerName, payload.name, defaultWorkerName), 'workerName');
379
- if (state.workers.has(workerName))
380
- return { workerName, queueName, status: 'already-running' };
381
- const options = isRecord(args[2]) ? args[2] : payload;
382
- const worker = new Worker(queueName, createProcessor(options.processor), {
383
- connection: createConnection(state),
384
- prefix: state.prefix,
385
- concurrency: numberFrom(options.concurrency, 1),
386
- });
387
- state.workers.set(workerName, { queueName, worker });
388
- await worker.waitUntilReady();
389
- return { workerName, queueName, status: 'running' };
390
- }
496
+ case 'startWorker':
497
+ case 'startAppWorker':
498
+ case 'restart':
499
+ case 'restartWorker':
500
+ case 'restartAppWorker':
501
+ return saveWorkerRecord(state, buildWorkerRecord(payload, 'running'));
391
502
  case 'stop':
392
503
  case 'stopWorker': {
393
504
  const workerName = requireString(firstDefined(args[0], payload.workerName, payload.name), 'workerName');
394
- const entry = state.workers.get(workerName);
395
- if (!entry)
505
+ const current = await getWorkerRecord(state, workerName);
506
+ if (!current)
396
507
  return false;
397
- await entry.worker.close(true);
398
- state.workers.delete(workerName);
399
- return true;
508
+ return saveWorkerRecord(state, {
509
+ ...current,
510
+ status: 'stopped',
511
+ updatedAt: new Date().toISOString(),
512
+ });
400
513
  }
401
- case 'list':
402
- return Array.from(state.workers.entries()).map(([workerName, entry]) => ({
403
- workerName,
404
- queueName: entry.queueName,
514
+ case 'list': {
515
+ const registered = await listWorkerRecords(state);
516
+ const registeredQueues = new Set(registered.map((record) => record.queueName));
517
+ const placeholders = (await discoverQueueNames(state))
518
+ .filter((queueName) => !registeredQueues.has(queueName))
519
+ .map((queueName) => ({
520
+ workerName: `${queueName}:redis-rpc`,
521
+ queueName,
522
+ processorSpec: null,
523
+ concurrency: 1,
524
+ status: 'stopped',
525
+ updatedAt: new Date().toISOString(),
526
+ source: 'bullmq-discovery',
405
527
  }));
528
+ return [...registered, ...placeholders];
529
+ }
406
530
  default:
407
531
  throw createRpcValidationError(`Unsupported worker method: ${method}`);
408
532
  }
@@ -420,7 +544,7 @@ const dispatchMonitor = async (state, method, payload) => {
420
544
  queueNames = payload.queueNames;
421
545
  }
422
546
  else {
423
- queueNames = Array.from(state.queues.keys());
547
+ queueNames = await discoverQueueNames(state);
424
548
  }
425
549
  const queues = await Promise.all(queueNames.map(async (name) => {
426
550
  const queueName = requireString(name, 'queueName');
@@ -487,14 +611,6 @@ const dispatchCustom = async (backend, state, service, method, payload) => {
487
611
  return handler({ method, payload, backend });
488
612
  };
489
613
  const closeBackend = async (state) => {
490
- await Promise.allSettled(Array.from(state.workers.values()).map(async ({ worker }) => {
491
- try {
492
- await withTimeout(() => worker.close(true));
493
- }
494
- catch {
495
- await worker.disconnect();
496
- }
497
- }));
498
614
  await Promise.allSettled(Array.from(state.queueEvents.values()).map(async (events) => {
499
615
  try {
500
616
  await withTimeout(() => events.close());
@@ -514,7 +630,6 @@ const closeBackend = async (state) => {
514
630
  for (const connection of state.connections) {
515
631
  connection.disconnect();
516
632
  }
517
- state.workers.clear();
518
633
  state.queues.clear();
519
634
  state.queueEvents.clear();
520
635
  state.eventLogs.clear();
@@ -527,7 +642,6 @@ export const createRedisRpcBackend = (options = {}) => {
527
642
  connectionOptions: options.redis || redisConnectionOptions(),
528
643
  queues: new Map(),
529
644
  queueEvents: new Map(),
530
- workers: new Map(),
531
645
  eventLogs: new Map(),
532
646
  connections: new Set(),
533
647
  services: new Map(Object.entries(options.services ?? {})),
package/dist/server.js CHANGED
@@ -2,7 +2,7 @@ import { isObject } from '@zintrust/core/helper';
2
2
  import { Logger } from '@zintrust/core/runtime';
3
3
  import http from 'node:http';
4
4
  import { createRedisRpcBackend } from './backend.js';
5
- import { rpcServerOptions } from './env.js';
5
+ import { readString, rpcServerOptions } from './env.js';
6
6
  import { createRpcNotFoundError, createRpcUnauthorizedError, toErrorPayload } from './errors.js';
7
7
  const readBody = async (request) => {
8
8
  const chunks = [];
@@ -18,33 +18,186 @@ const json = (response, status, payload) => {
18
18
  });
19
19
  response.end(JSON.stringify(payload));
20
20
  };
21
+ const getHeaderSecret = (request) => {
22
+ const raw = request.headers['x-redis-rpc-secret'];
23
+ if (Array.isArray(raw)) {
24
+ return raw[0] ?? '';
25
+ }
26
+ return typeof raw === 'string' ? raw : '';
27
+ };
28
+ const previewSecret = (value) => value.slice(0, 5);
29
+ const readBool = (key, fallback) => {
30
+ const raw = readString(key, fallback ? 'true' : 'false').trim().toLowerCase();
31
+ if (raw === '')
32
+ return fallback;
33
+ return raw === '1' || raw === 'true' || raw === 'yes' || raw === 'on';
34
+ };
35
+ const shouldTraceServer = () => readBool('REDIS_RPC_SERVER_DEBUG', readBool('REDIS_RPC_TRACE', false));
36
+ const logStep = (step, details) => {
37
+ if (!shouldTraceServer())
38
+ return;
39
+ Logger.debug(`[redis-rpc][server] ${step}`, details);
40
+ };
41
+ const getRequestContext = (request, settings) => {
42
+ const method = request.method ?? '';
43
+ const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`);
44
+ const headerSecret = getHeaderSecret(request);
45
+ const settingsSecret = settings.secret || '';
46
+ return {
47
+ method,
48
+ url,
49
+ headerSecret,
50
+ settingsSecret,
51
+ };
52
+ };
53
+ const logRequestReceived = (context) => {
54
+ logStep('request.received', {
55
+ method: context.method,
56
+ path: context.url.pathname,
57
+ host: context.url.host,
58
+ headerSecretPreview: previewSecret(context.headerSecret),
59
+ settingsSecretPreview: previewSecret(context.settingsSecret),
60
+ });
61
+ };
62
+ const isHealthRoute = (context) => context.method === 'GET' && context.url.pathname === '/health';
63
+ const isRpcRoute = (context) => context.method === 'POST' && context.url.pathname === '/rpc';
64
+ const logHealthRoute = (prefix, path) => {
65
+ logStep('route.health', {
66
+ path,
67
+ prefix,
68
+ });
69
+ };
70
+ const logRouteCheck = (context) => {
71
+ logStep('route.check', {
72
+ method: context.method,
73
+ path: context.url.pathname,
74
+ isRpcRoute: isRpcRoute(context),
75
+ });
76
+ };
77
+ const logRouteNotFound = (context) => {
78
+ logStep('route.notFound', {
79
+ method: context.method,
80
+ path: context.url.pathname,
81
+ });
82
+ };
83
+ const validateRequestSecret = (context) => {
84
+ logStep('secret.validate.start', {
85
+ headerSecretPreview: previewSecret(context.headerSecret),
86
+ settingsSecretPreview: previewSecret(context.settingsSecret),
87
+ });
88
+ const secretMatches = context.settingsSecret !== '' && context.headerSecret === context.settingsSecret;
89
+ logStep('secret.validate.result', {
90
+ headerSecretPreview: previewSecret(context.headerSecret),
91
+ settingsSecretPreview: previewSecret(context.settingsSecret),
92
+ secretMatches,
93
+ });
94
+ return secretMatches;
95
+ };
96
+ const logSecretValidationFailure = (context) => {
97
+ logStep('secret.validate.failed', {
98
+ headerSecretPreview: previewSecret(context.headerSecret),
99
+ settingsSecretPreview: previewSecret(context.settingsSecret),
100
+ });
101
+ };
102
+ const readRpcBody = async (request) => {
103
+ logStep('body.read.start', {});
104
+ const bodyText = await readBody(request);
105
+ logStep('body.read.complete', {
106
+ length: bodyText.length,
107
+ isEmpty: bodyText.trim().length === 0,
108
+ });
109
+ try {
110
+ const body = (bodyText.trim().length === 0 ? {} : JSON.parse(bodyText));
111
+ logStep('body.parse.complete', {
112
+ requestId: body.requestId ?? null,
113
+ service: String(body.service || ''),
114
+ method: String(body.method || ''),
115
+ hasPayload: body.payload !== undefined,
116
+ });
117
+ return body;
118
+ }
119
+ catch (error) {
120
+ logStep('body.parse.failed', {
121
+ error: error instanceof Error ? error.message : String(error),
122
+ });
123
+ throw error;
124
+ }
125
+ };
126
+ const dispatchRpcRequest = async (backend, body) => {
127
+ logStep('dispatch.start', {
128
+ requestId: body.requestId ?? null,
129
+ service: String(body.service || ''),
130
+ method: String(body.method || ''),
131
+ });
132
+ const result = await backend.dispatch(String(body.service || ''), String(body.method || ''), body.payload ?? {});
133
+ logStep('dispatch.complete', {
134
+ requestId: body.requestId ?? null,
135
+ service: String(body.service || ''),
136
+ method: String(body.method || ''),
137
+ });
138
+ return result;
139
+ };
140
+ const sendRpcSuccess = (response, requestId, result) => {
141
+ json(response, 200, { ok: true, requestId, result, error: null });
142
+ logStep('response.sent', {
143
+ status: 200,
144
+ requestId,
145
+ });
146
+ };
147
+ const errorMessage = (payload, error) => {
148
+ if (payload.body && typeof payload.body === 'object' && 'message' in payload.body) {
149
+ return String(payload.body.message ?? '');
150
+ }
151
+ if (error instanceof Error)
152
+ return error.message;
153
+ return String(error);
154
+ };
155
+ const handleRequestError = (response, error) => {
156
+ const payload = toErrorPayload(error);
157
+ const message = errorMessage(payload, error);
158
+ logStep('request.error', {
159
+ status: payload.status,
160
+ message,
161
+ });
162
+ Logger.warn('[redis-rpc][server] request failed', { status: payload.status, message });
163
+ json(response, payload.status, payload.body);
164
+ };
165
+ const handleRpcRequest = async (request, response, context, backend) => {
166
+ logRouteCheck(context);
167
+ if (!isRpcRoute(context)) {
168
+ logRouteNotFound(context);
169
+ throw createRpcNotFoundError('Unknown Redis RPC route');
170
+ }
171
+ if (!validateRequestSecret(context)) {
172
+ logSecretValidationFailure(context);
173
+ throw createRpcUnauthorizedError('Invalid Redis RPC secret');
174
+ }
175
+ const body = await readRpcBody(request);
176
+ const result = await dispatchRpcRequest(backend, body);
177
+ sendRpcSuccess(response, body.requestId ?? null, result);
178
+ };
179
+ const handleHealthRequest = (response, backend) => {
180
+ logHealthRoute(backend.prefix, '/health');
181
+ json(response, 200, { ok: true, service: 'redis-rpc', prefix: backend.prefix });
182
+ };
183
+ const handleIncomingRequest = async (request, response, settings, backend) => {
184
+ const context = getRequestContext(request, settings);
185
+ logRequestReceived(context);
186
+ if (isHealthRoute(context)) {
187
+ handleHealthRequest(response, backend);
188
+ return;
189
+ }
190
+ await handleRpcRequest(request, response, context, backend);
191
+ };
21
192
  export const createRedisRpcServer = (options = {}) => {
22
193
  const settings = { ...rpcServerOptions(), ...options };
23
194
  const backend = isObject(options.backend)
24
195
  ? options.backend
25
196
  : createRedisRpcBackend(settings);
26
- const server = http.createServer(async (request, response) => {
27
- try {
28
- const url = new URL(request.url || '/', `http://${request.headers.host || 'localhost'}`);
29
- if (request.method === 'GET' && url.pathname === '/health') {
30
- json(response, 200, { ok: true, service: 'redis-rpc', prefix: backend.prefix });
31
- return;
32
- }
33
- if (request.method !== 'POST' || url.pathname !== '/rpc') {
34
- throw createRpcNotFoundError('Unknown Redis RPC route');
35
- }
36
- if (!settings.secret || request.headers['x-redis-rpc-secret'] !== settings.secret) {
37
- throw createRpcUnauthorizedError('Invalid Redis RPC secret');
38
- }
39
- const bodyText = await readBody(request);
40
- const body = (bodyText.trim().length === 0 ? {} : JSON.parse(bodyText));
41
- const result = await backend.dispatch(String(body.service || ''), String(body.method || ''), body.payload ?? {});
42
- json(response, 200, { ok: true, requestId: body.requestId ?? null, result, error: null });
43
- }
44
- catch (error) {
45
- const payload = toErrorPayload(error);
46
- json(response, payload.status, payload.body);
47
- }
197
+ const server = http.createServer((request, response) => {
198
+ void handleIncomingRequest(request, response, settings, backend).catch((error) => {
199
+ handleRequestError(response, error);
200
+ });
48
201
  });
49
202
  return { server, backend, settings };
50
203
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zintrust/redis-rpc",
3
- "version": "2.4.3",
3
+ "version": "2.4.6",
4
4
  "description": "Redis RPC backend for BullMQ queue operations in ZinTrust.",
5
5
  "private": false,
6
6
  "type": "module",