greentic-deployer-dev 1.1.27411998332

Greentic deployer runtime for plan construction and deployment-pack dispatch
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
442
443
444
445
446
447
448
//! [`EnvironmentMutations`] — typed-verb trait for state mutations on a
//! Greentic environment.
//!
//! Phase D rescope (2026-06-09): this trait replaces the closure-based
//! [`LocalFsStore::transact`](super::LocalFsStore::transact) pattern with one
//! method per logical CLI verb. See `plans/next-gen-deployment.md` §13.5 #2
//! for the architectural rationale; in short: closures can't cross the A8
//! HTTP wire contract (`greentic_deploy_spec::remote`), so the deployer-CLI's
//! seam against a remote store has to be typed verbs, not opaque
//! `FnOnce(&Locked)` closures.
//!
//! This module ships in **PR-3a.1 as signatures only** — there are no impls,
//! and no callers reach the trait yet. PR-3a.2..3a.16 migrate one verb group
//! at a time, each adding the `LocalFsStore` impl + flipping the matching
//! CLI helper from `store.transact(|locked| …)` to a typed call. PR-3b lands
//! `HttpEnvironmentStore` implementing the same trait over the A8 HTTP
//! contract.
//!
//! Signatures here are derived from the existing 33 `LocalFsStore::transact`
//! sites in `src/cli/*` (15 logical verb groups, ~28 methods). They may
//! tweak as PR-3a.2..16 add impls — flag drift in code review.

use greentic_deploy_spec::{
    BundleDeployment, BundleId, CapabilitySlot, DeploymentId, EnvId, EnvPackBinding, Environment,
    EnvironmentHostConfig, ExtensionBinding, IdempotencyKey, MessagingEndpoint,
    MessagingEndpointId, PackId, Revision, RevisionId,
};

use super::StoreError;

// PR-4.2a/4.2b/4.2c: the env-lifecycle payload shapes (`ExtensionKey`,
// `FieldUpdate`, `UpdateEnvironmentPayload`, `MigrateSeedPayload`,
// `MigrateMergePayload`), the revision verb group's
// (`StageRevisionPayload`, `WarmRevisionPayload`,
// `RevisionTransitionOutcome`) and the traffic verb group's
// (`SetTrafficSplitPayload`, `ApplyTrafficSplitOutcome`,
// `RollbackTrafficSplitOutcome`) moved to `greentic_deploy_spec::engine` so
// the operator-store-server applies the same verb semantics (and wire
// encoding) as `LocalFsStore`. Re-exported here so every existing
// `environment::mutations::…` path keeps working. The revision payloads no
// longer carry `idempotency_key` — the key rides the trait methods (and the
// A8 `Idempotency-Key` header), matching every other verb group. (The
// traffic outcomes gained an `environment` snapshot: the CLI emits
// `TrafficSplitApplied` telemetry from it, identical local and remote.)
// PR-4.2f: the trust-root group's wire shapes (`AddTrustedKeyPayload`,
// `TrustRootSeed`, `TrustRootAddOutcome`, `TrustRootRemoveOutcome`)
// followed — shapes only; the pure transforms need crypto and live in
// `greentic-operator-trust`.
// PR-4.2g: the bundles group's shapes (`AddBundlePayload`,
// `UpdateBundlePayload`, `RemoveBundleOutcome`) followed, dropping their
// embedded `idempotency_key` — the key rides the trait methods (and the A8
// `Idempotency-Key` header), matching every other verb group.
pub use greentic_deploy_spec::engine::{
    AddBundlePayload, AddTrustedKeyPayload, ApplyTrafficSplitOutcome, ExtensionKey, FieldUpdate,
    MigrateMergePayload, MigrateSeedPayload, RemoveBundleOutcome, RevisionTransitionOutcome,
    RollbackTrafficSplitOutcome, SetTrafficSplitPayload, StageRevisionPayload, TrustRootAddOutcome,
    TrustRootRemoveOutcome, TrustRootSeed, UpdateBundlePayload, UpdateEnvironmentPayload,
    WarmRevisionPayload,
};

/// Inputs to [`EnvironmentMutations::add_messaging_endpoint`].
#[derive(Debug, Clone)]
pub struct AddMessagingEndpointPayload {
    pub provider_id: String,
    pub provider_type: String,
    pub display_name: String,
    pub secret_refs: Vec<String>,
    pub updated_by: String,
    pub idempotency_key: IdempotencyKey,
}

/// Inputs to [`EnvironmentMutations::set_messaging_welcome_flow`].
#[derive(Debug, Clone)]
pub struct SetMessagingWelcomeFlowPayload {
    pub endpoint_id: MessagingEndpointId,
    pub bundle_id: BundleId,
    pub pack_id: PackId,
    pub flow_id: String,
    pub updated_by: String,
    pub idempotency_key: IdempotencyKey,
}

