Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions crates/openshell-sdk/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,43 @@ impl OpenShellClient {
})
}

/// Stream the current sandbox status and subsequent snapshots in the default workspace.
///
/// Snapshots can skip intermediate states and have no replay cursor. Drop the
/// stream to stop watching. After a stream error, start a new watch to receive
/// the current snapshot.
pub fn watch_sandbox_status(&self, name: &str) -> impl Stream<Item = Result<SandboxRef>> + '_ {
self.watch_sandbox_status_in("default", name)
}

fn watch_sandbox_status_in(
&self,
workspace: &str,
name: &str,
) -> impl Stream<Item = Result<SandboxRef>> + use<'_> {
let request = proto::WatchSandboxRequest {
sandbox: name.to_string(),
workspace_scope: Some(proto::workspace_selector(workspace)),
follow_status: true,
..Default::default()
};
async_stream::try_stream! {
let mut stream = self
.unary(|mut grpc| {
let request = request.clone();
async move { grpc.watch_sandbox(request).await }
})
.await?;
while let Some(item) = stream.next().await {
if let Some(proto::sandbox_stream_event::Payload::Sandbox(sandbox)) =
item.map_err(map_status)?.payload
{
yield SandboxRef::from_proto(sandbox);
}
}
}
}

/// Watch a sandbox's logs and platform events with loss-aware resume.
///
/// Reconnects transparently on transient stream errors, resuming from the
Expand Down Expand Up @@ -1752,6 +1789,13 @@ impl WorkspaceScopedClient {
})
}

/// Stream status snapshots in this workspace.
///
/// See [`OpenShellClient::watch_sandbox_status`] for stream behavior.
pub fn watch_sandbox_status(&self, name: &str) -> impl Stream<Item = Result<SandboxRef>> + '_ {
self.client.watch_sandbox_status_in(&self.workspace, name)
}

/// Watch a sandbox's logs and platform events with loss-aware resume.
///
/// Reconnects transparently on transient stream errors, resuming from the
Expand Down
12 changes: 6 additions & 6 deletions crates/openshell-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,10 @@ pub use pagination::{Page, Pager};
pub use refresh::{Refresh, RefreshError, RefreshedToken, TokenSource};
pub use types::{
CreateRetryOptions, DeleteOptions, DeletionOutcome, DeletionResult, ExecOptions, ExecResult,
Health, ListOptions, LogLine, PlatformEvent, ResumeOptions, SandboxPhase, SandboxRef,
SandboxResources, SandboxRestartPolicy, SandboxServiceLevel, SandboxSpec, SandboxStartup,
SandboxTemplateCreateSpec, SandboxTemplateListOptions, SandboxWorkloadConfig,
SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec,
ServiceAuthorizationMode, ServiceExposure, ServiceStatus, WatchEvent, WatchOptions,
WorkspaceRef,
Health, ListOptions, LogLine, PlatformEvent, ResumeOptions, SandboxCondition, SandboxPhase,
SandboxProvisioning, SandboxRef, SandboxResources, SandboxRestartPolicy, SandboxServiceLevel,
SandboxSpec, SandboxStartup, SandboxTemplateCreateSpec, SandboxTemplateListOptions,
SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance,
SandboxWorkloadTemplateSpec, ServiceAuthorizationMode, ServiceExposure, ServiceStatus,
WatchEvent, WatchOptions, WorkspaceRef,
};
110 changes: 89 additions & 21 deletions crates/openshell-sdk/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,10 @@ pub struct SandboxRef {
pub labels: HashMap<String, String>,
pub resource_version: u64,
pub exit_code: Option<i32>,
/// Latest user-facing conditions reported by the gateway or its compute driver.
pub conditions: Vec<SandboxCondition>,
/// Provisioning attempt details, when reported by the gateway.
pub provisioning: Option<SandboxProvisioning>,
/// Public OpenSSH SHA256 host identity; absent on older gateways.
pub host_key_fingerprint: Option<String>,
pub created_from_workload_template: Option<SandboxWorkloadTemplateProvenance>,
Expand All @@ -437,6 +441,78 @@ pub struct SandboxRef {
pub main_process_started_at_ms: Option<i64>,
}

/// A user-facing readiness or lifecycle observation.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct SandboxCondition {
/// Condition class, as reported by the gateway or platform.
pub kind: String,
/// Reported state, such as `True`, `False`, or `Unknown`.
pub status: String,
/// Short machine-readable reason, when supplied.
pub reason: String,
/// Human-readable context, when supplied.
pub message: String,
/// Unix time in milliseconds of the last transition, when reported.
pub transition_at_ms: Option<i64>,
}

