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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 | 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 1x 87x 87x 87x 87x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 33x 33x 1x 1x 1x 1x 1x 33x 33x 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 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 54x 54x 54x 54x 54x 132x 132x 54x 54x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 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 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 13x 13x 14x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 14x 13x 13x 13x 13x 13x 13x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 75x 75x 75x 75x 75x 75x 75x 75x 1x 1x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 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 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 | /**
* Job Manager - Single Process Architecture
* API + Temporal Worker + Activities in one Node.js process
*
* Allows activities to write directly to SSE connections
*/
const express = require("express");
const cors = require("cors");
const { Client, Connection } = require("@temporalio/client");
const { MongoClient } = require("mongodb");
const { S3Client, ListObjectsV2Command, DeleteObjectsCommand } = require("@aws-sdk/client-s3");
const config = require("./config");
const pool = require("./pool");
const watcher = require("./watcher");
const persistence = require("./persistence");
const { getRedisClient } = require("./redis/client");
const { requireInternalKey } = require("../shared/internalAuth");
const {
terminateObsoleteWorkflows,
} = require("../shared/temporalWorkflowCleanup");
function getS3Client() {
return new S3Client({
endpoint: process.env.MINIO_URL || "http://minio:9000",
region: "us-east-1",
credentials: {
accessKeyId: process.env.MINIO_ACCESS_KEY || "minioadmin",
secretAccessKey: process.env.MINIO_SECRET_KEY || "minioadmin",
},
forcePathStyle: true,
});
}
const MINIO_BUCKET = process.env.MINIO_BUCKET || "workflow";
const app = express();
const PORT = config.port || 8001;
// MongoDB connection for reading job outputs
let mongoClient = null;
let jobOutputsCollection = null;
async function getMongoCollection() {
if (
mongoClient &&
mongoClient.topology &&
mongoClient.topology.isConnected()
) {
return jobOutputsCollection;
}
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
mongoClient = new MongoClient(mongodbUri, { maxPoolSize: 5 });
await mongoClient.connect();
const db = mongoClient.db("nooloom");
jobOutputsCollection = db.collection("job_outputs");
console.log("[JobManager] Connected to MongoDB for job outputs");
return jobOutputsCollection;
}
// Helper to get crawler job error from MongoDB
async function getCrawlerJobError(jobId) {
try {
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
const client = new MongoClient(mongodbUri, { maxPoolSize: 5 });
await client.connect();
const db = client.db("nooloom");
const job = await db.collection("jobs").findOne({ jobId });
await client.close();
return job?.error || null;
} catch (error) {
console.error(
"[JobManager] Error fetching crawler job error:",
error.message,
);
return null;
}
}
// Middleware
app.use(cors());
app.use(express.json({ limit: '100mb' }));
// ============================================================================
// SSE Connection Storage (shared between API and Activities)
// ============================================================================
const sseConnections = new Map();
const lastSSESignature = new Map(); // jobId -> signature (déduplication des événements)
function addSSEConnection(jobId, res) {
sseConnections.set(jobId, res);
}
function removeSSEConnection(jobId) {
sseConnections.delete(jobId);
lastSSESignature.delete(jobId);
}
function writeToSSE(jobId, data) {
const res = sseConnections.get(jobId);
if (!res || res.closed) return false;
const signature = `${data.status}|${data.progress}|${data.step}`;
if (lastSSESignature.get(jobId) === signature) return true; // déduplication (watcher + activité)
lastSSESignature.set(jobId, signature);
res.write(`data: ${JSON.stringify(data)}\n\n`);
return true;
}
const TERMINAL_STATUSES = ["COMPLETED", "FAILED", "CANCELED", "TERMINATED", "TIMED_OUT"];
/**
* Émet la fin d'un job (statut terminal en SSE) puis ferme la connexion.
* Best-effort : fonctionne même si le workflow n'a rien notifié.
*/
async function finalizeJob(jobId) {
let statusName = null;
try {
const client = await getTemporalClient();
const desc = await client.workflow.getHandle(jobId).describe();
statusName = desc.status?.name || null;
} catch (e) {
// ignore
}
const ok = statusName === "COMPLETED";
writeToSSE(jobId, {
type: ok ? "completed" : "error",
jobId,
status: ok ? "completed" : "failed",
progress: ok ? 100 : 0,
step: ok ? "complete" : "failed",
timestamp: new Date().toISOString(),
});
const conn = sseConnections.get(jobId);
if (conn && !conn.closed) {
try {
conn.end();
} catch (e) {
// ignore
}
}
removeSSEConnection(jobId);
}
// ============================================================================
// Temporal Client (for API polling)
// ============================================================================
let temporalClient = null;
async function getTemporalClient() {
if (!temporalClient) {
const connection = await Connection.connect({
address: config.temporalAddress,
});
temporalClient = new Client({ connection });
}
return temporalClient;
}
// ============================================================================
// // Job Manager API Routes (Multi-tenant)
// ============================================================================
// Helper to get job IDs for an organization from MongoDB (sorted by date desc)
async function getJobIdsByOrganization(organizationId, limit = 100) {
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
const client = new MongoClient(mongodbUri, { maxPoolSize: 5 });
await client.connect();
const db = client.db("nooloom");
const jobMap = new Map();
// Collection unique `jobs` (crawler + workflow)
const jobDocs = await db
.collection("jobs")
.find(
{ organizationId: organizationId },
{ projection: { jobId: 1, createdAt: 1, updatedAt: 1 } },
)
.sort({ updatedAt: -1 })
.limit(parseInt(limit))
.toArray();
jobDocs.forEach((j) => {
if (!jobMap.has(j.jobId)) {
jobMap.set(j.jobId, { jobId: j.jobId, createdAt: j.createdAt || j.updatedAt });
}
});
await client.close();
// Sort by date desc and return jobIds
const sortedJobs = Array.from(jobMap.values()).sort((a, b) => {
const dateA = a.createdAt ? new Date(a.createdAt) : new Date(0);
const dateB = b.createdAt ? new Date(b.createdAt) : new Date(0);
return dateB - dateA;
});
return sortedJobs.slice(0, parseInt(limit)).map((j) => j.jobId);
}
/**
* GET /:organizationId/jobs
* Liste tous les jobs (crawler + workflow) pour une organisation depuis Temporal
*/
app.get("/:organizationId/jobs", async (req, res) => {
const { organizationId } = req.params;
const { limit = 100, status = "all", scheduleId } = req.query;
console.log(`[JobManager] GET /${organizationId}/jobs (status=${status})`);
try {
// Get job IDs for this organization from MongoDB
const orgJobIds = await getJobIdsByOrganization(organizationId, limit);
console.log(
`[JobManager] Found ${orgJobIds.length} jobs for organization ${organizationId}`,
);
// If no jobs found, return empty
if (orgJobIds.length === 0) {
return res.json({
success: true,
data: {
jobs: [],
pagination: {
total: 0,
limit: parseInt(limit),
status,
source: "temporal",
},
},
});
}
const jobs = [];
// Connect to MongoDB for all job data
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
const mongoClient = new MongoClient(mongodbUri, { maxPoolSize: 5 });
await mongoClient.connect();
const db = mongoClient.db("nooloom");
// Collection unique `jobs` (source de vérité du statut)
for (const jobId of orgJobIds) {
const query = { jobId };
if (scheduleId) query.scheduleId = scheduleId;
const jobDoc = await db.collection("jobs").findOne(query);
if (!jobDoc) continue;
const jobStatus = jobDoc.status || "unknown";
if (status !== "all" && status !== jobStatus) continue;
const isCrawler =
jobDoc.type === "crawler" || jobDoc.metadata?.type === "crawler";
jobs.push({
workflowId: jobId,
type: isCrawler ? "crawler" : jobDoc.type || jobDoc.metadata?.type || "workflow",
status: jobStatus,
startTime: jobDoc.createdAt
? typeof jobDoc.createdAt === "string"
? jobDoc.createdAt
: jobDoc.createdAt?.toISOString()
: null,
closeTime: jobDoc.closeTime
? typeof jobDoc.closeTime === "string"
? jobDoc.closeTime
: new Date(jobDoc.closeTime).toISOString()
: null,
phases: jobDoc.phases || [],
runId: null,
taskQueue: isCrawler ? "crawler-workflows" : "workflow-workflows",
metadata: jobDoc.metadata,
});
}
await mongoClient.close();
res.json({
success: true,
data: {
jobs,
pagination: {
total: jobs.length,
limit: parseInt(limit),
status,
source: "mongodb",
},
},
});
} catch (error) {
console.error("[JobManager] Error listing jobs:", error.message);
res.status(500).json({
success: false,
message: "Error listing jobs",
error: error.message,
});
}
});
/**
* GET /:organizationId/jobs/crawler
* Liste tous les jobs crawler pour une organisation depuis Temporal
*/
app.get("/:organizationId/jobs/crawler", async (req, res) => {
const { organizationId } = req.params;
const { limit = 50, status = "running" } = req.query;
console.log(
`[JobManager] GET /${organizationId}/jobs/crawler (status=${status})`,
);
try {
// Get crawler config IDs for this organization
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
const mongoClient = new MongoClient(mongodbUri, { maxPoolSize: 5 });
await mongoClient.connect();
const db = mongoClient.db("nooloom");
const crawlerConfigs = db.collection("crawlerconfigs");
const configs = await crawlerConfigs
.find(
{ organizationId: organizationId },
{ projection: { _id: 1 }, limit: 100 },
)
.toArray();
const configIds = configs.map((c) => c._id.toString());
// Jobs crawler de l'org — collection unique `jobs` (source de vérité)
const query = { crawlerConfigId: { $in: configIds }, type: "crawler" };
if (status !== "all") query.status = status;
const docs = await db
.collection("jobs")
.find(query)
.sort({ updatedAt: -1 })
.limit(parseInt(limit))
.toArray();
await mongoClient.close();
const crawlerJobs = docs.map((d) => ({
workflowId: d.jobId,
type: "crawler",
status: d.status || "unknown",
startTime: d.createdAt ? new Date(d.createdAt).toISOString() : null,
closeTime: d.closeTime ? new Date(d.closeTime).toISOString() : null,
progress: (d.crawler && d.crawler.progress) || {},
error: d.error || null,
metadata: d.metadata,
}));
res.json({
success: true,
data: {
jobs: crawlerJobs,
pagination: {
total: crawlerJobs.length,
limit: parseInt(limit),
status,
source: "mongodb",
},
},
});
} catch (error) {
console.error("[JobManager] Error listing crawler jobs:", error.message);
res.status(500).json({
success: false,
message: "Error listing crawler jobs",
error: error.message,
});
}
});
/**
* POST /jobs/cleanup
* Clean up old workflows (terminate running, delete closed)
* Body params:
* - taskQueue: filter by task queue ('crawler', 'workflow', or '' for all)
* - olderThanHours: only clean workflows older than X hours (default: 24)
* - deleteClosed: also delete closed workflows (completed/failed/cancelled), default true
*/
app.post("/jobs/cleanup", async (req, res) => {
const { taskQueue, olderThanHours = 24, deleteClosed = true } = req.body;
console.log(
`[JobManager] Cleanup request: taskQueue=${taskQueue || "all"}, olderThanHours=${olderThanHours}, deleteClosed=${deleteClosed}`,
);
try {
const connection = await Connection.connect({
address: config.temporalAddress,
});
const client = new Client({ connection });
let queryParts = [];
if (taskQueue === "crawler") {
queryParts.push(`TaskQueue = "crawler-workflows"`);
} else if (taskQueue === "workflow") {
queryParts.push(`TaskQueue = "workflow-workflows"`);
}
const cutoffTime = new Date();
cutoffTime.setHours(cutoffTime.getHours() - parseInt(olderThanHours));
const closedQuery = [
...queryParts,
`CloseTime < "${cutoffTime.toISOString()}"`,
].join(" AND ");
const runningQuery = [
...queryParts,
`ExecutionStatus = "Running"`,
`StartTime < "${cutoffTime.toISOString()}"`,
].join(" AND ");
let terminatedCount = 0;
let deletedCount = 0;
let errorCount = 0;
let closedFound = 0;
let runningFound = 0;
if (deleteClosed) {
console.log(
`[JobManager] Deleting closed workflows with query: ${closedQuery}`,
);
const closedIterator = client.workflow.list({
query: closedQuery,
limit: 100,
});
for await (const wf of closedIterator) {
closedFound++;
try {
await connection.workflowService.deleteWorkflowExecution({
namespace: "default",
workflowExecution: {
workflowId: wf.workflowId,
runId: wf.runId || undefined,
},
});
deletedCount++;
console.log(`[JobManager] Deleted workflow: ${wf.workflowId}`);
} catch (e) {
if (e.name === 'NotFoundError') {
console.log(`[JobManager] Workflow already gone: ${wf.workflowId}`);
} else {
errorCount++;
console.error(
`[JobManager] Failed to delete ${wf.workflowId}: ${e.message}`,
);
}
}
}
}
console.log(
`[JobManager] Terminating running workflows with query: ${runningQuery}`,
);
const runningIterator = client.workflow.list({
query: runningQuery,
limit: 100,
});
const terminatedIds = [];
for await (const wf of runningIterator) {
runningFound++;
try {
await connection.workflowService.terminateWorkflowExecution({
namespace: "default",
workflowExecution: {
workflowId: wf.workflowId,
runId: wf.runId || undefined,
},
reason: "Cleanup - running too long",
});
terminatedCount++;
terminatedIds.push(wf.workflowId);
console.log(`[JobManager] Terminated workflow: ${wf.workflowId}`);
} catch (e) {
errorCount++;
console.error(
`[JobManager] Failed to terminate ${wf.workflowId}: ${e.message}`,
);
}
}
if (deleteClosed && terminatedIds.length > 0) {
console.log(
`[JobManager] Deleting just-terminated workflows: ${terminatedIds.join(", ")}`,
);
for (const wfId of terminatedIds) {
try {
await connection.workflowService.deleteWorkflowExecution({
namespace: "default",
workflowExecution: { workflowId: wfId },
});
deletedCount++;
console.log(`[JobManager] Deleted terminated workflow: ${wfId}`);
} catch (e) {
console.error(`[JobManager] Failed to delete ${wfId}: ${e.message}`);
}
}
}
res.json({
success: true,
data: {
terminated: terminatedCount,
deleted: deletedCount,
errors: errorCount,
closedFound,
runningFound,
cutoffTime: cutoffTime.toISOString(),
},
});
} catch (error) {
console.error("[JobManager] Cleanup error:", error.message);
res.status(500).json({
success: false,
message: "Error cleaning up workflows",
error: error.message,
});
}
});
/**
* GET /jobs/workflow
* Liste tous les workflows du workflow-service-worker (taskQueue: "workflow-workflows")
*/
app.get("/jobs/workflow", async (req, res) => {
const { limit = 50, status = "running" } = req.query;
console.log(`[JobManager] GET /jobs/workflow (status=${status})`);
try {
const client = await getTemporalClient();
let query;
if (status === "completed") {
query =
'ExecutionStatus = "Completed" AND TaskQueue = "workflow-workflows"';
} else if (status === "failed") {
query = 'ExecutionStatus = "Failed" AND TaskQueue = "workflow-workflows"';
} else if (status === "cancelled") {
query =
'ExecutionStatus = "Canceled" AND TaskQueue = "workflow-workflows"';
} else if (status === "all") {
query = 'TaskQueue = "workflow-workflows"';
} else {
query =
'ExecutionStatus = "Running" AND TaskQueue = "workflow-workflows"';
}
const workflows = [];
const iterator = client.workflow.list({
query: query,
limit: parseInt(limit),
});
for await (const wf of iterator) {
const workflowInfo = {
workflowId: wf.workflowId,
type: wf.type?.name || "unknown",
status: wf.status?.name || "unknown",
startTime: wf.startTime?.toISOString(),
closeTime: wf.closeTime?.toISOString(),
runId: wf.runId,
taskQueue: wf.taskQueue,
};
if (wf.status?.name === "Running" || status === "all") {
try {
const handle = client.workflow.getHandle(wf.workflowId);
const queryResult = await handle.query("getStatus");
workflowInfo.progress = queryResult?.progress || {};
} catch (e) {
// Query not available
}
}
workflows.push(workflowInfo);
}
res.json({
success: true,
data: {
workflows,
pagination: {
total: workflows.length,
limit: parseInt(limit),
status,
source: "temporal",
},
},
});
} catch (error) {
console.error("[JobManager] Error listing workflows:", error.message);
res.status(500).json({
success: false,
message: "Error listing workflows",
error: error.message,
});
}
});
/**
* GET /jobs/:jobId/status
* SSE stream for job status
*/
app.get("/jobs/:jobId/status", async (req, res) => {
const { jobId } = req.params;
console.log(`[JobManager] Status request for jobId: ${jobId}`);
if (!jobId.includes("-")) {
return res.status(400).json({
success: false,
message: "Invalid jobId format. Expected: service-jobId",
});
}
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
});
addSSEConnection(jobId, res);
console.log(`[JobManager] SSE connection opened for jobId: ${jobId}`);
req.on("close", () => {
removeSSEConnection(jobId);
console.log(`[JobManager] SSE connection closed for jobId: ${jobId}`);
});
// Replay de l'état courant (connexion tardive / reconnexion) + armement du watcher
(async () => {
try {
const client = await getTemporalClient();
const handle = client.workflow.getHandle(jobId);
const desc = await handle.describe();
if (TERMINAL_STATUSES.includes(desc.status?.name)) {
await finalizeJob(jobId);
return;
}
const status = await handle.query("getStatus");
writeToSSE(jobId, {
type: "notification",
jobId,
status: status?.status || "running",
progress: status?.progress?.percent ?? 0,
step: status?.progress?.step || "unknown",
timestamp: new Date().toISOString(),
});
watcher.arm({ jobId });
} catch (e) {
// workflow pas encore visible : les pushs (activité) ou le watcher prendront le relais
}
})();
});
/**
* Format workflow result to flat outputs array format
*/
function formatResultAsOutputs(workflowResult) {
if (!workflowResult) return { outputs: [] };
const minioUrl = config.minioPublicUrl;
const defaultBucket = "workflow";
// If workflow provides its own outputs array, use it
if (workflowResult.outputs && Array.isArray(workflowResult.outputs)) {
const outputs = workflowResult.outputs.map((output) => {
// If URL is already complete, use it as-is
if (
output.url &&
(output.url.startsWith("http://") || output.url.startsWith("https://"))
) {
return output;
}
// Otherwise build full URL from bucket and outputPath
if (output.outputPath) {
const bucket = output.bucket || defaultBucket;
return {
...output,
url: `${minioUrl}/${bucket}/${output.outputPath}`,
};
}
return output;
});
return {
jobId: workflowResult.jobId,
sourceType: workflowResult.sourceType,
title: workflowResult.title,
url: workflowResult.url,
provider: workflowResult.provider,
outputs,
};
}
// Handle crawler results with MinIO output
if (workflowResult.output && workflowResult.output.outputPath) {
const outputs = [
{
type: "crawl-results",
format: "json",
outputPath: workflowResult.output.outputPath,
bucket: workflowResult.output.bucket || defaultBucket,
url:
workflowResult.output.url ||
`${minioUrl}/${workflowResult.output.bucket || defaultBucket}/${workflowResult.output.outputPath}`,
},
];
return {
jobId: workflowResult.jobId,
sourceType: "crawl",
outputs,
stats: workflowResult.stats,
};
}
// Legacy: construct outputs from individual fields
const outputs = [];
// Markdown output
if (workflowResult.outputPath) {
outputs.push({
format: "markdown",
type: "markdown",
url: `${minioUrl}/${defaultBucket}/${workflowResult.outputPath}`,
metadata: {
title: workflowResult.title,
url: workflowResult.url,
provider: workflowResult.provider,
},
});
}
// Screenshot output
if (workflowResult.screenshotPath) {
outputs.push({
format: "screenshot",
type: "screenshots",
urls: [`${minioUrl}/${defaultBucket}/${workflowResult.screenshotPath}`],
metadata: { page: 1 },
});
}
// Return flat structure - all properties at root level
return {
jobId: workflowResult.jobId,
sourceType: workflowResult.sourceType,
title: workflowResult.title,
url: workflowResult.url,
provider: workflowResult.provider,
outputs,
};
}
/**
* GET /jobs/:jobId/results
* MongoDB is the source of truth for outputs
*/
const SENSITIVE_FIELDS = ['llmApiKey', 'authToken', 'markerApiKey'];
function sanitizeInput(input) {
if (!input || typeof input !== 'object') return input;
const sanitized = Array.isArray(input) ? [...input] : { ...input };
for (const key of SENSITIVE_FIELDS) delete sanitized[key];
for (const val of Object.values(sanitized)) {
if (val && typeof val === 'object') sanitizeInput(val);
}
return sanitized;
}
app.get("/jobs/:jobId/results", async (req, res) => {
const { jobId } = req.params;
console.log(`[JobManager] /results REQUEST for jobId="${jobId}"`);
// Determine if this is a crawler job by checking Temporal
let isCrawlerJob = false;
try {
const client = await getTemporalClient();
const handle = await client.workflow.getHandle(jobId);
const desc = await handle.describe();
isCrawlerJob = desc.taskQueue === "crawler-workflows";
} catch (e) {
// Ignore - will fallback to regular workflow handling
}
// Get outputs from MongoDB
let outputs = [];
let metadata = null;
let mongoStatus = null;
let mongoError = null;
let workflowInput = null;
let crawlResults = null;
let crawlProgress = {};
try {
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
const mongoClient = new (require("mongodb").MongoClient)(mongodbUri, {
maxPoolSize: 5,
});
await mongoClient.connect();
const db = mongoClient.db("nooloom");
if (isCrawlerJob) {
// Crawler jobs : collection unique `jobs` (sous-doc `crawler`)
const jobDoc = await db.collection("jobs").findOne({ jobId });
if (jobDoc) {
const crawlStats = jobDoc.crawler?.stats || {};
crawlProgress = jobDoc.crawler?.progress || {};
const stopReason =
jobDoc.crawler?.stopReason || crawlProgress.stopReason || null;
const routedTo = jobDoc.crawler?.routedTo || [];
mongoStatus = jobDoc.status || "completed";
mongoError = jobDoc.error || null;
crawlResults = crawlStats;
workflowInput = jobDoc.inputs || null;
metadata = {
pagesCrawled: crawlProgress.pagesCrawled || 0,
pagesRelevant: crawlProgress.pagesRelevant || 0,
pagesFailed: crawlProgress.pagesFailed || 0,
stopReason,
routedTo,
};
stats = {
pagesCrawled: crawlProgress.pagesCrawled || 0,
pagesRelevant: crawlProgress.pagesRelevant || 0,
pagesFailed: crawlProgress.pagesFailed || 0,
stopReason,
linksQueued: crawlStats.linksQueued || 0,
synthesisTriggered: crawlStats.synthesisTriggered || 0,
routerUsed: crawlStats.destinationsUsed || false,
routedTo,
startedAt: crawlStats.startedAt || jobDoc.createdAt || null,
factsExtracted: [],
assertionsExtracted: [],
};
// Try to load assertions count from MinIO assertions.json (legacy: facts.json)
try {
const minioAssertionsUrl = `${config.minioUrl}/workflow/${jobId}/assertions.json`;
const minioFactsUrl = `${config.minioUrl}/workflow/${jobId}/facts.json`;
const assertionsResp = await fetch(minioAssertionsUrl);
const resp = assertionsResp.ok ? assertionsResp : await fetch(minioFactsUrl);
if (resp.ok) {
const factsData = await resp.json();
if (Array.isArray(factsData.assertions)) {
stats.assertionsExtracted = factsData.assertions;
stats.factsExtracted = factsData.assertions;
} else if (Array.isArray(factsData.facts)) {
stats.assertionsExtracted = factsData.facts;
stats.factsExtracted = factsData.facts;
}
}
} catch (e) {
// Assertions file may not exist yet - this is normal
}
console.log(
`[JobManager] jobs (crawler) found for ${jobId}, status: ${mongoStatus}`,
);
} else {
console.log(`[JobManager] No jobs doc for ${jobId}`);
}
} else {
// Workflow jobs store outputs in jobs collection
const collection = db.collection("jobs");
const mongoDoc = await collection.findOne({ jobId });
if (mongoDoc) {
outputs = mongoDoc.outputs || [];
metadata = mongoDoc.metadata || null;
mongoStatus = mongoDoc.status || "completed";
mongoError = mongoDoc.error || null;
workflowInput = mongoDoc.input || null;
console.log(
`[JobManager] MongoDB found ${outputs.length} outputs for ${jobId}, error: ${mongoError || "none"}`,
);
} else {
console.log(`[JobManager] MongoDB no doc for ${jobId}`);
}
}
await mongoClient.close();
} catch (e) {
console.error("[JobManager] MongoDB error:", e.message);
}
// Try to get workflow input from Temporal history (even if we have outputs from MongoDB)
if (!workflowInput && !isCrawlerJob) {
try {
const connection = await Connection.connect({
address: config.temporalAddress,
});
const historyResponse =
await connection.workflowService.getWorkflowExecutionHistory({
namespace: "default",
execution: { workflowId: jobId },
});
for (const event of historyResponse.history?.events || []) {
if (event.eventType === 1) {
// WORKFLOW_EXECUTION_STARTED
const attrs = event.workflowExecutionStartedEventAttributes || {};
if (attrs.input) {
// Input is in protobuf payload format - decode it
const payloads = attrs.input?.payloads || [];
if (payloads.length > 0) {
const firstPayload = payloads[0];
let data = firstPayload.data;
// data can be Buffer (Node.js), Uint8Array, or Array of bytes
if (Buffer.isBuffer(data)) {
data = data.toString("utf8");
} else if (Array.isArray(data)) {
// Array of numbers (byte values) from protobuf
data = Buffer.from(data).toString("utf8");
}
// Now data should be a JSON string - parse it
try {
workflowInput = JSON.parse(data);
} catch (e) {
// If parsing fails, return as string
workflowInput = data;
}
}
break;
}
}
}
} catch (e) {
console.log(
`[JobManager] Could not get input from history: ${e.message}`,
);
}
}
// Add full public URLs to outputs
const minioUrl = config.minioPublicUrl || "http://localhost:9090";
const outputsWithUrls = outputs.map((output) => ({
...output,
url: `${minioUrl}/${output.bucket || "workflow"}/${output.outputPath}`,
}));
// If we have outputs from MongoDB, return them regardless of Temporal
if (outputs.length > 0 || mongoStatus) {
console.log(
`[JobManager] Returning ${outputsWithUrls.length} outputs (mongoStatus: ${mongoStatus})`,
);
// For crawler jobs, format crawl results as outputs
if (isCrawlerJob) {
const crawlOutputs = [];
// Crawler stores assertions at workflow/{jobId}/assertions.json
crawlOutputs.push({
type: "crawl-results",
format: "json",
bucket: "workflow",
outputPath: `${jobId}/assertions.json`,
url: `${minioUrl}/workflow/${jobId}/assertions.json`,
});
return res.json({
jobId,
status: mongoStatus,
error: mongoError,
outputs: crawlOutputs,
metadata,
stats,
progress: crawlProgress,
input: sanitizeInput(workflowInput),
});
}
return res.json({
jobId,
status: mongoStatus,
error: mongoError,
outputs: outputsWithUrls,
metadata,
input: sanitizeInput(workflowInput),
});
}
// No outputs in MongoDB - try Temporal as fallback
let workflowStatus = "unknown";
let workflowError = null;
try {
const client = await getTemporalClient();
const handle = await client.workflow.getHandle(jobId);
const desc = await handle.describe();
workflowStatus = desc.status.name.toLowerCase();
console.log(
`[JobManager] desc.status.name = "${desc.status?.name}", workflowStatus = "${workflowStatus}"`,
);
if (desc.status?.name === "FAILED") {
try {
const connection = await Connection.connect({
address: config.temporalAddress,
});
const response =
await connection.workflowService.getWorkflowExecutionHistory({
namespace: "default",
execution: { workflowId: jobId },
});
// First, find the activity task failed event and extract error
let activityName = "Unknown";
for (const event of response.history?.events || []) {
if (event.eventType === 13) {
// EVENT_TYPE_ACTIVITY_TASK_FAILED
const eventStr = JSON.stringify(event);
// The activityTaskFailedEventAttributes contains the failure
const attrsKey = "activityTaskFailedEventAttributes";
const attrs = event[attrsKey] || {};
// Try to get activityType.name from the event
// In protobuf, this might be nested differently
let activityTypeName = null;
if (attrs.activityType?.name) {
activityTypeName = attrs.activityType.name;
} else if (attrs.activity_type?.name) {
activityTypeName = attrs.activity_type.name;
}
// If still not found, try to extract from stack trace
if (!activityTypeName && attrs.failure?.stackTrace) {
const stackMatch =
attrs.failure.stackTrace.match(/at\s+(\w+)\s+\(/);
if (stackMatch) {
activityTypeName = stackMatch[1];
}
}
if (activityTypeName) {
activityName = activityTypeName;
}
// Get the failure message
const failure = attrs.failure || {};
let errorMsg =
failure.message || failure.cause?.message || "Activity failed";
// Remove "Call log:" and everything after it (for compatibility with old errors)
errorMsg = errorMsg;
workflowError = `Activity "${activityName}" failed: ${errorMsg}`;
break;
}
if (event.eventType === 3) {
// EVENT_TYPE_WORKFLOW_EXECUTION_FAILED
const attrs = event.attributes || {};
const failure = attrs.failure || {};
workflowError =
failure.message || failure.cause?.message || "Workflow failed";
break;
}
}
} catch (e) {
console.log(`[JobManager] Could not get history: ${e.message}`);
}
}
} catch (e) {
console.log(`[JobManager] Temporal error: ${e.message}`);
}
if (workflowStatus === "unknown") {
return res.status(404).json({
jobId,
status: "not_found",
error: "Job not found",
});
}
if (workflowStatus === "failed" || workflowStatus === "cancelled") {
// Try to get error from crawler jobs MongoDB first
const crawlerError = await getCrawlerJobError(jobId);
return res.json({
jobId,
status: workflowStatus,
error: crawlerError || workflowError || null,
outputs: [],
input: sanitizeInput(workflowInput),
});
}
// Running or pending but no outputs yet
return res.json({
jobId,
status: workflowStatus,
outputs: [],
input: sanitizeInput(workflowInput),
});
});
/**
* Health check
*/
app.get("/health", (req, res) => {
res.json({
success: true,
status: "healthy",
service: "job-manager-service",
timestamp: new Date().toISOString(),
});
});
// ============================================================================
// Organization-scoped routes
// ============================================================================
/**
* POST /:organizationId/jobs/cleanup
* Clean up jobs for a specific organization (Redis queues + MongoDB)
* Body params:
* - taskQueue: filter by task queue ('crawler', 'workflow', or '' for all)
* - olderThanHours: only clean jobs older than X hours (default: 0 = all)
*/
app.post("/:organizationId/jobs/cleanup", async (req, res) => {
const { organizationId } = req.params;
let { taskQueue, olderThanHours = 0 } = req.body;
console.log(
`[JobManager] Cleanup request for org ${organizationId}: taskQueue=${taskQueue || "all"}, olderThanHours=${olderThanHours}`,
);
try {
const redis = getRedisClient();
let deletedRedisCrawler = 0;
let deletedRedisWorkflow = 0;
if (taskQueue === "crawler" || taskQueue === "") {
const crawlerQueueKey = `pool:${organizationId}:crawler:queue`;
const crawlerQueueLen = await redis.llen(crawlerQueueKey);
if (crawlerQueueLen > 0) {
await redis.del(crawlerQueueKey);
deletedRedisCrawler = crawlerQueueLen;
console.log(`[JobManager] Deleted ${deletedRedisCrawler} jobs from Redis crawler queue`);
}
}
if (taskQueue === "workflow" || taskQueue === "") {
const workflowQueueKey = `pool:${organizationId}:workflow:queue`;
const workflowQueueLen = await redis.llen(workflowQueueKey);
if (workflowQueueLen > 0) {
await redis.del(workflowQueueKey);
deletedRedisWorkflow = workflowQueueLen;
console.log(`[JobManager] Deleted ${deletedRedisWorkflow} jobs from Redis workflow queue`);
}
}
const mongodbUri =
process.env.MONGODB_URI || "mongodb://mongodb:27017/nooloom";
const mongoClient = new MongoClient(mongodbUri, { maxPoolSize: 5 });
await mongoClient.connect();
const db = mongoClient.db("nooloom");
let deletedMongoCrawljobs = 0;
let deletedMongoJobs = 0;
const mongoQuery = { organizationId };
if (olderThanHours > 0) {
const cutoffTime = new Date();
cutoffTime.setHours(cutoffTime.getHours() - parseInt(olderThanHours));
mongoQuery.updatedAt = { $lt: cutoffTime.toISOString() };
}
if (taskQueue === "crawler") mongoQuery.type = "crawler";
else if (taskQueue === "workflow") mongoQuery.type = "workflow";
// Collect jobIds and their cacheKeys BEFORE deletion
let jobIdsToSignal = [];
let cacheKeysToDelete = [];
// Collection unique `jobs` (crawler + workflow)
const jobsToDelete = await db
.collection("jobs")
.find(mongoQuery, { projection: { jobId: 1, type: 1, "metadata.cacheKeys": 1 } })
.toArray();
for (const job of jobsToDelete) {
jobIdsToSignal.push(job.jobId);
if (job.metadata?.cacheKeys?.length > 0) {
cacheKeysToDelete.push(...job.metadata.cacheKeys);
}
if (job.type === "crawler") deletedMongoCrawljobs++;
else deletedMongoJobs++;
}
const jobsResult = await db.collection("jobs").deleteMany(mongoQuery);
console.log(
`[JobManager] Deleted ${jobsResult.deletedCount} jobs from MongoDB (crawler: ${deletedMongoCrawljobs}, workflow: ${deletedMongoJobs})`,
);
await mongoClient.close();
// Clean up MinIO files and cache entries for deleted jobs
if (jobIdsToSignal.length > 0) {
try {
const s3 = getS3Client();
const redis = getRedisClient();
let minioDeletedCount = 0;
let cacheDeletedCount = 0;
// Delete cache keys referenced in MongoDB job documents
if (cacheKeysToDelete.length > 0) {
const uniqueKeys = [...new Set(cacheKeysToDelete)];
await redis.del(...uniqueKeys);
cacheDeletedCount += uniqueKeys.length;
console.log(`[JobManager] Deleted ${uniqueKeys.length} cache keys from MongoDB refs`);
}
for (const jobId of jobIdsToSignal) {
// Delete MinIO files with prefix jobId/
try {
const listResult = await s3.send(new ListObjectsV2Command({
Bucket: MINIO_BUCKET,
Prefix: `${jobId}/`,
}));
const objects = listResult.Contents || [];
if (objects.length > 0) {
await s3.send(new DeleteObjectsCommand({
Bucket: MINIO_BUCKET,
Delete: {
Objects: objects.map(obj => ({ Key: obj.Key })),
},
}));
minioDeletedCount += objects.length;
console.log(`[JobManager] Deleted ${objects.length} MinIO files for job ${jobId}`);
}
} catch (e) {
console.warn(`[JobManager] MinIO cleanup error for job ${jobId}: ${e.message}`);
}
}
console.log(`[JobManager] Cleanup complete: ${minioDeletedCount} MinIO files, ${cacheDeletedCount} cache entries`);
} catch (e) {
console.warn(`[JobManager] Cleanup storage error: ${e.message}`);
}
}
// Terminate running Temporal workflows for deleted jobs so they stop immediately
if (jobIdsToSignal.length > 0) {
try {
const tConnection = await Connection.connect({
address: config.temporalAddress,
});
const tClient = new Client({ connection: tConnection });
const tqFilter = taskQueue === "crawler" ? 'TaskQueue = "crawler-workflows"' :
taskQueue === "workflow" ? 'TaskQueue = "workflow-workflows"' :
'(TaskQueue = "crawler-workflows" OR TaskQueue = "workflow-workflows")';
const runningQuery = `${tqFilter} AND ExecutionStatus = "Running"`;
const runningIterator = tClient.workflow.list({ query: runningQuery, limit: 100 });
let terminatedCount = 0;
for await (const wf of runningIterator) {
if (jobIdsToSignal.includes(wf.workflowId)) {
try {
await tConnection.workflowService.terminateWorkflowExecution({
namespace: "default",
workflowExecution: {
workflowId: wf.workflowId,
runId: wf.runId || undefined,
},
reason: "Cleanup - job deleted by user",
});
terminatedCount++;
console.log(`[JobManager] Terminated workflow ${wf.workflowId}`);
} catch (e) {
console.warn(`[JobManager] Failed to terminate workflow ${wf.workflowId}: ${e.message}`);
}
}
}
tConnection.close();
console.log(`[JobManager] Terminated ${terminatedCount} running workflows`);
} catch (e) {
console.warn(`[JobManager] Failed to terminate Temporal workflows: ${e.message}`);
}
}
res.json({
success: true,
data: {
deletedRedisCrawler,
deletedRedisWorkflow,
deletedMongoCrawljobs,
deletedMongoJobs,
organizationId,
},
});
} catch (err) {
console.error("[JobManager] Cleanup error:", err.message);
res.status(500).json({ success: false, error: err.message });
}
});
// ============================================================================
// Pool Routes (/pool/*)
// ============================================================================
/**
* Add a job to the queue and try to start it.
* Shared by the public route (called by the gateway, which authenticates the
* request) and the HMAC-protected internal route (direct service-to-service).
*/
async function handlePoolAdd(req, res) {
const {
jobId,
organizationId,
workflowType,
input,
} = req.body;
if (!jobId || !organizationId || !workflowType) {
return res.status(400).json({
success: false,
error: "jobId, organizationId, and workflowType are required",
});
}
const { type, taskQueue } = pool.getWorkflowInfo(workflowType);
if (!type || !taskQueue) {
return res.status(400).json({
success: false,
error: "Unknown workflowType",
});
}
try {
const result = await pool.addJob({
jobId,
type,
organizationId,
workflowType,
taskQueue,
input,
});
// Démarrage immédiat si un slot est libre (ne pas attendre le filet de 30 s)
let started = false;
try {
const startResult = await pool.tryStartNext({ organizationId, type });
started = !!startResult.started;
} catch (e) {
console.warn(`[Pool] immediate start failed: ${e.message}`);
}
res.json({
success: true,
enqueued: true,
position: result.position,
started,
jobId: started ? jobId : null,
});
} catch (err) {
console.error("[Pool] Add error:", err.message);
res.status(500).json({ success: false, error: err.message });
}
}
/**
* POST /internal/pool/add → internal route, direct service-to-service calls (HMAC required).
* Adding a job is NOT exposed by the API gateway; the only entry point is this HMAC route.
*/
app.post("/internal/pool/add", requireInternalKey, handlePoolAdd);
// ============================================================================
// Watcher wiring + filet de sécurité
// ============================================================================
// Notifications SSE issues du watcher (progression + clôture)
watcher.setHooks({
onProgress: (jobId, status, progress) => {
writeToSSE(jobId, {
type: "notification",
jobId,
status: status || "running",
progress: progress?.percent ?? 0,
step: progress?.step || "unknown",
timestamp: new Date().toISOString(),
});
},
onClose: async (jobId) => {
await persistFinal(jobId);
try {
await finalizeJob(jobId);
} catch (e) {
console.error(`[JobManager] finalizeJob error for ${jobId}: ${e.message}`);
}
try {
await pool.reconcilePools();
} catch (e) {
console.error(`[JobManager] reconcilePools error: ${e.message}`);
}
},
});
/**
* Persiste le résultat final du workflow dans `jobs` (seul le job-manager écrit).
*/
async function persistFinal(jobId) {
try {
const client = await getTemporalClient();
const handle = client.workflow.getHandle(jobId);
let status = "completed";
try {
const desc = await handle.describe();
status = desc.status?.name === "COMPLETED" ? "completed" : "failed";
} catch (e) {
// ignore
}
let result = null;
let error = null;
try {
result = await handle.result();
} catch (e) {
error = e.cause?.message || e.message || "Workflow failed";
}
await persistence.storeFinal(jobId, { status, result, error });
} catch (e) {
console.error(`[JobManager] persistFinal error for ${jobId}: ${e.message}`);
}
}
/**
* Filet de sécurité :
* - libère le pool (slots) si des workflows sont terminés ;
* - débloque les appelants dont le workflow est terminé mais non notifié
* (événement manqué, redémarrage du service...).
*/
async function reconciliationTick() {
try {
await pool.reconcilePools();
} catch (e) {
console.error(`[JobManager] reconciliation (pool) error: ${e.message}`);
}
for (const jobId of Array.from(sseConnections.keys())) {
try {
const client = await getTemporalClient();
const desc = await client.workflow.getHandle(jobId).describe();
if (TERMINAL_STATUSES.includes(desc.status?.name)) {
console.log(
`[JobManager] reconciliation: workflow ${jobId} clos (${desc.status?.name}) sans notification → finalize`,
);
await finalizeJob(jobId);
}
} catch (e) {
// ignore
}
}
}
/**
* Ré-arme les watchers pour les workflows encore en cours (redémarrage du service).
*/
async function rearmWatchers() {
const { Connection } = require("@temporalio/client");
const address = process.env.TEMPORAL_ADDRESS || "temporal:7233";
const connection = await Connection.connect({ address });
try {
for (const wfType of ["CrawlerTW", "WorkflowTW"]) {
const resp = await connection.workflowService.listWorkflowExecutions({
namespace: "default",
query: `ExecutionStatus = 'Running' and WorkflowType = '${wfType}'`,
});
for (const exec of resp.executions || []) {
watcher.arm({ jobId: exec.execution?.workflowId });
}
}
} finally {
connection.close();
}
}
// ============================================================================
// Start Everything
// ============================================================================
async function main() {
// Initialize Redis connection
const redis = require("./redis/client");
redis.getRedisClient();
// Armer le watcher dès qu'un workflow démarre
pool.setOnStarted((info) => {
// Le watcher suit le workflow ; le job-manager crée le doc `jobs` (running).
watcher.arm({ jobId: info.jobId });
persistence.storeRunning(info).catch((e) =>
console.error(`[JobManager] storeRunning error: ${e.message}`),
);
});
// Drain queues (start waiting jobs based on current Temporal state)
await pool.drainQueues();
// Termine les exécutions Temporal orphelines (type renommé → non servi par
// le bundle courant → retry infini). Voir shared/temporalWorkflowCleanup.js.
try {
const { Connection } = require("@temporalio/client");
const connection = await Connection.connect({
address: process.env.TEMPORAL_ADDRESS || "temporal:7233",
});
try {
await terminateObsoleteWorkflows(connection);
} finally {
connection.close();
}
} catch (e) {
console.error("[JobManager] terminateObsoleteWorkflows error:", e.message);
}
// Ré-arme les watchers des workflows déjà en cours (redémarrage)
rearmWatchers().catch((e) =>
console.error("[JobManager] rearmWatchers error:", e.message),
);
// Filet de sécurité : réconciliation au démarrage + toutes les 30 s
reconciliationTick().catch((e) =>
console.error("[JobManager] reconciliationTick error:", e.message),
);
setInterval(() => {
reconciliationTick().catch((e) =>
console.error("[JobManager] reconciliationTick error:", e.message),
);
}, 30000);
// Sync pool (filet) toutes les 30 s — le déclenchement principal est à la clôture
pool.startSyncInterval(30000);
// Start Express API
app.listen(PORT, () => {
console.log(`[JobManager] API running on port ${PORT}`);
console.log(`[JobManager] Endpoints:`);
console.log(` - GET /jobs/crawler (list crawler jobs from Temporal)`);
console.log(` - GET /jobs/workflow (list workflow jobs from Temporal)`);
console.log(` - GET /jobs/:jobId/status (SSE)`);
console.log(` - GET /jobs/:jobId/results`);
console.log(` - POST /jobs/cleanup (clean old workflows)`);
console.log(` - POST /internal/pool/add (add job to queue, HMAC required)`);
console.log(` - GET /health`);
});
}
// Graceful shutdown
process.on("SIGINT", () => {
console.log("[JobManager] Shutting down...");
process.exit(0);
});
process.on("SIGTERM", () => {
console.log("[JobManager] Shutting down...");
process.exit(0);
});
main().catch((error) => {
console.error("[JobManager] Fatal error:", error);
process.exit(1);
});
|