imbi-scheduler 2.23.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.
- imbi_scheduler-2.23.0/.gitignore +22 -0
- imbi_scheduler-2.23.0/PKG-INFO +54 -0
- imbi_scheduler-2.23.0/README.md +37 -0
- imbi_scheduler-2.23.0/moon.yml +22 -0
- imbi_scheduler-2.23.0/pyproject.toml +47 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/__init__.py +6 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/app.py +59 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/app_status.py +72 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/endpoints/__init__.py +16 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/endpoints/dependencies.py +131 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/endpoints/runs.py +165 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/endpoints/tasks.py +359 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/engine.py +540 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/executor.py +353 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/identity.py +247 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/lifespans.py +97 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/models.py +365 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/py.typed +0 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/render.py +205 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/runs.py +264 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/settings.py +169 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/store/__init__.py +96 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/store/initializer.py +166 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/store/schemata.toml +91 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/store/tasks.py +619 -0
- imbi_scheduler-2.23.0/src/imbi/scheduler/triggers.py +286 -0
- imbi_scheduler-2.23.0/tests/__init__.py +0 -0
- imbi_scheduler-2.23.0/tests/helpers.py +79 -0
- imbi_scheduler-2.23.0/tests/test_app.py +131 -0
- imbi_scheduler-2.23.0/tests/test_endpoints.py +904 -0
- imbi_scheduler-2.23.0/tests/test_engine.py +677 -0
- imbi_scheduler-2.23.0/tests/test_executor.py +977 -0
- imbi_scheduler-2.23.0/tests/test_models.py +185 -0
- imbi_scheduler-2.23.0/tests/test_runs.py +252 -0
- imbi_scheduler-2.23.0/tests/test_store.py +758 -0
- imbi_scheduler-2.23.0/tests/test_triggers.py +382 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
__pycache__
|
|
2
|
+
*.egg-info
|
|
3
|
+
*.pyc
|
|
4
|
+
*.env
|
|
5
|
+
.env
|
|
6
|
+
.env.test
|
|
7
|
+
build/
|
|
8
|
+
dist/
|
|
9
|
+
docs/site/
|
|
10
|
+
helm/imbi/charts/
|
|
11
|
+
runtime/state/
|
|
12
|
+
.venv/
|
|
13
|
+
.coverage
|
|
14
|
+
.mypy_cache/
|
|
15
|
+
.pytest_cache/
|
|
16
|
+
.ruff_cache/
|
|
17
|
+
coverage.xml
|
|
18
|
+
site/
|
|
19
|
+
|
|
20
|
+
# moon
|
|
21
|
+
.moon/cache
|
|
22
|
+
.moon/docker
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: imbi-scheduler
|
|
3
|
+
Version: 2.23.0
|
|
4
|
+
Summary: Imbi scheduled task trigger service
|
|
5
|
+
Author-email: "Gavin M. Roy" <gavinr@aweber.com>
|
|
6
|
+
License-Expression: BSD-3-Clause
|
|
7
|
+
Requires-Python: >=3.14
|
|
8
|
+
Requires-Dist: croniter>=6.0
|
|
9
|
+
Requires-Dist: fastapi<0.137,>=0.135.1
|
|
10
|
+
Requires-Dist: httpx>=0.28.1
|
|
11
|
+
Requires-Dist: imbi-common[databases,server]==2.23.0
|
|
12
|
+
Requires-Dist: jinja2~=3.1
|
|
13
|
+
Requires-Dist: psycopg[binary,pool]~=3.3.2
|
|
14
|
+
Requires-Dist: pydantic~=2.12
|
|
15
|
+
Requires-Dist: sentry-sdk>=2.48.0
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# Imbi Scheduler
|
|
19
|
+
|
|
20
|
+
Triggers remote execution on a schedule. The scheduler fires cron, interval,
|
|
21
|
+
calendar, and one-shot triggers, then makes a single HTTP request per run — to
|
|
22
|
+
`imbi-api` as a named principal, or to `imbi-gateway` as a webhook delivery. It
|
|
23
|
+
does not execute the work itself; it triggers whichever service owns it.
|
|
24
|
+
|
|
25
|
+
Task definitions and trigger state live in the `scheduler` Postgres schema; run
|
|
26
|
+
history lives in ClickHouse (`imbi.scheduler_runs`).
|
|
27
|
+
|
|
28
|
+
## Developer Quickstart
|
|
29
|
+
|
|
30
|
+
This project uses [uv](https://docs.astral.sh/uv/) for project management and [moon](https://moonrepo.dev) as its task runner. Install moon before you can contribute changes.
|
|
31
|
+
|
|
32
|
+
```shell
|
|
33
|
+
moon run root:setup
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Run `moon query tasks` for the available commands.
|
|
37
|
+
|
|
38
|
+
## Code Formatting
|
|
39
|
+
|
|
40
|
+
This project uses automated formatting tools that are the sole authority on code style:
|
|
41
|
+
|
|
42
|
+
- **Ruff** for Python code (formatting and linting)
|
|
43
|
+
- **Tombi** for TOML files
|
|
44
|
+
- **Pre-commit hooks** to run formatters automatically on commit
|
|
45
|
+
|
|
46
|
+
**Do not manually format code.** Instead, use:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
uv run pre-commit run --all-files # Format all files
|
|
50
|
+
uv run pre-commit run --files src/app.py # Format a specific file
|
|
51
|
+
moon run scheduler:lint scheduler:typecheck scheduler:format # Check for lint errors
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The formatters use complex, nuanced rules (line length, quote style, etc.) that are configured in `pyproject.toml` and `.pre-commit-config.yaml`. See `AGENTS.md` for complete details.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Imbi Scheduler
|
|
2
|
+
|
|
3
|
+
Triggers remote execution on a schedule. The scheduler fires cron, interval,
|
|
4
|
+
calendar, and one-shot triggers, then makes a single HTTP request per run — to
|
|
5
|
+
`imbi-api` as a named principal, or to `imbi-gateway` as a webhook delivery. It
|
|
6
|
+
does not execute the work itself; it triggers whichever service owns it.
|
|
7
|
+
|
|
8
|
+
Task definitions and trigger state live in the `scheduler` Postgres schema; run
|
|
9
|
+
history lives in ClickHouse (`imbi.scheduler_runs`).
|
|
10
|
+
|
|
11
|
+
## Developer Quickstart
|
|
12
|
+
|
|
13
|
+
This project uses [uv](https://docs.astral.sh/uv/) for project management and [moon](https://moonrepo.dev) as its task runner. Install moon before you can contribute changes.
|
|
14
|
+
|
|
15
|
+
```shell
|
|
16
|
+
moon run root:setup
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Run `moon query tasks` for the available commands.
|
|
20
|
+
|
|
21
|
+
## Code Formatting
|
|
22
|
+
|
|
23
|
+
This project uses automated formatting tools that are the sole authority on code style:
|
|
24
|
+
|
|
25
|
+
- **Ruff** for Python code (formatting and linting)
|
|
26
|
+
- **Tombi** for TOML files
|
|
27
|
+
- **Pre-commit hooks** to run formatters automatically on commit
|
|
28
|
+
|
|
29
|
+
**Do not manually format code.** Instead, use:
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
uv run pre-commit run --all-files # Format all files
|
|
33
|
+
uv run pre-commit run --files src/app.py # Format a specific file
|
|
34
|
+
moon run scheduler:lint scheduler:typecheck scheduler:format # Check for lint errors
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The formatters use complex, nuanced rules (line length, quote style, etc.) that are configured in `pyproject.toml` and `.pre-commit-config.yaml`. See `AGENTS.md` for complete details.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# yaml-language-server: $schema=https://moonrepo.dev/schemas/project.json
|
|
2
|
+
layer: 'application'
|
|
3
|
+
stack: 'backend'
|
|
4
|
+
language: 'python'
|
|
5
|
+
tags:
|
|
6
|
+
- 'python'
|
|
7
|
+
|
|
8
|
+
project:
|
|
9
|
+
name: 'imbi-scheduler'
|
|
10
|
+
description: 'Imbi scheduled task trigger service (:8005)'
|
|
11
|
+
|
|
12
|
+
dependsOn:
|
|
13
|
+
- 'common'
|
|
14
|
+
|
|
15
|
+
# Inherits lint / format / typecheck / test from .moon/tasks/python.yml. The
|
|
16
|
+
# shared test task points --cov-config at this member's pyproject, where
|
|
17
|
+
# [tool.coverage] scopes source + threshold to the member.
|
|
18
|
+
tasks:
|
|
19
|
+
test:
|
|
20
|
+
args:
|
|
21
|
+
- '--cov'
|
|
22
|
+
- '--cov-report=term-missing'
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "imbi-scheduler"
|
|
3
|
+
version = "2.23.0"
|
|
4
|
+
description = "Imbi scheduled task trigger service"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.14"
|
|
7
|
+
license = "BSD-3-Clause"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Gavin M. Roy", email = "gavinr@aweber.com" },
|
|
10
|
+
]
|
|
11
|
+
classifiers = []
|
|
12
|
+
dependencies = [
|
|
13
|
+
"croniter>=6.0",
|
|
14
|
+
"fastapi>=0.135.1,<0.137",
|
|
15
|
+
"httpx>=0.28.1",
|
|
16
|
+
"imbi-common[databases,server]==2.23.0",
|
|
17
|
+
"jinja2~=3.1",
|
|
18
|
+
"psycopg[binary,pool]~=3.3.2",
|
|
19
|
+
"pydantic~=2.12",
|
|
20
|
+
"sentry-sdk>=2.48.0",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
[project.scripts]
|
|
24
|
+
imbi-scheduler = "imbi.scheduler.app:cli"
|
|
25
|
+
|
|
26
|
+
[build-system]
|
|
27
|
+
requires = ["hatchling"]
|
|
28
|
+
build-backend = "hatchling.build"
|
|
29
|
+
|
|
30
|
+
# Coverage for the per-member `moon run scheduler:test` run. Scoped to this
|
|
31
|
+
# member so the report/threshold reflect only imbi.scheduler; the aggregate
|
|
32
|
+
# `root:coverage` run uses the root pyproject config instead.
|
|
33
|
+
[tool.coverage.run]
|
|
34
|
+
branch = true
|
|
35
|
+
source_pkgs = ["imbi.scheduler"]
|
|
36
|
+
|
|
37
|
+
[tool.coverage.report]
|
|
38
|
+
exclude_also = ["typing.TYPE_CHECKING"]
|
|
39
|
+
fail_under = 85
|
|
40
|
+
show_missing = true
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.wheel]
|
|
43
|
+
packages = ["src/imbi"]
|
|
44
|
+
include = [
|
|
45
|
+
"src/imbi/scheduler/py.typed",
|
|
46
|
+
"src/imbi/scheduler/store/schemata.toml",
|
|
47
|
+
]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
|
|
3
|
+
import fastapi
|
|
4
|
+
import typer
|
|
5
|
+
|
|
6
|
+
import imbi.scheduler
|
|
7
|
+
from imbi.common import access_log, graph, lifespan, server
|
|
8
|
+
from imbi.scheduler import app_status, endpoints, lifespans, settings, store
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def create_app() -> fastapi.FastAPI:
|
|
12
|
+
"""Create and configure the FastAPI application instance."""
|
|
13
|
+
app = fastapi.FastAPI(
|
|
14
|
+
version=imbi.scheduler.version,
|
|
15
|
+
started_at=datetime.datetime.now(datetime.UTC),
|
|
16
|
+
# `graph_lifespan` is here for the endpoints: every route below
|
|
17
|
+
# `/tasks` resolves the caller's permissions from the graph, and
|
|
18
|
+
# `graph.Pool` is what the shared auth dependency injects. It
|
|
19
|
+
# costs the full graph bootstrap (extensions, vlabels, indexes,
|
|
20
|
+
# embeddings table, SQL functions) against schema this member
|
|
21
|
+
# never writes, raced with imbi-api's own bootstrap on every
|
|
22
|
+
# boot -- the same bargain imbi-assistant already makes, and the
|
|
23
|
+
# reason the trigger loop does NOT read the graph.
|
|
24
|
+
# Order matters: `engine_hook` borrows the pool `store_lifespan`
|
|
25
|
+
# opens, and the run history it writes needs ClickHouse.
|
|
26
|
+
lifespan=lifespan.Lifespan(
|
|
27
|
+
lifespans.clickhouse_hook,
|
|
28
|
+
graph.graph_lifespan,
|
|
29
|
+
store.store_lifespan,
|
|
30
|
+
lifespans.engine_hook,
|
|
31
|
+
),
|
|
32
|
+
)
|
|
33
|
+
# `/status` stays unprefixed, as imbi-assistant does it: a health check
|
|
34
|
+
# should not move when the API is relocated, and the probes read it
|
|
35
|
+
# directly on the pod rather than through the Caddy mount.
|
|
36
|
+
app.include_router(app_status.router)
|
|
37
|
+
# A fresh read rather than `get_settings()`: this runs once at startup, so
|
|
38
|
+
# the parse is free, and the route table should reflect the environment as
|
|
39
|
+
# it is now rather than whenever something first cached it.
|
|
40
|
+
app.include_router(
|
|
41
|
+
endpoints.router, prefix=settings.Scheduler().api_prefix
|
|
42
|
+
)
|
|
43
|
+
app.add_middleware(
|
|
44
|
+
access_log.AccessLogMiddleware,
|
|
45
|
+
quiet_paths={'/status'},
|
|
46
|
+
)
|
|
47
|
+
return app
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
cli = typer.Typer(no_args_is_help=True)
|
|
51
|
+
cli.command('serve')(server.bind_entrypoint('imbi.scheduler.app:create_app'))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@cli.callback()
|
|
55
|
+
def _callback() -> None: # pyright: ignore[reportUnusedFunction]
|
|
56
|
+
"""Imbi Scheduler CLI"""
|
|
57
|
+
# Providing an empty callback forces typer to require a command
|
|
58
|
+
# name - https://typer.tiangolo.com/tutorial/commands/one-or-multiple/
|
|
59
|
+
# This is only necessary since we only have one command.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""The unprefixed ``/status`` endpoint.
|
|
2
|
+
|
|
3
|
+
Deliberately outside ``IMBI_SCHEDULER_API_PREFIX``, matching imbi-assistant:
|
|
4
|
+
the Kubernetes probes address the pod directly and know nothing about the
|
|
5
|
+
prefix the task and run routes are mounted under. The chart aims both the
|
|
6
|
+
liveness and the readiness probe at this path -- see ``deployment.yaml``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import datetime
|
|
10
|
+
import os
|
|
11
|
+
import typing
|
|
12
|
+
|
|
13
|
+
import fastapi
|
|
14
|
+
import pydantic
|
|
15
|
+
|
|
16
|
+
router = fastapi.APIRouter()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Status(pydantic.BaseModel):
|
|
20
|
+
"""What ``/status`` reports about this process."""
|
|
21
|
+
|
|
22
|
+
environment: typing.Annotated[
|
|
23
|
+
str,
|
|
24
|
+
pydantic.Field(
|
|
25
|
+
description='Operating environment', examples=['production']
|
|
26
|
+
),
|
|
27
|
+
]
|
|
28
|
+
service: typing.Annotated[
|
|
29
|
+
str, pydantic.Field(description='Service instance name')
|
|
30
|
+
] = 'imbi-scheduler'
|
|
31
|
+
#: One value on purpose. A reply *is* the signal, so a `'failing'` variant
|
|
32
|
+
#: could only ever be advertised and never returned — see the endpoint.
|
|
33
|
+
status: typing.Literal['ok']
|
|
34
|
+
version: typing.Annotated[
|
|
35
|
+
str,
|
|
36
|
+
pydantic.Field(description='Application version', examples=['0.0.0']),
|
|
37
|
+
]
|
|
38
|
+
started_at: datetime.datetime
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@router.get('/status', summary='Operational status', operation_id='getStatus')
|
|
42
|
+
def status_endpoint(*, request: fastapi.Request) -> Status:
|
|
43
|
+
"""Report that this process is up and serving.
|
|
44
|
+
|
|
45
|
+
Answers from process state alone and touches no dependency, and
|
|
46
|
+
:attr:`Status.status` is narrowed to a single value to say so in the type.
|
|
47
|
+
That is deliberate, and the obvious change — widen the literal, add a
|
|
48
|
+
readiness check over the store pool, the ClickHouse client and the engine
|
|
49
|
+
task — is the one to resist here.
|
|
50
|
+
|
|
51
|
+
The chart points **both** the liveness and the readiness probe at this
|
|
52
|
+
path (see ``helm/imbi/templates/deployment.yaml``). So a dependency-aware
|
|
53
|
+
answer cannot be scoped to readiness: it would make *liveness*
|
|
54
|
+
dependency-shaped too, and a Postgres blip would restart every replica —
|
|
55
|
+
discarding in-flight ticks to fix nothing, since restarting does not
|
|
56
|
+
shorten a database outage.
|
|
57
|
+
|
|
58
|
+
Readiness signalling also earns its keep only when some replicas are
|
|
59
|
+
healthier than others, and here none ever are: every replica shares one
|
|
60
|
+
Postgres and one ClickHouse, so a dependency check fails them together and
|
|
61
|
+
leaves no healthier endpoint for traffic to move to.
|
|
62
|
+
|
|
63
|
+
Real readiness therefore needs a **separate path that only the readiness
|
|
64
|
+
probe uses**, plus the chart change to point at it. That is a deliberate
|
|
65
|
+
piece of work, not an edit to this function.
|
|
66
|
+
"""
|
|
67
|
+
return Status(
|
|
68
|
+
environment=os.environ.get('ENVIRONMENT', 'development'),
|
|
69
|
+
status='ok',
|
|
70
|
+
version=request.app.version,
|
|
71
|
+
started_at=request.app.extra['started_at'],
|
|
72
|
+
)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""HTTP API for imbi-scheduler.
|
|
2
|
+
|
|
3
|
+
One router per PRD section 10, mounted by :func:`imbi.scheduler.app.create_app`
|
|
4
|
+
under the base path. There are no ``/credentials`` routes: ADR 0002 removed
|
|
5
|
+
the credential store, so there is nothing for them to manage.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import fastapi
|
|
9
|
+
|
|
10
|
+
from imbi.scheduler.endpoints import runs, tasks
|
|
11
|
+
|
|
12
|
+
router = fastapi.APIRouter()
|
|
13
|
+
router.include_router(tasks.router)
|
|
14
|
+
router.include_router(runs.router)
|
|
15
|
+
|
|
16
|
+
__all__ = ['router']
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Injected resources and the ownership rule.
|
|
2
|
+
|
|
3
|
+
Authentication is entirely :mod:`imbi.common.auth.permissions` -- the same
|
|
4
|
+
bearer handling, the same graph-resolved permissions, the same
|
|
5
|
+
``require_permission`` as imbi-api. What is local to this member is
|
|
6
|
+
authorization *over a task*, which the PRD states as: a caller manages the
|
|
7
|
+
tasks they created, and anything else needs ``scheduled_task:admin``.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import typing
|
|
11
|
+
|
|
12
|
+
import fastapi
|
|
13
|
+
|
|
14
|
+
from imbi.common.auth import permissions
|
|
15
|
+
from imbi.scheduler import lifespans, models, store
|
|
16
|
+
|
|
17
|
+
#: Every permission this service checks. Named here so the routes read as the
|
|
18
|
+
#: PRD table does, and so a typo is an import error rather than a 403.
|
|
19
|
+
READ = 'scheduled_task:read'
|
|
20
|
+
CREATE = 'scheduled_task:create'
|
|
21
|
+
WRITE = 'scheduled_task:write'
|
|
22
|
+
DELETE = 'scheduled_task:delete'
|
|
23
|
+
RUN = 'scheduled_task:run'
|
|
24
|
+
ADMIN = 'scheduled_task:admin'
|
|
25
|
+
|
|
26
|
+
# Each injected resource is declared beside the lifespan hook that opens it,
|
|
27
|
+
# so there is one dependency identity per resource. A second alias here would
|
|
28
|
+
# mean a test overriding one of them silently misses routes wired to the other.
|
|
29
|
+
Tasks = store.TaskStore
|
|
30
|
+
Engine = lifespans.EngineDependency
|
|
31
|
+
|
|
32
|
+
AuthContext = permissions.AuthContext
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def requires(permission: str) -> typing.Any:
|
|
36
|
+
"""Return a route-level dependency enforcing `permission`.
|
|
37
|
+
|
|
38
|
+
For routes that need the permission checked but never read the resulting
|
|
39
|
+
context -- the read-only ones. Route-level rather than a parameter so
|
|
40
|
+
there is no unused argument to discard, and the permission stays
|
|
41
|
+
introspectable: the OpenAPI stamper walks the whole dependency tree.
|
|
42
|
+
"""
|
|
43
|
+
return fastapi.Depends(permissions.require_permission(permission))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# An alias per permission whose routes actually use the context, to hand to
|
|
47
|
+
# `authorize`. Spelled out rather than built by a helper because a helper
|
|
48
|
+
# returning `Any` is invisible to the type checker, which would leave every
|
|
49
|
+
# route's `auth` parameter untyped.
|
|
50
|
+
RequiresRead = typing.Annotated[
|
|
51
|
+
permissions.AuthContext,
|
|
52
|
+
fastapi.Depends(permissions.require_permission(READ)),
|
|
53
|
+
]
|
|
54
|
+
RequiresCreate = typing.Annotated[
|
|
55
|
+
permissions.AuthContext,
|
|
56
|
+
fastapi.Depends(permissions.require_permission(CREATE)),
|
|
57
|
+
]
|
|
58
|
+
RequiresWrite = typing.Annotated[
|
|
59
|
+
permissions.AuthContext,
|
|
60
|
+
fastapi.Depends(permissions.require_permission(WRITE)),
|
|
61
|
+
]
|
|
62
|
+
RequiresDelete = typing.Annotated[
|
|
63
|
+
permissions.AuthContext,
|
|
64
|
+
fastapi.Depends(permissions.require_permission(DELETE)),
|
|
65
|
+
]
|
|
66
|
+
RequiresRun = typing.Annotated[
|
|
67
|
+
permissions.AuthContext,
|
|
68
|
+
fastapi.Depends(permissions.require_permission(RUN)),
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def is_admin(auth: AuthContext) -> bool:
|
|
73
|
+
"""Return whether `auth` may manage tasks it does not own."""
|
|
74
|
+
return ADMIN in auth.permissions or auth.is_admin
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def authorize_system_kind(auth: AuthContext, kind: str) -> None:
|
|
78
|
+
"""Raise 403 unless `auth` may act on a task of `kind`.
|
|
79
|
+
|
|
80
|
+
A ``system`` task is off limits without ``scheduled_task:admin`` however
|
|
81
|
+
it was created: those are the platform's own jobs, and the scheduler's
|
|
82
|
+
service account is what creates them, so ownership alone would hand
|
|
83
|
+
control of every system task to that account's holders. Creation checks
|
|
84
|
+
this too -- against the requested kind rather than a stored one -- which
|
|
85
|
+
is why it lives here and not inside :func:`authorize`.
|
|
86
|
+
"""
|
|
87
|
+
if kind == 'system' and not is_admin(auth):
|
|
88
|
+
raise fastapi.HTTPException(
|
|
89
|
+
status_code=403,
|
|
90
|
+
detail=f'{ADMIN} is required to manage system tasks',
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def authorize(auth: AuthContext, task: models.Task) -> None:
|
|
95
|
+
"""Raise 403 unless `auth` may manage `task`."""
|
|
96
|
+
if is_admin(auth):
|
|
97
|
+
return
|
|
98
|
+
authorize_system_kind(auth, task.kind)
|
|
99
|
+
if task.created_by != auth.principal_name:
|
|
100
|
+
raise fastapi.HTTPException(
|
|
101
|
+
status_code=403,
|
|
102
|
+
detail=(
|
|
103
|
+
f'{task.slug} belongs to {task.created_by}; '
|
|
104
|
+
f'{ADMIN} is required to manage tasks owned by others'
|
|
105
|
+
),
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def load(tasks: store.Tasks, slug: str) -> models.Task:
|
|
110
|
+
"""Return the task with `slug`, or raise 404."""
|
|
111
|
+
task = await tasks.get(slug)
|
|
112
|
+
if task is None:
|
|
113
|
+
raise fastapi.HTTPException(
|
|
114
|
+
status_code=404, detail=f'No such scheduled task: {slug}'
|
|
115
|
+
)
|
|
116
|
+
return task
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
async def load_for_management(
|
|
120
|
+
tasks: store.Tasks, slug: str, auth: AuthContext
|
|
121
|
+
) -> models.Task:
|
|
122
|
+
"""Return the task with `slug`, enforcing the ownership rule.
|
|
123
|
+
|
|
124
|
+
Existence is checked first, so a caller who cannot manage a task still
|
|
125
|
+
learns it exists. That is the same disclosure every route here makes to
|
|
126
|
+
anyone holding ``scheduled_task:read`` -- which the ownership rule does
|
|
127
|
+
not restrict, since reading the schedule is not managing it.
|
|
128
|
+
"""
|
|
129
|
+
task = await load(tasks, slug)
|
|
130
|
+
authorize(auth, task)
|
|
131
|
+
return task
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Run history and cancellation.
|
|
2
|
+
|
|
3
|
+
History lives in ClickHouse and task definitions in Postgres, so a run is
|
|
4
|
+
read from one and authorized against the other: the ownership rule is a
|
|
5
|
+
property of the task, and a run only carries its ``task_id``.
|
|
6
|
+
|
|
7
|
+
Every route here enforces that rule, reads included. This is narrower than
|
|
8
|
+
the task-definition routes, where `GET /tasks` and `GET /tasks/{slug}` are
|
|
9
|
+
deliberately unscoped because reading the schedule is not managing it. A run
|
|
10
|
+
is not just the schedule: `response_excerpt` carries part of what the target
|
|
11
|
+
sent back, which the definition never exposes. Two consequences worth keeping
|
|
12
|
+
straight -- a caller can therefore read a task it cannot get the runs of, and
|
|
13
|
+
tightening this side did not tighten that one.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import typing
|
|
17
|
+
import uuid
|
|
18
|
+
|
|
19
|
+
import fastapi
|
|
20
|
+
import pydantic
|
|
21
|
+
|
|
22
|
+
from imbi.scheduler import runs as runs_module
|
|
23
|
+
from imbi.scheduler.endpoints import dependencies
|
|
24
|
+
|
|
25
|
+
router = fastapi.APIRouter(tags=['Scheduled Task Runs'])
|
|
26
|
+
|
|
27
|
+
DEFAULT_HISTORY_LIMIT = 50
|
|
28
|
+
MAX_HISTORY_LIMIT = 500
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CancelResult(pydantic.BaseModel):
|
|
32
|
+
"""The outcome of asking a run to stop.
|
|
33
|
+
|
|
34
|
+
``requested`` rather than ``cancelled``: the request is recorded and
|
|
35
|
+
broadcast synchronously, but the replica running the job is the one that
|
|
36
|
+
acts on it, so a caller learns the ask landed rather than that the job is
|
|
37
|
+
already stopped. Poll ``GET /runs/{run_id}`` for the terminal state.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
run_id: str
|
|
41
|
+
requested: bool
|
|
42
|
+
detail: str
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
async def _load(run_id: str) -> runs_module.Run:
|
|
46
|
+
"""Return the run with `run_id`, or raise 404."""
|
|
47
|
+
run = await runs_module.get(run_id)
|
|
48
|
+
if run is None:
|
|
49
|
+
raise fastapi.HTTPException(
|
|
50
|
+
status_code=404, detail=f'No such run: {run_id}'
|
|
51
|
+
)
|
|
52
|
+
return run
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@router.get(
|
|
56
|
+
'/tasks/{slug}/runs',
|
|
57
|
+
summary='List a task run history',
|
|
58
|
+
operation_id='listTaskRuns',
|
|
59
|
+
)
|
|
60
|
+
async def list_task_runs(
|
|
61
|
+
*,
|
|
62
|
+
tasks: dependencies.Tasks,
|
|
63
|
+
slug: str,
|
|
64
|
+
auth: dependencies.RequiresRead,
|
|
65
|
+
limit: typing.Annotated[
|
|
66
|
+
int, fastapi.Query(ge=1, le=MAX_HISTORY_LIMIT)
|
|
67
|
+
] = DEFAULT_HISTORY_LIMIT,
|
|
68
|
+
offset: typing.Annotated[int, fastapi.Query(ge=0)] = 0,
|
|
69
|
+
) -> list[runs_module.Run]:
|
|
70
|
+
"""Return the task's runs, newest first.
|
|
71
|
+
|
|
72
|
+
Authorized against the owning task, unlike the task-definition reads.
|
|
73
|
+
A run carries more than the definition does -- `response_excerpt` holds
|
|
74
|
+
part of the target's reply -- so ownership is enforced here even though
|
|
75
|
+
``GET /tasks/{slug}`` deliberately does not enforce it.
|
|
76
|
+
"""
|
|
77
|
+
task = await dependencies.load(tasks, slug)
|
|
78
|
+
dependencies.authorize(auth, task)
|
|
79
|
+
return await runs_module.for_task(task.id, limit=limit, offset=offset)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@router.get(
|
|
83
|
+
'/runs/{run_id}',
|
|
84
|
+
summary='Fetch a single run',
|
|
85
|
+
operation_id='getRun',
|
|
86
|
+
)
|
|
87
|
+
async def get_run(
|
|
88
|
+
*,
|
|
89
|
+
tasks: dependencies.Tasks,
|
|
90
|
+
run_id: str,
|
|
91
|
+
auth: dependencies.RequiresRead,
|
|
92
|
+
) -> runs_module.Run:
|
|
93
|
+
"""Return one run with its response excerpt and timings.
|
|
94
|
+
|
|
95
|
+
Authorized against the run's task, so a run cannot be read by id to get
|
|
96
|
+
around :func:`list_task_runs`.
|
|
97
|
+
|
|
98
|
+
A run whose task has since been deleted is readable only by an admin.
|
|
99
|
+
This is deliberately stricter than `cancel_run`, which allows it to
|
|
100
|
+
anyone holding ``scheduled_task:run``: leaving a job nobody can stop is
|
|
101
|
+
worse than the disclosure, while for a read there is no such necessity
|
|
102
|
+
and no owner left to check.
|
|
103
|
+
"""
|
|
104
|
+
run = await _load(run_id)
|
|
105
|
+
task = await tasks.get_by_id(uuid.UUID(run.task_id))
|
|
106
|
+
if task is None:
|
|
107
|
+
if not dependencies.is_admin(auth):
|
|
108
|
+
raise fastapi.HTTPException(
|
|
109
|
+
status_code=404, detail=f'No such run: {run_id}'
|
|
110
|
+
)
|
|
111
|
+
else:
|
|
112
|
+
dependencies.authorize(auth, task)
|
|
113
|
+
return run
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@router.post(
|
|
117
|
+
'/runs/{run_id}/cancel',
|
|
118
|
+
summary='Cancel an in-flight run',
|
|
119
|
+
operation_id='cancelRun',
|
|
120
|
+
)
|
|
121
|
+
async def cancel_run(
|
|
122
|
+
*,
|
|
123
|
+
tasks: dependencies.Tasks,
|
|
124
|
+
engine: dependencies.Engine,
|
|
125
|
+
run_id: str,
|
|
126
|
+
auth: dependencies.RequiresRun,
|
|
127
|
+
) -> CancelResult:
|
|
128
|
+
"""Ask the replica running `run_id` to stop it.
|
|
129
|
+
|
|
130
|
+
Authorized against the run's task, so cancelling somebody else's job
|
|
131
|
+
needs the same ``scheduled_task:admin`` as editing it. A run whose task
|
|
132
|
+
has since been deleted is cancellable by anyone holding
|
|
133
|
+
``scheduled_task:run``: there is no owner left to check, and refusing
|
|
134
|
+
would leave a job nobody can stop.
|
|
135
|
+
"""
|
|
136
|
+
run = await _load(run_id)
|
|
137
|
+
task = await tasks.get_by_id(uuid.UUID(run.task_id))
|
|
138
|
+
if task is not None:
|
|
139
|
+
dependencies.authorize(auth, task)
|
|
140
|
+
if run.is_terminal:
|
|
141
|
+
raise fastapi.HTTPException(
|
|
142
|
+
status_code=409,
|
|
143
|
+
detail=f'Run {run_id} already finished as {run.state}',
|
|
144
|
+
)
|
|
145
|
+
requested = await engine.cancel(run_id)
|
|
146
|
+
if not requested:
|
|
147
|
+
# No lease: the run finished between the history read and now, or the
|
|
148
|
+
# lease expired because the replica running it died. Either way there
|
|
149
|
+
# is nothing to interrupt, and 409 says so without implying the run
|
|
150
|
+
# never existed.
|
|
151
|
+
raise fastapi.HTTPException(
|
|
152
|
+
status_code=409,
|
|
153
|
+
detail=(
|
|
154
|
+
f'Run {run_id} is not in flight; it finished or its '
|
|
155
|
+
'execution lease expired'
|
|
156
|
+
),
|
|
157
|
+
)
|
|
158
|
+
return CancelResult(
|
|
159
|
+
run_id=run_id,
|
|
160
|
+
requested=True,
|
|
161
|
+
detail=(
|
|
162
|
+
'Cancellation requested. The replica running this job will '
|
|
163
|
+
'interrupt it; poll the run for its terminal state.'
|
|
164
|
+
),
|
|
165
|
+
)
|