Skip to content

Commit a366fb2

Browse files
Merge pull request #527 from cleverage/105-router
#105 - New router task
2 parents 29795cd + 45e4726 commit a366fb2

14 files changed

Lines changed: 766 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ Latest
2121

2222
## Changes
2323
* [#105](https://github.com/cleverage/process-bundle/issues/105) Conditional branches: the new `branches` key of a task configuration lists the tasks receiving its output by branch name, only when the task selects their branch with `ProcessState::setOutputBranch()` (in addition to its `outputs`); an unknown branch makes the execution fail, an unknown task or a task listed several times in the `outputs` and `branches` is rejected; `cleverage:process:help` shows the branch leading to each task. Update documentation, add tests.
24+
* [#105](https://github.com/cleverage/process-bundle/issues/105) New `router` task: sends each input to the conditional branches of the task whose conditions it matches (conditions of `ConditionTrait` and an `expression`, by branch name), the first one (`mode: first`, default) or all of them (`mode: all`), else the `default` branch; without a default branch, an input matching no branch goes to the error outputs with a warning. The conditions and the default branch must match the `branches` of the task, checked at its initialization. Add the reference page and a recipe replacing a cascade of filters, add tests.
2425
* [#428](https://github.com/cleverage/process-bundle/issues/428) Tests on PHPUnit 12.5 and 13 (PHPUnit 10 and 11 dropped), with the lowest dependencies on PHP 8.3 and 8.5.
2526
* [#510](https://github.com/cleverage/process-bundle/issues/510) Support PHP 8.6: tests on PHP 8.6 (lowest dependencies, highest with Symfony 7.4 and 8.x), PHPStan and Rector on PHP 8.6, `symfony/polyfill-php86` is required so that the PHP 8.6 functions can be used on PHP 8.3 to 8.5.
2627
* [#493](https://github.com/cleverage/process-bundle/issues/493) Documentation: the `constant()` function of the `evaluator` expressions is deprecated by Symfony 8.2 (a `ConstantFunctionProvider` must be registered), avoid it.

‎config/services/task.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
use CleverAge\ProcessBundle\Task\Reporting\AdvancedStatCounterTask;
6161
use CleverAge\ProcessBundle\Task\Reporting\LoggerTask;
6262
use CleverAge\ProcessBundle\Task\Reporting\StatCounterTask;
63+
use CleverAge\ProcessBundle\Task\RouterTask;
6364
use CleverAge\ProcessBundle\Task\RowAggregatorTask;
6465
use CleverAge\ProcessBundle\Task\Serialization\DenormalizerTask;
6566
use CleverAge\ProcessBundle\Task\Serialization\DeserializerTask;
@@ -340,6 +341,15 @@
340341
service('logger'),
341342
]);
342343

344+
$services->set(RouterTask::class)
345+
->tag('cleverage.task', ['code' => 'router'])
346+
->share(false)
347+
->args([
348+
service('logger'),
349+
service('property_accessor'),
350+
service('cleverage_process.expression_language'),
351+
]);
352+
343353
$services->set(RowAggregatorTask::class)
344354
->tag('cleverage.task', ['code' => 'row_aggregator'])
345355
->share(false)

‎docs/04-advanced_workflow.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,10 @@ A task can send its output to some of its next tasks only: the tasks of its `bra
187187
The selection is reset before each execution of the task. `cleverage:process:help` shows the branch leading to each
188188
task (`[branch <task>.<branch>]`).
189189

190+
The [RouterTask](reference/tasks/router_task.md) selects the branches from conditions on the input (the first matching
191+
branch or all of them, else a default branch), without code; a custom task calls `setOutputBranch()` itself, e.g. when
192+
the branch depends on a service (see the [recipe](cookbooks/router.md)).
193+
190194
Unlike a [FilterTask](reference/tasks/filter_task.md) with `error_outputs`, the tasks of a branch are in the main
191195
branch: the items of no branch are not mixed with the errors of the task. Some behaviours to know:
192196
- a blocking task in a branch never selected is not proceeded: nothing comes out of it, without error; a flushable

‎docs/cookbooks/router.md‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
Dispatching items with a router
2+
===============================
3+
4+
This recipe dispatches the lines of a single file between several processings, according to their content: a typical
5+
partner file mixing products, categories and comments.
6+
7+
```csv
8+
type;code;label;total
9+
product;P001;Chair;10
10+
category;C01;Furniture;
11+
product;P002;Table;2500
12+
comment;;File of 2026-12-03;
13+
promo;X1;Black Friday;
14+
```
15+
16+
Before the [RouterTask](../reference/tasks/router_task.md), this was done with a cascade of
17+
[FilterTask](../reference/tasks/filter_task.md), each rejected line going to the next filter through `error_outputs`:
18+
19+
```yaml
20+
is_product:
21+
task: filter
22+
options: { match: { '[type]': product } }
23+
outputs: [write_product]
24+
error_outputs: [is_category] # "else", through the error channel
25+
is_category:
26+
task: filter
27+
options: { match: { '[type]': category } }
28+
outputs: [write_category] # the other lines are lost without trace
29+
```
30+
31+
- The next filters and their tasks are an error branch (shown as such by `cleverage:process:help`).
32+
- A failure of `is_product` with `error_strategy: skip` sends the line to `is_category`, as if it were not a product.
33+
- Each new type adds a filter, and a line of no known type is silently dropped.
34+
35+
With a router, the dispatch is a single task, the lines of no known type are reported, and the errors stay errors:
36+
37+
```yaml
38+
cleverage_process:
39+
configurations:
40+
app.import_catalog:
41+
description: 'Import the catalog file of the partner'
42+
tasks:
43+
read:
44+
task: csv_reader
45+
options:
46+
file_path: '%kernel.project_dir%/var/data/catalog.csv'
47+
delimiter: ';'
48+
outputs: [route]
49+
50+
route:
51+
task: router
52+
options:
53+
mode: all
54+
conditions:
55+
product: { match: { '[type]': product } }
56+
category: { match: { '[type]': category } }
57+
comment: { match: { '[type]': comment } }
58+
big: { expression: 'data["type"] == "product" and data["total"] > 1000' }
59+
default: unknown # a line of no known type (e.g. promo)
60+
outputs: [count] # every line
61+
branches:
62+
product: [write_product]
63+
category: [write_category]
64+
comment: [] # ignored
65+
big: [log_big]
66+
unknown: [log_unknown]
67+
68+
count:
69+
task: stat_counter
70+
71+
write_product:
72+
task: csv_writer
73+
options:
74+
file_path: '%kernel.project_dir%/var/exports/products.csv'
75+
76+
write_category:
77+
task: csv_writer
78+
options:
79+
file_path: '%kernel.project_dir%/var/exports/categories.csv'
80+
81+
log_big:
82+
task: logger
83+
options:
84+
level: notice
85+
message: 'Big product'
86+
87+
log_unknown:
88+
task: logger
89+
options:
90+
level: warning
91+
message: 'Unknown line type'
92+
```
93+
94+
How it works:
95+
- [CsvReaderTask](../reference/tasks/csv_reader_task.md) is iterable: each line goes through the router before the
96+
next one is read.
97+
- The [RouterTask](../reference/tasks/router_task.md) sends every line to its `outputs` (the
98+
[StatCounterTask](../reference/tasks/stat_counter_task.md)), and to the tasks of the branches it matches. With
99+
`mode: all`, the line `P002` goes to `write_product` and `log_big`; with the default `mode: first`, only the first
100+
matching branch (in the order of `conditions`) would get it.
101+
- The `comment` branch has no task: the comments are dropped on purpose, without warning.
102+
- The line `promo` matches no branch: it goes to the `default` branch, `log_unknown`. Without a `default` branch, it
103+
would go to the `error_outputs` of the router, with a warning, mixed with the errors of the router (e.g. a missing
104+
key in an expression, with `error_strategy: skip`): a `default` branch keeps them apart.
105+
- `cleverage:process:help app.import_catalog` shows the branch leading to each task (`write_product [branch
106+
route.product]`), in the main branch.
107+
108+
Keep the [FilterTask](../reference/tasks/filter_task.md) to drop the items that do not match (e.g. the lines without
109+
`sku`): a router is meant to dispatch them. The branches of a router cannot be joined back with an
110+
[InputAggregatorTask](../reference/tasks/input_aggregator_task.md), see
111+
[conditional branches](../04-advanced_workflow.md#conditional-branches).

‎docs/index.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
- [ETL report aggregation](cookbooks/etl_aggregate_reports.md)
1313
- [Performances monitoring](cookbooks/performances_monitoring.md)
1414
- [Memory usage analysis](cookbooks/memory_usage_graph.md)
15+
- [Dispatching items with a router](cookbooks/router.md)
1516
- Reference
1617
- [Process definition](reference/01-process_definition.md)
1718
- [Task definition](reference/02-task_definition.md)
@@ -74,6 +75,7 @@
7475
- [ColumnAggregatorTask](reference/tasks/column_aggregator_task.md)
7576
- [RowAggregatorTask](reference/tasks/row_aggregator_task.md)
7677
- [FilterTask](reference/tasks/filter_task.md)
78+
- [RouterTask](reference/tasks/router_task.md)
7779
- [GroupByAggregateIterableTask](reference/tasks/group_by_aggregate_iterable_task.md)
7880
- [SimpleBatchTask](reference/tasks/simple_batch_task.md)
7981
- [IterableBatchTask](reference/tasks/iterable_batch_task.md)

‎docs/reference/tasks/filter_task.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ FilterTask
44
Passes the input to the output only if it matches all the configured conditions. Otherwise, the input is sent to the
55
error output and the task is skipped.
66

7+
Use it to drop the items that do not match (and optionally report them through `error_outputs`). To dispatch the items
8+
between several processings, use the [RouterTask](router_task.md) instead of a cascade of filters linked by their
9+
`error_outputs` (see the [recipe](../../cookbooks/router.md)).
10+
711
Task reference
812
--------------
913

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
RouterTask
2+
==========
3+
4+
Sends each input to the [conditional branches](../../04-advanced_workflow.md#conditional-branches) of the task whose
5+
conditions it matches: the first matching branch, or all of them, else a default branch. Use it to dispatch the items
6+
between several processings (e.g. the lines of a file by type, the responses of an API by status); to drop the items
7+
that do not match, use the [FilterTask](filter_task.md).
8+
9+
The conditions are given by branch name in the `conditions` option, the tasks of each branch in the `branches` key of
10+
the task configuration (see [task definition](../02-task_definition.md)). Each branch of the task must have conditions
11+
or be the `default` branch, and each branch of the options must be a branch of the task: otherwise the process fails
12+
at the initialization of the task, before any input.
13+
14+
Task reference
15+
--------------
16+
17+
* **Service**: `CleverAge\ProcessBundle\Task\RouterTask`
18+
* **Code**: `router` (`task: router`)
19+
20+
Accepted inputs
21+
---------------
22+
23+
`any`: the conditions of [ConditionTrait](../traits/condition_trait.md) read the values of an `array` or an `object`
24+
with the Symfony PropertyAccessor (a non-readable property is `null`, use the empty path `''` for a scalar input); an
25+
`expression` gets the input as the `data` variable.
26+
27+
Possible outputs
28+
----------------
29+
30+
`any`: the input, unchanged, sent to the `outputs` of the task and to the tasks of the selected branches.
31+
32+
Error output: the input, unchanged, when it matches no branch and there is no `default` branch (logged as a warning on
33+
the `cleverage_process_task` channel). An error while checking a condition (e.g. an expression calling a method of an
34+
array, a missing array key) makes the task fail: its `error_strategy` applies, the input never goes to the default
35+
branch. Both go to the same error outputs: use a `default` branch to keep the inputs of no branch apart from the errors.
36+
37+
Options
38+
-------
39+
40+
| Code | Type | Required | Default | Description |
41+
|--------------|-------------------------|:--------:|---------|--------------------------------------------------------------------------------------|
42+
| `conditions` | `array` | **X** | | Branch name => conditions of the branch (see below); all of them must hold |
43+
| `mode` | `string` | | `first` | `first`: the first matching branch, in the order of `conditions`; `all`: all of them |
44+
| `default` | `string`, `int`, `null` | | `null` | Branch of the inputs matching no branch; `null`: they go to the error outputs |
45+
46+
The conditions of a branch are the options of [ConditionTrait](../traits/condition_trait.md) (`match`, `not_match`,
47+
`empty`, `not_empty`, `match_regexp`, `not_match_regexp`) and `expression`, a Symfony
48+
[ExpressionLanguage](https://symfony.com/doc/current/components/expression_language.html) expression evaluated with the
49+
input as `data` (the bundle's `cleverage_process.expression_language` service, with its `preg_match` function, as in
50+
the [RulesTransformer](../transformers/rules_transformer.md)); its result is cast to `bool`. A branch without conditions
51+
(`~`) matches every input; another value than a mapping or `~` is rejected. An expression gives the alternatives
52+
(`or`) the other conditions cannot express. A missing array key in an expression is an error: give a default value
53+
when the key may be missing (`(data["total"] ?? 0) > 1000`).
54+
55+
Do not put a `{{ key }}` contextual value in an `expression`: it is replaced before the expression is parsed, so a value
56+
given by the context (command line, scheduler, UI form) would become expression code and change the routing. Read the
57+
values in the input (`data`) instead.
58+
59+
Examples
60+
--------
61+
62+
* Dispatch the lines of a catalog file by type, ignore the comments, report the unknown types
63+
64+
```yaml
65+
# Task configuration level
66+
route:
67+
task: router
68+
options:
69+
conditions:
70+
product: { match: { '[type]': product } }
71+
category: { match: { '[type]': category } }
72+
comment: { match: { '[type]': comment } }
73+
outputs: [count] # every line
74+
branches:
75+
product: [write_product]
76+
category: [write_category]
77+
comment: [] # ignored
78+
error_outputs: [report] # an unknown type, with a warning
79+
```
80+
81+
* Route the responses of an API by status code, with a default branch; flag the big orders as well (mode `all`)
82+
83+
```yaml
84+
# Task configuration level
85+
route_status:
86+
task: router
87+
options:
88+
conditions:
89+
200: { match: { '[status]': 200 } }
90+
404: { match: { '[status]': 404 } }
91+
default: failed
92+
branches:
93+
200: [update_stock]
94+
404: [disable_product]
95+
failed: [alert]
96+
97+
route_order:
98+
task: router
99+
options:
100+
mode: all
101+
conditions:
102+
erp: ~ # every order
103+
big_order: { expression: 'data["total"] > 1000 or data["vip"]' }
104+
branches:
105+
erp: [export_erp]
106+
big_order: [notify_sales]
107+
```
108+
109+
See the [conditional branches](../../04-advanced_workflow.md#conditional-branches) for the behaviour of the branches
110+
(blocking tasks, end point, no join with an [InputAggregatorTask](input_aggregator_task.md)), and the
111+
[recipe](../../cookbooks/router.md) replacing a cascade of filters.

‎docs/reference/traits/condition_trait.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ array_filter:
9494
## Implementors
9595

9696
* [FilterTask](../tasks/filter_task.md): condition options at the root of the task options
97+
* [RouterTask](../tasks/router_task.md): condition options of each branch, in its `conditions` option
9798
* [ColumnAggregatorTask](../tasks/column_aggregator_task.md): `condition` option, checked against
9899
`{input_column_value: <column value>, input: <input>}` (so use paths like `[input_column_value]` or `[input][key]`)
99100
* [ArrayFilterTransformer](../transformers/array_filter_transformer.md): `condition` option, checked against each item

‎src/Configuration/TaskConfiguration.php‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,17 @@ final class TaskConfiguration
4848
/**
4949
* The next tasks of each branch, indexed by branch name.
5050
*
51-
* @var array<string, list<TaskConfiguration>>
51+
* @var array<int|string, list<TaskConfiguration>>
5252
*/
5353
protected array $branchTasksConfigurations = [];
5454

5555
protected bool $inErrorBranch = false;
5656

5757
/**
58-
* @param array<string, mixed> $options
59-
* @param list<string> $outputs
60-
* @param list<string> $errorOutputs
61-
* @param array<string, list<string>> $branches tasks receiving the output when the task selects their branch
58+
* @param array<string, mixed> $options
59+
* @param list<string> $outputs
60+
* @param list<string> $errorOutputs
61+
* @param array<int|string, list<string>> $branches tasks receiving the output when the task selects their branch
6262
*/
6363
public function __construct(
6464
protected string $code,
@@ -140,7 +140,7 @@ public function getErrorOutputs(): array
140140
/**
141141
* The codes of the tasks of each branch, indexed by branch name.
142142
*
143-
* @return array<string, list<string>>
143+
* @return array<int|string, list<string>>
144144
*/
145145
public function getBranches(): array
146146
{
@@ -173,7 +173,7 @@ public function addNextTaskConfiguration(self $nextTaskConfiguration): void
173173
/**
174174
* The next tasks of each branch, indexed by branch name: they are also in getNextTasksConfigurations().
175175
*
176-
* @return array<string, list<TaskConfiguration>>
176+
* @return array<int|string, list<TaskConfiguration>>
177177
*/
178178
public function getBranchTasksConfigurations(): array
179179
{

0 commit comments

Comments
 (0)