Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3045cedf62 | ||
|
|
7735ddff28 | ||
|
|
649386f0b8 | ||
|
|
457f95d3b1 | ||
|
|
ae5ab904fd | ||
|
|
506ae58410 | ||
|
|
7ef5b02698 | ||
|
|
0f41d71a0b | ||
|
|
7099d402a0 | ||
|
|
b7b5c36c55 | ||
|
|
54905cccab | ||
|
|
64f0f05200 | ||
|
|
84834e40af | ||
|
|
c9eddc0eda | ||
|
|
eb070b7be5 | ||
|
|
13d14b13a7 | ||
|
|
060bb8f276 | ||
|
|
ff34b72f9a | ||
|
|
8273956058 | ||
|
|
a7b1a90e9c | ||
|
|
2fbe23476c | ||
|
|
8b78cd9a61 | ||
|
|
e6a29a5cda | ||
|
|
3636be5ddd | ||
|
|
2be898d584 | ||
|
|
304db34ac2 | ||
|
|
6ab94962ac | ||
|
|
8940671aa3 | ||
|
|
f57684399c | ||
|
|
64e3c95667 | ||
|
|
5ff027fc42 | ||
|
|
e6fc2cb3aa | ||
|
|
2f0017a663 | ||
|
|
46761c0142 | ||
|
|
a221d71971 | ||
|
|
50c31091b2 | ||
|
|
9340263940 | ||
|
|
d6ee44f0e7 | ||
|
|
fca442c5da | ||
|
|
2a1393def5 | ||
|
|
8657ce5e55 |
No files matched your search
@@ -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
|
||||
@@ -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.
|
||||
@@ -3,13 +3,28 @@
|
||||
Для Романа и второго 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 и живой статус.
|
||||
Крупные кнопки: Jellyfin, SSO, Audit 360, Fitness, Gitea, опросник приёмки.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
version: 1
|
||||
source: "stage5 model registry v0"
|
||||
models:
|
||||
- id: deepseek-chat
|
||||
provider: deepseek
|
||||
role: primary-reasoning
|
||||
endpoint: "https://api.deepseek.com"
|
||||
health: external
|
||||
note: "ключ только на сервере"
|
||||
- id: qwen2.5:3b
|
||||
provider: ollama-pc
|
||||
role: local-fast
|
||||
endpoint: "http://192.168.1.194:11434"
|
||||
health: ollama
|
||||
note: "ПК, модель может быть выгружена"
|
||||
- id: qwen2.5:3b
|
||||
provider: ollama-host
|
||||
role: local-fallback
|
||||
endpoint: "http://192.168.1.10:11434"
|
||||
health: ollama
|
||||
note: "host fallback"
|
||||
@@ -51,7 +51,7 @@ services:
|
||||
tier: 0
|
||||
ct: 108
|
||||
owner: roman
|
||||
endpoint: "http://127.0.0.1:9120/status"
|
||||
endpoint: "http://127.0.0.1:9120/health"
|
||||
health: "http"
|
||||
backup: "config"
|
||||
restore: "config"
|
||||
@@ -89,3 +89,10 @@ services:
|
||||
endpoint: "http://192.168.1.108:5680/healthz"
|
||||
health: "http"
|
||||
note: "port 5680 -> container 5678"
|
||||
- id: hub-tools
|
||||
tier: 1
|
||||
ct: 10
|
||||
owner: roman
|
||||
endpoint: "http://127.0.0.1:9137/health"
|
||||
health: "http"
|
||||
note: "Tool Gateway; agents must use this for tools"
|
||||
@@ -0,0 +1,27 @@
|
||||
version: 1
|
||||
policy: "agents may use only gateway-listed tools; direct production access is forbidden"
|
||||
tools:
|
||||
- name: catalog.read
|
||||
gateway: http://127.0.0.1:9120/catalog
|
||||
mode: read
|
||||
approval: false
|
||||
- name: status.read
|
||||
gateway: http://127.0.0.1:9120/status
|
||||
mode: read
|
||||
approval: false
|
||||
- name: notify.send
|
||||
gateway: http://127.0.0.1:9120/notify
|
||||
mode: write
|
||||
approval: true
|
||||
- name: media.read
|
||||
gateway: http://127.0.0.1:9180/v1/media
|
||||
mode: read
|
||||
approval: false
|
||||
- name: events.read
|
||||
gateway: http://127.0.0.1:9180/v1/events
|
||||
mode: read
|
||||
approval: false
|
||||
- name: audit.write
|
||||
gateway: http://127.0.0.1:9160/api/sprint/status
|
||||
mode: write
|
||||
approval: true
|
||||
@@ -38,10 +38,15 @@
|
||||
| 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 | open | | architect | pending | 0 | |
|
||||
| S2-05 | S2 | Adapters + ownership matrix | open | | architect | pending | 0 | |
|
||||
| S2-06 | S2 | pgvector pilot | open | | architect | pending | 0 | |
|
||||
| S2-07 | S2 | Gate G2 proof | open | YES | architect | pending | 0 | G2 |
|
||||
| S2-04 | S2 | NATS JetStream relay | done | | architect | enqueue1 relayed1 processed1; inbox/effects 1 | 1 | |
|
||||
| S2-05 | S2 | Adapters + ownership matrix | done | | architect | pipeline active; jellyfin 7 events; ownership.yaml | 3 | |
|
||||
| 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 |
|
||||
| S3-01 | S3 | Аудит RU/direct-play | done | | architect | /v1/media/coverage | 0 | |
|
||||
| S3-02 | S3 | RU-дорожки/субтитры | blocked | | architect | Bazarr status200; login TLS error; no RU | 5 | |
|
||||
| S3-03 | S3 | Direct-play 7/7 | done | | architect | coverage total6 direct6 | 2 | |
|
||||
| S3-04 | S3 | Запрос из Alpha/Telegram/Matrix | done | | architect | /alpha/request; !request; request/check | 5 | |
|
||||
| S3-05 | S3 | Gate G3 | open | YES | architect | pending | 0 | G3 |
|
||||
| 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 |
|
||||
@@ -54,14 +59,16 @@
|
||||
- M / done: 7
|
||||
- S0 / done: 10
|
||||
- S1 / done: 10
|
||||
- S2 / done: 3
|
||||
- S2 / open: 4
|
||||
- S2 / done: 7
|
||||
- S3 / blocked: 1
|
||||
- S3 / done: 3
|
||||
- S3 / open: 1
|
||||
- U / done: 2
|
||||
- U / dropped: 3
|
||||
|
||||
## Пользовательская очередь
|
||||
|
||||
- **S2-07** — Gate G2 proof:
|
||||
- **S3-05** — Gate G3:
|
||||
- **U-02** — Seerr vs Jellyseerr decision: Выбрать после evidence
|
||||
- **U-03** — RAM/GPU/disk data: Прислать/подтвердить параметры
|
||||
- **U-04** — Approve Stage1 write actions: Разрешить только после Gate G1
|
||||
@@ -17,10 +17,10 @@ Gate G2: повтор события 100 раз = один эффект; пот
|
||||
| S2-01 | CloudEvents envelope v1 | done |
|
||||
| S2-02 | Outbox schema + enqueue | done |
|
||||
| S2-03 | Inbox + effects idempotency | done |
|
||||
| S2-04 | NATS JetStream relay | open |
|
||||
| S2-05 | Adapters + ownership matrix | open |
|
||||
| S2-06 | pgvector pilot | open |
|
||||
| S2-07 | Gate G2 proof | open |
|
||||
| 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 |
|
||||
|
||||
## Проверка
|
||||
|
||||
@@ -35,6 +35,77 @@ python3 ops/events/event_store.py
|
||||
{"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:
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# Stage 3 — Media Product
|
||||
|
||||
Статус: начат 2026-11-27.
|
||||
Gate G3: семья делает запрос → смотрит с RU-озвучкой; 0 дублей.
|
||||
|
||||
## Факт на старте
|
||||
|
||||
Jellyfin:
|
||||
|
||||
```text
|
||||
всего медиа 6
|
||||
RU audio 0
|
||||
RU субтитры 0
|
||||
direct-play 6
|
||||
```
|
||||
|
||||
Direct-play исправлен: сериал считается по эпизодам, BoxSet исключён из playable-медиа.
|
||||
|
||||
Это честный gap, не «всё хорошо».
|
||||
|
||||
Проверка диска: `.srt/.ass/.vtt` нет; имён `rus/russian` нет.
|
||||
Значит RU-контента нет и вне индекса Jellyfin.
|
||||
|
||||
## Bazarr: RU-источник
|
||||
|
||||
- RU-профиль `Русский + English` существует;
|
||||
- Dune/Interstellar получили профиль 1;
|
||||
- subf2m исправлен User-Agent;
|
||||
- throttle-файл сброшен;
|
||||
- но RU-файл всё равно не скачался.
|
||||
|
||||
Бэкап конфига:
|
||||
|
||||
```text
|
||||
/opt/bazarr/config/config/config.yaml.bak-subf2m-20261127
|
||||
/opt/bazarr/config/config/config.yaml.bak-opensubtitles-20261127
|
||||
```
|
||||
|
||||
## OpenSubtitles API
|
||||
|
||||
Ключ лежит только на хосте:
|
||||
|
||||
```text
|
||||
/root/.opensubtitles-key (600)
|
||||
```
|
||||
|
||||
Проверено:
|
||||
|
||||
- поиск RU работает: 23 варианта для Dune;
|
||||
- прямой download link отдаёт файл очень медленно и обрывается;
|
||||
- Bazarr `opensubtitlescom` настроен с username/password + API key;
|
||||
- из контейнера Bazarr login падает по TLS (`SSLEOFError`), subf2m таймаутит.
|
||||
|
||||
Поэтому RU-файл пока не установлен. Обрезанный `.srt` не используется.
|
||||
|
||||
Секреты:
|
||||
|
||||
```text
|
||||
/root/.opensubtitles-key
|
||||
/root/.opensubtitles-user
|
||||
/root/.opensubtitles-pass
|
||||
```
|
||||
|
||||
## Задачи
|
||||
|
||||
| Код | Задача | Статус |
|
||||
|---|---|---|
|
||||
| S3-01 | Аудит RU/direct-play | done (0/6 RU, 6/6 direct) |
|
||||
| S3-02 | RU-дорожки/субтитры | blocked: Bazarr RU профиль есть, subf2m не отдал файл |
|
||||
| S3-03 | Direct-play 6/6 | done |
|
||||
| S3-04 | Запрос из Alpha/Matrix | done (Telegram исключён по решению) |
|
||||
| S3-05 | Gate G3 | open |
|
||||
|
||||
## Проверка
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/acceptance
|
||||
```
|
||||
|
||||
Карточка «RU-озвучка» сейчас **FAIL** — специально, пока нет RU-дорожек.
|
||||
|
||||
```text
|
||||
GET /v1/media/coverage
|
||||
```
|
||||
|
||||
Запрос из Alpha:
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/request
|
||||
```
|
||||
|
||||
Alpha ищет по Jellyfin; кнопка открывает Seerr. Alpha не пишет в Seerr/медиатеку.
|
||||
|
||||
Matrix:
|
||||
|
||||
```text
|
||||
!request Дюна
|
||||
```
|
||||
|
||||
Бот даёт ссылку на `https://requests.buryans.ru`, заявку создаёт семья в Seerr.
|
||||
Telegram-бота в текущем контуре нет.
|
||||
|
||||
Проверка дублей:
|
||||
|
||||
```text
|
||||
GET /v1/media/request/check?q=Дюна
|
||||
```
|
||||
|
||||
Alpha показывает предупреждение, если заявка уже есть в Seerr.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Stage 4 — Mission Control & SDK
|
||||
|
||||
Статус: **Gate G4 закрыт** 2026-11-27.
|
||||
|
||||
## Сделано
|
||||
|
||||
- Mission Control v0: `/alpha/mission`; 11/11 сервисов up.
|
||||
- Adapter SDK: `ops/events/adapter_plugins/base.py`; `poll(conn)`.
|
||||
- Auto-discovery: `registry.py`; новый файл = новый адаптер.
|
||||
- 4 адаптера: audit360, jellyfin, seerr, gitea-health.
|
||||
- Contract tests: 3/3 OK.
|
||||
- Preview: `preview_adapters.py`.
|
||||
- Gate G4: Gitea-health добавлен файлом, ядро pipeline не менялось.
|
||||
|
||||
## Доказательства
|
||||
|
||||
```text
|
||||
preview_adapters.py
|
||||
audit360 poll=callable
|
||||
gitea-health poll=callable
|
||||
jellyfin poll=callable
|
||||
seerr poll=callable
|
||||
total=4
|
||||
|
||||
unittest: Ran 3 tests ... OK
|
||||
pipeline: tick emitted={'audit360': 0, 'gitea-health': 0, 'jellyfin': 0, 'seerr': 0}
|
||||
gitea first tick: emitted 1, relayed 1, consumed 1
|
||||
```
|
||||
|
||||
## Задачи
|
||||
|
||||
| Код | Задача | Статус |
|
||||
|---|---|---|
|
||||
| S4-01 | Mission Control v0 | done |
|
||||
| S4-02 | Extension SDK | done |
|
||||
| S4-03 | 3+ adapters | done (4) |
|
||||
| S4-04 | Preview + contract tests | done |
|
||||
| S4-05 | Gate G4 | done |
|
||||
|
||||
## Ограничения
|
||||
|
||||
- Mission Control внутри Alpha, не отдельный Nexus.
|
||||
- Публичный Matrix/Element (`matrix.buryans.ru`, VPS `193.233.210.184`) недоступен; боты работают через локальный Synapse.
|
||||
@@ -0,0 +1,70 @@
|
||||
# Stage 5 — AI Factory & Agents
|
||||
|
||||
Статус: начат 2026-11-27.
|
||||
Gate G5: агент не имеет production-доступа вне Tool Gateway.
|
||||
|
||||
## Сделано
|
||||
|
||||
Model Registry v0:
|
||||
|
||||
```text
|
||||
http://192.168.1.10:9161/alpha/models
|
||||
GET /v1/models
|
||||
```
|
||||
|
||||
- реестр моделей/провайдеров;
|
||||
- external/Ollama health;
|
||||
- PC-Ollama offline показывается как down;
|
||||
- без выдачи агентам production-доступа.
|
||||
|
||||
## Задачи
|
||||
|
||||
| Код | Задача | Статус |
|
||||
|---|---|---|
|
||||
| S5-01 | Model Registry v0 | done |
|
||||
| S5-02 | GPU/model leases | in_progress: model lease runtime, нет GPU-планировщика |
|
||||
| S5-03 | Evals / golden set | open |
|
||||
| S5-04 | Memory | open |
|
||||
| S5-05 | Night Shift | open |
|
||||
| S5-06 | Tool Gateway / agent approvals | in_progress: runtime есть, агенты не переключены |
|
||||
| S5-07 | Gate G5 | open |
|
||||
|
||||
## Tool Gateway runtime
|
||||
|
||||
```text
|
||||
hub-tools.service → 127.0.0.1:9137
|
||||
GET /health
|
||||
GET /v1/tools
|
||||
GET /v1/call?tool=...
|
||||
POST /v1/call (write + X-Approval: approved)
|
||||
```
|
||||
|
||||
Проверено:
|
||||
|
||||
```text
|
||||
gateway_call=200
|
||||
tools=6
|
||||
```
|
||||
|
||||
## Model leases
|
||||
|
||||
```text
|
||||
GET /v1/models
|
||||
POST /v1/leases
|
||||
POST /v1/leases/release
|
||||
GET /v1/leases
|
||||
```
|
||||
|
||||
Проверено:
|
||||
|
||||
```text
|
||||
deepseek-chat → 201 lease
|
||||
qwen2.5:3b (offline) → 409 model unavailable
|
||||
```
|
||||
|
||||
## Ограничение
|
||||
|
||||
- GPU-планировщик и реальное распределение GPU ещё не реализованы.
|
||||
- Evals, memory не реализованы.
|
||||
- Агенты ещё не переключены на Tool Gateway; Gate G5 не закрыт.
|
||||
- Model Registry read-only, не выдаёт доступ к моделям.
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Buryans Tool Gateway
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/python3 /root/buryan-infra/ops/ai/tool_gateway_server.py
|
||||
Restart=on-failure
|
||||
RestartSec=3
|
||||
NoNewPrivileges=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,15 @@
|
||||
import sys, unittest
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from tool_gateway import load_tools
|
||||
|
||||
class GatewayTests(unittest.TestCase):
|
||||
def test_tools_have_gateway(self):
|
||||
tools = load_tools()
|
||||
self.assertGreaterEqual(len(tools), 3)
|
||||
for t in tools:
|
||||
self.assertTrue(t["gateway"].startswith("http"))
|
||||
self.assertFalse(t.get("direct_prod", False))
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,14 @@
|
||||
import sys, unittest
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from tool_gateway_server import tools
|
||||
|
||||
class GatewayServerTests(unittest.TestCase):
|
||||
def test_policy_loads(self):
|
||||
t = tools()
|
||||
self.assertIn("catalog.read", t)
|
||||
self.assertEqual(t["catalog.read"]["mode"], "read")
|
||||
self.assertTrue(t["notify.send"]["approval"])
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Read-only Tool Gateway policy registry (Stage 5)."""
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/tool_gateway.yaml")
|
||||
|
||||
|
||||
def load_tools():
|
||||
data = yaml.safe_load(PATH.read_text())
|
||||
tools = data.get("tools") or []
|
||||
for t in tools:
|
||||
if not t.get("gateway"):
|
||||
raise ValueError("tool without gateway: %s" % t.get("name"))
|
||||
if t.get("direct_prod"):
|
||||
raise ValueError("direct production access forbidden: %s" % t.get("name"))
|
||||
if t.get("mode") not in ("read", "write"):
|
||||
raise ValueError("bad mode: %s" % t.get("name"))
|
||||
return tools
|
||||
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stage 5 Tool Gateway: allowlisted proxy for agents.
|
||||
|
||||
Listens on 127.0.0.1:9137. It never exposes production directly:
|
||||
agents call a named tool, the gateway validates policy and forwards.
|
||||
Write tools require X-Approval: approved.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
|
||||
import yaml
|
||||
|
||||
POLICY = "/root/buryan-infra/docs/architecture/REGISTRY/tool_gateway.yaml"
|
||||
MODELS = "/root/buryan-infra/docs/architecture/REGISTRY/models.yaml"
|
||||
LEASES = "/var/lib/hub-tools/leases.json"
|
||||
LOG = "/var/log/hub-tools/gateway.jsonl"
|
||||
HOST, PORT = "127.0.0.1", 9137
|
||||
|
||||
|
||||
def tools():
|
||||
return {t["name"]: t for t in (yaml.safe_load(open(POLICY).read()).get("tools") or [])}
|
||||
|
||||
|
||||
def models():
|
||||
return {m["id"]: m for m in (yaml.safe_load(open(MODELS).read()).get("models") or [])}
|
||||
|
||||
|
||||
def model_up(model_id):
|
||||
m = models().get(model_id)
|
||||
if not m:
|
||||
return None
|
||||
if m.get("health") == "external":
|
||||
return True
|
||||
try:
|
||||
with urllib.request.urlopen(m["endpoint"].rstrip("/") + "/api/tags", timeout=3) as r:
|
||||
return r.status == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def read_leases():
|
||||
try:
|
||||
return json.loads(open(LEASES).read())
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def write_leases(data):
|
||||
os.makedirs(os.path.dirname(LEASES), exist_ok=True)
|
||||
tmp = LEASES + ".tmp"
|
||||
open(tmp, "w").write(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
os.replace(tmp, LEASES)
|
||||
|
||||
|
||||
def lease_create(model, agent, ttl_sec=900):
|
||||
if model not in models():
|
||||
return None, "unknown model"
|
||||
if model_up(model) is False:
|
||||
return None, "model unavailable"
|
||||
now = time.time()
|
||||
leases = {k: v for k, v in read_leases().items() if v.get("expires", 0) > now}
|
||||
lid = uuid.uuid4().hex[:12]
|
||||
leases[lid] = {"id": lid, "model": model, "agent": agent or "unknown",
|
||||
"created": now, "expires": now + max(60, min(int(ttl_sec), 3600)),
|
||||
"state": "active"}
|
||||
write_leases(leases)
|
||||
return leases[lid], None
|
||||
|
||||
|
||||
def lease_release(lid):
|
||||
leases = read_leases()
|
||||
if lid not in leases:
|
||||
return False
|
||||
leases[lid]["state"] = "released"
|
||||
write_leases(leases)
|
||||
return True
|
||||
|
||||
|
||||
def log(entry):
|
||||
os.makedirs(os.path.dirname(LOG), exist_ok=True)
|
||||
with open(LOG, "a") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def _json(self, code, obj):
|
||||
b = json.dumps(obj, ensure_ascii=False).encode()
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(b)))
|
||||
self.end_headers()
|
||||
self.wfile.write(b)
|
||||
|
||||
def do_GET(self):
|
||||
u = urlparse(self.path)
|
||||
if u.path == "/health":
|
||||
return self._json(200, {"ok": True, "service": "hub-tools", "tools": len(tools())})
|
||||
if u.path == "/v1/tools":
|
||||
return self._json(200, {"tools": list(tools().values())})
|
||||
if u.path == "/v1/models":
|
||||
return self._json(200, {"models": list(models().values())})
|
||||
if u.path == "/v1/leases":
|
||||
now = time.time()
|
||||
return self._json(200, {"leases": [v for v in read_leases().values() if v.get("expires", 0) > now]})
|
||||
if u.path != "/v1/call":
|
||||
return self._json(404, {"error": "not found"})
|
||||
name = (parse_qs(u.query).get("tool") or [""])[0]
|
||||
t = tools().get(name)
|
||||
if not t:
|
||||
return self._json(404, {"error": "unknown tool"})
|
||||
if t["mode"] != "read":
|
||||
return self._json(403, {"error": "write tool requires POST approval"})
|
||||
try:
|
||||
req = urllib.request.Request(t["gateway"], method="GET")
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
body = r.read(200000).decode("utf-8", "replace")
|
||||
log({"tool": name, "mode": "read", "code": 200})
|
||||
return self._json(200, {"tool": name, "upstream": t["gateway"], "body": body})
|
||||
except Exception as e:
|
||||
log({"tool": name, "mode": "read", "error": str(e)[:200]})
|
||||
return self._json(502, {"error": str(e)[:200]})
|
||||
|
||||
def do_POST(self):
|
||||
u = urlparse(self.path)
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
try:
|
||||
data = json.loads(self.rfile.read(n) or b"{}")
|
||||
except Exception:
|
||||
return self._json(400, {"error": "bad json"})
|
||||
if u.path == "/v1/leases":
|
||||
lease, err = lease_create(data.get("model"), data.get("agent"), data.get("ttl_sec", 900))
|
||||
if err:
|
||||
return self._json(409 if err == "model unavailable" else 404, {"error": err})
|
||||
log({"lease": lease["id"], "model": lease["model"], "agent": lease["agent"]})
|
||||
return self._json(201, lease)
|
||||
if u.path == "/v1/leases/release":
|
||||
ok = lease_release(data.get("id"))
|
||||
return self._json(200 if ok else 404, {"ok": ok})
|
||||
if u.path != "/v1/call":
|
||||
return self._json(404, {"error": "not found"})
|
||||
name = data.get("tool")
|
||||
t = tools().get(name)
|
||||
if not t:
|
||||
return self._json(404, {"error": "unknown tool"})
|
||||
if t["mode"] != "write":
|
||||
return self._json(200, {"error": "read tool; use GET"})
|
||||
if t.get("approval") and self.headers.get("X-Approval") != "approved":
|
||||
log({"tool": name, "mode": "write", "code": 403})
|
||||
return self._json(403, {"error": "approval required"})
|
||||
try:
|
||||
payload = json.dumps(data.get("body") or {}, ensure_ascii=False).encode()
|
||||
req = urllib.request.Request(t["gateway"], data=payload, method="POST",
|
||||
headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
body = r.read(200000).decode("utf-8", "replace")
|
||||
log({"tool": name, "mode": "write", "code": 200})
|
||||
return self._json(200, {"tool": name, "body": body})
|
||||
except Exception as e:
|
||||
log({"tool": name, "mode": "write", "error": str(e)[:200]})
|
||||
return self._json(502, {"error": str(e)[:200]})
|
||||
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ThreadingHTTPServer((HOST, PORT), H).serve_forever()
|
||||
@@ -23,6 +23,7 @@
|
||||
## Остальные
|
||||
|
||||
* **Медиа** — статистика, новинки, поиск, очередь, заявки, место, пробелы.
|
||||
- `!request <название>` — даёт ссылку на заявку в `https://requests.buryans.ru`; бот сам заявку не создаёт.
|
||||
* **Фото** — статистика, альбомы, место.
|
||||
* **Книги** — статистика, новинки, поиск.
|
||||
* **Дом** — статистика, состояние.
|
||||
|
||||
+10
-1
@@ -656,6 +656,7 @@ class MediaBot(Bot):
|
||||
self.cmd("now", "кто что смотрит прямо сейчас")(lambda a: self._now(jf))
|
||||
self.cmd("queue", "очередь загрузок в Sonarr и Radarr")(lambda a: self._queue())
|
||||
self.cmd("requests", "последние заявки в Seerr")(lambda a: self._requests(seerr))
|
||||
self.cmd("request", "ссылка на заявку в Seerr: `!request Дюна`")(lambda a: self._request_link(a))
|
||||
self.cmd("disk", "место на дисках медиасервисов")(lambda a: self._disk())
|
||||
self.cmd("wanted", "сколько ещё не найдено")(lambda a: self._wanted())
|
||||
self.cmd("paths", "где лежат файлы и куда их класть")(lambda a: self._paths())
|
||||
@@ -764,7 +765,7 @@ class MediaBot(Bot):
|
||||
if err:
|
||||
return f"Seerr не ответил: {err}"
|
||||
if not reqs:
|
||||
return "Заявок пока нет. Заказать можно на https://ombi.buryans.ru"
|
||||
return "Заявок пока нет. Заказать можно на https://requests.buryans.ru"
|
||||
lines = ["**Последние заявки**", ""]
|
||||
for r in reqs:
|
||||
media = r.get("media", {}) or {}
|
||||
@@ -774,6 +775,14 @@ class MediaBot(Bot):
|
||||
lines.append(f"• {title} — {status} (просил {who})")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _request_link(self, query):
|
||||
q = (query or "").strip()
|
||||
if not q:
|
||||
return "Использование: `!request Дюна`"
|
||||
return (f"**Заявка в Seerr**\n{q}\n"
|
||||
"Открой https://requests.buryans.ru, найди этот тайтл и отправь заявку.\n"
|
||||
"Alpha и бот не создают запрос сами — это защита от дублей.")
|
||||
|
||||
def _disk(self):
|
||||
lines = ["**Диски**", ""]
|
||||
for svc in (SONARR, RADARR):
|
||||
|
||||
@@ -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.
|
||||
Whitespace-only changes.
@@ -0,0 +1,9 @@
|
||||
from adapters import audit360
|
||||
from .base import Adapter
|
||||
|
||||
|
||||
class Audit360Adapter(Adapter):
|
||||
name = "audit360"
|
||||
|
||||
def poll(self, conn):
|
||||
return audit360(conn)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Adapter contract for the Stage 4 event fabric."""
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class Adapter(ABC):
|
||||
name = "adapter"
|
||||
|
||||
@abstractmethod
|
||||
def poll(self, conn) -> int:
|
||||
"""Emit zero or more events; return number of new events."""
|
||||
@@ -0,0 +1,38 @@
|
||||
import urllib.request
|
||||
|
||||
from event_store import enqueue, event
|
||||
from .base import Adapter
|
||||
|
||||
URL = "http://192.168.1.140:3000/api/v1/version"
|
||||
|
||||
|
||||
class GiteaHealthAdapter(Adapter):
|
||||
name = "gitea-health"
|
||||
|
||||
def poll(self, conn):
|
||||
up = False
|
||||
try:
|
||||
with urllib.request.urlopen(URL, timeout=4) as r:
|
||||
up = r.status == 200
|
||||
except Exception:
|
||||
up = False
|
||||
state = "up" if up else "down"
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("select cursor from events.adapter_state where adapter=%s", (self.name,))
|
||||
row = cur.fetchone()
|
||||
previous = row[0] if row and row[0] else None
|
||||
if previous == state:
|
||||
return 0
|
||||
ev = event(idempotency_key="gitea:health:%s:%d" % (state, int(__import__("time").time())),
|
||||
source="gitea", type_="system.service.%s" % state,
|
||||
subject="gitea", data={"service": "gitea", "state": state})
|
||||
enqueue(conn, ev)
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("""
|
||||
insert into events.adapter_state(adapter,cursor,updated_at)
|
||||
values (%s,%s,now())
|
||||
on conflict (adapter) do update
|
||||
set cursor=excluded.cursor, updated_at=now()
|
||||
""", (self.name, state))
|
||||
conn.commit()
|
||||
return 1
|
||||
@@ -0,0 +1,9 @@
|
||||
from adapters import jellyfin_media
|
||||
from .base import Adapter
|
||||
|
||||
|
||||
class JellyfinAdapter(Adapter):
|
||||
name = "jellyfin"
|
||||
|
||||
def poll(self, conn):
|
||||
return jellyfin_media(conn)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Discover and run event adapters without editing the pipeline core."""
|
||||
import importlib
|
||||
import pkgutil
|
||||
from pathlib import Path
|
||||
|
||||
from .base import Adapter
|
||||
|
||||
|
||||
def load_adapters():
|
||||
adapters = []
|
||||
pkg_dir = Path(__file__).resolve().parent
|
||||
for mod in sorted(pkgutil.iter_modules([str(pkg_dir)])):
|
||||
if mod.name in ("base", "registry") or mod.name.startswith("_"):
|
||||
continue
|
||||
m = importlib.import_module("adapter_plugins." + mod.name)
|
||||
for obj in vars(m).values():
|
||||
if isinstance(obj, type) and issubclass(obj, Adapter) and obj is not Adapter:
|
||||
adapters.append(obj())
|
||||
return adapters
|
||||
|
||||
|
||||
def run_all(conn):
|
||||
out = {}
|
||||
for a in load_adapters():
|
||||
try:
|
||||
out[a.name] = a.poll(conn)
|
||||
except Exception as e:
|
||||
out[a.name] = "error:%s" % str(e)[:120]
|
||||
return out
|
||||
@@ -0,0 +1,9 @@
|
||||
from adapters import seerr_requests
|
||||
from .base import Adapter
|
||||
|
||||
|
||||
class SeerrAdapter(Adapter):
|
||||
name = "seerr"
|
||||
|
||||
def poll(self, conn):
|
||||
return seerr_requests(conn)
|
||||
@@ -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
|
||||
@@ -24,6 +24,7 @@ def connect():
|
||||
dbname=os.getenv("PGDATABASE", "rag"),
|
||||
user=os.getenv("PGUSER", "postgres"),
|
||||
password=pw,
|
||||
client_encoding="UTF8",
|
||||
connect_timeout=5,
|
||||
)
|
||||
|
||||
|
||||
@@ -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 adapter_plugins.registry import run_all
|
||||
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 = run_all(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,7 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only preview of discovered adapters and their contract."""
|
||||
from adapter_plugins.registry import load_adapters
|
||||
|
||||
for a in load_adapters():
|
||||
print(f"{a.name:16} poll=callable")
|
||||
print(f"total={len(load_adapters())}")
|
||||
@@ -0,0 +1,2 @@
|
||||
nats-py
|
||||
psycopg2-binary
|
||||
@@ -40,6 +40,12 @@ CREATE TABLE IF NOT EXISTS events.inbox (
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Contract tests for Stage 4 adapters. No network writes."""
|
||||
import unittest
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from adapter_plugins.registry import load_adapters
|
||||
|
||||
|
||||
class AdapterContractTests(unittest.TestCase):
|
||||
def test_at_least_three_adapters(self):
|
||||
names = {a.name for a in load_adapters()}
|
||||
self.assertGreaterEqual(len(names), 3)
|
||||
self.assertIn("jellyfin", names)
|
||||
self.assertIn("audit360", names)
|
||||
self.assertIn("seerr", names)
|
||||
|
||||
def test_every_adapter_has_poll(self):
|
||||
for a in load_adapters():
|
||||
self.assertTrue(callable(a.poll), a.name)
|
||||
self.assertTrue(a.name and isinstance(a.name, str), a.name)
|
||||
|
||||
def test_new_adapter_without_core_edit(self):
|
||||
# Gitea was added as a plugin file; pipeline core was not changed after registry.
|
||||
self.assertIn("gitea-health", {a.name for a in load_adapters()})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3,6 +3,7 @@
|
||||
import html
|
||||
import http.cookiejar
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
@@ -101,6 +102,48 @@ def fitness():
|
||||
"items": [{"id": i, "name": n, "status": s} for i, n, s in items]}
|
||||
|
||||
|
||||
def media_coverage():
|
||||
qs = urllib.parse.urlencode({
|
||||
"Recursive": "true", "IncludeItemTypes": "Movie,Series",
|
||||
"Fields": "MediaStreams,MediaSources", "Limit": "200"})
|
||||
data = jf("/Items?" + qs)
|
||||
items = data.get("Items") or []
|
||||
rus = {"ru", "rus", "russian", "русский"}
|
||||
rows = []
|
||||
for x in items:
|
||||
if x.get("Type") in ("BoxSet", "Folder", "CollectionFolder"):
|
||||
continue
|
||||
streams = x.get("MediaStreams") or []
|
||||
sources = x.get("MediaSources") or []
|
||||
if x.get("Type") == "Series" and not sources:
|
||||
try:
|
||||
ep = jf("/Shows/%s/Episodes?Fields=MediaStreams,MediaSources&Limit=200"
|
||||
% x.get("Id"))
|
||||
eps = ep.get("Items") or []
|
||||
streams = [s for e in eps for s in (e.get("MediaStreams") or [])]
|
||||
sources = [s for e in eps for s in (e.get("MediaSources") or [])]
|
||||
except Exception:
|
||||
pass
|
||||
audio = [s for s in streams if s.get("Type") == "Audio"]
|
||||
subs = [s for s in streams if s.get("Type") == "Subtitle" or s.get("IsTextSubtitleStream")]
|
||||
has_ru_audio = any((s.get("Language") or "").lower() in rus or
|
||||
any(w in (s.get("DisplayTitle") or "").lower() for w in ("russian", "русск"))
|
||||
for s in audio)
|
||||
has_ru_subs = any((s.get("Language") or "").lower() in rus or
|
||||
any(w in (s.get("DisplayTitle") or "").lower() for w in ("russian", "русск"))
|
||||
for s in subs)
|
||||
direct = bool(sources) and all(
|
||||
bool(s.get("SupportsDirectPlay") or s.get("SupportsDirectStream")) for s in sources)
|
||||
rows.append({"id": x.get("Id"), "name": x.get("Name"), "type": x.get("Type"),
|
||||
"ru_audio": has_ru_audio, "ru_subs": has_ru_subs, "direct_play": direct})
|
||||
return {"ok": True, "total": len(rows),
|
||||
"ru_audio": sum(1 for x in rows if x["ru_audio"]),
|
||||
"ru_subs": sum(1 for x in rows if x["ru_subs"]),
|
||||
"direct_play": sum(1 for x in rows if x["direct_play"]),
|
||||
"missing_ru_audio": sum(1 for x in rows if not x["ru_audio"]),
|
||||
"items": rows}
|
||||
|
||||
|
||||
def audit_status():
|
||||
try:
|
||||
import psycopg2
|
||||
@@ -134,9 +177,149 @@ def home_status():
|
||||
out["audit"] = audit_status()
|
||||
fs = fitness()
|
||||
out["fitness"] = {"pass": fs["pass"], "total": fs["total"]}
|
||||
try:
|
||||
c = media_coverage()
|
||||
out["coverage"] = {"total": c["total"], "ru_audio": c["ru_audio"], "ru_subs": c["ru_subs"]}
|
||||
except Exception:
|
||||
out["coverage"] = {"error": "unavailable"}
|
||||
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": "RU-озвучка", "what": "русская дорожка/субтитры",
|
||||
"url": "/alpha/", "auto": (h.get("coverage") or {}).get("ru_audio", 0) > 0,
|
||||
"detail": "RU audio %s/%s · subs %s" % (
|
||||
(h.get("coverage") or {}).get("ru_audio", "—"),
|
||||
(h.get("coverage") or {}).get("total", "—"),
|
||||
(h.get("coverage") or {}).get("ru_subs", "—"))},
|
||||
{"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}
|
||||
|
||||
|
||||
SERVICES_PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/services.yaml")
|
||||
MODELS_PATH = Path("/root/buryan-infra/docs/architecture/REGISTRY/models.yaml")
|
||||
|
||||
|
||||
def service_health(svc):
|
||||
endpoint = (svc.get("endpoint") or "").strip()
|
||||
started = time.time()
|
||||
try:
|
||||
if endpoint.startswith("http"):
|
||||
try:
|
||||
with urllib.request.urlopen(endpoint, timeout=4) as r:
|
||||
code = r.status
|
||||
except urllib.error.HTTPError as e:
|
||||
code = e.code
|
||||
up = code < 400
|
||||
return {"up": up, "code": code, "ms": int((time.time() - started) * 1000)}
|
||||
if endpoint.startswith(("tcp://", "nats://")):
|
||||
u = urllib.parse.urlsplit(endpoint)
|
||||
host, port = u.hostname, u.port or 0
|
||||
with socket.create_connection((host, port), timeout=3):
|
||||
pass
|
||||
return {"up": True, "code": None, "ms": int((time.time() - started) * 1000)}
|
||||
return {"up": None, "code": None, "ms": None, "error": "no endpoint"}
|
||||
except Exception as e:
|
||||
return {"up": False, "code": None, "ms": int((time.time() - started) * 1000),
|
||||
"error": str(e)[:120]}
|
||||
|
||||
|
||||
def mission_services():
|
||||
import yaml
|
||||
data = yaml.safe_load(SERVICES_PATH.read_text())
|
||||
rows = []
|
||||
for s in data.get("services") or []:
|
||||
h = service_health(s)
|
||||
rows.append({
|
||||
"id": s.get("id"), "tier": s.get("tier"), "owner": s.get("owner"),
|
||||
"endpoint": s.get("endpoint"), "public": s.get("public"),
|
||||
"health": s.get("health"), "up": h.get("up"), "code": h.get("code"),
|
||||
"ms": h.get("ms"), "error": h.get("error"),
|
||||
})
|
||||
return {"ok": all(x["up"] is not False for x in rows),
|
||||
"total": len(rows), "up": sum(1 for x in rows if x["up"] is True),
|
||||
"down": sum(1 for x in rows if x["up"] is False), "items": rows}
|
||||
|
||||
|
||||
def model_health(m):
|
||||
if m.get("health") == "external":
|
||||
return {"up": None, "loaded": None, "error": "external provider"}
|
||||
endpoint = (m.get("endpoint") or "").rstrip("/")
|
||||
try:
|
||||
with urllib.request.urlopen(endpoint + "/api/tags", timeout=3) as r:
|
||||
body = json.loads(r.read().decode("utf-8", "replace"))
|
||||
names = [x.get("name") for x in body.get("models") or []]
|
||||
return {"up": True, "loaded": m.get("id") in names, "models": names[:10]}
|
||||
except Exception as e:
|
||||
return {"up": False, "loaded": None, "error": str(e)[:120]}
|
||||
|
||||
|
||||
def model_registry():
|
||||
import yaml
|
||||
data = yaml.safe_load(MODELS_PATH.read_text())
|
||||
rows = []
|
||||
for m in data.get("models") or []:
|
||||
h = model_health(m)
|
||||
rows.append({**{k: m.get(k) for k in ("id", "provider", "role", "endpoint", "health", "note")}, **h})
|
||||
return {"ok": all(x.get("up") is not False for x in rows), "total": len(rows), "items": rows}
|
||||
|
||||
|
||||
def request_check(q):
|
||||
qn = (q or "").strip().lower()
|
||||
if not qn:
|
||||
return {"ok": False, "error": "query_required"}
|
||||
code, body = seerr("/api/v1/request?take=50")
|
||||
if code != 200:
|
||||
return {"ok": False, "error": "seerr_unavailable", "code": code}
|
||||
for x in body.get("results") or []:
|
||||
media = x.get("media") or {}
|
||||
title = (media.get("title") or media.get("name") or "").lower()
|
||||
if qn in title or title in qn:
|
||||
return {"ok": True, "requested": True, "id": x.get("id"),
|
||||
"title": media.get("title") or media.get("name"),
|
||||
"status": x.get("status")}
|
||||
return {"ok": True, "requested": False}
|
||||
|
||||
|
||||
def seerr(path):
|
||||
"""Read-only Seerr requests via the local breakglass Jellyfin login."""
|
||||
global _SEERR_OP, _SEERR_TS
|
||||
@@ -345,12 +528,25 @@ class H(BaseHTTPRequestHandler):
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:300]})
|
||||
return
|
||||
if u.path == "/v1/media/coverage":
|
||||
try:
|
||||
self.out(200, media_coverage())
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:300]})
|
||||
return
|
||||
if u.path == "/v1/fitness":
|
||||
self.out(200, fitness())
|
||||
return
|
||||
if u.path == "/v1/home/status":
|
||||
self.out(200, home_status())
|
||||
return
|
||||
if u.path == "/v1/media/request/check":
|
||||
q = urllib.parse.parse_qs(u.query).get("q", [""])[0]
|
||||
try:
|
||||
self.out(200, request_check(q))
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:200]})
|
||||
return
|
||||
if u.path == "/v1/media/requests":
|
||||
code, body = seerr("/api/v1/request?take=20")
|
||||
if code == 503:
|
||||
@@ -400,6 +596,33 @@ 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 == "/v1/services":
|
||||
try:
|
||||
self.out(200, mission_services())
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:300]})
|
||||
return
|
||||
if u.path == "/mission":
|
||||
self.out(200, PAGE_MISSION, "text/html")
|
||||
return
|
||||
if u.path == "/v1/models":
|
||||
try:
|
||||
self.out(200, model_registry())
|
||||
except Exception as e:
|
||||
self.out(502, {"ok": False, "error": str(e)[:300]})
|
||||
return
|
||||
if u.path == "/models":
|
||||
self.out(200, PAGE_MODELS, "text/html")
|
||||
return
|
||||
if u.path == "/request":
|
||||
self.out(200, PAGE_REQUEST, "text/html")
|
||||
return
|
||||
if u.path == "/owner":
|
||||
self.out(200, PAGE_OWNER, "text/html")
|
||||
return
|
||||
@@ -426,7 +649,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></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> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/request">Запросить фильм →</a> <a class="card" style="display:inline-block;padding:10px 14px" href="/alpha/mission">Mission Control →</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>
|
||||
@@ -449,6 +672,7 @@ async function boot(){try{const m=await (await fetch('v1/me')).json();document.g
|
||||
<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>RU-озвучка</h3><div class=tag>${(s.coverage||{}).ru_audio??'—'}/${(s.coverage||{}).total??'—'} · субтитры ${(s.coverage||{}).ru_subs??'—'}</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 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();
|
||||
@@ -472,6 +696,9 @@ a{color:#58a6ff}code{background:#161b22;padding:2px 5px;border-radius:4px}
|
||||
<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="/alpha/request"><h3>Запросить фильм</h3><div class=tag>поиск по Jellyfin и кнопка запроса в Seerr.</div></a>
|
||||
<a class=big href="/alpha/mission"><h3>Mission Control</h3><div class=tag>карта сервисов, health, owners, ссылки.</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>
|
||||
@@ -487,5 +714,86 @@ async function boot(){try{const s=await (await fetch('v1/home/status')).json();c
|
||||
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>"""
|
||||
|
||||
PAGE_REQUEST = """<!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}
|
||||
input{width:min(600px,80%);padding:12px;border-radius:8px;border:1px solid #30363d;background:#161b22;color:#e6edf3;font-size:16px}
|
||||
button{padding:12px 16px;border-radius:8px;border:0;background:#2f81f7;color:#fff;font-size:16px;cursor:pointer}
|
||||
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:12px;margin-top:18px}
|
||||
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
|
||||
.card h3{margin:0 0 4px;font-size:16px}.tag{color:#8b949e;font-size:13px}
|
||||
a{color:#58a6ff}.warn{background:#161b22;border:1px solid #9e6a03;border-radius:10px;padding:12px;color:#d29922}
|
||||
</style></head><body>
|
||||
<h1>Запрос фильма</h1><div class=mut>Alpha только ищет. Запрос создаётся в Seerr, не в медиатеке.</div>
|
||||
<div style="margin:16px 0"><input id=q placeholder="Название фильма или сериала..." autofocus> <button onclick="go()">Найти</button></div>
|
||||
<div id=msg class=mut></div><div id=out class=grid></div>
|
||||
<div class=warn style="margin-top:18px">Если запрос уже существует, Seerr покажет это сам. Дубли в Jellyfin не создаются.</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();const xs=d.items||[];let warn='';try{const c=await (await fetch('v1/media/request/check?q='+encodeURIComponent(q))).json();if(c.requested)warn='⚠️ Похоже, заявка уже есть: '+e(c.title||q)+' (статус '+e(c.status)+').';}catch(e){}document.getElementById('msg').textContent=xs.length?'':'ничего не найдено';if(warn)document.getElementById('msg').textContent=warn;document.getElementById('out').innerHTML=xs.map(x=>`<div class=card><h3>${e(x.name)}</h3><div class=tag>${e(x.type)} ${e(x.year||'')}</div><div style="margin-top:8px"><a href="https://requests.buryans.ru/search?query=${encodeURIComponent(x.name)}" target=_blank>Запросить в Seerr →</a></div></div>`).join('')}
|
||||
document.getElementById('q').addEventListener('keydown',e=>{if(e.key==='Enter')go()});
|
||||
</script></body></html>"""
|
||||
|
||||
PAGE_MODELS = """<!doctype html><html lang=ru><head><meta charset=utf-8>
|
||||
<meta name=viewport content="width=device-width,initial-scale=1"><title>Models — Buryans</title>
|
||||
<style>body{background:#0d1117;color:#e6edf3;font:15px/1.5 system-ui,Arial;margin:0;padding:28px}h1{margin:0 0 6px}.mut{color:#8b949e}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px;margin-top:18px}.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}.card h3{margin:0 0 4px;font-size:17px}.tag{color:#8b949e;font-size:13px}.ok{color:#3fb950}.bad{color:#f85149}.unk{color:#d29922}a{color:#58a6ff}</style></head><body>
|
||||
<h1>Model Registry</h1><div class=mut>Read-only реестр моделей и health. Агенты не получают production-доступ через эту страницу. · <a href="/alpha/mission">Mission Control →</a></div>
|
||||
<div class=mut id=summary style="margin-top:10px">загрузка…</div><div class=grid id=rows></div>
|
||||
<script>
|
||||
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
fetch('v1/models').then(r=>r.json()).then(d=>{document.getElementById('summary').textContent=`моделей ${d.total} · ok ${d.ok}`;document.getElementById('rows').innerHTML=(d.items||[]).map(x=>{const st=x.up===true?'<span class=ok>● up</span>':x.up===false?'<span class=bad>● down</span>':'<span class=unk>● external</span>';return `<div class=card><h3>${e(x.id)}</h3><div class=tag>${e(x.provider)} · ${e(x.role)}</div><div style="margin-top:6px">${st} ${x.loaded===true?'· loaded':x.loaded===false?'· not loaded':''}</div><div class=tag>${e(x.health)} · ${e(x.endpoint)}</div>${x.error?`<div class=tag>${e(x.error)}</div>`:''}</div>`}).join('')}).catch(()=>document.getElementById('summary').textContent='не удалось получить реестр моделей');
|
||||
</script></body></html>"""
|
||||
|
||||
PAGE_MISSION = """<!doctype html><html lang=ru><head><meta charset=utf-8>
|
||||
<meta name=viewport content="width=device-width,initial-scale=1">
|
||||
<title>Mission Control — Buryans</title>
|
||||
<style>
|
||||
body{background:#0d1117;color:#e6edf3;font:15px/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(270px,1fr));gap:12px;margin:18px 0}
|
||||
.card{background:#161b22;border:1px solid #30363d;border-radius:10px;padding:14px}
|
||||
.card h3{margin:0 0 4px;font-size:17px}.tag{color:#8b949e;font-size:13px}
|
||||
.ok{color:#3fb950}.bad{color:#f85149}.unk{color:#d29922}
|
||||
a{color:#58a6ff}
|
||||
</style></head><body>
|
||||
<h1>Mission Control</h1><div class=mut>Read-only карта сервисов. Health, tier, owner, endpoints. Без изменения сервисов. · <a href="/alpha/models">Models →</a></div>
|
||||
<div class=mut id=summary style="margin-top:10px">загрузка…</div>
|
||||
<div class=grid id=rows></div>
|
||||
<script>
|
||||
const e=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&','<':'<','>':'>','"':'"'}[c]));
|
||||
async function boot(){try{const d=await (await fetch('v1/services')).json();document.getElementById('summary').textContent=`сервисов ${d.total} · up ${d.up} · down ${d.down}`;const xs=(d.items||[]).slice().sort((a,b)=>(a.tier-b.tier)||String(a.id).localeCompare(b.id));document.getElementById('rows').innerHTML=xs.map(x=>{const st=x.up===true?'<span class=ok>● up</span>':x.up===false?'<span class=bad>● down</span>':'<span class=unk>● unknown</span>';const url=x.public||x.endpoint||'';return `<div class=card><h3>${e(x.id)}</h3><div class=tag>tier ${e(x.tier)} · ${e(x.owner||'—')}</div><div style="margin-top:6px">${st} ${x.code?`HTTP ${e(x.code)}`:''} ${x.ms!=null?`· ${e(x.ms)}ms`:''}</div><div class=tag>${e(x.health||'')}</div>${url?`<div style="margin-top:8px"><a href="${e(url)}" target=_blank>${e(url)}</a></div>`:''}${x.error?`<div class=tag>${e(x.error)}</div>`:''}</div>`}).join('')}catch(e){document.getElementById('summary').textContent='не удалось получить карту сервисов'}}
|
||||
boot();
|
||||
</script></body></html>"""
|
||||
|
||||
if __name__ == "__main__":
|
||||
ThreadingHTTPServer((HOST, PORT), H).serve_forever()
|
||||
Reference in new issue
Block a user