TicketMetric-tool 0.1.2__py3-none-any.whl

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,304 @@
1
+ Metadata-Version: 2.4
2
+ Name: TicketMetric_tool
3
+ Version: 0.1.2
4
+ Summary: Shared internal helpers: config, logging, Mongo, retries, migrations, jobs, notifications.
5
+ License-Expression: LicenseRef-Proprietary
6
+ Project-URL: Source, https://github.com/aryansingh3/common_internal_tool
7
+ Classifier: Programming Language :: Python :: 3.9
8
+ Classifier: Programming Language :: Python :: 3.10
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: pymongo>=4.6.0
17
+ Requires-Dist: python-dotenv>=1.0.0
18
+ Requires-Dist: requests>=2.31.0
19
+ Provides-Extra: flask
20
+ Requires-Dist: Flask>=2.3.0; extra == "flask"
21
+ Provides-Extra: logging
22
+ Requires-Dist: pretty-pie-log>=0.1.0; extra == "logging"
23
+ Provides-Extra: dev
24
+ Requires-Dist: pytest>=7.4; extra == "dev"
25
+ Requires-Dist: mongomock>=4.1; extra == "dev"
26
+
27
+ # TicketMetric_tool
28
+
29
+ Shared internal helpers for the API, the scrapers, the crons and one-off migrations.
30
+
31
+ > **Two names, on purpose.** The pip distribution is
32
+ > `TicketMetric_tool`; the import is the short `tmcommon`.
33
+ > Same convention as `pip install python-dateutil` / `import dateutil`, so call
34
+ > sites stay readable instead of carrying a 36 character prefix.
35
+ >
36
+ > ```bash
37
+ > pip install TicketMetric_tool
38
+ > ```
39
+ > ```python
40
+ > from tmcommon.jobs import Job
41
+ > ```
42
+ >
43
+ > To make them identical instead, rename `src/tmcommon/` and update the two
44
+ > `[project.scripts]` paths in `pyproject.toml`.
45
+
46
+ Design rule: **the library ships mechanism, the app keeps policy and schema.** Connection
47
+ handling, batching, retries and migration plumbing live here. Collection names, index
48
+ definitions and business queries stay in the app.
49
+
50
+ It is importable with no Flask installed, no Slack configured and no database reachable,
51
+ because migrations and scrapers need it too.
52
+
53
+ ## Install
54
+
55
+ ```bash
56
+ # from the repo
57
+ pip install -e /path/to/common_internal_tool # core
58
+ pip install -e ".[flask,logging]" # API services
59
+
60
+ # straight from GitHub
61
+ pip install "git+https://github.com/aryansingh3/common_internal_tool.git@main"
62
+ ```
63
+
64
+ Pin a release once there is one, rather than tracking `main`:
65
+
66
+ ```bash
67
+ pip install "git+https://github.com/aryansingh3/common_internal_tool.git@v0.1.0"
68
+ ```
69
+
70
+ Build a wheel to hand around or host yourself:
71
+
72
+ ```bash
73
+ python -m build --wheel # dist/ticketmetric_tool-0.1.2-py3-none-any.whl
74
+ ```
75
+
76
+ ## Getting changes into the consuming repos
77
+
78
+ pip does not watch GitHub. Installing takes a snapshot, so a push to `main` changes
79
+ nothing in an environment that already installed the package. Pick the workflow that
80
+ matches where you are:
81
+
82
+ **Developing the library and an app together.** Clone once, install editable, and every
83
+ `git pull` is live with no reinstall. This is the only setup where changes really are
84
+ automatic.
85
+
86
+ ```bash
87
+ git clone https://github.com/aryansingh3/common_internal_tool.git
88
+ pip install -e ../common_internal_tool
89
+ ```
90
+
91
+ **Pulling the latest `main` into an environment.** pip caches aggressively, so an
92
+ `--upgrade` alone often appears to do nothing when the version string has not moved:
93
+
94
+ ```bash
95
+ pip install --upgrade --force-reinstall --no-cache-dir \
96
+ "git+https://github.com/aryansingh3/common_internal_tool.git@main"
97
+ ```
98
+
99
+ **Deployments.** Pin a tag, never `main`. A deploy that resolves `main` is not
100
+ reproducible, and the same Dockerfile will produce different images on different days.
101
+
102
+ ```
103
+ # requirements.txt
104
+ TicketMetric_tool @ git+https://github.com/aryansingh3/common_internal_tool.git@v0.1.2
105
+ ```
106
+
107
+ Bumping that pin is then a reviewable one-line diff, which is what you want for a library
108
+ several services depend on.
109
+
110
+ ### Cutting a release
111
+
112
+ ```bash
113
+ # bump version in pyproject.toml, commit, then
114
+ git tag v0.2.0 && git push origin v0.2.0
115
+ ```
116
+
117
+ The release workflow verifies the tag matches `pyproject.toml`, runs the suite, builds the
118
+ wheel and sdist, and attaches them to a GitHub Release.
119
+
120
+ ### The private-repo gotcha
121
+
122
+ This repo is private, so anything without your local git credentials, CI, Docker builds,
123
+ production hosts, cannot clone it. A `pip install git+https://...` there fails with an
124
+ authentication error. The usual fixes:
125
+
126
+ - a deploy key on this repo, with the private key as a secret in the consumer, using the
127
+ `git+ssh://git@github.com/...` form
128
+ - a fine-grained PAT with read access, injected as
129
+ `git+https://${TOKEN}@github.com/...`
130
+ - or build the wheel in CI and push it to a private index
131
+
132
+ For Docker, mount the credential as a build secret rather than baking a token into a layer.
133
+
134
+ ## Python support
135
+
136
+ **3.9 through 3.13.** 3.9 is the floor because the Flask API runs on it, so nothing here
137
+ uses 3.10+ syntax: no PEP 604 `X | Y` unions, no `match` statements. CI compiles every
138
+ file on each version to enforce that, including modules the tests do not import.
139
+
140
+ ## Tests
141
+
142
+ ```bash
143
+ python3 run_tests.py
144
+ ```
145
+
146
+ No pytest needed, so the suite runs on an interpreter carrying only the core
147
+ dependencies. The files are valid pytest modules too. A test file whose optional
148
+ dependency is missing prints `SKIP` and passes, so no Flask is not a failure.
149
+
150
+ Verified locally on 3.9.6 and 3.11.15; 3.10, 3.12 and 3.13 are covered by the CI matrix.
151
+
152
+ `tests/fake_mongo.py` is a small in-memory `Collection` covering only the operations these
153
+ modules use, so lock and batch logic is testable without mongomock and without pointing a
154
+ test at a real cluster.
155
+
156
+ ## Environment
157
+
158
+ | variable | required | purpose |
159
+ |---|---|---|
160
+ | `SERVICE_NAME` | recommended | identifies the service in logs and alerts |
161
+ | `APP_ENV` | no | `dev`/`local`/`test`/`staging` suppress Slack; anything else is production |
162
+ | `LOG_DIR` | no | absolute log directory, defaults to `<cwd>/logs` |
163
+ | `LOG_LEVEL` | no | defaults to `DEBUG` |
164
+ | `MONGODB_URI` | when using mongo | default cluster |
165
+ | `MONGODB_URI_<ALIAS>` | no | extra clusters, e.g. `MONGODB_URI_STAGING` |
166
+ | `SLACK_WEBHOOK_URL` | when notifying | absent means notifications are skipped, not an error |
167
+
168
+ ## Modules
169
+
170
+ | module | what it gives you |
171
+ |---|---|
172
+ | `config` | typed env access that raises at point of use, not on import |
173
+ | `logging` | `get_logger(name)`, cached, absolute log dir, falls back to stdlib when `pretty_pie_log` is absent |
174
+ | `context` | correlation id and extra fields via ContextVar, so a cron traceback is traceable |
175
+ | `exceptions` | `BaseAPIException` and the HTTP subclasses, dependency-free |
176
+ | `serialization` | one JSON encoder for ObjectId and datetime, plus `to_jsonable` |
177
+ | `retry` | `@retry` with exponential backoff and jitter |
178
+ | `timing` | `timed()`, `@timeit`, and `Stopwatch` for multi-phase jobs |
179
+ | `mongo.connection` | lazy multi-cluster registry, `DatabaseRouter` for the live/historical split |
180
+ | `mongo.batch` | chunked `insert_many` / `bulk_write` that separates duplicate keys from real errors |
181
+ | `mongo.iterate` | `iter_by_id` keyset paging, no cursor timeouts, resumable |
182
+ | `mongo.checkpoint` | watermarks so incremental jobs resume instead of guessing a `--since` |
183
+ | `migrations` | versioned migrations with an applied record, a lock and dry-run |
184
+ | `jobs` | scheduled work: expiring locks, run history, heartbeats, overdue detection |
185
+ | `notify.slack` | error alerts, framework-agnostic, context supplied by the app |
186
+ | `flask_ext` | `init_app(app)` for correlation ids and error handlers |
187
+
188
+ ## Jobs and crons
189
+
190
+ A `Job` gets a lock, a run row, a status document with heartbeat, a correlation id, a
191
+ checkpoint, failure alerting and timing. Records use the field names already in
192
+ `vc_worker_runs` and `vc_worker_status`, so existing queries keep working.
193
+
194
+ ```python
195
+ from tmcommon.jobs import Job
196
+
197
+ class SectionRosterJob(Job):
198
+ name = 'tm_section_roster'
199
+ description = 'Fold new TM snapshots into the section roster'
200
+ lock_ttl_seconds = 1800
201
+
202
+ def run(self, ctx):
203
+ since = ctx.checkpoint.get()
204
+ processed = 0
205
+ for event_id in events_since(since):
206
+ update_roster(event_id)
207
+ processed += 1
208
+ if not ctx.heartbeat(processed=processed):
209
+ break # lease lost, another process took over
210
+ ctx.checkpoint.advance(newest_seen)
211
+ return {'events': processed}
212
+ ```
213
+
214
+ Run it in-process, replacing the hand-rolled worker threads:
215
+
216
+ ```python
217
+ from tmcommon.jobs import Scheduler
218
+
219
+ scheduler = Scheduler(db)
220
+ scheduler.add(SectionRosterJob(), interval_seconds=86400)
221
+ scheduler.add(CleanupJob(), interval_seconds=86400, initial_delay_seconds=300)
222
+ scheduler.start()
223
+ ```
224
+
225
+ Or as a one-shot under system cron or a Kubernetes CronJob, with the same recording:
226
+
227
+ ```bash
228
+ tm-job run --package jobs --db tickets --name tm_section_roster
229
+ tm-job status --db tickets
230
+ tm-job overdue --db tickets --expect tm_section_roster=86400,cleanup_worker=86400
231
+ ```
232
+
233
+ `overdue` exits non-zero when a job is late, so a monitor can alert on it. That is the
234
+ failure currently invisible: `cron.py` is a bare `while True` loop, and if that process
235
+ dies every schedule inside it stops with no signal.
236
+
237
+ **Why the lock matters here.** `app.py` starts the workers at module scope, in the `else`
238
+ branch gunicorn takes, so every web worker process starts its own copy. Four gunicorn
239
+ workers run four cleanup loops concurrently today. Under `Scheduler` all four still start
240
+ and exactly one does the work per tick; the rest record `skipped`.
241
+
242
+ ## Flask wiring
243
+
244
+ ```python
245
+ from tmcommon.flask_ext import init_app, flask_context_provider
246
+ from tmcommon.notify import register_context_provider
247
+
248
+ init_app(app)
249
+ register_context_provider(lambda: {**flask_context_provider(),
250
+ 'User': get_request_user().email})
251
+ ```
252
+
253
+ `BaseAPIException` becomes its `to_dict()` response and is logged at warning. Anything else
254
+ is treated as a bug: logged with a traceback, sent to Slack, returned as a 500. A 404 or 405
255
+ is neither.
256
+
257
+ ## Migrations
258
+
259
+ ```python
260
+ # migrations/m20261001_section_roster.py
261
+ from tmcommon.migrations import Migration
262
+
263
+ class SectionRoster(Migration):
264
+ version = '20261001_section_roster'
265
+ description = 'Build tm_section_roster from ticketmaster_detail_data'
266
+
267
+ def up(self, db, dry_run=False):
268
+ count = db.ticketmaster_detail_data.estimated_document_count()
269
+ if dry_run:
270
+ return {'would_scan': count}
271
+ ...
272
+ return {'events': 412, 'sections': 9304}
273
+ ```
274
+
275
+ ```bash
276
+ tm-migrate status --package migrations --db tickets
277
+ tm-migrate up --package migrations --db tickets # dry run
278
+ tm-migrate up --package migrations --db tickets --apply
279
+ ```
280
+
281
+ Writes need `--apply`. Deliberate, given these run against collections with millions of rows.
282
+
283
+ ## Deliberately not here
284
+
285
+ - **Collection accessors and index definitions.** Your `DatabaseConnection._create_indexes()`
286
+ is app schema. Declare it in the app and call it at startup.
287
+ - **`DatabaseManager` business queries.** `get_user_from_email`, `get_analytics` and the
288
+ venue lookups are domain logic, not shared mechanism.
289
+ - **Domain models** such as `APIUser` and `Membership`.
290
+
291
+ ## Roadmap
292
+
293
+ Not built yet, in rough priority order:
294
+
295
+ 1. `http` client: session with retry, proxy rotation and UA rotation. Both repos already carry
296
+ `proxies.json` and `user_agent.json` plus their own rotation code.
297
+ 2. `pipeline` base: extract/transform/load with stats and failure reporting, to replace the
298
+ per-spider boilerplate.
299
+ 3. `ratelimit`: token bucket for upstream politeness.
300
+ 4. `dates`: `est_to_utc`, `convert_utc_to_timezone`, currently duplicated in both repos.
301
+ 5. `mongo.upsert`: find-or-create keyed on an alternate identity, the gap behind the duplicate
302
+ events bug.
303
+ 6. `schema`: declarative model base with `to_dict` / `from_dict` and validation.
304
+ 7. Test helpers: `mongomock` fixtures and a fake clock.
@@ -0,0 +1,29 @@
1
+ tmcommon/__init__.py,sha256=UcHce8oYKiZ1D1PotwXR7yjWNS7fydfZx9B16ggYe1Q,653
2
+ tmcommon/config.py,sha256=yECQwfKukJXPF-bYnuDSAHVBMwLK47mldclhJ-k8ijg,2323
3
+ tmcommon/context.py,sha256=HFlr7agBH7bvQUM8UN8a5aFtSKY6-4XMOTlkFejIPNg,2267
4
+ tmcommon/exceptions.py,sha256=PsXp2Qx519JB0wO9Q5G-121em3d2obAleXmczvppw1g,2924
5
+ tmcommon/flask_ext.py,sha256=y0zM23e6c09DGKK5XLersgj2hV_dD7Tk6k8xBUcrcdk,3516
6
+ tmcommon/logging.py,sha256=kCpqRWIOHmCIshxMLUzh6RKwykOY7Je6NaJtKKahOAQ,4882
7
+ tmcommon/retry.py,sha256=gnMPiTLUW_l0W1M2iRYmHgllN65r8aNkSIsPKTlwKbo,2982
8
+ tmcommon/serialization.py,sha256=2dtq7w_zNBlXtrSS5V39dRuHD5QaxhYaDRJOfMp6Rso,2637
9
+ tmcommon/timing.py,sha256=NgJzajp_r9xJi38mpF80Q33lB33hXkx8Eme2TPJkUJ8,2546
10
+ tmcommon/jobs/__init__.py,sha256=RvvBIyMiDZ9DzCo5iq-jcwwbX0hhUQpAUvMBq6dRkDQ,1467
11
+ tmcommon/jobs/cli.py,sha256=P4rIWNvrM4i9Bt9C9Hk0K8I1AEQftaXJNfquo2aUCiE,3950
12
+ tmcommon/jobs/job.py,sha256=je74RnqpdgTKWGahirti5NGtpIgGdwYAHmfUxHhK-SE,8656
13
+ tmcommon/jobs/lock.py,sha256=jHYs4EHjVZBOPdSF-X37ayEFZ8dbZo3U77cvm4ZHbbU,4866
14
+ tmcommon/jobs/scheduler.py,sha256=7LIqQMNDehYjK4qkxh4Sh4KKA7SlcHDyu_TJu9VQbAY,5331
15
+ tmcommon/migrations/__init__.py,sha256=YNNV1wY5LQstoF6AAhX7alNTA90TgR-4nGzOh1YogJs,1064
16
+ tmcommon/migrations/cli.py,sha256=9XD5yf9SEtoaboBDnnDxs-UqRGEQ3kstJsKBitICypg,2905
17
+ tmcommon/migrations/runner.py,sha256=lL-Z_UnQuhnLRAAaMdHbwbN_5TkGZM5re8PdAaCdOrk,7752
18
+ tmcommon/mongo/__init__.py,sha256=6XoKanYPmmBP5AQcg7TcX0Eu-1hXyVY1dz6F8EslpXQ,566
19
+ tmcommon/mongo/batch.py,sha256=4FLjjxK5uvV_WqmaEV6Herd9JXLvz3gV4tKX5xgCV3U,4386
20
+ tmcommon/mongo/checkpoint.py,sha256=Dh_OZJwh2Q9wOcn_wD9znvuc-reOLhy9VmBGAdhJ0dc,2818
21
+ tmcommon/mongo/connection.py,sha256=SpPSEFfBdeZE3WjA17qM2VlGdLA24_rB6x8Z_jlFK-E,4287
22
+ tmcommon/mongo/iterate.py,sha256=AuRBXcVVQV-_5PPBpc1FSxkgN8mUnxOULoI-6nuVP_8,3712
23
+ tmcommon/notify/__init__.py,sha256=9Ir_62wdjYiMJBwTXx_c3fpUrCfPXF-OthED9aNZBpQ,118
24
+ tmcommon/notify/slack.py,sha256=B4AF_1FZEzUqEgoZgBu48JrpqAYsfWYNRLFe_4LFO14,6846
25
+ ticketmetric_tool-0.1.2.dist-info/METADATA,sha256=IeVWuyPNxdm_KGLWy8NvJJGeLXIYjGEXtbA8unpN2eE,11879
26
+ ticketmetric_tool-0.1.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
27
+ ticketmetric_tool-0.1.2.dist-info/entry_points.txt,sha256=yOjQFXY0j2GfmO0v4vSaTCFaNKUBFf2HB4PQB3SGBp4,92
28
+ ticketmetric_tool-0.1.2.dist-info/top_level.txt,sha256=0hjLLI3FAhbXAb8UlrJe4hEtHPC726-1pfpRD9Gc1TQ,9
29
+ ticketmetric_tool-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ tm-job = tmcommon.jobs.cli:main
3
+ tm-migrate = tmcommon.migrations.cli:main
@@ -0,0 +1 @@
1
+ tmcommon
tmcommon/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """Shared internal helpers.
2
+
3
+ Deliberately importable without Flask, without Slack configured, and without a
4
+ reachable database, so the same package serves the API, the scrapers, the crons
5
+ and one-off migrations. Submodules are imported on demand rather than eagerly
6
+ here, for that reason.
7
+ """
8
+
9
+ from . import config, context, exceptions, serialization
10
+ from .logging import get_logger
11
+ from .retry import retry
12
+ from .timing import Stopwatch, timed, timeit
13
+
14
+ __version__ = '0.1.2'
15
+
16
+ __all__ = [
17
+ 'config',
18
+ 'context',
19
+ 'exceptions',
20
+ 'serialization',
21
+ 'get_logger',
22
+ 'retry',
23
+ 'Stopwatch',
24
+ 'timed',
25
+ 'timeit',
26
+ '__version__',
27
+ ]
tmcommon/config.py ADDED
@@ -0,0 +1,78 @@
1
+ """Typed environment access that fails loudly at the point of use.
2
+
3
+ Deliberately not a module-level singleton that raises on import. A migration
4
+ script should be able to ``import tmcommon`` without a Slack webhook configured,
5
+ and a scraper should not need the API's variables. Every getter either has a
6
+ default or raises only when something actually asks for it.
7
+ """
8
+
9
+ import os
10
+ from typing import List, Optional
11
+
12
+ from dotenv import load_dotenv
13
+
14
+ load_dotenv()
15
+
16
+ _TRUTHY = {'1', 'true', 'yes', 'on'}
17
+
18
+ # Values of APP_ENV that mean "not production". Anything else is treated as
19
+ # production, so a typo fails safe rather than silently disabling alerting.
20
+ _NON_PROD = {'dev', 'development', 'local', 'test', 'staging'}
21
+
22
+
23
+ class ConfigError(RuntimeError):
24
+ """A required setting is missing or unusable."""
25
+
26
+
27
+ def get(name: str, default: Optional[str] = None) -> Optional[str]:
28
+ value = os.getenv(name)
29
+ return default if value is None or value == '' else value
30
+
31
+
32
+ def require(name: str) -> str:
33
+ value = get(name)
34
+ if value is None:
35
+ raise ConfigError(
36
+ f"{name} is not set. Add it to the environment or the .env file."
37
+ )
38
+ return value
39
+
40
+
41
+ def get_bool(name: str, default: bool = False) -> bool:
42
+ value = get(name)
43
+ return default if value is None else value.strip().lower() in _TRUTHY
44
+
45
+
46
+ def get_int(name: str, default: Optional[int] = None) -> Optional[int]:
47
+ value = get(name)
48
+ if value is None:
49
+ return default
50
+ try:
51
+ return int(value)
52
+ except ValueError:
53
+ raise ConfigError(f"{name} must be an integer, got {value!r}")
54
+
55
+
56
+ def get_list(name: str, default: Optional[List[str]] = None) -> List[str]:
57
+ value = get(name)
58
+ if value is None:
59
+ return list(default or [])
60
+ return [part.strip() for part in value.split(',') if part.strip()]
61
+
62
+
63
+ def app_env() -> str:
64
+ return (get('APP_ENV', 'production') or 'production').strip().lower()
65
+
66
+
67
+ def is_dev_mode() -> bool:
68
+ """True when this process should skip side effects such as Slack alerts."""
69
+ return app_env() in _NON_PROD
70
+
71
+
72
+ def service_name() -> str:
73
+ """Identifies the calling service in logs and alerts.
74
+
75
+ Set SERVICE_NAME per deployment. It is the one piece of identity a shared
76
+ library cannot infer for itself.
77
+ """
78
+ return get('SERVICE_NAME', 'unknown-service')
tmcommon/context.py ADDED
@@ -0,0 +1,73 @@
1
+ """Correlation id that survives outside a web request.
2
+
3
+ Your current Slack notifier reads ``flask.g.request_id``, which means a traceback
4
+ from a cron, a scraper or a migration arrives with "N/A" and cannot be tied back
5
+ to anything. A ContextVar works in all of them, and is also coroutine- and
6
+ thread-safe, so a worker pool does not leak ids between jobs.
7
+ """
8
+
9
+ import uuid
10
+ from contextlib import contextmanager
11
+ from contextvars import ContextVar
12
+ from typing import Dict, Iterator, Optional
13
+
14
+ _correlation_id: ContextVar[Optional[str]] = ContextVar('tmcommon_correlation_id', default=None)
15
+ _extra: ContextVar[Optional[Dict[str, object]]] = ContextVar('tmcommon_extra', default=None)
16
+
17
+
18
+ def new_id() -> str:
19
+ return uuid.uuid4().hex
20
+
21
+
22
+ def set_correlation_id(value: Optional[str] = None) -> str:
23
+ cid = value or new_id()
24
+ _correlation_id.set(cid)
25
+ return cid
26
+
27
+
28
+ def get_correlation_id() -> Optional[str]:
29
+ """Current id, falling back to Flask's ``g.request_id`` when one is set.
30
+
31
+ The fallback keeps services that already populate ``g`` working unchanged.
32
+ """
33
+ cid = _correlation_id.get()
34
+ if cid:
35
+ return cid
36
+ try:
37
+ from flask import g, has_request_context
38
+
39
+ if has_request_context():
40
+ return getattr(g, 'request_id', None)
41
+ except Exception:
42
+ pass
43
+ return None
44
+
45
+
46
+ def set_extra(**fields: object) -> None:
47
+ """Attach fields that should ride along on logs and alerts, e.g. event_id."""
48
+ current = dict(_extra.get() or {})
49
+ current.update(fields)
50
+ _extra.set(current)
51
+
52
+
53
+ def get_extra() -> Dict[str, object]:
54
+ return dict(_extra.get() or {})
55
+
56
+
57
+ @contextmanager
58
+ def correlation(value: Optional[str] = None, **fields: object) -> Iterator[str]:
59
+ """Scope an id and extra fields to a block, restoring them afterwards.
60
+
61
+ Use one per unit of work so a long-running worker does not carry the previous
62
+ job's context into the next one:
63
+
64
+ with correlation(event_id=str(event_id)) as cid:
65
+ process(event_id)
66
+ """
67
+ cid_token = _correlation_id.set(value or new_id())
68
+ extra_token = _extra.set({**(_extra.get() or {}), **fields})
69
+ try:
70
+ yield _correlation_id.get()
71
+ finally:
72
+ _correlation_id.reset(cid_token)
73
+ _extra.reset(extra_token)
tmcommon/exceptions.py ADDED
@@ -0,0 +1,96 @@
1
+ """HTTP-shaped exceptions with a stable wire format.
2
+
3
+ Kept dependency-free on purpose: the Flask adapter injects the request id, so
4
+ these are usable from a scraper or a migration with no web framework present.
5
+ """
6
+
7
+ from typing import Any, Optional
8
+
9
+ __all__ = [
10
+ 'BaseAPIException',
11
+ 'BadRequest',
12
+ 'Unauthorized',
13
+ 'ValidationError',
14
+ 'Forbidden',
15
+ 'NotFound',
16
+ 'Conflict',
17
+ 'RateLimitExceeded',
18
+ 'InternalServerError',
19
+ 'ServiceUnavailable',
20
+ ]
21
+
22
+
23
+ class BaseAPIException(Exception):
24
+ def __init__(
25
+ self,
26
+ message: str,
27
+ status_code: int,
28
+ error_type: Optional[str] = None,
29
+ details: Any = None,
30
+ ):
31
+ super().__init__(message)
32
+ self.message = message
33
+ self.status_code = status_code
34
+ self.error_type = error_type or self.__class__.__name__
35
+ self.details = details
36
+
37
+ def to_dict(self, request_id: Optional[str] = None) -> dict:
38
+ error_dict = {
39
+ 'error': {
40
+ 'type': self.error_type,
41
+ 'message': self.message,
42
+ },
43
+ 'status': self.status_code,
44
+ }
45
+
46
+ if self.details is not None:
47
+ error_dict['error']['details'] = self.details
48
+ if request_id is not None:
49
+ error_dict['error']['request_id'] = request_id
50
+
51
+ return error_dict
52
+
53
+
54
+ class BadRequest(BaseAPIException):
55
+ def __init__(self, message='Invalid request', details=None):
56
+ super().__init__(message, 400, 'BadRequest', details)
57
+
58
+
59
+ class Unauthorized(BaseAPIException):
60
+ def __init__(self, message='Authentication required', details=None):
61
+ super().__init__(message, 401, 'Unauthorized', details)
62
+
63
+
64
+ class ValidationError(BaseAPIException):
65
+ def __init__(self, message='Validation error', details=None):
66
+ super().__init__(message, 400, 'ValidationError', details)
67
+
68
+
69
+ class Forbidden(BaseAPIException):
70
+ def __init__(self, message='Permission denied', details=None):
71
+ super().__init__(message, 403, 'Forbidden', details)
72
+
73
+
74
+ class NotFound(BaseAPIException):
75
+ def __init__(self, message='Resource not found', details=None):
76
+ super().__init__(message, 404, 'NotFound', details)
77
+
78
+
79
+ class Conflict(BaseAPIException):
80
+ def __init__(self, message='Resource conflict', details=None):
81
+ super().__init__(message, 409, 'Conflict', details)
82
+
83
+
84
+ class RateLimitExceeded(BaseAPIException):
85
+ def __init__(self, message='Rate limit exceeded', details=None):
86
+ super().__init__(message, 429, 'RateLimitExceeded', details)
87
+
88
+
89
+ class InternalServerError(BaseAPIException):
90
+ def __init__(self, message='Internal server error', details=None):
91
+ super().__init__(message, 500, 'InternalServerError', details)
92
+
93
+
94
+ class ServiceUnavailable(BaseAPIException):
95
+ def __init__(self, message='Service temporarily unavailable', details=None):
96
+ super().__init__(message, 503, 'ServiceUnavailable', details)