forked from mtusi2026/mtusi2026lab7
ЛР 7 — БПИ2304 — Кирюпина — на 3
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
'use strict';
|
||||
const sharp = require('sharp');
|
||||
const { randomUUID, createHash } = require('node:crypto');
|
||||
const { pool, transaction } = require('./db');
|
||||
const broker = require('./broker');
|
||||
const { client, bucket, unavailable } = require('./storage');
|
||||
const MAX_BYTES = 10485760, MAX_PIXELS = 40000000;
|
||||
sharp.cache(false);
|
||||
function fail(status, code, message) { throw Object.assign(new Error(message), { status, code }); }
|
||||
function visible(row) {
|
||||
const { object_key, staging_key, ...data } = row;
|
||||
return data;
|
||||
}
|
||||
function readLimited(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0, failed = false;
|
||||
const chunks = [];
|
||||
const tooLarge = () => {
|
||||
failed = true;
|
||||
reject(Object.assign(new Error('File exceeds 10 MiB'), { status: 413, code: 'payload_too_large' }));
|
||||
};
|
||||
if (Number(req.headers['content-length'] || 0) > MAX_BYTES) { req.resume(); tooLarge(); return; }
|
||||
req.on('data', chunk => {
|
||||
if (failed) return;
|
||||
size += chunk.length;
|
||||
if (size > MAX_BYTES) { chunks.length = 0; tooLarge(); }
|
||||
else chunks.push(chunk);
|
||||
});
|
||||
req.on('end', () => { if (!failed) resolve(Buffer.concat(chunks)); });
|
||||
req.on('error', () => reject(Object.assign(new Error('Upload interrupted'), { status: 400, code: 'invalid_request' })));
|
||||
});
|
||||
}
|
||||
async function validateImage(bytes, contentType) {
|
||||
// Reject other formats before asking the image decoder to process them.
|
||||
const png = bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]));
|
||||
const jpeg = bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
|
||||
if ((!png && !jpeg) || (png ? 'image/png' : 'image/jpeg') !== contentType)
|
||||
fail(415, 'unsupported_media_type', 'Expected a matching PNG or JPEG');
|
||||
try {
|
||||
const decoder = sharp(bytes, { limitInputPixels: MAX_PIXELS, failOn: 'warning' });
|
||||
const info = await decoder.metadata();
|
||||
if (!info.width || !info.height || info.width * info.height > MAX_PIXELS)
|
||||
fail(413, 'payload_too_large', 'Image exceeds 40 million pixels');
|
||||
if (!['png', 'jpeg'].includes(info.format)) fail(415, 'unsupported_media_type', 'Unsupported image');
|
||||
// Full decoding detects truncated/corrupt payloads; the raw result is discarded.
|
||||
// Pixel limit is enforced before allocation. Original bytes are never transformed.
|
||||
await decoder.raw().toBuffer();
|
||||
} catch (error) {
|
||||
if (error.status) throw error;
|
||||
if (/pixel limit/i.test(error.message)) fail(413, 'payload_too_large', 'Image exceeds 40 million pixels');
|
||||
fail(415, 'unsupported_media_type', 'Corrupt image');
|
||||
}
|
||||
}
|
||||
async function upload(req, query, chat, user) {
|
||||
const filename = query.get('filename');
|
||||
if (query.getAll('filename').length !== 1 || !filename || !filename.isWellFormed() ||
|
||||
/^[\p{White_Space}\uFEFF]*$/u.test(filename) || [...filename].length > 255 || /[\/\\\p{Cc}]/u.test(filename))
|
||||
fail(400, 'invalid_request', 'Invalid filename');
|
||||
const contentType = req.headers['content-type']?.split(';')[0].trim().toLowerCase();
|
||||
if (!['image/png', 'image/jpeg'].includes(contentType)) fail(415, 'unsupported_media_type', 'Expected PNG or JPEG');
|
||||
const bytes = await readLimited(req);
|
||||
await validateImage(bytes, contentType);
|
||||
const id = randomUUID(), objectKey = 'staging/' + id;
|
||||
const checksum = createHash('sha256').update(bytes).digest('hex');
|
||||
try { await client.putObject(bucket, objectKey, bytes, bytes.length, { 'Content-Type': contentType }); }
|
||||
catch { throw unavailable(); }
|
||||
let accepted;
|
||||
try {
|
||||
accepted = await transaction(async db => {
|
||||
const row = (await db.query(`INSERT INTO attachments
|
||||
(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,staging_key,status)
|
||||
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'queued') RETURNING *`,
|
||||
[id,chat.id,user.id,filename,contentType,bytes.length,checksum,'originals/'+id+'/v1',objectKey])).rows[0];
|
||||
const job = (await db.query('INSERT INTO attachment_jobs(id,attachment_id) VALUES($1,$2) RETURNING *',
|
||||
[randomUUID(),id])).rows[0];
|
||||
return {row,job};
|
||||
});
|
||||
} catch (error) {
|
||||
await client.removeObject(bucket,objectKey).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
// No 202 until the persistent job has a publisher confirm. A failed publish
|
||||
// leaves an unconfirmed queued row; grade 3 has no outbox/reconciler.
|
||||
try { await broker.publish(accepted.job); }
|
||||
catch { throw Object.assign(new Error('Broker unavailable'),{status:503,code:'unavailable'}); }
|
||||
return visible(accepted.row);
|
||||
}
|
||||
|
||||
async function accessible(id, user) {
|
||||
const result = await pool.query(`SELECT a.* FROM attachments a WHERE a.id=$1 AND EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=a.chat_id AND user_id=$2)`, [id, user.id]);
|
||||
if (!result.rowCount) fail(404, 'not_found', 'Object not found');
|
||||
return result.rows[0];
|
||||
}
|
||||
async function download(row) {
|
||||
try {
|
||||
const stream = await client.getObject(bucket, row.object_key);
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of stream) {
|
||||
size += chunk.length;
|
||||
if (size > MAX_BYTES) { stream.destroy(); throw new Error(); }
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const bytes = Buffer.concat(chunks);
|
||||
if (bytes.length !== row.size_bytes || createHash('sha256').update(bytes).digest('hex') !== row.sha256) throw new Error();
|
||||
return bytes;
|
||||
} catch { throw unavailable(); }
|
||||
}
|
||||
module.exports = { upload, accessible, visible, download, validateImage };
|
||||
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
const amqp = require('amqplib');
|
||||
const telemetry = require('./telemetry');
|
||||
const {readFileSync} = require('node:fs');
|
||||
const queue = 'attachments.v1';
|
||||
let pending;
|
||||
async function open() {
|
||||
const url = process.env.BROKER_URL || readFileSync(process.env.BROKER_URL_FILE || '/run/secrets/broker_url','utf8').trim();
|
||||
const connection = await amqp.connect(url, {timeout: 5000,ca:require('./tls').ca,rejectUnauthorized:true});
|
||||
connection.on('error', () => {});
|
||||
const channel = await connection.createConfirmChannel();
|
||||
channel.on('error', () => {});
|
||||
await channel.assertQueue(queue, {durable: true});
|
||||
return {connection, channel};
|
||||
}
|
||||
async function publisher() {
|
||||
if (!pending) pending = open().then(value => {
|
||||
value.connection.on('close', () => { pending = null; });
|
||||
value.channel.on('close', () => { pending = null; });
|
||||
return value;
|
||||
}).catch(error => { pending = null; throw error; });
|
||||
return pending;
|
||||
}
|
||||
function payload(job, attempt=1) {
|
||||
return {schema_version:1,job_id:job.id,type:'attachment.process.v1',attachment_id:job.attachment_id,
|
||||
pipeline_version:1,attempt,created_at:new Date(job.created_at).toISOString(),...telemetry.carrier()};
|
||||
}
|
||||
async function publish(job, attempt=1, channel) {
|
||||
return telemetry.operation('attachments.publish',telemetry.SpanKind.PRODUCER,async () => {
|
||||
channel = channel || (await publisher()).channel;
|
||||
await new Promise((resolve,reject) => channel.sendToQueue(queue, Buffer.from(JSON.stringify(payload(job,attempt))),
|
||||
{persistent:true,contentType:'application/json',messageId:job.id}, error => error ? reject(error) : resolve()));
|
||||
}, {'messaging.system':'rabbitmq'});
|
||||
}
|
||||
async function ready() {
|
||||
try { await (await publisher()).channel.checkQueue(queue); }
|
||||
catch { throw Object.assign(new Error('Broker unavailable'),{status:503,code:'unavailable'}); }
|
||||
}
|
||||
async function close() {
|
||||
if (pending) { const value=await pending; await value.connection.close(); }
|
||||
}
|
||||
module.exports = {open,publish,ready,queue,close};
|
||||
@@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { Pool } = require('pg');
|
||||
const telemetry = require('./telemetry');
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL || readFileSync(process.env.DATABASE_URL_FILE || '/run/secrets/database_url', 'utf8').trim(),
|
||||
ssl: {ca:readFileSync('/tls/ca.crt'),rejectUnauthorized:true},
|
||||
max: 10, connectionTimeoutMillis: 3000, idleTimeoutMillis: 10000,
|
||||
statement_timeout: 5000,
|
||||
});
|
||||
const originalQuery=pool.query.bind(pool);
|
||||
pool.query=(...args)=>telemetry.operation('postgres.query',telemetry.SpanKind.CLIENT,()=>originalQuery(...args),{'db.system':'postgresql'});
|
||||
pool.on('error', () => telemetry.log('database.unavailable',{},true));
|
||||
async function transaction(work) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const result = await work(client);
|
||||
await client.query('COMMIT');
|
||||
return result;
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw error;
|
||||
} finally { client.release(); }
|
||||
}
|
||||
module.exports = { pool, transaction };
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { transaction } = require('./db');
|
||||
const retention = Number(process.env.IDEMPOTENCY_TTL_SECONDS || 86400);
|
||||
if (!Number.isSafeInteger(retention) || retention < 86400) throw new Error('Idempotency retention must be at least 24 hours');
|
||||
|
||||
async function sendMessage(userId, chatId, key, text, attachmentIds = []) {
|
||||
return transaction(async client => {
|
||||
const attached = await client.query('SELECT id,status FROM attachments WHERE chat_id=$1 AND id=ANY($2::uuid[])', [chatId, attachmentIds]);
|
||||
if (attached.rowCount !== attachmentIds.length)
|
||||
throw Object.assign(new Error('Object not found'), { status: 404, code: 'not_found' });
|
||||
if (attached.rows.some(a => a.status === 'failed'))
|
||||
throw Object.assign(new Error('Attachment failed'),{status:409,code:'conflict'});
|
||||
// Shared PostgreSQL lock serializes this operation across all API replicas.
|
||||
// Hash collisions only serialize unrelated keys; the actual lookup uses the full scope.
|
||||
const scope = JSON.stringify([userId, chatId, key]);
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1, 0))', [scope]);
|
||||
await client.query(`DELETE FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3
|
||||
AND expires_at <= clock_timestamp()`, [userId, chatId, key]);
|
||||
const prior = await client.query('SELECT text,attachment_ids,response FROM message_requests WHERE user_id=$1 AND chat_id=$2 AND key=$3', [userId, chatId, key]);
|
||||
if (prior.rowCount) {
|
||||
if (prior.rows[0].text !== text || JSON.stringify(prior.rows[0].attachment_ids) !== JSON.stringify(attachmentIds))
|
||||
throw Object.assign(new Error('Key already used for another message'), { status: 409, code: 'conflict' });
|
||||
return prior.rows[0].response;
|
||||
}
|
||||
const message = (await client.query(`INSERT INTO messages(id,chat_id,sender_id,text)
|
||||
VALUES($1,$2,$3,$4) RETURNING *`, [randomUUID(), chatId, userId, text])).rows[0];
|
||||
for (let i = 0; i < attachmentIds.length; i++)
|
||||
await client.query('INSERT INTO message_attachments VALUES($1,$2,$3)', [message.id, attachmentIds[i], i]);
|
||||
message.attachment_ids = attachmentIds;
|
||||
await client.query(`INSERT INTO message_requests(user_id,chat_id,key,text,message_id,response,expires_at,attachment_ids)
|
||||
VALUES($1,$2,$3,$4,$5,$6::jsonb,clock_timestamp()+$7*interval '1 second',$8::uuid[])`,
|
||||
[userId, chatId, key, text, message.id, JSON.stringify(message), retention, attachmentIds]);
|
||||
// The HTTP handler returns 201 only after transaction() completes COMMIT.
|
||||
return message;
|
||||
});
|
||||
}
|
||||
module.exports = { sendMessage };
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
const { readFileSync, readdirSync } = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { createHash, randomBytes } = require('node:crypto');
|
||||
const { pool } = require('./db');
|
||||
async function migrate() {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('SELECT pg_advisory_lock(202602)');
|
||||
await client.query(`CREATE TABLE IF NOT EXISTS schema_migrations
|
||||
(version text PRIMARY KEY, checksum text NOT NULL)`);
|
||||
const dir = path.join(__dirname, '..', 'migrations');
|
||||
for (const version of readdirSync(dir).filter(f => /^\d+.*\.sql$/.test(f)).sort()) {
|
||||
const sql = readFileSync(path.join(dir, version), 'utf8').replace(/\r\n/g, '\n');
|
||||
const checksum = createHash('sha256').update(sql).digest('hex');
|
||||
const existing = await client.query('SELECT checksum FROM schema_migrations WHERE version=$1', [version]);
|
||||
if (existing.rowCount) {
|
||||
// Git may normalize Windows line endings; accept only equivalent LF/CRLF text.
|
||||
const windowsChecksum = createHash('sha256').update(sql.replace(/\n/g, '\r\n')).digest('hex');
|
||||
if (![checksum, windowsChecksum].includes(existing.rows[0].checksum)) throw new Error('Migration checksum mismatch');
|
||||
continue;
|
||||
}
|
||||
await client.query('BEGIN');
|
||||
try {
|
||||
await client.query(sql);
|
||||
await client.query('INSERT INTO schema_migrations VALUES ($1,$2)', [version, checksum]);
|
||||
await client.query('COMMIT');
|
||||
} catch (error) { await client.query('ROLLBACK'); throw error; }
|
||||
console.log('Applied migration ' + version);
|
||||
}
|
||||
await client.query(`INSERT INTO app_settings VALUES ('cursor_secret',$1) ON CONFLICT DO NOTHING`, [randomBytes(32).toString('hex')]);
|
||||
await client.query(`GRANT CONNECT ON DATABASE messenger TO api,worker;
|
||||
GRANT USAGE ON SCHEMA public TO api,worker;
|
||||
GRANT SELECT,INSERT,UPDATE,DELETE ON users,sessions,chats,chat_members,messages,message_requests,message_attachments,attachments,attachment_jobs,login_limits TO api;
|
||||
GRANT SELECT ON app_settings TO api;
|
||||
GRANT SELECT,UPDATE ON attachments,attachment_jobs TO worker;`);
|
||||
} finally {
|
||||
await client.query('SELECT pg_advisory_unlock(202602)').catch(() => {});
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
module.exports = { migrate };
|
||||
if (require.main === module) migrate().then(() => console.log('Migrations up to date'))
|
||||
.catch(() => { console.error('Migration failed'); process.exitCode = 1; }).finally(() => pool.end());
|
||||
@@ -0,0 +1,8 @@
|
||||
'use strict';
|
||||
const argon=require('@node-rs/argon2');
|
||||
const options={algorithm:2,version:1,memoryCost:19456,timeCost:2,parallelism:1,outputLen:32};
|
||||
const dummy=argon.hash('dummy-password-never-valid',options);
|
||||
module.exports={options,hashPassword:value=>argon.hash(value,options),verifyPassword:async(value,encoded)=>{
|
||||
try{return await argon.verify(encoded||await dummy,value) && Boolean(encoded);}catch{return false;}
|
||||
}};
|
||||
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
'use strict';
|
||||
const telemetry = require('./telemetry');
|
||||
const https = require('node:https');
|
||||
const tls = require('./tls');
|
||||
const {hashPassword,verifyPassword}=require('./password');
|
||||
const { randomUUID, randomBytes, createHash, createHmac, scrypt, timingSafeEqual } = require('node:crypto');
|
||||
const { promisify } = require('node:util');
|
||||
const { pool, transaction } = require('./db');
|
||||
const { sendMessage } = require('./messages');
|
||||
const attachments = require('./attachments');
|
||||
const storage = require('./storage');
|
||||
const broker = require('./broker');
|
||||
const instanceId = telemetry.instanceId;
|
||||
let stopping = false;
|
||||
const ttl = Number(process.env.SESSION_TTL_SECONDS || 3600);
|
||||
if (!Number.isSafeInteger(ttl) || ttl < 1) throw new Error('Invalid SESSION_TTL_SECONDS');
|
||||
let cursorSecret;
|
||||
const userColumns = 'id, username, display_name, created_at';
|
||||
const chatSelect = `SELECT c.id,c.title,c.created_at,
|
||||
ARRAY(SELECT user_id FROM chat_members WHERE chat_id=c.id ORDER BY user_id) AS member_ids FROM chats c`;
|
||||
function fail(status, code, message) { throw Object.assign(new Error(message), { status, code }); }
|
||||
function invalid(message = 'Invalid request') { fail(400, 'invalid_request', message); }
|
||||
function unauthorized() { fail(401, 'unauthorized', 'Invalid credentials or session'); }
|
||||
function uuid(value) {
|
||||
if (typeof value !== 'string' || value.length !== 36 || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(value)) invalid('Invalid UUID');
|
||||
return value.toLowerCase();
|
||||
}
|
||||
function fields(body, names) {
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body) ||
|
||||
Object.keys(body).length !== names.length || !names.every(k => Object.hasOwn(body, k))) invalid('Invalid fields');
|
||||
}
|
||||
function string(value, max, min = 1) {
|
||||
if (typeof value !== 'string' || !value.isWellFormed() || /^[\p{White_Space}\uFEFF]*$/u.test(value) ||
|
||||
[...value].length < min || [...value].length > max || value.includes('\0')) invalid('Invalid string');
|
||||
return value;
|
||||
}
|
||||
function username(value) {
|
||||
if (typeof value !== 'string' || value.length < 3 || value.length > 32 || /[^a-z0-9_]/.test(value)) invalid('Invalid username');
|
||||
}
|
||||
function password(value) {
|
||||
if (typeof value !== 'string' || !value.isWellFormed() || [...value].length < 12 || [...value].length > 128 ||
|
||||
/^[\p{White_Space}\uFEFF]*$/u.test(value)) invalid('Invalid password');
|
||||
}
|
||||
function digest(token) { return createHash('sha256').update(token).digest('hex'); }
|
||||
async function rawBody(req) {
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
if (size > 1024 * 1024) fail(413, 'payload_too_large', 'Request body too large');
|
||||
chunks.push(chunk);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
async function body(req) {
|
||||
if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json')
|
||||
fail(415, 'unsupported_media_type', 'Expected application/json');
|
||||
const bytes = await rawBody(req);
|
||||
try { return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); }
|
||||
catch { invalid('Invalid JSON'); }
|
||||
}
|
||||
async function identity(req) {
|
||||
const match = /^Bearer ([A-Za-z0-9_-]{43})$/i.exec(req.headers.authorization || '');
|
||||
if (!match) unauthorized();
|
||||
const tokenHash = digest(match[1]);
|
||||
const result = await pool.query(`SELECT u.id,u.username,u.display_name,u.created_at
|
||||
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||
WHERE token_hash=$1 AND expires_at > clock_timestamp()`, [tokenHash]);
|
||||
if (!result.rowCount) unauthorized();
|
||||
return { user: result.rows[0], tokenHash };
|
||||
}
|
||||
async function accessible(id, user) {
|
||||
const result = await pool.query(chatSelect + ` WHERE c.id=$1 AND EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, [uuid(id), user.id]);
|
||||
if (!result.rowCount) fail(404, 'not_found', 'Object not found');
|
||||
return result.rows[0];
|
||||
}
|
||||
function signature(payload) { return createHmac('sha256', cursorSecret).update(payload).digest('base64url'); }
|
||||
function pagination(query, scope) {
|
||||
if (query.getAll('limit').length > 1 || query.getAll('cursor').length > 1) invalid();
|
||||
const raw = query.get('limit') ?? '50';
|
||||
if (!/^\d+$/.test(raw) || Number(raw) < 1 || Number(raw) > 100) invalid('Invalid limit');
|
||||
let after = null;
|
||||
if (query.has('cursor')) {
|
||||
try {
|
||||
const token = query.get('cursor');
|
||||
if (!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) throw new Error();
|
||||
const [payload, mac] = token.split('.');
|
||||
if (signature(payload) !== mac) throw new Error();
|
||||
after = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
||||
if (after.scope !== scope || typeof after.created_at !== 'string' || !Number.isFinite(Date.parse(after.created_at))) throw new Error();
|
||||
uuid(after.id);
|
||||
} catch { invalid('Invalid cursor'); }
|
||||
}
|
||||
return { limit: Number(raw), after, scope };
|
||||
}
|
||||
function page(rows, paging) {
|
||||
const items = rows.slice(0, paging.limit);
|
||||
let next_cursor = null;
|
||||
if (rows.length > paging.limit) {
|
||||
const last = items.at(-1);
|
||||
const payload = Buffer.from(JSON.stringify({ scope: paging.scope, created_at: last.created_at, id: last.id })).toString('base64url');
|
||||
next_cursor = payload + '.' + signature(payload);
|
||||
}
|
||||
return { items, next_cursor };
|
||||
}
|
||||
|
||||
async function loginLimit(req){
|
||||
// LB overwrites this header; only allowlisted LB certificate reaches handler.
|
||||
const ip=req.headers['x-forwarded-for']||'unknown';
|
||||
const key=createHash('sha256').update(ip).digest('hex');
|
||||
const r=await pool.query(`INSERT INTO login_limits(key,window_start,attempts) VALUES($1,clock_timestamp(),1)
|
||||
ON CONFLICT(key) DO UPDATE SET attempts=CASE WHEN login_limits.window_start < clock_timestamp()-interval '60 seconds' THEN 1 ELSE login_limits.attempts+1 END,
|
||||
window_start=CASE WHEN login_limits.window_start < clock_timestamp()-interval '60 seconds' THEN clock_timestamp() ELSE login_limits.window_start END RETURNING attempts`,[key]);
|
||||
if(r.rows[0].attempts>30)fail(429,'rate_limited','Too many login attempts');
|
||||
}
|
||||
async function route(req) {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
const path = url.pathname, method = req.method;
|
||||
if (method === 'GET' && path === '/health/live') return [200, { status: 'ok' }];
|
||||
if (stopping) fail(503, 'unavailable', 'Server is stopping');
|
||||
if (method === 'GET' && path === '/health/ready') {
|
||||
try { await pool.query('SELECT 1'); }
|
||||
catch { fail(503, 'unavailable', 'Database unavailable'); }
|
||||
await storage.ready();
|
||||
await broker.ready();
|
||||
return [200, { status: 'ok' }];
|
||||
}
|
||||
if (method === 'POST' && path === '/api/v1/users') {
|
||||
const data = await body(req);
|
||||
fields(data, ['username', 'display_name', 'password']);
|
||||
username(data.username); string(data.display_name, 100); password(data.password);
|
||||
const hash = await hashPassword(data.password);
|
||||
try {
|
||||
const result = await pool.query(`INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES($1,$2,$3,$4) RETURNING ${userColumns}`, [randomUUID(), data.username, data.display_name, hash]);
|
||||
return [201, result.rows[0]];
|
||||
} catch (error) {
|
||||
if (error.code === '23505') fail(409, 'conflict', 'Username already exists');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (method === 'POST' && path === '/api/v1/auth/sessions') {
|
||||
await loginLimit(req);
|
||||
const match = /^Basic ([A-Za-z0-9+/]+={0,2})$/i.exec(req.headers.authorization || '');
|
||||
if (!match) unauthorized();
|
||||
let name, value;
|
||||
try {
|
||||
const bytes = Buffer.from(match[1], 'base64');
|
||||
if (bytes.toString('base64') !== match[1]) throw new Error();
|
||||
const decoded = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
||||
const colon = decoded.indexOf(':');
|
||||
if (colon < 0) throw new Error();
|
||||
name = decoded.slice(0, colon); value = decoded.slice(colon + 1);
|
||||
username(name); password(value);
|
||||
} catch { unauthorized(); }
|
||||
if ((await rawBody(req)).length) invalid('Login must not have a body');
|
||||
const result = await pool.query(`SELECT ${userColumns},password_hash FROM users WHERE username=$1`, [name]);
|
||||
const row = result.rows[0];
|
||||
if (!await verifyPassword(value, row?.password_hash)) unauthorized();
|
||||
const { password_hash, ...user } = row;
|
||||
const token = randomBytes(32).toString('base64url');
|
||||
const session = await pool.query(`INSERT INTO sessions(token_hash,user_id,expires_at)
|
||||
VALUES($1,$2,clock_timestamp()+$3*interval '1 second') RETURNING expires_at`, [digest(token), user.id, ttl]);
|
||||
return [201, { token, token_type: 'Bearer', expires_at: session.rows[0].expires_at, user }];
|
||||
}
|
||||
const { user, tokenHash } = await identity(req);
|
||||
if (method === 'DELETE' && path === '/api/v1/auth/sessions/current') {
|
||||
await pool.query('DELETE FROM sessions WHERE token_hash=$1', [tokenHash]);
|
||||
return [204, null];
|
||||
}
|
||||
if (method === 'GET' && path === '/api/v1/users/me') return [200, user];
|
||||
if (path === '/api/v1/chats' && method === 'POST') {
|
||||
const data = await body(req);
|
||||
fields(data, ['title', 'member_ids']); string(data.title, 100);
|
||||
if (!Array.isArray(data.member_ids) || data.member_ids.length < 1 || data.member_ids.length > 100) invalid('Invalid members');
|
||||
const ids = data.member_ids.map(uuid);
|
||||
if (new Set(ids).size !== ids.length || !ids.includes(user.id)) invalid('Invalid members');
|
||||
return [201, await transaction(async client => {
|
||||
const known = await client.query('SELECT id FROM users WHERE id=ANY($1::uuid[])', [ids]);
|
||||
if (known.rowCount !== ids.length) invalid('Unknown member');
|
||||
const chat = (await client.query('INSERT INTO chats(id,title) VALUES($1,$2) RETURNING *', [randomUUID(), data.title])).rows[0];
|
||||
await client.query('INSERT INTO chat_members(chat_id,user_id) SELECT $1,unnest($2::uuid[])', [chat.id, ids]);
|
||||
return { ...chat, member_ids: ids.sort() };
|
||||
})];
|
||||
}
|
||||
if (path === '/api/v1/chats' && method === 'GET') {
|
||||
const paging = pagination(url.searchParams, 'chats:' + user.id);
|
||||
const rows = (await pool.query(chatSelect + ` WHERE EXISTS
|
||||
(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1)
|
||||
AND ($2::timestamptz IS NULL OR (c.created_at,c.id)>($2::timestamptz,$3::uuid))
|
||||
ORDER BY c.created_at,c.id LIMIT $4`, [user.id, paging.after?.created_at ?? null, paging.after?.id ?? null, paging.limit + 1])).rows;
|
||||
return [200, page(rows, paging)];
|
||||
}
|
||||
const attachmentPath = path.match(/^\/api\/v1\/attachments\/([^/]+)(\/content)?$/);
|
||||
if (attachmentPath && method === 'GET') {
|
||||
const row = await attachments.accessible(uuid(attachmentPath[1]), user);
|
||||
if (!attachmentPath[2]) return [200, attachments.visible(row)];
|
||||
if (url.searchParams.getAll('variant').length > 1) invalid('Invalid variant');
|
||||
if (row.status !== 'ready') fail(409, 'conflict', 'Attachment is not ready');
|
||||
const variant = url.searchParams.get('variant') ?? 'original';
|
||||
let content = row;
|
||||
if (variant !== 'original') {
|
||||
const metadata = row.variants.find(v => v.name === variant);
|
||||
if (!metadata) fail(404, 'not_found', 'Object not found');
|
||||
content = {...metadata,object_key:'variants/'+row.id+'/v1/'+variant};
|
||||
}
|
||||
return [200, await attachments.download(content), { 'Content-Type': content.content_type, 'X-Content-Type-Options': 'nosniff' }];
|
||||
}
|
||||
const match = path.match(/^\/api\/v1\/chats\/([^/]+)(\/messages|\/attachments)?$/);
|
||||
if (match) {
|
||||
const chat = await accessible(match[1], user);
|
||||
if (!match[2] && method === 'GET') return [200, chat];
|
||||
if (match[2] === '/attachments' && method === 'POST') return [202, await attachments.upload(req, url.searchParams, chat, user)];
|
||||
if (match[2] === '/messages' && method === 'POST') {
|
||||
const key = req.headers['idempotency-key'];
|
||||
if (typeof key !== 'string' || key.length < 1 || key.length > 128 || /[^A-Za-z0-9._:-]/.test(key)) invalid('Invalid Idempotency-Key');
|
||||
const data = await body(req);
|
||||
if (!data || typeof data !== 'object' || Array.isArray(data) || !Object.hasOwn(data, 'text') ||
|
||||
Object.keys(data).some(k => !['text', 'attachment_ids'].includes(k))) invalid('Invalid fields');
|
||||
if (typeof data.text !== 'string' || !data.text.isWellFormed() || [...data.text].length > 4000 || data.text.includes('\0')) invalid('Invalid text');
|
||||
const rawIds = Object.hasOwn(data, 'attachment_ids') ? data.attachment_ids : [];
|
||||
if (!Array.isArray(rawIds) || rawIds.length > 10) invalid('Invalid attachments');
|
||||
const ids = rawIds.map(uuid);
|
||||
if (new Set(ids).size !== ids.length || (ids.length === 0 && /^[\p{White_Space}\uFEFF]*$/u.test(data.text))) invalid('Empty message or duplicate attachments');
|
||||
return [201, await sendMessage(user.id, chat.id, key, data.text, ids)];
|
||||
}
|
||||
if (match[2] === '/messages' && method === 'GET') {
|
||||
const paging = pagination(url.searchParams, 'messages:' + chat.id);
|
||||
const result = await pool.query(`SELECT m.*, ARRAY(SELECT attachment_id FROM message_attachments
|
||||
WHERE message_id=m.id ORDER BY position) AS attachment_ids FROM messages m WHERE m.chat_id=$1
|
||||
AND ($2::timestamptz IS NULL OR (m.created_at,m.id)>($2::timestamptz,$3::uuid))
|
||||
ORDER BY m.created_at,m.id LIMIT $4`, [chat.id, paging.after?.created_at ?? null, paging.after?.id ?? null, paging.limit + 1]);
|
||||
return [200, page(result.rows, paging)];
|
||||
}
|
||||
}
|
||||
fail(404, 'not_found', 'Object not found');
|
||||
}
|
||||
const server = https.createServer({...tls,requestCert:true,rejectUnauthorized:true}, async (req, res) => {
|
||||
if (!(req.socket.getPeerCertificate().subjectaltname||'').split(', ').includes('DNS:lb')) {req.socket.destroy();return;}
|
||||
const request_id = randomUUID();
|
||||
return telemetry.http(req,res,request_id,async () => {
|
||||
let status, data, responseHeaders;
|
||||
const headers = { 'Content-Type': 'application/json; charset=utf-8', 'X-Request-Id': request_id, 'X-Instance-Id': instanceId };
|
||||
try { [status, data, responseHeaders] = await route(req); }
|
||||
catch (error) {
|
||||
status = error.status || (/^(08|53|57)/.test(error.code || '') || ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT'].includes(error.code) ? 503 : 500);
|
||||
data = { error: { code: error.status ? error.code : status === 503 ? 'unavailable' : 'internal_error',
|
||||
message: error.status ? error.message : status === 503 ? 'Database unavailable' : 'Internal error', request_id } };
|
||||
if (status === 401) headers['WWW-Authenticate'] = req.url.split('?')[0] === '/api/v1/auth/sessions'
|
||||
? 'Basic realm="messenger", charset="UTF-8"' : 'Bearer realm="messenger"';
|
||||
}
|
||||
if (status === 429) headers['Retry-After']='60';
|
||||
if (status === 413) headers.Connection = 'close';
|
||||
res.writeHead(status, { ...headers, ...responseHeaders });
|
||||
res.end(status === 204 ? undefined : Buffer.isBuffer(data) ? data : JSON.stringify(data));
|
||||
});
|
||||
});
|
||||
async function main() {
|
||||
cursorSecret = (await pool.query("SELECT value FROM app_settings WHERE key='cursor_secret'")).rows[0].value;
|
||||
require('node:http').createServer(async(req,res)=>{
|
||||
if(!['/health/live','/health/ready'].includes(req.url)){res.writeHead(404);return res.end();}
|
||||
try{const [status,data]=await route(req);res.writeHead(status,{'X-Instance-Id':instanceId});res.end(JSON.stringify(data));}catch{res.writeHead(503);res.end();}
|
||||
}).listen(9001,'127.0.0.1');
|
||||
server.listen(Number(process.env.APP_PORT || 8443), process.env.APP_HOST || '0.0.0.0', () => telemetry.log('api.started'));
|
||||
}
|
||||
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => {
|
||||
stopping = true;
|
||||
server.close(async () => { await pool.end(); await broker.close().catch(() => {}); await telemetry.shutdown(); process.exit(0); });
|
||||
setTimeout(() => process.exit(1), 9000).unref();
|
||||
});
|
||||
main().catch(() => { telemetry.log('api.startup_failed',{},true); process.exitCode = 1; pool.end(); });
|
||||
@@ -0,0 +1,26 @@
|
||||
'use strict';
|
||||
// Certificates are bootstrap identity. KV credentials stay only in process memory.
|
||||
const https=require('node:https');
|
||||
const tls=require('./tls');
|
||||
async function bao(path,data,token) {
|
||||
return new Promise((resolve,reject)=>{
|
||||
const req=https.request('https://bao:8200/v1/'+path,{...tls,agent:tls.agent,method:data?'POST':'GET',headers:{'Content-Type':'application/json',...(token?{'X-Vault-Token':token}:{})},timeout:5000},res=>{
|
||||
let body='';res.on('data',b=>body+=b);res.on('end',()=>{if(res.statusCode!==200)return reject(Error('Secret service unavailable'));try{resolve(JSON.parse(body));}catch{reject(Error('Secret response invalid'));}});
|
||||
});req.on('timeout',()=>req.destroy(Error('Secret timeout')));req.on('error',()=>reject(Error('Secret connection failed')));req.end(data?JSON.stringify(data):undefined);
|
||||
});
|
||||
}
|
||||
async function main(){
|
||||
const role=process.env.SERVICE_ROLE;
|
||||
const auth=(await bao('auth/cert/login',{name:role})).auth;
|
||||
if(auth.policies.includes('root'))throw Error('Root policy forbidden');
|
||||
const credentials=(await bao('secret/data/'+role,null,auth.client_token)).data.data;
|
||||
process.env.DATABASE_URL=credentials.database_url;
|
||||
process.env.BROKER_URL=credentials.broker_url;
|
||||
process.env.S3_ACCESS_KEY_ID=credentials.s3_access_key;
|
||||
process.env.S3_SECRET_ACCESS_KEY=credentials.s3_secret_key;
|
||||
// No token needed after startup; explicitly revoke the short-lived token.
|
||||
await bao('auth/token/revoke-self',{},auth.client_token).catch(()=>{});
|
||||
require(role==='worker'?'./worker':'./server');
|
||||
}
|
||||
if(require.main===module)main().catch(()=>{console.error('Service bootstrap failed: check OpenBao readiness and service policy');process.exit(1);});
|
||||
module.exports={bao};
|
||||
@@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
const { readFileSync } = require('node:fs');
|
||||
const { Agent } = require('node:https');
|
||||
const { Client } = require('minio');
|
||||
const endpoint = new URL(process.env.S3_ENDPOINT || 'https://s3:9000');
|
||||
const bucket = process.env.S3_BUCKET || 'messenger-attachments';
|
||||
const client = new Client({
|
||||
endPoint: endpoint.hostname, port: Number(endpoint.port || 9000), useSSL: true,
|
||||
region: process.env.S3_REGION || 'us-east-1',
|
||||
accessKey: process.env.S3_ACCESS_KEY_ID || readFileSync(process.env.S3_ACCESS_KEY_ID_FILE || '/run/secrets/s3_access_key_id', 'utf8').trim(),
|
||||
secretKey: process.env.S3_SECRET_ACCESS_KEY || readFileSync(process.env.S3_SECRET_ACCESS_KEY_FILE || '/run/secrets/s3_secret_access_key', 'utf8').trim(),
|
||||
transportAgent: new Agent({ ca:readFileSync("/tls/ca.crt"),rejectUnauthorized:true, keepAlive: true, timeout: 5000, maxSockets: 16 }),
|
||||
});
|
||||
function unavailable() { return Object.assign(new Error('Object storage unavailable'), { status: 503, code: 'unavailable' }); }
|
||||
async function ready() {
|
||||
try { if (!await client.bucketExists(bucket)) throw new Error(); }
|
||||
catch { throw unavailable(); }
|
||||
}
|
||||
async function bootstrap() {
|
||||
for (let attempt = 0; attempt < 30; attempt++) {
|
||||
try {
|
||||
if (!await client.bucketExists(bucket)) await client.makeBucket(bucket, process.env.S3_REGION || 'us-east-1');
|
||||
// Remove any anonymous policy; newly created buckets are private by default.
|
||||
await client.setBucketPolicy(bucket, '');
|
||||
console.log('Private bucket ready');
|
||||
return;
|
||||
} catch (error) {
|
||||
if (attempt === 29) throw unavailable();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
module.exports = { client, bucket, ready, unavailable };
|
||||
if (require.main === module) bootstrap().then(() => process.exit(0)).catch(() => {
|
||||
console.error('Bucket initialization failed'); process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
const {randomUUID}=require('node:crypto');
|
||||
const {context,trace,propagation,SpanKind,SpanStatusCode}=require('@opentelemetry/api');
|
||||
const instanceId=randomUUID();
|
||||
const service=process.env.OTEL_SERVICE_NAME || 'messenger-api';
|
||||
const endpoint=process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
|
||||
let tracer,meter,logger;
|
||||
const providers=[];
|
||||
if(endpoint) {
|
||||
const {Resource}=require('@opentelemetry/resources');
|
||||
const {NodeTracerProvider}=require('@opentelemetry/sdk-trace-node');
|
||||
const {BatchSpanProcessor}=require('@opentelemetry/sdk-trace-base');
|
||||
const {MeterProvider,PeriodicExportingMetricReader,View,ExplicitBucketHistogramAggregation}=require('@opentelemetry/sdk-metrics');
|
||||
const {LoggerProvider,BatchLogRecordProcessor}=require('@opentelemetry/sdk-logs');
|
||||
const {OTLPTraceExporter}=require('@opentelemetry/exporter-trace-otlp-proto');
|
||||
const {OTLPMetricExporter}=require('@opentelemetry/exporter-metrics-otlp-proto');
|
||||
const {OTLPLogExporter}=require('@opentelemetry/exporter-logs-otlp-proto');
|
||||
const resource=new Resource({'service.name':service,'service.version':'7.0.0','service.instance.id':instanceId,'deployment.environment.name':'lab'});
|
||||
const batching={maxQueueSize:512,maxExportBatchSize:128,scheduledDelayMillis:1000,exportTimeoutMillis:1500};
|
||||
const tp=new NodeTracerProvider({resource});
|
||||
tp.addSpanProcessor(new BatchSpanProcessor(new OTLPTraceExporter({url:endpoint+'/v1/traces',timeoutMillis:1000,httpAgentOptions:require('./tls')}),batching));
|
||||
tp.register();tracer=tp.getTracer('messenger','7.0.0');providers.push(tp);
|
||||
const mp=new MeterProvider({resource,readers:[new PeriodicExportingMetricReader({exporter:new OTLPMetricExporter({url:endpoint+'/v1/metrics',timeoutMillis:1000,httpAgentOptions:require('./tls')}),exportIntervalMillis:5000,exportTimeoutMillis:1500})],
|
||||
views:[new View({instrumentName:'messenger_http_duration_seconds',aggregation:new ExplicitBucketHistogramAggregation([.005,.01,.025,.05,.1,.25,.5,1,2,5,10])}),
|
||||
new View({instrumentName:'messenger_job_duration_seconds',aggregation:new ExplicitBucketHistogramAggregation([.01,.05,.1,.25,.5,1,2,5,10,30,60])})]});
|
||||
meter=mp.getMeter('messenger','7.0.0');providers.push(mp);
|
||||
const lp=new LoggerProvider({resource});lp.addLogRecordProcessor(new BatchLogRecordProcessor(new OTLPLogExporter({url:endpoint+'/v1/logs',timeoutMillis:1000,httpAgentOptions:require('./tls')}),batching));
|
||||
logger=lp.getLogger('messenger','7.0.0');providers.push(lp);
|
||||
}
|
||||
tracer ||= trace.getTracer('messenger');
|
||||
const requests=meter?.createCounter('messenger_http_requests');
|
||||
const httpDuration=meter?.createHistogram('messenger_http_duration_seconds',{unit:'s'});
|
||||
const jobs=meter?.createCounter('messenger_jobs');
|
||||
const jobDuration=meter?.createHistogram('messenger_job_duration_seconds',{unit:'s'});
|
||||
function log(event,attributes={},error=false) {
|
||||
const span=trace.getSpan(context.active())?.spanContext();
|
||||
const record={timestamp:new Date().toISOString(),severity:error?'ERROR':'INFO','service.name':service,event,
|
||||
...(span?{trace_id:span.traceId,span_id:span.spanId}:{}),...attributes};
|
||||
// Only explicit safe attributes from call sites; never log headers, SQL, body or exception.message.
|
||||
logger?.emit({context:context.active(),severityNumber:error?17:9,severityText:record.severity,body:JSON.stringify(record),attributes:{event,...attributes}});
|
||||
console.log(JSON.stringify(record));
|
||||
}
|
||||
function routeTemplate(path) {
|
||||
if(['/health/live','/health/ready','/api/v1/users','/api/v1/users/me','/api/v1/auth/sessions','/api/v1/auth/sessions/current','/api/v1/chats'].includes(path))return path;
|
||||
if(/^\/api\/v1\/chats\/[^/]+\/messages$/.test(path))return '/api/v1/chats/{chat_id}/messages';
|
||||
if(/^\/api\/v1\/chats\/[^/]+\/attachments$/.test(path))return '/api/v1/chats/{chat_id}/attachments';
|
||||
if(/^\/api\/v1\/chats\/[^/]+$/.test(path))return '/api/v1/chats/{chat_id}';
|
||||
if(/^\/api\/v1\/attachments\/[^/]+\/content$/.test(path))return '/api/v1/attachments/{attachment_id}/content';
|
||||
if(/^\/api\/v1\/attachments\/[^/]+$/.test(path))return '/api/v1/attachments/{attachment_id}';
|
||||
return 'unmatched';
|
||||
}
|
||||
async function http(req,res,requestId,run) {
|
||||
const route=routeTemplate(req.url.split('?')[0]);
|
||||
const method=['GET','POST','DELETE','PUT','PATCH','OPTIONS','HEAD'].includes(req.method)?req.method:'OTHER';
|
||||
const parent=propagation.extract(context.active(),{'traceparent':req.headers.traceparent,'tracestate':req.headers.tracestate});
|
||||
return tracer.startActiveSpan(method+' '+route,{kind:SpanKind.SERVER,attributes:{'http.request.method':method,'http.route':route,'request_id':requestId}},parent,async span=>{
|
||||
const start=performance.now();
|
||||
try {return await run();}
|
||||
finally {
|
||||
const status=res.statusCode,duration=(performance.now()-start)/1000,attrs={method,route,status_class:Math.floor(status/100)+'xx'};
|
||||
requests?.add(1,attrs);httpDuration?.record(duration,attrs);
|
||||
span.setAttribute('http.response.status_code',status);span.setStatus({code:status>=500?SpanStatusCode.ERROR:SpanStatusCode.OK});
|
||||
log('http.completed',{request_id:requestId,method,route,status,duration_seconds:duration},status>=500);
|
||||
span.end();
|
||||
}
|
||||
});
|
||||
}
|
||||
async function operation(name,kind,run,attributes={}) {
|
||||
return tracer.startActiveSpan(name,{kind,attributes},async span=>{
|
||||
try {const result=await run();span.setStatus({code:SpanStatusCode.OK});return result;}
|
||||
catch(error){span.setStatus({code:SpanStatusCode.ERROR,message:'operation_failed'});log('dependency.failed',{dependency:name},true);throw error;}
|
||||
finally{span.end();}
|
||||
});
|
||||
}
|
||||
async function job(message,run) {
|
||||
let carrier={};try{carrier=JSON.parse(message.content);}catch{}
|
||||
const parent=propagation.extract(context.active(),carrier);
|
||||
return tracer.startActiveSpan('attachment.process',{kind:SpanKind.CONSUMER,attributes:{'messaging.system':'rabbitmq','job.type':'attachment.process.v1'}},parent,async span=>{
|
||||
const start=performance.now();let outcome='error';
|
||||
try{outcome=(await run()) || 'ignored';return outcome;}
|
||||
finally{
|
||||
const duration=(performance.now()-start)/1000,attrs={job_type:'attachment.process.v1',outcome};
|
||||
jobs?.add(1,attrs);jobDuration?.record(duration,attrs);
|
||||
const error=['failed','retry','error'].includes(outcome);
|
||||
span.setAttribute('job.outcome',outcome);span.setStatus({code:error?SpanStatusCode.ERROR:SpanStatusCode.OK});
|
||||
log('job.completed',{...attrs,duration_seconds:duration,...(/^[0-9a-f-]{36}$/i.test(carrier.attachment_id||'')?{attachment_id:carrier.attachment_id}:{})},error);span.end();
|
||||
}
|
||||
});
|
||||
}
|
||||
function carrier(){const headers={};propagation.inject(context.active(),headers);return headers;}
|
||||
async function shutdown(){await Promise.allSettled(providers.map(p=>p.shutdown()));}
|
||||
module.exports={instanceId,http,job,log,operation,carrier,shutdown,SpanKind};
|
||||
@@ -0,0 +1,17 @@
|
||||
'use strict';
|
||||
const https=require('node:https'),http=require('node:http');
|
||||
const tls=require('./tls');
|
||||
const mode=process.env.PROXY_MODE;
|
||||
const rules={
|
||||
collector:[['/v1/',4318,['api','worker'],['POST']],['/metrics',9464,['prometheus'],['GET']]],
|
||||
loki:[['/otlp/',3100,['collector'],['POST']],['/loki/api/v1/query',3100,['grafana','operator'],['GET','POST']],['/loki/api/v1/label',3100,['grafana','operator'],['GET']],['/loki/api/v1/series',3100,['grafana','operator'],['GET','POST']],['/loki/api/v1/index/stats',3100,['grafana','operator'],['GET']],['/ready',3100,['operator'],['GET']]],
|
||||
tempo:[['/v1/traces',4318,['collector'],['POST']],['/api/',3200,['grafana','operator'],['GET']],['/ready',3200,['operator'],['GET']]],
|
||||
prometheus:[['/api/v1/query',9090,['grafana','operator'],['GET','POST']],['/api/v1/label',9090,['grafana','operator'],['GET']],['/api/v1/series',9090,['grafana','operator'],['GET','POST']],['/api/v1/metadata',9090,['grafana','operator'],['GET']],['/api/v1/status/buildinfo',9090,['grafana','operator'],['GET']],['/-/ready',9090,['operator'],['GET']]]
|
||||
};
|
||||
https.createServer({...tls,requestCert:true,rejectUnauthorized:true},(req,res)=>{
|
||||
const sans=(req.socket.getPeerCertificate().subjectaltname||'').split(', ');
|
||||
const rule=rules[mode]?.find(([prefix,,roles,methods])=>req.url.split('?')[0].startsWith(prefix)&&methods.includes(req.method)&&roles.some(role=>sans.includes('DNS:'+role)));
|
||||
if(!rule){res.writeHead(403);return res.end('Denied');}
|
||||
const upstream=http.request({host:'127.0.0.1',port:rule[1],path:req.url,method:req.method,headers:{...req.headers,host:'localhost'},timeout:10000},r=>{res.writeHead(r.statusCode,r.headers);r.pipe(res);});
|
||||
upstream.on('error',()=>{if(!res.headersSent)res.writeHead(502);res.end();});upstream.on('timeout',()=>upstream.destroy());req.pipe(upstream);
|
||||
}).listen(3443,'0.0.0.0');
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');
|
||||
const https=require('node:https');
|
||||
const ca=fs.readFileSync('/tls/ca.crt');
|
||||
const cert=fs.readFileSync('/tls/cert.crt');
|
||||
const key=fs.readFileSync('/tls/key.pem');
|
||||
const options={ca,cert,key,minVersion:'TLSv1.2',rejectUnauthorized:true};
|
||||
const agent=new https.Agent({...options,keepAlive:true,maxSockets:16,timeout:5000});
|
||||
module.exports={...options,agent};
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
const telemetry = require('./telemetry');
|
||||
const sharp = require('sharp');
|
||||
const {createHash} = require('node:crypto');
|
||||
const {pool} = require('./db');
|
||||
const storage = require('./storage');
|
||||
const {download} = require('./attachments');
|
||||
const broker = require('./broker');
|
||||
const maximum = Number(process.env.JOB_MAX_ATTEMPTS || 5);
|
||||
const delay = Number(process.env.JOB_RETRY_DELAY_MS || 1000);
|
||||
if (!Number.isSafeInteger(maximum) || maximum < 1 || maximum > 20 || !Number.isSafeInteger(delay) || delay < 0 || delay > 60000)
|
||||
throw new Error('Invalid retry configuration');
|
||||
sharp.cache(false);
|
||||
const sha = b => createHash('sha256').update(b).digest('hex');
|
||||
async function processJob(message,channel) {
|
||||
let job;
|
||||
try { job=JSON.parse(message.content); } catch { channel.reject(message,false);return; }
|
||||
if (job.schema_version!==1 || job.type!=='attachment.process.v1' || job.pipeline_version!==1 ||
|
||||
!/^[0-9a-f-]{36}$/i.test(job.job_id || '') || !/^[0-9a-f-]{36}$/i.test(job.attachment_id || '')) {
|
||||
channel.reject(message,false);return;
|
||||
}
|
||||
const db=await pool.connect();
|
||||
let locked=false;
|
||||
try {
|
||||
locked=(await db.query('SELECT pg_try_advisory_lock(hashtextextended($1,5)) AS locked',[job.job_id])).rows[0].locked;
|
||||
if (!locked) { await new Promise(r=>setTimeout(r,250));channel.nack(message,false,true);return; }
|
||||
const work=(await db.query('SELECT * FROM attachment_jobs WHERE id=$1 AND attachment_id=$2',[job.job_id,job.attachment_id])).rows[0];
|
||||
if (!work) { channel.reject(message,false);return; }
|
||||
let row=(await db.query('SELECT * FROM attachments WHERE id=$1',[work.attachment_id])).rows[0];
|
||||
if (['ready','failed'].includes(row.status)) { channel.ack(message);return 'duplicate'; }
|
||||
if (work.attempts >= maximum) {
|
||||
await db.query("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=$1",[row.id]);
|
||||
channel.ack(message);return 'failed';
|
||||
}
|
||||
await db.query('BEGIN');
|
||||
await db.query('UPDATE attachment_jobs SET attempts=attempts+1 WHERE id=$1',[work.id]);
|
||||
await db.query("UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1",[row.id]);
|
||||
await db.query('COMMIT');
|
||||
const attempt=work.attempts+1;
|
||||
try {
|
||||
const bytes=await telemetry.operation('s3.get',telemetry.SpanKind.CLIENT,()=>download({...row,object_key:row.staging_key}));
|
||||
const info=await sharp(bytes,{limitInputPixels:40000000,failOn:'warning'}).metadata();
|
||||
const swapped=[5,6,7,8].includes(info.orientation);
|
||||
const width=swapped?info.height:info.width, height=swapped?info.width:info.height;
|
||||
const scale=Math.min(1,256/width,256/height);
|
||||
const thumbnail=await sharp(bytes,{limitInputPixels:40000000,failOn:'warning'}).rotate()
|
||||
.resize(Math.max(1,Math.floor(width*scale)),Math.max(1,Math.floor(height*scale)),{fit:'fill'})
|
||||
.flatten({background:'#ffffff'}).jpeg({quality:80}).toBuffer({resolveWithObject:true});
|
||||
const variant={name:'thumbnail',content_type:'image/jpeg',size_bytes:thumbnail.data.length,
|
||||
width:thumbnail.info.width,height:thumbnail.info.height,sha256:sha(thumbnail.data)};
|
||||
await storage.client.putObject(storage.bucket,row.object_key,bytes,bytes.length,{'Content-Type':row.content_type});
|
||||
await storage.client.putObject(storage.bucket,'variants/'+row.id+'/v1/thumbnail',thumbnail.data,
|
||||
thumbnail.data.length,{'Content-Type':'image/jpeg'});
|
||||
await db.query("UPDATE attachments SET status='ready',error_code=NULL,variants=$2::jsonb,updated_at=clock_timestamp() WHERE id=$1",[row.id,JSON.stringify([variant])]);
|
||||
// Both objects and committed metadata precede the consumer acknowledgement.
|
||||
channel.ack(message);
|
||||
return 'success';
|
||||
} catch (error) {
|
||||
const permanent=!error.status && /corrupt|unsupported|image|pixel limit/i.test(error.message);
|
||||
const failed=permanent || attempt>=maximum;
|
||||
await db.query('UPDATE attachments SET status=$2,error_code=$3,updated_at=clock_timestamp() WHERE id=$1',
|
||||
[row.id,failed?'failed':'queued',failed?(permanent?'invalid_image':'retry_exhausted'):null]);
|
||||
if (!failed) {
|
||||
await new Promise(r=>setTimeout(r,delay));
|
||||
await broker.publish(work,attempt+1,channel);
|
||||
}
|
||||
channel.ack(message);
|
||||
return failed?'failed':'retry';
|
||||
}
|
||||
} finally {
|
||||
await db.query('ROLLBACK').catch(()=>{});
|
||||
if (locked) await db.query('SELECT pg_advisory_unlock(hashtextextended($1,5))',[job.job_id]).catch(()=>{});
|
||||
db.release();
|
||||
}
|
||||
}
|
||||
async function main() {
|
||||
const {connection,channel}=await broker.open();
|
||||
connection.on('close',()=>process.exit(1));
|
||||
channel.on('close',()=>process.exit(1));
|
||||
await channel.prefetch(1);
|
||||
await channel.consume(broker.queue,message=>{
|
||||
if (message) telemetry.job(message,()=>processJob(message,channel)).catch(async ()=>{
|
||||
// Connection closure returns unacknowledged deliveries to the durable queue.
|
||||
telemetry.log('worker.interrupted',{},true);
|
||||
await telemetry.shutdown();
|
||||
process.exit(1);
|
||||
});
|
||||
},{noAck:false});
|
||||
telemetry.log('worker.started',{concurrency:1,max_attempts:maximum});
|
||||
}
|
||||
for (const signal of ['SIGTERM','SIGINT']) process.on(signal,async()=>{await telemetry.shutdown();process.exit(0);});
|
||||
main().catch(async()=>{telemetry.log('worker.startup_failed',{},true);await telemetry.shutdown();process.exit(1);});
|
||||
Reference in New Issue
Block a user