forked from dlang/cdcdb
Русификация DDoc и сообщений
This commit is contained in:
parent
49ee7a4053
commit
f34b26c2b5
7 changed files with 387 additions and 361 deletions
82
README.md
82
README.md
|
@ -1,66 +1,42 @@
|
|||
# cdcdb
|
||||
|
||||
A library for storing and managing snapshots of textual data in an SQLite database. It uses content-defined chunking (CDC) based on the FastCDC algorithm to split data into variable-size chunks for efficient deduplication. Supports optional Zstd compression, transactions, and end-to-end integrity verification via SHA-256. Primary use cases: backups and versioning of text files while minimizing storage footprint.
|
||||
Библиотека для версионирования и хранения данных в SQLite с опорой на content-defined chunking (CDC). Алгоритм **FastCDC** используется для разбиения входного потока на чанки переменного размера, что обеспечивает эффективную дедупликацию и экономию места. Поддерживаются опциональное сжатие **Zstd**, транзакции и проверка целостности на основе **SHA-256**. Дополнительно фиксируется контекст выполнения при создании снимков (UID, RUID, процесс). Основные сценарии применения — резервное копирование и контроль версий файлов.
|
||||
|
||||
## FastCDC algorithm
|
||||
FastCDC splits data into variable-size chunks using content hashing. A Gear table is used to compute rolling “fingerprints” and choose cut points while respecting minimum, target, and maximum chunk sizes. This efficiently detects changes and stores only unique chunks, reducing storage usage.
|
||||
## Алгоритм FastCDC
|
||||
**FastCDC** — это алгоритм разделения данных на чанки переменной длины, основанный на скользящем хэшировании содержимого. Он использует таблицу **Gear** для вычисления "отпечатков" данных и выбирает точки разреза с учётом минимального, целевого и максимального размеров чанка. Такой подход позволяет эффективно выявлять изменения и сохранять только уникальные части данных.
|
||||
|
||||
## Core classes
|
||||
## Архитектура и основные компоненты
|
||||
|
||||
### Storage
|
||||
High-level API for the SQLite store and snapshot management.
|
||||
Библиотека разделена на несколько уровней:
|
||||
|
||||
- **Constructor**: Initializes a connection to SQLite.
|
||||
- **Methods**:
|
||||
- `newSnapshot`: Creates a snapshot. Returns a `Snapshot` object or `null` if the data matches the latest snapshot.
|
||||
- `getSnapshots`: Returns a list of snapshots (all, or filtered by label). Returns an array of `Snapshot`.
|
||||
- `getSnapshot`: Fetches a snapshot by ID. Returns a `Snapshot`.
|
||||
- `setupCDC`: Configures CDC splitting parameters. Returns nothing.
|
||||
- `removeSnapshots`: Deletes snapshots by label, ID, or a `Snapshot` object. Returns the number of deleted snapshots (for label) or `true`/`false` (for ID or object).
|
||||
- `getVersion`: Returns the library version string.
|
||||
- **Storage** — фасад для работы с БД SQLite. Отвечает за разбиение данных (FastCDC), сохранение/удаление снимков, управление блобами и транзакциями.
|
||||
- **Snapshot** — объект-ссылка на конкретный снимок. Предоставляет доступ к данным (буфером или потоково), а также к метаданным и операциям удаления.
|
||||
- **Context** — структура с параметрами окружения (UID, RUID, имена пользователей, процесс), передаваемыми при создании снимка.
|
||||
|
||||
### Snapshot
|
||||
Work with an individual snapshot.
|
||||
|
||||
- **Constructor**: Creates a snapshot handle by its ID.
|
||||
- **Methods**:
|
||||
- `data`: Restores full snapshot data. Returns a byte array (`ubyte[]`).
|
||||
- `data`: Streams restored data via a delegate sink. Returns nothing.
|
||||
- `remove`: Deletes the snapshot from the database. Returns `true` on success, otherwise `false`.
|
||||
|
||||
- **Properties**:
|
||||
- `id`: Snapshot ID (`long`).
|
||||
- `label`: Snapshot label (`string`).
|
||||
- `created`: Creation timestamp (UTC, `DateTime`).
|
||||
- `length`: Original data length (`long`).
|
||||
- `sha256`: Data SHA-256 hash (`ubyte[32]`).
|
||||
- `status`: Snapshot status (`"pending"` or `"ready"`).
|
||||
- `description`: Snapshot description (`string`).
|
||||
|
||||
## Example
|
||||
## Пример использования
|
||||
```d
|
||||
import cdcdb;
|
||||
|
||||
import std.stdio : writeln, File;
|
||||
import std.file : exists, remove;
|
||||
|
||||
void main()
|
||||
{
|
||||
// Create DB
|
||||
string dbPath = "example.db";
|
||||
|
||||
// Initialize Storage with Zstd compression
|
||||
// Storage с Zstd-сжатием
|
||||
auto storage = new Storage(dbPath, true, 22);
|
||||
|
||||
// Create a snapshot
|
||||
// Контекст
|
||||
Context ctx = Context(1000, 1000, "user", "user", "example");
|
||||
|
||||
// Новый снимок
|
||||
ubyte[] data = cast(ubyte[]) "Hello, cdcdb!".dup;
|
||||
auto snap = storage.newSnapshot("example_file", data, "Version 1.0");
|
||||
auto snap = storage.newSnapshot("example_file", data, ctx, "Версия 1.0");
|
||||
if (snap)
|
||||
{
|
||||
writeln("Snapshot created: ID=", snap.id, ", Label=", snap.label);
|
||||
writeln("Создан снимок: ID=", snap.id, ", Файл=", snap.file);
|
||||
}
|
||||
|
||||
// Restore data
|
||||
// Восстановление через потоковую запись
|
||||
auto snapshots = storage.getSnapshots("example_file");
|
||||
if (snapshots.length > 0)
|
||||
{
|
||||
|
@ -68,35 +44,25 @@ void main()
|
|||
File outFile = File("restored.txt", "wb");
|
||||
lastSnap.data((const(ubyte)[] chunk) => outFile.rawWrite(chunk));
|
||||
outFile.close();
|
||||
writeln("Data restored to restored.txt");
|
||||
writeln("Данные восстановлены в restored.txt");
|
||||
}
|
||||
|
||||
// Delete snapshots
|
||||
// Удаление
|
||||
long deleted = storage.removeSnapshots("example_file");
|
||||
writeln("Deleted snapshots: ", deleted);
|
||||
writeln("Удалено снимков: ", deleted);
|
||||
}
|
||||
```
|
||||
|
||||
## Tools
|
||||
## Инструменты
|
||||
|
||||
The `tools` directory contains a small D script for generating a Gear table used by FastCDC. It lets you build custom hash tables to tune splitting behavior. To generate a new table:
|
||||
В директории `tools` есть скрипт на D для генерации таблицы Gear, используемой FastCDC.
|
||||
Чтобы создать новую таблицу:
|
||||
|
||||
```bash
|
||||
chmod +x ./tools/gen.d
|
||||
./tools/gen.d > ./source/gear.d
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
* **In `dub.json`**:
|
||||
|
||||
```json
|
||||
"dependencies": {
|
||||
"cdcdb": "~>0.1.0"
|
||||
}
|
||||
```
|
||||
* **Build**: `dub build`.
|
||||
|
||||
## License
|
||||
## Лицензия
|
||||
|
||||
Boost Software License 1.0 (BSL-1.0).
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue