cronMigrationManager.js 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  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. id: 'restore-legacy-lists',
  233. name: 'Restore Legacy Lists',
  234. description: 'Restore legacy lists to their original shared state across all swimlanes',
  235. weight: 3,
  236. completed: false,
  237. progress: 0,
  238. cronName: 'migration_restore_legacy_lists',
  239. schedule: 'every 1 minute',
  240. status: 'stopped'
  241. }
  242. ];
  243. }
  244. /**
  245. * Initialize all migration cron jobs
  246. */
  247. initializeCronJobs() {
  248. this.migrationSteps.forEach(step => {
  249. this.createCronJob(step);
  250. });
  251. // Start job processor
  252. this.startJobProcessor();
  253. // Update cron jobs list after a short delay to allow SyncedCron to initialize
  254. Meteor.setTimeout(() => {
  255. this.updateCronJobsList();
  256. }, 1000);
  257. }
  258. /**
  259. * Start the job processor for CPU-aware job execution
  260. */
  261. startJobProcessor() {
  262. if (this.processingInterval) {
  263. return; // Already running
  264. }
  265. this.processingInterval = Meteor.setInterval(() => {
  266. this.processJobQueue();
  267. }, 5000); // Check every 5 seconds
  268. // Cron job processor started with CPU throttling
  269. }
  270. /**
  271. * Stop the job processor
  272. */
  273. stopJobProcessor() {
  274. if (this.processingInterval) {
  275. Meteor.clearInterval(this.processingInterval);
  276. this.processingInterval = null;
  277. }
  278. }
  279. /**
  280. * Process the job queue with CPU throttling
  281. */
  282. async processJobQueue() {
  283. const canStart = cronJobStorage.canStartNewJob();
  284. if (!canStart.canStart) {
  285. // Suppress "Cannot start new job: Maximum concurrent jobs reached" message
  286. // console.log(`Cannot start new job: ${canStart.reason}`);
  287. return;
  288. }
  289. const nextJob = cronJobStorage.getNextJob();
  290. if (!nextJob) {
  291. return; // No jobs in queue
  292. }
  293. // Start the job
  294. await this.executeJob(nextJob);
  295. }
  296. /**
  297. * Execute a job from the queue
  298. */
  299. async executeJob(queueJob) {
  300. const { jobId, jobType, jobData } = queueJob;
  301. try {
  302. // Update queue status to running
  303. cronJobStorage.updateQueueStatus(jobId, 'running', { startedAt: new Date() });
  304. // Save job status
  305. cronJobStorage.saveJobStatus(jobId, {
  306. jobType,
  307. status: 'running',
  308. progress: 0,
  309. startedAt: new Date(),
  310. ...jobData
  311. });
  312. // Execute based on job type
  313. if (jobType === 'migration') {
  314. await this.executeMigrationJob(jobId, jobData);
  315. } else if (jobType === 'board_operation') {
  316. await this.executeBoardOperationJob(jobId, jobData);
  317. } else if (jobType === 'board_migration') {
  318. await this.executeBoardMigrationJob(jobId, jobData);
  319. } else {
  320. throw new Error(`Unknown job type: ${jobType}`);
  321. }
  322. // Mark as completed
  323. cronJobStorage.updateQueueStatus(jobId, 'completed', { completedAt: new Date() });
  324. cronJobStorage.saveJobStatus(jobId, {
  325. status: 'completed',
  326. progress: 100,
  327. completedAt: new Date()
  328. });
  329. } catch (error) {
  330. console.error(`Job ${jobId} failed:`, error);
  331. // Mark as failed
  332. cronJobStorage.updateQueueStatus(jobId, 'failed', {
  333. failedAt: new Date(),
  334. error: error.message
  335. });
  336. cronJobStorage.saveJobStatus(jobId, {
  337. status: 'failed',
  338. error: error.message,
  339. failedAt: new Date()
  340. });
  341. }
  342. }
  343. /**
  344. * Execute a migration job
  345. */
  346. async executeMigrationJob(jobId, jobData) {
  347. if (!jobData) {
  348. throw new Error('Job data is required for migration execution');
  349. }
  350. const { stepId } = jobData;
  351. if (!stepId) {
  352. throw new Error('Step ID is required in job data');
  353. }
  354. const step = this.migrationSteps.find(s => s.id === stepId);
  355. if (!step) {
  356. throw new Error(`Migration step ${stepId} not found`);
  357. }
  358. // Create steps for this migration
  359. const steps = this.createMigrationSteps(step);
  360. for (let i = 0; i < steps.length; i++) {
  361. const stepData = steps[i];
  362. // Save step status
  363. cronJobStorage.saveJobStep(jobId, i, {
  364. stepName: stepData.name,
  365. status: 'running',
  366. progress: 0
  367. });
  368. // Execute step
  369. await this.executeMigrationStep(jobId, i, stepData, stepId);
  370. // Mark step as completed
  371. cronJobStorage.saveJobStep(jobId, i, {
  372. status: 'completed',
  373. progress: 100,
  374. completedAt: new Date()
  375. });
  376. // Update overall progress
  377. const progress = Math.round(((i + 1) / steps.length) * 100);
  378. cronJobStorage.saveJobStatus(jobId, { progress });
  379. }
  380. }
  381. /**
  382. * Create migration steps for a job
  383. */
  384. createMigrationSteps(step) {
  385. const steps = [];
  386. switch (step.id) {
  387. case 'board-background-color':
  388. steps.push(
  389. { name: 'Initialize board colors', duration: 1000 },
  390. { name: 'Update board documents', duration: 2000 },
  391. { name: 'Finalize changes', duration: 500 }
  392. );
  393. break;
  394. case 'add-cardcounterlist-allowed':
  395. steps.push(
  396. { name: 'Add card counter permissions', duration: 800 },
  397. { name: 'Update existing boards', duration: 1500 },
  398. { name: 'Verify permissions', duration: 700 }
  399. );
  400. break;
  401. case 'migrate-attachments-collectionFS-to-ostrioFiles':
  402. steps.push(
  403. { name: 'Scan CollectionFS attachments', duration: 2000 },
  404. { name: 'Create Meteor-Files records', duration: 3000 },
  405. { name: 'Migrate file data', duration: 5000 },
  406. { name: 'Update references', duration: 2000 },
  407. { name: 'Cleanup old data', duration: 1000 }
  408. );
  409. break;
  410. case 'restore-legacy-lists':
  411. steps.push(
  412. { name: 'Identify legacy lists', duration: 1000 },
  413. { name: 'Restore lists to shared state', duration: 2000 },
  414. { name: 'Update board settings', duration: 500 },
  415. { name: 'Verify restoration', duration: 500 }
  416. );
  417. break;
  418. default:
  419. steps.push(
  420. { name: `Execute ${step.name}`, duration: 2000 },
  421. { name: 'Verify changes', duration: 1000 }
  422. );
  423. }
  424. return steps;
  425. }
  426. /**
  427. * Execute a migration step
  428. */
  429. async executeMigrationStep(jobId, stepIndex, stepData, stepId) {
  430. const { name, duration } = stepData;
  431. if (stepId === 'restore-legacy-lists') {
  432. await this.executeRestoreLegacyListsMigration(jobId, stepIndex, stepData);
  433. } else {
  434. // Simulate step execution with progress updates for other migrations
  435. const progressSteps = 10;
  436. for (let i = 0; i <= progressSteps; i++) {
  437. const progress = Math.round((i / progressSteps) * 100);
  438. // Update step progress
  439. cronJobStorage.saveJobStep(jobId, stepIndex, {
  440. progress,
  441. currentAction: `Executing: ${name} (${progress}%)`
  442. });
  443. // Simulate work
  444. await new Promise(resolve => setTimeout(resolve, duration / progressSteps));
  445. }
  446. }
  447. }
  448. /**
  449. * Execute the restore legacy lists migration
  450. */
  451. async executeRestoreLegacyListsMigration(jobId, stepIndex, stepData) {
  452. const { name } = stepData;
  453. try {
  454. // Import collections directly for server-side access
  455. const { default: Boards } = await import('/models/boards');
  456. const { default: Lists } = await import('/models/lists');
  457. // Step 1: Identify legacy lists
  458. cronJobStorage.saveJobStep(jobId, stepIndex, {
  459. progress: 25,
  460. currentAction: 'Identifying legacy lists...'
  461. });
  462. const boards = Boards.find({}).fetch();
  463. const migrationDate = new Date('2025-10-10T21:14:44.000Z'); // Date of commit 719ef87efceacfe91461a8eeca7cf74d11f4cc0a
  464. let totalLegacyLists = 0;
  465. for (const board of boards) {
  466. const allLists = Lists.find({ boardId: board._id }).fetch();
  467. const legacyLists = allLists.filter(list => {
  468. const listDate = list.createdAt || new Date(0);
  469. return listDate < migrationDate && list.swimlaneId && list.swimlaneId !== '';
  470. });
  471. totalLegacyLists += legacyLists.length;
  472. }
  473. // Step 2: Restore lists to shared state
  474. cronJobStorage.saveJobStep(jobId, stepIndex, {
  475. progress: 50,
  476. currentAction: 'Restoring lists to shared state...'
  477. });
  478. let restoredCount = 0;
  479. for (const board of boards) {
  480. const allLists = Lists.find({ boardId: board._id }).fetch();
  481. const legacyLists = allLists.filter(list => {
  482. const listDate = list.createdAt || new Date(0);
  483. return listDate < migrationDate && list.swimlaneId && list.swimlaneId !== '';
  484. });
  485. // Restore legacy lists to shared state (empty swimlaneId)
  486. for (const list of legacyLists) {
  487. Lists.direct.update(list._id, {
  488. $set: {
  489. swimlaneId: ''
  490. }
  491. });
  492. restoredCount++;
  493. }
  494. // Mark the board as having legacy lists
  495. if (legacyLists.length > 0) {
  496. Boards.direct.update(board._id, {
  497. $set: {
  498. hasLegacyLists: true
  499. }
  500. });
  501. }
  502. }
  503. // Step 3: Update board settings
  504. cronJobStorage.saveJobStep(jobId, stepIndex, {
  505. progress: 75,
  506. currentAction: 'Updating board settings...'
  507. });
  508. // Step 4: Verify restoration
  509. cronJobStorage.saveJobStep(jobId, stepIndex, {
  510. progress: 100,
  511. currentAction: `Verification complete. Restored ${restoredCount} legacy lists.`
  512. });
  513. console.log(`Successfully restored ${restoredCount} legacy lists across ${boards.length} boards`);
  514. } catch (error) {
  515. console.error('Error during restore legacy lists migration:', error);
  516. cronJobStorage.saveJobStep(jobId, stepIndex, {
  517. progress: 0,
  518. currentAction: `Error: ${error.message}`,
  519. status: 'error'
  520. });
  521. throw error;
  522. }
  523. }
  524. /**
  525. * Execute a board operation job
  526. */
  527. async executeBoardOperationJob(jobId, jobData) {
  528. const { operationType, operationData } = jobData;
  529. // Use existing board operation logic
  530. await this.executeBoardOperation(jobId, operationType, operationData);
  531. }
  532. /**
  533. * Execute a board migration job
  534. */
  535. async executeBoardMigrationJob(jobId, jobData) {
  536. const { boardId, boardTitle, migrationType } = jobData;
  537. try {
  538. // Starting board migration
  539. // Create migration steps for this board
  540. const steps = this.createBoardMigrationSteps(boardId, migrationType);
  541. for (let i = 0; i < steps.length; i++) {
  542. const stepData = steps[i];
  543. // Save step status
  544. cronJobStorage.saveJobStep(jobId, i, {
  545. stepName: stepData.name,
  546. status: 'running',
  547. progress: 0,
  548. boardId: boardId
  549. });
  550. // Execute step
  551. await this.executeBoardMigrationStep(jobId, i, stepData, boardId);
  552. // Mark step as completed
  553. cronJobStorage.saveJobStep(jobId, i, {
  554. status: 'completed',
  555. progress: 100,
  556. completedAt: new Date()
  557. });
  558. // Update overall progress
  559. const progress = Math.round(((i + 1) / steps.length) * 100);
  560. cronJobStorage.saveJobStatus(jobId, { progress });
  561. }
  562. // Mark board as migrated
  563. this.markBoardAsMigrated(boardId, migrationType);
  564. // Completed board migration
  565. } catch (error) {
  566. console.error(`Board migration failed for ${boardId}:`, error);
  567. throw error;
  568. }
  569. }
  570. /**
  571. * Create migration steps for a board
  572. */
  573. createBoardMigrationSteps(boardId, migrationType) {
  574. const steps = [];
  575. if (migrationType === 'full_board_migration') {
  576. steps.push(
  577. { name: 'Check board structure', duration: 500, type: 'validation' },
  578. { name: 'Migrate lists to swimlanes', duration: 2000, type: 'lists' },
  579. { name: 'Migrate attachments', duration: 3000, type: 'attachments' },
  580. { name: 'Update board metadata', duration: 1000, type: 'metadata' },
  581. { name: 'Verify migration', duration: 1000, type: 'verification' }
  582. );
  583. } else {
  584. // Default migration steps
  585. steps.push(
  586. { name: 'Initialize board migration', duration: 1000, type: 'init' },
  587. { name: 'Execute migration', duration: 2000, type: 'migration' },
  588. { name: 'Finalize changes', duration: 1000, type: 'finalize' }
  589. );
  590. }
  591. return steps;
  592. }
  593. /**
  594. * Execute a board migration step
  595. */
  596. async executeBoardMigrationStep(jobId, stepIndex, stepData, boardId) {
  597. const { name, duration, type } = stepData;
  598. // Simulate step execution with progress updates
  599. const progressSteps = 10;
  600. for (let i = 0; i <= progressSteps; i++) {
  601. const progress = Math.round((i / progressSteps) * 100);
  602. // Update step progress
  603. cronJobStorage.saveJobStep(jobId, stepIndex, {
  604. progress,
  605. currentAction: `Executing: ${name} (${progress}%)`
  606. });
  607. // Simulate work based on step type
  608. await this.simulateBoardMigrationWork(type, duration / progressSteps);
  609. }
  610. }
  611. /**
  612. * Simulate board migration work
  613. */
  614. async simulateBoardMigrationWork(stepType, duration) {
  615. // Simulate different types of migration work
  616. switch (stepType) {
  617. case 'validation':
  618. // Quick validation
  619. await new Promise(resolve => setTimeout(resolve, duration * 0.5));
  620. break;
  621. case 'lists':
  622. // List migration work
  623. await new Promise(resolve => setTimeout(resolve, duration));
  624. break;
  625. case 'attachments':
  626. // Attachment migration work
  627. await new Promise(resolve => setTimeout(resolve, duration * 1.2));
  628. break;
  629. case 'metadata':
  630. // Metadata update work
  631. await new Promise(resolve => setTimeout(resolve, duration * 0.8));
  632. break;
  633. case 'verification':
  634. // Verification work
  635. await new Promise(resolve => setTimeout(resolve, duration * 0.6));
  636. break;
  637. default:
  638. // Default work
  639. await new Promise(resolve => setTimeout(resolve, duration));
  640. }
  641. }
  642. /**
  643. * Mark a board as migrated
  644. */
  645. markBoardAsMigrated(boardId, migrationType) {
  646. try {
  647. // Update board with migration markers
  648. const updateQuery = {
  649. 'migrationMarkers.fullMigrationCompleted': true,
  650. 'migrationMarkers.lastMigration': new Date(),
  651. 'migrationMarkers.migrationType': migrationType
  652. };
  653. // Update the board document
  654. if (typeof Boards !== 'undefined') {
  655. Boards.update(boardId, { $set: updateQuery });
  656. }
  657. console.log(`Marked board ${boardId} as migrated`);
  658. } catch (error) {
  659. console.error(`Error marking board ${boardId} as migrated:`, error);
  660. }
  661. }
  662. /**
  663. * Create a cron job for a migration step
  664. */
  665. createCronJob(step) {
  666. SyncedCron.add({
  667. name: step.cronName,
  668. schedule: (parser) => parser.text(step.schedule),
  669. job: () => {
  670. this.runMigrationStep(step);
  671. },
  672. });
  673. }
  674. /**
  675. * Run a migration step
  676. */
  677. async runMigrationStep(step) {
  678. try {
  679. // Starting migration step
  680. cronMigrationCurrentStep.set(step.name);
  681. cronMigrationStatus.set(`Running: ${step.description}`);
  682. cronIsMigrating.set(true);
  683. // Simulate migration progress
  684. const progressSteps = 10;
  685. for (let i = 0; i <= progressSteps; i++) {
  686. step.progress = (i / progressSteps) * 100;
  687. this.updateProgress();
  688. // Simulate work
  689. await new Promise(resolve => setTimeout(resolve, 100));
  690. }
  691. // Mark as completed
  692. step.completed = true;
  693. step.progress = 100;
  694. step.status = 'completed';
  695. // Completed migration step
  696. // Update progress
  697. this.updateProgress();
  698. } catch (error) {
  699. console.error(`Migration ${step.name} failed:`, error);
  700. step.status = 'error';
  701. cronMigrationStatus.set(`Migration failed: ${error.message}`);
  702. }
  703. }
  704. /**
  705. * Start all migrations using job queue
  706. */
  707. async startAllMigrations() {
  708. if (this.isRunning) {
  709. return;
  710. }
  711. this.isRunning = true;
  712. cronIsMigrating.set(true);
  713. cronMigrationStatus.set('Adding migrations to job queue...');
  714. this.startTime = Date.now();
  715. try {
  716. // Add all migration steps to the job queue
  717. for (let i = 0; i < this.migrationSteps.length; i++) {
  718. const step = this.migrationSteps[i];
  719. if (step.completed) {
  720. continue; // Skip already completed steps
  721. }
  722. // Add to job queue
  723. const jobId = `migration_${step.id}_${Date.now()}`;
  724. cronJobStorage.addToQueue(jobId, 'migration', step.weight, {
  725. stepId: step.id,
  726. stepName: step.name,
  727. stepDescription: step.description
  728. });
  729. // Save initial job status
  730. cronJobStorage.saveJobStatus(jobId, {
  731. jobType: 'migration',
  732. status: 'pending',
  733. progress: 0,
  734. stepId: step.id,
  735. stepName: step.name,
  736. stepDescription: step.description
  737. });
  738. }
  739. cronMigrationStatus.set('Migrations added to queue. Processing will begin shortly...');
  740. // Start monitoring progress
  741. this.monitorMigrationProgress();
  742. } catch (error) {
  743. console.error('Failed to start migrations:', error);
  744. cronMigrationStatus.set(`Failed to start migrations: ${error.message}`);
  745. cronIsMigrating.set(false);
  746. this.isRunning = false;
  747. }
  748. }
  749. /**
  750. * Monitor migration progress
  751. */
  752. monitorMigrationProgress() {
  753. const monitorInterval = Meteor.setInterval(() => {
  754. const stats = cronJobStorage.getQueueStats();
  755. const incompleteJobs = cronJobStorage.getIncompleteJobs();
  756. // Update progress
  757. const totalJobs = stats.total;
  758. const completedJobs = stats.completed;
  759. const progress = totalJobs > 0 ? Math.round((completedJobs / totalJobs) * 100) : 0;
  760. cronMigrationProgress.set(progress);
  761. // Update status
  762. if (stats.running > 0) {
  763. const runningJob = incompleteJobs.find(job => job.status === 'running');
  764. if (runningJob) {
  765. cronMigrationCurrentStep.set(runningJob.stepName || 'Processing migration...');
  766. cronMigrationStatus.set(`Running: ${runningJob.stepName || 'Migration in progress'}`);
  767. }
  768. } else if (stats.pending > 0) {
  769. cronMigrationStatus.set(`${stats.pending} migrations pending in queue`);
  770. cronMigrationCurrentStep.set('Waiting for available resources...');
  771. } else if (stats.completed === totalJobs && totalJobs > 0) {
  772. // All migrations completed
  773. cronMigrationStatus.set('All migrations completed successfully!');
  774. cronMigrationProgress.set(100);
  775. cronMigrationCurrentStep.set('');
  776. // Clear status after delay
  777. setTimeout(() => {
  778. cronIsMigrating.set(false);
  779. cronMigrationStatus.set('');
  780. cronMigrationProgress.set(0);
  781. }, 3000);
  782. Meteor.clearInterval(monitorInterval);
  783. }
  784. }, 2000); // Check every 2 seconds
  785. }
  786. /**
  787. * Start a specific cron job
  788. */
  789. async startCronJob(cronName) {
  790. // Change schedule to run once
  791. const job = SyncedCron.jobs.find(j => j.name === cronName);
  792. if (job) {
  793. job.schedule = 'once';
  794. SyncedCron.start();
  795. }
  796. }
  797. /**
  798. * Wait for a cron job to complete
  799. */
  800. async waitForCronJobCompletion(step) {
  801. return new Promise((resolve) => {
  802. const checkInterval = setInterval(() => {
  803. if (step.completed || step.status === 'error') {
  804. clearInterval(checkInterval);
  805. resolve();
  806. }
  807. }, 1000);
  808. });
  809. }
  810. /**
  811. * Stop a specific cron job
  812. */
  813. stopCronJob(cronName) {
  814. SyncedCron.remove(cronName);
  815. const step = this.migrationSteps.find(s => s.cronName === cronName);
  816. if (step) {
  817. step.status = 'stopped';
  818. }
  819. this.updateCronJobsList();
  820. }
  821. /**
  822. * Pause a specific cron job
  823. */
  824. pauseCronJob(cronName) {
  825. SyncedCron.pause(cronName);
  826. const step = this.migrationSteps.find(s => s.cronName === cronName);
  827. if (step) {
  828. step.status = 'paused';
  829. }
  830. this.updateCronJobsList();
  831. }
  832. /**
  833. * Resume a specific cron job
  834. */
  835. resumeCronJob(cronName) {
  836. SyncedCron.resume(cronName);
  837. const step = this.migrationSteps.find(s => s.cronName === cronName);
  838. if (step) {
  839. step.status = 'running';
  840. }
  841. this.updateCronJobsList();
  842. }
  843. /**
  844. * Remove a cron job
  845. */
  846. removeCronJob(cronName) {
  847. SyncedCron.remove(cronName);
  848. this.migrationSteps = this.migrationSteps.filter(s => s.cronName !== cronName);
  849. this.updateCronJobsList();
  850. }
  851. /**
  852. * Add a new cron job
  853. */
  854. addCronJob(jobData) {
  855. const step = {
  856. id: jobData.id || `custom_${Date.now()}`,
  857. name: jobData.name,
  858. description: jobData.description,
  859. weight: jobData.weight || 1,
  860. completed: false,
  861. progress: 0,
  862. cronName: jobData.cronName || `custom_${Date.now()}`,
  863. schedule: jobData.schedule || 'every 1 minute',
  864. status: 'stopped'
  865. };
  866. this.migrationSteps.push(step);
  867. this.createCronJob(step);
  868. this.updateCronJobsList();
  869. }
  870. /**
  871. * Update progress variables
  872. */
  873. updateProgress() {
  874. const totalWeight = this.migrationSteps.reduce((total, step) => total + step.weight, 0);
  875. const completedWeight = this.migrationSteps.reduce((total, step) => {
  876. return total + (step.completed ? step.weight : step.progress * step.weight / 100);
  877. }, 0);
  878. const progress = Math.round((completedWeight / totalWeight) * 100);
  879. cronMigrationProgress.set(progress);
  880. cronMigrationSteps.set([...this.migrationSteps]);
  881. }
  882. /**
  883. * Update cron jobs list
  884. */
  885. updateCronJobsList() {
  886. // Check if SyncedCron is available and has jobs
  887. if (!SyncedCron || !SyncedCron.jobs || !Array.isArray(SyncedCron.jobs)) {
  888. // SyncedCron not available or no jobs yet
  889. cronJobs.set([]);
  890. return;
  891. }
  892. const jobs = SyncedCron.jobs.map(job => {
  893. const step = this.migrationSteps.find(s => s.cronName === job.name);
  894. return {
  895. name: job.name,
  896. schedule: job.schedule,
  897. status: step ? step.status : 'unknown',
  898. lastRun: job.lastRun,
  899. nextRun: job.nextRun,
  900. running: job.running
  901. };
  902. });
  903. cronJobs.set(jobs);
  904. }
  905. /**
  906. * Get all cron jobs
  907. */
  908. getAllCronJobs() {
  909. return cronJobs.get();
  910. }
  911. /**
  912. * Get migration steps
  913. */
  914. getMigrationSteps() {
  915. return this.migrationSteps;
  916. }
  917. /**
  918. * Start a long-running operation for a specific board
  919. */
  920. startBoardOperation(boardId, operationType, operationData) {
  921. const operationId = `${boardId}_${operationType}_${Date.now()}`;
  922. // Add to job queue
  923. cronJobStorage.addToQueue(operationId, 'board_operation', 3, {
  924. boardId,
  925. operationType,
  926. operationData
  927. });
  928. // Save initial job status
  929. cronJobStorage.saveJobStatus(operationId, {
  930. jobType: 'board_operation',
  931. status: 'pending',
  932. progress: 0,
  933. boardId,
  934. operationType,
  935. operationData,
  936. createdAt: new Date()
  937. });
  938. // Update board operations map for backward compatibility
  939. const operation = {
  940. id: operationId,
  941. boardId: boardId,
  942. type: operationType,
  943. data: operationData,
  944. status: 'pending',
  945. progress: 0,
  946. startTime: new Date(),
  947. endTime: null,
  948. error: null
  949. };
  950. const operations = boardOperations.get();
  951. operations.set(operationId, operation);
  952. boardOperations.set(operations);
  953. return operationId;
  954. }
  955. /**
  956. * Execute a board operation
  957. */
  958. async executeBoardOperation(operationId, operationType, operationData) {
  959. const operations = boardOperations.get();
  960. const operation = operations.get(operationId);
  961. if (!operation) {
  962. console.error(`Operation ${operationId} not found`);
  963. return;
  964. }
  965. try {
  966. console.log(`Starting board operation: ${operationType} for board ${operation.boardId}`);
  967. // Update operation status
  968. operation.status = 'running';
  969. operation.progress = 0;
  970. this.updateBoardOperation(operationId, operation);
  971. // Execute the specific operation
  972. switch (operationType) {
  973. case 'copy_board':
  974. await this.copyBoard(operationId, operationData);
  975. break;
  976. case 'move_board':
  977. await this.moveBoard(operationId, operationData);
  978. break;
  979. case 'copy_swimlane':
  980. await this.copySwimlane(operationId, operationData);
  981. break;
  982. case 'move_swimlane':
  983. await this.moveSwimlane(operationId, operationData);
  984. break;
  985. case 'copy_list':
  986. await this.copyList(operationId, operationData);
  987. break;
  988. case 'move_list':
  989. await this.moveList(operationId, operationData);
  990. break;
  991. case 'copy_card':
  992. await this.copyCard(operationId, operationData);
  993. break;
  994. case 'move_card':
  995. await this.moveCard(operationId, operationData);
  996. break;
  997. case 'copy_checklist':
  998. await this.copyChecklist(operationId, operationData);
  999. break;
  1000. case 'move_checklist':
  1001. await this.moveChecklist(operationId, operationData);
  1002. break;
  1003. default:
  1004. throw new Error(`Unknown operation type: ${operationType}`);
  1005. }
  1006. // Mark as completed
  1007. operation.status = 'completed';
  1008. operation.progress = 100;
  1009. operation.endTime = new Date();
  1010. this.updateBoardOperation(operationId, operation);
  1011. console.log(`Completed board operation: ${operationType} for board ${operation.boardId}`);
  1012. } catch (error) {
  1013. console.error(`Board operation ${operationType} failed:`, error);
  1014. operation.status = 'error';
  1015. operation.error = error.message;
  1016. operation.endTime = new Date();
  1017. this.updateBoardOperation(operationId, operation);
  1018. }
  1019. }
  1020. /**
  1021. * Update board operation progress
  1022. */
  1023. updateBoardOperation(operationId, operation) {
  1024. const operations = boardOperations.get();
  1025. operations.set(operationId, operation);
  1026. boardOperations.set(operations);
  1027. // Update progress map
  1028. const progressMap = boardOperationProgress.get();
  1029. progressMap.set(operationId, {
  1030. progress: operation.progress,
  1031. status: operation.status,
  1032. error: operation.error
  1033. });
  1034. boardOperationProgress.set(progressMap);
  1035. }
  1036. /**
  1037. * Copy board operation
  1038. */
  1039. async copyBoard(operationId, data) {
  1040. const { sourceBoardId, targetBoardId, copyOptions } = data;
  1041. const operation = boardOperations.get().get(operationId);
  1042. // Simulate copy progress
  1043. const steps = ['copying_swimlanes', 'copying_lists', 'copying_cards', 'copying_attachments', 'finalizing'];
  1044. for (let i = 0; i < steps.length; i++) {
  1045. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1046. this.updateBoardOperation(operationId, operation);
  1047. // Simulate work
  1048. await new Promise(resolve => setTimeout(resolve, 1000));
  1049. }
  1050. }
  1051. /**
  1052. * Move board operation
  1053. */
  1054. async moveBoard(operationId, data) {
  1055. const { sourceBoardId, targetBoardId, moveOptions } = data;
  1056. const operation = boardOperations.get().get(operationId);
  1057. // Simulate move progress
  1058. const steps = ['preparing_move', 'moving_swimlanes', 'moving_lists', 'moving_cards', 'updating_references', 'finalizing'];
  1059. for (let i = 0; i < steps.length; i++) {
  1060. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1061. this.updateBoardOperation(operationId, operation);
  1062. // Simulate work
  1063. await new Promise(resolve => setTimeout(resolve, 800));
  1064. }
  1065. }
  1066. /**
  1067. * Copy swimlane operation
  1068. */
  1069. async copySwimlane(operationId, data) {
  1070. const { sourceSwimlaneId, targetBoardId, copyOptions } = data;
  1071. const operation = boardOperations.get().get(operationId);
  1072. // Simulate copy progress
  1073. const steps = ['copying_swimlane', 'copying_lists', 'copying_cards', 'finalizing'];
  1074. for (let i = 0; i < steps.length; i++) {
  1075. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1076. this.updateBoardOperation(operationId, operation);
  1077. // Simulate work
  1078. await new Promise(resolve => setTimeout(resolve, 500));
  1079. }
  1080. }
  1081. /**
  1082. * Move swimlane operation
  1083. */
  1084. async moveSwimlane(operationId, data) {
  1085. const { sourceSwimlaneId, targetBoardId, moveOptions } = data;
  1086. const operation = boardOperations.get().get(operationId);
  1087. // Simulate move progress
  1088. const steps = ['preparing_move', 'moving_swimlane', 'updating_references', 'finalizing'];
  1089. for (let i = 0; i < steps.length; i++) {
  1090. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1091. this.updateBoardOperation(operationId, operation);
  1092. // Simulate work
  1093. await new Promise(resolve => setTimeout(resolve, 400));
  1094. }
  1095. }
  1096. /**
  1097. * Copy list operation
  1098. */
  1099. async copyList(operationId, data) {
  1100. const { sourceListId, targetBoardId, copyOptions } = data;
  1101. const operation = boardOperations.get().get(operationId);
  1102. // Simulate copy progress
  1103. const steps = ['copying_list', 'copying_cards', 'copying_attachments', 'finalizing'];
  1104. for (let i = 0; i < steps.length; i++) {
  1105. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1106. this.updateBoardOperation(operationId, operation);
  1107. // Simulate work
  1108. await new Promise(resolve => setTimeout(resolve, 300));
  1109. }
  1110. }
  1111. /**
  1112. * Move list operation
  1113. */
  1114. async moveList(operationId, data) {
  1115. const { sourceListId, targetBoardId, moveOptions } = data;
  1116. const operation = boardOperations.get().get(operationId);
  1117. // Simulate move progress
  1118. const steps = ['preparing_move', 'moving_list', 'updating_references', 'finalizing'];
  1119. for (let i = 0; i < steps.length; i++) {
  1120. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1121. this.updateBoardOperation(operationId, operation);
  1122. // Simulate work
  1123. await new Promise(resolve => setTimeout(resolve, 200));
  1124. }
  1125. }
  1126. /**
  1127. * Copy card operation
  1128. */
  1129. async copyCard(operationId, data) {
  1130. const { sourceCardId, targetListId, copyOptions } = data;
  1131. const operation = boardOperations.get().get(operationId);
  1132. // Simulate copy progress
  1133. const steps = ['copying_card', 'copying_attachments', 'copying_checklists', 'finalizing'];
  1134. for (let i = 0; i < steps.length; i++) {
  1135. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1136. this.updateBoardOperation(operationId, operation);
  1137. // Simulate work
  1138. await new Promise(resolve => setTimeout(resolve, 150));
  1139. }
  1140. }
  1141. /**
  1142. * Move card operation
  1143. */
  1144. async moveCard(operationId, data) {
  1145. const { sourceCardId, targetListId, moveOptions } = data;
  1146. const operation = boardOperations.get().get(operationId);
  1147. // Simulate move progress
  1148. const steps = ['preparing_move', 'moving_card', 'updating_references', 'finalizing'];
  1149. for (let i = 0; i < steps.length; i++) {
  1150. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1151. this.updateBoardOperation(operationId, operation);
  1152. // Simulate work
  1153. await new Promise(resolve => setTimeout(resolve, 100));
  1154. }
  1155. }
  1156. /**
  1157. * Copy checklist operation
  1158. */
  1159. async copyChecklist(operationId, data) {
  1160. const { sourceChecklistId, targetCardId, copyOptions } = data;
  1161. const operation = boardOperations.get().get(operationId);
  1162. // Simulate copy progress
  1163. const steps = ['copying_checklist', 'copying_items', 'finalizing'];
  1164. for (let i = 0; i < steps.length; i++) {
  1165. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1166. this.updateBoardOperation(operationId, operation);
  1167. // Simulate work
  1168. await new Promise(resolve => setTimeout(resolve, 100));
  1169. }
  1170. }
  1171. /**
  1172. * Move checklist operation
  1173. */
  1174. async moveChecklist(operationId, data) {
  1175. const { sourceChecklistId, targetCardId, moveOptions } = data;
  1176. const operation = boardOperations.get().get(operationId);
  1177. // Simulate move progress
  1178. const steps = ['preparing_move', 'moving_checklist', 'finalizing'];
  1179. for (let i = 0; i < steps.length; i++) {
  1180. operation.progress = Math.round(((i + 1) / steps.length) * 100);
  1181. this.updateBoardOperation(operationId, operation);
  1182. // Simulate work
  1183. await new Promise(resolve => setTimeout(resolve, 50));
  1184. }
  1185. }
  1186. /**
  1187. * Get board operations for a specific board
  1188. */
  1189. getBoardOperations(boardId) {
  1190. const operations = boardOperations.get();
  1191. const boardOps = [];
  1192. for (const [operationId, operation] of operations) {
  1193. if (operation.boardId === boardId) {
  1194. boardOps.push(operation);
  1195. }
  1196. }
  1197. return boardOps.sort((a, b) => b.startTime - a.startTime);
  1198. }
  1199. /**
  1200. * Get all board operations with pagination
  1201. */
  1202. getAllBoardOperations(page = 1, limit = 20, searchTerm = '') {
  1203. const operations = boardOperations.get();
  1204. const allOps = Array.from(operations.values());
  1205. // Filter by search term if provided
  1206. let filteredOps = allOps;
  1207. if (searchTerm) {
  1208. filteredOps = allOps.filter(op =>
  1209. op.boardId.toLowerCase().includes(searchTerm.toLowerCase()) ||
  1210. op.type.toLowerCase().includes(searchTerm.toLowerCase())
  1211. );
  1212. }
  1213. // Sort by start time (newest first)
  1214. filteredOps.sort((a, b) => b.startTime - a.startTime);
  1215. // Paginate
  1216. const startIndex = (page - 1) * limit;
  1217. const endIndex = startIndex + limit;
  1218. const paginatedOps = filteredOps.slice(startIndex, endIndex);
  1219. return {
  1220. operations: paginatedOps,
  1221. total: filteredOps.length,
  1222. page: page,
  1223. limit: limit,
  1224. totalPages: Math.ceil(filteredOps.length / limit)
  1225. };
  1226. }
  1227. /**
  1228. * Get board operation statistics
  1229. */
  1230. getBoardOperationStats() {
  1231. const operations = boardOperations.get();
  1232. const stats = {
  1233. total: operations.size,
  1234. running: 0,
  1235. completed: 0,
  1236. error: 0,
  1237. byType: {}
  1238. };
  1239. for (const [operationId, operation] of operations) {
  1240. stats[operation.status]++;
  1241. if (!stats.byType[operation.type]) {
  1242. stats.byType[operation.type] = 0;
  1243. }
  1244. stats.byType[operation.type]++;
  1245. }
  1246. return stats;
  1247. }
  1248. /**
  1249. * Trigger restore legacy lists migration
  1250. */
  1251. async triggerRestoreLegacyListsMigration() {
  1252. try {
  1253. // Find the restore legacy lists step
  1254. const step = this.migrationSteps.find(s => s.id === 'restore-legacy-lists');
  1255. if (!step) {
  1256. throw new Error('Restore legacy lists migration step not found');
  1257. }
  1258. // Create a job for this migration
  1259. const jobId = `restore_legacy_lists_${Date.now()}`;
  1260. cronJobStorage.addToQueue(jobId, 'migration', step.weight, {
  1261. stepId: step.id,
  1262. stepName: step.name,
  1263. stepDescription: step.description
  1264. });
  1265. // Save initial job status
  1266. cronJobStorage.saveJobStatus(jobId, {
  1267. jobType: 'migration',
  1268. status: 'pending',
  1269. progress: 0,
  1270. stepId: step.id,
  1271. stepName: step.name
  1272. });
  1273. // Execute the migration immediately
  1274. const jobData = {
  1275. stepId: step.id,
  1276. stepName: step.name,
  1277. stepDescription: step.description
  1278. };
  1279. await this.executeMigrationJob(jobId, jobData);
  1280. return {
  1281. success: true,
  1282. jobId: jobId,
  1283. message: 'Restore legacy lists migration triggered successfully'
  1284. };
  1285. } catch (error) {
  1286. console.error('Error triggering restore legacy lists migration:', error);
  1287. throw new Meteor.Error('migration-trigger-failed', `Failed to trigger migration: ${error.message}`);
  1288. }
  1289. }
  1290. }
  1291. // Export singleton instance
  1292. export const cronMigrationManager = new CronMigrationManager();
  1293. // Initialize cron jobs on server start
  1294. Meteor.startup(() => {
  1295. cronMigrationManager.initializeCronJobs();
  1296. });
  1297. // Meteor methods for client-server communication
  1298. Meteor.methods({
  1299. 'cron.startAllMigrations'() {
  1300. if (!this.userId) {
  1301. throw new Meteor.Error('not-authorized');
  1302. }
  1303. return cronMigrationManager.startAllMigrations();
  1304. },
  1305. 'cron.startJob'(cronName) {
  1306. if (!this.userId) {
  1307. throw new Meteor.Error('not-authorized');
  1308. }
  1309. return cronMigrationManager.startCronJob(cronName);
  1310. },
  1311. 'cron.stopJob'(cronName) {
  1312. if (!this.userId) {
  1313. throw new Meteor.Error('not-authorized');
  1314. }
  1315. return cronMigrationManager.stopCronJob(cronName);
  1316. },
  1317. 'cron.pauseJob'(cronName) {
  1318. if (!this.userId) {
  1319. throw new Meteor.Error('not-authorized');
  1320. }
  1321. return cronMigrationManager.pauseCronJob(cronName);
  1322. },
  1323. 'cron.resumeJob'(cronName) {
  1324. if (!this.userId) {
  1325. throw new Meteor.Error('not-authorized');
  1326. }
  1327. return cronMigrationManager.resumeCronJob(cronName);
  1328. },
  1329. 'cron.removeJob'(cronName) {
  1330. if (!this.userId) {
  1331. throw new Meteor.Error('not-authorized');
  1332. }
  1333. return cronMigrationManager.removeCronJob(cronName);
  1334. },
  1335. 'cron.addJob'(jobData) {
  1336. if (!this.userId) {
  1337. throw new Meteor.Error('not-authorized');
  1338. }
  1339. return cronMigrationManager.addCronJob(jobData);
  1340. },
  1341. 'cron.getJobs'() {
  1342. return cronMigrationManager.getAllCronJobs();
  1343. },
  1344. 'cron.getMigrationProgress'() {
  1345. return {
  1346. progress: cronMigrationProgress.get(),
  1347. status: cronMigrationStatus.get(),
  1348. currentStep: cronMigrationCurrentStep.get(),
  1349. steps: cronMigrationSteps.get(),
  1350. isMigrating: cronIsMigrating.get()
  1351. };
  1352. },
  1353. 'cron.startBoardOperation'(boardId, operationType, operationData) {
  1354. if (!this.userId) {
  1355. throw new Meteor.Error('not-authorized');
  1356. }
  1357. return cronMigrationManager.startBoardOperation(boardId, operationType, operationData);
  1358. },
  1359. 'cron.getBoardOperations'(boardId) {
  1360. if (!this.userId) {
  1361. throw new Meteor.Error('not-authorized');
  1362. }
  1363. return cronMigrationManager.getBoardOperations(boardId);
  1364. },
  1365. 'cron.getAllBoardOperations'(page, limit, searchTerm) {
  1366. if (!this.userId) {
  1367. throw new Meteor.Error('not-authorized');
  1368. }
  1369. return cronMigrationManager.getAllBoardOperations(page, limit, searchTerm);
  1370. },
  1371. 'cron.getBoardOperationStats'() {
  1372. if (!this.userId) {
  1373. throw new Meteor.Error('not-authorized');
  1374. }
  1375. return cronMigrationManager.getBoardOperationStats();
  1376. },
  1377. 'cron.getJobDetails'(jobId) {
  1378. if (!this.userId) {
  1379. throw new Meteor.Error('not-authorized');
  1380. }
  1381. return cronJobStorage.getJobDetails(jobId);
  1382. },
  1383. 'cron.getQueueStats'() {
  1384. if (!this.userId) {
  1385. throw new Meteor.Error('not-authorized');
  1386. }
  1387. return cronJobStorage.getQueueStats();
  1388. },
  1389. 'cron.getSystemResources'() {
  1390. if (!this.userId) {
  1391. throw new Meteor.Error('not-authorized');
  1392. }
  1393. return cronJobStorage.getSystemResources();
  1394. },
  1395. 'cron.pauseJob'(jobId) {
  1396. if (!this.userId) {
  1397. throw new Meteor.Error('not-authorized');
  1398. }
  1399. cronJobStorage.updateQueueStatus(jobId, 'paused');
  1400. cronJobStorage.saveJobStatus(jobId, { status: 'paused' });
  1401. return { success: true };
  1402. },
  1403. 'cron.resumeJob'(jobId) {
  1404. if (!this.userId) {
  1405. throw new Meteor.Error('not-authorized');
  1406. }
  1407. cronJobStorage.updateQueueStatus(jobId, 'pending');
  1408. cronJobStorage.saveJobStatus(jobId, { status: 'pending' });
  1409. return { success: true };
  1410. },
  1411. 'cron.stopJob'(jobId) {
  1412. if (!this.userId) {
  1413. throw new Meteor.Error('not-authorized');
  1414. }
  1415. cronJobStorage.updateQueueStatus(jobId, 'stopped');
  1416. cronJobStorage.saveJobStatus(jobId, {
  1417. status: 'stopped',
  1418. stoppedAt: new Date()
  1419. });
  1420. return { success: true };
  1421. },
  1422. 'cron.cleanupOldJobs'(daysOld) {
  1423. if (!this.userId) {
  1424. throw new Meteor.Error('not-authorized');
  1425. }
  1426. return cronJobStorage.cleanupOldJobs(daysOld);
  1427. },
  1428. 'cron.getBoardMigrationStats'() {
  1429. if (!this.userId) {
  1430. throw new Meteor.Error('not-authorized');
  1431. }
  1432. // Import the board migration detector
  1433. const { boardMigrationDetector } = require('./boardMigrationDetector');
  1434. return boardMigrationDetector.getMigrationStats();
  1435. },
  1436. 'cron.forceBoardMigrationScan'() {
  1437. if (!this.userId) {
  1438. throw new Meteor.Error('not-authorized');
  1439. }
  1440. // Import the board migration detector
  1441. const { boardMigrationDetector } = require('./boardMigrationDetector');
  1442. return boardMigrationDetector.forceScan();
  1443. },
  1444. 'cron.triggerRestoreLegacyLists'() {
  1445. if (!this.userId) {
  1446. throw new Meteor.Error('not-authorized');
  1447. }
  1448. // Check if user is admin (optional - you can remove this if you want any user to trigger it)
  1449. const user = ReactiveCache.getCurrentUser();
  1450. if (!user || !user.isAdmin) {
  1451. throw new Meteor.Error('not-authorized', 'Only administrators can trigger this migration');
  1452. }
  1453. return cronMigrationManager.triggerRestoreLegacyListsMigration();
  1454. }
  1455. });