sequenceDiagram
autonumber
actor App as APP (Mobile Client)
participant Nginx as Nginx Proxy
participant GW as GATEWAY (backend-api)
participant Auth as AUTH (auth-service)
participant DB as DB_AUTH (PostgreSQL)
App->>Nginx: Step 1: GET /api/v1/auth/error-directory (Headers: X-App-Version, app_lang)
activate Nginx
Nginx->>GW: Step 2: GET /backend-api/v1/auth/error-directory
activate GW
GW->>Auth: Step 3: gRPC: GetErrorDirectory(DirectoryRequest)
activate Auth
Auth->>DB: Step 4: SQL SELECT * FROM error_directory WHERE is_active = true
activate DB
DB-->>Auth: Step 5: Return code registry and localized texts
deactivate DB
Auth-->>GW: Step 6: gRPC: DirectoryResponse (Full Registry)
deactivate Auth
GW-->>Nginx: Step 7: HTTP 200 OK (Translate directory to JSON)
deactivate GW
Nginx-->>App: Step 8: Deliver JSON registry to the app
deactivate Nginx
note over App: Step 9: Internal method<br/>Parsing and dynamic mapping of error tokens<br/>into the local state manager (no App Store update)
Метод GET /api/v1/auth/error-directory
Документация API: Справочник локализованных бизнес-ошибок для динамического маппинга на клиенте
- IAD-MIGRATION-116 Backlog — Краткое Описание задачи 1.
В открытом доступе представлена демонстрационная версия метода. В настоящей публичной документации отображены не все шаги, технические сценарии и приватные эндпоинты для системы цифровых симуляторов бизнес-процессов.
- Полная спецификация метода: Будет доступна только во внутреннем контуре разработки (Confluence / Swagger Enterprise).
Функциональное назначение
This method is designed to synchronize and dynamically update the system error directory on the mobile client.
Within the architecture, this method acts as an Error Context Provider:
- Exception Registry Extraction: It reads active links of low-level errors (DBMS, gRPC), simulator canonical codes, and their localized descriptions from the DBMS.
- Ensuring Interface Independence: It allows the mobile application to instantly learn about new types of errors from AI modules and backend business rules without needing to republish the build to the App Store or Google Play. The local state manager replaces system alerts on the fly based on the up-to-date JSON registry.
Interaction Protocol (HTTP Contract)
- Method:
GET - Route:
/api/v1/auth/error-directory - Data Format:
application/json
Header Specification (HTTP Headers)
| Header | Required | Description | Example Value |
|---|---|---|---|
X-App-Version |
Yes | Current mobile app build version to filter compatible error codes | 1.4.2 |
X-Request-ID |
Yes | End-to-end request ID for error directory synchronization session tracing | req-err-dir-99aa |
Query Parameters Specification (Query Parameters)
| Parameter | Type | Required | Description | Example Value |
|---|---|---|---|---|
app_lang |
String | Yes | Target localization language for the returned error messages | ru |
HTTP Request Example (URL):
GET /api/v1/auth/error-directory?app_lang=ru HTTP/1.1
Host: foodlifecycle.com
X-App-Version: 1.4.2
X-Request-ID: req-err-dir-99aa
Success Response Specification (Response Body)
HTTP 200 OK
Returned upon successful generation of the up-to-date error code registry for the client.
{
"status": "success",
"error_directory": [
{
"system_trigger": "PostgreSQL: users_email_key violation",
"grpc_status": "ALREADY_EXISTS (6)",
"http_status": "409 Conflict",
"canonical_code": "IAD_AUTH_EMAIL_DUPLICATE",
"localized_text": "Данный Email уже зарегистрирован.",
"ui_reaction": "Подсветить поле ввода Email красным цветом."
},
{
"system_trigger": "Redis: refresh_token blacklist match",
"grpc_status": "UNAUTHENTICATED (16)",
"http_status": "401 Unauthorized",
"canonical_code": "IAD_JWT_REFRESH_STOLEN",
"localized_text": "Сессия скомпрометирована. Войдите заново.",
"ui_reaction": "Очистить secure storage, принудительный вылет на экран Login."
}
],
"synced_at": 1783309600
}Метод предназначен для синхронизации и динамического обновления системного справочника ошибок на мобильном клиенте.
В рамках архитектуры этот метод выполняет роль поставщика локализации и каноничных кодов (Error Context Provider):
- Извлечение реестра исключений: Вычитывает из СУБД активные связки низкоуровневых ошибок (СУБД, gRPC), каноничных кодов симулятора и их локализованных описаний.
- Обеспечение независимости интерфейса: Позволяет мобильному приложению мгновенно узнавать о новых типах ошибок ИИ-модулей и бизнес-правил бэкенда без необходимости повторной публикации сборки в App Store или Google Play. Локальный стейт-менеджер налету подменяет системные алерты на основе актуального JSON-реестра.
Протокол взаимодействия (HTTP Контракт)
- Метод:
GET - Маршрут:
/api/v1/auth/error-directory - Формат данных:
application/json
Спецификация заголовков (HTTP Headers)
| Заголовок | Обязательный | Описание | Пример значения |
|---|---|---|---|
X-App-Version |
Да | Текущая версия сборки мобильного приложения для фильтрации совместимых кодов | 1.4.2 |
X-Request-ID |
Да | Сквозной ID запроса для трассировки сессии синхронизации справочника | req-err-dir-99aa |
Спецификация параметров запроса (Query Parameters)
| Параметр | Тип | Обязательный | Описание | Пример значения |
|---|---|---|---|---|
app_lang |
String | Да | Целевой язык локализации возвращаемых сообщений об ошибках | ru |
Пример HTTP-запроса (URL):
GET /api/v1/auth/error-directory?app_lang=ru HTTP/1.1
Host: foodlifecycle.com
X-App-Version: 1.4.2
X-Request-ID: req-err-dir-99aa
Спецификация успешного ответа (Response Body)
HTTP 200 OK
Возвращается при успешном формировании актуального реестра кодов ошибок для клиента.
{
"status": "success",
"error_directory": [
{
"system_trigger": "PostgreSQL: users_email_key violation",
"grpc_status": "ALREADY_EXISTS (6)",
"http_status": "409 Conflict",
"canonical_code": "IAD_AUTH_EMAIL_DUPLICATE",
"localized_text": "Данный Email уже зарегистрирован.",
"ui_reaction": "Подсветить поле ввода Email красным цветом."
},
{
"system_trigger": "Redis: refresh_token blacklist match",
"grpc_status": "UNAUTHENTICATED (16)",
"http_status": "401 Unauthorized",
"canonical_code": "IAD_JWT_REFRESH_STOLEN",
"localized_text": "Сессия скомпрометирована. Войдите заново.",
"ui_reaction": "Очистить secure storage, принудительный вылет на экран Login."
}
],
"synced_at": 1783309600
}Диаграмма последовательности (Mermaid)
The diagram illustrates the logic of the dynamic synchronization of the error directory. The API Gateway forwards the request to the Auth service, which retrieves active records from PostgreSQL, filters them according to the client configuration, and returns a structured payload for client-side mapping.
На диаграмме представлена логика аутентификации. Сервис Authorization сверяет хэш пароля в PostgreSQL, извлекает параметры привязки к пространству и генерирует JWT-токен, содержащий зашитые JWT Claims.
sequenceDiagram
autonumber
actor App as APP ( Мобильный клиент)
participant Nginx as Nginx Proxy
participant GW as GATEWAY (backend-api)
participant Auth as AUTH (auth-service)
participant DB as DB_AUTH (PostgreSQL)
App->>Nginx: Шаг 1: GET /api/v1/auth/error-directory (Headers: X-App-Version, app_lang)
activate Nginx
Nginx->>GW: Шаг 2: GET /backend-api/v1/auth/error-directory
activate GW
GW->>Auth: Шаг 3: gRPC: GetErrorDirectory(DirectoryRequest)
activate Auth
Auth->>DB: Шаг 4: SQL SELECT * FROM error_directory WHERE is_active = true
activate DB
DB-->>Auth: Шаг 5: Возврат реестра кодов и локализованных текстов
deactivate DB
Auth-->>GW: Шаг 6: gRPC: DirectoryResponse (Полный реестр)
deactivate Auth
GW-->>Nginx: Шаг 7: HTTP 200 OK (Трансляция справочника в JSON)
deactivate GW
Nginx-->>App: Шаг 8: Доставка JSON-реестра в приложение
deactivate Nginx
note over App: Шаг 9: Внутренний метод<br/>Парсинг и динамический маппинг токенов ошибок<br/>в локальный стейт-менеджер (без апдейта из App Store)
Расшифровка шагов
| Step | Action | Parameters | Errors (Exceptions / Statuses) |
|---|---|---|---|
Step 1 (APP -> NGINX) |
At cold start or session update, the mobile app sends a request to retrieve the up-to-date error directory registry. | HTTP GET /api/v1/auth/error-directoryHeaders: X-App-Version, app_lang |
No business errors |
Step 2 (NGINX -> Gateway) |
Nginx Proxy performs basic routing and forwards the system request to the API Gateway. |
HTTP GET /backend-api/v1/auth/error-directory |
No business errors |
Step 3 (Gateway -> AUTH) |
The API Gateway (backend-api) forwards the call to the master service via the internal gRPC interface. |
gRPC Method: GetErrorDirectory(DirectoryRequest)Args: app_version, language |
HTTP 400 Bad Request / gRPC: INVALID_ARGUMENT (passed an empty or unsupported app_lang) |
Step 4 (AUTH -> DB_AUTH) |
The auth-service microservice queries the DBMS to extract active error codes and their respective localized strings. |
SQL SELECT * FROM error_directory WHERE is_active = true |
No business errors |
Step 5 (DB_AUTH -> AUTH) |
The database returns the full registry of codes, canonical names, and localized messages. | Result: Set of rows (error_code, canonical_code, message_translations, ...) |
No business errors |
Step 6 (AUTH -> Gateway) |
The service constructs the directory data structure and returns a gRPC response to the API Gateway. | gRPC Response: DirectoryResponseFields: repeated ErrorItem errors |
No business errors |
Step 7 (Gateway -> NGINX) |
The API Gateway serializes the retrieved data into a valid JSON contract and relays it through Nginx. | HTTP 200 OKBody: [{"code": "IAD_AUTH_EMAIL_DUPLICATE", "text": "..."}, ...] |
No business errors |
Step 8 (NGINX -> APP) |
The infrastructure proxy delivers the JSON error code registry back to the mobile client. | Network packet delivery | No business errors |
Step 9 (APP -> APP) |
Internal Action: The network layer hands over the JSON payload to the local state manager. The app parses the registry and dynamically updates the mapping dictionary. | Invocation: StateManager.updateErrorDirectory(json) |
JsonUnsupportedObjectError (critical client-side parsing error due to a corrupted or malformed JSON contract structure) |
| Шаг | Действие | Параметры | Ошибки (Исключения / Статусы) |
|---|---|---|---|
Шаг 1 (APP -> NGINX) |
Мобильное приложение при холодном старте или обновлении сессии отправляет запрос на получение актуального реестра ошибок. | HTTP GET /api/v1/auth/error-directoryHeaders: X-App-Version, app_lang |
DioException: no internet connectionHTTP 502 Bad Gateway |
Шаг 2 (NGINX -> GATEWAY) |
Nginx Proxy выполняет базовую маршрутизацию и пробрасывает системный запрос на API Gateway. |
HTTP GET /backend-api/v1/auth/error-directory |
HTTP 403 Forbidden (если заблокирован IP-диапазон) |
Шаг 3 (GATEWAY -> AUTH) |
API Gateway (backend-api) направляет вызов в мастер-сервис через внутренний gRPC-интерфейс. |
gRPC Метод: GetErrorDirectory(DirectoryRequest)Args: app_version, language |
gRPC: INVALID_ARGUMENTHTTP 400 Bad Request (передан неподдерживаемый app_lang) |
Шаг 4 (AUTH -> DB_AUTH) |
Микросервис auth-service обращается к СУБД для извлечения активных кодов ошибок и соответствующих локализованных текстов. |
SQL SELECT * FROM error_directory WHERE is_active = true |
PostgreSQL: table "error_directory" does not existgRPC: INTERNAL (13) |
Шаг 5 (DB_AUTH -> AUTH) |
База данных возвращает полный реестр кодов, канонических имен и локализованных сообщений. | Result: Набор строк (error_code, canonical_code, ru_text, ...) |
PostgreSQL: connection pool timeout |
Шаг 6 (AUTH -> GATEWAY) |
Сервис формирует структуру данных справочника и возвращает gRPC-ответ на API Gateway. | gRPC Response: DirectoryResponseFields: repeated ErrorItem errors |
gRPC: DEADLINE_EXCEEDED (4) (база отвечала слишком долго) |
Шаг 7 (GATEWAY -> NGINX) |
API Gateway сериализует полученные данные в валидный JSON-контракт и транслирует его через Nginx. | HTTP 200 OKBody: [{"code": "IAD_AUTH_EMAIL_DUPLICATE", "text": "..."}, ...] |
HTTP 500 Internal Server Error (ошибка маппинга JSON структуры) |
Шаг 8 (NGINX -> APP) |
Инфраструктурный шлюз доставляет JSON-реестр кодов ошибок симулятора обратно в мобильный клиент. | Доставка сетевого пакета данных | DioException: receive timeout |
Шаг 9 (APP -> APP) |
Внутреннее действие: Сетевой слой передает JSON в локальный стейт-менеджер. Приложение парсит реестр и динамически обновляет карту соответствий. | Вызов: StateManager.updateErrorDirectory(json) |
JsonUnsupportedObjectError (ошибка парсинга из-за поврежденной структуры JSON) |
| Шаг | Действие | Параметры | Ошибки (Исключения / Статусы) |
|---|---|---|---|
Шаг 1 (APP -> NGINX) |
Мобильное приложение при холодном старте или обновлении сессии отправляет запрос на получение актуального реестра ошибок. | HTTP GET /api/v1/auth/error-directoryHeaders: X-App-Version, app_lang |
Бизнес-ошибки отсутствуют |
Шаг 2 (NGINX -> GATEWAY) |
Nginx Proxy выполняет базовую маршрутизацию и пробрасывает системный запрос на API Gateway. |
HTTP GET /backend-api/v1/auth/error-directory |
Бизнес-ошибки отсутствуют |
Шаг 3 (GATEWAY -> AUTH) |
API Gateway (backend-api) направляет вызов в мастер-сервис через внутренний gRPC-интерфейс. |
gRPC Метод: GetErrorDirectory(DirectoryRequest)Args: app_version, language |
HTTP 400 Bad Request / gRPC: INVALID_ARGUMENT (передан пустой или неподдерживаемый app_lang) |
Шаг 4 (AUTH -> DB_AUTH) |
Микросервис auth-service обращается к СУБД для извлечения активных кодов ошибок и соответствующих локализованных текстов. |
SQL SELECT * FROM error_directory WHERE is_active = true |
Бизнес-ошибки отсутствуют |
Шаг 5 (DB_AUTH -> AUTH) |
База данных возвращает полный реестр кодов, канонических имен и локализованных сообщений. | Result: Набор строк (error_code, canonical_code, message_translations, ...) |
Бизнес-ошибки отсутствуют |
Шаг 6 (AUTH -> GATEWAY) |
Сервис формирует структуру данных справочника и возвращает gRPC-ответ на API Gateway. | gRPC Response: DirectoryResponseFields: repeated ErrorItem errors |
Бизнес-ошибки отсутствуют |
Шаг 7 (GATEWAY -> NGINX) |
API Gateway сериализует полученные данные в валидный JSON-контракт и транслирует его через Nginx. | HTTP 200 OKBody: [{"code": "IAD_AUTH_EMAIL_DUPLICATE", "text": "..."}, ...] |
Бизнес-ошибки отсутствуют |
Шаг 8 (NGINX -> APP) |
Инфраструктурный шлюз доставляет JSON-реестр кодов ошибок симулятора обратно в мобильный клиент. | Доставка сетевого пакета данных | Бизнес-ошибки отсутствуют |
Шаг 9 (APP -> APP) |
Внутреннее действие: Сетевой слой передает JSON в локальный стейт-менеджер. Приложение парсит реестр и динамически обновляет карту соответствий. | Вызов: StateManager.updateErrorDirectory(json) |
JsonUnsupportedObjectError (критическая ошибка парсинга на фронтенде из-за поврежденной или невалидной структуры JSON-контракта) |
Error Item Structure (Error Item Claims)
When the mobile client or the internal gateway parses an element of the error_directory array, they see the following standardized JSON dataset within the application code:
{
"system_trigger": "PostgreSQL: users_email_key violation",
"grpc_status": "ALREADY_EXISTS (6)",
"http_status": "409 Conflict",
"canonical_code": "IAD_AUTH_EMAIL_DUPLICATE",
"localized_text": "Данный Email уже зарегистрирован.",
"ui_reaction": "Подсветить поле ввода Email красным цветом."
}system_trigger— the original system or platform exception (low-level DBMS log or gRPC failure string).grpc_status— the standardized gRPC status code of the internal cross-service error used for system tracing.http_status— the HTTP REST status code returned by the API Gateway back to the mobile client.canonical_code— the unique simulator error string token that serves as the mapping key for the client-side state manager.localized_text— the ready-to-display user message translated into the target language requested viaapp_lang.ui_reaction— a functional instruction/hint for the frontend engineering team defining the interface behavior logic (e.g., show alert, highlight input field, or force logout).
Cтруктура элемента реестра ошибок (Error Item Claims):
Когда мобильный клиент или внутренний шлюз парсят элемент массива error_directory, они в коде приложения видят следующий стандартизированный JSON-датасет:
{
"system_trigger": "PostgreSQL: users_email_key violation",
"grpc_status": "ALREADY_EXISTS (6)",
"http_status": "409 Conflict",
"canonical_code": "IAD_AUTH_EMAIL_DUPLICATE",
"localized_text": "Данный Email уже зарегистрирован.",
"ui_reaction": "Подсветить поле ввода Email красным цветом."
}system_trigger— исходное системное или платформенное исключение (низкоуровневый лог СУБД или gRPC).grpc_status— стандартизированный gRPC статус-код внутренней межсервисной ошибки для трассировки.http_status— HTTP REST статус, возвращаемый API шлюзом на мобильный клиент.canonical_code— уникальный строковый токен ошибки симулятора, служащий ключом для стейт-менеджера.localized_text— готовая для вывода на экран пользователя фраза на целевом языке (app_lang).ui_reaction— инструкция-подсказка для фронтенд-команды, определяющая логику поведения интерфейса (алерт, подсветка поля, вылет).
Спецификация вилок исключений и обработки ошибок
During the error directory synchronization, the system processes critical infrastructural failures to protect interface stability during a cold start.
2. Request Language Parameter Validation Error (HTTP 422 Unprocessable Entity)
Returned by the backend gateway if the localization string passed in the app_lang query parameter is missing from the registry of supported languages in the FoodLifeCycleApp.
{
"error_code": "ERR-VALIDATION-FAILED",
"message": "Передан некорректный или неподдерживаемый код локализации приложения.",
"details": [
{
"loc": ["query", "app_lang"],
"msg": "value is not a valid supported language code (ru, kz)",
"type": "value_error.language"
}
]
}При синхронизации справочника ошибок система обрабатывает критические инфраструктурные сбои, защищая стабильность интерфейса при холодном старте.
2. Ошибка валидации параметров запроса языка (HTTP 422 Unprocessable Entity)
Возвращается бэкенд-шлюзом, если переданная строка локализации в Query-параметре app_lang отсутствует в реестре поддерживаемых языков приложения FoodLifeCycleApp.
{
"error_code": "ERR-VALIDATION-FAILED",
"message": "Передан некорректный или неподдерживаемый код локализации приложения.",
"details": [
{
"loc": ["query", "app_lang"],
"msg": "value is not a valid supported language code (ru, kz)",
"type": "value_error.language"
}
]
}