use std::time::Duration;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::{DebuggerManager, DebuggerSession, now_ms};
const TAP_SENTINEL_PREFIX: &str = "__apoc_tap:";
const WATCH_POLL_MS: u64 = 250;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTap {
pub id: String,
pub session_id: String,
pub backend_id: Option<String>,
pub file: String,
pub line: u64,
pub expression: String,
pub url_regex: String,
pub resolved: bool,
pub enabled: bool,
pub hits: u64,
pub created_at: u64,
pub updated_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTapHit {
pub id: String,
pub tap_id: String,
pub session_id: String,
pub at: u64,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerTapEvent {
pub sequence: u64,
pub id: String,
pub tap_id: String,
pub at: u64,
pub value: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWatch {
pub id: String,
pub session_id: String,
pub target: String,
pub expression: String,
pub access: String,
pub enabled: bool,
pub hits: u64,
pub last_value: Option<String>,
pub last_error: Option<String>,
pub created_at: u64,
pub updated_at: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DebuggerWatchHit {
pub id: String,
pub watch_id: String,
pub session_id: String,
pub at: u64,
pub old_value: Option<String>,
pub new_value: Option<String>,
pub error: Option<String>,
}
impl DebuggerManager {
pub async fn tap_add(
&self,
session_id: &str,
file: String,
line: u64,
expression: String,
url_regex: Option<String>,
) -> Result<DebuggerTap, String> {
if line == 0 {
return Err("Debugger tap line must be at least 1".to_string());
}
if expression.trim().is_empty() {
return Err("Debugger tap expression cannot be empty".to_string());
}
let session = self.session(session_id).await?;
let at = now_ms();
let mut tap = DebuggerTap {
id: uuid::Uuid::now_v7().to_string(),
session_id: session_id.to_string(),
backend_id: None,
file: file.clone(),
line,
expression,
url_regex: url_regex.unwrap_or_else(|| suffix_url_regex(&file)),
resolved: false,
enabled: true,
hits: 0,
created_at: at,
updated_at: at,
};
let result = install_tap(&session, &tap).await?;
tap.backend_id = result
.get("breakpointId")
.and_then(Value::as_str)
.map(ToString::to_string);
tap.resolved = result
.get("locations")
.and_then(Value::as_array)
.is_some_and(|locations| !locations.is_empty());
self.store.put_debugger_tap(&tap)?;
Ok(tap)
}
pub fn tap_list(&self, session_id: &str) -> Result<Vec<DebuggerTap>, String> {
self.store.debugger_taps(session_id)
}
pub fn tap_hits(
&self,
session_id: &str,
tap_id: &str,
limit: usize,
) -> Result<Vec<DebuggerTapHit>, String> {
let tap = self
.store
.debugger_tap(tap_id)?
.ok_or_else(|| format!("Debugger tap \"{tap_id}\" not found"))?;
if tap.session_id != session_id {
return Err(format!(
"Debugger tap \"{tap_id}\" does not belong to session \"{session_id}\""
));
}
self.store.debugger_tap_hits(tap_id, limit)
}
pub async fn tap_remove(&self, session_id: &str, tap_id: &str) -> Result<DebuggerTap, String> {
let mut tap = self
.store
.debugger_tap(tap_id)?
.ok_or_else(|| format!("Debugger tap \"{tap_id}\" not found"))?;
if tap.session_id != session_id {
return Err(format!(
"Debugger tap \"{tap_id}\" does not belong to session \"{session_id}\""
));
}
if let Some(backend_id) = tap.backend_id.as_deref()
&& let Ok(session) = self.session(session_id).await
{
let _ = session
.send(
"Debugger.removeBreakpoint",
json!({"breakpointId":backend_id}),
)
.await;
}
tap.enabled = false;
tap.backend_id = None;
tap.updated_at = now_ms();
self.store.put_debugger_tap(&tap)?;
Ok(tap)
}
pub(super) async fn restore_taps(
&self,
session: &std::sync::Arc<DebuggerSession>,
) -> Result<(), String> {
for mut tap in self.store.debugger_taps(&session.id)? {
if !tap.enabled {
continue;
}
let result = install_tap(session, &tap).await?;
tap.backend_id = result
.get("breakpointId")
.and_then(Value::as_str)
.map(ToString::to_string);
tap.resolved = result
.get("locations")
.and_then(Value::as_array)
.is_some_and(|locations| !locations.is_empty());
tap.updated_at = now_ms();
self.store.put_debugger_tap(&tap)?;
}
Ok(())
}
pub async fn watch_add(
&self,
session_id: &str,
target: String,
expression: Option<String>,
access: String,
) -> Result<DebuggerWatch, String> {
self.session(session_id).await?;
if target.trim().is_empty() {
return Err("Debugger watch target cannot be empty".to_string());
}
if !matches!(access.as_str(), "read" | "write" | "rw") {
return Err("Debugger watch access must be read, write, or rw".to_string());
}
let expression = expression.unwrap_or_else(|| target.clone());
if expression.trim().is_empty() {
return Err("Debugger watch expression cannot be empty".to_string());
}
let at = now_ms();
let watch = DebuggerWatch {
id: uuid::Uuid::now_v7().to_string(),
session_id: session_id.to_string(),
target,
expression,
access,
enabled: true,
hits: 0,
last_value: None,
last_error: None,
created_at: at,
updated_at: at,
};
self.store.put_debugger_watch(&watch)?;
self.spawn_watch_worker(session_id).await;
Ok(watch)
}
pub fn watch_list(&self, session_id: &str) -> Result<Vec<DebuggerWatch>, String> {
self.store.debugger_watches(session_id)
}
pub fn watch_hits(
&self,
session_id: &str,
watch_id: &str,
limit: usize,
) -> Result<Vec<DebuggerWatchHit>, String> {
let watch = self
.store
.debugger_watch(watch_id)?
.ok_or_else(|| format!("Debugger watch \"{watch_id}\" not found"))?;
if watch.session_id != session_id {
return Err(format!(
"Debugger watch \"{watch_id}\" does not belong to session \"{session_id}\""
));
}
self.store.debugger_watch_hits(watch_id, limit)
}
pub async fn watch_remove(
&self,
session_id: &str,
watch_id: &str,
) -> Result<DebuggerWatch, String> {
let mut watch = self
.store
.debugger_watch(watch_id)?
.ok_or_else(|| format!("Debugger watch \"{watch_id}\" not found"))?;
if watch.session_id != session_id {
return Err(format!(
"Debugger watch \"{watch_id}\" does not belong to session \"{session_id}\""
));
}
watch.enabled = false;
watch.updated_at = now_ms();
self.store.put_debugger_watch(&watch)?;
Ok(watch)
}
pub(super) async fn resume_watch_worker(&self, session_id: &str) {
if self
.store
.debugger_watches(session_id)
.is_ok_and(|watches| watches.iter().any(|watch| watch.enabled))
{
self.spawn_watch_worker(session_id).await;
}
}
async fn spawn_watch_worker(&self, session_id: &str) {
self.stop_watch_worker(session_id).await;
let manager = self.clone();
let session_id = session_id.to_string();
let task_session = session_id.clone();
let task = tokio::spawn(async move {
while let Ok(watches) = manager.store.debugger_watches(&task_session) {
let watches = watches
.into_iter()
.filter(|watch| watch.enabled)
.collect::<Vec<_>>();
if watches.is_empty() {
break;
}
let session = match manager.session(&task_session).await {
Ok(session) => session,
Err(_) => break,
};
for watch in watches {
let result = evaluate_watch(&session, &watch.expression).await;
let (new_value, error) = match result {
Ok(value) => (Some(value), None),
Err(error) => (None, Some(error)),
};
if watch.last_value == new_value && watch.last_error == error {
continue;
}
let hit = DebuggerWatchHit {
id: uuid::Uuid::now_v7().to_string(),
watch_id: watch.id.clone(),
session_id: task_session.clone(),
at: now_ms(),
old_value: watch.last_value.clone(),
new_value,
error,
};
let _ = manager.store.record_debugger_watch_hit(&hit);
}
tokio::time::sleep(Duration::from_millis(WATCH_POLL_MS)).await;
}
});
self.watch_tasks.lock().await.insert(session_id, task);
}
async fn stop_watch_worker(&self, session_id: &str) {
if let Some(task) = self.watch_tasks.lock().await.remove(session_id) {
task.abort();
}
}
}
async fn install_tap(session: &DebuggerSession, tap: &DebuggerTap) -> Result<Value, String> {
session
.send(
"Debugger.setBreakpointByUrl",
json!({
"lineNumber":tap.line - 1,
"columnNumber":0,
"urlRegex":tap.url_regex,
"condition":tap_condition(&tap.id, &tap.expression)
}),
)
.await
}
async fn evaluate_watch(session: &DebuggerSession, expression: &str) -> Result<String, String> {
let result = session
.send(
"Runtime.evaluate",
json!({
"expression":expression,
"returnByValue":true,
"awaitPromise":true,
"silent":true
}),
)
.await?;
if let Some(details) = result.get("exceptionDetails") {
return Err(details
.pointer("/exception/description")
.and_then(Value::as_str)
.or_else(|| details.get("text").and_then(Value::as_str))
.unwrap_or("Watch expression failed")
.to_string());
}
let object = result.get("result").unwrap_or(&result);
Ok(remote_value(object))
}
pub(super) fn parse_tap_sentinel(params: &Value) -> Option<(String, String)> {
let args = params.get("args")?.as_array()?;
let sentinel = args.first()?.get("value")?.as_str()?;
let tap_id = sentinel.strip_prefix(TAP_SENTINEL_PREFIX)?.to_string();
if tap_id.is_empty() {
return None;
}
let value = args.get(1).map_or_else(String::new, remote_value);
Some((tap_id, value))
}
fn tap_condition(tap_id: &str, expression: &str) -> String {
let sentinel = serde_json::to_string(&format!("{TAP_SENTINEL_PREFIX}{tap_id}"))
.expect("tap sentinel is serializable");
format!(
"void console.log({sentinel},(()=>{{try{{return ({expression})}}catch(e){{return 'tap-expr-error:'+e}}}})())"
)
}
fn suffix_url_regex(file: &str) -> String {
let cleaned = file
.strip_prefix("./")
.or_else(|| file.strip_prefix('/'))
.unwrap_or(file);
let mut escaped = String::with_capacity(cleaned.len());
for character in cleaned.chars() {
if matches!(
character,
'.' | '*' | '+' | '?' | '^' | '$' | '{' | '}' | '(' | ')' | '|' | '[' | ']' | '\\'
) {
escaped.push('\\');
}
escaped.push(character);
}
escaped
}
fn remote_value(value: &Value) -> String {
if let Some(value) = value.get("value") {
return match value {
Value::String(value) => value.clone(),
value => serde_json::to_string(value).unwrap_or_default(),
};
}
value
.get("unserializableValue")
.and_then(Value::as_str)
.or_else(|| value.get("description").and_then(Value::as_str))
.or_else(|| value.get("type").and_then(Value::as_str))
.unwrap_or_default()
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tap_condition_is_non_pausing_and_guards_expression_errors() {
let condition = tap_condition("tap-1", "value * 2");
assert!(condition.starts_with("void console.log("));
assert!(condition.contains("__apoc_tap:tap-1"));
assert!(condition.contains("tap-expr-error:"));
}
#[test]
fn parses_tap_sentinel_values_and_rejects_user_console() {
let params = json!({"args":[
{"type":"string","value":"__apoc_tap:tap-1"},
{"type":"number","value":42}
]});
assert_eq!(
parse_tap_sentinel(¶ms),
Some(("tap-1".to_string(), "42".to_string()))
);
assert!(parse_tap_sentinel(&json!({"args":[{"value":"hello"}]})).is_none());
}
#[test]
fn source_suffix_becomes_a_literal_url_regex() {
assert_eq!(suffix_url_regex("./src/a+b.ts"), "src/a\\+b\\.ts");
}
}