Spaces:
Sleeping

File size: 2,722 Bytes
7f81110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { BaseService } from "../../../../../libs/shared/application/BaseService";
import { TenantContext } from "../../../../../libs/shared/domain/valueObjects/TenantContext";
import { ISyncJobRepository } from "../../../domain/repositories/ISyncJobRepository";
import { IEventPublisher } from "../../ports/IEventPublisher";
import { SyncJobCreatedEvent } from "../../../domain/events/SyncJobCreatedEvent";

export interface TriggerSyncInput {
    tenantId: string;
    action: "full" | "retry_failed";
}

export class TriggerSyncUseCase extends BaseService {
    constructor(
        tenantContext: TenantContext,
        private readonly repository: ISyncJobRepository,
        private readonly eventPublisher: IEventPublisher
    ) {
        super(tenantContext);
    }

    async execute(input: TriggerSyncInput) {

        // ── 2. Check for already active job (dedup) ────────────────────────
        const activeJob = await this.repository.findActiveSyncJob(input.tenantId);
        if (activeJob) {
            return {
                jobId: activeJob.id,
                status: activeJob.status.getValue(),
                reused: true,
            };
        }

        // ── 3. Handle retry_failed: re-enqueue latest failed job's type ────
        if (input.action === "retry_failed") {
            const failedJob = await this.repository.findLatestFailedJob(input.tenantId);
            if (failedJob) {
                const job = await this.repository.createSyncJob({
                    tenantId: input.tenantId,
                    type: failedJob.type, // preserve original type
                    triggeredBy: "manual_retry_failed",
                });

                await this.eventPublisher.publish(
                    new SyncJobCreatedEvent(job.id, job.tenantId, job.type)
                );

                return {
                    jobId: job.id,
                    status: job.status.getValue(),
                    reused: false,
                };
            }
            // No failed job found β€” fall through to full sync
        }

        // ── 4. Create new full backfill job ────────────────────────────────
        const job = await this.repository.createSyncJob({
            tenantId: input.tenantId,
            type: "full_backfill",
            triggeredBy: "manual",
        });

        await this.eventPublisher.publish(
            new SyncJobCreatedEvent(job.id, job.tenantId, job.type)
        );

        return {
            jobId: job.id,
            status: job.status.getValue(),
            reused: false,
        };
    }
}