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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ aws-credential-types = { version = "1.2.13", optional = true }
testcontainers = "0.27.3"
dicom-test-files = "0.4.0"
dicom-web = "0.5.0"
reqwest = { version = "0.13.2", default-features = false, features = ["json"] }

[lints.rust]
unsafe_code = "forbid"
Expand Down
4 changes: 3 additions & 1 deletion src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ mod aets;
mod home;
pub mod mwl;
pub mod qido;
pub mod stgcmt;
pub mod stow;
pub mod wado;

Expand All @@ -27,7 +28,8 @@ pub fn routes(base_path: &str) -> Router<AppState> {
.merge(qido::routes())
.merge(wado::routes())
.merge(stow::routes())
.merge(mwl::routes()),
.merge(mwl::routes())
.merge(stgcmt::routes()),
);

// axum no longer supports nesting at the root
Expand Down
5 changes: 5 additions & 0 deletions src/api/stgcmt/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod routes;
mod service;

pub use routes::routes;
pub use service::*;
84 changes: 84 additions & 0 deletions src/api/stgcmt/routes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use crate::api::stgcmt::{CommitRequest, CommitmentState};
use crate::backend::ServiceProvider;
use crate::utils::dicom_json::DicomJsonBody;
use crate::AppState;
use axum::body::Body;
use axum::extract::Path;
use axum::http::header::CONTENT_TYPE;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::post;
use axum::Router;
use dicom::object::InMemDicomObject;
use dicom_json::DicomJson;
use tracing::instrument;

/// HTTP Router for the Storage Commitment Service.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/chapter_13.html>
pub fn routes() -> Router<AppState> {
Router::new().route(
"/commitment-requests/{transaction_uid}",
post(commit).get(check_result),
)
}

/// Commit Transaction.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/sect_13.4.html>
#[instrument(skip_all)]
async fn commit(
provider: ServiceProvider,
Path((_aet, transaction_uid)): Path<(String, String)>,
DicomJsonBody(object): DicomJsonBody,
) -> Response {
let Some(stgcmt) = provider.stgcmt else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"Storage Commitment endpoint is disabled",
)
.into_response();
};

let request = match CommitRequest::from_object(transaction_uid, &object) {
Ok(request) => request,
Err(err) => return err.into_response(),
};

match stgcmt.commit(request).await {
Ok(()) => StatusCode::ACCEPTED.into_response(),
Err(err) => err.into_response(),
}
}

/// Check Commit Result Transaction.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/sect_13.5.html>
#[instrument(skip_all)]
async fn check_result(
provider: ServiceProvider,
Path((_aet, transaction_uid)): Path<(String, String)>,
) -> Response {
let Some(stgcmt) = provider.stgcmt else {
return (
StatusCode::SERVICE_UNAVAILABLE,
"Storage Commitment endpoint is disabled",
)
.into_response();
};

match stgcmt.check_result(&transaction_uid).await {
None => (
StatusCode::NOT_FOUND,
format!("Unknown Transaction UID {transaction_uid}"),
)
.into_response(),
Some(CommitmentState::Pending) => StatusCode::ACCEPTED.into_response(),
Some(CommitmentState::Completed(result)) => {
let json = DicomJson::from(InMemDicomObject::from(result));

Response::builder()
.status(StatusCode::OK)
.header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())
.body(Body::from(serde_json::to_string(&json).unwrap()))
.unwrap()
}
}
}
183 changes: 183 additions & 0 deletions src/api/stgcmt/service.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
use crate::api::stow::InstanceReference;
use crate::types::{UI, US};
use async_trait::async_trait;
use axum::body::Body;
use axum::http::{Response, StatusCode};
use axum::response::IntoResponse;
use dicom::core::value::{DataSetSequence, Value};
use dicom::core::{DataElement, VR};
use dicom::dicom_value;
use dicom::dictionary_std::tags;
use dicom::object::mem::InMemElement;
use dicom::object::InMemDicomObject;
use thiserror::Error;

/// Storage Commitment Request Module.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/chapter_J.html#sect_J.1>
pub struct CommitRequest {
pub transaction_uid: UI,
pub referenced_sop_sequence: Vec<InstanceReference>,
}

