1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
use crate::{CounterComparator, DistkitError, DistkitRedisKey};
/// Async interface for distributed counter operations.
///
/// Both [`StrictCounter`](super::StrictCounter) and
/// [`LaxCounter`](super::LaxCounter) implement this trait, so generic code
/// can work with either.
#[async_trait::async_trait]
pub trait CounterTrait {
/// Increments the counter by `count` and returns the new total.
///
/// A negative `count` decrements. Passing `0` returns the current value
/// without modification.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("visits".to_string())?;
/// assert_eq!(counter.inc(&key, 1).await?, 1);
/// assert_eq!(counter.inc(&key, 9).await?, 10);
/// // Negative count is the same as calling dec.
/// assert_eq!(counter.inc(&key, -3).await?, 7);
/// # Ok(())
/// # }
/// ```
async fn inc(&self, key: &DistkitRedisKey, count: i64) -> Result<i64, DistkitError>;
/// Conditionally increments the counter by `count` when the current value
/// satisfies `comparator`.
///
/// Returns the updated total on success, or the current total unchanged
/// when the condition fails.
///
/// # Examples
///
/// ```rust
/// # use distkit::{CounterComparator, DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("inventory".to_string())?;
/// counter.set(&key, 10).await?;
///
/// assert_eq!(
/// counter.inc_if(&key, CounterComparator::Eq(10), 5).await?,
/// 15
/// );
/// assert_eq!(
/// counter.inc_if(&key, CounterComparator::Lt(10), 5).await?,
/// 15
/// );
/// assert_eq!(
/// counter.inc_if(&key, CounterComparator::Nil, 5).await?,
/// 20
/// );
/// # Ok(())
/// # }
/// ```
async fn inc_if(
&self,
key: &DistkitRedisKey,
comparator: CounterComparator,
count: i64,
) -> Result<i64, DistkitError>;
/// Decrements the counter by `count` and returns the new total.
///
/// Equivalent to `inc(key, -count)`. Counters can go negative.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("tokens".to_string())?;
/// counter.set(&key, 10).await?;
/// assert_eq!(counter.dec(&key, 3).await?, 7);
/// // Counters can go negative.
/// assert_eq!(counter.dec(&key, 100).await?, -93);
/// # Ok(())
/// # }
/// ```
async fn dec(&self, key: &DistkitRedisKey, count: i64) -> Result<i64, DistkitError>;
/// Returns the current value of the counter, or `0` if the key does not
/// exist.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("visits".to_string())?;
/// // A key that does not exist returns 0.
/// assert_eq!(counter.get(&key).await?, 0);
/// counter.inc(&key, 5).await?;
/// assert_eq!(counter.get(&key).await?, 5);
/// # Ok(())
/// # }
/// ```
async fn get(&self, key: &DistkitRedisKey) -> Result<i64, DistkitError>;
/// Sets the counter to an exact value, overwriting any previous state.
/// Returns the value that was set.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("inventory".to_string())?;
/// counter.inc(&key, 1000).await?;
/// // Overwrite with an authoritative count.
/// assert_eq!(counter.set(&key, 850).await?, 850);
/// assert_eq!(counter.get(&key).await?, 850);
/// # Ok(())
/// # }
/// ```
async fn set(&self, key: &DistkitRedisKey, count: i64) -> Result<i64, DistkitError>;
/// Conditionally sets the counter to `count` when the current value
/// satisfies `comparator`.
///
/// Returns the value after evaluation: `count` when the write applied, or
/// the current total unchanged when the condition failed.
///
/// # Examples
///
/// ```rust
/// # use distkit::{CounterComparator, DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("inventory".to_string())?;
/// counter.set(&key, 10).await?;
///
/// assert_eq!(
/// counter.set_if(&key, CounterComparator::Gt(5), 25).await?,
/// 25
/// );
/// assert_eq!(
/// counter.set_if(&key, CounterComparator::Eq(10), 50).await?,
/// 25
/// );
/// assert_eq!(
/// counter.set_if(&key, CounterComparator::Nil, 40).await?,
/// 40
/// );
/// # Ok(())
/// # }
/// ```
async fn set_if(
&self,
key: &DistkitRedisKey,
comparator: CounterComparator,
count: i64,
) -> Result<i64, DistkitError>;
/// Deletes the counter and returns the value it held before deletion.
/// Returns `0` if the key did not exist.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let key = DistkitRedisKey::try_from("session".to_string())?;
/// counter.set(&key, 42).await?;
/// assert_eq!(counter.del(&key).await?, 42);
/// // After deletion the key reads back as 0.
/// assert_eq!(counter.get(&key).await?, 0);
/// // Deleting a non-existent key returns 0.
/// assert_eq!(counter.del(&key).await?, 0);
/// # Ok(())
/// # }
/// ```
async fn del(&self, key: &DistkitRedisKey) -> Result<i64, DistkitError>;
/// Removes all counters under the current prefix.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let k1 = DistkitRedisKey::try_from("a".to_string())?;
/// let k2 = DistkitRedisKey::try_from("b".to_string())?;
/// counter.set(&k1, 10).await?;
/// counter.set(&k2, 20).await?;
/// counter.clear().await?;
/// assert_eq!(counter.get(&k1).await?, 0);
/// assert_eq!(counter.get(&k2).await?, 0);
/// # Ok(())
/// # }
/// ```
async fn clear(&self) -> Result<(), DistkitError>;
/// Returns `(key, value)` for each key in `keys`, in the same order.
/// A missing key returns `(key, 0)`.
async fn get_all<'k>(
&self,
keys: &[&'k DistkitRedisKey],
) -> Result<Vec<(&'k DistkitRedisKey, i64)>, DistkitError>;
/// Increments each `(key, delta)` pair and returns `(key, new_total)` in
/// the same order.
///
/// Duplicate keys are processed sequentially in input order, so later
/// entries observe earlier same-call updates.
///
/// # Examples
///
/// ```rust
/// # use distkit::{DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let k1 = DistkitRedisKey::try_from("a".to_string())?;
/// let k2 = DistkitRedisKey::try_from("b".to_string())?;
///
/// let results = counter.inc_all(&[(&k1, 3), (&k2, 5)]).await?;
///
/// assert_eq!(results, vec![(&k1, 3), (&k2, 5)]);
/// # Ok(())
/// # }
/// ```
async fn inc_all<'k>(
&self,
updates: &[(&'k DistkitRedisKey, i64)],
) -> Result<Vec<(&'k DistkitRedisKey, i64)>, DistkitError>;
/// Conditionally increments each `(key, delta)` pair when the current
/// value satisfies the corresponding comparator.
///
/// Each tuple is `(key, comparator, delta)`. Evaluation is per-item,
/// results preserve input order, and duplicate keys are processed
/// sequentially in input order. Use [`CounterComparator::Nil`] for
/// unconditional entries in a mixed batch.
///
/// # Examples
///
/// ```rust
/// # use distkit::{CounterComparator, DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let k1 = DistkitRedisKey::try_from("a".to_string())?;
/// let k2 = DistkitRedisKey::try_from("b".to_string())?;
/// counter.set(&k1, 10).await?;
///
/// let results = counter
/// .inc_all_if(&[
/// (&k1, CounterComparator::Eq(10), 5),
/// (&k2, CounterComparator::Nil, 2),
/// ])
/// .await?;
///
/// assert_eq!(results, vec![(&k1, 15), (&k2, 2)]);
/// # Ok(())
/// # }
/// ```
async fn inc_all_if<'k>(
&self,
updates: &[(&'k DistkitRedisKey, CounterComparator, i64)],
) -> Result<Vec<(&'k DistkitRedisKey, i64)>, DistkitError>;
/// Sets each `(key, count)` pair and returns `(key, count)` in the same
/// order. Semantics match `set` for each individual key.
async fn set_all<'k>(
&self,
updates: &[(&'k DistkitRedisKey, i64)],
) -> Result<Vec<(&'k DistkitRedisKey, i64)>, DistkitError>;
/// Conditionally sets each `(key, count)` pair when the current value
/// satisfies the corresponding comparator.
///
/// Each tuple is `(key, comparator, count)`. Evaluation is per-item and
/// results preserve input order. Use [`CounterComparator::Nil`] for
/// unconditional entries in a mixed batch.
///
/// # Examples
///
/// ```rust
/// # use distkit::{CounterComparator, DistkitRedisKey, counter::CounterTrait};
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let counter = distkit::__doctest_helpers::strict_counter().await?;
/// let k1 = DistkitRedisKey::try_from("a".to_string())?;
/// let k2 = DistkitRedisKey::try_from("b".to_string())?;
/// counter.set(&k1, 10).await?;
///
/// let results = counter
/// .set_all_if(&[
/// (&k1, CounterComparator::Eq(10), 15),
/// (&k2, CounterComparator::Nil, 20),
/// ])
/// .await?;
///
/// assert_eq!(results, vec![(&k1, 15), (&k2, 20)]);
/// # Ok(())
/// # }
/// ```
async fn set_all_if<'k>(
&self,
updates: &[(&'k DistkitRedisKey, CounterComparator, i64)],
) -> Result<Vec<(&'k DistkitRedisKey, i64)>, DistkitError>;
}