hindsightdb 0.1.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.
Files changed (65) hide show
  1. hindsightdb-0.1.0/LICENSE +201 -0
  2. hindsightdb-0.1.0/PKG-INFO +36 -0
  3. hindsightdb-0.1.0/README.md +1 -0
  4. hindsightdb-0.1.0/hindsight/__init__.py +251 -0
  5. hindsightdb-0.1.0/hindsight/canonical.py +145 -0
  6. hindsightdb-0.1.0/hindsight/cli/__init__.py +0 -0
  7. hindsightdb-0.1.0/hindsight/cli/apply.py +93 -0
  8. hindsightdb-0.1.0/hindsight/cli/audit.py +180 -0
  9. hindsightdb-0.1.0/hindsight/cli/check.py +46 -0
  10. hindsightdb-0.1.0/hindsight/cli/client.py +193 -0
  11. hindsightdb-0.1.0/hindsight/cli/config.py +150 -0
  12. hindsightdb-0.1.0/hindsight/cli/doctor.py +182 -0
  13. hindsightdb-0.1.0/hindsight/cli/genesis.py +155 -0
  14. hindsightdb-0.1.0/hindsight/cli/main.py +392 -0
  15. hindsightdb-0.1.0/hindsight/cli/materialize.py +41 -0
  16. hindsightdb-0.1.0/hindsight/cli/reconcile.py +259 -0
  17. hindsightdb-0.1.0/hindsight/cli/scan.py +64 -0
  18. hindsightdb-0.1.0/hindsight/cli/wal.py +120 -0
  19. hindsightdb-0.1.0/hindsight/config.py +180 -0
  20. hindsightdb-0.1.0/hindsight/contract.py +91 -0
  21. hindsightdb-0.1.0/hindsight/keys.py +35 -0
  22. hindsightdb-0.1.0/hindsight/outbox/__init__.py +1 -0
  23. hindsightdb-0.1.0/hindsight/outbox/adapter.py +65 -0
  24. hindsightdb-0.1.0/hindsight/outbox/catalog.py +111 -0
  25. hindsightdb-0.1.0/hindsight/outbox/db.py +135 -0
  26. hindsightdb-0.1.0/hindsight/outbox/shipper.py +328 -0
  27. hindsightdb-0.1.0/hindsight/outbox/spec.py +43 -0
  28. hindsightdb-0.1.0/hindsight/outbox/sql.py +190 -0
  29. hindsightdb-0.1.0/hindsight/py.typed +0 -0
  30. hindsightdb-0.1.0/hindsight/queue.py +95 -0
  31. hindsightdb-0.1.0/hindsight/restore.py +104 -0
  32. hindsightdb-0.1.0/hindsight/shipper.py +213 -0
  33. hindsightdb-0.1.0/hindsight/sqlalchemy/__init__.py +4 -0
  34. hindsightdb-0.1.0/hindsight/sqlalchemy/adapter.py +403 -0
  35. hindsightdb-0.1.0/hindsight/sqlalchemy/manifest.py +89 -0
  36. hindsightdb-0.1.0/hindsight/transport.py +52 -0
  37. hindsightdb-0.1.0/hindsight/wal/__init__.py +25 -0
  38. hindsightdb-0.1.0/hindsight/wal/pgoutput.py +372 -0
  39. hindsightdb-0.1.0/hindsight/wal/reader.py +695 -0
  40. hindsightdb-0.1.0/hindsight/wal/sql.py +137 -0
  41. hindsightdb-0.1.0/hindsightdb.egg-info/PKG-INFO +36 -0
  42. hindsightdb-0.1.0/hindsightdb.egg-info/SOURCES.txt +63 -0
  43. hindsightdb-0.1.0/hindsightdb.egg-info/dependency_links.txt +1 -0
  44. hindsightdb-0.1.0/hindsightdb.egg-info/entry_points.txt +2 -0
  45. hindsightdb-0.1.0/hindsightdb.egg-info/requires.txt +22 -0
  46. hindsightdb-0.1.0/hindsightdb.egg-info/top_level.txt +1 -0
  47. hindsightdb-0.1.0/pyproject.toml +71 -0
  48. hindsightdb-0.1.0/setup.cfg +4 -0
  49. hindsightdb-0.1.0/tests/test_canonical.py +77 -0
  50. hindsightdb-0.1.0/tests/test_cli.py +74 -0
  51. hindsightdb-0.1.0/tests/test_config.py +93 -0
  52. hindsightdb-0.1.0/tests/test_config_cli.py +190 -0
  53. hindsightdb-0.1.0/tests/test_outbox_adapter.py +107 -0
  54. hindsightdb-0.1.0/tests/test_outbox_pg.py +262 -0
  55. hindsightdb-0.1.0/tests/test_outbox_shipper.py +340 -0
  56. hindsightdb-0.1.0/tests/test_outbox_sql.py +126 -0
  57. hindsightdb-0.1.0/tests/test_queue_shipper.py +104 -0
  58. hindsightdb-0.1.0/tests/test_sqlalchemy_adapter.py +201 -0
  59. hindsightdb-0.1.0/tests/test_step4_cli.py +491 -0
  60. hindsightdb-0.1.0/tests/test_wal_assembler.py +351 -0
  61. hindsightdb-0.1.0/tests/test_wal_cli.py +139 -0
  62. hindsightdb-0.1.0/tests/test_wal_pg.py +246 -0
  63. hindsightdb-0.1.0/tests/test_wal_pgoutput.py +247 -0
  64. hindsightdb-0.1.0/tests/test_wal_reader.py +300 -0
  65. hindsightdb-0.1.0/tests/test_wal_sql.py +245 -0
