<a id="internals"></a>

# Нутрощі Weblate

#### NOTE
У цьому розділі наведено базовий огляд нутрощів Weblate.

Структура більшої частини коду Weblate походить від [Django](https://www.djangoproject.com/) і засновано на структурі коду Django.

## Структура каталогів

Короткий огляд структури каталогів основного сховища Weblate:

`docs`
: Початковий код цієї документації, який можна зібрати за допомогою [Sphinx](https://www.sphinx-doc.org/).

`dev-docker`
: Код Docker для запуску сервера розробки, див. [Запуск Weblate локально у Docker](https://docs.weblate.org/uk/latest/contributing/start.md#dev-docker).

`weblate`
: Вихідний код Weblate як програми [Django](https://www.djangoproject.com/), див. [Нутрощі Weblate](#internals).

`weblate/static`
: Клієнтські файли (CSS, Javascript і зображення), див. [Оболонка Weblate](https://docs.weblate.org/uk/latest/contributing/frontend.md).

## Модулі

Weblate складається з декількох програм Django (деякі є необов’язковими, див. [Додаткові модулі Weblate](https://docs.weblate.org/uk/latest/admin/optionals.md)):

`accounts`

> Обліковий запис користувача, профілі та сповіщення.

`addons`

> Додатки для коригування поведінки Weblate, див. [Додатки](https://docs.weblate.org/uk/latest/admin/addons.md#addons).

`api`

> Програмний інтерфейс на основі [Django REST framework](https://www.django-rest-framework.org/).

`auth`

> Розпізнавання і права доступу.

`billing`

> Додатковий модуль [Оплата](https://docs.weblate.org/uk/latest/admin/optionals.md#billing).

`checks`

> Модуль [Перевірки якості](https://docs.weblate.org/uk/latest/user/checks.md#checks) для рядків перекладів.

`fonts`

> Модуль перевірок обробки шрифтів.

`formats`

> Шар абстракції форматів файлів на основі translate-toolkit.

`gitexport`

> Додатковий модуль [Засіб експортування Git](https://docs.weblate.org/uk/latest/admin/optionals.md#git-exporter).

`lang`

> Модуль визначення мов і моделей форм множини.

`legal`

> Додатковий модуль [Юридичний модуль](https://docs.weblate.org/uk/latest/admin/optionals.md#legal).

`machinery`

> Інтеграція служб комп’ютерного перекладу.

`memory`

> Вбудована пам’ять перекладів, див. [Пам’ять перекладів](https://docs.weblate.org/uk/latest/admin/memory.md#translation-memory).

`screenshots`

> Керування знімками вікон та модуль оптичного розпізнавання тексту.

`trans`

> Головний модуль для обробки перекладів.

`utils`

> Різноманітні допоміжні інструменти.

`vcs`

> Абстракція системи керування версіями.

`wladmin`

> Налаштовування адміністративного інтерфейсу Django.

## Translation sources

A unit has a canonical file source and may have a translation from another
language as its effective source. Keep `Unit.source` and `Unit.source_unit`
canonical: repository synchronization and file formats depend on this. Use
`effective_source` and its language and plural accessors for content shown to
translators. Do not replace `source` on a copied unit to simulate an effective
source; other fields and related objects still describe the canonical source.

Use `Unit.source_snapshot` when an operation needs to preserve the source text,
language, plural rules, and terminology metadata together. Its `identity` defines source changes for
dependency reconciliation, editor conflict detection, and AI diagnostics. For
historical rendering and reports, read the snapshot recorded on the change,
rather than reconstructing it from the current unit.

A missing configured parent remains a custom source: its text is empty, its
language is retained, and its child is blocked. `effective_source_unit` is
then `None`. Only removing the workflow or selecting the canonical language
restores the canonical source.

Text-only accessors do not load language or plural metadata. For batch consumers
that need the complete effective source, use
`UnitQuerySet.prefetch_translation_parent()` alongside their existing unit
prefetches. `prefetch_source()` already includes this. Ordinary searches keep
the canonical query path and ordinary units retain their existing content hashes.

Source-dependent writes enter `source_operation()` before locking unit rows.
The outer operation takes a shared project gate and reads its workflow mapping
in one database round trip, including for projects without custom workflows.
Workflow changes take `source_project_gate(..., exclusive=True)` before
validation or persistence. Configuration changes affecting several projects
acquire their gates in ascending project ID order. Never upgrade a shared gate
to an exclusive one inside an operation.

The database gate function locks first and reads workflows in a separate
statement, so a waiter sees configuration committed while it waited. Write paths
use this transaction-scoped view rather than cached model settings. Nested
operations reuse it; rolled-back savepoints discard their dependency work.
Queued dependencies are reconciled before commit and external memory updates
are scheduled after commit. Source-change history is written in bulk, preserving
individual records while batching their notification dispatch.

Acquire any required repository locks before project gates, then component and
unit row locks. Reconciliation itself only changes database state and does not
acquire repository locks. Apply this boundary to bulk imports, automatic
translation, file-save failures, deletion, and restoration as well as editor
writes. Language and plural-rule changes require exclusive gates before their
updates. Historical migrations use historical models without these runtime
helpers.

Machinery source selection happens before mapping language codes to a provider.
Use `get_unit_source_language()` for translation and `uses_custom_source()`
for workflow-specific glossary handling. Provider codes can merge distinct
language variants, so code equality cannot determine whether a workflow source
was selected. Explicit component or secondary source selection takes precedence
over the workflow source.

<a id="background-tasks-internals"></a>

## Внутрішні функції фонових завдань

#### HINT
У цьому розділі описано внутрішню роботу завдань Celery. [Фонові завдання з використанням Celery](https://docs.weblate.org/uk/latest/admin/install.md#celery) описує, як налаштувати Celery для виконання завдань.

Weblate використовує Celery для виконання завдань у фоновому режимі. Деякі завдання запускаються подіями, а деякі – за розкладом.

Celery Beat використовується для планування завдань, а django-celery-beat використовується для зберігання періодичного розкладу завдань у базі даних. Розклад завдань налаштовується у файлі `tasks.py` у кожному з застосунків Django.

Завдання виконуються за допомогою кількох черг; маршрутизація налаштовується у `settings.py`. Черги були розроблені для розділення різних типів робочого навантаження:

`celery`
: Черга за замовчуванням, де обробляються фонові завдання.

`notify`
: Надсилає електронні листи зі сповіщеннями як для подій у Weblate, так і для автентифікації чи реєстрації. Це окрема черга, яка забезпечує безперебійну доставку електронної пошти, навіть якщо є затримка з виконанням інших завдань.

`memory`
: Оновлює записи пам’яті перекладів. Черга оновлення може бути довгою під час імпорту нових рядків, і тривала обробка тут не має великого значення, тому наявність окремої черги дозволяє уникнути блокування інших завдань.

`backup`
: Завдання резервного копіювання не можуть виконуватися паралельно, і один виділений виконавець спрощує це.

`translate`
: Відомо, що завдання автоматичного перекладу тривають довго, оскільки вони залучають зовнішні сервіси.
