Carry over the lab 5 solution
Bring the application, own tests, Dockerfile, toolchain, compose stack,
HAProxy, k6, RustFS and RabbitMQ configuration, migrations, hooks,
scenario scripts and the CI job from the lab 5 solution commit 64d5c67,
keep the lab 5 Makefile targets on top of the unchanged skeleton
targets, and append the lab 5 solution variables to the skeleton
.env.example. The package and the application follow the contract
version 1.6.0, and the image, the throwaway test containers and the
broker vhost description are tagged lab6 so they do not collide with a
lab 5 stand on the same host.
This is the starting point of the lab 6 cycle: lint, own tests and the
offline skeleton check pass before any lab 6 change.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a0d3947710
commit
5ae3d77152
@@ -0,0 +1,18 @@
|
||||
services:
|
||||
relay:
|
||||
restart: "no"
|
||||
environment:
|
||||
FAULT_POINT: ${RELAY_FAULT_POINT:-}
|
||||
OUTBOX_POLL_SECONDS: "0.5"
|
||||
SWEEP_INTERVAL_SECONDS: "1"
|
||||
STAGING_RETENTION_SECONDS: ${FAULT_STAGING_RETENTION_SECONDS:-${STAGING_RETENTION_SECONDS:-86400}}
|
||||
|
||||
worker:
|
||||
restart: "no"
|
||||
environment:
|
||||
FAULT_POINT: ${WORKER_FAULT_POINT:-}
|
||||
FAULT_STALL_SECONDS: ${FAULT_STALL_SECONDS:-15}
|
||||
JOB_TIMEOUT_SECONDS: ${FAULT_JOB_TIMEOUT_SECONDS:-5}
|
||||
JOB_BACKOFF_BASE_SECONDS: ${FAULT_BACKOFF_BASE_SECONDS:-1}
|
||||
RENDER_TIMEOUT_SECONDS: ${FAULT_RENDER_TIMEOUT_SECONDS:-${RENDER_TIMEOUT_SECONDS:-30}}
|
||||
RENDER_MEMORY_MB: ${FAULT_RENDER_MEMORY_MB:-${RENDER_MEMORY_MB:-448}}
|
||||
@@ -0,0 +1,71 @@
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 4096
|
||||
hard-stop-after 5s
|
||||
tune.bufsize 32768
|
||||
tune.rcvbuf.client 65536
|
||||
tune.rcvbuf.server 65536
|
||||
tune.sndbuf.client 65536
|
||||
tune.sndbuf.server 65536
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
accepted_payload_size 8192
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold nx 2s
|
||||
hold other 2s
|
||||
hold refused 2s
|
||||
hold timeout 2s
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option dontlognull
|
||||
option dontlog-normal
|
||||
log-format "%ci [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] %HM %HPO"
|
||||
option http-server-close
|
||||
option redispatch 1
|
||||
retries 2
|
||||
retry-on conn-failure empty-response
|
||||
timeout connect 500ms
|
||||
timeout client 30s
|
||||
timeout server 10s
|
||||
timeout http-request 5s
|
||||
timeout http-keep-alive 5s
|
||||
timeout queue 3s
|
||||
timeout check 1s
|
||||
http-error status 502 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream replica failed","request_id":"%[var(txn.request_id)]"}}'
|
||||
http-error status 503 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"No ready API replica","request_id":"%[var(txn.request_id)]"}}'
|
||||
http-error status 504 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Upstream timeout","request_id":"%[var(txn.request_id)]"}}'
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
option forwardfor
|
||||
http-request set-var(txn.request_id) req.fhdr(X-Request-Id) if { req.fhdr(X-Request-Id) -m len 1:200 }
|
||||
http-request set-var(txn.request_id) uuid(4) unless { var(txn.request_id) -m found }
|
||||
http-request set-header X-Request-Id %[var(txn.request_id)]
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb
|
||||
http-check expect status 200
|
||||
acl message_path path_reg ^/api/v1/chats/[^/]+/messages$
|
||||
acl has_key req.hdr(Idempotency-Key) -m found
|
||||
http-request set-var(txn.replay_safe) bool(1) if METH_GET
|
||||
http-request set-var(txn.replay_safe) bool(1) if METH_POST message_path has_key
|
||||
http-request disable-l7-retry unless { var(txn.replay_safe) -m bool }
|
||||
default-server check init-state fully-down inter 1s fastinter 500ms downinter 2s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none maxconn "${API_SERVER_MAXCONN-64}"
|
||||
server-template api 8 api:8080
|
||||
|
||||
frontend stats
|
||||
bind :8404
|
||||
monitor-uri /healthz
|
||||
monitor fail if { nbsrv(api) lt 1 }
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 5s
|
||||
@@ -0,0 +1,106 @@
|
||||
import http from 'k6/http';
|
||||
import { check } from 'k6';
|
||||
import encoding from 'k6/encoding';
|
||||
import exec from 'k6/execution';
|
||||
|
||||
const BASE = __ENV.BASE_URL || 'http://lb:8080';
|
||||
const RATE = Number(__ENV.RATE || 50);
|
||||
const WARMUP = Number(__ENV.WARMUP || 10);
|
||||
const DURATION = Number(__ENV.DURATION || 60);
|
||||
const USERS = Math.max(2, Number(__ENV.USERS || 20));
|
||||
const READ_RATIO = Number(__ENV.READ_RATIO || 0.2);
|
||||
const VUS = Number(__ENV.VUS || Math.max(10, Math.ceil(RATE / 10)));
|
||||
const MAX_VUS = Number(__ENV.MAX_VUS || Math.max(VUS, Math.min(VUS * 4, 1000)));
|
||||
const RUN = __ENV.RUN_ID || Date.now().toString(36);
|
||||
const SUMMARY = __ENV.SUMMARY || '/out/summary.json';
|
||||
const JSON_HEADERS = { 'Content-Type': 'application/json' };
|
||||
|
||||
const phase = (startTime, duration) => ({
|
||||
executor: 'constant-arrival-rate',
|
||||
rate: RATE,
|
||||
timeUnit: '1s',
|
||||
startTime: `${startTime}s`,
|
||||
duration: `${duration}s`,
|
||||
preAllocatedVUs: VUS,
|
||||
maxVUs: MAX_VUS,
|
||||
gracefulStop: '5s',
|
||||
});
|
||||
|
||||
const measured = ['http_reqs', 'http_req_failed', 'http_req_duration', 'dropped_iterations', 'iterations'];
|
||||
|
||||
export const options = {
|
||||
setupTimeout: '180s',
|
||||
summaryTrendStats: ['avg', 'min', 'med', 'p(90)', 'p(95)', 'p(99)', 'max'],
|
||||
scenarios: Object.assign(WARMUP > 0 ? { warmup: phase(0, WARMUP) } : {}, { measure: phase(WARMUP, DURATION) }),
|
||||
thresholds: Object.fromEntries([
|
||||
...measured.map((metric) => [`${metric}{scenario:measure}`, []]),
|
||||
['http_req_duration{scenario:measure,name:post_message}', []],
|
||||
['http_req_duration{scenario:measure,name:get_history}', []],
|
||||
]),
|
||||
};
|
||||
|
||||
function created(response, what) {
|
||||
if (response.status !== 201) {
|
||||
throw new Error(`${what}: HTTP ${response.status}`);
|
||||
}
|
||||
return response.json();
|
||||
}
|
||||
|
||||
const bearer = (token, extra) => Object.assign({ Authorization: `Bearer ${token}` }, extra || {});
|
||||
|
||||
export function setup() {
|
||||
const actors = [];
|
||||
for (let i = 0; i < USERS; i++) {
|
||||
const username = `k6_${RUN}_${i}`.slice(0, 32);
|
||||
const password = `K6-${RUN}-${i}-synthetic`;
|
||||
const user = created(
|
||||
http.post(`${BASE}/api/v1/users`, JSON.stringify({ username, display_name: `k6 ${i}`, password }), { headers: JSON_HEADERS }),
|
||||
'register',
|
||||
);
|
||||
const basic = encoding.b64encode(`${username}:${password}`);
|
||||
const session = created(
|
||||
http.post(`${BASE}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${basic}` } }),
|
||||
'login',
|
||||
);
|
||||
actors.push({ id: user.id, token: session.token });
|
||||
}
|
||||
const chats = [];
|
||||
for (let i = 0; i < USERS; i += 2) {
|
||||
const [a, b] = [actors[i], actors[(i + 1) % USERS]];
|
||||
const body = JSON.stringify({ title: `k6 ${RUN} ${i}`, member_ids: [a.id, b.id] });
|
||||
const chat = created(http.post(`${BASE}/api/v1/chats`, body, { headers: bearer(a.token, JSON_HEADERS) }), 'chat');
|
||||
chats.push({ id: chat.id, tokens: [a.token, b.token] });
|
||||
}
|
||||
console.log('LOAD-START');
|
||||
return { chats };
|
||||
}
|
||||
|
||||
export default function (data) {
|
||||
const n = exec.scenario.iterationInTest;
|
||||
const chat = data.chats[n % data.chats.length];
|
||||
const token = chat.tokens[Math.floor(n / data.chats.length) % 2];
|
||||
if (Math.random() < READ_RATIO) {
|
||||
const response = http.get(`${BASE}/api/v1/chats/${chat.id}/messages?limit=50`, {
|
||||
headers: bearer(token),
|
||||
tags: { name: 'get_history' },
|
||||
timeout: '10s',
|
||||
});
|
||||
check(response, { 'history 200': (r) => r.status === 200 });
|
||||
return;
|
||||
}
|
||||
const key = `${RUN}-${exec.scenario.name}-${n}`;
|
||||
const response = http.post(`${BASE}/api/v1/chats/${chat.id}/messages`, JSON.stringify({ text: `k6 ${key}` }), {
|
||||
headers: bearer(token, Object.assign({ 'Idempotency-Key': key }, JSON_HEADERS)),
|
||||
tags: { name: 'post_message' },
|
||||
timeout: '10s',
|
||||
});
|
||||
check(response, { 'message 201': (r) => r.status === 201 });
|
||||
}
|
||||
|
||||
export function handleSummary(data) {
|
||||
delete data.setup_data;
|
||||
const reqs = data.metrics['http_reqs{scenario:measure}'];
|
||||
const failed = data.metrics['http_req_failed{scenario:measure}'];
|
||||
const line = `measure: ${reqs ? reqs.values.count : 0} requests, failed ratio ${failed ? failed.values.rate : 'n/a'}\n`;
|
||||
return { [SUMMARY]: JSON.stringify(data, null, 1), stdout: line };
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
{
|
||||
"rabbit_version": "4.1.8",
|
||||
"vhosts": [
|
||||
{"name": "messenger", "description": "lab6 attachment pipeline", "default_queue_type": "quorum"}
|
||||
],
|
||||
"exchanges": [
|
||||
{"name": "attachments", "vhost": "messenger", "type": "direct", "durable": true, "auto_delete": false, "internal": false, "arguments": {}},
|
||||
{"name": "attachments.dlx", "vhost": "messenger", "type": "fanout", "durable": true, "auto_delete": false, "internal": false, "arguments": {}}
|
||||
],
|
||||
"queues": [
|
||||
{"name": "attachments.process", "vhost": "messenger", "durable": true, "auto_delete": false, "arguments": {"x-queue-type": "quorum"}},
|
||||
{"name": "attachments.process.dlq", "vhost": "messenger", "durable": true, "auto_delete": false, "arguments": {"x-queue-type": "quorum"}}
|
||||
],
|
||||
"bindings": [
|
||||
{"source": "attachments", "vhost": "messenger", "destination": "attachments.process", "destination_type": "queue", "routing_key": "attachment.process.v1", "arguments": {}},
|
||||
{"source": "attachments.dlx", "vhost": "messenger", "destination": "attachments.process.dlq", "destination_type": "queue", "routing_key": "", "arguments": {}}
|
||||
],
|
||||
"policies": [
|
||||
{
|
||||
"vhost": "messenger",
|
||||
"name": "attachments-process",
|
||||
"pattern": "^attachments\\.process$",
|
||||
"apply-to": "queues",
|
||||
"priority": 10,
|
||||
"definition": {
|
||||
"dead-letter-exchange": "attachments.dlx",
|
||||
"dead-letter-strategy": "at-least-once",
|
||||
"overflow": "reject-publish",
|
||||
"delivery-limit": 10
|
||||
}
|
||||
},
|
||||
{
|
||||
"vhost": "messenger",
|
||||
"name": "attachments-dlq",
|
||||
"pattern": "^attachments\\.process\\.dlq$",
|
||||
"apply-to": "queues",
|
||||
"priority": 10,
|
||||
"definition": {
|
||||
"max-length": 100000,
|
||||
"overflow": "reject-publish"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
[rabbitmq_management,rabbitmq_prometheus].
|
||||
@@ -0,0 +1,21 @@
|
||||
listeners.tcp.default = 5672
|
||||
management.tcp.port = 15672
|
||||
prometheus.tcp.port = 15692
|
||||
|
||||
loopback_users.guest = true
|
||||
log.console = true
|
||||
log.console.level = info
|
||||
log.file = false
|
||||
|
||||
definitions.import_backend = local_filesystem
|
||||
definitions.local.path = /etc/rabbitmq/definitions.d
|
||||
|
||||
vm_memory_high_watermark.absolute = 256MiB
|
||||
disk_free_limit.absolute = 256MB
|
||||
raft.wal_max_size_bytes = 64000000
|
||||
|
||||
consumer_timeout = 300000
|
||||
heartbeat = 30
|
||||
|
||||
deprecated_features.permit.transient_nonexcl_queues = false
|
||||
deprecated_features.permit.global_qos = false
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "MessengerApiObjects",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:PutObject",
|
||||
"s3:DeleteObject",
|
||||
"s3:AbortMultipartUpload",
|
||||
"s3:ListMultipartUploadParts"
|
||||
],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments/*"]
|
||||
},
|
||||
{
|
||||
"Sid": "MessengerApiBucket",
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket", "s3:ListBucketMultipartUploads", "s3:GetBucketLocation"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments"]
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
secret() { tr -d '\r\n' < "/run/secrets/$1"; }
|
||||
endpoint="${S3_ENDPOINT:-http://s3:9000}"
|
||||
RC_HOST_root="${endpoint%%://*}://$(secret s3_root_user):$(secret s3_root_password)@${endpoint#*://}"
|
||||
RC_HOST_api="${endpoint%%://*}://$(secret s3_access_key_id):$(secret s3_secret_access_key)@${endpoint#*://}"
|
||||
export RC_HOST_root RC_HOST_api
|
||||
rc alias set anon "$endpoint" --anonymous >/dev/null
|
||||
case "${1:-}" in
|
||||
sh|wget) exec "$@" ;;
|
||||
esac
|
||||
exec rc "$@"
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
secret() { tr -d '\r\n' < "/run/secrets/$1"; }
|
||||
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||
endpoint="${S3_ENDPOINT:-http://s3:9000}"
|
||||
policy="${S3_API_POLICY:-messenger-api}"
|
||||
RC_HOST_root="${endpoint%%://*}://$(secret s3_root_user):$(secret s3_root_password)@${endpoint#*://}"
|
||||
export RC_HOST_root
|
||||
api_key=$(secret s3_access_key_id)
|
||||
rc ready root --timeout 10 >/dev/null
|
||||
rc bucket create --ignore-existing "root/$bucket" >/dev/null
|
||||
rc bucket anonymous set private "root/$bucket" >/dev/null
|
||||
sed "s/messenger-attachments/$bucket/g" /s3/api-policy.json > /tmp/api-policy.json
|
||||
rc admin policy create root "$policy" /tmp/api-policy.json >/dev/null
|
||||
rc admin user add root "$api_key" "$(secret s3_secret_access_key)" >/dev/null
|
||||
rc admin policy attach root "$policy" --user "$api_key" >/dev/null
|
||||
worker_key=$(secret s3_worker_access_key_id)
|
||||
sed "s/messenger-attachments/$bucket/g" /s3/worker-policy.json > /tmp/worker-policy.json
|
||||
rc admin policy create root messenger-worker /tmp/worker-policy.json >/dev/null
|
||||
rc admin user add root "$worker_key" "$(secret s3_worker_secret_access_key)" >/dev/null
|
||||
rc admin policy attach root messenger-worker --user "$worker_key" >/dev/null
|
||||
rc bucket lifecycle rule import "root/$bucket" /s3/lifecycle.json >/dev/null
|
||||
rc bucket anonymous get "root/$bucket" --json | grep -q '"permission": *"private"'
|
||||
rc admin user info root "$api_key" --json | grep -q "\"$policy\""
|
||||
rc admin user info root "$worker_key" --json | grep -q '"messenger-worker"'
|
||||
echo "s3-init: bucket=$bucket anonymous=private policy=$policy worker=messenger-worker lifecycle=abort-incomplete-uploads"
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"rules": [
|
||||
{
|
||||
"id": "abort-incomplete-uploads",
|
||||
"status": "Enabled",
|
||||
"prefix": "",
|
||||
"abortIncompleteMultipartUploadDays": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "MessengerWorkerRead",
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/staging/*",
|
||||
"arn:aws:s3:::messenger-attachments/originals/*",
|
||||
"arn:aws:s3:::messenger-attachments/variants/*"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "MessengerWorkerWrite",
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:PutObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::messenger-attachments/originals/*",
|
||||
"arn:aws:s3:::messenger-attachments/variants/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user