Skip to content
Merged
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
35 changes: 30 additions & 5 deletions bt-daemon/src/collections/span_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
attachments::Attachment,
pipeline::live::{Multiplexer, Receiver, Record, SharedOp, BYTE_BUDGET, WINDOW},
translate::{OriginSnapshot, SinkFields, SpanOp, SpanRow, SpanType},
wire::{SessionConfig, SessionRoute},
wire::{BackendAuth, SessionConfig, SessionRoute},
};
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -590,13 +590,38 @@ impl SessionStorage {
.await
}

fn binding(auth: &BackendAuth) -> anyhow::Result<String> {
Ok(serde_json::to_string(&serde_json::json!({
"api_url": auth.api_url.as_deref().unwrap_or("https://api.braintrust.dev"),
"org_id": auth.org_id,
"org_name": auth.org_name,
}))?)
}

/// Validate refreshed credentials without creating or changing a binding.
pub async fn check_binding(&self, route: &str, auth: &BackendAuth) -> anyhow::Result<bool> {
let route = route.to_owned();
let binding = Self::binding(auth)?;
self.run(move |db| {
let previous: Option<String> = db
.query_row("SELECT binding FROM heads WHERE route=?", [route], |row| {
row.get(0)
})
.optional()?
.flatten();
if let Some(previous) = previous {
anyhow::ensure!(previous == binding, BindingChanged);
return Ok(true);
}
Ok(false)
})
.await
}

