celers-canvas 0.2.0

Workflow primitives for CeleRS (Chain, Chord, Group, Map)
Documentation
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# Migration from Celery Canvas

> Complete guide for migrating from Python Celery Canvas to celers-canvas

## Table of Contents

1. [Overview]#overview
2. [Core Concepts]#core-concepts
3. [API Comparison]#api-comparison
4. [Common Patterns]#common-patterns
5. [Feature Parity]#feature-parity
6. [Migration Checklist]#migration-checklist
7. [Troubleshooting]#troubleshooting

---

## Overview

celers-canvas provides a Rust implementation of Celery's Canvas workflow primitives, offering:

- **Type Safety**: Compile-time guarantees for workflow correctness
- **Performance**: Zero-cost abstractions and async execution
- **Compatibility**: Similar API to Python Celery Canvas
- **Advanced Features**: Additional patterns and error handling

### Key Differences

| Aspect | Celery (Python) | celers-canvas (Rust) |
|--------|-----------------|---------------------|
| Language | Python | Rust |
| Type System | Dynamic | Static |
| Execution | Sync/Async | Async (tokio) |
| Error Handling | Exceptions | Result types |
| Memory | GC | Ownership |
| Null Safety | None checks | Option/Result |

---

## Core Concepts

### Signatures

**Python (Celery):**
```python
from celery import signature

sig = signature('tasks.add', args=(2, 2))
sig = tasks.add.s(2, 2)  # shorthand
sig = tasks.add.si(2, 2)  # immutable
```

**Rust (celers-canvas):**
```rust
use celers_canvas::Signature;
use serde_json::json;

let sig = Signature::new("tasks.add".to_string())
    .with_args(vec![json!(2), json!(2)]);

// Immutable signature
let sig = Signature::new("tasks.add".to_string())
    .with_args(vec![json!(2), json!(2)])
    .si();  // or .immutable()
```

### Chains

**Python:**
```python
from celery import chain

workflow = chain(
    tasks.task1.s(),
    tasks.task2.s(),
    tasks.task3.s()
)

# Or using pipe operator
workflow = tasks.task1.s() | tasks.task2.s() | tasks.task3.s()

workflow.apply_async()
```

**Rust:**
```rust
use celers_canvas::Chain;

let workflow = Chain::new()
    .then("tasks.task1", vec![])
    .then("tasks.task2", vec![])
    .then("tasks.task3", vec![]);

workflow.apply(&broker).await?;
```

### Groups

**Python:**
```python
from celery import group

workflow = group(
    tasks.task1.s(1),
    tasks.task2.s(2),
    tasks.task3.s(3)
)

workflow.apply_async()
```

**Rust:**
```rust
use celers_canvas::Group;

let workflow = Group::new()
    .add("tasks.task1", vec![json!(1)])
    .add("tasks.task2", vec![json!(2)])
    .add("tasks.task3", vec![json!(3)]);

workflow.apply(&broker).await?;
```

### Chords

**Python:**
```python
from celery import chord

workflow = chord(
    group(tasks.process.s(i) for i in range(10))
)(tasks.aggregate.s())

# Or using pipe
workflow = group(tasks.process.s(i) for i in range(10)) | tasks.aggregate.s()

workflow.apply_async()
```

**Rust:**
```rust
use celers_canvas::Chord;

let mut workflow = Chord::new();
for i in 0..10 {
    workflow = workflow.add("tasks.process", vec![json!(i)]);
}
workflow = workflow.callback("tasks.aggregate", vec![]);

workflow.apply(&broker, &mut backend).await?;
```

### Map

**Python:**
```python
from celery import group

# Map pattern
workflow = group(tasks.process.s(i) for i in items)
workflow.apply_async()
```

**Rust:**
```rust
use celers_canvas::Map;

let items: Vec<Vec<serde_json::Value>> =
    items.iter()
        .map(|i| vec![json!(i)])
        .collect();

let workflow = Map::new(
    Signature::new("tasks.process".to_string()),
    items
);

workflow.apply(&broker).await?;
```

---

## API Comparison

### Task Options

