66 lines
1.7 KiB
TypeScript
66 lines
1.7 KiB
TypeScript
import {
|
|
Injectable,
|
|
Logger,
|
|
OnModuleDestroy,
|
|
OnModuleInit,
|
|
} from '@nestjs/common';
|
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
|
import { DakaoOutboxService } from './dakao-outbox.service';
|
|
|
|
const SWEEP_INTERVAL_MS = 60 * 1000;
|
|
const STALE_OUTBOX_MS = 5 * 60 * 1000;
|
|
const SWEEP_LOCK_KEY =
|
|
'distributed-lock:dakao-outbox:sweep-stale-publish-leases';
|
|
const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000;
|
|
|
|
@Injectable()
|
|
export class DakaoOutboxSweeperService
|
|
implements OnModuleInit, OnModuleDestroy
|
|
{
|
|
private readonly logger = new Logger(DakaoOutboxSweeperService.name);
|
|
private timer: NodeJS.Timeout | undefined;
|
|
|
|
constructor(
|
|
private readonly outboxService: DakaoOutboxService,
|
|
private readonly distributedLockService: DistributedLockService,
|
|
) {}
|
|
|
|
onModuleInit() {
|
|
this.timer = setInterval(() => {
|
|
void this.sweep();
|
|
}, SWEEP_INTERVAL_MS);
|
|
this.timer.unref();
|
|
}
|
|
|
|
onModuleDestroy() {
|
|
if (this.timer) clearInterval(this.timer);
|
|
}
|
|
|
|
private async sweep(): Promise<void> {
|
|
try {
|
|
const swept = await this.distributedLockService.runWithLock(
|
|
{
|
|
lockKey: SWEEP_LOCK_KEY,
|
|
lockExpirationDurationMilliseconds:
|
|
SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS,
|
|
},
|
|
async () =>
|
|
this.outboxService.sweepStale({
|
|
staleMs: STALE_OUTBOX_MS,
|
|
limit: 20,
|
|
}),
|
|
);
|
|
const sweptCount = swept ?? 0;
|
|
if (sweptCount > 0) {
|
|
this.logger.warn(
|
|
`Re-published ${sweptCount} stale Dakao outbox messages.`,
|
|
);
|
|
}
|
|
} catch (err) {
|
|
this.logger.error(
|
|
`Dakao outbox sweep failed: ${(err as Error)?.stack ?? err}`,
|
|
);
|
|
}
|
|
}
|
|
}
|