javascript Copy code
const crypto = require('crypto');
const Redis = require('ioredis'); // or 'redis'
const zlib = require('zlib'); // optional for handling compression
// Redis client (configure with your connection details)
const redis = new Redis({
host: 'localhost',
port: 6379,
// Add retry_strategy, etc., for production
});
// Configuration
const IDEMPOTENT_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
const TTL_SECONDS = 300; // 5-minute sliding window (TTL from first insertion)
const MAX_PAYLOAD_SIZE = 1 * 1024 * 1024; // 1MB limit to prevent abuse
const PROCESSING_TTL_SECONDS = 30; // Short lock for processing (assumes ops <30s)
/**
* Canonical serialization for deterministic payload hashing.
* Sorts object keys recursively to handle non-deterministic JSON.stringify.
*/
function canonicalSerialize(obj) {
if (obj === null || obj === undefined) return String(obj);
if (typeof obj !== 'object') return String(obj);
if (Array.isArray(obj)) {
return `[${obj.map(canonicalSerialize).join(',')}]`;
}
const sortedKeys = Object.keys(obj).sort();
const entries = sortedKeys.map(key => `${key}:${canonicalSerialize(obj[key])}`);
return `{${entries.join(',')}}`;
}
/**
* Generates SHA-256 hash of canonical payload + method + URL for deduplication key.
*/
async function generateDedupeKey(req) {
if (req.body && Buffer.byteLength(JSON.stringify(req.body)) > MAX_PAYLOAD_SIZE) {
throw new Error('Payload too large for deduplication');
}
const canonicalPayload = canonicalSerialize(req.body);
const payloadDigest = crypto
.createHash('sha256')
.update(canonicalPayload)
.digest('hex');
return `dedupe:${req.method}:${req.originalUrl}:${payloadDigest}`;
}
/**
* Request deduplication middleware for Express.js.
* - Applies only to idempotent methods.
* - Dedupes based on method + full URL (path + query) + hashed payload.
* - Uses Redis for distributed storage with sliding TTL window (expires TTL seconds after first seen).
* - Captures and replays full response (status, headers, body) on duplicates.
* - Handles race conditions with NX atomic "processing" lock.
* - If locked (processing), returns 202 Accepted immediately (client can retry).
* - Buffers response body (non-streaming; add streaming support if needed).
* - Compression-aware (detects gzip, stores/unzips raw body).
* - Note: Place BEFORE body-parser, compression, and cors middleware.
*/
async function dedupeMiddleware(req, res, next) {
if (!IDEMPOTENT_METHODS.includes(req.method)) return next();
try {
const dedupeKey = await generateDedupeKey(req);
res.locals.dedupeKey = dedupeKey; // For app-level access if needed
// Atomic check-and-set for processing lock
const processingValue = Buffer.from(JSON.stringify({
status: 202,
body: { message: 'request processing, please retry' },
headers: {}
})).toString('base64');
const setResult = await redis.set(dedupeKey, processingValue, 'NX', 'EX', PROCESSING_TTL_SECONDS);
if (setResult !== 'OK') {
// Already seen/processing: fetch and replay
const cachedRaw = await redis.get(dedupeKey);
if (!cachedRaw) return next(); // Race: expired during check
const cached = JSON.parse(Buffer.from(cachedRaw, 'base64').toString());
res.status(cached.status);
// Replay significant headers (e.g., Content-Type, ETag)
Object.entries(cached.headers || {}).forEach(([key, value]) => {
if (key.toLowerCase() !== 'content-encoding') { // Avoid double-gzip
res.set(key, value);
}
});
let body = cached.body;
if (cached.compressed) {
body = zlib.gunzipSync(Buffer.from(body, 'base64')).toString();
}
res.send(body);
return;
}
// First request: override res.write/end to capture response on completion
const chunks = [];
const originalWrite = res.write;
const originalEnd = res.end;
const originalWriteHead = res.writeHead; // For headers
res.writeHead = function(code, headers) {
res.statusCode = code;
Object.entries(headers || {}).forEach(([k, v]) => res.setHeader(k, v));
return originalWriteHead.call(this, code, headers);
};
res.write = function(chunk) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
return originalWrite.call(this, chunk);
};
res.end = function(chunk) {
if (chunk) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
// Capture on finish
const fullBody = Buffer.concat(chunks);
const contentType = res.get('Content-Type') || '';
const isJson = contentType.includes('application/json');
const isCompressed = res.get('Content-Encoding') === 'gzip';
let bodyStr;
if (isCompressed) {
bodyStr = fullBody.toString('base64'); // Store compressed
} else if (isJson) {
bodyStr = fullBody.toString('utf8');
} else {
bodyStr = fullBody.toString('base64'); // Binary-safe
}
const cacheData = {
status: res.statusCode,
headers: Object.fromEntries(
Object.entries(res.getHeaders()).filter(([k]) => !k.match(/^(content-length|transfer-encoding)$/i))
),
body: bodyStr,
compressed: !!isCompressed
};
// Upsert full response with longer TTL (sliding window)
await redis.set(
dedupeKey,
Buffer.from(JSON.stringify(cacheData)).toString('base64'),
'EX',
TTL_SECONDS
);
return originalEnd.call(this, chunk);
};
// Ensure cleanup on errors
res.on('finish', () => {
// Redis cleanup already handled via TTL
});
next();
} catch (err) {
console.error('Dedupe middleware error:', err);
// Unlock on error (best effort)
if (res.locals.dedupeKey) {
redis.del(res.locals.dedupeKey).catch(() => {});
}
next();
}
}
module.exports = dedupeMiddleware;