Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 27 additions & 13 deletions content/docs/api-service/architecture.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -188,16 +188,30 @@ reports 503 while the database does not answer; `/live` checks nothing and stays
`audit.partition_check_interval`; partitions older than
`audit.retention_months` are dropped.

## Single replica

The plugin cache on disk is not safe to share between processes: unpacking ends
with a remove and a rename serialised only by an in-process lock, and each
process accounts `cache_max_bytes` separately. The Helm chart runs one replica
with a `ReadWriteOnce` volume and the `Recreate` strategy. It *permits*
`replicaCount > 1` with a `ReadWriteMany` volume; that combination is not
supported and corrupts the cache under concurrent misses. The database side is
safe for several processes (migrations and partition maintenance take locks),
which is what makes a restart into a new version safe. Scale vertically:
more CPU and a higher `max_concurrent_generations`, keeping
`max_concurrent_generations × max_output_size` inside the memory limit (the
chart refuses an install where it is not).
## Scaling out

The service scales horizontally, with a plugin cache per pod. The cache on disk
is not safe to share between processes: unpacking ends with a remove and a
rename serialised only by an in-process lock, and each process accounts
`cache_max_bytes` separately, so two pods on one `ReadWriteMany` volume corrupt
it under concurrent misses.

Since v1.2.0 the Helm chart runs a StatefulSet that gives every replica a
`ReadWriteOnce` claim of its own, `plugins-<release>-easyp-service-N` (or an
`emptyDir` with `persistence.enabled=false`), and refuses a shared access mode.
Upgrades roll one pod at a time. `autoscaling.enabled` adds a
HorizontalPodAutoscaler on CPU.

Every replica's cache starts empty and is filled from object storage, so more
than one replica — `replicaCount` above 1, or an autoscaler whose
`maxReplicas` is — needs `config.registry.s3.bucket`, and the chart refuses the
install without it. Without S3 the plugins directory is the only copy of every
plugin, and only one replica can hold it.

