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 }); }