/// Tokens can change; a durable head's backend and organization cannot.
pub async fn bind(&self, route: &str, config: &SessionConfig) -> anyhow::Result<()> {
let route = route.to_owned();
let binding = serde_json::to_string(&serde_json::json!({
"api_url": config.auth.api_url.as_deref().unwrap_or("https://api.braintrust.dev"),
"org_id":config.auth.org_id,"org_name":config.auth.org_name,
}))?;
let binding = Self::binding(&config.auth)?;
self.write(move |tx| {
let previous: Option<String> =
tx.one("SELECT binding FROM heads WHERE route=?", [&route])?;
Expand Down
11 changes: 2 additions & 9 deletions bt-daemon/src/pipeline/consumer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,6 @@ impl ConsumerOptions {
route.auth.profile_id.is_none() || route.auth.profile_id == lease.selection.profile_id,
"credential refresh changed the pinned profile"
);
anyhow::ensure!(
config.auth.org_id.is_none() || config.auth.org_id == lease.auth.org_id,
"credential refresh changed the pinned organization"
);
anyhow::ensure!(
config.auth.api_url.is_none() || config.auth.api_url == lease.auth.api_url,
"credential refresh changed the pinned backend"
);
config.auth = lease.auth;
Ok(())
}
Expand Down Expand Up @@ -233,7 +225,8 @@ impl Consumer {
if matches!(failure.boundary, Boundary::Credentials) {
if let Err(error) = options.credentials(&mut current).await {
held = Some(Box::new((
Failure::credentials(error.to_string(), attempts),
Failure::credentials(error.to_string(), attempts)
.at(failure.position),
work,
)));
continue;
Expand Down
12 changes: 9 additions & 3 deletions bt-daemon/src/pipeline/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ pub(crate) async fn reconfigure_held(
failure.condition,
super::recovery::Condition::Configuration { .. }
| super::recovery::Condition::Plugin { .. }
) || !held.route.same_destination(&route)
) || failure.is_legacy_binding_mismatch()
|| !held.route.same_destination(&route)
{
return None;
}
Expand Down Expand Up @@ -359,11 +360,13 @@ impl Cursor {
None => return Err(error.into()),
},
};
// Older daemons persisted binding mismatches as settings holds.
// Recheck the binding below even if no settings changed.
if matches!(failure.boundary, Boundary::Completion)
&& self.completed >= failure.through.unwrap_or(failure.position)
{
self.session.set_failure(&self.route, None).await?;
} else {
} else if !failure.is_legacy_binding_mismatch() {
*self.error.lock() = Some(failure.message());
*self.recovery.lock() = Some(failure.info(false));
if matches!(
Expand All @@ -386,7 +389,10 @@ impl Cursor {
if let Err(error) = self.session.bind(&self.route, config).await {
if error.downcast_ref::<BindingChanged>().is_some() {
let failure =
Failure::legacy(error.to_string(), self.completed + 1, config);
Failure::credentials(error.to_string(), 0).at(self.completed + 1);
tracing::warn!(
"trace delivery paused; restore the selected credentials for the original backend and organization"
);
self.session
.set_failure(&self.route, Some(serde_json::to_string(&failure)?))
.await?;
Expand Down
12 changes: 12 additions & 0 deletions bt-daemon/src/pipeline/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,18 @@ impl Failure {
}
failure
}
pub fn is_legacy_binding_mismatch(&self) -> bool {
self.boundary == Boundary::Sink
&& matches!(
self.condition,
Condition::Configuration {
recheck_ms: None,
..
}
)
&& self.reason == crate::collections::BindingChanged.to_string()
}

pub fn legacy(reason: String, position: u64, config: &SessionConfig) -> Self {
Self {
boundary: Boundary::Sink,
Expand Down
28 changes: 20 additions & 8 deletions bt-daemon/src/server/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub(crate) async fn resolve_route_auth(
struct RouteAuthProvider {
provider: Arc<dyn AuthProvider>,
key: DeliveryKey,
storage: Option<SessionStorage>,
states: Arc<tokio::sync::Mutex<HashMap<DeliveryKey, SessionAuthState>>>,
}
#[async_trait::async_trait]
Expand All @@ -48,16 +49,21 @@ impl AuthProvider for RouteAuthProvider {
reason: AuthResolveReason,
) -> anyhow::Result<AuthLease> {
let lease = self.provider.resolve(selection, reason).await?;
let durably_bound = match &self.storage {
Some(storage) => storage.check_binding(&self.key.route, &lease.auth).await?,
None => false,
};
let mut states = self.states.lock().await;
if let Some(state) = states.get_mut(&self.key) {
anyhow::ensure!(
lease.selection == state.lease.selection,
"credential refresh changed the pinned auth selection"
);
anyhow::ensure!(
lease.auth.api_url == state.lease.auth.api_url
&& lease.auth.org_id == state.lease.auth.org_id
&& lease.auth.org_name == state.lease.auth.org_name,
durably_bound
|| (lease.auth.api_url == state.lease.auth.api_url
&& lease.auth.org_id == state.lease.auth.org_id
&& lease.auth.org_name == state.lease.auth.org_name),
"credential refresh changed the pinned backend or organization"
);
state.lease = lease.clone();
Expand All @@ -67,11 +73,16 @@ impl AuthProvider for RouteAuthProvider {
}

impl Daemon {
pub(super) fn route_auth_provider(&self, key: &DeliveryKey) -> Option<Arc<dyn AuthProvider>> {
pub(super) fn route_auth_provider(
&self,
key: &DeliveryKey,
storage: Option<SessionStorage>,
) -> Option<Arc<dyn AuthProvider>> {
self.auth_provider.as_ref().map(|provider| {
Arc::new(RouteAuthProvider {
provider: provider.clone(),
key: key.clone(),
storage,
states: self.session_auth.clone(),
}) as Arc<dyn AuthProvider>
})
Expand Down Expand Up @@ -119,7 +130,7 @@ impl Daemon {
};

let provider = self
.route_auth_provider(&key)
.route_auth_provider(&key, None)
.ok_or_else(|| anyhow::anyhow!("daemon host has no Braintrust auth provider"))?;
let lease = resolve_route_auth(
provider.as_ref(),
Expand Down Expand Up @@ -220,15 +231,16 @@ impl Daemon {
&self,
key: &DeliveryKey,
) -> anyhow::Result<()> {
let Some(provider) = self.route_auth_provider(key) else {
return Ok(());
};
let Some(state) = self.session_auth.lock().await.get(key).cloned() else {
return Ok(());
};
if !lease_is_expiring(&state.lease) {
return Ok(());
}
let storage = self.storage_for(&key.source, &key.session_id).await?;
let Some(provider) = self.route_auth_provider(key, Some(storage)) else {
return Ok(());
};
let selection = state.lease.selection.clone();
let lease = provider
.resolve(&selection, AuthResolveReason::Expiring)
Expand Down
11 changes: 10 additions & 1 deletion bt-daemon/src/server/ingress.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ pub(super) async fn accept_resolved_event(
let session_lock = daemon.dispatch_lock(&source, &session_id);
let _session_guard = session_lock.lock().await;

let result = async {
let result: Result<_, Failure> = async {
let delivery_key = daemon
.configure_event(&mut env)
.await
Expand Down Expand Up @@ -313,6 +313,15 @@ pub(super) async fn accept_resolved_event(
}
tracing::debug!(source, event, session_id, "event accepted")
}
Err(error) if error.boundary == crate::pipeline::recovery::Boundary::Credentials => {
if attempt == 0 {
tracing::warn!(
source,
session_id,
"trace delivery paused; captures are queued locally. Run `bt trace status` for credential recovery instructions"
);
}
}
Err(error) => tracing::warn!(source, event, session_id, %error, "event rejected"),
}
if result.is_ok() && schedule_flush {
Expand Down
3 changes: 2 additions & 1 deletion bt-daemon/src/server/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ impl Daemon {
translation.advance(replay_through).await?;
let _ = translation.barrier().await;
let input = translation.subscribe(&route).await?;
let storage = self.storage_for(&env.source, &env.session_id).await?;
let mut map = self.sessions.lock();
if let Some(s) = map.get(key) {
return Ok(s.clone());
Expand All @@ -126,7 +127,7 @@ impl Daemon {
translation,
input,
route: route.clone(),
auth_provider: self.route_auth_provider(key),
auth_provider: self.route_auth_provider(key, Some(storage)),
session_id: env.session_id.clone(),
source: env.source.clone(),
bt_version: self.version.clone(),
Expand Down
Loading
Loading