**Python:**
```python
sig = tasks.add.s(2, 2)
sig.set(
    queue='high_priority',
    priority=9,
    countdown=10,
    eta=datetime.now() + timedelta(seconds=60),
    expires=3600,
    retry=True,
    retry_policy={
        'max_retries': 3,
        'interval_start': 0,
        'interval_step': 0.2,
        'interval_max': 0.2,
    }
)
```

**Rust:**
```rust
let sig = Signature::new("tasks.add".to_string())
    .with_args(vec![json!(2), json!(2)])
    .with_queue("high_priority".to_string())
    .with_priority(9)
    .with_time_limit(3600)
    .with_retry_delay(10)
    .with_retry_backoff(0.2)
    .with_retry_backoff_max(3600);
```

### Callbacks (Links)

**Python:**
```python
# Success callback
sig = tasks.task1.s()
sig.link(tasks.on_success.s())

# Error callback
sig.link_error(tasks.on_error.s())

# Multiple callbacks
sig.link(tasks.callback1.s())
sig.link(tasks.callback2.s())
```

**Rust:**
```rust
// Single callbacks
let sig = Signature::new("tasks.task1".to_string())
    .with_link(
        Signature::new("tasks.on_success".to_string())
    )
    .with_link_error(
        Signature::new("tasks.on_error".to_string())
    );

// Multiple callbacks
let sig = Signature::new("tasks.task1".to_string())
    .add_link(Signature::new("tasks.callback1".to_string()))
    .add_link(Signature::new("tasks.callback2".to_string()));
```

### Partial Application

**Python:**
```python
# Partial args
partial_sig = tasks.add.s(2)
result = partial_sig.delay(2)  # Completes as add(2, 2)

# Clone
cloned = sig.clone()
```

**Rust:**
```rust
// Partial args (via signature mutation)
let mut sig = Signature::new("tasks.add".to_string())
    .with_args(vec![json!(2)]);

// Add more args later
sig.args.push(json!(2));

// Clone
let cloned = sig.clone();
```

---

## Common Patterns

### Pattern 1: Sequential Pipeline

**Python:**
```python
from celery import chain

pipeline = chain(
    tasks.extract.s(),
    tasks.transform.s(),
    tasks.load.s()
)

pipeline.apply_async()
```

**Rust:**
```rust
let pipeline = Chain::new()
    .then("tasks.extract", vec![])
    .then("tasks.transform", vec![])
    .then("tasks.load", vec![]);

pipeline.apply(&broker).await?;
```

### Pattern 2: Parallel + Aggregate

**Python:**
```python
from celery import chord, group

workflow = chord(
    group(tasks.fetch.s(url) for url in urls)
)(tasks.combine.s())

workflow.apply_async()
```

**Rust:**
```rust
let mut workflow = Chord::new();
for url in urls {
    workflow = workflow.add("tasks.fetch", vec![json!(url)]);
}
workflow = workflow.callback("tasks.combine", vec![]);

workflow.apply(&broker, &mut backend).await?;
```

### Pattern 3: Dynamic Workflows

**Python:**
```python
from celery import chain, group

# Build workflow dynamically
tasks_list = []
for item in items:
    if item.needs_processing:
        tasks_list.append(tasks.process.s(item))

workflow = group(tasks_list)
workflow.apply_async()
```

**Rust:**
```rust
let mut workflow = Group::new();

for item in items {
    if item.needs_processing {
        workflow = workflow.add("tasks.process", vec![json!(item)]);
    }
}

workflow.apply(&broker).await?;
```

### Pattern 4: Error Handling

**Python:**
```python
from celery import chain

workflow = chain(
    tasks.task1.s(),
    tasks.task2.s().set(link_error=tasks.handle_error.s()),
    tasks.task3.s()
)

workflow.apply_async()
```

**Rust:**
```rust
let workflow = Chain::new()
    .then("tasks.task1", vec![])
    .then("tasks.task2", vec![])
    .then("tasks.task3", vec![]);

// Add error handler at workflow level
let handler = WorkflowErrorHandler::new()
    .with_strategy(ErrorStrategy::Fallback(
        Chain::new().then("tasks.handle_error", vec![])
    ));

let workflow = workflow.with_error_handler(handler);
```

### Pattern 5: Retries

