spatial-computing 0.14.0__tar.gz → 0.16.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.
Files changed (138) hide show
  1. {spatial_computing-0.14.0/spatial_computing.egg-info → spatial_computing-0.16.0}/PKG-INFO +12 -2
  2. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/README.md +11 -1
  3. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/pyproject.toml +3 -1
  4. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/__init__.py +1 -1
  5. spatial_computing-0.16.0/spatial/ai/llm.py +43 -0
  6. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/cli.py +36 -1
  7. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/auth.py +21 -5
  8. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/registry.py +4 -1
  9. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fleet/hub.py +21 -7
  10. spatial_computing-0.16.0/spatial/platform/__init__.py +5 -0
  11. spatial_computing-0.16.0/spatial/platform/billing.py +133 -0
  12. spatial_computing-0.16.0/spatial/platform/db.py +100 -0
  13. spatial_computing-0.16.0/spatial/platform/mailer.py +57 -0
  14. spatial_computing-0.16.0/spatial/platform/pdf.py +85 -0
  15. spatial_computing-0.16.0/spatial/platform/security.py +79 -0
  16. spatial_computing-0.16.0/spatial/platform/server.py +521 -0
  17. spatial_computing-0.16.0/spatial/platform/service.py +1081 -0
  18. spatial_computing-0.16.0/spatial/platform/static/app.js +474 -0
  19. spatial_computing-0.16.0/spatial/platform/static/fonts/DMMono-normal-400.woff2 +0 -0
  20. spatial_computing-0.16.0/spatial/platform/static/fonts/DMMono-normal-500.woff2 +0 -0
  21. spatial_computing-0.16.0/spatial/platform/static/fonts/InstrumentSerif-italic-400.woff2 +0 -0
  22. spatial_computing-0.16.0/spatial/platform/static/fonts/InstrumentSerif-normal-400.woff2 +0 -0
  23. spatial_computing-0.16.0/spatial/platform/static/fonts/Inter-normal-400.woff2 +0 -0
  24. spatial_computing-0.16.0/spatial/platform/static/fonts/Inter-normal-500.woff2 +0 -0
  25. spatial_computing-0.16.0/spatial/platform/static/fonts/Inter-normal-600.woff2 +0 -0
  26. spatial_computing-0.16.0/spatial/platform/static/fonts.css +56 -0
  27. spatial_computing-0.16.0/spatial/platform/static/index.html +10 -0
  28. spatial_computing-0.16.0/spatial/platform/static/logo.svg +1 -0
  29. spatial_computing-0.16.0/spatial/platform/static/style.css +80 -0
  30. spatial_computing-0.16.0/spatial/platform/totp.py +48 -0
  31. spatial_computing-0.16.0/spatial/runtime/desktop/Dockerfile +11 -0
  32. spatial_computing-0.16.0/spatial/runtime/desktop/__init__.py +85 -0
  33. spatial_computing-0.16.0/spatial/runtime/desktop/start.sh +11 -0
  34. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/planner.py +114 -4
  35. {spatial_computing-0.14.0 → spatial_computing-0.16.0/spatial_computing.egg-info}/PKG-INFO +12 -2
  36. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial_computing.egg-info/SOURCES.txt +27 -0
  37. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_fleet.py +21 -0
  38. spatial_computing-0.16.0/tests/test_platform.py +510 -0
  39. spatial_computing-0.16.0/tests/test_platform2.py +454 -0
  40. spatial_computing-0.16.0/tests/test_runtime.py +151 -0
  41. spatial_computing-0.14.0/tests/test_runtime.py +0 -68
  42. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/LICENSE +0 -0
  43. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/setup.cfg +0 -0
  44. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/ai/__init__.py +0 -0
  45. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/ai/kvcache.py +0 -0
  46. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/__init__.py +0 -0
  47. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/cost.py +0 -0
  48. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/detect.py +0 -0
  49. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/monitor.py +0 -0
  50. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/scheduler.py +0 -0
  51. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/taskqueue.py +0 -0
  52. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/worker.py +0 -0
  53. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/compute/workloads.py +0 -0
  54. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/__init__.py +0 -0
  55. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/energy.py +0 -0
  56. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/ledger.py +0 -0
  57. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/model.py +0 -0
  58. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/core/protocol.py +0 -0
  59. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fabric/__init__.py +0 -0
  60. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fabric/cuda.py +0 -0
  61. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fabric/devices.py +0 -0
  62. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fabric/metal.py +0 -0
  63. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fabric/metal_mandel.swift +0 -0
  64. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fabric/metal_run.swift +0 -0
  65. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fleet/__init__.py +0 -0
  66. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fleet/agent.py +0 -0
  67. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fleet/alerts.py +0 -0
  68. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fleet/dashboard.py +0 -0
  69. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/fleet/ha.py +0 -0
  70. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/holographic/__init__.py +0 -0
  71. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/holographic/cgh.py +0 -0
  72. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/holographic/model.py +0 -0
  73. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/intelligence/__init__.py +0 -0
  74. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/intelligence/predictor.py +0 -0
  75. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/interconnect/__init__.py +0 -0
  76. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/interconnect/collectives.py +0 -0
  77. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/interconnect/comm.py +0 -0
  78. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/interconnect/model.py +0 -0
  79. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/interconnect/tasks.py +0 -0
  80. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/kernel/__init__.py +0 -0
  81. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/kernel/dsl.py +0 -0
  82. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/kernel/library.py +0 -0
  83. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/memory/__init__.py +0 -0
  84. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/memory/fararray.py +0 -0
  85. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/memory/pageserver.py +0 -0
  86. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/memory/secure.py +0 -0
  87. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/memory/shared.py +0 -0
  88. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/memory/tiered.py +0 -0
  89. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/__init__.py +0 -0
  90. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/__main__.py +0 -0
  91. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/backends/__init__.py +0 -0
  92. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/codegen.py +0 -0
  93. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/compiler.py +0 -0
  94. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/ir.py +0 -0
  95. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/lexer.py +0 -0
  96. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/parser.py +0 -0
  97. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/qir.py +0 -0
  98. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/runtime.py +0 -0
  99. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/q/sim.py +0 -0
  100. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/__init__.py +0 -0
  101. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/envs.py +0 -0
  102. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/inspect.py +0 -0
  103. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/microvm.py +0 -0
  104. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/runner.py +0 -0
  105. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/runtime/toolchain.py +0 -0
  106. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/scientific/__init__.py +0 -0
  107. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/scientific/jobs.py +0 -0
  108. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/simulation/__init__.py +0 -0
  109. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/simulation/heat.py +0 -0
  110. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/simulation/nbody.py +0 -0
  111. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/unified/__init__.py +0 -0
  112. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/unified/model.py +0 -0
  113. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/unified/planner.py +0 -0
  114. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial/unified/providers.py +0 -0
  115. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial_computing.egg-info/dependency_links.txt +0 -0
  116. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial_computing.egg-info/entry_points.txt +0 -0
  117. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial_computing.egg-info/requires.txt +0 -0
  118. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/spatial_computing.egg-info/top_level.txt +0 -0
  119. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_auth.py +0 -0
  120. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_compute.py +0 -0
  121. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_core.py +0 -0
  122. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_dashboard.py +0 -0
  123. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_domains.py +0 -0
  124. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_engines.py +0 -0
  125. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_fabric.py +0 -0
  126. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_ha.py +0 -0
  127. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_hardening.py +0 -0
  128. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_interconnect.py +0 -0
  129. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_kernel.py +0 -0
  130. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_memory.py +0 -0
  131. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_optimizer.py +0 -0
  132. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_q.py +0 -0
  133. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_quorum.py +0 -0
  134. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_unified.py +0 -0
  135. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_v02.py +0 -0
  136. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_v03.py +0 -0
  137. {spatial_computing-0.14.0 → spatial_computing-0.16.0}/tests/test_v05.py +0 -0
  138. {spatial_computing-0.14.0 → spatial_computing-0.16.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.14.0
3
+ Version: 0.16.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.14.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).
40
+ > **Status: v0.16.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.14.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).
7
+ > **Status: v0.16.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.14.0"
7
+ version = "0.16.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,8 @@ include = ["spatial*"]
33
33
 
