svc-infra 0.1.589__py3-none-any.whl → 0.1.706__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.

Potentially problematic release.


This version of svc-infra might be problematic. Click here for more details.

Files changed (260) hide show
  1. svc_infra/__init__.py +58 -2
  2. svc_infra/apf_payments/README.md +732 -0
  3. svc_infra/apf_payments/models.py +133 -42
  4. svc_infra/apf_payments/provider/__init__.py +4 -0
  5. svc_infra/apf_payments/provider/aiydan.py +871 -0
  6. svc_infra/apf_payments/provider/base.py +30 -9
  7. svc_infra/apf_payments/provider/stripe.py +156 -62
  8. svc_infra/apf_payments/schemas.py +19 -10
  9. svc_infra/apf_payments/service.py +211 -68
  10. svc_infra/apf_payments/settings.py +27 -3
  11. svc_infra/api/__init__.py +61 -0
  12. svc_infra/api/fastapi/__init__.py +15 -0
  13. svc_infra/api/fastapi/admin/__init__.py +3 -0
  14. svc_infra/api/fastapi/admin/add.py +245 -0
  15. svc_infra/api/fastapi/apf_payments/router.py +145 -46
  16. svc_infra/api/fastapi/apf_payments/setup.py +26 -8
  17. svc_infra/api/fastapi/auth/__init__.py +65 -0
  18. svc_infra/api/fastapi/auth/_cookies.py +6 -2
  19. svc_infra/api/fastapi/auth/add.py +27 -14
  20. svc_infra/api/fastapi/auth/gaurd.py +104 -13
  21. svc_infra/api/fastapi/auth/mfa/models.py +3 -1
  22. svc_infra/api/fastapi/auth/mfa/pre_auth.py +10 -6
  23. svc_infra/api/fastapi/auth/mfa/router.py +15 -8
  24. svc_infra/api/fastapi/auth/mfa/security.py +1 -2
  25. svc_infra/api/fastapi/auth/mfa/utils.py +2 -1
  26. svc_infra/api/fastapi/auth/mfa/verify.py +9 -2
  27. svc_infra/api/fastapi/auth/policy.py +0 -1
  28. svc_infra/api/fastapi/auth/providers.py +3 -1
  29. svc_infra/api/fastapi/auth/routers/apikey_router.py +6 -6
  30. svc_infra/api/fastapi/auth/routers/oauth_router.py +214 -75
  31. svc_infra/api/fastapi/auth/routers/session_router.py +67 -0
  32. svc_infra/api/fastapi/auth/security.py +31 -10
  33. svc_infra/api/fastapi/auth/sender.py +8 -1
  34. svc_infra/api/fastapi/auth/settings.py +2 -0
  35. svc_infra/api/fastapi/auth/state.py +3 -1
  36. svc_infra/api/fastapi/auth/ws_security.py +275 -0
  37. svc_infra/api/fastapi/billing/router.py +73 -0
  38. svc_infra/api/fastapi/billing/setup.py +19 -0
  39. svc_infra/api/fastapi/cache/add.py +9 -5
  40. svc_infra/api/fastapi/db/__init__.py +5 -1
  41. svc_infra/api/fastapi/db/http.py +3 -1
  42. svc_infra/api/fastapi/db/nosql/__init__.py +39 -1
  43. svc_infra/api/fastapi/db/nosql/mongo/add.py +47 -32
  44. svc_infra/api/fastapi/db/nosql/mongo/crud_router.py +30 -11
  45. svc_infra/api/fastapi/db/sql/__init__.py +5 -1
  46. svc_infra/api/fastapi/db/sql/add.py +71 -26
  47. svc_infra/api/fastapi/db/sql/crud_router.py +210 -22
  48. svc_infra/api/fastapi/db/sql/health.py +3 -1
  49. svc_infra/api/fastapi/db/sql/session.py +18 -0
  50. svc_infra/api/fastapi/db/sql/users.py +29 -5
  51. svc_infra/api/fastapi/dependencies/ratelimit.py +130 -0
  52. svc_infra/api/fastapi/docs/add.py +173 -0
  53. svc_infra/api/fastapi/docs/landing.py +4 -2
  54. svc_infra/api/fastapi/docs/scoped.py +62 -15
  55. svc_infra/api/fastapi/dual/__init__.py +12 -2
  56. svc_infra/api/fastapi/dual/dualize.py +1 -1
  57. svc_infra/api/fastapi/dual/protected.py +126 -4
  58. svc_infra/api/fastapi/dual/public.py +25 -0
  59. svc_infra/api/fastapi/dual/router.py +40 -13
  60. svc_infra/api/fastapi/dx.py +33 -2
  61. svc_infra/api/fastapi/ease.py +10 -2
  62. svc_infra/api/fastapi/http/concurrency.py +2 -1
  63. svc_infra/api/fastapi/http/conditional.py +3 -1
  64. svc_infra/api/fastapi/middleware/debug.py +4 -1
  65. svc_infra/api/fastapi/middleware/errors/catchall.py +6 -2
  66. svc_infra/api/fastapi/middleware/errors/exceptions.py +1 -1
  67. svc_infra/api/fastapi/middleware/errors/handlers.py +54 -8
  68. svc_infra/api/fastapi/middleware/graceful_shutdown.py +104 -0
  69. svc_infra/api/fastapi/middleware/idempotency.py +197 -70
  70. svc_infra/api/fastapi/middleware/idempotency_store.py +187 -0
  71. svc_infra/api/fastapi/middleware/optimistic_lock.py +42 -0
  72. svc_infra/api/fastapi/middleware/ratelimit.py +143 -31
  73. svc_infra/api/fastapi/middleware/ratelimit_store.py +111 -0
  74. svc_infra/api/fastapi/middleware/request_id.py +27 -11
  75. svc_infra/api/fastapi/middleware/request_size_limit.py +36 -0
  76. svc_infra/api/fastapi/middleware/timeout.py +177 -0
  77. svc_infra/api/fastapi/openapi/apply.py +5 -3
  78. svc_infra/api/fastapi/openapi/conventions.py +9 -2
  79. svc_infra/api/fastapi/openapi/mutators.py +165 -20
  80. svc_infra/api/fastapi/openapi/pipeline.py +1 -1
  81. svc_infra/api/fastapi/openapi/security.py +3 -1
  82. svc_infra/api/fastapi/ops/add.py +75 -0
  83. svc_infra/api/fastapi/pagination.py +47 -20
  84. svc_infra/api/fastapi/routers/__init__.py +43 -15
  85. svc_infra/api/fastapi/routers/ping.py +1 -0
  86. svc_infra/api/fastapi/setup.py +188 -56
  87. svc_infra/api/fastapi/tenancy/add.py +19 -0
  88. svc_infra/api/fastapi/tenancy/context.py +112 -0
  89. svc_infra/api/fastapi/versioned.py +101 -0
  90. svc_infra/app/README.md +5 -5
  91. svc_infra/app/__init__.py +3 -1
  92. svc_infra/app/env.py +69 -1
  93. svc_infra/app/logging/add.py +9 -2
  94. svc_infra/app/logging/formats.py +12 -5
  95. svc_infra/billing/__init__.py +23 -0
  96. svc_infra/billing/async_service.py +147 -0
  97. svc_infra/billing/jobs.py +241 -0
  98. svc_infra/billing/models.py +177 -0
  99. svc_infra/billing/quotas.py +103 -0
  100. svc_infra/billing/schemas.py +36 -0
  101. svc_infra/billing/service.py +123 -0
  102. svc_infra/bundled_docs/README.md +5 -0
  103. svc_infra/bundled_docs/__init__.py +1 -0
  104. svc_infra/bundled_docs/getting-started.md +6 -0
  105. svc_infra/cache/__init__.py +9 -0
  106. svc_infra/cache/add.py +170 -0
  107. svc_infra/cache/backend.py +7 -6
  108. svc_infra/cache/decorators.py +81 -15
  109. svc_infra/cache/demo.py +2 -2
  110. svc_infra/cache/keys.py +24 -4
  111. svc_infra/cache/recache.py +26 -14
  112. svc_infra/cache/resources.py +14 -5
  113. svc_infra/cache/tags.py +19 -44
  114. svc_infra/cache/utils.py +3 -1
  115. svc_infra/cli/__init__.py +52 -8
  116. svc_infra/cli/__main__.py +4 -0
  117. svc_infra/cli/cmds/__init__.py +39 -2
  118. svc_infra/cli/cmds/db/nosql/mongo/mongo_cmds.py +7 -4
  119. svc_infra/cli/cmds/db/nosql/mongo/mongo_scaffold_cmds.py +7 -5
  120. svc_infra/cli/cmds/db/ops_cmds.py +270 -0
  121. svc_infra/cli/cmds/db/sql/alembic_cmds.py +103 -18
  122. svc_infra/cli/cmds/db/sql/sql_export_cmds.py +88 -0
  123. svc_infra/cli/cmds/db/sql/sql_scaffold_cmds.py +3 -3
  124. svc_infra/cli/cmds/docs/docs_cmds.py +142 -0
  125. svc_infra/cli/cmds/dx/__init__.py +12 -0
  126. svc_infra/cli/cmds/dx/dx_cmds.py +116 -0
  127. svc_infra/cli/cmds/health/__init__.py +179 -0
  128. svc_infra/cli/cmds/health/health_cmds.py +8 -0
  129. svc_infra/cli/cmds/help.py +4 -0
  130. svc_infra/cli/cmds/jobs/__init__.py +1 -0
  131. svc_infra/cli/cmds/jobs/jobs_cmds.py +47 -0
  132. svc_infra/cli/cmds/obs/obs_cmds.py +36 -15
  133. svc_infra/cli/cmds/sdk/__init__.py +0 -0
  134. svc_infra/cli/cmds/sdk/sdk_cmds.py +112 -0
  135. svc_infra/cli/foundation/runner.py +6 -2
  136. svc_infra/data/add.py +61 -0
  137. svc_infra/data/backup.py +58 -0
  138. svc_infra/data/erasure.py +45 -0
  139. svc_infra/data/fixtures.py +42 -0
  140. svc_infra/data/retention.py +61 -0
  141. svc_infra/db/__init__.py +15 -0
  142. svc_infra/db/crud_schema.py +9 -9
  143. svc_infra/db/inbox.py +67 -0
  144. svc_infra/db/nosql/__init__.py +3 -0
  145. svc_infra/db/nosql/core.py +30 -9
  146. svc_infra/db/nosql/indexes.py +3 -1
  147. svc_infra/db/nosql/management.py +1 -1
  148. svc_infra/db/nosql/mongo/README.md +13 -13
  149. svc_infra/db/nosql/mongo/client.py +19 -2
  150. svc_infra/db/nosql/mongo/settings.py +6 -2
  151. svc_infra/db/nosql/repository.py +35 -15
  152. svc_infra/db/nosql/resource.py +20 -3
  153. svc_infra/db/nosql/scaffold.py +9 -3
  154. svc_infra/db/nosql/service.py +3 -1
  155. svc_infra/db/nosql/types.py +6 -2
  156. svc_infra/db/ops.py +384 -0
  157. svc_infra/db/outbox.py +108 -0
  158. svc_infra/db/sql/apikey.py +37 -9
  159. svc_infra/db/sql/authref.py +9 -3
  160. svc_infra/db/sql/constants.py +12 -8
  161. svc_infra/db/sql/core.py +2 -2
  162. svc_infra/db/sql/management.py +11 -8
  163. svc_infra/db/sql/repository.py +99 -26
  164. svc_infra/db/sql/resource.py +5 -0
  165. svc_infra/db/sql/scaffold.py +6 -2
  166. svc_infra/db/sql/service.py +15 -5
  167. svc_infra/db/sql/templates/models_schemas/auth/models.py.tmpl +7 -56
  168. svc_infra/db/sql/templates/models_schemas/auth/schemas.py.tmpl +1 -1
  169. svc_infra/db/sql/templates/setup/env_async.py.tmpl +34 -12
  170. svc_infra/db/sql/templates/setup/env_sync.py.tmpl +29 -7
  171. svc_infra/db/sql/tenant.py +88 -0
  172. svc_infra/db/sql/uniq_hooks.py +9 -3
  173. svc_infra/db/sql/utils.py +138 -51
  174. svc_infra/db/sql/versioning.py +14 -0
  175. svc_infra/deploy/__init__.py +538 -0
  176. svc_infra/documents/__init__.py +100 -0
  177. svc_infra/documents/add.py +264 -0
  178. svc_infra/documents/ease.py +233 -0
  179. svc_infra/documents/models.py +114 -0
  180. svc_infra/documents/storage.py +264 -0
  181. svc_infra/dx/add.py +65 -0
  182. svc_infra/dx/changelog.py +74 -0
  183. svc_infra/dx/checks.py +68 -0
  184. svc_infra/exceptions.py +141 -0
  185. svc_infra/health/__init__.py +864 -0
  186. svc_infra/http/__init__.py +13 -0
  187. svc_infra/http/client.py +105 -0
  188. svc_infra/jobs/builtins/outbox_processor.py +40 -0
  189. svc_infra/jobs/builtins/webhook_delivery.py +95 -0
  190. svc_infra/jobs/easy.py +33 -0
  191. svc_infra/jobs/loader.py +50 -0
  192. svc_infra/jobs/queue.py +116 -0
  193. svc_infra/jobs/redis_queue.py +256 -0
  194. svc_infra/jobs/runner.py +79 -0
  195. svc_infra/jobs/scheduler.py +53 -0
  196. svc_infra/jobs/worker.py +40 -0
  197. svc_infra/loaders/__init__.py +186 -0
  198. svc_infra/loaders/base.py +142 -0
  199. svc_infra/loaders/github.py +311 -0
  200. svc_infra/loaders/models.py +147 -0
  201. svc_infra/loaders/url.py +235 -0
  202. svc_infra/logging/__init__.py +374 -0
  203. svc_infra/mcp/svc_infra_mcp.py +91 -33
  204. svc_infra/obs/README.md +2 -0
  205. svc_infra/obs/add.py +65 -9
  206. svc_infra/obs/cloud_dash.py +2 -1
  207. svc_infra/obs/grafana/dashboards/http-overview.json +45 -0
  208. svc_infra/obs/metrics/__init__.py +52 -0
  209. svc_infra/obs/metrics/asgi.py +13 -7
  210. svc_infra/obs/metrics/http.py +9 -5
  211. svc_infra/obs/metrics/sqlalchemy.py +13 -9
  212. svc_infra/obs/metrics.py +53 -0
  213. svc_infra/obs/settings.py +6 -2
  214. svc_infra/security/add.py +217 -0
  215. svc_infra/security/audit.py +212 -0
  216. svc_infra/security/audit_service.py +74 -0
  217. svc_infra/security/headers.py +52 -0
  218. svc_infra/security/hibp.py +101 -0
  219. svc_infra/security/jwt_rotation.py +105 -0
  220. svc_infra/security/lockout.py +102 -0
  221. svc_infra/security/models.py +287 -0
  222. svc_infra/security/oauth_models.py +73 -0
  223. svc_infra/security/org_invites.py +130 -0
  224. svc_infra/security/passwords.py +79 -0
  225. svc_infra/security/permissions.py +171 -0
  226. svc_infra/security/session.py +98 -0
  227. svc_infra/security/signed_cookies.py +100 -0
  228. svc_infra/storage/__init__.py +93 -0
  229. svc_infra/storage/add.py +253 -0
  230. svc_infra/storage/backends/__init__.py +11 -0
  231. svc_infra/storage/backends/local.py +339 -0
  232. svc_infra/storage/backends/memory.py +216 -0
  233. svc_infra/storage/backends/s3.py +353 -0
  234. svc_infra/storage/base.py +239 -0
  235. svc_infra/storage/easy.py +185 -0
  236. svc_infra/storage/settings.py +195 -0
  237. svc_infra/testing/__init__.py +685 -0
  238. svc_infra/utils.py +7 -3
  239. svc_infra/webhooks/__init__.py +69 -0
  240. svc_infra/webhooks/add.py +339 -0
  241. svc_infra/webhooks/encryption.py +115 -0
  242. svc_infra/webhooks/fastapi.py +39 -0
  243. svc_infra/webhooks/router.py +55 -0
  244. svc_infra/webhooks/service.py +70 -0
  245. svc_infra/webhooks/signing.py +34 -0
  246. svc_infra/websocket/__init__.py +79 -0
  247. svc_infra/websocket/add.py +140 -0
  248. svc_infra/websocket/client.py +282 -0
  249. svc_infra/websocket/config.py +69 -0
  250. svc_infra/websocket/easy.py +76 -0
  251. svc_infra/websocket/exceptions.py +61 -0
  252. svc_infra/websocket/manager.py +344 -0
  253. svc_infra/websocket/models.py +49 -0
  254. svc_infra-0.1.706.dist-info/LICENSE +21 -0
  255. svc_infra-0.1.706.dist-info/METADATA +356 -0
  256. svc_infra-0.1.706.dist-info/RECORD +357 -0
  257. svc_infra-0.1.589.dist-info/METADATA +0 -79
  258. svc_infra-0.1.589.dist-info/RECORD +0 -234
  259. {svc_infra-0.1.589.dist-info → svc_infra-0.1.706.dist-info}/WHEEL +0 -0
  260. {svc_infra-0.1.589.dist-info → svc_infra-0.1.706.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,13 @@
1
+ from .client import (
2
+ get_default_timeout_seconds,
3
+ make_timeout,
4
+ new_async_httpx_client,
5
+ new_httpx_client,
6
+ )
7
+
8
+ __all__ = [
9
+ "get_default_timeout_seconds",
10
+ "new_httpx_client",
11
+ "new_async_httpx_client",
12
+ "make_timeout",
13
+ ]
@@ -0,0 +1,105 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from contextvars import ContextVar
5
+ from typing import Any, Dict, Optional
6
+
7
+ import httpx
8
+
9
+ from svc_infra.app.env import pick
10
+
11
+ # Context var for request ID propagation across async boundaries
12
+ _request_id_ctx: ContextVar[str | None] = ContextVar("request_id", default=None)
13
+
14
+
15
+ def set_request_id(request_id: str | None) -> None:
16
+ """Set the current request ID for propagation to outbound HTTP calls."""
17
+ _request_id_ctx.set(request_id)
18
+
19
+
20
+ def get_request_id() -> str | None:
21
+ """Get the current request ID for propagation."""
22
+ return _request_id_ctx.get()
23
+
24
+
25
+ def _merge_request_id_header(headers: Dict[str, str] | None) -> Dict[str, str]:
26
+ """Merge X-Request-Id header into headers dict if request ID is set."""
27
+ result = dict(headers) if headers else {}
28
+ request_id = get_request_id()
29
+ if request_id and "X-Request-Id" not in result:
30
+ result["X-Request-Id"] = request_id
31
+ return result
32
+
33
+
34
+ def _parse_float_env(name: str, default: float) -> float:
35
+ raw = os.getenv(name)
36
+ if raw is None or raw == "":
37
+ return default
38
+ try:
39
+ return float(raw)
40
+ except ValueError:
41
+ return default
42
+
43
+
44
+ def get_default_timeout_seconds() -> float:
45
+ """Return default outbound HTTP client timeout in seconds.
46
+
47
+ Env var: HTTP_CLIENT_TIMEOUT_SECONDS (float)
48
+ Defaults: 10.0 seconds for all envs unless overridden; tweakable via pick() if needed.
49
+ """
50
+ default = pick(prod=10.0, nonprod=10.0)
51
+ return _parse_float_env("HTTP_CLIENT_TIMEOUT_SECONDS", default)
52
+
53
+
54
+ def make_timeout(seconds: float | None = None) -> httpx.Timeout:
55
+ s = seconds if seconds is not None else get_default_timeout_seconds()
56
+ # Apply same timeout for connect/read/write/pool for simplicity
57
+ return httpx.Timeout(timeout=s)
58
+
59
+
60
+ def new_httpx_client(
61
+ *,
62
+ timeout_seconds: Optional[float] = None,
63
+ headers: Optional[Dict[str, str]] = None,
64
+ base_url: Optional[str] = None,
65
+ propagate_request_id: bool = True,
66
+ **kwargs: Any,
67
+ ) -> httpx.Client:
68
+ """Create a sync httpx Client with default timeout and optional headers/base_url.
69
+
70
+ Callers can override timeout_seconds; remaining kwargs are forwarded to httpx.Client.
71
+ If propagate_request_id=True (default), X-Request-Id header is added from context.
72
+ """
73
+ timeout = make_timeout(timeout_seconds)
74
+ merged_headers = (
75
+ _merge_request_id_header(headers) if propagate_request_id else headers
76
+ )
77
+ # httpx doesn't accept base_url=None; only pass if non-None
78
+ client_kwargs = {"timeout": timeout, "headers": merged_headers, **kwargs}
79
+ if base_url is not None:
80
+ client_kwargs["base_url"] = base_url
81
+ return httpx.Client(**client_kwargs)
82
+
83
+
84
+ def new_async_httpx_client(
85
+ *,
86
+ timeout_seconds: Optional[float] = None,
87
+ headers: Optional[Dict[str, str]] = None,
88
+ base_url: Optional[str] = None,
89
+ propagate_request_id: bool = True,
90
+ **kwargs: Any,
91
+ ) -> httpx.AsyncClient:
92
+ """Create an async httpx AsyncClient with default timeout and optional headers/base_url.
93
+
94
+ Callers can override timeout_seconds; remaining kwargs are forwarded to httpx.AsyncClient.
95
+ If propagate_request_id=True (default), X-Request-Id header is added from context.
96
+ """
97
+ timeout = make_timeout(timeout_seconds)
98
+ merged_headers = (
99
+ _merge_request_id_header(headers) if propagate_request_id else headers
100
+ )
101
+ # httpx doesn't accept base_url=None; only pass if non-None
102
+ client_kwargs = {"timeout": timeout, "headers": merged_headers, **kwargs}
103
+ if base_url is not None:
104
+ client_kwargs["base_url"] = base_url
105
+ return httpx.AsyncClient(**client_kwargs)
@@ -0,0 +1,40 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Iterable, Optional
4
+
5
+ from svc_infra.db.outbox import OutboxStore
6
+ from svc_infra.jobs.queue import JobQueue
7
+
8
+
9
+ def make_outbox_tick(
10
+ outbox: OutboxStore,
11
+ queue: JobQueue,
12
+ *,
13
+ topics: Optional[Iterable[str]] = None,
14
+ job_name_prefix: str = "outbox",
15
+ ):
16
+ """Return an async task function to move one outbox message into the job queue.
17
+
18
+ - It fetches at most one unprocessed message per tick to avoid starving others.
19
+ - The enqueued job name is f"{job_name_prefix}.{topic}" to allow routing.
20
+ - The job payload contains `outbox_id`, `topic`, and original `payload`.
21
+ """
22
+
23
+ dispatched: set[int] = set()
24
+
25
+ async def _tick():
26
+ # Outbox is sync; this wrapper is async for scheduler compatibility
27
+ msg = outbox.fetch_next(topics=topics)
28
+ if not msg:
29
+ return
30
+ if msg.id in dispatched:
31
+ return
32
+ job_name = f"{job_name_prefix}.{msg.topic}"
33
+ queue.enqueue(
34
+ job_name, {"outbox_id": msg.id, "topic": msg.topic, "payload": msg.payload}
35
+ )
36
+ # mark as dispatched (bump attempts) so it won't be re-enqueued by fetch_next
37
+ outbox.mark_failed(msg.id)
38
+ dispatched.add(msg.id)
39
+
40
+ return _tick
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from svc_infra.db.inbox import InboxStore
6
+ from svc_infra.db.outbox import OutboxStore
7
+ from svc_infra.http import get_default_timeout_seconds, new_async_httpx_client
8
+ from svc_infra.jobs.queue import Job
9
+ from svc_infra.webhooks.encryption import decrypt_secret
10
+ from svc_infra.webhooks.signing import sign
11
+
12
+
13
+ def make_webhook_handler(
14
+ *,
15
+ outbox: OutboxStore,
16
+ inbox: InboxStore,
17
+ get_webhook_url_for_topic,
18
+ get_secret_for_topic,
19
+ header_name: str = "X-Signature",
20
+ ):
21
+ """Return an async job handler to deliver webhooks.
22
+
23
+ Expected job payload shape:
24
+ {"outbox_id": int, "topic": str, "payload": {...}}
25
+ """
26
+
27
+ async def _handler(job: Job) -> None:
28
+ data = job.payload or {}
29
+ outbox_id = data.get("outbox_id")
30
+ topic = data.get("topic")
31
+ payload = data.get("payload") or {}
32
+ if not outbox_id or not topic:
33
+ # Nothing we can do; ack to avoid poison loop
34
+ return
35
+ # dedupe marker key (marked after successful delivery)
36
+ key = f"webhook:{outbox_id}"
37
+ if inbox.is_marked(key):
38
+ # already delivered
39
+ outbox.mark_processed(int(outbox_id))
40
+ return
41
+ event = payload.get("event") if isinstance(payload, dict) else None
42
+ subscription = (
43
+ payload.get("subscription") if isinstance(payload, dict) else None
44
+ )
45
+ if event is not None and subscription is not None:
46
+ delivery_payload = event
47
+ url = subscription.get("url") or get_webhook_url_for_topic(topic)
48
+ # Decrypt secret (handles both encrypted and plaintext for backwards compat)
49
+ raw_secret = subscription.get("secret") or get_secret_for_topic(topic)
50
+ secret = decrypt_secret(raw_secret)
51
+ subscription_id = subscription.get("id")
52
+ else:
53
+ delivery_payload = payload
54
+ url = get_webhook_url_for_topic(topic)
55
+ secret = get_secret_for_topic(topic)
56
+ subscription_id = None
57
+ sig = sign(secret, delivery_payload)
58
+ headers = {
59
+ header_name: sig,
60
+ "X-Event-Id": str(outbox_id),
61
+ "X-Topic": str(topic),
62
+ "X-Attempt": str(job.attempts or 1),
63
+ "X-Signature-Alg": "hmac-sha256",
64
+ "X-Signature-Version": "v1",
65
+ }
66
+ if subscription_id:
67
+ headers["X-Webhook-Subscription"] = str(subscription_id)
68
+ # include event payload version if present
69
+ version = None
70
+ if isinstance(delivery_payload, dict):
71
+ version = delivery_payload.get("version")
72
+ if version is not None:
73
+ headers["X-Payload-Version"] = str(version)
74
+ # Derive timeout: dedicated WEBHOOK_DELIVERY_TIMEOUT_SECONDS or default HTTP client timeout
75
+ timeout_seconds = None
76
+ env_timeout = os.getenv("WEBHOOK_DELIVERY_TIMEOUT_SECONDS")
77
+ if env_timeout:
78
+ try:
79
+ timeout_seconds = float(env_timeout)
80
+ except ValueError:
81
+ timeout_seconds = get_default_timeout_seconds()
82
+ else:
83
+ timeout_seconds = get_default_timeout_seconds()
84
+
85
+ async with new_async_httpx_client(timeout_seconds=timeout_seconds) as client:
86
+ resp = await client.post(url, json=delivery_payload, headers=headers)
87
+ if 200 <= resp.status_code < 300:
88
+ # record delivery and mark processed
89
+ inbox.mark_if_new(key, ttl_seconds=24 * 3600)
90
+ outbox.mark_processed(int(outbox_id))
91
+ return
92
+ # allow retry on non-2xx: raise to trigger fail/backoff
93
+ raise RuntimeError(f"webhook delivery failed: {resp.status_code}")
94
+
95
+ return _handler
svc_infra/jobs/easy.py ADDED
@@ -0,0 +1,33 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from redis import Redis
6
+
7
+ from .queue import InMemoryJobQueue, JobQueue
8
+ from .redis_queue import RedisJobQueue
9
+ from .scheduler import InMemoryScheduler
10
+
11
+
12
+ class JobsConfig:
13
+ def __init__(self, driver: str | None = None):
14
+ # Future: support redis/sql drivers via extras
15
+ self.driver = driver or os.getenv("JOBS_DRIVER", "memory").lower()
16
+
17
+
18
+ def easy_jobs(*, driver: str | None = None) -> tuple[JobQueue, InMemoryScheduler]:
19
+ """One-call wiring for jobs: returns (queue, scheduler).
20
+
21
+ Defaults to in-memory implementations for local/dev. ENV override via JOBS_DRIVER.
22
+ """
23
+ cfg = JobsConfig(driver=driver)
24
+ # Choose backend
25
+ queue: JobQueue
26
+ if cfg.driver == "redis":
27
+ url = os.getenv("REDIS_URL", "redis://localhost:6379/0")
28
+ client = Redis.from_url(url)
29
+ queue = RedisJobQueue(client)
30
+ else:
31
+ queue = InMemoryJobQueue()
32
+ scheduler = InMemoryScheduler()
33
+ return queue, scheduler
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import importlib
5
+ import json
6
+ import logging
7
+ import os
8
+ from typing import Awaitable, Callable, cast
9
+
10
+ from .scheduler import InMemoryScheduler
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def _resolve_target(path: str) -> Callable[[], Awaitable[None]]:
16
+ mod_name, func_name = path.split(":", 1)
17
+ mod = importlib.import_module(mod_name)
18
+ fn = getattr(mod, func_name)
19
+ if asyncio.iscoroutinefunction(fn):
20
+ return cast(Callable[[], Awaitable[None]], fn)
21
+
22
+ # wrap sync into async
23
+ async def _wrapped():
24
+ fn()
25
+
26
+ return _wrapped
27
+
28
+
29
+ def schedule_from_env(
30
+ scheduler: InMemoryScheduler, env_var: str = "JOBS_SCHEDULE_JSON"
31
+ ) -> None:
32
+ data = os.getenv(env_var)
33
+ if not data:
34
+ return
35
+ try:
36
+ tasks = json.loads(data)
37
+ except json.JSONDecodeError:
38
+ return
39
+ if not isinstance(tasks, list):
40
+ return
41
+ for t in tasks:
42
+ try:
43
+ name = t["name"]
44
+ interval = int(t.get("interval_seconds", 60))
45
+ target = t["target"]
46
+ fn = _resolve_target(target)
47
+ scheduler.add_task(name, interval, fn)
48
+ except Exception as e:
49
+ logger.warning("Failed to load scheduled job entry %s: %s", t, e)
50
+ continue
@@ -0,0 +1,116 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import os
5
+ import warnings
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime, timedelta, timezone
8
+ from typing import Any, Dict, Optional, Protocol
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ _INMEMORY_WARNED = False
13
+
14
+
15
+ def _check_inmemory_production_warning(class_name: str) -> None:
16
+ """Warn if in-memory store is used in production."""
17
+ global _INMEMORY_WARNED
18
+ if _INMEMORY_WARNED:
19
+ return
20
+ env = os.getenv("ENV", "development").lower()
21
+ if env in ("production", "staging", "prod"):
22
+ _INMEMORY_WARNED = True
23
+ msg = (
24
+ f"{class_name} is being used in {env} environment. "
25
+ "This is NOT suitable for production - data will be lost on restart. "
26
+ "Use RedisJobQueue instead."
27
+ )
28
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
29
+ logger.critical(msg)
30
+
31
+
32
+ @dataclass
33
+ class Job:
34
+ id: str
35
+ name: str
36
+ payload: Dict[str, Any]
37
+ available_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
38
+ attempts: int = 0
39
+ max_attempts: int = 5
40
+ backoff_seconds: int = 60 # base backoff for retry
41
+ last_error: Optional[str] = None
42
+
43
+
44
+ class JobQueue(Protocol):
45
+ def enqueue(
46
+ self, name: str, payload: Dict[str, Any], *, delay_seconds: int = 0
47
+ ) -> Job:
48
+ pass
49
+
50
+ def reserve_next(self) -> Optional[Job]:
51
+ pass
52
+
53
+ def ack(self, job_id: str) -> None:
54
+ pass
55
+
56
+ def fail(self, job_id: str, *, error: str | None = None) -> None:
57
+ pass
58
+
59
+
60
+ class InMemoryJobQueue:
61
+ """Simple in-memory queue for tests and local runs.
62
+
63
+ Single-threaded reserve/ack/fail semantics. Not suitable for production.
64
+ """
65
+
66
+ def __init__(self):
67
+ _check_inmemory_production_warning("InMemoryJobQueue")
68
+ self._seq = 0
69
+ self._jobs: list[Job] = []
70
+
71
+ def _next_id(self) -> str:
72
+ self._seq += 1
73
+ return str(self._seq)
74
+
75
+ def enqueue(
76
+ self, name: str, payload: Dict[str, Any], *, delay_seconds: int = 0
77
+ ) -> Job:
78
+ when = datetime.now(timezone.utc) + timedelta(seconds=delay_seconds)
79
+ job = Job(
80
+ id=self._next_id(), name=name, payload=dict(payload), available_at=when
81
+ )
82
+ self._jobs.append(job)
83
+ return job
84
+
85
+ def reserve_next(self) -> Optional[Job]:
86
+ now = datetime.now(timezone.utc)
87
+ for job in self._jobs:
88
+ if (
89
+ job.available_at <= now
90
+ and job.attempts >= 0
91
+ and job.attempts < job.max_attempts
92
+ ):
93
+ job.attempts += 1
94
+ return job
95
+ return None
96
+
97
+ def ack(self, job_id: str) -> None:
98
+ self._jobs = [j for j in self._jobs if j.id != job_id]
99
+
100
+ def fail(self, job_id: str, *, error: str | None = None) -> None:
101
+ now = datetime.now(timezone.utc)
102
+ for job in self._jobs:
103
+ if job.id == job_id:
104
+ job.last_error = error
105
+ # Exponential backoff: base * attempts
106
+ delay = job.backoff_seconds * max(1, job.attempts)
107
+ if delay > 0:
108
+ # Add a tiny fudge so an immediate subsequent poll in ultra-fast
109
+ # environments (like our acceptance API) doesn't re-reserve the job.
110
+ # This keeps tests deterministic without impacting semantics.
111
+ job.available_at = now + timedelta(seconds=delay, milliseconds=250)
112
+ else:
113
+ # When backoff is explicitly zero (e.g., unit tests forcing
114
+ # immediate retry), make the job available right away.
115
+ job.available_at = now
116
+ return