alembic-engine 0.7.0

Planning, apply, and state engine for Alembic.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! core engine types and adapter contract.

use alembic_core::{key_string, JsonMap, Key, Object, Schema, TypeName, Uid};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;

/// generic backend identifier (integer or string/uuid).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum BackendId {
    Int(u64),
    String(String),
}

impl fmt::Display for BackendId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BackendId::Int(id) => write!(f, "{}", id),
            BackendId::String(id) => write!(f, "{}", id),
        }
    }
}

impl From<u64> for BackendId {
    fn from(id: u64) -> Self {
        BackendId::Int(id)
    }
}

impl From<String> for BackendId {
    fn from(id: String) -> Self {
        BackendId::String(id)
    }
}

/// field-level change for an update op.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Hash, Eq)]
pub struct FieldChange {
    /// field name within attrs.
    pub field: String,
    /// previous value from observed state.
    pub from: serde_json::Value,
    /// desired value from the ir.
    pub to: serde_json::Value,
}

/// plan operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Hash, Eq)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Op {
    /// create a new backend object.
    Create {
        uid: Uid,
        type_name: TypeName,
        desired: Object,
    },
    /// update an existing backend object.
    Update {
        uid: Uid,
        type_name: TypeName,
        desired: Object,
        changes: Vec<FieldChange>,
        #[serde(skip_serializing_if = "Option::is_none")]
        backend_id: Option<BackendId>,
    },
    /// delete a backend object.
    Delete {
        uid: Uid,
        type_name: TypeName,
        key: Key,
        #[serde(skip_serializing_if = "Option::is_none")]
        backend_id: Option<BackendId>,
    },
}

impl Op {
    /// returns the ir uid for this operation.
    pub fn uid(&self) -> Uid {
        match self {
            Op::Create { uid, .. } => *uid,
            Op::Update { uid, .. } => *uid,
            Op::Delete { uid, .. } => *uid,
        }
    }

    /// returns the type name for this operation.
    pub fn type_name(&self) -> &TypeName {
        match self {
            Op::Create { type_name, .. } => type_name,
            Op::Update { type_name, .. } => type_name,
            Op::Delete { type_name, .. } => type_name,
        }
    }

    pub fn hashed(&self) -> u64 {
        stable_json_hash(self)
    }
}

/// hash a value's json serialization via the same v5 uuid mechanism ir
/// identity is built on. journal identity (file names, per-op hashes) is
/// persisted to disk and compared across runs, so it must not depend on
/// `DefaultHasher`, whose algorithm is not stable across rust releases.
pub(crate) fn stable_json_hash<T: Serialize>(value: &T) -> u64 {
    // serializing engine types cannot fail: plain structs and enums whose only
    // maps are string-keyed.
    let bytes = serde_json::to_vec(value).expect("engine value serializes to json");
    uuid::Uuid::new_v5(&alembic_core::ALEMBIC_UID_NAMESPACE, &bytes)
        .as_u64_pair()
        .0
}

/// full plan document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Plan {
    /// schema definitions required for apply.
    pub schema: Schema,
    /// ordered list of operations.
    pub ops: Vec<Op>,
    /// high-level summary of the plan.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<PlanSummary>,
    /// read-only preview of the schema provisioning apply would perform, populated at
    /// plan time. `None` when the backend cannot preview schema (or was not asked).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_preview: Option<ProvisionReport>,
}

/// high-level summary of plan operations.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PlanSummary {
    /// number of objects to create.
    pub create: usize,
    /// number of objects to update.
    pub update: usize,
    /// number of objects to delete.
    pub delete: usize,
}

impl Plan {
    /// build a summary for the current plan.
    pub fn summary(&self) -> PlanSummary {
        let mut summary = PlanSummary::default();
        for op in &self.ops {
            match op {
                Op::Create { .. } => summary.create += 1,
                Op::Update { .. } => summary.update += 1,
                Op::Delete { .. } => summary.delete += 1,
            }
        }
        summary
    }
}

/// observed backend object representation.
#[derive(Debug, Clone)]
pub struct ObservedObject {
    /// object type.
    pub type_name: TypeName,
    /// human key for matching.
    pub key: Key,
    /// observed attrs mapped to ir types.
    pub attrs: JsonMap,
    /// backend id when known.
    pub backend_id: Option<BackendId>,
}

