@zintrust/workers 2.4.2 → 2.4.4
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/dist/SLAMonitor.d.ts +7 -0
- package/dist/SLAMonitor.js +17 -0
- package/dist/WorkerFactory.js +17 -0
- package/dist/build-manifest.json +27 -19
- package/dist/dashboard/workerManifest.d.ts +15 -0
- package/dist/dashboard/workerManifest.js +67 -0
- package/dist/dashboard/workers-api.js +173 -30
- package/dist/http/WorkerController.js +192 -7
- package/dist/index.d.ts +1 -1
- package/dist/routes/workers.js +9 -10
- package/package.json +1 -1
- package/src/SLAMonitor.ts +27 -0
- package/src/WorkerFactory.ts +24 -0
- package/src/dashboard/workerManifest.ts +112 -0
- package/src/dashboard/workers-api.ts +227 -31
- package/src/http/WorkerController.ts +257 -21
- package/src/index.ts +8 -1
- package/src/routes/workers.ts +18 -10
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Env, queueConfig } from '@zintrust/core/config';
|
|
1
|
+
import { Cloudflare, Env, queueConfig } from '@zintrust/core/config';
|
|
2
2
|
import { ErrorFactory } from '@zintrust/core/errors';
|
|
3
3
|
import { Logger } from '@zintrust/core/logger';
|
|
4
4
|
import { WorkerFactory } from '../WorkerFactory';
|
|
@@ -19,6 +19,11 @@ import type {
|
|
|
19
19
|
WorkerMetrics,
|
|
20
20
|
WorkersListResponse,
|
|
21
21
|
} from './types';
|
|
22
|
+
import {
|
|
23
|
+
getWorkerManifestEntries,
|
|
24
|
+
getWorkerManifestQueueNames,
|
|
25
|
+
getWorkerManifestRecord,
|
|
26
|
+
} from './workerManifest';
|
|
22
27
|
|
|
23
28
|
const DEFAULT_PAGE_SIZE = 100;
|
|
24
29
|
const MAX_PAGE_SIZE = 200;
|
|
@@ -44,6 +49,154 @@ type PersistenceResult = {
|
|
|
44
49
|
prePaginated: boolean;
|
|
45
50
|
};
|
|
46
51
|
|
|
52
|
+
type RedisRpcWorkerRecord = {
|
|
53
|
+
workerName?: string;
|
|
54
|
+
name?: string;
|
|
55
|
+
queueName?: string;
|
|
56
|
+
status?: string;
|
|
57
|
+
autoStart?: boolean;
|
|
58
|
+
concurrency?: number;
|
|
59
|
+
processorSpec?: string | null;
|
|
60
|
+
source?: string;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const shouldUseRedisRpcWorkerApi = (): boolean =>
|
|
64
|
+
Cloudflare.getWorkersEnv() !== null &&
|
|
65
|
+
Env.getBool('USE_REDIS_PROXY', false) &&
|
|
66
|
+
Env.get('REDIS_RPC_URL', '').trim().length > 0;
|
|
67
|
+
|
|
68
|
+
const createRequestId = (): string => {
|
|
69
|
+
const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;
|
|
70
|
+
if (typeof cryptoApi?.randomUUID === 'function') return cryptoApi.randomUUID();
|
|
71
|
+
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const callRedisRpc = async <T = unknown>(
|
|
75
|
+
service: string,
|
|
76
|
+
method: string,
|
|
77
|
+
payload: Record<string, unknown> = {}
|
|
78
|
+
): Promise<T> => {
|
|
79
|
+
const baseUrl = Env.get('REDIS_RPC_URL', '').trim();
|
|
80
|
+
const endpoint = new URL('/rpc', baseUrl);
|
|
81
|
+
const secret = Env.get('REDIS_RPC_SECRET', Env.get('REDIS_PROXY_SECRET', Env.APP_KEY));
|
|
82
|
+
const response = await fetch(endpoint, {
|
|
83
|
+
method: 'POST',
|
|
84
|
+
headers: {
|
|
85
|
+
'content-type': 'application/json',
|
|
86
|
+
...(secret.trim() === '' ? {} : { 'x-redis-rpc-secret': secret }),
|
|
87
|
+
},
|
|
88
|
+
body: JSON.stringify({ requestId: createRequestId(), service, method, payload }),
|
|
89
|
+
});
|
|
90
|
+
const body = (await response.json().catch(() => ({}))) as {
|
|
91
|
+
ok?: boolean;
|
|
92
|
+
result: T;
|
|
93
|
+
error?: { message?: string };
|
|
94
|
+
};
|
|
95
|
+
if (!response.ok || body.ok !== true) {
|
|
96
|
+
throw ErrorFactory.createTryCatchError(
|
|
97
|
+
body.error?.message ?? `Redis RPC request failed with status ${response.status}`
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
return body.result;
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const manifestWorkers = (): WorkerData[] =>
|
|
104
|
+
transformToWorkerData(
|
|
105
|
+
getWorkerManifestEntries()
|
|
106
|
+
.map((entry): RawWorkerData | null => {
|
|
107
|
+
const name = entry.name ?? entry.workerName;
|
|
108
|
+
if (typeof name !== 'string' || name.trim() === '') return null;
|
|
109
|
+
const autoStart = entry.autoStart ?? false;
|
|
110
|
+
let status: RawWorkerData['status'];
|
|
111
|
+
if (entry.status) {
|
|
112
|
+
status = normalizeStatus(entry.status);
|
|
113
|
+
} else if (autoStart) {
|
|
114
|
+
status = 'running';
|
|
115
|
+
} else {
|
|
116
|
+
status = 'stopped';
|
|
117
|
+
}
|
|
118
|
+
const trimmedName = name.trim();
|
|
119
|
+
return {
|
|
120
|
+
name: trimmedName,
|
|
121
|
+
queueName: typeof entry.queueName === 'string' ? entry.queueName : `${trimmedName}-queue`,
|
|
122
|
+
status,
|
|
123
|
+
autoStart,
|
|
124
|
+
activeStatus: entry.activeStatus ?? true,
|
|
125
|
+
};
|
|
126
|
+
})
|
|
127
|
+
.filter((entry): entry is RawWorkerData => entry !== null),
|
|
128
|
+
'redis'
|
|
129
|
+
);
|
|
130
|
+
|
|
131
|
+
const mergeManifestWorkers = (
|
|
132
|
+
backendWorkers: WorkerData[],
|
|
133
|
+
manifest: WorkerData[] = manifestWorkers()
|
|
134
|
+
): WorkerData[] => {
|
|
135
|
+
const manifestQueues = new Set(manifest.map((worker) => worker.queueName));
|
|
136
|
+
const byName = new Map<string, WorkerData>();
|
|
137
|
+
for (const worker of manifest) {
|
|
138
|
+
byName.set(worker.name, worker);
|
|
139
|
+
}
|
|
140
|
+
for (const worker of backendWorkers) {
|
|
141
|
+
const isPlaceholder =
|
|
142
|
+
worker.name === `${worker.queueName}:redis-rpc` && manifestQueues.has(worker.queueName);
|
|
143
|
+
if (isPlaceholder) continue;
|
|
144
|
+
byName.set(worker.name, { ...byName.get(worker.name), ...worker });
|
|
145
|
+
}
|
|
146
|
+
return Array.from(byName.values()).sort((left, right) => left.name.localeCompare(right.name));
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const redisRpcPersistence = async (limit: number): Promise<PersistenceResult> => {
|
|
150
|
+
const manifest = manifestWorkers();
|
|
151
|
+
try {
|
|
152
|
+
const records = await callRedisRpc<RedisRpcWorkerRecord[]>('worker', 'list');
|
|
153
|
+
const backendWorkers = transformToWorkerData(
|
|
154
|
+
records
|
|
155
|
+
.map((record): RawWorkerData | null => {
|
|
156
|
+
const name = record.workerName ?? record.name;
|
|
157
|
+
if (typeof name !== 'string' || name.trim() === '') return null;
|
|
158
|
+
return {
|
|
159
|
+
name: name.trim(),
|
|
160
|
+
queueName: record.queueName,
|
|
161
|
+
status: normalizeStatus(record.status ?? 'stopped'),
|
|
162
|
+
autoStart: record.autoStart ?? false,
|
|
163
|
+
details: {
|
|
164
|
+
configuration: {
|
|
165
|
+
processorSpec: record.processorSpec ?? null,
|
|
166
|
+
concurrency: record.concurrency ?? null,
|
|
167
|
+
},
|
|
168
|
+
health: {} as WorkerHealth,
|
|
169
|
+
metrics: {} as WorkerMetrics,
|
|
170
|
+
recentLogs: [],
|
|
171
|
+
},
|
|
172
|
+
};
|
|
173
|
+
})
|
|
174
|
+
.filter((record): record is RawWorkerData => record !== null),
|
|
175
|
+
'redis'
|
|
176
|
+
);
|
|
177
|
+
const workers = mergeManifestWorkers(backendWorkers, manifest);
|
|
178
|
+
return {
|
|
179
|
+
workers,
|
|
180
|
+
total: workers.length,
|
|
181
|
+
drivers: ['redis'],
|
|
182
|
+
effectiveLimit: limit,
|
|
183
|
+
prePaginated: false,
|
|
184
|
+
};
|
|
185
|
+
} catch (error) {
|
|
186
|
+
Logger.debug(
|
|
187
|
+
'[getWorkers] Redis RPC persistence unavailable; returning manifest result',
|
|
188
|
+
error
|
|
189
|
+
);
|
|
190
|
+
return {
|
|
191
|
+
workers: manifest,
|
|
192
|
+
total: manifest.length,
|
|
193
|
+
drivers: ['redis'],
|
|
194
|
+
effectiveLimit: limit,
|
|
195
|
+
prePaginated: false,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
47
200
|
// Helper for timeout handling
|
|
48
201
|
async function withTimeout<T>(
|
|
49
202
|
promise: Promise<T>,
|
|
@@ -72,6 +225,10 @@ async function fetchPersistenceWithTimeout(
|
|
|
72
225
|
limit: number,
|
|
73
226
|
query: GetWorkersQuery
|
|
74
227
|
): Promise<PersistenceResult> {
|
|
228
|
+
if (shouldUseRedisRpcWorkerApi()) {
|
|
229
|
+
return redisRpcPersistence(limit);
|
|
230
|
+
}
|
|
231
|
+
|
|
75
232
|
const driver = Env.get('WORKER_PERSISTENCE_DRIVER', 'memory');
|
|
76
233
|
try {
|
|
77
234
|
const result = await withTimeout(
|
|
@@ -450,6 +607,28 @@ const buildWorkerFromRecord = (record: WorkerRecord, driver: WorkerDriver): Work
|
|
|
450
607
|
return buildWorkerFromRaw(rawData, driver);
|
|
451
608
|
};
|
|
452
609
|
|
|
610
|
+
const resolveWorkerDetailsFromPersistence = async (
|
|
611
|
+
name: string,
|
|
612
|
+
driver: WorkerDriver
|
|
613
|
+
): Promise<WorkerData | undefined> => {
|
|
614
|
+
if (driver === 'database') {
|
|
615
|
+
const dbRecord = await WorkerFactory.getPersisted(name, { driver: 'database' });
|
|
616
|
+
if (dbRecord) return buildWorkerFromRecord(dbRecord, 'database');
|
|
617
|
+
|
|
618
|
+
const redisRecord = await WorkerFactory.getPersisted(name, { driver: 'redis' });
|
|
619
|
+
if (redisRecord) return buildWorkerFromRecord(redisRecord, 'redis');
|
|
620
|
+
return undefined;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
const record = await WorkerFactory.getPersisted(name, { driver });
|
|
624
|
+
if (record) return buildWorkerFromRecord(record, driver);
|
|
625
|
+
|
|
626
|
+
const fileBacked = await WorkerFactory.getFileBackedRecord(name);
|
|
627
|
+
if (fileBacked) return buildWorkerFromRecord(fileBacked, 'memory');
|
|
628
|
+
|
|
629
|
+
return undefined;
|
|
630
|
+
};
|
|
631
|
+
|
|
453
632
|
const buildWorkerFromRaw = (workerData: RawWorkerData, driver: WorkerDriver): WorkerData => {
|
|
454
633
|
const status = normalizeStatus(workerData.status ?? 'stopped');
|
|
455
634
|
return {
|
|
@@ -625,6 +804,11 @@ async function getRedisQueueData(): Promise<QueueData> {
|
|
|
625
804
|
|
|
626
805
|
const monitor = QueueMonitor.create({
|
|
627
806
|
knownQueues: async () => {
|
|
807
|
+
const manifestQueues = getWorkerManifestQueueNames();
|
|
808
|
+
if (shouldUseRedisRpcWorkerApi() && manifestQueues.length > 0) {
|
|
809
|
+
return manifestQueues;
|
|
810
|
+
}
|
|
811
|
+
|
|
628
812
|
const records = await WorkerFactory.listPersistedRecords();
|
|
629
813
|
return Array.from(
|
|
630
814
|
new Set(
|
|
@@ -666,7 +850,11 @@ async function getRedisQueueData(): Promise<QueueData> {
|
|
|
666
850
|
failedJobs,
|
|
667
851
|
};
|
|
668
852
|
} catch (error) {
|
|
669
|
-
|
|
853
|
+
if (shouldUseRedisRpcWorkerApi()) {
|
|
854
|
+
Logger.debug('Error fetching Redis queue data:', error);
|
|
855
|
+
} else {
|
|
856
|
+
Logger.error('Error fetching Redis queue data:', error);
|
|
857
|
+
}
|
|
670
858
|
return {
|
|
671
859
|
driver: 'redis',
|
|
672
860
|
totalQueues: 0,
|
|
@@ -1109,40 +1297,48 @@ const getLiveWorkerMetricsByName = (): ReadonlyMap<string, LiveWorkerMetrics> =>
|
|
|
1109
1297
|
return liveMetrics;
|
|
1110
1298
|
};
|
|
1111
1299
|
|
|
1300
|
+
const buildRedisRpcManifestWorker = (
|
|
1301
|
+
name: string,
|
|
1302
|
+
manifestRecord: ReturnType<typeof getWorkerManifestRecord>
|
|
1303
|
+
): WorkerData | undefined => {
|
|
1304
|
+
if (!manifestRecord) return undefined;
|
|
1305
|
+
|
|
1306
|
+
const trimmedName = (manifestRecord.name ?? manifestRecord.workerName ?? name).trim();
|
|
1307
|
+
return buildWorkerFromRaw(
|
|
1308
|
+
{
|
|
1309
|
+
name: trimmedName,
|
|
1310
|
+
queueName:
|
|
1311
|
+
typeof manifestRecord.queueName === 'string' && manifestRecord.queueName.trim().length > 0
|
|
1312
|
+
? manifestRecord.queueName.trim()
|
|
1313
|
+
: `${trimmedName}-queue`,
|
|
1314
|
+
status: normalizeStatus(manifestRecord.status ?? 'stopped'),
|
|
1315
|
+
autoStart: manifestRecord.autoStart ?? false,
|
|
1316
|
+
activeStatus: manifestRecord.activeStatus ?? true,
|
|
1317
|
+
},
|
|
1318
|
+
'redis'
|
|
1319
|
+
);
|
|
1320
|
+
};
|
|
1321
|
+
|
|
1322
|
+
const resolveRedisRpcWorkerDetails = async (name: string): Promise<WorkerData | undefined> => {
|
|
1323
|
+
const persistence = await redisRpcPersistence(5000);
|
|
1324
|
+
const persistedWorker = persistence.workers.find((candidate) => candidate.name === name);
|
|
1325
|
+
if (persistedWorker) return persistedWorker;
|
|
1326
|
+
return buildRedisRpcManifestWorker(name, getWorkerManifestRecord(name));
|
|
1327
|
+
};
|
|
1328
|
+
|
|
1112
1329
|
export async function toggleAutoStart(name: string, enabled: boolean): Promise<void> {
|
|
1113
1330
|
await WorkerFactory.setAutoStart(name, enabled);
|
|
1114
1331
|
}
|
|
1115
1332
|
|
|
1116
1333
|
export async function getWorkerDetails(name: string, driver?: string): Promise<WorkerData> {
|
|
1117
|
-
const persistenceDriver = (driver ||
|
|
1118
|
-
const
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
worker = buildWorkerFromRecord(dbRecord, 'database');
|
|
1126
|
-
} else {
|
|
1127
|
-
const redisRecord = await WorkerFactory.getPersisted(name, { driver: 'redis' });
|
|
1128
|
-
if (redisRecord) {
|
|
1129
|
-
worker = buildWorkerFromRecord(redisRecord, 'redis');
|
|
1130
|
-
}
|
|
1131
|
-
}
|
|
1132
|
-
} else {
|
|
1133
|
-
const normalizedDriver = normalizeDriver(persistenceDriver);
|
|
1134
|
-
const record = await WorkerFactory.getPersisted(name, { driver: normalizedDriver });
|
|
1135
|
-
if (record) {
|
|
1136
|
-
worker = buildWorkerFromRecord(record, normalizedDriver);
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
1139
|
-
|
|
1140
|
-
if (!worker) {
|
|
1141
|
-
const fileBacked = await WorkerFactory.getFileBackedRecord(name);
|
|
1142
|
-
if (fileBacked) {
|
|
1143
|
-
worker = buildWorkerFromRecord(fileBacked, 'memory');
|
|
1144
|
-
}
|
|
1145
|
-
}
|
|
1334
|
+
const persistenceDriver = (driver || Env.get('WORKER_PERSISTENCE_DRIVER', 'memory')) ?? 'memory';
|
|
1335
|
+
const normalizedDriver = normalizeDriver(String(persistenceDriver).toLowerCase());
|
|
1336
|
+
|
|
1337
|
+
const fromRedisRpc =
|
|
1338
|
+
shouldUseRedisRpcWorkerApi() && (driver === undefined || normalizedDriver === 'redis');
|
|
1339
|
+
const worker = fromRedisRpc
|
|
1340
|
+
? await resolveRedisRpcWorkerDetails(name)
|
|
1341
|
+
: await resolveWorkerDetailsFromPersistence(name, normalizedDriver);
|
|
1146
1342
|
|
|
1147
1343
|
if (!worker) {
|
|
1148
1344
|
throw ErrorFactory.createWorkerError(`Worker ${name} not found`);
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
import { Cloudflare } from '@zintrust/core/cloudflare';
|
|
8
8
|
import { Env } from '@zintrust/core/config';
|
|
9
|
+
import { ErrorFactory } from '@zintrust/core/errors';
|
|
9
10
|
import type { IRequest, IResponse } from '@zintrust/core/http';
|
|
10
11
|
import { getValidatedBody } from '@zintrust/core/http';
|
|
11
12
|
import { Logger } from '@zintrust/core/logger';
|
|
@@ -31,7 +32,7 @@ const getBody = (req: IRequest): Record<string, unknown> => {
|
|
|
31
32
|
return (
|
|
32
33
|
getValidatedBody<Record<string, unknown>>(req) ??
|
|
33
34
|
(req.getBody?.() as Record<string, unknown> | undefined) ??
|
|
34
|
-
|
|
35
|
+
req.body ??
|
|
35
36
|
{}
|
|
36
37
|
);
|
|
37
38
|
};
|
|
@@ -40,6 +41,162 @@ const getBody = (req: IRequest): Record<string, unknown> => {
|
|
|
40
41
|
|
|
41
42
|
const isCloudflareEnv = (): boolean => Cloudflare.getWorkersEnv() !== null;
|
|
42
43
|
|
|
44
|
+
const shouldUseRedisRpcWorkerLifecycle = (
|
|
45
|
+
persistenceOverride: PersistenceOverride | undefined
|
|
46
|
+
): boolean => {
|
|
47
|
+
if (!isCloudflareEnv()) return false;
|
|
48
|
+
if (persistenceOverride?.driver !== 'redis') return false;
|
|
49
|
+
return Env.getBool('USE_REDIS_PROXY', false) && Env.get('REDIS_RPC_URL', '').trim().length > 0;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const createRequestId = (): string => {
|
|
53
|
+
const cryptoApi = globalThis.crypto as { randomUUID?: () => string } | undefined;
|
|
54
|
+
if (typeof cryptoApi?.randomUUID === 'function') return cryptoApi.randomUUID();
|
|
55
|
+
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const callRedisRpc = async <T = unknown>(
|
|
59
|
+
service: string,
|
|
60
|
+
method: string,
|
|
61
|
+
payload: Record<string, unknown> = {}
|
|
62
|
+
): Promise<T> => {
|
|
63
|
+
const baseUrl = Env.get('REDIS_RPC_URL', '').trim();
|
|
64
|
+
const endpoint = new URL('/rpc', baseUrl);
|
|
65
|
+
const secret = Env.get('REDIS_RPC_SECRET', Env.get('REDIS_PROXY_SECRET', Env.APP_KEY));
|
|
66
|
+
const response = await fetch(endpoint, {
|
|
67
|
+
method: 'POST',
|
|
68
|
+
headers: {
|
|
69
|
+
'content-type': 'application/json',
|
|
70
|
+
...(secret.trim() === '' ? {} : { 'x-redis-rpc-secret': secret }),
|
|
71
|
+
},
|
|
72
|
+
body: JSON.stringify({ requestId: createRequestId(), service, method, payload }),
|
|
73
|
+
});
|
|
74
|
+
const body = (await response.json().catch(() => ({}))) as {
|
|
75
|
+
ok?: boolean;
|
|
76
|
+
result: T;
|
|
77
|
+
error?: { message?: string };
|
|
78
|
+
};
|
|
79
|
+
if (!response.ok || body.ok !== true) {
|
|
80
|
+
throw ErrorFactory.createTryCatchError(
|
|
81
|
+
body.error?.message ?? `Redis RPC request failed with status ${response.status}`
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
return body.result;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
type WorkerManifestEntry = Readonly<{
|
|
88
|
+
name?: string;
|
|
89
|
+
workerName?: string;
|
|
90
|
+
queueName?: string;
|
|
91
|
+
processorSpec?: string | null;
|
|
92
|
+
concurrency?: number;
|
|
93
|
+
autoStart?: boolean;
|
|
94
|
+
activeStatus?: boolean;
|
|
95
|
+
}>;
|
|
96
|
+
|
|
97
|
+
type PersistenceOverride =
|
|
98
|
+
| { driver: 'memory' }
|
|
99
|
+
| { driver: 'redis'; redis: { env: true }; keyPrefix?: string }
|
|
100
|
+
| { driver: 'database'; connection?: string; table?: string };
|
|
101
|
+
|
|
102
|
+
type WorkersManifestGlobal = typeof globalThis & {
|
|
103
|
+
__zintrustWorkerManifestGlobalKeys?: ReadonlyArray<string>;
|
|
104
|
+
[key: string]: unknown;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const DEFAULT_WORKER_MANIFEST_GLOBAL_KEYS = Object.freeze([
|
|
108
|
+
'__zintrustWorkersManifest',
|
|
109
|
+
'__zintrustWorkerManifest',
|
|
110
|
+
'__zintrustAppWorkerManifest',
|
|
111
|
+
] as const);
|
|
112
|
+
|
|
113
|
+
const readWorkerManifestGlobalKeys = (): string[] => {
|
|
114
|
+
const manifestGlobal = globalThis as WorkersManifestGlobal;
|
|
115
|
+
const fromGlobal = manifestGlobal.__zintrustWorkerManifestGlobalKeys;
|
|
116
|
+
if (Array.isArray(fromGlobal) && fromGlobal.every((key) => typeof key === 'string')) {
|
|
117
|
+
return Array.from(new Set(fromGlobal.map((key) => key.trim()).filter(Boolean)));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const raw = Env.get('WORKER_MANIFEST_GLOBAL_KEYS', '').trim();
|
|
121
|
+
if (raw.length > 0) {
|
|
122
|
+
try {
|
|
123
|
+
const parsed = JSON.parse(raw) as unknown;
|
|
124
|
+
if (Array.isArray(parsed)) {
|
|
125
|
+
return Array.from(
|
|
126
|
+
new Set(parsed.map((key) => String(key).trim()).filter((key) => key.length > 0))
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
} catch {
|
|
130
|
+
// fall through
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const csv = raw
|
|
134
|
+
.split(',')
|
|
135
|
+
.map((key) => key.trim())
|
|
136
|
+
.filter(Boolean);
|
|
137
|
+
if (csv.length > 0) return Array.from(new Set(csv));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return [...DEFAULT_WORKER_MANIFEST_GLOBAL_KEYS];
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const resolveManifestWorker = (
|
|
144
|
+
workerName: string
|
|
145
|
+
): {
|
|
146
|
+
workerName: string;
|
|
147
|
+
queueName: string;
|
|
148
|
+
processorSpec: string | null;
|
|
149
|
+
concurrency: number;
|
|
150
|
+
} | null => {
|
|
151
|
+
const manifestGlobal = globalThis as WorkersManifestGlobal;
|
|
152
|
+
const keys = readWorkerManifestGlobalKeys();
|
|
153
|
+
for (const key of keys) {
|
|
154
|
+
const value = manifestGlobal[key];
|
|
155
|
+
if (!Array.isArray(value)) continue;
|
|
156
|
+
const entries = value as WorkerManifestEntry[];
|
|
157
|
+
const match = entries.find((entry) => (entry.name ?? entry.workerName) === workerName);
|
|
158
|
+
if (!match) continue;
|
|
159
|
+
const queueName =
|
|
160
|
+
typeof match.queueName === 'string' && match.queueName.trim().length > 0
|
|
161
|
+
? match.queueName.trim()
|
|
162
|
+
: `${workerName}-queue`;
|
|
163
|
+
const processorSpec =
|
|
164
|
+
typeof match.processorSpec === 'string' && match.processorSpec.trim().length > 0
|
|
165
|
+
? match.processorSpec.trim()
|
|
166
|
+
: null;
|
|
167
|
+
const concurrency = Math.max(1, Number(match.concurrency ?? 1) || 1);
|
|
168
|
+
return { workerName, queueName, processorSpec, concurrency };
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const isManifestWorkerInactive = (workerName: string): boolean => {
|
|
174
|
+
const manifestGlobal = globalThis as WorkersManifestGlobal;
|
|
175
|
+
const keys = readWorkerManifestGlobalKeys();
|
|
176
|
+
for (const key of keys) {
|
|
177
|
+
const value = manifestGlobal[key];
|
|
178
|
+
if (!Array.isArray(value)) continue;
|
|
179
|
+
const entries = value as WorkerManifestEntry[];
|
|
180
|
+
const match = entries.find((entry) => (entry.name ?? entry.workerName) === workerName);
|
|
181
|
+
if (match?.activeStatus === false) return true;
|
|
182
|
+
}
|
|
183
|
+
return false;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const assertSlaAllowsWorkerRequest = async (workerName: string): Promise<void> => {
|
|
187
|
+
const gate = await SLAMonitor.canSendWorkerRequest(workerName);
|
|
188
|
+
if (gate.allowed) return;
|
|
189
|
+
throw ErrorFactory.createConfigError(
|
|
190
|
+
`Worker "${workerName}" blocked because SLA status is not compliant`,
|
|
191
|
+
{
|
|
192
|
+
kind: 'worker_sla_blocked',
|
|
193
|
+
workerName,
|
|
194
|
+
reason: gate.reason,
|
|
195
|
+
status: gate.status?.status,
|
|
196
|
+
}
|
|
197
|
+
);
|
|
198
|
+
};
|
|
199
|
+
|
|
43
200
|
const validateCreatePayload = (body: WorkerFactoryConfig, res: IResponse): boolean => {
|
|
44
201
|
if (!body.name || !body.queueName || !body.processor || !body.version) {
|
|
45
202
|
res.setStatus(400).json({
|
|
@@ -52,6 +209,29 @@ const validateCreatePayload = (body: WorkerFactoryConfig, res: IResponse): boole
|
|
|
52
209
|
return true;
|
|
53
210
|
};
|
|
54
211
|
|
|
212
|
+
const isSlaBlockedError = (error: unknown): boolean => {
|
|
213
|
+
const details = (error as { details?: { kind?: unknown } } | undefined)?.details;
|
|
214
|
+
if (details?.kind === 'worker_sla_blocked') return true;
|
|
215
|
+
return error instanceof Error && error.message.includes('SLA status is not compliant');
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
const respondWorkerOperationError = (
|
|
219
|
+
res: IResponse,
|
|
220
|
+
error: unknown,
|
|
221
|
+
fallbackStatus = 500
|
|
222
|
+
): void => {
|
|
223
|
+
if (isSlaBlockedError(error)) {
|
|
224
|
+
res.setStatus(409).json({
|
|
225
|
+
ok: false,
|
|
226
|
+
error: (error as Error).message,
|
|
227
|
+
code: 'WORKER_SLA_BLOCKED',
|
|
228
|
+
});
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
res.setStatus(fallbackStatus).json({ error: (error as Error).message });
|
|
233
|
+
};
|
|
234
|
+
|
|
55
235
|
const respondIfWorkerExists = async (
|
|
56
236
|
name: string,
|
|
57
237
|
persistenceOverride: ReturnType<typeof resolvePersistenceOverride>,
|
|
@@ -161,7 +341,7 @@ async function create(req: IRequest, res: IResponse): Promise<void> {
|
|
|
161
341
|
if (!resolvedProcessor) return;
|
|
162
342
|
|
|
163
343
|
const config = {
|
|
164
|
-
...
|
|
344
|
+
...body,
|
|
165
345
|
processor: resolvedProcessor.processor,
|
|
166
346
|
processorSpec: resolvedProcessor.processorSpec,
|
|
167
347
|
};
|
|
@@ -169,7 +349,7 @@ async function create(req: IRequest, res: IResponse): Promise<void> {
|
|
|
169
349
|
await finalizeWorkerCreate(config, res);
|
|
170
350
|
} catch (error) {
|
|
171
351
|
Logger.error('WorkerController.create failed', error);
|
|
172
|
-
res
|
|
352
|
+
respondWorkerOperationError(res, error);
|
|
173
353
|
}
|
|
174
354
|
}
|
|
175
355
|
|
|
@@ -188,6 +368,23 @@ async function start(req: IRequest, res: IResponse): Promise<void> {
|
|
|
188
368
|
const persistenceOverride = resolvePersistenceOverride(req);
|
|
189
369
|
const isActive = await ensureActiveWorker(name, persistenceOverride, res);
|
|
190
370
|
if (!isActive) return;
|
|
371
|
+
|
|
372
|
+
if (shouldUseRedisRpcWorkerLifecycle(persistenceOverride)) {
|
|
373
|
+
await assertSlaAllowsWorkerRequest(name);
|
|
374
|
+
const manifest = resolveManifestWorker(name);
|
|
375
|
+
if (!manifest) {
|
|
376
|
+
res.setStatus(404).json({ ok: false, error: `Worker ${name} not found in manifest` });
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
const record = await callRedisRpc('worker', 'startAppWorker', manifest);
|
|
380
|
+
res.json({
|
|
381
|
+
ok: true,
|
|
382
|
+
message: `Worker ${name} started (redis-rpc registry updated)`,
|
|
383
|
+
record,
|
|
384
|
+
});
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
|
|
191
388
|
const registered = WorkerRegistry.list().includes(name);
|
|
192
389
|
|
|
193
390
|
if (!registered) {
|
|
@@ -199,7 +396,7 @@ async function start(req: IRequest, res: IResponse): Promise<void> {
|
|
|
199
396
|
res.json({ ok: true, message: `Worker ${name} started` });
|
|
200
397
|
} catch (error) {
|
|
201
398
|
Logger.error('WorkerController.start failed', error);
|
|
202
|
-
res
|
|
399
|
+
respondWorkerOperationError(res, error);
|
|
203
400
|
}
|
|
204
401
|
}
|
|
205
402
|
|
|
@@ -214,11 +411,34 @@ async function stop(req: IRequest, res: IResponse): Promise<void> {
|
|
|
214
411
|
const persistenceOverride = resolvePersistenceOverride(req);
|
|
215
412
|
const isActive = await ensureActiveWorker(name, persistenceOverride, res);
|
|
216
413
|
if (!isActive) return;
|
|
414
|
+
|
|
415
|
+
if (name && shouldUseRedisRpcWorkerLifecycle(persistenceOverride)) {
|
|
416
|
+
await assertSlaAllowsWorkerRequest(name);
|
|
417
|
+
// The registry stop operation is idempotent, but may return false if the worker
|
|
418
|
+
// has not been registered yet. In that case, register then stop to ensure the
|
|
419
|
+
// "stopped" state persists after a single click.
|
|
420
|
+
let recordOrFalse = await callRedisRpc<unknown>('worker', 'stopWorker', { workerName: name });
|
|
421
|
+
if (recordOrFalse === false) {
|
|
422
|
+
const manifest = resolveManifestWorker(name);
|
|
423
|
+
if (manifest) {
|
|
424
|
+
await callRedisRpc('worker', 'startAppWorker', manifest);
|
|
425
|
+
}
|
|
426
|
+
recordOrFalse = await callRedisRpc('worker', 'stopWorker', { workerName: name });
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
res.json({
|
|
430
|
+
ok: true,
|
|
431
|
+
message: `Worker ${name} stopped (redis-rpc registry updated)`,
|
|
432
|
+
result: recordOrFalse,
|
|
433
|
+
});
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
|
|
217
437
|
await WorkerFactory.stop(name, persistenceOverride);
|
|
218
438
|
res.json({ ok: true, message: `Worker ${name} stopped` });
|
|
219
439
|
} catch (error) {
|
|
220
440
|
Logger.error('WorkerController.stop failed', error);
|
|
221
|
-
res
|
|
441
|
+
respondWorkerOperationError(res, error);
|
|
222
442
|
}
|
|
223
443
|
}
|
|
224
444
|
|
|
@@ -233,11 +453,28 @@ async function restart(req: IRequest, res: IResponse): Promise<void> {
|
|
|
233
453
|
const persistenceOverride = resolvePersistenceOverride(req);
|
|
234
454
|
const isActive = await ensureActiveWorker(name, persistenceOverride, res);
|
|
235
455
|
if (!isActive) return;
|
|
456
|
+
|
|
457
|
+
if (name && shouldUseRedisRpcWorkerLifecycle(persistenceOverride)) {
|
|
458
|
+
await assertSlaAllowsWorkerRequest(name);
|
|
459
|
+
const manifest = resolveManifestWorker(name);
|
|
460
|
+
if (!manifest) {
|
|
461
|
+
res.setStatus(404).json({ ok: false, error: `Worker ${name} not found in manifest` });
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
const record = await callRedisRpc('worker', 'restartAppWorker', manifest);
|
|
465
|
+
res.json({
|
|
466
|
+
ok: true,
|
|
467
|
+
message: `Worker ${name} restarted (redis-rpc registry updated)`,
|
|
468
|
+
record,
|
|
469
|
+
});
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
|
|
236
473
|
await WorkerFactory.restart(name, persistenceOverride);
|
|
237
474
|
res.json({ ok: true, message: `Worker ${name} restarted` });
|
|
238
475
|
} catch (error) {
|
|
239
476
|
Logger.error('WorkerController.restart failed', error);
|
|
240
|
-
res
|
|
477
|
+
respondWorkerOperationError(res, error);
|
|
241
478
|
}
|
|
242
479
|
}
|
|
243
480
|
|
|
@@ -347,13 +584,7 @@ const normalizeQueryValue = (value: string | string[] | undefined): string | und
|
|
|
347
584
|
return undefined;
|
|
348
585
|
};
|
|
349
586
|
|
|
350
|
-
const resolvePersistenceOverride = (
|
|
351
|
-
req: IRequest
|
|
352
|
-
):
|
|
353
|
-
| { driver: 'memory' }
|
|
354
|
-
| { driver: 'redis'; redis: { env: true }; keyPrefix?: string }
|
|
355
|
-
| { driver: 'database'; connection?: string; table?: string }
|
|
356
|
-
| undefined => {
|
|
587
|
+
const resolvePersistenceOverride = (req: IRequest): PersistenceOverride | undefined => {
|
|
357
588
|
// Check for 'driver' parameter first (from frontend), then fallback to 'storage'
|
|
358
589
|
const driverRaw =
|
|
359
590
|
normalizeQueryValue(req.getQueryParam?.('driver')) ||
|
|
@@ -391,11 +622,7 @@ const resolvePersistenceOverride = (
|
|
|
391
622
|
|
|
392
623
|
const ensureActiveWorker = async (
|
|
393
624
|
name: string | undefined,
|
|
394
|
-
persistenceOverride:
|
|
395
|
-
| { driver: 'memory' }
|
|
396
|
-
| { driver: 'redis'; redis: { env: true }; keyPrefix?: string }
|
|
397
|
-
| { driver: 'database'; connection?: string; table?: string }
|
|
398
|
-
| undefined,
|
|
625
|
+
persistenceOverride: PersistenceOverride | undefined,
|
|
399
626
|
res: IResponse
|
|
400
627
|
): Promise<boolean> => {
|
|
401
628
|
if (!name) return false;
|
|
@@ -406,12 +633,21 @@ const ensureActiveWorker = async (
|
|
|
406
633
|
return false;
|
|
407
634
|
}
|
|
408
635
|
|
|
409
|
-
|
|
410
|
-
if
|
|
636
|
+
// In Cloudflare Redis-RPC mode we cannot rely on direct persistence reads. Use the app manifest
|
|
637
|
+
// to determine if the worker is intentionally inactive.
|
|
638
|
+
if (shouldUseRedisRpcWorkerLifecycle(persistenceOverride) && isManifestWorkerInactive(name)) {
|
|
411
639
|
res.setStatus(410).json({ error: 'Worker is inactive', code: 'WORKER_INACTIVE' });
|
|
412
640
|
return false;
|
|
413
641
|
}
|
|
414
642
|
|
|
643
|
+
if (!shouldUseRedisRpcWorkerLifecycle(persistenceOverride)) {
|
|
644
|
+
const persisted = await WorkerFactory.getPersisted(name, persistenceOverride);
|
|
645
|
+
if (persisted?.activeStatus === false) {
|
|
646
|
+
res.setStatus(410).json({ error: 'Worker is inactive', code: 'WORKER_INACTIVE' });
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
415
651
|
return true;
|
|
416
652
|
};
|
|
417
653
|
|
|
@@ -737,7 +973,7 @@ async function getSlaStatus(req: IRequest, res: IResponse): Promise<void> {
|
|
|
737
973
|
try {
|
|
738
974
|
const name = getParam(req, 'name');
|
|
739
975
|
const slaStatus = await SLAMonitor.checkCompliance(name);
|
|
740
|
-
res.json({ ok: true, status: slaStatus });
|
|
976
|
+
res.json({ ok: true, allowed: slaStatus.status === 'compliant', status: slaStatus });
|
|
741
977
|
} catch (error) {
|
|
742
978
|
Logger.error('WorkerController.getSlaStatus failed', error);
|
|
743
979
|
if ((error as Error).message.includes('SLA config not found')) {
|