Skip to content

Commit 37fd970

Browse files
feat(sdk): add workspace-scoped client and workspace CRUD
Add WorkspaceScopedClient modeled after kube::Api::namespaced — captures workspace once and injects it into every sandbox request. Add workspace CRUD methods (create, get, list, delete) and list_sandboxes_all_workspaces on OpenShellClient. Extend SandboxRef with workspace field and add WorkspaceRef type. Include mock tests for all new operations. Signed-off-by: Derek Carr <decarr@redhat.com>
1 parent ae86488 commit 37fd970

5 files changed

Lines changed: 536 additions & 16 deletions

File tree

‎crates/openshell-sdk/src/client.rs‎

Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use crate::refresh::{RefreshedToken, TokenSource};
1616
use crate::transport;
1717
use crate::types::{
1818
ExecOptions, ExecResult, Health, ListOptions, SandboxPhase, SandboxRef, SandboxSpec,
19+
WorkspaceRef,
1920
};
2021
use futures::StreamExt;
2122
use openshell_core::proto;
@@ -256,6 +257,110 @@ impl OpenShellClient {
256257
}
257258
}
258259

260+
/// Return a workspace-scoped handle for sandbox operations.
261+
///
262+
/// Analogous to `kube::Api::namespaced` — captures the workspace once and
263+
/// injects it into every request.
264+
pub fn workspace(&self, workspace: &str) -> WorkspaceScopedClient {
265+
WorkspaceScopedClient {
266+
client: self.clone(),
267+
workspace: workspace.to_string(),
268+
}
269+
}
270+
271+
/// List sandboxes across all workspaces.
272+
pub async fn list_sandboxes_all_workspaces(
273+
&self,
274+
opts: ListOptions,
275+
) -> Result<Vec<SandboxRef>> {
276+
let response = self
277+
.unary(|mut grpc| {
278+
let request = proto::ListSandboxesRequest {
279+
limit: opts.limit,
280+
offset: opts.offset,
281+
label_selector: opts.label_selector.clone().unwrap_or_default(),
282+
workspace: String::new(),
283+
all_workspaces: true,
284+
};
285+
async move { grpc.list_sandboxes(request).await }
286+
})
287+
.await?;
288+
Ok(response
289+
.sandboxes
290+
.into_iter()
291+
.map(SandboxRef::from_proto)
292+
.collect())
293+
}
294+
295+
/// Create a new workspace.
296+
pub async fn create_workspace(
297+
&self,
298+
name: &str,
299+
labels: HashMap<String, String>,
300+
) -> Result<WorkspaceRef> {
301+
let response = self
302+
.unary(|mut grpc| {
303+
let request = proto::CreateWorkspaceRequest {
304+
name: name.to_string(),
305+
labels: labels.clone(),
306+
};
307+
async move { grpc.create_workspace(request).await }
308+
})
309+
.await?;
310+
response
311+
.workspace
312+
.map(WorkspaceRef::from_proto)
313+
.ok_or_else(|| SdkError::invalid_config("workspace missing from gateway response"))
314+
}
315+
316+
/// Fetch a workspace by name.
317+
pub async fn get_workspace(&self, name: &str) -> Result<WorkspaceRef> {
318+
let response = self
319+
.unary(|mut grpc| {
320+
let request = proto::GetWorkspaceRequest {
321+
name: name.to_string(),
322+
};
323+
async move { grpc.get_workspace(request).await }
324+
})
325+
.await?;
326+
response
327+
.workspace
328+
.map(WorkspaceRef::from_proto)
329+
.ok_or_else(|| SdkError::invalid_config("workspace missing from gateway response"))
330+
}
331+
332+
/// List workspaces.
333+
pub async fn list_workspaces(&self, opts: ListOptions) -> Result<Vec<WorkspaceRef>> {
334+
let response = self
335+
.unary(|mut grpc| {
336+
let request = proto::ListWorkspacesRequest {
337+
limit: opts.limit,
338+
offset: opts.offset,
339+
label_selector: opts.label_selector.clone().unwrap_or_default(),
340+
};
341+
async move { grpc.list_workspaces(request).await }
342+
})
343+
.await?;
344+
Ok(response
345+
.workspaces
346+
.into_iter()
347+
.map(WorkspaceRef::from_proto)
348+
.collect())
349+
}
350+
351+
/// Delete a workspace by name.
352+
pub async fn delete_workspace(&self, name: &str) -> Result<bool> {
353+
let response = self
354+
.unary(|mut grpc| {
355+
let request = proto::DeleteWorkspaceRequest {
356+
name: name.to_string(),
357+
};
358+
async move { grpc.delete_workspace(request).await }
359+
})
360+
.await?;
361+
Ok(response.deleted)
362+
}
363+
259364
/// Run a command inside a sandbox and buffer stdout/stderr to the end.
260365
///
261366
/// For streaming output, drop down to [`OpenShellClient::raw_grpc`] and
@@ -399,6 +504,192 @@ impl OpenShellClient {
399504
}
400505
}
401506

