aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
6
akode-rs/attachment-store/BUILD.bazel
Normal file
6
akode-rs/attachment-store/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "attachment-store",
|
||||
crate_name = "akode_attachment_store",
|
||||
)
|
||||
21
akode-rs/attachment-store/Cargo.toml
Normal file
21
akode-rs/attachment-store/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
name = "akode-attachment-store"
|
||||
version.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
name = "akode_attachment_store"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
tracing = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tokio = { workspace = true, features = ["macros", "rt", "sync"] }
|
||||
260
akode-rs/attachment-store/src/lib.rs
Normal file
260
akode-rs/attachment-store/src/lib.rs
Normal file
@@ -0,0 +1,260 @@
|
||||
//! Storage-neutral attachment persistence and availability checks.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
/// Result returned by [`AttachmentStore`] operations.
|
||||
pub type AttachmentStoreResult<T> = Result<T, AttachmentStoreError>;
|
||||
|
||||
/// Future returned by [`AttachmentStore::upload`].
|
||||
pub type UploadFuture<'a> =
|
||||
Pin<Box<dyn Future<Output = AttachmentStoreResult<UploadResult>> + Send + 'a>>;
|
||||
|
||||
/// Future returned by [`AttachmentStore::resolve`].
|
||||
pub type ResolveFuture<'a> =
|
||||
Pin<Box<dyn Future<Output = AttachmentStoreResult<AttachmentMetadata>> + Send + 'a>>;
|
||||
|
||||
/// Future returned by [`AttachmentStore::is_resolvable`].
|
||||
pub type IsResolvableFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
|
||||
|
||||
/// Uploads attachments and resolves metadata for stored files.
|
||||
///
|
||||
/// Implementations choose whether uploaded attachments remain inline or become file references.
|
||||
/// File references returned by [`AttachmentStore::upload`] must be resolvable by
|
||||
/// [`AttachmentStore::resolve`].
|
||||
pub trait AttachmentStore: Send + Sync {
|
||||
/// Uploads an attachment and returns the representation callers should retain.
|
||||
fn upload(&self, request: UploadRequest) -> UploadFuture<'_>;
|
||||
|
||||
/// Resolves metadata and, when requested, a fresh URL for a stored attachment.
|
||||
fn resolve<'a>(&'a self, request: ResolveRequest<'a>) -> ResolveFuture<'a>;
|
||||
|
||||
/// Checks whether a file reference should be retained in a model request.
|
||||
///
|
||||
/// The default retains all references, including provider-owned IDs this store cannot
|
||||
/// resolve. Authoritative stores may opt in to checking and return `false` only when the
|
||||
/// file is confirmed missing. Backend and access errors must retain the reference.
|
||||
fn is_resolvable<'a>(&'a self, _file_id: &'a str) -> IsResolvableFuture<'a> {
|
||||
Box::pin(async { true })
|
||||
}
|
||||
}
|
||||
|
||||
/// Attachment data supplied to [`AttachmentStore::upload`].
|
||||
#[derive(Clone, Eq, PartialEq)]
|
||||
pub struct UploadRequest {
|
||||
/// Thread receiving this attachment; storage backends may use it for placement.
|
||||
pub thread_id: String,
|
||||
/// Whether the originating thread intentionally skips durable persistence.
|
||||
pub ephemeral: bool,
|
||||
/// Optional name associated with the attachment.
|
||||
pub file_name: Option<String>,
|
||||
/// Caller-supplied tags used by storage backends for policy decisions.
|
||||
pub tags: HashMap<String, String>,
|
||||
/// Attachment bytes to persist.
|
||||
pub data: Vec<u8>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for UploadRequest {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("UploadRequest")
|
||||
.field("thread_id", &self.thread_id)
|
||||
.field("ephemeral", &self.ephemeral)
|
||||
.field("file_name", &self.file_name)
|
||||
.field("tags", &self.tags)
|
||||
.field("data", &"<redacted>")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters supplied to [`AttachmentStore::resolve`].
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ResolveRequest<'a> {
|
||||
/// Identifier assigned by the attachment store.
|
||||
pub file_id: &'a str,
|
||||
/// Caller-supplied tags used by storage backends for policy decisions.
|
||||
pub tags: HashMap<String, String>,
|
||||
/// Minimum remaining lifetime required for the returned file URL.
|
||||
///
|
||||
/// When absent, implementations must omit the file URL and may return cached metadata. When
|
||||
/// present, implementations must return a URL that remains valid for at least this duration
|
||||
/// after the resolve operation completes.
|
||||
pub download_url_ttl: Option<Duration>,
|
||||
}
|
||||
|
||||
/// Metadata used to validate and interpret an attachment.
|
||||
#[derive(Clone, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct AttachmentMetadata {
|
||||
/// Name associated with the attachment.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub file_name: Option<String>,
|
||||
/// MD5 digest of the attachment bytes.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub digest: Option<String>,
|
||||
/// Length of the attachment byte payload.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size_bytes: Option<u64>,
|
||||
/// IANA media type used to interpret the attachment bytes.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mime_type: Option<String>,
|
||||
/// Metadata specific to the attachment's format.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub format_specific: Option<FormatSpecificMetadata>,
|
||||
/// URL for reading the attachment bytes when requested during resolution.
|
||||
///
|
||||
/// Implementations must omit this field when [`ResolveRequest::download_url_ttl`] is absent.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub file_url: Option<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for AttachmentMetadata {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let file_url = self.file_url.as_ref().map(|_| "<redacted>");
|
||||
formatter
|
||||
.debug_struct("AttachmentMetadata")
|
||||
.field("file_name", &self.file_name)
|
||||
.field("digest", &self.digest)
|
||||
.field("size_bytes", &self.size_bytes)
|
||||
.field("mime_type", &self.mime_type)
|
||||
.field("format_specific", &self.format_specific)
|
||||
.field("file_url", &file_url)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata specific to an attachment format.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum FormatSpecificMetadata {
|
||||
/// Metadata for an image attachment.
|
||||
Image(ImageMetadata),
|
||||
/// Metadata for an audio attachment.
|
||||
Audio(AudioMetadata),
|
||||
}
|
||||
|
||||
/// Metadata specific to an image attachment.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct ImageMetadata {
|
||||
/// Image width in pixels.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub width: Option<u32>,
|
||||
/// Image height in pixels.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub height: Option<u32>,
|
||||
}
|
||||
|
||||
/// Metadata specific to an audio attachment.
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct AudioMetadata {
|
||||
/// Measured audio duration in milliseconds, when known by the store.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub duration_ms: Option<u64>,
|
||||
}
|
||||
|
||||
/// Representation callers should retain after uploading an attachment.
|
||||
#[derive(Clone, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub enum UploadResult {
|
||||
/// Attachment data remains inline.
|
||||
Inline {
|
||||
/// Original attachment bytes passed to [`AttachmentStore::upload`].
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
/// Attachment data is available through an external file reference.
|
||||
File {
|
||||
/// Identifier assigned by the attachment store.
|
||||
file_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Debug for UploadResult {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Inline { .. } => formatter
|
||||
.debug_struct("Inline")
|
||||
.field("bytes", &"<redacted>")
|
||||
.finish(),
|
||||
Self::File { file_id } => formatter
|
||||
.debug_struct("File")
|
||||
.field("file_id", file_id)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Leaves attachments inline instead of storing them.
|
||||
pub struct InlineAttachmentStore;
|
||||
|
||||
impl AttachmentStore for InlineAttachmentStore {
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
fn upload(&self, request: UploadRequest) -> UploadFuture<'_> {
|
||||
Box::pin(async move {
|
||||
Ok(UploadResult::Inline {
|
||||
bytes: request.data,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "trace", skip_all)]
|
||||
fn resolve<'a>(&'a self, request: ResolveRequest<'a>) -> ResolveFuture<'a> {
|
||||
let file_id = request.file_id;
|
||||
Box::pin(async move {
|
||||
Err(AttachmentStoreError::new(
|
||||
AttachmentStoreErrorKind::NotFound,
|
||||
format!("attachment `{file_id}` was not found"),
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Category of failure returned by an [`AttachmentStore`].
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum AttachmentStoreErrorKind {
|
||||
/// The requested attachment could not be resolved.
|
||||
NotFound,
|
||||
/// The attachment data or metadata is invalid.
|
||||
InvalidAttachment,
|
||||
/// The backing store could not complete the operation.
|
||||
Backend,
|
||||
}
|
||||
|
||||
/// Error returned by an [`AttachmentStore`] implementation.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct AttachmentStoreError {
|
||||
kind: AttachmentStoreErrorKind,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl AttachmentStoreError {
|
||||
/// Creates an error without exposing backend-specific error types.
|
||||
pub fn new(kind: AttachmentStoreErrorKind, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the category callers can use to handle this error.
|
||||
#[must_use]
|
||||
pub const fn kind(&self) -> AttachmentStoreErrorKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AttachmentStoreError {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.message.fmt(formatter)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for AttachmentStoreError {}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lib_tests.rs"]
|
||||
mod tests;
|
||||
84
akode-rs/attachment-store/src/lib_tests.rs
Normal file
84
akode-rs/attachment-store/src/lib_tests.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Debug output redacts attachment bytes in requests and results.
|
||||
#[test]
|
||||
fn attachment_debug_output_redacts_bytes() {
|
||||
let request = UploadRequest {
|
||||
thread_id: "thread-1".to_string(),
|
||||
ephemeral: false,
|
||||
file_name: Some("image.png".to_string()),
|
||||
tags: HashMap::new(),
|
||||
data: b"secret".to_vec(),
|
||||
};
|
||||
let result = UploadResult::Inline {
|
||||
bytes: b"secret".to_vec(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
(format!("{request:?}"), format!("{result:?}")),
|
||||
(
|
||||
r#"UploadRequest { thread_id: "thread-1", ephemeral: false, file_name: Some("image.png"), tags: {}, data: "<redacted>" }"#.to_string(),
|
||||
r#"Inline { bytes: "<redacted>" }"#.to_string(),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/// Debug output redacts credential-bearing file URLs in resolved metadata.
|
||||
#[test]
|
||||
fn attachment_metadata_debug_output_redacts_file_url() {
|
||||
let metadata = AttachmentMetadata {
|
||||
file_url: Some("https://attachments.test/file?signed=secret".to_string()),
|
||||
..AttachmentMetadata::default()
|
||||
};
|
||||
|
||||
let debug = format!("{metadata:?}");
|
||||
|
||||
assert!(!debug.contains("signed=secret"));
|
||||
assert!(debug.contains("<redacted>"));
|
||||
}
|
||||
|
||||
/// The inline store preserves PNG and JPEG attachment bytes.
|
||||
#[tokio::test]
|
||||
async fn inline_store_preserves_image_bytes() {
|
||||
let cases: [(&str, &[u8]); 2] = [
|
||||
("image.png", b"\x89PNG\r\n\x1a\n"),
|
||||
("image.jpg", b"\xff\xd8\xff\xe0JFIF\x00\xff\xd9"),
|
||||
];
|
||||
|
||||
for (file_name, data) in cases {
|
||||
let attachment = InlineAttachmentStore
|
||||
.upload(UploadRequest {
|
||||
thread_id: "thread-1".to_string(),
|
||||
ephemeral: false,
|
||||
file_name: Some(file_name.to_string()),
|
||||
tags: HashMap::new(),
|
||||
data: data.to_vec(),
|
||||
})
|
||||
.await
|
||||
.expect("inline attachment");
|
||||
let UploadResult::Inline { bytes } = attachment else {
|
||||
panic!("inline store returned a file reference");
|
||||
};
|
||||
|
||||
assert_eq!(bytes, data);
|
||||
}
|
||||
}
|
||||
|
||||
/// The inline store preserves opaque file references even though it cannot resolve them.
|
||||
#[tokio::test]
|
||||
async fn inline_store_cannot_resolve_file_references() {
|
||||
assert!(InlineAttachmentStore.is_resolvable("file_123").await);
|
||||
|
||||
let error = InlineAttachmentStore
|
||||
.resolve(ResolveRequest {
|
||||
file_id: "file_123",
|
||||
tags: HashMap::new(),
|
||||
download_url_ttl: None,
|
||||
})
|
||||
.await
|
||||
.expect_err("inline store cannot resolve file references");
|
||||
|
||||
assert_eq!(error.kind(), AttachmentStoreErrorKind::NotFound);
|
||||
}
|
||||
Reference in New Issue
Block a user