/// The typed-verb persistence operations a Greentic environment store
/// performs in response to `op …` CLI verbs.
///
/// Replaces the closure-based `LocalFsStore::transact` pattern with one
/// method per logical verb. All methods take `&self` — concurrency is the
/// impl's responsibility (flock for `LocalFsStore`, optimistic CAS via
/// `If-Match` for `HttpEnvironmentStore` against an A8-compliant server).
///
/// Methods that need idempotency replay (per A8 §2) take an
/// [`IdempotencyKey`]; methods that are intrinsically idempotent (e.g.
/// `seed_trust_root_if_absent`) do not.
///
/// **Errors**: all methods return [`StoreError`]. Impls may map their
/// transport-specific errors into the existing variants; new variants land
/// alongside the impl that needs them.
pub trait EnvironmentMutations: Send + Sync {
    // -------------------------------------------------------------
    // Environment lifecycle
    //   `op env create | update | set-public-url`
    //   `op config set`
    //
    // `op env init` / `gtc setup` is NOT on this trait — it's local-FS
    // only (default-binding heal + runtime stub), so it stays inherent
    // on `LocalFsStore`. The HTTP backend has its own bootstrap path.
    // -------------------------------------------------------------

    /// Create a fresh environment with empty bundles/revisions/packs.
    /// Rejects if the env already exists.
    fn create_environment(
        &self,
        env_id: &EnvId,
        name: String,
        host_config: EnvironmentHostConfig,
    ) -> Result<Environment, StoreError>;

    /// Patch the named scalar fields on an existing environment.
    /// [`FieldUpdate::Keep`] fields are skipped, [`FieldUpdate::Set`]
    /// writes the new value, [`FieldUpdate::Clear`] resets optional
    /// fields to `None`. The full updated `Environment` is returned.
    /// Covers what was previously split across `update_environment` (no
    /// `listen_addr`), `set_public_url` (single field), and `set_config`
    /// (host-level fields including `listen_addr`). One verb, one HTTP
    /// endpoint, one impl body per backend.
    fn update_environment(
        &self,
        env_id: &EnvId,
        patch: UpdateEnvironmentPayload,
    ) -> Result<Environment, StoreError>;

    // -------------------------------------------------------------
    // Migration
    //   `op env migrate-dev --apply`
    // -------------------------------------------------------------

    /// Merge pack bindings and extension bindings into `target_env_id`.
    /// Skips slots / extension keys already bound in the target. Returns
    /// the list of newly-merged slots + extension key strings (in the
    /// form `"<kind_path>::<instance_id>"`).
    ///
    /// `payload.seed_if_missing` is the optional seed-on-create-target
    /// branch used by `op env migrate-dev` to migrate a legacy `dev` env
    /// into a fresh `local` target atomically — load, fallback-to-seed,
    /// merge, save all happen under one lock.
    fn migrate_merge_bindings(
        &self,
        target_env_id: &EnvId,
        payload: MigrateMergePayload,
    ) -> Result<(Vec<String>, Vec<String>), StoreError>;

    // -------------------------------------------------------------
    // Revision lifecycle
    //   `op revisions stage | warm | drain | archive`
    // -------------------------------------------------------------

    /// Stage a fresh revision under `deployment_id`. The caller supplies
    /// the pinned artifact pointers; `LocalFsStore`'s CLI helper resolves
    /// them from a local `.gtbundle` upstream of this call so the trait
    /// stays storage-only.
    ///
    /// `idempotency_key`: A8 §2 — same-key replay returns the originally
    /// staged `Revision` without re-minting the ULID or advancing the
    /// sequence. Local impl accepts and ignores; HTTP backends cache it.
    fn stage_revision(
        &self,
        env_id: &EnvId,
        payload: StageRevisionPayload,
        idempotency_key: IdempotencyKey,
    ) -> Result<Revision, StoreError>;

    /// Transition a revision through its `warm` lifecycle chain, applying the
    /// client-evaluated health-gate outcome. The deployer CLI runs the
    /// runner-side health checks locally and ships the result in
    /// [`WarmRevisionPayload::health_gate`]: `Ok(())` advances the revision
    /// to `Ready`; `Err(failure)` flips it to `Failed` atomically. This
    /// replaces the closure-based gate so the operation can cross the A8
    /// HTTP wire contract.
    fn warm_revision(
        &self,
        env_id: &EnvId,
        payload: WarmRevisionPayload,
        idempotency_key: IdempotencyKey,
    ) -> Result<RevisionTransitionOutcome, StoreError>;