impl From<proto::SandboxCondition> for SandboxCondition {
fn from(condition: proto::SandboxCondition) -> Self {
Self {
kind: condition.r#type,
status: condition.status,
reason: condition.reason,
message: condition.message,
transition_at_ms: condition
.transition_time
.as_ref()
.and_then(|time| openshell_core::time::timestamp_to_millis(time).ok()),
}
}
}

/// Gateway-reported timing and outcome for the current provisioning attempt.
///
/// Timestamps are Unix milliseconds. A missing value means the gateway has
/// not reported that milestone.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct SandboxProvisioning {
pub attempt_id: String,
/// Absolute deadline for initial image preparation and supervisor startup.
pub preparation_deadline_ms: Option<i64>,
/// First authenticated supervisor configuration report for this attempt.
pub admission_started_at_ms: Option<i64>,
/// Current preparation or admission-repair deadline.
pub deadline_ms: Option<i64>,
/// Time the gateway declared the attempt timed out.
pub timed_out_at_ms: Option<i64>,
/// Time the gateway finished reclaiming the failed attempt's compute.
pub cleanup_completed_at_ms: Option<i64>,
/// Safe gateway-authored cleanup diagnostic, when available.
pub cleanup_error: Option<String>,
}

impl From<proto::SandboxProvisioning> for SandboxProvisioning {
fn from(provisioning: proto::SandboxProvisioning) -> Self {
let millis = |time: Option<_>| {
time.as_ref()
.and_then(|time| openshell_core::time::timestamp_to_millis(time).ok())
};
Self {
attempt_id: provisioning.attempt_id,
preparation_deadline_ms: millis(provisioning.preparation_deadline),
admission_started_at_ms: millis(provisioning.admission_start_time),
deadline_ms: millis(provisioning.deadline),
timed_out_at_ms: millis(provisioning.timeout_time),
cleanup_completed_at_ms: millis(provisioning.cleanup_completed_time),
cleanup_error: (!provisioning.cleanup_error.is_empty())
.then_some(provisioning.cleanup_error),
}
}
}

/// Reusable workload template revision used to create a sandbox.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
Expand All @@ -455,23 +531,7 @@ impl SandboxRef {
name: p.name,
resource_version: p.resource_version,
});
let (exit_code, restart_count, next_restart_at_ms, main_process_started_at_ms) = sandbox
.status
.as_ref()
.map_or((None, 0, None, None), |status| {
(
status.exit_code,
status.restart_count,
status
.next_restart_time
.as_ref()
.and_then(|time| openshell_core::time::timestamp_to_millis(time).ok()),
status
.main_process_started_time
.as_ref()
.and_then(|time| openshell_core::time::timestamp_to_millis(time).ok()),
)
});
let status = sandbox.status.unwrap_or_default();
let meta = sandbox.metadata.unwrap_or_default();
Self {
id: meta.id,
Expand All @@ -480,16 +540,24 @@ impl SandboxRef {
phase,
labels: meta.labels,
resource_version: meta.resource_version,
exit_code,
exit_code: status.exit_code,
conditions: status.conditions.into_iter().map(Into::into).collect(),
provisioning: status.provisioning.map(Into::into),
host_key_fingerprint: (!sandbox.host_key_fingerprint.is_empty())
.then_some(sandbox.host_key_fingerprint),
created_from_workload_template,
service_urls: HashMap::new(),
application_service_urls: HashMap::new(),
gateway_service_urls: HashMap::new(),
restart_count,
next_restart_at_ms,
main_process_started_at_ms,
restart_count: status.restart_count,
next_restart_at_ms: status
.next_restart_time
.as_ref()
.and_then(|time| openshell_core::time::timestamp_to_millis(time).ok()),
main_process_started_at_ms: status
.main_process_started_time
.as_ref()
.and_then(|time| openshell_core::time::timestamp_to_millis(time).ok()),
}
}
}
Expand Down
92 changes: 92 additions & 0 deletions crates/openshell-sdk/tests/client_mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3414,6 +3414,98 @@ async fn raw_discovery_shares_transport_and_refreshes_the_live_auth_slot() {
.unwrap();
}

