feat: add s3 readiness and orphan object reconciler
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { S3Service } from '../storage/s3.service';
|
||||
|
||||
const MAX_REPORTED_KEYS = 20;
|
||||
|
||||
export interface ReconcileOptions {
|
||||
apply: boolean;
|
||||
graceMs: number;
|
||||
prefix?: string;
|
||||
now?: Date;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export interface ReconcileReport {
|
||||
mode: 'apply' | 'dry-run';
|
||||
grace_seconds: number;
|
||||
scanned: number;
|
||||
fresh_skipped: number;
|
||||
referenced: number;
|
||||
orphans: number;
|
||||
deleted: number;
|
||||
failed: number;
|
||||
orphan_keys: string[];
|
||||
duration_ms: number;
|
||||
}
|
||||
|
||||
export async function reconcile(
|
||||
prisma: Pick<PrismaClient, 'attachment'>,
|
||||
s3: S3Service,
|
||||
options: ReconcileOptions,
|
||||
): Promise<ReconcileReport> {
|
||||
const started = Date.now();
|
||||
const cutoff = (options.now ?? new Date()).getTime() - options.graceMs;
|
||||
const report: ReconcileReport = {
|
||||
mode: options.apply ? 'apply' : 'dry-run',
|
||||
grace_seconds: options.graceMs / 1000,
|
||||
scanned: 0,
|
||||
fresh_skipped: 0,
|
||||
referenced: 0,
|
||||
orphans: 0,
|
||||
deleted: 0,
|
||||
failed: 0,
|
||||
orphan_keys: [],
|
||||
duration_ms: 0,
|
||||
};
|
||||
let token: string | undefined;
|
||||
do {
|
||||
const page = await s3.listObjects(
|
||||
options.prefix ?? 'attachments/',
|
||||
options.pageSize ?? 500,
|
||||
token,
|
||||
);
|
||||
token = page.nextToken;
|
||||
report.scanned += page.objects.length;
|
||||
const old = page.objects.filter((object) => object.lastModified.getTime() < cutoff);
|
||||
report.fresh_skipped += page.objects.length - old.length;
|
||||
const rows = await prisma.attachment.findMany({
|
||||
where: { objectKey: { in: old.map((object) => object.key) } },
|
||||
select: { objectKey: true },
|
||||
});
|
||||
const known = new Set(rows.map((row) => row.objectKey));
|
||||
for (const { key } of old) {
|
||||
if (known.has(key)) {
|
||||
report.referenced++;
|
||||
continue;
|
||||
}
|
||||
report.orphans++;
|
||||
if (report.orphan_keys.length < MAX_REPORTED_KEYS) {
|
||||
report.orphan_keys.push(key);
|
||||
}
|
||||
if (options.apply) {
|
||||
await s3.delete(key).then(
|
||||
() => report.deleted++,
|
||||
() => report.failed++,
|
||||
);
|
||||
}
|
||||
}
|
||||
} while (token);
|
||||
report.duration_ms = Date.now() - started;
|
||||
return report;
|
||||
}
|
||||
@@ -1,19 +1,37 @@
|
||||
import { Controller, Get } from '@nestjs/common';
|
||||
import { ApiError } from '../common/filters/api-error';
|
||||
import { PrismaService } from '../db/prisma.service';
|
||||
import { S3Service } from '../storage/s3.service';
|
||||
import { isDraining } from './shutdown';
|
||||
|
||||
@Controller('health')
|
||||
export class HealthController {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly s3: S3Service,
|
||||
) {}
|
||||
|
||||
@Get('live')
|
||||
live(): { status: 'ok' } {
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
@Get('core')
|
||||
async core(): Promise<{ status: 'ok' }> {
|
||||
await this.assertCoreReady();
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
@Get('ready')
|
||||
async ready(): Promise<{ status: 'ok' }> {
|
||||
await this.assertCoreReady();
|
||||
if (!(await this.s3.isAvailable())) {
|
||||
throw new ApiError('unavailable', 'object storage unavailable');
|
||||
}
|
||||
return { status: 'ok' };
|
||||
}
|
||||
|
||||
private async assertCoreReady(): Promise<void> {
|
||||
if (isDraining()) {
|
||||
throw new ApiError('unavailable', 'shutting down');
|
||||
}
|
||||
@@ -22,6 +40,5 @@ export class HealthController {
|
||||
} catch {
|
||||
throw new ApiError('unavailable', 'database unavailable');
|
||||
}
|
||||
return { status: 'ok' };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { reconcile } from './attachments/reconciler';
|
||||
import { PrismaService } from './db/prisma.service';
|
||||
import { S3Service } from './storage/s3.service';
|
||||
|
||||
const DEFAULT_GRACE_SECONDS = 3600;
|
||||
const DEFAULT_INTERVAL_SECONDS = 300;
|
||||
|
||||
function option(name: string, fallback: number): number {
|
||||
const prefix = `--${name}=`;
|
||||
const raw = process.argv.find((arg) => arg.startsWith(prefix));
|
||||
const value = raw ? Number(raw.slice(prefix.length)) : fallback;
|
||||
if (!Number.isInteger(value) || value < 0) {
|
||||
throw new Error(`--${name} must be a non-negative integer`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
process.once('SIGTERM', () => process.exit(0));
|
||||
process.once('SIGINT', () => process.exit(0));
|
||||
const apply = process.argv.includes('--apply');
|
||||
const loop = process.argv.includes('--loop');
|
||||
const graceSeconds = option('grace-seconds', DEFAULT_GRACE_SECONDS);
|
||||
const intervalSeconds = option('interval-seconds', DEFAULT_INTERVAL_SECONDS);
|
||||
const prisma = new PrismaService();
|
||||
const s3 = new S3Service();
|
||||
do {
|
||||
try {
|
||||
const report = await reconcile(prisma, s3, {
|
||||
apply,
|
||||
graceMs: graceSeconds * 1000,
|
||||
});
|
||||
process.stdout.write(`${JSON.stringify(report)}\n`);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.name : 'unknown error';
|
||||
Logger.error(`reconcile pass aborted: ${reason}`, 'Reconciler');
|
||||
process.exitCode = loop ? 0 : 1;
|
||||
}
|
||||
if (loop) {
|
||||
await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000));
|
||||
}
|
||||
} while (loop);
|
||||
await prisma.$disconnect();
|
||||
s3.onModuleDestroy();
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
Logger.error(error instanceof Error ? error.message : 'fatal error', 'Reconciler');
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectCommand,
|
||||
HeadBucketCommand,
|
||||
ListObjectsV2Command,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3';
|
||||
@@ -12,6 +14,12 @@ import { ApiError } from '../common/filters/api-error';
|
||||
const CONNECT_TIMEOUT_MS = 1000;
|
||||
const IDLE_TIMEOUT_MS = 5000;
|
||||
const OPERATION_TIMEOUT_MS = 20000;
|
||||
const HEALTH_TIMEOUT_MS = 1000;
|
||||
|
||||
export interface ObjectPage {
|
||||
objects: { key: string; lastModified: Date }[];
|
||||
nextToken?: string;
|
||||
}
|
||||
|
||||
export interface StoredFile {
|
||||
key: string;
|
||||
@@ -89,6 +97,42 @@ export class S3Service implements OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
async isAvailable(): Promise<boolean> {
|
||||
try {
|
||||
await this.client.send(new HeadBucketCommand({ Bucket: this.bucket }), {
|
||||
abortSignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async listObjects(
|
||||
prefix: string,
|
||||
pageSize: number,
|
||||
token?: string,
|
||||
): Promise<ObjectPage> {
|
||||
const page = await this.guard(`list ${prefix}`, () =>
|
||||
this.client.send(
|
||||
new ListObjectsV2Command({
|
||||
Bucket: this.bucket,
|
||||
Prefix: prefix,
|
||||
MaxKeys: pageSize,
|
||||
ContinuationToken: token,
|
||||
}),
|
||||
{ abortSignal: AbortSignal.timeout(OPERATION_TIMEOUT_MS) },
|
||||
),
|
||||
);
|
||||
return {
|
||||
objects: (page.Contents ?? []).map((object) => ({
|
||||
key: object.Key!,
|
||||
lastModified: object.LastModified!,
|
||||
})),
|
||||
nextToken: page.NextContinuationToken,
|
||||
};
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<void> {
|
||||
await this.guard(`delete ${key}`, () =>
|
||||
this.client.send(
|
||||
|
||||
Reference in New Issue
Block a user