jigkit 0.2.0__tar.gz → 0.3.1__tar.gz
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.
- {jigkit-0.2.0 → jigkit-0.3.1}/PKG-INFO +14 -1
- {jigkit-0.2.0 → jigkit-0.3.1}/README.md +4 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/pyproject.toml +13 -2
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/logging.py +3 -2
- jigkit-0.3.1/src/jigkit/notify.py +58 -0
- jigkit-0.3.1/src/jigkit/ratelimit.py +35 -0
- jigkit-0.3.1/src/jigkit/scheduler.py +73 -0
- jigkit-0.3.1/src/jigkit/testing/notify.py +27 -0
- jigkit-0.3.1/src/jigkit/web/__init__.py +40 -0
- jigkit-0.3.1/src/jigkit/web/guard.py +86 -0
- jigkit-0.3.1/src/jigkit/web/health.py +53 -0
- jigkit-0.3.1/src/jigkit/web/manifest.py +87 -0
- jigkit-0.3.1/src/jigkit/web/server.py +49 -0
- jigkit-0.3.1/src/jigkit/web/spa.py +63 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_heartbeat.py +20 -0
- jigkit-0.3.1/tests/test_notify.py +68 -0
- jigkit-0.3.1/tests/test_ratelimit.py +87 -0
- jigkit-0.3.1/tests/test_scheduler.py +104 -0
- jigkit-0.3.1/tests/test_web.py +367 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/.gitignore +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/LICENSE +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/__init__.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/db.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/delivery.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/healthcheck.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/heartbeat.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/influx/__init__.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/influx/lineprotocol.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/influx/sink.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/migrations.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/models.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/py.typed +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/secrets.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/settings.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/sinks.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/spool.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/testing/__init__.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/testing/http.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/src/jigkit/testing/migrations.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/conftest.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/sample_app/alembic/env.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/sample_app/alembic/script.py.mako +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/sample_app/alembic/versions/0001_initial.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/sample_app/alembic.ini +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/sample_app/sample_schema.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_db.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_delivery.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_healthcheck.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_influx_lineprotocol.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_influx_read.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_influx_sink.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_logging.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_migrations.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_models.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_secrets.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_settings.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_sinks.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_spool.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_testing_plugin.py +0 -0
- {jigkit-0.2.0 → jigkit-0.3.1}/tests/test_version.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: jigkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.1
|
|
4
4
|
Summary: The shared foundations of small self-hosted web apps: settings, database, migrations, logging, health checks and test fixtures
|
|
5
5
|
Project-URL: Homepage, https://github.com/jmerhar/jigkit
|
|
6
6
|
Project-URL: Changelog, https://github.com/jmerhar/jigkit/blob/main/CHANGELOG.md
|
|
@@ -25,18 +25,24 @@ Requires-Dist: sqlalchemy[asyncio]>=2.0.52; extra == 'db'
|
|
|
25
25
|
Provides-Extra: dev
|
|
26
26
|
Requires-Dist: aiosqlite>=0.22; extra == 'dev'
|
|
27
27
|
Requires-Dist: alembic>=1.19; extra == 'dev'
|
|
28
|
+
Requires-Dist: apprise>=1.9; extra == 'dev'
|
|
28
29
|
Requires-Dist: build>=1.3; extra == 'dev'
|
|
30
|
+
Requires-Dist: fastapi<0.144,>=0.141; extra == 'dev'
|
|
29
31
|
Requires-Dist: httpx2>=2.13; extra == 'dev'
|
|
32
|
+
Requires-Dist: httpx>=0.28; extra == 'dev'
|
|
30
33
|
Requires-Dist: pytest-asyncio>=1.4; extra == 'dev'
|
|
31
34
|
Requires-Dist: pytest-cov>=7.1; extra == 'dev'
|
|
32
35
|
Requires-Dist: pytest>=9.1; extra == 'dev'
|
|
33
36
|
Requires-Dist: ruff>=0.16; extra == 'dev'
|
|
34
37
|
Requires-Dist: sqlalchemy[asyncio]>=2.0.52; extra == 'dev'
|
|
35
38
|
Requires-Dist: twine>=6.2; extra == 'dev'
|
|
39
|
+
Requires-Dist: uvicorn[standard]>=0.30; extra == 'dev'
|
|
36
40
|
Provides-Extra: heartbeat
|
|
37
41
|
Requires-Dist: httpx2>=2.13; extra == 'heartbeat'
|
|
38
42
|
Provides-Extra: influx
|
|
39
43
|
Requires-Dist: httpx2>=2.13; extra == 'influx'
|
|
44
|
+
Provides-Extra: notify
|
|
45
|
+
Requires-Dist: apprise>=1.9; extra == 'notify'
|
|
40
46
|
Provides-Extra: postgres
|
|
41
47
|
Requires-Dist: aiosqlite>=0.22; extra == 'postgres'
|
|
42
48
|
Requires-Dist: alembic>=1.19; extra == 'postgres'
|
|
@@ -45,6 +51,9 @@ Requires-Dist: sqlalchemy[asyncio]>=2.0.52; extra == 'postgres'
|
|
|
45
51
|
Provides-Extra: testing
|
|
46
52
|
Requires-Dist: pytest-asyncio>=1.4; extra == 'testing'
|
|
47
53
|
Requires-Dist: pytest>=9.1; extra == 'testing'
|
|
54
|
+
Provides-Extra: web
|
|
55
|
+
Requires-Dist: fastapi<0.144,>=0.141; extra == 'web'
|
|
56
|
+
Requires-Dist: uvicorn[standard]>=0.30; extra == 'web'
|
|
48
57
|
Description-Content-Type: text/markdown
|
|
49
58
|
|
|
50
59
|
# jigkit
|
|
@@ -70,6 +79,10 @@ pip install "jigkit[db]"
|
|
|
70
79
|
| `jigkit.spool`, `jigkit.delivery` | — | a bounded on-disk queue per destination, and write-now-or-spool-and-replay |
|
|
71
80
|
| `jigkit.influx` | `influx` | InfluxDB 3 and 2.x sinks: line protocol in each batch's precision, and SQL reads from InfluxDB 3 |
|
|
72
81
|
| `jigkit.heartbeat` | `heartbeat` | a push-monitor heartbeat after delivered writes, at most once per interval |
|
|
82
|
+
| `jigkit.web` | `web` | FastAPI building blocks: write guard, security headers, SPA serving, health router, PWA manifest, `serve()` |
|
|
83
|
+
| `jigkit.scheduler` | — | `TickLoop`: in-process work on a fixed tick |
|
|
84
|
+
| `jigkit.notify` | `notify` | Apprise delivery off the event loop, and URL redaction for logs |
|
|
85
|
+
| `jigkit.ratelimit` | — | `RateLimiter`: a token bucket per client with bounded memory |
|
|
73
86
|
| `jigkit.testing` | `testing` | a pytest plugin (`data_dir`, `no_network`), migration checks run through the application's own `env.py`, and a recording stand-in HTTP server |
|
|
74
87
|
|
|
75
88
|
PostgreSQL is supported through the `postgres` extra. Python 3.14 or newer.
|
|
@@ -21,6 +21,10 @@ pip install "jigkit[db]"
|
|
|
21
21
|
| `jigkit.spool`, `jigkit.delivery` | — | a bounded on-disk queue per destination, and write-now-or-spool-and-replay |
|
|
22
22
|
| `jigkit.influx` | `influx` | InfluxDB 3 and 2.x sinks: line protocol in each batch's precision, and SQL reads from InfluxDB 3 |
|
|
23
23
|
| `jigkit.heartbeat` | `heartbeat` | a push-monitor heartbeat after delivered writes, at most once per interval |
|
|
24
|
+
| `jigkit.web` | `web` | FastAPI building blocks: write guard, security headers, SPA serving, health router, PWA manifest, `serve()` |
|
|
25
|
+
| `jigkit.scheduler` | — | `TickLoop`: in-process work on a fixed tick |
|
|
26
|
+
| `jigkit.notify` | `notify` | Apprise delivery off the event loop, and URL redaction for logs |
|
|
27
|
+
| `jigkit.ratelimit` | — | `RateLimiter`: a token bucket per client with bounded memory |
|
|
24
28
|
| `jigkit.testing` | `testing` | a pytest plugin (`data_dir`, `no_network`), migration checks run through the application's own `env.py`, and a recording stand-in HTTP server |
|
|
25
29
|
|
|
26
30
|
PostgreSQL is supported through the `postgres` extra. Python 3.14 or newer.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "jigkit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.3.1"
|
|
8
8
|
description = "The shared foundations of small self-hosted web apps: settings, database, migrations, logging, health checks and test fixtures"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.14"
|
|
@@ -47,6 +47,16 @@ influx = [
|
|
|
47
47
|
heartbeat = [
|
|
48
48
|
"httpx2>=2.13",
|
|
49
49
|
]
|
|
50
|
+
# FastAPI building blocks and uvicorn. FastAPI is held to a minor line: how it reports a matched
|
|
51
|
+
# route's path has changed within a minor release before.
|
|
52
|
+
web = [
|
|
53
|
+
"fastapi>=0.141,<0.144",
|
|
54
|
+
"uvicorn[standard]>=0.30",
|
|
55
|
+
]
|
|
56
|
+
# Notifications through Apprise.
|
|
57
|
+
notify = [
|
|
58
|
+
"apprise>=1.9",
|
|
59
|
+
]
|
|
50
60
|
# The pytest plugin: fixtures and migration checks for applications built on jigkit.
|
|
51
61
|
testing = [
|
|
52
62
|
"pytest>=9.1",
|
|
@@ -54,7 +64,8 @@ testing = [
|
|
|
54
64
|
]
|
|
55
65
|
# Everything this repository's own checks need.
|
|
56
66
|
dev = [
|
|
57
|
-
"jigkit[db,heartbeat,influx,testing]",
|
|
67
|
+
"jigkit[db,heartbeat,influx,notify,testing,web]",
|
|
68
|
+
"httpx>=0.28",
|
|
58
69
|
"pytest-cov>=7.1",
|
|
59
70
|
"ruff>=0.16",
|
|
60
71
|
"build>=1.3",
|
|
@@ -30,8 +30,9 @@ FOLLOW_ROOT = ("uvicorn", "uvicorn.access", "uvicorn.error")
|
|
|
30
30
|
|
|
31
31
|
#: Loggers held at WARNING however low the application goes. httpx logs every request's URL at
|
|
32
32
|
#: INFO and httpcore logs headers at DEBUG, and URLs and headers carry credentials: push-monitor
|
|
33
|
-
#: tokens, bot tokens, session cookies.
|
|
34
|
-
|
|
33
|
+
#: tokens, bot tokens, session cookies. httpx2 and httpcore2, which jigkit's own HTTP clients
|
|
34
|
+
#: use, log the same under their own names.
|
|
35
|
+
QUIET = ("httpx", "httpcore", "httpx2", "httpcore2")
|
|
35
36
|
|
|
36
37
|
# Marks the handlers this module installed, so a repeated call replaces them rather than stacking
|
|
37
38
|
# a second copy that logs every line twice.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Notifications through Apprise (extra ``notify``).
|
|
2
|
+
|
|
3
|
+
One URL list covers email, Signal, Telegram, ntfy, Discord and the rest, so an application needs
|
|
4
|
+
no transport configuration of its own. Which events reach whom, and in which words, stays with
|
|
5
|
+
the application; this module only delivers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger(__name__)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Sender(Protocol):
|
|
18
|
+
"""Delivers one message to a set of Apprise URLs."""
|
|
19
|
+
|
|
20
|
+
async def send(self, urls: list[str], title: str, body: str) -> bool:
|
|
21
|
+
"""Return whether at least one destination accepted the message."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AppriseSender:
|
|
25
|
+
"""Sends through Apprise.
|
|
26
|
+
|
|
27
|
+
Apprise is synchronous and does network IO, so it runs in a worker thread: called directly
|
|
28
|
+
it would block the event loop for as long as the slowest destination takes to answer.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
async def send(self, urls: list[str], title: str, body: str) -> bool:
|
|
32
|
+
"""Send to every URL Apprise recognises; False when none is usable or none accepts."""
|
|
33
|
+
return await asyncio.to_thread(self._send, urls, title, body)
|
|
34
|
+
|
|
35
|
+
@staticmethod
|
|
36
|
+
def _send(urls: list[str], title: str, body: str) -> bool:
|
|
37
|
+
"""The blocking send, run off the event loop."""
|
|
38
|
+
import apprise
|
|
39
|
+
|
|
40
|
+
client = apprise.Apprise()
|
|
41
|
+
for url in urls:
|
|
42
|
+
if not client.add(url):
|
|
43
|
+
logger.warning("apprise did not recognise a destination: %s", redact_url(url))
|
|
44
|
+
if not len(client):
|
|
45
|
+
return False
|
|
46
|
+
return bool(client.notify(title=title, body=body))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def redact_url(url: str) -> str:
|
|
50
|
+
"""A notification URL with its credentials removed, for logging.
|
|
51
|
+
|
|
52
|
+
An Apprise URL is mostly credential -- a bot token, an SMTP password -- so only its scheme
|
|
53
|
+
and last four characters are kept, enough to tell two destinations apart.
|
|
54
|
+
"""
|
|
55
|
+
scheme, separator, rest = url.partition("://")
|
|
56
|
+
if not separator:
|
|
57
|
+
return "<malformed url>"
|
|
58
|
+
return f"{scheme}://…" if len(rest) <= 8 else f"{scheme}://…{rest[-4:]}"
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""A per-client request budget: a token bucket per address, with bounded memory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections import OrderedDict
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class RateLimiter:
|
|
13
|
+
"""A token bucket per client.
|
|
14
|
+
|
|
15
|
+
Each client may make ``burst`` requests at once and ``rate`` per second after that. Clients
|
|
16
|
+
are tracked in least-recently-used order and the oldest is forgotten beyond ``max_clients``,
|
|
17
|
+
so a scan from many addresses cannot grow this without bound.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
rate: float = 2.0
|
|
21
|
+
burst: int = 20
|
|
22
|
+
max_clients: int = 10_000
|
|
23
|
+
clock: Callable[[], float] = time.monotonic
|
|
24
|
+
_buckets: OrderedDict[str, tuple[float, float]] = field(default_factory=OrderedDict)
|
|
25
|
+
|
|
26
|
+
def allow(self, client: str) -> bool:
|
|
27
|
+
"""Spend one token for ``client``, returning whether it had one."""
|
|
28
|
+
now = self.clock()
|
|
29
|
+
tokens, last = self._buckets.pop(client, (float(self.burst), now))
|
|
30
|
+
tokens = min(float(self.burst), tokens + (now - last) * self.rate)
|
|
31
|
+
allowed = tokens >= 1
|
|
32
|
+
self._buckets[client] = (tokens - 1 if allowed else tokens, now)
|
|
33
|
+
while len(self._buckets) > self.max_clients:
|
|
34
|
+
self._buckets.popitem(last=False)
|
|
35
|
+
return allowed
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Work an application does on its own, on a fixed tick, inside its own process.
|
|
2
|
+
|
|
3
|
+
A plain asyncio loop rather than a scheduling library: an application's scheduled work is "do
|
|
4
|
+
whatever is due", with what is due kept in its own data, and a tick that is a method call can be
|
|
5
|
+
driven directly by a test instead of waited for.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import contextlib
|
|
12
|
+
import logging
|
|
13
|
+
from collections.abc import Awaitable, Callable
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TickLoop:
|
|
19
|
+
"""Calls ``tick`` every ``interval_seconds`` between :meth:`start` and :meth:`stop`.
|
|
20
|
+
|
|
21
|
+
A tick that raises is logged and the loop carries on: a loop that died on one bad tick would
|
|
22
|
+
stop every later piece of work without saying so. ``enabled=False`` makes :meth:`start` do
|
|
23
|
+
nothing, which is how tests drive ``tick`` themselves.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
tick: Callable[[], Awaitable[None]],
|
|
29
|
+
interval_seconds: float,
|
|
30
|
+
*,
|
|
31
|
+
enabled: bool = True,
|
|
32
|
+
name: str = "scheduler",
|
|
33
|
+
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
|
|
34
|
+
) -> None:
|
|
35
|
+
self._tick = tick
|
|
36
|
+
self._interval = interval_seconds
|
|
37
|
+
self._enabled = enabled
|
|
38
|
+
self._name = name
|
|
39
|
+
self._sleep = sleep
|
|
40
|
+
self._task: asyncio.Task[None] | None = None
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def running(self) -> bool:
|
|
44
|
+
"""Whether the loop has been started and not stopped."""
|
|
45
|
+
return self._task is not None
|
|
46
|
+
|
|
47
|
+
def start(self) -> None:
|
|
48
|
+
"""Begin ticking, unless disabled or already started."""
|
|
49
|
+
if not self._enabled:
|
|
50
|
+
logger.info("%s disabled by configuration", self._name)
|
|
51
|
+
return
|
|
52
|
+
if self._task is not None:
|
|
53
|
+
return
|
|
54
|
+
self._task = asyncio.create_task(self._loop(), name=self._name)
|
|
55
|
+
logger.info("%s started, ticking every %gs", self._name, self._interval)
|
|
56
|
+
|
|
57
|
+
async def stop(self) -> None:
|
|
58
|
+
"""Stop ticking and wait for the loop to unwind."""
|
|
59
|
+
if self._task is None:
|
|
60
|
+
return
|
|
61
|
+
self._task.cancel()
|
|
62
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
63
|
+
await self._task
|
|
64
|
+
self._task = None
|
|
65
|
+
|
|
66
|
+
async def _loop(self) -> None:
|
|
67
|
+
"""Tick, then wait, for ever."""
|
|
68
|
+
while True:
|
|
69
|
+
try:
|
|
70
|
+
await self._tick()
|
|
71
|
+
except Exception:
|
|
72
|
+
logger.exception("%s tick failed; the next one tries again", self._name)
|
|
73
|
+
await self._sleep(self._interval)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""A stand-in for :class:`jigkit.notify.Sender` that records what it was asked to send."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Sent:
|
|
10
|
+
"""One message a :class:`RecordingSender` was given."""
|
|
11
|
+
|
|
12
|
+
urls: list[str]
|
|
13
|
+
title: str
|
|
14
|
+
body: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class RecordingSender:
|
|
19
|
+
"""Keeps every message instead of sending it, and answers with ``accept``."""
|
|
20
|
+
|
|
21
|
+
accept: bool = True
|
|
22
|
+
sent: list[Sent] = field(default_factory=list)
|
|
23
|
+
|
|
24
|
+
async def send(self, urls: list[str], title: str, body: str) -> bool:
|
|
25
|
+
"""Record the message and return ``accept``."""
|
|
26
|
+
self.sent.append(Sent(list(urls), title, body))
|
|
27
|
+
return self.accept
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Building blocks for a FastAPI application (extra ``web``).
|
|
2
|
+
|
|
3
|
+
Each is applied to an application the app builds itself, so an application keeps its own
|
|
4
|
+
factory and lifespan and takes only the pieces it wants:
|
|
5
|
+
|
|
6
|
+
- :func:`install_write_guard`: writes under the API only from the application's own pages;
|
|
7
|
+
- :func:`install_security_headers`: nosniff, a same-origin referrer, no framing;
|
|
8
|
+
- :func:`mount_spa`: the built single-page app, with its client-side routes and cache headers;
|
|
9
|
+
- :func:`health_router`: ``/health``, which queries the database;
|
|
10
|
+
- :func:`web_manifest` and :func:`manifest_response`: the PWA manifest;
|
|
11
|
+
- :func:`serve`: uvicorn, believing forwarded headers only from the configured proxies.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from jigkit.web.guard import (
|
|
15
|
+
WRITE_HEADER,
|
|
16
|
+
WRITES,
|
|
17
|
+
install_security_headers,
|
|
18
|
+
install_write_guard,
|
|
19
|
+
origin_allowed,
|
|
20
|
+
)
|
|
21
|
+
from jigkit.web.health import Health, health_router
|
|
22
|
+
from jigkit.web.manifest import manifest_response, preferred_language, web_manifest
|
|
23
|
+
from jigkit.web.server import serve
|
|
24
|
+
from jigkit.web.spa import IMMUTABLE, mount_spa
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"IMMUTABLE",
|
|
28
|
+
"WRITES",
|
|
29
|
+
"WRITE_HEADER",
|
|
30
|
+
"Health",
|
|
31
|
+
"health_router",
|
|
32
|
+
"install_security_headers",
|
|
33
|
+
"install_write_guard",
|
|
34
|
+
"manifest_response",
|
|
35
|
+
"mount_spa",
|
|
36
|
+
"origin_allowed",
|
|
37
|
+
"preferred_language",
|
|
38
|
+
"serve",
|
|
39
|
+
"web_manifest",
|
|
40
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Requests the application refuses, and the headers it adds to every response."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from urllib.parse import urlsplit
|
|
7
|
+
|
|
8
|
+
from fastapi import FastAPI, Request, Response
|
|
9
|
+
from fastapi.responses import JSONResponse
|
|
10
|
+
|
|
11
|
+
#: Methods that change something, which only the application's own pages may send.
|
|
12
|
+
WRITES = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
|
13
|
+
#: The header every write must carry. A page on another site cannot add a custom header to a
|
|
14
|
+
#: request without a CORS preflight, which an application built on this never grants.
|
|
15
|
+
WRITE_HEADER = "X-Requested-With"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def origin_allowed(origin: str | None, host: str | None, public_url: str | None) -> bool:
|
|
19
|
+
"""Whether a write's Origin header is this application's own.
|
|
20
|
+
|
|
21
|
+
No Origin at all is allowed: browsers send one on every cross-origin write, so its absence
|
|
22
|
+
means a same-origin request or a client that is not a browser, and the write header still
|
|
23
|
+
has to be there. Otherwise the origin must be the configured public URL's, or name the host
|
|
24
|
+
the request was sent to; an opaque ``null`` origin never does.
|
|
25
|
+
"""
|
|
26
|
+
if origin is None:
|
|
27
|
+
return True
|
|
28
|
+
allowed = set()
|
|
29
|
+
if public_url:
|
|
30
|
+
parts = urlsplit(public_url)
|
|
31
|
+
allowed.add(f"{parts.scheme}://{parts.netloc}".lower())
|
|
32
|
+
if host:
|
|
33
|
+
allowed.update({f"http://{host}".lower(), f"https://{host}".lower()})
|
|
34
|
+
return origin.lower() in allowed
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def install_write_guard(
|
|
38
|
+
app: FastAPI, *, value: str, public_url: str | None, prefix: str = "/api"
|
|
39
|
+
) -> None:
|
|
40
|
+
"""Refuse a write under ``prefix`` unless it plainly comes from the application's own pages.
|
|
41
|
+
|
|
42
|
+
Every write must carry ``X-Requested-With: <value>``, and any Origin it has must be the
|
|
43
|
+
application's own; otherwise it is answered 403 with ``missing_write_header`` or
|
|
44
|
+
``foreign_origin``. With a SameSite=Lax session cookie this is the second of two locks
|
|
45
|
+
against cross-site writes.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
@app.middleware("http")
|
|
49
|
+
async def guard(
|
|
50
|
+
request: Request, call_next: Callable[[Request], Awaitable[Response]]
|
|
51
|
+
) -> Response:
|
|
52
|
+
if request.method in WRITES and request.url.path.startswith(f"{prefix}/"):
|
|
53
|
+
if request.headers.get(WRITE_HEADER) != value:
|
|
54
|
+
return JSONResponse({"detail": "missing_write_header"}, status_code=403)
|
|
55
|
+
if not origin_allowed(
|
|
56
|
+
request.headers.get("origin"), request.headers.get("host"), public_url
|
|
57
|
+
):
|
|
58
|
+
return JSONResponse({"detail": "foreign_origin"}, status_code=403)
|
|
59
|
+
return await call_next(request)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
#: Headers added to every response that does not set them itself.
|
|
63
|
+
SECURITY_HEADERS = {
|
|
64
|
+
"X-Content-Type-Options": "nosniff",
|
|
65
|
+
"Referrer-Policy": "same-origin",
|
|
66
|
+
"Content-Security-Policy": "frame-ancestors 'none'",
|
|
67
|
+
"X-Frame-Options": "DENY",
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def install_security_headers(app: FastAPI) -> None:
|
|
72
|
+
"""Add :data:`SECURITY_HEADERS` to every response that has not set them itself.
|
|
73
|
+
|
|
74
|
+
Responses are never sniffed into another type, never framed by another site, and send their
|
|
75
|
+
URL as a referrer only to the application itself. A response that sets one of these headers
|
|
76
|
+
keeps its own, so a route that needs a fuller Content-Security-Policy can send one.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
@app.middleware("http")
|
|
80
|
+
async def secure(
|
|
81
|
+
request: Request, call_next: Callable[[Request], Awaitable[Response]]
|
|
82
|
+
) -> Response:
|
|
83
|
+
response = await call_next(request)
|
|
84
|
+
for name, value in SECURITY_HEADERS.items():
|
|
85
|
+
response.headers.setdefault(name, value)
|
|
86
|
+
return response
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""The endpoint a container's health probe calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Awaitable, Callable
|
|
7
|
+
|
|
8
|
+
from fastapi import APIRouter, Request
|
|
9
|
+
from fastapi.responses import JSONResponse
|
|
10
|
+
from pydantic import BaseModel
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Health(BaseModel):
|
|
16
|
+
"""The application's state as the health probe sees it."""
|
|
17
|
+
|
|
18
|
+
status: str
|
|
19
|
+
database: str
|
|
20
|
+
version: str
|
|
21
|
+
#: The commit the running image was built from, when it was built by CI.
|
|
22
|
+
revision: str | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def health_router(
|
|
26
|
+
check_database: Callable[[Request], Awaitable[None]],
|
|
27
|
+
*,
|
|
28
|
+
version: str,
|
|
29
|
+
revision: str | None = None,
|
|
30
|
+
) -> APIRouter:
|
|
31
|
+
"""A router with ``GET /health``, unauthenticated, that asks the database before answering.
|
|
32
|
+
|
|
33
|
+
``check_database`` runs a trivial query (``SELECT 1``) and raises when the database cannot
|
|
34
|
+
answer. A process that answers while its database is unreachable is not healthy, so that is
|
|
35
|
+
a 503 with ``database: unreachable``; ``python -m jigkit.healthcheck URL --expect
|
|
36
|
+
database=connected`` then fails either way.
|
|
37
|
+
"""
|
|
38
|
+
router = APIRouter(tags=["health"])
|
|
39
|
+
|
|
40
|
+
@router.get("/health", response_model=Health, responses={503: {"model": Health}})
|
|
41
|
+
async def health(request: Request) -> Health | JSONResponse:
|
|
42
|
+
"""Report that the process is up and its database answers."""
|
|
43
|
+
try:
|
|
44
|
+
await check_database(request)
|
|
45
|
+
except Exception:
|
|
46
|
+
logger.exception("health check: the database did not answer")
|
|
47
|
+
down = Health(
|
|
48
|
+
status="error", database="unreachable", version=version, revision=revision
|
|
49
|
+
)
|
|
50
|
+
return JSONResponse(down.model_dump(), status_code=503)
|
|
51
|
+
return Health(status="ok", database="connected", version=version, revision=revision)
|
|
52
|
+
|
|
53
|
+
return router
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""The web app manifest: what a phone needs to add the application to its home screen."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Mapping
|
|
6
|
+
|
|
7
|
+
from fastapi.responses import JSONResponse
|
|
8
|
+
|
|
9
|
+
#: The PNG icons a manifest lists, by size; the largest is also offered as maskable.
|
|
10
|
+
ICON_SIZES = (192, 512)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def preferred_language(accept_language: str | None, languages: Iterable[str], default: str) -> str:
|
|
14
|
+
"""The first of ``languages`` an Accept-Language header asks for, by primary subtag.
|
|
15
|
+
|
|
16
|
+
``pt-BR`` and ``pt`` both choose ``pt-PT`` when that is the offered Portuguese. Quality
|
|
17
|
+
values are not weighed; browsers list languages in order of preference anyway.
|
|
18
|
+
"""
|
|
19
|
+
offered = {language.split("-")[0].lower(): language for language in languages}
|
|
20
|
+
for part in (accept_language or "").split(","):
|
|
21
|
+
tag = part.split(";")[0].strip().lower()
|
|
22
|
+
if not tag:
|
|
23
|
+
continue
|
|
24
|
+
match = offered.get(tag.split("-")[0])
|
|
25
|
+
if match is not None:
|
|
26
|
+
return match
|
|
27
|
+
return default
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def web_manifest(
|
|
31
|
+
*,
|
|
32
|
+
name: str,
|
|
33
|
+
description: str,
|
|
34
|
+
lang: str,
|
|
35
|
+
background_color: str,
|
|
36
|
+
theme_color: str,
|
|
37
|
+
short_name: str | None = None,
|
|
38
|
+
icon: str = "/icons/icon-{size}.png",
|
|
39
|
+
) -> dict[str, object]:
|
|
40
|
+
"""A manifest for an application served from the root of its origin.
|
|
41
|
+
|
|
42
|
+
``icon`` is a path pattern with ``{size}``. The largest icon is offered as maskable too: an
|
|
43
|
+
icon drawn to keep to its centre survives a launcher's crop whole.
|
|
44
|
+
"""
|
|
45
|
+
icons: list[Mapping[str, str]] = [
|
|
46
|
+
{"src": icon.format(size=s), "sizes": f"{s}x{s}", "type": "image/png", "purpose": "any"}
|
|
47
|
+
for s in ICON_SIZES
|
|
48
|
+
]
|
|
49
|
+
largest = max(ICON_SIZES)
|
|
50
|
+
icons.append(
|
|
51
|
+
{
|
|
52
|
+
"src": icon.format(size=largest),
|
|
53
|
+
"sizes": f"{largest}x{largest}",
|
|
54
|
+
"type": "image/png",
|
|
55
|
+
"purpose": "maskable",
|
|
56
|
+
}
|
|
57
|
+
)
|
|
58
|
+
return {
|
|
59
|
+
"name": name,
|
|
60
|
+
"short_name": short_name or name,
|
|
61
|
+
"description": description,
|
|
62
|
+
"lang": lang,
|
|
63
|
+
"start_url": "/",
|
|
64
|
+
"scope": "/",
|
|
65
|
+
"display": "standalone",
|
|
66
|
+
"background_color": background_color,
|
|
67
|
+
"theme_color": theme_color,
|
|
68
|
+
"icons": icons,
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def manifest_response(manifest: Mapping[str, object]) -> JSONResponse:
|
|
73
|
+
"""The manifest as a response a browser will re-check on every load.
|
|
74
|
+
|
|
75
|
+
The browser fetches it itself, with no session, so it varies by Accept-Language rather than
|
|
76
|
+
by account; and an application that can be renamed must not leave the old name cached on a
|
|
77
|
+
home screen.
|
|
78
|
+
"""
|
|
79
|
+
return JSONResponse(
|
|
80
|
+
dict(manifest),
|
|
81
|
+
media_type="application/manifest+json",
|
|
82
|
+
headers={
|
|
83
|
+
"Cache-Control": "no-cache",
|
|
84
|
+
"Content-Language": str(manifest.get("lang", "")),
|
|
85
|
+
"Vary": "Accept-Language",
|
|
86
|
+
},
|
|
87
|
+
)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Running an application with uvicorn, the way every application built on jigkit runs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import uvicorn
|
|
8
|
+
|
|
9
|
+
from jigkit.settings import AppSettings
|
|
10
|
+
|
|
11
|
+
#: Inside the container; the compose file decides what the host publishes.
|
|
12
|
+
HOST = "0.0.0.0" # noqa: S104
|
|
13
|
+
PORT = 8000
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def serve(
|
|
17
|
+
factory: str,
|
|
18
|
+
settings: AppSettings,
|
|
19
|
+
*,
|
|
20
|
+
reload: bool = False,
|
|
21
|
+
host: str = HOST,
|
|
22
|
+
port: int = PORT,
|
|
23
|
+
**uvicorn_options: Any,
|
|
24
|
+
) -> None:
|
|
25
|
+
"""Serve the application ``factory`` builds, an import string such as ``myapp.api:create_app``.
|
|
26
|
+
|
|
27
|
+
- The logging the application configured is kept (``log_config=None``) instead of
|
|
28
|
+
uvicorn's own handlers replacing it.
|
|
29
|
+
- X-Forwarded-For and X-Forwarded-Proto are believed only from
|
|
30
|
+
``settings.forwarded_allow_ips``: they decide the client address a login throttle counts
|
|
31
|
+
and whether a session cookie is Secure, so believing them from anyone lets a client
|
|
32
|
+
choose both.
|
|
33
|
+
- No ``Server`` header names the server software.
|
|
34
|
+
- ``reload`` restarts on source changes, for development.
|
|
35
|
+
|
|
36
|
+
Further keyword arguments go to ``uvicorn.run``.
|
|
37
|
+
"""
|
|
38
|
+
options: dict[str, Any] = {
|
|
39
|
+
"factory": True,
|
|
40
|
+
"host": host,
|
|
41
|
+
"port": port,
|
|
42
|
+
"log_config": None,
|
|
43
|
+
"proxy_headers": True,
|
|
44
|
+
"forwarded_allow_ips": settings.forwarded_allow_ips,
|
|
45
|
+
"server_header": False,
|
|
46
|
+
"reload": reload,
|
|
47
|
+
}
|
|
48
|
+
options.update(uvicorn_options)
|
|
49
|
+
uvicorn.run(factory, **options)
|