cronMigrationManager.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. /**
  2. * Cron Migration Manager
  3. * Manages database migrations as cron jobs using percolate:synced-cron
  4. */
  5. import { Meteor } from 'meteor/meteor';
  6. import { SyncedCron } from 'meteor/percolate:synced-cron';
  7. import { ReactiveVar } from 'meteor/reactive-var';
  8. import { cronJobStorage } from './cronJobStorage';
  9. // Server-side reactive variables for cron migration progress
  10. export const cronMigrationProgress = new ReactiveVar(0);
  11. export const cronMigrationStatus = new ReactiveVar('');
  12. export const cronMigrationCurrentStep = new ReactiveVar('');
  13. export const cronMigrationSteps = new ReactiveVar([]);
  14. export const cronIsMigrating = new ReactiveVar(false);
  15. export const cronJobs = new ReactiveVar([]);
  16. // Board-specific operation tracking
  17. export const boardOperations = new ReactiveVar(new Map());
  18. export const boardOperationProgress = new ReactiveVar(new Map());
  19. class CronMigrationManager {
  20. constructor() {
  21. this.migrationSteps = this.initializeMigrationSteps();
  22. this.currentStepIndex = 0;
  23. this.startTime = null;
  24. this.isRunning = false;
  25. this.jobProcessor = null;
  26. this.processingInterval = null;
  27. }
  28. /**
  29. * Initialize migration steps as cron jobs
  30. */
  31. initializeMigrationSteps() {
  32. return [
  33. {
  34. id: 'board-background-color',
  35. name: 'Board Background Colors',
  36. description: 'Setting up board background colors',
  37. weight: 1,
  38. completed: false,
  39. progress: 0,
  40. cronName: 'migration_board_background_color',
  41. schedule: 'every 1 minute', // Will be changed to 'once' when triggered
  42. status: 'stopped'
  43. },
  44. {
  45. id: 'add-cardcounterlist-allowed',
  46. name: 'Card Counter List Settings',
  47. description: 'Adding card counter list permissions',
  48. weight: 1,
  49. completed: false,
  50. progress: 0,
  51. cronName: 'migration_card_counter_list',
  52. schedule: 'every 1 minute',
  53. status: 'stopped'
  54. },
  55. {
  56. id: 'add-boardmemberlist-allowed',
  57. name: 'Board Member List Settings',
  58. description: 'Adding board member list permissions',
  59. weight: 1,
  60. completed: false,
  61. progress: 0,
  62. cronName: 'migration_board_member_list',
  63. schedule: 'every 1 minute',
  64. status: 'stopped'
  65. },
  66. {
  67. id: 'lowercase-board-permission',
  68. name: 'Board Permission Standardization',
  69. description: 'Converting board permissions to lowercase',
  70. weight: 1,
  71. completed: false,
  72. progress: 0,
  73. cronName: 'migration_lowercase_permission',
  74. schedule: 'every 1 minute',
  75. status: 'stopped'
  76. },
  77. {
  78. id: 'change-attachments-type-for-non-images',
  79. name: 'Attachment Type Standardization',
  80. description: 'Updating attachment types for non-images',
  81. weight: 2,
  82. completed: false,
  83. progress: 0,
  84. cronName: 'migration_attachment_types',
  85. schedule: 'every 1 minute',
  86. status: 'stopped'
  87. },
  88. {
  89. id: 'card-covers',
  90. name: 'Card Covers System',
  91. description: 'Setting up card cover functionality',
  92. weight: 2,
  93. completed: false,
  94. progress: 0,
  95. cronName: 'migration_card_covers',
  96. schedule: 'every 1 minute',
  97. status: 'stopped'
  98. },
  99. {
  100. id: 'use-css-class-for-boards-colors',
  101. name: 'Board Color CSS Classes',
  102. description: 'Converting board colors to CSS classes',
  103. weight: 2,
  104. completed: false,
  105. progress: 0,
  106. cronName: 'migration_board_color_css',
  107. schedule: 'every 1 minute',
  108. status: 'stopped'
  109. },
  110. {
  111. id: 'denormalize-star-number-per-board',
  112. name: 'Board Star Counts',
  113. description: 'Calculating star counts per board',
  114. weight: 3,
  115. completed: false,
  116. progress: 0,
  117. cronName: 'migration_star_numbers',
  118. schedule: 'every 1 minute',
  119. status: 'stopped'
  120. },
  121. {
  122. id: 'add-member-isactive-field',
  123. name: 'Member Activity Status',
  124. description: 'Adding member activity tracking',
  125. weight: 2,
  126. completed: false,
  127. progress: 0,
  128. cronName: 'migration_member_activity',
  129. schedule: 'every 1 minute',
  130. status: 'stopped'
  131. },
  132. {
  133. id: 'add-sort-checklists',
  134. name: 'Checklist Sorting',
  135. description: 'Adding sort order to checklists',
  136. weight: 2,
  137. completed: false,
  138. progress: 0,
  139. cronName: 'migration_sort_checklists',
  140. schedule: 'every 1 minute',
  141. status: 'stopped'
  142. },
  143. {
  144. id: 'add-swimlanes',
  145. name: 'Swimlanes System',
  146. description: 'Setting up swimlanes functionality',
  147. weight: 4,
  148. completed: false,
  149. progress: 0,
  150. cronName: 'migration_swimlanes',
  151. schedule: 'every 1 minute',
  152. status: 'stopped'
  153. },
  154. {
  155. id: 'add-views',
  156. name: 'Board Views',
  157. description: 'Adding board view options',
  158. weight: 2,
  159. completed: false,
  160. progress: 0,
  161. cronName: 'migration_views',
  162. schedule: 'every 1 minute',
  163. status: 'stopped'
  164. },
  165. {
  166. id: 'add-checklist-items',
  167. name: 'Checklist Items',
  168. description: 'Setting up checklist items system',
  169. weight: 3,
  170. completed: false,
  171. progress: 0,
  172. cronName: 'migration_checklist_items',
  173. schedule: 'every 1 minute',
  174. status: 'stopped'
  175. },
  176. {
  177. id: 'add-card-types',
  178. name: 'Card Types',
  179. description: 'Adding card type functionality',
  180. weight: 2,
  181. completed: false,
  182. progress: 0,
  183. cronName: 'migration_card_types',
  184. schedule: 'every 1 minute',
  185. status: 'stopped'
  186. },
  187. {
  188. id: 'add-custom-fields-to-cards',
  189. name: 'Custom Fields',
  190. description: 'Adding custom fields to cards',
  191. weight: 3,
  192. completed: false,
  193. progress: 0,
  194. cronName: 'migration_custom_fields',
  195. schedule: 'every 1 minute',
  196. status: 'stopped'
  197. },
  198. {
  199. id: 'migrate-attachments-collectionFS-to-ostrioFiles',
  200. name: 'Migrate Attachments to Meteor-Files',
  201. description: 'Migrating attachments from CollectionFS to Meteor-Files',
  202. weight: 8,
  203. completed: false,
  204. progress: 0,
  205. cronName: 'migration_attachments_collectionfs',
  206. schedule: 'every 1 minute',
  207. status: 'stopped'
  208. },
  209. {
  210. id: 'migrate-avatars-collectionFS-to-ostrioFiles',
  211. name: 'Migrate Avatars to Meteor-Files',
  212. description: 'Migrating avatars from CollectionFS to Meteor-Files',
  213. weight: 6,
  214. completed: false,
  215. progress: 0,
  216. cronName: 'migration_avatars_collectionfs',
  217. schedule: 'every 1 minute',
  218. status: 'stopped'
  219. },
  220. {
  221. id: 'migrate-lists-to-per-swimlane',
  222. name: 'Migrate Lists to Per-Swimlane',
  223. description: 'Migrating lists to per-swimlane structure',
  224. weight: 5,
  225. completed: false,
  226. progress: 0,
  227. cronName: 'migration_lists_per_swimlane',
  228. schedule: 'every 1 minute',
  229. status: 'stopped'
  230. },
  231. ];
  232. }
  233. /**
  234. * Initialize all migration cron jobs
  235. */
  236. initializeCronJobs() {
  237. this.migrationSteps.forEach(step => {
  238. this.createCronJob(step);
  239. });
  240. // Start job processor
  241. this.startJobProcessor();
  242. // Update cron jobs list after a short delay to allow SyncedCron to initialize
  243. Meteor.setTimeout(() => {
  244. this.updateCronJobsList();
  245. }, 1000);
  246. }
  247. /**
  248. * Start the job processor for CPU-aware job execution
  249. */
  250. startJobProcessor() {
  251. if (this.processingInterval) {
  252. return; // Already running
  253. }
  254. this.processingInterval = Meteor.setInterval(() => {
  255. this.processJobQueue();
  256. }, 5000); // Check every 5 seconds
  257. // Cron job processor started with CPU throttling
  258. }
  259. /**
  260. * Stop the job processor
  261. */
  262. stopJobProcessor() {
  263. if (this.processingInterval) {
  264. Meteor.clearInterval(this.processingInterval);
  265. this.processingInterval = null;
  266. }
  267. }
  268. /**
  269. * Process the job queue with CPU throttling
  270. */
  271. async processJobQueue() {
  272. const canStart = cronJobStorage.canStartNewJob();
  273. if (!canStart.canStart) {
  274. // Suppress "Cannot start new job: Maximum concurrent jobs reached" message
  275. // console.log(`Cannot start new job: ${canStart.reason}`);
  276. return;
  277. }
  278. const nextJob = cronJobStorage.getNextJob();
  279. if (!nextJob) {
  280. return; // No jobs in queue
  281. }
  282. // Start the job
  283. await this.executeJob(nextJob);
  284. }
  285. /**
  286. * Execute a job from the queue
  287. */
  288. async executeJob(queueJob) {
  289. const { jobId, jobType, jobData } = queueJob;
  290. try {
  291. // Update queue status to running
  292. cronJobStorage.updateQueueStatus(jobId, 'running', { startedAt: new Date() });
  293. // Save job status
  294. cronJobStorage.saveJobStatus(jobId, {
  295. jobType,
  296. status: 'running',
  297. progress: 0,
  298. startedAt: new Date(),
  299. ...jobData
  300. });
  301. // Execute based on job type
  302. if (jobType === 'migration') {
  303. await this.executeMigrationJob(jobId, jobData);
  304. } else if (jobType === 'board_operation') {
  305. await this.executeBoardOperationJob(jobId, jobData);
  306. } else if (jobType === 'board_migration') {
  307. await this.executeBoardMigrationJob(jobId, jobData);
  308. } else {
  309. throw new Error(`Unknown job type: ${jobType}`);
  310. }
  311. // Mark as completed
  312. cronJobStorage.updateQueueStatus(jobId, 'completed', { completedAt: new Date() });
  313. cronJobStorage.saveJobStatus(jobId, {
  314. status: 'completed',
  315. progress: 100,
  316. completedAt: new Date()
  317. });
  318. } catch (error) {
  319. console.error(`Job ${jobId} failed:`, error);
  320. // Mark as failed
  321. cronJobStorage.updateQueueStatus(jobId, 'failed', {
  322. failedAt: new Date(),
  323. error: error.message
  324. });
  325. cronJobStorage.saveJobStatus(jobId, {
  326. status: 'failed',
  327. error: error.message,
  328. failedAt: new Date()
  329. });
  330. }
  331. }
  332. /**
  333. * Execute a migration job
  334. */
  335. async executeMigrationJob(jobId, jobData) {
  336. if (!jobData) {
  337. throw new Error('Job data is required for migration execution');
  338. }
  339. const { stepId } = jobData;
  340. if (!stepId) {
  341. throw new Error('Step ID is required in job data');
  342. }
  343. const step = this.migrationSteps.find(s => s.id === stepId);
  344. if (!step) {
  345. throw new Error(`Migration step ${stepId} not found`);
  346. }
  347. // Create steps for this migration
  348. const steps = this.createMigrationSteps(step);
  349. for (let i = 0; i < steps.length; i++) {
  350. const stepData = steps[i];
  351. // Save step status
  352. cronJobStorage.saveJobStep(jobId, i, {
  353. stepName: stepData.name,
  354. status: 'running',
  355. progress: 0
  356. });
  357. // Execute step
  358. await this.executeMigrationStep(jobId, i, stepData, stepId);
  359. // Mark step as completed
  360. cronJobStorage.saveJobStep(jobId, i, {
  361. status: 'completed',
  362. progress: 100,
  363. completedAt: new Date()
  364. });
  365. // Update overall progress
  366. const progress = Math.round(((i + 1) / steps.length) * 100);
  367. cronJobStorage.saveJobStatus(jobId, { progress });
  368. }
  369. }
  370. /**
  371. * Create migration steps for a job
  372. */
  373. createMigrationSteps(step) {
  374. const steps = [];
  375. switch (step.id) {
  376. case 'board-background-color':
  377. steps.push(
  378. { name: 'Initialize board colors', duration: 1000 },
  379. { name: 'Update board documents', duration: 2000 },
  380. { name: 'Finalize changes', duration: 500 }
  381. );
  382. break;
  383. case 'add-cardcounterlist-allowed':
  384. steps.push(
  385. { name: 'Add card counter permissions', duration: 800 },
  386. { name: 'Update existing boards', duration: 1500 },
  387. { name: 'Verify permissions', duration: 700 }
  388. );
  389. break;
  390. case 'migrate-attachments-collectionFS-to-ostrioFiles':
  391. steps.push(
  392. { name: 'Scan CollectionFS attachments', duration: 2000 },
  393. { name: 'Create Meteor-Files records', duration: 3000 },
  394. { name: 'Migrate file data', duration: 5000 },
  395. { name: 'Update references', duration: 2000 },
  396. { name: 'Cleanup old data', duration: 1000 }
  397. );
  398. break;
  399. default:
  400. steps.push(
  401. { name: `Execute ${step.name}`, duration: 2000 },
  402. { name: 'Verify changes', duration: 1000 }
  403. );
  404. }
  405. return steps;
  406. }
  407. /**
  408. * Execute a migration step
  409. */
  410. async executeMigrationStep(jobId, stepIndex, stepData, stepId) {
  411. const { name, duration } = stepData;
  412. // Simulate step execution with progress updates for other migrations
  413. const progressSteps = 10;
  414. for (let i = 0; i <= progressSteps; i++) {
  415. const progress = Math.round((i / progressSteps) * 100);
  416. // Update step progress
  417. cronJobStorage.saveJobStep(jobId, stepIndex, {
  418. progress,
  419. currentAction: `Executing: ${name} (${progress}%)`
  420. });
  421. // Simulate work
  422. await new Promise(resolve => setTimeout(resolve, duration / progressSteps));
  423. }
  424. }
  425. /**
  426. * Execute a board operation job
  427. */
  428. async executeBoardOperationJob(jobId, jobData) {
  429. const { operationType, operationData } = jobData;
  430. // Use existing board operation logic
  431. await this.executeBoardOperation(jobId, operationType, operationData);
  432. }
  433. /**
  434. * Execute a board migration job
  435. */
  436. async executeBoardMigrationJob(jobId, jobData) {
  437. const { boardId, boardTitle, migrationType } = jobData;
  438. try {
  439. // Starting board migration
  440. // Create migration steps for this board
  441. const steps = this.createBoardMigrationSteps(boardId, migrationType);
  442. for (let i = 0; i < steps.length; i++) {
  443. const stepData = steps[i];
  444. // Save step status
  445. cronJobStorage.saveJobStep(jobId, i, {
  446. stepName: stepData.name,
  447. status: 'running',
  448. progress: 0,
  449. boardId: boardId
  450. });
  451. // Execute step
  452. await this.executeBoardMigrationStep(jobId, i, stepData, boardId);
  453. // Mark step as completed
  454. cronJobStorage.saveJobStep(jobId, i, {
  455. status: 'completed',
  456. progress: 100,
  457. completedAt: new Date()
  458. });
  459. // Update overall progress
  460. const progress = Math.round(((i + 1) / steps.length) * 100);
  461. cronJobStorage.saveJobStatus(jobId, { progress });
  462. }
  463. // Mark board as migrated
  464. this.markBoardAsMigrated(boardId, migrationType);
  465. // Completed board migration
  466. } catch (error) {
  467. console.error(`Board migration failed for ${boardId}:`, error);
  468. throw error;
  469. }
  470. }
  471. /**
  472. * Create migration steps for a board
  473. */
  474. createBoardMigrationSteps(boardId, migrationType) {
  475. const steps = [];
  476. if (migrationType === 'full_board_migration') {
  477. steps.push(
  478. { name: 'Check board structure', duration: 500, type: 'validation' },
  479. { name: 'Migrate lists to swimlanes', duration: 2000, type: 'lists' },
  480. { name: 'Migrate attachments', duration: 3000, type: 'attachments' },
  481. { name: 'Update board metadata', duration: 1000, type: 'metadata' },
  482. { name: 'Verify migration', duration: 1000, type: 'verification' }
  483. );
  484. } else {
  485. // Default migration steps
  486. steps.push(
  487. { name: 'Initialize board migration', duration: 1000, type: 'init' },
  488. { name: 'Execute migration', duration: 2000, type: 'migration' },
  489. { name: 'Finalize changes', duration: 1000, type: 'finalize' }
  490. );
  491. }
  492. return steps;
  493. }
  494. /**
  495. * Execute a board migration step
  496. */
  497. async executeBoardMigrationStep(jobId, stepIndex, stepData, boardId) {
  498. const { name, duration, type } = stepData;
  499. // Simulate step execution with progress updates
  500. const progressSteps = 10;
  501. for (let i = 0; i <= progressSteps; i++) {
  502. const progress = Math.round((i / progressSteps) * 100);
  503. // Update step progress
  504. cronJobStorage.saveJobStep(jobId, stepIndex, {
  505. progress,
  506. currentAction: `Executing: ${name} (${progress}%)`
  507. });
  508. // Simulate work based on step type
  509. await this.simulateBoardMigrationWork(type, duration / progressSteps);
  510. }
  511. }
  512. /**
  513. * Simulate board migration work
  514. */
  515. async simulateBoardMigrationWork(stepType, duration) {
  516. // Simulate different types of migration work
  517. switch (stepType) {
  518. case 'validation':
  519. // Quick validation
  520. await new Promise(resolve => setTimeout(resolve, duration * 0.5));
  521. break;
  522. case 'lists':
  523. // List migration work
  524. await new Promise(resolve => setTimeout(resolve, duration));
  525. break;
  526. case 'attachments':
  527. // Attachment migration work
  528. await new Promise(resolve => setTimeout(resolve, duration * 1.2));
  529. break;
  530. case 'metadata':
  531. // Metadata update work
  532. await new Promise(resolve => setTimeout(resolve, duration * 0.8));
  533. break;
  534. case 'verification':
  535. // Verification work
  536. await new Promise(resolve => setTimeout(resolve, duration * 0.6));
  537. break;
  538. default:
  539. // Default work
  540. await new Promise(resolve => setTimeout(resolve, duration));
  541. }
  542. }
  543. /**
  544. * Mark a board as migrated
  545. */
  546. markBoardAsMigrated(boardId, migrationType) {
  547. try {
  548. // Update board with migration markers and version
  549. const updateQuery = {
  550. 'migrationMarkers.fullMigrationCompleted': true,
  551. 'migrationMarkers.lastMigration': new Date(),
  552. 'migrationMarkers.migrationType': migrationType,
  553. 'migrationVersion': 1 // Set migration version to prevent re-migration
  554. };
  555. // Update the board document
  556. if (typeof Boards !== 'undefined') {
  557. Boards.update(boardId, { $set: updateQuery });
  558. }
  559. console.log(`Marked board ${boardId} as migrated`);
  560. } catch (error) {
  561. console.error(`Error marking board ${boardId} as migrated:`, error);
  562. }
  563. }
  564. /**
  565. * Create a cron job for a migration step
  566. */
  567. createCronJob(step) {
  568. SyncedCron.add({
  569. name: step.cronName,
  570. schedule: (parser) => parser.text(step.schedule),
  571. job: () => {
  572. this.runMigrationStep(step);
  573. },
  574. });
  575. }
  576. /**
  577. * Run a migration step
  578. */
  579. async runMigrationStep(step) {
  580. try {
  581. // Starting migration step
  582. cronMigrationCurrentStep.set(step.name);
  583. cronMigrationStatus.set(`Running: ${step.description}`);
  584. cronIsMigrating.set(true);
  585. // Simulate migration progress
  586. const progressSteps = 10;
  587. for (let i = 0; i <= progressSteps; i++) {
  588. step.progress = (i / progressSteps) * 100;
  589. this.updateProgress();
  590. // Simulate work
  591. await new Promise(resolve => setTimeout(resolve, 100));
  592. }
  593. // Mark as completed
  594. step.completed = true;
  595. step.progress = 100;
  596. step.status = 'completed';
  597. // Completed migration step
  598. // Update progress
  599. this.updateProgress();
  600. } catch (error) {
  601. console.error(`Migration ${step.name} failed:`, error);
  602. step.status = 'error';
  603. cronMigrationStatus.set(`Migration failed: ${error.message}`);
  604. }
  605. }
  606. /**
  607. * Start all migrations using job queue
  608. */
  609. async startAllMigrations() {
  610. if (this.isRunning) {
  611. return;
  612. }
  613. this.isRunning = true;
  614. cronIsMigrating.set(true);
  615. cronMigrationStatus.set('Adding migrations to job queue...');
  616. this.startTime = Date.now();
  617. try {
  618. // Add all migration steps to the job queue
  619. for (let i = 0; i < this.migrationSteps.length; i++) {
  620. const step = this.migrationSteps[i];
  621. if (step.completed) {
  622. continue; // Skip already completed steps
  623. }
  624. // Add to job queue
  625. const jobId = `migration_${step.id}_${Date.now()}`;
  626. cronJobStorage.addToQueue(jobId, 'migration', step.weight, {
  627. stepId: step.id,
  628. stepName: step.name,
  629. stepDescription: step.description
  630. });
  631. // Save initial job status
  632. cronJobStorage.saveJobStatus(jobId, {
  633. jobType: 'migration',
  634. status: 'pending',
  635. progress: 0,
  636. stepId: step.id,
  637. stepName: step.name,
  638. stepDescription: step.description
  639. });
  640. }
  641. cronMigrationStatus.set('Migrations added to queue. Processing will begin shortly...');
  642. // Start monitoring progress
  643. this.monitorMigrationProgress();
  644. } catch (error) {
  645. console.error('Failed to start migrations:', error);
  646. cronMigrationStatus.set(`Failed to start migrations: ${error.message}`);
  647. cronIsMigrating.set(false);
  648. this.isRunning = false;
  649. }
  650. }
  651. /**
  652. * Monitor migration progress
  653. */
  654. monitorMigrationProgress() {
  655. const monitorInterval = Meteor.setInterval(() => {
  656. const stats = cronJobStorage.getQueueStats();
  657. const incompleteJobs = cronJobStorage.getIncompleteJobs();
  658. // Update progress
  659. const totalJobs = stats.total;
  660. const completedJobs = stats.completed;
  661. const progress = totalJobs > 0 ? Math.round((completedJobs / totalJobs) * 100) : 0;
  662. cronMigrationProgress.set(progress);
  663. // Update status
  664. if (stats.running > 0) {
  665. const runningJob = incompleteJobs.find(job => job.status === 'running');
  666. if (runningJob) {
  667. cronMigrationCurrentStep.set(runningJob.stepName || 'Processing migration...');
  668. cronMigrationStatus.set(`Running: ${runningJob.stepName || 'Migration in progress'}`);
  669. }
  670. } else if (stats.pending > 0) {
  671. cronMigrationStatus.set(`${stats.pending} migrations pending in queue`);
  672. cronMigrationCurrentStep.set('Waiting for available resources...');
  673. } else if (stats.completed === totalJobs && totalJobs > 0) {
  674. // All migrations completed
  675. cronMigrationStatus.set('All migrations completed successfully!');
  676. cronMigrationProgress.set(100);
  677. cronMigrationCurrentStep.set('');
  678. // Clear status after delay
  679. setTimeout(() => {
  680. cronIsMigrating.set(false);
  681. cronMigrationStatus.set('');
  682. cronMigrationProgress.set(0);
  683. }, 3000);
  684. Meteor.clearInterval(monitorInterval);
  685. }
  686. }, 2000); // Check every 2 seconds
  687. }
  688. /**
  689. * Start a specific cron job
  690. */
  691. async startCronJob(cronName) {
  692. // Change schedule to run once
  693. const job = SyncedCron.jobs.find(j => j.name === cronName);
  694. if (job) {
  695. job.schedule = 'once';
  696. SyncedCron.start();
  697. }
  698. }
  699. /**
  700. * Wait for a cron job to complete
  701. */
  702. async waitForCronJobCompletion(step) {
  703. return new Promise((resolve) => {
  704. const checkInterval = setInterval(() => {
  705. if (step.completed || step.status === 'error') {
  706. clearInterval(checkInterval);
  707. resolve();
  708. }
  709. }, 1000);
  710. });
  711. }
  712. /**
  713. * Stop a specific cron job
  714. */
  715. stopCronJob(cronName) {
  716. SyncedCron.remove(cronName);
  717. const step = this.migrationSteps.find(s => s.cronName === cronName);
  718. if (step) {
  719. step.status = 'stopped';
  720. }
  721. this.updateCronJobsList();
  722. }
  723. /**
  724. * Pause a specific cron job
  725. */
  726. pauseCronJob(cronName) {
  727. SyncedCron.pause(cronName);
  728. const step = this.migrationSteps.find(s => s.cronName === cronName);
  729. if (step) {
  730. step.status = 'paused';
  731. }
  732. this.updateCronJobsList();
  733. }
  734. /**
  735. * Resume a specific cron job
  736. */
  737. resumeCronJob(cronName) {
  738. SyncedCron.resume(cronName);
  739. const step = this.migrationSteps.find(s => s.cronName === cronName);
  740. if (step) {
  741. step.status = 'running';
  742. }
  743. this.updateCronJobsList();
  744. }
  745. /**
  746. * Remove a cron job
  747. */
  748. removeCronJob(cronName) {
  749. SyncedCron.remove(cronName);
  750. this.migrationSteps = this.migrationSteps.filter(s => s.cronName !== cronName);
  751. this.updateCronJobsList();
  752. }
  753. /**
  754. * Add a new cron job
  755. */
  756. addCronJob(jobData) {
  757. const step = {
  758. id: jobData.id || `custom_${Date.now()}`,
  759. name: jobData.name,
  760. description: jobData.description,
  761. weight: jobData.weight || 1,
  762. completed: false,
  763. progress: 0,
  764. cronName: jobData.cronName || `custom_${Date.now()}`,
  765. schedule: jobData.schedule || 'every 1 minute',
  766. status: 'stopped'
  767. };
  768. this.migrationSteps.push(step);
  769. this.createCronJob(step);
  770. this.updateCronJobsList();
  771. }
  772. /**
  773. * Update progress variables
  774. */
  775. updateProgress() {
  776. const totalWeight = this.migrationSteps.reduce((total, step) => total + step.weight, 0);
  777. const completedWeight = this.migrationSteps.reduce((total, step) => {
  778. return total + (step.completed ? step.weight : step.progress * step.weight / 100);
  779. }, 0);
  780. const progress = Math.round((completedWeight / totalWeight) * 100);
  781. cronMigrationProgress.set(progress);
  782. cronMigrationSteps.set([...this.migrationSteps]);
  783. }
  784. /**
  785. * Update cron jobs list
  786. */
  787. updateCronJobsList() {
  788. // Check if SyncedCron is available and has jobs
  789. if (!SyncedCron || !SyncedCron.jobs || !Array.isArray(SyncedCron.jobs)) {
  790. // SyncedCron not available or no jobs yet
  791. cronJobs.set([]);
  792. return;
  793. }
  794. const jobs = SyncedCron.jobs.map(job => {
  795. const step = this.migrationSteps.find(s => s.cronName === job.name);
  796. return {
  797. name: job.name,
  798. schedule: job.schedule,
  799. status: step ? step.status : 'unknown',
  800. lastRun: job.lastRun,
  801. nextRun: job.nextRun,
  802. running: job.running
  803. };
  804. });
  805. cronJobs.set(jobs);
  806. }
  807. /**
  808. * Get all cron jobs
  809. */
  810. getAllCronJobs() {
  811. return cronJobs.get();
  812. }
  813. /**
  814. * Get migration steps
  815. */
  816. getMigrationSteps() {
  817. return this.migrationSteps;
  818. }
  819. /**
  820. * Start a long-running operation for a specific board
  821. */
  822. startBoardOperation(boardId, operationType, operationData) {
  823. const operationId = `${boardId}_${operationType}_${Date.now()}`;
  824. // Add to job queue
  825. cronJobStorage.addToQueue(operationId, 'board_operation', 3, {
  826. boardId,
  827. operationType,
  828. operationData
  829. });
  830. // Save initial job status
  831. cronJobStorage.saveJobStatus(operationId, {
  832. jobType: 'board_operation',
  833. status: 'pending',
  834. progress: 0,
  835. boardId,
  836. operationType,
  837. operationData,
  838. createdAt: new Date()
  839. });
  840. // Update board operations map for backward compatibility
  841. const operation = {
  842. id: operationId,
  843. boardId: boardId,
  844. type: operationType,
  845. data: operationData,
  846. status: 'pending',
  847. progress: 0,
  848. startTime: new Date(),
  849. endTime: null,
  850. error: null
  851. };
  852. const operations = boardOperations.get();
  853. operations.set(operationId, operation);
  854. boardOperations.set(operations);
  855. return operationId;
  856. }
  857. /**
  858. * Execute a board operation
  859. */
  860. async executeBoardOperation(operationId, operationType, operationData) {
  861. const operations = boardOperations.get();
  862. const operation = operations.get(operationId);
  863. if (!operation) {
  864. console.error(`Operation ${operationId} not found`);
  865. return;
  866. }
  867. try {
  868. console.log(`Starting board operation: ${operationType} for board ${operation.boardId}`);
  869. // Update operation status
  870. operation.status = 'running';
  871. operation.progress = 0;
  872. this.updateBoardOperation(operationId, operation);
  873. // Execute the specific operation
  874. switch (operationType) {
  875. case 'copy_board':
  876. await this.copyBoard(operationId, operationData);
  877. break;
  878. case 'move_board':
  879. await this.moveBoard(operationId, operationData);
  880. break;
  881. case 'copy_swimlane':
  882. await this.copySwimlane(operationId, operationData);
  883. break;
  884. case 'move_swimlane':
  885. await this.moveSwimlane(operationId, operationData);
  886. break;
  887. case 'copy_list':
  888. await this.copyList(operationId, operationData);
  889. break;
  890. case 'move_list':
  891. await this.moveList(operationId, operationData);
  892. break;
  893. case 'copy_card':
  894. await this.copyCard(operationId, operationData);
  895. break;
  896. case 'move_card':
  897. await this.moveCard(operationId, operationData);
  898. break;
  899. case 'copy_checklist':
  900. await this.copyChecklist(operationId, operationData);
  901. break;
  902. case 'move_checklist':
  903. await this.moveChecklist(operationId, operationData);
  904. break;
  905. default:
  906. throw new Error(`Unknown operation type: ${operationType}`);
  907. }
  908. // Mark as completed
  909. operation.status = 'completed';
  910. operation.progress = 100;
  911. operation.endTime = new Date();
  912. this.updateBoardOperation(operationId, operation);
  913. console.log(`Completed board operation: ${operationType} for board ${operation.boardId}`);
  914. } catch (error) {
  915. console.error(`Board operation ${operationType} failed:`, error);
  916. operation.status = 'error';
  917. operation.error = error.message;
  918. operation.endTime = new Date();
  919. this.updateBoardOperation(operationId, operation);
  920. }
  921. }
  922. /**
  923. * Update board operation progress
  924. */
  925. updateBoardOperation(operationId, operation) {
  926. const operations = boardOperations.get();
  927. operations.set(operationId, operation);
  928. boardOperations.set(operations);
  929. // Update progress map
  930. const progressMap = boardOperationProgress.get();
  931. progressMap.set(operationId, {
  932. progress: operation.progress,
  933. status: operation.status,
  934. error: operation.error
  935. });
  936. boardOperationProgress.set(progressMap);
  937. }
  938. /**
  939. * Copy board operation
  940. */
  941. async copyBoard(operationId, data) {
  942. const { sourceBoardId, targetBoardId, copyOptions } = data;
  943. const operation = boardOperations.get().get(operationId);
  944. // Simulate copy progress
  945. const steps = ['copying_swimlanes', 'copying_lists', 'copying_cards', 'copying_attachments', 'finalizing'];
  946. for (let i = 0; i < steps.length; i++) {
  947. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  948. this.updateBoardOperation(operationId, operation);
  949. // Simulate work
  950. await new Promise(resolve => setTimeout(resolve, 1000));
  951. }
  952. }
  953. /**
  954. * Move board operation
  955. */
  956. async moveBoard(operationId, data) {
  957. const { sourceBoardId, targetBoardId, moveOptions } = data;
  958. const operation = boardOperations.get().get(operationId);
  959. // Simulate move progress
  960. const steps = ['preparing_move', 'moving_swimlanes', 'moving_lists', 'moving_cards', 'updating_references', 'finalizing'];
  961. for (let i = 0; i < steps.length; i++) {
  962. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  963. this.updateBoardOperation(operationId, operation);
  964. // Simulate work
  965. await new Promise(resolve => setTimeout(resolve, 800));
  966. }
  967. }
  968. /**
  969. * Copy swimlane operation
  970. */
  971. async copySwimlane(operationId, data) {
  972. const { sourceSwimlaneId, targetBoardId, copyOptions } = data;
  973. const operation = boardOperations.get().get(operationId);
  974. // Simulate copy progress
  975. const steps = ['copying_swimlane', 'copying_lists', 'copying_cards', 'finalizing'];
  976. for (let i = 0; i < steps.length; i++) {
  977. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  978. this.updateBoardOperation(operationId, operation);
  979. // Simulate work
  980. await new Promise(resolve => setTimeout(resolve, 500));
  981. }
  982. }
  983. /**
  984. * Move swimlane operation
  985. */
  986. async moveSwimlane(operationId, data) {
  987. const { sourceSwimlaneId, targetBoardId, moveOptions } = data;
  988. const operation = boardOperations.get().get(operationId);
  989. // Simulate move progress
  990. const steps = ['preparing_move', 'moving_swimlane', 'updating_references', 'finalizing'];
  991. for (let i = 0; i < steps.length; i++) {
  992. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  993. this.updateBoardOperation(operationId, operation);
  994. // Simulate work
  995. await new Promise(resolve => setTimeout(resolve, 400));
  996. }
  997. }
  998. /**
  999. * Copy list operation
  1000. */
  1001. async copyList(operationId, data) {
  1002. const { sourceListId, targetBoardId, copyOptions } = data;
  1003. const operation = boardOperations.get().get(operationId);
  1004. // Simulate copy progress
  1005. const steps = ['copying_list', 'copying_cards', 'copying_attachments', 'finalizing'];
  1006. for (let i = 0; i < steps.length; i++) {
  1007. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1008. this.updateBoardOperation(operationId, operation);
  1009. // Simulate work
  1010. await new Promise(resolve => setTimeout(resolve, 300));
  1011. }
  1012. }
  1013. /**
  1014. * Move list operation
  1015. */
  1016. async moveList(operationId, data) {
  1017. const { sourceListId, targetBoardId, moveOptions } = data;
  1018. const operation = boardOperations.get().get(operationId);
  1019. // Simulate move progress
  1020. const steps = ['preparing_move', 'moving_list', 'updating_references', 'finalizing'];
  1021. for (let i = 0; i < steps.length; i++) {
  1022. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1023. this.updateBoardOperation(operationId, operation);
  1024. // Simulate work
  1025. await new Promise(resolve => setTimeout(resolve, 200));
  1026. }
  1027. }
  1028. /**
  1029. * Copy card operation
  1030. */
  1031. async copyCard(operationId, data) {
  1032. const { sourceCardId, targetListId, copyOptions } = data;
  1033. const operation = boardOperations.get().get(operationId);
  1034. // Simulate copy progress
  1035. const steps = ['copying_card', 'copying_attachments', 'copying_checklists', 'finalizing'];
  1036. for (let i = 0; i < steps.length; i++) {
  1037. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1038. this.updateBoardOperation(operationId, operation);
  1039. // Simulate work
  1040. await new Promise(resolve => setTimeout(resolve, 150));
  1041. }
  1042. }
  1043. /**
  1044. * Move card operation
  1045. */
  1046. async moveCard(operationId, data) {
  1047. const { sourceCardId, targetListId, moveOptions } = data;
  1048. const operation = boardOperations.get().get(operationId);
  1049. // Simulate move progress
  1050. const steps = ['preparing_move', 'moving_card', 'updating_references', 'finalizing'];
  1051. for (let i = 0; i < steps.length; i++) {
  1052. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1053. this.updateBoardOperation(operationId, operation);
  1054. // Simulate work
  1055. await new Promise(resolve => setTimeout(resolve, 100));
  1056. }
  1057. }
  1058. /**
  1059. * Copy checklist operation
  1060. */
  1061. async copyChecklist(operationId, data) {
  1062. const { sourceChecklistId, targetCardId, copyOptions } = data;
  1063. const operation = boardOperations.get().get(operationId);
  1064. // Simulate copy progress
  1065. const steps = ['copying_checklist', 'copying_items', 'finalizing'];
  1066. for (let i = 0; i < steps.length; i++) {
  1067. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1068. this.updateBoardOperation(operationId, operation);
  1069. // Simulate work
  1070. await new Promise(resolve => setTimeout(resolve, 100));
  1071. }
  1072. }
  1073. /**
  1074. * Move checklist operation
  1075. */
  1076. async moveChecklist(operationId, data) {
  1077. const { sourceChecklistId, targetCardId, moveOptions } = data;
  1078. const operation = boardOperations.get().get(operationId);
  1079. // Simulate move progress
  1080. const steps = ['preparing_move', 'moving_checklist', 'finalizing'];
  1081. for (let i = 0; i < steps.length; i++) {
  1082. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1083. this.updateBoardOperation(operationId, operation);
  1084. // Simulate work
  1085. await new Promise(resolve => setTimeout(resolve, 50));
  1086. }
  1087. }
  1088. /**
  1089. * Get board operations for a specific board
  1090. */
  1091. getBoardOperations(boardId) {
  1092. const operations = boardOperations.get();
  1093. const boardOps = [];
  1094. for (const [operationId, operation] of operations) {
  1095. if (operation.boardId === boardId) {
  1096. boardOps.push(operation);
  1097. }
  1098. }
  1099. return boardOps.sort((a, b) => b.startTime - a.startTime);
  1100. }
  1101. /**
  1102. * Get all board operations with pagination
  1103. */
  1104. getAllBoardOperations(page = 1, limit = 20, searchTerm = '') {
  1105. const operations = boardOperations.get();
  1106. const allOps = Array.from(operations.values());
  1107. // Filter by search term if provided
  1108. let filteredOps = allOps;
  1109. if (searchTerm) {
  1110. filteredOps = allOps.filter(op =>
  1111. op.boardId.toLowerCase().includes(searchTerm.toLowerCase()) ||
  1112. op.type.toLowerCase().includes(searchTerm.toLowerCase())
  1113. );
  1114. }
  1115. // Sort by start time (newest first)
  1116. filteredOps.sort((a, b) => b.startTime - a.startTime);
  1117. // Paginate
  1118. const startIndex = (page - 1) * limit;
  1119. const endIndex = startIndex + limit;
  1120. const paginatedOps = filteredOps.slice(startIndex, endIndex);
  1121. return {
  1122. operations: paginatedOps,
  1123. total: filteredOps.length,
  1124. page: page,
  1125. limit: limit,
  1126. totalPages: Math.ceil(filteredOps.length / limit)
  1127. };
  1128. }
  1129. /**
  1130. * Get board operation statistics
  1131. */
  1132. getBoardOperationStats() {
  1133. const operations = boardOperations.get();
  1134. const stats = {
  1135. total: operations.size,
  1136. running: 0,
  1137. completed: 0,
  1138. error: 0,
  1139. byType: {}
  1140. };
  1141. for (const [operationId, operation] of operations) {
  1142. stats[operation.status]++;
  1143. if (!stats.byType[operation.type]) {
  1144. stats.byType[operation.type] = 0;
  1145. }
  1146. stats.byType[operation.type]++;
  1147. }
  1148. return stats;
  1149. }
  1150. /**
  1151. * Clear all cron jobs and restart migration system
  1152. */
  1153. clearAllCronJobs() {
  1154. try {
  1155. // Stop all existing cron jobs
  1156. if (SyncedCron && SyncedCron.jobs) {
  1157. SyncedCron.jobs.forEach(job => {
  1158. try {
  1159. SyncedCron.remove(job.name);
  1160. } catch (error) {
  1161. console.warn(`Failed to remove cron job ${job.name}:`, error.message);
  1162. }
  1163. });
  1164. }
  1165. // Clear job storage
  1166. cronJobStorage.clearAllJobs();
  1167. // Reset migration steps
  1168. this.migrationSteps = this.initializeMigrationSteps();
  1169. this.currentStepIndex = 0;
  1170. this.isRunning = false;
  1171. // Restart the migration system
  1172. this.initialize();
  1173. console.log('All cron jobs cleared and migration system restarted');
  1174. return { success: true, message: 'All cron jobs cleared and migration system restarted' };
  1175. } catch (error) {
  1176. console.error('Error clearing cron jobs:', error);
  1177. return { success: false, error: error.message };
  1178. }
  1179. }
  1180. }
  1181. // Export singleton instance
  1182. export const cronMigrationManager = new CronMigrationManager();
  1183. // Initialize cron jobs on server start
  1184. Meteor.startup(() => {
  1185. cronMigrationManager.initializeCronJobs();
  1186. });
  1187. // Meteor methods for client-server communication
  1188. Meteor.methods({
  1189. 'cron.startAllMigrations'() {
  1190. if (!this.userId) {
  1191. throw new Meteor.Error('not-authorized');
  1192. }
  1193. return cronMigrationManager.startAllMigrations();
  1194. },
  1195. 'cron.startJob'(cronName) {
  1196. if (!this.userId) {
  1197. throw new Meteor.Error('not-authorized');
  1198. }
  1199. return cronMigrationManager.startCronJob(cronName);
  1200. },
  1201. 'cron.stopJob'(cronName) {
  1202. if (!this.userId) {
  1203. throw new Meteor.Error('not-authorized');
  1204. }
  1205. return cronMigrationManager.stopCronJob(cronName);
  1206. },
  1207. 'cron.pauseJob'(cronName) {
  1208. if (!this.userId) {
  1209. throw new Meteor.Error('not-authorized');
  1210. }
  1211. return cronMigrationManager.pauseCronJob(cronName);
  1212. },
  1213. 'cron.resumeJob'(cronName) {
  1214. if (!this.userId) {
  1215. throw new Meteor.Error('not-authorized');
  1216. }
  1217. return cronMigrationManager.resumeCronJob(cronName);
  1218. },
  1219. 'cron.removeJob'(cronName) {
  1220. if (!this.userId) {
  1221. throw new Meteor.Error('not-authorized');
  1222. }
  1223. return cronMigrationManager.removeCronJob(cronName);
  1224. },
  1225. 'cron.addJob'(jobData) {
  1226. if (!this.userId) {
  1227. throw new Meteor.Error('not-authorized');
  1228. }
  1229. return cronMigrationManager.addCronJob(jobData);
  1230. },
  1231. 'cron.getJobs'() {
  1232. return cronMigrationManager.getAllCronJobs();
  1233. },
  1234. 'cron.getMigrationProgress'() {
  1235. return {
  1236. progress: cronMigrationProgress.get(),
  1237. status: cronMigrationStatus.get(),
  1238. currentStep: cronMigrationCurrentStep.get(),
  1239. steps: cronMigrationSteps.get(),
  1240. isMigrating: cronIsMigrating.get()
  1241. };
  1242. },
  1243. 'cron.startBoardOperation'(boardId, operationType, operationData) {
  1244. if (!this.userId) {
  1245. throw new Meteor.Error('not-authorized');
  1246. }
  1247. return cronMigrationManager.startBoardOperation(boardId, operationType, operationData);
  1248. },
  1249. 'cron.getBoardOperations'(boardId) {
  1250. if (!this.userId) {
  1251. throw new Meteor.Error('not-authorized');
  1252. }
  1253. return cronMigrationManager.getBoardOperations(boardId);
  1254. },
  1255. 'cron.getAllBoardOperations'(page, limit, searchTerm) {
  1256. if (!this.userId) {
  1257. throw new Meteor.Error('not-authorized');
  1258. }
  1259. return cronMigrationManager.getAllBoardOperations(page, limit, searchTerm);
  1260. },
  1261. 'cron.getBoardOperationStats'() {
  1262. if (!this.userId) {
  1263. throw new Meteor.Error('not-authorized');
  1264. }
  1265. return cronMigrationManager.getBoardOperationStats();
  1266. },
  1267. 'cron.getJobDetails'(jobId) {
  1268. if (!this.userId) {
  1269. throw new Meteor.Error('not-authorized');
  1270. }
  1271. return cronJobStorage.getJobDetails(jobId);
  1272. },
  1273. 'cron.getQueueStats'() {
  1274. if (!this.userId) {
  1275. throw new Meteor.Error('not-authorized');
  1276. }
  1277. return cronJobStorage.getQueueStats();
  1278. },
  1279. 'cron.getSystemResources'() {
  1280. if (!this.userId) {
  1281. throw new Meteor.Error('not-authorized');
  1282. }
  1283. return cronJobStorage.getSystemResources();
  1284. },
  1285. 'cron.clearAllJobs'() {
  1286. if (!this.userId) {
  1287. throw new Meteor.Error('not-authorized');
  1288. }
  1289. return cronMigrationManager.clearAllCronJobs();
  1290. },
  1291. 'cron.pauseJob'(jobId) {
  1292. if (!this.userId) {
  1293. throw new Meteor.Error('not-authorized');
  1294. }
  1295. cronJobStorage.updateQueueStatus(jobId, 'paused');
  1296. cronJobStorage.saveJobStatus(jobId, { status: 'paused' });
  1297. return { success: true };
  1298. },
  1299. 'cron.resumeJob'(jobId) {
  1300. if (!this.userId) {
  1301. throw new Meteor.Error('not-authorized');
  1302. }
  1303. cronJobStorage.updateQueueStatus(jobId, 'pending');
  1304. cronJobStorage.saveJobStatus(jobId, { status: 'pending' });
  1305. return { success: true };
  1306. },
  1307. 'cron.stopJob'(jobId) {
  1308. if (!this.userId) {
  1309. throw new Meteor.Error('not-authorized');
  1310. }
  1311. cronJobStorage.updateQueueStatus(jobId, 'stopped');
  1312. cronJobStorage.saveJobStatus(jobId, {
  1313. status: 'stopped',
  1314. stoppedAt: new Date()
  1315. });
  1316. return { success: true };
  1317. },
  1318. 'cron.cleanupOldJobs'(daysOld) {
  1319. if (!this.userId) {
  1320. throw new Meteor.Error('not-authorized');
  1321. }
  1322. return cronJobStorage.cleanupOldJobs(daysOld);
  1323. },
  1324. 'cron.getBoardMigrationStats'() {
  1325. if (!this.userId) {
  1326. throw new Meteor.Error('not-authorized');
  1327. }
  1328. // Import the board migration detector
  1329. const { boardMigrationDetector } = require('./boardMigrationDetector');
  1330. return boardMigrationDetector.getMigrationStats();
  1331. },
  1332. 'cron.forceBoardMigrationScan'() {
  1333. if (!this.userId) {
  1334. throw new Meteor.Error('not-authorized');
  1335. }
  1336. // Import the board migration detector
  1337. const { boardMigrationDetector } = require('./boardMigrationDetector');
  1338. return boardMigrationDetector.forceScan();
  1339. },
  1340. });