lab7: базовый коммит из lab6 (bf06167)
Перенесена кодовая база и инфраструктура lab6: NestJS-приложение (API +
worker, RabbitMQ, outbox, S3, OpenTelemetry), Dockerfile, compose.yaml,
infra/{grafana,haproxy,loki,minio,otel/collector.yaml,prometheus,
rabbitmq,tempo}, docs/runbooks, стендовые скрипты, scripts/lab{4,5,6} и
contracts/extensions.openapi.json.
Задание lab7 оставлено своим: README, REPORT, COURSE, CONTRIBUTING,
MAINTAINERS, lab.json, contracts/{openapi,infrastructure,jobs.schema,
attachment-states,examples,observability,trust-matrix,README},
security/THREAT_MODEL.md, tests (включая security.py), compose.example.yaml,
infra/{openbao,otel}/README.md, .github/pull_request_template.md.
Не переносились старые evidence/lab4..lab6 (18 МБ трека lab6) и
неотслеживаемый docs/lab6.html.
Адаптации при переносе:
- docker-проект mtusi-lab6 -> mtusi-lab7, тег образа mtusi-messenger:lab7
и папка Grafana Messenger lab7 (compose.yaml, scripts/stop-one.sh,
.env.example, infra/README.md, infra/grafana/provisioning/dashboards),
чтобы тома и контейнеры не пересекались с lab6;
- Makefile: сохранены BASE_URL=https://localhost:8443 и цель test-security
из skeleton lab7, добавлены стендовые и проверочные цели lab6;
- .env.example: рабочие переменные приложения и стенда lab6 + блок
переменных lab7 (PUBLIC_BASE_URL, TLS_*, BAO_*, ARGON2_*) из skeleton.
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import type { AppConfig } from '../config/app-config.schema.js';
|
||||
import { MetricsService } from '../metrics/metrics.service.js';
|
||||
import { RedisClient } from '../redis/redis.client.js';
|
||||
|
||||
export type FaultPoint =
|
||||
| 'api.after_commit_before_publish'
|
||||
| 'relay.after_publish_before_mark'
|
||||
| 'worker.before_side_effect'
|
||||
| 'worker.after_side_effect'
|
||||
| 'worker.after_commit_before_ack';
|
||||
|
||||
export type FaultTarget = {
|
||||
attachmentId: string;
|
||||
pipelineVersion: number;
|
||||
};
|
||||
|
||||
export type FaultKind = 'permanent' | 'transient';
|
||||
|
||||
// Node timers overflow above 2^31-1 ms and fire immediately.
|
||||
const MAX_TIMER_MS = 2_147_483_647;
|
||||
|
||||
export class InjectedFaultError extends Error {
|
||||
constructor(readonly kind: FaultKind) {
|
||||
super(`Injected ${kind} fault`);
|
||||
this.name = 'InjectedFaultError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Active only with FAULT_INJECTION_ENABLED=1. The switch is deliberately
|
||||
* checked before every Redis call so a normal stand never depends on Redis for
|
||||
* job correctness.
|
||||
*
|
||||
* `transient` stays until the key is deleted; every other value is consumed by
|
||||
* the first point that observes it. Worker points are addressed to one
|
||||
* attachment and pipeline version; the untargeted key is a fallback.
|
||||
*/
|
||||
@Injectable()
|
||||
export class FaultInjector {
|
||||
private readonly logger = new Logger(FaultInjector.name);
|
||||
private readonly enabled: boolean;
|
||||
|
||||
constructor(
|
||||
config: ConfigService<AppConfig>,
|
||||
private readonly redis: RedisClient,
|
||||
private readonly metrics: MetricsService,
|
||||
) {
|
||||
this.enabled = config.getOrThrow('FAULT_INJECTION_ENABLED') === 1;
|
||||
}
|
||||
|
||||
async point(
|
||||
name: FaultPoint,
|
||||
target?: FaultTarget,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
if (!this.enabled) return;
|
||||
const keys = target
|
||||
? [
|
||||
`fault:${name}:${target.attachmentId}:${target.pipelineVersion}`,
|
||||
`fault:${name}`,
|
||||
]
|
||||
: [`fault:${name}`];
|
||||
for (const key of keys) {
|
||||
let value: string | null;
|
||||
let deleted: number;
|
||||
try {
|
||||
value = await this.redis.get(key);
|
||||
if (value === null) continue;
|
||||
if (value === 'transient') {
|
||||
this.metrics.increment('faults.triggered');
|
||||
throw new InjectedFaultError('transient');
|
||||
}
|
||||
deleted = await this.redis.del(key);
|
||||
} catch (error) {
|
||||
if (error instanceof InjectedFaultError) throw error;
|
||||
this.logger.warn(
|
||||
`Fault point ${name} could not read Redis: ${error instanceof Error ? error.message : 'unknown error'}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (deleted !== 1) continue;
|
||||
// The action is outside the Redis try/catch: an abort or an injected
|
||||
// fault must reach the job processor, not be logged as an outage.
|
||||
await this.act(value, signal);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async act(value: string, signal?: AbortSignal): Promise<void> {
|
||||
if (value === 'crash') {
|
||||
this.metrics.increment('faults.triggered');
|
||||
// PID 1 in a container namespace may not be killable by SIGKILL;
|
||||
// exit 137 gives the same observable crash (no graceful shutdown).
|
||||
process.kill(process.pid, 'SIGKILL');
|
||||
process.exit(137);
|
||||
}
|
||||
if (value === 'permanent') {
|
||||
this.metrics.increment('faults.triggered');
|
||||
throw new InjectedFaultError('permanent');
|
||||
}
|
||||
if (value.startsWith('delay:')) {
|
||||
const milliseconds = Number(value.slice('delay:'.length));
|
||||
if (!Number.isFinite(milliseconds) || milliseconds < 0) return;
|
||||
this.metrics.increment('faults.triggered');
|
||||
await this.sleep(Math.min(milliseconds, MAX_TIMER_MS), signal);
|
||||
}
|
||||
}
|
||||
|
||||
private sleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
|
||||
if (signal?.aborted)
|
||||
return Promise.reject(
|
||||
signal.reason instanceof Error
|
||||
? signal.reason
|
||||
: new Error('Aborted'),
|
||||
);
|
||||
const { promise, resolve, reject } = Promise.withResolvers<void>();
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener('abort', cancel);
|
||||
resolve();
|
||||
}, milliseconds);
|
||||
const cancel = (): void => {
|
||||
clearTimeout(timer);
|
||||
reject(
|
||||
signal?.reason instanceof Error
|
||||
? signal.reason
|
||||
: new Error('Aborted'),
|
||||
);
|
||||
};
|
||||
signal?.addEventListener('abort', cancel, { once: true });
|
||||
return promise;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user