@zintrust/redis-rpc 2.4.4 → 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 +14 -6
- package/dist/adapters.d.ts +3 -1
- package/dist/adapters.js +2 -0
- package/dist/backend.js +176 -62
- package/dist/server.js +21 -4
- package/package.json +1 -1
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
|
|
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
|
|
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
|
-
- `
|
|
212
|
+
- `start` / `startWorker` / `startAppWorker`
|
|
213
|
+
- `restart` / `restartWorker` / `restartAppWorker`
|
|
214
|
+
- `stop` / `stopWorker`
|
|
211
215
|
- `list`
|
|
212
216
|
|
|
213
|
-
The
|
|
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
|
|
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.
|
package/dist/adapters.d.ts
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
259
|
-
const
|
|
260
|
-
if (
|
|
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
|
|
263
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
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
|
|
395
|
-
if (!
|
|
505
|
+
const current = await getWorkerRecord(state, workerName);
|
|
506
|
+
if (!current)
|
|
396
507
|
return false;
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
508
|
+
return saveWorkerRecord(state, {
|
|
509
|
+
...current,
|
|
510
|
+
status: 'stopped',
|
|
511
|
+
updatedAt: new Date().toISOString(),
|
|
512
|
+
});
|
|
400
513
|
}
|
|
401
|
-
case 'list':
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
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 =
|
|
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 = [];
|
|
@@ -26,7 +26,16 @@ const getHeaderSecret = (request) => {
|
|
|
26
26
|
return typeof raw === 'string' ? raw : '';
|
|
27
27
|
};
|
|
28
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));
|
|
29
36
|
const logStep = (step, details) => {
|
|
37
|
+
if (!shouldTraceServer())
|
|
38
|
+
return;
|
|
30
39
|
Logger.debug(`[redis-rpc][server] ${step}`, details);
|
|
31
40
|
};
|
|
32
41
|
const getRequestContext = (request, settings) => {
|
|
@@ -135,14 +144,22 @@ const sendRpcSuccess = (response, requestId, result) => {
|
|
|
135
144
|
requestId,
|
|
136
145
|
});
|
|
137
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
|
+
};
|
|
138
155
|
const handleRequestError = (response, error) => {
|
|
139
156
|
const payload = toErrorPayload(error);
|
|
157
|
+
const message = errorMessage(payload, error);
|
|
140
158
|
logStep('request.error', {
|
|
141
159
|
status: payload.status,
|
|
142
|
-
message
|
|
143
|
-
? String(payload.body.message ?? '')
|
|
144
|
-
: '',
|
|
160
|
+
message,
|
|
145
161
|
});
|
|
162
|
+
Logger.warn('[redis-rpc][server] request failed', { status: payload.status, message });
|
|
146
163
|
json(response, payload.status, payload.body);
|
|
147
164
|
};
|
|
148
165
|
const handleRpcRequest = async (request, response, context, backend) => {
|