fix(api): resolve duplicate key constraint errors in host package updates

This commit is contained in:
tigattack
2025-09-26 20:57:01 +01:00
parent d85920669d
commit be3fe52aea

View File

@@ -375,14 +375,21 @@ router.post(
updateData.status = "active"; updateData.status = "active";
} }
await prisma.hosts.update({ // Calculate package counts before transaction
where: { id: host.id }, const securityCount = packages.filter(
data: updateData, (pkg) => pkg.isSecurityUpdate,
}); ).length;
const updatesCount = packages.filter((pkg) => pkg.needsUpdate).length;
// Process packages in transaction // Process everything in a single transaction to avoid race conditions
await prisma.$transaction(async (tx) => { await prisma.$transaction(async (tx) => {
// Clear existing host packages // Update host data
await tx.hosts.update({
where: { id: host.id },
data: updateData,
});
// Clear existing host packages to avoid duplicates
await tx.host_packages.deleteMany({ await tx.host_packages.deleteMany({
where: { host_id: host.id }, where: { host_id: host.id },
}); });
@@ -423,8 +430,22 @@ router.post(
} }
// Create host package relationship // Create host package relationship
await tx.host_packages.create({ // Use upsert to handle potential duplicates gracefully
data: { await tx.host_packages.upsert({
where: {
host_id_package_id: {
host_id: host.id,
package_id: pkg.id,
},
},
update: {
current_version: packageData.currentVersion,
available_version: packageData.availableVersion || null,
needs_update: packageData.needsUpdate,
is_security_update: packageData.isSecurityUpdate || false,
last_checked: new Date(),
},
create: {
id: uuidv4(), id: uuidv4(),
host_id: host.id, host_id: host.id,
package_id: pkg.id, package_id: pkg.id,
@@ -493,22 +514,17 @@ router.post(
}); });
} }
} }
});
// Create update history record // Create update history record
const securityCount = packages.filter( await tx.update_history.create({
(pkg) => pkg.isSecurityUpdate, data: {
).length; id: uuidv4(),
const updatesCount = packages.filter((pkg) => pkg.needsUpdate).length; host_id: host.id,
packages_count: updatesCount,
await prisma.update_history.create({ security_count: securityCount,
data: { status: "success",
id: uuidv4(), },
host_id: host.id, });
packages_count: updatesCount,
security_count: securityCount,
status: "success",
},
}); });
// Check if auto-update is enabled and if there's a newer agent version available // Check if auto-update is enabled and if there's a newer agent version available