use std::borrow::Cow;
use crate::inference::{ProviderId, ShapeEvidence, classify_model_shape};
const ARN_HEAD: &str = "arn:aws:bedrock:";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArnKind {
ApplicationInferenceProfile,
InferenceProfile,
FoundationModel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BedrockArn<'a> {
pub region: &'a str,
pub kind: ArnKind,
pub name: &'a str,
}
impl<'a> BedrockArn<'a> {
pub fn priced_model(&self) -> Option<&'a str> {
match self.kind {
ArnKind::ApplicationInferenceProfile => None,
ArnKind::InferenceProfile | ArnKind::FoundationModel => Some(self.name),
}
}
}
pub fn parse(id: &str) -> Option<BedrockArn<'_>> {
if !id.starts_with(ARN_HEAD) || id.trim() != id {
return None;
}
if classify_model_shape(id) != Some((ProviderId::Bedrock, ShapeEvidence::Conclusive)) {
return None;
}
let mut fields = id.splitn(6, ':');
let region = fields.nth(3)?;
let resource = fields.nth(1)?;
let (kind, name) = resource.split_once('/')?;
let kind = match kind {
"application-inference-profile" => ArnKind::ApplicationInferenceProfile,
"inference-profile" => ArnKind::InferenceProfile,
"foundation-model" => ArnKind::FoundationModel,
_ => return None,
};
Some(BedrockArn { region, kind, name })
}
pub fn is_unpriced(model: &str) -> bool {
parse(model).is_some_and(|arn| arn.priced_model().is_none())
}
const ACCOUNT_MASK: &str = "****";
pub fn mask_account_ids(text: &str) -> Cow<'_, str> {
let mut out = String::new();
let mut copied = 0;
let mut search = 0;
while let Some(offset) = text[search..].find("arn:") {
let start = search + offset;
search = start + "arn:".len();
if let Some((from, to)) = account_span(&text[start..]) {
out.push_str(&text[copied..start + from]);
out.push_str(ACCOUNT_MASK);
copied = start + to;
search = copied;
}
}
if copied == 0 {
return Cow::Borrowed(text);
}
out.push_str(&text[copied..]);
Cow::Owned(out)
}
fn account_span(arn: &str) -> Option<(usize, usize)> {
let bytes = arn.as_bytes();
let mut i = "arn:".len();
for min_len in [1, 1, 0] {
let start = i;
while bytes
.get(i)
.is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
{
i += 1;
}
if i - start < min_len || bytes.get(i) != Some(&b':') {
return None;
}
i += 1;
}
let end = i + 12;
let account = bytes.get(i..end)?;
(account.iter().all(u8::is_ascii_digit) && bytes.get(end) == Some(&b':')).then_some((i, end))
}
#[cfg(test)]
#[path = "arn_tests.rs"]
mod tests;