docs: перевести документацию на русский

This commit is contained in:
Георгий
2026-07-13 21:21:42 +03:00
parent d3be367910
commit 3ed29fa8e6
2 changed files with 158 additions and 128 deletions

161
README.md
View File

@@ -1,77 +1,79 @@
# Mila # Mila
Mila is a small Go library for BVK media-complex content exchange. Mila — небольшая Go-библиотека для обмена данными между БВК и
медиакомплексом.
It implements the HTTP protocol where BVK pushes the currently displayed Библиотека реализует HTTP-протокол, в котором БВК отправляет в медиакомплекс
content state to the media complex: текущее состояние отображаемого контента:
```text ```text
GET /set-content?route=<R>&str=<S>&tpl_name=<T> GET /set-content?route=<R>&str=<S>&tpl_name=<T>
GET /get-content GET /get-content
``` ```
The library intentionally does not know anything about snapshots, route Mila намеренно не знает ничего про снапшоты, геопозицию, прогресс маршрута,
progress, geolocation, frontend state, or media playback rules. It only parses, фронтенд, правила воспроизведения медиа и структуру контента White Nights. Она
validates, stores, logs, and returns BVK content state. только принимает, валидирует, сохраняет, логирует и возвращает состояние,
полученное от БВК.
## Install ## Установка
```bash ```bash
go get gitea.unprism.ru/KRBL/mila go get gitea.unprism.ru/KRBL/mila
``` ```
## Scope ## Зона Ответственности
Mila is a protocol library. It should be embedded into an application service, Mila — библиотека протокола. Ее нужно встраивать в прикладной сервис, например
for example `wn-content`, and exposed on the address required by the transport в `wn-content`, и открывать на адресе, который требуется транспортной
integration. интеграцией.
Mila does: Mila делает:
- parse `GET /set-content` - разбирает `GET /set-content`;
- parse `GET /get-content` - разбирает `GET /get-content`;
- validate `route`, `str`, and `tpl_name` - валидирует `route`, `str` и `tpl_name`;
- URL-decode query parameters through Go's standard HTTP parser - декодирует URL-параметры стандартным HTTP-парсером Go;
- store the latest state in memory or in a JSON file - хранит последнее состояние в памяти или JSON-файле;
- return protocol-compatible JSON - возвращает JSON, совместимый с протоколом;
- log each HTTP request with method, path, status, remote address, and duration - логирует каждый HTTP-запрос: метод, путь, статус, удаленный адрес и время;
- call an optional callback after successful `set-content` - вызывает опциональный callback после успешного `set-content`.
Mila does not: Mila не делает:
- calculate route progress - не считает прогресс маршрута;
- work with geolocation or NMEA - не работает с геопозицией или NMEA;
- map `tpl_name` to real media playlists - не сопоставляет `tpl_name` с реальными плейлистами;
- read or write snapshots - не читает и не пишет снапшоты;
- communicate with frontend directly - не общается с фронтендом напрямую;
- decide how content should be rendered - не решает, как именно должен отображаться контент.
## Protocol ## Протокол
The media complex acts as an HTTP server. BVK acts as an HTTP client. Медиакомплекс выступает HTTP-сервером. БВК выступает HTTP-клиентом.
Default address from the PDF: Адрес по документу:
```text ```text
172.16.16.2:13280 172.16.16.2:13280
``` ```
Endpoints: Ручки:
```text ```text
GET /set-content?route=<R>&str=<S>&tpl_name=<T> GET /set-content?route=<R>&str=<S>&tpl_name=<T>
GET /get-content GET /get-content
``` ```
`set-content` accepts URL-encoded query parameters: `set-content` принимает URL-encoded query-параметры:
| Parameter | Required | Meaning | | Параметр | Обязательный | Описание |
| --- | --- | --- | | --- | --- | --- |
| `route` | yes | route number, default limit is 1-3 characters | | `route` | да | номер маршрута, по умолчанию 1-3 символа |
| `str` | no | ticker/running text, default limit is 200 characters | | `str` | нет | текст бегущей строки, по умолчанию до 200 символов |
| `tpl_name` | yes | media content template name, default limit is 200 characters | | `tpl_name` | да | название шаблона медиаконтента, по умолчанию до 200 символов |
`get-content` response: Ответ `get-content`:
```json ```json
{ {
@@ -81,10 +83,11 @@ GET /get-content
} }
``` ```
`updated_at` is stored internally but is not exposed by `/get-content`, because Поле `updated_at` хранится внутри состояния, но не отдается через
the protocol response should stay strict. `/get-content`, потому что ответ должен оставаться строгим относительно
протокола.
## Usage ## Использование
```go ```go
package main package main
@@ -101,7 +104,10 @@ store := mila.NewFileStore("/srv/persistence/client_logs/bvk_content.json")
handler := mila.NewHandler(mila.DefaultConfig(), store, handler := mila.NewHandler(mila.DefaultConfig(), store,
mila.WithOnSet(func(state mila.ContentState) { mila.WithOnSet(func(state mila.ContentState) {
// Application-specific integration goes here. // Здесь прикладная интеграция:
// - передать route/str/tpl_name в состояние приложения;
// - сопоставить state.Template с локальным шаблоном;
// - записать дополнительные логи.
}), }),
) )
@@ -114,15 +120,15 @@ log.Fatal(srv.ListenAndServe())
} }
``` ```
## Configuration ## Конфигурация
Default validation config: Конфигурация валидации по умолчанию:
```go ```go
cfg := mila.DefaultConfig() cfg := mila.DefaultConfig()
``` ```
Which currently means: Сейчас это:
```go ```go
mila.Config{ mila.Config{
@@ -132,45 +138,46 @@ mila.Config{
} }
``` ```
The text/template limits should be confirmed with the integrator. The provided Лимиты для `str` и `tpl_name` нужно подтвердить у интегратора. В переданном PDF
PDF has an ambiguous text layer for those values. текстовый слой неоднозначно распознает исходное значение.
## Stores ## Хранилища
Use `MemoryStore` when state does not need to survive process restart: `MemoryStore` подходит, когда состояние не должно переживать рестарт процесса:
```go ```go
store := mila.NewMemoryStore() store := mila.NewMemoryStore()
``` ```
Use `FileStore` on a device when the latest BVK state should be persisted: `FileStore` подходит для устройства, если последнее состояние от БВК нужно
сохранять на диске:
```go ```go
store := mila.NewFileStore("/srv/persistence/client_logs/bvk_content.json") store := mila.NewFileStore("/srv/persistence/client_logs/bvk_content.json")
``` ```
`FileStore` writes atomically through a temporary file and keeps an in-memory `FileStore` пишет состояние атомарно через временный файл и держит копию в
copy after the first successful read or write. памяти после первого успешного чтения или записи.
## Callback ## Callback
`WithOnSet` lets the host application react to a valid BVK update: `WithOnSet` позволяет приложению отреагировать на валидное обновление от БВК:
```go ```go
handler := mila.NewHandler(mila.DefaultConfig(), store, handler := mila.NewHandler(mila.DefaultConfig(), store,
mila.WithOnSet(func(state mila.ContentState) { mila.WithOnSet(func(state mila.ContentState) {
// Example host-side decisions: // Возможные действия на стороне приложения:
// - publish route and ticker to frontend state // - опубликовать номер маршрута и бегущую строку;
// - map state.Template to a local playlist/template // - сопоставить state.Template с локальным плейлистом;
// - write application-specific logs // - записать прикладные логи.
}), }),
) )
``` ```
The callback is intentionally synchronous. Keep it fast; if integration work is Callback выполняется синхронно. Его нужно держать быстрым. Если интеграционная
heavy, push the state into an internal queue. логика тяжелая, лучше положить состояние во внутреннюю очередь.
## State Model ## Модель Состояния
```json ```json
{ {
@@ -181,7 +188,7 @@ heavy, push the state into an internal queue.
} }
``` ```
Go type: Go-тип:
```go ```go
type ContentState struct { type ContentState struct {
@@ -192,18 +199,18 @@ type ContentState struct {
} }
``` ```
## Status Codes ## Коды Ответов
| Code | When | | Код | Когда возвращается |
| ---: | --- | | ---: | --- |
| 200 | valid `set-content` or ready `get-content` | | 200 | валидный `set-content` или готовый `get-content` |
| 400 | invalid request parameters | | 400 | невалидные параметры запроса |
| 404 | unknown path | | 404 | неизвестный путь |
| 405 | method is not `GET` | | 405 | метод не `GET` |
| 500 | store/internal error | | 500 | ошибка хранилища или внутренняя ошибка |
| 503 | `get-content` before first state, canceled/deadline context, unavailable dependency | | 503 | `get-content` до первого состояния, отмененный контекст, недоступная зависимость |
Error response: Формат ошибки:
```json ```json
{ {
@@ -211,17 +218,17 @@ Error response:
} }
``` ```
## Testing ## Тестирование
```bash ```bash
go test ./... go test ./...
``` ```
Current tests cover: Текущие тесты покрывают:
- successful `set-content` + `get-content` - успешный `set-content` + `get-content`;
- `get-content` before state is ready - `get-content` до готовности состояния;
- invalid route validation - невалидный `route`;
- UTF-8 text/template validation - UTF-8 и лимиты для текста/шаблона;
- file store persistence - сохранение и чтение через `FileStore`;
- missing file store state - отсутствие файла состояния в `FileStore`.

View File

@@ -1,45 +1,46 @@
# BVK Exchange Protocol # Протокол Обмена С БВК
Based on ротокол_обменаедиакомплекса_и_БВК.pdf`. Документ основан на файле
ротокол_обменаедиакомплекса_и_БВК.pdf`.
## Role ## Роли
- BVK is the HTTP client. - БВК — HTTP-клиент.
- Media complex is the HTTP server. - Медиакомплекс — HTTP-сервер.
- Default address from the document: `172.16.16.2:13280`. - Адрес по документу: `172.16.16.2:13280`.
## Set Content ## Установка Контента
```text ```text
GET /set-content?route=<R>&str=<S>&tpl_name=<T> GET /set-content?route=<R>&str=<S>&tpl_name=<T>
``` ```
Parameters are URL-encoded. Параметры передаются в query string и должны быть URL-encoded.
| Parameter | Meaning | | Параметр | Описание |
| --- | --- | | --- | --- |
| `route` | Route number, 1 to 3 characters | | `route` | номер маршрута, от 1 до 3 символов |
| `str` | Ticker/running text | | `str` | текст бегущей строки |
| `tpl_name` | Media content template name | | `tpl_name` | название шаблона медиаконтента |
Current library defaults: Текущие значения по умолчанию в библиотеке:
| Field | Default limit | | Поле | Лимит по умолчанию |
| --- | ---: | | --- | ---: |
| `route` | 3 characters | | `route` | 3 символа |
| `str` | 200 characters | | `str` | 200 символов |
| `tpl_name` | 200 characters | | `tpl_name` | 200 символов |
The exact text/template limits must be confirmed with the integrator because the Точные лимиты для `str` и `tpl_name` нужно подтвердить у интегратора, потому что
PDF text layer is ambiguous for the original value. текстовый слой PDF неоднозначно распознает исходное значение.
## Get Content ## Запрос Контента
```text ```text
GET /get-content GET /get-content
``` ```
Response: Ответ:
```json ```json
{ {
@@ -49,15 +50,37 @@ Response:
} }
``` ```
Mila keeps `updated_at` internally, but the HTTP response is strict and exposes Mila хранит `updated_at` внутри состояния, но HTTP-ответ оставляет строгим и
only the fields defined by the protocol. отдает только поля, описанные в протоколе.
## Status Codes ## Коды Ответов
| Code | Meaning | | Код | Значение |
| ---: | --- | | ---: | --- |
| 200 | OK | | 200 | OK |
| 400 | Bad request / validation error | | 400 | ошибка в запросе или валидации |
| 404 | Path not found | | 404 | путь не найден |
| 500 | Internal server error | | 405 | метод не поддерживается |
| 503 | State is not ready or dependency unavailable | | 500 | внутренняя ошибка сервера |
| 503 | состояние еще не готово или зависимость недоступна |
## Важное Ограничение
Протокол БВК передает только:
- номер маршрута;
- текст бегущей строки;
- название шаблона медиаконтента.
Он не передает:
- координаты;
- направление движения;
- текущий сегмент маршрута;
- процент прохождения маршрута;
- ближайшую остановку;
- ближайшие достопримечательности.
Поэтому Mila не должна использоваться как источник геопозиции или route
progress. Эти данные должны приходить из отдельного источника: NMEA, API,
симулятора или другого механизма геолокации.