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
//! Gatling (ordered streaming sink) — the **item-oriented** sibling of the byte
//! streaming engine, for a labelled-discrete-entry pipeline.
//!
//! Where [`crate::gatling::run`] / [`run_typed`](crate::gatling::run_typed) own
//! the reader and *split* one byte stream into segments, this variant does **no
//! reading and no splitting**. The caller stays the producer: it yields discrete
//! **labelled items** `(Label, Input)` (e.g. znippy's io_uring batched small-file
//! reader handing over `(path, bytes)`), the engine fans them across N workers
//! that run a caller `map`, and the outputs are streamed to a caller [`OrderedSink`]
//! in **producer order** through a **bounded** reorder buffer.
//!
//! ```text
//! Producer.next() → [dispatch] → N Workers(map) → [collector: reorder] → Sink.emit(seq, out)
//! ▲ pulled only when a permit is free (≤ cap items alive) │
//! └──────────────── permit released after each in-order emit ───────────┘
//! ```
//!
//! # The gatling soul, kept
//! - **No barrier / self-dispatch.** Workers pull the next item the instant they
//! finish the last one (LPT) — never a static chunk-per-worker carve-up. A slow
//! item never idles a sibling.
//! - **rayon-free.** Pure `std::thread::scope` + `std::sync::mpsc`; no global pool.
//! - **Ordered out.** The collector emits strictly in producer sequence, so the
//! sink can `pwrite` to an archive and record offsets/metadata incrementally.
//!
//! # What this variant adds over the existing API
//! - **Lazy pull + backpressure.** The producer is pulled **only when a worker
//! slot is free** — at most `cap` items are *alive* (pulled-but-not-yet-emitted)
//! at any instant. A single counting-permit pool (primed with `cap` tokens)
//! gates the producer: acquire a permit before pulling, release it after the
//! item is emitted. Memory is bounded by `cap`, not by the input length.
//! - **Streaming sink, never a RAM `Vec`.** Outputs are handed to the sink one at
//! a time as each in-order output becomes ready; the reorder buffer holds at
//! most `cap` outputs, so a slow item near the front applies backpressure to the
//! producer instead of letting the buffer grow without bound.
//! - **Deterministic.** Same producer sequence + same `map` ⇒ identical ordered
//! output for any worker count (emit order is the producer order, `map` is pure).
//!
//! # Example
//! ```
//! use gatling::gatling::ordered::{run_ordered_sink, OrderedSink};
//!
//! // Producer: 100 labelled items, pulled lazily.
//! let mut next = 0usize;
//! let producer = move || {
//! if next < 100 { let i = next; next += 1; Some((i, vec![i as u8; 4])) }
//! else { None }
//! };
//!
//! // Sink: collect outputs in producer order.
//! let mut out: Vec<(u64, usize)> = Vec::new();
//! run_ordered_sink(
//! producer,
//! /* workers */ 8,
//! /* cap */ 16,
//! /* map */ |label: usize, bytes: Vec<u8>| (label, bytes.len()),
//! /* sink */ &mut |seq, (label, len)| { out.push((seq, label)); let _ = len; Ok(()) },
//! ).unwrap();
//!
//! assert_eq!(out.len(), 100);
//! assert!(out.iter().enumerate().all(|(i, &(seq, label))| seq as usize == i && label == i));
//! ```
use HashMap;
use ;
use Result;
/// Streaming consumer of ordered outputs. The collector calls [`emit`](Self::emit)
/// exactly once per item, in **strict producer order** (`seq = 0, 1, 2, …`), as
/// each in-order output becomes ready. A `&mut` method, so the sink owns mutable
/// state (an archive writer, an offset table) and updates it incrementally — it is
/// never handed the whole output set at once.
///
/// A blanket impl is provided for `FnMut(u64, O) -> Result<()>`, so a closure can
/// be passed directly as the sink.
/// Run an **item-oriented, ordered, streaming-sink** gatling to completion.
///
/// - `producer` is pulled lazily — `next()`-style `FnMut` returning `Some((label,
/// input))` per item and `None` at end of stream. It is pulled **only when a
/// worker slot is free** (≤ `cap` items alive), so the caller's reader is itself
/// back-pressured and total memory is bounded by `cap`, never by stream length.
/// - `n_workers` map workers run `map(label, input) -> output` with no barrier
/// (self-dispatch: each pulls the next item as soon as it finishes its last).
/// - `cap` is the in-flight / reorder-buffer bound: the maximum number of items
/// that may be pulled-but-not-yet-emitted at once. `0` ⇒ `max(2 * n_workers, 1)`.
/// - `sink` receives outputs via [`OrderedSink::emit`] in strict producer order,
/// one at a time as they become ready — the reorder buffer holds ≤ `cap` outputs.
///
/// Determinism: same producer sequence + same `map` ⇒ identical ordered emit
/// sequence for any `n_workers`.
///
/// Threading: the collector runs on the **calling thread** (so `sink` need not be
/// `Send` and stays where the caller built it); the producer dispatch loop and the
/// `n_workers` map workers run on scoped threads joined before return.