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,139 @@
|
|
|
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 login page's routes, a part of the console's API (streamwright.console.api.app): what the page offers, a console
|
|
19
|
+
user's sign-in, single sign-on (streamwright.console.auth.sso), and who the caller is.
|
|
20
|
+
|
|
21
|
+
GET /v1/config whether the page asks to sign in, and how (login: {users, sso})
|
|
22
|
+
POST /v1/login {user, password} -> {token, expires_at, name}: a session (401 for any failure; 429
|
|
23
|
+
while the name or address waits)
|
|
24
|
+
GET /login/sso to the provider; it sends the person back to /login/callback
|
|
25
|
+
GET /login/callback back to the page with a one-time code (#/signed-in?code=...)
|
|
26
|
+
POST /v1/login/exchange {code} -> {token, expires_at, name}: the session the code stands for (once, 60 s)
|
|
27
|
+
GET /v1/me {id, kind, name, recorded_as, acknowledges: [client ids]}
|
|
28
|
+
|
|
29
|
+
A session is sent as `Authorization: Bearer`; signing out is the page forgetting it.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
import ipaddress
|
|
33
|
+
import logging
|
|
34
|
+
from types import MappingProxyType
|
|
35
|
+
|
|
36
|
+
from starlette.concurrency import run_in_threadpool
|
|
37
|
+
from starlette.responses import RedirectResponse
|
|
38
|
+
from streamwright.core.http_service.errors import RequestError
|
|
39
|
+
|
|
40
|
+
from streamwright.console.api.query import json_body, parse_query
|
|
41
|
+
from streamwright.console.auth.access import display_name, may_ack, may_pick, recorded_as
|
|
42
|
+
from streamwright.console.auth.sso import SsoError
|
|
43
|
+
from streamwright.console.auth.throttle import WAIT_SECONDS
|
|
44
|
+
from streamwright.console.auth.users import UsersUnreachableError
|
|
45
|
+
from streamwright.console.db.users import USER_ID
|
|
46
|
+
|
|
47
|
+
__all__ = ["LoginRoutes"]
|
|
48
|
+
|
|
49
|
+
LOG = logging.getLogger("streamwright.console")
|
|
50
|
+
_NO_STORE = MappingProxyType({"Cache-Control": "no-store", "Referrer-Policy": "no-referrer"})
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _address(request):
|
|
54
|
+
return request.client.host if request.client else "-"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _callback_url(request):
|
|
58
|
+
"""Where the provider sends the person back: https (the proxy's TLS), but on a loopback address."""
|
|
59
|
+
url = request.url_for("sso_callback")
|
|
60
|
+
try:
|
|
61
|
+
loopback = ipaddress.ip_address((url.hostname or "").strip("[]")).is_loopback
|
|
62
|
+
except ValueError:
|
|
63
|
+
loopback = url.hostname == "localhost"
|
|
64
|
+
return str(url if loopback else url.replace(scheme="https"))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class LoginRoutes:
|
|
68
|
+
"""The login routes of the console's API (self.console, self.sessions, self.users, self.sso, self.throttle)."""
|
|
69
|
+
|
|
70
|
+
async def config(self, request, principal):
|
|
71
|
+
login = self.console.login
|
|
72
|
+
return {"auth": self.console.has_auth,
|
|
73
|
+
"login": None if login is None else {"users": login.users is not None,
|
|
74
|
+
"sso": login.sso.label if login.sso else None}}
|
|
75
|
+
|
|
76
|
+
async def login(self, request, principal):
|
|
77
|
+
if self.users is None:
|
|
78
|
+
raise RequestError(404, "not-found", "console.yaml's auth.login has no users")
|
|
79
|
+
body = await json_body(request, ("user", "password"))
|
|
80
|
+
user, password = body.get("user"), body.get("password")
|
|
81
|
+
if not isinstance(user, str) or not isinstance(password, str) or not user.strip() or not password:
|
|
82
|
+
raise RequestError(400, "bad-body", "give user and password")
|
|
83
|
+
user, address = user.strip(), _address(request)
|
|
84
|
+
if self.throttle.waiting(user, address):
|
|
85
|
+
LOG.warning("sign-in of %r from %s refused: too many failures, it waits a minute", user, address)
|
|
86
|
+
raise RequestError(429, "wait", "too many failed sign-ins: try again in a minute",
|
|
87
|
+
{"Retry-After": str(WAIT_SECONDS)})
|
|
88
|
+
try:
|
|
89
|
+
found = await run_in_threadpool(self.users.sign_in, user if USER_ID.match(user) else "", password)
|
|
90
|
+
except UsersUnreachableError:
|
|
91
|
+
raise RequestError(503, "users-unreachable", "the console users cannot be read: the console's log says "
|
|
92
|
+
"why") from None
|
|
93
|
+
if found is None:
|
|
94
|
+
self.throttle.failed(user, address)
|
|
95
|
+
LOG.warning("sign-in of %r from %s failed", user, address)
|
|
96
|
+
raise RequestError(401, "sign-in-failed", "the user name or password is not right")
|
|
97
|
+
self.throttle.succeeded(user)
|
|
98
|
+
LOG.info("%s signed in from %s", found.id, address)
|
|
99
|
+
return {**self.sessions.issue(found), "name": display_name(found)}
|
|
100
|
+
|
|
101
|
+
async def me(self, request, principal):
|
|
102
|
+
parse_query(request, ())
|
|
103
|
+
visible = [client for client in self.console.clients.values() if may_pick(self.console, principal, client)]
|
|
104
|
+
return {"id": principal.id, "kind": principal.kind, "name": display_name(principal),
|
|
105
|
+
"recorded_as": recorded_as(principal),
|
|
106
|
+
"acknowledges": [client.id for client in visible if may_ack(self.console, principal, client)]}
|
|
107
|
+
|
|
108
|
+
# --- single sign-on --------------------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
def _sso(self):
|
|
111
|
+
if self.sso is None:
|
|
112
|
+
raise RequestError(404, "not-found", "console.yaml's auth.login has no sso")
|
|
113
|
+
return self.sso
|
|
114
|
+
|
|
115
|
+
async def sso_start(self, request, principal):
|
|
116
|
+
sso = self._sso()
|
|
117
|
+
try:
|
|
118
|
+
target = await run_in_threadpool(sso.start, _callback_url(request))
|
|
119
|
+
except SsoError as exc: # the provider cannot be reached: back to the login page
|
|
120
|
+
LOG.warning("single sign-on cannot start: %s", exc)
|
|
121
|
+
target = "/#/signed-out?error=sso"
|
|
122
|
+
return RedirectResponse(target, status_code=302, headers=_NO_STORE)
|
|
123
|
+
|
|
124
|
+
async def sso_callback(self, request, principal):
|
|
125
|
+
sso, query = self._sso(), request.query_params
|
|
126
|
+
try:
|
|
127
|
+
code = await run_in_threadpool(sso.finish, query.get("state"), query.get("code"), query.get("error"))
|
|
128
|
+
except SsoError as exc:
|
|
129
|
+
LOG.warning("single sign-on from %s failed: %s", _address(request), exc)
|
|
130
|
+
return RedirectResponse("/#/signed-out?error=sso", status_code=302, headers=_NO_STORE)
|
|
131
|
+
return RedirectResponse("/#/signed-in?code=%s" % code, status_code=302, headers=_NO_STORE)
|
|
132
|
+
|
|
133
|
+
async def sso_exchange(self, request, principal):
|
|
134
|
+
body = await json_body(request, ("code",))
|
|
135
|
+
found = self._sso().exchange(body.get("code")) if isinstance(body.get("code"), str) else None
|
|
136
|
+
if found is None:
|
|
137
|
+
raise RequestError(401, "sign-in-failed", "the sign-in code is not valid (it lasts a minute, once)")
|
|
138
|
+
LOG.info("%s signed in with single sign-on from %s", found.id, _address(request))
|
|
139
|
+
return {**self.sessions.issue(found), "name": display_name(found)}
|
|
@@ -0,0 +1,113 @@
|
|
|
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 run log routes of the console's API (streamwright.console.views.run_log): a page of a run's own log file, and the
|
|
19
|
+
file itself. Only for a store whose console.yaml entry sets logs.dir, and for who may read the client's logs (its
|
|
20
|
+
log_principals, else all its principals).
|
|
21
|
+
|
|
22
|
+
GET /v1/clients/C/job-runs/RUN_ID/log ?store=&job=&before=|after=&limit=&level=&q=&job_id=
|
|
23
|
+
GET /v1/clients/C/job-runs/RUN_ID/log/download ?store=&job=
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import logging
|
|
27
|
+
import os
|
|
28
|
+
|
|
29
|
+
from starlette.concurrency import run_in_threadpool
|
|
30
|
+
from starlette.responses import StreamingResponse
|
|
31
|
+
from streamwright.core.http_service.errors import RequestError
|
|
32
|
+
from streamwright.core.runtime.logs.run_log_read import LEVELS
|
|
33
|
+
|
|
34
|
+
from streamwright.console.api.query import parse_query
|
|
35
|
+
from streamwright.console.auth.access import may_read_logs
|
|
36
|
+
from streamwright.console.views import run_log
|
|
37
|
+
|
|
38
|
+
__all__ = ["LogRoutes"]
|
|
39
|
+
|
|
40
|
+
LOG = logging.getLogger("streamwright.console")
|
|
41
|
+
_PAGE = ("store", "job", "before", "after", "limit", "level", "q", "job_id")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _levels(text):
|
|
45
|
+
levels = tuple(level for level in (text or "").split(",") if level)
|
|
46
|
+
if any(level not in LEVELS for level in levels):
|
|
47
|
+
raise RequestError(400, "bad-query", "level: one or more of %s, comma-separated" % ", ".join(LEVELS))
|
|
48
|
+
return levels
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class LogRoutes:
|
|
52
|
+
"""The log routes (a mixin of the console's _Api: _client, _store and _read)."""
|
|
53
|
+
|
|
54
|
+
def _log_stores(self, client, principal):
|
|
55
|
+
"""The client's stores whose runs' logs `principal` sees (those with a logs.dir; none if they may not)."""
|
|
56
|
+
return tuple(client.log_dirs) if may_read_logs(self.console, principal, client) else ()
|
|
57
|
+
|
|
58
|
+
def _log_folder(self, client, principal, store):
|
|
59
|
+
if not may_read_logs(self.console, principal, client):
|
|
60
|
+
raise RequestError(403, "forbidden", "you may not read this client's logs (its log_principals)")
|
|
61
|
+
folder = client.log_dirs.get(store)
|
|
62
|
+
if folder is None:
|
|
63
|
+
raise RequestError(404, "logs-not-set", "store %s shows no logs: its console.yaml entry sets no "
|
|
64
|
+
"logs.dir" % store)
|
|
65
|
+
return folder
|
|
66
|
+
|
|
67
|
+
async def _log_entry(self, client, store, run_id, job):
|
|
68
|
+
def work(opened):
|
|
69
|
+
found, failed = run_log.log_entry(opened, store, run_id, job)
|
|
70
|
+
return (found, "unreachable" if store in failed else opened.errors.get(store)), failed
|
|
71
|
+
|
|
72
|
+
found, error = await self._read(client, work)
|
|
73
|
+
if run_log.is_pending(found):
|
|
74
|
+
raise RequestError(503, "migrations-pending", "store %s: its state tables need `streamwright state "
|
|
75
|
+
"migrate` before runs' logs show" % store)
|
|
76
|
+
if found is not None and "several" in found:
|
|
77
|
+
raise RequestError(400, "job-required", found["several"])
|
|
78
|
+
if found is None:
|
|
79
|
+
raise RequestError(503, error, "store %s: %s" % (store, error)) if error else RequestError(
|
|
80
|
+
404, "no-log", "run %r has no log file in store %s (it ran without --log-dir)" % (run_id, store))
|
|
81
|
+
return found
|
|
82
|
+
|
|
83
|
+
def _refused(self, client, store, run_id, reason, why):
|
|
84
|
+
if reason == "refused": # a row that names another file: say so in the operator's log
|
|
85
|
+
LOG.warning("client %s, store %s, run %s: its log's path is refused: %s", client.id, store, run_id, why)
|
|
86
|
+
|
|
87
|
+
async def run_log(self, request, principal):
|
|
88
|
+
client = self._client(request, principal)
|
|
89
|
+
query = parse_query(request, _PAGE, client)
|
|
90
|
+
if "before" in query and "after" in query:
|
|
91
|
+
raise RequestError(400, "bad-query", "give before or after, not both")
|
|
92
|
+
levels = _levels(query.get("level"))
|
|
93
|
+
store, run_id = self._store(client, query), request.path_params["run_id"]
|
|
94
|
+
folder = self._log_folder(client, principal, store)
|
|
95
|
+
entry = await self._log_entry(client, store, run_id, query.get("job"))
|
|
96
|
+
page = await run_in_threadpool(run_log.log_page, folder, entry, run_id, before=query.get("before"),
|
|
97
|
+
after=query.get("after"), limit=query.get("limit", 200), levels=levels,
|
|
98
|
+
text=query.get("q"), job_id=query.get("job_id"))
|
|
99
|
+
self._refused(client, store, run_id, page["reason"], page["message"])
|
|
100
|
+
return dict(page, client=client.id, store=store, job=entry["job_name"], run_id=run_id)
|
|
101
|
+
|
|
102
|
+
async def run_log_download(self, request, principal):
|
|
103
|
+
client = self._client(request, principal)
|
|
104
|
+
query = parse_query(request, ("store", "job"), client)
|
|
105
|
+
store, run_id = self._store(client, query), request.path_params["run_id"]
|
|
106
|
+
folder = self._log_folder(client, principal, store)
|
|
107
|
+
entry = await self._log_entry(client, store, run_id, query.get("job"))
|
|
108
|
+
reader, problem = await run_in_threadpool(run_log.log_reader, folder, entry, run_id)
|
|
109
|
+
if reader is None:
|
|
110
|
+
self._refused(client, store, run_id, *problem)
|
|
111
|
+
raise RequestError(404, "log-%s" % problem[0], problem[1])
|
|
112
|
+
return StreamingResponse(reader.chunks(), media_type=reader.media_type, headers={
|
|
113
|
+
"Content-Disposition": 'attachment; filename="%s"' % os.path.basename(reader.path)})
|
|
@@ -0,0 +1,205 @@
|
|
|
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
|
+
"""The console API's OpenAPI 3.1 document (`GET /openapi.json`): its routes, their filters and bodies."""
|
|
18
|
+
|
|
19
|
+
from types import MappingProxyType
|
|
20
|
+
|
|
21
|
+
from streamwright.core.jobs.state.acks import MAX_NOTE
|
|
22
|
+
from streamwright.core.jobs.state.conditions import OPS
|
|
23
|
+
|
|
24
|
+
from streamwright.console.views.attention import KINDS
|
|
25
|
+
from streamwright.console.views.filters import (
|
|
26
|
+
ATTENTION_FIELDS,
|
|
27
|
+
JOB_FIELDS,
|
|
28
|
+
JOB_RUN_FIELDS,
|
|
29
|
+
JOB_SUMMARY_FIELDS,
|
|
30
|
+
LEASE_FIELDS,
|
|
31
|
+
MAX_FILTERS,
|
|
32
|
+
SERVE_RUN_FIELDS,
|
|
33
|
+
)
|
|
34
|
+
from streamwright.console.views.job_runs import JOB_RUN_SORTS, RUN_STATUSES
|
|
35
|
+
from streamwright.console.views.job_summaries import JOB_SUMMARY_SORTS
|
|
36
|
+
from streamwright.console.views.overview import ACKED
|
|
37
|
+
from streamwright.console.views.reads import HEALTHS, RUN_SORTS, SORTS
|
|
38
|
+
|
|
39
|
+
__all__ = ["openapi"]
|
|
40
|
+
|
|
41
|
+
_ERROR = MappingProxyType({"type": "object", "required": ["status", "code", "message", "request_id"],
|
|
42
|
+
"properties": {key: {"type": "string"} for key in ("status", "code", "message",
|
|
43
|
+
"request_id")}})
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _filter(fields):
|
|
47
|
+
return {"type": "array", "items": {"type": "string"}, "maxItems": MAX_FILTERS,
|
|
48
|
+
"description": "FIELD:OP:VALUE, repeatable, all must hold (case aside): FIELD %s; OP %s" % (
|
|
49
|
+
", ".join(fields), ", ".join(OPS))}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
_ROUTES = MappingProxyType({
|
|
53
|
+
"/v1/clients": ("list_clients", "the clients the caller may pick (no store is opened), and the logs link", ()),
|
|
54
|
+
"/v1/clients/{client}/overview": ("get_overview", "stores, jobs and scopes counted by health, failed runs, and how "
|
|
55
|
+
"many items need a person or were acknowledged", ()),
|
|
56
|
+
"/v1/clients/{client}/jobs": ("list_jobs", "a page of the jobs and scopes (of one job), newest batch first: "
|
|
57
|
+
"health, latest batch, last success, 24 hours, acknowledgement; with the total and "
|
|
58
|
+
"each health's count",
|
|
59
|
+
("job", "health", "q", ("filter", "job_filter"), "store", "since", "until", "sort",
|
|
60
|
+
"order", "limit", "offset")),
|
|
61
|
+
"/v1/clients/{client}/job-summaries": ("list_job_summaries", "a page of the jobs, each once: health, scopes by "
|
|
62
|
+
"health now, latest run, runs and rows in the period; with the total and "
|
|
63
|
+
"each health's count",
|
|
64
|
+
("job", "health", ("filter", "job_summary_filter"), "since", "until",
|
|
65
|
+
("sort", "job_summary_sort"), "order", "limit", "offset")),
|
|
66
|
+
"/v1/clients/{client}/jobs/{job}/batches": ("list_batches", "a job's batches, newest first",
|
|
67
|
+
("store", "scope", "status", "limit")),
|
|
68
|
+
"/v1/clients/{client}/batches/{job_id}": ("get_batch", "one batch: timeline, pinned config, outputs, the rows "
|
|
69
|
+
"not applied (no row values), its acknowledgement and commands",
|
|
70
|
+
("store", "job")),
|
|
71
|
+
"/v1/clients/{client}/attention": ("list_attention", "a page of what needs a person (or was acknowledged), each "
|
|
72
|
+
"with the commands that settle it; with each kind's and each tab's count",
|
|
73
|
+
("kind", "acked", ("filter", "attention_filter"), "since", "until", "limit",
|
|
74
|
+
"offset")),
|
|
75
|
+
"/v1/clients/{client}/leases": ("list_leases", "each lease, its holder and expiry", (("filter", "lease_filter"),)),
|
|
76
|
+
"/v1/clients/{client}/runs": ("list_runs", "a page of the serve runs of stores that are serve queues, newest "
|
|
77
|
+
"first, with the total (no inputs, no rows)",
|
|
78
|
+
("job", ("filter", "run_filter"), "status", "since", "until", ("sort", "run_sort"),
|
|
79
|
+
"order", "limit", "offset")),
|
|
80
|
+
"/v1/clients/{client}/job-runs": ("list_job_runs", "a page of the jobs' runs (sw_runs), newest first: how each "
|
|
81
|
+
"ended, its passes and the failures no batch shows; with the total and each "
|
|
82
|
+
"status's count", ("job", "q", ("filter", "job_run_filter"),
|
|
83
|
+
("status", "run_status"), "since", "until",
|
|
84
|
+
("sort", "job_run_sort"), "order", "limit", "offset")),
|
|
85
|
+
"/v1/clients/{client}/job-runs/{run_id}": ("get_job_run", "one run of a job: what failed in it (each pass or "
|
|
86
|
+
"item, its batches, its error), its batches' totals and outputs, and "
|
|
87
|
+
"the commands that settle them", ("store", "job")),
|
|
88
|
+
"/v1/clients/{client}/job-runs/{run_id}/batches": ("list_job_run_batches", "a page of the batches a run made or "
|
|
89
|
+
"resumed, newest first, with the total and each status's count",
|
|
90
|
+
("store", "job", "status", "limit", "offset")),
|
|
91
|
+
"/v1/clients/{client}/job-runs/{run_id}/rows": ("list_job_run_rows", "the rows a run's batches did not apply (no "
|
|
92
|
+
"values) and its rejected rows grouped by output, tag and error "
|
|
93
|
+
"code", ("store", "job", "limit")),
|
|
94
|
+
"/v1/clients/{client}/job-runs/{run_id}/log": ("get_job_run_log", "a page of a run's own log file (--log-dir; "
|
|
95
|
+
"a store with logs.dir): its last lines, or those before or after "
|
|
96
|
+
"a cursor, filtered; where it is, or why this host cannot read it",
|
|
97
|
+
("store", "job", ("before", "log_cursor"), ("after", "log_cursor"),
|
|
98
|
+
"limit", ("level", "log_level"), ("q", "log_text"),
|
|
99
|
+
("job_id", "log_job_id"))),
|
|
100
|
+
"/v1/clients/{client}/job-runs/{run_id}/log/download": ("download_job_run_log", "a run's own log file: "
|
|
101
|
+
"<name>.log.gz once the run ended, else its JSON lines",
|
|
102
|
+
("store", "job")),
|
|
103
|
+
"/v1/clients/{client}/jobs/{job}": ("get_job", "one job: its runs and batches in a period (counts, durations, "
|
|
104
|
+
"outputs, rows applied and rejected, rejections grouped), its scopes' health "
|
|
105
|
+
"now", ("store", "since", "until")),
|
|
106
|
+
})
|
|
107
|
+
_FILTERS = MappingProxyType({
|
|
108
|
+
"store": {"type": "string", "description": "the store's name (needed when the client has several)"},
|
|
109
|
+
"scope": {"type": "string", "description": "a scope; empty: the unscoped batches"}, "job": {"type": "string"},
|
|
110
|
+
"status": {"type": "string", "description": "a batch or run status"},
|
|
111
|
+
"limit": {"type": "integer", "minimum": 1, "maximum": 500},
|
|
112
|
+
"offset": {"type": "integer", "minimum": 0, "description": "the rows to skip (default 0)"},
|
|
113
|
+
"health": {"type": "string", "enum": list(HEALTHS)},
|
|
114
|
+
"q": {"type": "string", "description": "text in the job, the scope or the store (any case)"},
|
|
115
|
+
"since": {"type": "string", "description": "made at or after: an ISO date (UTC midnight) or time"},
|
|
116
|
+
"until": {"type": "string", "description": "made before: an ISO date (that whole day is in) or time"},
|
|
117
|
+
"sort": {"type": "string", "enum": list(SORTS), "description": "default: last (the newest batch's time)"},
|
|
118
|
+
"run_sort": {"type": "string", "enum": list(RUN_SORTS), "description": "default: queued (newest first)"},
|
|
119
|
+
"run_status": {"type": "string", "enum": list(RUN_STATUSES)},
|
|
120
|
+
"job_run_sort": {"type": "string", "enum": list(JOB_RUN_SORTS), "description": "default: started (newest first)"},
|
|
121
|
+
"job_summary_sort": {"type": "string", "enum": list(JOB_SUMMARY_SORTS),
|
|
122
|
+
"description": "default: health (the worst first, then the newest)"},
|
|
123
|
+
"kind": {"type": "string", "enum": list(KINDS), "description": "held takes interrupted batches; other: expired "
|
|
124
|
+
"leases, pending migrations, stores down"},
|
|
125
|
+
"acked": {"type": "string", "enum": list(ACKED), "description": "no (default): what needs a person; yes: what a "
|
|
126
|
+
"person acknowledged (state ack); all"},
|
|
127
|
+
"order": {"type": "string", "enum": ["asc", "desc"],
|
|
128
|
+
"description": "default: desc for times, durations and rows, else asc"},
|
|
129
|
+
"all": {"type": "string", "enum": ["1"], "description": "every acknowledgement of the job"},
|
|
130
|
+
"log_cursor": {"type": "string", "description": "a page's before or after cursor"},
|
|
131
|
+
"log_level": {"type": "string", "description": "levels, comma-separated: error, warning, info, debug"},
|
|
132
|
+
"log_text": {"type": "string", "description": "text in a line's message or exception (any case)"},
|
|
133
|
+
"log_job_id": {"type": "string", "description": "one batch's lines (its job id)"},
|
|
134
|
+
**{name: _filter(fields) for name, fields in (("job_filter", JOB_FIELDS), ("job_run_filter", JOB_RUN_FIELDS),
|
|
135
|
+
("run_filter", SERVE_RUN_FIELDS), ("lease_filter", LEASE_FIELDS),
|
|
136
|
+
("attention_filter", ATTENTION_FIELDS),
|
|
137
|
+
("job_summary_filter", JOB_SUMMARY_FIELDS))},
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
_TEXT = MappingProxyType({"type": "string"})
|
|
142
|
+
_BODIES = MappingProxyType({
|
|
143
|
+
"login": {"type": "object", "required": ["user", "password"],
|
|
144
|
+
"properties": {"user": dict(_TEXT), "password": {"type": "string", "format": "password"}}},
|
|
145
|
+
"exchange": {"type": "object", "required": ["code"], "properties": {"code": dict(_TEXT)}},
|
|
146
|
+
"ack": {"type": "object", "properties": {
|
|
147
|
+
"store": {"type": "string", "description": "the store's name (needed when the client has several)"},
|
|
148
|
+
"job": {"type": "string", "description": "the job (needed with all, or for a job id several jobs have)"},
|
|
149
|
+
"target": {"type": "string", "description": "a batch's job id or a run's id"},
|
|
150
|
+
"all": {"type": "boolean", "description": "the job's failed and rejected scopes and failed run, held ones "
|
|
151
|
+
"aside (as `state ack --job`)"},
|
|
152
|
+
"note": {"type": "string", "maxLength": MAX_NOTE}}},
|
|
153
|
+
})
|
|
154
|
+
# (path, method, operationId, summary, query parameters, body, open to anyone)
|
|
155
|
+
_ACTIONS = (
|
|
156
|
+
("/v1/me", "get", "get_me", "who the caller is: id, name, what an acknowledgement records as them, the clients "
|
|
157
|
+
"they may acknowledge in", (), None, False),
|
|
158
|
+
("/v1/login", "post", "sign_in", "a console user's sign-in: a session {token, expires_at, name}; 401 for any "
|
|
159
|
+
"failure, 429 while the name or address waits", (), "login", True),
|
|
160
|
+
("/v1/login/exchange", "post", "exchange_sign_in_code", "the session a single sign-on's one-time code stands for "
|
|
161
|
+
"(once, within a minute)", (), "exchange", True),
|
|
162
|
+
("/v1/clients/{client}/acks", "post", "acknowledge", "acknowledge an item (target) or a job's items (all: true): "
|
|
163
|
+
"403 for a caller the client's ack_principals do not list, "
|
|
164
|
+
"409 for an item that needs no one, 501 for a DuckDB store",
|
|
165
|
+
(), "ack", False),
|
|
166
|
+
("/v1/clients/{client}/acks", "delete", "undo_job_acknowledgements", "undo every acknowledgement of a job",
|
|
167
|
+
("store", "job", "all"), None, False),
|
|
168
|
+
("/v1/clients/{client}/acks/{target}", "delete", "undo_acknowledgement", "undo an item's acknowledgement (409: "
|
|
169
|
+
"it has none)", ("store", "job"), None,
|
|
170
|
+
False),
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _operation(path, operation, summary, filters, body=None):
|
|
175
|
+
parameters = [{"name": name, "in": "path", "required": True, "schema": {"type": "string"}}
|
|
176
|
+
for name in ("client", "job", "job_id", "run_id", "target") if "{%s}" % name in path]
|
|
177
|
+
parameters += [{"name": name, "in": "query", "required": False, "schema": dict(_FILTERS[schema])}
|
|
178
|
+
for name, schema in (item if isinstance(item, tuple) else (item, item) for item in filters)]
|
|
179
|
+
found = {"operationId": operation, "summary": summary, "parameters": parameters, "responses": {
|
|
180
|
+
"200": {"description": summary, "content": {"application/json": {"schema": {"type": "object"}}}},
|
|
181
|
+
"404": {"description": "no such client, or one the caller may not pick"},
|
|
182
|
+
"default": {"description": "an error", "content": {"application/json": {"schema": dict(_ERROR)}}}}}
|
|
183
|
+
if body:
|
|
184
|
+
found["requestBody"] = {"required": True, "content": {"application/json": {"schema": dict(_BODIES[body])}}}
|
|
185
|
+
return found
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def openapi(authenticated):
|
|
189
|
+
"""OpenAPI 3.1 of the console's API (`authenticated`: callers send a bearer token)."""
|
|
190
|
+
paths = {path: {"get": _operation(path, operation, summary, filters)}
|
|
191
|
+
for path, (operation, summary, filters) in _ROUTES.items()}
|
|
192
|
+
paths["/v1/clients/{client}/job-runs/{run_id}/log/download"]["get"]["responses"]["200"]["content"] = {
|
|
193
|
+
"application/gzip": {}, "application/x-ndjson": {}}
|
|
194
|
+
for path, method, operation, summary, filters, body, anyone in _ACTIONS:
|
|
195
|
+
paths.setdefault(path, {})[method] = _operation(path, operation, summary, filters, body)
|
|
196
|
+
if anyone and authenticated:
|
|
197
|
+
paths[path][method]["security"] = []
|
|
198
|
+
document = {"openapi": "3.1.0", "info": {"title": "StreamWright console", "version": "1",
|
|
199
|
+
"description": "Read-only, but for acknowledgements. Job health: %s." %
|
|
200
|
+
", ".join(HEALTHS)},
|
|
201
|
+
"paths": paths}
|
|
202
|
+
if authenticated:
|
|
203
|
+
document["components"] = {"securitySchemes": {"bearer": {"type": "http", "scheme": "bearer"}}}
|
|
204
|
+
document["security"] = [{"bearer": []}]
|
|
205
|
+
return document
|
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
"""
|
|
19
|
+
The query strings of the console's API: the parameters a route takes, each once (a filter may repeat), as checked text;
|
|
20
|
+
limit and offset as numbers, since and until as aware UTC times, filters as conditions on a list's fields. A bad one is
|
|
21
|
+
a RequestError (400; a store the client does not have: 404). And the JSON bodies of its few POST routes.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import datetime
|
|
25
|
+
import json
|
|
26
|
+
import re
|
|
27
|
+
|
|
28
|
+
from streamwright.core.http_service.errors import RequestError
|
|
29
|
+
|
|
30
|
+
from streamwright.console.views import filters
|
|
31
|
+
|
|
32
|
+
__all__ = ["filter_conditions", "json_body", "one_of", "parse_query"]
|
|
33
|
+
|
|
34
|
+
_TEXT = re.compile(r"^[\x20-\x7e]{1,512}$")
|
|
35
|
+
_LIMIT = 500
|
|
36
|
+
_OFFSET = 1_000_000
|
|
37
|
+
_DATE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
|
|
38
|
+
_MAX_BODY = 16 * 1024
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_query(request, allowed, client=None):
|
|
42
|
+
"""The request's filters: only `allowed` names, each once, as checked text (400 otherwise)."""
|
|
43
|
+
found = {}
|
|
44
|
+
for name, value in request.query_params.multi_items():
|
|
45
|
+
if name not in allowed or (name in found and name != "filter"):
|
|
46
|
+
raise RequestError(400, "bad-query", "query parameters: %s (each once; filter may repeat)" % ", ".join(
|
|
47
|
+
sorted(allowed)))
|
|
48
|
+
if not _TEXT.match(value) and not (name == "scope" and value == ""): # scope= : the unscoped batches
|
|
49
|
+
raise RequestError(400, "bad-query", "%s: printable text, at most 512 characters" % name)
|
|
50
|
+
if name == "filter":
|
|
51
|
+
found.setdefault(name, []).append(value)
|
|
52
|
+
else:
|
|
53
|
+
found[name] = value
|
|
54
|
+
for name, low, high in (("limit", 1, _LIMIT), ("offset", 0, _OFFSET)):
|
|
55
|
+
if name in found:
|
|
56
|
+
if not found[name].isdigit() or not low <= int(found[name]) <= high:
|
|
57
|
+
raise RequestError(400, "bad-query", "%s: a whole number from %d to %d" % (name, low, high))
|
|
58
|
+
found[name] = int(found[name])
|
|
59
|
+
for name in ("since", "until"):
|
|
60
|
+
if name in found:
|
|
61
|
+
found[name] = _instant(name, found[name])
|
|
62
|
+
if found.get("since") and found.get("until") and found["since"] >= found["until"]:
|
|
63
|
+
raise RequestError(400, "bad-query", "since: before until")
|
|
64
|
+
if "store" in found and client is not None and found["store"] not in client.stores:
|
|
65
|
+
raise RequestError(404, "not-found", "no store %r" % found["store"])
|
|
66
|
+
return found
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def filter_conditions(query, fields):
|
|
70
|
+
"""The list's filter conditions (filters.parse_filters), 400 when one is not FIELD:OP:VALUE of its fields."""
|
|
71
|
+
try:
|
|
72
|
+
return filters.parse_filters(query.get("filter"), fields)
|
|
73
|
+
except ValueError as exc:
|
|
74
|
+
raise RequestError(400, "bad-query", str(exc)) from None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _instant(name, text):
|
|
78
|
+
"""An aware UTC time from an ISO date (its midnight; for `until`, the next day's) or an ISO time (UTC if bare)."""
|
|
79
|
+
try:
|
|
80
|
+
if _DATE.match(text):
|
|
81
|
+
day = datetime.datetime.combine(datetime.date.fromisoformat(text), datetime.time(), datetime.UTC)
|
|
82
|
+
return day + datetime.timedelta(days=1) if name == "until" else day
|
|
83
|
+
when = datetime.datetime.fromisoformat(text.replace("Z", "+00:00"))
|
|
84
|
+
except ValueError:
|
|
85
|
+
raise RequestError(400, "bad-query", "%s: an ISO date (2026-11-28) or time (2026-11-28T09:30:00Z)" % name) \
|
|
86
|
+
from None
|
|
87
|
+
return when.replace(tzinfo=datetime.UTC) if when.tzinfo is None else when.astimezone(datetime.UTC)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def one_of(query, name, allowed):
|
|
91
|
+
if query.get(name) not in (None, *allowed):
|
|
92
|
+
raise RequestError(400, "bad-query", "%s: one of %s" % (name, ", ".join(allowed)))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
async def json_body(request, allowed):
|
|
96
|
+
"""
|
|
97
|
+
The request's JSON object: only `allowed` keys (400 otherwise). It is `application/json`, so a page on another
|
|
98
|
+
site cannot send it without the browser asking first (415 otherwise), and at most 16 KiB, read no further (413).
|
|
99
|
+
"""
|
|
100
|
+
if request.headers.get("content-type", "").split(";")[0].strip().lower() != "application/json":
|
|
101
|
+
raise RequestError(415, "bad-media-type", "send the body as application/json")
|
|
102
|
+
body = b""
|
|
103
|
+
async for chunk in request.stream():
|
|
104
|
+
body += chunk
|
|
105
|
+
if len(body) > _MAX_BODY:
|
|
106
|
+
raise RequestError(413, "too-large", "the body is over 16 KiB")
|
|
107
|
+
try:
|
|
108
|
+
found = json.loads(body)
|
|
109
|
+
except ValueError:
|
|
110
|
+
found = None
|
|
111
|
+
if not isinstance(found, dict) or set(found) - set(allowed):
|
|
112
|
+
raise RequestError(400, "bad-body", "a JSON object of %s (at most 16 KiB)" % ", ".join(sorted(allowed)))
|
|
113
|
+
return found
|
|
@@ -0,0 +1,21 @@
|
|
|
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
|
+
Who calls the console and what they may do: who may pick or acknowledge, and how a caller is named (access); the
|
|
19
|
+
console's sessions (sessions) and who a request comes from (authenticator); console users signing in (users, their
|
|
20
|
+
passwords, and a throttle of failed sign-ins); single sign-on with OpenID Connect (sso).
|
|
21
|
+
"""
|