alembic-runner 0.1.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.
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ .ruff_cache/
9
+ .mypy_cache/
10
+ .pytest_cache/
11
+ .coverage
12
+ .coverage.*
13
+ coverage.xml
14
+ htmlcov/
15
+ site/
16
+ .DS_Store
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 cyberwitchery labs
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.5
2
+ Name: alembic-runner
3
+ Version: 0.1.0
4
+ Summary: run alembic plan, review and apply from a host application
5
+ Project-URL: Homepage, https://github.com/cyberwitchery/alembic-sot-plugins
6
+ Project-URL: Repository, https://github.com/cyberwitchery/alembic-sot-plugins
7
+ Project-URL: alembic (core), https://github.com/cyberwitchery/alembic
8
+ Author-email: cyberwitchery lab <contact@cyberwitchery.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: alembic,nautobot,netbox,network-automation
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: System :: Networking
17
+ Requires-Python: >=3.10
18
+ Provides-Extra: dev
19
+ Requires-Dist: coverage[toml]; extra == 'dev'
20
+ Requires-Dist: ruff; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # alembic-runner
24
+
25
+ the host-independent core of the alembic netbox and nautobot plugins. it runs
26
+ the `alembic` cli for a flow's plan, stale check, apply and drift report, parses
27
+ what the cli writes, and owns the run state machine. no django in here.
28
+
29
+ each run gets an environment built from scratch: the worker's own secrets never
30
+ reach alembic, and credentials go through environment variables, never a file.
31
+
32
+ it is installed as a dependency of
33
+ [netbox-alembic](https://pypi.org/project/netbox-alembic/) and
34
+ [nautobot-alembic](https://pypi.org/project/nautobot-alembic/); on its own it
35
+ needs only python 3.10+ and the `alembic` binary.
@@ -0,0 +1,13 @@
1
+ # alembic-runner
2
+
3
+ the host-independent core of the alembic netbox and nautobot plugins. it runs
4
+ the `alembic` cli for a flow's plan, stale check, apply and drift report, parses
5
+ what the cli writes, and owns the run state machine. no django in here.
6
+
7
+ each run gets an environment built from scratch: the worker's own secrets never
8
+ reach alembic, and credentials go through environment variables, never a file.
9
+
10
+ it is installed as a dependency of
11
+ [netbox-alembic](https://pypi.org/project/netbox-alembic/) and
12
+ [nautobot-alembic](https://pypi.org/project/nautobot-alembic/); on its own it
13
+ needs only python 3.10+ and the `alembic` binary.
@@ -0,0 +1,47 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "alembic-runner"
7
+ version = "0.1.0"
8
+ description = "run alembic plan, review and apply from a host application"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "cyberwitchery lab", email = "contact@cyberwitchery.com" }]
13
+ keywords = ["alembic", "netbox", "nautobot", "network-automation"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: System Administrators",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Topic :: System :: Networking",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/cyberwitchery/alembic-sot-plugins"
25
+ Repository = "https://github.com/cyberwitchery/alembic-sot-plugins"
26
+ "alembic (core)" = "https://github.com/cyberwitchery/alembic"
27
+
28
+ [project.optional-dependencies]
29
+ dev = ["coverage[toml]", "ruff"]
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ exclude = ["tests"]
33
+ packages = ["src/alembic_runner"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100
37
+ target-version = "py310"
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "F", "I", "B", "UP"]
41
+
42
+ [tool.coverage.run]
43
+ source = ["alembic_runner"]
44
+ branch = true
45
+
46
+ [tool.coverage.report]
47
+ show_missing = true
@@ -0,0 +1,61 @@
1
+ """run alembic plan, review and apply from a host application."""
2
+
3
+ from .backend import CONFIG_KEYS, KINDS, TOKEN_ENV, Backend, BackendError, StateStore, token_env
4
+ from .plan import ApplyReport, DocumentError, DriftReport, Plan
5
+ from .runner import (
6
+ SUPPORTED,
7
+ ApplyOutcome,
8
+ Completed,
9
+ DriftOutcome,
10
+ Flow,
11
+ InventoryOutcome,
12
+ PlanOutcome,
13
+ Runner,
14
+ RunnerError,
15
+ StaleCheck,
16
+ )
17
+ from .status import (
18
+ ACTIVE,
19
+ TERMINAL,
20
+ TRANSITIONS,
21
+ RunStatus,
22
+ TransitionError,
23
+ check_transition,
24
+ failure_status,
25
+ )
26
+ from .workspace import Workspace, WorkspaceError
27
+
28
+ __version__ = "0.1.0"
29
+
30
+ __all__ = [
31
+ "ACTIVE",
32
+ "CONFIG_KEYS",
33
+ "KINDS",
34
+ "SUPPORTED",
35
+ "TERMINAL",
36
+ "TOKEN_ENV",
37
+ "TRANSITIONS",
38
+ "ApplyOutcome",
39
+ "ApplyReport",
40
+ "Backend",
41
+ "BackendError",
42
+ "Completed",
43
+ "DocumentError",
44
+ "DriftOutcome",
45
+ "DriftReport",
46
+ "Flow",
47
+ "InventoryOutcome",
48
+ "Plan",
49
+ "PlanOutcome",
50
+ "RunStatus",
51
+ "Runner",
52
+ "RunnerError",
53
+ "StaleCheck",
54
+ "StateStore",
55
+ "TransitionError",
56
+ "Workspace",
57
+ "WorkspaceError",
58
+ "check_transition",
59
+ "failure_status",
60
+ "token_env",
61
+ ]
@@ -0,0 +1,111 @@
1
+ """backends and state stores, as the environment and files a run hands to alembic."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ KINDS = ("netbox", "nautobot", "infrahub", "peeringdb", "external")
9
+
10
+ # the config keys a stored backend may set. anything that names a command, a
11
+ # working directory or an environment for a process stays in host settings:
12
+ # whoever can edit a backend must not be able to run something on the worker.
13
+ CONFIG_KEYS = {
14
+ "netbox": frozenset({"url", "instance"}),
15
+ "nautobot": frozenset({"url", "instance"}),
16
+ "infrahub": frozenset({"url", "instance"}),
17
+ "peeringdb": frozenset({"url", "instance"}),
18
+ "external": frozenset({"args", "setup", "timeout_seconds", "instance"}),
19
+ }
20
+
21
+ # the environment variable each built-in adapter reads its credential from.
22
+ TOKEN_ENV = {
23
+ "netbox": "NETBOX_TOKEN",
24
+ "nautobot": "NAUTOBOT_TOKEN",
25
+ "infrahub": "INFRAHUB_TOKEN",
26
+ "peeringdb": "PEERINGDB_API_KEY",
27
+ }
28
+
29
+
30
+ class BackendError(ValueError):
31
+ pass
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Backend:
36
+ """one backend as a run sees it.
37
+
38
+ `config` is the non-secret part of an alembic backend config, without the
39
+ `backend:` key. `env` holds the credentials, by variable name. an external
40
+ backend's `command` comes from host settings, never from stored config.
41
+ """
42
+
43
+ kind: str
44
+ config: dict[str, Any] = field(default_factory=dict)
45
+ env: dict[str, str] = field(default_factory=dict)
46
+ command: str | None = None
47
+
48
+ def __post_init__(self) -> None:
49
+ if self.kind not in KINDS:
50
+ raise BackendError(f"unknown backend kind {self.kind!r}")
51
+ unknown = self.config.keys() - CONFIG_KEYS[self.kind]
52
+ if unknown:
53
+ raise BackendError(
54
+ f"a {self.kind} backend config cannot set {', '.join(sorted(unknown))}; "
55
+ f"it takes {', '.join(sorted(CONFIG_KEYS[self.kind]))}"
56
+ )
57
+ if self.kind == "external":
58
+ if not self.command:
59
+ raise BackendError("an external backend needs a command from host settings")
60
+ elif self.command:
61
+ raise BackendError(f"a {self.kind} backend takes no command")
62
+
63
+ def config_document(self) -> dict[str, Any]:
64
+ doc = {"backend": self.kind, **self.config}
65
+ if self.command:
66
+ doc["command"] = self.command
67
+ return doc
68
+
69
+
70
+ def token_env(kind: str, token: str) -> dict[str, str]:
71
+ """the environment that hands `token` to a built-in adapter of `kind`."""
72
+ try:
73
+ return {TOKEN_ENV[kind]: token}
74
+ except KeyError:
75
+ raise BackendError(f"a {kind} backend reads no token variable") from None
76
+
77
+
78
+ @dataclass(frozen=True)
79
+ class StateStore:
80
+ """where identity state lives. `local` keeps it in the flow directory."""
81
+
82
+ backend: str = "local"
83
+ postgres_url: str | None = None
84
+ postgres_tls: str | None = None
85
+
86
+ def __post_init__(self) -> None:
87
+ if self.backend not in ("local", "postgres"):
88
+ raise BackendError(f"unknown state backend {self.backend!r}")
89
+ if self.backend == "postgres" and not self.postgres_url:
90
+ raise BackendError("postgres state needs a postgres_url")
91
+
92
+ @classmethod
93
+ def from_settings(cls, settings: dict[str, Any] | None) -> StateStore:
94
+ settings = settings or {}
95
+ return cls(
96
+ backend=settings.get("backend", "local"),
97
+ postgres_url=settings.get("postgres_url"),
98
+ postgres_tls=settings.get("postgres_tls"),
99
+ )
100
+
101
+ def env(self, key: str) -> dict[str, str]:
102
+ if self.backend == "local":
103
+ return {"ALEMBIC_STATE_BACKEND": "local"}
104
+ env = {
105
+ "ALEMBIC_STATE_BACKEND": "postgres",
106
+ "ALEMBIC_STATE_POSTGRES_URL": self.postgres_url or "",
107
+ "ALEMBIC_STATE_KEY": key,
108
+ }
109
+ if self.postgres_tls:
110
+ env["ALEMBIC_STATE_POSTGRES_TLS"] = self.postgres_tls
111
+ return env
@@ -0,0 +1,197 @@
1
+ """run bookkeeping the host apps share: moves, locks, approval checks and the job
2
+ wrapper. it needs django, so only the host apps import it; the rest of the core
3
+ stays stdlib-only.
4
+
5
+ a host's run model carries the fields both apps define: `flow`, `kind`,
6
+ `status`, `requested_by`, `decided_by`, `decided_at`, `planned_at`,
7
+ `apply_started_at`, `finished_at`, `plan`, `plan_sha256`, `approved_sha256`,
8
+ `error`, `output`."""
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Callable, Iterable
13
+ from datetime import timedelta
14
+ from typing import Any
15
+
16
+ from django.core.exceptions import PermissionDenied, ValidationError
17
+ from django.db import IntegrityError, transaction
18
+ from django.utils import timezone
19
+
20
+ from .pipeline import Outcome, RunFailed, approved_plan
21
+ from .plan import Plan
22
+ from .status import RunStatus, TransitionError, check_transition, failure_status
23
+
24
+ S = RunStatus
25
+
26
+ # a new plan of a flow takes these runs' place.
27
+ SUPERSEDABLE = (S.AWAITING_APPROVAL.value, S.APPLY_FAILED.value)
28
+
29
+
30
+ class ActionError(ValidationError):
31
+ """a run cannot do what was asked of it in its current state."""
32
+
33
+
34
+ def _save(run) -> None:
35
+ # nautobot validates on save through `validated_save`; netbox has only `save`.
36
+ getattr(run, "validated_save", run.save)()
37
+
38
+
39
+ def move(run, new: RunStatus | str, **fields: Any):
40
+ """move a locked run to `new`, setting `fields`, or raise ActionError."""
41
+ try:
42
+ check_transition(run.status, new)
43
+ except TransitionError as e:
44
+ raise ActionError(str(e)) from e
45
+ run.status = RunStatus(new).value
46
+ for name, value in fields.items():
47
+ setattr(run, name, value)
48
+ _save(run)
49
+ return run
50
+
51
+
52
+ def locked(run):
53
+ return type(run).objects.select_for_update().get(pk=run.pk)
54
+
55
+
56
+ def expired(run, ttl_hours: int | None) -> bool:
57
+ return bool(
58
+ ttl_hours
59
+ and run.planned_at
60
+ and timezone.now() > run.planned_at + timedelta(hours=ttl_hours)
61
+ )
62
+
63
+
64
+ def create_run(model, flow, user, kind: str, supersede: bool, retire: Callable = lambda run: None):
65
+ """create a pending run of `flow`. a plan (`supersede`) takes the place of the
66
+ flow's waiting runs, each passed to `retire` first. call inside a transaction."""
67
+ if supersede:
68
+ for run in model.objects.select_for_update().filter(flow=flow, status__in=SUPERSEDABLE):
69
+ retire(run)
70
+ move(run, S.SUPERSEDED, finished_at=timezone.now())
71
+ try:
72
+ with transaction.atomic():
73
+ return model.objects.create(flow=flow, kind=kind, requested_by=user)
74
+ except IntegrityError:
75
+ raise ActionError("This flow already has a run in progress.") from None
76
+
77
+
78
+ def _approve_perm(run) -> str:
79
+ return f"{run._meta.app_label}.approve_run"
80
+
81
+
82
+ def refusal(run, user, distinct: bool, ttl_hours: int | None = None) -> str | None:
83
+ """why `user` may not approve or reject `run`, or None if they may."""
84
+ if not user.has_perm(_approve_perm(run), run):
85
+ return "You may not approve or reject this run."
86
+ if distinct and run.requested_by_id == user.pk:
87
+ return "Someone other than the requester approves this run."
88
+ if expired(run, ttl_hours):
89
+ return "This plan is too old to approve. Plan again."
90
+ return None
91
+
92
+
93
+ def check_approver(run, user, distinct: bool) -> None:
94
+ reason = refusal(run, user, distinct)
95
+ if reason:
96
+ raise PermissionDenied(reason)
97
+
98
+
99
+ def approve(run, user, ttl_hours: int | None) -> bool:
100
+ """move a locked, waiting run to approved, or to expired when its plan is too
101
+ old. returns whether it was approved; the caller queues the apply."""
102
+ if expired(run, ttl_hours):
103
+ move(run, S.EXPIRED, finished_at=timezone.now())
104
+ return False
105
+ move(
106
+ run,
107
+ S.APPROVED,
108
+ decided_by=user,
109
+ decided_at=timezone.now(),
110
+ approved_sha256=run.plan_sha256,
111
+ )
112
+ return True
113
+
114
+
115
+ def reject(run, user):
116
+ now = timezone.now()
117
+ return move(run, S.REJECTED, decided_by=user, decided_at=now, finished_at=now)
118
+
119
+
120
+ def check_resumable(run, user) -> None:
121
+ if not user.has_perm(_approve_perm(run), run):
122
+ raise PermissionDenied("You may not resume this run.")
123
+ if run.status != S.APPLY_FAILED.value:
124
+ raise ActionError("Only a failed apply can be resumed.")
125
+
126
+
127
+ # jobs
128
+
129
+
130
+ def transition(run, new: RunStatus | str, **fields: Any) -> None:
131
+ with transaction.atomic():
132
+ move(locked(run), new, **fields)
133
+ run.refresh_from_db()
134
+
135
+
136
+ def settle(run, outcome: Outcome, **fields: Any) -> None:
137
+ """store what a pipeline step decided on the run."""
138
+ if outcome.finished:
139
+ fields["finished_at"] = timezone.now()
140
+ transition(run, outcome.status, **outcome.fields, **fields)
141
+
142
+
143
+ def fail(run, message: str, output: str = "") -> None:
144
+ """record a failure on the run, in the status its phase fails into."""
145
+ fields: dict[str, Any] = {"error": message}
146
+ if output:
147
+ fields["output"] = output
148
+ with transaction.atomic():
149
+ run = locked(run)
150
+ new = failure_status(run.status)
151
+ if new is S.FAILED:
152
+ fields["finished_at"] = timezone.now()
153
+ if new is not None:
154
+ move(run, new, **fields)
155
+
156
+
157
+ def run_guarded(run, execute: Callable, logger, known: Iterable[type[Exception]] = ()) -> None:
158
+ """run a job's body. a failure it expects becomes the run's status; anything
159
+ else does too, and is raised again so the host marks its job as errored."""
160
+ try:
161
+ execute(run)
162
+ except RunFailed as e:
163
+ logger.error(str(e))
164
+ fail(run, str(e), e.output)
165
+ except ActionError as e:
166
+ # the run is not in a state this job can act on; leave it as it is.
167
+ logger.error(" ".join(e.messages))
168
+ except tuple(known) as e:
169
+ logger.error(str(e))
170
+ fail(run, str(e))
171
+ except Exception as e:
172
+ fail(run, f"{type(e).__name__}: {e}")
173
+ raise
174
+
175
+
176
+ def start_apply(run) -> tuple[Plan, bool]:
177
+ """take the run into applying: one apply per target at a time, from an
178
+ approved run or a failed apply, and only with the plan that was approved.
179
+ returns the plan and whether this resumes a failed apply."""
180
+ model = type(run)
181
+ with transaction.atomic():
182
+ current = locked(run)
183
+ busy = (
184
+ model.objects.filter(flow__target=run.flow.target, status=S.APPLYING.value)
185
+ .exclude(pk=run.pk)
186
+ .select_for_update()
187
+ )
188
+ if busy.exists():
189
+ raise RunFailed(f"Another run is applying to {run.flow.target}; try again later.")
190
+ if current.status not in (S.APPROVED.value, S.APPLY_FAILED.value):
191
+ raise ActionError(f"a {current.status} run is not applied")
192
+ resuming = current.status == S.APPLY_FAILED.value
193
+ # checked before the move, so a plan that fails it never becomes resumable.
194
+ plan = approved_plan(current.plan, current.approved_sha256)
195
+ move(current, S.APPLYING, apply_started_at=current.apply_started_at or timezone.now())
196
+ run.refresh_from_db()
197
+ return plan, resuming