streamwright-console 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- streamwright/console/__init__.py +29 -0
- streamwright/console/api/__init__.py +20 -0
- streamwright/console/api/acks.py +162 -0
- streamwright/console/api/app.py +401 -0
- streamwright/console/api/login.py +139 -0
- streamwright/console/api/logs.py +113 -0
- streamwright/console/api/openapi.py +205 -0
- streamwright/console/api/query.py +113 -0
- streamwright/console/auth/__init__.py +21 -0
- streamwright/console/auth/access.py +99 -0
- streamwright/console/auth/authenticator.py +45 -0
- streamwright/console/auth/passwords.py +83 -0
- streamwright/console/auth/sessions.py +65 -0
- streamwright/console/auth/sso.py +186 -0
- streamwright/console/auth/throttle.py +60 -0
- streamwright/console/auth/users.py +111 -0
- streamwright/console/cli/__init__.py +21 -0
- streamwright/console/cli/admin.py +267 -0
- streamwright/console/cli/main.py +110 -0
- streamwright/console/config/__init__.py +18 -0
- streamwright/console/config/check.py +48 -0
- streamwright/console/config/console.py +289 -0
- streamwright/console/config/login.py +141 -0
- streamwright/console/config/service.py +32 -0
- streamwright/console/db/__init__.py +18 -0
- streamwright/console/db/migrations/0001_console_users.py +40 -0
- streamwright/console/db/migrations/__init__.py +29 -0
- streamwright/console/db/tables/__init__.py +34 -0
- streamwright/console/db/tables/base.py +24 -0
- streamwright/console/db/tables/migrations.py +27 -0
- streamwright/console/db/tables/users.py +42 -0
- streamwright/console/db/users.py +95 -0
- streamwright/console/guide.md +99 -0
- streamwright/console/static/app.js +2014 -0
- streamwright/console/static/favicon.png +0 -0
- streamwright/console/static/favicon.svg +1 -0
- streamwright/console/static/index.html +66 -0
- streamwright/console/static/streamwright-logo-dark.svg +1 -0
- streamwright/console/static/style.css +410 -0
- streamwright/console/views/__init__.py +21 -0
- streamwright/console/views/attention.py +145 -0
- streamwright/console/views/filters.py +62 -0
- streamwright/console/views/job_page.py +97 -0
- streamwright/console/views/job_runs.py +222 -0
- streamwright/console/views/job_summaries.py +123 -0
- streamwright/console/views/overview.py +156 -0
- streamwright/console/views/reads.py +354 -0
- streamwright/console/views/run_log.py +77 -0
- streamwright/console/views/stores.py +190 -0
- streamwright_console-0.3.0.dist-info/METADATA +109 -0
- streamwright_console-0.3.0.dist-info/RECORD +55 -0
- streamwright_console-0.3.0.dist-info/WHEEL +5 -0
- streamwright_console-0.3.0.dist-info/entry_points.txt +5 -0
- streamwright_console-0.3.0.dist-info/licenses/LICENSE +201 -0
- streamwright_console-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
`streamwright console`: a console over the state databases of many clients' jobs (pip install streamwright-console;
|
|
19
|
+
it plugs into the streamwright CLI). An operator picks a client and sees its jobs and scopes (health, latest batch,
|
|
20
|
+
last success), a batch's story, what needs a person, the leases and the serve runs; the people a client lets
|
|
21
|
+
acknowledge its problems do so from the page.
|
|
22
|
+
|
|
23
|
+
config/ console.yaml: clients, stores, the login page; its checks and ServiceConfig
|
|
24
|
+
views/ what the pages show of each client's stores (opened when the client is picked)
|
|
25
|
+
api/ the HTTP API and the page (static/), sign-in and acknowledge routes
|
|
26
|
+
auth/ who calls and what they may do: sessions, console users, single sign-on
|
|
27
|
+
db/ the console's own database: its tables (tables/), its store and users, their migrations
|
|
28
|
+
cli/ `streamwright console CONSOLE_YAML`, `console migrate`, `console users`
|
|
29
|
+
"""
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
The console's HTTP API and page (app), its sign-in routes (login), acknowledging from the page (acks), its query
|
|
19
|
+
strings and JSON bodies (query) and its OpenAPI document (openapi).
|
|
20
|
+
"""
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
Acknowledging from the page, a part of the console's API (streamwright.console.api.app), for those a client's
|
|
19
|
+
ack_principals list (anyone, without auth). The rules are `streamwright state ack`'s (core's acknowledge); the
|
|
20
|
+
console writes sw_job_acks alone, never a batch, and records who as the person signed in (auth.access).
|
|
21
|
+
|
|
22
|
+
POST /v1/clients/C/acks {store, job, target, note} or {store, job, all: true, note}
|
|
23
|
+
DELETE /v1/clients/C/acks/TARGET ?store=&job= one acknowledgement
|
|
24
|
+
DELETE /v1/clients/C/acks ?store=&job=&all=1 every acknowledgement of the job
|
|
25
|
+
|
|
26
|
+
403 for a caller who may see the client but not acknowledge; 409 for an item that needs no one (or is not
|
|
27
|
+
acknowledged); 501 for a DuckDB store (a job holds the file: `streamwright state ack` there); 503 when the store
|
|
28
|
+
cannot be written.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
import ipaddress
|
|
32
|
+
import logging
|
|
33
|
+
from types import MappingProxyType
|
|
34
|
+
|
|
35
|
+
from starlette.concurrency import run_in_threadpool
|
|
36
|
+
from streamwright.core.http_service.errors import RequestError
|
|
37
|
+
from streamwright.core.jobs.state import acknowledge
|
|
38
|
+
from streamwright.core.jobs.state.protocol import StateError
|
|
39
|
+
|
|
40
|
+
from streamwright.console.api.query import json_body, parse_query
|
|
41
|
+
from streamwright.console.auth.access import may_ack, recorded_as
|
|
42
|
+
|
|
43
|
+
__all__ = ["AckRoutes"]
|
|
44
|
+
|
|
45
|
+
LOG = logging.getLogger("streamwright.console")
|
|
46
|
+
_REFUSED = MappingProxyType({
|
|
47
|
+
"not-found": (404, "not-found"), "several-jobs": (400, "job-required"), "bad-note": (400, "bad-body"),
|
|
48
|
+
"nothing-to-acknowledge": (409, "nothing-to-acknowledge"), "not-acknowledged": (409, "not-acknowledged")})
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _one(writer, target, job, note, by):
|
|
52
|
+
"""(the item the id names, whether it was not acknowledged before), once it is."""
|
|
53
|
+
item = acknowledge.named(writer, target, job)
|
|
54
|
+
if item.problem is None:
|
|
55
|
+
raise acknowledge.AckRefusedError("nothing-to-acknowledge", "%s %s is %s: nothing needs a person" % (
|
|
56
|
+
item.what, target, item.status))
|
|
57
|
+
return item, bool(writer.ack(item.job, [(target, item.problem, item.scope)], note=note, acked_by=by))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _undone(writer, target, job):
|
|
61
|
+
item = acknowledge.named(writer, target, job)
|
|
62
|
+
if not writer.unack(item.job, [target]):
|
|
63
|
+
raise acknowledge.AckRefusedError("not-acknowledged", "%s %s is not acknowledged" % (item.what, target))
|
|
64
|
+
return item
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _loopback(host):
|
|
68
|
+
"""Whether the address the page was asked at is loopback (a page another site serves by rebinding its own name to
|
|
69
|
+
127.0.0.1 is not)."""
|
|
70
|
+
try:
|
|
71
|
+
return ipaddress.ip_address((host or "").strip("[]")).is_loopback
|
|
72
|
+
except ValueError:
|
|
73
|
+
return host == "localhost"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _text(body, name, required=True):
|
|
77
|
+
value = body.get(name)
|
|
78
|
+
if (value is None and not required) or (isinstance(value, str) and value.strip()):
|
|
79
|
+
return value
|
|
80
|
+
raise RequestError(400, "bad-body", "%s: text" % name)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class AckRoutes:
|
|
84
|
+
"""The acknowledge routes of the console's API (self.console, self.stores, and _client, _store of app._Api)."""
|
|
85
|
+
|
|
86
|
+
def _acker(self, request, principal):
|
|
87
|
+
if not self.console.has_auth and not _loopback(request.url.hostname):
|
|
88
|
+
raise RequestError(403, "not-allowed", "without auth, acknowledge on a loopback address only")
|
|
89
|
+
client = self._client(request, principal)
|
|
90
|
+
if not may_ack(self.console, principal, client):
|
|
91
|
+
raise RequestError(403, "not-allowed", "you may see %s, not acknowledge its problems (console.yaml: "
|
|
92
|
+
"the client's ack_principals)" % client.name)
|
|
93
|
+
return client
|
|
94
|
+
|
|
95
|
+
async def _write(self, client, store, work):
|
|
96
|
+
"""work(writer) on the client's store opened to write; the refusals said as HTTP errors."""
|
|
97
|
+
def run():
|
|
98
|
+
writer, why = self.stores.writer(client.id, store)
|
|
99
|
+
if why == "duckdb":
|
|
100
|
+
raise RequestError(501, "read-only-store", "store %s is a DuckDB file a job holds: acknowledge with "
|
|
101
|
+
"`streamwright state ack` there" % store)
|
|
102
|
+
if writer is None:
|
|
103
|
+
raise RequestError(503, why, "store %s: %s" % (store, why))
|
|
104
|
+
try:
|
|
105
|
+
writer.prepare(migrate=False)
|
|
106
|
+
return work(writer)
|
|
107
|
+
except acknowledge.AckRefusedError as exc:
|
|
108
|
+
status, code = _REFUSED[exc.code]
|
|
109
|
+
raise RequestError(status, code, str(exc)) from None
|
|
110
|
+
except StateError as exc: # its migrations are pending
|
|
111
|
+
raise RequestError(409, "migrations-pending", str(exc)) from None
|
|
112
|
+
except RequestError:
|
|
113
|
+
raise
|
|
114
|
+
except Exception as exc: # the driver's error: its type varies with the database
|
|
115
|
+
LOG.warning("%s", self.stores.get(client.id).redact("client %s, store %s: cannot record an "
|
|
116
|
+
"acknowledgement: %s" % (client.id, store, exc)))
|
|
117
|
+
raise RequestError(503, "unreachable", "store %s: unreachable" % store) from None
|
|
118
|
+
|
|
119
|
+
return await run_in_threadpool(run)
|
|
120
|
+
|
|
121
|
+
async def ack(self, request, principal):
|
|
122
|
+
client = self._acker(request, principal)
|
|
123
|
+
body = await json_body(request, ("store", "job", "target", "all", "note"))
|
|
124
|
+
store = self._store(client, {"store": _text(body, "store")} if "store" in body else {})
|
|
125
|
+
if store not in client.stores:
|
|
126
|
+
raise RequestError(404, "not-found", "no store %r" % store)
|
|
127
|
+
job, every = _text(body, "job", required=False), body.get("all", False)
|
|
128
|
+
if every not in (True, False) or every == ("target" in body) or (every and job is None):
|
|
129
|
+
raise RequestError(400, "bad-body", "give target (a batch's job id or a run's id), or all: true and job")
|
|
130
|
+
try:
|
|
131
|
+
note = acknowledge.clean_note(body.get("note"))
|
|
132
|
+
except acknowledge.AckRefusedError as exc:
|
|
133
|
+
raise RequestError(400, "bad-body", str(exc)) from None
|
|
134
|
+
by = recorded_as(principal)
|
|
135
|
+
if every:
|
|
136
|
+
chosen, left = await self._write(client, store, lambda writer: acknowledge.ack_job(writer, job, note, by))
|
|
137
|
+
LOG.info("client %s, store %s: %s acknowledged %d item(s) of %s", client.id, store, by, len(chosen), job)
|
|
138
|
+
return {"job": job, "acknowledged": [item.get("job_id") or item["run_id"] for item in chosen],
|
|
139
|
+
"kinds": acknowledge.counted(chosen), "left": acknowledge.counted(left), "acked_by": by}
|
|
140
|
+
target = _text(body, "target")
|
|
141
|
+
item, new = await self._write(client, store, lambda writer: _one(writer, target, job, note, by))
|
|
142
|
+
LOG.info("client %s, store %s: %s acknowledged %s %s of %s (%s)", client.id, store, by, item.what, target,
|
|
143
|
+
item.job, item.problem)
|
|
144
|
+
return {"job": item.job, "target": target, "kind": item.problem, "new": new, "acked_by": by}
|
|
145
|
+
|
|
146
|
+
async def unack(self, request, principal):
|
|
147
|
+
client = self._acker(request, principal)
|
|
148
|
+
target = request.path_params.get("target")
|
|
149
|
+
query = parse_query(request, ("store", "job") if target else ("store", "job", "all"), client)
|
|
150
|
+
store = self._store(client, query)
|
|
151
|
+
if target:
|
|
152
|
+
item = await self._write(client, store, lambda writer: _undone(writer, target, query.get("job")))
|
|
153
|
+
LOG.info("client %s, store %s: %s undid the acknowledgement of %s %s of %s", client.id, store,
|
|
154
|
+
recorded_as(principal), item.what, target, item.job)
|
|
155
|
+
return {"job": item.job, "target": target, "removed": 1}
|
|
156
|
+
if query.get("all") != "1" or not query.get("job"):
|
|
157
|
+
raise RequestError(400, "bad-query", "every acknowledgement of a job: give job and all=1")
|
|
158
|
+
job = query["job"]
|
|
159
|
+
removed = await self._write(client, store, lambda writer: writer.unack(job))
|
|
160
|
+
LOG.info("client %s, store %s: %s undid %d acknowledgement(s) of %s", client.id, store,
|
|
161
|
+
recorded_as(principal), removed, job)
|
|
162
|
+
return {"job": job, "removed": removed}
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
# /*************************************************************************
|
|
3
|
+
# * Copyright 2026 Karthick Jaganathan
|
|
4
|
+
# *
|
|
5
|
+
# * Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
# * you may not use this file except in compliance with the License.
|
|
7
|
+
# * You may obtain a copy of the License at
|
|
8
|
+
# *
|
|
9
|
+
# * https://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
# *
|
|
11
|
+
# * Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
# * distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
# * See the License for the specific language governing permissions and
|
|
15
|
+
# * limitations under the License.
|
|
16
|
+
# **************************************************************************/
|
|
17
|
+
"""
|
|
18
|
+
The HTTP API and page of `streamwright console`: pick a client, see its jobs, acknowledge its problems (when its
|
|
19
|
+
ack_principals let the caller; the console writes nothing else).
|
|
20
|
+
|
|
21
|
+
GET / the console (a static page; its data comes from the API)
|
|
22
|
+
GET /static/app.js, /static/style.css its script and styles, and its logo and favicons (/static/NAME)
|
|
23
|
+
GET /v1/config what the page needs before sign-in: whether and how it signs in
|
|
24
|
+
POST /v1/login, GET /login/sso, ... signing in on the login page; GET /v1/me: who the caller is
|
|
25
|
+
(streamwright.console.api.login)
|
|
26
|
+
GET /v1/clients the clients the caller may pick (no store is opened), the stores
|
|
27
|
+
the caller may acknowledge in, the logs link
|
|
28
|
+
GET /v1/clients/C/overview stores (reachable, pending migrations), jobs and scopes by health,
|
|
29
|
+
how many items need a person and how many were acknowledged
|
|
30
|
+
GET /v1/clients/C/jobs ?job=&health=&q=&filter=&store=&since=&until=&sort=&order=&limit=
|
|
31
|
+
&offset= a page of the jobs and scopes (a job's scopes), newest
|
|
32
|
+
batch first: health, latest batch, last success, 24 hours, its
|
|
33
|
+
acknowledgement; with the total and each health's count
|
|
34
|
+
GET /v1/clients/C/job-summaries ?job=&health=&filter=&since=&until=&sort=&order=&limit=&offset=
|
|
35
|
+
a page of the jobs, each once: health, scopes by health, latest run,
|
|
36
|
+
runs and rows in the period; with the total and each health's count
|
|
37
|
+
GET /v1/clients/C/jobs/JOB/batches ?store=&scope=&status=&limit= a job's batches
|
|
38
|
+
GET /v1/clients/C/batches/JOB_ID ?store=&job= one batch (no row values)
|
|
39
|
+
GET /v1/clients/C/attention ?kind=&acked=&filter=&since=&until=&limit=&offset= a page of what
|
|
40
|
+
needs a person (or was acknowledged), with the `streamwright state`
|
|
41
|
+
commands
|
|
42
|
+
GET /v1/clients/C/leases ?filter= leases and their holders
|
|
43
|
+
GET /v1/clients/C/runs ?job=&filter=&status=&since=&until=&sort=&order=&limit=&offset=
|
|
44
|
+
a page of serve runs, newest first, with the total (no inputs or rows)
|
|
45
|
+
GET /v1/clients/C/job-runs ?job=&q=&filter=&status=&since=&until=&sort=&order=&limit=&offset=
|
|
46
|
+
a page of the jobs' runs (sw_runs), newest first, with the total and
|
|
47
|
+
each status's count
|
|
48
|
+
GET /v1/clients/C/job-runs/RUN_ID ?store=&job= one run: what failed, its batches' totals, outputs
|
|
49
|
+
GET /v1/clients/C/job-runs/RUN_ID/batches ?store=&job=&status=&limit=&offset= the batches it made or resumed
|
|
50
|
+
GET /v1/clients/C/job-runs/RUN_ID/rows ?store=&job=&limit= its rows not applied, its rejections grouped
|
|
51
|
+
GET /v1/clients/C/job-runs/RUN_ID/log[/download] its own log file (--log-dir): a page, or the file (logs.py)
|
|
52
|
+
GET /v1/clients/C/jobs/JOB ?store=&since=&until= one job: runs, batches, outputs, scopes
|
|
53
|
+
POST, DELETE /v1/clients/C/acks[/TARGET] acknowledge, or undo (streamwright.console.api.acks)
|
|
54
|
+
GET /healthz, /readyz liveness, readiness
|
|
55
|
+
GET /openapi.json this API (OpenAPI 3.1)
|
|
56
|
+
|
|
57
|
+
A client the caller may not pick is 404, as one that does not exist. Query strings carry only the filters listed
|
|
58
|
+
(400 otherwise). `since` and `until` are an ISO date (2026-11-28: `until` takes in that whole day) or a UTC time
|
|
59
|
+
(2026-11-28T09:30:00Z, or with an offset); a list is newest first unless `sort`/`order` say otherwise. A store
|
|
60
|
+
that cannot be read is retried once with the client's secrets looked up again, then shown by its error code
|
|
61
|
+
(`unreachable`, `secrets-failed`, `secrets-missing`).
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
import logging
|
|
65
|
+
import os
|
|
66
|
+
import time
|
|
67
|
+
from types import MappingProxyType
|
|
68
|
+
|
|
69
|
+
from starlette.applications import Starlette
|
|
70
|
+
from starlette.concurrency import run_in_threadpool
|
|
71
|
+
from starlette.responses import JSONResponse, Response
|
|
72
|
+
from starlette.routing import Route
|
|
73
|
+
from streamwright.core.http_service.errors import RequestError
|
|
74
|
+
from streamwright.core.jobs.state.protocol import STATUSES
|
|
75
|
+
from streamwright.core.jobs.state.requests import REQUEST_STATUSES
|
|
76
|
+
from streamwright.core.runtime.logs import log_context
|
|
77
|
+
from streamwright.core.runtime.logs.context import new_request_id
|
|
78
|
+
|
|
79
|
+
from streamwright.console.api.acks import AckRoutes
|
|
80
|
+
from streamwright.console.api.login import LoginRoutes
|
|
81
|
+
from streamwright.console.api.logs import LogRoutes
|
|
82
|
+
from streamwright.console.api.openapi import openapi
|
|
83
|
+
from streamwright.console.api.query import filter_conditions, one_of, parse_query
|
|
84
|
+
from streamwright.console.auth.access import may_ack, may_pick
|
|
85
|
+
from streamwright.console.auth.authenticator import ConsoleAuthenticator
|
|
86
|
+
from streamwright.console.auth.sessions import Sessions
|
|
87
|
+
from streamwright.console.auth.sso import Sso
|
|
88
|
+
from streamwright.console.auth.throttle import Throttle
|
|
89
|
+
from streamwright.console.auth.users import Users
|
|
90
|
+
from streamwright.console.views import attention, filters, job_page, job_runs, job_summaries, overview, reads
|
|
91
|
+
from streamwright.console.views.stores import ClientStores, duckdb_store
|
|
92
|
+
|
|
93
|
+
__all__ = ["create_app"]
|
|
94
|
+
|
|
95
|
+
LOG = logging.getLogger("streamwright.console")
|
|
96
|
+
ACCESS = logging.getLogger("streamwright.console.access")
|
|
97
|
+
_HEADERS = MappingProxyType({"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
|
|
98
|
+
"Referrer-Policy": "no-referrer"})
|
|
99
|
+
_POLICY = ("default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; "
|
|
100
|
+
"frame-ancestors 'none'; base-uri 'none'; form-action 'none'")
|
|
101
|
+
_STATIC = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static") # streamwright/console/static
|
|
102
|
+
_FILES = MappingProxyType({"app.js": "text/javascript", "style.css": "text/css", "favicon.svg": "image/svg+xml",
|
|
103
|
+
"favicon.png": "image/png", "streamwright-logo-dark.svg": "image/svg+xml"})
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _json(status, body, request_id):
|
|
107
|
+
return JSONResponse(body, status_code=status, headers={**_HEADERS, "X-Request-ID": request_id})
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class _Api(LoginRoutes, AckRoutes, LogRoutes):
|
|
111
|
+
def __init__(self, console, stores, authenticator, *, sessions=None, users=None, sso=None):
|
|
112
|
+
self.console, self.stores, self.auth = console, stores, authenticator
|
|
113
|
+
self.sessions, self.users, self.sso, self.throttle = sessions, users, sso, Throttle()
|
|
114
|
+
|
|
115
|
+
async def handle(self, request, operation, *, authenticate=True):
|
|
116
|
+
started, request_id, principal_id, status = time.monotonic(), new_request_id(), "-", 500
|
|
117
|
+
with log_context(request_id=request_id):
|
|
118
|
+
try:
|
|
119
|
+
principal = None
|
|
120
|
+
if authenticate:
|
|
121
|
+
principal = await run_in_threadpool(self.auth.authenticate, request.headers.get("authorization"))
|
|
122
|
+
principal_id = principal.id
|
|
123
|
+
result = await operation(request, principal)
|
|
124
|
+
response = result if isinstance(result, Response) else _json(200, result, request_id)
|
|
125
|
+
except RequestError as exc:
|
|
126
|
+
response = JSONResponse({"status": "error", "code": exc.code, "message": exc.message,
|
|
127
|
+
"request_id": request_id}, status_code=exc.status,
|
|
128
|
+
headers={**_HEADERS, **(exc.headers or {}), "X-Request-ID": request_id})
|
|
129
|
+
except Exception:
|
|
130
|
+
LOG.exception("request %s failed", request_id)
|
|
131
|
+
response = _json(500, {"status": "error", "code": "internal", "message": "the request failed; the "
|
|
132
|
+
"operator's log has the details", "request_id": request_id}, request_id)
|
|
133
|
+
for name, value in {**_HEADERS, "X-Request-ID": request_id}.items(): # a file's too
|
|
134
|
+
response.headers.setdefault(name, value)
|
|
135
|
+
status = response.status_code
|
|
136
|
+
ACCESS.info("%s %s %s %d %.0fms", request.method, request.url.path, principal_id, status,
|
|
137
|
+
(time.monotonic() - started) * 1000, extra={"principal": principal_id, "status": status})
|
|
138
|
+
return response
|
|
139
|
+
|
|
140
|
+
def _client(self, request, principal):
|
|
141
|
+
client = self.console.clients.get(request.path_params["client"])
|
|
142
|
+
if client is None or not may_pick(self.console, principal, client):
|
|
143
|
+
raise RequestError(404, "not-found", "no client %r" % request.path_params["client"])
|
|
144
|
+
return client
|
|
145
|
+
|
|
146
|
+
def _store(self, client, query):
|
|
147
|
+
if "store" in query:
|
|
148
|
+
return query["store"]
|
|
149
|
+
if len(client.stores) == 1:
|
|
150
|
+
return next(iter(client.stores))
|
|
151
|
+
raise RequestError(400, "store-required", "the client has several stores: give ?store= (%s)" % ", ".join(
|
|
152
|
+
client.stores))
|
|
153
|
+
|
|
154
|
+
async def _read(self, client, read):
|
|
155
|
+
"""read(opened) on the client's open stores; a store that failed is retried once with fresh secrets (at most
|
|
156
|
+
every ERROR_SECONDS)."""
|
|
157
|
+
def work():
|
|
158
|
+
opened = self.stores.get(client.id)
|
|
159
|
+
result, failed = read(opened)
|
|
160
|
+
again = self.stores.reopen(client.id, opened) if failed else None
|
|
161
|
+
if again is not None:
|
|
162
|
+
result, failed = read(again)
|
|
163
|
+
return result
|
|
164
|
+
return await run_in_threadpool(work)
|
|
165
|
+
|
|
166
|
+
# --- pages ------------------------------------------------------------------------------------------------
|
|
167
|
+
|
|
168
|
+
async def page(self, request, principal):
|
|
169
|
+
with open(os.path.join(_STATIC, "index.html"), encoding="utf-8") as stream:
|
|
170
|
+
body = stream.read()
|
|
171
|
+
return Response(body, media_type="text/html", headers={**_HEADERS, "Content-Security-Policy": _POLICY})
|
|
172
|
+
|
|
173
|
+
async def static(self, request, principal):
|
|
174
|
+
name = request.path_params["name"]
|
|
175
|
+
if name not in _FILES:
|
|
176
|
+
raise RequestError(404, "not-found", "no such file")
|
|
177
|
+
with open(os.path.join(_STATIC, name), "rb") as stream:
|
|
178
|
+
return Response(stream.read(), media_type=_FILES[name], headers=dict(_HEADERS))
|
|
179
|
+
|
|
180
|
+
async def healthz(self, request, principal):
|
|
181
|
+
return {"status": "ok"}
|
|
182
|
+
|
|
183
|
+
async def openapi(self, request, principal):
|
|
184
|
+
return openapi(self.console.has_auth)
|
|
185
|
+
|
|
186
|
+
# --- the API ----------------------------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
async def clients(self, request, principal):
|
|
189
|
+
parse_query(request, ())
|
|
190
|
+
return {"clients": [{"id": client.id, "name": client.name, "stores": list(client.stores),
|
|
191
|
+
"acknowledge": [name for name, block in client.stores.items() if not duckdb_store(block)]
|
|
192
|
+
if may_ack(self.console, principal, client) else [],
|
|
193
|
+
"logs": list(self._log_stores(client, principal))}
|
|
194
|
+
for client in self.console.clients.values()
|
|
195
|
+
if may_pick(self.console, principal, client)], "logs_link": self.console.logs_link}
|
|
196
|
+
|
|
197
|
+
async def overview(self, request, principal):
|
|
198
|
+
client = self._client(request, principal)
|
|
199
|
+
parse_query(request, ())
|
|
200
|
+
return await self._read(client, overview.overview)
|
|
201
|
+
|
|
202
|
+
async def jobs(self, request, principal):
|
|
203
|
+
client = self._client(request, principal)
|
|
204
|
+
query = parse_query(request, ("job", "health", "q", "filter", "store", "since", "until", "sort", "order",
|
|
205
|
+
"limit", "offset"), client)
|
|
206
|
+
for name, allowed in (("health", reads.HEALTHS), ("sort", reads.SORTS), ("order", ("asc", "desc"))):
|
|
207
|
+
one_of(query, name, allowed)
|
|
208
|
+
order, conditions = query.get("order"), filter_conditions(query, filters.JOB_FIELDS)
|
|
209
|
+
return await self._read(client, lambda opened: reads.jobs(
|
|
210
|
+
opened, job=query.get("job"), health=query.get("health"), text=query.get("q"), since=query.get("since"),
|
|
211
|
+
until=query.get("until"), sort=query.get("sort", "last"), descending=order and order == "desc",
|
|
212
|
+
store=query.get("store"), limit=query.get("limit", 50), offset=query.get("offset", 0),
|
|
213
|
+
conditions=conditions))
|
|
214
|
+
|
|
215
|
+
async def batches(self, request, principal):
|
|
216
|
+
client = self._client(request, principal)
|
|
217
|
+
query = parse_query(request, ("store", "scope", "status", "limit"), client)
|
|
218
|
+
one_of(query, "status", STATUSES)
|
|
219
|
+
store, job = self._store(client, query), request.path_params["job"]
|
|
220
|
+
return await self._read(client, lambda opened: reads.batches(
|
|
221
|
+
opened, store, job, scope=query.get("scope"), status=query.get("status"), limit=query.get("limit", 50)))
|
|
222
|
+
|
|
223
|
+
async def batch(self, request, principal):
|
|
224
|
+
client = self._client(request, principal)
|
|
225
|
+
query = parse_query(request, ("store", "job"), client)
|
|
226
|
+
store, job_id = self._store(client, query), request.path_params["job_id"]
|
|
227
|
+
|
|
228
|
+
def read(opened):
|
|
229
|
+
found, failed = reads.batch(opened, store, job_id, query.get("job"))
|
|
230
|
+
return (found, "unreachable" if store in failed else opened.errors.get(store)), failed
|
|
231
|
+
|
|
232
|
+
found, error = await self._read(client, read)
|
|
233
|
+
if found is None:
|
|
234
|
+
raise RequestError(503, error, "store %s: %s" % (store, error)) if error else RequestError(
|
|
235
|
+
404, "not-found", "no batch %r in store %s" % (job_id, store))
|
|
236
|
+
return dict(found, client=client.id, store=store)
|
|
237
|
+
|
|
238
|
+
async def attention(self, request, principal):
|
|
239
|
+
client = self._client(request, principal)
|
|
240
|
+
query = parse_query(request, ("kind", "acked", "filter", "since", "until", "limit", "offset"), client)
|
|
241
|
+
for name, allowed in (("kind", attention.KINDS), ("acked", overview.ACKED)):
|
|
242
|
+
one_of(query, name, allowed)
|
|
243
|
+
conditions = filter_conditions(query, filters.ATTENTION_FIELDS)
|
|
244
|
+
return await self._read(client, lambda opened: overview.attention(
|
|
245
|
+
opened, kind=query.get("kind"), acked=query.get("acked", "no"), since=query.get("since"),
|
|
246
|
+
until=query.get("until"), conditions=conditions, limit=query.get("limit", 50),
|
|
247
|
+
offset=query.get("offset", 0)))
|
|
248
|
+
|
|
249
|
+
async def job_summaries(self, request, principal):
|
|
250
|
+
client = self._client(request, principal)
|
|
251
|
+
query = parse_query(request, ("job", "health", "filter", "since", "until", "sort", "order", "limit",
|
|
252
|
+
"offset"), client)
|
|
253
|
+
for name, allowed in (("health", reads.HEALTHS), ("sort", job_summaries.JOB_SUMMARY_SORTS),
|
|
254
|
+
("order", ("asc", "desc"))):
|
|
255
|
+
one_of(query, name, allowed)
|
|
256
|
+
order, conditions = query.get("order"), filter_conditions(query, filters.JOB_SUMMARY_FIELDS)
|
|
257
|
+
return await self._read(client, lambda opened: job_summaries.job_summaries(
|
|
258
|
+
opened, job=query.get("job"), health=query.get("health"), since=query.get("since"),
|
|
259
|
+
until=query.get("until"), sort=query.get("sort", "health"), descending=order and order == "desc",
|
|
260
|
+
limit=query.get("limit", 50), offset=query.get("offset", 0), conditions=conditions))
|
|
261
|
+
|
|
262
|
+
async def leases(self, request, principal):
|
|
263
|
+
client = self._client(request, principal)
|
|
264
|
+
conditions = filter_conditions(parse_query(request, ("filter",)), filters.LEASE_FIELDS)
|
|
265
|
+
return await self._read(client, lambda opened: reads.leases(opened, conditions=conditions))
|
|
266
|
+
|
|
267
|
+
async def job_runs(self, request, principal):
|
|
268
|
+
client = self._client(request, principal)
|
|
269
|
+
query = parse_query(request, ("job", "q", "filter", "status", "since", "until", "sort", "order", "limit",
|
|
270
|
+
"offset"), client)
|
|
271
|
+
for name, allowed in (("status", job_runs.RUN_STATUSES), ("sort", job_runs.JOB_RUN_SORTS),
|
|
272
|
+
("order", ("asc", "desc"))):
|
|
273
|
+
one_of(query, name, allowed)
|
|
274
|
+
statuses, order = (query["status"],) if "status" in query else (), query.get("order")
|
|
275
|
+
conditions = filter_conditions(query, filters.JOB_RUN_FIELDS)
|
|
276
|
+
logs = self._log_stores(client, principal)
|
|
277
|
+
return await self._read(client, lambda opened: job_runs.job_runs(
|
|
278
|
+
opened, job=query.get("job"), text=query.get("q"), statuses=statuses, since=query.get("since"),
|
|
279
|
+
until=query.get("until"), sort=query.get("sort", "started"), descending=order and order == "desc",
|
|
280
|
+
limit=query.get("limit", 50), offset=query.get("offset", 0), conditions=conditions, logs=logs))
|
|
281
|
+
|
|
282
|
+
async def _run_part(self, client, store, run_id, read):
|
|
283
|
+
"""read(opened) -> (a part of a run, failed stores): 400 for a run id several jobs have, 404 for none."""
|
|
284
|
+
def work(opened):
|
|
285
|
+
found, failed = read(opened)
|
|
286
|
+
return (found, "unreachable" if store in failed else opened.errors.get(store)), failed
|
|
287
|
+
|
|
288
|
+
found, error = await self._read(client, work)
|
|
289
|
+
if found is not None and "several" in found:
|
|
290
|
+
raise RequestError(400, "job-required", found["several"])
|
|
291
|
+
if found is None:
|
|
292
|
+
raise RequestError(503, error, "store %s: %s" % (store, error)) if error else RequestError(
|
|
293
|
+
404, "not-found", "no run %r in store %s" % (run_id, store))
|
|
294
|
+
return dict(found, client=client.id)
|
|
295
|
+
|
|
296
|
+
async def job_run(self, request, principal):
|
|
297
|
+
client = self._client(request, principal)
|
|
298
|
+
query = parse_query(request, ("store", "job"), client)
|
|
299
|
+
store, run_id = self._store(client, query), request.path_params["run_id"]
|
|
300
|
+
log = store in self._log_stores(client, principal)
|
|
301
|
+
return await self._run_part(client, store, run_id,
|
|
302
|
+
lambda opened: job_runs.job_run(opened, store, run_id, query.get("job"), log=log))
|
|
303
|
+
|
|
304
|
+
async def job_run_batches(self, request, principal):
|
|
305
|
+
client = self._client(request, principal)
|
|
306
|
+
query = parse_query(request, ("store", "job", "status", "limit", "offset"), client)
|
|
307
|
+
one_of(query, "status", STATUSES)
|
|
308
|
+
store, run_id = self._store(client, query), request.path_params["run_id"]
|
|
309
|
+
return await self._run_part(client, store, run_id, lambda opened: job_runs.job_run_batches(
|
|
310
|
+
opened, store, run_id, query.get("job"), status=query.get("status"), limit=query.get("limit", 50),
|
|
311
|
+
offset=query.get("offset", 0)))
|
|
312
|
+
|
|
313
|
+
async def job_run_rows(self, request, principal):
|
|
314
|
+
client = self._client(request, principal)
|
|
315
|
+
query = parse_query(request, ("store", "job", "limit"), client)
|
|
316
|
+
store, run_id = self._store(client, query), request.path_params["run_id"]
|
|
317
|
+
return await self._run_part(client, store, run_id, lambda opened: job_runs.job_run_rows(
|
|
318
|
+
opened, store, run_id, query.get("job"), limit=query.get("limit", 500)))
|
|
319
|
+
|
|
320
|
+
async def job(self, request, principal):
|
|
321
|
+
client = self._client(request, principal)
|
|
322
|
+
query = parse_query(request, ("store", "since", "until"), client)
|
|
323
|
+
return await self._read(client, lambda opened: job_page.job_page(
|
|
324
|
+
opened, request.path_params["job"], since=query.get("since"), until=query.get("until"),
|
|
325
|
+
store=query.get("store")))
|
|
326
|
+
|
|
327
|
+
async def runs(self, request, principal):
|
|
328
|
+
client = self._client(request, principal)
|
|
329
|
+
query = parse_query(request, ("job", "filter", "status", "since", "until", "sort", "order", "limit",
|
|
330
|
+
"offset"), client)
|
|
331
|
+
for name, allowed in (("status", REQUEST_STATUSES), ("sort", reads.RUN_SORTS), ("order", ("asc", "desc"))):
|
|
332
|
+
one_of(query, name, allowed)
|
|
333
|
+
statuses, order = (query["status"],) if "status" in query else (), query.get("order")
|
|
334
|
+
conditions = filter_conditions(query, filters.SERVE_RUN_FIELDS)
|
|
335
|
+
return await self._read(client, lambda opened: reads.runs(
|
|
336
|
+
opened, job=query.get("job"), statuses=statuses, since=query.get("since"), until=query.get("until"),
|
|
337
|
+
sort=query.get("sort", "queued"), descending=order and order == "desc", limit=query.get("limit", 50),
|
|
338
|
+
offset=query.get("offset", 0), conditions=conditions))
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _people(console, users, sso):
|
|
342
|
+
"""(sessions, console users, single sign-on) of auth.login (None where it sets none up)."""
|
|
343
|
+
login = console.login
|
|
344
|
+
if login is None:
|
|
345
|
+
return None, None, None
|
|
346
|
+
named = {name for client in console.clients.values() for name in (*client.principals, *client.ack_principals)}
|
|
347
|
+
return (Sessions(login), users or (Users(login.users, secrets=login.users_secrets) if login.users else None),
|
|
348
|
+
sso or (Sso(login.sso, groups=named) if login.sso else None))
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def create_app(console, stores=None, authenticator=None, *, users=None, sso=None):
|
|
352
|
+
"""The Starlette app of a Console (`stores`: its ClientStores; `authenticator`: API keys, JWTs and its sessions;
|
|
353
|
+
`users`, `sso`: auth.login's, by default)."""
|
|
354
|
+
sessions, users, sso = _people(console, users, sso)
|
|
355
|
+
authenticator = authenticator or ConsoleAuthenticator(console, sessions, users)
|
|
356
|
+
api = _Api(console, stores or ClientStores(console), authenticator, sessions=sessions, users=users, sso=sso)
|
|
357
|
+
|
|
358
|
+
def route(path, operation, authenticate=True, methods=("GET",), name=None):
|
|
359
|
+
async def endpoint(request):
|
|
360
|
+
return await api.handle(request, operation, authenticate=authenticate)
|
|
361
|
+
return Route(path, endpoint, methods=list(methods), name=name)
|
|
362
|
+
|
|
363
|
+
async def not_found(request, exc):
|
|
364
|
+
request_id = new_request_id()
|
|
365
|
+
status = getattr(exc, "status_code", 404)
|
|
366
|
+
return _json(status, {"status": "error", "code": "not-found" if status == 404 else "method-not-allowed",
|
|
367
|
+
"message": "no such endpoint" if status == 404 else "method not allowed",
|
|
368
|
+
"request_id": request_id}, request_id)
|
|
369
|
+
|
|
370
|
+
return Starlette(exception_handlers={404: not_found, 405: not_found}, routes=[
|
|
371
|
+
route("/", api.page, authenticate=False),
|
|
372
|
+
route("/static/{name}", api.static, authenticate=False),
|
|
373
|
+
route("/healthz", api.healthz, authenticate=False),
|
|
374
|
+
route("/readyz", api.healthz, authenticate=False),
|
|
375
|
+
route("/openapi.json", api.openapi),
|
|
376
|
+
route("/v1/config", api.config, authenticate=False),
|
|
377
|
+
route("/v1/login", api.login, authenticate=False, methods=("POST",)),
|
|
378
|
+
route("/login/sso", api.sso_start, authenticate=False),
|
|
379
|
+
route("/login/callback", api.sso_callback, authenticate=False, name="sso_callback"),
|
|
380
|
+
route("/v1/login/exchange", api.sso_exchange, authenticate=False, methods=("POST",)),
|
|
381
|
+
route("/v1/me", api.me),
|
|
382
|
+
route("/v1/clients", api.clients),
|
|
383
|
+
route("/v1/clients/{client}/overview", api.overview),
|
|
384
|
+
route("/v1/clients/{client}/jobs", api.jobs),
|
|
385
|
+
route("/v1/clients/{client}/job-summaries", api.job_summaries),
|
|
386
|
+
route("/v1/clients/{client}/jobs/{job}/batches", api.batches),
|
|
387
|
+
route("/v1/clients/{client}/batches/{job_id}", api.batch),
|
|
388
|
+
route("/v1/clients/{client}/attention", api.attention),
|
|
389
|
+
route("/v1/clients/{client}/leases", api.leases),
|
|
390
|
+
route("/v1/clients/{client}/runs", api.runs),
|
|
391
|
+
route("/v1/clients/{client}/job-runs", api.job_runs),
|
|
392
|
+
route("/v1/clients/{client}/job-runs/{run_id}", api.job_run),
|
|
393
|
+
route("/v1/clients/{client}/job-runs/{run_id}/batches", api.job_run_batches),
|
|
394
|
+
route("/v1/clients/{client}/job-runs/{run_id}/rows", api.job_run_rows),
|
|
395
|
+
route("/v1/clients/{client}/job-runs/{run_id}/log", api.run_log),
|
|
396
|
+
route("/v1/clients/{client}/job-runs/{run_id}/log/download", api.run_log_download),
|
|
397
|
+
route("/v1/clients/{client}/jobs/{job}", api.job),
|
|
398
|
+
route("/v1/clients/{client}/acks", api.ack, methods=("POST",)),
|
|
399
|
+
route("/v1/clients/{client}/acks", api.unack, methods=("DELETE",)),
|
|
400
|
+
route("/v1/clients/{client}/acks/{target}", api.unack, methods=("DELETE",)),
|
|
401
|
+
])
|