alembic-adapter-sdk 0.1.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.
@@ -0,0 +1,71 @@
1
+ """Python SDK for writing `alembic <https://github.com/cyberwitchery/alembic>`_
2
+ external adapters.
3
+
4
+ An external adapter is a standalone program the alembic host spawns as a
5
+ subprocess, speaking one JSON request/response over stdin/stdout. Implement
6
+ :class:`Adapter` and call :func:`run`::
7
+
8
+ from alembic_adapter import Adapter, ApplyReport, AppliedOp, run
9
+
10
+ class MyAdapter(Adapter):
11
+ def setup(self, config):
12
+ self.host = (config or {}).get("host", "http://localhost:8080")
13
+
14
+ def write(self, schema, ops, state):
15
+ report = ApplyReport()
16
+ for op in ops:
17
+ report.applied.append(AppliedOp(uid=op.uid, type_name=op.type_name))
18
+ return report
19
+
20
+ if __name__ == "__main__":
21
+ run(MyAdapter())
22
+ """
23
+
24
+ from .model import (
25
+ PROTOCOL_VERSION,
26
+ AppliedOp,
27
+ ApplyReport,
28
+ BackendId,
29
+ Create,
30
+ Delete,
31
+ ExternalObject,
32
+ FieldChange,
33
+ FieldSchema,
34
+ FieldType,
35
+ JsonMap,
36
+ Object,
37
+ Op,
38
+ ProvisionReport,
39
+ Schema,
40
+ State,
41
+ TypeSchema,
42
+ Update,
43
+ op_from_json,
44
+ )
45
+ from .runtime import Adapter, run
46
+
47
+ __version__ = "0.1.0"
48
+
49
+ __all__ = [
50
+ "PROTOCOL_VERSION",
51
+ "Adapter",
52
+ "AppliedOp",
53
+ "ApplyReport",
54
+ "BackendId",
55
+ "Create",
56
+ "Delete",
57
+ "ExternalObject",
58
+ "FieldChange",
59
+ "FieldSchema",
60
+ "FieldType",
61
+ "JsonMap",
62
+ "Object",
63
+ "Op",
64
+ "ProvisionReport",
65
+ "Schema",
66
+ "State",
67
+ "TypeSchema",
68
+ "Update",
69
+ "op_from_json",
70
+ "run",
71
+ ]
@@ -0,0 +1,330 @@
1
+ """Typed model for the alembic external-adapter protocol.
2
+
3
+ These dataclasses mirror the JSON shapes the alembic host exchanges with an
4
+ adapter. The host serializes the whole request -- including the YAML ``setup:``
5
+ block -- as JSON, so this SDK needs no third-party dependencies.
6
+
7
+ The types fall into two groups:
8
+
9
+ * parsed from the request (``Object``, ``Op`` and its ``Create``/``Update``/
10
+ ``Delete`` variants, ``Schema``, ``State``): these have ``from_json``.
11
+ * produced by the adapter (``ExternalObject``, ``AppliedOp``, ``ApplyReport``,
12
+ ``ProvisionReport``): these have ``to_json`` and skip empty optional fields to
13
+ match the Rust serializer.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Any
20
+
21
+ # protocol version this SDK speaks. bumped in lockstep with the host.
22
+ PROTOCOL_VERSION = 1
23
+
24
+ # a backend identifier is an integer or a string (uuid, slug, ...).
25
+ BackendId = int | str
26
+
27
+ # the canonical representation of a `{string: json}` attrs/key map.
28
+ JsonMap = dict
29
+
30
+
31
+ # --------------------------------------------------------------------------- #
32
+ # schema #
33
+ # --------------------------------------------------------------------------- #
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class FieldType:
38
+ """A schema field type.
39
+
40
+ ``kind`` is a scalar ("string", "int", "ip_address", "cidr", ...) or one of
41
+ the composite kinds: "enum" (with ``values``), "list" (with ``item``), "map"
42
+ (with ``value``), or "ref"/"list_ref" (with ``target``). The composite
43
+ attributes are ``None`` for scalar kinds.
44
+ """
45
+
46
+ kind: str
47
+ values: list[str] | None = None
48
+ item: FieldType | None = None
49
+ value: FieldType | None = None
50
+ target: str | None = None
51
+
52
+ @classmethod
53
+ def from_json(cls, data: Any) -> FieldType:
54
+ if isinstance(data, str):
55
+ return cls(kind=data)
56
+ if isinstance(data, dict):
57
+ return _field_type_from_obj(data)
58
+ raise ValueError("field type must be a string or object")
59
+
60
+
61
+ def _field_type_from_obj(data: dict) -> FieldType:
62
+ kind = data.get("type")
63
+ if not isinstance(kind, str):
64
+ raise ValueError("field type requires a string 'type'")
65
+ if kind == "enum":
66
+ return FieldType(kind="enum", values=list(data.get("values", [])))
67
+ if kind == "list":
68
+ return FieldType(kind="list", item=FieldType.from_json(data["item"]))
69
+ if kind == "map":
70
+ return FieldType(kind="map", value=FieldType.from_json(data["value"]))
71
+ if kind in ("ref", "list_ref"):
72
+ return FieldType(kind=kind, target=data.get("target"))
73
+ return FieldType(kind=kind)
74
+
75
+
76
+ @dataclass
77
+ class FieldSchema:
78
+ """Metadata for a single field: its type and constraints."""
79
+
80
+ type: FieldType
81
+ required: bool = False
82
+ nullable: bool = False
83
+ format: str | None = None
84
+ pattern: str | None = None
85
+ description: str | None = None
86
+
87
+ @classmethod
88
+ def from_json(cls, data: dict) -> FieldSchema:
89
+ # composite type info ("item"/"value"/"values"/"target") lives next to
90
+ # "type" in a FieldSchema, mirroring the host's deserializer.
91
+ return cls(
92
+ type=_field_type_from_obj(data),
93
+ required=bool(data.get("required", False)),
94
+ nullable=bool(data.get("nullable", False)),
95
+ format=data.get("format"),
96
+ pattern=data.get("pattern"),
97
+ description=data.get("description"),
98
+ )
99
+
100
+
101
+ @dataclass
102
+ class TypeSchema:
103
+ """Key fields and attribute fields for one object type."""
104
+
105
+ key: dict[str, FieldSchema] = field(default_factory=dict)
106
+ fields: dict[str, FieldSchema] = field(default_factory=dict)
107
+
108
+ @classmethod
109
+ def from_json(cls, data: dict) -> TypeSchema:
110
+ return cls(
111
+ key={k: FieldSchema.from_json(v) for k, v in (data.get("key") or {}).items()},
112
+ fields={k: FieldSchema.from_json(v) for k, v in (data.get("fields") or {}).items()},
113
+ )
114
+
115
+
116
+ @dataclass
117
+ class Schema:
118
+ """The schema for the types in play, keyed by type name."""
119
+
120
+ types: dict[str, TypeSchema] = field(default_factory=dict)
121
+
122
+ @classmethod
123
+ def from_json(cls, data: Any) -> Schema:
124
+ raw = (data or {}).get("types", {})
125
+ return cls(types={name: TypeSchema.from_json(ts) for name, ts in raw.items()})
126
+
127
+
128
+ # --------------------------------------------------------------------------- #
129
+ # objects and operations (request side) #
130
+ # --------------------------------------------------------------------------- #
131
+
132
+
133
+ @dataclass
134
+ class Object:
135
+ """An IR object: a stable uid, a type, a natural key, and attrs."""
136
+
137
+ uid: str
138
+ type_name: str
139
+ key: JsonMap = field(default_factory=dict)
140
+ attrs: JsonMap = field(default_factory=dict)
141
+
142
+ @classmethod
143
+ def from_json(cls, data: dict) -> Object:
144
+ type_name = data.get("type", data.get("kind"))
145
+ if type_name is None:
146
+ raise ValueError("object missing 'type'")
147
+ return cls(
148
+ uid=data["uid"],
149
+ type_name=type_name,
150
+ key=dict(data.get("key") or {}),
151
+ attrs=dict(data.get("attrs") or {}),
152
+ )
153
+
154
+ def to_json(self) -> dict:
155
+ return {"uid": self.uid, "type": self.type_name, "key": self.key, "attrs": self.attrs}
156
+
157
+
158
+ @dataclass
159
+ class FieldChange:
160
+ """A single field-level change on an update op."""
161
+
162
+ field: str
163
+ from_value: Any = None
164
+ to_value: Any = None
165
+
166
+ @classmethod
167
+ def from_json(cls, data: dict) -> FieldChange:
168
+ return cls(field=data["field"], from_value=data.get("from"), to_value=data.get("to"))
169
+
170
+
171
+ @dataclass
172
+ class Op:
173
+ """Base class for a plan operation. See ``Create``/``Update``/``Delete``."""
174
+
175
+ uid: str
176
+ type_name: str
177
+
178
+
179
+ @dataclass
180
+ class Create(Op):
181
+ """Create a new backend object from ``desired``."""
182
+
183
+ desired: Object
184
+
185
+
186
+ @dataclass
187
+ class Update(Op):
188
+ """Update an existing backend object identified by ``backend_id``."""
189
+
190
+ desired: Object
191
+ changes: list[FieldChange] = field(default_factory=list)
192
+ backend_id: BackendId | None = None
193
+
194
+
195
+ @dataclass
196
+ class Delete(Op):
197
+ """Delete the backend object identified by ``backend_id``/``key``."""
198
+
199
+ key: JsonMap = field(default_factory=dict)
200
+ backend_id: BackendId | None = None
201
+
202
+
203
+ def op_from_json(data: dict) -> Op:
204
+ """Parse a plan operation from its tagged JSON form."""
205
+ kind = data.get("op")
206
+ uid = data["uid"]
207
+ type_name = data["type_name"]
208
+ if kind == "create":
209
+ return Create(uid=uid, type_name=type_name, desired=Object.from_json(data["desired"]))
210
+ if kind == "update":
211
+ return Update(
212
+ uid=uid,
213
+ type_name=type_name,
214
+ desired=Object.from_json(data["desired"]),
215
+ changes=[FieldChange.from_json(c) for c in data.get("changes") or []],
216
+ backend_id=data.get("backend_id"),
217
+ )
218
+ if kind == "delete":
219
+ return Delete(
220
+ uid=uid,
221
+ type_name=type_name,
222
+ key=dict(data.get("key") or {}),
223
+ backend_id=data.get("backend_id"),
224
+ )
225
+ raise ValueError(f"unknown op kind: {kind!r}")
226
+
227
+
228
+ # --------------------------------------------------------------------------- #
229
+ # state (request side) #
230
+ # --------------------------------------------------------------------------- #
231
+
232
+
233
+ @dataclass
234
+ class State:
235
+ """The engine's uid -> backend_id mappings, keyed by type name."""
236
+
237
+ mappings: dict[str, dict[str, BackendId]] = field(default_factory=dict)
238
+
239
+ @classmethod
240
+ def from_json(cls, data: Any) -> State:
241
+ raw = (data or {}).get("mappings") or {}
242
+ return cls(mappings={t: dict(m) for t, m in raw.items()})
243
+
244
+ def backend_id(self, type_name: str, uid: str) -> BackendId | None:
245
+ """Look up the backend id mapped to ``uid`` for ``type_name``, if any."""
246
+ return self.mappings.get(type_name, {}).get(uid)
247
+
248
+
249
+ # --------------------------------------------------------------------------- #
250
+ # adapter results (response side) #
251
+ # --------------------------------------------------------------------------- #
252
+
253
+
254
+ @dataclass
255
+ class ExternalObject:
256
+ """An object observed on the backend, returned from ``read``."""
257
+
258
+ type_name: str
259
+ key: JsonMap = field(default_factory=dict)
260
+ attrs: JsonMap = field(default_factory=dict)
261
+ backend_id: BackendId | None = None
262
+
263
+ def to_json(self) -> dict:
264
+ out: dict = {"type_name": self.type_name, "key": self.key, "attrs": self.attrs}
265
+ if self.backend_id is not None:
266
+ out["backend_id"] = self.backend_id
267
+ return out
268
+
269
+
270
+ @dataclass
271
+ class AppliedOp:
272
+ """The result of applying one operation, recorded in an ``ApplyReport``."""
273
+
274
+ uid: str
275
+ type_name: str
276
+ backend_id: BackendId | None = None
277
+
278
+ def to_json(self) -> dict:
279
+ out: dict = {"uid": self.uid, "type_name": self.type_name}
280
+ if self.backend_id is not None:
281
+ out["backend_id"] = self.backend_id
282
+ return out
283
+
284
+
285
+ @dataclass
286
+ class ProvisionReport:
287
+ """Schema elements provisioned by ``ensure_schema``."""
288
+
289
+ created_fields: list[str] = field(default_factory=list)
290
+ created_tags: list[str] = field(default_factory=list)
291
+ created_object_types: list[str] = field(default_factory=list)
292
+ created_object_fields: list[str] = field(default_factory=list)
293
+ deprecated_object_types: list[str] = field(default_factory=list)
294
+ deprecated_object_fields: list[str] = field(default_factory=list)
295
+ deleted_object_types: list[str] = field(default_factory=list)
296
+ deleted_object_fields: list[str] = field(default_factory=list)
297
+
298
+ def to_json(self) -> dict:
299
+ # created_fields/created_tags are always emitted (the host requires
300
+ # them); the rest are omitted when empty.
301
+ out: dict = {"created_fields": self.created_fields, "created_tags": self.created_tags}
302
+ for name in (
303
+ "created_object_types",
304
+ "created_object_fields",
305
+ "deprecated_object_types",
306
+ "deprecated_object_fields",
307
+ "deleted_object_types",
308
+ "deleted_object_fields",
309
+ ):
310
+ value = getattr(self, name)
311
+ if value:
312
+ out[name] = value
313
+ return out
314
+
315
+
316
+ @dataclass
317
+ class ApplyReport:
318
+ """Aggregated result of a ``write``: the ops applied plus any provisioning."""
319
+
320
+ applied: list[AppliedOp] = field(default_factory=list)
321
+ previously_applied_count: int | None = None
322
+ provision: ProvisionReport | None = None
323
+
324
+ def to_json(self) -> dict:
325
+ out: dict = {"applied": [op.to_json() for op in self.applied]}
326
+ if self.previously_applied_count is not None:
327
+ out["previously_applied_count"] = self.previously_applied_count
328
+ if self.provision is not None:
329
+ out["provision"] = self.provision.to_json()
330
+ return out
File without changes
@@ -0,0 +1,127 @@
1
+ """stdin/stdout protocol runner for alembic external adapters.
2
+
3
+ An external adapter is a standalone program. The alembic host spawns it, writes
4
+ one JSON request to its stdin, and reads one JSON response from its stdout.
5
+ Subclass :class:`Adapter`, implement the methods you need, and call :func:`run`
6
+ from your ``__main__``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from typing import Any, TextIO
14
+
15
+ from .model import (
16
+ PROTOCOL_VERSION,
17
+ ApplyReport,
18
+ ExternalObject,
19
+ Op,
20
+ ProvisionReport,
21
+ Schema,
22
+ State,
23
+ op_from_json,
24
+ )
25
+
26
+
27
+ class Adapter:
28
+ """Base class for an alembic external adapter.
29
+
30
+ Override the methods your backend supports. ``read`` defaults to returning
31
+ nothing (the right behaviour for emit-only adapters) and ``ensure_schema``
32
+ defaults to a no-op; ``write`` raises until you implement it.
33
+ """
34
+
35
+ def setup(self, config: Any) -> None:
36
+ """Configure the adapter from the ``setup:`` block.
37
+
38
+ ``config`` is the parsed ``setup:`` value from the backend config,
39
+ usually a ``dict`` (it may be ``None`` when no setup was provided).
40
+ Called once before each request.
41
+ """
42
+
43
+ def read(self, schema: Schema, types: list[str], state: State) -> list[ExternalObject]:
44
+ """Observe backend state for ``types``.
45
+
46
+ Return one :class:`ExternalObject` per backend record. The engine diffs
47
+ these against the desired inventory to build a plan. Emit-only adapters
48
+ can leave this as the default empty result.
49
+ """
50
+ return []
51
+
52
+ def write(self, schema: Schema, ops: list[Op], state: State) -> ApplyReport:
53
+ """Apply plan operations to the backend.
54
+
55
+ Handle each :class:`~alembic_adapter.Create`/``Update``/``Delete`` op,
56
+ then return an :class:`ApplyReport` recording what was applied.
57
+ """
58
+ raise NotImplementedError("adapter does not implement write")
59
+
60
+ def ensure_schema(self, schema: Schema) -> ProvisionReport:
61
+ """Provision backend schema before apply. Defaults to a no-op."""
62
+ return ProvisionReport()
63
+
64
+
65
+ def run(adapter: Adapter, *, stdin: TextIO | None = None, stdout: TextIO | None = None) -> None:
66
+ """Run a single request/response cycle for ``adapter`` over stdio.
67
+
68
+ Reads the entire request from ``stdin`` (default :data:`sys.stdin`), handles
69
+ it, and writes a newline-terminated JSON response to ``stdout`` (default
70
+ :data:`sys.stdout`). Any error is reported as a well-formed ``ok: false``
71
+ response rather than a crash, matching the protocol.
72
+ """
73
+ source = stdin if stdin is not None else sys.stdin
74
+ sink = stdout if stdout is not None else sys.stdout
75
+ response = _handle(adapter, source.read())
76
+ sink.write(json.dumps(response))
77
+ sink.write("\n")
78
+ sink.flush()
79
+
80
+
81
+ def _handle(adapter: Adapter, raw: str) -> dict:
82
+ try:
83
+ envelope = json.loads(raw)
84
+ except (ValueError, TypeError) as err:
85
+ return _error(f"invalid request: {err}")
86
+
87
+ if not isinstance(envelope, dict):
88
+ return _error("invalid request: expected a JSON object")
89
+
90
+ version = envelope.get("version")
91
+ if version != PROTOCOL_VERSION:
92
+ return _error(f"unsupported protocol version {version} (expected {PROTOCOL_VERSION})")
93
+
94
+ try:
95
+ adapter.setup(envelope.get("setup"))
96
+ return _dispatch(adapter, envelope)
97
+ except Exception as err: # noqa: BLE001 -- any adapter error becomes a protocol error.
98
+ return _error(str(err))
99
+
100
+
101
+ def _dispatch(adapter: Adapter, envelope: dict) -> dict:
102
+ method = envelope.get("method")
103
+ if method == "read":
104
+ schema = Schema.from_json(envelope.get("schema"))
105
+ types = list(envelope.get("types") or [])
106
+ state = State.from_json(envelope.get("state"))
107
+ observed = adapter.read(schema, types, state)
108
+ return _ok([obj.to_json() for obj in observed])
109
+ if method == "write":
110
+ schema = Schema.from_json(envelope.get("schema"))
111
+ ops = [op_from_json(op) for op in envelope.get("ops") or []]
112
+ state = State.from_json(envelope.get("state"))
113
+ report = adapter.write(schema, ops, state)
114
+ return _ok(report.to_json())
115
+ if method == "ensure_schema":
116
+ schema = Schema.from_json(envelope.get("schema"))
117
+ report = adapter.ensure_schema(schema)
118
+ return _ok(report.to_json())
119
+ return _error(f"unknown method: {method!r}")
120
+
121
+
122
+ def _ok(result: Any) -> dict:
123
+ return {"ok": True, "result": result}
124
+
125
+
126
+ def _error(message: str) -> dict:
127
+ return {"ok": False, "error": message}
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: alembic-adapter-sdk
3
+ Version: 0.1.0
4
+ Summary: SDK for writing alembic external adapters in Python
5
+ Project-URL: Homepage, https://github.com/cyberwitchery/alembic-adapter-sdk-python
6
+ Project-URL: Repository, https://github.com/cyberwitchery/alembic-adapter-sdk-python
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: adapter,alembic,dcim,ipam,network-automation
12
+ Classifier: Development Status :: 4 - Beta
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-adapter-sdk (python)
24
+
25
+ a small, dependency-free sdk for writing [alembic](https://github.com/cyberwitchery/alembic)
26
+ external adapters in python.
27
+
28
+ network engineering lives in python, so adapters should be writable there too.
29
+ alembic delegates backend i/o to *external adapters*: standalone programs the
30
+ alembic host spawns as subprocesses, exchanging one json request and one json
31
+ response over stdin/stdout. this sdk handles that protocol so you only write the
32
+ backend logic.
33
+
34
+ the import package is `alembic_adapter`. (the pypi distribution is
35
+ `alembic-adapter-sdk`; the bare name `alembic` belongs to sqlalchemy's migration
36
+ tool and is unrelated.)
37
+
38
+ ## install
39
+
40
+ ```bash
41
+ pip install alembic-adapter-sdk
42
+ ```
43
+
44
+ or, from a checkout:
45
+
46
+ ```bash
47
+ pip install -e .
48
+ ```
49
+
50
+ the sdk has no runtime dependencies; it speaks json with the stdlib.
51
+
52
+ ## writing an adapter
53
+
54
+ subclass `Adapter`, implement the methods your backend needs, and call `run`:
55
+
56
+ ```python
57
+ from alembic_adapter import Adapter, ApplyReport, AppliedOp, Create, run
58
+
59
+ class MyAdapter(Adapter):
60
+ def setup(self, config):
61
+ # `config` is the parsed `setup:` block from the backend config.
62
+ self.host = (config or {}).get("host", "http://localhost:8080")
63
+
64
+ def read(self, schema, types, state):
65
+ # observe backend state -> list[ExternalObject]; the engine diffs it
66
+ # against the desired inventory to build a plan. emit-only adapters
67
+ # return [] (the default).
68
+ return []
69
+
70
+ def write(self, schema, ops, state):
71
+ # apply create/update/delete ops, then report what was applied.
72
+ report = ApplyReport()
73
+ for op in ops:
74
+ if isinstance(op, Create):
75
+ ... # create op.desired on the backend
76
+ report.applied.append(AppliedOp(uid=op.uid, type_name=op.type_name))
77
+ return report
78
+
79
+ if __name__ == "__main__":
80
+ run(MyAdapter())
81
+ ```
82
+
83
+ `run` reads one request from stdin, dispatches it, and writes a
84
+ newline-terminated json response to stdout. any exception your adapter raises is
85
+ turned into a well-formed `{"ok": false, "error": ...}` response.
86
+
87
+ see [`examples/example_adapter.py`](examples/example_adapter.py) for a complete,
88
+ copyable starting point.
89
+
90
+ ## the protocol
91
+
92
+ every request carries `version` (currently `1`) and a `method`. the sdk parses
93
+ the payload into typed objects and serializes your results back:
94
+
95
+ | method | you receive | you return |
96
+ | --------------- | --------------------------------- | ------------------------- |
97
+ | `read` | `schema`, `types`, `state` | `list[ExternalObject]` |
98
+ | `write` | `schema`, `ops`, `state` | `ApplyReport` |
99
+ | `ensure_schema` | `schema` | `ProvisionReport` |
100
+
101
+ `setup` is the `setup:` block from the backend config (parsed json, usually a
102
+ dict); `Adapter.setup` is called once before each request.
103
+
104
+ the model mirrors alembic's ir:
105
+
106
+ - `Op` is `Create`, `Update`, or `Delete` (dispatch with `isinstance`). `Create`
107
+ and `Update` carry the full desired `Object`; `Update` also carries `changes`
108
+ and `backend_id`; `Delete` carries `key` and `backend_id`.
109
+ - `Object` has `uid`, `type_name`, `key`, and `attrs`.
110
+ - `State.backend_id(type_name, uid)` looks up the engine's existing backend id
111
+ for an object, so renames stay stable.
112
+ - `Schema` parses into `TypeSchema` / `FieldSchema` / `FieldType`, so
113
+ schema-driven adapters can, for example, find reference fields via
114
+ `field.type.kind == "ref"` and `field.type.target`.
115
+
116
+ for the full request/response shapes, see alembic's
117
+ [`docs/external-adapters.md`](https://github.com/cyberwitchery/alembic/blob/main/docs/external-adapters.md).
118
+
119
+ ## wiring into alembic
120
+
121
+ point a backend config at your program (see [`examples/backend.yaml`](examples/backend.yaml)):
122
+
123
+ ```yaml
124
+ backend: external
125
+ command: python3
126
+ args: ["examples/example_adapter.py"]
127
+ setup:
128
+ host: http://localhost:8080
129
+ ```
130
+
131
+ ```bash
132
+ alembic plan --backend external --backend-config examples/backend.yaml \
133
+ -f inventory.yaml -o plan.json
134
+ alembic apply --backend external --backend-config examples/backend.yaml \
135
+ -p plan.json
136
+ ```
137
+
138
+ you can also debug the protocol by hand by piping a request into your adapter:
139
+
140
+ ```bash
141
+ echo '{"version":1,"setup":{},"method":"read","schema":{"types":{}},"types":[],"state":{"mappings":{}}}' \
142
+ | python3 examples/example_adapter.py
143
+ ```
144
+
145
+ ## develop
146
+
147
+ ```bash
148
+ pip install -e ".[dev]"
149
+
150
+ # tests
151
+ PYTHONPATH=src python -m unittest discover -s tests
152
+
153
+ # tests with the coverage gate (fails under 100%, matching ci)
154
+ coverage run -m unittest discover -s tests
155
+ coverage report
156
+
157
+ ruff check
158
+ ruff format --check
159
+ ```
160
+
161
+ ## license
162
+
163
+ Apache-2.0
@@ -0,0 +1,8 @@
1
+ alembic_adapter/__init__.py,sha256=WisBVCCfbDJBZOVLIS7hOS_j1VVsAFhCsWhtCah2nnY,1509
2
+ alembic_adapter/model.py,sha256=KpcWjtufW16yf-WD46Et2snBoD_LchfvWCDX_1qB9dI,10938
3
+ alembic_adapter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ alembic_adapter/runtime.py,sha256=Gq4A9p_LG4s2DWbHLzJ7oC9Bxfw1DvZ_mF4JFChyrZU,4559
5
+ alembic_adapter_sdk-0.1.0.dist-info/METADATA,sha256=bZ_krq_I4jDJY6eWjTtdS5XcLEMChxVtZr8tffrNoZE,5641
6
+ alembic_adapter_sdk-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
7
+ alembic_adapter_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=QQQdFdXXMD9XBQHK41cCjfv-_1y5zwgNNmdF1PA8Ht4,11348
8
+ alembic_adapter_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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.