Skip to content

Commit 9aae562

Browse files
committed
refactor: deduplicate shared code across ocsf builders and driver crates
Extract repeated patterns into shared helpers: - Add impl_builder_setters! macro to openshell-ocsf/builders that generates the identical severity(), status(), and message() setter methods present on all 7 OCSF event builders - Add SandboxContext::apply_common_fields() to consolidate the four-line build() finalization (set_status, set_message, set_device, set_container) repeated in every builder - Add driver_utils::sandbox_token_path() to centralize the XDG state path construction for sandbox JWT files used by both the Docker and Podman drivers - Add driver_utils::build_capabilities_response() to eliminate the identical GetCapabilitiesResponse struct literal repeated across the Docker, Podman, and Kubernetes compute drivers
1 parent c5c3f03 commit 9aae562

13 files changed

Lines changed: 174 additions & 215 deletions

File tree

‎crates/openshell-core/src/driver_utils.rs‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33

44
//! Utility helpers shared across compute-driver crates.
55
6-
use crate::proto::compute::v1::DriverSandbox;
6+
use std::path::PathBuf;
7+
8+
use crate::proto::compute::v1::{DriverSandbox, GetCapabilitiesResponse};
79

810
// ---------------------------------------------------------------------------
911
// Sandbox container/pod label keys (openshell.ai/ namespace)
@@ -34,6 +36,50 @@ pub const LABEL_SANDBOX_NAMESPACE: &str = "openshell.ai/sandbox-namespace";
3436
/// path used when building the `openshell-sandbox` image layer.
3537
pub const SUPERVISOR_IMAGE_BINARY_PATH: &str = "/openshell-sandbox";
3638

39+
/// Return the XDG state path for a driver's sandbox JWT token file.
40+
///
41+
/// The resulting path is `$XDG_STATE_HOME/openshell/<driver_subdir>[/<namespace>]/<sandbox_id>/sandbox.jwt`.
42+
///
43+
/// `driver_subdir` is driver-specific, e.g. `"docker-sandbox-tokens"` or
44+
/// `"podman-sandbox-tokens"`. When `namespace` is `Some`, it is appended as
45+
/// an additional path component (with `/` and `\` replaced by `-`).
46+
///
47+
/// # Errors
48+
/// Returns an error if the XDG state directory cannot be resolved.
49+
pub fn sandbox_token_path(
50+
driver_subdir: &str,
51+
namespace: Option<&str>,
52+
sandbox_id: &str,
53+
) -> miette::Result<PathBuf> {
54+
let mut path = crate::paths::xdg_state_dir()?
55+
.join("openshell")
56+
.join(driver_subdir);
57+
if let Some(ns) = namespace {
58+
path = path.join(ns.replace(['/', '\\'], "-"));
59+
}
60+
Ok(path.join(sandbox_id).join("sandbox.jwt"))
61+
}
62+
63+
/// Build a [`GetCapabilitiesResponse`] from the common driver capability fields.
64+
///
65+
/// Every compute driver constructs this response with the same fields. Shared
66+
/// here to avoid repeating the struct literal (and the always-zero `gpu_count`
67+
/// default) in each driver crate.
68+
pub fn build_capabilities_response(
69+
driver_name: &str,
70+
driver_version: impl Into<String>,
71+
default_image: impl Into<String>,
72+
supports_gpu: bool,
73+
) -> GetCapabilitiesResponse {
74+
GetCapabilitiesResponse {
75+
driver_name: driver_name.to_string(),
76+
driver_version: driver_version.into(),
77+
default_image: default_image.into(),
78+
supports_gpu,
79+
gpu_count: 0,
80+
}
81+
}
82+
3783
/// Return the effective log level for a sandbox.
3884
///
3985
/// Uses the level from the sandbox spec when non-empty, falling back to

‎crates/openshell-driver-docker/src/lib.rs‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -320,13 +320,12 @@ impl DockerComputeDriver {
320320
}
321321