    /// Drain a `Ready` revision (graceful step-down → `Drained`).
    /// `idempotency_key` is required for A8 mutation consistency even though
    /// drain is logically idempotent — the key enables audit-event replay.
    fn drain_revision(
        &self,
        env_id: &EnvId,
        revision_id: RevisionId,
        idempotency_key: IdempotencyKey,
    ) -> Result<RevisionTransitionOutcome, StoreError>;

    /// Archive a `Drained` / `Failed` revision (terminal).
    /// `idempotency_key` is required for A8 mutation consistency even though
    /// archive is logically idempotent — the key enables audit-event replay.
    fn archive_revision(
        &self,
        env_id: &EnvId,
        revision_id: RevisionId,
        idempotency_key: IdempotencyKey,
    ) -> Result<RevisionTransitionOutcome, StoreError>;

    // -------------------------------------------------------------
    // Bundle deployment CRUD
    //   `op bundles add | update | remove`
    // -------------------------------------------------------------

    /// `idempotency_key` is required for A8 §2 mutation replay; the local
    /// impl accepts and ignores, the HTTP backend caches the original
    /// outcome.
    fn add_bundle(
        &self,
        env_id: &EnvId,
        payload: AddBundlePayload,
        idempotency_key: IdempotencyKey,
    ) -> Result<BundleDeployment, StoreError>;

    /// `idempotency_key` is required for A8 §2 mutation replay; the local
    /// impl accepts and ignores, the HTTP backend caches the original
    /// outcome.
    fn update_bundle(
        &self,
        env_id: &EnvId,
        payload: UpdateBundlePayload,
        idempotency_key: IdempotencyKey,
    ) -> Result<BundleDeployment, StoreError>;

    /// Remove a bundle deployment from the env. Refuses if the deployment
    /// still has live traffic splits or non-archived revisions —
    /// callers must `op traffic clear` and archive revisions first.
    ///
    /// Also drops archived revisions for the same `deployment_id` so the
    /// env stays compact. The pruned IDs are surfaced on the outcome so
    /// the destructive side effect is explicit on the contract —
    /// HTTP backends can apply a separate authorization check against
    /// the prune set, the CLI logs the IDs in the audit target.
    ///
    /// `idempotency_key` is required for A8 §2 mutation replay; the local
    /// impl accepts and ignores, the HTTP backend caches the original
    /// outcome.
    fn remove_bundle(
        &self,
        env_id: &EnvId,
        deployment_id: DeploymentId,
        idempotency_key: IdempotencyKey,
    ) -> Result<RemoveBundleOutcome, StoreError>;

    // -------------------------------------------------------------
    // Env-pack binding CRUD
    //   `op env-packs add | update | remove | rollback`
    // -------------------------------------------------------------

    fn add_pack_binding(
        &self,
        env_id: &EnvId,
        binding: EnvPackBinding,
        idempotency_key: IdempotencyKey,
    ) -> Result<EnvPackBinding, StoreError>;

    /// Returns `(new_binding, new_generation)` — the bumped audit generation
    /// is surfaced for downstream observability.
    fn update_pack_binding(
        &self,
        env_id: &EnvId,
        slot: CapabilitySlot,
        binding: EnvPackBinding,
        idempotency_key: IdempotencyKey,
    ) -> Result<(EnvPackBinding, u64), StoreError>;

    fn remove_pack_binding(
        &self,
        env_id: &EnvId,
        slot: CapabilitySlot,
        idempotency_key: IdempotencyKey,
    ) -> Result<(EnvPackBinding, u64), StoreError>;

    fn rollback_pack_binding(
        &self,
        env_id: &EnvId,
        slot: CapabilitySlot,
        idempotency_key: IdempotencyKey,
    ) -> Result<(EnvPackBinding, u64), StoreError>;

    // -------------------------------------------------------------
    // Extension binding CRUD
    //   `op extensions add | update | remove | rollback`
    // -------------------------------------------------------------

    fn add_extension_binding(
        &self,
        env_id: &EnvId,
        binding: ExtensionBinding,
        idempotency_key: IdempotencyKey,
    ) -> Result<ExtensionBinding, StoreError>;

    fn update_extension_binding(
        &self,
        env_id: &EnvId,
        key: ExtensionKey,
        binding: ExtensionBinding,
        idempotency_key: IdempotencyKey,
    ) -> Result<(ExtensionBinding, u64), StoreError>;

    fn remove_extension_binding(
        &self,
        env_id: &EnvId,
        key: ExtensionKey,
        idempotency_key: IdempotencyKey,
    ) -> Result<(ExtensionBinding, u64), StoreError>;

    fn rollback_extension_binding(
        &self,
        env_id: &EnvId,
        key: ExtensionKey,
        idempotency_key: IdempotencyKey,
    ) -> Result<(ExtensionBinding, u64), StoreError>;

    // -------------------------------------------------------------
    // Traffic
    //   `op traffic set | rollback`
    // -------------------------------------------------------------

