From 350cc23e5442f8ad500568b2393cf6c261e3965a Mon Sep 17 00:00:00 2001 From: aegor Date: Sun, 15 Nov 2026 16:08:11 +0300 Subject: [PATCH] feat: add rabbitmq broker, outbox relay and worker services --- compose.yaml | 103 +++++++++++++++++++++-- package-lock.json | 74 ++++++++++++++++ package.json | 4 +- scripts/job-scenario.py | 182 ++++++++++++++++++++++++++++++++++++++++ scripts/restart.sh | 4 +- src/broker/broker.ts | 57 +++++++++++++ src/jobs/job-store.ts | 29 +++++++ src/jobs/processor.ts | 8 +- src/relay.ts | 130 ++++++++++++++++++++++++++++ src/worker.ts | 138 ++++++++++++++++++++++++++++++ test/helpers.ts | 3 +- test/jobs.e2e-spec.ts | 20 ++++- 12 files changed, 741 insertions(+), 11 deletions(-) create mode 100644 scripts/job-scenario.py create mode 100644 src/broker/broker.ts create mode 100644 src/relay.ts create mode 100644 src/worker.ts diff --git a/compose.yaml b/compose.yaml index 1be7f56d..e2aa7224 100644 --- a/compose.yaml +++ b/compose.yaml @@ -10,18 +10,25 @@ services: - -ec - | cd /secrets - mkdir -p postgres redis api migrate s3 s3-init reconciler - for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20; do + mkdir -p postgres redis api migrate s3 s3-init reconciler broker rabbitmq relay worker + for entry in pg_password:postgres:24 redis_password:redis:24 s3_root_user:s3:10 s3_root_password:s3:20 s3_access_key_id:api:10 s3_secret_access_key:api:20 broker_password:broker:24; do file=$${entry%%:*}; rest=$${entry#*:}; dir=$${rest%%:*}; size=$${rest##*:} [ -s "$$dir/$$file" ] || head -c "$$size" /dev/urandom | od -An -tx1 | tr -d ' \n' > "$$dir/$$file" done - rm -f s3-init/* + rm -f s3-init/* rabbitmq/* relay/* worker/* cp s3/s3_root_user s3/s3_root_password api/s3_access_key_id api/s3_secret_access_key s3-init/ - printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=10&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=api&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" > api/database_url + db_url() { printf 'postgresql://messenger:%s@postgres:5432/messenger?connection_limit=%s&pool_timeout=5&connect_timeout=5&socket_timeout=10&application_name=%s&options=-c%%20statement_timeout%%3D5000' "$$(cat postgres/pg_password)" "$$1" "$$2"; } + db_url 10 api > api/database_url + db_url 5 worker > worker/database_url + db_url 3 relay > relay/database_url printf 'redis://:%s@redis:6379/0' "$$(cat redis/redis_password)" > api/cache_url printf 'postgresql://messenger:%s@postgres:5432/messenger' "$$(cat postgres/pg_password)" > migrate/database_url + printf 'amqp://messenger:%s@rabbitmq:5672/' "$$(cat broker/broker_password)" > worker/broker_url + cp worker/broker_url relay/ + printf 'default_user = messenger\ndefault_pass = %s\nloopback_users = none\nlog.console = true\nlisteners.tcp.default = 5672\n' "$$(cat broker/broker_password)" > rabbitmq/10-messenger.conf cp api/database_url api/s3_access_key_id api/s3_secret_access_key reconciler/ - chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/* + cp api/s3_access_key_id api/s3_secret_access_key worker/ + chmod 0444 postgres/* redis/* api/* migrate/* s3/* s3-init/* reconciler/* broker/* rabbitmq/* relay/* worker/* deploy: resources: limits: { cpus: "0.1", memory: 32M } @@ -160,6 +167,7 @@ services: S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} volumes: - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: api } } deploy: @@ -184,6 +192,7 @@ services: command: ["node", "dist/reconcile.js", "--apply", "--loop", "--grace-seconds=${RECONCILE_GRACE_SECONDS:-3600}", "--interval-seconds=${RECONCILE_INTERVAL_SECONDS:-300}"] environment: DATABASE_URL_FILE: /run/secrets/database_url + STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400} S3_ENDPOINT: http://s3:9000 S3_REGION: ${S3_REGION:-us-east-1} S3_BUCKET: ${S3_BUCKET:-messenger-attachments} @@ -203,6 +212,89 @@ services: condition: service_completed_successfully restart: unless-stopped + rabbitmq: + image: rabbitmq:4.0.5-alpine@sha256:e045b5166b9188a38eee5c99411709aa1f0ffa2ac75664053e64cb69411f7c32 + hostname: rabbitmq + volumes: + - rabbitmqdata:/var/lib/rabbitmq + - { type: volume, source: secrets, target: /etc/rabbitmq/conf.d, read_only: true, volume: { subpath: rabbitmq } } + deploy: + resources: + limits: { cpus: "0.5", memory: 512M } + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "check_port_connectivity"] + interval: 10s + timeout: 10s + retries: 12 + start_period: 20s + depends_on: + secrets-init: + condition: service_completed_successfully + restart: unless-stopped + + relay: + build: + context: . + target: runtime + image: mtusi-messenger-lab5-api:dev + command: ["node", "dist/relay.js"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + JOB_STALE_SECONDS: ${JOB_STALE_SECONDS:-300} + RELAY_FAULT: ${RELAY_FAULT:-} + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: relay } } + deploy: + resources: + limits: { cpus: "0.25", memory: 128M } + healthcheck: + disable: true + stop_grace_period: 10s + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + restart: unless-stopped + + worker: + build: + context: . + target: runtime + image: mtusi-messenger-lab5-api:dev + command: ["node", "dist/worker.js"] + environment: + DATABASE_URL_FILE: /run/secrets/database_url + BROKER_URL_FILE: /run/secrets/broker_url + S3_ENDPOINT: http://s3:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-90} + WORKER_FAULT: ${WORKER_FAULT:-} + volumes: + - { type: volume, source: secrets, target: /run/secrets, read_only: true, volume: { subpath: worker } } + deploy: + resources: + limits: { cpus: "1.0", memory: 768M } + healthcheck: + disable: true + stop_grace_period: 30s + depends_on: + migrate: + condition: service_completed_successfully + rabbitmq: + condition: service_healthy + s3-init: + condition: service_completed_successfully + restart: unless-stopped + lb: image: haproxy:3.0.6-alpine ports: @@ -237,4 +329,5 @@ services: volumes: pgdata: s3data: + rabbitmqdata: secrets: diff --git a/package-lock.json b/package-lock.json index 33632d6b..b0690fb2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,6 +16,7 @@ "@nestjs/platform-fastify": "^10.4.15", "@nestjs/swagger": "7.4.2", "@prisma/client": "6.1.0", + "amqplib": "0.10.5", "argon2": "0.41.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", @@ -28,6 +29,7 @@ "@nestjs/cli": "^10.4.9", "@nestjs/schematics": "^10.2.3", "@nestjs/testing": "^10.4.15", + "@types/amqplib": "0.10.6", "@types/jest": "^29.5.14", "@types/node": "^20.17.9", "@types/supertest": "^6.0.2", @@ -46,6 +48,26 @@ "typescript": "^5.7.2" } }, + "node_modules/@acuminous/bitsyntax": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@acuminous/bitsyntax/-/bitsyntax-0.1.2.tgz", + "integrity": "sha512-29lUK80d1muEQqiUsSo+3A0yP6CdspgC95EnKBMi22Xlwt79i/En4Vr67+cXhU+cZjbti3TgGGC5wy1stIywVQ==", + "license": "MIT", + "dependencies": { + "buffer-more-ints": "~1.0.0", + "debug": "^4.3.4", + "safe-buffer": "~5.1.2" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/@acuminous/bitsyntax/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, "node_modules/@angular-devkit/core": { "version": "17.3.11", "resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-17.3.11.tgz", @@ -4334,6 +4356,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/amqplib": { + "version": "0.10.6", + "resolved": "https://registry.npmjs.org/@types/amqplib/-/amqplib-0.10.6.tgz", + "integrity": "sha512-vQLVypBS1JQcfTXhl1Td1EEeLdtb+vuulOb4TrzYiLyP2aYLMAEzB3pNmEA0jBm0xIXu946Y7Xwl19Eidl32SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/babel__core": { "version": "7.20.5", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", @@ -5044,6 +5076,20 @@ "ajv": "^8.8.2" } }, + "node_modules/amqplib": { + "version": "0.10.5", + "resolved": "https://registry.npmjs.org/amqplib/-/amqplib-0.10.5.tgz", + "integrity": "sha512-Dx5zmy0Ur+Q7LPPdhz+jx5IzmJBoHd15tOeAfQ8SuvEtyPJ20hBemhOBA4b1WeORCRa0ENM/kHCzmem1w/zHvQ==", + "license": "MIT", + "dependencies": { + "@acuminous/bitsyntax": "^0.1.2", + "buffer-more-ints": "~1.0.0", + "url-parse": "~1.5.10" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/ansi-colors": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", @@ -5518,6 +5564,12 @@ "dev": true, "license": "MIT" }, + "node_modules/buffer-more-ints": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz", + "integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg==", + "license": "MIT" + }, "node_modules/call-bind": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz", @@ -10056,6 +10108,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/querystringify": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", + "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", + "license": "MIT" + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", @@ -10196,6 +10254,12 @@ "node": ">=0.10.0" } }, + "node_modules/requires-port": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", + "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", + "license": "MIT" + }, "node_modules/resolve": { "version": "1.22.12", "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", @@ -11806,6 +11870,16 @@ "punycode": "^2.1.0" } }, + "node_modules/url-parse": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", + "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, "node_modules/util-deprecate": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", diff --git a/package.json b/package.json index 6b4f848d..88254751 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "mtusi-messenger-lab5", "version": "1.0.0", - "description": "Lab 4: messenger API with S3 attachments (NestJS + Fastify)", + "description": "Lab 5: messenger API with S3 attachments and background image processing (NestJS + Fastify)", "private": true, "license": "UNLICENSED", "scripts": { @@ -20,6 +20,7 @@ "@nestjs/platform-fastify": "^10.4.15", "@nestjs/swagger": "7.4.2", "@prisma/client": "6.1.0", + "amqplib": "0.10.5", "argon2": "0.41.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.1", @@ -32,6 +33,7 @@ "@nestjs/cli": "^10.4.9", "@nestjs/schematics": "^10.2.3", "@nestjs/testing": "^10.4.15", + "@types/amqplib": "0.10.6", "@types/jest": "^29.5.14", "@types/node": "^20.17.9", "@types/supertest": "^6.0.2", diff --git a/scripts/job-scenario.py b/scripts/job-scenario.py new file mode 100644 index 00000000..ea3abd7a --- /dev/null +++ b/scripts/job-scenario.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Defense scenarios for background attachment processing; run inside the tools container.""" +import base64 +import hashlib +import json +import os +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid + +BASE = os.environ.get('BASE_URL', 'http://localhost:8080') +SAMPLE = open(os.path.join(os.path.dirname(__file__), '..', 'tests', 'fixtures', 'sample.png'), 'rb').read() +STARTED = time.monotonic() + + +def log(*parts): + print('[%6.1fs]' % (time.monotonic() - STARTED), *parts, flush=True) + + +def call(method, path, body=None, headers=None, raw=None): + data = raw if raw is not None else (json.dumps(body).encode() if body is not None else None) + all_headers = dict(headers or {}) + if body is not None: + all_headers['Content-Type'] = 'application/json' + request = urllib.request.Request(BASE + path, data=data, method=method, headers=all_headers) + try: + with urllib.request.urlopen(request, timeout=15) as response: + return response.status, response.read(), response.headers + except urllib.error.HTTPError as error: + return error.code, error.read(), error.headers + except OSError as error: + return 0, str(error).encode(), {} + + +def json_of(raw): + try: + return json.loads(raw or b'null') + except ValueError: + return None + + +def compose(*args): + log('$ docker compose', ' '.join(args)) + subprocess.run(['docker', 'compose', *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def psql(sql): + out = subprocess.run( + ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-tA', '-F', ' | ', '-c', sql], + check=True, capture_output=True, text=True, + ) + return out.stdout.strip() + + +def queue_depth(): + time.sleep(6) + out = subprocess.run( + ['docker', 'compose', 'exec', '-T', 'rabbitmq', 'rabbitmqctl', '-q', 'list_queues', 'name', 'type', 'durable', 'messages_ready', 'messages_unacknowledged'], + capture_output=True, text=True, + ) + return out.stdout.strip() or out.stderr.strip() + + +def wait_ready(timeout=90): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if call('GET', '/health/ready')[0] == 200: + return + time.sleep(1) + sys.exit('API did not become ready') + + +def session(): + username = 'job_' + uuid.uuid4().hex[:8] + password = 'Job-scenario-' + uuid.uuid4().hex + code, raw, _ = call('POST', '/api/v1/users', {'username': username, 'display_name': 'Job scenario', 'password': password}) + if code != 201: + sys.exit('register failed: %s' % code) + user = json_of(raw) + credential = base64.b64encode((username + ':' + password).encode()).decode() + code, raw, _ = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential}) + if code != 201: + sys.exit('login failed: %s' % code) + auth = {'Authorization': 'Bearer ' + json_of(raw)['token']} + code, raw, _ = call('POST', '/api/v1/chats', {'title': 'Job scenario', 'member_ids': [user['id']]}, auth) + if code != 201: + sys.exit('chat failed: %s' % code) + chat = json_of(raw)['id'] + log('user', user['id'], 'chat', chat) + return auth, chat + + +def upload(auth, chat, body=SAMPLE): + code, raw, headers = call( + 'POST', '/api/v1/chats/%s/attachments?filename=sample.png' % chat, + headers={**auth, 'Content-Type': 'image/png'}, raw=body, + ) + attachment = json_of(raw) + log('POST attachment ->', code, 'status=%s' % attachment.get('status'), 'id=%s' % attachment.get('id'), + 'instance=%s' % headers.get('X-Instance-Id')) + if code != 202: + sys.exit('upload failed') + return attachment['id'] + + +def message(auth, chat, text, attachments=()): + code, raw, _ = call( + 'POST', '/api/v1/chats/%s/messages' % chat, {'text': text, 'attachment_ids': list(attachments)}, + {**auth, 'Idempotency-Key': uuid.uuid4().hex}, + ) + log('POST message', 'with %d attachment(s)' % len(attachments), '->', code, 'id=%s' % (json_of(raw) or {}).get('id')) + return code + + +def metadata(auth, attachment): + code, raw, _ = call('GET', '/api/v1/attachments/' + attachment, headers=auth) + return code, json_of(raw) + + +def content_status(auth, attachment, variant='original'): + return call('GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment, variant), headers=auth)[0] + + +def wait_status(auth, attachment, wanted, timeout=150): + deadline = time.monotonic() + timeout + last = None + while time.monotonic() < deadline: + code, meta = metadata(auth, attachment) + if code == 200 and meta['status'] != last: + last = meta['status'] + log('GET attachment -> status=%s error_code=%s' % (last, meta['error_code'])) + if code == 200 and meta['status'] in wanted: + return meta + time.sleep(1) + sys.exit('attachment did not reach %s' % '/'.join(wanted)) + + +def check_ready(auth, attachment, meta): + code, raw, _ = call('GET', '/api/v1/attachments/%s/content' % attachment, headers=auth) + log('original ->', code, 'sha256 matches upload:', code == 200 and hashlib.sha256(raw).hexdigest() == hashlib.sha256(SAMPLE).hexdigest()) + for variant in meta['variants']: + code, raw, headers = call('GET', '/api/v1/attachments/%s/content?variant=%s' % (attachment, variant['name']), headers=auth) + log('%-9s -> %s %s %dx%d sha256 matches metadata: %s' % ( + variant['name'], code, headers.get('Content-Type'), variant['width'], variant['height'], + hashlib.sha256(raw).hexdigest() == variant['sha256'])) + + +def job_state(attachment): + log('job:', psql("SELECT id, status, attempt, max_attempts, error_code FROM attachment_jobs WHERE attachment_id = '%s'" % attachment)) + log('variants rows:', psql("SELECT count(*) FROM attachment_variants WHERE attachment_id = '%s'" % attachment)) + log('events:', psql("SELECT string_agg(e.event, ' -> ' ORDER BY e.id) FROM job_events e JOIN attachment_jobs j ON j.id = e.job_id WHERE j.attachment_id = '%s'" % attachment)) + + +def scenario_restart(): + """Level 3: worker down -> upload 202 -> restart API and broker -> worker up -> ready.""" + wait_ready() + auth, chat = session() + compose('stop', 'worker') + attachment = upload(auth, chat) + log('content while queued ->', content_status(auth, attachment)) + message(auth, chat, '', [attachment]) + message(auth, chat, 'other messages keep working') + log('queues:', queue_depth()) + compose('restart', 'api', 'rabbitmq') + wait_ready() + log('queues after broker restart:', queue_depth()) + log('status after restarts:', metadata(auth, attachment)[1]['status']) + compose('start', 'worker') + meta = wait_status(auth, attachment, ['ready', 'failed']) + check_ready(auth, attachment, meta) + job_state(attachment) + + +SCENARIOS = {'restart': scenario_restart} + +if __name__ == '__main__': + if len(sys.argv) != 2 or sys.argv[1] not in SCENARIOS: + sys.exit('usage: job-scenario.py %s' % '|'.join(SCENARIOS)) + SCENARIOS[sys.argv[1]]() diff --git a/scripts/restart.sh b/scripts/restart.sh index 20e1da65..416c6280 100644 --- a/scripts/restart.sh +++ b/scripts/restart.sh @@ -2,8 +2,8 @@ set -eu cd "$(dirname "$0")/.." started() { - docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis s3 api lb) + docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis s3 rabbitmq api lb) } started -docker compose restart postgres redis s3 api lb +docker compose restart postgres redis s3 rabbitmq api lb started diff --git a/src/broker/broker.ts b/src/broker/broker.ts new file mode 100644 index 00000000..700efb43 --- /dev/null +++ b/src/broker/broker.ts @@ -0,0 +1,57 @@ +import { Logger } from '@nestjs/common'; +import amqp, { Channel, Connection } from 'amqplib'; +import { readFileSync } from 'fs'; + +export const JOB_QUEUE = 'attachment.jobs'; +export const DEAD_LETTER_QUEUE = 'attachment.jobs.dlq'; +const DELIVERY_LIMIT = 20; +const RECONNECT_MAX_MS = 10000; + +export function brokerUrl(): string { + const file = process.env.BROKER_URL_FILE; + const url = file ? readFileSync(file, 'utf8').trim() : process.env.BROKER_URL; + if (!url) { + throw new Error('BROKER_URL_FILE or BROKER_URL must be set'); + } + return url; +} + +export async function assertTopology(channel: Channel): Promise { + await channel.assertQueue(DEAD_LETTER_QUEUE, { + durable: true, + arguments: { 'x-queue-type': 'quorum' }, + }); + await channel.assertQueue(JOB_QUEUE, { + durable: true, + arguments: { + 'x-queue-type': 'quorum', + 'x-delivery-limit': DELIVERY_LIMIT, + 'x-dead-letter-exchange': '', + 'x-dead-letter-routing-key': DEAD_LETTER_QUEUE, + }, + }); +} + +export async function connectWithRetry( + logger: Logger, + stopping: () => boolean, +): Promise { + let delay = 500; + while (!stopping()) { + try { + const connection = await amqp.connect(brokerUrl(), { timeout: 5000 }); + logger.log('connected to broker'); + return connection; + } catch (error) { + const reason = error instanceof Error ? error.message.split(' ')[0] : 'unknown'; + logger.warn(`broker unavailable (${reason}), retry in ${delay} ms`); + await sleep(delay); + delay = Math.min(RECONNECT_MAX_MS, delay * 2); + } + } + return null; +} + +export function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/src/jobs/job-store.ts b/src/jobs/job-store.ts index b1b4a599..82b38e2d 100644 --- a/src/jobs/job-store.ts +++ b/src/jobs/job-store.ts @@ -158,6 +158,35 @@ export async function recoverExpiredLeases( return recovered; } +export async function republishStale( + prisma: PrismaClient, + staleMs: number, + now = new Date(), + limit = 100, +): Promise { + const cutoff = new Date(now.getTime() - staleMs); + const stale = await prisma.$queryRaw` + SELECT j.id, j.attachment_id AS "attachmentId", j.pipeline_version AS "pipelineVersion", j.attempt + FROM attachment_jobs j + WHERE j.status = 'queued' + AND j.next_attempt_at < ${cutoff} + AND NOT EXISTS ( + SELECT 1 FROM outbox o + WHERE o.job_id = j.id AND (o.published_at IS NULL OR o.published_at > ${cutoff}) + ) + ORDER BY j.next_attempt_at + LIMIT ${limit}`; + for (const job of stale) { + await prisma.$transaction(async (tx) => { + await tx.jobEvent.create({ + data: { jobId: job.id, attempt: job.attempt, event: 'republished', createdAt: now }, + }); + await publishLater(tx, job, now); + }); + } + return stale.length; +} + export type ReplayResult = 'replayed' | 'already_ready' | 'not_failed' | 'not_found'; export async function replayJob( diff --git a/src/jobs/processor.ts b/src/jobs/processor.ts index 8183885f..13ceea2d 100644 --- a/src/jobs/processor.ts +++ b/src/jobs/processor.ts @@ -29,6 +29,11 @@ export function processorOptions(): ProcessorOptions { }; } +export interface ProcessorHooks { + afterStore?: () => Promise; + afterCommit?: () => Promise; +} + class PermanentError extends Error { constructor( readonly code: string, @@ -47,7 +52,7 @@ export class JobProcessor { private readonly prisma: PrismaClient, private readonly s3: S3Service, private readonly options: ProcessorOptions = processorOptions(), - private readonly hooks: { afterStore?: () => Promise } = {}, + private readonly hooks: ProcessorHooks = {}, ) {} async handle(message: JobMessage): Promise { @@ -195,6 +200,7 @@ export class JobProcessor { this.logger.warn(`job ${lease.id}: lease lost before commit, result left to owner`); return 'skipped'; } + await this.hooks.afterCommit?.(); await this.removeStaging(attachment); return 'ready'; } diff --git a/src/relay.ts b/src/relay.ts new file mode 100644 index 00000000..082d6b98 --- /dev/null +++ b/src/relay.ts @@ -0,0 +1,130 @@ +import { Logger } from '@nestjs/common'; +import { ConfirmChannel } from 'amqplib'; +import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; +import { PrismaService } from './db/prisma.service'; +import { JobMessage } from './jobs/job-message'; +import { recoverExpiredLeases, republishStale } from './jobs/job-store'; + +const BATCH_SIZE = 100; +const POLL_MS = Number(process.env.RELAY_POLL_MS ?? 500); +const SWEEP_MS = Number(process.env.RELAY_SWEEP_MS ?? 5000); +const STALE_MS = Number(process.env.JOB_STALE_SECONDS ?? 300) * 1000; +const FAULT = process.env.RELAY_FAULT; + +const logger = new Logger('OutboxRelay'); +const prisma = new PrismaService(); +let stopping = false; + +async function publishBatch(channel: ConfirmChannel): Promise { + return prisma.$transaction( + async (tx) => { + const rows = await tx.$queryRaw<{ id: bigint; payload: JobMessage }[]>` + SELECT id, payload FROM outbox + WHERE published_at IS NULL AND available_at <= ${new Date()} + ORDER BY id + LIMIT ${BATCH_SIZE} + FOR UPDATE SKIP LOCKED`; + if (rows.length === 0) { + return 0; + } + for (const { payload } of rows) { + channel.sendToQueue(JOB_QUEUE, Buffer.from(JSON.stringify(payload)), { + persistent: true, + contentType: 'application/json', + messageId: payload.job_id, + type: payload.type, + }); + } + await channel.waitForConfirms(); + logger.log(`published ${rows.length} job message(s), broker confirmed`); + if (FAULT === 'exit-after-confirm') { + logger.warn('fault injection: exit after broker confirm, before outbox is marked'); + process.kill(process.pid, 'SIGKILL'); + await sleep(60000); + } + await tx.outboxEntry.updateMany({ + where: { id: { in: rows.map((row) => row.id) } }, + data: { publishedAt: new Date(), publishAttempts: { increment: 1 } }, + }); + return rows.length; + }, + { timeout: 15000 }, + ); +} + +async function sweep(): Promise { + const recovered = await recoverExpiredLeases(prisma); + const republished = await republishStale(prisma, STALE_MS); + if (recovered + republished > 0) { + logger.log(`lease expired: ${recovered}, stale queued republished: ${republished}`); + } +} + +async function run(): Promise { + let lastSweep = 0; + while (!stopping) { + const connection = await connectWithRetry(logger, () => stopping); + if (!connection) { + break; + } + let closed = false; + connection.on('close', () => { + closed = true; + }); + connection.on('error', () => { + closed = true; + }); + try { + const channel = await connection.createConfirmChannel(); + channel.on('error', () => { + closed = true; + }); + channel.on('close', () => { + closed = true; + }); + await assertTopology(channel); + while (!stopping && !closed) { + let published = 0; + try { + published = await publishBatch(channel); + if (Date.now() - lastSweep >= SWEEP_MS) { + await sweep(); + lastSweep = Date.now(); + } + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`relay pass failed: ${reason}`); + await sleep(1000); + } + if (published < BATCH_SIZE) { + await sleep(POLL_MS); + } + } + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`broker channel failed: ${reason}`); + } + await connection.close().catch(() => undefined); + if (!stopping) { + logger.warn('broker connection lost, reconnecting'); + await sleep(1000); + } + } +} + +for (const signal of ['SIGTERM', 'SIGINT'] as const) { + process.once(signal, () => { + stopping = true; + }); +} + +run() + .then(async () => { + await prisma.$disconnect(); + logger.log('stopped'); + process.exit(0); + }) + .catch((error) => { + logger.error(error instanceof Error ? error.message : 'fatal error'); + process.exit(1); + }); diff --git a/src/worker.ts b/src/worker.ts new file mode 100644 index 00000000..079a1a25 --- /dev/null +++ b/src/worker.ts @@ -0,0 +1,138 @@ +import { Logger } from '@nestjs/common'; +import { Channel, ConsumeMessage } from 'amqplib'; +import { assertTopology, connectWithRetry, JOB_QUEUE, sleep } from './broker/broker'; +import { PrismaService } from './db/prisma.service'; +import { parseJobMessage } from './jobs/job-message'; +import { JobProcessor, ProcessorHooks, processorOptions } from './jobs/processor'; +import { S3Service } from './storage/s3.service'; + +const CONCURRENCY = Number(process.env.WORKER_CONCURRENCY ?? 2); +const INFRA_RETRY_MS = Number(process.env.WORKER_INFRA_RETRY_MS ?? 5000); +const DRAIN_TIMEOUT_MS = Number(process.env.WORKER_DRAIN_TIMEOUT_MS ?? 25000); +const FAULT = process.env.WORKER_FAULT; + +const logger = new Logger('Worker'); +const prisma = new PrismaService(); +const s3 = new S3Service(); +const processor = new JobProcessor(prisma, s3, processorOptions(), faultHooks()); +let stopping = false; +let inFlight = 0; + +function faultHooks(): ProcessorHooks { + const crash = (point: string) => async () => { + logger.warn(`fault injection: worker killed ${point}`); + process.kill(process.pid, 'SIGKILL'); + await sleep(60000); + }; + if (FAULT === 'exit-after-store') { + return { afterStore: crash('after storing objects, before commit and ack') }; + } + if (FAULT === 'exit-after-commit') { + return { afterCommit: crash('after commit, before ack') }; + } + return {}; +} + +async function handle(channel: Channel, delivery: ConsumeMessage): Promise { + inFlight++; + try { + const message = parseJobMessage(delivery.content); + if (!message) { + logger.warn('malformed job message moved to dead letter queue'); + channel.nack(delivery, false, false); + return; + } + const outcome = await processor.handle(message); + logger.log( + `job ${message.job_id} attempt ${message.attempt}` + + `${delivery.fields.redelivered ? ' (redelivered)' : ''}: ${outcome}`, + ); + channel.ack(delivery); + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`job handling interrupted (${reason}), returning message after ${INFRA_RETRY_MS} ms`); + await sleep(INFRA_RETRY_MS); + try { + channel.nack(delivery, false, true); + } catch { + logger.warn('channel closed, broker will redeliver unacked message'); + } + } finally { + inFlight--; + } +} + +async function run(): Promise { + while (!stopping) { + const connection = await connectWithRetry(logger, () => stopping); + if (!connection) { + break; + } + const closed = new Promise((resolve) => { + connection.on('close', () => resolve()); + connection.on('error', () => resolve()); + }); + try { + const channel = await connection.createChannel(); + await assertTopology(channel); + await channel.prefetch(CONCURRENCY); + const { consumerTag } = await channel.consume( + JOB_QUEUE, + (delivery) => { + if (delivery) { + void handle(channel, delivery); + } + }, + { noAck: false }, + ); + logger.log(`consuming ${JOB_QUEUE} with prefetch ${CONCURRENCY}`); + const stop = new Promise((resolve) => { + const timer = setInterval(() => { + if (stopping) { + clearInterval(timer); + resolve(); + } + }, 200); + void closed.then(() => { + clearInterval(timer); + resolve(); + }); + }); + await stop; + if (stopping) { + await channel.cancel(consumerTag).catch(() => undefined); + const deadline = Date.now() + DRAIN_TIMEOUT_MS; + while (inFlight > 0 && Date.now() < deadline) { + await sleep(100); + } + logger.log(`drained, ${inFlight} job(s) left unacked for redelivery`); + } + } catch (error) { + const reason = error instanceof Error ? error.name : 'unknown error'; + logger.error(`broker channel failed: ${reason}`); + } + await connection.close().catch(() => undefined); + if (!stopping) { + logger.warn('broker connection lost, reconnecting'); + await sleep(1000); + } + } +} + +for (const signal of ['SIGTERM', 'SIGINT'] as const) { + process.once(signal, () => { + stopping = true; + }); +} + +run() + .then(async () => { + await prisma.$disconnect(); + s3.onModuleDestroy(); + logger.log('stopped'); + process.exit(0); + }) + .catch((error) => { + logger.error(error instanceof Error ? error.message : 'fatal error'); + process.exit(1); + }); diff --git a/test/helpers.ts b/test/helpers.ts index 5f315855..2d083815 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -13,6 +13,7 @@ import { parseJobMessage } from '../src/jobs/job-message'; import { JobProcessor, Outcome, + ProcessorHooks, ProcessorOptions, processorOptions, } from '../src/jobs/processor'; @@ -55,7 +56,7 @@ export async function createTestApp( export async function processAttachment( app: INestApplication, attachmentId: string, - hooks: { afterStore?: () => Promise } = {}, + hooks: ProcessorHooks = {}, options: Partial = {}, ): Promise { const prisma = app.get(PrismaService); diff --git a/test/jobs.e2e-spec.ts b/test/jobs.e2e-spec.ts index bba96b5c..85573e0d 100644 --- a/test/jobs.e2e-spec.ts +++ b/test/jobs.e2e-spec.ts @@ -5,7 +5,7 @@ import request from 'supertest'; import { ApiError } from '../src/common/filters/api-error'; import { PrismaService } from '../src/db/prisma.service'; import { jobMessage, parseJobMessage } from '../src/jobs/job-message'; -import { backoffMs, recoverExpiredLeases, replayJob } from '../src/jobs/job-store'; +import { backoffMs, recoverExpiredLeases, replayJob, republishStale } from '../src/jobs/job-store'; import { JobProcessor, processorOptions } from '../src/jobs/processor'; import { fitInside } from '../src/jobs/variants'; import { S3Service } from '../src/storage/s3.service'; @@ -235,6 +235,24 @@ describe('Фоновая обработка вложений (e2e)', () => { expect(await events(id)).toEqual(['enqueued', 'processing', 'lease_expired', 'processing', 'ready']); }); + it('сообщение потеряно брокером: queued без свежей публикации публикуется повторно один раз', async () => { + const id = await upload(); + const row = await job(id); + const later = new Date(Date.now() + 10 * 60 * 1000); + expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBe(0); + await prisma.outboxEntry.updateMany({ + where: { jobId: row.id }, + data: { publishedAt: new Date() }, + }); + expect(await republishStale(prisma, 5 * 60 * 1000, new Date())).toBe(0); + expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBeGreaterThanOrEqual(1); + expect(await prisma.outboxEntry.count({ where: { jobId: row.id } })).toBe(2); + expect(await republishStale(prisma, 5 * 60 * 1000, later)).toBe(0); + expect(await prisma.outboxEntry.count({ where: { jobId: row.id } })).toBe(2); + expect(await processAttachment(app, id)).toBe('ready'); + expect(await events(id)).toEqual(['enqueued', 'republished', 'processing', 'ready']); + }); + it('устаревшее сообщение, чужой attachment_id и другая pipeline_version игнорируются', async () => { const id = await upload(); const row = await job(id);