/// observed backend state indexed by id and key.
#[derive(Debug, Default, Clone)]
pub struct ObservedState {
    /// observed objects keyed by backend id.
    pub by_backend_id: BTreeMap<(TypeName, BackendId), ObservedObject>,
    /// observed objects keyed by natural key.
    pub by_key: BTreeMap<(TypeName, String), ObservedObject>,
}

impl ObservedState {
    /// insert an observed object into both indexes.
    /// Disallows duplicate backend ids.
    pub fn insert(&mut self, object: ObservedObject) -> Result<()> {
        if let Some(id) = &object.backend_id {
            let key = (object.type_name.clone(), id.clone());
            if self.by_backend_id.contains_key(&key) {
                return Err(anyhow!(
                    "ObservedState already contains an object with backend id {} for type {}",
                    id,
                    object.type_name
                ));
            }
            self.by_backend_id.insert(key, object.clone());
        }

        let key = (object.type_name.clone(), key_string(&object.key));
        if self.by_key.contains_key(&key) {
            return Err(anyhow!(
                "ObservedState already contains an object with natural key {:?}",
                key
            ));
        }
        self.by_key.insert(key, object);

        Ok(())
    }
}

/// result for a single applied operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppliedOp {
    /// ir uid for the operation.
    pub uid: Uid,
    /// type for the operation.
    pub type_name: TypeName,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// backend id returned by the adapter, if any.
    pub backend_id: Option<BackendId>,
}

/// aggregated apply report.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ApplyReport {
    /// list of operations applied by the adapter.
    pub applied: Vec<AppliedOp>,
    /// number of previously applied operations, only set when apply is accompanied by a journal
    #[serde(skip_serializing_if = "Option::is_none")]
    pub previously_applied_count: Option<usize>,
    /// schema provisioning report (populated when ensure_schema runs).
    #[serde(default)]
    pub provision: ProvisionReport,
}

/// report from ensure_schema provisioning.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProvisionReport {
    /// custom fields created on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub created_fields: Vec<String>,
    /// tags created on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub created_tags: Vec<String>,
    /// custom object types created on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub created_object_types: Vec<String>,
    /// custom object fields created on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub created_object_fields: Vec<String>,
    /// object types deprecated on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deprecated_object_types: Vec<String>,
    /// object fields deprecated on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deprecated_object_fields: Vec<String>,
    /// object types deleted on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deleted_object_types: Vec<String>,
    /// object fields deleted on the backend.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deleted_object_fields: Vec<String>,
}

impl ProvisionReport {
    pub fn is_empty(&self) -> bool {
        self.created_fields.is_empty()
            && self.created_tags.is_empty()
            && self.created_object_types.is_empty()
            && self.created_object_fields.is_empty()
            && self.deprecated_object_types.is_empty()
            && self.deprecated_object_fields.is_empty()
            && self.deleted_object_types.is_empty()
            && self.deleted_object_fields.is_empty()
    }
}

impl fmt::Display for ProvisionReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_empty() {
            return write!(f, "no schema changes");
        }

        let mut first = true;
        let sections: &[(&str, &[String])] = &[
            ("fields created", &self.created_fields),
            ("tags created", &self.created_tags),
            ("object types created", &self.created_object_types),
            ("object fields created", &self.created_object_fields),
            ("object types deprecated", &self.deprecated_object_types),
            ("object fields deprecated", &self.deprecated_object_fields),
            ("object types deleted", &self.deleted_object_types),
            ("object fields deleted", &self.deleted_object_fields),
        ];

        for (label, items) in sections {
            if items.is_empty() {
                continue;
            }
            if !first {
                write!(f, ", ")?;
            }
            write!(f, "{} {label}", items.len())?;
            first = false;
        }

        Ok(())
    }
}

/// read capability: observe backend state.
#[async_trait]
pub trait Observer: Send + Sync {
    async fn read(
        &self,
        schema: &Schema,
        types: &[TypeName],
        state: &crate::state::StateStore,
    ) -> anyhow::Result<ObservedState>;
}