The database side is safe for several processes: migrations and partition
maintenance take locks, which is also what makes a restart into a new version
safe. Everything else a replica enforces is its own — the worker pool,
`max_concurrent_generations` and the per-client rate limit — so capacity grows
with the replica count, and a client spread across N pods gets up to N times its
limit. Within one pod, keep `max_concurrent_generations × max_output_size`
inside the memory limit (the chart refuses an install where it is not).
37 changes: 27 additions & 10 deletions content/docs/api-service/architecture.ru.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,30 @@ health-порту отвечает 503, пока БД не отвечает; `/l
`audit.partition_check_interval`; партиции старше `audit.retention_months`
удаляются.

## Одна реплика [#single-replica]

Кеш плагинов на диске нельзя делить между процессами: распаковка заканчивается
удалением и переименованием, которые сериализует только блокировка внутри
процесса, а `cache_max_bytes` каждый процесс считает сам. Helm-чарт запускает
одну реплику с томом `ReadWriteOnce` и стратегией `Recreate`. Он *разрешает*
`replicaCount > 1` с томом `ReadWriteMany`; такая комбинация не поддерживается и
портит кеш при одновременных промахах. Сторона БД безопасна для нескольких
процессов (миграции и обслуживание партиций берут блокировки) — именно поэтому
перезапуск на новую версию безопасен.
## Горизонтальное масштабирование [#scaling-out]

Сервис масштабируется горизонтально, и у каждого пода свой кеш плагинов. Общим
кеш на диске быть не может: распаковка заканчивается удалением и
переименованием, которые сериализует только блокировка внутри процесса, а
`cache_max_bytes` каждый процесс считает сам. Два пода на одном томе
`ReadWriteMany` портят кеш при одновременных промахах.

С v1.2.0 Helm-чарт запускает StatefulSet: каждая реплика получает собственный
том `ReadWriteOnce`, `plugins-<release>-easyp-service-N` (или `emptyDir` при
`persistence.enabled=false`), а общий режим доступа чарт отвергает. Обновление
идёт по одному поду. `autoscaling.enabled` добавляет HorizontalPodAutoscaler по
CPU.

Кеш новой реплики пуст и наполняется из объектного хранилища, поэтому для
нескольких реплик — `replicaCount` больше 1 или автоскейлер с таким
`maxReplicas` — нужен `config.registry.s3.bucket`; без него чарт откажется
устанавливаться. Без S3 каталог плагинов — единственная копия всех плагинов, и
держать её может только одна реплика.

База данных несколько процессов выдерживает: миграции и обслуживание партиций
берут блокировки, поэтому и перезапуск на новую версию безопасен. Всё остальное
у каждой реплики своё — пул воркеров, `max_concurrent_generations` и лимит
запросов на клиента, — так что пропускная способность растёт с числом реплик, а
клиент, чьи запросы расходятся по N подам, получает до N своих лимитов. В
пределах одного пода держите `max_concurrent_generations × max_output_size` в
рамках лимита памяти (иначе чарт откажется устанавливаться).
4 changes: 2 additions & 2 deletions content/docs/api-service/backup.ru.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ description: "Что обязано попасть в бэкап API Service, с
| **Таблица `plugins`** | Сам реестр: какие версии плагинов существуют, их конфигурация, командная строка, записанные контрольные суммы. Больше это не хранится нигде. |
| **Партиции `audit_log`** | Журнал аудита. Он продаётся в Enterprise, существует в единственном экземпляре, второй копии нет. |
| **Таблица `goose_db_version`** | Какие миграции применены. Восстановление данных без неё приводит к тому, что следующий старт либо прогонит миграции заново, либо откажется стартовать. |
| **Бакет объектного хранилища** | Архивы плагинов. Локальный кэш — это кэш, из него вытесняют, так что бакет остаётся единственной копией бинарей. |
| **Бакет объектного хранилища** | Архивы плагинов. Локальный кеш — это кеш, из него вытесняют, так что бакет остаётся единственной копией бинарей. |
| **`DB_POSTGRES_DSN`, `AUTH_WRITE_TOKENS`, ключи S3** | Секретов нет в базе, и обычно их нет и в бэкапе кластера. |
| **`LICENSE_KEY` и `LICENSE_PUBLIC_KEYS`** | Восстановимы из реестра лицензий — но не вами и не в три часа ночи. Без них восстановленный сервис работает в community: без аудита, четыре воркера, десять плагинов. |

Expand Down Expand Up @@ -75,7 +75,7 @@ RPO в несколько часов нормален для `plugins`: реги
собой **вперёд**. **Считайте откат ограниченным
`config.audit.preCreateMonths`** (по умолчанию три) и предпочитайте
восстановление на соответствующий релиз.
4. **Ожидайте пустой кэш плагинов.** Это кэш, и при `persistence.enabled=false`
4. **Ожидайте пустой кеш плагинов.** Это кеш, и при `persistence.enabled=false`
он пуст после каждого перезапуска в любом случае. Первый запрос к каждому
плагину скачает его заново. Смотрите, как растёт
`easyp_plugin_cache_bytes`; делать ничего не нужно.
Expand Down
11 changes: 7 additions & 4 deletions content/docs/api-service/client-usage.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,9 @@ ceiling) and `DEADLINE_EXCEEDED` are returned immediately: retrying the first
adds load exactly when the server has none to spare, and retrying the second
re-runs a generation that already used its full timeout.

Methods: `GenerateCode`, `ListPlugins` (walks every page), `CreatePlugin`,
`UpdatePlugin`, `DeletePlugin`, `Close`.
Methods: `GenerateCode`, `ListPlugins` (walks every page), `Platform` (the
`os/arch` the service runs plugins on, empty from a server older than v1.3.0),
`CreatePlugin`, `UpdatePlugin`, `DeletePlugin`, `Close`.

`CreatePlugin` and `UpdatePlugin` take a `config` struct. On a v1.2.0 or newer
service `command` may be omitted: the service derives
Expand Down Expand Up @@ -171,8 +172,10 @@ grpcurl -protoset api.protoset -plaintext localhost:23410 \

### Errors

Every non-OK status carries `google.rpc.ErrorInfo` with domain `easyp.tech` and a
stable `reason`. Branch on the reason, not the message.
Every error the handlers return carries `google.rpc.ErrorInfo` with domain
`easyp.tech` and a stable `reason`. Branch on the reason, not the message.
Refusals from the interceptors in front of the handlers carry none; they are
listed below the table.

| Reason | gRPC code | Typical cause |
|---|---|---|
Expand Down
15 changes: 9 additions & 6 deletions content/docs/api-service/client-usage.ru.mdx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
title: "Использование клиентами"
title: "Подключение клиентов"
description: "Как направить easyp CLI на сервис, как пользоваться Go SDK и как вызывать gRPC API напрямую."
---

Expand Down Expand Up @@ -128,8 +128,9 @@ func main() {
добавляет нагрузки ровно тогда, когда у сервера её некуда девать, а повтор
второго заново запускает генерацию, уже потратившую весь таймаут.

Методы: `GenerateCode`, `ListPlugins` (обходит все страницы), `CreatePlugin`,
`UpdatePlugin`, `DeletePlugin`, `Close`.
Методы: `GenerateCode`, `ListPlugins` (обходит все страницы), `Platform`
(`os/arch`, на которой сервис запускает плагины; сервер старше v1.3.0 отдаёт
пустую строку), `CreatePlugin`, `UpdatePlugin`, `DeletePlugin`, `Close`.

`CreatePlugin` и `UpdatePlugin` принимают структуру `config`. На сервисе v1.2.0
или новее `command` можно не указывать: сервис выводит
Expand Down Expand Up @@ -171,8 +172,10 @@ grpcurl -protoset api.protoset -plaintext localhost:23410 \

### Ошибки

Каждый не-OK статус несёт `google.rpc.ErrorInfo` с доменом `easyp.tech` и
стабильным `reason`. Ветвитесь по reason, а не по тексту.
Каждая ошибка, которую возвращают обработчики, несёт `google.rpc.ErrorInfo` с
доменом `easyp.tech` и стабильным `reason`. Проверяйте `reason`, а не текст
сообщения. У отказов от интерсепторов, стоящих перед обработчиками, `ErrorInfo`
нет — они перечислены под таблицей.

| Reason | Код gRPC | Типичная причина |
|---|---|---|
Expand All @@ -189,7 +192,7 @@ grpcurl -protoset api.protoset -plaintext localhost:23410 \
| `SHUTTING_DOWN` | `UNAVAILABLE` | Сервис останавливается. |
| `FEATURE_DENIED` | `PERMISSION_DENIED` | Функции нет в лицензии. |
| `DEADLINE_EXCEEDED` | `DEADLINE_EXCEEDED` | Плагин не уложился в таймаут. |
| `CANCELED` | `CANCELLED` | Клиент ушёл. |
| `CANCELED` | `CANCELLED` | Клиент отменил запрос. |
| `INTERNAL` | `INTERNAL` | Всё остальное. |

Отказы rate limit и лимита одновременных запросов на клиента приходят от
Expand Down
16 changes: 8 additions & 8 deletions content/docs/api-service/installation.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
title: "Installation"
description: "Container image tags, the Helm chart and its required values, the compose stack, and release binaries."
description: "Container image tags, the Helm chart and its required values, Docker Compose, and release binaries."
---

Every release publishes a container image, a Helm chart and binaries. The
Expand Down Expand Up @@ -90,15 +90,15 @@ Helm release history.

| Value | Default | Why it matters |
|---|---|---|
| `replicaCount` | `1` | Do not raise it on a shared volume. See [Architecture](/docs/api-service/architecture#single-replica). |
| `replicaCount` | `1` | Each replica gets its own volume; above 1 needs `config.registry.s3.bucket`. See [Architecture](/docs/api-service/architecture#scaling-out). |
| `image.tag` | `""` (chart appVersion) | Pin it. |
| `ports.grpc` / `metric` / `health` / `mcp` | `8080` / `8081` / `8082` / `8083` | The chart overrides the binary's 23410–23413. |
| `mcp.enabled` | `false` | MCP sits outside the gRPC interceptor chain. |
| `config.server.trustedProxies` | `[]` | Required behind an ingress, else every client shares one rate-limit bucket. |
| `config.workerPool.*` | binary defaults | `workers: 4`, `queueSize: 16`, `maxConcurrentGenerations: 16`, `generationTimeoutSeconds: 120`. |
| `config.registry.s3.bucket` | `""` | Empty means local mode. |
| `config.license.publicKeys` | easyp.tech key `2026-08` | The licence trust anchor. Replace only if you issue your own licences. |
| `tls.enabled` / `tls.clientCASecret` | `true` / `""` | With a CA the listener requires client certificates (mTLS). `"-"` disables the client check. |
| `tls.enabled` / `tls.clientCASecret` | `true` / `""` | With TLS on, mTLS is on by default: an empty value checks client certificates against `ca.crt` in the server certificate's secret (`tls.serverSecret` or cert-manager's). `"-"` disables the client check. |
| `certManager.enabled` | `false` | Let cert-manager issue server and ingress client certificates. |
| `ingress.*` | disabled, Traefik | Defaults target Traefik because it can express an mTLS backend leg (`ServersTransport`). |
| `persistence.size` | `25Gi` | Must exceed `cacheMaxBytes`. |
Expand All @@ -119,11 +119,11 @@ same pod. See [Security](/docs/api-service/security).

## Docker Compose

`deploy/docker-compose.yml` in the service repository is the development stack:
PostgreSQL, RustFS as S3, Traefik with mutual TLS in front, and a Grafana/Loki/
Tempo/Mimir/Pyroscope suite. It is driven by `task up` and is the reference for
how the pieces fit, not a production template. A minimal compose file is in the
[Quickstart](/docs/api-service/quickstart).
The service repository ships no compose stack. A minimal compose file —
PostgreSQL and the released image — is in the
[API Service quickstart](/docs/api-service/quickstart); running the binary from
a checkout is in the service README's
[From source](https://github.com/easyp-tech/service#from-source) section.

## Binaries

Expand Down
Loading
Loading