impl CommitRequest {
pub fn from_object(
transaction_uid: UI,
object: &InMemDicomObject,
) -> Result<Self, CommitError> {
let items = object
.get(tags::REFERENCED_SOP_SEQUENCE)
.and_then(InMemElement::items)
.ok_or(CommitError::MissingReferencedSopSequence)?;

let referenced_sop_sequence = items
.iter()
.map(|item| {
let sop_class_uid = item
.get(tags::REFERENCED_SOP_CLASS_UID)
.map(InMemElement::to_str)
.and_then(Result::ok)
.ok_or(CommitError::MissingReferencedSopSequence)?
.into_owned();
let sop_instance_uid = item
.get(tags::REFERENCED_SOP_INSTANCE_UID)
.map(InMemElement::to_str)
.and_then(Result::ok)
.ok_or(CommitError::MissingReferencedSopSequence)?
.into_owned();

Ok(InstanceReference {
sop_class_uid,
sop_instance_uid,
})
})
.collect::<Result<Vec<_>, CommitError>>()?;

if referenced_sop_sequence.is_empty() {
return Err(CommitError::MissingReferencedSopSequence);
}

Ok(Self {
transaction_uid,
referenced_sop_sequence,
})
}
}

/// An instance for which storage has not been committed.
#[derive(Debug, Clone)]
pub struct FailedInstance {
pub reference: InstanceReference,
pub failure_reason: US,
}

/// The result of a storage commitment request, once known.
/// Storage Commitment Response Module.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/chapter_J.html#sect_J.2>
#[derive(Debug, Clone, Default)]
pub struct CommitmentResult {
pub referenced_sequence: Vec<InstanceReference>,
pub failed_sequence: Vec<FailedInstance>,
}

impl From<CommitmentResult> for InMemDicomObject {
fn from(result: CommitmentResult) -> Self {
let mut object = Self::new_empty();

let mut referenced_sequence = InMemElement::new(
tags::REFERENCED_SOP_SEQUENCE,
VR::SQ,
Value::Sequence(DataSetSequence::empty()),
);
let referenced_items = referenced_sequence.items_mut().expect("Sequence exists");
for referenced in result.referenced_sequence {
referenced_items.push(Self::from_element_iter([
DataElement::new(
tags::REFERENCED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, referenced.sop_class_uid),
),
DataElement::new(
tags::REFERENCED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, referenced.sop_instance_uid),
),
]));
}

let mut failed_sequence = InMemElement::new(
tags::FAILED_SOP_SEQUENCE,
VR::SQ,
Value::Sequence(DataSetSequence::empty()),
);
let failed_items = failed_sequence.items_mut().expect("Sequence exists");
for failed in result.failed_sequence {
failed_items.push(Self::from_element_iter([
DataElement::new(
tags::REFERENCED_SOP_CLASS_UID,
VR::UI,
dicom_value!(Str, failed.reference.sop_class_uid),
),
DataElement::new(
tags::REFERENCED_SOP_INSTANCE_UID,
VR::UI,
dicom_value!(Str, failed.reference.sop_instance_uid),
),
DataElement::new(
tags::FAILURE_REASON,
VR::US,
dicom_value!(U16, [failed.failure_reason]),
),
]));
}

object.put(referenced_sequence);
object.put(failed_sequence);
object
}
}

/// The state of a previously submitted commitment request.
#[derive(Debug, Clone)]
pub enum CommitmentState {
/// The origin server has not finished processing the storage commitment request yet.
Pending,
/// The origin server finished processing the storage commitment request.
Completed(CommitmentResult),
}

/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/chapter_13.html>
#[async_trait]
pub trait StgcmtService: Sync + Send {
/// Commit Transaction.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/sect_13.4.html>
async fn commit(&self, request: CommitRequest) -> Result<(), CommitError>;

/// Check Commit Result Transaction.
/// <https://dicom.nema.org/medical/dicom/current/output/chtml/part18/sect_13.5.html>
async fn check_result(&self, transaction_uid: &str) -> Option<CommitmentState>;
}

#[derive(Debug, Error)]
pub enum CommitError {
#[error("A commitment request with Transaction UID {0} already exists")]
DuplicateTransaction(UI),
#[error("The request payload did not contain a (non-empty) Referenced SOP Sequence")]
MissingReferencedSopSequence,
#[error("Failed to send N-ACTION-RQ: {0:#}")]
Backend(#[from] anyhow::Error),
}

impl IntoResponse for CommitError {
fn into_response(self) -> Response<Body> {
let status = match &self {
Self::DuplicateTransaction(_) => StatusCode::CONFLICT,
Self::MissingReferencedSopSequence => StatusCode::BAD_REQUEST,
Self::Backend(_) => StatusCode::SERVICE_UNAVAILABLE,
};

Response::builder()
.status(status)
.body(Body::from(self.to_string()))
.unwrap()
}
}
2 changes: 1 addition & 1 deletion src/api/stow/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub struct StoreRequest {
}

/// <https://dicom.nema.org/medical/dicom/current/output/html/part03.html#table_10-11>
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct InstanceReference {
pub sop_class_uid: UI,
pub sop_instance_uid: UI,
Expand Down
Loading
Loading