Files
Calbook/lib/services/delivery-issues.ts

90 lines
2.2 KiB
TypeScript

import type { DeliveryChannel } from "@prisma/client";
import { prisma } from "@/lib/prisma";
type DeliveryIssueInput = {
channel: DeliveryChannel;
operation: string;
target: string;
error: unknown;
attemptIncrement?: number;
};
type ResolveDeliveryIssueInput = {
channel: DeliveryChannel;
operation: string;
target: string;
};
function toErrorMessage(error: unknown) {
if (error instanceof Error) {
return error.message.slice(0, 4000);
}
return String(error).slice(0, 4000);
}
export async function reportDeliveryFailure(input: DeliveryIssueInput) {
const message = toErrorMessage(input.error);
const increment = Math.max(1, input.attemptIncrement ?? 1);
try {
const existing = await prisma.deliveryIssue.findFirst({
where: {
channel: input.channel,
operation: input.operation,
target: input.target,
resolvedAt: null
},
orderBy: {
lastSeenAt: "desc"
},
select: { id: true, attemptCount: true }
});
if (existing) {
await prisma.deliveryIssue.update({
where: { id: existing.id },
data: {
lastError: message,
attemptCount: existing.attemptCount + increment,
lastSeenAt: new Date()
}
});
return;
}
await prisma.deliveryIssue.create({
data: {
channel: input.channel,
operation: input.operation,
target: input.target,
lastError: message,
attemptCount: increment,
firstSeenAt: new Date(),
lastSeenAt: new Date()
}
});
} catch (error) {
// eslint-disable-next-line no-console
console.error("[calbook] DeliveryIssue speichern fehlgeschlagen", error);
}
}
export async function resolveDeliveryIssues(input: ResolveDeliveryIssueInput) {
try {
await prisma.deliveryIssue.updateMany({
where: {
channel: input.channel,
operation: input.operation,
target: input.target,
resolvedAt: null
},
data: {
resolvedAt: new Date()
}
});
} catch (error) {
// eslint-disable-next-line no-console
console.error("[calbook] DeliveryIssue resolve fehlgeschlagen", error);
}
}