use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use base64::Engine as _;
use futures::{SinkExt, StreamExt};
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use tokio::sync::{Mutex, RwLock, mpsc, oneshot, watch};
use tokio_tungstenite::tungstenite::Message;
use crate::model::Execution;
use crate::model::now_ms;
use crate::store::Store;
mod browser;
pub use browser::*;
mod apple_device;
pub use apple_device::*;
mod causal;
pub use causal::*;
pub(crate) mod dap;
mod sourcemap;
pub use dap::*;
mod evidence_trace;
pub use evidence_trace::*;
mod extension;
pub use extension::*;
mod flow;
pub use flow::*;
mod migration;
pub use migration::*;
mod recorder;
pub use recorder::*;
mod rr;
pub use rr::*;
mod tap_watch;
pub use tap_watch::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DebuggerDesiredState {
Open,
Closed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DebuggerAdapterKind {
NodeCdp,
BrowserCdp,
Dap,
Lldb,
Rr,
Extension,
AppleDevice,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerSessionRecord {
pub id: String,
pub adapter: DebuggerAdapterKind,
pub target: String,
#[serde(default)]
pub target_id: Option<String>,
#[serde(default)]
pub host: Option<String>,
#[serde(default)]
pub port: Option<u16>,
pub execution_id: Option<String>,
pub desired_state: DebuggerDesiredState,
pub observed_state: DebuggerSnapshot,
pub created_at: u64,
pub updated_at: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DebuggerMutationState {
Pending,
Applied,
Failed,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerMutationRecord {
pub id: String,
pub idempotency_key: String,
pub operation: String,
pub fingerprint: String,
pub session_id: String,
pub execution_id: Option<String>,
pub state: DebuggerMutationState,
pub result: Option<Value>,
pub error: Option<String>,
pub started_at: u64,
pub completed_at: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerEvent {
pub sequence: u64,
pub id: String,
pub session_id: String,
pub execution_id: Option<String>,
pub at: u64,
pub kind: String,
pub details: Value,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerFrame {
pub id: String,
pub function: String,
pub file: String,
pub line: u64,
pub column: u64,
pub script_id: String,
pub scopes: Vec<DebuggerScope>,
pub this_object_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerScope {
pub kind: String,
pub name: String,
pub object_id: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerAsyncFrame {
pub function: String,
pub file: String,
pub line: u64,
pub column: u64,
pub description: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerScript {
pub id: String,
pub url: String,
pub file: String,
pub start_line: u64,
pub end_line: u64,
pub source_map_url: Option<String>,
pub module: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerConsoleEntry {
pub id: u64,
pub kind: String,
pub text: String,
pub at: f64,
pub stack: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerExceptionEntry {
pub id: u64,
pub text: String,
pub kind: String,
pub file: String,
pub line: u64,
pub at: f64,
pub uncaught: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTraceEntry {
pub sequence: u64,
pub at: u64,
pub direction: String,
pub method: String,
pub request_id: Option<u64>,
pub latency_ms: Option<u64>,
pub error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerBreakpointResolution {
pub backend_id: String,
pub script_id: String,
pub line: u64,
pub column: u64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerHealth {
pub connected_at: Option<u64>,
pub disconnected_at: Option<u64>,
pub requests: u64,
pub responses: u64,
pub events: u64,
pub failures: u64,
pub last_latency_ms: Option<u64>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DebuggerPhase {
Connecting,
Running,
Paused,
Exited,
#[default]
Disconnected,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerSnapshot {
pub phase: DebuggerPhase,
pub connected: bool,
pub paused: bool,
pub reason: Option<String>,
pub frames: Vec<DebuggerFrame>,
pub async_frames: Vec<DebuggerAsyncFrame>,
pub scripts: Vec<DebuggerScript>,
pub console: Vec<DebuggerConsoleEntry>,
pub exceptions: Vec<DebuggerExceptionEntry>,
#[serde(default)]
pub tap_events: Vec<DebuggerTapEvent>,
pub trace: Vec<DebuggerTraceEntry>,
pub health: DebuggerHealth,
#[serde(default)]
pub browser: DebuggerBrowserState,
pub pause_epoch: u64,
pub hit_breakpoints: Vec<String>,
pub breakpoint_resolutions: Vec<DebuggerBreakpointResolution>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerSessionView {
pub id: String,
pub adapter: DebuggerAdapterKind,
pub target_id: Option<String>,
pub target: String,
pub execution_id: Option<String>,
pub state: DebuggerSnapshot,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerBreakpoint {
pub id: String,
pub session_id: String,
pub backend_id: Option<String>,
pub file: String,
pub line: u64,
pub condition: Option<String>,
pub resolved: bool,
pub hits: u64,
pub enabled: bool,
pub created_at: u64,
pub updated_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerEvaluation {
pub kind: String,
pub value: Value,
pub subtype: Option<String>,
pub class_name: Option<String>,
pub description: Option<String>,
pub object_id: Option<String>,
pub unserializable_value: Option<String>,
pub exception: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerRemoteValue {
pub kind: String,
pub subtype: Option<String>,
pub class_name: Option<String>,
pub description: Option<String>,
pub value: Value,
pub object_id: Option<String>,
pub unserializable_value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerProperty {
pub name: String,
pub value: DebuggerRemoteValue,
pub writable: bool,
pub configurable: bool,
pub enumerable: bool,
pub internal: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerVariable {
pub frame: usize,
pub scope: String,
pub property: DebuggerProperty,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerSource {
pub script_id: String,
pub file: String,
pub source_map_url: Option<String>,
pub from_line: u64,
pub to_line: u64,
pub lines: Vec<String>,
pub mapped_sources: Vec<DebuggerMappedSource>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerMappedSource {
pub source: String,
pub content: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerListener {
pub object_id: String,
pub kind: String,
pub handler: String,
pub once: bool,
pub use_capture: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerPrototype {
pub depth: usize,
pub object_id: String,
pub properties: Vec<DebuggerProperty>,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTarget {
pub id: String,
pub kind: String,
pub title: String,
pub url: String,
pub websocket_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerRunResult {
pub execution: Execution,
pub session: DebuggerSessionView,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerSelection {
pub actor: String,
pub session_id: String,
pub updated_at: u64,
}
#[derive(Debug)]
enum ActorCommand {
Send {
method: String,
params: Value,
reply: oneshot::Sender<Result<Value, String>>,
},
Close {
reply: oneshot::Sender<()>,
},
BrowserState {
browser: DebuggerBrowserState,
reply: oneshot::Sender<()>,
},
}
#[derive(Debug)]
struct PendingRequest {
method: String,
sent_at: u64,
reply: oneshot::Sender<Result<Value, String>>,
}
#[derive(Debug)]
struct DebuggerSession {
id: String,
adapter: DebuggerAdapterKind,
target_id: Option<String>,
target: String,
execution_id: Option<String>,
commands: mpsc::UnboundedSender<ActorCommand>,
state: watch::Receiver<DebuggerSnapshot>,
}
struct OpenWebsocketRequest {
id: String,
ws_url: String,
execution_id: Option<String>,
host: Option<String>,
port: Option<u16>,
target_id: Option<String>,
adapter: DebuggerAdapterKind,
}
impl DebuggerSession {
fn view(&self) -> DebuggerSessionView {
DebuggerSessionView {
id: self.id.clone(),
adapter: self.adapter,
target_id: self.target_id.clone(),
target: self.target.clone(),
execution_id: self.execution_id.clone(),
state: self.state.borrow().clone(),
}
}
async fn send(&self, method: &str, params: Value) -> Result<Value, String> {
let (reply, response) = oneshot::channel();
self.commands
.send(ActorCommand::Send {
method: method.to_string(),
params,
reply,
})
.map_err(|_| format!("Debugger session \"{}\" is disconnected", self.id))?;
tokio::time::timeout(Duration::from_secs(10), response)
.await
.map_err(|_| format!("Timed out calling {method}"))?
.map_err(|_| format!("Debugger session \"{}\" stopped", self.id))?
}
async fn wait_for_pause(&self, after: u64, timeout: Duration) -> Result<(), String> {
let mut state = self.state.clone();
tokio::time::timeout(timeout, async move {
loop {
let current = state.borrow().clone();
if current.pause_epoch > after && current.paused {
return Ok(());
}
if !current.connected {
return Ok(());
}
state
.changed()
.await
.map_err(|_| "Debugger state channel closed".to_string())?;
}
})
.await
.map_err(|_| "Timed out waiting for debugger pause".to_string())?
}
async fn wait_for_running(&self, timeout: Duration) -> Result<(), String> {
let mut state = self.state.clone();
tokio::time::timeout(timeout, async move {
loop {
let current = state.borrow().clone();
if !current.paused || !current.connected {
return Ok(());
}
state
.changed()
.await
.map_err(|_| "Debugger state channel closed".to_string())?;
}
})
.await
.map_err(|_| "Timed out waiting for debugger resume".to_string())?
}
}
#[derive(Clone)]
pub struct DebuggerManager {
store: Arc<Store>,
sessions: Arc<RwLock<HashMap<String, Arc<DebuggerSession>>>>,
dap_sessions: Arc<RwLock<HashMap<String, Arc<DapSession>>>>,
mutation_locks: Arc<Mutex<HashMap<String, Arc<Mutex<()>>>>>,
recording_tasks: Arc<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>>,
recording_capture_locks: Arc<Mutex<HashMap<String, Arc<Mutex<()>>>>>,
flow_tasks: Arc<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>>,
watch_tasks: Arc<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>>,
}
impl DebuggerManager {
pub fn new(store: Arc<Store>) -> Self {
Self {
store,
sessions: Arc::new(RwLock::new(HashMap::new())),
dap_sessions: Arc::new(RwLock::new(HashMap::new())),
mutation_locks: Arc::new(Mutex::new(HashMap::new())),
recording_tasks: Arc::new(Mutex::new(HashMap::new())),
recording_capture_locks: Arc::new(Mutex::new(HashMap::new())),
flow_tasks: Arc::new(Mutex::new(HashMap::new())),
watch_tasks: Arc::new(Mutex::new(HashMap::new())),
}
}
pub async fn mutation<T, F, Fut>(
&self,
key: String,
operation: &str,
material: Value,
action: F,
) -> Result<T, String>
where
T: Serialize + DeserializeOwned,
F: FnOnce() -> Fut,
Fut: Future<Output = Result<T, String>>,
{
if key.is_empty() {
return Err(format!("{operation} requires idempotency_key"));
}
let session_id = material
.get("id")
.and_then(Value::as_str)
.ok_or_else(|| format!("{operation} requires a debugger session id"))?
.to_string();
let lock = {
let mut locks = self.mutation_locks.lock().await;
locks
.entry(session_id.clone())
.or_insert_with(|| Arc::new(Mutex::new(())))
.clone()
};
let _guard = lock.lock().await;
let encoded =
serde_json::to_vec(&(operation, material)).map_err(|error| error.to_string())?;
let fingerprint = format!("sha256:{:x}", Sha256::digest(encoded));
let started_at = now_ms();
let mut record = DebuggerMutationRecord {
id: uuid::Uuid::now_v7().to_string(),
idempotency_key: key.clone(),
operation: operation.to_string(),
fingerprint: fingerprint.clone(),
session_id: session_id.clone(),
execution_id: self
.store
.debugger_session(&session_id)?
.and_then(|session| session.execution_id),
state: DebuggerMutationState::Pending,
result: None,
error: None,
started_at,
completed_at: None,
};
match self.store.claim_debugger_mutation(&record)? {
crate::store::DebuggerMutationClaim::Replayed(replay) => {
if replay.operation != operation || replay.fingerprint != fingerprint {
return Err(format!(
"Debugger idempotency key \"{key}\" was already used for a different mutation"
));
}
return match replay.state {
DebuggerMutationState::Applied => replay
.result
.ok_or_else(|| {
format!(
"Debugger mutation receipt \"{}\" has no applied result",
replay.id
)
})
.and_then(|value| {
serde_json::from_value(value).map_err(|error| error.to_string())
}),
DebuggerMutationState::Failed => Err(replay
.error
.unwrap_or_else(|| "Debugger mutation failed".to_string())),
DebuggerMutationState::Pending | DebuggerMutationState::Unknown => {
Err(replay.error.unwrap_or_else(|| {
format!(
"Debugger mutation receipt \"{}\" has an unknown external result",
replay.id
)
}))
}
};
}
crate::store::DebuggerMutationClaim::Claimed => {}
}
self.store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id: session_id.clone(),
execution_id: record.execution_id.clone(),
at: started_at,
kind: format!("{operation}.intent"),
details: json!({"receipt_id": record.id, "idempotency_key": key}),
})?;
let result = action()
.await
.and_then(|value| serde_json::to_value(value).map_err(|error| error.to_string()));
record.completed_at = Some(now_ms());
match &result {
Ok(value) => {
record.state = DebuggerMutationState::Applied;
record.result = Some(value.clone());
}
Err(error) => {
record.state = DebuggerMutationState::Failed;
record.error = Some(error.clone());
}
}
if let Err(error) = self.store.put_debugger_mutation(&record) {
record.state = DebuggerMutationState::Unknown;
record.result = None;
record.error = Some(format!(
"Debugger mutation reached the adapter but its terminal result could not be persisted: {error}"
));
let _ = self.store.put_debugger_mutation(&record);
return Err(record.error.expect("unknown debugger receipt has an error"));
}
self.store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id,
execution_id: record.execution_id.clone(),
at: record.completed_at.expect("debugger mutation completed"),
kind: format!("{operation}.result"),
details: json!({"receipt_id": record.id, "state": record.state}),
})?;
result.and_then(|value| serde_json::from_value(value).map_err(|error| error.to_string()))
}
pub async fn open(
&self,
id: String,
host: String,
port: u16,
target_id: Option<String>,
execution_id: Option<String>,
) -> Result<DebuggerSessionView, String> {
if self.sessions.read().await.contains_key(&id) {
return Err(format!("Debugger session \"{id}\" already exists"));
}
let target = discover_target(&host, port, target_id.as_deref()).await?;
let adapter = if target.kind == "page" {
DebuggerAdapterKind::BrowserCdp
} else {
DebuggerAdapterKind::NodeCdp
};
self.open_websocket_at(OpenWebsocketRequest {
id,
ws_url: target.websocket_url,
execution_id,
host: Some(host),
port: Some(port),
target_id: Some(target.id),
adapter,
})
.await
}
pub async fn open_websocket(
&self,
id: String,
ws_url: String,
execution_id: Option<String>,
) -> Result<DebuggerSessionView, String> {
self.open_websocket_at(OpenWebsocketRequest {
id,
ws_url: ws_url.to_string(),
execution_id,
host: None,
port: None,
target_id: None,
adapter: DebuggerAdapterKind::NodeCdp,
})
.await
}
async fn open_websocket_at(
&self,
request: OpenWebsocketRequest,
) -> Result<DebuggerSessionView, String> {
let OpenWebsocketRequest {
id,
ws_url,
execution_id,
host,
port,
target_id,
adapter,
} = request;
if self.sessions.read().await.contains_key(&id) {
return Err(format!("Debugger session \"{id}\" already exists"));
}
let now = now_ms();
let existing = self.store.debugger_session(&id)?;
let mut observed_state = existing
.as_ref()
.map(|session| session.observed_state.clone())
.unwrap_or_default();
observed_state.phase = DebuggerPhase::Connecting;
observed_state.connected = false;
observed_state.paused = false;
observed_state.frames.clear();
observed_state.async_frames.clear();
observed_state.hit_breakpoints.clear();
observed_state.error = Some("Debugger connection is starting".to_string());
let mut record = DebuggerSessionRecord {
id: id.clone(),
adapter,
target: ws_url.clone(),
target_id: target_id.or_else(|| {
existing
.as_ref()
.and_then(|session| session.target_id.clone())
}),
host: host.or_else(|| existing.as_ref().and_then(|session| session.host.clone())),
port: port.or_else(|| existing.as_ref().and_then(|session| session.port)),
execution_id: execution_id.clone().or_else(|| {
existing
.as_ref()
.and_then(|session| session.execution_id.clone())
}),
desired_state: DebuggerDesiredState::Open,
observed_state,
created_at: existing.as_ref().map_or(now, |session| session.created_at),
updated_at: now,
};
self.store.put_debugger_session(&record)?;
let (socket, _) = match tokio_tungstenite::connect_async(&ws_url).await {
Ok(connection) => connection,
Err(error) => {
record.observed_state.error =
Some(format!("Failed to connect to debugger target: {error}"));
record.updated_at = now_ms();
self.store.put_debugger_session(&record)?;
return Err(record
.observed_state
.error
.clone()
.expect("failed debugger connection has an error"));
}
};
let (commands, receiver) = mpsc::unbounded_channel();
let mut initial_state = record.observed_state.clone();
initial_state.phase = DebuggerPhase::Running;
initial_state.connected = true;
initial_state.error = None;
initial_state.health.connected_at = Some(now_ms());
initial_state.health.disconnected_at = None;
let (state_tx, state_rx) = watch::channel(initial_state);
tokio::spawn(debugger_actor(socket, receiver, state_tx));
let session = Arc::new(DebuggerSession {
id: id.clone(),
adapter,
target_id: record.target_id.clone(),
target: ws_url,
execution_id: record.execution_id.clone(),
commands,
state: state_rx,
});
session.send("Debugger.enable", json!({})).await?;
session
.send("Debugger.setAsyncCallStackDepth", json!({"maxDepth": 32}))
.await?;
session.send("Runtime.enable", json!({})).await?;
let _ = session
.send(
"Debugger.setBlackboxPatterns",
json!({"patterns": STEP_BLACKBOX_PATTERNS}),
)
.await;
let _ = session
.send("Runtime.runIfWaitingForDebugger", json!({}))
.await;
self.sessions.write().await.insert(id, session.clone());
if adapter == DebuggerAdapterKind::BrowserCdp {
self.initialize_browser_session(&session).await?;
}
record.observed_state = session.state.borrow().clone();
record.updated_at = now_ms();
self.store.put_debugger_session(&record)?;
self.restore_breakpoints(&session).await?;
self.restore_taps(&session).await?;
self.spawn_state_persistence(session.clone());
self.resume_recording_worker(&session.id).await;
self.resume_flow_worker(&session.id).await;
self.resume_watch_worker(&session.id).await;
Ok(session.view())
}
fn spawn_state_persistence(&self, session: Arc<DebuggerSession>) {
let store = self.store.clone();
tokio::spawn(async move {
let mut state = session.state.clone();
let mut last_phase = None;
let mut last_pause_epoch = 0;
let mut last_tap_sequence = state
.borrow()
.tap_events
.last()
.map_or(0, |event| event.sequence);
while state.changed().await.is_ok() {
coalesce_changes(&mut state, PERSIST_DEBOUNCE).await;
let snapshot = state.borrow().clone();
let new_tap_events = snapshot
.tap_events
.iter()
.filter(|event| event.sequence > last_tap_sequence)
.cloned()
.collect::<Vec<_>>();
for event in new_tap_events {
let hit = DebuggerTapHit {
id: event.id,
tap_id: event.tap_id,
session_id: session.id.clone(),
at: event.at,
value: event.value,
};
if store.record_debugger_tap_hit(&hit).is_err() {
return;
}
last_tap_sequence = event.sequence;
}
let Ok(Some(mut record)) = store.debugger_session(&session.id) else {
break;
};
record.observed_state = snapshot.clone();
record.updated_at = now_ms();
if store.put_debugger_session(&record).is_err() {
break;
}
if snapshot.paused
&& !snapshot.hit_breakpoints.is_empty()
&& let Ok(breakpoints) = store.debugger_breakpoints(&session.id)
{
for mut breakpoint in breakpoints {
if breakpoint
.backend_id
.as_ref()
.is_some_and(|id| snapshot.hit_breakpoints.contains(id))
{
breakpoint.hits = breakpoint.hits.saturating_add(1);
breakpoint.resolved = true;
breakpoint.updated_at = record.updated_at;
let _ = store.put_debugger_breakpoint(&breakpoint);
}
}
}
if !snapshot.breakpoint_resolutions.is_empty()
&& let Ok(breakpoints) = store.debugger_breakpoints(&session.id)
{
for mut breakpoint in breakpoints {
if let Some(resolution) =
snapshot.breakpoint_resolutions.iter().find(|resolution| {
breakpoint.backend_id.as_deref()
== Some(resolution.backend_id.as_str())
})
{
breakpoint.resolved = true;
breakpoint.line = resolution.line;
breakpoint.updated_at = record.updated_at;
let _ = store.put_debugger_breakpoint(&breakpoint);
}
}
}
if !snapshot.breakpoint_resolutions.is_empty()
&& let Ok(taps) = store.debugger_taps(&session.id)
{
for mut tap in taps {
if let Some(resolution) =
snapshot.breakpoint_resolutions.iter().find(|resolution| {
tap.backend_id.as_deref() == Some(resolution.backend_id.as_str())
})
{
tap.resolved = true;
tap.line = resolution.line;
tap.updated_at = record.updated_at;
let _ = store.put_debugger_tap(&tap);
}
}
}
if last_phase != Some(snapshot.phase)
|| (snapshot.paused && last_pause_epoch != snapshot.pause_epoch)
{
let kind = match snapshot.phase {
DebuggerPhase::Connecting => "debugger.connecting",
DebuggerPhase::Running => "debugger.running",
DebuggerPhase::Paused => "debugger.paused",
DebuggerPhase::Exited => "debugger.exited",
DebuggerPhase::Disconnected => "debugger.disconnected",
};
let _ = store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id: session.id.clone(),
execution_id: session.execution_id.clone(),
at: record.updated_at,
kind: kind.to_string(),
details: json!({
"reason": snapshot.reason,
"pause_epoch": snapshot.pause_epoch,
"error": snapshot.error
}),
});
last_phase = Some(snapshot.phase);
last_pause_epoch = snapshot.pause_epoch;
}
if !snapshot.connected {
break;
}
}
});
}
async fn restore_breakpoints(&self, session: &Arc<DebuggerSession>) -> Result<(), String> {
for mut breakpoint in self.store.debugger_breakpoints(&session.id)? {
if !breakpoint.enabled {
continue;
}
let result = session
.send(
"Debugger.setBreakpointByUrl",
breakpoint_params(
&breakpoint.file,
breakpoint.line,
breakpoint.condition.clone(),
)?,
)
.await?;
breakpoint.backend_id = result
.get("breakpointId")
.and_then(Value::as_str)
.map(ToString::to_string);
breakpoint.resolved = result
.get("locations")
.and_then(Value::as_array)
.is_some_and(|locations| !locations.is_empty());
breakpoint.updated_at = now_ms();
self.store.put_debugger_breakpoint(&breakpoint)?;
}
Ok(())
}
pub async fn recover(&self) -> Result<(), String> {
let recovered = self.store.recover_debugger_mutations()?;
for mutation in recovered {
self.store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id: mutation.session_id,
execution_id: mutation.execution_id,
at: now_ms(),
kind: "debugger.mutation.unknown".to_string(),
details: json!({"receipt_id": mutation.id, "operation": mutation.operation}),
})?;
}
for mut session in self.store.debugger_sessions()? {
if session.desired_state != DebuggerDesiredState::Open {
continue;
}
if matches!(
session.adapter,
DebuggerAdapterKind::Dap | DebuggerAdapterKind::Lldb
) {
session.observed_state.phase = DebuggerPhase::Disconnected;
session.observed_state.connected = false;
session.observed_state.paused = false;
session.observed_state.error = Some(
"DAP stdio transport cannot reconnect after daemon restart; launch or attach a new adapter session"
.to_string(),
);
session.updated_at = now_ms();
self.store.put_debugger_session(&session)?;
self.store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id: session.id,
execution_id: session.execution_id,
at: session.updated_at,
kind: "debugger.dap.disconnected".to_string(),
details: json!({"reason":"daemon_restart"}),
})?;
continue;
}
if !matches!(
session.adapter,
DebuggerAdapterKind::NodeCdp | DebuggerAdapterKind::BrowserCdp
) {
continue;
}
let reconnect = if let (Some(host), Some(port)) = (session.host.clone(), session.port) {
self.open(
session.id.clone(),
host,
port,
session.target_id.clone(),
session.execution_id.clone(),
)
.await
} else {
self.open_websocket(
session.id.clone(),
session.target.clone(),
session.execution_id.clone(),
)
.await
};
if let Err(error) = reconnect {
self.store.append_debugger_event(DebuggerEvent {
sequence: 0,
id: uuid::Uuid::now_v7().to_string(),
session_id: session.id,
execution_id: session.execution_id,
at: now_ms(),
kind: "debugger.reconnect.failed".to_string(),
details: json!({"error": error}),
})?;
}
}
Ok(())
}
async fn session(&self, id: &str) -> Result<Arc<DebuggerSession>, String> {
if let Some(session) = self.sessions.read().await.get(id).cloned() {
return Ok(session);
}
if self.dap_sessions.read().await.contains_key(id) {
return Err(format!(
"Debugger session \"{id}\" is a native session; this operation needs a JavaScript runtime session"
));
}
Err(format!("Debugger session \"{id}\" not found"))
}
pub async fn status(&self, id: &str) -> Result<DebuggerSessionView, String> {
if self.dap_sessions.read().await.contains_key(id) {
return Ok(self.dap_state(id).await?.view);
}
if let Some(session) = self.sessions.read().await.get(id).cloned() {
let mut view = session.view();
self.apply_execution_phase(&mut view)?;
return Ok(view);
}
let record = self
.store
.debugger_session(id)?
.ok_or_else(|| format!("Debugger session \"{id}\" not found"))?;
let mut view = DebuggerSessionView {
id: record.id,
adapter: record.adapter,
target_id: record.target_id,
target: record.target,
execution_id: record.execution_id,
state: record.observed_state,
};
self.apply_execution_phase(&mut view)?;
Ok(view)
}
fn apply_execution_phase(&self, view: &mut DebuggerSessionView) -> Result<(), String> {
let recovery_disconnected = view.state.phase == DebuggerPhase::Disconnected
&& view
.state
.error
.as_deref()
.is_some_and(|error| error.contains("cannot reconnect after daemon restart"));
if !recovery_disconnected
&& let Some(execution_id) = view.execution_id.as_deref()
&& let Some(execution) = self.store.get_execution_record(execution_id)?
&& matches!(
execution.status,
crate::model::ExecutionStatus::Completed
| crate::model::ExecutionStatus::Failed
| crate::model::ExecutionStatus::Canceled
)
{
view.state.phase = DebuggerPhase::Exited;
view.state.connected = false;
view.state.paused = false;
}
Ok(())
}
pub fn list(&self) -> Result<Vec<DebuggerSessionRecord>, String> {
self.store.debugger_sessions()
}
pub fn record(&self, id: &str) -> Result<DebuggerSessionRecord, String> {
self.store
.debugger_session(id)?
.ok_or_else(|| format!("Debugger session \"{id}\" not found"))
}
pub fn select(&self, actor: String, id: &str) -> Result<DebuggerSelection, String> {
self.record(id)?;
let selection = DebuggerSelection {
actor,
session_id: id.to_string(),
updated_at: now_ms(),
};
self.store.put_debugger_selection(&selection)?;
Ok(selection)
}
pub fn selected(&self, actor: &str) -> Result<Option<DebuggerSelection>, String> {
self.store.debugger_selection(actor)
}
pub fn events(&self, id: &str, after: u64, limit: usize) -> Result<Vec<DebuggerEvent>, String> {
self.store.debugger_events(id, after, limit)
}
pub async fn stack(&self, id: &str) -> Result<Vec<DebuggerFrame>, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_stack(id).await;
}
Ok(self.session(id).await?.state.borrow().frames.clone())
}
pub async fn pause(&self, id: &str, timeout: Duration) -> Result<DebuggerSessionView, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_pause(id, timeout).await;
}
let session = self.session(id).await?;
let state = session.state.borrow().clone();
if state.paused {
return self.status(id).await;
}
session.send("Debugger.pause", json!({})).await?;
session.wait_for_pause(state.pause_epoch, timeout).await?;
self.status(id).await
}
pub async fn resume(&self, id: &str) -> Result<DebuggerSessionView, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_resume(id).await;
}
let session = self.session(id).await?;
if !session.state.borrow().paused {
return Err("Debugger is not paused".to_string());
}
session.send("Debugger.resume", json!({})).await?;
session.wait_for_running(Duration::from_secs(10)).await?;
self.status(id).await
}
pub async fn continue_to_pause(
&self,
id: &str,
timeout: Duration,
) -> Result<DebuggerSessionView, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_continue_to_pause(id, timeout).await;
}
let session = self.session(id).await?;
let state = session.state.borrow().clone();
if !state.paused {
return Err("Debugger is not paused".to_string());
}
session.send("Debugger.resume", json!({})).await?;
session.wait_for_pause(state.pause_epoch, timeout).await?;
self.status(id).await
}
pub async fn step(
&self,
id: &str,
kind: &str,
timeout: Duration,
) -> Result<DebuggerSessionView, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_step(id, kind, timeout).await;
}
let session = self.session(id).await?;
let state = session.state.borrow().clone();
if !state.paused {
return Err("Debugger is not paused".to_string());
}
let method = match kind {
"over" => "Debugger.stepOver",
"into" => "Debugger.stepInto",
"out" => "Debugger.stepOut",
other => return Err(format!("Unknown debugger step kind \"{other}\"")),
};
session.send(method, json!({})).await?;
let mut epoch = state.pause_epoch;
session.wait_for_pause(epoch, timeout).await?;
for _ in 0..STEP_SKIP_LIMIT {
let current = session.state.borrow().clone();
if !current.paused {
break;
}
let Some(frame) = current.frames.first() else {
break;
};
let frame_origin = |frame: &DebuggerFrame| {
current
.scripts
.iter()
.find(|script| script.id == frame.script_id)
.map(|script| script.url.clone())
.unwrap_or_else(|| frame.file.clone())
};
if !is_step_skipped(&frame_origin(frame)) {
break;
}
if current
.frames
.iter()
.all(|frame| is_step_skipped(&frame_origin(frame)))
{
break;
}
epoch = current.pause_epoch;
session.send("Debugger.stepOut", json!({})).await?;
session.wait_for_pause(epoch, timeout).await?;
}
self.status(id).await
}
async fn generated_location(
&self,
session: &Arc<DebuggerSession>,
file: &str,
line: u64,
) -> Option<(String, u64)> {
let scripts = session.state.borrow().scripts.clone();
let names_file =
|candidate: &str| !candidate.is_empty() && source_paths_match(candidate, file);
if scripts
.iter()
.any(|script| names_file(&script.file) || names_file(&script.url))
{
return None;
}
for script in scripts
.iter()
.filter(|script| script.source_map_url.is_some())
{
let Some(map) = load_source_map(script) else {
continue;
};
if let Some(generated) = sourcemap::generated_line_for(&map, file, line) {
return Some((script.url.clone(), generated));
}
}
None
}
pub async fn set_breakpoint(
&self,
id: &str,
file: String,
line: u64,
condition: Option<String>,
) -> Result<DebuggerBreakpoint, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_set_breakpoint(id, file, line, condition).await;
}
let session = self.session(id).await?;
let (request_file, request_line) = self
.generated_location(&session, &file, line)
.await
.unwrap_or_else(|| (file.clone(), line));
let params = breakpoint_params(&request_file, request_line, condition.clone())?;
let result = session.send("Debugger.setBreakpointByUrl", params).await?;
let backend_id = result
.get("breakpointId")
.and_then(Value::as_str)
.ok_or_else(|| "Debugger returned no breakpointId".to_string())?;
let translated = request_file != file;
let actual = if translated {
line
} else {
result
.get("locations")
.and_then(Value::as_array)
.and_then(|locations| locations.first())
.and_then(|location| location.get("lineNumber"))
.and_then(Value::as_u64)
.map(|value| value + 1)
.unwrap_or(line)
};
let now = now_ms();
let breakpoint = DebuggerBreakpoint {
id: uuid::Uuid::now_v7().to_string(),
session_id: id.to_string(),
backend_id: Some(backend_id.to_string()),
file,
line: actual,
condition,
resolved: result
.get("locations")
.and_then(Value::as_array)
.is_some_and(|locations| !locations.is_empty()),
hits: 0,
enabled: true,
created_at: now,
updated_at: now,
};
self.store.put_debugger_breakpoint(&breakpoint)?;
Ok(breakpoint)
}
pub fn list_breakpoints(&self, id: &str) -> Result<Vec<DebuggerBreakpoint>, String> {
self.store.debugger_breakpoints(id)
}
pub async fn delete_breakpoint(
&self,
id: &str,
breakpoint_id: &str,
) -> Result<DebuggerBreakpoint, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_delete_breakpoint(id, breakpoint_id).await;
}
let session = self.session(id).await?;
let breakpoint = self
.store
.debugger_breakpoint(breakpoint_id)?
.ok_or_else(|| format!("Debugger breakpoint \"{breakpoint_id}\" not found"))?;
if breakpoint.session_id != id {
return Err(format!(
"Debugger breakpoint \"{breakpoint_id}\" does not belong to session \"{id}\""
));
}
if let Some(backend_id) = breakpoint.backend_id.as_deref() {
session
.send(
"Debugger.removeBreakpoint",
json!({"breakpointId": backend_id}),
)
.await?;
}
self.store.delete_debugger_breakpoint(breakpoint_id)?;
Ok(breakpoint)
}
pub async fn evaluate(
&self,
id: &str,
expression: String,
frame: usize,
) -> Result<DebuggerEvaluation, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_evaluate(id, expression, frame).await;
}
let session = self.session(id).await?;
let state = session.state.borrow().clone();
let result = if state.paused {
let frame = state
.frames
.get(frame)
.ok_or_else(|| format!("Debugger frame {frame} not found"))?;
session
.send(
"Debugger.evaluateOnCallFrame",
json!({
"callFrameId": frame.id,
"expression": expression,
"returnByValue": false,
"generatePreview": true,
"awaitPromise": true
}),
)
.await?
} else {
session
.send(
"Runtime.evaluate",
json!({
"expression": expression,
"returnByValue": false,
"generatePreview": true,
"awaitPromise": true
}),
)
.await?
};
let remote = result
.get("result")
.ok_or_else(|| "Debugger evaluation returned no result".to_string())?;
let value = remote_value(remote);
Ok(DebuggerEvaluation {
kind: value.kind,
value: value.value,
subtype: value.subtype,
class_name: value.class_name,
description: value.description,
object_id: value.object_id,
unserializable_value: value.unserializable_value,
exception: result.get("exceptionDetails").cloned(),
})
}
pub async fn properties(
&self,
id: &str,
object_id: &str,
) -> Result<Vec<DebuggerProperty>, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_properties(id, object_id).await;
}
let session = self.session(id).await?;
let result = session
.send(
"Runtime.getProperties",
json!({
"objectId": object_id,
"ownProperties": true,
"accessorPropertiesOnly": false,
"generatePreview": true
}),
)
.await?;
Ok(parse_properties(&result))
}
pub async fn listeners(
&self,
id: &str,
object_id: &str,
) -> Result<Vec<DebuggerListener>, String> {
let session = self.session(id).await?;
let result = session
.send(
"DOMDebugger.getEventListeners",
json!({"objectId": object_id}),
)
.await?;
Ok(result
.get("listeners")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|listener| DebuggerListener {
object_id: object_id.to_string(),
kind: listener
.get("type")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
handler: listener
.pointer("/handler/description")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
once: listener
.get("once")
.and_then(Value::as_bool)
.unwrap_or(false),
use_capture: listener
.get("useCapture")
.and_then(Value::as_bool)
.unwrap_or(false),
})
.collect())
}
pub async fn prototypes(
&self,
id: &str,
object_id: &str,
limit: usize,
) -> Result<Vec<DebuggerPrototype>, String> {
let mut current = object_id.to_string();
let mut prototypes = Vec::new();
for depth in 0..limit.clamp(1, 32) {
let properties = self.properties(id, ¤t).await?;
let next = properties
.iter()
.find(|property| property.internal && property.name == "[[Prototype]]")
.and_then(|property| property.value.object_id.clone());
prototypes.push(DebuggerPrototype {
depth,
object_id: current,
properties,
});
let Some(next) = next else {
break;
};
current = next;
}
Ok(prototypes)
}
pub async fn variables(&self, id: &str, frame: usize) -> Result<Vec<DebuggerVariable>, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_variables(id, frame).await;
}
let session = self.session(id).await?;
let snapshot = session.state.borrow().clone();
let frame_state = snapshot
.frames
.get(frame)
.ok_or_else(|| format!("Debugger frame {frame} not found"))?;
let mut variables = Vec::new();
for scope in &frame_state.scopes {
if scope.object_id.is_empty() {
continue;
}
for property in self.properties(id, &scope.object_id).await? {
variables.push(DebuggerVariable {
frame,
scope: scope.kind.clone(),
property,
});
}
}
Ok(variables)
}
pub async fn this_properties(
&self,
id: &str,
frame: usize,
) -> Result<Vec<DebuggerProperty>, String> {
let session = self.session(id).await?;
let object_id = session
.state
.borrow()
.frames
.get(frame)
.and_then(|frame| frame.this_object_id.clone())
.ok_or_else(|| format!("Debugger frame {frame} has no object identity for this"))?;
self.properties(id, &object_id).await
}
pub async fn source(
&self,
id: &str,
script_id: Option<&str>,
file: Option<&str>,
from_line: Option<u64>,
to_line: Option<u64>,
) -> Result<DebuggerSource, String> {
if self.dap_session_if_present(id).await.is_some() {
return self.dap_source(id, file, from_line, to_line).await;
}
let session = self.session(id).await?;
let snapshot = session.state.borrow().clone();
let script = if let Some(script_id) = script_id {
snapshot
.scripts
.iter()
.find(|script| script.id == script_id)
} else if let Some(file) = file {
snapshot
.scripts
.iter()
.find(|script| script.file == file || script.url.ends_with(file))
} else {
snapshot.frames.first().and_then(|frame| {
snapshot
.scripts
.iter()
.find(|script| script.id == frame.script_id)
})
}
.ok_or_else(|| "No matching debugger script was found".to_string())?
.clone();
let result = session
.send("Debugger.getScriptSource", json!({"scriptId": script.id}))
.await?;
let lines = result
.get("scriptSource")
.and_then(Value::as_str)
.ok_or_else(|| "Debugger returned no script source".to_string())?
.split('\n')
.map(ToString::to_string)
.collect::<Vec<_>>();
let from_line = from_line.unwrap_or(1).max(1);
let to_line = to_line
.unwrap_or_else(|| from_line.saturating_add(499))
.max(from_line)
.min(from_line.saturating_add(499))
.min(lines.len() as u64);
let selected = if from_line > lines.len() as u64 {
Vec::new()
} else {
lines[(from_line - 1) as usize..to_line as usize].to_vec()
};
let mapped_sources = mapped_sources(&script);
Ok(DebuggerSource {
script_id: script.id,
file: script.file,
source_map_url: script.source_map_url,
from_line,
to_line,
lines: selected,
mapped_sources,
})
}
async fn dap_source(
&self,
id: &str,
file: Option<&str>,
from_line: Option<u64>,
to_line: Option<u64>,
) -> Result<DebuggerSource, String> {
let snapshot = self.dap_session(id).await?.observed();
let frame = snapshot.frames.first();
let path = match file {
Some(file) => file.to_string(),
None => frame
.map(|frame| frame.file.clone())
.filter(|file| !file.is_empty())
.ok_or_else(|| "No paused native frame names a source file".to_string())?,
};
let contents = std::fs::read_to_string(&path)
.map_err(|error| format!("Cannot read native source \"{path}\": {error}"))?;
let lines = contents
.split('\n')
.map(ToString::to_string)
.collect::<Vec<_>>();
let default_from = frame
.filter(|_| file.is_none())
.map(|frame| frame.line.saturating_sub(10).max(1))
.unwrap_or(1);
let from_line = from_line.unwrap_or(default_from).max(1);
let to_line = to_line
.unwrap_or_else(|| from_line.saturating_add(499))
.max(from_line)
.min(from_line.saturating_add(499))
.min(lines.len() as u64);
let selected = if from_line > lines.len() as u64 {
Vec::new()
} else {
lines[(from_line - 1) as usize..to_line as usize].to_vec()
};
Ok(DebuggerSource {
script_id: frame
.map(|frame| frame.script_id.clone())
.unwrap_or_default(),
file: path,
source_map_url: None,
from_line,
to_line,
lines: selected,
mapped_sources: Vec::new(),
})
}
pub async fn snapshot(&self, id: &str) -> Result<DebuggerSnapshot, String> {
Ok(self.status(id).await?.state)
}
pub async fn scopes(&self, id: &str, frame: usize) -> Result<Vec<DebuggerScope>, String> {
self.snapshot(id)
.await?
.frames
.get(frame)
.map(|frame| frame.scopes.clone())
.ok_or_else(|| format!("Debugger frame {frame} not found"))
}
pub async fn scripts(&self, id: &str) -> Result<Vec<DebuggerScript>, String> {
Ok(self.snapshot(id).await?.scripts)
}
pub async fn console(&self, id: &str) -> Result<Vec<DebuggerConsoleEntry>, String> {
Ok(self.snapshot(id).await?.console)
}
pub async fn exceptions(&self, id: &str) -> Result<Vec<DebuggerExceptionEntry>, String> {
Ok(self.snapshot(id).await?.exceptions)
}
pub async fn health(&self, id: &str) -> Result<DebuggerHealth, String> {
Ok(self.snapshot(id).await?.health)
}
pub async fn trace(
&self,
id: &str,
after: u64,
limit: usize,
) -> Result<Vec<DebuggerTraceEntry>, String> {
Ok(self
.snapshot(id)
.await?
.trace
.into_iter()
.filter(|entry| entry.sequence > after)
.take(limit.min(1_000))
.collect())
}
pub async fn close(&self, id: &str) -> Result<DebuggerSessionView, String> {
if self.dap_session_if_present(id).await.is_some() {
self.dap_close(id).await?;
}
let mut record = self
.store
.debugger_session(id)?
.ok_or_else(|| format!("Debugger session \"{id}\" not found"))?;
record.desired_state = DebuggerDesiredState::Closed;
record.updated_at = now_ms();
self.store.put_debugger_session(&record)?;
if let Some(session) = self.sessions.write().await.remove(id) {
let (reply, response) = oneshot::channel();
let _ = session.commands.send(ActorCommand::Close { reply });
let _ = tokio::time::timeout(Duration::from_secs(2), response).await;
record.observed_state = session.state.borrow().clone();
}
record.observed_state.connected = false;
record.observed_state.paused = false;
record.observed_state.phase = DebuggerPhase::Disconnected;
record.observed_state.frames.clear();
record.observed_state.hit_breakpoints.clear();
record.updated_at = now_ms();
self.store.put_debugger_session(&record)?;
Ok(DebuggerSessionView {
id: record.id,
adapter: record.adapter,
target_id: record.target_id,
target: record.target,
execution_id: record.execution_id,
state: record.observed_state,
})
}
pub async fn disconnect_live(&self, id: &str) {
if let Some(session) = self.sessions.write().await.remove(id) {
let (reply, response) = oneshot::channel();
let _ = session.commands.send(ActorCommand::Close { reply });
let _ = tokio::time::timeout(Duration::from_secs(2), response).await;
}
}
pub async fn reconnect(&self, id: &str) -> Result<DebuggerSessionView, String> {
let record = self
.store
.debugger_session(id)?
.ok_or_else(|| format!("Debugger session \"{id}\" not found"))?;
self.disconnect_live(id).await;
if let (Some(host), Some(port)) = (record.host, record.port) {
self.open(record.id, host, port, record.target_id, record.execution_id)
.await
} else {
self.open_websocket(record.id, record.target, record.execution_id)
.await
}
}
}
async fn discover_target(
host: &str,
port: u16,
target_id: Option<&str>,
) -> Result<DebuggerTarget, String> {
let targets = discover_targets(host, port).await?;
targets
.into_iter()
.find(|target| {
target_id.is_some_and(|id| target.id == id)
|| (target_id.is_none() && target.kind == "node")
})
.ok_or_else(|| "No matching debugger target was found".to_string())
}
pub async fn discover_targets(host: &str, port: u16) -> Result<Vec<DebuggerTarget>, String> {
let url = format!("http://{host}:{port}/json/list");
let targets = reqwest::Client::new()
.get(url)
.timeout(Duration::from_secs(5))
.send()
.await
.map_err(|error| format!("Failed to discover debugger target: {error}"))?
.error_for_status()
.map_err(|error| format!("Debugger discovery failed: {error}"))?
.json::<Vec<Value>>()
.await
.map_err(|error| format!("Invalid debugger discovery response: {error}"))?;
Ok(targets
.into_iter()
.filter_map(|target| {
Some(DebuggerTarget {
id: target.get("id")?.as_str()?.to_string(),
kind: target.get("type")?.as_str()?.to_string(),
title: target
.get("title")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
url: target
.get("url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
websocket_url: target.get("webSocketDebuggerUrl")?.as_str()?.to_string(),
})
})
.collect())
}
async fn debugger_actor<S>(
socket: tokio_tungstenite::WebSocketStream<S>,
mut commands: mpsc::UnboundedReceiver<ActorCommand>,
state_tx: watch::Sender<DebuggerSnapshot>,
) where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
let (mut sink, mut stream) = socket.split();
let mut sequence = 0_u64;
let mut pending = HashMap::<u64, PendingRequest>::new();
let mut scripts = HashMap::<String, DebuggerScript>::new();
let mut closed_because = "the debugger was closed".to_string();
loop {
tokio::select! {
command = commands.recv() => match command {
Some(ActorCommand::Send { method, params, reply }) => {
sequence += 1;
let request = json!({"id": sequence, "method": method, "params": params});
record_trace(
&state_tx,
"sent",
&method,
Some(sequence),
None,
None,
);
if let Err(error) = sink.send(Message::Text(request.to_string().into())).await {
closed_because = format!("sending {method} failed: {error}");
let _ = reply.send(Err(error.to_string()));
break;
}
pending.insert(sequence, PendingRequest {
method,
sent_at: now_ms(),
reply,
});
}
Some(ActorCommand::Close { reply }) => {
let _ = sink.close().await;
let _ = reply.send(());
break;
}
Some(ActorCommand::BrowserState { browser, reply }) => {
let mut state = state_tx.borrow().clone();
state.browser = browser;
state_tx.send_replace(state);
let _ = reply.send(());
}
None => break,
},
message = stream.next() => match message {
Some(Ok(Message::Text(text))) => {
if let Ok(value) = serde_json::from_str::<Value>(&text) {
if let Some(id) = value.get("id").and_then(Value::as_u64) {
if let Some(pending) = pending.remove(&id) {
let error = value.get("error").map(|error| {
error.get("message").and_then(Value::as_str)
.unwrap_or("CDP request failed").to_string()
});
record_trace(
&state_tx,
"received",
&pending.method,
Some(id),
Some(now_ms().saturating_sub(pending.sent_at)),
error.clone(),
);
let response = if let Some(error) = error {
Err(error)
} else {
Ok(value.get("result").cloned().unwrap_or_else(|| json!({})))
};
let _ = pending.reply.send(response);
}
} else if let Some(method) = value.get("method").and_then(Value::as_str) {
record_trace(&state_tx, "event", method, None, None, None);
if method == "Fetch.requestPaused" {
sequence += 1;
let params = value.get("params").cloned().unwrap_or_else(|| json!({}));
let request_id = params.get("requestId").and_then(Value::as_str).unwrap_or_default();
let url = params.pointer("/request/url").and_then(Value::as_str).unwrap_or_default();
let rule = state_tx.borrow().browser.mocks.iter()
.find(|rule| url.contains(&rule.pattern)).cloned();
let request = if let Some(rule) = rule {
json!({
"id":sequence,
"method":"Fetch.fulfillRequest",
"params":{
"requestId":request_id,
"responseCode":rule.status,
"responseHeaders":rule.headers.iter().map(|(name,value)| json!({"name":name,"value":value})).collect::<Vec<_>>(),
"body":base64::engine::general_purpose::STANDARD.encode(rule.body.as_bytes())
}
})
} else {
json!({"id":sequence,"method":"Fetch.continueRequest","params":{"requestId":request_id}})
};
let _ = sink.send(Message::Text(request.to_string().into())).await;
}
update_state(method, value.get("params"), &state_tx, &mut scripts);
}
}
}
Some(Ok(Message::Ping(data))) => {
let _ = sink.send(Message::Pong(data)).await;
}
Some(Ok(Message::Close(frame))) => {
closed_because = match frame {
Some(frame) => format!("the target closed the connection ({}: {})", frame.code, frame.reason),
None => "the target closed the connection".to_string(),
};
break;
}
None => {
closed_because = "the target ended the connection".to_string();
break;
}
Some(Err(error)) => {
closed_because = format!("the connection failed: {error}");
break;
}
_ => {}
}
}
}
let mut state = state_tx.borrow().clone();
state.connected = false;
state.paused = false;
state.phase = DebuggerPhase::Disconnected;
state.frames.clear();
state.hit_breakpoints.clear();
state.error = Some(format!("Debugger connection closed: {closed_because}"));
state.health.disconnected_at = Some(now_ms());
state_tx.send_replace(state);
for (_, pending) in pending {
let _ = pending
.reply
.send(Err(format!("Debugger connection closed: {closed_because}")));
}
}
fn record_trace(
state_tx: &watch::Sender<DebuggerSnapshot>,
direction: &str,
method: &str,
request_id: Option<u64>,
latency_ms: Option<u64>,
error: Option<String>,
) {
let mut state = state_tx.borrow().clone();
let sequence = state.trace.last().map_or(1, |entry| entry.sequence + 1);
state.trace.push(DebuggerTraceEntry {
sequence,
at: now_ms(),
direction: direction.to_string(),
method: method.to_string(),
request_id,
latency_ms,
error: error.clone(),
});
retain_last(&mut state.trace, 1_000);
match direction {
"sent" => state.health.requests = state.health.requests.saturating_add(1),
"received" => {
state.health.responses = state.health.responses.saturating_add(1);
state.health.last_latency_ms = latency_ms;
}
"event" => state.health.events = state.health.events.saturating_add(1),
_ => {}
}
if error.is_some() {
state.health.failures = state.health.failures.saturating_add(1);
}
state_tx.send_replace(state);
}
fn update_state(
method: &str,
params: Option<&Value>,
state_tx: &watch::Sender<DebuggerSnapshot>,
scripts: &mut HashMap<String, DebuggerScript>,
) {
match method {
"Debugger.paused" => {
if let Some(mut params) = params.and_then(|value| paused_snapshot(value).ok()) {
resolve_frame_urls(&mut params.frames, scripts);
let mut current = state_tx.borrow().clone();
current.paused = true;
current.phase = DebuggerPhase::Paused;
current.reason = params.reason;
current.frames = params.frames;
current.async_frames = params.async_frames;
current.hit_breakpoints = params.hit_breakpoints;
current.pause_epoch += 1;
state_tx.send_replace(current);
}
}
"Debugger.resumed" => {
let mut current = state_tx.borrow().clone();
current.paused = false;
current.phase = DebuggerPhase::Running;
current.reason = None;
current.frames.clear();
current.async_frames.clear();
current.hit_breakpoints.clear();
state_tx.send_replace(current);
}
"Debugger.scriptParsed" => {
if let Some(params) = params
&& let (Some(script_id), Some(url)) = (
params.get("scriptId").and_then(Value::as_str),
params.get("url").and_then(Value::as_str),
)
&& !url.is_empty()
{
scripts.insert(
script_id.to_string(),
DebuggerScript {
id: script_id.to_string(),
url: url.to_string(),
file: source_file(url),
start_line: params.get("startLine").and_then(Value::as_u64).unwrap_or(0)
+ 1,
end_line: params.get("endLine").and_then(Value::as_u64).unwrap_or(0) + 1,
source_map_url: params
.get("sourceMapURL")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(ToString::to_string),
module: params
.get("isModule")
.and_then(Value::as_bool)
.unwrap_or(false),
},
);
let mut current = state_tx.borrow().clone();
current.scripts = scripts.values().cloned().collect();
current
.scripts
.sort_by(|left, right| left.id.cmp(&right.id));
state_tx.send_replace(current);
}
}
"Debugger.breakpointResolved" => {
if let Some(params) = params
&& let (Some(backend_id), Some(location)) = (
params.get("breakpointId").and_then(Value::as_str),
params.get("location"),
)
{
let mut current = state_tx.borrow().clone();
current
.breakpoint_resolutions
.retain(|resolution| resolution.backend_id != backend_id);
current
.breakpoint_resolutions
.push(DebuggerBreakpointResolution {
backend_id: backend_id.to_string(),
script_id: location
.get("scriptId")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
line: location
.get("lineNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1,
column: location
.get("columnNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1,
});
retain_last(&mut current.breakpoint_resolutions, 1_000);
state_tx.send_replace(current);
}
}
"Runtime.consoleAPICalled" => {
if let Some(params) = params {
let mut current = state_tx.borrow().clone();
if let Some((tap_id, value)) = parse_tap_sentinel(params) {
let sequence = current
.tap_events
.last()
.map_or(1, |event| event.sequence + 1);
current.tap_events.push(DebuggerTapEvent {
sequence,
id: uuid::Uuid::now_v7().to_string(),
tap_id,
at: now_ms(),
value,
});
retain_last(&mut current.tap_events, 1_000);
state_tx.send_replace(current);
return;
}
let text = params
.get("args")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(remote_description)
.collect::<Vec<_>>()
.join(" ");
let stack = params
.pointer("/stackTrace/callFrames")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|frame| {
format!(
"{}:{}:{}",
frame.get("url").and_then(Value::as_str).unwrap_or_default(),
frame.get("lineNumber").and_then(Value::as_u64).unwrap_or(0) + 1,
frame
.get("columnNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1
)
})
.collect();
let id = current.console.last().map_or(1, |entry| entry.id + 1);
current.console.push(DebuggerConsoleEntry {
id,
kind: params
.get("type")
.and_then(Value::as_str)
.unwrap_or("log")
.to_string(),
text,
at: params
.get("timestamp")
.and_then(Value::as_f64)
.unwrap_or_default(),
stack,
});
retain_last(&mut current.console, 1_000);
state_tx.send_replace(current);
}
}
"Runtime.exceptionThrown" => {
if let Some(params) = params {
let details = params.get("exceptionDetails").unwrap_or(params);
let mut current = state_tx.borrow().clone();
let id = current.exceptions.last().map_or(1, |entry| entry.id + 1);
let description = details
.pointer("/exception/description")
.and_then(Value::as_str)
.or_else(|| details.get("text").and_then(Value::as_str))
.unwrap_or("JavaScript exception");
current.exceptions.push(DebuggerExceptionEntry {
id,
text: description.to_string(),
kind: details
.pointer("/exception/className")
.and_then(Value::as_str)
.unwrap_or("Error")
.to_string(),
file: details
.get("url")
.and_then(Value::as_str)
.map(source_file)
.unwrap_or_default(),
line: details
.get("lineNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1,
at: params
.get("timestamp")
.and_then(Value::as_f64)
.unwrap_or_default(),
uncaught: details
.get("executionContextId")
.and_then(Value::as_u64)
.is_some(),
});
retain_last(&mut current.exceptions, 1_000);
state_tx.send_replace(current);
}
}
_ => {
let mut current = state_tx.borrow().clone();
if update_browser_state(method, params, &mut current) {
state_tx.send_replace(current);
}
}
}
}
fn resolve_frame_urls(frames: &mut [DebuggerFrame], scripts: &HashMap<String, DebuggerScript>) {
for frame in frames {
if frame.file.is_empty()
&& let Some(url) = scripts.get(&frame.script_id)
{
frame.file.clone_from(&url.url);
}
}
}
fn paused_snapshot(params: &Value) -> Result<DebuggerSnapshot, String> {
let frames = params
.get("callFrames")
.and_then(Value::as_array)
.ok_or_else(|| "Debugger pause event has no callFrames".to_string())?
.iter()
.map(|frame| {
let location = frame
.get("location")
.ok_or_else(|| "Debugger frame has no location".to_string())?;
Ok(DebuggerFrame {
id: required_string(frame, "callFrameId")?,
function: frame
.get("functionName")
.and_then(Value::as_str)
.unwrap_or("(anonymous)")
.to_string(),
file: frame
.get("url")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
line: location
.get("lineNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1,
column: location
.get("columnNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1,
script_id: required_string(location, "scriptId")?,
scopes: frame
.get("scopeChain")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|scope| DebuggerScope {
kind: scope
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown")
.to_string(),
name: scope
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
object_id: scope
.pointer("/object/objectId")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
})
.collect(),
this_object_id: frame
.pointer("/this/objectId")
.and_then(Value::as_str)
.map(ToString::to_string),
})
})
.collect::<Result<Vec<_>, String>>()?;
Ok(DebuggerSnapshot {
phase: DebuggerPhase::Paused,
connected: true,
paused: true,
reason: params
.get("reason")
.and_then(Value::as_str)
.map(ToString::to_string),
frames,
async_frames: parse_async_frames(params.get("asyncStackTrace")),
scripts: Vec::new(),
console: Vec::new(),
exceptions: Vec::new(),
tap_events: Vec::new(),
trace: Vec::new(),
health: DebuggerHealth::default(),
browser: DebuggerBrowserState::default(),
pause_epoch: 0,
hit_breakpoints: params
.get("hitBreakpoints")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(ToString::to_string)
.collect(),
breakpoint_resolutions: Vec::new(),
error: None,
})
}
fn parse_async_frames(value: Option<&Value>) -> Vec<DebuggerAsyncFrame> {
let mut frames = Vec::new();
let mut current = value;
while let Some(trace) = current {
let description = trace
.get("description")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
for frame in trace
.get("callFrames")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
frames.push(DebuggerAsyncFrame {
function: frame
.get("functionName")
.and_then(Value::as_str)
.unwrap_or("(anonymous)")
.to_string(),
file: frame
.get("url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
line: frame.get("lineNumber").and_then(Value::as_u64).unwrap_or(0) + 1,
column: frame
.get("columnNumber")
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1,
description: description.clone(),
});
}
current = trace.get("parent");
}
frames
}
fn source_file(url: &str) -> String {
url.rsplit('/').next().unwrap_or(url).to_string()
}
fn load_source_map(script: &DebuggerScript) -> Option<Value> {
let reference = script.source_map_url.as_deref()?;
let bytes = if let Some(encoded) = reference
.strip_prefix("data:application/json;base64,")
.or_else(|| reference.strip_prefix("data:application/octet-stream;base64,"))
{
base64::engine::general_purpose::STANDARD
.decode(encoded)
.ok()
} else if script.url.starts_with("file://") {
let script_path = std::path::Path::new(script.url.trim_start_matches("file://"));
let path = script_path
.parent()
.unwrap_or_else(|| std::path::Path::new("/"))
.join(reference);
std::fs::read(path).ok()
} else {
None
};
bytes
.as_deref()
.and_then(|bytes| serde_json::from_slice::<Value>(bytes).ok())
}
fn mapped_sources(script: &DebuggerScript) -> Vec<DebuggerMappedSource> {
let Some(map) = load_source_map(script) else {
return Vec::new();
};
let sources = map
.get("sources")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let contents = map
.get("sourcesContent")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
sources
.into_iter()
.enumerate()
.filter_map(|(index, source)| {
Some(DebuggerMappedSource {
source: source.as_str()?.to_string(),
content: contents
.get(index)
.and_then(Value::as_str)
.map(ToString::to_string),
})
})
.collect()
}
fn remote_description(value: &Value) -> String {
value
.get("value")
.map(|value| match value {
Value::String(value) => value.clone(),
value => value.to_string(),
})
.or_else(|| {
value
.get("unserializableValue")
.and_then(Value::as_str)
.map(ToString::to_string)
})
.or_else(|| {
value
.get("description")
.and_then(Value::as_str)
.map(ToString::to_string)
})
.unwrap_or_else(|| {
format!(
"[{}]",
value
.get("type")
.and_then(Value::as_str)
.unwrap_or("unknown")
)
})
}
fn remote_value(value: &Value) -> DebuggerRemoteValue {
DebuggerRemoteValue {
kind: value
.get("type")
.and_then(Value::as_str)
.unwrap_or("undefined")
.to_string(),
subtype: value
.get("subtype")
.and_then(Value::as_str)
.map(ToString::to_string),
class_name: value
.get("className")
.and_then(Value::as_str)
.map(ToString::to_string),
description: value
.get("description")
.and_then(Value::as_str)
.map(ToString::to_string),
value: value.get("value").cloned().unwrap_or(Value::Null),
object_id: value
.get("objectId")
.and_then(Value::as_str)
.map(ToString::to_string),
unserializable_value: value
.get("unserializableValue")
.and_then(Value::as_str)
.map(ToString::to_string),
}
}
fn parse_properties(result: &Value) -> Vec<DebuggerProperty> {
let regular = result
.get("result")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|property| DebuggerProperty {
name: property
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
value: property
.get("value")
.map(remote_value)
.unwrap_or_else(|| remote_value(&json!({"type":"undefined"}))),
writable: property
.get("writable")
.and_then(Value::as_bool)
.unwrap_or(false),
configurable: property
.get("configurable")
.and_then(Value::as_bool)
.unwrap_or(false),
enumerable: property
.get("enumerable")
.and_then(Value::as_bool)
.unwrap_or(false),
internal: false,
});
let internal = result
.get("internalProperties")
.and_then(Value::as_array)
.into_iter()
.flatten()
.map(|property| DebuggerProperty {
name: property
.get("name")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
value: property
.get("value")
.map(remote_value)
.unwrap_or_else(|| remote_value(&json!({"type":"undefined"}))),
writable: false,
configurable: false,
enumerable: false,
internal: true,
});
regular.chain(internal).collect()
}
fn source_paths_match(frame_file: &str, breakpoint_file: &str) -> bool {
if frame_file.is_empty() || breakpoint_file.is_empty() {
return false;
}
let frame = frame_file.rsplit('/').collect::<Vec<_>>();
let stored = breakpoint_file.rsplit('/').collect::<Vec<_>>();
stored
.iter()
.zip(frame.iter())
.all(|(stored, frame)| stored == frame)
}
const STEP_SKIP_LIMIT: usize = 16;
fn is_step_skipped(file: &str) -> bool {
file.starts_with("node:")
|| file.starts_with("internal/")
|| file.contains("/node_modules/")
|| file.starts_with("webpack-internal://")
|| file.starts_with("webpack://")
}
const STEP_BLACKBOX_PATTERNS: &[&str] = &[
"^node:",
"^internal/",
"/node_modules/",
"^webpack-internal://",
"^webpack://",
];
const PERSIST_DEBOUNCE: Duration = Duration::from_millis(250);
async fn coalesce_changes(state: &mut watch::Receiver<DebuggerSnapshot>, window: Duration) {
let deadline = tokio::time::sleep(window);
tokio::pin!(deadline);
loop {
tokio::select! {
() = &mut deadline => return,
changed = state.changed() => {
if changed.is_err() {
return;
}
}
}
}
}
pub(crate) fn retain_last<T>(values: &mut Vec<T>, limit: usize) {
if values.len() > limit {
values.drain(..values.len() - limit);
}
}
fn breakpoint_params(file: &str, line: u64, condition: Option<String>) -> Result<Value, String> {
if line == 0 {
return Err("Debugger breakpoint line must be at least 1".to_string());
}
let escaped = regex::escape(file);
let mut params = json!({
"lineNumber": line - 1,
"columnNumber": 0,
"urlRegex": format!(".*{escaped}$")
});
if let Some(condition) = condition.filter(|condition| !condition.is_empty()) {
params["condition"] = Value::String(condition);
}
Ok(params)
}
fn required_string(value: &Value, key: &str) -> Result<String, String> {
value
.get(key)
.and_then(Value::as_str)
.map(ToString::to_string)
.ok_or_else(|| format!("Debugger value has no {key}"))
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use super::*;
#[tokio::test]
async fn a_connection_reset_by_the_target_names_its_cause() {
use tokio_tungstenite::tungstenite::protocol::Role;
let (ours, theirs) = tokio::io::duplex(1 << 16);
let ours =
tokio_tungstenite::WebSocketStream::from_raw_socket(ours, Role::Client, None).await;
let theirs =
tokio_tungstenite::WebSocketStream::from_raw_socket(theirs, Role::Server, None).await;
let (_commands, receiver) = mpsc::unbounded_channel();
let (state_tx, state_rx) = watch::channel(DebuggerSnapshot::default());
let actor = tokio::spawn(debugger_actor(ours, receiver, state_tx));
drop(theirs);
tokio::time::timeout(Duration::from_secs(5), actor)
.await
.expect("the session should notice the target is gone")
.unwrap();
let state = state_rx.borrow().clone();
assert_eq!(state.phase, DebuggerPhase::Disconnected);
let error = state.error.expect("a disconnected session must say why");
assert!(
error.starts_with("Debugger connection closed: the connection failed:"),
"unexpected cause: {error}"
);
}
#[tokio::test]
async fn a_clean_close_by_the_target_names_its_cause() {
use tokio_tungstenite::tungstenite::protocol::Role;
let (ours, theirs) = tokio::io::duplex(1 << 16);
let ours =
tokio_tungstenite::WebSocketStream::from_raw_socket(ours, Role::Client, None).await;
let mut theirs =
tokio_tungstenite::WebSocketStream::from_raw_socket(theirs, Role::Server, None).await;
let (_commands, receiver) = mpsc::unbounded_channel();
let (state_tx, state_rx) = watch::channel(DebuggerSnapshot::default());
let actor = tokio::spawn(debugger_actor(ours, receiver, state_tx));
theirs.close(None).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), actor)
.await
.expect("the session should notice the close")
.unwrap();
let error = state_rx.borrow().clone().error.unwrap();
assert!(
error.starts_with("Debugger connection closed: the target closed the connection"),
"unexpected cause: {error}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn coalescing_waits_for_the_stream_to_fall_quiet() {
let (tx, rx) = watch::channel(DebuggerSnapshot::default());
let mut receiver = rx.clone();
let sender = tokio::spawn(async move {
for _ in 0..20 {
tx.send_replace(DebuggerSnapshot::default());
tokio::time::sleep(Duration::from_millis(5)).await;
}
});
assert!(receiver.changed().await.is_ok());
let started = std::time::Instant::now();
coalesce_changes(&mut receiver, Duration::from_millis(40)).await;
let elapsed = started.elapsed();
sender.abort();
assert!(
elapsed >= Duration::from_millis(30),
"coalescing must absorb a burst, returned after {elapsed:?}"
);
assert!(
elapsed < Duration::from_millis(400),
"coalescing must be bounded even while changes keep arriving, took {elapsed:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn coalescing_returns_even_while_changes_keep_arriving() {
let (tx, rx) = watch::channel(DebuggerSnapshot::default());
let mut receiver = rx.clone();
let sender = tokio::spawn(async move {
loop {
tx.send_replace(DebuggerSnapshot::default());
tokio::time::sleep(Duration::from_millis(2)).await;
}
});
assert!(receiver.changed().await.is_ok());
tokio::time::timeout(
Duration::from_secs(2),
coalesce_changes(&mut receiver, Duration::from_millis(50)),
)
.await
.expect("must return under never-ending traffic");
sender.abort();
}
#[tokio::test(flavor = "multi_thread")]
async fn coalescing_returns_as_soon_as_the_sender_is_dropped() {
let (tx, rx) = watch::channel(DebuggerSnapshot::default());
let mut receiver = rx.clone();
tx.send_replace(DebuggerSnapshot::default());
drop(tx);
tokio::time::timeout(
Duration::from_secs(5),
coalesce_changes(&mut receiver, Duration::from_secs(60)),
)
.await
.expect("must return as soon as the sender is gone");
}
#[test]
fn step_skipping_covers_runtime_and_dependency_origins() {
assert!(is_step_skipped("node:internal/console/constructor"));
assert!(is_step_skipped("node:diagnostics_channel"));
assert!(is_step_skipped("internal/modules/cjs/loader"));
assert!(is_step_skipped(
"file:///repo/node_modules/express/lib/router.js"
));
assert!(is_step_skipped("webpack-internal:///./src/x.js"));
assert!(!is_step_skipped("file:///repo/src/app.ts"));
assert!(!is_step_skipped("file:///repo/my-node_modules-tool/app.js"));
assert!(!is_step_skipped(""));
}
#[test]
fn source_paths_match_compares_whole_trailing_segments() {
assert!(source_paths_match("/build/app/src/main.rs", "src/main.rs"));
assert!(source_paths_match("/build/app/src/main.rs", "main.rs"));
assert!(source_paths_match(
"/build/app/src/main.rs",
"/build/app/src/main.rs"
));
assert!(!source_paths_match(
"/build/app/other/main.rs",
"src/main.rs"
));
assert!(!source_paths_match("/build/app/src/domain.rs", "main.rs"));
assert!(!source_paths_match("", "src/main.rs"));
assert!(!source_paths_match("/build/app/src/main.rs", ""));
}
#[test]
fn paused_event_maps_frames_to_one_based_source_locations() {
let snapshot = paused_snapshot(&json!({
"reason": "other",
"callFrames": [{
"callFrameId": "frame-1",
"functionName": "work",
"url": "file:///tmp/app.js",
"location": {"scriptId": "7", "lineNumber": 4, "columnNumber": 2}
}]
}))
.unwrap();
assert!(snapshot.paused);
assert_eq!(snapshot.reason.as_deref(), Some("other"));
assert_eq!(snapshot.frames[0].file, "file:///tmp/app.js");
assert_eq!(snapshot.frames[0].line, 5);
assert_eq!(snapshot.frames[0].column, 3);
}
#[test]
fn breakpoint_request_is_restart_safe_and_converts_user_line() {
let params = breakpoint_params("src/app.js", 42, Some("ready".to_string())).unwrap();
assert_eq!(params["lineNumber"], 41);
assert_eq!(params["columnNumber"], 0);
assert_eq!(params["urlRegex"], ".*src/app\\.js$");
assert_eq!(params["condition"], "ready");
}
#[test]
fn tap_sentinel_is_routed_out_of_user_console_state() {
let (state_tx, _) = watch::channel(DebuggerSnapshot::default());
let mut scripts = HashMap::new();
update_state(
"Runtime.consoleAPICalled",
Some(&json!({
"type":"log",
"args":[
{"type":"string","value":"__apoc_tap:tap-1"},
{"type":"number","value":42}
]
})),
&state_tx,
&mut scripts,
);
update_state(
"Runtime.consoleAPICalled",
Some(&json!({
"type":"log",
"args":[{"type":"string","value":"visible"}]
})),
&state_tx,
&mut scripts,
);
let snapshot = state_tx.borrow().clone();
assert_eq!(snapshot.tap_events.len(), 1);
assert_eq!(snapshot.tap_events[0].tap_id, "tap-1");
assert_eq!(snapshot.tap_events[0].value, "42");
assert_eq!(snapshot.console.len(), 1);
assert_eq!(snapshot.console[0].text, "visible");
}
#[test]
fn pause_frames_resolve_missing_urls_from_script_events() {
let mut frames = vec![DebuggerFrame {
id: "frame-1".to_string(),
function: "work".to_string(),
file: String::new(),
line: 4,
column: 3,
script_id: "88".to_string(),
scopes: Vec::new(),
this_object_id: None,
}];
let scripts = HashMap::from([(
"88".to_string(),
DebuggerScript {
id: "88".to_string(),
url: "file:///tmp/debugger_target.js".to_string(),
file: "debugger_target.js".to_string(),
start_line: 1,
end_line: 10,
source_map_url: None,
module: false,
},
)]);
resolve_frame_urls(&mut frames, &scripts);
assert_eq!(frames[0].file, "file:///tmp/debugger_target.js");
}
#[test]
fn reads_embedded_source_map_originals() {
let map = json!({
"version": 3,
"sources": ["src/app.ts"],
"sourcesContent": ["const answer: number = 42;"],
"names": [],
"mappings": "AAAA"
});
let encoded = base64::engine::general_purpose::STANDARD.encode(map.to_string());
let script = DebuggerScript {
id: "7".to_string(),
url: "file:///tmp/app.js".to_string(),
file: "app.js".to_string(),
start_line: 1,
end_line: 1,
source_map_url: Some(format!("data:application/json;base64,{encoded}")),
module: true,
};
let originals = mapped_sources(&script);
assert_eq!(originals.len(), 1);
assert_eq!(originals[0].source, "src/app.ts");
assert_eq!(
originals[0].content.as_deref(),
Some("const answer: number = 42;")
);
}
#[test]
fn retains_runtime_exception_events() {
let (state_tx, state_rx) = watch::channel(DebuggerSnapshot::default());
let mut scripts = HashMap::new();
update_state(
"Runtime.exceptionThrown",
Some(&json!({
"timestamp": 123.5,
"exceptionDetails": {
"text": "Uncaught",
"url": "file:///tmp/app.js",
"lineNumber": 6,
"executionContextId": 1,
"exception": {
"className": "TypeError",
"description": "TypeError: broken"
}
}
})),
&state_tx,
&mut scripts,
);
let exceptions = &state_rx.borrow().exceptions;
assert_eq!(exceptions.len(), 1);
assert_eq!(exceptions[0].text, "TypeError: broken");
assert_eq!(exceptions[0].kind, "TypeError");
assert_eq!(exceptions[0].file, "app.js");
assert_eq!(exceptions[0].line, 7);
}
#[tokio::test]
async fn mutation_replay_returns_original_result_without_repeating_action() {
let directory = tempfile::tempdir().unwrap();
let manager = DebuggerManager::new(Arc::new(
Store::open(directory.path().join("apoc.sqlite3")).unwrap(),
));
let calls = AtomicUsize::new(0);
let first: u64 = manager
.mutation(
"key-1".to_string(),
"debugger.pause",
json!({"id":"s0"}),
|| async {
calls.fetch_add(1, Ordering::SeqCst);
Ok(7)
},
)
.await
.unwrap();
let replayed: u64 = manager
.mutation(
"key-1".to_string(),
"debugger.pause",
json!({"id":"s0"}),
|| async {
calls.fetch_add(1, Ordering::SeqCst);
Ok(9)
},
)
.await
.unwrap();
assert_eq!(first, 7);
assert_eq!(replayed, 7);
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn mutation_replay_rejects_conflicting_key_reuse() {
let directory = tempfile::tempdir().unwrap();
let manager = DebuggerManager::new(Arc::new(
Store::open(directory.path().join("apoc.sqlite3")).unwrap(),
));
let _: u64 = manager
.mutation(
"key-1".to_string(),
"debugger.pause",
json!({"id":"s0"}),
|| async { Ok(7) },
)
.await
.unwrap();
let error = manager
.mutation::<u64, _, _>(
"key-1".to_string(),
"debugger.resume",
json!({"id":"s0"}),
|| async { Ok(9) },
)
.await
.unwrap_err();
assert!(error.contains("different mutation"));
}
#[tokio::test]
async fn mutation_replay_survives_manager_recreation() {
let directory = tempfile::tempdir().unwrap();
let store = Arc::new(Store::open(directory.path().join("apoc.sqlite3")).unwrap());
let first = DebuggerManager::new(store.clone());
let value: u64 = first
.mutation(
"durable-key".to_string(),
"debugger.pause",
json!({"id":"s0"}),
|| async { Ok(41) },
)
.await
.unwrap();
assert_eq!(value, 41);
drop(first);
let second = DebuggerManager::new(store);
let calls = AtomicUsize::new(0);
let replayed: u64 = second
.mutation(
"durable-key".to_string(),
"debugger.pause",
json!({"id":"s0"}),
|| async {
calls.fetch_add(1, Ordering::SeqCst);
Ok(99)
},
)
.await
.unwrap();
assert_eq!(replayed, 41);
assert_eq!(calls.load(Ordering::SeqCst), 0);
}
#[test]
fn recovery_marks_accepted_mutations_unknown_without_replay() {
let directory = tempfile::tempdir().unwrap();
let store = Store::open(directory.path().join("apoc.sqlite3")).unwrap();
let record = DebuggerMutationRecord {
id: "receipt-1".to_string(),
idempotency_key: "unknown-key".to_string(),
operation: "debugger.pause".to_string(),
fingerprint: "sha256:test".to_string(),
session_id: "s0".to_string(),
execution_id: None,
state: DebuggerMutationState::Pending,
result: None,
error: None,
started_at: 10,
completed_at: None,
};
assert!(matches!(
store.claim_debugger_mutation(&record).unwrap(),
crate::store::DebuggerMutationClaim::Claimed
));
store.recover_debugger_mutations().unwrap();
let recovered = store.debugger_mutation("unknown-key").unwrap().unwrap();
assert_eq!(recovered.state, DebuggerMutationState::Unknown);
assert!(recovered.completed_at.is_some());
assert!(
recovered
.error
.unwrap()
.contains("external result is unknown")
);
}
}