svc-infra 0.1.595__py3-none-any.whl → 1.1.0__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 (274) hide show
  1. svc_infra/__init__.py +58 -2
  2. svc_infra/apf_payments/models.py +68 -38
  3. svc_infra/apf_payments/provider/__init__.py +2 -2
  4. svc_infra/apf_payments/provider/aiydan.py +39 -23
  5. svc_infra/apf_payments/provider/base.py +8 -3
  6. svc_infra/apf_payments/provider/registry.py +3 -5
  7. svc_infra/apf_payments/provider/stripe.py +74 -52
  8. svc_infra/apf_payments/schemas.py +84 -83
  9. svc_infra/apf_payments/service.py +27 -16
  10. svc_infra/apf_payments/settings.py +12 -11
  11. svc_infra/api/__init__.py +61 -0
  12. svc_infra/api/fastapi/__init__.py +34 -0
  13. svc_infra/api/fastapi/admin/__init__.py +3 -0
  14. svc_infra/api/fastapi/admin/add.py +240 -0
  15. svc_infra/api/fastapi/apf_payments/router.py +94 -73
  16. svc_infra/api/fastapi/apf_payments/setup.py +10 -9
  17. svc_infra/api/fastapi/auth/__init__.py +65 -0
  18. svc_infra/api/fastapi/auth/_cookies.py +1 -3
  19. svc_infra/api/fastapi/auth/add.py +14 -15
  20. svc_infra/api/fastapi/auth/gaurd.py +32 -20
  21. svc_infra/api/fastapi/auth/mfa/models.py +3 -4
  22. svc_infra/api/fastapi/auth/mfa/pre_auth.py +13 -9
  23. svc_infra/api/fastapi/auth/mfa/router.py +9 -8
  24. svc_infra/api/fastapi/auth/mfa/security.py +4 -7
  25. svc_infra/api/fastapi/auth/mfa/utils.py +5 -3
  26. svc_infra/api/fastapi/auth/policy.py +0 -1
  27. svc_infra/api/fastapi/auth/providers.py +3 -3
  28. svc_infra/api/fastapi/auth/routers/apikey_router.py +19 -21
  29. svc_infra/api/fastapi/auth/routers/oauth_router.py +98 -52
  30. svc_infra/api/fastapi/auth/routers/session_router.py +6 -5
  31. svc_infra/api/fastapi/auth/security.py +25 -15
  32. svc_infra/api/fastapi/auth/sender.py +5 -0
  33. svc_infra/api/fastapi/auth/settings.py +18 -19
  34. svc_infra/api/fastapi/auth/state.py +5 -4
  35. svc_infra/api/fastapi/auth/ws_security.py +275 -0
  36. svc_infra/api/fastapi/billing/router.py +71 -0
  37. svc_infra/api/fastapi/billing/setup.py +19 -0
  38. svc_infra/api/fastapi/cache/add.py +9 -5
  39. svc_infra/api/fastapi/db/__init__.py +5 -1
  40. svc_infra/api/fastapi/db/http.py +10 -9
  41. svc_infra/api/fastapi/db/nosql/__init__.py +39 -1
  42. svc_infra/api/fastapi/db/nosql/mongo/add.py +35 -30
  43. svc_infra/api/fastapi/db/nosql/mongo/crud_router.py +39 -21
  44. svc_infra/api/fastapi/db/sql/__init__.py +5 -1
  45. svc_infra/api/fastapi/db/sql/add.py +62 -25
  46. svc_infra/api/fastapi/db/sql/crud_router.py +205 -30
  47. svc_infra/api/fastapi/db/sql/session.py +19 -2
  48. svc_infra/api/fastapi/db/sql/users.py +18 -9
  49. svc_infra/api/fastapi/dependencies/ratelimit.py +76 -14
  50. svc_infra/api/fastapi/docs/add.py +163 -0
  51. svc_infra/api/fastapi/docs/landing.py +6 -6
  52. svc_infra/api/fastapi/docs/scoped.py +75 -36
  53. svc_infra/api/fastapi/dual/__init__.py +12 -2
  54. svc_infra/api/fastapi/dual/dualize.py +2 -2
  55. svc_infra/api/fastapi/dual/protected.py +123 -10
  56. svc_infra/api/fastapi/dual/public.py +25 -0
  57. svc_infra/api/fastapi/dual/router.py +18 -8
  58. svc_infra/api/fastapi/dx.py +33 -2
  59. svc_infra/api/fastapi/ease.py +59 -7
  60. svc_infra/api/fastapi/http/concurrency.py +2 -1
  61. svc_infra/api/fastapi/http/conditional.py +2 -2
  62. svc_infra/api/fastapi/middleware/debug.py +4 -1
  63. svc_infra/api/fastapi/middleware/errors/exceptions.py +2 -5
  64. svc_infra/api/fastapi/middleware/errors/handlers.py +50 -10
  65. svc_infra/api/fastapi/middleware/graceful_shutdown.py +95 -0
  66. svc_infra/api/fastapi/middleware/idempotency.py +190 -68
  67. svc_infra/api/fastapi/middleware/idempotency_store.py +187 -0
  68. svc_infra/api/fastapi/middleware/optimistic_lock.py +39 -0
  69. svc_infra/api/fastapi/middleware/ratelimit.py +125 -28
  70. svc_infra/api/fastapi/middleware/ratelimit_store.py +45 -13
  71. svc_infra/api/fastapi/middleware/request_id.py +24 -10
  72. svc_infra/api/fastapi/middleware/request_size_limit.py +3 -3
  73. svc_infra/api/fastapi/middleware/timeout.py +176 -0
  74. svc_infra/api/fastapi/object_router.py +1060 -0
  75. svc_infra/api/fastapi/openapi/apply.py +4 -3
  76. svc_infra/api/fastapi/openapi/conventions.py +13 -6
  77. svc_infra/api/fastapi/openapi/mutators.py +144 -17
  78. svc_infra/api/fastapi/openapi/pipeline.py +2 -2
  79. svc_infra/api/fastapi/openapi/responses.py +4 -6
  80. svc_infra/api/fastapi/openapi/security.py +1 -1
  81. svc_infra/api/fastapi/ops/add.py +73 -0
  82. svc_infra/api/fastapi/pagination.py +47 -32
  83. svc_infra/api/fastapi/routers/__init__.py +16 -10
  84. svc_infra/api/fastapi/routers/ping.py +1 -0
  85. svc_infra/api/fastapi/setup.py +167 -54
  86. svc_infra/api/fastapi/tenancy/add.py +20 -0
  87. svc_infra/api/fastapi/tenancy/context.py +113 -0
  88. svc_infra/api/fastapi/versioned.py +102 -0
  89. svc_infra/app/README.md +5 -5
  90. svc_infra/app/__init__.py +3 -1
  91. svc_infra/app/env.py +70 -4
  92. svc_infra/app/logging/add.py +10 -2
  93. svc_infra/app/logging/filter.py +1 -1
  94. svc_infra/app/logging/formats.py +13 -5
  95. svc_infra/app/root.py +3 -3
  96. svc_infra/billing/__init__.py +40 -0
  97. svc_infra/billing/async_service.py +167 -0
  98. svc_infra/billing/jobs.py +231 -0
  99. svc_infra/billing/models.py +146 -0
  100. svc_infra/billing/quotas.py +101 -0
  101. svc_infra/billing/schemas.py +34 -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 +21 -5
  106. svc_infra/cache/add.py +167 -0
  107. svc_infra/cache/backend.py +9 -7
  108. svc_infra/cache/decorators.py +75 -20
  109. svc_infra/cache/demo.py +2 -2
  110. svc_infra/cache/keys.py +26 -6
  111. svc_infra/cache/recache.py +26 -27
  112. svc_infra/cache/resources.py +6 -5
  113. svc_infra/cache/tags.py +19 -44
  114. svc_infra/cache/ttl.py +2 -3
  115. svc_infra/cache/utils.py +4 -3
  116. svc_infra/cli/__init__.py +44 -8
  117. svc_infra/cli/__main__.py +4 -0
  118. svc_infra/cli/cmds/__init__.py +39 -2
  119. svc_infra/cli/cmds/db/nosql/mongo/mongo_cmds.py +18 -14
  120. svc_infra/cli/cmds/db/nosql/mongo/mongo_scaffold_cmds.py +9 -10
  121. svc_infra/cli/cmds/db/ops_cmds.py +267 -0
  122. svc_infra/cli/cmds/db/sql/alembic_cmds.py +97 -29
  123. svc_infra/cli/cmds/db/sql/sql_export_cmds.py +80 -0
  124. svc_infra/cli/cmds/db/sql/sql_scaffold_cmds.py +13 -13
  125. svc_infra/cli/cmds/docs/docs_cmds.py +139 -0
  126. svc_infra/cli/cmds/dx/__init__.py +12 -0
  127. svc_infra/cli/cmds/dx/dx_cmds.py +110 -0
  128. svc_infra/cli/cmds/health/__init__.py +179 -0
  129. svc_infra/cli/cmds/health/health_cmds.py +8 -0
  130. svc_infra/cli/cmds/help.py +4 -0
  131. svc_infra/cli/cmds/jobs/__init__.py +1 -0
  132. svc_infra/cli/cmds/jobs/jobs_cmds.py +42 -0
  133. svc_infra/cli/cmds/obs/obs_cmds.py +31 -13
  134. svc_infra/cli/cmds/sdk/__init__.py +0 -0
  135. svc_infra/cli/cmds/sdk/sdk_cmds.py +102 -0
  136. svc_infra/cli/foundation/runner.py +4 -5
  137. svc_infra/cli/foundation/typer_bootstrap.py +1 -2
  138. svc_infra/data/__init__.py +83 -0
  139. svc_infra/data/add.py +61 -0
  140. svc_infra/data/backup.py +56 -0
  141. svc_infra/data/erasure.py +46 -0
  142. svc_infra/data/fixtures.py +42 -0
  143. svc_infra/data/retention.py +56 -0
  144. svc_infra/db/__init__.py +15 -0
  145. svc_infra/db/crud_schema.py +14 -13
  146. svc_infra/db/inbox.py +67 -0
  147. svc_infra/db/nosql/__init__.py +2 -0
  148. svc_infra/db/nosql/constants.py +1 -1
  149. svc_infra/db/nosql/core.py +19 -5
  150. svc_infra/db/nosql/indexes.py +12 -9
  151. svc_infra/db/nosql/management.py +4 -4
  152. svc_infra/db/nosql/mongo/README.md +13 -13
  153. svc_infra/db/nosql/mongo/client.py +21 -4
  154. svc_infra/db/nosql/mongo/settings.py +1 -1
  155. svc_infra/db/nosql/repository.py +46 -27
  156. svc_infra/db/nosql/resource.py +28 -16
  157. svc_infra/db/nosql/scaffold.py +14 -12
  158. svc_infra/db/nosql/service.py +2 -1
  159. svc_infra/db/nosql/service_with_hooks.py +4 -3
  160. svc_infra/db/nosql/utils.py +4 -4
  161. svc_infra/db/ops.py +380 -0
  162. svc_infra/db/outbox.py +105 -0
  163. svc_infra/db/sql/apikey.py +34 -15
  164. svc_infra/db/sql/authref.py +8 -6
  165. svc_infra/db/sql/constants.py +5 -1
  166. svc_infra/db/sql/core.py +13 -13
  167. svc_infra/db/sql/management.py +5 -6
  168. svc_infra/db/sql/repository.py +92 -26
  169. svc_infra/db/sql/resource.py +18 -12
  170. svc_infra/db/sql/scaffold.py +11 -11
  171. svc_infra/db/sql/service.py +2 -1
  172. svc_infra/db/sql/service_with_hooks.py +4 -3
  173. svc_infra/db/sql/templates/models_schemas/auth/models.py.tmpl +7 -56
  174. svc_infra/db/sql/templates/setup/env_async.py.tmpl +34 -12
  175. svc_infra/db/sql/templates/setup/env_sync.py.tmpl +29 -7
  176. svc_infra/db/sql/tenant.py +80 -0
  177. svc_infra/db/sql/uniq.py +8 -7
  178. svc_infra/db/sql/uniq_hooks.py +12 -11
  179. svc_infra/db/sql/utils.py +105 -47
  180. svc_infra/db/sql/versioning.py +14 -0
  181. svc_infra/db/utils.py +3 -3
  182. svc_infra/deploy/__init__.py +531 -0
  183. svc_infra/documents/__init__.py +100 -0
  184. svc_infra/documents/add.py +263 -0
  185. svc_infra/documents/ease.py +233 -0
  186. svc_infra/documents/models.py +114 -0
  187. svc_infra/documents/storage.py +262 -0
  188. svc_infra/dx/__init__.py +58 -0
  189. svc_infra/dx/add.py +63 -0
  190. svc_infra/dx/changelog.py +74 -0
  191. svc_infra/dx/checks.py +68 -0
  192. svc_infra/exceptions.py +141 -0
  193. svc_infra/health/__init__.py +863 -0
  194. svc_infra/http/__init__.py +13 -0
  195. svc_infra/http/client.py +101 -0
  196. svc_infra/jobs/__init__.py +79 -0
  197. svc_infra/jobs/builtins/outbox_processor.py +38 -0
  198. svc_infra/jobs/builtins/webhook_delivery.py +93 -0
  199. svc_infra/jobs/easy.py +33 -0
  200. svc_infra/jobs/loader.py +49 -0
  201. svc_infra/jobs/queue.py +106 -0
  202. svc_infra/jobs/redis_queue.py +242 -0
  203. svc_infra/jobs/runner.py +75 -0
  204. svc_infra/jobs/scheduler.py +53 -0
  205. svc_infra/jobs/worker.py +40 -0
  206. svc_infra/loaders/__init__.py +186 -0
  207. svc_infra/loaders/base.py +143 -0
  208. svc_infra/loaders/github.py +309 -0
  209. svc_infra/loaders/models.py +147 -0
  210. svc_infra/loaders/url.py +229 -0
  211. svc_infra/logging/__init__.py +375 -0
  212. svc_infra/mcp/__init__.py +82 -0
  213. svc_infra/mcp/svc_infra_mcp.py +91 -33
  214. svc_infra/obs/README.md +2 -0
  215. svc_infra/obs/add.py +68 -11
  216. svc_infra/obs/cloud_dash.py +2 -1
  217. svc_infra/obs/grafana/dashboards/http-overview.json +45 -0
  218. svc_infra/obs/metrics/__init__.py +6 -7
  219. svc_infra/obs/metrics/asgi.py +8 -7
  220. svc_infra/obs/metrics/base.py +13 -13
  221. svc_infra/obs/metrics/http.py +3 -3
  222. svc_infra/obs/metrics/sqlalchemy.py +14 -13
  223. svc_infra/obs/metrics.py +9 -8
  224. svc_infra/resilience/__init__.py +44 -0
  225. svc_infra/resilience/circuit_breaker.py +328 -0
  226. svc_infra/resilience/retry.py +289 -0
  227. svc_infra/security/__init__.py +167 -0
  228. svc_infra/security/add.py +213 -0
  229. svc_infra/security/audit.py +97 -18
  230. svc_infra/security/audit_service.py +10 -9
  231. svc_infra/security/headers.py +15 -2
  232. svc_infra/security/hibp.py +14 -7
  233. svc_infra/security/jwt_rotation.py +78 -29
  234. svc_infra/security/lockout.py +23 -16
  235. svc_infra/security/models.py +77 -44
  236. svc_infra/security/oauth_models.py +73 -0
  237. svc_infra/security/org_invites.py +12 -12
  238. svc_infra/security/passwords.py +3 -3
  239. svc_infra/security/permissions.py +31 -7
  240. svc_infra/security/session.py +7 -8
  241. svc_infra/security/signed_cookies.py +26 -6
  242. svc_infra/storage/__init__.py +93 -0
  243. svc_infra/storage/add.py +250 -0
  244. svc_infra/storage/backends/__init__.py +11 -0
  245. svc_infra/storage/backends/local.py +331 -0
  246. svc_infra/storage/backends/memory.py +213 -0
  247. svc_infra/storage/backends/s3.py +334 -0
  248. svc_infra/storage/base.py +239 -0
  249. svc_infra/storage/easy.py +181 -0
  250. svc_infra/storage/settings.py +193 -0
  251. svc_infra/testing/__init__.py +682 -0
  252. svc_infra/utils.py +170 -5
  253. svc_infra/webhooks/__init__.py +69 -0
  254. svc_infra/webhooks/add.py +327 -0
  255. svc_infra/webhooks/encryption.py +115 -0
  256. svc_infra/webhooks/fastapi.py +37 -0
  257. svc_infra/webhooks/router.py +55 -0
  258. svc_infra/webhooks/service.py +69 -0
  259. svc_infra/webhooks/signing.py +34 -0
  260. svc_infra/websocket/__init__.py +79 -0
  261. svc_infra/websocket/add.py +139 -0
  262. svc_infra/websocket/client.py +283 -0
  263. svc_infra/websocket/config.py +57 -0
  264. svc_infra/websocket/easy.py +76 -0
  265. svc_infra/websocket/exceptions.py +61 -0
  266. svc_infra/websocket/manager.py +343 -0
  267. svc_infra/websocket/models.py +49 -0
  268. svc_infra-1.1.0.dist-info/LICENSE +21 -0
  269. svc_infra-1.1.0.dist-info/METADATA +362 -0
  270. svc_infra-1.1.0.dist-info/RECORD +364 -0
  271. svc_infra-0.1.595.dist-info/METADATA +0 -80
  272. svc_infra-0.1.595.dist-info/RECORD +0 -253
  273. {svc_infra-0.1.595.dist-info → svc_infra-1.1.0.dist-info}/WHEEL +0 -0
  274. {svc_infra-0.1.595.dist-info → svc_infra-1.1.0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,167 @@
1
+ """Async Billing Service - Primary billing API.
2
+
3
+ This is the recommended billing service for all new code. It provides
4
+ full async/await support for usage tracking, aggregation, and invoicing.
5
+
6
+ Usage:
7
+ from svc_infra.billing import AsyncBillingService
8
+
9
+ async with async_session_maker() as session:
10
+ service = AsyncBillingService(session, tenant_id="tenant_123")
11
+ await service.record_usage(
12
+ metric="api_calls",
13
+ amount=1,
14
+ at=datetime.now(timezone.utc),
15
+ idempotency_key="unique-key",
16
+ metadata={"endpoint": "/api/v1/users"},
17
+ )
18
+
19
+ See also:
20
+ - models: Invoice, UsageEvent, UsageAggregate, etc.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import uuid
26
+ from collections.abc import Sequence
27
+ from datetime import UTC, datetime, timedelta
28
+
29
+ from sqlalchemy import select
30
+ from sqlalchemy.ext.asyncio import AsyncSession
31
+
32
+ from .models import Invoice, InvoiceLine, UsageAggregate, UsageEvent
33
+
34
+
35
+ class AsyncBillingService:
36
+ def __init__(self, session: AsyncSession, tenant_id: str):
37
+ self.session = session
38
+ self.tenant_id = tenant_id
39
+
40
+ async def record_usage(
41
+ self,
42
+ *,
43
+ metric: str,
44
+ amount: int,
45
+ at: datetime,
46
+ idempotency_key: str,
47
+ metadata: dict | None,
48
+ ) -> str:
49
+ if at.tzinfo is None:
50
+ at = at.replace(tzinfo=UTC)
51
+ evt = UsageEvent(
52
+ id=str(uuid.uuid4()),
53
+ tenant_id=self.tenant_id,
54
+ metric=metric,
55
+ amount=amount,
56
+ at_ts=at,
57
+ idempotency_key=idempotency_key,
58
+ metadata_json=metadata or {},
59
+ )
60
+ self.session.add(evt)
61
+ await self.session.flush()
62
+ return evt.id
63
+
64
+ async def aggregate_daily(self, *, metric: str, day_start: datetime) -> int:
65
+ day_start = day_start.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=UTC)
66
+ next_day = day_start + timedelta(days=1)
67
+ total = 0
68
+ rows: Sequence[UsageEvent] = (
69
+ (
70
+ await self.session.execute(
71
+ select(UsageEvent).where(
72
+ UsageEvent.tenant_id == self.tenant_id,
73
+ UsageEvent.metric == metric,
74
+ UsageEvent.at_ts >= day_start,
75
+ UsageEvent.at_ts < next_day,
76
+ )
77
+ )
78
+ )
79
+ .scalars()
80
+ .all()
81
+ )
82
+ for r in rows:
83
+ total += int(r.amount)
84
+
85
+ agg = (
86
+ await self.session.execute(
87
+ select(UsageAggregate).where(
88
+ UsageAggregate.tenant_id == self.tenant_id,
89
+ UsageAggregate.metric == metric,
90
+ UsageAggregate.period_start == day_start,
91
+ UsageAggregate.granularity == "day",
92
+ )
93
+ )
94
+ ).scalar_one_or_none()
95
+ if agg:
96
+ agg.total = total
97
+ else:
98
+ self.session.add(
99
+ UsageAggregate(
100
+ id=str(uuid.uuid4()),
101
+ tenant_id=self.tenant_id,
102
+ metric=metric,
103
+ period_start=day_start,
104
+ granularity="day",
105
+ total=total,
106
+ )
107
+ )
108
+ return total
109
+
110
+ async def list_daily_aggregates(
111
+ self, *, metric: str, date_from: datetime | None, date_to: datetime | None
112
+ ) -> list[UsageAggregate]:
113
+ q = select(UsageAggregate).where(
114
+ UsageAggregate.tenant_id == self.tenant_id,
115
+ UsageAggregate.metric == metric,
116
+ UsageAggregate.granularity == "day",
117
+ )
118
+ if date_from is not None:
119
+ q = q.where(UsageAggregate.period_start >= date_from)
120
+ if date_to is not None:
121
+ q = q.where(UsageAggregate.period_start < date_to)
122
+ rows = list((await self.session.execute(q)).scalars().all())
123
+ return rows
124
+
125
+ async def generate_monthly_invoice(
126
+ self, *, period_start: datetime, period_end: datetime, currency: str
127
+ ) -> str:
128
+ total = 0
129
+ aggs: Sequence[UsageAggregate] = (
130
+ (
131
+ await self.session.execute(
132
+ select(UsageAggregate).where(
133
+ UsageAggregate.tenant_id == self.tenant_id,
134
+ UsageAggregate.period_start >= period_start,
135
+ UsageAggregate.period_start < period_end,
136
+ UsageAggregate.granularity == "day",
137
+ )
138
+ )
139
+ )
140
+ .scalars()
141
+ .all()
142
+ )
143
+ for r in aggs:
144
+ total += int(r.total)
145
+
146
+ inv = Invoice(
147
+ id=str(uuid.uuid4()),
148
+ tenant_id=self.tenant_id,
149
+ period_start=period_start,
150
+ period_end=period_end,
151
+ status="created",
152
+ total_amount=total,
153
+ currency=currency,
154
+ )
155
+ self.session.add(inv)
156
+ await self.session.flush()
157
+
158
+ line = InvoiceLine(
159
+ id=str(uuid.uuid4()),
160
+ invoice_id=inv.id,
161
+ price_id=None,
162
+ metric=None,
163
+ quantity=1,
164
+ amount=total,
165
+ )
166
+ self.session.add(line)
167
+ return inv.id
@@ -0,0 +1,231 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import Awaitable, Callable
5
+ from datetime import UTC, datetime
6
+ from typing import Any
7
+
8
+ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
9
+
10
+ from svc_infra.jobs.queue import Job, JobQueue
11
+ from svc_infra.jobs.scheduler import InMemoryScheduler
12
+ from svc_infra.webhooks.service import WebhookService
13
+
14
+ from .async_service import AsyncBillingService
15
+
16
+
17
+ async def job_aggregate_daily(
18
+ session: AsyncSession, *, tenant_id: str, metric: str, day_start: datetime
19
+ ) -> None:
20
+ """
21
+ Aggregate usage for a tenant/metric for the given day_start (UTC).
22
+
23
+ Intended to be called from a scheduler/worker with an AsyncSession created by the host app.
24
+ """
25
+ svc = AsyncBillingService(session=session, tenant_id=tenant_id)
26
+ if day_start.tzinfo is None:
27
+ day_start = day_start.replace(tzinfo=UTC)
28
+ await svc.aggregate_daily(metric=metric, day_start=day_start)
29
+
30
+
31
+ async def job_generate_monthly_invoice(
32
+ session: AsyncSession,
33
+ *,
34
+ tenant_id: str,
35
+ period_start: datetime,
36
+ period_end: datetime,
37
+ currency: str,
38
+ ) -> str:
39
+ """
40
+ Generate a monthly invoice for a tenant between [period_start, period_end).
41
+ Returns the internal invoice id.
42
+ """
43
+ svc = AsyncBillingService(session=session, tenant_id=tenant_id)
44
+ if period_start.tzinfo is None:
45
+ period_start = period_start.replace(tzinfo=UTC)
46
+ if period_end.tzinfo is None:
47
+ period_end = period_end.replace(tzinfo=UTC)
48
+ return await svc.generate_monthly_invoice(
49
+ period_start=period_start, period_end=period_end, currency=currency
50
+ )
51
+
52
+
53
+ # -------- Job helpers and handlers (scheduler/worker wiring) ---------
54
+
55
+ BILLING_AGGREGATE_JOB = "billing.aggregate_daily"
56
+ BILLING_INVOICE_JOB = "billing.generate_monthly_invoice"
57
+
58
+
59
+ def enqueue_aggregate_daily(
60
+ queue: JobQueue,
61
+ *,
62
+ tenant_id: str,
63
+ metric: str,
64
+ day_start: datetime,
65
+ delay_seconds: int = 0,
66
+ ) -> None:
67
+ payload = {
68
+ "tenant_id": tenant_id,
69
+ "metric": metric,
70
+ "day_start": day_start.astimezone(UTC).isoformat(),
71
+ }
72
+ queue.enqueue(BILLING_AGGREGATE_JOB, payload, delay_seconds=delay_seconds)
73
+
74
+
75
+ def enqueue_generate_monthly_invoice(
76
+ queue: JobQueue,
77
+ *,
78
+ tenant_id: str,
79
+ period_start: datetime,
80
+ period_end: datetime,
81
+ currency: str,
82
+ delay_seconds: int = 0,
83
+ ) -> None:
84
+ payload = {
85
+ "tenant_id": tenant_id,
86
+ "period_start": period_start.astimezone(UTC).isoformat(),
87
+ "period_end": period_end.astimezone(UTC).isoformat(),
88
+ "currency": currency,
89
+ }
90
+ queue.enqueue(BILLING_INVOICE_JOB, payload, delay_seconds=delay_seconds)
91
+
92
+
93
+ def make_daily_aggregate_tick(
94
+ queue: JobQueue,
95
+ *,
96
+ tenant_id: str,
97
+ metric: str,
98
+ when: datetime | None = None,
99
+ ):
100
+ """Return an async function that enqueues a daily aggregate job.
101
+
102
+ This is a simple helper for local/dev schedulers; it schedules an aggregate
103
+ for the UTC day of ``when`` (or now). Call repeatedly via a scheduler.
104
+ """
105
+
106
+ async def _tick():
107
+ ts = (when or datetime.now(UTC)).astimezone(UTC)
108
+ day_start = ts.replace(hour=0, minute=0, second=0, microsecond=0)
109
+ enqueue_aggregate_daily(queue, tenant_id=tenant_id, metric=metric, day_start=day_start)
110
+
111
+ return _tick
112
+
113
+
114
+ def make_billing_job_handler(
115
+ *,
116
+ session_factory: async_sessionmaker[AsyncSession],
117
+ webhooks: WebhookService,
118
+ ) -> Callable[[Job], Awaitable[None]]:
119
+ """Create a worker handler that processes billing jobs and emits webhooks.
120
+
121
+ Supported jobs and their expected payloads:
122
+ - billing.aggregate_daily {tenant_id, metric, day_start: ISO8601}
123
+ → emits topic 'billing.usage_aggregated'
124
+ - billing.generate_monthly_invoice {tenant_id, period_start: ISO8601, period_end: ISO8601, currency}
125
+ → emits topic 'billing.invoice.created'
126
+ """
127
+
128
+ async def _maybe_commit(session: Any) -> None:
129
+ """Commit if the session exposes a commit method (await if coroutine).
130
+
131
+ This makes the handler resilient in tests/dev where a dummy session is used.
132
+ """
133
+ commit = getattr(session, "commit", None)
134
+ if callable(commit):
135
+ result = commit()
136
+ if inspect.isawaitable(result):
137
+ await result
138
+
139
+ async def _handler(job: Job) -> None:
140
+ name = job.name
141
+ data: dict[str, Any] = job.payload or {}
142
+ if name == BILLING_AGGREGATE_JOB:
143
+ tenant_id = str(data.get("tenant_id"))
144
+ metric = str(data.get("metric"))
145
+ day_raw = data.get("day_start")
146
+ if not tenant_id or not metric or not day_raw:
147
+ return
148
+ day_start = datetime.fromisoformat(str(day_raw))
149
+ async with session_factory() as session:
150
+ svc = AsyncBillingService(session=session, tenant_id=tenant_id)
151
+ total = await svc.aggregate_daily(metric=metric, day_start=day_start)
152
+ await _maybe_commit(session)
153
+ webhooks.publish(
154
+ "billing.usage_aggregated",
155
+ {
156
+ "tenant_id": tenant_id,
157
+ "metric": metric,
158
+ "day_start": day_start.astimezone(UTC).isoformat(),
159
+ "total": int(total),
160
+ },
161
+ )
162
+ return
163
+ if name == BILLING_INVOICE_JOB:
164
+ tenant_id = str(data.get("tenant_id"))
165
+ period_start_raw = data.get("period_start")
166
+ period_end_raw = data.get("period_end")
167
+ currency = str(data.get("currency"))
168
+ if not tenant_id or not period_start_raw or not period_end_raw or not currency:
169
+ return
170
+ period_start = datetime.fromisoformat(str(period_start_raw))
171
+ period_end = datetime.fromisoformat(str(period_end_raw))
172
+ async with session_factory() as session:
173
+ svc = AsyncBillingService(session=session, tenant_id=tenant_id)
174
+ invoice_id = await svc.generate_monthly_invoice(
175
+ period_start=period_start, period_end=period_end, currency=currency
176
+ )
177
+ await _maybe_commit(session)
178
+ webhooks.publish(
179
+ "billing.invoice.created",
180
+ {
181
+ "tenant_id": tenant_id,
182
+ "invoice_id": invoice_id,
183
+ "period_start": period_start.astimezone(UTC).isoformat(),
184
+ "period_end": period_end.astimezone(UTC).isoformat(),
185
+ "currency": currency,
186
+ },
187
+ )
188
+ return
189
+ # Ignore unrelated jobs
190
+
191
+ return _handler
192
+
193
+
194
+ def add_billing_jobs(
195
+ *,
196
+ scheduler: InMemoryScheduler,
197
+ queue: JobQueue,
198
+ jobs: list[dict],
199
+ ) -> None:
200
+ """Register simple interval-based billing job enqueuers.
201
+
202
+ jobs: list of dicts with shape {"name": "aggregate", "tenant_id": ..., "metric": ..., "interval_seconds": 86400}
203
+ or {"name": "invoice", "tenant_id": ..., "period_start": ISO, "period_end": ISO, "currency": ..., "interval_seconds": 2592000}
204
+ """
205
+
206
+ for j in jobs:
207
+ name = j.get("name")
208
+ interval = int(j.get("interval_seconds", 86400))
209
+ if name == "aggregate":
210
+ tenant_id = j["tenant_id"]
211
+ metric = j["metric"]
212
+
213
+ async def _tick_fn(tid=tenant_id, m=metric):
214
+ # Enqueue for the current UTC day
215
+ now = datetime.now(UTC)
216
+ day_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
217
+ enqueue_aggregate_daily(queue, tenant_id=tid, metric=m, day_start=day_start)
218
+
219
+ scheduler.add_task(f"billing.aggregate.{tenant_id}.{metric}", interval, _tick_fn)
220
+ elif name == "invoice":
221
+ tenant_id = j["tenant_id"]
222
+ currency = j["currency"]
223
+ pstart = datetime.fromisoformat(j["period_start"]).astimezone(UTC)
224
+ pend = datetime.fromisoformat(j["period_end"]).astimezone(UTC)
225
+
226
+ async def _tick_inv(tid=tenant_id, cs=currency, ps=pstart, pe=pend):
227
+ enqueue_generate_monthly_invoice(
228
+ queue, tenant_id=tid, period_start=ps, period_end=pe, currency=cs
229
+ )
230
+
231
+ scheduler.add_task(f"billing.invoice.{tenant_id}", interval, _tick_inv)
@@ -0,0 +1,146 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+
5
+ from sqlalchemy import JSON, DateTime, Index, Numeric, String, UniqueConstraint, text
6
+ from sqlalchemy.orm import Mapped, mapped_column
7
+
8
+ from svc_infra.db.sql.base import ModelBase
9
+
10
+ TENANT_ID_LEN = 64
11
+
12
+
13
+ class UsageEvent(ModelBase):
14
+ __tablename__ = "billing_usage_events"
15
+
16
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
17
+ tenant_id: Mapped[str] = mapped_column(String(TENANT_ID_LEN), index=True, nullable=False)
18
+ metric: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
19
+ amount: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False)
20
+ at_ts: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
21
+ idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
22
+ metadata_json: Mapped[dict] = mapped_column(JSON, default=dict)
23
+ created_at: Mapped[datetime] = mapped_column(
24
+ DateTime(timezone=True),
25
+ server_default=text("CURRENT_TIMESTAMP"),
26
+ nullable=False,
27
+ )
28
+
29
+ __table_args__ = (
30
+ UniqueConstraint("tenant_id", "metric", "idempotency_key", name="uq_usage_idem"),
31
+ Index("ix_usage_tenant_metric_ts", "tenant_id", "metric", "at_ts"),
32
+ )
33
+
34
+
35
+ class UsageAggregate(ModelBase):
36
+ __tablename__ = "billing_usage_aggregates"
37
+
38
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
39
+ tenant_id: Mapped[str] = mapped_column(String(TENANT_ID_LEN), index=True, nullable=False)
40
+ metric: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
41
+ period_start: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
42
+ granularity: Mapped[str] = mapped_column(String(8), nullable=False) # hour|day|month
43
+ total: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False)
44
+ updated_at: Mapped[datetime] = mapped_column(
45
+ DateTime(timezone=True),
46
+ server_default=text("CURRENT_TIMESTAMP"),
47
+ nullable=False,
48
+ )
49
+
50
+ __table_args__ = (
51
+ UniqueConstraint("tenant_id", "metric", "period_start", "granularity", name="uq_usage_agg"),
52
+ )
53
+
54
+
55
+ class Plan(ModelBase):
56
+ __tablename__ = "billing_plans"
57
+
58
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
59
+ key: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
60
+ name: Mapped[str] = mapped_column(String(128), nullable=False)
61
+ description: Mapped[str | None] = mapped_column(String(255))
62
+ created_at: Mapped[datetime] = mapped_column(
63
+ DateTime(timezone=True),
64
+ server_default=text("CURRENT_TIMESTAMP"),
65
+ nullable=False,
66
+ )
67
+
68
+
69
+ class PlanEntitlement(ModelBase):
70
+ __tablename__ = "billing_plan_entitlements"
71
+
72
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
73
+ plan_id: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
74
+ key: Mapped[str] = mapped_column(String(64), nullable=False)
75
+ limit_per_window: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False)
76
+ window: Mapped[str] = mapped_column(String(8), nullable=False) # day|month
77
+ created_at: Mapped[datetime] = mapped_column(
78
+ DateTime(timezone=True),
79
+ server_default=text("CURRENT_TIMESTAMP"),
80
+ nullable=False,
81
+ )
82
+
83
+
84
+ class Subscription(ModelBase):
85
+ __tablename__ = "billing_subscriptions"
86
+
87
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
88
+ tenant_id: Mapped[str] = mapped_column(String(TENANT_ID_LEN), index=True, nullable=False)
89
+ plan_id: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
90
+ effective_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
91
+ ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
92
+ created_at: Mapped[datetime] = mapped_column(
93
+ DateTime(timezone=True),
94
+ server_default=text("CURRENT_TIMESTAMP"),
95
+ nullable=False,
96
+ )
97
+
98
+
99
+ class Price(ModelBase):
100
+ __tablename__ = "billing_prices"
101
+
102
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
103
+ key: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
104
+ currency: Mapped[str] = mapped_column(String(8), nullable=False)
105
+ unit_amount: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False) # minor units
106
+ metric: Mapped[str | None] = mapped_column(String(64)) # null for fixed recurring
107
+ recurring_interval: Mapped[str | None] = mapped_column(String(8)) # month|year
108
+ created_at: Mapped[datetime] = mapped_column(
109
+ DateTime(timezone=True),
110
+ server_default=text("CURRENT_TIMESTAMP"),
111
+ nullable=False,
112
+ )
113
+
114
+
115
+ class Invoice(ModelBase):
116
+ __tablename__ = "billing_invoices"
117
+
118
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
119
+ tenant_id: Mapped[str] = mapped_column(String(TENANT_ID_LEN), index=True, nullable=False)
120
+ period_start: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
121
+ period_end: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
122
+ status: Mapped[str] = mapped_column(String(16), index=True, nullable=False)
123
+ total_amount: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False)
124
+ currency: Mapped[str] = mapped_column(String(8), nullable=False)
125
+ provider_invoice_id: Mapped[str | None] = mapped_column(String(128), index=True)
126
+ created_at: Mapped[datetime] = mapped_column(
127
+ DateTime(timezone=True),
128
+ server_default=text("CURRENT_TIMESTAMP"),
129
+ nullable=False,
130
+ )
131
+
132
+
133
+ class InvoiceLine(ModelBase):
134
+ __tablename__ = "billing_invoice_lines"
135
+
136
+ id: Mapped[str] = mapped_column(String(64), primary_key=True)
137
+ invoice_id: Mapped[str] = mapped_column(String(64), index=True, nullable=False)
138
+ price_id: Mapped[str | None] = mapped_column(String(64), index=True)
139
+ metric: Mapped[str | None] = mapped_column(String(64))
140
+ quantity: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False)
141
+ amount: Mapped[int] = mapped_column(Numeric(18, 0), nullable=False)
142
+ created_at: Mapped[datetime] = mapped_column(
143
+ DateTime(timezone=True),
144
+ server_default=text("CURRENT_TIMESTAMP"),
145
+ nullable=False,
146
+ )
@@ -0,0 +1,101 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import UTC, datetime
4
+ from typing import Annotated
5
+
6
+ from fastapi import Depends, HTTPException, status
7
+ from sqlalchemy import select
8
+ from sqlalchemy.ext.asyncio import AsyncSession
9
+
10
+ from svc_infra.api.fastapi.db.sql.session import SqlSessionDep
11
+ from svc_infra.api.fastapi.tenancy.context import TenantId
12
+
13
+ from .models import PlanEntitlement, Subscription, UsageAggregate
14
+
15
+
16
+ async def _current_subscription(session: AsyncSession, tenant_id: str) -> Subscription | None:
17
+ now = datetime.now(tz=UTC)
18
+ row = (
19
+ (
20
+ await session.execute(
21
+ select(Subscription)
22
+ .where(Subscription.tenant_id == tenant_id)
23
+ .order_by(Subscription.effective_at.desc())
24
+ )
25
+ )
26
+ .scalars()
27
+ .first()
28
+ )
29
+ if row is None:
30
+ return None
31
+ # basic check: if ended_at is set and in the past, treat as inactive
32
+ if row.ended_at is not None and row.ended_at <= now:
33
+ return None
34
+ return row
35
+
36
+
37
+ def require_quota(metric: str, *, window: str = "day", soft: bool = True):
38
+ async def _dep(tenant_id: TenantId, session: SqlSessionDep) -> None:
39
+ sub = await _current_subscription(session, tenant_id)
40
+ if sub is None:
41
+ # no subscription → allow (unlimited) by default
42
+ return
43
+ ent = (
44
+ (
45
+ await session.execute(
46
+ select(PlanEntitlement).where(
47
+ PlanEntitlement.plan_id == sub.plan_id,
48
+ PlanEntitlement.key == metric,
49
+ PlanEntitlement.window == window,
50
+ )
51
+ )
52
+ )
53
+ .scalars()
54
+ .first()
55
+ )
56
+ if ent is None:
57
+ # no entitlement → unlimited
58
+ return
59
+ # compute current window start
60
+ now = datetime.now(tz=UTC)
61
+ if window == "day":
62
+ period_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
63
+ granularity = "day"
64
+ elif window == "month":
65
+ period_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
66
+ granularity = "month" # we only aggregate per day, but future-proof
67
+ else:
68
+ period_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
69
+ granularity = "day"
70
+
71
+ used_row = (
72
+ (
73
+ await session.execute(
74
+ select(UsageAggregate).where(
75
+ UsageAggregate.tenant_id == tenant_id,
76
+ UsageAggregate.metric == metric,
77
+ UsageAggregate.granularity == granularity, # v1 daily baseline
78
+ UsageAggregate.period_start == period_start,
79
+ )
80
+ )
81
+ )
82
+ .scalars()
83
+ .first()
84
+ )
85
+ used = int(used_row.total) if used_row else 0
86
+ limit_ = int(ent.limit_per_window)
87
+ if used >= limit_:
88
+ if soft:
89
+ # allow but signal overage via header later (TODO: add header hook)
90
+ return
91
+ raise HTTPException(
92
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
93
+ detail=f"Quota exceeded for {metric} in {window} window",
94
+ )
95
+
96
+ return _dep
97
+
98
+
99
+ QuotaDep = Annotated[None, Depends(require_quota)]
100
+
101
+ __all__ = ["require_quota"]
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import datetime
4
+ from typing import Annotated
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+
9
+ class UsageIn(BaseModel):
10
+ metric: str = Field(..., min_length=1, max_length=64)
11
+ amount: Annotated[int, Field(ge=0, description="Non-negative amount for the metric")]
12
+ at: datetime | None = Field(
13
+ default=None,
14
+ description="Event timestamp (UTC). Defaults to server time if omitted.",
15
+ )
16
+ idempotency_key: str = Field(..., min_length=1, max_length=128)
17
+ metadata: dict = Field(default_factory=dict)
18
+
19
+
20
+ class UsageAckOut(BaseModel):
21
+ id: str
22
+ accepted: bool = True
23
+
24
+
25
+ class UsageAggregateRow(BaseModel):
26
+ period_start: datetime
27
+ granularity: str
28
+ metric: str
29
+ total: int
30
+
31
+
32
+ class UsageAggregatesOut(BaseModel):
33
+ items: list[UsageAggregateRow] = Field(default_factory=list)
34
+ next_cursor: str | None = None
@@ -0,0 +1,5 @@
1
+ # Bundled Docs
2
+
3
+ This directory contains a minimal set of Markdown files that the `svc-infra docs` CLI can fall back to when the project running the CLI doesn't have a local `docs/` directory.
4
+
5
+ You can add more topics here as needed; each `*.md` file becomes a topic named after its stem (e.g., `getting-started.md` -> `getting-started`).
@@ -0,0 +1 @@
1
+ # Bundled docs package for zip-safe importlib.resources access
@@ -0,0 +1,6 @@
1
+ # Getting Started
2
+
3
+ Welcome to svc-infra docs. Use `svc-infra docs list` to see topics.
4
+
5
+ - This content is bundled with the package.
6
+ - If your project doesn't have a local `docs/` folder, you'll still see this.