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 | 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 | /**
* Crawler API routes
*/
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const { CrawlerConfig, CrawlJob } = require('../models');
const { getUserId, requireAuth } = require('../middleware/auth');
const {
launchCrawlingWorkflow,
createKnowledgeBase,
createKnowledgeRouter,
deleteKnowledgeBase,
deleteKnowledgeRouter,
} = require('./helpers');
const router = express.Router({ mergeParams: true });
// GET /crawlers - List all crawler configurations
router.get('/crawlers', requireAuth, async (req, res) => {
try {
const query = {
isActive: true,
};
// Use organizationId if available (multi-tenant), otherwise fallback to userId
if (req.organizationId) {
query.organizationId = req.organizationId;
} else {
query.userId = req.userId;
}
const crawlers = await CrawlerConfig.find(query).sort({ createdAt: -1 });
res.json({
success: true,
data: crawlers,
});
} catch (error) {
console.error('[CrawlerAPI] Error listing crawlers:', error);
res.status(500).json({
success: false,
message: 'Error retrieving crawlers',
error: error.message,
});
}
});
// POST /crawlers - Create a new crawler configuration
router.post('/crawlers', requireAuth, async (req, res) => {
let createdKbId = null;
let createdRouterId = null;
try {
const { name, description, prompt, extractPrompt, startUrl, config, organizationId, createKb } = req.body;
if (!name) {
return res.status(400).json({
success: false,
message: 'Name is required',
});
}
// Accept organizationId from body (multi-tenant) or use the one from JWT
const orgId = organizationId || req.organizationId;
if (!orgId) {
return res.status(400).json({
success: false,
message: 'organizationId is required',
});
}
const authToken = req.headers.authorization?.split(' ')[1];
let router = config?.router;
if (createKb) {
if (!createKb.name) {
return res.status(400).json({
success: false,
message: 'createKb.name is required when creating a new KB',
});
}
const kb = await createKnowledgeBase(authToken, orgId, createKb.name, createKb.description || '');
createdKbId = kb._id;
const routerName = createKb.routerName || createKb.name;
const newRouter = await createKnowledgeRouter(authToken, orgId, routerName, createKb.routerDescription || '', [kb._id]);
createdRouterId = newRouter._id;
router = [{ type: 'meilisearch', id: newRouter._id }];
}
if (!router || router.length === 0) {
return res.status(400).json({
success: false,
message: 'Router is required (provide config.router or createKb)',
});
}
const crawler = new CrawlerConfig({
userId: req.userId,
organizationId: orgId,
name,
description: description || '',
prompt: prompt || '',
extractPrompt: extractPrompt || '',
startUrl: startUrl || '',
config: {
maxPages: config?.maxPages ?? 10,
maxDepth: config?.maxDepth ?? 3,
pageThreshold: config?.pageThreshold ?? 60,
linkThreshold: config?.linkThreshold ?? 40,
crawlDelay: config?.crawlDelay ?? 100,
llmModel: config?.llmModel || 'deepseek/deepseek-v4-flash',
sameDomain: config?.sameDomain === true,
enableSynthesis: config?.enableSynthesis !== false,
synthetiser: config?.synthetiser || { mode: 'fact', spec: {} },
router,
},
});
await crawler.save();
res.status(201).json({
success: true,
message: 'Crawler configuration created successfully',
data: {
...crawler.toObject(),
createdKb: createKb ? { _id: createdKbId } : undefined,
createdRouter: createKb ? { _id: createdRouterId } : undefined,
},
});
} catch (error) {
console.error('[CrawlerAPI] Error creating crawler:', error);
if (createdRouterId) {
try {
const authToken = req.headers.authorization?.split(' ')[1];
await deleteKnowledgeRouter(authToken, createdRouterId);
} catch (cleanupErr) {
console.error('[CrawlerAPI] Cleanup failed for router:', cleanupErr.message);
}
}
if (createdKbId) {
try {
const authToken = req.headers.authorization?.split(' ')[1];
await deleteKnowledgeBase(authToken, createdKbId);
} catch (cleanupErr) {
console.error('[CrawlerAPI] Cleanup failed for KB:', cleanupErr.message);
}
}
res.status(500).json({
success: false,
message: 'Error creating crawler',
error: error.message,
});
}
});
// POST /crawlers/:configId/start - Start a crawling job
router.post('/crawlers/:configId/start', requireAuth, async (req, res) => {
try {
const { configId } = req.params;
const { startUrl, scheduleId } = req.body;
// Fetch configuration
const query = {
_id: configId,
isActive: true,
};
// Use organizationId if available (multi-tenant), otherwise fallback to userId
if (req.organizationId) {
query.organizationId = req.organizationId;
} else {
query.userId = req.userId;
}
const crawlerConfig = await CrawlerConfig.findOne(query);
if (!crawlerConfig) {
return res.status(404).json({
success: false,
message: 'Crawler configuration not found',
});
}
const url = startUrl || crawlerConfig.startUrl;
if (!url) {
return res.status(400).json({
success: false,
message: 'startUrl is required (provide in body or in crawler config)',
});
}
const jobId = uuidv4();
// Create job in MongoDB
const crawlJob = new CrawlJob({
jobId,
configId: crawlerConfig._id,
userId: req.userId,
organizationId: crawlerConfig.organizationId,
scheduleId: scheduleId || null,
status: 'pending',
config: {
startUrls: [url],
maxDepth: crawlerConfig.config.maxDepth,
maxPages: crawlerConfig.config.maxPages,
pageThreshold: crawlerConfig.config.pageThreshold,
linkThreshold: crawlerConfig.config.linkThreshold,
},
progress: {
step: 'starting',
percent: 0,
pagesCrawled: 0,
},
});
await crawlJob.save();
// Launch Temporal workflow
try {
const authToken = req.headers.authorization?.split(' ')[1];
await launchCrawlingWorkflow(jobId, [url], crawlerConfig, req.userId, authToken, crawlerConfig.organizationId);
} catch (workflowError) {
console.error('[CrawlerAPI] Failed to launch workflow:', workflowError);
crawlJob.status = 'failed';
crawlJob.errorMessage = workflowError.message;
await crawlJob.save();
return res.status(500).json({
success: false,
message: 'Failed to start crawling workflow',
error: workflowError.message,
});
}
// Update config run count
crawlerConfig.runCount = (crawlerConfig.runCount || 0) + 1;
await crawlerConfig.save();
// Mark as running immediately (workflow also updates on first activity)
crawlJob.status = 'running';
crawlJob.progress = { step: 'launched', percent: 1 };
await crawlJob.save();
res.json({
success: true,
data: {
jobId,
status: 'running',
configId,
},
});
} catch (error) {
console.error('[CrawlerAPI] Error starting crawl:', error);
res.status(500).json({
success: false,
message: 'Error starting crawling job',
error: error.message,
});
}
});
module.exports = router;
|