507+
/// Workspace-scoped sandbox operations, analogous to `kube::Api::namespaced`.
508+
///
509+
/// Constructed via [`OpenShellClient::workspace`]. Captures the workspace
510+
/// once and injects it into every request.
511+
#[derive(Clone)]
512+
pub struct WorkspaceScopedClient {
513+
client: OpenShellClient,
514+
workspace: String,
515+
}
516+
517+
impl WorkspaceScopedClient {
518+
/// The workspace this client targets.
519+
pub fn workspace_name(&self) -> &str {
520+
&self.workspace
521+
}
522+
523+
/// Create a new sandbox in this workspace.
524+
pub async fn create_sandbox(&self, spec: SandboxSpec) -> Result<SandboxRef> {
525+
let mut request = create_sandbox_request(spec);
526+
request.workspace = self.workspace.clone();
527+
let response = self
528+
.client
529+
.unary(|mut grpc| {
530+
let request = request.clone();
531+
async move { grpc.create_sandbox(request).await }
532+
})
533+
.await?;
534+
sandbox_from_response(response.sandbox)
535+
}
536+
537+
/// Fetch a sandbox by name in this workspace.
538+
pub async fn get_sandbox(&self, name: &str) -> Result<SandboxRef> {
539+
let response = self
540+
.client
541+
.unary(|mut grpc| {
542+
let request = proto::GetSandboxRequest {
543+
name: name.to_string(),
544+
workspace: self.workspace.clone(),
545+
};
546+
async move { grpc.get_sandbox(request).await }
547+
})
548+
.await?;
549+
sandbox_from_response(response.sandbox)
550+
}
551+
552+
/// List sandboxes in this workspace.
553+
pub async fn list_sandboxes(&self, opts: ListOptions) -> Result<Vec<SandboxRef>> {
554+
let response = self
555+
.client
556+
.unary(|mut grpc| {
557+
let request = proto::ListSandboxesRequest {
558+
limit: opts.limit,
559+
offset: opts.offset,
560+
label_selector: opts.label_selector.clone().unwrap_or_default(),
561+
workspace: self.workspace.clone(),
562+
all_workspaces: false,
563+
};
564+
async move { grpc.list_sandboxes(request).await }
565+
})
566+
.await?;
567+
Ok(response
568+
.sandboxes
569+
.into_iter()
570+
.map(SandboxRef::from_proto)
571+
.collect())
572+
}
573+
574+
/// Delete a sandbox by name in this workspace.
575+
pub async fn delete_sandbox(&self, name: &str) -> Result<bool> {
576+
let response = self
577+
.client
578+
.unary(|mut grpc| {
579+
let request = proto::DeleteSandboxRequest {
580+
name: name.to_string(),
581+
workspace: self.workspace.clone(),
582+
};
583+
async move { grpc.delete_sandbox(request).await }
584+
})
585+
.await?;
586+
Ok(response.deleted)
587+
}
588+
589+
/// Poll until the sandbox reaches [`SandboxPhase::Ready`] or the timeout
590+
/// elapses.
591+
pub async fn wait_ready(&self, name: &str, timeout: Duration) -> Result<SandboxRef> {
592+
let deadline = Instant::now() + timeout;
593+
let mut delay = Duration::from_millis(250);
594+
loop {
595+
let snapshot = self.get_sandbox(name).await?;
596+
match snapshot.phase {
597+
SandboxPhase::Ready => return Ok(snapshot),
598+
SandboxPhase::Error => {
599+
return Err(SdkError::connect(format!(
600+
"sandbox '{name}' entered error phase"
601+
)));
602+
}
603+
_ => {}
604+
}
605+
if Instant::now() >= deadline {
606+
return Err(SdkError::connect(format!(
607+
"timed out waiting for sandbox '{name}'"
608+
)));
609+
}
610+
tokio::time::sleep(delay).await;
611+
delay = (delay * 2).min(Duration::from_secs(2));
612+
}
613+
}
614+
615+
/// Poll until the sandbox is gone (`NotFound`) or the timeout elapses.
616+
pub async fn wait_deleted(&self, name: &str, timeout: Duration) -> Result<()> {
617+
let deadline = Instant::now() + timeout;
618+
let mut delay = Duration::from_millis(250);
619+
loop {
620+
match self.get_sandbox(name).await {
621+
Err(SdkError::NotFound { .. }) => return Ok(()),
622+
Err(other) => return Err(other),
623+
Ok(_) => {}
624+
}
625+
if Instant::now() >= deadline {
626+
return Err(SdkError::connect(format!(
627+
"timed out waiting for sandbox '{name}' to delete"
628+
)));
629+
}
630+
tokio::time::sleep(delay).await;
631+
delay = (delay * 2).min(Duration::from_secs(2));
632+
}
633+
}
634+
635+
/// Run a command inside a sandbox and buffer stdout/stderr.
636+
pub async fn exec(
637+
&self,
638+
name: &str,
639+
cmd: &[String],
640+
opts: ExecOptions,
641+
) -> Result<ExecResult> {
642+
let sandbox = self.get_sandbox(name).await?;
643+
let request = proto::ExecSandboxRequest {
644+
sandbox_id: sandbox.id,
645+
command: cmd.to_vec(),
646+
workdir: opts.workdir.unwrap_or_default(),
647+
environment: opts.environment,
648+
timeout_seconds: opts
649+
.timeout
650+
.map_or(0, |d| u32::try_from(d.as_secs()).unwrap_or(u32::MAX)),
651+
stdin: opts.stdin.unwrap_or_default(),
652+
tty: false,
653+
cols: 0,
654+
rows: 0,
655+
};
656+
657+
let mut stream = self
658+
.client
659+
.unary(|mut grpc| {
660+
let request = request.clone();
661+
async move { grpc.exec_sandbox(request).await }
662+
})
663+
.await?;
664+
665+
let mut stdout = Vec::new();
666+
let mut stderr = Vec::new();
667+
let mut exit_code: Option<i32> = None;
668+
669+
while let Some(event) = stream.next().await {
670+
let event = event.map_err(map_status)?;
671+
match event.payload {
672+
Some(proto::exec_sandbox_event::Payload::Stdout(chunk)) => {
673+
stdout.extend_from_slice(&chunk.data);
674+
}
675+
Some(proto::exec_sandbox_event::Payload::Stderr(chunk)) => {
676+
stderr.extend_from_slice(&chunk.data);
677+
}
678+
Some(proto::exec_sandbox_event::Payload::Exit(exit)) => {
679+
exit_code = Some(exit.exit_code);
680+
}
681+
None => {}
682+
}
683+
}
684+
685+
Ok(ExecResult {
686+
exit_code: exit_code.unwrap_or(-1),
687+
stdout,
688+
stderr,
689+
})
690+
}
691+
}
692+
402693
fn interceptor_from_config(config: &ClientConfig) -> Result<EdgeAuthInterceptor> {
403694
match &config.auth {
404695
None => Ok(EdgeAuthInterceptor::noop()),

‎crates/openshell-sdk/src/lib.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,11 @@ pub mod transport;
4141
pub mod types;
4242

4343
pub use auth::EdgeAuthInterceptor;
44-
pub use client::OpenShellClient;
44+
pub use client::{OpenShellClient, WorkspaceScopedClient};
4545
pub use config::{AuthConfig, ClientConfig};
4646
pub use error::SdkError;
4747
pub use refresh::{Refresh, RefreshError, RefreshedToken, TokenSource};
4848
pub use types::{
4949
ExecOptions, ExecResult, Health, ListOptions, SandboxPhase, SandboxRef, SandboxSpec,
50-
ServiceStatus,
50+
ServiceStatus, WorkspaceRef,
5151
};

‎crates/openshell-sdk/src/raw.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,11 @@ pub use openshell_core::proto;
2222
pub use openshell_core::proto::inference_client::InferenceClient;
2323
pub use openshell_core::proto::open_shell_client::OpenShellClient as GrpcClient;
2424
pub use openshell_core::proto::{
25-
CreateSandboxRequest, DeleteSandboxRequest, ExecSandboxRequest, GetSandboxRequest,
26-
HealthRequest, ListProvidersRequest, ListSandboxesRequest, Sandbox,
25+
CreateSandboxRequest, CreateWorkspaceRequest, DeleteSandboxRequest, DeleteWorkspaceRequest,
26+
ExecSandboxRequest, GetSandboxRequest, GetWorkspaceRequest, HealthRequest,
27+
ListProvidersRequest, ListSandboxesRequest, ListWorkspacesRequest, Sandbox,
2728
SandboxPhase as ProtoSandboxPhase, SandboxSpec as ProtoSandboxSpec, SandboxTemplate,
28-
ServiceStatus as ProtoServiceStatus,
29+
ServiceStatus as ProtoServiceStatus, Workspace,
2930
};
3031

3132
/// Type alias for the gRPC client wrapped in the SDK's auth interceptor.

‎crates/openshell-sdk/src/types.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ pub struct SandboxSpec {
111111
pub struct SandboxRef {
112112
pub id: String,
113113
pub name: String,
114+
pub workspace: String,
114115
pub phase: SandboxPhase,
115116
pub labels: HashMap<String, String>,
116117
pub resource_version: u64,
@@ -123,13 +124,42 @@ impl SandboxRef {
123124
Self {
124125
id: meta.id,
125126
name: meta.name,
127+
workspace: meta.workspace,
126128
phase,
127129
labels: meta.labels,
128130
resource_version: meta.resource_version,
129131
}
130132
}
131133
}
132134

135+
/// Reference to a workspace on the gateway.
136+
#[derive(Clone, Debug)]
137+
#[non_exhaustive]
138+
pub struct WorkspaceRef {
139+
pub name: String,
140+
pub phase: String,
141+
pub labels: HashMap<String, String>,
142+
}
143+
144+
impl WorkspaceRef {
145+
pub(crate) fn from_proto(workspace: proto::Workspace) -> Self {
146+
let meta = workspace.metadata.unwrap_or_default();
147+
let phase = workspace
148+
.status
149+
.and_then(|s| proto::datamodel::v1::WorkspacePhase::try_from(s.phase).ok())
150+
.map_or("Unknown", |p| match p {
151+
proto::datamodel::v1::WorkspacePhase::Unspecified => "Unspecified",
152+
proto::datamodel::v1::WorkspacePhase::Active => "Active",
153+
proto::datamodel::v1::WorkspacePhase::Terminating => "Terminating",
154+
});
155+
Self {
156+
name: meta.name,
157+
phase: phase.to_string(),
158+
labels: meta.labels,
159+
}
160+
}
161+
}
162+
133163
/// Options for listing sandboxes.
134164
#[derive(Clone, Debug, Default)]
135165
pub struct ListOptions {

0 commit comments

Comments
 (0)