spatial-computing 0.14.0__tar.gz → 0.15.0__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.
- {spatial_computing-0.14.0/spatial_computing.egg-info → spatial_computing-0.15.0}/PKG-INFO +12 -2
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/README.md +11 -1
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/pyproject.toml +2 -1
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/__init__.py +1 -1
- spatial_computing-0.15.0/spatial/ai/llm.py +43 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/cli.py +16 -1
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/auth.py +21 -5
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/registry.py +4 -1
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fleet/hub.py +21 -7
- spatial_computing-0.15.0/spatial/platform/__init__.py +5 -0
- spatial_computing-0.15.0/spatial/platform/billing.py +101 -0
- spatial_computing-0.15.0/spatial/platform/db.py +61 -0
- spatial_computing-0.15.0/spatial/platform/security.py +79 -0
- spatial_computing-0.15.0/spatial/platform/server.py +386 -0
- spatial_computing-0.15.0/spatial/platform/service.py +666 -0
- spatial_computing-0.15.0/spatial/platform/static/app.js +367 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/DMMono-normal-400.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/DMMono-normal-500.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/InstrumentSerif-italic-400.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/InstrumentSerif-normal-400.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/Inter-normal-400.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/Inter-normal-500.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts/Inter-normal-600.woff2 +0 -0
- spatial_computing-0.15.0/spatial/platform/static/fonts.css +56 -0
- spatial_computing-0.15.0/spatial/platform/static/index.html +10 -0
- spatial_computing-0.15.0/spatial/platform/static/logo.svg +1 -0
- spatial_computing-0.15.0/spatial/platform/static/style.css +75 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/planner.py +114 -4
- {spatial_computing-0.14.0 → spatial_computing-0.15.0/spatial_computing.egg-info}/PKG-INFO +12 -2
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial_computing.egg-info/SOURCES.txt +20 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_fleet.py +21 -0
- spatial_computing-0.15.0/tests/test_platform.py +508 -0
- spatial_computing-0.15.0/tests/test_runtime.py +122 -0
- spatial_computing-0.14.0/tests/test_runtime.py +0 -68
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/LICENSE +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/setup.cfg +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/ai/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/ai/kvcache.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/cost.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/detect.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/monitor.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/scheduler.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/taskqueue.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/worker.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/compute/workloads.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/energy.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/ledger.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/model.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/core/protocol.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fabric/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fabric/cuda.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fabric/devices.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fabric/metal.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fabric/metal_mandel.swift +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fabric/metal_run.swift +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fleet/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fleet/agent.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fleet/alerts.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fleet/dashboard.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/fleet/ha.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/holographic/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/holographic/cgh.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/holographic/model.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/intelligence/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/intelligence/predictor.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/interconnect/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/interconnect/collectives.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/interconnect/comm.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/interconnect/model.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/interconnect/tasks.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/kernel/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/kernel/dsl.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/kernel/library.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/memory/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/memory/fararray.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/memory/pageserver.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/memory/secure.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/memory/shared.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/memory/tiered.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/__main__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/backends/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/codegen.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/compiler.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/ir.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/lexer.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/parser.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/qir.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/runtime.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/q/sim.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/envs.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/inspect.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/microvm.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/runner.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/runtime/toolchain.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/scientific/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/scientific/jobs.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/simulation/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/simulation/heat.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/simulation/nbody.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/unified/__init__.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/unified/model.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/unified/planner.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial/unified/providers.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial_computing.egg-info/entry_points.txt +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial_computing.egg-info/requires.txt +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/spatial_computing.egg-info/top_level.txt +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_auth.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_compute.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_core.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_dashboard.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_domains.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_engines.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_fabric.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_ha.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_hardening.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_interconnect.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_kernel.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_memory.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_optimizer.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_q.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_quorum.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_unified.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_v02.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_v03.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_v05.py +0 -0
- {spatial_computing-0.14.0 → spatial_computing-0.15.0}/tests/test_v07.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: spatial-computing
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.15.0
|
|
4
4
|
Summary: Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)
|
|
5
5
|
Author: Spatial Computing contributors
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -37,7 +37,7 @@ Dynamic: license-file
|
|
|
37
37
|
|
|
38
38
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
39
39
|
|
|
40
|
-
> **Status: v0.
|
|
40
|
+
> **Status: v0.15.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
41
41
|
|
|
42
42
|
[Français](README.fr.md)
|
|
43
43
|
|
|
@@ -68,6 +68,16 @@ curl -o busybox-x86_64 https://busybox.net/downloads/binaries/1.35.0-x86_64-linu
|
|
|
68
68
|
shasum -a 256 -c SHA256SUMS
|
|
69
69
|
```
|
|
70
70
|
|
|
71
|
+
## Console (accounts, apps, API keys, jobs, billing)
|
|
72
|
+
```bash
|
|
73
|
+
spatial token init --master-key-file hub.key
|
|
74
|
+
spatial serve hub --master-key-file hub.key --port 7700 --usage-file usage.jsonl --revoked-file revoked.txt
|
|
75
|
+
spatial platform serve --master-key-file hub.key --hub 127.0.0.1:7700 --usage-file usage.jsonl --revoked-file revoked.txt
|
|
76
|
+
# open http://127.0.0.1:8090/ : sign up, create an app, create a node key and a client key
|
|
77
|
+
spatial agent --hub 127.0.0.1:7700 --token-file node.tok # the machine appears in Fleet; submit jobs from Jobs
|
|
78
|
+
```
|
|
79
|
+
Production (hub, console, HTTPS): `docker compose --env-file deploy/.env up -d --build`. See [docs/PLATFORM.md](docs/PLATFORM.md) and [docs/DEPLOY.md](docs/DEPLOY.md).
|
|
80
|
+
|
|
71
81
|
## Use
|
|
72
82
|
|
|
73
83
|
```bash
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
One objective for the whole infrastructure: get every job done correctly at the lowest cost, and prove it. Spatial Computing prices every way to run a job across compute, memory, runtime, quantum, AI, science and a fleet of machines, picks the cheapest, and records the estimate next to what really happened. A gain is claimed only when it is measured. It does not add RAM, cores or GPUs: it compares execution strategies on the hardware you have, trades one resource for another in numbers, and says plainly what it cannot do.
|
|
6
6
|
|
|
7
|
-
> **Status: v0.
|
|
7
|
+
> **Status: v0.15.0, early-stage open-source toolkit.** Everything here was built and measured on a single 2017 MacBook Pro (Intel i7-7660U, 2 cores, 16 GB). Nothing has been proven on a second machine, a data-center GPU or a real quantum computer. See [Limitations](docs/LIMITATIONS.md) and the [site](https://spatial-computing-ecru.vercel.app).
|
|
8
8
|
|
|
9
9
|
[Français](README.fr.md)
|
|
10
10
|
|
|
@@ -35,6 +35,16 @@ curl -o busybox-x86_64 https://busybox.net/downloads/binaries/1.35.0-x86_64-linu
|
|
|
35
35
|
shasum -a 256 -c SHA256SUMS
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
## Console (accounts, apps, API keys, jobs, billing)
|
|
39
|
+
```bash
|
|
40
|
+
spatial token init --master-key-file hub.key
|
|
41
|
+
spatial serve hub --master-key-file hub.key --port 7700 --usage-file usage.jsonl --revoked-file revoked.txt
|
|
42
|
+
spatial platform serve --master-key-file hub.key --hub 127.0.0.1:7700 --usage-file usage.jsonl --revoked-file revoked.txt
|
|
43
|
+
# open http://127.0.0.1:8090/ : sign up, create an app, create a node key and a client key
|
|
44
|
+
spatial agent --hub 127.0.0.1:7700 --token-file node.tok # the machine appears in Fleet; submit jobs from Jobs
|
|
45
|
+
```
|
|
46
|
+
Production (hub, console, HTTPS): `docker compose --env-file deploy/.env up -d --build`. See [docs/PLATFORM.md](docs/PLATFORM.md) and [docs/DEPLOY.md](docs/DEPLOY.md).
|
|
47
|
+
|
|
38
48
|
## Use
|
|
39
49
|
|
|
40
50
|
```bash
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "spatial-computing"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.15.0"
|
|
8
8
|
description = "Spatial Computing: open-source infrastructure efficiency toolkit. Measure, decide, prove (compute, tiered memory, runtime routing, hybrid quantum language)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "Apache-2.0"
|
|
@@ -33,6 +33,7 @@ include = ["spatial*"]
|
|
|
33
33
|
|
|
34
34
|
[tool.setuptools.package-data]
|
|
35
35
|
"spatial.fabric" = ["*.swift"]
|
|
36
|
+
"spatial.platform" = ["static/*", "static/fonts/*"]
|
|
36
37
|
|
|
37
38
|
[tool.pytest.ini_options]
|
|
38
39
|
testpaths = ["tests"]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Client for a real inference server that speaks the llama.cpp HTTP API (llama-server). Used to measure what the toy
|
|
2
|
+
KV-cache model only simulates: how much a cached prompt prefix really saves on a real model.
|
|
3
|
+
|
|
4
|
+
Only the standard library; the server is yours (a container, a local binary). Nothing is sent anywhere else.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import urllib.request
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class LlmError(Exception):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class LlamaServer:
|
|
17
|
+
def __init__(self, base_url: str = "http://127.0.0.1:8081", timeout: float = 600.0):
|
|
18
|
+
if not base_url.startswith(("http://127.0.0.1", "http://localhost", "https://")):
|
|
19
|
+
raise LlmError("refusing a plain-HTTP non-loopback server URL (use https or a loopback address)")
|
|
20
|
+
self.base, self.timeout = base_url.rstrip("/"), timeout
|
|
21
|
+
|
|
22
|
+
def _post(self, path: str, body: dict) -> dict:
|
|
23
|
+
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}, method="POST")
|
|
24
|
+
try:
|
|
25
|
+
return json.load(urllib.request.urlopen(req, timeout=self.timeout))
|
|
26
|
+
except Exception as e:
|
|
27
|
+
raise LlmError(f"{type(e).__name__}: {e}") from e
|
|
28
|
+
|
|
29
|
+
def healthy(self) -> bool:
|
|
30
|
+
try:
|
|
31
|
+
return json.load(urllib.request.urlopen(self.base + "/health", timeout=5)).get("status") == "ok"
|
|
32
|
+
except Exception:
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
def complete(self, prompt: str, n_predict: int = 8, cache_prompt: bool = True, seed: int = 0) -> dict:
|
|
36
|
+
"""One greedy completion. Returns the text and the server's own timings (prompt tokens processed, cached
|
|
37
|
+
tokens reused, milliseconds for the prompt and for the generated tokens)."""
|
|
38
|
+
r = self._post("/completion", {"prompt": prompt, "n_predict": n_predict, "temperature": 0, "top_k": 1, "seed": seed,
|
|
39
|
+
"cache_prompt": cache_prompt, "stream": False})
|
|
40
|
+
t = r.get("timings", {})
|
|
41
|
+
return {"text": r.get("content", ""), "prompt_tokens_processed": t.get("prompt_n"), "cached_tokens": t.get("cache_n", r.get("tokens_cached")),
|
|
42
|
+
"prompt_ms": t.get("prompt_ms"), "predicted_n": t.get("predicted_n"), "predicted_ms": t.get("predicted_ms"),
|
|
43
|
+
"total_prompt_tokens": r.get("tokens_evaluated")}
|
|
@@ -103,6 +103,13 @@ def cmd_agent(a):
|
|
|
103
103
|
return 0
|
|
104
104
|
|
|
105
105
|
|
|
106
|
+
def cmd_platform(a):
|
|
107
|
+
from .platform import server
|
|
108
|
+
rest = [x for x in a.rest if x != "serve"] if a.rest[:1] == ["serve"] else a.rest
|
|
109
|
+
server.main(rest)
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
106
113
|
def cmd_dashboard(a):
|
|
107
114
|
from .fleet.dashboard import Dashboard
|
|
108
115
|
d = Dashboard(a.hub, _read_token(a.token_file), port=a.port, min_severity=a.min_severity, webhook=a.webhook).start()
|
|
@@ -241,6 +248,7 @@ def cmd_worker(a):
|
|
|
241
248
|
cmd += ["--audit-log", a.audit_log]
|
|
242
249
|
if a.allow_remote:
|
|
243
250
|
cmd.append("--allow-remote")
|
|
251
|
+
cmd += a.extra # service-specific flags, e.g. the hub's --state-file, --usage-file, --peer
|
|
244
252
|
return subprocess.run(cmd).returncode
|
|
245
253
|
|
|
246
254
|
|
|
@@ -313,6 +321,9 @@ def main(argv=None):
|
|
|
313
321
|
p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
|
|
314
322
|
p.add_argument("--task-id", type=int)
|
|
315
323
|
p.set_defaults(fn=cmd_fleet)
|
|
324
|
+
p = sub.add_parser("platform", help="account service: sign up, sign in, apps, API keys, usage, billing (`spatial platform serve --help`)")
|
|
325
|
+
p.add_argument("rest", nargs=argparse.REMAINDER)
|
|
326
|
+
p.set_defaults(fn=cmd_platform)
|
|
316
327
|
p = sub.add_parser("dashboard", help="read-only fleet dashboard in your browser (served on 127.0.0.1 only, behind a random key)")
|
|
317
328
|
p.add_argument("--hub", required=True, help="host:port, or h1:p,h2:p for a hub pair")
|
|
318
329
|
p.add_argument("--token-file", required=True, help="scoped token with fleet:read")
|
|
@@ -335,7 +346,11 @@ def main(argv=None):
|
|
|
335
346
|
p.add_argument("--max-ops", type=int)
|
|
336
347
|
p.add_argument("--max-bytes", type=int)
|
|
337
348
|
p.set_defaults(fn=cmd_token)
|
|
338
|
-
a = ap.
|
|
349
|
+
a, extra = ap.parse_known_args(argv)
|
|
350
|
+
if getattr(a, "cmd", None) == "serve":
|
|
351
|
+
a.extra = extra # forwarded to the service
|
|
352
|
+
elif extra:
|
|
353
|
+
ap.error("unrecognized arguments: " + " ".join(extra))
|
|
339
354
|
if getattr(a, "cmd", None) == "serve" and bool(a.token_file) == bool(a.master_key_file):
|
|
340
355
|
ap.error("serve needs exactly one of --token-file or --master-key-file")
|
|
341
356
|
try:
|
|
@@ -10,7 +10,8 @@ Scopes are strings such as "run:mandel_numba", "mem:read", "mem:write", "exec:el
|
|
|
10
10
|
"*" matches a prefix ("run:*", "*"). Services call require(scope) before acting.
|
|
11
11
|
Every request (allowed or denied) is appended to a hash-chained audit ledger.
|
|
12
12
|
|
|
13
|
-
Limits:
|
|
13
|
+
Limits: usage counters live in the server process (restart resets them); revocation lives in memory unless a
|
|
14
|
+
revoked-names file is given (one name per line, re-read when it changes);
|
|
14
15
|
a stolen token works until it expires or is revoked.
|
|
15
16
|
"""
|
|
16
17
|
from __future__ import annotations
|
|
@@ -82,13 +83,28 @@ def _unb64(s: str) -> bytes:
|
|
|
82
83
|
|
|
83
84
|
|
|
84
85
|
class Authorizer:
|
|
85
|
-
def __init__(self, master_key: bytes, audit: Ledger | None = None):
|
|
86
|
+
def __init__(self, master_key: bytes, audit: Ledger | None = None, revoked_file=None):
|
|
86
87
|
if len(master_key) < 16:
|
|
87
88
|
raise ValueError("master key must be at least 16 bytes")
|
|
88
89
|
self._master = master_key
|
|
89
90
|
self.audit = audit
|
|
90
91
|
self._revoked: set[str] = set()
|
|
91
92
|
self._seen: dict[str, Principal] = {}
|
|
93
|
+
self._revoked_file, self._revoked_mtime = revoked_file, None # one name per line; edited by the account service
|
|
94
|
+
|
|
95
|
+
def _file_revoked(self, name: str) -> bool:
|
|
96
|
+
if not self._revoked_file:
|
|
97
|
+
return False
|
|
98
|
+
import os
|
|
99
|
+
try:
|
|
100
|
+
m = os.stat(self._revoked_file).st_mtime_ns
|
|
101
|
+
except OSError:
|
|
102
|
+
return False
|
|
103
|
+
if m != self._revoked_mtime:
|
|
104
|
+
with open(self._revoked_file) as f:
|
|
105
|
+
self._file_names = {l.strip() for l in f if l.strip()}
|
|
106
|
+
self._revoked_mtime = m
|
|
107
|
+
return name in getattr(self, "_file_names", ())
|
|
92
108
|
|
|
93
109
|
def _sig(self, payload: str) -> str:
|
|
94
110
|
return hmac.new(self._master, b"sig|" + payload.encode(), hashlib.sha256).hexdigest()[:32]
|
|
@@ -121,7 +137,7 @@ class Authorizer:
|
|
|
121
137
|
body = json.loads(_unb64(payload))
|
|
122
138
|
if body["e"] < time.time():
|
|
123
139
|
raise AuthError("credential expired")
|
|
124
|
-
if body["n"] in self._revoked:
|
|
140
|
+
if body["n"] in self._revoked or self._file_revoked(body["n"]):
|
|
125
141
|
raise AuthError("credential revoked")
|
|
126
142
|
if cred not in self._seen:
|
|
127
143
|
self._seen[cred] = Principal(body["n"], tuple(body["s"]), body["e"], body.get("o"), body.get("b"), cred)
|
|
@@ -164,7 +180,7 @@ def init_master_key(path) -> None:
|
|
|
164
180
|
f.write(os.urandom(32))
|
|
165
181
|
|
|
166
182
|
|
|
167
|
-
def authorizer_from_file(master_key_file, audit_path=None) -> Authorizer:
|
|
183
|
+
def authorizer_from_file(master_key_file, audit_path=None, revoked_file=None) -> Authorizer:
|
|
168
184
|
from pathlib import Path
|
|
169
185
|
audit = Ledger(audit_path) if audit_path else Ledger(Path.home() / ".spatial" / "audit.jsonl")
|
|
170
|
-
return Authorizer(Path(master_key_file).read_bytes(), audit)
|
|
186
|
+
return Authorizer(Path(master_key_file).read_bytes(), audit, revoked_file)
|
|
@@ -38,6 +38,9 @@ ENGINES: list[Engine] = [
|
|
|
38
38
|
Engine("kernel", "Portable kernels", "spatial.kernel", Status.FIRST_COMPONENTS,
|
|
39
39
|
"tests/test_kernel.py, benchmarks/bench_kernel.py (planner right 4 of 6; integer kernel bit-identical CPU vs Metal)",
|
|
40
40
|
"CUDA C and HIP generated, never compiled or run; two kernel shapes (2-D map, whole-grid sum with shared memory), no tiling or tensor cores"),
|
|
41
|
+
Engine("platform", "Console and account service", "spatial.platform", Status.FIRST_COMPONENTS,
|
|
42
|
+
"tests/test_platform.py (14 tests, real hub and agent), a driven browser session",
|
|
43
|
+
"one process with SQLite; no teams, roles, two-factor or e-mail verification; payments tested against a fake Stripe API only; default prices are an example"),
|
|
41
44
|
Engine("planner", "Spatial Planner (the one objective)", "spatial.unified", Status.OPERATIONAL_PROTOTYPE,
|
|
42
45
|
"tests/test_unified.py",
|
|
43
46
|
"estimates come from probes and measured constants on one machine; calibration is a median of past ratios; no learned model; fleet and QPU pricing need the caller's prices"),
|
|
@@ -46,7 +49,7 @@ ENGINES: list[Engine] = [
|
|
|
46
49
|
"validated on one machine (agents on loopback); HA: active/standby for two hubs, majority election (election safety, no replicated log) for three or more, tested on one machine with simulated clocks; dashboard is read-only and local; recommendations are estimates; never applies changes by itself"),
|
|
47
50
|
Engine("runtime", "Spatial Runtime Engine", "spatial.runtime", Status.OPERATIONAL_PROTOTYPE,
|
|
48
51
|
"tests/test_runtime.py, benchmarks/bench_runtime.py",
|
|
49
|
-
"Windows
|
|
52
|
+
"Windows: one console program and one GUI window (Notepad) under Wine, nothing more; containers: static Linux ELF, tested with Docker (Colima) and Podman; no GUI streaming"),
|
|
50
53
|
Engine("q", "SPATIAL Q", "spatial.q", Status.OPERATIONAL_PROTOTYPE,
|
|
51
54
|
"tests/test_q.py, benchmarks/bench_q.py",
|
|
52
55
|
"no real QPU executed (OpenQASM 3 and QIR export only); simulator limited by RAM"),
|
|
@@ -55,6 +55,7 @@ class Hub:
|
|
|
55
55
|
self.ha = None # a fleet.ha controller, if any
|
|
56
56
|
self.max_finished, self.max_affinity = max_finished, max_affinity # bounded memory: the soak test showed the hub grew without limit
|
|
57
57
|
self._finished: deque = deque() # ids of done/failed tasks, oldest first
|
|
58
|
+
self.usage_path = None # JSONL file: one line per finished task, read by the account service for billing
|
|
58
59
|
|
|
59
60
|
# ------------------------------------------------------------------ identity
|
|
60
61
|
@staticmethod
|
|
@@ -120,13 +121,15 @@ class Hub:
|
|
|
120
121
|
running = sum(now - t.get("started", now) for t in self.tasks.values() if t["state"] == "running" and t["tenant"] == tenant)
|
|
121
122
|
return (self.usage.get(tenant, 0.0) + running) / self.weights.get(tenant, 1.0)
|
|
122
123
|
|
|
123
|
-
def queue_view(self, recent: int = 12) -> dict:
|
|
124
|
-
"""Counts per state plus the most recent tasks (no parameters or results: those can be large).
|
|
124
|
+
def queue_view(self, recent: int = 12, tenants: list | None = None) -> dict:
|
|
125
|
+
"""Counts per state plus the most recent tasks (no parameters or results: those can be large).
|
|
126
|
+
`tenants` restricts both to those tenants."""
|
|
125
127
|
with self._lock:
|
|
128
|
+
pool = [t for t in self.tasks.values() if tenants is None or t["tenant"] in tenants]
|
|
126
129
|
counts: dict[str, int] = {}
|
|
127
|
-
for t in
|
|
130
|
+
for t in pool:
|
|
128
131
|
counts[t["state"]] = counts.get(t["state"], 0) + 1
|
|
129
|
-
last = sorted(
|
|
132
|
+
last = sorted(pool, key=lambda t: t["id"], reverse=True)[:min(int(recent), 500)]
|
|
130
133
|
return {"counts": counts, "recent": [{k: t.get(k) for k in ("id", "workload", "state", "node", "tenant", "gang", "wall_s")} for t in last]}
|
|
131
134
|
|
|
132
135
|
def tenants(self) -> list[dict]:
|
|
@@ -245,6 +248,13 @@ class Hub:
|
|
|
245
248
|
self.affinity[t["needs"]["affinity"]] = node
|
|
246
249
|
while len(self.affinity) > self.max_affinity:
|
|
247
250
|
self.affinity.pop(next(iter(self.affinity)))
|
|
251
|
+
if self.usage_path:
|
|
252
|
+
try:
|
|
253
|
+
with open(self.usage_path, "a") as f:
|
|
254
|
+
f.write(json.dumps({"ts": self.clock(), "tenant": t["tenant"], "task": task_id, "workload": t["workload"], "node": node,
|
|
255
|
+
"ok": bool(ok), "wall_s": wall_s if wall_s is not None else 0.0}) + "\n")
|
|
256
|
+
except OSError:
|
|
257
|
+
pass # metering must never break scheduling; the gap is visible in the file
|
|
248
258
|
self._finished.append(task_id)
|
|
249
259
|
while len(self._finished) > self.max_finished: # forget the oldest finished tasks (and gangs with no task left)
|
|
250
260
|
self.tasks.pop(self._finished.popleft(), None)
|
|
@@ -422,7 +432,7 @@ def _avg(xs):
|
|
|
422
432
|
def _tenant(h: dict) -> str:
|
|
423
433
|
"""With scoped credentials the tenant is the credential name (it cannot be spoofed); otherwise the declared one."""
|
|
424
434
|
p = auth.current()
|
|
425
|
-
t = p.name if p is not None else h.get("tenant", "default")
|
|
435
|
+
t = p.name.split(":", 1)[0] if p is not None else h.get("tenant", "default") # "app7:k3" (app 7, key 3) -> tenant "app7"
|
|
426
436
|
return str(t)[:128]
|
|
427
437
|
|
|
428
438
|
|
|
@@ -464,7 +474,8 @@ def make_handler(hub: Hub):
|
|
|
464
474
|
return hub.submit_gang(h["workload"], h["params_list"], h.get("needs"), h.get("priority", 10), _tenant(h)), b""
|
|
465
475
|
if op == "queue":
|
|
466
476
|
require("fleet:read")
|
|
467
|
-
|
|
477
|
+
ten = h.get("tenants")
|
|
478
|
+
return hub.queue_view(int(h.get("recent", 12)), [str(x) for x in ten] if isinstance(ten, list) else None), b""
|
|
468
479
|
if op == "tenants":
|
|
469
480
|
require("fleet:read")
|
|
470
481
|
return {"tenants": hub.tenants()}, b""
|
|
@@ -499,6 +510,8 @@ def main():
|
|
|
499
510
|
ap.add_argument("--state-file", help="save tasks, queue, tenant usage here every 5 s and reload it at start")
|
|
500
511
|
ap.add_argument("--peer", action="append", default=[], help="host:port of another hub (repeatable): active/standby with automatic promotion")
|
|
501
512
|
ap.add_argument("--peer-token-file", help="token this hub presents to its peers (scope fleet:replicate); default: --token-file")
|
|
513
|
+
ap.add_argument("--usage-file", help="append one JSON line per finished task (tenant, workload, wall_s) for metering and billing")
|
|
514
|
+
ap.add_argument("--revoked-file", help="credential names revoked by the account service, one per line")
|
|
502
515
|
ap.add_argument("--max-finished", type=int, default=5000, help="finished tasks kept in memory (older ones are forgotten)")
|
|
503
516
|
ap.add_argument("--name", default="hub", help="this hub's name (HA tie-break: the smaller name stays active)")
|
|
504
517
|
ap.add_argument("--fail-after", type=float, default=6.0, help="seconds without an active peer before a standby promotes itself")
|
|
@@ -506,9 +519,10 @@ def main():
|
|
|
506
519
|
if bool(a.token_file) == bool(a.master_key_file):
|
|
507
520
|
raise SystemExit("give exactly one of --token-file or --master-key-file")
|
|
508
521
|
srv, hub = serve_hub(Path(a.token_file).read_bytes() if a.token_file else None, a.host, a.port, a.allow_remote,
|
|
509
|
-
authorizer_from_file(a.master_key_file, a.audit_log) if a.master_key_file else None,
|
|
522
|
+
authorizer_from_file(a.master_key_file, a.audit_log, a.revoked_file) if a.master_key_file else None,
|
|
510
523
|
ledger=Ledger(a.decision_log))
|
|
511
524
|
hub.max_finished = a.max_finished
|
|
525
|
+
hub.usage_path = a.usage_file
|
|
512
526
|
if a.state_file:
|
|
513
527
|
print("restored", hub.load(a.state_file), flush=True)
|
|
514
528
|
if a.peer:
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""Account and billing service for Spatial Computing: sign up, sign in, apps linked to the infrastructure,
|
|
2
|
+
API keys (scoped hub credentials), usage metering, invoices and payment.
|
|
3
|
+
|
|
4
|
+
Run it: spatial platform serve --master-key-file hub.key --hub HOST:PORT --usage-file usage.jsonl
|
|
5
|
+
"""
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Pricing, usage rating and payment.
|
|
2
|
+
|
|
3
|
+
PRICING IS A CONFIGURATION, NOT A FACT: the defaults below are an example price list so the dashboard has
|
|
4
|
+
something to show. Set your real prices with --pricing-file (JSON) before charging anybody.
|
|
5
|
+
|
|
6
|
+
Payment goes through Stripe Checkout when STRIPE_SECRET_KEY is set. Without it, the "Pay" action is
|
|
7
|
+
refused with a clear message: nothing is ever marked paid without a payment provider confirming it.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import hmac
|
|
13
|
+
import json
|
|
14
|
+
import time
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
DEFAULT_PRICING = {
|
|
20
|
+
"currency": "usd",
|
|
21
|
+
"note": "Example price list: set your own with --pricing-file before charging anyone.",
|
|
22
|
+
"free_compute_hours_per_month": 1.0,
|
|
23
|
+
"compute_usd_per_hour": 0.10, # per hour of task wall time on the fleet
|
|
24
|
+
"min_invoice_usd": 0.50, # below this the period carries over (no tiny charges)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Pricing:
|
|
30
|
+
data: dict = field(default_factory=lambda: dict(DEFAULT_PRICING))
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def load(cls, path: str | None) -> "Pricing":
|
|
34
|
+
d = dict(DEFAULT_PRICING)
|
|
35
|
+
if path:
|
|
36
|
+
d.update(json.load(open(path)))
|
|
37
|
+
return cls(d)
|
|
38
|
+
|
|
39
|
+
def rate(self, seconds_by_app: dict[int, float]) -> dict:
|
|
40
|
+
"""Cost of one period. The free allowance is shared by the whole account, applied app by app in id order."""
|
|
41
|
+
free = self.data["free_compute_hours_per_month"] * 3600
|
|
42
|
+
lines, total = [], 0.0
|
|
43
|
+
for app_id in sorted(seconds_by_app):
|
|
44
|
+
sec = seconds_by_app[app_id]
|
|
45
|
+
billable = max(0.0, sec - free)
|
|
46
|
+
free = max(0.0, free - sec)
|
|
47
|
+
cost = round(billable / 3600 * self.data["compute_usd_per_hour"], 4)
|
|
48
|
+
lines.append({"app_id": app_id, "seconds": round(sec, 3), "billable_seconds": round(billable, 3), "usd": cost})
|
|
49
|
+
total += cost
|
|
50
|
+
return {"lines": lines, "total_usd": round(total, 4)}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PaymentError(Exception):
|
|
54
|
+
pass
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Stripe:
|
|
58
|
+
"""Stripe Checkout over plain HTTPS (no SDK). `api_base` is overridable for tests."""
|
|
59
|
+
|
|
60
|
+
def __init__(self, secret_key: str | None, webhook_secret: str | None, api_base: str = "https://api.stripe.com"):
|
|
61
|
+
self.key, self.whsec, self.base = secret_key, webhook_secret, api_base
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def configured(self) -> bool:
|
|
65
|
+
return bool(self.key)
|
|
66
|
+
|
|
67
|
+
def checkout_url(self, invoice_id: int, amount_usd: float, email: str, success_url: str, cancel_url: str, currency: str = "usd") -> tuple[str, str]:
|
|
68
|
+
if not self.key:
|
|
69
|
+
raise PaymentError("payments are not configured on this server (no STRIPE_SECRET_KEY)")
|
|
70
|
+
cents = int(round(amount_usd * 100))
|
|
71
|
+
if cents < 50:
|
|
72
|
+
raise PaymentError("amount is below the payment provider's minimum")
|
|
73
|
+
form = urllib.parse.urlencode({
|
|
74
|
+
"mode": "payment", "success_url": success_url, "cancel_url": cancel_url, "customer_email": email,
|
|
75
|
+
"client_reference_id": str(invoice_id), "metadata[invoice_id]": str(invoice_id),
|
|
76
|
+
"line_items[0][quantity]": "1", "line_items[0][price_data][currency]": currency,
|
|
77
|
+
"line_items[0][price_data][unit_amount]": str(cents),
|
|
78
|
+
"line_items[0][price_data][product_data][name]": f"Spatial Computing usage, invoice {invoice_id}"}).encode()
|
|
79
|
+
req = urllib.request.Request(self.base + "/v1/checkout/sessions", data=form, method="POST",
|
|
80
|
+
headers={"Authorization": f"Bearer {self.key}", "Content-Type": "application/x-www-form-urlencoded"})
|
|
81
|
+
try:
|
|
82
|
+
r = json.load(urllib.request.urlopen(req, timeout=15))
|
|
83
|
+
except Exception as e:
|
|
84
|
+
raise PaymentError(f"payment provider error: {type(e).__name__}") from e
|
|
85
|
+
return r["url"], r["id"]
|
|
86
|
+
|
|
87
|
+
def verify_webhook(self, payload: bytes, header: str, tolerance_s: int = 300, now: float | None = None) -> dict:
|
|
88
|
+
"""Check the Stripe-Signature header (t=..,v1=hmac_sha256(secret, 't.payload')) and return the event."""
|
|
89
|
+
if not self.whsec:
|
|
90
|
+
raise PaymentError("webhook secret not configured")
|
|
91
|
+
try:
|
|
92
|
+
parts = dict(p.split("=", 1) for p in header.split(","))
|
|
93
|
+
t, sig = int(parts["t"]), parts["v1"]
|
|
94
|
+
except Exception:
|
|
95
|
+
raise PaymentError("malformed signature header")
|
|
96
|
+
expected = hmac.new(self.whsec.encode(), f"{t}.".encode() + payload, hashlib.sha256).hexdigest()
|
|
97
|
+
if not hmac.compare_digest(expected, sig):
|
|
98
|
+
raise PaymentError("bad signature")
|
|
99
|
+
if abs((now or time.time()) - t) > tolerance_s:
|
|
100
|
+
raise PaymentError("signature too old")
|
|
101
|
+
return json.loads(payload)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""SQLite store. One connection guarded by a lock: enough for one service process; swap for Postgres behind
|
|
2
|
+
the same functions when you need several."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sqlite3
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
SCHEMA = """
|
|
10
|
+
CREATE TABLE IF NOT EXISTS users(
|
|
11
|
+
id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pw_hash TEXT NOT NULL,
|
|
12
|
+
created REAL NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, failed INTEGER NOT NULL DEFAULT 0, locked_until REAL NOT NULL DEFAULT 0);
|
|
13
|
+
CREATE TABLE IF NOT EXISTS sessions(
|
|
14
|
+
token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, csrf TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, ip TEXT, ua TEXT);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS apps(
|
|
16
|
+
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',
|
|
17
|
+
budget_usd REAL, created REAL NOT NULL, deleted REAL);
|
|
18
|
+
CREATE TABLE IF NOT EXISTS api_keys(
|
|
19
|
+
id INTEGER PRIMARY KEY, app_id INTEGER NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, cred_name TEXT NOT NULL,
|
|
20
|
+
hint TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, revoked REAL);
|
|
21
|
+
CREATE TABLE IF NOT EXISTS usage(
|
|
22
|
+
id INTEGER PRIMARY KEY, app_id INTEGER NOT NULL, ts REAL NOT NULL, workload TEXT, node TEXT, ok INTEGER, seconds REAL NOT NULL);
|
|
23
|
+
CREATE INDEX IF NOT EXISTS usage_app_ts ON usage(app_id, ts);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS offsets(name TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
|
25
|
+
CREATE TABLE IF NOT EXISTS invoices(
|
|
26
|
+
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, period TEXT NOT NULL, amount_usd REAL NOT NULL, status TEXT NOT NULL,
|
|
27
|
+
lines TEXT NOT NULL, created REAL NOT NULL, paid REAL, provider_ref TEXT, UNIQUE(user_id, period));
|
|
28
|
+
CREATE TABLE IF NOT EXISTS resets(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL, used INTEGER NOT NULL DEFAULT 0);
|
|
29
|
+
CREATE TABLE IF NOT EXISTS outbox(id INTEGER PRIMARY KEY, to_addr TEXT NOT NULL, subject TEXT NOT NULL, body TEXT NOT NULL, created REAL NOT NULL, sent REAL);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS tokens(
|
|
31
|
+
id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL, token_hash TEXT UNIQUE NOT NULL, hint TEXT NOT NULL,
|
|
32
|
+
scope TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, last_used REAL, revoked REAL);
|
|
33
|
+
CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY, ts REAL NOT NULL, user_id INTEGER, kind TEXT NOT NULL, detail TEXT);
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class DB:
|
|
38
|
+
def __init__(self, path: str = ":memory:"):
|
|
39
|
+
self.conn = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
|
|
40
|
+
self.conn.row_factory = sqlite3.Row
|
|
41
|
+
self.lock = threading.RLock()
|
|
42
|
+
with self.lock:
|
|
43
|
+
self.conn.execute("PRAGMA journal_mode=WAL")
|
|
44
|
+
self.conn.execute("PRAGMA foreign_keys=ON")
|
|
45
|
+
self.conn.executescript(SCHEMA)
|
|
46
|
+
|
|
47
|
+
def q(self, sql: str, args=()) -> list[sqlite3.Row]:
|
|
48
|
+
with self.lock:
|
|
49
|
+
return self.conn.execute(sql, args).fetchall()
|
|
50
|
+
|
|
51
|
+
def one(self, sql: str, args=()):
|
|
52
|
+
r = self.q(sql, args)
|
|
53
|
+
return r[0] if r else None
|
|
54
|
+
|
|
55
|
+
def x(self, sql: str, args=()) -> int:
|
|
56
|
+
with self.lock:
|
|
57
|
+
cur = self.conn.execute(sql, args)
|
|
58
|
+
return cur.lastrowid
|
|
59
|
+
|
|
60
|
+
def event(self, user_id, kind: str, detail: str = "") -> None:
|
|
61
|
+
self.x("INSERT INTO events(ts,user_id,kind,detail) VALUES(?,?,?,?)", (time.time(), user_id, kind, detail[:500]))
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Passwords, sessions, CSRF tokens, rate limiting. Standard library only."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import base64
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import secrets
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
SCRYPT_N, SCRYPT_R, SCRYPT_P = 2 ** 14, 8, 1
|
|
14
|
+
EMAIL_RE = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,190}\.[^@\s]{2,24}$")
|
|
15
|
+
COMMON = {"password", "12345678", "123456789", "qwertyuiop", "iloveyou1", "password1", "azertyuiop", "11111111"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def hash_password(pw: str) -> str:
|
|
19
|
+
salt = os.urandom(16)
|
|
20
|
+
h = hashlib.scrypt(pw.encode(), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P, dklen=32)
|
|
21
|
+
return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${base64.b64encode(salt).decode()}${base64.b64encode(h).decode()}"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def verify_password(pw: str, stored: str) -> bool:
|
|
25
|
+
try:
|
|
26
|
+
_, n, r, p, salt, h = stored.split("$")
|
|
27
|
+
calc = hashlib.scrypt(pw.encode(), salt=base64.b64decode(salt), n=int(n), r=int(r), p=int(p), dklen=32)
|
|
28
|
+
return hmac.compare_digest(calc, base64.b64decode(h))
|
|
29
|
+
except Exception:
|
|
30
|
+
return False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
DUMMY_HASH = hash_password("dummy-password-for-timing") # verified when the account does not exist: same cost either way
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check_password_policy(pw: str, email: str = "") -> str | None:
|
|
37
|
+
if len(pw) < 10:
|
|
38
|
+
return "password must have at least 10 characters"
|
|
39
|
+
if len(pw) > 200:
|
|
40
|
+
return "password is too long"
|
|
41
|
+
if pw.lower() in COMMON or (email and pw.lower() == email.lower()):
|
|
42
|
+
return "password is too common"
|
|
43
|
+
if len(set(pw)) < 5:
|
|
44
|
+
return "password is too repetitive"
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def valid_email(e: str) -> bool:
|
|
49
|
+
return bool(EMAIL_RE.match(e))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def new_token() -> str:
|
|
53
|
+
return secrets.token_urlsafe(32)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def token_hash(t: str) -> str:
|
|
57
|
+
return hashlib.sha256(t.encode()).hexdigest()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class RateLimiter:
|
|
61
|
+
"""At most `limit` events per `window_s` per key, in memory."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, limit: int, window_s: float, clock=time.time):
|
|
64
|
+
self.limit, self.window, self.clock = limit, window_s, clock
|
|
65
|
+
self._hits: dict[str, list[float]] = {}
|
|
66
|
+
self._lock = threading.Lock()
|
|
67
|
+
|
|
68
|
+
def allow(self, key: str) -> bool:
|
|
69
|
+
now = self.clock()
|
|
70
|
+
with self._lock:
|
|
71
|
+
hits = [t for t in self._hits.get(key, []) if now - t < self.window]
|
|
72
|
+
if len(hits) >= self.limit:
|
|
73
|
+
self._hits[key] = hits
|
|
74
|
+
return False
|
|
75
|
+
hits.append(now)
|
|
76
|
+
self._hits[key] = hits
|
|
77
|
+
if len(self._hits) > 20000: # bound memory
|
|
78
|
+
self._hits = {k: v for k, v in self._hits.items() if v and now - v[-1] < self.window}
|
|
79
|
+
return True
|