hive_btle/sync/mod.rs
1// Copyright (c) 2025-2026 (r)evolve - Revolve Team LLC
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! HIVE-Lite Sync Protocol
17//!
18//! Efficient CRDT synchronization over BLE GATT characteristics.
19//!
20//! ## Overview
21//!
22//! This module provides the sync layer for HIVE-Lite nodes, enabling
23//! efficient state synchronization over bandwidth-constrained BLE links.
24//!
25//! ## Key Components
26//!
27//! - **CRDTs**: Conflict-free replicated data types (LWW-Register, G-Counter)
28//! - **Batching**: Accumulates changes to reduce radio activity
29//! - **Delta Encoding**: Only sends changes since last sync
30//! - **Chunking**: Splits large messages across MTU boundaries
31//!
32//! ## Architecture
33//!
34//! ```text
35//! ┌────────────────────────────────────────────────────┐
36//! │ Application │
37//! │ (position updates, health status, alerts) │
38//! └─────────────────────┬──────────────────────────────┘
39//! │
40//! ▼
41//! ┌────────────────────────────────────────────────────┐
42//! │ GattSyncProtocol │
43//! │ ┌──────────────┐ ┌────────────┐ ┌────────────┐ │
44//! │ │ Batch │ │ Delta │ │ Chunked │ │
45//! │ │ Accumulator │─▶│ Encoder │─▶│ Transfer │ │
46//! │ └──────────────┘ └────────────┘ └────────────┘ │
47//! └─────────────────────┬──────────────────────────────┘
48//! │
49//! ▼
50//! ┌────────────────────────────────────────────────────┐
51//! │ GATT Characteristics │
52//! │ (Sync Data, Sync State) │
53//! └────────────────────────────────────────────────────┘
54//! ```
55//!
56//! ## Usage
57//!
58//! ```ignore
59//! use hive_btle::sync::{GattSyncProtocol, SyncConfig, CrdtOperation, Position};
60//! use hive_btle::NodeId;
61//!
62//! // Create sync protocol
63//! let mut sync = GattSyncProtocol::new(
64//! NodeId::new(0x12345678),
65//! SyncConfig::default(),
66//! );
67//!
68//! // Add a peer
69//! sync.add_peer(&peer_id);
70//!
71//! // Queue position update
72//! sync.queue_operation(CrdtOperation::UpdatePosition {
73//! node_id: my_node_id,
74//! position: Position::new(37.7749, -122.4194),
75//! timestamp: current_time_ms,
76//! });
77//!
78//! // Check if time to sync
79//! if sync.should_sync() {
80//! let chunks = sync.prepare_sync(&peer_id);
81//! for chunk in chunks {
82//! // Write chunk to GATT characteristic
83//! gatt.write_sync_data(&chunk.encode());
84//! }
85//! }
86//!
87//! // Process received data
88//! if let Some(ops) = sync.process_received(chunk, &peer_id) {
89//! for op in ops {
90//! // Apply CRDT operation to local state
91//! apply_operation(op);
92//! }
93//! }
94//! ```
95//!
96//! ## Power Efficiency
97//!
98//! The sync protocol is designed for constrained devices:
99//!
100//! | Feature | Benefit |
101//! |---------|---------|
102//! | Batching | Reduces sync frequency (less radio time) |
103//! | Delta Encoding | Sends only changes (less bytes) |
104//! | Configurable Intervals | Trade freshness for battery |
105//! | Compact CRDT Encoding | Minimal overhead |
106//!
107//! ## Sync Profiles
108//!
109//! ```ignore
110//! // For smartwatch (battery critical)
111//! let config = SyncConfig::low_power();
112//!
113//! // For tablet (responsiveness preferred)
114//! let config = SyncConfig::responsive();
115//! ```
116
117pub mod batch;
118pub mod crdt;
119pub mod delta;
120pub mod delta_document;
121pub mod protocol;
122
123pub use batch::{BatchAccumulator, BatchConfig, OperationBatch};
124pub use crdt::{
125 ChatCRDT, ChatMessage, CrdtOperation, EventType, GCounter, HealthStatus, LwwRegister,
126 Peripheral, PeripheralEvent, PeripheralType, Position, Timestamp, CHAT_MAX_MESSAGES,
127 CHAT_MAX_SENDER_LEN, CHAT_MAX_TEXT_LEN,
128};
129pub use delta::{DeltaEncoder, DeltaStats, PeerSyncState, VectorClock};
130pub use delta_document::{DeltaDocument, DeltaFlags, Operation, DELTA_DOCUMENT_MARKER};
131pub use protocol::{
132 chunk_data, ChunkHeader, ChunkReassembler, GattSyncProtocol, SyncChunk, SyncConfig, SyncState,
133 SyncStats, CHUNK_HEADER_SIZE, DEFAULT_MTU, MAX_MTU,
134};