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/// The reserved command-target id of a system-provisioned operations worker.
149///
150/// Unlike [`OPERATOR_COMMAND_TARGET_ID`], this is a real Worker in the
151/// deployment's stack, so it resolves like any other stack target and uses the
152/// Worker's push delivery. It runs operations, so the same access rules as the
153/// operator apply: only an operations capability may address it, and
154/// single-target shorthand never selects it.
155pub const OPERATIONS_WORKER_COMMAND_TARGET_ID: &str = "operations-worker";
156
157/// Whether `resource_id` names a reserved target that runs operations.
158pub fn is_operations_command_target(resource_id: &str) -> bool {
159    resource_id == OPERATOR_COMMAND_TARGET_ID || resource_id == OPERATIONS_WORKER_COMMAND_TARGET_ID
160}
161
162/// Whether `target` is a reserved operations target with its expected type:
163/// the operator is always a daemon, the operations worker always a Worker.
164pub fn is_operations_target(target: &CommandTarget) -> bool {
165    (target.resource_id == OPERATOR_COMMAND_TARGET_ID
166        && target.resource_type == CommandTargetType::Daemon)
167        || (target.resource_id == OPERATIONS_WORKER_COMMAND_TARGET_ID
168            && target.resource_type == CommandTargetType::Worker)
169}
170
171/// Target-selection rules shared by both the
172/// in-memory and SQLite registries route through.
173///
174/// - `requested = Some(id)`: the id must be well-formed (no `:`) and name an
175///   existing command-capable target, else `COMMAND_TARGET_NOT_FOUND`. An empty
176///   id never falls back to shorthand. The reserved
177///   [`OPERATOR_COMMAND_TARGET_ID`] always resolves to a pull-mode daemon
178///   target for the operator, independent of the stack.
179/// - `requested = None` (single-target shorthand): exactly one non-reserved
180///   stack target must exist, else `COMMAND_TARGET_AMBIGUOUS` (more than one)
181///   or `NO_COMMAND_TARGETS` (none). Reserved operations targets (see
182///   [`is_operations_command_target`]) are excluded so shorthand can never
183///   address them.
184///
185/// The resolved target's own id is also validated, so a target registered with
186/// a `:`-bearing id can never resolve into the key grammar.
187pub fn select_command_target(
188    deployment_id: &str,
189    targets: &[CommandTarget],
190    requested: Option<&str>,
191) -> Result<CommandTarget> {
192    // The operator is a reserved target, not a stack resource — resolve it
193    // directly so operations commands can be addressed to the operator without
194    // it having to appear in the deployment's command-capable stack targets.
195    if requested == Some(OPERATOR_COMMAND_TARGET_ID) {
196        return Ok(CommandTarget::new(
197            OPERATOR_COMMAND_TARGET_ID.to_string(),
198            CommandTargetType::Daemon,
199        ));
200    }
201
202    let target = match requested {
203        Some(resource_id) => {
204            // Reject ids that would break the key grammar before any lookup.
205            validate_command_target_id(resource_id)?;
206            // An empty resource id is never a valid target — in particular it
207            // must NOT silently fall back to shorthand resolution.
208            let found = if resource_id.is_empty() {
209                None
210            } else {
211                targets.iter().find(|t| t.resource_id == resource_id)
212            };
213            found
214                .ok_or_else(|| {
215                    AlienError::new(ErrorData::CommandTargetNotFound {
216                        resource_id: resource_id.to_string(),
217                        deployment_id: deployment_id.to_string(),
218                    })
219                })?
220                .clone()
221        }
222        None => {
223            let candidates: Vec<&CommandTarget> = targets
224                .iter()
225                .filter(|target| !is_operations_command_target(&target.resource_id))
226                .collect();
227            match candidates.as_slice() {
228                [] => {
229                    return Err(AlienError::new(ErrorData::NoCommandTargets {
230                        deployment_id: deployment_id.to_string(),
231                    }));
232                }
233                [single] => (*single).clone(),
234                several => {
235                    // List only targets shorthand could pick, so the error never
236                    // suggests a reserved operations target the caller can't use.
237                    let mut target_resource_ids: Vec<String> = several
238                        .iter()
239                        .map(|target| target.resource_id.clone())
240                        .collect();
241                    target_resource_ids.sort();
242                    return Err(AlienError::new(ErrorData::CommandTargetAmbiguous {
243                        deployment_id: deployment_id.to_string(),
244                        target_resource_ids,
245                    }));
246                }
247            }
248        }
249    };
250
251    // A registered target whose id breaks the key grammar must never resolve.
252    validate_command_target_id(&target.resource_id)?;
253    Ok(target)
254}
255
256/// Pinned per-type delivery rule — the single implementation both registries
257/// route through. Container and Daemon targets are always Pull; a Worker target
258/// follows `worker_mode`, the caller's derived worker context (production: Push
259/// only when the platform has a push path AND `stack_settings.deployment_model`
260/// is Push).
261pub fn delivery_mode_for(
262    resource_type: CommandTargetType,
263    worker_mode: CommandDeliveryMode,
264) -> CommandDeliveryMode {
265    match resource_type {
266        CommandTargetType::Container | CommandTargetType::Daemon => CommandDeliveryMode::Pull,
267        CommandTargetType::Worker => worker_mode,
268    }
269}
270
271/// Abstraction for command metadata storage and lifecycle tracking.
272///
273/// The CommandRegistry is the source of truth for all command metadata.
274/// Implementations store command state, timestamps, and result information.
275#[async_trait]
276pub trait CommandRegistry: Send + Sync {
277    /// Whether this registry durably stores an operation result contract in
278    /// the same create transaction that makes a command visible.
279    fn persists_operation_result_contract(&self) -> bool {
280        false
281    }
282
283    /// Resolve which command-capable resource a command is addressed to.
284    ///
285    /// `command` is the name being invoked. Registries that know about
286    /// commands served outside the deployment stack (for example operations)
287    /// can use it to reject a name that must be invoked another way, with an
288    /// error that says how. The standalone registries ignore it.
289    ///
290    /// - `requested = Some(id)`: the target must exist and be command-capable,
291    ///   else `COMMAND_TARGET_NOT_FOUND` (an empty id never resolves).
292    /// - `requested = None` (single-target shorthand): exactly one
293    ///   command-capable target must exist, else `COMMAND_TARGET_AMBIGUOUS`
294    ///   (more than one) or `NO_COMMAND_TARGETS` (none).
295    ///
296    /// The returned delivery mode is derived from the target: Container and
297    /// Daemon targets are always Pull. Worker delivery is resolved from the
298    /// deployment model and platform: Kubernetes uses its in-cluster operator
299    /// relay, Local supports embedded Push and remote Pull, and cloud Workers
300    /// use their provider push path only for Push deployments.
301    async fn resolve_target(
302        &self,
303        deployment_id: &str,
304        command: &str,
305        requested: Option<&str>,
306    ) -> Result<ResolvedCommandTarget>;
307
308    /// Create a new command addressed to a previously resolved target and
309    /// return metadata for routing.
310    ///
311    /// The registry generates the command_id and stores all metadata
312    /// (state, target, timestamps, etc.).
313    async fn create_command(
314        &self,
315        deployment_id: &str,
316        command_name: &str,
317        target: &ResolvedCommandTarget,
318        initial_state: CommandState,
319        deadline: Option<DateTime<Utc>>,
320        request_size_bytes: Option<u64>,
321        operation_result_contract: Option<serde_json::Value>,
322    ) -> Result<CommandMetadata>;
323
324    /// Get metadata needed to build an envelope during lease acquisition.
325    ///
326    /// Returns None if command doesn't exist.
327    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>>;
328
329    /// Get full command status for status endpoint.
330    ///
331    /// Returns None if command doesn't exist.
332    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>>;
333
334    /// Get the canonical ownership fields used to authorize command reads.
335    ///
336    /// The status record is the command registry's source of truth for these
337    /// fields, so this does not require a deployment lookup.
338    async fn get_command_access_context(
339        &self,
340        command_id: &str,
341    ) -> Result<Option<CommandAccessContext>> {
342        Ok(self
343            .get_command_status(command_id)
344            .await?
345            .map(|status| CommandAccessContext {
346                workspace_id: status.workspace_id,
347                project_id: status.project_id,
348                deployment_id: status.deployment_id,
349                target: status.target,
350            }))
351    }
352
353    /// Atomically update a non-terminal command's lifecycle state.
354    ///
355    /// Returns `false` when the command became terminal before the update.
356    /// Terminal transitions use [`Self::complete_command`] instead.
357    async fn update_command_state(
358        &self,
359        command_id: &str,
360        state: CommandState,
361        dispatched_at: Option<DateTime<Utc>>,
362        completed_at: Option<DateTime<Utc>>,
363        response_size_bytes: Option<u64>,
364        error: Option<serde_json::Value>,
365    ) -> Result<bool>;
366
367    /// Atomically transition a command from any NON-terminal state to the
368    /// given terminal `state`.
369    ///
370    /// Returns `false` when the command was already terminal — a concurrent
371    /// submitter won the race — so a terminal record can never be
372    /// overwritten by a late duplicate (redelivered execution racing the
373    /// original whose lease expired).
374    async fn complete_command(
375        &self,
376        command_id: &str,
377        state: CommandState,
378        completed_at: DateTime<Utc>,
379        response_size_bytes: Option<u64>,
380        error: Option<serde_json::Value>,
381    ) -> Result<bool>;
382
383    /// Atomically mark a command Dispatched unless it is already terminal.
384    ///
385    /// Returns `false` when the command reached a terminal state in the
386    /// meantime — e.g. a lease TTL-expired, a new poller won the takeover
387    /// put, and the ORIGINAL holder's submit landed between the poller's
388    /// terminal check and this write. An unconditional write there would
389    /// flip a committed terminal state back to Dispatched.
390    async fn mark_dispatched_if_not_terminal(
391        &self,
392        command_id: &str,
393        dispatched_at: DateTime<Utc>,
394    ) -> Result<bool>;
395
396    /// Increment attempt count (on lease release/expiry).
397    ///
398    /// Returns the new attempt number.
399    async fn increment_attempt(&self, command_id: &str) -> Result<u32>;
400}
401
402/// In-memory implementation for tests and local development.
403///
404/// Tracks command metadata in memory. Targets are registered explicitly via
405/// [`register_target`](Self::register_target); resolution then follows exactly
406/// the production rules documented on [`CommandRegistry::resolve_target`].
407pub struct InMemoryCommandRegistry {
408    commands: Arc<RwLock<HashMap<String, CommandRecord>>>,
409    /// Registered command-capable targets, in registration (declaration) order.
410    ///
411    /// Not scoped per deployment: this registry models a single local
412    /// deployment universe, so every deployment id resolves against the same
413    /// target set (the per-call resolution rules are identical to production).
414    targets: Arc<RwLock<Vec<CommandTarget>>>,
415    /// Delivery mode for Worker targets.
416    ///
417    /// In production this is derived from the deployment's platform and stack
418    /// settings (Push only when the platform has a push path AND
419    /// `stack_settings.deployment_model == Push`). The registrant supplies
420    /// that derived context here once, and the registry applies the pinned
421    /// per-type rule itself — so it is impossible to register a Container or
422    /// Daemon target with a Push mode that production could never produce.
423    worker_delivery_mode: CommandDeliveryMode,
424}
425
426impl InMemoryCommandRegistry {
427    /// Create a new in-memory registry whose Worker targets use Pull delivery
428    /// (the safe default: matches platforms without a push path).
429    pub fn new() -> Self {
430        Self::with_worker_delivery_mode(CommandDeliveryMode::Pull)
431    }
432
433    /// Create a new in-memory registry with the specified Worker delivery mode.
434    ///
435    /// Container/Daemon targets are always Pull regardless of this setting.
436    pub fn with_worker_delivery_mode(worker_delivery_mode: CommandDeliveryMode) -> Self {
437        Self {
438            commands: Arc::new(RwLock::new(HashMap::new())),
439            targets: Arc::new(RwLock::new(Vec::new())),
440            worker_delivery_mode,
441        }
442    }
443
444    /// Register a command-capable target that commands can resolve to.
445    ///
446    /// Mirrors production, where the target set comes from the deployment's
447    /// stack (`Stack::command_targets()`: Worker/Container/Daemon resources
448    /// with `commands_enabled`). The id is validated through the same shared
449    /// guard as resolution, so a `:`-bearing id is rejected here at registration
450    /// rather than surfacing later as a key-grammar collision.
451    pub async fn register_target(
452        &self,
453        resource_id: impl Into<String>,
454        resource_type: CommandTargetType,
455    ) -> Result<()> {
456        let resource_id = resource_id.into();
457        validate_command_target_id(&resource_id)?;
458        self.targets
459            .write()
460            .await
461            .push(CommandTarget::new(resource_id, resource_type));
462        Ok(())
463    }
464
465    /// List all command IDs (useful for debugging/testing)
466    #[allow(dead_code)]
467    pub async fn list_command_ids(&self) -> Vec<String> {
468        let commands = self.commands.read().await;
469        commands.keys().cloned().collect()
470    }
471}
472
473impl Default for InMemoryCommandRegistry {
474    fn default() -> Self {
475        Self::new()
476    }
477}
478
479#[async_trait]
480impl CommandRegistry for InMemoryCommandRegistry {
481    async fn resolve_target(
482        &self,
483        deployment_id: &str,
484        _command: &str,
485        requested: Option<&str>,
486    ) -> Result<ResolvedCommandTarget> {
487        let targets = self.targets.read().await;
488        let target = select_command_target(deployment_id, &targets, requested)?;
489        let delivery_mode = delivery_mode_for(target.resource_type, self.worker_delivery_mode);
490        Ok(ResolvedCommandTarget {
491            target,
492            delivery_mode,
493        })
494    }
495
496    async fn create_command(
497        &self,
498        deployment_id: &str,
499        command_name: &str,
500        target: &ResolvedCommandTarget,
501        initial_state: CommandState,
502        deadline: Option<DateTime<Utc>>,
503        request_size_bytes: Option<u64>,
504        _operation_result_contract: Option<serde_json::Value>,
505    ) -> Result<CommandMetadata> {
506        let command_id = format!("cmd_{}", Uuid::new_v4());
507
508        let record = CommandRecord {
509            id: command_id.clone(),
510            deployment_id: deployment_id.to_string(),
511            command: command_name.to_string(),
512            state: initial_state,
513            attempt: 1,
514            deadline,
515            created_at: Utc::now(),
516            dispatched_at: None,
517            completed_at: None,
518            request_size_bytes,
519            response_size_bytes: None,
520            error: None,
521            target: target.target.clone(),
522            delivery_mode: target.delivery_mode,
523            project_id: "default".to_string(),
524        };
525
526        self.commands
527            .write()
528            .await
529            .insert(command_id.clone(), record);
530
531        Ok(CommandMetadata {
532            command_id,
533            target: target.target.clone(),
534            delivery_mode: target.delivery_mode,
535            project_id: "default".to_string(),
536        })
537    }
538
539    async fn get_command_metadata(&self, command_id: &str) -> Result<Option<CommandEnvelopeData>> {
540        let commands = self.commands.read().await;
541
542        Ok(commands.get(command_id).map(|r| CommandEnvelopeData {
543            command_id: r.id.clone(),
544            deployment_id: r.deployment_id.clone(),
545            command: r.command.clone(),
546            attempt: r.attempt,
547            deadline: r.deadline,
548            state: r.state,
549            target: r.target.clone(),
550            delivery_mode: r.delivery_mode,
551        }))
552    }
553
554    async fn get_command_status(&self, command_id: &str) -> Result<Option<CommandStatus>> {
555        let commands = self.commands.read().await;
556
557        Ok(commands.get(command_id).map(|r| CommandStatus {
558            command_id: r.id.clone(),
559            workspace_id: "default".to_string(),
560            project_id: r.project_id.clone(),
561            deployment_id: r.deployment_id.clone(),
562            command: r.command.clone(),
563            state: r.state,
564            attempt: r.attempt,
565            deadline: r.deadline,
566            created_at: r.created_at,
567            dispatched_at: r.dispatched_at,
568            completed_at: r.completed_at,
569            error: r.error.clone(),
570            request_size_bytes: r.request_size_bytes,
571            response_size_bytes: r.response_size_bytes,
572            target: r.target.clone(),
573        }))
574    }
575
576    async fn update_command_state(
577        &self,
578        command_id: &str,
579        state: CommandState,
580        dispatched_at: Option<DateTime<Utc>>,
581        completed_at: Option<DateTime<Utc>>,
582        response_size_bytes: Option<u64>,
583        error: Option<serde_json::Value>,
584    ) -> Result<bool> {
585        let mut commands = self.commands.write().await;
586
587        if let Some(record) = commands.get_mut(command_id) {
588            if record.state.is_terminal() {
589                return Ok(false);
590            }
591            record.state = state;
592
593            if let Some(ts) = dispatched_at {
594                record.dispatched_at = Some(ts);
595            }
596
597            if let Some(ts) = completed_at {
598                record.completed_at = Some(ts);
599            }
600
601            if let Some(size) = response_size_bytes {
602                record.response_size_bytes = Some(size);
603            }
604
605            if let Some(err) = error {
606                record.error = Some(err);
607            }
608            return Ok(true);
609        }
610
611        Ok(false)
612    }
613
614    async fn complete_command(
615        &self,
616        command_id: &str,
617        state: CommandState,
618        completed_at: DateTime<Utc>,
619        response_size_bytes: Option<u64>,
620        error: Option<serde_json::Value>,
621    ) -> Result<bool> {
622        let mut commands = self.commands.write().await;
623        let Some(record) = commands.get_mut(command_id) else {
624            return Ok(false);
625        };
626        if record.state.is_terminal() {
627            return Ok(false);
628        }
629        record.state = state;
630        record.completed_at = Some(completed_at);
631        if let Some(size) = response_size_bytes {
632            record.response_size_bytes = Some(size);
633        }
634        if let Some(err) = error {
635            record.error = Some(err);
636        }
637        Ok(true)
638    }
639
640    async fn mark_dispatched_if_not_terminal(
641        &self,
642        command_id: &str,
643        dispatched_at: DateTime<Utc>,
644    ) -> Result<bool> {
645        let mut commands = self.commands.write().await;
646        let Some(record) = commands.get_mut(command_id) else {
647            return Ok(false);
648        };
649        if record.state.is_terminal() {
650            return Ok(false);
651        }
652        record.state = CommandState::Dispatched;
653        record.dispatched_at = Some(dispatched_at);
654        Ok(true)
655    }
656
657    async fn increment_attempt(&self, command_id: &str) -> Result<u32> {
658        let mut commands = self.commands.write().await;
659
660        if let Some(record) = commands.get_mut(command_id) {
661            record.attempt += 1;
662            Ok(record.attempt)
663        } else {
664            Ok(1) // Default if not found
665        }
666    }
667}
668
669#[cfg(test)]
670mod tests {
671    use super::*;
672    use alien_core::{CommandDeliveryMode, CommandTarget, CommandTargetType};
673
674    async fn resolved(
675        registry: &InMemoryCommandRegistry,
676        requested: Option<&str>,
677    ) -> Result<ResolvedCommandTarget> {
678        registry
679            .resolve_target("dep-1", "test-command", requested)
680            .await
681    }
682
683    #[tokio::test]
684    async fn test_resolve_explicit_target_found() {
685        let registry = InMemoryCommandRegistry::new();
686        registry
687            .register_target("worker-a", CommandTargetType::Worker)
688            .await
689            .unwrap();
690        registry
691            .register_target("daemon-b", CommandTargetType::Daemon)
692            .await
693            .unwrap();
694
695        let result = resolved(&registry, Some("daemon-b")).await.unwrap();
696        assert_eq!(
697            result.target,
698            CommandTarget::new("daemon-b", CommandTargetType::Daemon)
699        );
700    }
701
702    #[tokio::test]
703    async fn test_resolve_explicit_unknown_target_is_not_found() {
704        let registry = InMemoryCommandRegistry::new();
705        registry
706            .register_target("worker-a", CommandTargetType::Worker)
707            .await
708            .unwrap();
709
710        let err = resolved(&registry, Some("no-such-resource"))
711            .await
712            .unwrap_err();
713        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
714        assert_eq!(err.http_status_code, Some(404));
715    }
716
717    #[tokio::test]
718    async fn test_resolve_explicit_empty_string_is_not_found() {
719        let registry = InMemoryCommandRegistry::new();
720        registry
721            .register_target("worker-a", CommandTargetType::Worker)
722            .await
723            .unwrap();
724
725        // An explicitly requested empty resource id must never resolve (in
726        // particular it must NOT fall back to shorthand resolution).
727        let err = resolved(&registry, Some("")).await.unwrap_err();
728        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
729    }
730
731    #[tokio::test]
732    async fn test_resolve_shorthand_single_target_resolves() {
733        let registry = InMemoryCommandRegistry::new();
734        registry
735            .register_target("container-1", CommandTargetType::Container)
736            .await
737            .unwrap();
738
739        let result = resolved(&registry, None).await.unwrap();
740        assert_eq!(
741            result.target,
742            CommandTarget::new("container-1", CommandTargetType::Container)
743        );
744    }
745
746    #[tokio::test]
747    async fn test_resolve_shorthand_two_targets_is_ambiguous() {
748        let registry = InMemoryCommandRegistry::new();
749        // Registered out of order, beside both reserved operations targets, so
750        // the error must sort the ids and leave the reserved ones out.
751        registry
752            .register_target("worker-b", CommandTargetType::Worker)
753            .await
754            .unwrap();
755        registry
756            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
757            .await
758            .unwrap();
759        registry
760            .register_target(
761                OPERATIONS_WORKER_COMMAND_TARGET_ID,
762                CommandTargetType::Worker,
763            )
764            .await
765            .unwrap();
766        registry
767            .register_target("worker-a", CommandTargetType::Worker)
768            .await
769            .unwrap();
770
771        let err = resolved(&registry, None).await.unwrap_err();
772        assert_eq!(err.code, "COMMAND_TARGET_AMBIGUOUS");
773        assert_eq!(err.http_status_code, Some(409));
774        assert_eq!(
775            err.context
776                .as_ref()
777                .and_then(|context| context.get("target_resource_ids")),
778            Some(&serde_json::json!(["worker-a", "worker-b"])),
779            "the error must name every target the caller can choose: {err:?}"
780        );
781        assert!(
782            err.message.contains(r#"["worker-a", "worker-b"]"#),
783            "the message must list the targets: {}",
784            err.message
785        );
786    }
787
788    #[tokio::test]
789    async fn test_resolve_shorthand_zero_targets_is_no_targets() {
790        let registry = InMemoryCommandRegistry::new();
791
792        let err = resolved(&registry, None).await.unwrap_err();
793        assert_eq!(err.code, "NO_COMMAND_TARGETS");
794        assert_eq!(err.http_status_code, Some(422));
795    }
796
797    #[tokio::test]
798    async fn test_resolve_shorthand_operator_only_is_no_targets() {
799        let registry = InMemoryCommandRegistry::new();
800        registry
801            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
802            .await
803            .unwrap();
804
805        let err = resolved(&registry, None).await.unwrap_err();
806        assert_eq!(err.code, "NO_COMMAND_TARGETS");
807        assert_eq!(err.http_status_code, Some(422));
808    }
809
810    #[tokio::test]
811    async fn test_resolve_shorthand_ignores_operator_beside_one_stack_target() {
812        let registry = InMemoryCommandRegistry::new();
813        registry
814            .register_target(OPERATOR_COMMAND_TARGET_ID, CommandTargetType::Daemon)
815            .await
816            .unwrap();
817        registry
818            .register_target("daemon-1", CommandTargetType::Daemon)
819            .await
820            .unwrap();
821
822        let result = resolved(&registry, None).await.unwrap();
823        assert_eq!(
824            result.target,
825            CommandTarget::new("daemon-1", CommandTargetType::Daemon)
826        );
827    }
828
829    #[tokio::test]
830    async fn test_delivery_mode_container_and_daemon_always_pull() {
831        // Even with a Push-capable worker context, Container/Daemon are Pull.
832        let registry =
833            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
834        registry
835            .register_target("container-1", CommandTargetType::Container)
836            .await
837            .unwrap();
838        registry
839            .register_target("daemon-1", CommandTargetType::Daemon)
840            .await
841            .unwrap();
842
843        let container = resolved(&registry, Some("container-1")).await.unwrap();
844        assert_eq!(container.delivery_mode, CommandDeliveryMode::Pull);
845
846        let daemon = resolved(&registry, Some("daemon-1")).await.unwrap();
847        assert_eq!(daemon.delivery_mode, CommandDeliveryMode::Pull);
848    }
849
850    #[tokio::test]
851    async fn test_delivery_mode_worker_follows_registered_context() {
852        let push_registry =
853            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Push);
854        push_registry
855            .register_target("worker-1", CommandTargetType::Worker)
856            .await
857            .unwrap();
858        let push_worker = push_registry
859            .resolve_target("dep-1", "test-command", Some("worker-1"))
860            .await
861            .unwrap();
862        assert_eq!(push_worker.delivery_mode, CommandDeliveryMode::Push);
863
864        // A manager-side pending path (e.g. Kubernetes operator relay, or a
865        // cloud stack whose deployment model is Pull).
866        let pull_registry =
867            InMemoryCommandRegistry::with_worker_delivery_mode(CommandDeliveryMode::Pull);
868        pull_registry
869            .register_target("worker-1", CommandTargetType::Worker)
870            .await
871            .unwrap();
872        let pull_worker = pull_registry
873            .resolve_target("dep-1", "test-command", Some("worker-1"))
874            .await
875            .unwrap();
876        assert_eq!(pull_worker.delivery_mode, CommandDeliveryMode::Pull);
877    }
878
879    #[tokio::test]
880    async fn test_create_command_stores_target_in_status_and_envelope_data() {
881        let registry = InMemoryCommandRegistry::new();
882        registry
883            .register_target("daemon-1", CommandTargetType::Daemon)
884            .await
885            .unwrap();
886
887        let resolved_target = registry
888            .resolve_target("dep-1", "test-command", None)
889            .await
890            .unwrap();
891        let metadata = registry
892            .create_command(
893                "dep-1",
894                "sync-data",
895                &resolved_target,
896                CommandState::Pending,
897                None,
898                None,
899                None,
900            )
901            .await
902            .unwrap();
903
904        let expected = CommandTarget::new("daemon-1", CommandTargetType::Daemon);
905        assert_eq!(metadata.target, expected);
906        assert_eq!(metadata.delivery_mode, CommandDeliveryMode::Pull);
907
908        let status = registry
909            .get_command_status(&metadata.command_id)
910            .await
911            .unwrap()
912            .unwrap();
913        assert_eq!(status.target, expected);
914
915        let envelope_data = registry
916            .get_command_metadata(&metadata.command_id)
917            .await
918            .unwrap()
919            .unwrap();
920        assert_eq!(envelope_data.target, expected);
921        assert_eq!(envelope_data.delivery_mode, CommandDeliveryMode::Pull);
922    }
923
924    #[tokio::test]
925    async fn non_terminal_update_cannot_resurrect_completed_command() {
926        let registry = InMemoryCommandRegistry::new();
927        registry
928            .register_target("daemon-1", CommandTargetType::Daemon)
929            .await
930            .unwrap();
931        let target = registry
932            .resolve_target("dep-1", "test-command", None)
933            .await
934            .unwrap();
935        let command = registry
936            .create_command(
937                "dep-1",
938                "run",
939                &target,
940                CommandState::Dispatched,
941                None,
942                None,
943                None,
944            )
945            .await
946            .unwrap();
947
948        assert!(registry
949            .complete_command(
950                &command.command_id,
951                CommandState::Succeeded,
952                Utc::now(),
953                None,
954                None,
955            )
956            .await
957            .unwrap());
958        assert!(!registry
959            .update_command_state(
960                &command.command_id,
961                CommandState::Pending,
962                None,
963                None,
964                None,
965                None,
966            )
967            .await
968            .unwrap());
969        assert_eq!(
970            registry
971                .get_command_status(&command.command_id)
972                .await
973                .unwrap()
974                .unwrap()
975                .state,
976            CommandState::Succeeded
977        );
978    }
979
980    #[tokio::test]
981    async fn in_memory_command_access_uses_oss_tenant_context() {
982        let registry = InMemoryCommandRegistry::new();
983        registry
984            .register_target("worker-1", CommandTargetType::Worker)
985            .await
986            .unwrap();
987        let target = registry
988            .resolve_target("dep-1", "test-command", None)
989            .await
990            .unwrap();
991        let command = registry
992            .create_command(
993                "dep-1",
994                "run",
995                &target,
996                CommandState::Pending,
997                None,
998                None,
999                None,
1000            )
1001            .await
1002            .unwrap();
1003
1004        assert_eq!(command.project_id, "default");
1005        assert_eq!(
1006            registry
1007                .get_command_access_context(&command.command_id)
1008                .await
1009                .unwrap()
1010                .unwrap(),
1011            CommandAccessContext {
1012                workspace_id: "default".to_string(),
1013                project_id: "default".to_string(),
1014                deployment_id: "dep-1".to_string(),
1015                target: CommandTarget::new("worker-1", CommandTargetType::Worker),
1016            }
1017        );
1018    }
1019
1020    #[tokio::test]
1021    async fn test_register_target_rejects_colon_in_id() {
1022        let registry = InMemoryCommandRegistry::new();
1023        let err = registry
1024            .register_target("evil:pending:x", CommandTargetType::Worker)
1025            .await
1026            .unwrap_err();
1027        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
1028        assert_eq!(err.http_status_code, Some(400));
1029    }
1030
1031    #[tokio::test]
1032    async fn test_resolve_explicit_colon_id_is_invalid() {
1033        let registry = InMemoryCommandRegistry::new();
1034        registry
1035            .register_target("worker-a", CommandTargetType::Worker)
1036            .await
1037            .unwrap();
1038
1039        // A requested id containing ':' is rejected with a typed error before
1040        // any lookup — it can never be resolved into the key grammar.
1041        let err = resolved(&registry, Some("worker-a:pending:1"))
1042            .await
1043            .unwrap_err();
1044        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
1045    }
1046
1047    #[test]
1048    fn test_select_command_target_rejects_registered_colon_id() {
1049        // Even if a `:`-bearing target slips into the slice (e.g. an unvalidated
1050        // upstream path), selecting it fails loudly rather than resolving.
1051        let targets = vec![CommandTarget::new("a:pending:x", CommandTargetType::Worker)];
1052        let err = select_command_target("dep-1", &targets, None).unwrap_err();
1053        assert_eq!(err.code, "COMMAND_TARGET_ID_INVALID");
1054    }
1055
1056    #[test]
1057    fn operator_target_resolves_without_a_stack_resource() {
1058        // The reserved operator id resolves to a pull-mode daemon target even
1059        // when no stack targets exist — operations commands address the operator
1060        // itself, which is never a stack resource.
1061        let target = select_command_target("dep-1", &[], Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
1062        assert_eq!(target.resource_id, OPERATOR_COMMAND_TARGET_ID);
1063        assert_eq!(target.resource_type, CommandTargetType::Daemon);
1064        // A daemon target always delivers via pull, regardless of worker mode.
1065        assert_eq!(
1066            delivery_mode_for(target.resource_type, CommandDeliveryMode::Push),
1067            CommandDeliveryMode::Pull
1068        );
1069    }
1070
1071    #[test]
1072    fn operations_worker_resolves_from_the_stack_as_a_push_worker() {
1073        let targets = vec![CommandTarget::new(
1074            OPERATIONS_WORKER_COMMAND_TARGET_ID,
1075            CommandTargetType::Worker,
1076        )];
1077        let target =
1078            select_command_target("dep-1", &targets, Some(OPERATIONS_WORKER_COMMAND_TARGET_ID))
1079                .unwrap();
1080        assert!(is_operations_target(&target));
1081        assert_eq!(
1082            delivery_mode_for(target.resource_type, CommandDeliveryMode::Push),
1083            CommandDeliveryMode::Push
1084        );
1085
1086        // Without the worker in the stack, addressing it fails like any
1087        // missing target instead of resolving to something else.
1088        let err = select_command_target("dep-1", &[], Some(OPERATIONS_WORKER_COMMAND_TARGET_ID))
1089            .unwrap_err();
1090        assert_eq!(err.code, "COMMAND_TARGET_NOT_FOUND");
1091    }
1092
1093    #[test]
1094    fn shorthand_never_selects_the_operations_worker() {
1095        let only_worker = vec![CommandTarget::new(
1096            OPERATIONS_WORKER_COMMAND_TARGET_ID,
1097            CommandTargetType::Worker,
1098        )];
1099        let err = select_command_target("dep-1", &only_worker, None).unwrap_err();
1100        assert_eq!(err.code, "NO_COMMAND_TARGETS");
1101
1102        let with_app = vec![
1103            CommandTarget::new(
1104                OPERATIONS_WORKER_COMMAND_TARGET_ID,
1105                CommandTargetType::Worker,
1106            ),
1107            CommandTarget::new("api", CommandTargetType::Worker),
1108        ];
1109        let target = select_command_target("dep-1", &with_app, None).unwrap();
1110        assert_eq!(target.resource_id, "api");
1111    }
1112
1113    #[test]
1114    fn operator_target_is_not_shadowed_by_a_same_named_stack_resource() {
1115        // Even if a stack somehow registered a "operator" worker, the reserved id
1116        // resolves to the operator daemon (the short-circuit wins).
1117        let targets = vec![CommandTarget::new(
1118            OPERATOR_COMMAND_TARGET_ID,
1119            CommandTargetType::Worker,
1120        )];
1121        let target =
1122            select_command_target("dep-1", &targets, Some(OPERATOR_COMMAND_TARGET_ID)).unwrap();
1123        assert_eq!(target.resource_type, CommandTargetType::Daemon);
1124    }
1125}