34
34
  [tool.setuptools.package-data]
35
35
  "spatial.fabric" = ["*.swift"]
36
+ "spatial.platform" = ["static/*", "static/fonts/*"]
37
+ "spatial.runtime.desktop" = ["Dockerfile", "start.sh"]
36
38
 
37
39
  [tool.pytest.ini_options]
38
40
  testpaths = ["tests"]
@@ -3,4 +3,4 @@
3
3
  Status of every engine is declared in spatial.core.registry and must be backed
4
4
  by a test or benchmark before being set to OPERATIONAL.
5
5
  """
6
- __version__ = "0.14.0"
6
+ __version__ = "0.16.0"
@@ -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,30 @@ def cmd_agent(a):
103
103
  return 0
104
104
 
105
105
 
106
+ def cmd_desktop(a):
107
+ from .runtime.desktop import DesktopError, start
108
+ try:
109
+ d = start(a.app)
110
+ except DesktopError as e:
111
+ print(f"spatial: {e}", file=sys.stderr)
112
+ return 1
113
+ print(f"desktop ({a.app}, {d.runtime}), loopback only: {d.url}", flush=True)
114
+ print("Ctrl+C removes it", flush=True)
115
+ try:
116
+ while True:
117
+ time.sleep(3600)
118
+ except KeyboardInterrupt:
119
+ d.stop()
120
+ return 0
121
+
122
+
123
+ def cmd_platform(a):
124
+ from .platform import server
125
+ rest = [x for x in a.rest if x != "serve"] if a.rest[:1] == ["serve"] else a.rest
126
+ server.main(rest)
127
+ return 0
128
+
129
+
106
130
  def cmd_dashboard(a):
107
131
  from .fleet.dashboard import Dashboard
108
132
  d = Dashboard(a.hub, _read_token(a.token_file), port=a.port, min_severity=a.min_severity, webhook=a.webhook).start()
@@ -241,6 +265,7 @@ def cmd_worker(a):
241
265
  cmd += ["--audit-log", a.audit_log]
242
266
  if a.allow_remote:
243
267
  cmd.append("--allow-remote")
268
+ cmd += a.extra # service-specific flags, e.g. the hub's --state-file, --usage-file, --peer
244
269
  return subprocess.run(cmd).returncode
245
270
 
246
271
 
@@ -313,6 +338,12 @@ def main(argv=None):
313
338
  p.add_argument("--workload"); p.add_argument("--params", default="{}"); p.add_argument("--needs", default="{}")
314
339
  p.add_argument("--task-id", type=int)
315
340
  p.set_defaults(fn=cmd_fleet)
341
+ p = sub.add_parser("desktop", help="run a graphical Linux app (xterm, xclock, mousepad) in a container and open it in your browser (noVNC, loopback only)")
342
+ p.add_argument("app", nargs="?", default="xterm", choices=["xterm", "xclock", "mousepad"])
343
+ p.set_defaults(fn=cmd_desktop)
344
+ p = sub.add_parser("platform", help="account service: sign up, sign in, apps, API keys, usage, billing (`spatial platform serve --help`)")
345
+ p.add_argument("rest", nargs=argparse.REMAINDER)
346
+ p.set_defaults(fn=cmd_platform)
316
347
  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
348
  p.add_argument("--hub", required=True, help="host:port, or h1:p,h2:p for a hub pair")
318
349
  p.add_argument("--token-file", required=True, help="scoped token with fleet:read")
@@ -335,7 +366,11 @@ def main(argv=None):
335
366
  p.add_argument("--max-ops", type=int)
336
367
  p.add_argument("--max-bytes", type=int)
337
368
  p.set_defaults(fn=cmd_token)
338
- a = ap.parse_args(argv)
369
+ a, extra = ap.parse_known_args(argv)
370
+ if getattr(a, "cmd", None) == "serve":
371
+ a.extra = extra # forwarded to the service
372
+ elif extra:
373
+ ap.error("unrecognized arguments: " + " ".join(extra))
339
374
  if getattr(a, "cmd", None) == "serve" and bool(a.token_file) == bool(a.master_key_file):
340
375
  ap.error("serve needs exactly one of --token-file or --master-key-file")
341
376
  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: revocation and usage counters live in the server process (restart resets counters);
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; roles are fixed; tax is a rate table, not a compliance engine; e-mail tested against a local SMTP stand-in, payments against a fake Stripe API only"),
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 apps not demonstrated (no Wine / Windows image); no containers; no GUI streaming"),
52
+ "Windows: one console program and one GUI window (Notepad) under Wine, nothing more; containers: static Linux ELF, tested with Docker (Colima) and Podman; Linux GUI apps stream through a container and noVNC (three allow-listed apps)"),
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 self.tasks.values():
130
+ for t in pool:
128
131
  counts[t["state"]] = counts.get(t["state"], 0) + 1
129
- last = sorted(self.tasks.values(), key=lambda t: t["id"], reverse=True)[:recent]
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
- return hub.queue_view(int(h.get("recent", 12))), b""
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,133 @@
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: the operator has not set real prices yet.",
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 is waived (no tiny charges)
25
+ "tax_label": "VAT",
26
+ "tax_rate_percent": 0.0, # default rate added to every invoice
27
+ "tax_by_country": {}, # {"FR": 20, "DE": 19}: overrides the default rate by the customer's billing country
28
+ "no_tax_with_vat_id_abroad": False, # simplified B2B reverse charge: a customer with a VAT id outside the seller's country pays no tax
29
+ }
30
+
31
+ PRICING_KEYS = {"currency": str, "note": str, "free_compute_hours_per_month": (int, float), "compute_usd_per_hour": (int, float), "min_invoice_usd": (int, float),
32
+ "tax_label": str, "tax_rate_percent": (int, float), "tax_by_country": dict, "no_tax_with_vat_id_abroad": bool}
33
+
34
+
35
+ def validate_pricing(d: dict) -> dict:
36
+ """Return a clean pricing dict or raise ValueError. Bounds keep a typo from charging 1000x."""
37
+ out = dict(DEFAULT_PRICING)
38
+ for k, v in d.items():
39
+ if k not in PRICING_KEYS:
40
+ raise ValueError(f"unknown pricing field '{k}'")
41
+ if isinstance(v, bool) != (PRICING_KEYS[k] is bool) or not isinstance(v, PRICING_KEYS[k]):
42
+ raise ValueError(f"'{k}' has the wrong type")
43
+ out[k] = v
44
+ if not (isinstance(out["currency"], str) and len(out["currency"]) == 3 and out["currency"].isalpha()):
45
+ raise ValueError("currency must be a 3-letter code")
46
+ for k, lo, hi in (("free_compute_hours_per_month", 0, 100000), ("compute_usd_per_hour", 0, 1000), ("min_invoice_usd", 0, 1000), ("tax_rate_percent", 0, 50)):
47
+ if not lo <= out[k] <= hi:
48
+ raise ValueError(f"'{k}' must be between {lo} and {hi}")
49
+ for c, r in out["tax_by_country"].items():
50
+ if not (isinstance(c, str) and len(c) == 2 and c.isalpha() and isinstance(r, (int, float)) and not isinstance(r, bool) and 0 <= r <= 50):
51
+ raise ValueError("tax_by_country must map 2-letter country codes to rates between 0 and 50")
52
+ out["tax_by_country"] = {c.upper(): r for c, r in out["tax_by_country"].items()}
53
+ out["currency"] = out["currency"].lower()
54
+ return out
55
+
56
+
57
+ @dataclass
58
+ class Pricing:
59
+ data: dict = field(default_factory=lambda: dict(DEFAULT_PRICING))
60
+
61
+ def __post_init__(self):
62
+ self.data = {**DEFAULT_PRICING, **self.data} # fields added in later versions keep their defaults
63
+
64
+ @classmethod
65
+ def load(cls, path: str | None) -> "Pricing":
66
+ d = dict(DEFAULT_PRICING)
67
+ if path:
68
+ d.update(json.load(open(path)))
69
+ return cls(d)
70
+
71
+ def rate(self, seconds_by_app: dict[int, float]) -> dict:
72
+ """Cost of one period. The free allowance is shared by the whole account, applied app by app in id order."""
73
+ free = self.data["free_compute_hours_per_month"] * 3600
74
+ lines, total = [], 0.0
75
+ for app_id in sorted(seconds_by_app):
76
+ sec = seconds_by_app[app_id]
77
+ billable = max(0.0, sec - free)
78
+ free = max(0.0, free - sec)
79
+ cost = round(billable / 3600 * self.data["compute_usd_per_hour"], 4)
80
+ lines.append({"app_id": app_id, "seconds": round(sec, 3), "billable_seconds": round(billable, 3), "usd": cost})
81
+ total += cost
82
+ return {"lines": lines, "total_usd": round(total, 4)}
83
+
84
+
85
+ class PaymentError(Exception):
86
+ pass
87
+
88
+
89
+ class Stripe:
90
+ """Stripe Checkout over plain HTTPS (no SDK). `api_base` is overridable for tests."""
91
+
92
+ def __init__(self, secret_key: str | None, webhook_secret: str | None, api_base: str = "https://api.stripe.com"):
93
+ self.key, self.whsec, self.base = secret_key, webhook_secret, api_base
94
+
95
+ @property
96
+ def configured(self) -> bool:
97
+ return bool(self.key)
98
+
99
+ def checkout_url(self, invoice_id: int, amount_usd: float, email: str, success_url: str, cancel_url: str, currency: str = "usd") -> tuple[str, str]:
100
+ if not self.key:
101
+ raise PaymentError("payments are not configured on this server (no STRIPE_SECRET_KEY)")
102
+ cents = int(round(amount_usd * 100))
103
+ if cents < 50:
104
+ raise PaymentError("amount is below the payment provider's minimum")
105
+ form = urllib.parse.urlencode({
106
+ "mode": "payment", "success_url": success_url, "cancel_url": cancel_url, "customer_email": email,
107
+ "client_reference_id": str(invoice_id), "metadata[invoice_id]": str(invoice_id),
108
+ "line_items[0][quantity]": "1", "line_items[0][price_data][currency]": currency,
109
+ "line_items[0][price_data][unit_amount]": str(cents),
110
+ "line_items[0][price_data][product_data][name]": f"Spatial Computing usage, invoice {invoice_id}"}).encode()
111
+ req = urllib.request.Request(self.base + "/v1/checkout/sessions", data=form, method="POST",
112
+ headers={"Authorization": f"Bearer {self.key}", "Content-Type": "application/x-www-form-urlencoded"})
113
+ try:
114
+ r = json.load(urllib.request.urlopen(req, timeout=15))
115
+ except Exception as e:
116
+ raise PaymentError(f"payment provider error: {type(e).__name__}") from e
117
+ return r["url"], r["id"]
118
+
119
+ def verify_webhook(self, payload: bytes, header: str, tolerance_s: int = 300, now: float | None = None) -> dict:
120
+ """Check the Stripe-Signature header (t=..,v1=hmac_sha256(secret, 't.payload')) and return the event."""
121
+ if not self.whsec:
122
+ raise PaymentError("webhook secret not configured")
123
+ try:
124
+ parts = dict(p.split("=", 1) for p in header.split(","))
125
+ t, sig = int(parts["t"]), parts["v1"]
126
+ except Exception:
127
+ raise PaymentError("malformed signature header")
128
+ expected = hmac.new(self.whsec.encode(), f"{t}.".encode() + payload, hashlib.sha256).hexdigest()
129
+ if not hmac.compare_digest(expected, sig):
130
+ raise PaymentError("bad signature")
131
+ if abs((now or time.time()) - t) > tolerance_s:
132
+ raise PaymentError("signature too old")
133
+ return json.loads(payload)
@@ -0,0 +1,100 @@
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
+ email_verified INTEGER NOT NULL DEFAULT 0, totp_secret TEXT, totp_enabled INTEGER NOT NULL DEFAULT 0, totp_last_step INTEGER NOT NULL DEFAULT 0,
14
+ recovery TEXT NOT NULL DEFAULT '[]', personal_org INTEGER);
15
+ CREATE TABLE IF NOT EXISTS orgs(
16
+ id INTEGER PRIMARY KEY, name TEXT NOT NULL, created REAL NOT NULL, personal INTEGER NOT NULL DEFAULT 0,
17
+ billing_name TEXT NOT NULL DEFAULT '', billing_address TEXT NOT NULL DEFAULT '', billing_country TEXT NOT NULL DEFAULT '', vat_id TEXT NOT NULL DEFAULT '');
18
+ CREATE TABLE IF NOT EXISTS members(org_id INTEGER NOT NULL, user_id INTEGER NOT NULL, role TEXT NOT NULL, created REAL NOT NULL, PRIMARY KEY(org_id, user_id));
19
+ CREATE TABLE IF NOT EXISTS invites(
20
+ id INTEGER PRIMARY KEY, org_id INTEGER NOT NULL, email TEXT NOT NULL, role TEXT NOT NULL, token_hash TEXT UNIQUE NOT NULL, invited_by INTEGER NOT NULL,
21
+ created REAL NOT NULL, expires REAL NOT NULL, accepted REAL);
22
+ CREATE TABLE IF NOT EXISTS verifications(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL);
23
+ CREATE TABLE IF NOT EXISTS challenges(token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, expires REAL NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, ip TEXT, ua TEXT);
24
+ CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT NOT NULL, updated REAL NOT NULL);
25
+ CREATE TABLE IF NOT EXISTS counters(name TEXT PRIMARY KEY, value INTEGER NOT NULL);
26
+ CREATE TABLE IF NOT EXISTS sessions(
27
+ 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);
28
+ CREATE TABLE IF NOT EXISTS apps(
29
+ id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '',
30
+ budget_usd REAL, created REAL NOT NULL, deleted REAL, org_id INTEGER);
31
+ CREATE TABLE IF NOT EXISTS api_keys(
32
+ id INTEGER PRIMARY KEY, app_id INTEGER NOT NULL, name TEXT NOT NULL, kind TEXT NOT NULL, cred_name TEXT NOT NULL,
33
+ hint TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, revoked REAL);
34
+ CREATE TABLE IF NOT EXISTS usage(
35
+ id INTEGER PRIMARY KEY, app_id INTEGER NOT NULL, ts REAL NOT NULL, workload TEXT, node TEXT, ok INTEGER, seconds REAL NOT NULL);
36
+ CREATE INDEX IF NOT EXISTS usage_app_ts ON usage(app_id, ts);
37
+ CREATE TABLE IF NOT EXISTS offsets(name TEXT PRIMARY KEY, value INTEGER NOT NULL);
38
+ CREATE TABLE IF NOT EXISTS invoices(
39
+ id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, period TEXT NOT NULL, amount_usd REAL NOT NULL, status TEXT NOT NULL,
40
+ lines TEXT NOT NULL, created REAL NOT NULL, paid REAL, provider_ref TEXT, org_id INTEGER, number TEXT, subtotal_usd REAL, tax_rate REAL, tax_usd REAL,
41
+ billing TEXT, seller TEXT);
42
+ 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);
43
+ 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,
44
+ attempts INTEGER NOT NULL DEFAULT 0, next_try REAL NOT NULL DEFAULT 0, last_error TEXT);
45
+ CREATE TABLE IF NOT EXISTS tokens(
46
+ id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, name TEXT NOT NULL, token_hash TEXT UNIQUE NOT NULL, hint TEXT NOT NULL,
47
+ scope TEXT NOT NULL, created REAL NOT NULL, expires REAL NOT NULL, last_used REAL, revoked REAL);
48
+ CREATE TABLE IF NOT EXISTS events(id INTEGER PRIMARY KEY, ts REAL NOT NULL, user_id INTEGER, kind TEXT NOT NULL, detail TEXT);
49
+ """
50
+
51
+
52
+ class DB:
53
+ def __init__(self, path: str = ":memory:"):
54
+ self.conn = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
55
+ self.conn.row_factory = sqlite3.Row
56
+ self.lock = threading.RLock()
57
+ with self.lock:
58
+ self.conn.execute("PRAGMA journal_mode=WAL")
59
+ self.conn.execute("PRAGMA foreign_keys=ON")
60
+ self.conn.executescript(SCHEMA)
61
+ self._migrate()
62
+
63
+ def q(self, sql: str, args=()) -> list[sqlite3.Row]:
64
+ with self.lock:
65
+ return self.conn.execute(sql, args).fetchall()
66
+
67
+ def one(self, sql: str, args=()):
68
+ r = self.q(sql, args)
69
+ return r[0] if r else None
70
+
71
+ def x(self, sql: str, args=()) -> int:
72
+ with self.lock:
73
+ cur = self.conn.execute(sql, args)
74
+ return cur.lastrowid
75
+
76
+ def event(self, user_id, kind: str, detail: str = "") -> None:
77
+ self.x("INSERT INTO events(ts,user_id,kind,detail) VALUES(?,?,?,?)", (time.time(), user_id, kind, detail[:500]))
78
+
79
+ # ------------------------------------------------------------------ migration of databases created by older versions
80
+ ADD = {"users": [("email_verified", "INTEGER NOT NULL DEFAULT 0"), ("totp_secret", "TEXT"), ("totp_enabled", "INTEGER NOT NULL DEFAULT 0"),
81
+ ("totp_last_step", "INTEGER NOT NULL DEFAULT 0"), ("recovery", "TEXT NOT NULL DEFAULT '[]'"), ("personal_org", "INTEGER")],
82
+ "apps": [("org_id", "INTEGER")],
83
+ "invoices": [("org_id", "INTEGER"), ("number", "TEXT"), ("subtotal_usd", "REAL"), ("tax_rate", "REAL"), ("tax_usd", "REAL"), ("billing", "TEXT"), ("seller", "TEXT")],
84
+ "outbox": [("attempts", "INTEGER NOT NULL DEFAULT 0"), ("next_try", "REAL NOT NULL DEFAULT 0"), ("last_error", "TEXT")]}
85
+
86
+ def _migrate(self) -> None:
87
+ for table, cols in self.ADD.items():
88
+ have = {r["name"] for r in self.conn.execute(f"PRAGMA table_info({table})")}
89
+ for name, decl in cols:
90
+ if name not in have:
91
+ self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}")
92
+ # the unique (user_id, period) constraint of the first version is replaced by (org_id, period)
93
+ self.conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS invoices_org_period ON invoices(org_id, period)")
94
+ now = time.time()
95
+ for u in self.conn.execute("SELECT id, name FROM users WHERE personal_org IS NULL").fetchall(): # one personal organisation per user
96
+ oid = self.conn.execute("INSERT INTO orgs(name,created,personal) VALUES(?,?,1)", (u["name"] + "'s workspace", now)).lastrowid
97
+ self.conn.execute("INSERT INTO members(org_id,user_id,role,created) VALUES(?,?,?,?)", (oid, u["id"], "owner", now))
98
+ self.conn.execute("UPDATE users SET personal_org=? WHERE id=?", (oid, u["id"]))
99
+ self.conn.execute("UPDATE apps SET org_id=(SELECT personal_org FROM users WHERE users.id=apps.user_id) WHERE org_id IS NULL")
100
+ self.conn.execute("UPDATE invoices SET org_id=(SELECT personal_org FROM users WHERE users.id=invoices.user_id) WHERE org_id IS NULL")