/* eslint-disable no-console */ import Inject, { ServiceProvider } from "@entity-access/entity-access/dist/di/di.js"; import Workflow, { UniqueActivity } from "@entity-access/entity-access/dist/workflows/Workflow.js"; import WorkflowContext from "@entity-access/entity-access/dist/workflows/WorkflowContext.js"; import SocialMailContext from "../../../model/SocialMailContext.js"; import IndexEmailService from "../../../services/emails/IndexEmailService.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; import { globalEnv } from "../../../../common/globalEnv.js"; import AsyncTaskManager from "../../../../common/AsyncTaskManager.js"; export default class IndexEmailTextContentWorkflow extends Workflow { static taskGroup = "batch"; static queue(context: WorkflowContext) { return context.queue(IndexEmailTextContentWorkflow, "", { id: `index-email-content`, }); } async run() { this.preserveTime = TimeSpan.fromSeconds(15); await this.index(); } @UniqueActivity async index( @Inject db?: SocialMailContext ) { for(let i = 0;i<1000;i++) { const pending = await db.emails.where((x) => x.searchIndexed === false && x.statePostReceiveInvoked === true) .orderByDescending((x) => x.emailID) .map((x) => ({ emailID: x.emailID, subject: x.subject, textBody: x.textBody})) .limit(200) .toArray(); if (!pending.length) { console.log(`No more emails to index for ${globalEnv.serverID}`); return; } const at = new AsyncTaskManager(); at.rateLimit = 10; const start = Date.now(); await Promise.all(pending.map((x) => at.run(() => this.indexEmail(x)))); const end = Date.now() - start; console.log(`${pending.length} indexed in ${(end/1000).toFixed(2)}s`); db.changeSet.clear(); } } async indexEmail(email: { emailID: number; subject: string, textBody: string; }) { using scope = ServiceProvider.createScope(this.context); const db = scope.resolve(SocialMailContext); const indexService = scope.resolve(IndexEmailService); try { await indexService.indexEmail(email); } catch (error) { console.error(error); } const { emailID } = email; await db.emails.statements.update({ searchIndexed: true }, { emailID }); } }