PyReverseETL 3.2.0__tar.gz → 3.3.1__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.
Files changed (97) hide show
  1. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/Cargo.lock +2 -2
  2. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/Cargo.toml +1 -1
  3. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/PKG-INFO +60 -4
  4. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/README.md +57 -3
  5. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/pyproject.toml +5 -1
  6. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/python/pyreverseetl/__init__.py +6 -0
  7. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/python/pyreverseetl/cli.py +109 -19
  8. pyreverseetl-3.3.1/python/pyreverseetl/secure_state.py +125 -0
  9. pyreverseetl-3.3.1/python/pyreverseetl/singer.py +114 -0
  10. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/LICENSE +0 -0
  11. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/Cargo.toml +0 -0
  12. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/benches/load_test.rs +0 -0
  13. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/bin/pyreverseetl_dashboard.rs +0 -0
  14. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/activation.rs +0 -0
  15. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/alert_compat.rs +0 -0
  16. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/error.rs +0 -0
  17. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/http_client.rs +0 -0
  18. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/hubspot.rs +0 -0
  19. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/mapping.rs +0 -0
  20. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/marketo.rs +0 -0
  21. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/mod.rs +0 -0
  22. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/oauth_manager.rs +0 -0
  23. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/retry_policy.rs +0 -0
  24. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/salesforce.rs +0 -0
  25. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/schema_detect.rs +0 -0
  26. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/adapters/webhook.rs +0 -0
  27. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/cdc/change_detector.rs +0 -0
  28. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/cdc/changelog.rs +0 -0
  29. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/cdc/checkpoint.rs +0 -0
  30. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/cdc/mod.rs +0 -0
  31. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/config.rs +0 -0
  32. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/connectors_db.rs +0 -0
  33. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/database_advanced.rs +0 -0
  34. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/destination.rs +0 -0
  35. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/error.rs +0 -0
  36. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/hdfs.rs +0 -0
  37. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/mod.rs +0 -0
  38. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/mysql.rs +0 -0
  39. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/object_storage.rs +0 -0
  40. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/postgres.rs +0 -0
  41. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/rate_limiting.rs +0 -0
  42. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/registry.rs +0 -0
  43. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/saas.rs +0 -0
  44. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/source.rs +0 -0
  45. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/connectors/web.rs +0 -0
  46. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/destination.rs +0 -0
  47. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/dlq.rs +0 -0
  48. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/entity.rs +0 -0
  49. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/error.rs +0 -0
  50. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/executor.rs +0 -0
  51. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/cached_gate.rs +0 -0
  52. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/compliance_rules.rs +0 -0
  53. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/credentials.rs +0 -0
  54. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/mod.rs +0 -0
  55. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/quality_gate.rs +0 -0
  56. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/retry_policy.rs +0 -0
  57. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/schema_evolution.rs +0 -0
  58. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/governance/statguardian_client.rs +0 -0
  59. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/idempotency.rs +0 -0
  60. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/lib.rs +0 -0
  61. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/lineage.rs +0 -0
  62. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/observability/dashboard_launcher.rs +0 -0
  63. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/observability/logs.rs +0 -0
  64. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/observability/metrics.rs +0 -0
  65. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/observability/metrics_server.rs +0 -0
  66. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/observability/mod.rs +0 -0
  67. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/observability/traces.rs +0 -0
  68. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/pipeline/activation_pipeline.rs +0 -0
  69. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/pipeline/backpressure.rs +0 -0
  70. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/pipeline/latency_tracker.rs +0 -0
  71. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/pipeline/mod.rs +0 -0
  72. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/sources/kafka.rs +0 -0
  73. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/sources/mod.rs +0 -0
  74. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/sources/polling.rs +0 -0
  75. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/sources/sync_config.rs +0 -0
  76. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/statguardian.rs +0 -0
  77. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/storage/mod.rs +0 -0
  78. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/storage/repository.rs +0 -0
  79. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/storage/schema.rs +0 -0
  80. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/streaming/event_processor.rs +0 -0
  81. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/streaming/event_schema.rs +0 -0
  82. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/streaming/mod.rs +0 -0
  83. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/streampdf.rs +0 -0
  84. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/streamxl.rs +0 -0
  85. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/sync.rs +0 -0
  86. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/testing/connector_test.rs +0 -0
  87. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/testing/harness.rs +0 -0
  88. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/testing/metrics.rs +0 -0
  89. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/testing/mock_http.rs +0 -0
  90. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/testing/mod.rs +0 -0
  91. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/testing/test_data.rs +0 -0
  92. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/transformers/mod.rs +0 -0
  93. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/transformers/spark.rs +0 -0
  94. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/core/src/workflow.rs +0 -0
  95. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/python/Cargo.toml +0 -0
  96. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/python/pyreverseetl/server.py +0 -0
  97. {pyreverseetl-3.2.0 → pyreverseetl-3.3.1}/python/src/lib.rs +0 -0
