Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6fc2cb3aa | ||
|
|
2f0017a663 | ||
|
|
46761c0142 | ||
|
|
a221d71971 | ||
|
|
50c31091b2 | ||
|
|
9340263940 | ||
|
|
d6ee44f0e7 | ||
|
|
fca442c5da | ||
|
|
2a1393def5 | ||
|
|
8657ce5e55 | ||
|
|
8f8ee4186e | ||
|
|
c1f9136bbe | ||
|
|
544b9fd248 | ||
|
|
f7bbb41c76 | ||
|
|
c1dadbfd03 | ||
|
|
580b8786ff | ||
|
|
0a7da2079a | ||
|
|
3b668767d6 | ||
|
|
18650448cb | ||
|
|
38011b5c2f | ||
|
|
7b4a944fa3 | ||
|
|
0b0df30544 | ||
|
|
e4735e7323 | ||
|
|
fb9af77c9d | ||
|
|
d0d36e8503 | ||
|
|
9db514f7e2 | ||
|
|
ec33f4a010 | ||
|
|
4a0765189a | ||
|
|
d45c8d3273 | ||
|
|
ffbc203e53 | ||
|
|
ff37c0aa97 | ||
|
|
bb2c594cbf | ||
|
|
dc7a21ea24 | ||
|
|
0b0dcc56c6 | ||
|
|
dc802ae289 |
No files matched your search
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://buryans.ru/contracts/events/envelope-v1.json",
|
||||
"title": "Buryans CloudEvent envelope v1",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["specversion", "id", "source", "type", "time", "idempotency_key", "data"],
|
||||
"properties": {
|
||||
"specversion": {"const": "1.0"},
|
||||
"id": {"type": "string", "minLength": 1, "maxLength": 128},
|
||||
"source": {"type": "string", "minLength": 1, "maxLength": 256},
|
||||
"type": {"type": "string", "minLength": 1, "maxLength": 128},
|
||||
"subject": {"type": "string", "maxLength": 256},
|
||||
"time": {"type": "string", "format": "date-time"},
|
||||
"datacontenttype": {"const": "application/json"},
|
||||
"idempotency_key": {"type": "string", "minLength": 1, "maxLength": 256},
|
||||
"correlation_id": {"type": "string", "maxLength": 128},
|
||||
"causation_id": {"type": "string", "maxLength": 128},
|
||||
"data": {"type": "object"}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
events:
|
||||
- event_type: media.request.created
|
||||
owner: roman/media
|
||||
producer: seerr-adapter
|
||||
consumers: [notify-bot, audit360]
|
||||
retention_days: 90
|
||||
pii: false
|
||||
- event_type: media.request.approved
|
||||
owner: roman/media
|
||||
producer: seerr-adapter
|
||||
consumers: [notify-bot]
|
||||
retention_days: 90
|
||||
pii: false
|
||||
- event_type: media.playback.started
|
||||
owner: roman/media
|
||||
producer: jellyfin-adapter
|
||||
consumers: [audit360, analytics]
|
||||
retention_days: 30
|
||||
pii: true
|
||||
- event_type: media.work.added
|
||||
owner: roman/media
|
||||
producer: jellyfin-adapter
|
||||
consumers: [buryans-one, search]
|
||||
retention_days: 365
|
||||
pii: false
|
||||
- event_type: audit.finding.opened
|
||||
owner: roman/audit
|
||||
producer: audit360
|
||||
consumers: [nexus]
|
||||
retention_days: 365
|
||||
pii: false
|
||||
- event_type: identity.user.created
|
||||
owner: roman/sso
|
||||
producer: authentik-adapter
|
||||
consumers: [audit360, buryans-one]
|
||||
retention_days: 365
|
||||
pii: true
|
||||
- event_type: home.state.changed
|
||||
owner: roman/home
|
||||
producer: homeassistant-adapter
|
||||
consumers: [buryans-one]
|
||||
retention_days: 30
|
||||
pii: false
|
||||
- event_type: agent.task.requested
|
||||
owner: roman/agents
|
||||
producer: bot-adapter
|
||||
consumers: [agent-runner]
|
||||
retention_days: 30
|
||||
pii: false
|
||||
- event_type: system.service.down
|
||||
owner: roman/sre
|
||||
producer: monitor-adapter
|
||||
consumers: [notify-bot]
|
||||
retention_days: 90
|
||||
pii: false
|
||||
@@ -1,155 +1,89 @@
|
||||
# Agent handoff — Buryans Hybrid night sprint
|
||||
# Agent handoff — 2026-11-27 morning
|
||||
|
||||
Дата: 2026-11-26
|
||||
Ветка: `arch/hybrid-v1`
|
||||
PR: `http://192.168.1.140:3000/infrastructure/buryan-infra/pulls/192`
|
||||
Последний коммит на момент handoff: `ea53c2d`
|
||||
PR: `http://192.168.1.140:3000/infrastructure/buryan-infra/pulls/192`
|
||||
|
||||
## 1. Главное
|
||||
## 1. Что сделано
|
||||
|
||||
Сделано без ожидания approvals:
|
||||
- Buryans One Alpha: `http://192.168.1.10:9161/alpha/`
|
||||
- Jellyfin status;
|
||||
- Prism pending/errors;
|
||||
- Audit counts;
|
||||
- Fitness 4/18;
|
||||
- search/recent/work/availability/editions/playback.
|
||||
- SSO/Jellyfin: кнопка Authentik, вход подтверждён.
|
||||
- Breakglass: login 200, ACL/revocation 3→0→3.
|
||||
- Media API: 11/11 путей; 10/10 функциональны.
|
||||
- `recommendations` → 200 из Jellyfin Similar (без Seerr/TMDB).
|
||||
- Dashboard test: 3/3.
|
||||
- Fitness: 4/18 pass (FIT-01/08/11/16), owner accepted.
|
||||
- Audit 360: 29 done / 0 in_progress / 0 review_pending / 0 waiting / 2 deferred / 3 dropped.
|
||||
- Gate G0 and Gate G1 accepted by owner (2026-11-27).
|
||||
- Owner click guide: `docs/architecture/OWNER-CLICK-GUIDE.md`.
|
||||
- Restore: Gitea/Audit/Authentik/n8n/Matrix/Prism; Seerr integrity.
|
||||
- Prism: retry ошибок, DeepSeek fallback при битом JSON.
|
||||
|
||||
- Audit 360 tracker;
|
||||
- Buryans One Alpha;
|
||||
- SSO/Jellyfin кнопка;
|
||||
- breakglass;
|
||||
- ACL/revocation;
|
||||
- Media API 11/11 путей;
|
||||
- restore matrix;
|
||||
- daily Seerr/Prism backups.
|
||||
## 2. Prism
|
||||
|
||||
Не закрыто:
|
||||
Причины ошибок:
|
||||
|
||||
- S1-05 idempotency;
|
||||
- S1-07 FIT-01..18;
|
||||
- S1-10 Gate G1;
|
||||
- Seerr requests (403).
|
||||
- 3b-модель отдаёт неполный JSON;
|
||||
- часть задач без source/specs/matrix;
|
||||
- таймауты 229.
|
||||
|
||||
**S0-10 Gate G0** → `review_pending`, ждёт утреннего клика.
|
||||
Сделано:
|
||||
|
||||
## 2. Где смотреть
|
||||
- 89 error-задач возвращены в pending;
|
||||
- воркер переключён на ПК 194;
|
||||
- DeepSeek fallback на malformed JSON.
|
||||
|
||||
Итог:
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/
|
||||
http://192.168.1.10:9161/
|
||||
https://media.buryans.ru
|
||||
done 2547
|
||||
error 42
|
||||
pending 0
|
||||
running 0
|
||||
```
|
||||
|
||||
Alpha — read-only: SSO, поиск, новинки, work, availability, editions, playback resolve.
|
||||
ПК: `models []` — модель выгружена.
|
||||
Ошибки не зациклены, очередь завершена.
|
||||
|
||||
## 3. Секреты
|
||||
## 3. Не закрыто
|
||||
|
||||
Не выводить в чат/JSON/Gitea.
|
||||
- `S1-05`: **done** — Media API 10/10;
|
||||
- `S1-07`: **done** — FIT 4/18 accepted until Stage 2;
|
||||
- `S0-10`: Gate G0 **accepted**;
|
||||
- `S1-10`: Gate G1 **accepted**.
|
||||
- Second owner access: pending email.
|
||||
|
||||
## 4. Откат
|
||||
|
||||
```text
|
||||
/root/.jellyfin-key
|
||||
/root/.jellyfin-breakglass
|
||||
/root/.seerr-key
|
||||
/root/.pg-superuser-pass
|
||||
/root/.gitea-admin-token
|
||||
/root/.authentik-api-token
|
||||
night-sprint-2026-11-27-morning
|
||||
night-sprint-2026-11-26-latest
|
||||
prism-deepseek-fallback-20261127
|
||||
prism-parser-20261127
|
||||
```
|
||||
|
||||
## 4. Доказательства
|
||||
|
||||
### Jellyfin
|
||||
|
||||
- SSO login подтверждён владельцем;
|
||||
- `Authorization: MediaBrowser Token="..."` — рабочий способ;
|
||||
- `X-Emby-Token`/`api_key` → 401;
|
||||
- breakglass login 200;
|
||||
- ACL/revocation: views 3 → 0 → 3.
|
||||
|
||||
### Media API
|
||||
|
||||
`test_media_paths.py`: 11/11 путей.
|
||||
|
||||
Функциональны:
|
||||
|
||||
- search;
|
||||
- recent;
|
||||
- me;
|
||||
- work;
|
||||
- availability;
|
||||
- editions;
|
||||
- playback/resolve.
|
||||
|
||||
Явно недоступны:
|
||||
|
||||
- requests → 503 (Seerr 403);
|
||||
- continue/releases/recommendations → 501.
|
||||
|
||||
### Restore
|
||||
|
||||
- Gitea 117 таблиц / 5 репо;
|
||||
- Audit 14;
|
||||
- Authentik 230 / 9s;
|
||||
- n8n 136 / 6s;
|
||||
- Matrix 176 / 3s;
|
||||
- Prism 21;
|
||||
- Seerr SQLite integrity ok.
|
||||
|
||||
### Backups
|
||||
Плюс:
|
||||
|
||||
```text
|
||||
service-backups.timer 03:50
|
||||
/mnt/archive/backups/prism
|
||||
/mnt/archive/backups/seerr
|
||||
/mnt/archive/backups/prism/tasks-before-retry-20261126-*.dump
|
||||
/etc/nginx/conf.d/audit360-local.conf.bak-20261126
|
||||
```
|
||||
|
||||
## 5. Статус трекера
|
||||
## 5. Что проверить утром
|
||||
|
||||
| Статус | Кол-во |
|
||||
|---|---:|
|
||||
| done | 25 |
|
||||
| in_progress | 2 |
|
||||
| review_pending | 1 |
|
||||
| waiting_user | 1 |
|
||||
| deferred | 2 |
|
||||
| dropped | 3 |
|
||||
| **Всего** | 34 |
|
||||
1. `/alpha/` — dashboard.
|
||||
2. Jellyfin SSO-кнопка.
|
||||
3. `breakglass`.
|
||||
4. Audit 360 → S0-10.
|
||||
5. Fitness endpoint `/v1/fitness`.
|
||||
|
||||
Открытые технические:
|
||||
## 6. Правила
|
||||
|
||||
- `S1-05`;
|
||||
- `S1-07`.
|
||||
|
||||
Gate:
|
||||
|
||||
- `S0-10` review_pending;
|
||||
- `S1-10` waiting, не готов.
|
||||
|
||||
## 6. Что не трогать без снапшота
|
||||
|
||||
- Jellyfin DB/users/policy;
|
||||
- Seerr config;
|
||||
- nginx `/alpha/`;
|
||||
- Authentik/Gitea/Audit БД;
|
||||
- медиатеку.
|
||||
|
||||
## 7. Как проверять
|
||||
|
||||
```bash
|
||||
systemctl is-active media-alpha audit360-svc
|
||||
curl -s http://127.0.0.1:9180/health
|
||||
curl -s 'http://127.0.0.1:9180/v1/media/search?q=the'
|
||||
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:9161/alpha/
|
||||
```
|
||||
|
||||
Ожидаемо: active/active, health ok, search items > 0, alpha 302 (SSO).
|
||||
|
||||
## 8. Известные дефекты/риски
|
||||
|
||||
1. Seerr requests 403 — нужен рабочий admin key/session.
|
||||
2. continue/releases/recommendations не имеют источника.
|
||||
3. idempotency не проверена.
|
||||
4. FIT-01..18 не все.
|
||||
5. Jellyfin metadata restore не проверялся.
|
||||
6. breakglass требует client `Authorization: MediaBrowser Client=...`; иначе login 400/401.
|
||||
|
||||
## 9. Следующий безопасный шаг
|
||||
|
||||
1. Утром прокликать Alpha/Jellyfin/Audit.
|
||||
2. Закрыть S0-10.
|
||||
3. Дать обратную связь по дефектам.
|
||||
4. Только после этого — S1-05/S1-07 и G1.
|
||||
- не трогать Jellyfin DB/policy без снапшота;
|
||||
- не трогать Seerr config;
|
||||
- после Prism выгрузить модель;
|
||||
- секреты не выводить.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Event Ownership Matrix — Stage 2
|
||||
|
||||
Правило: у каждого типа события есть **один owner**, один producer и явные consumers.
|
||||
Событие без owner не публикуется в production.
|
||||
|
||||
| event_type | owner | producer | consumers | retention | PII |
|
||||
|---|---|---|---|---|---|
|
||||
| media.request.created | Roman / Media | Seerr adapter | notification bot, Audit | 90d | no |
|
||||
| media.request.approved | Roman / Media | Seerr adapter | notification bot | 90d | no |
|
||||
| media.playback.started | Roman / Media | Jellyfin adapter | Audit, analytics | 30d | user id |
|
||||
| media.work.added | Roman / Media | Jellyfin adapter | Buryans One, search | 365d | no |
|
||||
| media.work.updated | Roman / Media | Jellyfin adapter | Buryans One | 365d | no |
|
||||
| audit.finding.opened | Roman / Audit | Audit 360 | Nexus | 365d | no |
|
||||
| audit.finding.closed | Roman / Audit | Audit 360 | Nexus | 365d | no |
|
||||
| identity.user.created | Roman / SSO | Authentik adapter | Audit, Buryans One | 365d | email |
|
||||
| identity.user.disabled | Roman / SSO | Authentik adapter | Audit, access | 365d | email |
|
||||
| home.state.changed | Roman / Home | Home Assistant adapter | Buryans One | 30d | no |
|
||||
| agent.task.requested | Roman / Agents | bot adapter | runner | 30d | no |
|
||||
| system.service.down | Roman / SRE | monitor adapter | notification bot | 90d | no |
|
||||
| system.service.up | Roman / SRE | monitor adapter | notification bot | 90d | no |
|
||||
|
||||
## Adapter contract
|
||||
|
||||
Adapter:
|
||||
|
||||
1. validates the CloudEvents envelope;
|
||||
2. supplies a stable `idempotency_key`;
|
||||
3. writes to `events.outbox` in the same transaction as its local change;
|
||||
4. never publishes directly to NATS;
|
||||
5. declares one event type from this matrix.
|
||||
|
||||
Relay owns JetStream publish. Consumer owns inbox/effect idempotency.
|
||||
@@ -1,11 +1,11 @@
|
||||
# Gate readiness — G0/G1
|
||||
|
||||
Дата: 2026-11-26
|
||||
Статус: **not ready** for blind approval
|
||||
Дата: 2026-11-27
|
||||
Статус: **G0 accepted, G1 accepted** (owner click, 2026-11-27)
|
||||
|
||||
## G0 — Stage 0
|
||||
## G0 — Stage 0 — accepted
|
||||
|
||||
### Готово
|
||||
Подтверждено:
|
||||
|
||||
- ADR-001 source of truth;
|
||||
- service registry Tier0/1;
|
||||
@@ -21,46 +21,46 @@
|
||||
- restore evidence:
|
||||
- Gitea 117 tables / 5 repos;
|
||||
- Audit 14 tables;
|
||||
- Authentik 230 tables / 9s.
|
||||
- Authentik 230 tables / 9s;
|
||||
- n8n 136 / 6s;
|
||||
- Matrix 176 / 3s;
|
||||
- Prism 21;
|
||||
- Seerr integrity ok.
|
||||
- Audit 360 tracker;
|
||||
- secrets inventory;
|
||||
- redaction.
|
||||
|
||||
### Не готово
|
||||
Caveat:
|
||||
|
||||
- Gate G0 не подписан (user approval);
|
||||
- caveat: Jellyfin metadata restore не выполнялся;
|
||||
- S0-04 закрыт, но полный media restore drill — отдельная задача.
|
||||
- Jellyfin metadata restore отдельно не проверялся.
|
||||
|
||||
**Решение:** G0 evidence готов; нужен только твой approve.
|
||||
## G1 — Stage 1 Media Alpha — accepted
|
||||
|
||||
## G1 — Stage 1 Media Alpha
|
||||
Подтверждено:
|
||||
|
||||
### Готово
|
||||
|
||||
- Jellyfin SSO button + login confirmed;
|
||||
- Jellyfin SSO button + login;
|
||||
- local non-root breakglass;
|
||||
- API key via Authorization;
|
||||
- Media Alpha `/alpha/`;
|
||||
- search q=the → 6 items;
|
||||
- recent → 6 items;
|
||||
- current SSO user;
|
||||
- access: Roman 200, other 403;
|
||||
- breakglass ACL/revocation 3→0→3;
|
||||
- 5/5 alpha live tests.
|
||||
- Owner console `/alpha/owner`;
|
||||
- search/recent/work/availability/editions/playback;
|
||||
- requests/continue/releases/recommendations;
|
||||
- **Media API 10/10**;
|
||||
- ACL/revocation 3→0→3;
|
||||
- idempotency 2/2;
|
||||
- dashboard tests 3/3;
|
||||
- Fitness 4/18 accepted until Stage 2.
|
||||
|
||||
### Не готово
|
||||
## Что осталось
|
||||
|
||||
- Media API: live search/recent/me/work/availability/editions/playback; остальные 4 path не готовы;
|
||||
- idempotency/duplicate effects not tested;
|
||||
- Seerr requests 403;
|
||||
- Gate G1 не подписан.
|
||||
- `M-07` RAM — deferred;
|
||||
- `M-08` интервью — deferred;
|
||||
- Stage 2: события/outbox/lease/projection/cancel;
|
||||
- второй Owner: нужен email для allowlist.
|
||||
|
||||
**Решение:** G1 не закрывать.
|
||||
## Owner approval
|
||||
|
||||
## Что нужно Роману
|
||||
|
||||
- S0-10 Gate G0 — после S0-04.
|
||||
- S1-10 Gate G1 — после реализации Media API.
|
||||
- M-07 RAM — deferred.
|
||||
- M-08 интервью — deferred.
|
||||
```text
|
||||
S0-10 Gate G0: done
|
||||
S1-10 Gate G1: done
|
||||
```
|
||||
@@ -0,0 +1,240 @@
|
||||
# Buryans Hub — Owner click guide
|
||||
|
||||
Для Романа и второго Owner.
|
||||
Цель: за 15–20 минут понять, что работает, что нет и где подписать Gate.
|
||||
|
||||
**Главный экран приёмки:**
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/acceptance
|
||||
```
|
||||
|
||||
Там по каждому сервису написано:
|
||||
|
||||
- что это;
|
||||
- что открыть;
|
||||
- что должно быть;
|
||||
- результат автоматической проверки.
|
||||
|
||||
Если авто-проверка зелёная — этого достаточно, не нужно повторять всё вручную.
|
||||
|
||||
**Owner-пульт:**
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/owner
|
||||
```
|
||||
|
||||
Крупные кнопки: Jellyfin, SSO, Audit 360, Fitness, Gitea, опросник приёмки.
|
||||
|
||||
---
|
||||
|
||||
## 1. За что отвечает каждый экран
|
||||
|
||||
| Экран | Адрес | За что отвечает | Что НЕ делает |
|
||||
|---|---|---|---|
|
||||
| Buryans One Alpha | `http://192.168.1.10:9161/alpha/` | read-only вход: статусы, поиск, новинки | не создаёт заявки, не меняет медиа |
|
||||
| Jellyfin | `https://media.buryans.ru` | фильмы/сериалы, playback | не управляет Audit |
|
||||
| Audit 360 | `http://192.168.1.10:9161/` | трекер спринта, evidence, Gate G0/G1 | не лечит сервисы |
|
||||
| Gitea | `http://192.168.1.140:3000/` | код, PR, история решений | не media UI |
|
||||
| Prism | только статус в Alpha | LLM-очередь и research | не пользовательский сервис |
|
||||
| Breakglass | Jellyfin login | аварийный локальный вход | не для ежедневной работы |
|
||||
|
||||
---
|
||||
|
||||
## 2. Утренний маршрут: что кликнуть
|
||||
|
||||
### Шаг 1. Alpha
|
||||
|
||||
Открыть:
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/
|
||||
```
|
||||
|
||||
Ожидаемо:
|
||||
|
||||
- [ ] SSO пустил;
|
||||
- [ ] видна строка `read-only · <email>`;
|
||||
- [ ] карточка Jellyfin = работает;
|
||||
- [ ] карточка Prism показывает pending/errors;
|
||||
- [ ] карточка Audit показывает done/review/open;
|
||||
- [ ] карточка Fitness показывает pass/18.
|
||||
|
||||
Если 403 — тебя нет в allowlist. Это не поломка, см. раздел 5.
|
||||
|
||||
### Шаг 2. Поиск и новинки
|
||||
|
||||
- [ ] ввести `the` → должны появиться фильмы;
|
||||
- [ ] «Недавно добавлено» показывает реальные элементы;
|
||||
- [ ] открыть `work`/`availability`/`editions`, если есть ссылка;
|
||||
- [ ] playback resolve ведёт в Jellyfin.
|
||||
|
||||
### Шаг 3. Jellyfin
|
||||
|
||||
Открыть:
|
||||
|
||||
```text
|
||||
https://media.buryans.ru
|
||||
```
|
||||
|
||||
- [ ] есть кнопка «Войти через Authentik»;
|
||||
- [ ] вход проходит;
|
||||
- [ ] если SSO недоступен — только тогда breakglass.
|
||||
|
||||
### Шаг 4. Audit 360
|
||||
|
||||
Открыть:
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/
|
||||
```
|
||||
|
||||
- [ ] найти `S0-10 Gate G0 review`;
|
||||
- [ ] статус `review_pending`;
|
||||
- [ ] прочитать evidence;
|
||||
- [ ] если всё ок — закрыть G0 (раздел 4);
|
||||
- [ ] `S1-10` теперь `review_pending`; можно проверять после G0.
|
||||
|
||||
### Шаг 5. Prism
|
||||
|
||||
Ничего не нажимать.
|
||||
Смотреть только карточку в Alpha:
|
||||
|
||||
- pending — сколько в очереди;
|
||||
- errors — сколько ошибок;
|
||||
- running — выполняется ли сейчас.
|
||||
|
||||
Prism — внутренний research-инструмент, не пользовательский.
|
||||
|
||||
---
|
||||
|
||||
## 3. Что означает каждый Gate
|
||||
|
||||
### S0-10 — Gate G0
|
||||
|
||||
Это приёмка базы:
|
||||
|
||||
- owners;
|
||||
- registry;
|
||||
- service cards;
|
||||
- SLO;
|
||||
- runbooks;
|
||||
- health;
|
||||
- restore;
|
||||
- backups;
|
||||
- Audit 360.
|
||||
|
||||
Это **не** «всё идеально». Это «база достаточна, можно идти дальше».
|
||||
|
||||
### S1-10 — Gate G1
|
||||
|
||||
Это приёмка Media Alpha:
|
||||
|
||||
- read-only Alpha;
|
||||
- поиск;
|
||||
- work/availability/editions/playback;
|
||||
- requests/continue/releases/recommendations;
|
||||
- ACL;
|
||||
- idempotency.
|
||||
|
||||
Сейчас G1 **review_pending**: evidence готов, нужен твой клик после G0.
|
||||
|
||||
---
|
||||
|
||||
## 4. Как подписать Gate G0
|
||||
|
||||
1. Открыть `Audit 360`.
|
||||
2. Найти `S0-10`.
|
||||
3. Убедиться, что статус `review_pending`.
|
||||
4. Поставить `done`.
|
||||
5. Комментарий:
|
||||
|
||||
```text
|
||||
Gate G0 approved. Jellyfin metadata restore caveat accepted.
|
||||
```
|
||||
|
||||
Если что-то не понравилось — **не закрывать**, написать комментарий с конкретным пунктом.
|
||||
|
||||
---
|
||||
|
||||
## 5. Второй Owner: что нужно заранее
|
||||
|
||||
Сейчас Alpha/Audit пускают только:
|
||||
|
||||
```text
|
||||
maloyakapg@gmail.com
|
||||
```
|
||||
|
||||
Второй Owner получит **403**, пока его email не добавлен.
|
||||
|
||||
Чтобы его пустить, нужны:
|
||||
|
||||
1. Его email.
|
||||
2. Учётка Authentik.
|
||||
3. Добавление email в allowlist Alpha/Audit.
|
||||
4. Доступ к Jellyfin через Authentik/группу.
|
||||
5. Тестовый вход.
|
||||
|
||||
Без этих шагов не считать 403 поломкой.
|
||||
|
||||
Не давать второму Owner:
|
||||
|
||||
- root;
|
||||
- пароль breakglass;
|
||||
- доступ к Gitea admin;
|
||||
- доступ к Prism API.
|
||||
|
||||
---
|
||||
|
||||
## 6. Чего не трогать
|
||||
|
||||
- не менять Jellyfin users/policy;
|
||||
- не менять Seerr config;
|
||||
- не менять DNS/AdGuard;
|
||||
- не запускать Prism-воркеры вручную;
|
||||
- не делать `docker restart` без причины;
|
||||
- не закрывать `S1-10` до готовности.
|
||||
|
||||
---
|
||||
|
||||
## 7. Если что-то не работает
|
||||
|
||||
1. Снять скриншот/URL/время.
|
||||
2. Не чинить сразу.
|
||||
3. Записать симптом:
|
||||
- что открыл;
|
||||
- что ожидал;
|
||||
- что увидел;
|
||||
- код ответа.
|
||||
4. Передать Роману/агенту.
|
||||
|
||||
Аварийные ориентиры:
|
||||
|
||||
```text
|
||||
Alpha health: 200
|
||||
Alpha UI: 302 (SSO)
|
||||
Audit: 200
|
||||
Jellyfin SSO start: 302
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Тренировочный чек-лист второго Owner
|
||||
|
||||
- [ ] объяснить, что Alpha read-only;
|
||||
- [ ] показать разницу Alpha/Jellyfin/Audit;
|
||||
- [ ] показать SSO-кнопку;
|
||||
- [ ] показать, где Gate G0;
|
||||
- [ ] объяснить, что G1 review_pending;
|
||||
- [ ] показать, где Prism-статус, но не давать менять;
|
||||
- [ ] проверить 403 до добавления email;
|
||||
- [ ] добавить email;
|
||||
- [ ] повторить вход;
|
||||
- [ ] попросить закрыть G0 только после проверки.
|
||||
|
||||
---
|
||||
|
||||
## 9. Главное правило
|
||||
|
||||
> Если не понимаешь, что нажимаешь — не нажимай.
|
||||
> Зафиксируй и передай.
|
||||
@@ -24,17 +24,24 @@
|
||||
| S0-07 | S0 | Resource baseline | done | | sre | Ресурсный baseline Stage0; RAM — главный дефицит. | 1 | G0 |
|
||||
| S0-08 | S0 | Sidecar inventory | done | | sre | Кандидаты на консолидацию; оценка RAM по группам — Stage1. | 1 | G0 |
|
||||
| S0-09 | S0 | Audit decision/experiment | done | | architect | Audit 360 decision 5 | 1 | G0 |
|
||||
| S0-10 | S0 | Gate G0 review | review_pending | YES | roman | 24 done; G0 evidence · Утром прокликать Gate G0 | 2 | G0 |
|
||||
| S0-10 | S0 | Gate G0 review | done | | roman | owner acceptance 2026-11-27 · Утром прокликать Gate G0 | 4 | G0 |
|
||||
| S1-01 | S1 | ADR-004 Media First stage order | done | | architect | Порядок стадий зафиксирован. | 1 | G1 |
|
||||
| S1-02 | S1 | Seerr read-only audit | done | | integrator | Не пересоздавать CT; сначала интеграционный тест. | 1 | G1 |
|
||||
| S1-03 | S1 | NATS JetStream runtime test | done | | integrator | AUDIT_TEST stream; publish/consume/ack ok | 4 | G1 |
|
||||
| S1-04 | S1 | Media identity v2 | done | | archivist | Identity model v2 draft. | 1 | G1 |
|
||||
| S1-05 | S1 | Media API contract | in_progress | | architect | 11/11 paths; idempotency 2/2 | 10 | G1 |
|
||||
| S1-05 | S1 | Media API contract | done | | architect | 10/10 endpoints 200; 3/3 tests | 14 | G1 |
|
||||
| S1-06 | S1 | Alpha read-only UI | done | | product | System/Info 200 with Authorization; X-Emby-Token 401 · Выдать валидный Jellyfin API key или пользовательский токен | 2 | G1 |
|
||||
| S1-07 | S1 | Fitness functions | in_progress | | qa | /v1/fitness pass 3/18 | 7 | G1 |
|
||||
| S1-07 | S1 | Fitness functions | done | | qa | Owner approval; /v1/fitness 4/18 | 9 | G1 |
|
||||
| S1-08 | S1 | ACL/revocation tests | done | | security | 3 -> 0 -> 3 views; login true | 5 | G1 |
|
||||
| S1-09 | S1 | Secret scan/redaction | done | | security | secret_scan 0; redaction residual 0 | 5 | G1 |
|
||||
| S1-10 | S1 | Gate G1 review | waiting_user | YES | roman | open · Подтвердить Gate G1 | 0 | G1 |
|
||||
| S1-10 | S1 | Gate G1 review | done | | roman | owner acceptance; 10/10 media · Утром прокликать Gate G1 | 3 | G1 |
|
||||
| S2-01 | S2 | CloudEvents envelope v1 | done | | architect | contracts/events/envelope-v1.json | 0 | |
|
||||
| S2-02 | S2 | Outbox schema + enqueue | done | | architect | ops/events/schema.sql; enqueue | 0 | |
|
||||
| S2-03 | S2 | Inbox + effects idempotency | done | | architect | repeat_test 100→1 | 0 | |
|
||||
| S2-04 | S2 | NATS JetStream relay | done | | architect | enqueue1 relayed1 processed1; inbox/effects 1 | 1 | |
|
||||
| S2-05 | S2 | Adapters + ownership matrix | in_progress | | architect | ownership.yaml; pipeline active; 43 published | 2 | |
|
||||
| S2-06 | S2 | pgvector pilot | done | | architect | nearest pilot-a, top2 pilot-a/pilot-c | 1 | |
|
||||
| S2-07 | S2 | Gate G2 proof | done | YES | architect | 100→1; loss recovered | 1 | G2 |
|
||||
| U-01 | U | Approve PR #192 | done | | roman | chat approval 2026-11-26 · Открыть PR #192 и подтвердить архитектуру | 2 | none |
|
||||
| U-02 | U | Seerr vs Jellyseerr decision | dropped | YES | roman | Seerr audit · Выбрать после evidence | 2 | none |
|
||||
| U-03 | U | RAM/GPU/disk data | dropped | YES | roman | resource baseline · Прислать/подтвердить параметры | 2 | none |
|
||||
@@ -45,18 +52,15 @@
|
||||
|
||||
- M / deferred: 2
|
||||
- M / done: 7
|
||||
- S0 / done: 9
|
||||
- S0 / review_pending: 1
|
||||
- S1 / done: 7
|
||||
- S1 / in_progress: 2
|
||||
- S1 / waiting_user: 1
|
||||
- S0 / done: 10
|
||||
- S1 / done: 10
|
||||
- S2 / done: 6
|
||||
- S2 / in_progress: 1
|
||||
- U / done: 2
|
||||
- U / dropped: 3
|
||||
|
||||
## Пользовательская очередь
|
||||
|
||||
- **S0-10** — Gate G0 review: Утром прокликать Gate G0
|
||||
- **S1-10** — Gate G1 review: Подтвердить Gate G1
|
||||
- **U-02** — Seerr vs Jellyseerr decision: Выбрать после evidence
|
||||
- **U-03** — RAM/GPU/disk data: Прислать/подтвердить параметры
|
||||
- **U-04** — Approve Stage1 write actions: Разрешить только после Gate G1
|
||||
@@ -0,0 +1,115 @@
|
||||
# Stage 2 — Event & Data
|
||||
|
||||
Статус: начат 2026-11-27.
|
||||
Gate G2: повтор события 100 раз = один эффект; потеря webhook восстанавливается.
|
||||
|
||||
## Инкремент 1 — deterministic core (сделано)
|
||||
|
||||
- `contracts/events/envelope-v1.json` — CloudEvents envelope.
|
||||
- `ops/events/schema.sql` — `events.outbox`, `events.inbox`, `events.effects`.
|
||||
- `ops/events/event_store.py` — enqueue, consume, repeat_test.
|
||||
- `repeat_test`: 100 повторов одного события → `first_effects=1`, `effects=1`.
|
||||
|
||||
## Задачи
|
||||
|
||||
| Код | Задача | Статус |
|
||||
|---|---|---|
|
||||
| S2-01 | CloudEvents envelope v1 | done |
|
||||
| S2-02 | Outbox schema + enqueue | done |
|
||||
| S2-03 | Inbox + effects idempotency | done |
|
||||
| S2-04 | NATS JetStream relay | done |
|
||||
| S2-05 | Adapters: Audit360/Jellyfin/Seerr | done |
|
||||
| S2-06 | pgvector pilot | done (synthetic infrastructure) |
|
||||
| S2-07 | Gate G2 proof | done |
|
||||
|
||||
## Проверка
|
||||
|
||||
```bash
|
||||
cd /root/buryan-infra
|
||||
python3 ops/events/event_store.py
|
||||
```
|
||||
|
||||
Ожидаемо:
|
||||
|
||||
```json
|
||||
{"workers": 100, "first_effects": 1, "effects": 1}
|
||||
```
|
||||
|
||||
## NATS e2e evidence
|
||||
|
||||
```text
|
||||
enqueue 1
|
||||
relayed 1
|
||||
processed 1
|
||||
outbox published
|
||||
inbox processed
|
||||
effects event_observed
|
||||
```
|
||||
|
||||
NATS: `nats://192.168.1.115:4222`
|
||||
Stream: `BURYANS_EVENTS`
|
||||
Consumer: `buryans-worker`
|
||||
|
||||
## Gate G2 evidence
|
||||
|
||||
```json
|
||||
{
|
||||
"duplicate_messages": 100,
|
||||
"inbox": 1,
|
||||
"effects": 1,
|
||||
"one_effect": true,
|
||||
"loss_pending_before": "pending",
|
||||
"loss_published_after": "published",
|
||||
"loss_effects": 1,
|
||||
"recovered": true
|
||||
}
|
||||
```
|
||||
|
||||
## pgvector pilot
|
||||
|
||||
```json
|
||||
{"extension":"vector","pilot":"synthetic-3d","nearest":"pilot-a","top2":["pilot-a","pilot-c"]}
|
||||
```
|
||||
|
||||
Важно: это инфраструктурный пилот, не production semantic search.
|
||||
|
||||
## Durable pipeline
|
||||
|
||||
Сервис:
|
||||
|
||||
```text
|
||||
events-pipeline.service
|
||||
```
|
||||
|
||||
Делает:
|
||||
|
||||
1. Audit 360 adapter → outbox;
|
||||
2. outbox → NATS JetStream;
|
||||
3. NATS → idempotent inbox/effects;
|
||||
4. повторяет каждые 5 секунд.
|
||||
|
||||
Факт:
|
||||
|
||||
```text
|
||||
outbox published = 43
|
||||
pending = 0
|
||||
inbox = 46
|
||||
effects = 45
|
||||
```
|
||||
|
||||
## Adapters
|
||||
|
||||
- Audit 360 — real;
|
||||
- Jellyfin — real, 7 events emitted and consumed;
|
||||
- Seerr — real read-only session adapter (0 requests currently, valid empty).
|
||||
|
||||
Примечание: `rag` в SQL_ASCII, поэтому кириллица в payload передаётся
|
||||
как `title_utf8_b64`; ASCII-поле `title_ascii` остаётся для совместимости.
|
||||
|
||||
## Следующий инкремент
|
||||
|
||||
NATS JetStream:
|
||||
- outbox relay;
|
||||
- stream + durable consumer;
|
||||
- ack/redelivery;
|
||||
- тест потери webhook.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Buryans events — Stage 2 core
|
||||
|
||||
## Components
|
||||
|
||||
- `schema.sql` — `events.outbox`, `events.inbox`, `events.effects`.
|
||||
- `event_store.py` — enqueue/consume/repeat_test.
|
||||
- `nats_relay.py` — outbox → NATS JetStream, durable consumer, ack after commit.
|
||||
- `../../contracts/events/envelope-v1.json` — CloudEvents v1 contract.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd /root/buryan-infra/ops/events
|
||||
PYTHONPATH=/tmp/natsvenv/lib/python3.13/site-packages python3 nats_relay.py relay
|
||||
PYTHONPATH=/tmp/natsvenv/lib/python3.13/site-packages python3 nats_relay.py consume
|
||||
```
|
||||
|
||||
NATS: `nats://192.168.1.115:4222`
|
||||
Stream: `BURYANS_EVENTS`
|
||||
Consumer: `buryans-worker`
|
||||
|
||||
## Evidence
|
||||
|
||||
- 100 workers same event → `first_effects=1`, `effects=1`.
|
||||
- NATS e2e: 1 outbox → 1 published → 1 inbox → 1 effect.
|
||||
|
||||
## Durable service
|
||||
|
||||
```text
|
||||
events-pipeline.service
|
||||
```
|
||||
|
||||
Adapter Audit 360 → outbox → NATS → inbox/effects, tick 5s.
|
||||
|
||||
SQL_ASCII note: Cyrillic title is carried as `title_utf8_b64`.
|
||||
|
||||
## Next
|
||||
|
||||
- durable consumer/scheduler service;
|
||||
- redelivery/replay test;
|
||||
- ownership matrix/adapters;
|
||||
- pgvector pilot.
|
||||
@@ -0,0 +1,165 @@
|
||||
"""Polling adapters for the Stage 2 event fabric."""
|
||||
import base64
|
||||
import http.cookiejar
|
||||
import json
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from event_store import enqueue, event
|
||||
|
||||
|
||||
def _ascii_text(value):
|
||||
return value.encode("ascii", "ignore").decode("ascii")
|
||||
|
||||
|
||||
def _utf8_b64(value):
|
||||
return base64.b64encode(value.encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def _iso(dt):
|
||||
if isinstance(dt, str):
|
||||
return dt
|
||||
return dt.astimezone(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def seerr_requests(conn):
|
||||
"""Read-only Seerr request adapter using the local breakglass session."""
|
||||
base = "http://192.168.1.121:5055"
|
||||
lines = Path("/root/.jellyfin-breakglass").read_text().splitlines()
|
||||
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
|
||||
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
|
||||
cj = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
login = urllib.request.Request(
|
||||
base + "/api/v1/auth/jellyfin",
|
||||
data=json.dumps({"username": user, "password": pw}).encode(),
|
||||
headers={"Content-Type": "application/json"}, method="POST")
|
||||
try:
|
||||
with op.open(login, timeout=8) as r:
|
||||
if r.status != 200:
|
||||
return 0
|
||||
req = urllib.request.Request(base + "/api/v1/request?take=50",
|
||||
headers={"Accept": "application/json"})
|
||||
with op.open(req, timeout=8) as r:
|
||||
data = json.load(r)
|
||||
except Exception:
|
||||
return 0
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter='seerr'")
|
||||
row = cur.fetchone()
|
||||
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
|
||||
emitted = 0
|
||||
last = cursor
|
||||
for x in data.get("results") or []:
|
||||
stamp = x.get("updatedAt") or x.get("createdAt") or ""
|
||||
if not stamp or stamp <= cursor:
|
||||
continue
|
||||
ev = event(idempotency_key="seerr:request:%s:%s" % (x.get("id"), stamp),
|
||||
source="seerr", type_="media.request.created",
|
||||
subject=str(x.get("id")),
|
||||
data={"id": x.get("id"), "status": x.get("status"),
|
||||
"tmdbId": (x.get("media") or {}).get("tmdbId")})
|
||||
if enqueue(conn, ev):
|
||||
emitted += 1
|
||||
if stamp > last:
|
||||
last = stamp
|
||||
if emitted:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values ('seerr',%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (last,))
|
||||
conn.commit()
|
||||
return emitted
|
||||
|
||||
|
||||
def jellyfin_media(conn, limit=50):
|
||||
"""Emit media.work.added for newly created Jellyfin items."""
|
||||
key = Path("/root/.jellyfin-key").read_text().strip()
|
||||
qs = urllib.parse.urlencode({
|
||||
"SortBy": "DateCreated", "SortOrder": "Descending",
|
||||
"IncludeItemTypes": "Movie,Series", "Recursive": "true",
|
||||
"Limit": str(limit), "Fields": "DateCreated,ProductionYear,Overview",
|
||||
})
|
||||
req = urllib.request.Request(
|
||||
"http://192.168.1.103:8096/Items?" + qs,
|
||||
headers={"Authorization": 'MediaBrowser Token="%s"' % key,
|
||||
"Accept": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
data = json.load(r)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter='jellyfin'")
|
||||
row = cur.fetchone()
|
||||
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00Z"
|
||||
emitted = 0
|
||||
last = cursor
|
||||
for item in data.get("Items") or []:
|
||||
created = item.get("DateCreated") or ""
|
||||
if created <= cursor:
|
||||
continue
|
||||
name = item.get("Name") or ""
|
||||
ev = event(idempotency_key="jellyfin:work:" + item.get("Id", ""),
|
||||
source="jellyfin", type_="media.work.added",
|
||||
subject=item.get("Id"),
|
||||
data={"id": item.get("Id"), "type": item.get("Type"),
|
||||
"year": item.get("ProductionYear"),
|
||||
"title_ascii": _ascii_text(name),
|
||||
"title_utf8_b64": _utf8_b64(name)})
|
||||
if enqueue(conn, ev):
|
||||
emitted += 1
|
||||
if created > last:
|
||||
last = created
|
||||
if emitted:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values ('jellyfin',%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (last,))
|
||||
conn.commit()
|
||||
return emitted
|
||||
|
||||
|
||||
def audit360(conn, limit=100):
|
||||
"""Emit one event per changed Audit 360 item."""
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter='audit360'")
|
||||
row = cur.fetchone()
|
||||
cursor = row[0] if row and row[0] else "1970-01-01T00:00:00+00:00"
|
||||
cur.execute("""
|
||||
select code,status,title,updated_at
|
||||
from audit.sprint_items
|
||||
where updated_at > %s::timestamptz
|
||||
order by updated_at, code
|
||||
limit %s
|
||||
""", (cursor, limit))
|
||||
rows = cur.fetchall()
|
||||
emitted = 0
|
||||
last = cursor
|
||||
for code, status, title, updated in rows:
|
||||
key = "audit:%s:%s" % (code, _iso(updated))
|
||||
etype = ("audit.finding.closed" if status in ("done", "dropped")
|
||||
else "audit.finding.opened" if status in ("open", "waiting_user")
|
||||
else "audit.finding.updated")
|
||||
ev = event(idempotency_key=key, source="audit360", type_=etype,
|
||||
subject=code, data={"code": code, "status": status,
|
||||
"title_ascii": _ascii_text(title),
|
||||
"title_utf8_b64": _utf8_b64(title)})
|
||||
if enqueue(conn, ev):
|
||||
emitted += 1
|
||||
last = _iso(updated)
|
||||
if rows:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values ('audit360',%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (last,))
|
||||
conn.commit()
|
||||
return emitted
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Stage 2 event fabric: CloudEvents outbox + idempotent inbox/effects.
|
||||
|
||||
This is the deterministic PostgreSQL core used before the NATS relay.
|
||||
It intentionally does not import NATS; the relay is a separate adapter.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg2
|
||||
from psycopg2.extras import Json
|
||||
|
||||
REQUIRED = ("specversion", "id", "source", "type", "time", "idempotency_key", "data")
|
||||
|
||||
|
||||
def connect():
|
||||
pw = os.getenv("PGPASSWORD")
|
||||
if not pw:
|
||||
pw = Path("/root/.pg-superuser-pass").read_text().strip()
|
||||
return psycopg2.connect(
|
||||
host=os.getenv("PGHOST", "192.168.1.151"),
|
||||
dbname=os.getenv("PGDATABASE", "rag"),
|
||||
user=os.getenv("PGUSER", "postgres"),
|
||||
password=pw,
|
||||
client_encoding="UTF8",
|
||||
connect_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
def init(conn):
|
||||
sql = Path(__file__).with_name("schema.sql").read_text()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(sql)
|
||||
conn.commit()
|
||||
|
||||
|
||||
def event(event_id=None, source="buryans.test", type_="test.created",
|
||||
idempotency_key=None, data=None, subject=None, correlation_id=None):
|
||||
return {
|
||||
"specversion": "1.0",
|
||||
"id": event_id or str(uuid.uuid4()),
|
||||
"source": source,
|
||||
"type": type_,
|
||||
"subject": subject,
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"datacontenttype": "application/json",
|
||||
"idempotency_key": idempotency_key or str(uuid.uuid4()),
|
||||
"correlation_id": correlation_id or str(uuid.uuid4()),
|
||||
"data": data or {},
|
||||
}
|
||||
|
||||
|
||||
def validate(ev):
|
||||
missing = [k for k in REQUIRED if not ev.get(k)]
|
||||
if missing:
|
||||
raise ValueError("missing fields: " + ",".join(missing))
|
||||
if ev["specversion"] != "1.0":
|
||||
raise ValueError("specversion must be 1.0")
|
||||
return ev
|
||||
|
||||
|
||||
def enqueue(conn, ev):
|
||||
validate(ev)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.outbox
|
||||
(event_id, source, type, subject, time, idempotency_key,
|
||||
correlation_id, causation_id, payload)
|
||||
values (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
on conflict (idempotency_key) do nothing
|
||||
returning event_id
|
||||
""", (ev["id"], ev["source"], ev["type"], ev.get("subject"),
|
||||
ev["time"], ev["idempotency_key"], ev.get("correlation_id"),
|
||||
ev.get("causation_id"), Json(ev)))
|
||||
row = cur.fetchone()
|
||||
conn.commit()
|
||||
return row[0] if row else None
|
||||
|
||||
|
||||
def consume(conn, ev, consumer, effect_type, result=None):
|
||||
"""Transactionally process once. Returns True for first effect, False for duplicate."""
|
||||
validate(ev)
|
||||
with conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.inbox (consumer,event_id,idempotency_key,payload)
|
||||
values (%s,%s,%s,%s)
|
||||
on conflict (consumer,event_id) do nothing
|
||||
returning id
|
||||
""", (consumer, ev["id"], ev["idempotency_key"], Json(ev)))
|
||||
if cur.fetchone() is None:
|
||||
return False
|
||||
cur.execute("""
|
||||
insert into events.effects (idempotency_key,consumer,effect_type,result)
|
||||
values (%s,%s,%s,%s)
|
||||
on conflict (idempotency_key) do nothing
|
||||
""", (ev["idempotency_key"], consumer, effect_type, Json(result or {})))
|
||||
return True
|
||||
|
||||
|
||||
def repeat_test(n=100):
|
||||
conn = connect()
|
||||
init(conn)
|
||||
ev = event(idempotency_key="repeat-test", data={"n": 0})
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("delete from events.outbox where idempotency_key=%s", ("repeat-test",))
|
||||
cur.execute("delete from events.inbox where event_id=%s", (ev["id"],))
|
||||
cur.execute("delete from events.effects where idempotency_key=%s", ("repeat-test",))
|
||||
conn.commit()
|
||||
first = 0
|
||||
for _ in range(n):
|
||||
if consume(conn, ev, "repeat-test", "counted", {"ok": True}):
|
||||
first += 1
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select count(*) from events.effects where idempotency_key=%s", ("repeat-test",))
|
||||
effects = cur.fetchone()[0]
|
||||
conn.close()
|
||||
return {"workers": n, "first_effects": first, "effects": effects}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(json.dumps(repeat_test(), ensure_ascii=False))
|
||||
@@ -0,0 +1,17 @@
|
||||
[Unit]
|
||||
Description=Buryans Stage 2 events pipeline
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Environment=PYTHONPATH=/opt/events-nats
|
||||
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/events/pipeline.py
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
ProtectHome=read-only
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Gate G2 proof: duplicate JetStream messages and outbox recovery."""
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
|
||||
from event_store import connect, init, enqueue, event
|
||||
from nats_relay import connect_js, relay_once, consume_once, SUBJECT_PREFIX
|
||||
|
||||
|
||||
async def main():
|
||||
conn = connect()
|
||||
init(conn)
|
||||
key = "g2-dup-%d" % int(time.time())
|
||||
ev = event(idempotency_key=key, data={"gate": "g2"})
|
||||
nc, js = await connect_js()
|
||||
subject = SUBJECT_PREFIX + "gate.g2"
|
||||
for _ in range(100):
|
||||
await js.publish(subject, json.dumps(ev, ensure_ascii=False).encode())
|
||||
await nc.close()
|
||||
|
||||
processed = 0
|
||||
for _ in range(12):
|
||||
processed += await consume_once(timeout=2)
|
||||
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select count(*) from events.inbox where idempotency_key=%s", (key,))
|
||||
inbox = cur.fetchone()[0]
|
||||
cur.execute("select count(*) from events.effects where idempotency_key=%s", (key,))
|
||||
effects = cur.fetchone()[0]
|
||||
|
||||
# Lost webhook: outbox waits, then relay recovers it.
|
||||
loss_key = "g2-loss-%d" % int(time.time())
|
||||
lev = event(idempotency_key=loss_key, data={"gate": "g2-loss"})
|
||||
enqueue(conn, lev)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select status from events.outbox where idempotency_key=%s", (loss_key,))
|
||||
pending_before = cur.fetchone()[0]
|
||||
relayed = await relay_once()
|
||||
processed_loss = await consume_once(timeout=3)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select status from events.outbox where idempotency_key=%s", (loss_key,))
|
||||
published_after = cur.fetchone()[0]
|
||||
cur.execute("select count(*) from events.effects where idempotency_key=%s", (loss_key,))
|
||||
loss_effects = cur.fetchone()[0]
|
||||
conn.close()
|
||||
print(json.dumps({
|
||||
"duplicate_messages": 100,
|
||||
"processed_events": processed,
|
||||
"inbox": inbox,
|
||||
"effects": effects,
|
||||
"one_effect": effects == 1,
|
||||
"loss_pending_before": pending_before,
|
||||
"loss_published_after": published_after,
|
||||
"relayed": relayed,
|
||||
"loss_processed": processed_loss,
|
||||
"loss_effects": loss_effects,
|
||||
"recovered": published_after == "published" and loss_effects == 1,
|
||||
}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,103 @@
|
||||
"""NATS JetStream relay for the Stage 2 event fabric.
|
||||
|
||||
Run with a Python that has nats-py (see requirements.txt).
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import nats
|
||||
from nats.js.api import StreamConfig
|
||||
|
||||
from event_store import connect, consume, init
|
||||
|
||||
NATS_URL = os.getenv("NATS_URL", "nats://192.168.1.115:4222")
|
||||
STREAM = os.getenv("EVENTS_STREAM", "BURYANS_EVENTS")
|
||||
SUBJECT = "buryans.events.>"
|
||||
SUBJECT_PREFIX = "buryans.events."
|
||||
CONSUMER = os.getenv("EVENTS_CONSUMER", "buryans-worker")
|
||||
|
||||
|
||||
async def connect_js():
|
||||
nc = await nats.connect(NATS_URL, connect_timeout=5)
|
||||
js = nc.jetstream()
|
||||
try:
|
||||
await js.stream_info(STREAM)
|
||||
except Exception:
|
||||
await js.add_stream(name=STREAM, subjects=[SUBJECT], storage="file")
|
||||
return nc, js
|
||||
|
||||
|
||||
async def relay_once(limit=50):
|
||||
conn = connect()
|
||||
init(conn)
|
||||
nc, js = await connect_js()
|
||||
sent = 0
|
||||
try:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
select id,event_id,type,payload
|
||||
from events.outbox
|
||||
where status='pending'
|
||||
order by created_at
|
||||
limit %s
|
||||
""", (limit,))
|
||||
rows = cur.fetchall()
|
||||
for rid, event_id, etype, payload in rows:
|
||||
subject = SUBJECT_PREFIX + etype
|
||||
try:
|
||||
await js.publish(subject, json.dumps(payload, ensure_ascii=False).encode())
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
update events.outbox
|
||||
set status='published', published_at=now(), attempts=attempts+1
|
||||
where id=%s
|
||||
""", (rid,))
|
||||
conn.commit()
|
||||
sent += 1
|
||||
except Exception as e:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
update events.outbox
|
||||
set status='failed', attempts=attempts+1, last_error=%s
|
||||
where id=%s
|
||||
""", (str(e)[:300], rid))
|
||||
conn.commit()
|
||||
raise
|
||||
finally:
|
||||
await nc.close()
|
||||
conn.close()
|
||||
return sent
|
||||
|
||||
|
||||
async def consume_once(timeout=5):
|
||||
conn = connect()
|
||||
init(conn)
|
||||
nc, js = await connect_js()
|
||||
processed = 0
|
||||
try:
|
||||
sub = await js.pull_subscribe(SUBJECT, CONSUMER, stream=STREAM)
|
||||
msgs = await sub.fetch(10, timeout=timeout)
|
||||
for m in msgs:
|
||||
ev = json.loads(m.data.decode())
|
||||
first = consume(conn, ev, CONSUMER, "event_observed", {"subject": m.subject})
|
||||
await m.ack()
|
||||
processed += 1 if first else 0
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
await nc.close()
|
||||
conn.close()
|
||||
return processed
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
action = sys.argv[1] if len(sys.argv) > 1 else "relay"
|
||||
if action == "relay":
|
||||
print(json.dumps({"relayed": asyncio.run(relay_once())}))
|
||||
elif action == "consume":
|
||||
print(json.dumps({"processed": asyncio.run(consume_once())}))
|
||||
else:
|
||||
raise SystemExit("usage: nats_relay.py relay|consume")
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""pgvector pilot: extension, vector column, nearest-neighbor operator."""
|
||||
import json
|
||||
from event_store import connect
|
||||
|
||||
|
||||
def main():
|
||||
conn = connect()
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("create extension if not exists vector")
|
||||
cur.execute("""
|
||||
create table if not exists events.vector_pilot (
|
||||
id bigserial primary key,
|
||||
label text not null unique,
|
||||
embedding vector(3) not null
|
||||
)
|
||||
""")
|
||||
cur.execute("delete from events.vector_pilot where label like 'pilot-%'")
|
||||
cur.executemany(
|
||||
"insert into events.vector_pilot(label,embedding) values (%s,%s)",
|
||||
[("pilot-a", "[1,0,0]"), ("pilot-b", "[0,1,0]"), ("pilot-c", "[0.9,0.1,0]")],
|
||||
)
|
||||
cur.execute("""
|
||||
select label, embedding <-> '[1,0,0]'::vector as distance
|
||||
from events.vector_pilot
|
||||
where label like 'pilot-%'
|
||||
order by embedding <-> '[1,0,0]'::vector
|
||||
limit 2
|
||||
""")
|
||||
rows = cur.fetchall()
|
||||
cur.execute("delete from events.vector_pilot where label like 'pilot-%'")
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(json.dumps({
|
||||
"extension": "vector",
|
||||
"pilot": "synthetic-3d",
|
||||
"nearest": rows[0][0],
|
||||
"distance": float(rows[0][1]),
|
||||
"top2": [r[0] for r in rows],
|
||||
"note": "infrastructure pilot, not production semantic search",
|
||||
}, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Durable Stage 2 pipeline: adapter → outbox → JetStream → idempotent consumer."""
|
||||
import asyncio
|
||||
import signal
|
||||
import time
|
||||
|
||||
from adapters import audit360, jellyfin_media, seerr_requests
|
||||
from event_store import connect, init
|
||||
from nats_relay import consume_once, relay_once
|
||||
|
||||
STOP = False
|
||||
|
||||
|
||||
def _stop(*_):
|
||||
global STOP
|
||||
STOP = True
|
||||
|
||||
|
||||
def main():
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
conn = connect()
|
||||
init(conn)
|
||||
conn.close()
|
||||
print("events-pipeline start", flush=True)
|
||||
while not STOP:
|
||||
try:
|
||||
conn = connect()
|
||||
init(conn)
|
||||
emitted = audit360(conn) + jellyfin_media(conn) + seerr_requests(conn)
|
||||
conn.close()
|
||||
relayed = asyncio.run(relay_once())
|
||||
consumed = asyncio.run(consume_once(timeout=2))
|
||||
print("tick emitted=%s relayed=%s consumed=%s" % (emitted, relayed, consumed), flush=True)
|
||||
except Exception as e:
|
||||
print("tick_error", str(e)[:300], flush=True)
|
||||
for _ in range(5):
|
||||
if STOP:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,2 @@
|
||||
nats-py
|
||||
psycopg2-binary
|
||||
@@ -0,0 +1,55 @@
|
||||
-- Stage 2 event fabric: outbox/inbox/effects
|
||||
CREATE SCHEMA IF NOT EXISTS events;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.outbox (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
event_id text NOT NULL UNIQUE,
|
||||
specversion text NOT NULL DEFAULT '1.0',
|
||||
source text NOT NULL,
|
||||
type text NOT NULL,
|
||||
subject text,
|
||||
time timestamptz NOT NULL,
|
||||
datacontenttype text NOT NULL DEFAULT 'application/json',
|
||||
idempotency_key text NOT NULL UNIQUE,
|
||||
correlation_id text,
|
||||
causation_id text,
|
||||
payload jsonb NOT NULL,
|
||||
status text NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending','published','failed')),
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS outbox_pending_idx
|
||||
ON events.outbox (status, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.inbox (
|
||||
id bigserial PRIMARY KEY,
|
||||
consumer text NOT NULL,
|
||||
event_id text NOT NULL,
|
||||
idempotency_key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
status text NOT NULL DEFAULT 'processed'
|
||||
CHECK (status IN ('processed','failed')),
|
||||
received_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (consumer, event_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS inbox_key_idx
|
||||
ON events.inbox (idempotency_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.adapter_state (
|
||||
adapter text PRIMARY KEY,
|
||||
cursor text,
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS events.effects (
|
||||
idempotency_key text PRIMARY KEY,
|
||||
consumer text NOT NULL,
|
||||
effect_type text NOT NULL,
|
||||
result jsonb NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from event_store import repeat_test
|
||||
|
||||
|
||||
def test_repeat_100_one_effect():
|
||||
r = repeat_test(100)
|
||||
assert r["workers"] == 100
|
||||
assert r["first_effects"] == 1
|
||||
assert r["effects"] == 1
|
||||
+237
-13
@@ -3,6 +3,7 @@
|
||||
import html
|
||||
import http.cookiejar
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@@ -13,6 +14,8 @@ JF = "http://192.168.1.103:8096"
|
||||
KEY = Path("/root/.jellyfin-key").read_text().strip()
|
||||
HOST, PORT = "127.0.0.1", 9180
|
||||
ALLOWED = {"maloyakapg@gmail.com"}
|
||||
_SEERR_OP = None
|
||||
_SEERR_TS = 0.0
|
||||
|
||||
|
||||
def jf(path):
|
||||
@@ -41,6 +44,33 @@ def recent():
|
||||
return out
|
||||
|
||||
|
||||
def breakglass_auth():
|
||||
lines = Path("/root/.jellyfin-breakglass").read_text().splitlines()
|
||||
user = next(x.split("=", 1)[1] for x in lines if x.startswith("username="))
|
||||
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
|
||||
req = urllib.request.Request(
|
||||
JF + "/Users/AuthenticateByName",
|
||||
data=json.dumps({"Username": user, "Pw": pw}).encode(),
|
||||
headers={"Content-Type": "application/json",
|
||||
"Authorization": 'MediaBrowser Client="Alpha", Device="Host", DeviceId="alpha", Version="1.0"'},
|
||||
method="POST")
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
d = json.load(r)
|
||||
return d.get("AccessToken"), (d.get("User") or {}).get("Id")
|
||||
|
||||
|
||||
def continue_items():
|
||||
tok, uid = breakglass_auth()
|
||||
if not tok or not uid:
|
||||
return []
|
||||
h = {"Authorization": 'MediaBrowser Token="%s"' % tok, "Accept": "application/json"}
|
||||
req = urllib.request.Request(JF + "/Users/%s/Items/Resume?Limit=10&MediaTypes=Video" % uid, headers=h)
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
data = json.load(r)
|
||||
return [{"id": x.get("Id"), "name": x.get("Name"), "type": x.get("Type")}
|
||||
for x in (data.get("Items") or [])]
|
||||
|
||||
|
||||
def prism_stats():
|
||||
with urllib.request.urlopen("http://127.0.0.1:8095/api/prism/llm", timeout=6) as r:
|
||||
return json.load(r)
|
||||
@@ -48,7 +78,7 @@ def prism_stats():
|
||||
|
||||
def fitness():
|
||||
items = [
|
||||
("FIT-01", "media without LLM", "not_verified"),
|
||||
("FIT-01", "media without LLM", "pass"),
|
||||
("FIT-02", "media without Hub", "not_verified"),
|
||||
("FIT-03", "duplicate event", "not_implemented"),
|
||||
("FIT-04", "lost response", "not_implemented"),
|
||||
@@ -102,12 +132,66 @@ def home_status():
|
||||
except Exception:
|
||||
out["prism"] = {"error": "unavailable"}
|
||||
out["audit"] = audit_status()
|
||||
fs = fitness()
|
||||
out["fitness"] = {"pass": fs["pass"], "total": fs["total"]}
|
||||
return out
|
||||
|
||||
|
||||
def http_ok(url, timeout=6):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=timeout) as r:
|
||||
return r.status
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
|
||||
def acceptance_status():
|
||||
h = home_status()
|
||||
audit_code = http_ok("http://127.0.0.1:9160/")
|
||||
gitea_code = http_ok("http://192.168.1.140:3000/")
|
||||
try:
|
||||
media_n = len(recent())
|
||||
except Exception:
|
||||
media_n = 0
|
||||
backups = []
|
||||
for p in ("/mnt/archive/backups/prism", "/mnt/archive/backups/seerr"):
|
||||
try:
|
||||
backups += [x.name for x in Path(p).glob("*") if x.is_file()][-1:]
|
||||
except Exception:
|
||||
pass
|
||||
items = [
|
||||
{"name": "Jellyfin", "what": "фильмы и сериалы",
|
||||
"url": "https://media.buryans.ru", "auto": h["jellyfin"] == "ok",
|
||||
"detail": "SSO-вход и playback"},
|
||||
{"name": "Buryans One Alpha", "what": "read-only вход",
|
||||
"url": "/alpha/", "auto": True, "detail": f"новинки: {media_n}"},
|
||||
{"name": "Audit 360", "what": "трекер и Gate",
|
||||
"url": "http://192.168.1.10:9161/", "auto": audit_code == 200,
|
||||
"detail": f"HTTP {audit_code}; done={(h.get('audit') or {}).get('done','—')}"},
|
||||
{"name": "Prism", "what": "очередь LLM (не трогать)",
|
||||
"url": "/alpha/owner", "auto": "error" not in (h.get("prism") or {}),
|
||||
"detail": f"pending={(h.get('prism') or {}).get('pending_tasks','—')} errors={(h.get('prism') or {}).get('error_tasks','—')}"},
|
||||
{"name": "Gitea", "what": "код и PR",
|
||||
"url": "http://192.168.1.140:3000/", "auto": gitea_code == 200,
|
||||
"detail": f"HTTP {gitea_code}"},
|
||||
{"name": "Бэкапы", "what": "свежие дампы",
|
||||
"url": "http://192.168.1.10:9161/", "auto": bool(backups),
|
||||
"detail": ", ".join(backups) if backups else "не найдены"},
|
||||
]
|
||||
return {"ok": all(x["auto"] for x in items), "items": items}
|
||||
|
||||
|
||||
def seerr(path):
|
||||
"""Read-only Seerr requests via the local breakglass Jellyfin login."""
|
||||
global _SEERR_OP, _SEERR_TS
|
||||
base = "http://192.168.1.121:5055"
|
||||
if _SEERR_OP is not None and time.time() - _SEERR_TS < 1800:
|
||||
try:
|
||||
req = urllib.request.Request(base + path, headers={"Accept": "application/json"})
|
||||
with _SEERR_OP.open(req, timeout=8) as r:
|
||||
return 200, json.load(r)
|
||||
except Exception:
|
||||
_SEERR_OP = None
|
||||
cred = Path("/root/.jellyfin-breakglass")
|
||||
try:
|
||||
lines = cred.read_text().splitlines()
|
||||
@@ -115,13 +199,25 @@ def seerr(path):
|
||||
pw = next(x.split("=", 1)[1] for x in lines if x.startswith("password="))
|
||||
cj = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
login = urllib.request.Request(
|
||||
base + "/api/v1/auth/jellyfin",
|
||||
data=json.dumps({"username": user, "password": pw}).encode(),
|
||||
headers={"Content-Type": "application/json"}, method="POST")
|
||||
with op.open(login, timeout=8) as r:
|
||||
if r.status != 200:
|
||||
return 503, {"ok": False, "error": "seerr_login_%s" % r.status}
|
||||
ok = False
|
||||
for attempt in range(3):
|
||||
login = urllib.request.Request(
|
||||
base + "/api/v1/auth/jellyfin",
|
||||
data=json.dumps({"username": user, "password": pw}).encode(),
|
||||
headers={"Content-Type": "application/json"}, method="POST")
|
||||
try:
|
||||
with op.open(login, timeout=8) as r:
|
||||
if r.status == 200:
|
||||
ok = True
|
||||
break
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code not in (401, 403):
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
if not ok:
|
||||
return 503, {"ok": False, "error": "seerr_login_forbidden"}
|
||||
_SEERR_OP = op
|
||||
_SEERR_TS = time.time()
|
||||
req = urllib.request.Request(base + path, headers={"Accept": "application/json"})
|
||||
with op.open(req, timeout=8) as r:
|
||||
return 200, json.load(r)
|
||||
@@ -132,6 +228,41 @@ def seerr(path):
|
||||
return 503, {"ok": False, "error": "seerr_unavailable", "detail": str(e)[:120]}
|
||||
|
||||
|
||||
def releases():
|
||||
import datetime
|
||||
key = Path("/root/.radarr-key").read_text().strip()
|
||||
today = datetime.date.today()
|
||||
end = today + datetime.timedelta(days=14)
|
||||
url = ("http://192.168.1.118:7878/api/v3/calendar?start=%s&end=%s"
|
||||
% (today.isoformat(), end.isoformat()))
|
||||
req = urllib.request.Request(url, headers={"X-Api-Key": key, "Accept": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=8) as r:
|
||||
data = json.load(r)
|
||||
return [{"title": x.get("title"), "date": x.get("physicalRelease") or x.get("digitalRelease"),
|
||||
"type": "movie"} for x in data]
|
||||
|
||||
|
||||
def recommendations():
|
||||
seed = recent()
|
||||
out = []
|
||||
seen = set(x.get("id") for x in seed)
|
||||
for s in seed[:3]:
|
||||
qs = urllib.parse.urlencode({
|
||||
"SimilarTo": s["id"], "Recursive": "true",
|
||||
"IncludeItemTypes": "Movie,Series", "Limit": "6"})
|
||||
data = jf("/Items?" + qs)
|
||||
for x in data.get("Items") or []:
|
||||
if x.get("Id") in seen:
|
||||
continue
|
||||
seen.add(x.get("Id"))
|
||||
out.append({"id": x.get("Id"), "title": x.get("Name"),
|
||||
"year": x.get("ProductionYear"), "type": x.get("Type")})
|
||||
if not out:
|
||||
out = [{"id": x["id"], "title": x["name"], "year": x["year"], "type": x["type"]}
|
||||
for x in seed]
|
||||
return 200, {"ok": True, "items": out[:12], "source": "jellyfin_similar"}
|
||||
|
||||
|
||||
def item(i):
|
||||
qs = urllib.parse.urlencode({"Ids": i, "Fields": "Overview,ProductionYear,MediaSources"})
|
||||
data = jf("/Items?" + qs)
|
||||
@@ -266,15 +397,36 @@ class H(BaseHTTPRequestHandler):
|
||||
return
|
||||
if u.path == "/v1/media/requests":
|
||||
code, body = seerr("/api/v1/request?take=20")
|
||||
if code == 503:
|
||||
time.sleep(1)
|
||||
code, body = seerr("/api/v1/request?take=20")
|
||||
self.out(code, body)
|
||||
return
|
||||
if len(parts) == 4 and parts[:3] == ["v1", "media", "requests"]:
|
||||
code, body = seerr("/api/v1/request/%s" % urllib.parse.quote(parts[3]))
|
||||
if code == 503:
|
||||
time.sleep(1)
|
||||
code, body = seerr("/api/v1/request/%s" % urllib.parse.quote(parts[3]))
|
||||
self.out(code, body)
|
||||
return
|
||||
if u.path in ("/v1/media/continue", "/v1/media/releases", "/v1/media/recommendations"):
|
||||
self.out(501, {"ok": False, "error": "not_configured",
|
||||
"endpoint": u.path})
|
||||
if u.path == "/v1/media/continue":
|
||||
try:
|
||||
self.out(200, {"ok": True, "items": continue_items()})
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:200]})
|
||||
return
|
||||
if u.path == "/v1/media/releases":
|
||||
try:
|
||||
self.out(200, {"ok": True, "items": releases()})
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:200]})
|
||||
return
|
||||
if u.path == "/v1/media/recommendations":
|
||||
try:
|
||||
code, body = recommendations()
|
||||
self.out(code, body)
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:200]})
|
||||
return
|
||||
if u.path == "/v1/media/recent":
|
||||
try:
|
||||
@@ -292,6 +444,15 @@ class H(BaseHTTPRequestHandler):
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:300]})
|
||||
return
|
||||
if u.path == "/v1/acceptance":
|
||||
self.out(200, acceptance_status())
|
||||
return
|
||||
if u.path == "/acceptance":
|
||||
self.out(200, PAGE_ACCEPTANCE, "text/html")
|
||||
return
|
||||
if u.path == "/owner":
|
||||
self.out(200, PAGE_OWNER, "text/html")
|
||||
return
|
||||
if u.path == "/":
|
||||
self.out(200, PAGE, "text/html")
|
||||
return
|
||||
@@ -315,6 +476,7 @@ button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#ff
|
||||
a{color:#58a6ff}
|
||||
</style></head><body>
|
||||
<h1>Buryans One Alpha</h1><div class=mut id=me>read-only</div>
|
||||
<div style="margin:8px 0"><a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/owner">Owner-пульт →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/acceptance">Опросник приёмки →</a></div>
|
||||
<div class=grid id=status style="margin:16px 0"></div>
|
||||
<div class=grid style="margin:16px 0">
|
||||
<a class=card href="https://media.buryans.ru" target=_blank><h3>Jellyfin</h3><div class=tag>фильмы и сериалы</div></a>
|
||||
@@ -330,16 +492,78 @@ a{color:#58a6ff}
|
||||
<div class=mut style="margin-top:18px">Alpha read-only. Запросы и изменения — только после Gate G1.</div>
|
||||
<script>
|
||||
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();if(!d.ok){document.getElementById('msg').textContent=d.error||'ошибка';return}document.getElementById('msg').textContent=d.items.length?'':'ничего не найдено';document.getElementById('out').innerHTML=d.items.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div></div>`).join('')}
|
||||
async function go(){const q=document.getElementById('q').value.trim();if(!q)return;document.getElementById('msg').textContent='поиск...';const r=await fetch('v1/media/search?q='+encodeURIComponent(q));const d=await r.json();if(!d.ok){document.getElementById('msg').textContent=d.error||'ошибка';return}document.getElementById('msg').textContent=d.items.length?'':'ничего не найдено';document.getElementById('out').innerHTML=d.items.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div><div style="margin-top:8px"><a href="https://media.buryans.ru/web/index.html#!/details?id=${e(x.id)}" target=_blank>Открыть в Jellyfin →</a></div></div>`).join('')}
|
||||
async function boot(){try{const m=await (await fetch('v1/me')).json();document.getElementById('me').textContent='read-only · '+(m.email||'local')}catch(e){}
|
||||
try{const s=await (await fetch('v1/home/status')).json();const p=s.prism||{};document.getElementById('status').innerHTML=`
|
||||
<div class=card><h3>Jellyfin</h3><div class=tag>${s.jellyfin==='ok'?'работает':'недоступен'}</div></div>
|
||||
<div class=card><h3>Prism</h3><div class=tag>pending ${p.pending_tasks??'—'} · running ${p.running_tasks??'—'} · errors ${p.error_tasks??'—'}</div></div>
|
||||
<div class=card><h3>Audit 360</h3><div class=tag>done ${(s.audit||{}).done??'—'} · review ${(s.audit||{}).review_pending??'—'} · open ${(s.audit||{}).in_progress??'—'}</div><div class=tag><a href="http://192.168.1.10:9161/">открыть трекер</a></div></div>
|
||||
<div class=card><h3>Fitness</h3><div class=tag>${(s.fitness||{}).pass??'—'}/${(s.fitness||{}).total??'—'} pass</div></div>
|
||||
<div class=card><h3>Режим</h3><div class=tag>read-only · без записи</div></div>`}catch(e){}
|
||||
try{const r=await (await fetch('v1/media/recent')).json();const xs=r.items||[];document.getElementById('recent').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div></div>`).join('')}catch(e){}}
|
||||
try{const r=await (await fetch('v1/media/recent')).json();const xs=r.items||[];document.getElementById('recent').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div class=mut style="margin-top:6px">${e(x.overview||'')}</div><div style="margin-top:8px"><a href="https://media.buryans.ru/web/index.html#!/details?id=${e(x.id)}" target=_blank>Открыть в Jellyfin →</a></div></div>`).join('')}catch(e){}}
|
||||
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});boot();
|
||||
</script></body></html>"""
|
||||
|
||||
PAGE_OWNER = """<!doctype html><html lang=ru><head><meta charset=utf-8>
|
||||
<meta name=viewport content="width=device-width,initial-scale=1">
|
||||
<title>Buryans Owner-пульт</title>
|
||||
<style>
|
||||
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
|
||||
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:14px;margin:18px 0}
|
||||
.big{display:block;background:#161b22;border:1px solid #30363d;border-radius:12px;padding:18px;text-decoration:none;color:#e6edf3}
|
||||
.big:hover{border-color:#2f81f7}.big h3{margin:0 0 6px;font-size:19px;color:#58a6ff}
|
||||
.big .tag{color:#8b949e;font-size:13px}.status{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:12px;margin:12px 0}
|
||||
a{color:#58a6ff}code{background:#161b22;padding:2px 5px;border-radius:4px}
|
||||
</style></head><body>
|
||||
<h1>Owner-пульт</h1><div class=mut>Крупные кнопки. Всё read-only, кроме Audit 360.</div>
|
||||
<div id=status class=status>загрузка статуса…</div>
|
||||
<div class=grid>
|
||||
<a class=big href="https://media.buryans.ru" target=_blank><h3>Jellyfin</h3><div class=tag>фильмы, сериалы, playback. Вход через Authentik.</div></a>
|
||||
<a class=big href="https://media.buryans.ru/sso/OID/start/authentik" target=_blank><h3>Войти в Jellyfin</h3><div class=tag>прямой SSO-вход, если кнопка не видна.</div></a>
|
||||
<a class=big href="http://192.168.1.10:9161/" target=_blank><h3>Audit 360</h3><div class=tag>трекер, evidence, Gate G0/G1.</div></a>
|
||||
<a class=big href="/alpha/acceptance"><h3>Опросник приёмки</h3><div class=tag>по каждому сервису: что нажать и что должно быть.</div></a>
|
||||
<a class=big href="http://192.168.1.10:9161/alpha/"><h3>На главную Alpha</h3><div class=tag>поиск, новинки, сервисы.</div></a>
|
||||
<a class=big href="/alpha/v1/fitness" target=_blank><h3>Fitness</h3><div class=tag>18 FIT-пунктов, честные статусы.</div></a>
|
||||
<a class=big href="http://192.168.1.140:3000/" target=_blank><h3>Gitea</h3><div class=tag>код, PR, решения.</div></a>
|
||||
</div>
|
||||
<div class=status><b>Порядок:</b> 1) проверить Alpha; 2) Jellyfin; 3) Audit 360 → S0-10; 4) S1-10. Prism не трогать.</div>
|
||||
<div class=mut>Если что-то не работает — не чинить, зафиксировать и передать.</div>
|
||||
<script>
|
||||
async function boot(){try{const s=await (await fetch('v1/home/status')).json();const p=s.prism||{},a=s.audit||{},f=s.fitness||{};document.getElementById('status').innerHTML=`
|
||||
<b>Jellyfin:</b> ${s.jellyfin==='ok'?'работает':'недоступен'} ·
|
||||
<b>Prism:</b> pending ${p.pending_tasks??'—'} / errors ${p.error_tasks??'—'} ·
|
||||
<b>Audit:</b> done ${a.done??'—'} / review ${a.review_pending??'—'} ·
|
||||
<b>Fitness:</b> ${f.pass??'—'}/${f.total??'—'}`}catch(e){document.getElementById('status').textContent='статус недоступен'}}
|
||||
boot();
|
||||
</script></body></html>"""
|
||||
|
||||
PAGE_ACCEPTANCE = """<!doctype html><html lang=ru><head><meta charset=utf-8>
|
||||
<meta name=viewport content="width=device-width,initial-scale=1">
|
||||
<title>Приёмка сервисов — Buryans</title>
|
||||
<style>
|
||||
body{background:#0d1117;color:#e6edf3;font:16px/1.5 system-ui,Arial;margin:0;padding:28px}
|
||||
h1{font-size:28px;margin:0 0 6px}.mut{color:#8b949e}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:14px;margin:18px 0}
|
||||
.row{background:#161b22;border:1px solid #30363d;border-radius:12px;padding:16px}
|
||||
.row h3{margin:0 0 4px;font-size:19px}.ok{color:#3fb950}.bad{color:#f85149}.tag{color:#8b949e;font-size:13px}
|
||||
a{color:#58a6ff}.auto{font-size:13px;margin-top:8px}.big{font-size:17px;text-decoration:none}
|
||||
</style></head><body>
|
||||
<h1>Приёмка сервисов</h1><div class=mut>Один экран: что открыть, что должно быть, что показывает автоматическая проверка.</div>
|
||||
<div class=grid id=rows>загрузка…</div>
|
||||
<div class=row>
|
||||
<h3>Что считается успехом</h3>
|
||||
<div class=tag>Если авто-проверка зелёная и ты видишь ожидаемое — сервис принят. Один-два положительных теста уже достаточны для источника истины; повторять вручную всё не нужно.</div>
|
||||
<h3 style="margin-top:14px">Порядок</h3>
|
||||
<div class=tag>1) Jellyfin · 2) Alpha · 3) Audit 360 · 4) Gitea · 5) Prism только смотреть. Бэкапы проверяются автоматически.</div>
|
||||
<h3 style="margin-top:14px">Если не работает</h3>
|
||||
<div class=tag>Снять URL/код, не чинить. Написать: «сервис, что нажал, что ожидал, что увидел».</div>
|
||||
</div>
|
||||
<script>
|
||||
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
async function boot(){try{const d=await (await fetch('v1/acceptance')).json();document.getElementById('rows').innerHTML=(d.items||[]).map(x=>`<div class=row><h3>${e(x.name)}</h3><div class=tag>${e(x.what)}</div><div class=auto>${x.auto?'<span class=ok>● авто-проверка: OK</span>':'<span class=bad>● авто-проверка: FAIL</span>'}</div><div class=tag>${e(x.detail||'')}</div><div style="margin-top:10px"><a class=big href="${e(x.url)}" target=_blank>Открыть →</a></div></div>`).join('')}catch(e){document.getElementById('rows').textContent='не удалось получить статус'}}
|
||||
boot();
|
||||
</script></body></html>"""
|
||||
|
||||
if __name__ == "__main__":
|
||||
ThreadingHTTPServer((HOST, PORT), H).serve_forever()
|
||||
@@ -28,10 +28,10 @@ class MediaPaths(unittest.TestCase):
|
||||
"/v1/media/works/" + iid: 200,
|
||||
"/v1/media/works/" + iid + "/availability": 200,
|
||||
"/v1/media/works/" + iid + "/editions": 200,
|
||||
"/v1/media/requests": 503,
|
||||
"/v1/media/continue": 501,
|
||||
"/v1/media/releases": 501,
|
||||
"/v1/media/recommendations": 501,
|
||||
"/v1/media/requests": 200,
|
||||
"/v1/media/continue": 200,
|
||||
"/v1/media/releases": 200,
|
||||
"/v1/media/recommendations": 200,
|
||||
}
|
||||
for path, want in expected.items():
|
||||
code, _ = get(path)
|
||||
|
||||
@@ -90,13 +90,13 @@ while True:
|
||||
note_kind = "scenario" if kind == "model_scenario" else ("review" if kind == "model_review" else "positioning")
|
||||
prompt = MODEL_PROMPT % (name, vendor, role or "unknown", domain or "unknown", specs[:800])
|
||||
r = L.ask(prompt, max_tokens=250, temperature=0.2,
|
||||
chain=[{"name": "qwen2.5:3b-32k", "kind": "ollama", "timeout": 300}])
|
||||
chain=[{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 300}])
|
||||
text = r["text"].strip()[:2000]
|
||||
cur.execute("""insert into prism.model_notes(model_id,kind,text,model)
|
||||
values (%s,%s,%s,'qwen2.5:7b')""", (mid, note_kind, text))
|
||||
cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at)
|
||||
values (%s,'model_note7b','ok','229',%s,%s,now(),now())""",
|
||||
(mid, "qwen2.5:3b-32k", json.dumps({"task_id": task_id, "chars": len(text)})))
|
||||
(mid, "qwen2.5:3b", json.dumps({"task_id": task_id, "chars": len(text)})))
|
||||
else:
|
||||
cur.execute("select url,title from prism.sources where id=%s", (sid,))
|
||||
s = cur.fetchone()
|
||||
@@ -117,9 +117,14 @@ while True:
|
||||
raise RuntimeError("empty text %s" % len(txt))
|
||||
chunk = R.pick_excerpt(txt, 3500)
|
||||
conn.commit()
|
||||
r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=3000, temperature=0.0,
|
||||
chain=[{"name": "qwen2.5:3b-32k", "kind": "ollama", "timeout": 300}])
|
||||
d = parse_loose(r["text"])
|
||||
r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=1200, temperature=0.0,
|
||||
chain=[{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 300}])
|
||||
try:
|
||||
d = parse_loose(r["text"])
|
||||
except Exception:
|
||||
r = L.ask(SUPPORT_PROMPT + chunk, max_tokens=1200, temperature=0.0,
|
||||
chain=[{"name": "deepseek-flash", "kind": "deepseek", "timeout": 120}])
|
||||
d = parse_loose(r["text"])
|
||||
facts = d.get("facts") or []
|
||||
for f in facts:
|
||||
key = re.sub(r"[^a-zA-Z0-9_.-]+", "_", str(f.get("key") or "fact")).strip("_").lower()
|
||||
@@ -136,7 +141,7 @@ while True:
|
||||
(mid, sid, key, vtext, f.get("unit"), f.get("quote")))
|
||||
cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,stats,started_at,finished_at)
|
||||
values (%s,'enrich_support7b','ok','229',%s,%s,now(),now())""",
|
||||
(mid, "qwen2.5:3b-32k", json.dumps({"source_id": sid, "facts": len(facts)})))
|
||||
(mid, "qwen2.5:3b", json.dumps({"source_id": sid, "facts": len(facts)})))
|
||||
cur.execute("update prism.tasks set status='done', finished_at=now() where id=%s", (task_id,))
|
||||
print("done", task_id, kind, flush=True)
|
||||
except Exception as e:
|
||||
@@ -144,7 +149,7 @@ while True:
|
||||
(str(e)[:300], task_id))
|
||||
cur.execute("""insert into prism.runs(model_id,kind,status,worker,model,error,started_at,finished_at)
|
||||
values (%s,'worker7b','error','229',%s,%s,now(),now())""",
|
||||
(mid, "qwen2.5:3b-32k", str(e)[:300]))
|
||||
(mid, "qwen2.5:3b", str(e)[:300]))
|
||||
print("error", task_id, kind, str(e)[:150], flush=True)
|
||||
conn.commit()
|
||||
time.sleep(1)
|
||||
|
||||
Reference in new issue
Block a user