    fn set_traffic_split(
        &self,
        env_id: &EnvId,
        payload: SetTrafficSplitPayload,
        idempotency_key: IdempotencyKey,
    ) -> Result<ApplyTrafficSplitOutcome, StoreError>;

    fn rollback_traffic_split(
        &self,
        env_id: &EnvId,
        deployment_id: DeploymentId,
        idempotency_key: IdempotencyKey,
    ) -> Result<RollbackTrafficSplitOutcome, StoreError>;

    // -------------------------------------------------------------
    // Messaging endpoints
    //   `op messaging endpoint add | link-bundle | unlink-bundle
    //                  | set-welcome-flow | remove | rotate-webhook-secret`
    // -------------------------------------------------------------

    fn add_messaging_endpoint(
        &self,
        env_id: &EnvId,
        payload: AddMessagingEndpointPayload,
    ) -> Result<MessagingEndpoint, StoreError>;

    fn link_messaging_bundle(
        &self,
        env_id: &EnvId,
        endpoint_id: MessagingEndpointId,
        bundle_id: BundleId,
        updated_by: String,
        idempotency_key: IdempotencyKey,
    ) -> Result<MessagingEndpoint, StoreError>;

    fn unlink_messaging_bundle(
        &self,
        env_id: &EnvId,
        endpoint_id: MessagingEndpointId,
        bundle_id: BundleId,
        updated_by: String,
        idempotency_key: IdempotencyKey,
    ) -> Result<MessagingEndpoint, StoreError>;

    fn set_messaging_welcome_flow(
        &self,
        env_id: &EnvId,
        payload: SetMessagingWelcomeFlowPayload,
    ) -> Result<MessagingEndpoint, StoreError>;

    fn remove_messaging_endpoint(
        &self,
        env_id: &EnvId,
        endpoint_id: MessagingEndpointId,
    ) -> Result<MessagingEndpointId, StoreError>;

    fn rotate_messaging_webhook_secret(
        &self,
        env_id: &EnvId,
        endpoint_id: MessagingEndpointId,
        updated_by: String,
        idempotency_key: IdempotencyKey,
    ) -> Result<MessagingEndpoint, StoreError>;

    // -------------------------------------------------------------
    // Trust root
    //   `op trust-root bootstrap | add | remove`
    //   (`seed_trust_root_if_absent` is called from `op env init`)
    // -------------------------------------------------------------

    /// Load (or generate) the backend's operator signing key and add it to
    /// the env trust root. Idempotent re-grant: a second call with the same
    /// operator key is a no-op on the key set (case-insensitive `key_id`
    /// dedup), and it never rejects on an existing trust root.
    fn bootstrap_trust_root(&self, env_id: &EnvId) -> Result<TrustRootSeed, StoreError>;

    /// Idempotent variant called from `op env init`: returns `Some(seed)`
    /// when a key was minted, `None` when a trust root already existed.
    fn seed_trust_root_if_absent(
        &self,
        env_id: &EnvId,
    ) -> Result<Option<TrustRootSeed>, StoreError>;

    /// `idempotency_key` is required for A8 mutation consistency even though
    /// `add_trusted_key` is intrinsically idempotent on `key_id` collision —
    /// the key enables HTTP-backend audit-event replay. Local-FS impls accept
    /// and ignore it; HTTP impls cache it for replay.
    fn add_trusted_key(
        &self,
        env_id: &EnvId,
        key_id: String,
        public_key_pem: String,
        idempotency_key: IdempotencyKey,
    ) -> Result<TrustRootAddOutcome, StoreError>;

    /// `idempotency_key` is required for A8 mutation consistency. `remove`
    /// is logically idempotent on the trust-root state, but the wire-shape
    /// `removed_public_key_pem` field would be `null` on retry (the original
    /// PEM is gone) — so a retry without replay loses recovery material AND
    /// audit fidelity. The key enables HTTP-backend replay of the original
    /// response/audit; local-FS impls accept and ignore it.
    fn remove_trusted_key(
        &self,
        env_id: &EnvId,
        key_id: String,
        idempotency_key: IdempotencyKey,
    ) -> Result<TrustRootRemoveOutcome, StoreError>;
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Compile-time guard: the trait stays object-safe so future code can
    /// hold `&dyn EnvironmentMutations` / `Box<dyn EnvironmentMutations>`
    /// (e.g. for runtime selection between `LocalFsStore` and
    /// `HttpEnvironmentStore` in PR-3c).
    #[allow(dead_code)]
    fn _is_object_safe(_: &dyn EnvironmentMutations) {}

    // `FieldUpdate` / `UpdateEnvironmentPayload` / `ExtensionKey` unit tests
    // moved to `greentic_deploy_spec::engine` alongside the types (PR-4.2a).
}