@@ -3199,7 +3199,7 @@ dependencies = [
3199
3199
 
3200
3200
  [[package]]
3201
3201
  name = "pyreverseetl"
3202
- version = "3.2.0"
3202
+ version = "3.3.1"
3203
3203
  dependencies = [
3204
3204
  "chrono",
3205
3205
  "pyo3",
@@ -3210,7 +3210,7 @@ dependencies = [
3210
3210
 
3211
3211
  [[package]]
3212
3212
  name = "pyreverseetl-core"
3213
- version = "3.2.0"
3213
+ version = "3.3.1"
3214
3214
  dependencies = [
3215
3215
  "async-trait",
3216
3216
  "aws-config",
@@ -3,7 +3,7 @@ members = ["core", "python"]
3
3
  resolver = "2"
4
4
 
5
5
  [workspace.package]
6
- version = "3.2.0"
6
+ version = "3.3.1"
7
7
  authors = ["Georgi Mammen Mullassery <mullassery@gmail.com>"]
8
8
  license = "Apache-2.0"
9
9
  repository = "https://github.com/Mullassery/PyReverseETL"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyReverseETL
3
- Version: 3.2.0
3
+ Version: 3.3.1
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Python :: 3
@@ -9,6 +9,8 @@ Classifier: Programming Language :: Python :: 3.10
9
9
  Classifier: Programming Language :: Python :: 3.11
10
10
  Classifier: Programming Language :: Python :: 3.12
11
11
  Classifier: Programming Language :: Python :: 3.13
12
+ Requires-Dist: cryptography>=42
13
+ Requires-Dist: keyring>=24
12
14
  Requires-Dist: pytest>=7.0 ; extra == 'dev'
13
15
  Requires-Dist: ruff>=0.6 ; extra == 'dev'
14
16
  Provides-Extra: dev
@@ -167,6 +169,43 @@ pyreverseetl execute ltv_to_hook --compliance-rules \
167
169
  '[{"id":"mask_email","rule_type":"pii_masking","target_fields":["email"],"action":{"type":"mask","pattern":"****"}}]'
168
170
  ```
169
171
 
172
+ ## Singer target protocol
173
+
174
+ Consume Singer NDJSON and forward RECORD batches to a sink:
175
+
176
+ ```bash
177
+ cat singer-output.ndjson | pyreverseetl-singer-target --output records.jsonl
178
+ ```
179
+
180
+ ```python
181
+ from pyreverseetl.singer import run_target, jsonl_sink
182
+ run_target(lines, jsonl_sink("records.jsonl"))
183
+ ```
184
+
185
+ Supported messages: SCHEMA, RECORD (batched) and STATE (flushes the batch).
186
+ This is a protocol adapter; native Rust connectors remain the execution path.
187
+
188
+ ## Changelog
189
+
190
+ ### 3.3.1
191
+ - Encrypted CLI state (Fernet/keyring) with legacy plaintext migration.
192
+ - Key export/import for backup and recovery.
193
+ - Singer SCHEMA/RECORD/STATE target adapter.
194
+
195
+ ## Encrypted local state
196
+
197
+ Workflow/activation credentials are no longer stored as plaintext JSON. The CLI
198
+ state file is encrypted with Fernet; the key lives in the OS keyring, or in
199
+ `PYREVERSEETL_STATE_KEY` for headless CI:
200
+
201
+ ```bash
202
+ export PYREVERSEETL_STATE_KEY="$(python -c 'from cryptography.fernet import Fernet;print(Fernet.generate_key().decode())')"
203
+ ```
204
+
205
+ Existing plaintext state is read and transparently re-encrypted on the next
206
+ save. Losing the key means losing the local state file (re-enter credentials);
207
+ the error is explicit rather than silently falling back to plaintext.
208
+
170
209
  ## Usage
171
210
 
172
211
  ### Python API
@@ -252,12 +291,17 @@ Python CLI / API → pyreverseetl._core (PyO3 bindings) → pyreverseetl_cor
252
291
  ## Validation gate
253
292
 
254
293
  ```bash
294
+ # File-based report
255
295
  pyreverseetl execute-activation my-activation --validation-report statguardian-report.json
296
+
297
+ # Live StatGuardian service: validate a sample before the real sync
298
+ pyreverseetl execute-activation my-activation --statguardian-url http://127.0.0.1:8000
256
299
  ```
257
300
 
258
- The report must be a JSON object with `"passed": true`; anything else blocks
259
- the sync before reading or writing data. This is a file-based gate until a live
260
- StatGuardian service endpoint is available.
301
+ A file report must have `"passed": true`; anything else blocks the sync. The
302
+ live `--statguardian-url` gate dry-runs a sample and calls the service's
303
+ `/validate`; a failure or network error blocks the real sync. It is a sample
304
+ gate, not a full-table scan.
261
305
 
262
306
  ## Documentation
263
307
 
@@ -268,6 +312,18 @@ StatGuardian service endpoint is available.
268
312
  - [COMPLIANCE_CHECKLIST.md](COMPLIANCE_CHECKLIST.md) — compliance posture.
269
313
  - [SECURITY.md](SECURITY.md) — how to report a vulnerability.
270
314
 
315
+ ## Known issues and deferred work
316
+
317
+ **Blocked / failed:**
318
+ - Live Salesforce/HubSpot/Marketo verification (no accounts).
319
+ - Scheduler/run-history observability.
320
+ - CDC/streaming.
321
+
322
+ **Rejected / deferred:**
323
+ - Spark transforms and streaming CDC now — outside the proven sync path.
324
+
325
+ Full shipped/blocked/rejected detail: [`QUEUE_STATUS.md`](QUEUE_STATUS.md).
326
+
271
327
  ## Contributing
272
328
 
273
329
  See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and
@@ -144,6 +144,43 @@ pyreverseetl execute ltv_to_hook --compliance-rules \
144
144
  '[{"id":"mask_email","rule_type":"pii_masking","target_fields":["email"],"action":{"type":"mask","pattern":"****"}}]'
145
145
  ```
146
146
 
147
+ ## Singer target protocol
148
+
149
+ Consume Singer NDJSON and forward RECORD batches to a sink:
150
+
151
+ ```bash
152
+ cat singer-output.ndjson | pyreverseetl-singer-target --output records.jsonl
153
+ ```
154
+
155
+ ```python
156
+ from pyreverseetl.singer import run_target, jsonl_sink
157
+ run_target(lines, jsonl_sink("records.jsonl"))
158
+ ```
159
+
160
+ Supported messages: SCHEMA, RECORD (batched) and STATE (flushes the batch).
161
+ This is a protocol adapter; native Rust connectors remain the execution path.
162
+
163
+ ## Changelog
164
+
165
+ ### 3.3.1
166
+ - Encrypted CLI state (Fernet/keyring) with legacy plaintext migration.
167
+ - Key export/import for backup and recovery.
168
+ - Singer SCHEMA/RECORD/STATE target adapter.
169
+
170
+ ## Encrypted local state
171
+
172
+ Workflow/activation credentials are no longer stored as plaintext JSON. The CLI
173
+ state file is encrypted with Fernet; the key lives in the OS keyring, or in
174
+ `PYREVERSEETL_STATE_KEY` for headless CI:
175
+
176
+ ```bash
177
+ export PYREVERSEETL_STATE_KEY="$(python -c 'from cryptography.fernet import Fernet;print(Fernet.generate_key().decode())')"
178
+ ```
179
+
180
+ Existing plaintext state is read and transparently re-encrypted on the next
181
+ save. Losing the key means losing the local state file (re-enter credentials);
182
+ the error is explicit rather than silently falling back to plaintext.
183
+
147
184
  ## Usage
148
185
 
149
186
  ### Python API
@@ -229,12 +266,17 @@ Python CLI / API → pyreverseetl._core (PyO3 bindings) → pyreverseetl_cor
229
266
  ## Validation gate
230
267
 
231
268
  ```bash
269
+ # File-based report
232
270
  pyreverseetl execute-activation my-activation --validation-report statguardian-report.json
271
+
272
+ # Live StatGuardian service: validate a sample before the real sync
273
+ pyreverseetl execute-activation my-activation --statguardian-url http://127.0.0.1:8000
233
274
  ```
234
275
 
235
- The report must be a JSON object with `"passed": true`; anything else blocks
236
- the sync before reading or writing data. This is a file-based gate until a live
237
- StatGuardian service endpoint is available.
276
+ A file report must have `"passed": true`; anything else blocks the sync. The
277
+ live `--statguardian-url` gate dry-runs a sample and calls the service's
278
+ `/validate`; a failure or network error blocks the real sync. It is a sample
279
+ gate, not a full-table scan.
238
280
 
239
281
  ## Documentation
240
282
 
@@ -245,6 +287,18 @@ StatGuardian service endpoint is available.
245
287
  - [COMPLIANCE_CHECKLIST.md](COMPLIANCE_CHECKLIST.md) — compliance posture.
246
288
  - [SECURITY.md](SECURITY.md) — how to report a vulnerability.
247
289
 
290
+ ## Known issues and deferred work
291
+
292
+ **Blocked / failed:**
293
+ - Live Salesforce/HubSpot/Marketo verification (no accounts).
294
+ - Scheduler/run-history observability.
295
+ - CDC/streaming.
296
+
297
+ **Rejected / deferred:**
298
+ - Spark transforms and streaming CDC now — outside the proven sync path.
299
+
300
+ Full shipped/blocked/rejected detail: [`QUEUE_STATUS.md`](QUEUE_STATUS.md).
301
+
248
302
  ## Contributing
249
303
 
250
304
  See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and
@@ -4,11 +4,15 @@ build-backend = "maturin"
4
4
 
5
5
  [project]
6
6
  name = "PyReverseETL"
7
- version = "3.2.0"
7
+ version = "3.3.1"
8
8
  description = "The Open Operational Data Activation Runtime"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
11
11
  authors = [{ name = "Georgi Mammen Mullassery", email = "mullassery@gmail.com" }]
12
+ dependencies = [
13
+ "cryptography>=42",
14
+ "keyring>=24",
15
+ ]
12
16
  requires-python = ">=3.9"
13
17
  classifiers = [
14
18
  "Development Status :: 4 - Beta",
@@ -4,6 +4,7 @@ Re-exports the compiled Rust core's public classes so they're reachable as
4
4
  `pyreverseetl.X` instead of requiring `pyreverseetl._core.X`.
5
5
  """
6
6
 
7
+ from .singer import SingerBatch, SingerSchema, jsonl_sink, parse_messages, run_target
7
8
  from ._core import (
8
9
  PyActivation,
9
10
  PyDestination,
@@ -28,4 +29,9 @@ __all__ = [
28
29
  "lineage_dot",
29
30
  "lineage_json",
30
31
  "run_sync",
32
+ "SingerBatch",
33
+ "SingerSchema",
34
+ "parse_messages",
35
+ "run_target",
36
+ "jsonl_sink",
31
37
  ]
@@ -27,10 +27,49 @@ from __future__ import annotations
27
27
  import json
28
28
  import os
29
29
  import sys
30
+ import urllib.error
31
+ import urllib.request
30
32
 
31
33
  DEFAULT_STATE_PATH = os.path.join(os.path.expanduser("~"), ".pyreverseetl", "state.json")
32
34
 
33
35
 
36
+ def validate_activation_rows(
37
+ rows: list[dict],
38
+ service_url: str,
39
+ *,
40
+ limit: int = 100,
41
+ timeout_seconds: float = 10.0,
42
+ ) -> tuple[bool, dict]:
43
+ """POST sample rows to StatGuardian's ``/validate`` endpoint.
44
+
45
+ Fails closed on network/HTTP/parse errors. Only the first ``limit`` rows
46
+ are checked; this is a pre-activation sample gate, not a full-table scan.
47
+ """
48
+ url = service_url.rstrip("/") + "/validate"
49
+ checked = 0
50
+ for row in rows[: max(1, limit)]:
51
+ checked += 1
52
+ body = json.dumps({"entity": {"attributes": row}}).encode("utf-8")
53
+ request = urllib.request.Request(
54
+ url,
55
+ data=body,
56
+ headers={"Content-Type": "application/json"},
57
+ method="POST",
58
+ )
59
+ try:
60
+ with urllib.request.urlopen(request, timeout=timeout_seconds) as response:
61
+ payload = json.loads(response.read().decode("utf-8"))
62
+ except (urllib.error.URLError, OSError, ValueError) as exc:
63
+ return False, {"reason": f"StatGuardian request failed: {exc}", "checked": checked}
64
+ if payload.get("passed") is not True:
65
+ return False, {
66
+ "reason": "StatGuardian rejected a sample row",
67
+ "checked": checked,
68
+ "issues": payload.get("issues", []),
69
+ }
70
+ return True, {"checked": checked}
71
+
72
+
34
73
  def validation_report_allows(path: str) -> tuple[bool, dict]:
35
74
  """Read a StatGuardian-style JSON report and decide whether sync may run.
36
75
 
@@ -64,25 +103,20 @@ class CLIInterface:
64
103
  self._load_state()
65
104
 
66
105
  def _load_state(self):
67
- try:
68
- with open(self.state_path) as f:
69
- data = json.load(f)
70
- self.workflows = data.get("workflows", {})
71
- self.activations = data.get("activations", {})
72
- self.runs = data.get("runs", {})
73
- except (FileNotFoundError, json.JSONDecodeError):
74
- pass
106
+ from .secure_state import load_state
107
+
108
+ data = load_state(self.state_path)
109
+ self.workflows = data.get("workflows", {})
110
+ self.activations = data.get("activations", {})
111
+ self.runs = data.get("runs", {})
75
112
 
76
113
  def _save_state(self):
77
- directory = os.path.dirname(self.state_path)
78
- if directory:
79
- os.makedirs(directory, exist_ok=True)
80
- with open(self.state_path, "w") as f:
81
- json.dump(
82
- {"workflows": self.workflows, "activations": self.activations, "runs": self.runs},
83
- f,
84
- indent=2,
85
- )
114
+ from .secure_state import save_state
115
+
116
+ save_state(
117
+ self.state_path,
118
+ {"workflows": self.workflows, "activations": self.activations, "runs": self.runs},
119
+ )
86
120
 
87
121
  def create_workflow(
88
122
  self,
@@ -185,6 +219,8 @@ class CLIInterface:
185
219
  idempotency_store_path: str | None = None,
186
220
  dlq_store_path: str | None = None,
187
221
  validation_report_path: str | None = None,
222
+ statguardian_url: str | None = None,
223
+ statguardian_limit: int = 100,
188
224
  ) -> dict:
189
225
  """Execute an activation: run a real sync through the Rust engine.
190
226
 
@@ -226,8 +262,13 @@ class CLIInterface:
226
262
  validation_report_path: Optional path to a JSON validation report
227
263
  (``{"passed": bool, ...}``). If supplied and not passing, the
228
264
  sync is blocked before any source read or destination write.
229
- This is a file-based StatGuardian gate; it does not call the
230
- StatGuardian service.
265
+ This is a file-based StatGuardian gate.
266
+ statguardian_url: Optional base URL of a running StatGuardian
267
+ service. A dry-run reads a sample of source rows and POSTs them
268
+ to ``/validate``; any failure (or network error) blocks the real
269
+ sync. This doubles the source read for the sample pass.
270
+ statguardian_limit: Maximum sample rows sent to StatGuardian
271
+ (default 100).
231
272
  dlq_store_path: Optional path to a SQLite file used as a
232
273
  dead-letter queue (quarantine) for records the destination
233
274
  rejects. Each failed record is stored with its run id, the
@@ -276,6 +317,38 @@ class CLIInterface:
276
317
  source_config.setdefault("table", workflow.get("table"))
277
318
  destination_config = activation.get("destination_config") or {}
278
319
 
320
+ if statguardian_url:
321
+ try:
322
+ preview = _core.run_sync(
323
+ source_type=workflow["source"],
324
+ source_config=json.dumps(source_config),
325
+ destination_type=activation["destination"],
326
+ destination_config=json.dumps(destination_config),
327
+ limit=limit,
328
+ compliance_rules=json.dumps(compliance_rules) if compliance_rules else None,
329
+ dry_run=True,
330
+ schema_store_path=None,
331
+ idempotency_store_path=None,
332
+ dlq_store_path=None,
333
+ )
334
+ except Exception as exc: # noqa: BLE001
335
+ return {
336
+ "status": "error",
337
+ "activation_id": activation_id,
338
+ "message": f"StatGuardian sample read failed: {exc}",
339
+ }
340
+ sample_rows = [json.loads(row) for row in preview.dry_run_preview]
341
+ allowed, detail = validate_activation_rows(
342
+ sample_rows, statguardian_url, limit=statguardian_limit
343
+ )
344
+ if not allowed:
345
+ return {
346
+ "status": "error",
347
+ "activation_id": activation_id,
348
+ "message": "Blocked by StatGuardian sample validation",
349
+ "validation": detail,
350
+ }
351
+
279
352
  try:
280
353
  result = _core.run_sync(
281
354
  source_type=workflow["source"],
@@ -546,6 +619,21 @@ def main():
546
619
  sys.exit(1)
547
620
  validation_report_path = sys.argv[idx + 1]
548
621
 
622
+ statguardian_url = None
623
+ if "--statguardian-url" in sys.argv:
624
+ idx = sys.argv.index("--statguardian-url")
625
+ if idx + 1 >= len(sys.argv):
626
+ print(json.dumps({"error": "--statguardian-url requires a URL"}))
627
+ sys.exit(1)
628
+ statguardian_url = sys.argv[idx + 1]
629
+ statguardian_limit = 100
630
+ if "--statguardian-limit" in sys.argv:
631
+ idx = sys.argv.index("--statguardian-limit")
632
+ if idx + 1 >= len(sys.argv):
633
+ print(json.dumps({"error": "--statguardian-limit requires a number"}))
634
+ sys.exit(1)
635
+ statguardian_limit = int(sys.argv[idx + 1])
636
+
549
637
  result = cli.execute_activation(
550
638
  activation_id,
551
639
  limit,
@@ -555,6 +643,8 @@ def main():
555
643
  idempotency_store_path,
556
644
  dlq_store_path,
557
645
  validation_report_path,
646
+ statguardian_url,
647
+ statguardian_limit,
558
648
  )
559
649
  print(json.dumps(result))
560
650
 
@@ -0,0 +1,125 @@
1
+ """Encrypted local state storage.
2
+
3
+ Workflow/activation configs can contain database and API credentials. The CLI
4
+ state file is encrypted with Fernet; the key lives in the OS keyring (or
5
+ ``PYREVERSEETL_STATE_KEY`` for headless CI). Existing plaintext state is
6
+ read and transparently re-encrypted on the next save.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import secrets
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from cryptography.fernet import Fernet, InvalidToken
18
+
19
+ KEYRING_SERVICE = "pyreverseetl"
20
+ KEYRING_USER = "state-key"
21
+ ENV_KEY = "PYREVERSEETL_STATE_KEY"
22
+
23
+
24
+ class SecureStateError(RuntimeError):
25
+ """Raised when state encryption/decryption cannot be performed."""
26
+
27
+
28
+ def _load_key() -> bytes:
29
+ env = os.environ.get(ENV_KEY)
30
+ if env:
31
+ return env.encode("ascii")
32
+ try:
33
+ import keyring
34
+ except ImportError as exc:
35
+ raise SecureStateError(
36
+ "keyring is required to store the state encryption key; install "
37
+ "`pip install keyring` or set PYREVERSEETL_STATE_KEY."
38
+ ) from exc
39
+ stored = keyring.get_password(KEYRING_SERVICE, KEYRING_USER)
40
+ if stored:
41
+ return stored.encode("ascii")
42
+ key = Fernet.generate_key()
43
+ keyring.set_password(KEYRING_SERVICE, KEYRING_USER, key.decode("ascii"))
44
+ return key
45
+
46
+
47
+ def encrypt_bytes(payload: bytes, key: bytes | None = None) -> bytes:
48
+ return Fernet(key or _load_key()).encrypt(payload)
49
+
50
+
51
+ def decrypt_bytes(token: bytes, key: bytes | None = None) -> bytes:
52
+ try:
53
+ return Fernet(key or _load_key()).decrypt(token)
54
+ except InvalidToken as exc:
55
+ raise SecureStateError("state file could not be decrypted with the stored key") from exc
56
+
57
+
58
+ def load_state(path: str | Path) -> dict[str, Any]:
59
+ path = Path(path)
60
+ if not path.is_file():
61
+ return {}
62
+ raw = path.read_bytes()
63
+ if not raw.strip():
64
+ return {}
65
+ # Try encrypted first, then fall back to legacy plaintext JSON.
66
+ try:
67
+ decoded = decrypt_bytes(raw)
68
+ data = json.loads(decoded.decode("utf-8"))
69
+ return data if isinstance(data, dict) else {}
70
+ except (SecureStateError, ValueError, json.JSONDecodeError):
71
+ pass
72
+ try:
73
+ data = json.loads(raw.decode("utf-8"))
74
+ return data if isinstance(data, dict) else {}
75
+ except (ValueError, json.JSONDecodeError):
76
+ raise SecureStateError(f"state file {path} is neither encrypted nor valid JSON")
77
+
78
+
79
+ def save_state(path: str | Path, data: dict[str, Any]) -> None:
80
+ path = Path(path)
81
+ path.parent.mkdir(parents=True, exist_ok=True)
82
+ token = encrypt_bytes(json.dumps(data, indent=2).encode("utf-8"))
83
+ tmp = path.with_name(f".{path.name}.{secrets.token_hex(4)}.tmp")
84
+ tmp.write_bytes(token)
85
+ os.replace(tmp, path)
86
+
87
+
88
+ __all__ = [
89
+ "ENV_KEY",
90
+ "SecureStateError",
91
+ "decrypt_bytes",
92
+ "encrypt_bytes",
93
+ "load_state",
94
+ "save_state",
95
+ ]
96
+
97
+
98
+ def export_key(path: str | Path) -> str:
99
+ """Export the active Fernet key (0600) for backup/recovery."""
100
+ key = _load_key()
101
+ path = Path(path)
102
+ path.parent.mkdir(parents=True, exist_ok=True)
103
+ path.write_bytes(key)
104
+ try:
105
+ os.chmod(path, 0o600)
106
+ except OSError:
107
+ pass
108
+ return str(path)
109
+
110
+
111
+ def import_key(path: str | Path) -> None:
112
+ """Validate and install a key from a backup file into the keyring/env."""
113
+ key = Path(path).read_bytes().strip()
114
+ Fernet(key) # validates key shape
115
+ try:
116
+ import keyring
117
+
118
+ keyring.set_password(KEYRING_SERVICE, KEYRING_USER, key.decode("ascii"))
119
+ except ImportError as exc:
120
+ raise SecureStateError(
121
+ "keyring is not installed; set PYREVERSEETL_STATE_KEY to the imported key"
122
+ ) from exc
123
+
124
+
125
+ __all__ += ["export_key", "import_key"]
@@ -0,0 +1,114 @@
1
+ """Singer protocol target adapter.
2
+
3
+ Singer is the open tap/target protocol used by Meltano and many connectors.
4
+ This module parses Singer NDJSON messages and forwards RECORD batches to a
5
+ caller-provided sink. It is a protocol adapter, not a replacement for
6
+ PyReverseETL's native connectors.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from collections.abc import Iterable
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any, Callable
17
+
18
+
19
+ @dataclass
20
+ class SingerSchema:
21
+ stream: str
22
+ schema: dict[str, Any]
23
+ key_properties: list[str] = field(default_factory=list)
24
+
25
+
26
+ @dataclass
27
+ class SingerBatch:
28
+ schema: SingerSchema | None = None
29
+ records: list[dict[str, Any]] = field(default_factory=list)
30
+ state: dict[str, Any] | None = None
31
+
32
+
33
+ def parse_messages(lines: Iterable[str]) -> Iterable[dict[str, Any]]:
34
+ for line in lines:
35
+ line = line.strip()
36
+ if not line:
37
+ continue
38
+ message = json.loads(line)
39
+ if isinstance(message, dict) and "type" in message:
40
+ yield message
41
+
42
+
43
+ def run_target(
44
+ lines: Iterable[str],
45
+ sink: Callable[[SingerSchema, list[dict[str, Any]]], None],
46
+ *,
47
+ batch_size: int = 1000,
48
+ ) -> int:
49
+ """Consume Singer messages, batching RECORDs per stream into ``sink``."""
50
+ schema: SingerSchema | None = None
51
+ batch: list[dict[str, Any]] = []
52
+ written = 0
53
+
54
+ def flush() -> None:
55
+ nonlocal batch, written
56
+ if schema is not None and batch:
57
+ sink(schema, batch)
58
+ written += len(batch)
59
+ batch = []
60
+
61
+ for message in parse_messages(lines):
62
+ kind = message.get("type")
63
+ if kind == "SCHEMA":
64
+ flush()
65
+ schema = SingerSchema(
66
+ stream=str(message.get("stream") or "default"),
67
+ schema=message.get("schema") or {},
68
+ key_properties=list(message.get("key_properties") or []),
69
+ )
70
+ elif kind == "RECORD":
71
+ if schema is None:
72
+ raise ValueError("RECORD received before SCHEMA")
73
+ batch.append(dict(message.get("record") or {}))
74
+ if len(batch) >= batch_size:
75
+ flush()
76
+ elif kind == "STATE":
77
+ flush()
78
+ flush()
79
+ return written
80
+
81
+
82
+ def jsonl_sink(path: str | Path) -> Callable[[SingerSchema, list[dict[str, Any]]], None]:
83
+ path = Path(path)
84
+ path.parent.mkdir(parents=True, exist_ok=True)
85
+
86
+ def sink(schema: SingerSchema, records: list[dict[str, Any]]) -> None:
87
+ with path.open("a", encoding="utf-8") as handle:
88
+ for record in records:
89
+ handle.write(json.dumps({"stream": schema.stream, "record": record}) + "\n")
90
+
91
+ return sink
92
+
93
+
94
+ def main(argv: list[str] | None = None) -> int:
95
+ import argparse
96
+
97
+ parser = argparse.ArgumentParser(prog="pyreverseetl-singer-target")
98
+ parser.add_argument("--output", required=True, help="JSONL output path")
99
+ parser.add_argument("--input", default="-", help="Singer NDJSON file or - for stdin")
100
+ args = parser.parse_args(argv)
101
+ if args.input == "-":
102
+ count = run_target(sys.stdin, jsonl_sink(args.output))
103
+ else:
104
+ with open(args.input, encoding="utf-8") as stream:
105
+ count = run_target(stream, jsonl_sink(args.output))
106
+ print(f"wrote {count} record(s) to {args.output}")
107
+ return 0
108
+
109
+
110
+ if __name__ == "__main__":
111
+ raise SystemExit(main())
112
+
113
+
114
+ __all__ = ["SingerBatch", "SingerSchema", "jsonl_sink", "main", "parse_messages", "run_target"]
File without changes