**Python:**
```python
sig = tasks.unreliable_task.s()
sig.set(
    retry=True,
    retry_policy={
        'max_retries': 3,
        'interval_start': 1,
        'interval_step': 2,
        'interval_max': 10,
    }
)

sig.apply_async()
```

**Rust:**
```rust
let workflow = Chain::new()
    .then("tasks.unreliable_task", vec![])
    .with_retry_policy(
        WorkflowRetryPolicy::new()
            .with_max_retries(3)
            .with_backoff_strategy(BackoffStrategy::Exponential)
            .with_initial_delay(Duration::from_secs(1))
            .with_max_delay(Duration::from_secs(10))
    );
```

---

## Feature Parity

### ✅ Fully Supported

| Feature | Celery | celers-canvas |
|---------|--------|---------------|
| Chain |||
| Group |||
| Chord |||
| Map |||
| Starmap |||
| Chunks |||
| Signatures |||
| Immutable Signatures |||
| Callbacks (link) |||
| Error Callbacks |||
| Task Priority |||
| Task Queues |||
| Task IDs |||
| Timeouts |||

### 🎁 Enhanced Features

Features that go beyond Celery:

| Feature | Description |
|---------|-------------|
| Workflow Cancellation | Cancel entire workflow trees |
| Workflow Retry Policies | Retry entire workflows with backoff |
| Conditional Workflows | Branch, Switch, Maybe patterns |
| Loops | ForEach, While loops |
| State Tracking | Real-time progress monitoring |
| DAG Export | GraphViz, Mermaid, JSON formats |
| Result Caching | Memoization of task results |
| Saga Pattern | Distributed transactions with compensation |
| Advanced Patterns | Scatter-Gather, Pipeline, Fan-Out/Fan-In |
| Workflow Validation | Pre-execution validation |
| Workflow Compilation | Optimization passes |
| Time-Travel Debugging | Step through workflow execution |
| Sub-Workflow Isolation | Isolated execution contexts |
| Event-Driven Workflows | React to events |
| Reactive Workflows | Observable streams |

### ⚠️ Limited Support

| Feature | Status | Notes |
|---------|--------|-------|
| Nested Groups | Partial | Use CanvasElement pattern |
| Dynamic Routing | Manual | Use routing keys in options |
| Task Revocation | Basic | Use cancel() method |

### ❌ Not Supported

| Feature | Alternative |
|---------|-------------|
| Python-specific features | N/A |
| Celery Beat (periodic tasks) | Use celers-beat crate |
| Result backends (other than Redis) | Redis only for chords |

---

## Migration Checklist

### Pre-Migration

- [ ] Audit existing Celery workflows
- [ ] Identify dependencies and task definitions
- [ ] Document task signatures and arguments
- [ ] Review error handling strategies
- [ ] List required queue configurations

### During Migration

- [ ] Set up Rust development environment
- [ ] Install celers crates
- [ ] Port task definitions to Rust
- [ ] Convert workflow definitions
- [ ] Update broker configurations
- [ ] Implement error handlers
- [ ] Add tests for workflows
- [ ] Set up monitoring

### Post-Migration

- [ ] Verify workflow execution
- [ ] Monitor performance metrics
- [ ] Compare error rates
- [ ] Validate result correctness
- [ ] Document new patterns
- [ ] Train team on new system

---

## Migration Examples

### Example 1: Simple Chain

**Before (Python):**
```python
from celery import chain
from tasks import process_data, validate, save

workflow = chain(
    process_data.s(input_data),
    validate.s(),
    save.s()
)

result = workflow.apply_async()
```

**After (Rust):**
```rust
use celers_canvas::Chain;
use serde_json::json;

let workflow = Chain::new()
    .then("tasks.process_data", vec![json!(input_data)])
    .then("tasks.validate", vec![])
    .then("tasks.save", vec![]);

let result = workflow.apply(&broker).await?;
```

### Example 2: Parallel Processing

**Before (Python):**
```python
from celery import group
from tasks import fetch_data

urls = ['url1', 'url2', 'url3']
workflow = group(fetch_data.s(url) for url in urls)

result = workflow.apply_async()
```

**After (Rust):**
```rust
use celers_canvas::Group;

let mut workflow = Group::new();
for url in &urls {
    workflow = workflow.add("tasks.fetch_data", vec![json!(url)]);
}

let result = workflow.apply(&broker).await?;
```

