svc-infra 0.1.595__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.
- svc_infra/__init__.py +58 -2
- svc_infra/apf_payments/models.py +133 -42
- svc_infra/apf_payments/provider/aiydan.py +121 -47
- svc_infra/apf_payments/provider/base.py +30 -9
- svc_infra/apf_payments/provider/stripe.py +156 -62
- svc_infra/apf_payments/schemas.py +18 -9
- svc_infra/apf_payments/service.py +98 -41
- svc_infra/apf_payments/settings.py +5 -1
- svc_infra/api/__init__.py +61 -0
- svc_infra/api/fastapi/__init__.py +15 -0
- svc_infra/api/fastapi/admin/__init__.py +3 -0
- svc_infra/api/fastapi/admin/add.py +245 -0
- svc_infra/api/fastapi/apf_payments/router.py +128 -70
- svc_infra/api/fastapi/apf_payments/setup.py +13 -6
- svc_infra/api/fastapi/auth/__init__.py +65 -0
- svc_infra/api/fastapi/auth/_cookies.py +6 -2
- svc_infra/api/fastapi/auth/add.py +17 -14
- svc_infra/api/fastapi/auth/gaurd.py +45 -16
- svc_infra/api/fastapi/auth/mfa/models.py +3 -1
- svc_infra/api/fastapi/auth/mfa/pre_auth.py +10 -6
- svc_infra/api/fastapi/auth/mfa/router.py +15 -8
- svc_infra/api/fastapi/auth/mfa/security.py +1 -2
- svc_infra/api/fastapi/auth/mfa/utils.py +2 -1
- svc_infra/api/fastapi/auth/mfa/verify.py +9 -2
- svc_infra/api/fastapi/auth/policy.py +0 -1
- svc_infra/api/fastapi/auth/providers.py +3 -1
- svc_infra/api/fastapi/auth/routers/apikey_router.py +6 -6
- svc_infra/api/fastapi/auth/routers/oauth_router.py +146 -52
- svc_infra/api/fastapi/auth/routers/session_router.py +6 -2
- svc_infra/api/fastapi/auth/security.py +31 -10
- svc_infra/api/fastapi/auth/sender.py +8 -1
- svc_infra/api/fastapi/auth/state.py +3 -1
- svc_infra/api/fastapi/auth/ws_security.py +275 -0
- svc_infra/api/fastapi/billing/router.py +73 -0
- svc_infra/api/fastapi/billing/setup.py +19 -0
- svc_infra/api/fastapi/cache/add.py +9 -5
- svc_infra/api/fastapi/db/__init__.py +5 -1
- svc_infra/api/fastapi/db/http.py +3 -1
- svc_infra/api/fastapi/db/nosql/__init__.py +39 -1
- svc_infra/api/fastapi/db/nosql/mongo/add.py +47 -32
- svc_infra/api/fastapi/db/nosql/mongo/crud_router.py +30 -11
- svc_infra/api/fastapi/db/sql/__init__.py +5 -1
- svc_infra/api/fastapi/db/sql/add.py +71 -26
- svc_infra/api/fastapi/db/sql/crud_router.py +210 -22
- svc_infra/api/fastapi/db/sql/health.py +3 -1
- svc_infra/api/fastapi/db/sql/session.py +18 -0
- svc_infra/api/fastapi/db/sql/users.py +18 -6
- svc_infra/api/fastapi/dependencies/ratelimit.py +78 -14
- svc_infra/api/fastapi/docs/add.py +173 -0
- svc_infra/api/fastapi/docs/landing.py +4 -2
- svc_infra/api/fastapi/docs/scoped.py +62 -15
- svc_infra/api/fastapi/dual/__init__.py +12 -2
- svc_infra/api/fastapi/dual/dualize.py +1 -1
- svc_infra/api/fastapi/dual/protected.py +126 -4
- svc_infra/api/fastapi/dual/public.py +25 -0
- svc_infra/api/fastapi/dual/router.py +40 -13
- svc_infra/api/fastapi/dx.py +33 -2
- svc_infra/api/fastapi/ease.py +10 -2
- svc_infra/api/fastapi/http/concurrency.py +2 -1
- svc_infra/api/fastapi/http/conditional.py +3 -1
- svc_infra/api/fastapi/middleware/debug.py +4 -1
- svc_infra/api/fastapi/middleware/errors/catchall.py +6 -2
- svc_infra/api/fastapi/middleware/errors/exceptions.py +1 -1
- svc_infra/api/fastapi/middleware/errors/handlers.py +54 -8
- svc_infra/api/fastapi/middleware/graceful_shutdown.py +104 -0
- svc_infra/api/fastapi/middleware/idempotency.py +197 -70
- svc_infra/api/fastapi/middleware/idempotency_store.py +187 -0
- svc_infra/api/fastapi/middleware/optimistic_lock.py +42 -0
- svc_infra/api/fastapi/middleware/ratelimit.py +125 -28
- svc_infra/api/fastapi/middleware/ratelimit_store.py +43 -10
- svc_infra/api/fastapi/middleware/request_id.py +27 -11
- svc_infra/api/fastapi/middleware/request_size_limit.py +3 -3
- svc_infra/api/fastapi/middleware/timeout.py +177 -0
- svc_infra/api/fastapi/openapi/apply.py +5 -3
- svc_infra/api/fastapi/openapi/conventions.py +9 -2
- svc_infra/api/fastapi/openapi/mutators.py +165 -20
- svc_infra/api/fastapi/openapi/pipeline.py +1 -1
- svc_infra/api/fastapi/openapi/security.py +3 -1
- svc_infra/api/fastapi/ops/add.py +75 -0
- svc_infra/api/fastapi/pagination.py +47 -20
- svc_infra/api/fastapi/routers/__init__.py +43 -15
- svc_infra/api/fastapi/routers/ping.py +1 -0
- svc_infra/api/fastapi/setup.py +188 -57
- svc_infra/api/fastapi/tenancy/add.py +19 -0
- svc_infra/api/fastapi/tenancy/context.py +112 -0
- svc_infra/api/fastapi/versioned.py +101 -0
- svc_infra/app/README.md +5 -5
- svc_infra/app/__init__.py +3 -1
- svc_infra/app/env.py +69 -1
- svc_infra/app/logging/add.py +9 -2
- svc_infra/app/logging/formats.py +12 -5
- svc_infra/billing/__init__.py +23 -0
- svc_infra/billing/async_service.py +147 -0
- svc_infra/billing/jobs.py +241 -0
- svc_infra/billing/models.py +177 -0
- svc_infra/billing/quotas.py +103 -0
- svc_infra/billing/schemas.py +36 -0
- svc_infra/billing/service.py +123 -0
- svc_infra/bundled_docs/README.md +5 -0
- svc_infra/bundled_docs/__init__.py +1 -0
- svc_infra/bundled_docs/getting-started.md +6 -0
- svc_infra/cache/__init__.py +9 -0
- svc_infra/cache/add.py +170 -0
- svc_infra/cache/backend.py +7 -6
- svc_infra/cache/decorators.py +81 -15
- svc_infra/cache/demo.py +2 -2
- svc_infra/cache/keys.py +24 -4
- svc_infra/cache/recache.py +26 -14
- svc_infra/cache/resources.py +14 -5
- svc_infra/cache/tags.py +19 -44
- svc_infra/cache/utils.py +3 -1
- svc_infra/cli/__init__.py +52 -8
- svc_infra/cli/__main__.py +4 -0
- svc_infra/cli/cmds/__init__.py +39 -2
- svc_infra/cli/cmds/db/nosql/mongo/mongo_cmds.py +7 -4
- svc_infra/cli/cmds/db/nosql/mongo/mongo_scaffold_cmds.py +7 -5
- svc_infra/cli/cmds/db/ops_cmds.py +270 -0
- svc_infra/cli/cmds/db/sql/alembic_cmds.py +103 -18
- svc_infra/cli/cmds/db/sql/sql_export_cmds.py +88 -0
- svc_infra/cli/cmds/db/sql/sql_scaffold_cmds.py +3 -3
- svc_infra/cli/cmds/docs/docs_cmds.py +142 -0
- svc_infra/cli/cmds/dx/__init__.py +12 -0
- svc_infra/cli/cmds/dx/dx_cmds.py +116 -0
- svc_infra/cli/cmds/health/__init__.py +179 -0
- svc_infra/cli/cmds/health/health_cmds.py +8 -0
- svc_infra/cli/cmds/help.py +4 -0
- svc_infra/cli/cmds/jobs/__init__.py +1 -0
- svc_infra/cli/cmds/jobs/jobs_cmds.py +47 -0
- svc_infra/cli/cmds/obs/obs_cmds.py +36 -15
- svc_infra/cli/cmds/sdk/__init__.py +0 -0
- svc_infra/cli/cmds/sdk/sdk_cmds.py +112 -0
- svc_infra/cli/foundation/runner.py +6 -2
- svc_infra/data/add.py +61 -0
- svc_infra/data/backup.py +58 -0
- svc_infra/data/erasure.py +45 -0
- svc_infra/data/fixtures.py +42 -0
- svc_infra/data/retention.py +61 -0
- svc_infra/db/__init__.py +15 -0
- svc_infra/db/crud_schema.py +9 -9
- svc_infra/db/inbox.py +67 -0
- svc_infra/db/nosql/__init__.py +3 -0
- svc_infra/db/nosql/core.py +30 -9
- svc_infra/db/nosql/indexes.py +3 -1
- svc_infra/db/nosql/management.py +1 -1
- svc_infra/db/nosql/mongo/README.md +13 -13
- svc_infra/db/nosql/mongo/client.py +19 -2
- svc_infra/db/nosql/mongo/settings.py +6 -2
- svc_infra/db/nosql/repository.py +35 -15
- svc_infra/db/nosql/resource.py +20 -3
- svc_infra/db/nosql/scaffold.py +9 -3
- svc_infra/db/nosql/service.py +3 -1
- svc_infra/db/nosql/types.py +6 -2
- svc_infra/db/ops.py +384 -0
- svc_infra/db/outbox.py +108 -0
- svc_infra/db/sql/apikey.py +37 -9
- svc_infra/db/sql/authref.py +9 -3
- svc_infra/db/sql/constants.py +12 -8
- svc_infra/db/sql/core.py +2 -2
- svc_infra/db/sql/management.py +11 -8
- svc_infra/db/sql/repository.py +99 -26
- svc_infra/db/sql/resource.py +5 -0
- svc_infra/db/sql/scaffold.py +6 -2
- svc_infra/db/sql/service.py +15 -5
- svc_infra/db/sql/templates/models_schemas/auth/models.py.tmpl +7 -56
- svc_infra/db/sql/templates/setup/env_async.py.tmpl +34 -12
- svc_infra/db/sql/templates/setup/env_sync.py.tmpl +29 -7
- svc_infra/db/sql/tenant.py +88 -0
- svc_infra/db/sql/uniq_hooks.py +9 -3
- svc_infra/db/sql/utils.py +138 -51
- svc_infra/db/sql/versioning.py +14 -0
- svc_infra/deploy/__init__.py +538 -0
- svc_infra/documents/__init__.py +100 -0
- svc_infra/documents/add.py +264 -0
- svc_infra/documents/ease.py +233 -0
- svc_infra/documents/models.py +114 -0
- svc_infra/documents/storage.py +264 -0
- svc_infra/dx/add.py +65 -0
- svc_infra/dx/changelog.py +74 -0
- svc_infra/dx/checks.py +68 -0
- svc_infra/exceptions.py +141 -0
- svc_infra/health/__init__.py +864 -0
- svc_infra/http/__init__.py +13 -0
- svc_infra/http/client.py +105 -0
- svc_infra/jobs/builtins/outbox_processor.py +40 -0
- svc_infra/jobs/builtins/webhook_delivery.py +95 -0
- svc_infra/jobs/easy.py +33 -0
- svc_infra/jobs/loader.py +50 -0
- svc_infra/jobs/queue.py +116 -0
- svc_infra/jobs/redis_queue.py +256 -0
- svc_infra/jobs/runner.py +79 -0
- svc_infra/jobs/scheduler.py +53 -0
- svc_infra/jobs/worker.py +40 -0
- svc_infra/loaders/__init__.py +186 -0
- svc_infra/loaders/base.py +142 -0
- svc_infra/loaders/github.py +311 -0
- svc_infra/loaders/models.py +147 -0
- svc_infra/loaders/url.py +235 -0
- svc_infra/logging/__init__.py +374 -0
- svc_infra/mcp/svc_infra_mcp.py +91 -33
- svc_infra/obs/README.md +2 -0
- svc_infra/obs/add.py +65 -9
- svc_infra/obs/cloud_dash.py +2 -1
- svc_infra/obs/grafana/dashboards/http-overview.json +45 -0
- svc_infra/obs/metrics/__init__.py +3 -4
- svc_infra/obs/metrics/asgi.py +13 -7
- svc_infra/obs/metrics/http.py +9 -5
- svc_infra/obs/metrics/sqlalchemy.py +13 -9
- svc_infra/obs/metrics.py +6 -5
- svc_infra/obs/settings.py +6 -2
- svc_infra/security/add.py +217 -0
- svc_infra/security/audit.py +92 -10
- svc_infra/security/audit_service.py +4 -3
- svc_infra/security/headers.py +15 -2
- svc_infra/security/hibp.py +14 -4
- svc_infra/security/jwt_rotation.py +74 -22
- svc_infra/security/lockout.py +11 -5
- svc_infra/security/models.py +54 -12
- svc_infra/security/oauth_models.py +73 -0
- svc_infra/security/org_invites.py +5 -3
- svc_infra/security/passwords.py +3 -1
- svc_infra/security/permissions.py +25 -2
- svc_infra/security/session.py +1 -1
- svc_infra/security/signed_cookies.py +21 -1
- svc_infra/storage/__init__.py +93 -0
- svc_infra/storage/add.py +253 -0
- svc_infra/storage/backends/__init__.py +11 -0
- svc_infra/storage/backends/local.py +339 -0
- svc_infra/storage/backends/memory.py +216 -0
- svc_infra/storage/backends/s3.py +353 -0
- svc_infra/storage/base.py +239 -0
- svc_infra/storage/easy.py +185 -0
- svc_infra/storage/settings.py +195 -0
- svc_infra/testing/__init__.py +685 -0
- svc_infra/utils.py +7 -3
- svc_infra/webhooks/__init__.py +69 -0
- svc_infra/webhooks/add.py +339 -0
- svc_infra/webhooks/encryption.py +115 -0
- svc_infra/webhooks/fastapi.py +39 -0
- svc_infra/webhooks/router.py +55 -0
- svc_infra/webhooks/service.py +70 -0
- svc_infra/webhooks/signing.py +34 -0
- svc_infra/websocket/__init__.py +79 -0
- svc_infra/websocket/add.py +140 -0
- svc_infra/websocket/client.py +282 -0
- svc_infra/websocket/config.py +69 -0
- svc_infra/websocket/easy.py +76 -0
- svc_infra/websocket/exceptions.py +61 -0
- svc_infra/websocket/manager.py +344 -0
- svc_infra/websocket/models.py +49 -0
- svc_infra-0.1.706.dist-info/LICENSE +21 -0
- svc_infra-0.1.706.dist-info/METADATA +356 -0
- svc_infra-0.1.706.dist-info/RECORD +357 -0
- svc_infra-0.1.595.dist-info/METADATA +0 -80
- svc_infra-0.1.595.dist-info/RECORD +0 -253
- {svc_infra-0.1.595.dist-info → svc_infra-0.1.706.dist-info}/WHEEL +0 -0
- {svc_infra-0.1.595.dist-info → svc_infra-0.1.706.dist-info}/entry_points.txt +0 -0
svc_infra/http/client.py
ADDED
|
@@ -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
|
svc_infra/jobs/loader.py
ADDED
|
@@ -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
|
svc_infra/jobs/queue.py
ADDED
|
@@ -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
|