de-pilum 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ *.egg-info/
5
+ dist/
6
+ .coverage
7
+ coverage.xml
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .arsenal/
11
+ data/
12
+ .DS_Store
de_pilum-0.6.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 KooEric
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.5
2
+ Name: de-pilum
3
+ Version: 0.6.0
4
+ Summary: Pilum — reverse ETL: dispatch changed records from Parquet to HTTP endpoints and Slack, once per change
5
+ Project-URL: Homepage, https://github.com/KooEric/de-arsenal
6
+ Project-URL: Repository, https://github.com/KooEric/de-arsenal
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Database
17
+ Requires-Python: >=3.11
18
+ Requires-Dist: arsenal-core<0.7,>=0.6
19
+ Requires-Dist: duckdb>=1.0
20
+ Requires-Dist: httpx>=0.27
21
+ Requires-Dist: pyarrow>=17
22
+ Requires-Dist: pydantic>=2.7
23
+ Requires-Dist: pyyaml>=6
24
+ Requires-Dist: typer>=0.12
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Pilum (`de-pilum`)
28
+
29
+ **Experimental.** Reverse ETL for a DE Arsenal repo: send records from a Parquet
30
+ dataset (or a DuckDB query over one) to an HTTP endpoint or a Slack webhook, and
31
+ send each change once. The spec format, the ledger file and the CLI may change in
32
+ any 0.x release.
33
+
34
+ Each run compares the source with a local ledger of what the destination already
35
+ accepted, and sends only the difference:
36
+
37
+ | `mode` | Sends |
38
+ |---|---|
39
+ | `insert` | records whose key is new |
40
+ | `upsert` (default) | new keys, and keys whose content changed |
41
+ | `mirror` | the above, plus a delete request for keys that left the source |
42
+
43
+ ```yaml
44
+ # churn.yaml
45
+ name: churn-alerts
46
+ source:
47
+ type: parquet
48
+ path: data/marts/churn_risk
49
+ key: [customer_id]
50
+ destination:
51
+ type: http
52
+ url: https://api.example.com/v1/alerts
53
+ headers: { Authorization: "Bearer ${ALERTS_TOKEN}" }
54
+ body: { id: "{customer_id}", score: "{risk_score}", note: "risk for {customer_id}" }
55
+ idempotency_header: Idempotency-Key
56
+ rps: 5
57
+ ```
58
+
59
+ ```bash
60
+ pip install de-pilum
61
+ pilum plan churn.yaml # counts and sample keys; sends nothing, writes nothing
62
+ pilum run churn.yaml # exits 1 if any record was not delivered
63
+ pilum status churn.yaml # ledger size, last run, dead letters; exits 1 on alerts
64
+ pilum replay churn.yaml # put dead letters back in line for the next run
65
+ pilum reset churn.yaml --confirm # forget what was sent; next run sends everything
66
+ ```
67
+
68
+ ## What it guarantees, and what it does not
69
+
70
+ - **A record is recorded as sent only after a 2xx response.** If the process dies
71
+ between the response and the ledger write, the next run sends that record again
72
+ with the same `Idempotency-Key`.
73
+ - **Delivery is at-least-once.** It is exactly-once only when the endpoint
74
+ deduplicates on the idempotency header. Slack webhooks do not, so a crash at
75
+ the wrong moment can post one message twice.
76
+ - **The ledger is the only memory.** Pilum does not read the destination. If
77
+ something else changes the destination, Pilum does not notice; `reset` and
78
+ re-send is the way to resynchronise.
79
+ - **Rotating a token or changing the URL does not re-send anything.** The
80
+ dispatch id is derived from the dispatch name, the record key and the record
81
+ content only.
82
+
83
+ ## Failure handling
84
+
85
+ | Response | What happens |
86
+ |---|---|
87
+ | 2xx | recorded in the ledger |
88
+ | 408, 429, 5xx, network error | retried with backoff (`retry.max_attempts`); if every try fails the record stays queued for the next run, and moves to the dead-letter queue once its failed tries reach `dlq.after_attempts` |
89
+ | other 4xx | the record goes straight to the dead-letter queue with the response text |
90
+ | 401, 403 | the run stops; nothing is counted against the records |
91
+ | `safety.max_consecutive_failures` records fail in a row | the run stops: the destination is down |
92
+
93
+ A dead letter is skipped until `pilum replay`. If its source record changes, the
94
+ new version is sent normally and the dead letter is dropped.
95
+
96
+ ## Safety rails
97
+
98
+ - **First run.** With an empty ledger, a run that would send more than
99
+ `safety.max_first_dispatch` (1,000) records is refused unless
100
+ `--confirm-initial-load` is given.
101
+ - **Deletes.** A `mirror` run that would delete more than
102
+ `safety.max_delete_fraction` (50%) of the ledger is refused unless
103
+ `--confirm-deletes` is given. An empty or mis-pointed source otherwise looks
104
+ like "every record was removed".
105
+ - **One sender.** A second `run`, `replay` or `reset` on the same dispatch is
106
+ refused while one is in progress.
107
+ - **Secrets.** `${ENV_VAR}` in `url` and `headers` is read when a request is
108
+ sent. It is never written to the ledger or shown by `status`, and it is masked
109
+ in error messages. `${...}` is not expanded inside `body` or Slack `text`.
110
+
111
+ ## Not in this version
112
+
113
+ Bulk (multi-record) requests, OAuth token refresh, named SaaS connectors,
114
+ event-driven dispatch from a Hasta outbox, and `arsenal run` / Aquila
115
+ integration. Field reference: [dispatch-schema.md](https://github.com/KooEric/de-arsenal/blob/main/docs/reference/dispatch-schema.md).
@@ -0,0 +1,89 @@
1
+ # Pilum (`de-pilum`)
2
+
3
+ **Experimental.** Reverse ETL for a DE Arsenal repo: send records from a Parquet
4
+ dataset (or a DuckDB query over one) to an HTTP endpoint or a Slack webhook, and
5
+ send each change once. The spec format, the ledger file and the CLI may change in
6
+ any 0.x release.
7
+
8
+ Each run compares the source with a local ledger of what the destination already
9
+ accepted, and sends only the difference:
10
+
11
+ | `mode` | Sends |
12
+ |---|---|
13
+ | `insert` | records whose key is new |
14
+ | `upsert` (default) | new keys, and keys whose content changed |
15
+ | `mirror` | the above, plus a delete request for keys that left the source |
16
+
17
+ ```yaml
18
+ # churn.yaml
19
+ name: churn-alerts
20
+ source:
21
+ type: parquet
22
+ path: data/marts/churn_risk
23
+ key: [customer_id]
24
+ destination:
25
+ type: http
26
+ url: https://api.example.com/v1/alerts
27
+ headers: { Authorization: "Bearer ${ALERTS_TOKEN}" }
28
+ body: { id: "{customer_id}", score: "{risk_score}", note: "risk for {customer_id}" }
29
+ idempotency_header: Idempotency-Key
30
+ rps: 5
31
+ ```
32
+
33
+ ```bash
34
+ pip install de-pilum
35
+ pilum plan churn.yaml # counts and sample keys; sends nothing, writes nothing
36
+ pilum run churn.yaml # exits 1 if any record was not delivered
37
+ pilum status churn.yaml # ledger size, last run, dead letters; exits 1 on alerts
38
+ pilum replay churn.yaml # put dead letters back in line for the next run
39
+ pilum reset churn.yaml --confirm # forget what was sent; next run sends everything
40
+ ```
41
+
42
+ ## What it guarantees, and what it does not
43
+
44
+ - **A record is recorded as sent only after a 2xx response.** If the process dies
45
+ between the response and the ledger write, the next run sends that record again
46
+ with the same `Idempotency-Key`.
47
+ - **Delivery is at-least-once.** It is exactly-once only when the endpoint
48
+ deduplicates on the idempotency header. Slack webhooks do not, so a crash at
49
+ the wrong moment can post one message twice.
50
+ - **The ledger is the only memory.** Pilum does not read the destination. If
51
+ something else changes the destination, Pilum does not notice; `reset` and
52
+ re-send is the way to resynchronise.
53
+ - **Rotating a token or changing the URL does not re-send anything.** The
54
+ dispatch id is derived from the dispatch name, the record key and the record
55
+ content only.
56
+
57
+ ## Failure handling
58
+
59
+ | Response | What happens |
60
+ |---|---|
61
+ | 2xx | recorded in the ledger |
62
+ | 408, 429, 5xx, network error | retried with backoff (`retry.max_attempts`); if every try fails the record stays queued for the next run, and moves to the dead-letter queue once its failed tries reach `dlq.after_attempts` |
63
+ | other 4xx | the record goes straight to the dead-letter queue with the response text |
64
+ | 401, 403 | the run stops; nothing is counted against the records |
65
+ | `safety.max_consecutive_failures` records fail in a row | the run stops: the destination is down |
66
+
67
+ A dead letter is skipped until `pilum replay`. If its source record changes, the
68
+ new version is sent normally and the dead letter is dropped.
69
+
70
+ ## Safety rails
71
+
72
+ - **First run.** With an empty ledger, a run that would send more than
73
+ `safety.max_first_dispatch` (1,000) records is refused unless
74
+ `--confirm-initial-load` is given.
75
+ - **Deletes.** A `mirror` run that would delete more than
76
+ `safety.max_delete_fraction` (50%) of the ledger is refused unless
77
+ `--confirm-deletes` is given. An empty or mis-pointed source otherwise looks
78
+ like "every record was removed".
79
+ - **One sender.** A second `run`, `replay` or `reset` on the same dispatch is
80
+ refused while one is in progress.
81
+ - **Secrets.** `${ENV_VAR}` in `url` and `headers` is read when a request is
82
+ sent. It is never written to the ledger or shown by `status`, and it is masked
83
+ in error messages. `${...}` is not expanded inside `body` or Slack `text`.
84
+
85
+ ## Not in this version
86
+
87
+ Bulk (multi-record) requests, OAuth token refresh, named SaaS connectors,
88
+ event-driven dispatch from a Hasta outbox, and `arsenal run` / Aquila
89
+ integration. Field reference: [dispatch-schema.md](https://github.com/KooEric/de-arsenal/blob/main/docs/reference/dispatch-schema.md).
@@ -0,0 +1,41 @@
1
+ [project]
2
+ name = "de-pilum"
3
+ version = "0.6.0"
4
+ description = "Pilum — reverse ETL: dispatch changed records from Parquet to HTTP endpoints and Slack, once per change"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ dependencies = [
10
+ "arsenal-core>=0.6,<0.7",
11
+ "duckdb>=1.0",
12
+ "httpx>=0.27",
13
+ "pyarrow>=17",
14
+ "pydantic>=2.7",
15
+ "pyyaml>=6",
16
+ "typer>=0.12",
17
+ ]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "License :: OSI Approved :: Apache Software License",
24
+ "Operating System :: OS Independent",
25
+ "Intended Audience :: Developers",
26
+ "Topic :: Database",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/KooEric/de-arsenal"
31
+ Repository = "https://github.com/KooEric/de-arsenal"
32
+
33
+ [project.scripts]
34
+ pilum = "pilum.cli:app"
35
+
36
+ [build-system]
37
+ requires = ["hatchling"]
38
+ build-backend = "hatchling.build"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/pilum"]
@@ -0,0 +1,17 @@
1
+ """Pilum — the javelin: send changed records out of the lake, once per change.
2
+
3
+ Experimental (0.6). A dispatch spec names a Parquet dataset or a query, a record
4
+ key and one destination (an HTTP endpoint or a Slack webhook). Each run diffs
5
+ the source against a local ledger and sends only new, changed or (in ``mirror``
6
+ mode) removed records. A record enters the ledger only after the destination
7
+ answers 2xx, so a crash re-sends it under the same idempotency key.
8
+ """
9
+
10
+ from importlib.metadata import PackageNotFoundError, version
11
+
12
+ try:
13
+ __version__ = version("de-pilum")
14
+ except PackageNotFoundError:
15
+ __version__ = "0.6.0"
16
+
17
+ __all__ = ["__version__"]
@@ -0,0 +1,147 @@
1
+ """Pilum CLI: plan, run, status, replay, reset."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import typer
10
+
11
+ from arsenal_core.errors import ArsenalError
12
+ from pilum.ledger import Ledger, RunLock, ledger_path
13
+ from pilum.loader import load_dispatch
14
+ from pilum.runner import dispatch_status, plan_dispatch, run_dispatch
15
+
16
+ app = typer.Typer(help="Pilum (experimental) — send changed records to HTTP endpoints and Slack.")
17
+
18
+ _SAMPLE = 3
19
+
20
+
21
+ def _fail(error: Exception) -> typer.Exit:
22
+ typer.echo(f"error: {error}", err=True)
23
+ return typer.Exit(1)
24
+
25
+
26
+ @app.command(name="plan")
27
+ def plan_cmd(spec_path: Path) -> None:
28
+ """Show what `run` would send. Sends nothing and writes nothing."""
29
+
30
+ try:
31
+ spec = load_dispatch(spec_path)
32
+ plan = plan_dispatch(spec)
33
+ except ArsenalError as error:
34
+ raise _fail(error) from error
35
+ samples: dict[str, list[Any]] = {}
36
+ for action in plan.actions:
37
+ bucket = samples.setdefault(action.kind, [])
38
+ if len(bucket) < _SAMPLE:
39
+ bucket.append(json.loads(action.record_key))
40
+ payload = {
41
+ "dispatch": spec.name,
42
+ "mode": spec.mode,
43
+ "first_dispatch": plan.first_dispatch,
44
+ **plan.summary(),
45
+ "sample_keys": samples,
46
+ }
47
+ typer.echo(json.dumps(payload, sort_keys=True))
48
+
49
+
50
+ @app.command(name="run")
51
+ def run_cmd(
52
+ spec_path: Path,
53
+ confirm_initial_load: bool = typer.Option(
54
+ False,
55
+ "--confirm-initial-load",
56
+ help="Allow a first run larger than safety.max_first_dispatch.",
57
+ ),
58
+ confirm_deletes: bool = typer.Option(
59
+ False,
60
+ "--confirm-deletes",
61
+ help="Allow a mirror run to delete more than safety.max_delete_fraction of the ledger.",
62
+ ),
63
+ ) -> None:
64
+ """Send new, changed and (mirror) removed records. Exits 1 if any were not delivered."""
65
+
66
+ try:
67
+ report = run_dispatch(
68
+ load_dispatch(spec_path),
69
+ confirm_initial_load=confirm_initial_load,
70
+ confirm_deletes=confirm_deletes,
71
+ )
72
+ except ArsenalError as error:
73
+ raise _fail(error) from error
74
+ typer.echo(json.dumps(report.to_dict(), sort_keys=True))
75
+ if not report.ok:
76
+ if report.aborted:
77
+ typer.echo(f"error: {report.aborted}", err=True)
78
+ raise typer.Exit(1)
79
+
80
+
81
+ @app.command(name="status")
82
+ def status_cmd(spec_path: Path) -> None:
83
+ """Ledger size, last run and dead letters as JSON. Exits 1 when something needs attention."""
84
+
85
+ try:
86
+ payload = dispatch_status(load_dispatch(spec_path))
87
+ except ArsenalError as error:
88
+ raise _fail(error) from error
89
+ typer.echo(json.dumps(payload, sort_keys=True))
90
+ if payload["alert"]:
91
+ raise typer.Exit(1)
92
+
93
+
94
+ @app.command(name="replay")
95
+ def replay_cmd(
96
+ spec_path: Path,
97
+ limit: int | None = typer.Option(None, "--limit", min=1, help="Requeue at most N."),
98
+ ) -> None:
99
+ """Put dead letters back in line. The next `run` sends their current version."""
100
+
101
+ try:
102
+ spec = load_dispatch(spec_path)
103
+ path = ledger_path(spec.state_dir, spec.name)
104
+ with RunLock(path):
105
+ ledger = Ledger(path)
106
+ try:
107
+ requeued = ledger.requeue(limit)
108
+ finally:
109
+ ledger.close()
110
+ except ArsenalError as error:
111
+ raise _fail(error) from error
112
+ typer.echo(json.dumps({"dispatch": spec.name, "requeued": requeued}, sort_keys=True))
113
+
114
+
115
+ @app.command(name="reset")
116
+ def reset_cmd(
117
+ spec_path: Path,
118
+ confirm: bool = typer.Option(False, "--confirm", help="Apply. Without it, only describe."),
119
+ ) -> None:
120
+ """Forget everything that was sent. The next run sends every record again."""
121
+
122
+ try:
123
+ spec = load_dispatch(spec_path)
124
+ path = ledger_path(spec.state_dir, spec.name)
125
+ with RunLock(path):
126
+ ledger = Ledger(path)
127
+ try:
128
+ size = ledger.size()
129
+ if confirm:
130
+ ledger.reset()
131
+ finally:
132
+ ledger.close()
133
+ except ArsenalError as error:
134
+ raise _fail(error) from error
135
+ payload = {
136
+ "dispatch": spec.name,
137
+ "action": "reset" if confirm else "dry-run",
138
+ "forgotten_records": size,
139
+ "warning": f"the next run re-sends all source records to {spec.destination.type}",
140
+ }
141
+ typer.echo(json.dumps(payload, sort_keys=True))
142
+ if not confirm:
143
+ typer.echo("dry-run: re-run with --confirm to apply", err=True)
144
+
145
+
146
+ if __name__ == "__main__": # pragma: no cover
147
+ app()