feat(backend & dba): implement inventory concurrency guard, redis distributed locks, magic byte file validation, slow query logger, and db check constraints

This commit is contained in:
devops committed 2026-10-18 15:29:37 +00:00
1 parent 73bc79b4bb
commit dda1caf3e0
7 files changed
+104 -23

No files matched your search

+22
View File
@@ -79,6 +79,28 @@ export class MediaService {
"پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).",
);
}
// SEC-01: Magic number verification for uploaded binary content
const buf = file.buffer;
if (!buf || buf.length < 4) {
throw new BadRequestException("فایل نامعتبر یا آسیب‌دیده است.");
}
const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47;
const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a
const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF
const isWebp =
buf.length >= 12 &&
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF
buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP
if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) {
throw new BadRequestException(
"محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).",
);
}
const filename = `${uniqueSuffix}${ext}`;
const filePath = path.join(uploadDir, filename);
+2 -1
View File
@@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
import { TasksService } from './tasks.service';
import { OrdersModule } from '../../orders/orders.module';
import { PaymentModule } from '../../payment/payment.module';
import { RedisModule } from '../../redis/redis.module';
@Module({
imports: [OrdersModule, PaymentModule],
imports: [OrdersModule, PaymentModule, RedisModule],
providers: [TasksService],
exports: [TasksService],
})
@@ -1,5 +1,6 @@
import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common';
import { OrdersService } from '../../orders/orders.service';
import { RedisService } from '../../redis/redis.service';
import { PaymentService } from '../../payment/payment.service';
@Injectable()
@@ -11,6 +12,7 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo
constructor(
private readonly ordersService: OrdersService,
private readonly paymentService: PaymentService,
private readonly redisService: RedisService,
) {}
onApplicationBootstrap() {
@@ -18,6 +20,11 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo
// 1. Release expired inventory reservations every 5 minutes (300,000 ms)
this.reservationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240);
if (!lockAcquired) {
this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.ordersService.releaseExpiredInventoryReservations();
if (result.releasedCount > 0) {
@@ -25,11 +32,18 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo
}
} catch (err) {
this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err);
} finally {
await this.redisService.releaseLock('task:inventory_release');
}
}, 5 * 60 * 1000);
// 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms)
this.reconciliationTimer = setInterval(async () => {
const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540);
if (!lockAcquired) {
this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.');
return;
}
try {
const result = await this.paymentService.reconcilePendingTransactions();
if (result.total > 0) {
@@ -37,6 +51,8 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo
}
} catch (err) {
this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err);
} finally {
await this.redisService.releaseLock('task:payment_reconciliation');
}
}, 10 * 60 * 1000);
+12 -11
View File
@@ -346,17 +346,18 @@ export class OrdersService {
// Deduct inventory immediately for non-online orders (card to card)
if (!isOnline) {
for (const item of createOrderDto.items) {
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
});
// BE-05: Atomic decrement with inventory constraint guard
const updateCount = await tx.$executeRaw`
UPDATE products
SET stock = stock - ${item.quantity},
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
`;
if (updateCount === 0) {
throw new BadRequestException(
`موجودی محصول مورد نظر در حین ثبت نهایی به پایان رسید یا کمتر از تعداد درخواستی شد.`
);
}
}
}
+12 -11
View File
@@ -447,17 +447,18 @@ export class PaymentService {
if (orderWithItems?.orderItems) {
for (const item of orderWithItems.orderItems) {
if (item.productId) {
const updated = await tx.product.update({
where: { id: item.productId },
data: {
stock: { decrement: item.quantity },
},
});
if (updated.stock <= 0) {
await tx.product.update({
where: { id: item.productId },
data: { stockStatus: "OUT_OF_STOCK" },
});
// BE-05: Atomic decrement with inventory constraint guard
const updateCount = await tx.$executeRaw`
UPDATE products
SET stock = stock - ${item.quantity},
stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END
WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity}
`;
if (updateCount === 0) {
this.logger.error(
`[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.`
);
}
}
}
+24
View File
@@ -1,13 +1,37 @@
import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
import { Logger } from "@nestjs/common";
@Injectable()
export class PrismaService
extends PrismaClient
implements OnModuleInit, OnModuleDestroy
{
private readonly logger = new Logger(PrismaService.name);
constructor() {
super({
log: [
{ emit: "event", level: "query" },
{ emit: "stdout", level: "error" },
{ emit: "stdout", level: "warn" },
],
});
}
async onModuleInit() {
await this.$connect();
// BE-07: Slow query logging interceptor (> 300ms)
(this as any).$on("query", (e: any) => {
if (e.duration >= 300) {
this.logger.warn(
`[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`,
);
}
});
await this.ensureTablesExist();
}
+16
View File
@@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
async ttl(key: string): Promise<number> {
return this.client.ttl(key);
}
/**
* Acquire a distributed lock using Redis SET NX EX
* Returns true if lock acquired, false otherwise
*/
async acquireLock(key: string, ttlSeconds: number = 60): Promise<boolean> {
const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX");
return res === "OK";
}
/**
* Release a distributed lock
*/
async releaseLock(key: string): Promise<void> {
await this.client.del(`lock:${key}`);
}
}