#[tokio::test]
async fn watch_sandbox_status_exposes_provisioning_failure() {
use proto::sandbox_stream_event::Payload;

let timestamp = openshell_core::time::timestamp_from_millis(1_234).unwrap();
let snapshot =
|phase: proto::SandboxPhase, resource_version, failed: bool| proto::SandboxStreamEvent {
payload: Some(Payload::Sandbox(proto::Sandbox {
metadata: Some(proto::datamodel::v1::ObjectMeta {
name: "worker".into(),
workspace: "production".into(),
resource_version,
..Default::default()
}),
status: Some(proto::SandboxStatus {
phase: phase.into(),
provisioning: failed.then(|| proto::SandboxProvisioning {
attempt_id: "attempt-1".into(),
timeout_time: Some(timestamp.clone()),
..Default::default()
}),
conditions: if failed {
vec![proto::SandboxCondition {
r#type: "Ready".into(),
status: "False".into(),
reason: "ImagePreparationTimedOut".into(),
message: "Sandbox preparation timed out".into(),
transition_time: Some(timestamp.clone()),
}]
} else {
Vec::new()
},
..Default::default()
}),
..Default::default()
})),
..Default::default()
};
let state = Arc::new(MockState {
watch_script: vec![WatchDial {
events: vec![
snapshot(proto::SandboxPhase::Provisioning, 1, false),
snapshot(proto::SandboxPhase::Error, 2, true),
],
end: DialEnd::Err(tonic::Code::Unavailable),
}],
..Default::default()
});
let endpoint = start_mock(state.clone()).await;
let client = connect(&endpoint).await;
let workspace = client.workspace("production");
let stream = workspace.watch_sandbox_status("worker");
tokio::pin!(stream);

let initial = stream.next().await.unwrap().unwrap();
assert_eq!(initial.phase, SandboxPhase::Provisioning);
assert!(initial.conditions.is_empty());
assert!(initial.provisioning.is_none());

let failed = stream.next().await.unwrap().unwrap();
assert_eq!(failed.phase, SandboxPhase::Error);
assert_eq!(failed.resource_version, 2);
let condition = &failed.conditions[0];
assert_eq!(condition.kind, "Ready");
assert_eq!(condition.status, "False");
assert_eq!(condition.reason, "ImagePreparationTimedOut");
assert_eq!(condition.message, "Sandbox preparation timed out");
assert_eq!(condition.transition_at_ms, Some(1_234));
let provisioning = failed.provisioning.unwrap();
assert_eq!(provisioning.attempt_id, "attempt-1");
assert_eq!(provisioning.timed_out_at_ms, Some(1_234));
assert!(provisioning.deadline_ms.is_none());

let error = stream.next().await.unwrap().unwrap_err();
assert_eq!(
error.grpc_status().unwrap().code(),
tonic::Code::Unavailable
);
assert!(stream.next().await.is_none());

let requests = state.last_watch_requests.lock().await;
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].sandbox, "worker");
assert_eq!(
selected_workspace(&requests[0].workspace_scope),
Some("production")
);
assert!(requests[0].follow_status);
assert!(!requests[0].follow_logs);
assert!(!requests[0].follow_events);
}

#[tokio::test]
async fn watch_logs_forwards_logs_and_warnings() {
let state = Arc::new(MockState {
Expand Down
8 changes: 8 additions & 0 deletions docs/sdk/rust.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
```

Use `watch_sandbox_status(name)` to display provisioning progress in a long-running
client. It streams the current `SandboxRef` and later status snapshots. Read
`phase` for the lifecycle state, `conditions` for gateway or platform reasons
and messages, and `provisioning` for attempt timing and timeout details. For a
one-time status check, the same fields are available through `get_sandbox(name)`.
Older gateways may omit the details. Use `client.workspace("team")` for a named
workspace.

Use `raw_grpc_fresh()` for RPCs that the curated API does not yet wrap. The raw
client returns generated protobuf types and requires callers to assemble full
requests.
Expand Down
Loading