Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 13x 13x 13x 13x 14x 13x 13x 13x 13x 13x 14x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 15x 15x 15x 1x 1x 1x 1x 1x 1x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | const { getRedisClient } = require('./redis/client');
const { getTemporalClient, countRunningWorkflows } = require('./temporal/client');
const MAX_CONCURRENT = { crawler: 3, workflow: 2 };
// Hook appelé après le démarrage effectif d'un workflow (permet d'armer le watcher)
let onStarted = null;
function setOnStarted(fn) {
onStarted = fn;
}
const WORKFLOW_MAP = {
CrawlerTW: { type: 'crawler', taskQueue: 'crawler-workflows' },
WorkflowTW: { type: 'workflow', taskQueue: 'workflow-workflows' },
};
function getWorkflowInfo(workflowType) {
return WORKFLOW_MAP[workflowType] || {};
}
async function addJob(jobData) {
const redis = getRedisClient();
const { jobId, type, organizationId, workflowType, taskQueue, input } = jobData;
const jobKey = `pool:meta:${jobId}`;
const jobStore = {
jobId,
type,
organizationId,
workflowType,
taskQueue,
createdAt: new Date().toISOString(),
};
if (input) {
jobStore.input = typeof input === 'string' ? input : JSON.stringify(input);
}
await redis.hmset(jobKey, jobStore);
await redis.expire(jobKey, 86400);
const queueKey = `pool:${organizationId}:${type}:queue`;
await redis.lrem(queueKey, 0, jobId);
const position = await redis.lpush(queueKey, jobId);
console.log(`[Pool] Added ${type} job ${jobId} for org ${organizationId}, position: ${position}`);
return { success: true, position };
}
async function tryStartNext({ organizationId, type }) {
const redis = getRedisClient();
const maxAllowed = MAX_CONCURRENT[type] || 3;
const typeName = type === 'crawler' ? 'CrawlerTW' : 'WorkflowTW';
// Toujours interroger Temporal pour le nombre réel de workflows en cours
let runningCount = 0;
try {
runningCount = await countRunningWorkflows(typeName);
} catch (err) {
console.warn(`[Pool] Could not count running workflows for ${type}: ${err.message}`);
}
if (runningCount >= maxAllowed) {
return { started: false, reason: 'max_reached', runningCount, max: maxAllowed };
}
const queueKey = `pool:${organizationId}:${type}:queue`;
const result = await redis.rpop(queueKey);
if (!result) {
return { started: false, reason: 'queue_empty' };
}
const jobId = result;
const jobKey = `pool:meta:${jobId}`;
const jobData = await redis.hgetall(jobKey);
if (!jobData || Object.keys(jobData).length === 0) {
console.warn(`[Pool] Job ${jobId} not found in Redis, skipping`);
return { started: false, reason: 'job_not_found' };
}
if (jobData.input) {
try {
jobData.input = JSON.parse(jobData.input);
} catch (e) {
jobData.input = { raw: jobData.input };
}
}
const { workflowType, taskQueue, input } = jobData;
console.log(`[Pool] Starting ${type} job ${jobId} (running: ${runningCount}/${maxAllowed})`);
try {
const client = await getTemporalClient();
await client.workflow.start(workflowType, {
args: [input],
taskQueue: taskQueue,
workflowId: jobId,
workflowIdConflictPolicy: 'USE_EXISTING',
retry: {
maximumAttempts: 3,
nonRetryableErrorTypes: ['BudgetExceededError'],
},
});
console.log(`[Pool] Started ${workflowType}: ${jobId}`);
await redis.del(jobKey);
if (typeof onStarted === 'function') {
try {
await onStarted({ jobId, organizationId, type, workflowType, taskQueue, input });
} catch (e) {
console.warn(`[Pool] onStarted hook error: ${e.message}`);
}
}
return { started: true, workflowId: jobId, runningCount: runningCount + 1 };
} catch (err) {
if (
err.name === 'WorkflowExecutionAlreadyStartedError' ||
err.constructor?.name === 'WorkflowExecutionAlreadyStartedError'
) {
console.log(`[Pool] Job ${jobId} already started (idempotent)`);
return { started: true, workflowId: jobId, runningCount };
}
console.error(`[Pool] Failed to start ${workflowType} ${jobId}: ${err.message}`);
return { started: false, reason: 'launch_failed', error: err.message };
}
}
function getMaxAllowed() {
return { ...MAX_CONCURRENT };
}
async function getAllQueueKeys() {
const redis = getRedisClient();
const keys = await redis.keys('pool:*:crawler:queue');
const workflowKeys = await redis.keys('pool:*:workflow:queue');
return [...keys, ...workflowKeys];
}
async function drainQueues() {
const redis = getRedisClient();
console.log('[Pool] Initializing queues...');
const keys = await getAllQueueKeys();
console.log(`[Pool] Found ${keys.length} queue keys`);
for (const key of keys) {
const match = key.match(/^pool:([^:]+):(crawler|workflow):queue$/);
if (!match) continue;
const organizationId = match[1];
const type = match[2];
while (true) {
const result = await tryStartNext({ organizationId, type });
if (result.started) {
console.log(`[Pool] Started queued ${type} job at startup`);
} else {
if (result.reason !== 'queue_empty') {
console.log(`[Pool] Queue processing stopped for ${type}: ${result.reason}`);
}
break;
}
}
}
// Afficher l'état actuel via Temporal
try {
const crawlers = await countRunningWorkflows('CrawlerTW');
const workflows = await countRunningWorkflows('WorkflowTW');
console.log(`[Pool] Queue initialization complete: ${crawlers} crawlers, ${workflows} workflows running`);
} catch (err) {
console.error('[Pool] Error counting running workflows:', err.message);
}
}
/**
* Réconciliation : parcourt les files non vides et tente de démarrer le job suivant
* (si un slot est libre selon Temporal). Utilisée :
* - au démarrage (drainQueues)
* - à la clôture d'un workflow (déclenchement immédiat)
* - périodiquement (filet de sécurité, intervalle par défaut 30 s)
*/
async function reconcilePools() {
const redis = getRedisClient();
const keys = await redis.keys('pool:*:queue');
for (const key of keys) {
const match = key.match(/^pool:([^:]+):(crawler|workflow):queue$/);
if (!match) continue;
const size = await redis.llen(key);
if (size === 0) continue;
await tryStartNext({ organizationId: match[1], type: match[2] });
}
}
function startSyncInterval(intervalMs = 30000) {
setInterval(async () => {
try {
await reconcilePools();
} catch (err) {
console.error('[Pool] Sync interval error:', err.message);
}
}, intervalMs);
console.log(`[Pool] Sync interval started every ${intervalMs}ms`);
}
module.exports = {
addJob,
tryStartNext,
getMaxAllowed,
getWorkflowInfo,
drainQueues,
reconcilePools,
startSyncInterval,
setOnStarted,
};
|