delta_stream/api.rs
1use std::marker::PhantomData;
2
3use crate::{
4 adaptive::{AdaptivePolicy, EncodeDecision},
5 error::DeltaError,
6 migration::MigrationRegistry,
7 packet::{DecodeConfig, Packet},
8 schema::DeltaState,
9 sync::{GenericApplyResult, GenericDecoder, GenericEncoder},
10};
11
12/// Publishes application-state updates as DeltaStream packets or bytes.
13///
14/// A publisher owns the sending side of one state stream. It observes each new
15/// application state and emits either a snapshot or a delta packet according to
16/// the configured adaptive policy. The usual flow is:
17///
18/// `application state -> Publisher -> snapshot or delta packet -> serialized bytes`.
19///
20/// Use [`Publisher::encode`] for the simple byte-oriented API, or [`Publisher::update`]
21/// when an integration needs direct access to packet metadata before serialization.
22///
23/// # Example
24///
25/// ```
26/// use delta_stream::{DeltaState, Publisher};
27/// use serde::{Deserialize, Serialize};
28///
29/// #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, DeltaState)]
30/// struct State {
31/// progress: u8,
32/// }
33///
34/// # fn main() -> Result<(), delta_stream::DeltaError> {
35/// let mut publisher = Publisher::<State>::new();
36/// let bytes = publisher.encode(&State { progress: 10 })?;
37/// assert!(!bytes.is_empty());
38/// # Ok(())
39/// # }
40/// ```
41pub struct StatePublisher<T: DeltaState> {
42 encoder: GenericEncoder<T>,
43}
44
45impl<T: DeltaState> Default for StatePublisher<T> {
46 fn default() -> Self {
47 Self {
48 encoder: GenericEncoder::default(),
49 }
50 }
51}
52
53impl<T: DeltaState> StatePublisher<T> {
54 /// Creates a publisher with the default adaptive policy.
55 pub fn new() -> Self {
56 Self::default()
57 }
58
59 /// Starts building a publisher with custom settings.
60 pub fn builder() -> PublisherBuilder<T> {
61 PublisherBuilder::default()
62 }
63
64 /// Creates a publisher with an explicit adaptive encoding policy.
65 pub fn with_policy(policy: AdaptivePolicy) -> Self {
66 Self {
67 encoder: GenericEncoder::with_policy(policy),
68 }
69 }
70
71 /// Encodes a new authoritative state into transport-independent bytes.
72 ///
73 /// This is the high-level publishing path. It creates either a snapshot or delta
74 /// with the same logic as [`Publisher::update`], then serializes that packet with
75 /// [`Packet::to_bytes`]. The returned bytes can be carried by any byte-capable
76 /// transport, including TCP, WebSocket, PubNub, MQTT, NATS, UDP with reliability
77 /// handled externally, files, IPC, or an in-memory channel.
78 pub fn encode(&mut self, state: &T) -> Result<Vec<u8>, DeltaError> {
79 self.update(state)?.to_bytes()
80 }
81
82 /// Encodes a new authoritative state as a packet.
83 ///
84 /// The first update is a snapshot. Later updates may be deltas or snapshots, and
85 /// raw or zstd-compressed, depending on the active [`AdaptivePolicy`]. This method
86 /// preserves the stream sequence, schema hash, base hash, and compression behavior
87 /// used by the lower-level packet API.
88 pub fn update(&mut self, state: &T) -> Result<Packet, DeltaError> {
89 self.encoder.encode(state)
90 }
91
92 /// Forces a new snapshot and advances the stream sequence.
93 pub fn force_snapshot(&mut self, state: &T) -> Result<Packet, DeltaError> {
94 self.encoder.force_snapshot(state)
95 }
96
97 /// Builds a recovery snapshot at the current stream sequence.
98 ///
99 /// This does not advance the publisher sequence, so recovering one client does not
100 /// create a sequence gap for healthy clients.
101 pub fn recovery_snapshot(&self, state: &T) -> Result<Packet, DeltaError> {
102 self.encoder.recovery_snapshot(state)
103 }
104
105 /// Returns the current publisher sequence.
106 pub fn sequence(&self) -> u64 {
107 self.encoder.sequence()
108 }
109
110 /// Returns the most recent adaptive encoding decision, if one exists.
111 pub fn last_decision(&self) -> Option<EncodeDecision> {
112 self.encoder.last_decision()
113 }
114}
115
116/// Builder for [`StatePublisher`].
117pub struct PublisherBuilder<T: DeltaState> {
118 policy: AdaptivePolicy,
119 _marker: PhantomData<T>,
120}
121
122impl<T: DeltaState> Default for PublisherBuilder<T> {
123 fn default() -> Self {
124 Self {
125 policy: AdaptivePolicy::default(),
126 _marker: PhantomData,
127 }
128 }
129}
130
131impl<T: DeltaState> PublisherBuilder<T> {
132 /// Replaces the adaptive encoding policy.
133 pub fn adaptive_policy(mut self, policy: AdaptivePolicy) -> Self {
134 self.policy = policy;
135 self
136 }
137
138 /// Enables or disables zstd candidate selection.
139 pub fn compression(mut self, enabled: bool) -> Self {
140 self.policy.enable_zstd = enabled;
141 self
142 }
143
144 /// Sets the zstd compression level used for compressed candidates.
145 pub fn zstd_level(mut self, level: i32) -> Self {
146 self.policy.zstd_level = level;
147 self
148 }
149
150 /// Builds the publisher.
151 pub fn build(self) -> StatePublisher<T> {
152 StatePublisher::with_policy(self.policy)
153 }
154}
155
156/// Receives and applies DeltaStream packets for one application-state stream.
157///
158/// A subscriber owns the receiving side of a stream. The usual flow is:
159///
160/// `serialized bytes -> Subscriber -> validated synchronized state`.
161///
162/// It validates schema identity, sequence/base-state relationships, duplicate and stale
163/// packets, packet integrity, and decompression limits before committing a new state.
164pub struct StateSubscriber<T: DeltaState> {
165 decoder: GenericDecoder<T>,
166 decode_config: DecodeConfig,
167}
168
169impl<T: DeltaState> Default for StateSubscriber<T> {
170 fn default() -> Self {
171 let decode_config = DecodeConfig::default();
172 Self {
173 decoder: GenericDecoder::with_decode_config(decode_config),
174 decode_config,
175 }
176 }
177}
178
179impl<T: DeltaState> StateSubscriber<T> {
180 /// Creates an empty subscriber.
181 pub fn new() -> Self {
182 Self::default()
183 }
184
185 /// Creates an empty subscriber with explicit packet decoding limits.
186 pub fn with_decode_config(decode_config: DecodeConfig) -> Self {
187 Self {
188 decoder: GenericDecoder::with_decode_config(decode_config),
189 decode_config,
190 }
191 }
192
193 /// Receives transport bytes, decodes a packet, and applies it.
194 ///
195 /// This is the high-level receiving path. It parses bytes with
196 /// [`Packet::from_bytes_with_config`], validates packet integrity, decompresses within
197 /// configured limits when needed, and then applies the packet with the same state-chain
198 /// logic as [`Subscriber::apply`]. It may apply a new state, report a duplicate, or
199 /// request a snapshot when a gap or incompatible base is detected.
200 pub fn receive(&mut self, bytes: &[u8]) -> Result<GenericApplyResult<T>, DeltaError> {
201 let packet = Packet::from_bytes_with_config(bytes, &self.decode_config)?;
202 self.apply(packet)
203 }
204
205 /// Applies a snapshot or delta packet.
206 ///
207 /// Snapshots establish or restore state. Deltas are committed only when the local
208 /// sequence and base-state hash match the packet metadata. Rejected packets do not
209 /// mutate the subscriber state.
210 pub fn apply(&mut self, packet: Packet) -> Result<GenericApplyResult<T>, DeltaError> {
211 self.decoder.apply_packet(packet)
212 }
213
214 /// Applies a packet and allows registered snapshot migrations when schemas differ.
215 pub fn apply_with_migrations(
216 &mut self,
217 packet: Packet,
218 migrations: &MigrationRegistry,
219 ) -> Result<GenericApplyResult<T>, DeltaError> {
220 self.decoder
221 .apply_packet_with_migrations(packet, migrations)
222 }
223
224 /// Returns the last synchronized state.
225 pub fn state(&self) -> Option<&T> {
226 self.decoder.state()
227 }
228
229 /// Returns the last applied sequence.
230 pub fn sequence(&self) -> Option<u64> {
231 self.decoder.sequence()
232 }
233
234 /// Clears local state and sequence tracking.
235 pub fn reset(&mut self) {
236 self.decoder = GenericDecoder::with_decode_config(self.decode_config);
237 }
238}
239
240/// Short public name for [`StatePublisher`].
241pub type Publisher<T> = StatePublisher<T>;
242
243/// Short public name for [`StateSubscriber`].
244pub type Subscriber<T> = StateSubscriber<T>;