All files / services/crawler-api/src/routes single.js

10.55% Statements 38/360
100% Branches 1/1
100% Functions 0/0
10.55% Lines 38/360

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 3611x 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 - Single Resource Routes
 * Routes for single resource operations (GET, PUT, DELETE by ID)
 * These routes do NOT require organizationId in the path
 */
 
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const { CrawlerConfig, CrawlJob } = require('../models');
const { requireAuth } = require('../middleware/auth');
const {
  launchCrawlingWorkflow,
  createKnowledgeBase,
  createKnowledgeRouter,
  deleteKnowledgeBase,
  deleteKnowledgeRouter,
} = require('./helpers');
const { checkOrgAccess } = require('../../shared/validation/src/org-auth');
 
const router = express.Router();
 
// POST /crawlers - Create a new crawler configuration (without orgId in path)
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',
      });
    }

    if (!organizationId) {
      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, organizationId, createKb.name, createKb.description || '');
      createdKbId = kb._id;

      const routerName = createKb.routerName || createKb.name;
      const newRouter = await createKnowledgeRouter(authToken, organizationId, 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,
      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,
    });
  }
});
 
router.get('/crawlers/:id', async (req, res) => {
  try {
    const query = {
      _id: req.params.id,
      isActive: true,
    };
    
    const crawler = await CrawlerConfig.findOne(query);

    if (!crawler) {
      return res.status(404).json({
        success: false,
        message: 'Crawler configuration not found',
      });
    }

    if (!await checkOrgAccess(crawler.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    res.json({
      success: true,
      data: crawler,
    });
  } catch (error) {
    console.error('[CrawlerAPI] Error getting crawler:', error);
    res.status(500).json({
      success: false,
      message: 'Error retrieving crawler',
      error: error.message,
    });
  }
});
 
router.put('/crawlers/:id', async (req, res) => {
  try {
    const existingCrawler = await CrawlerConfig.findOne({
      _id: req.params.id,
      isActive: true,
    });

    if (!existingCrawler) {
      return res.status(404).json({
        success: false,
        message: 'Crawler configuration not found',
      });
    }

    if (!await checkOrgAccess(existingCrawler.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    const { name, description, prompt, extractPrompt, startUrl, config } = req.body;

    if (config && (!config.router || config.router.length === 0)) {
      return res.status(400).json({
        success: false,
        message: 'Router is required',
      });
    }

    const updates = {};

    if (name !== undefined) updates.name = name;
    if (description !== undefined) updates.description = description;
    if (prompt !== undefined) updates.prompt = prompt;
    if (extractPrompt !== undefined) updates.extractPrompt = extractPrompt;
    if (startUrl !== undefined) updates.startUrl = startUrl;
    if (config !== undefined) updates.config = config;

    const crawler = await CrawlerConfig.findOneAndUpdate(
      { _id: req.params.id, isActive: true },
      { $set: updates },
      { new: true }
    );

    res.json({
      success: true,
      message: 'Crawler configuration updated successfully',
      data: crawler,
    });
  } catch (error) {
    console.error('[CrawlerAPI] Error updating crawler:', error);
    res.status(500).json({
      success: false,
      message: 'Error updating crawler',
      error: error.message,
    });
  }
});
 
router.delete('/crawlers/:id', async (req, res) => {
  try {
    const existingCrawler = await CrawlerConfig.findOne({
      _id: req.params.id,
      isActive: true,
    });

    if (!existingCrawler) {
      return res.status(404).json({
        success: false,
        message: 'Crawler configuration not found',
      });
    }

    if (!await checkOrgAccess(existingCrawler.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    const crawler = await CrawlerConfig.findOneAndUpdate(
      { _id: req.params.id, isActive: true },
      { $set: { isActive: false } },
      { new: true }
    );

    res.json({
      success: true,
      message: 'Crawler configuration deleted successfully',
    });
  } catch (error) {
    console.error('[CrawlerAPI] Error deleting crawler:', error);
    res.status(500).json({
      success: false,
      message: 'Error deleting crawler',
      error: error.message,
    });
  }
});
 
router.post('/crawlers/:id/start', requireAuth, async (req, res) => {
  try {
    const { id } = req.params;
    const { startUrl, scheduleId } = req.body;

    const crawlerConfig = await CrawlerConfig.findOne({
      _id: id,
      isActive: true,
    });

    if (!crawlerConfig) {
      return res.status(404).json({
        success: false,
        message: 'Crawler configuration not found',
      });
    }

    if (!await checkOrgAccess(crawlerConfig.organizationId, req)) {
      return res.status(403).json({ success: false, message: 'Access denied to this resource' });
    }

    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();

    const crawlJob = new CrawlJob({
      jobId,
      configId: crawlerConfig._id,
      userId: req.userId || req.headers['x-config-id'] || 'api-key',
      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: crawlerConfig._id,
      },
    });
  } 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;