forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import {check, sleep} from 'k6';
|
||||
import {Counter, Trend} from 'k6/metrics';
|
||||
|
||||
const base = __ENV.BASE_URL || 'http://127.0.0.1:18084';
|
||||
const original = open('../../tests/fixtures/sample.png', 'b');
|
||||
const uploaded = new Counter('attachments_ready');
|
||||
const rejected = new Counter('attachments_rejected');
|
||||
const latency = new Trend('attachment_upload_ms', true);
|
||||
export const options = {vus: 10, iterations: 100, setupTimeout: '60s', thresholds: {checks: ['rate==1'], attachments_ready: ['count>0']}};
|
||||
|
||||
export function setup() {
|
||||
const actors = [];
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const username = `a_${Date.now()}_${i}`;
|
||||
const password = 'synthetic-attachment-password';
|
||||
const user = http.post(`${base}/api/v1/users`, JSON.stringify({username, display_name: 'Synthetic', password}), {headers: {'Content-Type': 'application/json'}});
|
||||
if (user.status !== 201) throw new Error(`registration: ${user.status}`);
|
||||
const session = http.post(`${base}/api/v1/auth/sessions`, null, {headers: {Authorization: `Basic ${encoding.b64encode(username + ':' + password)}`}});
|
||||
if (session.status !== 201) throw new Error(`login: ${session.status}`);
|
||||
const headers = {Authorization: `Bearer ${session.json('token')}`};
|
||||
const chat = http.post(`${base}/api/v1/chats`, JSON.stringify({title: 'Attachment experiment', member_ids: [user.json('id')]}), {headers: {...headers, 'Content-Type': 'application/json'}});
|
||||
if (chat.status !== 201) throw new Error(`chat: ${chat.status}`);
|
||||
actors.push({headers, chat: chat.json('id')});
|
||||
}
|
||||
return actors;
|
||||
}
|
||||
|
||||
export default function (actors) {
|
||||
const actor = actors[(__VU - 1) % actors.length];
|
||||
const response = http.post(`${base}/api/v1/chats/${actor.chat}/attachments?filename=sample.png`, original, {headers: {...actor.headers, 'Content-Type': 'image/png'}});
|
||||
latency.add(response.timings.duration);
|
||||
if (response.status === 201) {
|
||||
uploaded.add(1);
|
||||
const read = http.get(`${base}/api/v1/attachments/${response.json('id')}/content`, {headers: actor.headers, responseType: 'binary'});
|
||||
check(read, {'download complete': r => r.status === 200 && r.body.byteLength === original.byteLength});
|
||||
} else {
|
||||
rejected.add(1);
|
||||
check(response, {'bounded overload': r => r.status === 429 || r.status === 503});
|
||||
}
|
||||
sleep(0.05);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import { sleep } from 'k6';
|
||||
export const options = { vus: 1, iterations: 1, setupTimeout: '120s' };
|
||||
const base = __ENV.BASE_URL;
|
||||
const target = __ENV.TARGET_INSTANCE_ID;
|
||||
export function setup() {
|
||||
const username = 'fail_' + Date.now();
|
||||
const password = 'synthetic-failover-password';
|
||||
const user = http.post(base + '/api/v1/users', JSON.stringify({username, password, display_name:'Failover'}), {headers:{'Content-Type':'application/json'}});
|
||||
if (user.status !== 201) throw new Error('registration ' + user.status);
|
||||
const session = http.post(base + '/api/v1/auth/sessions', null, {headers:{Authorization:'Basic ' + encoding.b64encode(username + ':' + password)}});
|
||||
if (session.status !== 201) throw new Error('login ' + session.status);
|
||||
const headers = {Authorization:'Bearer ' + session.json().token, 'Content-Type':'application/json'};
|
||||
const chat = http.post(base + '/api/v1/chats', JSON.stringify({title:'Failover',member_ids:[user.json().id]}), {headers});
|
||||
if (chat.status !== 201) throw new Error('chat ' + chat.status);
|
||||
const seen = new Set();
|
||||
for (let i=0; i<20; i++) {
|
||||
const response = http.get(base + '/api/v1/users/me', {headers, timeout:'2s'});
|
||||
if (response.status !== 200) throw new Error('initial read ' + response.status);
|
||||
seen.add(response.headers['X-Instance-Id']);
|
||||
}
|
||||
if (seen.size < 2 || !seen.has(target)) throw new Error('target not observed through LB');
|
||||
const path = base + '/api/v1/chats/' + chat.json().id + '/messages';
|
||||
const original = http.post(path, JSON.stringify({text:'before failure'}), {headers:{...headers,'Idempotency-Key':'before'}});
|
||||
if (original.status !== 201) throw new Error('initial message ' + original.status);
|
||||
return {headers,path,original:original.json()};
|
||||
}
|
||||
export default function(data) {
|
||||
console.log('READY_TO_STOP ' + target);
|
||||
const started = Date.now();
|
||||
const confirmed = new Set([data.original.id]);
|
||||
let errors = 0, reads = 0, sequence = 0;
|
||||
const events = [];
|
||||
const lastInstances = [];
|
||||
while (Date.now() - started < 25000) {
|
||||
const response = http.post(data.path, JSON.stringify({text:'during-' + sequence}), {headers:{...data.headers,'Idempotency-Key':'during-' + sequence},timeout:'2s'});
|
||||
if (response.status === 201) {
|
||||
confirmed.add(response.json().id); sequence++;
|
||||
events.push({seconds:(Date.now()-started)/1000,instance:response.headers['X-Instance-Id']});
|
||||
lastInstances.push(response.headers['X-Instance-Id']);
|
||||
} else errors++;
|
||||
const read = http.get(data.path + '?limit=100', {headers:data.headers,timeout:'2s'});
|
||||
if (read.status === 200) reads++; else errors++;
|
||||
sleep(0.1);
|
||||
}
|
||||
const items = [];
|
||||
let path = data.path + '?limit=100';
|
||||
while (path) {
|
||||
const response = http.get(path, {headers:data.headers,timeout:'5s'});
|
||||
if (response.status !== 200) throw new Error('final history ' + response.status);
|
||||
items.push(...response.json().items);
|
||||
const cursor = response.json().next_cursor;
|
||||
path = cursor ? data.path + '?limit=100&cursor=' + encodeURIComponent(cursor) : null;
|
||||
}
|
||||
const ids = new Set(items.map(item=>item.id));
|
||||
if ([...confirmed].some(id=>!ids.has(id))) throw new Error('confirmed message lost');
|
||||
if (new Set(items.map(item=>item.text)).size !== items.length) throw new Error('uncertain retry duplicated');
|
||||
if (lastInstances.length < 5 || lastInstances.slice(-5).includes(target)) throw new Error('target still serves or insufficient writes');
|
||||
console.log(JSON.stringify({target,started_epoch_ms:started,confirmed:confirmed.size,reads,errors,events,pass:true}));
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import { check, sleep } from 'k6';
|
||||
export const options = { vus: 2, duration: '90s', thresholds: { checks: ['rate>0.95'] } };
|
||||
const base = __ENV.BASE_URL || 'https://hl.agapov.space';
|
||||
export function setup() {
|
||||
const username = `hpa_${Date.now()}`;
|
||||
const password = 'synthetic-autoscaling-password';
|
||||
const response = http.post(`${base}/api/v1/users`, JSON.stringify({ username, display_name: 'HPA CPU test', password }), { headers: { 'Content-Type': 'application/json' } });
|
||||
if (response.status !== 201) throw new Error(`registration: ${response.status}`);
|
||||
return { authorization: `Basic ${encoding.b64encode(`${username}:${password}`)}` };
|
||||
}
|
||||
export default function (data) {
|
||||
const response = http.post(`${base}/api/v1/auth/sessions`, null, { headers: { Authorization: data.authorization } });
|
||||
check(response, { 'authenticated login': r => r.status === 201 });
|
||||
// Keep one account below its 20 requests/s auth budget.
|
||||
sleep(0.1);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import { check, sleep } from 'k6';
|
||||
export const options = { vus: 8, iterations: 32, thresholds: { checks: ['rate==1'] } };
|
||||
const base = __ENV.BASE_URL || 'https://hl.agapov.space';
|
||||
export function setup() {
|
||||
const username = `idem_${Date.now()}`;
|
||||
const password = 'synthetic-idempotency-password';
|
||||
const registered = http.post(`${base}/api/v1/users`, JSON.stringify({ username, display_name: 'Idempotency', password }), { headers: { 'Content-Type': 'application/json' } });
|
||||
if (registered.status !== 201) throw new Error(`registration ${registered.status}`);
|
||||
const session = http.post(`${base}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${encoding.b64encode(`${username}:${password}`)}` } });
|
||||
if (session.status !== 201) throw new Error(`login ${session.status}`);
|
||||
const headers = { Authorization: `Bearer ${session.json().token}`, 'Content-Type': 'application/json', 'Idempotency-Key': 'shared-key' };
|
||||
const chat = http.post(`${base}/api/v1/chats`, JSON.stringify({ title: 'Retry race', member_ids: [registered.json().id] }), { headers });
|
||||
if (chat.status !== 201) throw new Error(`chat ${chat.status}`);
|
||||
return { headers, path: `${base}/api/v1/chats/${chat.json().id}/messages` };
|
||||
}
|
||||
export default function (data) {
|
||||
// Eight writers share four user slots. Retry admission failures with the same key/body.
|
||||
let response;
|
||||
for (let attempt = 0; attempt < 20; attempt++) {
|
||||
response = http.post(data.path, JSON.stringify({ text: 'one logical message' }), { headers: data.headers });
|
||||
if (response.status !== 503 && response.status !== 429) break;
|
||||
sleep(0.1);
|
||||
}
|
||||
check(response, { 'concurrent retry succeeds': r => r.status === 201 });
|
||||
console.log(`instance=${response.headers['X-Instance-Id']}, status=${response.status}`);
|
||||
}
|
||||
export function teardown(data) {
|
||||
const history = http.get(`${data.path}?limit=100`, { headers: data.headers });
|
||||
check(history, { 'exactly one stored message': r => r.status === 200 && r.json().items.length === 1 });
|
||||
const conflict = http.post(data.path, JSON.stringify({ text: 'different message' }), { headers: data.headers });
|
||||
check(conflict, { 'different body conflicts': r => r.status === 409 });
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import http from 'k6/http';
|
||||
import encoding from 'k6/encoding';
|
||||
import execution from 'k6/execution';
|
||||
import { check, sleep } from 'k6';
|
||||
import { Counter, Trend } from 'k6/metrics';
|
||||
|
||||
const base = __ENV.BASE_URL || 'https://hl.agapov.space';
|
||||
const seconds = Number(__ENV.DURATION || 30);
|
||||
const users = Number(__ENV.USERS || 16);
|
||||
const writes = new Counter('confirmed_messages');
|
||||
const attempts = new Counter('attempted_messages');
|
||||
const failures = new Counter('application_errors');
|
||||
const operations = new Counter('measured_operations');
|
||||
const failedWrites = new Counter('failed_writes');
|
||||
const latency = new Trend('message_latency_ms', true);
|
||||
export const options = {
|
||||
scenarios: {
|
||||
warmup: { executor: 'constant-vus', vus: 4, duration: '5s', gracefulStop: '0s' },
|
||||
measured: { executor: 'constant-vus', vus: Number(__ENV.VUS || 32), duration: `${seconds}s`, startTime: '10s', gracefulStop: '0s' },
|
||||
},
|
||||
setupTimeout: '180s',
|
||||
thresholds: { 'application_errors{status:429}': ['count>=0'], 'application_errors{status:503}': ['count>=0'], 'application_errors{status:0}': ['count>=0'] },
|
||||
summaryTrendStats: ['avg', 'p(50)', 'p(95)', 'p(99)', 'max'],
|
||||
};
|
||||
|
||||
export function setup() {
|
||||
const actors = [];
|
||||
const prefix = `bench_${Date.now()}`;
|
||||
for (let i = 0; i < users; i++) {
|
||||
let prepared = false;
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
for (let ready = 0; ready < 30; ready++) {
|
||||
if (http.get(base + '/health/ready', {timeout:'3s', tags:{phase:'setup'}}).status === 200) break;
|
||||
sleep(1);
|
||||
}
|
||||
const username = `${prefix}_${i}_${attempt}`;
|
||||
const password = 'synthetic-benchmark-password';
|
||||
let response = http.post(`${base}/api/v1/users`, JSON.stringify({ username, display_name: 'Synthetic', password }), { headers: { 'Content-Type': 'application/json' }, tags: { phase: 'setup' } });
|
||||
if (response.status !== 201) { console.warn(`setup registration: ${response.status}; abandoning synthetic actor`); sleep(1); continue; }
|
||||
const user = response.json();
|
||||
response = http.post(`${base}/api/v1/auth/sessions`, null, { headers: { Authorization: `Basic ${encoding.b64encode(`${username}:${password}`)}` }, tags: { phase: 'setup' } });
|
||||
if (response.status !== 201) { console.warn(`setup login: ${response.status}; abandoning synthetic actor`); sleep(1); continue; }
|
||||
const token = response.json().token;
|
||||
response = http.post(`${base}/api/v1/chats`, JSON.stringify({ title: 'Synthetic benchmark', member_ids: [user.id] }), { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, tags: { phase: 'setup' } });
|
||||
if (response.status !== 201) { console.warn(`setup chat: ${response.status}; abandoning synthetic actor`); sleep(1); continue; }
|
||||
actors.push({ token, chat: response.json().id });
|
||||
prepared = true;
|
||||
break;
|
||||
}
|
||||
if (!prepared) throw new Error("synthetic actor setup exhausted retries");
|
||||
}
|
||||
return actors;
|
||||
}
|
||||
|
||||
export default function (actors) {
|
||||
const measured = execution.scenario.name === 'measured';
|
||||
const actor = actors[(__VU - 1) % actors.length];
|
||||
const headers = { Authorization: `Bearer ${actor.token}`, 'Content-Type': 'application/json', 'Idempotency-Key': `${execution.scenario.name}:${__VU}:${__ITER}` };
|
||||
const path = `${base}/api/v1/chats/${actor.chat}/messages`;
|
||||
const payload = JSON.stringify({ text: `synthetic message ${__VU}:${__ITER}` });
|
||||
const response = http.post(path, payload, { headers, tags: { phase: 'load' } });
|
||||
if (measured) { latency.add(response.timings.duration); attempts.add(1); operations.add(1); }
|
||||
if (check(response, { 'message confirmed': r => r.status === 201 })) { if (measured) writes.add(1); }
|
||||
else if (measured) { failures.add(1, { status: String(response.status) }); failedWrites.add(1); }
|
||||
if (response.status === 201 && __ITER % 10 === 0) {
|
||||
if (measured) operations.add(1);
|
||||
const repeated = http.post(path, payload, { headers, tags: { phase: 'load' } });
|
||||
if (!check(repeated, { 'retry returns original': r => r.status === 201 && r.json().id === response.json().id })) { if (measured) failures.add(1, { status: String(repeated.status) }); }
|
||||
}
|
||||
if (measured) operations.add(1);
|
||||
const read = http.get(`${path}?limit=10`, { headers, tags: { phase: 'load' } });
|
||||
if (!check(read, { 'history readable': r => r.status === 200 })) { if (measured) failures.add(1, { status: String(read.status) }); }
|
||||
}
|
||||
|
||||
export function handleSummary(data) {
|
||||
return { stdout: JSON.stringify({ profile: { vus: Number(__ENV.VUS || 32), seconds, warmup_seconds: 5, drain_seconds: 5, users }, summary: data }) + '\n' };
|
||||
}
|
||||
Reference in New Issue
Block a user