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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Copyright (c) 2026 Super Durable, Inc.
//
// Licensed under the Sustainable Use License 1.0.
// You may not use this file except in compliance with the License.
// See the LICENSE file in the repository root.
//
// SPDX-License-Identifier: LicenseRef-Sustainable-Use-1.0
use ;
use cratevalidate_map_instance;
use crate::;
/// Identifies one round of a [`Join`] and the number of branches in that round.
///
/// [`Join::fork`] and [`Join::fork_with_round_key`] create the round. Pass the same value, unchanged,
/// to every branch Step, to the join Step, and to the next round's split Step when a loop resets the
/// Join. Treat it as an opaque token: the application never computes the key or the count itself.
///
/// A `JoinRound` is persisted inside Step inputs as the JSON object
/// `{"roundKey": string, "branchCount": integer}`. Every Dex SDK uses these field names, so a
/// round created by one SDK decodes in another. Deserializing a negative `branchCount` fails.
///
/// See [`Join`] for a complete example.
///
/// Since 1.44.0.
/// Synchronizes the parallel branches of one Flow by counting the results they report.
///
/// Use a Join when one Step starts several branches and a later Step must continue after all of
/// them, the first of them, or any `n` of them have finished. The Join produces the branch count and
/// the round key, so the application keeps no counter and no round number.
///
/// A round has three roles:
///
/// 1. The split Step calls [`Self::fork`] in `execute`. It passes one builder per branch and one
/// builder for the join Step. Each builder receives the round's [`JoinRound`] and returns a
/// [`StepMovement`]. Return the movements with [`StepDecision::go_to_many`].
/// 2. Each branch reports exactly one result. A single-Step branch returns [`Self::end_branch`]. A
/// branch that continues after reporting calls [`Self::report_branch_result`].
/// 3. The join Step waits in `wait_for` with [`Self::for_all_branches`], [`Self::for_first_branch`],
/// or [`Self::for_branches`]. Its `execute` reads the results with [`Self::branch_results`].
///
/// A Join is a [`ChannelMap`] of `T` with the same name. Each round uses its own instance, keyed by
/// [`JoinRound::round_key`]. A branch result is stored as the plain `T` value, so Dex Web,
/// pending-message reads, and Channel-map loads show and read the Join like any Channel map.
/// Results of another round never satisfy this round's condition. The conditions are ordinary
/// [`Condition`] values. Combine them with [`crate::Wait::all_of`], [`crate::Wait::any_of`], or
/// [`crate::Wait::any_combination_of`], for example with a [`crate::Timer`] as a deadline.
///
/// After a first-of-m or n-of-m join, the other branches still report. To reuse the Join in a loop,
/// reset the finished round, unless a cancelling join finished it. Pass its `JoinRound` to the next
/// round's split Step. That Step waits in `wait_for` with [`Self::for_remaining_branches`] and the
/// count the join consumed. Its `execute` can read the late results with
/// [`Self::remaining_branch_results`]. The next round therefore cannot start before the previous
/// round's branches have all reported. Without a reset, late results stay pending in the round's
/// instance until the Flow closes. They never count toward another round.
///
/// Add the Join to the Flow with [`crate::PersistenceSchema::join`]. Declare it as a module-level
/// [`std::sync::LazyLock`] static. The name follows the Channel-map rules: it is stable, it contains
/// no `/`, and it differs from every other persistence definition of the Flow.
///
/// # Rules and traps
///
/// - Each branch reports exactly one result per round. A branch that never reports keeps an all-of
/// join waiting forever. A branch that reports twice counts twice. When an execute failure routes
/// a branch to a recovery Step, that Step must report a result that represents the failure.
/// - A multi-Step branch passes its `JoinRound` down to the Step that reports. A branch passes the
/// round only to [`Self::end_branch`] or [`Self::report_branch_result`]. It never waits on a join
/// condition.
/// - Only the join Step that the fork started waits for a round. Two Steps that wait for the same
/// round split its results between them.
/// - The `received_count` of [`Self::for_remaining_branches`] equals the number of results the
/// join consumed: `count` after [`Self::for_branches`], and `1` after [`Self::for_first_branch`].
/// - A reset waits for every branch that has not reported yet, so it never completes while a
/// canceled branch has not reported. Never reset the round of a cancelling join. The next round
/// forks a new round without the reset wait, as the first round does. Without a reset, the
/// round's late results stay pending until the Flow closes.
/// - One invocation forks one Join at most once with [`Self::fork`]. Use a second Join, or
/// [`Self::fork_with_round_key`] with distinct keys, for two independent joins.
/// - An RPC has no Step execution ID, so it must use [`Self::fork_with_round_key`].
/// - A cancelling join adds [`StepDecision::cancel_sibling_step`] for each branch Step type to the
/// join Step's decision. The fork starts the branches and the join Step from one decision, so they
/// are siblings, and only this round's branches are selected. A later Step of a multi-Step branch
/// is not a sibling. Select it with [`StepDecision::cancel_step`], which is correct only while one
/// round is active. Steps started by an RPC count as siblings of every Step started by any call of
/// that RPC. For rounds that an RPC forks, also use [`StepDecision::cancel_step`] with one active
/// round.
/// - A canceled branch never reports, and no other code can safely report for it. Dex decides at
/// commit time whether a cancellation takes effect, so the code that cancels a branch cannot know
/// whether the branch already reported. If it did, the cancellation does nothing, and an extra
/// report counts that branch twice, so an all-of join can complete while another branch has not
/// reported. To keep an all-of join from waiting forever for a canceled branch, cancel the join
/// Step together with its branches, or wait on [`crate::Wait::any_of`] with the join condition
/// and a [`crate::Timer`] and handle the timeout in `execute`.
/// - When a join Step is canceled after its wait matched, what happens to the results it consumed
/// depends on the server version. A server that requeues them puts them back at the front of
/// the round's instance, unless the canceling decision closes the Flow. On a server that drops
/// them, a new join Step for that round never completes. See the server-zd change log at
/// <https://docs.superdurable.io/reference/server/changelog>.
///
/// # Examples
///
/// A structured partial join that loops: each round asks three suppliers, continues after the
/// first `required_quotes` quotes, and resets before the next round.
///
/// ```
/// use std::sync::LazyLock;
///
/// use dex_sdk::{
/// Context, Flow, HandlerResult, Join, JoinRound, PersistenceSchema, Step, StepDecision,
/// StepList, StepMovement, Wait,
/// };
/// use serde::{Deserialize, Serialize};
///
/// static QUOTE_RECEIVED: LazyLock<Join<String>> = LazyLock::new(|| Join::new("quoteReceived"));
///
/// #[derive(Serialize, Deserialize)]
/// struct QuoteRequest {
/// required_quotes: usize,
/// round_number: u32,
/// round_count: u32,
/// previous_round: Option<JoinRound>,
/// }
///
/// #[derive(Serialize, Deserialize)]
/// struct SupplierQuote {
/// supplier: String,
/// round: JoinRound,
/// }
///
/// #[derive(Serialize, Deserialize)]
/// struct AcceptQuotesInput {
/// request: QuoteRequest,
/// round: JoinRound,
/// }
///
/// // Split: resets the previous round, then forks one branch per supplier and the join.
/// struct RequestQuotes;
///
/// impl Step for RequestQuotes {
/// type Input = QuoteRequest;
///
/// fn wait_for(&self, _context: &mut Context, request: QuoteRequest) -> HandlerResult<Wait> {
/// match &request.previous_round {
/// None => Ok(Wait::skip_immediately()),
/// Some(previous_round) => Ok(Wait::until(
/// QUOTE_RECEIVED.for_remaining_branches(previous_round, request.required_quotes),
/// )),
/// }
/// }
///
/// fn execute(
/// &self,
/// context: &mut Context,
/// request: QuoteRequest,
/// ) -> HandlerResult<StepDecision> {
/// if let Some(previous_round) = &request.previous_round {
/// let late_quotes = QUOTE_RECEIVED.remaining_branch_results(context, previous_round)?;
/// context.record_event("lateQuotes", late_quotes)?;
/// }
/// let branch_builders = ["A", "B", "C"]
/// .into_iter()
/// .map(|supplier| {
/// Box::new(move |round: &JoinRound| {
/// StepMovement::to(
/// &QuoteFromSupplier,
/// SupplierQuote {
/// supplier: supplier.to_string(),
/// round: round.clone(),
/// },
/// )
/// }) as Box<dyn FnOnce(&JoinRound) -> StepMovement>
/// })
/// .collect();
/// let movements = QUOTE_RECEIVED.fork(context, branch_builders, |round| {
/// StepMovement::to(&AcceptQuotes, AcceptQuotesInput { request, round })
/// })?;
/// Ok(StepDecision::go_to_many(movements))
/// }
/// }
///
/// // Branch: reports one result and ends.
/// struct QuoteFromSupplier;
///
/// impl Step for QuoteFromSupplier {
/// type Input = SupplierQuote;
///
/// fn execute(
/// &self,
/// context: &mut Context,
/// quote: SupplierQuote,
/// ) -> HandlerResult<StepDecision> {
/// QUOTE_RECEIVED.end_branch(context, "e.round, quote.supplier)
/// }
/// }
///
/// // Join: continues after the required number of quotes, then starts the next round.
/// struct AcceptQuotes;
///
/// impl Step for AcceptQuotes {
/// type Input = AcceptQuotesInput;
///
/// fn wait_for(&self, _context: &mut Context, input: AcceptQuotesInput) -> HandlerResult<Wait> {
/// Ok(Wait::until(
/// QUOTE_RECEIVED.for_branches(&input.round, input.request.required_quotes),
/// ))
/// }
///
/// fn execute(
/// &self,
/// context: &mut Context,
/// input: AcceptQuotesInput,
/// ) -> HandlerResult<StepDecision> {
/// let accepted_quotes = QUOTE_RECEIVED.branch_results(context, &input.round)?;
/// let request = input.request;
/// if request.round_number == request.round_count {
/// return Ok(StepDecision::graceful_complete(accepted_quotes));
/// }
/// Ok(StepDecision::go_to(
/// &RequestQuotes,
/// QuoteRequest {
/// round_number: request.round_number + 1,
/// previous_round: Some(input.round),
/// ..request
/// },
/// ))
/// }
/// }
///
/// struct QuoteFlow {
/// request_quotes: RequestQuotes,
/// quote_from_supplier: QuoteFromSupplier,
/// accept_quotes: AcceptQuotes,
/// }
///
/// impl Flow for QuoteFlow {
/// type StartInput = QuoteRequest;
///
/// fn steps(&self) -> StepList<'_, QuoteRequest> {
/// StepList::start(&self.request_quotes)
/// .and(&self.quote_from_supplier)
/// .and(&self.accept_quotes)
/// }
///
/// fn persistence(&self) -> PersistenceSchema {
/// PersistenceSchema::new().join("E_RECEIVED)
/// }
/// }
/// ```
///
/// Since 1.44.0.