use std::sync::Arc;
use std::time::Duration;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use greentic_aw_runtime::door_reqwest as reqwest;
use greentic_aw_runtime::{ArtifactClientError, DoorRetry};
use greentic_ext_runtime::host_ports::{
ArtifactPort, ArtifactPortError, ArtifactPutRequest, HostCallContext,
};
use crate::host::ExtArtifactPort;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
const TOTAL_TIMEOUT: Duration = Duration::from_secs(30);
pub struct HttpArtifactPort {
client: reqwest::Client,
endpoint: String,
token: String,
handle: tokio::runtime::Handle,
door: DoorRetry,
}
impl std::fmt::Debug for HttpArtifactPort {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpArtifactPort")
.field("endpoint", &self.endpoint)
.field("token", &"<redacted>")
.finish()
}
}
impl HttpArtifactPort {
pub fn new(
endpoint: String,
token: String,
handle: tokio::runtime::Handle,
) -> Result<Self, ArtifactClientError> {
if token.trim().is_empty() {
return Err(ArtifactClientError::EmptyToken);
}
if token.chars().any(char::is_control) {
return Err(ArtifactClientError::InvalidToken);
}
let client = reqwest::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.connect_timeout(CONNECT_TIMEOUT)
.timeout(TOTAL_TIMEOUT)
.build()
.map_err(|_| ArtifactClientError::Client)?;
Ok(Self {
client,
endpoint,
token,
handle,
door: DoorRetry::new(),
})
}
}
const MAX_REPLY_BYTES: usize = 16 * 1024;
async fn read_capped(response: reqwest::Response) -> Option<Vec<u8>> {
use futures::StreamExt;
if response
.content_length()
.is_some_and(|n| n > MAX_REPLY_BYTES as u64)
{
return None;
}
let mut body = Vec::new();
let mut stream = response.bytes_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk.ok()?;
if body.len() + chunk.len() > MAX_REPLY_BYTES {
return None;
}
body.extend_from_slice(&chunk);
}
Some(body)
}
#[derive(serde::Deserialize)]
struct PutBody {
id: String,
}
enum PutOutcome {
Refused(u16),
Body(Option<Vec<u8>>),
}
fn unavailable(reason: &str) -> ArtifactPortError {
ArtifactPortError::Unavailable(reason.to_string())
}
fn can_block_here(stored: &tokio::runtime::Handle) -> bool {
use tokio::runtime::RuntimeFlavor::CurrentThread;
let caller_ok = tokio::runtime::Handle::try_current()
.map(|current| current.runtime_flavor() != CurrentThread)
.unwrap_or(true);
caller_ok && stored.runtime_flavor() != CurrentThread
}
impl ArtifactPort for HttpArtifactPort {
fn put(
&self,
extension_id: &str,
ctx: &HostCallContext,
request: ArtifactPutRequest,
) -> Result<String, ArtifactPortError> {
if ctx
.tenant
.as_deref()
.map(str::trim)
.is_none_or(str::is_empty)
{
return Err(unavailable("call carries no tenant"));
}
if !can_block_here(&self.handle) {
return Err(unavailable("artifact put needs a multi-thread runtime"));
}
let Some(url) = greentic_aw_runtime::door_url(&self.endpoint, "put") else {
return Err(unavailable("artifact endpoint is not usable"));
};
let body = serde_json::json!({
"name": request.name,
"mime_type": request.mime_type,
"data_base64": STANDARD.encode(&request.bytes),
"derived_from": null,
"conversation_id": null,
});
let exchange = async {
let reply = self
.door
.send(|| {
self.client
.post(url.clone())
.bearer_auth(&self.token)
.json(&body)
})
.await?;
Ok::<_, greentic_aw_runtime::DoorSendError>(match reply.response.status().as_u16() {
200 => PutOutcome::Body(read_capped(reply.response).await),
other => PutOutcome::Refused(other),
})
};
let outcome = tokio::task::block_in_place(|| self.handle.block_on(exchange))
.map_err(|_| unavailable("artifact door unreachable"))?;
let raw = match outcome {
PutOutcome::Body(raw) => raw,
PutOutcome::Refused(415) => return Err(ArtifactPortError::InvalidMediaType),
PutOutcome::Refused(422) => return Err(ArtifactPortError::QuotaExceeded),
PutOutcome::Refused(other) => {
let reason = match other {
401 => "unauthorized",
403 => "purpose_not_granted",
413 => "too_large",
429 => "rate_limited",
_ => "refused",
};
tracing::debug!(
extension = %extension_id,
status = other,
reason,
"artifact put refused"
);
tracing::warn!(
extension = %extension_id,
status = other,
code = "artifact_put_refused",
"artifact door refused a put"
);
return Err(ArtifactPortError::Unavailable(format!(
"door answered {other}"
)));
}
};
let raw = raw.ok_or_else(|| unavailable("artifact door answered an unreadable body"))?;
let parsed: PutBody = serde_json::from_slice(&raw)
.map_err(|_| unavailable("artifact door answered an unreadable body"))?;
if !greentic_aw_runtime::is_artifact_ref(&parsed.id) {
return Err(unavailable("artifact door answered an invalid id"));
}
Ok(parsed.id)
}
}
pub fn artifact_port_from_env() -> Option<ExtArtifactPort> {
let endpoint = std::env::var("GREENTIC_ARTIFACT_ENDPOINT")
.ok()
.filter(|v| !v.trim().is_empty())?;
let token = std::env::var("GREENTIC_ARTIFACT_TOKEN")
.ok()
.filter(|v| !v.trim().is_empty())?;
let handle = tokio::runtime::Handle::try_current().ok()?;
match HttpArtifactPort::new(endpoint, token, handle) {
Ok(port) => Some(Arc::new(port)),
Err(error) => {
tracing::warn!(
code = "artifact_port_unavailable",
%error,
"artifact port from the environment could not be built; \
host.artifact.put answers unsupported"
);
None
}
}
}
#[cfg(test)]
#[path = "ext_artifact_port_tests.rs"]
mod tests;
#[cfg(test)]
#[path = "ext_artifact_port_dispatch_tests.rs"]
mod dispatch_tests;