qodalis-cli-server-plugin-public-api 1.0.0b29__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ """Swagger UI for the public document, served from files vendored in this
2
+ package (``swagger_ui/``: ``swagger-ui-dist`` 5.35.1, Apache-2.0), so the page
3
+ where integrators paste tokens loads nothing from another origin."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import html
8
+ import json
9
+ import os
10
+ from typing import Any
11
+
12
+ SWAGGER_UI_VERSION = "5.35.1"
13
+ ASSETS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "swagger_ui")
14
+ #: The only files served under ``<base>/swagger/``.
15
+ ASSETS: dict[str, str] = {
16
+ "swagger-ui-bundle.js": "text/javascript; charset=utf-8",
17
+ "swagger-ui.css": "text/css; charset=utf-8",
18
+ "favicon-32x32.png": "image/png",
19
+ }
20
+ PARAMETERS: dict[str, Any] = {
21
+ "dom_id": "#swagger-ui",
22
+ "deepLinking": True,
23
+ "persistAuthorization": False,
24
+ "tryItOutEnabled": True,
25
+ }
26
+
27
+
28
+ def is_root_relative(url: Any) -> bool:
29
+ """A same-origin path: starts with one ``/``, nothing that can leave the
30
+ origin or an HTML attribute."""
31
+ return (
32
+ isinstance(url, str)
33
+ and url.startswith("/")
34
+ and not url.startswith("//")
35
+ and not any(c.isspace() or ord(c) < 0x20 or c in "\\\"'<>`" for c in url)
36
+ )
37
+
38
+
39
+ def _script_json(value: Any) -> str:
40
+ """JSON safe inside a ``<script>`` element."""
41
+ return (
42
+ json.dumps(value, indent=2)
43
+ .replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
44
+ )
45
+
46
+
47
+ def swagger_html(*, title: str, openapi_url: str, js_url: str, css_url: str, favicon_url: str) -> str:
48
+ """The page: every URL is HTML-escaped (attributes) or escaped JSON."""
49
+ config = {"url": openapi_url, **PARAMETERS}
50
+ return f"""<!DOCTYPE html>
51
+ <html>
52
+ <head>
53
+ <meta charset="utf-8">
54
+ <meta name="viewport" content="width=device-width, initial-scale=1">
55
+ <link type="text/css" rel="stylesheet" href="{html.escape(css_url, quote=True)}">
56
+ <link rel="icon" type="image/png" href="{html.escape(favicon_url, quote=True)}">
57
+ <title>{html.escape(title)}</title>
58
+ </head>
59
+ <body>
60
+ <div id="swagger-ui"></div>
61
+ <script src="{html.escape(js_url, quote=True)}"></script>
62
+ <script>
63
+ const ui = SwaggerUIBundle({_script_json(config)})
64
+ </script>
65
+ </body>
66
+ </html>
67
+ """
@@ -0,0 +1,137 @@
1
+ """Token and account usage of the public API: the token views' ``usage``
2
+ (users plugin hook) and ``public_api.usage.account(user_id)`` for a host's own
3
+ pages."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import inspect
8
+ from dataclasses import dataclass, field
9
+ from datetime import date, datetime, timedelta, timezone
10
+ from typing import Any, Callable
11
+
12
+ from qodalis_cli_users import QcliCaller, UsersApiError
13
+
14
+ from .quota import PublicApiQuota, QuotaResolver
15
+ from .usage_store import IPublicApiUsageStore
16
+
17
+ USAGE_DAYS = 30
18
+ USER_NOT_FOUND = "user not found"
19
+
20
+
21
+ def utc_now(clock: Callable[[], datetime]) -> datetime:
22
+ """The clock's time in UTC (a naive value is read as UTC)."""
23
+ now = clock()
24
+ if now.tzinfo is None:
25
+ return now.replace(tzinfo=timezone.utc)
26
+ return now.astimezone(timezone.utc)
27
+
28
+
29
+ def day_window(now: datetime) -> str:
30
+ return now.strftime("%Y-%m-%d")
31
+
32
+
33
+ def minute_window(now: datetime) -> str:
34
+ return now.strftime("%Y-%m-%dT%H:%M")
35
+
36
+
37
+ def dense_usage(days: dict[str, int], today: date) -> dict[str, Any]:
38
+ """``{"today", "last30Days", "days"}``: 30 days, oldest first, the last
39
+ one ``today``, zeros included."""
40
+ entries = []
41
+ for offset in range(USAGE_DAYS - 1, -1, -1):
42
+ key = (today - timedelta(days=offset)).isoformat()
43
+ entries.append({"date": key, "requests": int(days.get(key, 0))})
44
+ return {
45
+ "today": entries[-1]["requests"],
46
+ "last30Days": sum(e["requests"] for e in entries),
47
+ "days": entries,
48
+ }
49
+
50
+
51
+ @dataclass
52
+ class PublicApiTokenUsage:
53
+ token_id: str
54
+ name: str
55
+ #: ``{"today", "last30Days", "days"}`` as on the token views.
56
+ usage: dict[str, Any]
57
+
58
+ def to_dict(self) -> dict[str, Any]:
59
+ return {"tokenId": self.token_id, "name": self.name, "usage": self.usage}
60
+
61
+
62
+ @dataclass
63
+ class PublicApiAccountUsage:
64
+ #: The account's requests today (UTC), revoked tokens included.
65
+ today: int
66
+ quota: PublicApiQuota
67
+ #: The account's current tokens, oldest first.
68
+ tokens: list[PublicApiTokenUsage] = field(default_factory=list)
69
+
70
+ def to_dict(self) -> dict[str, Any]:
71
+ return {
72
+ "today": self.today,
73
+ "quota": self.quota.to_dict(),
74
+ "tokens": [t.to_dict() for t in self.tokens],
75
+ }
76
+
77
+
78
+ async def resolve_quota(resolver: QuotaResolver | None, caller: QcliCaller) -> PublicApiQuota:
79
+ """The resolver's quota for ``caller`` (unlimited without a resolver)."""
80
+ if resolver is None:
81
+ return PublicApiQuota()
82
+ quota = resolver(caller)
83
+ if inspect.isawaitable(quota):
84
+ quota = await quota
85
+ if quota is None:
86
+ return PublicApiQuota()
87
+ if not isinstance(quota, PublicApiQuota):
88
+ raise TypeError("the quota resolver must return a PublicApiQuota")
89
+ return quota
90
+
91
+
92
+ class PublicApiUsageService:
93
+ """``public_api.usage``: usage of tokens and accounts."""
94
+
95
+ def __init__(
96
+ self,
97
+ users: Any,
98
+ store: Callable[[], IPublicApiUsageStore],
99
+ resolver: Callable[[], QuotaResolver | None],
100
+ clock: Callable[[], datetime],
101
+ ) -> None:
102
+ self._users = users
103
+ self._store = store
104
+ self._resolver = resolver
105
+ self._clock = clock
106
+
107
+ async def tokens(self, token_ids: list[str]) -> dict[str, dict[str, Any]]:
108
+ """The token views' ``usage`` (the users plugin's usage provider)."""
109
+ today = utc_now(self._clock).date()
110
+ start = today - timedelta(days=USAGE_DAYS - 1)
111
+ days = await self._store().token_days(list(token_ids), start.isoformat(), today.isoformat())
112
+ return {token_id: dense_usage(days.get(token_id, {}), today) for token_id in token_ids}
113
+
114
+ async def account(self, user_id: str) -> PublicApiAccountUsage:
115
+ """The account's requests today, its quota (from the resolver, for a
116
+ caller without a token) and its tokens' usage. Raises
117
+ ``UsersApiError`` 404 ``user not found``."""
118
+ auth = self._users.auth_service
119
+ user = await auth.user_store.get_user(user_id) if isinstance(user_id, str) and user_id else None
120
+ if user is None or user.id != user_id:
121
+ raise UsersApiError(404, USER_NOT_FOUND)
122
+ permissions = await auth.user_permissions(user)
123
+ caller = QcliCaller(
124
+ user_id=user.id, user_name=user.name, token_id=None, audience=None,
125
+ permissions=tuple(permissions),
126
+ )
127
+ quota = await resolve_quota(self._resolver(), caller)
128
+ now = utc_now(self._clock)
129
+ today = await self._store().account_count(user.id, day_window(now))
130
+ records = await auth.api_token_store.get_tokens(user.id)
131
+ records.sort(key=lambda t: t.created_at)
132
+ usage = await self.tokens([r.id for r in records])
133
+ return PublicApiAccountUsage(
134
+ today=today,
135
+ quota=quota,
136
+ tokens=[PublicApiTokenUsage(r.id, r.name, usage[r.id]) for r in records],
137
+ )
@@ -0,0 +1,99 @@
1
+ """Request counters of the public API, per token and window.
2
+
3
+ A window is a UTC day (``yyyy-MM-dd``) or a UTC minute (``yyyy-MM-ddTHH:mm``).
4
+ Counters are kept per token for display (token usage) and summed per account
5
+ (``user_id``) for the limits, so revoked tokens keep counting. A persistent
6
+ store shared by several processes makes the limits hold across them; the
7
+ guard admits with increment, check, then compensate (``decrement``) when a
8
+ limit is exceeded.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ from abc import ABC, abstractmethod
15
+
16
+
17
+ def is_day(window: str) -> bool:
18
+ return len(window) == 10
19
+
20
+
21
+ class IPublicApiUsageStore(ABC):
22
+ """Where the public API's request counters live."""
23
+
24
+ @abstractmethod
25
+ async def increment(self, token_id: str, user_id: str, window: str) -> int:
26
+ """Add one request of ``token_id`` (owned by ``user_id``) to
27
+ ``window``; returns the token's count in it."""
28
+
29
+ @abstractmethod
30
+ async def decrement(self, token_id: str, window: str) -> None:
31
+ """Take back one request of ``token_id`` in ``window`` (a refused
32
+ request that was counted)."""
33
+
34
+ @abstractmethod
35
+ async def account_count(self, user_id: str, window: str) -> int:
36
+ """Requests of every token of ``user_id`` in ``window``."""
37
+
38
+ @abstractmethod
39
+ async def token_days(self, token_ids: list[str], from_day: str, to_day: str) -> dict[str, dict[str, int]]:
40
+ """``{token_id: {day: count}}`` for the day windows from ``from_day``
41
+ to ``to_day`` (inclusive); tokens and days without requests may be
42
+ left out."""
43
+
44
+ @abstractmethod
45
+ async def prune(self, before_day: str, before_minute: str) -> None:
46
+ """Drop day windows before ``before_day`` and minute windows before
47
+ ``before_minute``."""
48
+
49
+
50
+ class InMemoryPublicApiUsageStore(IPublicApiUsageStore):
51
+ """The default store: counters in this process only."""
52
+
53
+ def __init__(self) -> None:
54
+ #: ``(token_id, window) -> [user_id, count]``
55
+ self._counts: dict[tuple[str, str], list] = {}
56
+ #: ``(user_id, window) -> count``
57
+ self._accounts: dict[tuple[str, str], int] = {}
58
+ self._lock = asyncio.Lock()
59
+
60
+ async def increment(self, token_id: str, user_id: str, window: str) -> int:
61
+ async with self._lock:
62
+ row = self._counts.setdefault((token_id, window), [user_id, 0])
63
+ row[1] += 1
64
+ key = (row[0], window)
65
+ self._accounts[key] = self._accounts.get(key, 0) + 1
66
+ return row[1]
67
+
68
+ async def decrement(self, token_id: str, window: str) -> None:
69
+ async with self._lock:
70
+ row = self._counts.get((token_id, window))
71
+ if row is None or row[1] <= 0:
72
+ return
73
+ row[1] -= 1
74
+ key = (row[0], window)
75
+ self._accounts[key] = max(0, self._accounts.get(key, 0) - 1)
76
+
77
+ async def account_count(self, user_id: str, window: str) -> int:
78
+ async with self._lock:
79
+ return self._accounts.get((user_id, window), 0)
80
+
81
+ async def token_days(self, token_ids: list[str], from_day: str, to_day: str) -> dict[str, dict[str, int]]:
82
+ wanted = set(token_ids)
83
+ result: dict[str, dict[str, int]] = {}
84
+ async with self._lock:
85
+ for (token_id, window), (_, count) in self._counts.items():
86
+ if token_id in wanted and is_day(window) and from_day <= window <= to_day:
87
+ result.setdefault(token_id, {})[window] = count
88
+ return result
89
+
90
+ async def prune(self, before_day: str, before_minute: str) -> None:
91
+ async with self._lock:
92
+ for key in [k for k in self._counts if _expired(k[1], before_day, before_minute)]:
93
+ del self._counts[key]
94
+ for key in [k for k in self._accounts if _expired(k[1], before_day, before_minute)]:
95
+ del self._accounts[key]
96
+
97
+
98
+ def _expired(window: str, before_day: str, before_minute: str) -> bool:
99
+ return window < before_day if is_day(window) else window < before_minute
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.5
2
+ Name: qodalis-cli-server-plugin-public-api
3
+ Version: 1.0.0b29
4
+ Summary: Public API plugin for Qodalis CLI servers — routes guarded by host API tokens with per-account quotas, token usage, the public OpenAPI document and Swagger UI
5
+ Project-URL: Homepage, https://github.com/qodalis-solutions/cli-server-python
6
+ Project-URL: Repository, https://github.com/qodalis-solutions/cli-server-python
7
+ Project-URL: Issues, https://github.com/qodalis-solutions/cli-server-python/issues
8
+ Author-email: Nicolae Lupei <nicolae.lupei@qodalis.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: cli,openapi,plugin,public-api,qodalis,quota
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: fastapi>=0.100.0
22
+ Requires-Dist: qodalis-cli-server-abstractions>=1.0.0b17
23
+ Requires-Dist: qodalis-cli-server-plugin-users>=1.0.0b29
@@ -0,0 +1,18 @@
1
+ qodalis_cli_public_api/__init__.py,sha256=QcTaQrK6P-AwGlWAQ-cGrWtNt03p8-3JtEWnNPWYFeU,985
2
+ qodalis_cli_public_api/cli_public_api_builder.py,sha256=uC8Z3j7M5pqqWnOSDIb8BOWn2kLviaRLcxDjOVV2rHc,23278
3
+ qodalis_cli_public_api/headers_middleware.py,sha256=4b4lwAVZGsecgUqNDYfn9qsm7bUYvf7f08BhGFLv7_8,1607
4
+ qodalis_cli_public_api/openapi.py,sha256=TbhWLoecE6DJfWTDPdqijEo7iPbKWHIek7lB4Fx-0LY,6137
5
+ qodalis_cli_public_api/quota.py,sha256=x3XEi8ggjsKm57cQAYa-NkjG78jkW0KEPJ2t5Ac_pzU,966
6
+ qodalis_cli_public_api/swagger_ui.py,sha256=3rD-aLnP3GRsYnNRHemTUpLLw-g3r9fVpyytwE89uMQ,2148
7
+ qodalis_cli_public_api/usage_service.py,sha256=PogUGOf0Ukx_qzmTByszkJS8sdWTDfRSqq-k2bs8GP0,4906
8
+ qodalis_cli_public_api/usage_store.py,sha256=qJgs-wuYmhQfidFHfH1ZW1uSKW_YW0Ud4MdKPabCNlY,4044
9
+ qodalis_cli_public_api/swagger_ui/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ qodalis_cli_public_api/swagger_ui/NOTICE,sha256=DSDRre8YruP0DdJYFyFVUhznAqxEXLX3t9YO0y2tL7I,55
11
+ qodalis_cli_public_api/swagger_ui/favicon-32x32.png,sha256=PtYS9B4FDKXnAAytbxy-fn2jn2X8qZwC6Z5lkQVuWDc,628
12
+ qodalis_cli_public_api/swagger_ui/swagger-ui-bundle.js,sha256=0OC-6TcyQIyR-60FywwoEumtN-lNEnmcVQOp_nr6K4I,1732839
13
+ qodalis_cli_public_api/swagger_ui/swagger-ui-bundle.js.LICENSE.txt,sha256=N-tuflmu1XssGs8HZXS4GOoHt0JlcX4L1ntZ4Lr5q7s,4606
14
+ qodalis_cli_public_api/swagger_ui/swagger-ui.css,sha256=XtCHV-U9o-Am1svsxh_l1DWFyVYLMC1TStVmklGaJz0,187956
15
+ qodalis_cli_server_plugin_public_api-1.0.0b29.dist-info/METADATA,sha256=l34X1BZl3YsZwt7QYutm441TkSn1bsqP5oG4ftiBaKM,1210
16
+ qodalis_cli_server_plugin_public_api-1.0.0b29.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
17
+ qodalis_cli_server_plugin_public_api-1.0.0b29.dist-info/licenses/LICENSE,sha256=uagko_O2JboeVOW3cldvxKW4QIDjTHCCk5T32qqg_As,1079
18
+ qodalis_cli_server_plugin_public_api-1.0.0b29.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024-2026 Qodalis Solutions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.