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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! Bounded-concurrency terminal combinators for streams.
//!
//! [`for_each_concurrent`] and [`try_for_each_concurrent`] apply an async
//! function to every item of a stream with at most `limit` items in flight at
//! once.
//!
//! # Why these are not just `buffer_unordered(limit).for_each(..)`
//!
//! [`BufferUnordered`](super::BufferUnordered) holds *plain futures* that this
//! process polls inline. When it is dropped — on cancellation, on an early
//! return, on a `?` — those in-flight futures are dropped where they stand,
//! unpolled, with no cancellation signal and no cleanup budget. That is fine for
//! pure computation and wrong for work that holds obligations.
//!
//! The combinators here own **region tasks** instead. Every in-flight item is a
//! real child of the caller's region, so:
//!
//! - it participates in region-close quiescence — the region cannot close while
//! it runs;
//! - cancellation is delivered as the request → drain → finalize protocol
//! rather than a silent drop;
//! - the terminal [`Outcome`] of every member is *observed*, so a panicking or
//! cancelled item cannot vanish unnoticed.
//!
//! Both functions therefore end with an explicit drain: on cancellation, on the
//! first `Err`, and on the happy path, every member the set still owns is
//! cancelled and then **joined** before the function returns. No item is
//! abandoned in flight.
//!
//! # Cost of that guarantee
//!
//! Because members are real tasks, item values and item futures must be `Send +
//! 'static`, and the factory must be `Clone` so each member gets its own copy.
//! When the work is pure and cheap and no obligation is involved,
//! [`buffer_unordered`](super::StreamExt::buffer_unordered) remains the lighter
//! choice — it needs none of those bounds.
//!
//! # Observability
//!
//! Unlike the buffering combinators, these functions expose no
//! [`StreamTelemetrySnapshot`](super::StreamTelemetrySnapshot) accessor — a
//! deliberate decision, not an omission. They are async functions: the caller
//! holds no combinator object to snapshot while the call runs, and the two
//! ways to manufacture one (returning a handle instead of a plain future, or
//! threading a caller-supplied observer callback through the signature) would
//! reshape the public API of every call site to serve a diagnostic.
//!
//! The in-flight items do not need that instrument, because they are **region
//! tasks** — already visible to the runtime's own observability surfaces. Task
//! inspection reports their obligation holdings, poll counts, and cancellation
//! status; the lab oracles account for every member in quiescence and leak
//! checks; and each member's terminal [`Outcome`] is observed by the drive
//! loop rather than dropped. The buffering combinators need a snapshot API
//! precisely because their in-flight futures are *not* tasks and would
//! otherwise be invisible; these functions sit on the other side of that
//! trade.
use ;
use crateJoinSet;
use crateCx;
use crateyield_now;
use crateFailFast;
use crate;
use Infallible;
use Future;
/// Applies `f` to every item of `stream`, keeping at most `limit` items in
/// flight.
///
/// This is the bounded-parallelism "handle each item" pattern. Each item
/// becomes a region-owned task, so in-flight work is drained rather than
/// abandoned when the caller is cancelled.
///
/// The returned [`Outcome`] is `Ok(())` when every item completed. Its error
/// type is [`Infallible`] because the per-item future cannot fail — use
/// [`try_for_each_concurrent`] when it can. `Cancelled` and `Panicked` are still
/// reachable: the caller may be cancelled, and an item may panic.
///
/// # Example
///
/// ```ignore
/// use asupersync::stream::{for_each_concurrent, iter};
///
/// async fn fetch_all(cx: &asupersync::Cx, urls: Vec<String>) {
/// // At most 8 requests in flight, whatever the length of `urls`.
/// let outcome = for_each_concurrent(cx, iter(urls), 8, |item_cx, url| async move {
/// handle(&item_cx, url).await;
/// })
/// .await;
/// assert!(outcome.is_ok());
/// }
/// # async fn handle(_cx: &asupersync::Cx, _url: String) {}
/// ```
///
/// # Panics
///
/// Panics if `limit` is zero. A zero concurrency limit can make no progress, so
/// it is a caller bug rather than a runtime condition.
pub async
/// Applies fallible `f` to every item of `stream`, keeping at most `limit`
/// items in flight, and stops at the first failure.
///
/// # Short-circuit and drain
///
/// The first member to resolve non-`Ok` — `Err`, `Cancelled`, or `Panicked` —
/// stops admission of new items. Every member still in flight is then
/// **cancelled and joined** before this function returns. This drain-on-error
/// behaviour is the point of the combinator: the returned failure means "no
/// item of this stream is still running", not merely "one item failed and the
/// rest were abandoned".
///
/// The value returned is the *first* observed failure, not an aggregate. One
/// exception: if a member panics while being drained, the panic is reported
/// instead, because a panic is never an expected consequence of the
/// cancellation this function itself requested.
///
/// # Determinism
///
/// Completions are collected through [`JoinSet::join_next`], whose tie-break is
/// the earliest-spawned ready member. With a deterministic scheduler, the
/// reported first failure is therefore deterministic for a given schedule.
///
/// # Example
///
/// ```ignore
/// use asupersync::stream::{iter, try_for_each_concurrent};
/// use asupersync::Outcome;
///
/// async fn upload_all(cx: &asupersync::Cx, chunks: Vec<Vec<u8>>) -> Outcome<(), UploadError> {
/// // On the first failed chunk, the chunks still uploading are cancelled
/// // and joined before this returns - none is left running.
/// try_for_each_concurrent(cx, iter(chunks), 4, |item_cx, chunk| async move {
/// upload(&item_cx, chunk).await
/// })
/// .await
/// }
/// # struct UploadError;
/// # async fn upload(_cx: &asupersync::Cx, _c: Vec<u8>) -> Result<(), UploadError> { Ok(()) }
/// ```
///
/// # Panics
///
/// Panics if `limit` is zero.
pub async
/// Maps a member outcome to `Some(failure)` when it is not `Ok`.
/// Chooses what the combinator reports, given the first observed failure (if
/// any) and the outcomes of the drained members.
///
/// Rules, in order:
///
/// 1. A member that **panicked during drain** always wins. We asked those
/// members to cancel; a panic is not an expected response to that request,
/// so it is new information and must not be swallowed by the cancellation we
/// ourselves caused.
/// 2. Otherwise the first observed failure is reported unchanged. Drained
/// members are `Cancelled` because *we* cancelled them; reporting that back
/// would overwrite the real cause with our own reaction to it.
/// 3. Otherwise `Ok(())`.