Skip to main content

alien_commands/server/
command_registry.rs

1//! Command registry abstraction for command server
2//!
3//! The CommandRegistry is the **source of truth** for all command metadata.
4//! It tracks command state, timestamps, sizes, and errors.
5//!
6//! Implementations:
7//! - `InMemoryCommandRegistry`: In-memory implementation for tests and local dev (in this crate)
8//! - `PlatformCommandRegistry`: Platform API integration (in alien-manager)
9//!
10//! The command KV store holds only operational data: params/response blobs, pending indices, leases.
11
12use crate::error::{ErrorData, Result};
13use alien_core::{CommandDeliveryMode, CommandState, CommandTarget, CommandTargetType};
14use alien_error::AlienError;
15use async_trait::async_trait;
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use std::sync::Arc;
20use tokio::sync::RwLock;
21use uuid::Uuid;
22
23/// A command target resolved by the registry, plus how commands reach it.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ResolvedCommandTarget {
26    /// The specific resource the command is addressed to
27    pub target: CommandTarget,
28    /// How commands are delivered to this target (Push or Pull)
29    pub delivery_mode: CommandDeliveryMode,
30}
31
32/// Metadata returned when creating a command
33#[derive(Debug, Clone)]
34pub struct CommandMetadata {
35    /// Unique command ID
36    pub command_id: String,
37    /// The specific resource the command is addressed to
38    pub target: CommandTarget,
39    /// How to dispatch the command (Push or Pull)
40    pub delivery_mode: CommandDeliveryMode,
41    /// Project ID for routing/authorization
42    pub project_id: String,
43}
44
45/// Data needed to build an envelope during lease acquisition
46#[derive(Debug, Clone)]
47pub struct CommandEnvelopeData {
48    pub command_id: String,
49    pub deployment_id: String,
50    pub command: String, // command name
51    pub attempt: u32,
52    pub deadline: Option<DateTime<Utc>>,
53    pub state: CommandState,
54    pub target: CommandTarget,
55    pub delivery_mode: CommandDeliveryMode,
56}
57
58/// Full status for GET /commands/{id}
59#[derive(Debug, Clone)]
60pub struct CommandStatus {
61    pub command_id: String,
62    pub workspace_id: String,
63    pub project_id: String,
64    pub deployment_id: String,
65    pub command: String, // command name
66    pub state: CommandState,
67    pub attempt: u32,
68    pub deadline: Option<DateTime<Utc>>,
69    pub created_at: DateTime<Utc>,
70    pub dispatched_at: Option<DateTime<Utc>>,
71    pub completed_at: Option<DateTime<Utc>>,
72    pub error: Option<serde_json::Value>,
73    pub request_size_bytes: Option<u64>,
74    pub response_size_bytes: Option<u64>,
75    pub target: CommandTarget,
76}
77
78/// Canonical ownership fields needed to authorize command reads.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct CommandAccessContext {
81    pub workspace_id: String,
82    pub project_id: String,
83    pub deployment_id: String,
84    pub target: CommandTarget,
85}
86
87/// Internal command record stored in memory
88#[derive(Debug, Clone, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90struct CommandRecord {
91    id: String,
92    deployment_id: String,
93    command: String,
94    state: CommandState,
95    attempt: u32,
96    deadline: Option<DateTime<Utc>>,
97    created_at: DateTime<Utc>,
98    dispatched_at: Option<DateTime<Utc>>,
99    completed_at: Option<DateTime<Utc>>,
100    request_size_bytes: Option<u64>,
101    response_size_bytes: Option<u64>,
102    error: Option<serde_json::Value>,
103    target: CommandTarget,
104    delivery_mode: CommandDeliveryMode,
105    project_id: String,
106}
107
108/// Reject a command-target resource id that would break the `:`-delimited key
109/// grammar used by the pending index (`target:{dep}:{rid}:pending:…`) and the
110/// idempotency key (`{dep}:{rid}:{command}:{key}`).
111///
112/// An id containing `:` could forge or collide with another target's key
113/// segments, so it is rejected at the commands layer with a typed error. Only
114/// the delimiter that can forge index segments is enforced at this layer.
115pub fn validate_command_target_id(resource_id: &str) -> Result<()> {
116    if resource_id.contains(':') {
117        return Err(AlienError::new(ErrorData::CommandTargetIdInvalid {
118            resource_id: resource_id.to_string(),
119        }));
120    }
121    Ok(())
122}
123
124/// Reject a command name that would break the same `:`-delimited idempotency
125/// key grammar (`{dep}:{rid}:{command}:{key}`).
126///
127/// The trailing client key routinely contains ':', so a ':' in the command
128/// name would be indistinguishable from the key boundary: (command="a:b",
129/// key="c") and (command="a", key="b:c") would forge the same key. Rejecting
130/// ':' in the command name keeps the command segment unambiguous — the twin of
131/// [`validate_command_target_id`] for the command segment.
132pub fn validate_command_name(command: &str) -> Result<()> {
133    if command.contains(':') {
134        return Err(AlienError::new(ErrorData::InvalidCommand {
135            message: format!("Command name '{command}' must not contain ':'"),
136        }));
137    }
138    Ok(())
139}
140
141/// The reserved command-target id for the operator itself. Commands addressed
142/// to this id are operator-level operations (e.g. an operations-plugin command)
143/// the operator runs via its embedded receiver — not a resource in the
144/// deployment's stack. It is resolved to a pull-mode daemon target without
145/// consulting the stack, since the operator is not a stack resource.
146pub const OPERATOR_COMMAND_TARGET_ID: &str = "operator";
147
148/// Target-selection rules shared by both the
149/// in-memory and SQLite registries route through.
150///
151/// - `requested = Some(id)`: the id must be well-formed (no `:`) and name an
152///   existing command-capable target, else `COMMAND_TARGET_NOT_FOUND`. An empty
153///   id never falls back to shorthand. The reserved
154///   [`OPERATOR_COMMAND_TARGET_ID`] always resolves to a pull-mode daemon
155///   target for the operator, independent of the stack.
156/// - `requested = None` (single-target shorthand): exactly one non-reserved
157///   stack target must exist, else `COMMAND_TARGET_AMBIGUOUS` (more than one)
158///   or `NO_COMMAND_TARGETS` (none). A registered target named
159///   [`OPERATOR_COMMAND_TARGET_ID`] is excluded so shorthand can never address
160///   the operator.
161///
162/// The resolved target's own id is also validated, so a target registered with
163/// a `:`-bearing id can never resolve into the key grammar.
164pub fn select_command_target(
165    deployment_id: &str,
166    targets: &[CommandTarget],
167    requested: Option<&str>,
168) -> Result<CommandTarget> {
169    // The operator is a reserved target, not a stack resource — resolve it
170    // directly so operations commands can be addressed to the operator without
171    // it having to appear in the deployment's command-capable stack targets.
172    if requested == Some(OPERATOR_COMMAND_TARGET_ID) {
173        return Ok(CommandTarget::new(
174            OPERATOR_COMMAND_TARGET_ID.to_string(),
175            CommandTargetType::Daemon,
176        ));
177    }
178
179    let target = match requested {
180        Some(resource_id) => {
181            // Reject ids that would break the key grammar before any lookup.
182            validate_command_target_id(resource_id)?;
183            // An empty resource id is never a valid target — in particular it
184            // must NOT silently fall back to shorthand resolution.
185            let found = if resource_id.is_empty() {
186                None
187            } else {
188                targets.iter().find(|t| t.resource_id == resource_id)
189            };
190            found
191                .ok_or_else(|| {
192                    AlienError::new(ErrorData::CommandTargetNotFound {
193                        resource_id: resource_id.to_string(),
194                        deployment_id: deployment_id.to_string(),
195                    })
196                })?
197                .clone()
198        }
199        None => {
200            let mut candidates = targets
201                .iter()
202                .filter(|target| target.resource_id != OPERATOR_COMMAND_TARGET_ID);
203            let Some(single) = candidates.next() else {
204                return Err(AlienError::new(ErrorData::NoCommandTargets {
205                    deployment_id: deployment_id.to_string(),
206                }));
207            };
208            if candidates.next().is_some() {
209                return Err(AlienError::new(ErrorData::CommandTargetAmbiguous {
210                    deployment_id: deployment_id.to_string(),
211                }));
212            }
213            single.clone()
214        }
215    };
216
217    // A registered target whose id breaks the key grammar must never resolve.
218    validate_command_target_id(&target.resource_id)?;
219    Ok(target)
220}
221
222/// Pinned per-type delivery rule — the single implementation both registries
223/// route through. Container and Daemon targets are always Pull; a Worker target
224/// follows `worker_mode`, the caller's derived worker context (production: Push
225/// only when the platform has a push path AND `stack_settings.deployment_model`
226/// is Push).
227pub fn delivery_mode_for(
228    resource_type: CommandTargetType,
229    worker_mode: CommandDeliveryMode,
230) -> CommandDeliveryMode {
231    match resource_type {
232        CommandTargetType::Container | CommandTargetType::Daemon => CommandDeliveryMode::Pull,
233        CommandTargetType::Worker => worker_mode,
234    }
235}
236
237/// Abstraction for command metadata storage and lifecycle tracking.
238///
239/// The CommandRegistry is the source of truth for all command metadata.
240/// Implementations store command state, timestamps, and result information.
241#[async_trait]
242pub trait CommandRegistry: Send + Sync {
243    /// Whether this registry durably stores an operation result contract in
244    /// the same create transaction that makes a command visible.
245    fn persists_operation_result_contract(&self) -> bool {
246        false
247    }
248
249    /// Resolve which command-capable resource a command is addressed to.
250    ///
251    /// `command` is the name being invoked. Registries that know about
252    /// commands served outside the deployment stack (for example operations)
253    /// can use it to reject a name that must be invoked another way, with an
254    /// error that says how. The standalone registries ignore it.
255    ///
256    /// - `requested = Some(id)`: the target must exist and be command-capable,
257    ///   else `COMMAND_TARGET_NOT_FOUND` (an empty id never resolves).
258    /// - `requested = None` (single-target shorthand): exactly one
259    ///   command-capable target must exist, else `COMMAND_TARGET_AMBIGUOUS`
260    ///   (more than one) or `NO_COMMAND_TARGETS` (none).
261    ///
262    /// The returned delivery mode is derived from the target: Container and
263    /// Daemon targets are always Pull. Worker delivery is resolved from the
264    /// deployment model and platform: Kubernetes uses its in-cluster operator
265    /// relay, Local supports embedded Push and remote Pull, and cloud Workers
266    /// use their provider push path only for Push deployments.
267    async fn resolve_target(
268        &self,
269        deployment_id: &str,
270        command: &str,
271        requested: Option<&str>,
272    ) -> Result<ResolvedCommandTarget>;
273
274    /// Create a new command addressed to a previously resolved target and
275    /// return metadata for routing.
276    ///
277    /// The registry generates the command_id and stores all metadata
278    /// (state, target, timestamps, etc.).
279    async fn create_command(
280        &self,
281        deployment_id: &str,
282        command_name: &str,
283        target: &ResolvedCommandTarget,
284        initial_state: CommandState,
285        deadline: Option<DateTime<Utc>>,
286        request_size_bytes: Option<u64>,
287        operation_result_contract: Option<serde_json::Value>,
288    ) -> Result<CommandMetadata>;
289
290    /// Get metadata needed to build an envelope during lease acquisition.
291    ///
292    /// Returns None if command doesn't exist.
293    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>>;
294
295    /// Get full command status for status endpoint.
296    ///
297    /// Returns None if command doesn't exist.
298    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>>;
299
300    /// Get the canonical ownership fields used to authorize command reads.
301    ///
302    /// The status record is the command registry's source of truth for these
303    /// fields, so this does not require a deployment lookup.
304    async fn get_command_access_context(
305        &self,
306        command_id: &str,
307    ) -> Result<Option<CommandAccessContext>> {
308        Ok(self
309            .get_command_status(command_id)
310            .await?
311            .map(|status| CommandAccessContext {
312                workspace_id: status.workspace_id,
313                project_id: status.project_id,
314                deployment_id: status.deployment_id,
315                target: status.target,
316            }))
317    }
318
319    /// Atomically update a non-terminal command's lifecycle state.
320    ///
321    /// Returns `false` when the command became terminal before the update.
322    /// Terminal transitions use [`Self::complete_command`] instead.
323    async fn update_command_state(
324        &self,
325        command_id: &str,
326        state: CommandState,
327        dispatched_at: Option<DateTime<Utc>>,
328        completed_at: Option<DateTime<Utc>>,
329        response_size_bytes: Option<u64>,
330        error: Option<serde_json::Value>,
331    ) -> Result<bool>;
332
333    /// Atomically transition a command from any NON-terminal state to the
334    /// given terminal `state`.
335    ///
336    /// Returns `false` when the command was already terminal — a concurrent
337    /// submitter won the race — so a terminal record can never be
338    /// overwritten by a late duplicate (redelivered execution racing the
339    /// original whose lease expired).
340    async fn complete_command(
341        &self,
342        command_id: &str,
343        state: CommandState,
344        completed_at: DateTime<Utc>,
345        response_size_bytes: Option<u64>,
346        error: Option<serde_json::Value>,
347    ) -> Result<bool>;
348
349    /// Atomically mark a command Dispatched unless it is already terminal.
350    ///
351    /// Returns `false` when the command reached a terminal state in the
352    /// meantime — e.g. a lease TTL-expired, a new poller won the takeover
353    /// put, and the ORIGINAL holder's submit landed between the poller's
354    /// terminal check and this write. An unconditional write there would
355    /// flip a committed terminal state back to Dispatched.
356    async fn mark_dispatched_if_not_terminal(
357        &self,
358        command_id: &str,
359        dispatched_at: DateTime<Utc>,
360    ) -> Result<bool>;
361
362    /// Increment attempt count (on lease release/expiry).
363    ///
364    /// Returns the new attempt number.
365    async fn increment_attempt(&self, command_id: &str) -> Result<u32>;
366}
367
368/// In-memory implementation for tests and local development.
369///
370/// Tracks command metadata in memory. Targets are registered explicitly via
371/// [`register_target`](Self::register_target); resolution then follows exactly
372/// the production rules documented on [`CommandRegistry::resolve_target`].
373pub struct InMemoryCommandRegistry {
374    commands: Arc<RwLock<HashMap<String, CommandRecord>>>,
375    /// Registered command-capable targets, in registration (declaration) order.
376    ///
377    /// Not scoped per deployment: this registry models a single local
378    /// deployment universe, so every deployment id resolves against the same
379    /// target set (the per-call resolution rules are identical to production).
380    targets: Arc<RwLock<Vec<CommandTarget>>>,
381    /// Delivery mode for Worker targets.
382    ///
383    /// In production this is derived from the deployment's platform and stack
384    /// settings (Push only when the platform has a push path AND
385    /// `stack_settings.deployment_model == Push`). The registrant supplies
386    /// that derived context here once, and the registry applies the pinned
387    /// per-type rule itself — so it is impossible to register a Container or
388    /// Daemon target with a Push mode that production could never produce.
389    worker_delivery_mode: CommandDeliveryMode,
390}
391
392impl InMemoryCommandRegistry {
393    /// Create a new in-memory registry whose Worker targets use Pull delivery
394    /// (the safe default: matches platforms without a push path).
395    pub fn new() -> Self {
396        Self::with_worker_delivery_mode(CommandDeliveryMode::Pull)
397    }
398
399    /// Create a new in-memory registry with the specified Worker delivery mode.
400    ///
401    /// Container/Daemon targets are always Pull regardless of this setting.
402    pub fn with_worker_delivery_mode(worker_delivery_mode: CommandDeliveryMode) -> Self {
403        Self {
404            commands: Arc::new(RwLock::new(HashMap::new())),
405            targets: Arc::new(RwLock::new(Vec::new())),
406            worker_delivery_mode,
407        }
408    }
409
410    /// Register a command-capable target that commands can resolve to.
411    ///
412    /// Mirrors production, where the target set comes from the deployment's
413    /// stack (`Stack::command_targets()`: Worker/Container/Daemon resources
414    /// with `commands_enabled`). The id is validated through the same shared
415    /// guard as resolution, so a `:`-bearing id is rejected here at registration
416    /// rather than surfacing later as a key-grammar collision.
417    pub async fn register_target(
418        &self,
419        resource_id: impl Into<String>,
420        resource_type: CommandTargetType,
421    ) -> Result<()> {
422        let resource_id = resource_id.into();
423        validate_command_target_id(&resource_id)?;
424        self.targets
425            .write()
426            .await
427            .push(CommandTarget::new(resource_id, resource_type));
428        Ok(())
429    }
430
431    /// List all command IDs (useful for debugging/testing)
432    #[allow(dead_code)]
433    pub async fn list_command_ids(&self) -> Vec<String> {
434        let commands = self.commands.read().await;
435        commands.keys().cloned().collect()
436    }
437}
438
439impl Default for InMemoryCommandRegistry {
440    fn default() -> Self {
441        Self::new()
442    }
443}
444
445#[async_trait]
446impl CommandRegistry for InMemoryCommandRegistry {
447    async fn resolve_target(
448        &self,
449        deployment_id: &str,
450        _command: &str,
451        requested: Option<&str>,
452    ) -> Result<ResolvedCommandTarget> {
453        let targets = self.targets.read().await;
454        let target = select_command_target(deployment_id, &targets, requested)?;
455        let delivery_mode = delivery_mode_for(target.resource_type, self.worker_delivery_mode);
456        Ok(ResolvedCommandTarget {
457            target,
458            delivery_mode,
459        })
460    }
461
462    async fn create_command(
463        &self,
464        deployment_id: &str,
465        command_name: &str,
466        target: &ResolvedCommandTarget,
467        initial_state: CommandState,
468        deadline: Option<DateTime<Utc>>,
469        request_size_bytes: Option<u64>,
470        _operation_result_contract: Option<serde_json::Value>,
471    ) -> Result<CommandMetadata> {
472        let command_id = format!("cmd_{}", Uuid::new_v4());
473
474        let record = CommandRecord {
475            id: command_id.clone(),
476            deployment_id: deployment_id.to_string(),
477            command: command_name.to_string(),
478            state: initial_state,
479            attempt: 1,
480            deadline,
481            created_at: Utc::now(),
482            dispatched_at: None,
483            completed_at: None,
484            request_size_bytes,
485            response_size_bytes: None,
486            error: None,
487            target: target.target.clone(),
488            delivery_mode: target.delivery_mode,
489            project_id: "default".to_string(),
490        };
491
492        self.commands
493            .write()
494            .await
495            .insert(command_id.clone(), record);
496
497        Ok(CommandMetadata {
498            command_id,
499            target: target.target.clone(),
500            delivery_mode: target.delivery_mode,
501            project_id: "default".to_string(),
502        })
503    }
504
505    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>> {
506        let commands = self.commands.read().await;
507
508        Ok(commands.get(command_id).map(|r| CommandEnvelopeData {
509            command_id: r.id.clone(),
510            deployment_id: r.deployment_id.clone(),
511            command: r.command.clone(),
512            attempt: r.attempt,
513            deadline: r.deadline,
514            state: r.state,
515            target: r.target.clone(),
516            delivery_mode: r.delivery_mode,
517        }))
518    }
519
520    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>> {
521        let commands = self.commands.read().await;
522
523        Ok(commands.get(command_id).map(|r| CommandStatus {
524            command_id: r.id.clone(),
525            workspace_id: "default".to_string(),
526            project_id: r.project_id.clone(),
527            deployment_id: r.deployment_id.clone(),
528            command: r.command.clone(),
529            state: r.state,
530            attempt: r.attempt,
531            deadline: r.deadline,
532            created_at: r.created_at,
533            dispatched_at: r.dispatched_at,
534            completed_at: r.completed_at,
535            error: r.error.clone(),
536            request_size_bytes: r.request_size_bytes,
537            response_size_bytes: r.response_size_bytes,
538            target: r.target.clone(),
539        }))
540    }
541
542    async fn update_command_state(
543        &self,
544        command_id: &str,
545        state: CommandState,
546        dispatched_at: Option<DateTime<Utc>>,
547        completed_at: Option<DateTime<Utc>>,
548        response_size_bytes: Option<u64>,
549        error: Option<serde_json::Value>,
550    ) -> Result<bool> {
551        let mut commands = self.commands.write().await;
552
553        if let Some(record) = commands.get_mut(command_id) {
554            if record.state.is_terminal() {
555                return Ok(false);
556            }
557            record.state = state;
558
559            if let Some(ts) = dispatched_at {
560                record.dispatched_at = Some(ts);
561            }
562
563            if let Some(ts) = completed_at {
564                record.completed_at = Some(ts);
565            }
566
567            if let Some(size) = response_size_bytes {
568                record.response_size_bytes = Some(size);
569            }
570
571            if let Some(err) = error {
572                record.error = Some(err);
573            }
574            return Ok(true);
575        }
576
577        Ok(false)
578    }
579
580    async fn complete_command(
581        &self,
582        command_id: &str,
583        state: CommandState,
584        completed_at: DateTime<Utc>,
585        response_size_bytes: Option<u64>,
586        error: Option<serde_json::Value>,
587    ) -> Result<bool> {
588        let mut commands = self.commands.write().await;
589        let Some(record) = commands.get_mut(command_id) else {
590            return Ok(false);
591        };
592        if record.state.is_terminal() {
593            return Ok(false);
594        }
595        record.state = state;
596        record.completed_at = Some(completed_at);
597        if let Some(size) = response_size_bytes {
598            record.response_size_bytes = Some(size);
599        }
600        if let Some(err) = error {
601            record.error = Some(err);
602        }
603        Ok(true)
604    }
605
606    async fn mark_dispatched_if_not_terminal(
607        &self,
608        command_id: &str,
609        dispatched_at: DateTime<Utc>,
610    ) -> Result<bool> {
611        let mut commands = self.commands.write().await;
612        let Some(record) = commands.get_mut(command_id) else {
613            return Ok(false);
614        };
615        if record.state.is_terminal() {
616            return Ok(false);
617        }
618        record.state = CommandState::Dispatched;
619        record.dispatched_at = Some(dispatched_at);
620        Ok(true)
621    }
622
623    async fn increment_attempt(&self, command_id: &str) -> Result<u32> {
624        let mut commands = self.commands.write().await;
625
626        if let Some(record) = commands.get_mut(command_id) {
627            record.attempt += 1;
628            Ok(record.attempt)
629        } else {
630            Ok(1) // Default if not found
631        }
632    }
633}
634
635#[cfg(test)]
636mod tests {
637    use super::*;
638    use alien_core::{CommandDeliveryMode, CommandTarget, CommandTargetType};
639
640    async fn resolved(
641        registry: &InMemoryCommandRegistry,
642        requested: Option<&str>,
643    ) -> Result<ResolvedCommandTarget> {
644        registry
645            .resolve_target("dep-1", "test-command", requested)
646            .await
647    }
648
649    #[tokio::test]
650    async fn test_resolve_explicit_target_found() {
651        let registry = InMemoryCommandRegistry::new();
652        registry
653            .register_target("worker-a", CommandTargetType::Worker)
654            .await
655            .unwrap();
656        registry
657            .register_target("daemon-b", CommandTargetType::Daemon)
658            .await
659            .unwrap();
660
661        let result = resolved(&registry, Some("daemon-b")).await.unwrap();
662        assert_eq!(
663            result.target,
664            CommandTarget::new("daemon-b", CommandTargetType::Daemon)
665        );
666    }
667
668    #[tokio::test]
669    async fn test_resolve_explicit_unknown_target_is_not_found() {
670        let registry = InMemoryCommandRegistry::new();
671        registry
672            .register_target("worker-a", CommandTargetType::Worker)
673            .await
674            .unwrap();
675
676        let err = resolved(&registry, Some("no-such-resource"))
677            .await
678            .unwrap_err();
679        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
680        assert_eq!(err.http_status_code, Some(404));
681    }
682
683    #[tokio::test]
684    async fn test_resolve_explicit_empty_string_is_not_found() {
685        let registry = InMemoryCommandRegistry::new();
686        registry
687            .register_target("worker-a", CommandTargetType::Worker)
688            .await
689            .unwrap();
690
691        // An explicitly requested empty resource id must never resolve (in
692        // particular it must NOT fall back to shorthand resolution).
693        let err = resolved(&registry, Some("")).await.unwrap_err();
694        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
695    }
696
697    #[tokio::test]
698    async fn test_resolve_shorthand_single_target_resolves() {
699        let registry = InMemoryCommandRegistry::new();
700        registry
701            .register_target("container-1", CommandTargetType::Container)
702            .await
703            .unwrap();
704
705        let result = resolved(&registry, None).await.unwrap();
706        assert_eq!(
707            result.target,
708            CommandTarget::new("container-1", CommandTargetType::Container)
709        );
710    }
711
712    #[tokio::test]
713    async fn test_resolve_shorthand_two_targets_is_ambiguous() {
714        let registry = InMemoryCommandRegistry::new();
715        registry
716            .register_target("worker-a", CommandTargetType::Worker)
717            .await
718            .unwrap();
719        registry
720            .register_target("worker-b", CommandTargetType::Worker)
721            .await
722            .unwrap();
723
724        let err = resolved(&registry, None).await.unwrap_err();
725        assert_eq!(err.code, "COMMAND_TARGET_AMBIGUOUS");
726        assert_eq!(err.http_status_code, Some(409));
727    }
728
729    #[tokio::test]
730    async fn test_resolve_shorthand_zero_targets_is_no_targets() {
731        let registry = InMemoryCommandRegistry::new();
732
733        let err = resolved(&registry, None).await.unwrap_err();
734        assert_eq!(err.code, "NO_COMMAND_TARGETS");
735        assert_eq!(err.http_status_code, Some(422));
736    }
737
738    #[tokio::test]
739    async fn test_resolve_shorthand_operator_only_is_no_targets() {
740        let registry = InMemoryCommandRegistry::new();
741        registry
742            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
743            .await
744            .unwrap();
745
746        let err = resolved(&registry, None).await.unwrap_err();
747        assert_eq!(err.code, "NO_COMMAND_TARGETS");
748        assert_eq!(err.http_status_code, Some(422));
749    }
750
751    #[tokio::test]
752    async fn test_resolve_shorthand_ignores_operator_beside_one_stack_target() {
753        let registry = InMemoryCommandRegistry::new();
754        registry
755            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
756            .await
757            .unwrap();
758        registry
759            .register_target("daemon-1", CommandTargetType::Daemon)
760            .await
761            .unwrap();
762
763        let result = resolved(&registry, None).await.unwrap();
764        assert_eq!(
765            result.target,
766            CommandTarget::new("daemon-1", CommandTargetType::Daemon)
767        );
768    }
769
770    #[tokio::test]
771    async fn test_delivery_mode_container_and_daemon_always_pull() {
772        // Even with a Push-capable worker context, Container/Daemon are Pull.
773        let registry =
774            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
775        registry
776            .register_target("container-1", CommandTargetType::Container)
777            .await
778            .unwrap();
779        registry
780            .register_target("daemon-1", CommandTargetType::Daemon)
781            .await
782            .unwrap();
783
784        let container = resolved(&registry, Some("container-1")).await.unwrap();
785        assert_eq!(container.delivery_mode, CommandDeliveryMode::Pull);
786
787        let daemon = resolved(&registry, Some("daemon-1")).await.unwrap();
788        assert_eq!(daemon.delivery_mode, CommandDeliveryMode::Pull);
789    }
790
791    #[tokio::test]
792    async fn test_delivery_mode_worker_follows_registered_context() {
793        let push_registry =
794            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
795        push_registry
796            .register_target("worker-1", CommandTargetType::Worker)
797            .await
798            .unwrap();
799        let push_worker = push_registry
800            .resolve_target("dep-1", "test-command", Some("worker-1"))
801            .await
802            .unwrap();
803        assert_eq!(push_worker.delivery_mode, CommandDeliveryMode::Push);
804
805        // A manager-side pending path (e.g. Kubernetes operator relay, or a
806        // cloud stack whose deployment model is Pull).
807        let pull_registry =
808            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Pull);
809        pull_registry
810            .register_target("worker-1", CommandTargetType::Worker)
811            .await
812            .unwrap();
813        let pull_worker = pull_registry
814            .resolve_target("dep-1", "test-command", Some("worker-1"))
815            .await
816            .unwrap();
817        assert_eq!(pull_worker.delivery_mode, CommandDeliveryMode::Pull);
818    }
819
820    #[tokio::test]
821    async fn test_create_command_stores_target_in_status_and_envelope_data() {
822        let registry = InMemoryCommandRegistry::new();
823        registry
824            .register_target("daemon-1", CommandTargetType::Daemon)
825            .await
826            .unwrap();
827
828        let resolved_target = registry
829            .resolve_target("dep-1", "test-command", None)
830            .await
831            .unwrap();
832        let metadata = registry
833            .create_command(
834                "dep-1",
835                "sync-data",
836                &resolved_target,
837                CommandState::Pending,
838                None,
839                None,
840                None,
841            )
842            .await
843            .unwrap();
844
845        let expected = CommandTarget::new("daemon-1", CommandTargetType::Daemon);
846        assert_eq!(metadata.target, expected);
847        assert_eq!(metadata.delivery_mode, CommandDeliveryMode::Pull);
848
849        let status = registry
850            .get_command_status(&metadata.command_id)
851            .await
852            .unwrap()
853            .unwrap();
854        assert_eq!(status.target, expected);
855
856        let envelope_data = registry
857            .get_command_metadata(&metadata.command_id)
858            .await
859            .unwrap()
860            .unwrap();
861        assert_eq!(envelope_data.target, expected);
862        assert_eq!(envelope_data.delivery_mode, CommandDeliveryMode::Pull);
863    }
864
865    #[tokio::test]
866    async fn non_terminal_update_cannot_resurrect_completed_command() {
867        let registry = InMemoryCommandRegistry::new();
868        registry
869            .register_target("daemon-1", CommandTargetType::Daemon)
870            .await
871            .unwrap();
872        let target = registry
873            .resolve_target("dep-1", "test-command", None)
874            .await
875            .unwrap();
876        let command = registry
877            .create_command(
878                "dep-1",
879                "run",
880                &target,
881                CommandState::Dispatched,
882                None,
883                None,
884                None,
885            )
886            .await
887            .unwrap();
888
889        assert!(registry
890            .complete_command(
891                &command.command_id,
892                CommandState::Succeeded,
893                Utc::now(),
894                None,
895                None,
896            )
897            .await
898            .unwrap());
899        assert!(!registry
900            .update_command_state(
901                &command.command_id,
902                CommandState::Pending,
903                None,
904                None,
905                None,
906                None,
907            )
908            .await
909            .unwrap());
910        assert_eq!(
911            registry
912                .get_command_status(&command.command_id)
913                .await
914                .unwrap()
915                .unwrap()
916                .state,
917            CommandState::Succeeded
918        );
919    }
920
921    #[tokio::test]
922    async fn in_memory_command_access_uses_oss_tenant_context() {
923        let registry = InMemoryCommandRegistry::new();
924        registry
925            .register_target("worker-1", CommandTargetType::Worker)
926            .await
927            .unwrap();
928        let target = registry
929            .resolve_target("dep-1", "test-command", None)
930            .await
931            .unwrap();
932        let command = registry
933            .create_command(
934                "dep-1",
935                "run",
936                &target,
937                CommandState::Pending,
938                None,
939                None,
940                None,
941            )
942            .await
943            .unwrap();
944
945        assert_eq!(command.project_id, "default");
946        assert_eq!(
947            registry
948                .get_command_access_context(&command.command_id)
949                .await
950                .unwrap()
951                .unwrap(),
952            CommandAccessContext {
953                workspace_id: "default".to_string(),
954                project_id: "default".to_string(),
955                deployment_id: "dep-1".to_string(),
956                target: CommandTarget::new("worker-1", CommandTargetType::Worker),
957            }
958        );
959    }
960
961    #[tokio::test]
962    async fn test_register_target_rejects_colon_in_id() {
963        let registry = InMemoryCommandRegistry::new();
964        let err = registry
965            .register_target("evil:pending:x", CommandTargetType::Worker)
966            .await
967            .unwrap_err();
968        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
969        assert_eq!(err.http_status_code, Some(400));
970    }
971
972    #[tokio::test]
973    async fn test_resolve_explicit_colon_id_is_invalid() {
974        let registry = InMemoryCommandRegistry::new();
975        registry
976            .register_target("worker-a", CommandTargetType::Worker)
977            .await
978            .unwrap();
979
980        // A requested id containing ':' is rejected with a typed error before
981        // any lookup — it can never be resolved into the key grammar.
982        let err = resolved(&registry, Some("worker-a:pending:1"))
983            .await
984            .unwrap_err();
985        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
986    }
987
988    #[test]
989    fn test_select_command_target_rejects_registered_colon_id() {
990        // Even if a `:`-bearing target slips into the slice (e.g. an unvalidated
991        // upstream path), selecting it fails loudly rather than resolving.
992        let targets = vec![CommandTarget::new("a:pending:x", CommandTargetType::Worker)];
993        let err = select_command_target("dep-1", &targets, None).unwrap_err();
994        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
995    }
996
997    #[test]
998    fn operator_target_resolves_without_a_stack_resource() {
999        // The reserved operator id resolves to a pull-mode daemon target even
1000        // when no stack targets exist — operations commands address the operator
1001        // itself, which is never a stack resource.
1002        let target = select_command_target("dep-1", &[], Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
1003        assert_eq!(target.resource_id, OPERATOR_COMMAND_TARGET_ID);
1004        assert_eq!(target.resource_type, CommandTargetType::Daemon);
1005        // A daemon target always delivers via pull, regardless of worker mode.
1006        assert_eq!(
1007            delivery_mode_for(target.resource_type, CommandDeliveryMode::Push),
1008            CommandDeliveryMode::Pull
1009        );
1010    }
1011
1012    #[test]
1013    fn operator_target_is_not_shadowed_by_a_same_named_stack_resource() {
1014        // Even if a stack somehow registered a "operator" worker, the reserved id
1015        // resolves to the operator daemon (the short-circuit wins).
1016        let targets = vec![CommandTarget::new(
1017            OPERATOR_COMMAND_TARGET_ID,
1018            CommandTargetType::Worker,
1019        )];
1020        let target =
1021            select_command_target("dep-1", &targets, Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
1022        assert_eq!(target.resource_type, CommandTargetType::Daemon);
1023    }
1024}