@@ -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 Hindsight
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,36 @@
1
+ Metadata-Version: 2.4
2
+ Name: hindsightdb
3
+ Version: 0.1.0
4
+ Summary: Capture PostgreSQL row changes for per-field history, blame, and time travel.
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://hindsightdb.com
7
+ Keywords: postgresql,audit-log,change-data-capture,data-lineage,temporal-data
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Topic :: Database
12
+ Classifier: Topic :: System :: Logging
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: sqlalchemy
18
+ Requires-Dist: sqlalchemy>=2.0; extra == "sqlalchemy"
19
+ Provides-Extra: yaml
20
+ Requires-Dist: pyyaml>=6.0; extra == "yaml"
21
+ Provides-Extra: outbox
22
+ Requires-Dist: psycopg[binary]>=3.1; extra == "outbox"
23
+ Provides-Extra: wal
24
+ Requires-Dist: psycopg[binary]>=3.1; extra == "wal"
25
+ Provides-Extra: dev
26
+ Requires-Dist: sqlalchemy>=2.0; extra == "dev"
27
+ Requires-Dist: pyyaml>=6.0; extra == "dev"
28
+ Requires-Dist: psycopg[binary]>=3.1; extra == "dev"
29
+ Requires-Dist: pytest>=8.0; extra == "dev"
30
+ Requires-Dist: black>=24.0; extra == "dev"
31
+ Requires-Dist: ruff>=0.4; extra == "dev"
32
+ Requires-Dist: mypy>=1.10; extra == "dev"
33
+ Requires-Dist: types-PyYAML; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # hindsightdb — the Hindsight capture SDK: ship row changes from your app to Hindsight, for per-field history, blame and time travel.
@@ -0,0 +1 @@
1
+ # hindsightdb — the Hindsight capture SDK: ship row changes from your app to Hindsight, for per-field history, blame and time travel.
@@ -0,0 +1,251 @@
1
+ """Public API for Hindsight capture."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import atexit
6
+ import logging
7
+ import os
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ from hindsight.config import CaptureConfig
12
+ from hindsight.contract import SDK_VERSION
13
+ from hindsight.keys import parse_key, resolve_key, resolve_url
14
+ from hindsight.queue import RowQueue
15
+ from hindsight.shipper import Shipper
16
+ from hindsight.transport import Transport, UrllibTransport
17
+
18
+ __all__ = ["init", "shutdown", "flush", "stats", "Client", "CaptureConfig", "SDK_VERSION"]
19
+
20
+ log = logging.getLogger("hindsight")
21
+ _client: Client | None = None
22
+
23
+
24
+ class Client:
25
+ def __init__(
26
+ self,
27
+ *,
28
+ slug: str,
29
+ transport: Transport,
30
+ cfg: CaptureConfig,
31
+ queue_size: int = 10_000,
32
+ batch_rows: int = 500,
33
+ batch_interval: float = 2.0,
34
+ spool_dir: str | None = None,
35
+ producer: str = "orm",
36
+ ):
37
+ self.slug = slug
38
+ self.cfg = cfg
39
+ self.queue = RowQueue(queue_size)
40
+ self.shipper = Shipper(
41
+ transport,
42
+ slug,
43
+ self.queue,
44
+ producer=producer,
45
+ batch_rows=batch_rows,
46
+ batch_interval=batch_interval,
47
+ spool_dir=spool_dir,
48
+ )
49
+ self.adapter: Any = None
50
+ self.outbox: Any = None
51
+ self.manifest: dict[str, Any] | None = None
52
+
53
+ def set_metadata(self, metadata: Any) -> None:
54
+ from hindsight.sqlalchemy.manifest import build_manifest
55
+
56
+ self.manifest = build_manifest(metadata, self.cfg)
57
+ self.shipper.set_manifest(self.manifest)
58
+
59
+ def attach_sqlalchemy(
60
+ self, engine: Any, context_provider: Callable[[], dict[str, Any] | None] | None
61
+ ) -> None:
62
+ from hindsight.sqlalchemy.adapter import SQLAlchemyAdapter
63
+
64
+ self.adapter = SQLAlchemyAdapter(
65
+ self.queue,
66
+ self.cfg,
67
+ engine=engine,
68
+ context_provider=context_provider,
69
+ on_manifest=self.set_metadata,
70
+ )
71
+ self.adapter.install()
72
+
73
+ def attach_outbox(
74
+ self,
75
+ dsn: str,
76
+ *,
77
+ engine: Any = None,
78
+ context_provider: Callable[[], dict[str, Any] | None] | None = None,
79
+ metadata: Any = None,
80
+ auto_install: bool = False,
81
+ batch_rows: int = 500,
82
+ batch_interval: float = 2.0,
83
+ ) -> None:
84
+ from hindsight.outbox.adapter import OutboxAdapter
85
+ from hindsight.outbox.catalog import installed_triggers, introspect, manifest_from_catalog
86
+ from hindsight.outbox.db import Database, connector
87
+ from hindsight.outbox.shipper import OutboxShipper
88
+ from hindsight.outbox.spec import specs_from_manifest
89
+ from hindsight.outbox.sql import install_sql
90
+
91
+ db = Database(connector(dsn))
92
+ if metadata is not None:
93
+ from hindsight.sqlalchemy.manifest import build_manifest
94
+
95
+ self.manifest = build_manifest(metadata, self.cfg, mode="outbox")
96
+ else:
97
+ self.manifest = manifest_from_catalog(introspect(db), self.cfg)
98
+ self.shipper.set_manifest(self.manifest)
99
+ specs = specs_from_manifest(self.manifest, self.cfg)
100
+ if auto_install:
101
+ db.run(install_sql(specs))
102
+ have = installed_triggers(db)
103
+ missing = [s.name for s in specs if s.name not in have]
104
+ if missing:
105
+ log.warning(
106
+ "hindsight: %d captured tables have no trigger (run `hindsight apply`): %s",
107
+ len(missing),
108
+ ", ".join(missing[:10]),
109
+ )
110
+ begin_ok = db.fetchrow("SELECT to_regprocedure('capture_begin(jsonb)') IS NOT NULL")
111
+ if begin_ok and begin_ok[0]:
112
+ self.adapter = OutboxAdapter(engine=engine, context_provider=context_provider)
113
+ self.adapter.install()
114
+ else:
115
+ log.warning("hindsight: capture_begin() is missing — actor attribution is off")
116
+ self.outbox = OutboxShipper(
117
+ db,
118
+ self.shipper,
119
+ [s.name for s in specs],
120
+ batch_rows=batch_rows,
121
+ interval=batch_interval,
122
+ max_rows=self.cfg.outbox_max_rows,
123
+ max_bytes=self.cfg.outbox_max_bytes,
124
+ )
125
+
126
+ def start(self) -> None:
127
+ if self.outbox is not None:
128
+ self.outbox.start()
129
+ else:
130
+ self.shipper.start()
131
+
132
+ def flush(self, timeout: float = 10.0) -> int:
133
+ import time
134
+
135
+ deadline = time.monotonic() + timeout
136
+ if self.outbox is not None:
137
+ return int(self.outbox.drain(deadline=deadline))
138
+ return self.shipper.flush(deadline=deadline)
139
+
140
+ def close(self, timeout: float = 5.0) -> None:
141
+ if self.adapter is not None:
142
+ self.adapter.uninstall()
143
+ if self.outbox is not None:
144
+ self.outbox.stop(timeout)
145
+ self.shipper.stop(timeout)
146
+
147
+ def stats(self) -> dict[str, Any]:
148
+ return {
149
+ "slug": self.slug,
150
+ "boot_id": self.shipper.boot_id,
151
+ "queue": self.queue.stats(),
152
+ "shipper": dict(self.shipper.stats),
153
+ "adapter": dict(self.adapter.stats) if self.adapter else {},
154
+ "outbox": dict(self.outbox.stats) if self.outbox else {},
155
+ }
156
+
157
+
158
+ def init(
159
+ engine: Any = None,
160
+ *,
161
+ key: str | None = None,
162
+ url: str | None = None,
163
+ config: str | CaptureConfig | None = None,
164
+ context_provider: Callable[[], dict[str, Any] | None] | None = None,
165
+ metadata: Any = None,
166
+ mode: str | None = None,
167
+ dsn: str | None = None,
168
+ auto_install: bool = False,
169
+ spool_dir: str | None = None,
170
+ queue_size: int = 10_000,
171
+ batch_rows: int = 500,
172
+ batch_interval: float = 2.0,
173
+ transport: Transport | None = None,
174
+ start: bool = True,
175
+ ) -> Client | None:
176
+ """Start capture, returning ``None`` when capture is unavailable."""
177
+ global _client
178
+ try:
179
+ raw_key = resolve_key(key)
180
+ if not raw_key:
181
+ log.warning("hindsight: no HINDSIGHT_KEY — capture is off")
182
+ return None
183
+ slug, raw_key = parse_key(raw_key)
184
+ cfg = config if isinstance(config, CaptureConfig) else CaptureConfig.load(config)
185
+ if mode:
186
+ cfg.mode = mode
187
+ if cfg.mode not in ("orm", "outbox"):
188
+ log.warning("hindsight: unknown mode %r; using orm", cfg.mode)
189
+ cfg.mode = "orm"
190
+ if _client is not None:
191
+ _client.close(0.0)
192
+ client = Client(
193
+ slug=slug,
194
+ transport=transport or UrllibTransport(resolve_url(url), raw_key),
195
+ cfg=cfg,
196
+ queue_size=queue_size,
197
+ batch_rows=batch_rows,
198
+ batch_interval=batch_interval,
199
+ spool_dir=spool_dir,
200
+ producer=cfg.mode,
201
+ )
202
+ if cfg.mode == "outbox":
203
+ from hindsight.outbox.db import dsn_of_engine
204
+
205
+ dsn = dsn or os.environ.get("HINDSIGHT_DSN") or dsn_of_engine(engine)
206
+ if not dsn:
207
+ raise RuntimeError("outbox mode needs dsn= (or HINDSIGHT_DSN, or an engine)")
208
+ client.attach_outbox(
209
+ dsn,
210
+ engine=engine,
211
+ context_provider=context_provider,
212
+ metadata=metadata,
213
+ auto_install=auto_install,
214
+ batch_rows=batch_rows,
215
+ batch_interval=batch_interval,
216
+ )
217
+ else:
218
+ if metadata is not None:
219
+ client.set_metadata(metadata)
220
+ if engine is not None or metadata is not None:
221
+ client.attach_sqlalchemy(engine, context_provider)
222
+ if start:
223
+ client.start()
224
+ _client = client
225
+ atexit.register(_atexit)
226
+ log.info("hindsight: capturing for source %r (boot %s)", slug, client.shipper.boot_id)
227
+ return client
228
+ except Exception:
229
+ log.exception("hindsight: init failed — capture is off, the app is unaffected")
230
+ return None
231
+
232
+
233
+ def _atexit() -> None:
234
+ shutdown(timeout=3.0)
235
+
236
+
237
+ def shutdown(timeout: float = 5.0) -> None:
238
+ global _client
239
+ if _client is not None:
240
+ try:
241
+ _client.close(timeout)
242
+ finally:
243
+ _client = None
244
+
245
+
246
+ def flush(timeout: float = 10.0) -> int:
247
+ return _client.flush(timeout) if _client else 0
248
+
249
+
250
+ def stats() -> dict[str, Any]:
251
+ return _client.stats() if _client else {}
@@ -0,0 +1,145 @@
1
+ """Type-aware normalization and hashing for captured rows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as dt
6
+ import decimal
7
+ import hashlib
8
+ import json
9
+ import uuid
10
+ from typing import Any
11
+
12
+ _NUMERIC = ("int", "numeric", "decimal", "real", "double", "money", "serial", "float")
13
+ _TZ = ("timestamptz", "with time zone")
14
+ _JSON = ("json",)
15
+
16
+
17
+ def kind_of(pg_type: str) -> str:
18
+ """Map a PostgreSQL type to its normalization family."""
19
+ t = (pg_type or "").lower().strip()
20
+ if t.endswith("[]") or t.startswith("_") or t.startswith("array"):
21
+ return "array"
22
+ if any(k in t for k in _JSON):
23
+ return "json"
24
+ if t.startswith("bool"):
25
+ return "bool"
26
+ if any(k in t for k in _TZ):
27
+ return "timestamptz"
28
+ if t.startswith("timestamp") or t.startswith("date") or t.startswith("time"):
29
+ return "datetime"
30
+ if t == "uuid":
31
+ return "uuid"
32
+ if any(k in t for k in _NUMERIC):
33
+ return "numeric"
34
+ return "text"
35
+
36
+
37
+ def element_type(pg_type: str) -> str:
38
+ t = (pg_type or "").lower().strip()
39
+ if t.endswith("[]"):
40
+ return t[:-2]
41
+ if t.startswith("_"):
42
+ return t[1:]
43
+ return "text"
44
+
45
+
46
+ def _decimal(value: Any) -> str:
47
+ try:
48
+ d = decimal.Decimal(str(value))
49
+ except (decimal.InvalidOperation, ValueError):
50
+ return str(value)
51
+ if not d.is_finite():
52
+ return str(d)
53
+ d = d.normalize()
54
+ if d == 0:
55
+ return "0"
56
+ return format(d, "f")
57
+
58
+
59
+ def _parse_dt(value: Any) -> Any:
60
+ if isinstance(value, dt.datetime):
61
+ return value
62
+ if isinstance(value, str):
63
+ s = value.strip().replace(" ", "T", 1) if " " in value.strip() else value.strip()
64
+ if s.endswith("Z"):
65
+ s = s[:-1] + "+00:00"
66
+ try:
67
+ return dt.datetime.fromisoformat(s)
68
+ except ValueError:
69
+ return None
70
+ return None
71
+
72
+
73
+ def canonical_value(value: Any, pg_type: str) -> Any:
74
+ """Normalize a value using its PostgreSQL type."""
75
+ if value is None:
76
+ return None
77
+ kind = kind_of(pg_type)
78
+ if kind == "numeric":
79
+ if isinstance(value, bool):
80
+ return "1" if value else "0"
81
+ return _decimal(value)
82
+ if kind == "bool":
83
+ if isinstance(value, str):
84
+ return value.strip().lower() in ("t", "true", "1", "yes", "on")
85
+ return bool(value)
86
+ if kind == "timestamptz":
87
+ parsed = _parse_dt(value)
88
+ if parsed is None:
89
+ return str(value)
90
+ if parsed.tzinfo is None:
91
+ parsed = parsed.replace(tzinfo=dt.UTC)
92
+ return parsed.astimezone(dt.UTC).isoformat()
93
+ if kind == "datetime":
94
+ if isinstance(value, (dt.datetime, dt.date, dt.time)):
95
+ return value.isoformat()
96
+ return str(value).strip().replace(" ", "T", 1)
97
+ if kind == "uuid":
98
+ if isinstance(value, uuid.UUID):
99
+ return str(value)
100
+ return str(value).strip().lower()
101
+ if kind == "json":
102
+ if isinstance(value, str):
103
+ try:
104
+ return json.loads(value)
105
+ except ValueError:
106
+ return value
107
+ return value
108
+ if kind == "array":
109
+ if isinstance(value, str):
110
+ try:
111
+ value = json.loads(value)
112
+ except ValueError:
113
+ return value
114
+ if isinstance(value, (list, tuple)):
115
+ et = element_type(pg_type)
116
+ return [canonical_value(v, et) for v in value]
117
+ return value
118
+ if isinstance(value, (dict, list)):
119
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)
120
+ if isinstance(value, bool):
121
+ return "true" if value else "false"
122
+ if isinstance(value, (bytes, bytearray, memoryview)):
123
+ return bytes(value).hex()
124
+ return str(value)
125
+
126
+
127
+ def captured_columns(table: dict[str, Any]) -> dict[str, str]:
128
+ """Return captured column names and types."""
129
+ cols = table.get("columns") or {}
130
+ return {
131
+ name: str((spec or {}).get("pg_type") or "text")
132
+ for name, spec in sorted(cols.items())
133
+ if (spec or {}).get("captured", True) and not name.startswith("_")
134
+ }
135
+
136
+
137
+ def canonical_row(values: dict[str, Any], columns: dict[str, str]) -> dict[str, Any]:
138
+ return {name: canonical_value(values.get(name), pg_type) for name, pg_type in columns.items()}
139
+
140
+
141
+ def row_hash(values: dict[str, Any], columns: dict[str, str]) -> str:
142
+ canonical = json.dumps(
143
+ canonical_row(values, columns), sort_keys=True, separators=(",", ":"), default=str
144
+ )
145
+ return hashlib.sha256(canonical.encode()).hexdigest()[:32]
File without changes