### Example 3: Map-Reduce

**Before (Python):**
```python
from celery import chord, group
from tasks import process_item, aggregate

items = [1, 2, 3, 4, 5]
workflow = chord(
    group(process_item.s(item) for item in items)
)(aggregate.s())

result = workflow.apply_async()
```

**After (Rust):**
```rust
use celers_canvas::Chord;

let mut workflow = Chord::new();
for item in items {
    workflow = workflow.add("tasks.process_item", vec![json!(item)]);
}
workflow = workflow.callback("tasks.aggregate", vec![]);

let result = workflow.apply(&broker, &mut backend).await?;
```

### Example 4: Conditional Execution

**Before (Python):**
```python
from celery import chain
from tasks import check_condition, process_a, process_b

workflow = chain(
    check_condition.s(data),
    # Conditional logic in task
    process_a.s() if condition else process_b.s()
)
```

**After (Rust):**
```rust
use celers_canvas::{Branch, Condition, Chain};

let condition = Condition::new(
    "tasks.check_condition",
    vec![json!(data)]
);

let workflow = Branch::new(condition)
    .on_true(Chain::new().then("tasks.process_a", vec![]))
    .on_false(Chain::new().then("tasks.process_b", vec![]));
```

---

## Troubleshooting

### Issue: Serialization Errors

**Problem:** JSON serialization fails for complex types.

**Solution:**
```rust
// Use serde_json::Value for flexibility
let args = vec![serde_json::json!({
    "user_id": 123,
    "data": {
        "name": "John",
        "email": "john@example.com"
    }
})];
```

### Issue: Async/Await Confusion

**Problem:** Forgetting to await futures.

**Solution:**
```rust
// Wrong
let result = workflow.apply(&broker);  // Returns Future

// Correct
let result = workflow.apply(&broker).await?;
```

### Issue: Broker Connection

**Problem:** Broker connection not configured.

**Solution:**
```rust
// Ensure broker is properly initialized
use celers_broker_amqp::AmqpBroker;

let broker = AmqpBroker::new("amqp://localhost").await?;
```

### Issue: Type Mismatches

**Problem:** Static typing requires explicit types.

**Solution:**
```rust
// Be explicit with types
let items: Vec<Vec<serde_json::Value>> = vec![
    vec![json!(1)],
    vec![json!(2)],
];
```

### Issue: Error Handling

**Problem:** Not handling Result types.

**Solution:**
```rust
// Always handle errors
match workflow.apply(&broker).await {
    Ok(workflow_id) => println!("Started workflow: {}", workflow_id),
    Err(e) => eprintln!("Failed to start workflow: {}", e),
}

// Or use ? operator
let workflow_id = workflow.apply(&broker).await?;
```

---

## Performance Considerations

### Memory Usage

**Python Celery:**
- GC overhead
- Per-task memory allocation
- Dynamic typing overhead

**celers-canvas:**
- Zero-cost abstractions
- Stack allocation when possible
- Compile-time optimizations

### Throughput

**Benchmarks** (approximate):

| Operation | Celery (Python) | celers-canvas (Rust) |
|-----------|-----------------|---------------------|
| Chain creation (1000) | ~100ms | ~10ms |
| Group creation (1000) | ~150ms | ~15ms |
| Serialization (1000) | ~200ms | ~50ms |

### Concurrency

**Python:**
```python
# Limited by GIL
# Multi-process for CPU-bound tasks
```

**Rust:**
```rust
// True parallelism
// Async I/O with tokio
// No GIL limitations
```

---

## Additional Resources

- [Design Patterns Guide]./DESIGN_PATTERNS.md
- [API Documentation]https://docs.rs/celers-canvas
- [Examples]./examples/
- [Celery Canvas Documentation]https://docs.celeryproject.org/en/stable/userguide/canvas.html

---

## Getting Help

- **Issues**: [GitHub Issues]https://github.com/yourusername/celers/issues
- **Discussions**: [GitHub Discussions]https://github.com/yourusername/celers/discussions
- **Discord**: [celers Discord Server]#

---

## Contributing

We welcome contributions! See [CONTRIBUTING.md](../../CONTRIBUTING.md) for guidelines.