322322
fn capabilities(&self) -> GetCapabilitiesResponse {
323-
GetCapabilitiesResponse {
324-
driver_name: "docker".to_string(),
325-
driver_version: self.config.daemon_version.clone(),
326-
default_image: self.config.default_image.clone(),
327-
supports_gpu: self.config.supports_gpu,
328-
gpu_count: 0,
329-
}
323+
openshell_core::driver_utils::build_capabilities_response(
324+
"docker",
325+
&self.config.daemon_version,
326+
&self.config.default_image,
327+
self.config.supports_gpu,
328+
)
330329
}
331330

332331
fn validate_sandbox(
@@ -962,17 +961,16 @@ fn sandbox_token_host_path_by_id(
962961
sandbox_id: &str,
963962
config: &DockerDriverRuntimeConfig,
964963
) -> Result<PathBuf, Status> {
965-
let base = openshell_core::paths::xdg_state_dir().map_err(|err| {
964+
openshell_core::driver_utils::sandbox_token_path(
965+
"docker-sandbox-tokens",
966+
Some(&config.sandbox_namespace),
967+
sandbox_id,
968+
)
969+
.map_err(|err| {
966970
Status::internal(format!(
967971
"resolve sandbox token state directory failed: {err}"
968972
))
969-
})?;
970-
Ok(base
971-
.join("openshell")
972-
.join("docker-sandbox-tokens")
973-
.join(config.sandbox_namespace.replace(['/', '\\'], "-"))
974-
.join(sandbox_id)
975-
.join("sandbox.jwt"))
973+
})
976974
}
977975

978976
async fn write_sandbox_token_file(

‎crates/openshell-driver-kubernetes/src/driver.rs‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -160,13 +160,12 @@ impl KubernetesComputeDriver {
160160
}
161161

162162
pub async fn capabilities(&self) -> Result<GetCapabilitiesResponse, String> {
163-
Ok(GetCapabilitiesResponse {
164-
driver_name: "kubernetes".to_string(),
165-
driver_version: openshell_core::VERSION.to_string(),
166-
default_image: self.config.default_image.clone(),
167-
supports_gpu: self.has_gpu_capacity().await.unwrap_or(false),
168-
gpu_count: 0,
169-
})
163+
Ok(openshell_core::driver_utils::build_capabilities_response(
164+
"kubernetes",
165+
openshell_core::VERSION,
166+
&self.config.default_image,
167+
self.has_gpu_capacity().await.unwrap_or(false),
168+
))
170169
}
171170

172171
pub fn default_image(&self) -> &str {

‎crates/openshell-driver-podman/src/driver.rs‎

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -57,13 +57,8 @@ fn validated_container_name(sandbox_name: &str) -> Result<String, ComputeDriverE
5757
}
5858

5959
fn sandbox_token_host_path(sandbox_id: &str) -> Result<PathBuf, ComputeDriverError> {
60-
let base = openshell_core::paths::xdg_state_dir()
61-
.map_err(|err| ComputeDriverError::Message(format!("resolve state dir failed: {err}")))?;
62-
Ok(base
63-
.join("openshell")
64-
.join("podman-sandbox-tokens")
65-
.join(sandbox_id)
66-
.join("sandbox.jwt"))
60+
openshell_core::driver_utils::sandbox_token_path("podman-sandbox-tokens", None, sandbox_id)
61+
.map_err(|err| ComputeDriverError::Message(format!("resolve state dir failed: {err}")))
6762
}
6863

6964
async fn write_sandbox_token_file(
@@ -257,14 +252,12 @@ impl PodmanComputeDriver {
257252

258253
/// Report driver capabilities.
259254
pub fn capabilities(&self) -> Result<GetCapabilitiesResponse, ComputeDriverError> {
260-
let supports_gpu = Self::has_gpu_capacity();
261-
Ok(GetCapabilitiesResponse {
262-
driver_name: "podman".to_string(),
263-
driver_version: openshell_core::VERSION.to_string(),
264-
default_image: self.config.default_image.clone(),
265-
supports_gpu,
266-
gpu_count: 0,
267-
})
255+
Ok(openshell_core::driver_utils::build_capabilities_response(
256+
"podman",
257+
openshell_core::VERSION,
258+
&self.config.default_image,
259+
Self::has_gpu_capacity(),
260+
))
268261
}
269262

270263
#[must_use]

‎crates/openshell-ocsf/src/builders/base.rs‎

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -31,21 +31,6 @@ impl<'a> BaseEventBuilder<'a> {
3131
}
3232
}
3333

34-
#[must_use]
35-
pub fn severity(mut self, id: SeverityId) -> Self {
36-
self.severity = id;
37-
self
38-
}
39-
#[must_use]
40-
pub fn status(mut self, id: StatusId) -> Self {
41-
self.status = Some(id);
42-
self
43-
}
44-
#[must_use]
45-
pub fn message(mut self, msg: impl Into<String>) -> Self {
46-
self.message = Some(msg.into());
47-
self
48-
}
4934
#[must_use]
5035
pub fn activity_name(mut self, name: impl Into<String>) -> Self {
5136
self.activity_name = Some(name.into());
@@ -72,22 +57,18 @@ impl<'a> BaseEventBuilder<'a> {
7257
self.severity,
7358
self.ctx.metadata(&["container", "host"]),
7459
);
75-
if let Some(status) = self.status {
76-
base.set_status(status);
77-
}
78-
if let Some(msg) = self.message {
79-
base.set_message(msg);
80-
}
81-
base.set_device(self.ctx.device());
82-
base.set_container(self.ctx.container());
8360
if !self.unmapped.is_empty() {
8461
base.unmapped = Some(serde_json::Value::Object(self.unmapped));
8562
}
63+
self.ctx
64+
.apply_common_fields(&mut base, self.status, self.message);
8665

8766
OcsfEvent::Base(BaseEvent { base })
8867
}
8968
}
9069

70+
impl_builder_setters!(BaseEventBuilder);
71+
9172
#[cfg(test)]
9273
mod tests {
9374
use super::*;

‎crates/openshell-ocsf/src/builders/config.rs‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -37,22 +37,6 @@ impl<'a> ConfigStateChangeBuilder<'a> {
3737
}
3838
}
3939

40-
#[must_use]
41-
pub fn severity(mut self, id: SeverityId) -> Self {
42-
self.severity = id;
43-
self
44-
}
45-
#[must_use]
46-
pub fn status(mut self, id: StatusId) -> Self {
47-
self.status = Some(id);
48-
self
49-
}
50-
#[must_use]
51-
pub fn message(mut self, msg: impl Into<String>) -> Self {
52-
self.message = Some(msg.into());
53-
self
54-
}
55-
5640
/// Set state with a custom label (OCSF `state_id` + display label).
5741
#[must_use]
5842
pub fn state(mut self, id: StateId, label: &str) -> Self {
@@ -92,17 +76,11 @@ impl<'a> ConfigStateChangeBuilder<'a> {
9276
self.ctx
9377
.metadata(&["security_control", "container", "host"]),
9478
);
95-
if let Some(status) = self.status {
96-
base.set_status(status);
97-
}
98-
if let Some(msg) = self.message {
99-
base.set_message(msg);
100-
}
101-
base.set_device(self.ctx.device());
102-
base.set_container(self.ctx.container());
10379
if !self.unmapped.is_empty() {
10480
base.unmapped = Some(serde_json::Value::Object(self.unmapped));
10581
}
82+
self.ctx
83+
.apply_common_fields(&mut base, self.status, self.message);
10684

10785
OcsfEvent::DeviceConfigStateChange(DeviceConfigStateChangeEvent {
10886
base,
@@ -114,6 +92,8 @@ impl<'a> ConfigStateChangeBuilder<'a> {
11492
}
11593
}
11694

95+
impl_builder_setters!(ConfigStateChangeBuilder);
96+
11797
#[cfg(test)]
11898
mod tests {
11999
use super::*;

‎crates/openshell-ocsf/src/builders/finding.rs‎

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,6 @@ impl<'a> DetectionFindingBuilder<'a> {
5454
self
5555
}
5656
#[must_use]
57-
pub fn severity(mut self, id: SeverityId) -> Self {
58-
self.severity = id;
59-
self
60-
}
61-
#[must_use]
6257
pub fn action(mut self, id: ActionId) -> Self {
6358
self.action = Some(id);
6459
self
@@ -89,11 +84,6 @@ impl<'a> DetectionFindingBuilder<'a> {
8984
self
9085
}
9186
#[must_use]
92-
pub fn message(mut self, msg: impl Into<String>) -> Self {
93-
self.message = Some(msg.into());
94-
self
95-
}
96-
#[must_use]
9787
pub fn log_source(mut self, source: impl Into<String>) -> Self {
9888
self.log_source = Some(source.into());
9989
self
@@ -147,11 +137,7 @@ impl<'a> DetectionFindingBuilder<'a> {
147137
self.severity,
148138
metadata,
149139
);
150-
if let Some(msg) = self.message {
151-
base.set_message(msg);
152-
}
153-
base.set_device(self.ctx.device());
154-
base.set_container(self.ctx.container());
140+
self.ctx.apply_common_fields(&mut base, None, self.message);
155141

156142
OcsfEvent::DetectionFinding(DetectionFindingEvent {
157143
base,
@@ -178,6 +164,8 @@ impl<'a> DetectionFindingBuilder<'a> {
178164
}
179165
}
180166

167+
impl_builder_setters!(DetectionFindingBuilder, no_status);
168+
181169
#[cfg(test)]
182170
mod tests {
183171
use super::*;

‎crates/openshell-ocsf/src/builders/http.rs‎

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -64,16 +64,6 @@ impl<'a> HttpActivityBuilder<'a> {
6464
self
6565
}
6666
#[must_use]
67-
pub fn severity(mut self, id: SeverityId) -> Self {
68-
self.severity = id;
69-
self
70-
}
71-
#[must_use]
72-
pub fn status(mut self, id: StatusId) -> Self {
73-
self.status = Some(id);
74-
self
75-
}
76-
#[must_use]
7767
pub fn http_request(mut self, req: HttpRequest) -> Self {
7868
self.http_request = Some(req);
7969
self
@@ -104,11 +94,6 @@ impl<'a> HttpActivityBuilder<'a> {
10494
self
10595
}
10696
#[must_use]
107-
pub fn message(mut self, msg: impl Into<String>) -> Self {
108-
self.message = Some(msg.into());
109-
self
110-
}
111-
#[must_use]
11297
pub fn status_detail(mut self, detail: impl Into<String>) -> Self {
11398
self.status_detail = Some(detail.into());
11499
self
@@ -128,17 +113,11 @@ impl<'a> HttpActivityBuilder<'a> {
128113
self.ctx
129114
.metadata(&["security_control", "network_proxy", "container", "host"]),
130115
);
131-
if let Some(status) = self.status {
132-
base.set_status(status);
133-
}
134-
if let Some(msg) = self.message {
135-
base.set_message(msg);
136-
}
137116
if let Some(detail) = self.status_detail {
138117
base.set_status_detail(detail);
139118
}
140-
base.set_device(self.ctx.device());
141-
base.set_container(self.ctx.container());
119+
self.ctx
120+
.apply_common_fields(&mut base, self.status, self.message);
142121

143122
OcsfEvent::HttpActivity(HttpActivityEvent {
144123
base,
@@ -157,6 +136,8 @@ impl<'a> HttpActivityBuilder<'a> {
157136
}
158137
}
159138

139+
impl_builder_setters!(HttpActivityBuilder);
140+
160141
#[cfg(test)]
161142
mod tests {
162143
use super::*;

0 commit comments

Comments
 (0)