/// write capability: apply a plan's operations.
#[async_trait]
pub trait Emitter: Send + Sync {
    async fn write(
        &self,
        schema: &Schema,
        ops: &[Op],
        state: &crate::state::StateStore,
    ) -> anyhow::Result<ApplyReport>;
}

/// full adapter contract for read+write backends; may also provision schema.
#[async_trait]
pub trait Adapter: Observer + Emitter {
    async fn ensure_schema(&self, _schema: &Schema) -> anyhow::Result<ProvisionReport> {
        Ok(ProvisionReport::default())
    }

    /// read-only counterpart to [`Adapter::ensure_schema`]: report what provisioning
    /// apply would perform, writing nothing. `None` means this adapter cannot preview
    /// schema (reported honestly, never as "no schema changes"); `Some(report)` is the
    /// provisioning it would carry out, `Some(empty)` that there is nothing to provision.
    async fn preview_schema(&self, _schema: &Schema) -> anyhow::Result<Option<ProvisionReport>> {
        Ok(None)
    }
}

/// a constructed backend, tagged with its capability.
pub enum Backend {
    /// read-only backend (e.g. peeringdb).
    Observer(Box<dyn Observer>),
    /// write-only backend (e.g. django codegen).
    Emitter(Box<dyn Emitter>),
    /// read+write backend.
    Adapter(Box<dyn Adapter>),
}

impl Backend {
    pub fn observer(&self) -> anyhow::Result<&dyn Observer> {
        match self {
            Backend::Observer(observer) => Ok(observer.as_ref()),
            Backend::Adapter(adapter) => Ok(adapter.as_ref()),
            Backend::Emitter(_) => Err(anyhow::anyhow!(
                "backend is write-only; it cannot observe state"
            )),
        }
    }

    pub fn emitter(&self) -> anyhow::Result<&dyn Emitter> {
        match self {
            Backend::Emitter(emitter) => Ok(emitter.as_ref()),
            Backend::Adapter(adapter) => Ok(adapter.as_ref()),
            Backend::Observer(_) => Err(anyhow::anyhow!(
                "backend is read-only; it cannot apply changes"
            )),
        }
    }

    pub fn adapter(&self) -> anyhow::Result<&dyn Adapter> {
        match self {
            Backend::Adapter(adapter) => Ok(adapter.as_ref()),
            Backend::Observer(_) => Err(anyhow::anyhow!(
                "backend is read-only; it cannot provision schema"
            )),
            Backend::Emitter(_) => Err(anyhow::anyhow!(
                "backend is write-only; it cannot provision schema"
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alembic_core::{Key, TypeName, Uid};

    #[test]
    fn backend_id_serialization() {
        let int_id = BackendId::Int(123);
        let json = serde_json::to_string(&int_id).unwrap();
        assert_eq!(json, "123");
        let back: BackendId = serde_json::from_str(&json).unwrap();
        assert_eq!(back, int_id);

        let str_id = BackendId::String("uuid".to_string());
        let json = serde_json::to_string(&str_id).unwrap();
        assert_eq!(json, "\"uuid\"");
        let back: BackendId = serde_json::from_str(&json).unwrap();
        assert_eq!(back, str_id);
    }

    #[test]
    fn provision_report_defaults_omitted_lists() {
        // a non-Rust ensure_schema adapter that provisioned an object type but no
        // custom fields/tags naturally omits the empty lists; that must deserialize.
        let report: ProvisionReport =
            serde_json::from_value(serde_json::json!({"created_object_types": ["dcim.site"]}))
                .unwrap();
        assert!(report.created_fields.is_empty());
        assert!(report.created_tags.is_empty());
        assert_eq!(report.created_object_types, ["dcim.site"]);

        // the whole report deserializes from an empty object.
        assert!(serde_json::from_str::<ProvisionReport>("{}")
            .unwrap()
            .is_empty());
    }

    #[test]
    fn op_helpers() {
        let uid = Uid::from_u128(1);
        let type_name = TypeName::new("test.type");
        let op = Op::Delete {
            uid,
            type_name: type_name.clone(),
            key: Key::default(),
            backend_id: None,
        };
        assert_eq!(op.uid(), uid);
        assert_eq!(op.type_name(), &type_name);
    }
}