Добавить панель системы и временный внешний доступ

This commit is contained in:
Никита
2026-11-10 11:25:50 +03:00
parent 0e0efe5614
commit a81c0bad34
19 changed files with 383 additions and 8 deletions
+12
View File
@@ -62,3 +62,15 @@ student-test:
research-grade5:
$(PYTHON) student-tests/overload_research.py --base-url "$(BASE_URL)"
$(PYTHON) scripts/plot_overload.py
.PHONY: share stop-share operations-test
share:
python3 scripts/share.py
stop-share:
python3 scripts/share.py --stop
operations-test:
$(PYTHON) student-tests/operations_panel.py
.PHONY: operator
operator:
python3 scripts/configure-operator.py "$(USERNAME)"
+40
View File
@@ -231,3 +231,43 @@ ChatGPT использован при реализации и проверках
## Панель обработки изображений
Кнопка «Обработка» под изображением открывает состояния, число попыток, время всего цикла и события задания из PostgreSQL. После готовности доступны оригинал, миниатюра, crop и WebP с размерами и скачиванием. Endpoint GET /api/v1/attachments/{id}/processing доступен только участникам чата; ключи S3 и служебные lease не возвращаются. Панель обновляется только пока открыта и задание выполняется. Проверка: .venv/bin/python student-tests/processing_panel.py. Результаты нагрузочного эксперимента выше относятся к версии до добавления этого интерфейса.
## Панель системы и внешний доступ
Кнопка «Система» доступна только аккаунту, UUID которого задан в OPS_USER_ID.
После регистрации владельца: `make operator USERNAME=ваш_логин`. Команда записывает
UUID в локальный .env и обновляет API. Если OPS_USER_ID не настроен, панель закрыта
для всех. Клиентское скрытие кнопки дополнено проверкой каждой серверной операции.
Панель показывает две API-реплики по heartbeat Redis, PostgreSQL, Redis, S3,
RabbitMQ, worker и dispatcher. Heartbeat процессов хранится в pipeline_presence;
срок свежести 10 секунд. Это признак работающего процесса, а не гарантия успешной
обработки любого задания. Проверка HAProxy основана на ответе текущего адреса.
Графики содержат последние 60 замеров открытой панели: активные задания в БД
и длительность запроса проверки зависимостей. CPU и память здесь не измеряются.
При ошибке запроса старые состояния отмечаются как неизвестные.
Последние 30 заданий и событий доступны владельцу. Кнопка «Повторить» использует
существующий механизм replay: только failed с сохранённым staging. Проверка состояния
и изменение задания выполняются в одной транзакции под advisory lock; второй
запрос не создаёт ещё один replay. Обычный пользователь получает 404, анонимный 401.
Проверка: `OPS_TEST_PASSWORD=пароль_владельца make operations-test` (логин по умолчанию
n1k0der, другой задаётся OPS_TEST_USERNAME). Тест использует контролируемый failed
fixture и проверяет завершение настоящим worker, восстанавливая worker в finally.
Создать чат можно по @логину или UUID. Поиск выполняется только по точному логину,
после входа; возвращает публичный User DTO без password_hash.
Временный внешний доступ: установить cloudflared, затем `make share`.
Отключение: `make stop-share`. Ссылка и состояние процесса остаются в .local вне Git.
Ссылка работает, пока включён компьютер, запущены Docker и туннель; при следующем
запуске адрес может измениться. Снаружи доступен только HTTP-вход мессенджера,
порты БД и RabbitMQ не публикуются. Собеседник регистрирует свой аккаунт и создаёт
чат с @логином владельца. Учётная запись собеседника не получает права оператора.
Через HTTPS-туннель пустой POST входа может приходить с Transfer-Encoding: chunked.
API проверяет фактическое отсутствие тела (с таймаутом 3 секунды), а не отклоняет
такой способ передачи целиком. Непустое тело по-прежнему возвращает 400.
Проверка: `.venv/bin/python student-tests/chunked_login.py`.
Внешняя регистрация, вход, точный поиск, создание общего чата и сообщение проверены
через публичный HTTPS-адрес; результат без токенов записан в evidence/operations.txt.
+4
View File
@@ -4,6 +4,9 @@ x-api: &api
image: messenger-lab5:local
build: .
environment:
OPS_USER_ID: ${OPS_USER_ID:-}
BROKER_HOST: broker
BROKER_PASSWORD_FILE: /run/secrets/broker_password
APP_HOST: 0.0.0.0
APP_PORT: 8080
DATABASE_URL_FILE: /run/secrets/database_url
@@ -19,6 +22,7 @@ x-api: &api
Logging__LogLevel__Default: Warning
Logging__LogLevel__Microsoft.Hosting.Lifetime: Information
secrets:
- broker_password
- database_url
- s3_access
- s3_secret
+9
View File
@@ -0,0 +1,9 @@
Проверки дополнения панели системы:
- Сборка .NET: 0 ошибок, 0 предупреждений.
- make check, make validate, make test: PASS.
- operations_panel.py: PASS: operator-only metrics and replay; anonymous 401; regular user 404; exact login lookup; one replay completes with real worker.
- Повторный POST replay для queued: 409; replay_count остался 1.
- Интерфейс проверен в браузере: экземпляры API, службы, графики, события и повторный запуск доступны владельцу.
Первый прогон теста после рестарта API встретил временный 503 при ожидании ready; само задание завершилось. Ожидание учитывает 503 до общего таймаута, финальное состояние ready остаётся обязательным.
PASS: public HTTPS registration, login, lookup @n1k0der, shared chat and message; operations denied to guest
PASS: empty chunked login accepted; nonempty chunked login rejected (student-tests/chunked_login.py).
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Grant the local operations UI to an existing messenger account."""
import re,subprocess,sys
from pathlib import Path
root=Path(__file__).resolve().parents[1]
if len(sys.argv)!=2 or not re.fullmatch('[a-z0-9_]{3,32}',sys.argv[1]):raise SystemExit('Укажите логин: make operator USERNAME=n1k0der')
result=subprocess.check_output([str(root/'scripts/compose.sh'),'exec','-T','postgres','psql','-U','messenger','-d','messenger','-At','-c',"SELECT id FROM users WHERE username='"+sys.argv[1]+"'"],cwd=root,text=True).strip()
if not result:raise SystemExit('Сначала зарегистрируйте этот аккаунт в мессенджере')
p=root/'.env';lines=p.read_text().splitlines() if p.exists() else []
lines=[line for line in lines if not line.startswith('OPS_USER_ID=')];lines.append('OPS_USER_ID='+result);p.write_text('\n'.join(lines)+'\n');p.chmod(0o600)
subprocess.run([str(root/'scripts/compose.sh'),'up','-d','--no-deps','--wait','api'],cwd=root,check=True)
print('Панель доступна аккаунту '+sys.argv[1]+'. Перезайдите в мессенджер.')
+52
View File
@@ -0,0 +1,52 @@
#!/usr/bin/env python3
"""Manage a temporary HTTPS tunnel for this project's HTTP entry point."""
import fcntl,os,re,shutil,signal,socket,subprocess,sys,time,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
STATE=ROOT/'.local';STATE.mkdir(exist_ok=True)
PID=STATE/'share.pid';URL=STATE/'share.url';origin='http://127.0.0.1:18085'
def running():
if not PID.exists():return None
try:pid=int(PID.read_text())
except ValueError:return None
command=subprocess.run(['ps','-p',str(pid),'-o','command='],capture_output=True,text=True).stdout
return pid if 'cloudflared tunnel' in command and '--url '+origin in command else None
with (STATE/'share.lock').open('w') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
pid=running()
if '--stop' in sys.argv:
if pid:
os.kill(pid,signal.SIGTERM)
for _ in range(50):
if not running():break
time.sleep(.1)
else:
try:os.kill(pid,signal.SIGKILL)
except ProcessLookupError:pass
PID.unlink(missing_ok=True);URL.unlink(missing_ok=True)
print('Внешний доступ отключён. Localhost продолжает работать.');raise SystemExit
if pid:
print(URL.read_text().strip() if URL.exists() else 'Туннель запущен, ссылка ещё создаётся.');raise SystemExit
binary=shutil.which('cloudflared')
if not binary:raise SystemExit('Установите cloudflared: brew install cloudflared')
try:urllib.request.urlopen(origin+'/health/ready',timeout=5).close()
except Exception:raise SystemExit('Сначала запустите мессенджер: make up')
URL.unlink(missing_ok=True)
(STATE/'share.log').unlink(missing_ok=True)
with (STATE/'share.log').open('w') as log:
edge=socket.gethostbyname('region1.v2.argotunnel.com')
process=subprocess.Popen([binary,'tunnel','--no-autoupdate','--protocol','http2','--edge',edge+':7844','--url',origin],stdout=log,stderr=subprocess.STDOUT,start_new_session=True,env={**os.environ,'GODEBUG':'netdns=cgo'})
PID.write_text(str(process.pid));PID.chmod(0o600)
deadline=time.monotonic()+120
while time.monotonic()<deadline and process.poll() is None:
text=(STATE/'share.log').read_text()
match=re.search(r'https://[a-z0-9-]+\.trycloudflare\.com',text)
if match:URL.write_text(match.group(0)+'\n')
if match and 'Registered tunnel connection' in text:
check=subprocess.run(['curl','--fail','--silent','--max-time','8',match.group(0)+'/health/ready'],capture_output=True)
if check.returncode==0:
print(match.group(0));print('Отключение: make stop-share');raise SystemExit
time.sleep(.25)
if process.poll() is None:process.terminate()
PID.unlink(missing_ok=True)
raise SystemExit('Не удалось получить ссылку. Подробности в .local/share.log')
@@ -0,0 +1 @@
CREATE TABLE pipeline_presence (role text PRIMARY KEY, seen_at timestamptz NOT NULL);
+13 -1
View File
@@ -37,9 +37,21 @@ public static class AuthEndpoints
if (!Regex.IsMatch(username, "\\A[a-z0-9_]{3,32}\\z"))
return Unauthorized(context, basic: true);
if (context.Request.ContentLength > 0 || context.Request.Headers.ContainsKey("Transfer-Encoding"))
if (context.Request.ContentLength > 0)
return ApiError(context, 400, "invalid_request", "Вход принимает Basic без тела запроса");
if (context.Request.ContentLength is null && context.Request.Headers.ContainsKey("Transfer-Encoding"))
{
using var deadline=CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
deadline.CancelAfter(TimeSpan.FromSeconds(3));
try {
if(await context.Request.Body.ReadAsync(new byte[1],deadline.Token)>0)
return ApiError(context,400,"invalid_request","Вход принимает Basic без тела запроса");
} catch(OperationCanceledException) when(!context.RequestAborted.IsCancellationRequested) {
return ApiError(context,400,"invalid_request","Тело запроса не завершено");
}
}
var session = await sessions.LoginAsync(username, password);
return session is null
? Unauthorized(context, basic: true)
@@ -0,0 +1,79 @@
using Messenger.Api.Data;
using Messenger.Api.Infrastructure;
using Messenger.Api.Pipeline;
using Messenger.Api.Services;
using Npgsql;
using static Messenger.Api.Services.ApiSupport;
namespace Messenger.Api.Endpoints;
public static class OperationsEndpoints
{
public static bool IsOperator(Guid id,IConfiguration config)=>Guid.TryParse(config["OPS_USER_ID"],out var owner)&&owner==id;
public static IEndpointRouteBuilder MapOperationsEndpoints(this IEndpointRouteBuilder app)
{
app.MapGet("/api/ui/operator",async(HttpContext ctx,SessionService sessions,IConfiguration config)=> {
var(actor,_)=await sessions.AuthenticateAsync(ctx);if(actor is null)return Unauthorized(ctx);
ctx.Response.Headers.CacheControl="no-store";
return Results.Ok(new {enabled=IsOperator(actor.Id,config)});
});
app.MapGet("/api/ui/operations",async(HttpContext ctx,SessionService sessions,IConfiguration config,
NpgsqlDataSource source,ClusterPresence cluster,S3Storage storage)=> {
var(actor,_)=await sessions.AuthenticateAsync(ctx);if(actor is null)return Unauthorized(ctx);
if(!IsOperator(actor.Id,config))return ApiError(ctx,404,"not_found","Доступ только владельцу системы");
ctx.Response.Headers.CacheControl="no-store";
using var deadline=CancellationTokenSource.CreateLinkedTokenSource(ctx.RequestAborted);deadline.CancelAfter(TimeSpan.FromSeconds(7));
var ct=deadline.Token;
var counts=new Dictionary<string,long>{{"queued",0},{"processing",0},{"ready",0},{"failed",0}};
var recent=new List<object>();var history=new List<object>();var heartbeats=new Dictionary<string,DateTime>();
long pending=0;double? latency=null;
await using(var cmd=source.CreateCommand("SELECT state,count(*) FROM attachment_jobs GROUP BY state"))
await using(var rd=await cmd.ExecuteReaderAsync(ct))while(await rd.ReadAsync(ct))counts[rd.GetString(0)]=rd.GetInt64(1);
await using(var cmd=source.CreateCommand("SELECT count(*) FROM attachment_outbox WHERE published_at IS NULL"))pending=(long)(await cmd.ExecuteScalarAsync(ct))!;
await using(var cmd=source.CreateCommand("SELECT avg(extract(epoch FROM (completed_at-created_at)))::double precision FROM attachment_jobs WHERE state='ready' AND completed_at>now()-interval '15 minutes'")) {
var value=await cmd.ExecuteScalarAsync(ct);if(value is double seconds)latency=seconds;
}
await using(var cmd=source.CreateCommand("SELECT role,seen_at FROM pipeline_presence"))
await using(var rd=await cmd.ExecuteReaderAsync(ct))while(await rd.ReadAsync(ct))heartbeats[rd.GetString(0)]=rd.GetDateTime(1);
await using(var cmd=source.CreateCommand("""
SELECT a.id,a.filename,j.state,j.attempts,j.error_code,j.created_at,j.completed_at,
j.state='failed' AND j.staging_deleted_at IS NULL
FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id ORDER BY j.created_at DESC LIMIT 30
"""))
await using(var rd=await cmd.ExecuteReaderAsync(ct))while(await rd.ReadAsync(ct))recent.Add(new {
attachment_id=rd.GetGuid(0),filename=rd.GetString(1),state=rd.GetString(2),attempts=rd.GetInt32(3),
error_code=rd.IsDBNull(4)?null:rd.GetString(4),created_at=rd.GetDateTime(5),
completed_at=rd.IsDBNull(6)?(DateTime?)null:rd.GetDateTime(6),can_replay=rd.GetBoolean(7)});
await using(var cmd=source.CreateCommand("""
SELECT e.event,e.attempt,e.created_at,a.filename FROM attachment_job_events e
JOIN attachment_jobs j ON j.id=e.job_id JOIN attachments a ON a.id=j.attachment_id ORDER BY e.id DESC LIMIT 30
"""))
await using(var rd=await cmd.ExecuteReaderAsync(ct))while(await rd.ReadAsync(ct))history.Add(new {
name=rd.GetString(0),attempt=rd.GetInt32(1),at=rd.GetDateTime(2),filename=rd.GetString(3)});
bool? s3=null,broker=null;uint? messages=null,consumers=null;
async Task ProbeStorage() {try {await storage.Client.GetBucketLocationAsync(storage.Bucket,ct);s3=true;}catch {s3=false;}}
async Task ProbeBroker() {try {
await using var connection=await BrokerConnection.OpenAsync(config,ct);
await using var channel=await connection.CreateChannelAsync(cancellationToken:ct);
var result=await channel.QueueDeclarePassiveAsync(BrokerConnection.Queue,ct);
broker=true;messages=result.MessageCount;consumers=result.ConsumerCount;
}catch {broker=false;}}
var snapshotTask=cluster.ReadAsync();await Task.WhenAll(ProbeStorage(),ProbeBroker());var snapshot=await snapshotTask;
var now=DateTime.UtcNow;
return Results.Ok(new {checked_at=now,counts,pending_outbox=pending,average_cycle_seconds=latency,
services=new {postgres=true,redis=snapshot.RedisAvailable,s3,broker,
worker=heartbeats.TryGetValue("worker",out var worker)&&(now-worker).TotalSeconds<10,
dispatcher=heartbeats.TryGetValue("dispatcher",out var dispatcher)&&(now-dispatcher).TotalSeconds<10},
instances=snapshot.Instances,broker_messages=messages,broker_consumers=consumers,jobs=recent,events=history});
});
app.MapPost("/api/ui/operations/attachments/{id:guid}/replay",async(Guid id,HttpContext ctx,
SessionService sessions,IConfiguration config,NpgsqlDataSource source)=> {
var(actor,_)=await sessions.AuthenticateAsync(ctx);if(actor is null)return Unauthorized(ctx);
if(!IsOperator(actor.Id,config))return ApiError(ctx,404,"not_found","Доступ только владельцу системы");
await using var cmd=source.CreateCommand("SELECT id FROM attachment_jobs WHERE attachment_id=@id");cmd.Parameters.AddWithValue("id",id);
var job=await cmd.ExecuteScalarAsync(ctx.RequestAborted);
if(job is not Guid jobId)return ApiError(ctx,404,"not_found","Задание не найдено");
var changed=await new JobStore(source,config).ReplayAsync(jobId,ctx.RequestAborted);
return changed?Results.Accepted(value:new {status="queued"}):ApiError(ctx,409,"conflict","Повтор недоступен: задание не завершилось ошибкой или исходник уже удалён");
});
return app;
}
}
@@ -20,6 +20,13 @@ public static class UiEndpoints
return Results.Ok(await presence.ReadAsync());
});
app.MapGet("/api/ui/users/{username}",async(string username,HttpContext ctx,SessionService sessions,AppDatabase db)=> {
var(actor,_)=await sessions.AuthenticateAsync(ctx);if(actor is null)return Unauthorized(ctx);
if(!System.Text.RegularExpressions.Regex.IsMatch(username,"\\A[a-z0-9_]{3,32}\\z"))return ApiError(ctx,400,"invalid_request","Некорректный логин");
var user=await db.FindUserByUsernameAsync(username);
return user is null?ApiError(ctx,404,"not_found","Пользователь не найден"):Results.Ok(user.ToDto());
});
app.MapGet("/api/ui/chats", async (HttpContext context, SessionService sessions, AppDatabase database) =>
{
var (actor, _) = await sessions.AuthenticateAsync(context);
+2 -1
View File
@@ -107,7 +107,7 @@ public sealed class JobStore(NpgsqlDataSource db,IConfiguration config)
AND o.published_at<clock_timestamp()-interval '30 seconds' AND j.next_at<=clock_timestamp()
""");await rescue.ExecuteNonQueryAsync(ct);
}
public async Task ReplayAsync(Guid id,CancellationToken ct)
public async Task<bool> ReplayAsync(Guid id,CancellationToken ct)
{
await using var connection=await db.OpenConnectionAsync(ct);
await using var tx=await connection.BeginTransactionAsync(ct);
@@ -125,5 +125,6 @@ public sealed class JobStore(NpgsqlDataSource db,IConfiguration config)
await EventAsync(connection,id,"operator_replay",0,ct);
}
await tx.CommitAsync(ct);Console.WriteLine(attachment is Guid?"Replay scheduled":"No-op: job is not failed or staging has expired");
return attachment is Guid;
}
}
@@ -0,0 +1,17 @@
using Npgsql;
namespace Messenger.Api.Pipeline;
public static class ProcessPresence
{
public static async Task RunAsync(NpgsqlDataSource source,string role,CancellationToken ct)
{
try {
while(!ct.IsCancellationRequested) {
try {
await using var cmd=source.CreateCommand("INSERT INTO pipeline_presence(role,seen_at) VALUES(@role,clock_timestamp()) ON CONFLICT(role) DO UPDATE SET seen_at=EXCLUDED.seen_at");
cmd.Parameters.AddWithValue("role",role);await cmd.ExecuteNonQueryAsync(ct);
} catch(Exception) when(!ct.IsCancellationRequested) { }
await Task.Delay(2000,ct);
}
} catch(OperationCanceledException) when(ct.IsCancellationRequested) { }
}
}
+4
View File
@@ -68,6 +68,8 @@ if(args.Contains("--worker") || args.Contains("--dispatcher") || args.Contains("
using var cancellation=new CancellationTokenSource();
Console.CancelKeyPress+=(_,e)=>{e.Cancel=true;cancellation.Cancel();};
using var signal=System.Runtime.InteropServices.PosixSignalRegistration.Create(System.Runtime.InteropServices.PosixSignal.SIGTERM,ctx=>{ctx.Cancel=true;cancellation.Cancel();});
var heartbeat=(args.Contains("--worker") || args.Contains("--dispatcher"))
? ProcessPresence.RunAsync(dataSource,args.Contains("--worker")?"worker":"dispatcher",cancellation.Token) : Task.CompletedTask;
try {
if(args.Contains("--worker"))await new PipelineWorker(dataSource,storage,builder.Configuration).RunAsync(cancellation.Token);
else if(args.Contains("--dispatcher"))await new OutboxDispatcher(dataSource,storage,builder.Configuration).RunAsync(cancellation.Token);
@@ -75,6 +77,7 @@ if(args.Contains("--worker") || args.Contains("--dispatcher") || args.Contains("
else if(args.Contains("--replay"))await new JobStore(dataSource,builder.Configuration).ReplayAsync(Guid.Parse(args[Array.IndexOf(args,"--replay")+1]),cancellation.Token);
else await new PipelineMaintenance(dataSource,storage,builder.Configuration).ReconcileStagingAsync(args.Contains("--apply"),cancellation.Token);
}catch(OperationCanceledException) when(cancellation.IsCancellationRequested) { }
cancellation.Cancel();await heartbeat;
await dataSource.DisposeAsync();return;
}
builder.Services.AddSingleton(dataSource);
@@ -122,6 +125,7 @@ app.MapChatEndpoints();
app.MapMessageEndpoints();
app.MapAttachmentEndpoints();
app.MapUiEndpoints();
app.MapOperationsEndpoints();
app.MapReactionEndpoints();
app.Run();
+18 -5
View File
@@ -1,3 +1,4 @@
import { operationsSession } from '/operations.js';
import { attachmentSession } from '/attachments.js';
import { recordRequest, updateSessionInfo, updateHistoryInfo } from "/diagnostics.js";
@@ -104,6 +105,7 @@ async function enterSession(session) {
state.epoch++;
state.session = session;
attachmentSession(session.token);
operationsSession(session.token);
clearAttachedDrafts();
updateSessionInfo({ name: session.user.display_name, expiresAt: session.expires_at });
updateHistoryInfo(null);
@@ -140,6 +142,7 @@ function endSession(message = "") {
state.epoch++;
state.session = null;
attachmentSession(null);
operationsSession(null);
clearAttachedDrafts();
updateSessionInfo(null);
updateHistoryInfo(null);
@@ -570,13 +573,21 @@ $("new-chat-form").addEventListener("submit", async event => {
const form = event.currentTarget, token = state.session?.token;
const title = $("new-chat-title").value.trim();
if (!title || Array.from(title).length > 100) return notice("chat-dialog-notice", "Название должно содержать от 1 до 100 символов.");
const ids = $("new-chat-members").value.split(/[\s,;]+/u).filter(Boolean);
if (ids.some(id => !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id)))
return notice("chat-dialog-notice", "Проверьте ID участников: нужен полный ID из профиля.");
const members = [...new Set([state.session.user.id, ...ids.map(id => id.toLowerCase())])];
if (members.length > 100) return notice("chat-dialog-notice", "В чате может быть не более 100 участников.");
const entries = $("new-chat-members").value.split(/[\s,;]+/u).filter(Boolean);
if(entries.length>99)return notice("chat-dialog-notice","Не более 99 приглашений за раз.");
setFormBusy(form, true); notice("chat-dialog-notice", "");
try {
const ids=[];
for(const entry of entries) {
if(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(entry))ids.push(entry.toLowerCase());
else {
const username=entry.replace(/^@/,'').toLowerCase();
if(!/^[a-z0-9_]{3,32}$/.test(username))throw new Error('Введите логин или полный ID участника.');
const user=await request('/api/ui/users/'+encodeURIComponent(username));ids.push(user.id);
}
}
if(token!==state.session?.token)return;
const members=[...new Set([state.session.user.id,...ids])];
const chat = await request("/api/v1/chats", { method: "POST", body: { title, member_ids: members } });
if (token !== state.session?.token) return;
$("new-chat-dialog").close(); state.chats.push(chat); renderChats();
@@ -632,11 +643,13 @@ async function resume() {
if (!session?.token || !session.user || !(new Date(session.expires_at).getTime() > Date.now())) return endSession();
state.session = session;
attachmentSession(session.token);
operationsSession(session.token);
const user = await request("/api/v1/users/me");
await enterSession({ ...session, user });
} catch (error) {
state.session = null;
attachmentSession(null);
operationsSession(null);
clearAttachedDrafts();
if (error instanceof ApiError) notice("auth-notice", error.message);
else { try { sessionStorage.removeItem(storageKey); } catch { /* storage unavailable */ } }
+3 -1
View File
@@ -12,6 +12,7 @@
<link rel="stylesheet" href="/attachments.css">
<link rel="stylesheet" href="/showcase.css">
<script type="module" src="/app.js"></script>
<link rel="stylesheet" href="/operations.css">
</head>
<body>
<svg class="svg-sprite" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
@@ -125,6 +126,7 @@
<div class="sidebar-heading"><div><span class="eyebrow">На связи</span><h2>Ваши чаты<span id="chat-count" class="count"></span></h2></div><button id="new-chat" class="icon-button filled" aria-label="Создать чат" title="Создать чат"><svg><use href="#i-plus"/></svg></button></div>
<label class="search-field"><span class="visually-hidden">Поиск среди загруженных чатов</span><svg aria-hidden="true"><use href="#i-search"/></svg><input id="chat-search" placeholder="Найти разговор" type="search" autocomplete="off"></label>
<div id="chat-list" class="chat-list" aria-label="Список чатов"></div><button id="more-chats" class="text-button" hidden>Ещё чаты</button>
<button id="open-operations" class="diagnostics-toggle sidebar-diagnostics" type="button" hidden>Система</button>
<button class="diagnostics-toggle sidebar-diagnostics" type="button" data-diagnostics-toggle aria-controls="diagnostics-panel" aria-expanded="false"><svg><use href="#i-code"/></svg>Запросы API</button>
<div class="profile"><button id="open-profile" class="profile-main" title="Открыть профиль"><span id="profile-avatar" class="avatar"></span><span class="profile-text"><strong id="profile-name"></strong><span id="profile-username"></span></span></button><button id="logout" class="icon-button" aria-label="Выйти" title="Выйти"><svg><use href="#i-exit"/></svg></button></div>
</aside>
@@ -162,7 +164,7 @@
</aside>
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
<dialog id="new-chat-dialog"><div class="dialog-heading"><h2>Собрать чат</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><form id="new-chat-form"><label>Название чата<input id="new-chat-title" placeholder="Название" required></label><label>ID участников<textarea id="new-chat-members" rows="3" placeholder="Вставьте ID через запятую или с новой строки" spellcheck="false"></textarea><span class="field-note">Вы добавитесь автоматически. Для чата с собой оставьте поле пустым.</span></label><p id="chat-dialog-notice" class="form-notice" role="status" hidden></p><div class="dialog-actions"><button class="button secondary" type="button" data-close-dialog>Отмена</button><button class="button primary" type="submit">Создать чат</button></div></form></dialog>
<dialog id="new-chat-dialog"><div class="dialog-heading"><h2>Собрать чат</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><form id="new-chat-form"><label>Название чата<input id="new-chat-title" placeholder="Название" required></label><label>Логины или ID участников<textarea id="new-chat-members" rows="3" placeholder="Например, @n1k0der" spellcheck="false"></textarea><span class="field-note">Укажите логины через запятую. Вы добавитесь автоматически.</span></label><p id="chat-dialog-notice" class="form-notice" role="status" hidden></p><div class="dialog-actions"><button class="button secondary" type="button" data-close-dialog>Отмена</button><button class="button primary" type="submit">Создать чат</button></div></form></dialog>
<dialog id="profile-dialog"><div class="dialog-heading"><h2>Ваш профиль</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><p id="profile-details" class="muted"></p><label>Ваш ID<input id="my-id" readonly spellcheck="false"></label><p class="field-note">Поделитесь ID для приглашения в чат.</p><button id="copy-id" class="button primary wide"><svg><use href="#i-copy"/></svg>Скопировать ID</button></dialog>
<dialog id="members-dialog"><div class="dialog-heading"><h2>Участники чата</h2><button class="icon-button" data-close-dialog aria-label="Закрыть"><svg><use href="#i-close"/></svg></button></div><div id="members-list" class="members-list"></div></dialog>
</body>
+5
View File
@@ -0,0 +1,5 @@
.ops-panel {position:fixed;inset:0;width:100dvw;height:100dvh;max-width:none;max-height:none;margin:0;border:0;border-radius:0;background:#20211f;color:#efefe7;padding:0;overflow:auto;color-scheme:dark;}
.ops-panel::backdrop {background:#20211f;}.ops-shell {max-width:1450px;margin:auto;padding:0 36px;}.ops-header {display:flex;align-items:center;gap:25px;padding:24px 0;border-bottom:1px solid #ffffff12;}.ops-brand {font-size:23px;font-weight:750;letter-spacing:-1px;color:#ffe135;text-decoration:none;}.ops-brand span {color:#aaa;font-size:15px;font-weight:400;letter-spacing:0;}.ops-live {margin-left:auto;font-size:12px;color:#b6ce9c;}.ops-panel button {cursor:pointer;color:inherit;background:#ffffff08;border:1px solid #ffffff25;border-radius:9px;padding:9px 14px;font:inherit;font-size:12px;}.ops-panel button:hover {background:#ffffff18;}.ops-panel button:focus-visible,.ops-panel a:focus-visible {outline:2px solid #ffe135;outline-offset:3px;}.ops-intro {display:flex;justify-content:space-between;align-items:center;padding:40px 0 20px;}.ops-eyebrow {font-size:10px;text-transform:uppercase;letter-spacing:2px;color:#b5b6a4;}.ops-intro h1 {font-size:clamp(26px,3.3vw,44px);line-height:1.16;letter-spacing:-1.7px;margin:14px 0;}.ops-intro h1 span {color:#ffe135;}.ops-intro p {color:#a4a69c;font-size:13px;}.ops-art {width:230px;height:160px;}.ops-orbit {animation:ops-pulse 3s ease-in-out infinite;transform-origin:120px 80px;}.ops-notice {color:#ffb4a2;font-size:13px;}.ops-notice:empty {display:none;}.ops-metrics {display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin:18px 0 25px;}.ops-metrics article {background:#2b2c29;border:1px solid #ffffff10;padding:20px 24px;border-radius:14px;display:grid;gap:12px;}.ops-metrics span {color:#bdbeb2;font-size:12px;}.ops-metrics strong {font-size:36px;line-height:1;font-weight:550;font-variant-numeric:tabular-nums;}.ops-metrics [data-kind=queued] strong {color:#ffe135;}.ops-metrics [data-kind=failed] strong {color:#e7a18c;}.ops-box {background:#282925;border:1px solid #ffffff12;padding:24px;border-radius:16px;min-width:0;}.ops-section-head {display:flex;align-items:center;justify-content:space-between;gap:15px;}.ops-box h2 {font-size:19px;letter-spacing:-.4px;margin:8px 0 20px;}.ops-checked {font-size:11px;color:#a2a697;}.ops-flow {display:flex;align-items:center;gap:20px;padding:10px 0 25px;}.ops-node,.ops-api-nodes {flex:1;min-width:0;}.ops-node {padding:20px;border:1px solid #d9dcbb25;border-radius:12px;display:grid;gap:9px;}.ops-node>span {font-size:10px;color:#a3a594;text-transform:uppercase;letter-spacing:1px;}.ops-node strong {font-size:20px;}.ops-node small {font-size:11px;color:#a4a69b;}.ops-arrow {color:#ffe135;font-size:25px;}.ops-api-nodes {display:grid;gap:8px;}.ops-services {display:grid;grid-template-columns:repeat(6,1fr);gap:10px;}.ops-service {border:1px solid #ffffff16;border-radius:10px;padding:14px;display:grid;gap:9px;min-width:0;transition:border-color .4s,background .4s;}.ops-service>span {font-size:9px;color:#b6cd9f;}.ops-service strong {font-size:13px;overflow-wrap:anywhere;}.ops-service small {font-size:10px;color:#a5a897;line-height:1.5;}.ops-service[data-state=down] {border-color:#b0755744;}.ops-service[data-state=down]>span {color:#eaa590;}.ops-service[data-state=unknown]>span {color:#aaa;}.ops-service.served {border-color:#ffe13588;background:#ffe13508;animation:ops-served 1s ease-out;}.ops-pipeline {display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-top:25px;padding-top:20px;border-top:1px solid #ffffff10;font-size:11px;color:#c6c9b4;}.ops-pipeline i {color:#ffe135;font-style:normal;}.ops-footnote {font-size:10px;color:#919586;line-height:1.7;margin:16px 0 0;}.ops-charts {display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:18px;}.ops-charts svg {width:100%;height:150px;display:block;}.ops-chart-caption {display:flex;justify-content:space-between;color:#8f9384;font-size:10px;}.ops-queue-value,.ops-latency-value {font-variant-numeric:tabular-nums;color:#ffe135;font-size:20px;font-weight:500;}.ops-bottom {display:grid;grid-template-columns:1.3fr 1fr;gap:18px;margin:18px 0;}.ops-jobs {max-height:440px;overflow:auto;}.ops-job {display:flex;align-items:center;justify-content:space-between;gap:15px;padding:14px 0;border-top:1px solid #ffffff0d;}.ops-job>div {display:grid;gap:7px;min-width:0;}.ops-job strong {font-size:12px;font-weight:500;overflow-wrap:anywhere;}.ops-job small {font-size:10px;color:#b0b49e;}.ops-job button {color:#ffe135;flex-shrink:0;}.ops-events {list-style:none;padding:0;margin:0;max-height:440px;overflow:auto;}.ops-events li {display:grid;grid-template-columns:60px 1fr;gap:5px 10px;padding:12px 0;border-top:1px solid #ffffff0d;font-size:11px;}.ops-events time {color:#8f9580;font-variant-numeric:tabular-nums;}.ops-events strong {font-weight:450;}.ops-events li>span {grid-column:2;color:#8f9580;overflow-wrap:anywhere;font-size:10px;}.ops-empty {font-size:12px;color:#aaa;line-height:1.7;}.ops-shell footer {padding:15px 0 30px;font-size:11px;color:#959b85;}.ops-panel.is-stale .ops-orbit {animation-play-state:paused;}.ops-panel.is-stale .ops-live {color:#e7a18c;}
@keyframes ops-pulse {50% {opacity:.35;transform:scale(.7);}}@keyframes ops-served {from {box-shadow:0 0 20px #ffe13522;}to {box-shadow:none;}}
@media(max-width:1000px){.ops-services{grid-template-columns:repeat(3,1fr);}.ops-shell{padding:0 22px;}}@media(max-width:650px){.ops-shell{padding:0 14px;}.ops-header{gap:10px;}.ops-brand{font-size:20px;}.ops-brand span{display:none;}.ops-live{font-size:9px;}.ops-intro{padding:28px 0 10px;}.ops-art{width:90px;}.ops-intro h1{letter-spacing:-1px;}.ops-intro p{font-size:11px;max-width:220px;}.ops-metrics{grid-template-columns:repeat(2,1fr);gap:8px;}.ops-metrics article{padding:16px;}.ops-metrics strong{font-size:30px;}.ops-box{padding:16px;}.ops-flow{gap:7px;flex-wrap:wrap;}.ops-node{padding:12px;}.ops-node strong{font-size:15px;}.ops-node small{font-size:9px;}.ops-api-nodes{flex-basis:100%;grid-template-columns:1fr 1fr;}.ops-arrow{font-size:17px;}.ops-services{grid-template-columns:repeat(2,1fr);}.ops-charts,.ops-bottom{grid-template-columns:1fr;}.ops-box h2{font-size:17px;}.ops-checked{font-size:9px;}}
@media(prefers-reduced-motion:reduce){.ops-orbit,.ops-service.served{animation:none;}.ops-service{transition:none;}}
+53
View File
@@ -0,0 +1,53 @@
let token=null, epoch=0, panel, timer, abort, samples=[];
const $=selector=>panel.querySelector(selector);
const labels={queued:'В очереди',processing:'Обработка',ready:'Готово',failed:'Ошибка'};
const eventLabels={accepted:'Файл принят',published:'В очереди RabbitMQ',processing:'Обработчик начал работу',ready:'Результаты сохранены',retry_scheduled:'Назначен повтор',failed:'Ошибка обработки',lease_recovered:'Восстановлено после остановки',operator_replay:'Повторный запуск'};
function node(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
export async function operationsSession(value){
token=value;epoch++;panel?.close();clearTimeout(timer);abort?.abort();samples=[];
const button=document.getElementById('open-operations');button.hidden=true;
const version=epoch;if(!value)return;
try {const response=await fetch('/api/ui/operator',{headers:{Authorization:'Bearer '+value},cache:'no-store',signal:AbortSignal.timeout(8000)});const data=await response.json();if(version===epoch)button.hidden=!response.ok||!data.enabled;}catch{}
}
function init(){
panel=node('dialog',undefined,'ops-panel');panel.setAttribute('aria-label','Система мессенджера');
panel.innerHTML=`<div class="ops-shell"><header class="ops-header"><a href="#" class="ops-brand">n1k0der<span> / system</span></a><span class="ops-live">● Обновление каждые 3 с</span><button class="ops-close" type="button">Закрыть ×</button></header>
<main><section class="ops-intro"><div><span class="ops-eyebrow">Внутри мессенджера</span><h1>Каждое сообщение.<br><span>Всё на своих местах.</span></h1><p>От запроса в браузере до обработанного изображения.</p></div><svg class="ops-art" viewBox="0 0 240 160" aria-hidden="true"><path d="M35 80h170M120 25v110" stroke="#ffe135" stroke-opacity=".15"/><g fill="#262626" stroke="#ffe135" stroke-width="2"><rect x="18" y="54" width="50" height="50" rx="15"/><rect x="95" y="12" width="50" height="50" rx="15"/><rect x="95" y="96" width="50" height="50" rx="15"/><rect x="172" y="54" width="50" height="50" rx="15"/></g><path d="m35 78 6 6 12-12m57-34h20m-20 84h20m64-44h20" fill="none" stroke="#ffe135" stroke-width="3"/><circle class="ops-orbit" cx="120" cy="80" r="6" fill="#ffe135"/></svg></section>
<p class="ops-notice" role="status"></p><section class="ops-metrics" aria-label="Задания"></section>
<section class="ops-box ops-architecture"><div class="ops-section-head"><div><span class="ops-eyebrow">Архитектура</span><h2>Путь запроса</h2></div><span class="ops-checked">Проверяем…</span></div><div class="ops-flow"><div class="ops-node"><span>01 / клиент</span><strong>Браузер</strong><small>Сообщения и изображения</small></div><div class="ops-arrow">→</div><div class="ops-node" data-service="proxy"><span>02 / вход</span><strong>HAProxy</strong><small>Запрос прошёл через этот адрес</small></div><div class="ops-arrow">→</div><div class="ops-api-nodes"></div></div><div class="ops-services"></div><div class="ops-pipeline"><span>Загрузка</span><i>→</i><span>PostgreSQL + outbox</span><i>→</i><span>Dispatcher</span><i>→</i><span>RabbitMQ</span><i>→</i><span>Worker</span><i>→</i><span>S3: готовые файлы</span></div><p class="ops-footnote">API, worker и dispatcher: heartbeat. Redis, S3 и RabbitMQ: проверка соединения. HAProxy: доступность текущего адреса, без отдельной проверки процесса.</p></section>
<section class="ops-charts"><article class="ops-box"><div class="ops-section-head"><div><span class="ops-eyebrow">Очередь</span><h2>Задания в работе</h2></div><strong class="ops-queue-value">0</strong></div><div class="ops-queue-chart"></div><p class="ops-footnote">Ожидающие + выполняющиеся задания в PostgreSQL. Последние 60 замеров открытой панели.</p></article><article class="ops-box"><div class="ops-section-head"><div><span class="ops-eyebrow">Отклик</span><h2>Время проверки системы</h2></div><strong class="ops-latency-value">…</strong></div><div class="ops-latency-chart"></div><p class="ops-footnote">Время запроса этой панели, включая проверки зависимостей. Это не загрузка CPU.</p></article></section>
<section class="ops-bottom"><article class="ops-box"><div class="ops-section-head"><div><span class="ops-eyebrow">Обработка изображений</span><h2>Последние задания</h2></div><button class="ops-refresh" type="button">Обновить</button></div><div class="ops-jobs"></div></article><article class="ops-box"><span class="ops-eyebrow">События</span><h2>Что происходит</h2><ol class="ops-events"></ol></article></section></main><footer>Данные сервера · <span class="ops-cycle"></span></footer></div>`;
document.body.append(panel);$('.ops-close').onclick=()=>panel.close();$('.ops-brand').onclick=e=>e.preventDefault();$('.ops-refresh').onclick=()=>{clearTimeout(timer);void refresh();};
panel.addEventListener('close',()=>{clearTimeout(timer);abort?.abort();});
}
function chart(target,key,color){
const host=$(target);host.replaceChildren();const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 600 150');svg.setAttribute('role','img');svg.setAttribute('aria-label',samples.length<2?'Ожидаем второй замер':'График последних '+samples.length+' замеров');
const values=samples.map(s=>s[key]),max=Math.max(1,...values);for(let i=0;i<4;i++){const line=document.createElementNS(ns,'path');line.setAttribute('d',`M0 ${10+i*40}H600`);line.setAttribute('stroke','#ffffff10');svg.append(line);}
const path=document.createElementNS(ns,'polyline');path.setAttribute('points',values.map((v,i)=>`${i*600/Math.max(1,values.length-1)},${135-v/max*120}`).join(' '));path.setAttribute('stroke',color);path.setAttribute('stroke-width','3');path.setAttribute('fill','none');svg.append(path);host.append(svg);
const caption=node('div',undefined,'ops-chart-caption');caption.append(node('span',samples.length?new Date(samples[0].at).toLocaleTimeString():'…'),node('span','Макс. '+Math.round(Math.max(0,...values))),node('span',samples.length?new Date(samples.at(-1).at).toLocaleTimeString():'…'));host.append(caption);
}
function service(name,up,detail){const card=node('div',undefined,'ops-service');card.dataset.state=up?'up':'down';card.append(node('span',up?'● На связи':'● Нет свежего ответа'),node('strong',name),node('small',detail));return card;}
function stale(message){$('.ops-notice').textContent=message;panel.classList.add('is-stale');$('.ops-live').textContent='● Нет свежих данных';for(const item of panel.querySelectorAll('[data-state]'))item.dataset.state='unknown';}
async function refresh(){
if(!panel?.open||!token)return;if(document.hidden){timer=setTimeout(refresh,3000);return;}
if(abort&&!abort.signal.aborted)abort.abort();abort=new AbortController();const version=epoch,session=token,signal=abort.signal;const started=performance.now();
try {
const response=await fetch('/api/ui/operations',{headers:{Authorization:'Bearer '+session},cache:'no-store',signal:AbortSignal.any([signal,AbortSignal.timeout(10000)])});
if(!response.ok)throw new Error(response.status===404?'Нет доступа к управлению системой':response.status===401?'Войдите снова':'Сервер временно не отвечает');const data=await response.json();
if(version!==epoch||!panel.open||signal.aborted)return;
const elapsed=Math.round(performance.now()-started);samples.push({queue:data.counts.queued+data.counts.processing,latency:elapsed,at:Date.now()});if(samples.length>60)samples.shift();
panel.classList.remove('is-stale');$('.ops-live').textContent='● Данные обновлены';$('.ops-notice').textContent='';$('.ops-checked').textContent='Проверено '+new Date(data.checked_at).toLocaleTimeString();
$('.ops-metrics').replaceChildren(...Object.entries(labels).map(([key,label])=>{const card=node('article');card.dataset.kind=key;card.append(node('span',label),node('strong',String(data.counts[key])));return card;}));
const apis=$('.ops-api-nodes');apis.replaceChildren(...data.instances.filter(n=>n.ready).map(n=>service('API · '+n.id.slice(0,8),true,'Heartbeat · '+new Date(n.last_seen).toLocaleTimeString())));if(!apis.childNodes.length)apis.append(service('API',false,'Нет свежего heartbeat'));
const current=response.headers.get('X-Instance-Id');for(const card of apis.children)card.classList.toggle('served',card.textContent.includes(current?.slice(0,8)||'never'));
const s=data.services;$('.ops-services').replaceChildren(service('PostgreSQL',s.postgres,'Пользователи, чаты, задания'),service('Redis',s.redis,'Кэш и heartbeat API'),service('S3',s.s3,'Оригиналы и варианты'),service('RabbitMQ',s.broker,`Сообщений: ${data.broker_messages??'?'} · подписчиков: ${data.broker_consumers??'?'}`),service('Dispatcher',s.dispatcher,'Доставка outbox в очередь'),service('Worker',s.worker,'Обработка изображений'));
$('.ops-queue-value').textContent=String(samples.at(-1).queue);$('.ops-latency-value').textContent=elapsed+' мс';chart('.ops-queue-chart','queue','#ffe135');chart('.ops-latency-chart','latency','#a6cf9a');
$('.ops-cycle').textContent=`Outbox: ${data.pending_outbox} · Средний цикл за 15 мин: ${data.average_cycle_seconds===null?'нет завершённых заданий':data.average_cycle_seconds.toFixed(2)+' с'}`;
const jobs=$('.ops-jobs');jobs.replaceChildren();if(!data.jobs.length)jobs.append(node('p','Загрузите изображение в чат. Здесь появится его задание.','ops-empty'));
for(const job of data.jobs){const row=node('div',undefined,'ops-job');const info=node('div');info.append(node('strong',job.filename),node('small',`${labels[job.state]} · попыток ${job.attempts}${job.error_code?' · '+job.error_code:''}`));row.append(info);if(job.can_replay){const button=node('button','Повторить');button.type='button';button.onclick=()=>replay(job.attachment_id,button);row.append(button);}jobs.append(row);}
const list=$('.ops-events');list.replaceChildren();for(const event of data.events){const item=node('li');item.append(node('time',new Date(event.at).toLocaleTimeString()),node('strong',eventLabels[event.name]||event.name),node('span',event.filename));list.append(item);}if(!data.events.length)list.append(node('li','Событий пока нет'));
}catch(error){if(version===epoch&&panel.open&&!signal.aborted)stale(error.message);}finally{if(version===epoch&&panel?.open){clearTimeout(timer);timer=setTimeout(refresh,3000);}}
}
async function replay(id,button){button.disabled=true;button.textContent='Запускаем…';try{const response=await fetch(`/api/ui/operations/attachments/${id}/replay`,{method:'POST',headers:{Authorization:'Bearer '+token},signal:AbortSignal.timeout(10000)});const data=await response.json();if(!response.ok)throw new Error(data.error?.message||'Повтор недоступен');clearTimeout(timer);await refresh();}catch(error){$('.ops-notice').textContent=error.message;button.disabled=false;button.textContent='Повторить';}}
document.getElementById('open-operations').addEventListener('click',()=>{if(!panel)init();panel.showModal();void refresh();});
document.addEventListener('visibilitychange',()=>{if(!document.hidden&&panel?.open){clearTimeout(timer);void refresh();}});
+14
View File
@@ -0,0 +1,14 @@
import sys,base64,http.client,json
from pathlib import Path
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
from client import Client,check
c=Client('http://localhost:18085');actor=c.user('chunked')
registration=actor['registration']
auth='Basic '+base64.b64encode((registration['username']+':'+registration['password']).encode()).decode()
for body,expected in (([],201),([b'x'],400)):
conn=http.client.HTTPConnection('localhost',18085,timeout=10)
conn.request('POST','/api/v1/auth/sessions',body=iter(body),headers={'Authorization':auth,'Transfer-Encoding':'chunked'},encode_chunked=True)
response=conn.getresponse();data=json.loads(response.read());conn.close()
check(response.status==expected,'chunked login status mismatch')
check(('token' in data) if expected==201 else data['error']['code']=='invalid_request','unexpected result')
print('PASS: empty chunked login accepted; nonempty chunked login rejected')
+38
View File
@@ -0,0 +1,38 @@
import base64
from support import *
# The operator session is supplied locally, never stored in evidence.
import os
password=os.environ.get('OPS_TEST_PASSWORD')
if not password:raise SystemExit('Set OPS_TEST_PASSWORD for the configured local operator')
c=Client('http://localhost:18085')
credential=base64.b64encode((os.environ.get('OPS_TEST_USERNAME','n1k0der')+':'+password).encode()).decode()
session=parsed(c,'POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential})
owner={'id':session['user']['id'],'token':session['token']}
a,b,e,chat=c.bootstrap()
check(parsed(c,'GET','/api/ui/operator',actor=owner)['enabled'],'operator not enabled')
check(not parsed(c,'GET','/api/ui/operator',actor=a)['enabled'],'regular user promoted')
c.call('GET','/api/ui/operations',401)
c.call('GET','/api/ui/operations',404,actor=a)
snapshot=parsed(c,'GET','/api/ui/operations',actor=owner)
check(all(name in snapshot['counts'] for name in ('queued','processing','ready','failed')),'counts missing')
check(snapshot['services']['postgres'] and snapshot['services']['s3'] and snapshot['services']['broker'],'probes failed')
user=parsed(c,'GET','/api/ui/users/n1k0der',actor=a)
check(user['id']==owner['id'] and 'password_hash' not in user,'lookup unsafe')
c.call('GET','/api/ui/users/n1k0der',401)
attachment=upload(c,a,chat)['json'];ready(c,a,attachment)
path='/api/ui/operations/attachments/'+attachment['id']+'/replay'
c.call('POST',path,404,actor=a);c.call('POST',path,401);c.call('POST',path,409,actor=owner)
# A controlled failed-state fixture retains the original staging bytes for replay.
compose('stop','worker')
try:
attachment=upload(c,a,chat)['json'];id=job_id(attachment)
sql("UPDATE attachment_jobs SET state='failed',error_code='test_fixture' WHERE id='"+id+"'; UPDATE attachments SET status='failed',error_code='test_fixture' WHERE id='"+attachment['id']+"'")
path='/api/ui/operations/attachments/'+attachment['id']+'/replay'
c.call('POST',path,202,actor=owner);c.call('POST',path,409,actor=owner)
check(sql("SELECT replay_count FROM attachment_jobs WHERE id='"+id+"'")=='1','replay duplicated')
finally:compose('up','-d','--no-deps','worker')
def completed():
result=c.call('GET','/api/v1/attachments/'+attachment['id'],[200,503],actor=a,schema='Attachment')
return result['json']['status']=='ready' if result['status']==200 else False
wait(completed)
print('PASS: operator-only metrics and replay; anonymous 401; regular user 404; exact login lookup; one replay completes with real worker')