forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
# Проверки реализации
|
||||
|
||||
- `make test-local`: временные PostgreSQL/Valkey/S3/broker/Nginx, два настоящих API и worker; smoke, failover, persistence, durable queued work. Удаляет только собственные ресурсы.
|
||||
- `LOCAL_COVERAGE=true scripts/test-local.sh`: дополнительно race и минимум 90% statements каждого Go-файла, включая entrypoint.
|
||||
- `LOCAL_TELEMETRY_STATE=<private-path> scripts/telemetry-local.sh`: отдельные Collector/Prometheus/Loki/Tempo/Grafana. Source указанного файла перед запуском telemetry-сценариев.
|
||||
- `OBSERVABILITY_TESTS=true scripts/test-local.sh`: ограниченные реальные отказы PostgreSQL, worker и Tempo. Скрипт восстанавливает собственные процессы при ошибке.
|
||||
- `RETRY_TRACE_TEST=true scripts/test-local.sh`: отдельный отказ S3, неудачная попытка и успешный retry в одной trace.
|
||||
- `scripts/ready-slo.sh`: целевая проверка ready burn на работающем изолированном стенде с LOCAL_TEST_WORK, BASE_URL и PROMETHEUS_URL.
|
||||
- `scripts/trace-probe.sh`: ищет реальный upload/worker trace и связанные Loki logs; credentials хранятся только в явно заданной приватной папке PROBE_WORK.
|
||||
|
||||
[Матрица контрактов](../docs/CONTRACT-CHECK.md), [конфигурация](../docs/CONFIGURATION.md), [результаты и ограничения](../REPORT.md). Публичные tests не изменялись. Fault unit/integration tests и реальные остановки процессов в отчёте различаются.
|
||||
|
||||
`student-tests/alerts.test.yaml` запускается promtool из закреплённого Prometheus image; regression покрывает canonical `le="60.0"`. Kubernetes restart hook дополнительно включает worker/broker; его обновление проверено синтаксически, фактический restart evidence относится к локальному стенду.
|
||||
@@ -0,0 +1,44 @@
|
||||
rule_files:
|
||||
- /rules/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- name: short spike consumes no sustained budget
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/chats",status_class="2xx"}'
|
||||
values: '0+100x96'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/chats",status_class="5xx"}'
|
||||
values: '0+0x24 20+0x72'
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: MessengerAPIBurnRate
|
||||
exp_alerts: []
|
||||
- name: persistent errors burn both windows
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/chats",status_class="2xx"}'
|
||||
values: '0+100x96'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/chats",status_class="5xx"}'
|
||||
values: '0+0x24 20+20x72'
|
||||
promql_expr_test:
|
||||
- eval_time: 6m
|
||||
expr: 'ALERTS{alertname="MessengerAPIBurnRate",alertstate="firing"}'
|
||||
exp_samples:
|
||||
- labels: '{__name__="ALERTS",alertname="MessengerAPIBurnRate",alertstate="firing",severity="warning"}'
|
||||
value: 1
|
||||
- name: ready histogram canonical boundary and resolution
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_ready_duration_seconds_count'
|
||||
values: '0+0x24 20+0x72'
|
||||
- series: 'messenger_ready_duration_seconds_bucket{le="60.0"}'
|
||||
values: '0+0x96'
|
||||
promql_expr_test:
|
||||
- eval_time: 2m45s
|
||||
expr: 'ALERTS{alertname="MessengerReadyBurnRate",alertstate="firing"}'
|
||||
exp_samples:
|
||||
- labels: '{__name__="ALERTS",alertname="MessengerReadyBurnRate",alertstate="firing",severity="warning"}'
|
||||
value: 1
|
||||
- eval_time: 4m
|
||||
expr: 'ALERTS{alertname="MessengerReadyBurnRate"}'
|
||||
exp_samples: []
|
||||
@@ -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' };
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Repeat the same read and rolled-back write three times for each index.
|
||||
SELECT 'EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON)
|
||||
SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=md5(''1'')::uuid
|
||||
AND (created_at,id)>(''2026-01-01Z''::timestamptz+85000*interval ''1 microsecond'',md5(''85000'')::uuid)
|
||||
ORDER BY created_at,id LIMIT 51;
|
||||
BEGIN;
|
||||
EXPLAIN (ANALYZE,BUFFERS,FORMAT JSON)
|
||||
INSERT INTO messages
|
||||
SELECT md5(n::text)::uuid,md5(''1'')::uuid,
|
||||
''11111111-1111-4111-8111-111111111111'',''new-synthetic-''||n,
|
||||
''2026-01-01Z''::timestamptz+n*interval ''1 microsecond''
|
||||
FROM generate_series(100001,101000) n;
|
||||
ROLLBACK;'
|
||||
FROM generate_series(1,3)
|
||||
\gexec
|
||||
@@ -0,0 +1,125 @@
|
||||
// Package quality checks source-level conventions required by the lab implementation.
|
||||
package quality
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestExportedDocumentation checks functions, types, constants, fields and interface methods.
|
||||
func TestExportedDocumentation(t *testing.T) {
|
||||
visitProductionFiles(t, func(path string, file *ast.File) {
|
||||
ast.Inspect(file, func(node ast.Node) bool {
|
||||
switch declaration := node.(type) {
|
||||
case *ast.FuncDecl:
|
||||
if declaration.Doc == nil || !strings.HasPrefix(strings.TrimSpace(declaration.Doc.Text()), declaration.Name.Name+" ") {
|
||||
t.Errorf("%s: function %s needs a prefixed doc comment", path, declaration.Name.Name)
|
||||
}
|
||||
case *ast.GenDecl:
|
||||
for _, spec := range declaration.Specs {
|
||||
switch spec := spec.(type) {
|
||||
case *ast.TypeSpec:
|
||||
doc := spec.Doc
|
||||
if doc == nil {
|
||||
doc = declaration.Doc
|
||||
}
|
||||
requireDoc(t, path, spec.Name, doc)
|
||||
case *ast.ValueSpec:
|
||||
doc := spec.Doc
|
||||
if doc == nil {
|
||||
doc = declaration.Doc
|
||||
}
|
||||
for _, name := range spec.Names {
|
||||
requireDoc(t, path, name, doc)
|
||||
}
|
||||
}
|
||||
}
|
||||
case *ast.StructType:
|
||||
for _, field := range declaration.Fields.List {
|
||||
for _, name := range field.Names {
|
||||
requireDoc(t, path, name, field.Doc)
|
||||
}
|
||||
}
|
||||
case *ast.InterfaceType:
|
||||
for _, method := range declaration.Methods.List {
|
||||
for _, name := range method.Names {
|
||||
requireDoc(t, path, name, method.Doc)
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// requireDoc checks that an exported declaration has a correctly prefixed doc comment.
|
||||
func requireDoc(t *testing.T, path string, name *ast.Ident, doc *ast.CommentGroup) {
|
||||
t.Helper()
|
||||
if !name.IsExported() {
|
||||
return
|
||||
}
|
||||
if doc == nil || !strings.HasPrefix(strings.TrimSpace(doc.Text()), name.Name+" ") {
|
||||
t.Errorf("%s: %s needs a Go doc comment starting with its name", path, name.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDependencyDirection prevents concrete infrastructure leaking into higher layers.
|
||||
func TestDependencyDirection(t *testing.T) {
|
||||
visitProductionFiles(t, func(path string, file *ast.File) {
|
||||
normalized := filepath.ToSlash(path)
|
||||
for _, dependency := range file.Imports {
|
||||
imported, err := strconv.Unquote(dependency.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var forbidden []string
|
||||
switch {
|
||||
case strings.Contains(normalized, "internal/service/"):
|
||||
forbidden = []string{"net/http", "github.com/gofiber/", "/internal/controller", "/internal/store/memory", "/internal/store/postgres", "/internal/valkey", "/internal/config", "go.lab260.ru/fielderr"}
|
||||
case strings.Contains(normalized, "internal/admission/"), strings.Contains(normalized, "internal/strictjson/"):
|
||||
forbidden = []string{"net/http", "github.com/gofiber/", "/internal/"}
|
||||
case strings.Contains(normalized, "internal/cursor/"):
|
||||
forbidden = []string{"net/http", "github.com/gofiber/", "/internal/service", "/internal/store", "/internal/controller", "/internal/model"}
|
||||
case strings.Contains(normalized, "internal/store/"):
|
||||
forbidden = []string{"net/http", "github.com/gofiber/", "/internal/controller", "/internal/service"}
|
||||
case strings.Contains(normalized, "internal/controller/"):
|
||||
forbidden = []string{"/internal/service/production", "/internal/store"}
|
||||
}
|
||||
for _, fragment := range forbidden {
|
||||
if strings.Contains(imported, fragment) {
|
||||
t.Errorf("%s: forbidden dependency %s", path, imported)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// visitProductionFiles parses application Go files and visits their syntax trees.
|
||||
func visitProductionFiles(t *testing.T, visit func(string, *ast.File)) {
|
||||
t.Helper()
|
||||
for _, root := range []string{"../cmd", "../internal"} {
|
||||
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
file, err := parser.ParseFile(token.NewFileSet(), path, nil, parser.ParseComments)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
visit(path, file)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Isolated database: actual application schema and a deliberately skewed history.
|
||||
\set ON_ERROR_STOP on
|
||||
\timing on
|
||||
SELECT version();
|
||||
INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES('11111111-1111-4111-8111-111111111111','research','Synthetic','not-a-login-hash');
|
||||
INSERT INTO chats(id,title)
|
||||
SELECT md5(n::text)::uuid,'Synthetic '||n FROM generate_series(1,3) n;
|
||||
INSERT INTO chat_members(chat_id,user_id)
|
||||
SELECT id,'11111111-1111-4111-8111-111111111111' FROM chats;
|
||||
INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
SELECT md5(n::text)::uuid,
|
||||
md5((CASE WHEN n<=90000 THEN 1 WHEN n<=99000 THEN 2 ELSE 3 END)::text)::uuid,
|
||||
'11111111-1111-4111-8111-111111111111','synthetic-'||n,
|
||||
'2026-01-01Z'::timestamptz+n*interval '1 microsecond'
|
||||
FROM generate_series(1,100000) AS n;
|
||||
DROP INDEX messages_history;
|
||||
CREATE INDEX candidate ON messages(chat_id);
|
||||
\echo 'VARIANT: chat_only'
|
||||
ANALYZE messages;
|
||||
\i /tmp/plans.sql
|
||||
DROP INDEX candidate;
|
||||
CREATE INDEX candidate ON messages(chat_id,created_at,id);
|
||||
\echo 'VARIANT: history_keyset'
|
||||
ANALYZE messages;
|
||||
\i /tmp/plans.sql
|
||||
Reference in New Issue
Block a user