vuka 0.1.0__py3-none-win_amd64.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.
vuka/__init__.py ADDED
@@ -0,0 +1,182 @@
1
+ """Live vuka pages from Python.
2
+
3
+ A page is a ``.vuka.html`` file under ``pages/``: a ``<script
4
+ lang="python">`` header declaring a :class:`Live` class, then its markup.
5
+ ``vuka.run()`` loads the pages, compiles their markup, and serves them
6
+ through the vuka engine::
7
+
8
+ @vuka.live("/", key="", subscribe="counts")
9
+ class Index(vuka.Live):
10
+ count: int = 0
11
+ category: vuka.Url[str] = "all"
12
+
13
+ def add(self, n: int):
14
+ self.count += n
15
+
16
+ Services come from providers, injected by parameter annotation::
17
+
18
+ @vuka.provide
19
+ def billing(db: Database) -> Billing: ...
20
+
21
+ @vuka.live("/invoices")
22
+ class Invoices(vuka.Live):
23
+ def pay(self, id: int, billing: Billing): ... # id from the page, billing injected
24
+
25
+ The surface: :func:`live`, :class:`Live`, :class:`Url`, :class:`State`, :class:`Bind`, :class:`Html`, :func:`publish`,
26
+ :func:`run`, :func:`provide`, :class:`Context`, :class:`override`. Plain
27
+ request/response endpoints beside the pages: :func:`get`, :func:`post`,
28
+ :func:`put`, :func:`patch`, :func:`delete` (:class:`Request`, :class:`Response`).
29
+ :func:`guard` with :class:`Redirect` and :class:`Refuse` for guarded pages;
30
+ ``layouts/`` beside ``pages/`` for the markup around them; :func:`flash`
31
+ for a message the next page shows once (read as ``messages``);
32
+ ``errors/404.vuka.html`` (``errors/default.vuka.html``) for error pages.
33
+ :class:`Visitor` (``ctx.visitor``) for the visitor's session, which the engine keeps.
34
+ :func:`users` for the app's user loader, :func:`sign_in` / :func:`sign_out` (``ctx.user`` the
35
+ signed-in user), :data:`require_user` / :func:`requires` / :func:`requires_any` gates,
36
+ :func:`login_failed` / :func:`login_wait` for the login throttle, :func:`refresh_user`.
37
+ :mod:`vuka.config` for the app's ``vuka.toml`` settings.
38
+ :func:`url` (and :func:`url_path`) links to a route by its name, as ``route(…)``
39
+ does in markup; ``@vuka.live(..., name=…)`` names a route.
40
+ :func:`context_processor` for template variables every template reads, and
41
+ :func:`refresh` to recompute them after an event.
42
+ :class:`Invalid` for a form's field errors.
43
+ :class:`Deferred` fields (and :func:`defer`) load after the page renders,
44
+ filled by the method marked :func:`loads`.
45
+ :func:`cron` runs a module function on a schedule, in the engine's scheduler.
46
+ ``Db`` and ``AsyncDb`` (:mod:`vuka.db`) for the app's database.
47
+ :func:`query` fills a page's fields from the database in the engine, with no
48
+ call to the app (``@vuka.live(..., load=vuka.query(…))`` for a detail page;
49
+ :class:`From` names a parameter's source).
50
+ :class:`Cache` (``@vuka.live(..., cache=…)``, ``@vuka.get(..., cache=…)``) lets
51
+ the engine answer a page's loads and an endpoint's hits without calling the
52
+ app; :func:`vuka.cache.purge` drops the entries by tag. :mod:`vuka.cache`
53
+ also keeps the app's own values in the engine, shared by every worker
54
+ (``get``/``set``/``delete``, ``remember``, ``@vuka.cache.memo``).
55
+
56
+ Any of the functions the app hands over — handlers, endpoints, guards,
57
+ providers, crons — may be an ``async def``; it runs on the SDK's event loop.
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ from typing import Any
63
+
64
+ from ._context import context_processor, refresh
65
+ from ._crons import cron
66
+ from . import cache, config, tokens
67
+ from ._api import CORS, api
68
+ from .cache import Cache
69
+ from ._di import Context, override, provide
70
+ from ._endpoints import Request, Response, delete, get, patch, post, put, route
71
+ from ._errors import Invalid, UserError, VukaError
72
+ from ._flash import flash
73
+ from ._forms import Form, FormState, configure_forms, field
74
+ from ._fields import Bind, Deferred, Presence, State, Stream, Upload, Url, defer
75
+ from ._guard import Redirect, Refuse, guard
76
+ from ._html import Html
77
+ from ._identity import (
78
+ Gate,
79
+ Throttled,
80
+ login_failed,
81
+ login_wait,
82
+ refresh_user,
83
+ require_user,
84
+ requires,
85
+ requires_any,
86
+ sign_in,
87
+ sign_out,
88
+ users,
89
+ )
90
+ from ._live import Live, live, loads
91
+ from ._reads import From, query
92
+ from ._routes import url, url_path
93
+ from ._run import publish, run
94
+ from ._uploads import UploadedFile, UploadError
95
+ from ._visitor import Visitor
96
+
97
+ __all__ = [
98
+ "Bind",
99
+ "CORS",
100
+ "Cache",
101
+ "Context",
102
+ "Deferred",
103
+ "Form",
104
+ "FormState",
105
+ "From",
106
+ "Gate",
107
+ "Html",
108
+ "Invalid",
109
+ "Live",
110
+ "Presence",
111
+ "Redirect",
112
+ "Refuse",
113
+ "Request",
114
+ "Response",
115
+ "State",
116
+ "Stream",
117
+ "Throttled",
118
+ "Upload",
119
+ "UploadError",
120
+ "UploadedFile",
121
+ "Url",
122
+ "UserError",
123
+ "Visitor",
124
+ "VukaError",
125
+ "api",
126
+ "cache",
127
+ "context_processor",
128
+ "config",
129
+ "configure_forms",
130
+ "cron",
131
+ "defer",
132
+ "delete",
133
+ "field",
134
+ "flash",
135
+ "get",
136
+ "guard",
137
+ "live",
138
+ "loads",
139
+ "login_failed",
140
+ "login_wait",
141
+ "override",
142
+ "patch",
143
+ "post",
144
+ "provide",
145
+ "publish",
146
+ "put",
147
+ "query",
148
+ "refresh",
149
+ "refresh_user",
150
+ "require_user",
151
+ "requires",
152
+ "requires_any",
153
+ "route",
154
+ "run",
155
+ "sign_in",
156
+ "sign_out",
157
+ "tokens",
158
+ "url",
159
+ "url_path",
160
+ "users",
161
+ ]
162
+
163
+ __version__ = "0.1.0"
164
+
165
+
166
+ def __getattr__(name: str) -> Any:
167
+ # vuka.Prop is reserved: naming it (vuka.Prop[int], from vuka import
168
+ # Prop) is a startup error saying what's pending
169
+ if name == "Prop":
170
+ from ._fields import Prop
171
+
172
+ Prop.__class_getitem__(None)
173
+ if name in ("db", "Db", "AsyncDb"):
174
+ # the database (vuka.db): naming its types declares it, and loads nothing otherwise
175
+ import importlib
176
+
177
+ db = importlib.import_module(".db", __name__)
178
+ return db if name == "db" else getattr(db, name)
179
+ if name == "spawn":
180
+ # reserved: a coroutine run on the event loop beyond the call that started it
181
+ raise VukaError("vuka.spawn is reserved: background coroutines aren't in this version")
182
+ raise AttributeError(f"module 'vuka' has no attribute {name!r}")
vuka/_aio.py ADDED
@@ -0,0 +1,135 @@
1
+ """The asyncio loop that ``async def`` handlers, endpoints, guards and providers run on.
2
+
3
+ An ``async def`` is accepted wherever a plain function is — a page's
4
+ ``mount``/``update``/``info``/events, an endpoint, a guard, a
5
+ ``@vuka.provide`` constructor (an async generator for one with teardown).
6
+ The SDK tells them apart by :func:`is_async`; there is no decorator and no
7
+ mode to switch.
8
+
9
+ There is **one** event loop, on a thread of its own (``vuka-async``),
10
+ started the first time something async runs: an app without ``async def``
11
+ never starts it. A worker thread that takes an async call does the call's
12
+ synchronous part (find the page, build its instance from the state), hands
13
+ the coroutine to the loop with :func:`submit` and goes back to the pool —
14
+ it never waits on the loop. The call's reply is sent from the loop when the
15
+ coroutine finishes, and only then is the call's session released to its
16
+ next call (``_pool.Deferred``): the per-session order holds across sync and
17
+ async calls alike, and a session awaiting holds no thread.
18
+
19
+ :func:`run` is the one blocking bridge: a worker (or the main thread)
20
+ needing an async provider's value — a sync handler depending on an async
21
+ singleton, built once — waits for the loop to build it. It refuses to run
22
+ on the loop's own thread, where waiting would deadlock; code there awaits.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import concurrent.futures
29
+ import contextvars
30
+ import inspect
31
+ import threading
32
+ from collections.abc import Coroutine
33
+ from typing import Any, TypeVar
34
+
35
+ from ._errors import VukaError
36
+
37
+ T = TypeVar("T")
38
+
39
+ #: The loop's thread name.
40
+ THREAD_NAME = "vuka-async"
41
+
42
+
43
+ def is_async(func: Any) -> bool:
44
+ """Whether ``func`` is an ``async def`` (coroutine or async generator function)."""
45
+ return inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func)
46
+
47
+
48
+ class _Loop:
49
+ def __init__(self) -> None:
50
+ self._lock = threading.Lock()
51
+ self._loop: asyncio.AbstractEventLoop | None = None
52
+ self._ident: int | None = None
53
+
54
+ def get(self) -> asyncio.AbstractEventLoop:
55
+ loop = self._loop
56
+ if loop is not None:
57
+ return loop
58
+ with self._lock:
59
+ if self._loop is None:
60
+ loop = asyncio.new_event_loop()
61
+ up = threading.Event()
62
+
63
+ def main() -> None:
64
+ asyncio.set_event_loop(loop)
65
+ self._ident = threading.get_ident()
66
+ up.set()
67
+ loop.run_forever()
68
+
69
+ threading.Thread(target=main, name=THREAD_NAME, daemon=True).start()
70
+ up.wait()
71
+ self._loop = loop
72
+ return self._loop
73
+
74
+ def on_thread(self) -> bool:
75
+ return self._ident is not None and threading.get_ident() == self._ident
76
+
77
+
78
+ _loop = _Loop()
79
+
80
+
81
+ def loop() -> asyncio.AbstractEventLoop:
82
+ """The loop, started on first use."""
83
+ return _loop.get()
84
+
85
+
86
+ def on_loop_thread() -> bool:
87
+ """Whether the caller runs on the loop's thread: inside a coroutine of the app's."""
88
+ return _loop.on_thread()
89
+
90
+
91
+ async def _guarded(coro: Coroutine[Any, Any, T]) -> T:
92
+ # KeyboardInterrupt and SystemExit escaping a task stop the loop itself
93
+ # (asyncio re-raises them out of run_forever): the call fails instead
94
+ try:
95
+ return await coro
96
+ except (KeyboardInterrupt, SystemExit) as e:
97
+ raise RuntimeError(f"{type(e).__name__} raised inside a coroutine") from e
98
+
99
+
100
+ def submit(coro: Coroutine[Any, Any, T]) -> concurrent.futures.Future[T]:
101
+ """Schedule ``coro`` on the loop; its result arrives on the returned future.
102
+
103
+ The coroutine runs in a copy of the caller's context, as a plain call
104
+ would: what the call being served set (``vuka.flash``'s messages) is
105
+ what it sees."""
106
+ loop = _loop.get()
107
+ ctx = contextvars.copy_context()
108
+ out: concurrent.futures.Future[T] = concurrent.futures.Future()
109
+
110
+ def start() -> None:
111
+ if not out.set_running_or_notify_cancel():
112
+ coro.close()
113
+ return
114
+ task = loop.create_task(_guarded(coro), context=ctx)
115
+
116
+ def done(t: asyncio.Task[T]) -> None:
117
+ if t.cancelled():
118
+ out.set_exception(concurrent.futures.CancelledError())
119
+ elif (e := t.exception()) is not None:
120
+ out.set_exception(e)
121
+ else:
122
+ out.set_result(t.result())
123
+
124
+ task.add_done_callback(done)
125
+
126
+ loop.call_soon_threadsafe(start)
127
+ return out
128
+
129
+
130
+ def run(coro: Coroutine[Any, Any, T]) -> T:
131
+ """Run ``coro`` on the loop and wait for its result (never from the loop's own thread)."""
132
+ if _loop.on_thread():
133
+ coro.close()
134
+ raise VukaError("waiting on the event loop from its own thread would deadlock; await instead")
135
+ return submit(coro).result()
vuka/_api.py ADDED
@@ -0,0 +1,208 @@
1
+ """APIs other clients call: ``vuka.api(prefix, cors=…)`` (vuka-lang/web#188).
2
+
3
+ A mobile app, a partner's server or a script on another origin calls the
4
+ app's endpoints under a prefix the app declares, as a Go app declares
5
+ ``web.TokenOnly`` and ``web.CORS``::
6
+
7
+ vuka.api("/api/", cors=vuka.CORS(origins=["https://shop.example"]))
8
+
9
+ The engine does the rest before the app hears of a request. Under a
10
+ token-only prefix (the default) the request's cookies are taken off and
11
+ its answer sets none, so a browser's session never signs it in and a
12
+ cross-site script can't ride it; the request signs in with its
13
+ ``Authorization: Bearer`` header alone — a token the app issued
14
+ (:func:`vuka.tokens.issue`) or a JWT another service signed (the
15
+ ``[jwt]`` table, ``@vuka.users(jwt=True)``) — and its endpoint sees that
16
+ header in ``req.headers["authorization"]``. ``cors`` lets the listed
17
+ origins' scripts read the answers: the engine answers their preflights.
18
+ Pages need the visitor's cookie, so no page may live under a token-only
19
+ prefix.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import datetime
25
+ import sys
26
+ from dataclasses import dataclass
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from ._errors import VukaError
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class CORS:
35
+ """What other origins may do under an API prefix (Go's ``web.CORSConfig``).
36
+
37
+ ``origins`` are the origins allowed, exactly as a browser sends them
38
+ (``"https://shop.example"``), or ``["*"]`` for any; ``methods`` default
39
+ to GET, HEAD and POST; ``headers`` a request may carry besides the
40
+ safelisted ones default to Content-Type (and Authorization under a
41
+ token-only prefix), ``"*"`` for any; ``expose_headers`` are the
42
+ response headers a script may read; ``credentials`` lets the origins
43
+ send cookies (never with ``"*"``, never under a token-only prefix);
44
+ ``max_age`` is how long a browser keeps a preflight's answer (5
45
+ minutes; seconds, a timedelta or ``"10m"``, negative for never).
46
+ """
47
+
48
+ origins: tuple[str, ...]
49
+ methods: tuple[str, ...] = ()
50
+ headers: tuple[str, ...] = ()
51
+ expose_headers: tuple[str, ...] = ()
52
+ credentials: bool = False
53
+ max_age: Any = None
54
+
55
+ def __init__(
56
+ self,
57
+ origins: Any,
58
+ *,
59
+ methods: Any = (),
60
+ headers: Any = (),
61
+ expose_headers: Any = (),
62
+ credentials: bool = False,
63
+ max_age: Any = None,
64
+ ) -> None:
65
+ set_ = object.__setattr__
66
+ set_(self, "origins", _strings("origins", origins))
67
+ set_(self, "methods", _strings("methods", methods))
68
+ set_(self, "headers", _strings("headers", headers))
69
+ set_(self, "expose_headers", _strings("expose_headers", expose_headers))
70
+ set_(self, "credentials", bool(credentials))
71
+ set_(self, "max_age", max_age)
72
+ if not self.origins:
73
+ raise VukaError('vuka.CORS: no origins: list the origins allowed ("https://shop.example"), or ["*"]')
74
+
75
+ def manifest(self) -> dict[str, Any]:
76
+ m: dict[str, Any] = {"origins": list(self.origins)}
77
+ for k in ("methods", "headers", "expose_headers"):
78
+ if v := getattr(self, k):
79
+ m[k] = list(v)
80
+ if self.credentials:
81
+ m["credentials"] = True
82
+ if self.max_age is not None:
83
+ m["max_age"] = _duration(self.max_age)
84
+ return m
85
+
86
+
87
+ def _strings(name: str, v: Any) -> tuple[str, ...]:
88
+ if isinstance(v, str):
89
+ v = (v,)
90
+ out = tuple(v or ())
91
+ for s in out:
92
+ if not isinstance(s, str) or not s:
93
+ raise TypeError(f"vuka.CORS: {name} holds {s!r}: each is a non-empty string")
94
+ return out
95
+
96
+
97
+ def _duration(v: Any) -> str:
98
+ if isinstance(v, datetime.timedelta):
99
+ v = v.total_seconds()
100
+ if isinstance(v, bool):
101
+ raise TypeError(f'vuka.CORS: max_age={v!r}: seconds, a timedelta or a string ("10m")')
102
+ if isinstance(v, (int, float)):
103
+ return f"{round(v * 1000)}ms"
104
+ if isinstance(v, str) and v:
105
+ return v
106
+ raise TypeError(f'vuka.CORS: max_age={v!r}: seconds, a timedelta or a string ("10m")')
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class API:
111
+ prefix: str
112
+ token_only: bool
113
+ cors: CORS | None
114
+ where: str
115
+ module: str
116
+
117
+ def manifest(self) -> dict[str, Any]:
118
+ m: dict[str, Any] = {"prefix": self.prefix}
119
+ if self.token_only:
120
+ m["token_only"] = True
121
+ if self.cors is not None:
122
+ m["cors"] = self.cors.manifest()
123
+ return m
124
+
125
+
126
+ #: The app's API prefixes, by prefix.
127
+ _registry: dict[str, API] = {}
128
+
129
+
130
+ def _base(prefix: str) -> str:
131
+ return prefix.rstrip("/") or "/"
132
+
133
+
134
+ def api(prefix: str, *, cors: CORS | dict[str, Any] | None = None, token_only: bool = True) -> API:
135
+ """Declare the endpoints under ``prefix`` (``"/api/"`` covers /api and every
136
+ path under it) an API other clients call.
137
+
138
+ ``token_only`` (the default) keeps the visitor's cookies off: requests
139
+ sign in with ``Authorization: Bearer`` alone (:mod:`vuka.tokens`, or a
140
+ JWT the ``[jwt]`` table verifies) and their endpoints see the header.
141
+ ``cors`` (a :class:`CORS`, or its keywords as a dict) lets other
142
+ origins' scripts read the answers. Declare it once, at module level.
143
+ """
144
+ frame = sys._getframe(1)
145
+ where = f"{Path(frame.f_code.co_filename).name}:{frame.f_lineno}"
146
+ module = frame.f_globals.get("__name__", "")
147
+ if (
148
+ not isinstance(prefix, str)
149
+ or not prefix.startswith("/")
150
+ or prefix.startswith("//")
151
+ or any(c in prefix for c in "?#{}")
152
+ ):
153
+ raise VukaError(f'{where}: vuka.api({prefix!r}): a path prefix of the app ("/api/")')
154
+ if isinstance(cors, dict):
155
+ cors = CORS(**cors)
156
+ if cors is not None and not isinstance(cors, CORS):
157
+ raise VukaError(f"{where}: vuka.api({prefix!r}, cors={cors!r}): a vuka.CORS(origins=[…]) or its keywords")
158
+ if not token_only and cors is None:
159
+ raise VukaError(f"{where}: vuka.api({prefix!r}, token_only=False): give cors=, or leave token_only on")
160
+ if cors is not None and cors.credentials and token_only:
161
+ raise VukaError(
162
+ f"{where}: vuka.api({prefix!r}): cors credentials under a token-only prefix, which takes cookies off; "
163
+ "drop credentials (a token API sends Authorization), or pass token_only=False"
164
+ )
165
+ spec = API(prefix, bool(token_only), cors, where, module)
166
+ old = _registry.get(_base(prefix))
167
+ if old is not None and old.module != module:
168
+ raise VukaError(f"{where}: vuka.api({prefix!r}): the prefix is declared at {old.where} already")
169
+ _registry[_base(prefix)] = spec
170
+ return spec
171
+
172
+
173
+ def manifest() -> list[dict[str, Any]]:
174
+ """The manifest's ``api``."""
175
+ return [a.manifest() for a in _registry.values()]
176
+
177
+
178
+ def apis() -> list[API]:
179
+ return list(_registry.values())
180
+
181
+
182
+ def forget(modules: Any) -> None:
183
+ """Drop the prefixes declared by ``modules``: they are about to load again (the dev loop)."""
184
+ gone = set(modules)
185
+ for k, a in list(_registry.items()):
186
+ if a.module in gone:
187
+ del _registry[k]
188
+
189
+
190
+ def reset() -> None:
191
+ """No API prefixes (tests)."""
192
+ _registry.clear()
193
+
194
+
195
+ def check_routes(routes: Any) -> None:
196
+ """A page under a token-only prefix is a startup error: its requests would carry no cookie."""
197
+ for a in _registry.values():
198
+ if not a.token_only:
199
+ continue
200
+ base = _base(a.prefix)
201
+ for r in routes:
202
+ lit = r.split("{", 1)[0]
203
+ p = lit.rstrip("/") or "/"
204
+ if base == "/" or p == base or p.startswith(base + "/") or lit.startswith(base + "/"):
205
+ raise VukaError(
206
+ f"{a.where}: vuka.api({a.prefix!r}) is token-only, and the page {r} lies under it: "
207
+ "a page needs the visitor's cookie; keep pages off the prefix"
208
+ )