File size: 2,388 Bytes
c09f67c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | import { updateInboxAccount } from "@midday/db/queries";
import { triggerJob } from "@midday/job-client";
import type { Job } from "bullmq";
import { registerDynamicScheduler } from "../../schedulers/registry";
import type { InboxProviderInitialSetupPayload } from "../../schemas/inbox";
import { getDb } from "../../utils/db";
import { generateQuarterDailyCronTag } from "../../utils/generate-cron-tag";
import { BaseProcessor } from "../base";
/**
* Initial inbox setup processor
* Registers a dynamic scheduler for the inbox account and triggers initial sync
*/
export class InitialSetupProcessor extends BaseProcessor<InboxProviderInitialSetupPayload> {
async process(job: Job<InboxProviderInitialSetupPayload>): Promise<{
inboxAccountId: string;
schedulerRegistered: boolean;
}> {
const { inboxAccountId } = job.data;
const db = getDb();
this.logger.info("Starting initial inbox setup", { inboxAccountId });
// Register dynamic scheduler for this inbox account
// The scheduler will run every 6 hours with a random minute based on account ID
const cronPattern = generateQuarterDailyCronTag(inboxAccountId);
try {
await registerDynamicScheduler({
template: "inbox-sync-scheduler",
accountId: inboxAccountId,
cronPattern,
});
this.logger.info("Dynamic scheduler registered for inbox account", {
inboxAccountId,
cronPattern,
});
// Store the scheduler job key in the database (similar to scheduleId in Trigger.dev)
// The job key is: `inbox-sync-${inboxAccountId}`
const schedulerJobKey = `inbox-sync-${inboxAccountId}`;
await updateInboxAccount(db, {
id: inboxAccountId,
scheduleId: schedulerJobKey, // Store the BullMQ repeatable job key
});
// Trigger initial sync
await triggerJob(
"sync-scheduler",
{
id: inboxAccountId,
manualSync: true,
},
"inbox-provider",
);
this.logger.info("Initial inbox setup completed", { inboxAccountId });
return {
inboxAccountId,
schedulerRegistered: true,
};
} catch (error) {
this.logger.error("Failed to register inbox scheduler", {
inboxAccountId,
error: error instanceof Error ? error.message : "Unknown error",
});
throw error;
}
}
}
|