Keep the proxy app fast with many flows

The app held every flow in memory and redid all of its work for each new
one: the sidebar mounted every domain and path node (its tree scrolled
inside a container that never bounded it), every tree row looked up its
atoms by scanning every atom the family had made, and the layout, detail
pane and list rows re-rendered per flow. At 3,000 flows each new one cost
about 90 ms of main thread, more than the traffic left time for.

The app now holds a window of the newest 2,000 flows, applies new ones in
batches, and loads older ones in pages from the database on scrolling to
the top, through a new list_flows RPC that pages in SQL. The database
keeps every flow.

Also adds clear_flows: an RPC, POST /flows/clear on the control API, and
a Clear button in the header that Cmd+K opens, confirming first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and Stetta task tk_mvsazf4rsaotrdpf committed 2026-10-28 09:52:00 -07:00
1 parent 4abc882e13
commit 1a994f7532
19 files changed
+855 -216

No files matched your search

@@ -7,6 +7,7 @@ use ts_rs::TS;
pub enum GlobalAction {
ProxyStart,
ProxyStop,
FlowsClear,
}
#[derive(Debug, Clone, Serialize, Deserialize, TS)]
@@ -45,5 +46,12 @@ pub fn all_global_actions() -> Vec<(ActionInvocation, ActionMetadata)> {
default_hotkey: default_hotkey("Meta+Shift+S", "Ctrl+Shift+S"),
},
),
(
ActionInvocation::Global { action: GlobalAction::FlowsClear },
ActionMetadata {
label: "Clear Flows".into(),
default_hotkey: default_hotkey("Meta+K", "Ctrl+K"),
},
),
]
}
@@ -222,6 +222,12 @@ pub struct SystemProxyRequest {
pub enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClearResponse {
/// How many flows were deleted.
pub cleared: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorBody {
pub error: String,
@@ -470,6 +476,10 @@ async fn route(state: &ServerState, req: Request<Incoming>) -> Result<ControlRes
let filter = FlowFilter::from_query(&query).map_err(bad_request)?;
json(&flows::list(&ctx.db, &filter)?)
}
(&Method::POST, ["flows", "clear"]) => {
let ctx = ctx.clone();
json(&ClearResponse { cleared: blocking(move || ctx.clear_flows()).await? })
}
(&Method::GET, ["flows", id]) => {
found(ctx, id)?;
let limit = body_limit(&query)?;
+143 -26
View File
@@ -4,27 +4,40 @@ use crate::models::{Flow, FlowBody, FlowIden};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use serde::{Deserialize, Serialize};
use ts_rs::TS;
use yaak_database::UpsertModelInfo;
use yaak_models::blob_manager::BlobManager;
/// Which flows a listing or a HAR export covers. Every field narrows it; none is all of them.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(default, rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct FlowFilter {
/// Part of the host, any case: `stripe` matches `api.stripe.com`.
#[ts(optional)]
pub host: Option<String>,
/// The method, any case.
#[ts(optional)]
pub method: Option<String>,
/// A status (`404`), a class of them (`4xx`), or `error` for flows that failed.
#[ts(optional)]
pub status: Option<String>,
/// At most this many flows, the newest.
#[ts(optional, type = "number")]
pub limit: Option<usize>,
/// Only flows recorded after the flow with this id, for following new traffic. Flows are
/// recorded when they end, so a slow one that started earlier still comes through.
#[ts(optional)]
pub after: Option<String>,
/// Only flows older than the flow with this id, by start and then id, for paging back
/// through older traffic.
#[ts(optional)]
pub before: Option<String>,
}
impl FlowFilter {
/// The filter from a query string's `host`, `method`, `status`, `limit` and `after`.
/// The filter from a query string's `host`, `method`, `status`, `limit`, `after` and
/// `before`.
pub fn from_query(query: &str) -> Result<Self, String> {
let mut filter = Self::default();
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
@@ -34,6 +47,7 @@ impl FlowFilter {
"method" => filter.method = value,
"status" => filter.status = value,
"after" => filter.after = value,
"before" => filter.before = value,
"limit" => {
filter.limit = value
.map(|v| v.parse().map_err(|_| format!("Invalid limit {v:?}")))
@@ -54,6 +68,7 @@ impl FlowFilter {
("status", &self.status),
("limit", &limit),
("after", &self.after),
("before", &self.before),
] {
if let Some(value) = value {
query.append_pair(key, value);
@@ -91,35 +106,70 @@ fn host_of(url: &str) -> &str {
rest.split(['/', '?', '#']).next().unwrap_or_default()
}
/// The flows `filter` covers, newest first.
/// The flows `filter` covers, newest first: by start, then by id. Reads only as far into the
/// table as the limit needs, so a page costs the same however many flows there are.
pub fn list(db: &ProxyQueryManager, filter: &FlowFilter) -> Result<Vec<Flow>, String> {
db.with_conn(|c| {
let flows = c.find_all::<Flow>().map_err(|e| e.to_string())?;
let recorded_after = match &filter.after {
Some(id) => Some(recorded_after(c.conn().resolve(), id)?),
None => None,
};
Ok(flows
.into_iter()
.filter(|f| recorded_after.as_ref().is_none_or(|ids| ids.contains(&f.id)))
.filter(|f| filter.matches(f))
.take(filter.limit.unwrap_or(usize::MAX))
.collect())
let conn = c.conn().resolve();
let mut sql = String::from("SELECT * FROM flows WHERE 1");
let mut params: Vec<rusqlite::types::Value> = Vec::new();
if let Some(id) = &filter.after {
// By rowid, which only grows as flows are written.
let rowid: i64 = conn
.query_row("SELECT rowid FROM flows WHERE id = ?", [id], |r| r.get(0))
.map_err(|_| format!("No flow {id}"))?;
sql.push_str(" AND rowid > ?");
params.push(rowid.into());
}
if let Some(id) = &filter.before {
let started_at: rusqlite::types::Value = conn
.query_row("SELECT started_at FROM flows WHERE id = ?", [id], |r| r.get(0))
.map_err(|_| format!("No flow {id}"))?;
sql.push_str(" AND (started_at, id) < (?, ?)");
params.push(started_at);
params.push(id.clone().into());
}
sql.push_str(" ORDER BY started_at DESC, id DESC");
let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
let rows = stmt
.query_map(rusqlite::params_from_iter(params), Flow::from_row)
.map_err(|e| e.to_string())?;
let mut flows = Vec::new();
for flow in rows {
if flows.len() >= filter.limit.unwrap_or(usize::MAX) {
break;
}
let flow = flow.map_err(|e| e.to_string())?;
if filter.matches(&flow) {
flows.push(flow);
}
}
Ok(flows)
})
}
/// Ids of the flows inserted after flow `id`, by rowid, which only grows as flows are written.
fn recorded_after(
conn: &rusqlite::Connection,
id: &str,
) -> Result<std::collections::HashSet<String>, String> {
let rowid: i64 = conn
.query_row("SELECT rowid FROM flows WHERE id = ?", [id], |r| r.get(0))
.map_err(|_| format!("No flow {id}"))?;
let mut stmt =
conn.prepare("SELECT id FROM flows WHERE rowid > ?").map_err(|e| e.to_string())?;
let ids = stmt.query_map([rowid], |r| r.get(0)).map_err(|e| e.to_string())?;
ids.collect::<Result<_, _>>().map_err(|e| e.to_string())
/// Deletes every flow, then their bodies, each in a transaction. Returns how many there were.
pub fn clear(db: &ProxyQueryManager, blobs: &BlobManager) -> Result<usize, String> {
let ids = db
.with_tx(|c| {
let conn = c.conn().resolve();
let mut stmt = conn.prepare("SELECT id FROM flows")?;
let ids = stmt.query_map([], |r| r.get(0))?.collect::<Result<Vec<String>, _>>()?;
conn.execute("DELETE FROM flows", [])?;
Ok::<_, yaak_database::Error>(ids)
})
.map_err(|e| format!("Failed to clear flows: {e}"))?;
// Only the deleted flows' bodies, so a flow still in flight keeps what it has written.
blobs
.with_tx(|b| {
for id in &ids {
b.delete_chunks(&Flow::body_id(id, FlowBody::Request))?;
b.delete_chunks(&Flow::body_id(id, FlowBody::Response))?;
}
Ok::<_, yaak_models::error::Error>(())
})
.map_err(|e| format!("Failed to clear flow bodies: {e}"))?;
Ok(ids.len())
}
pub fn find(db: &ProxyQueryManager, flow_id: &str) -> Option<Flow> {
@@ -267,6 +317,73 @@ mod tests {
assert_eq!(list(&db, &missing).unwrap_err(), "No flow fl_gone");
}
#[test]
fn before_pages_back_through_older_flows() {
use yaak_database::UpdateSource;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let at = |s| chrono::DateTime::from_timestamp(s, 0).unwrap().naive_utc();
// Two started together, which their ids order.
for (id, started) in [("fl_a", 10), ("fl_b", 20), ("fl_c", 20), ("fl_d", 30), ("fl_e", 40)]
{
let flow = Flow {
id: id.into(),
started_at: at(started),
status: Some(if id == "fl_c" { 404 } else { 200 }),
..Default::default()
};
db.with_tx(|tx| tx.upsert(&flow, &UpdateSource::Background)).unwrap();
}
let page = |filter: FlowFilter| {
list(&db, &filter).unwrap().into_iter().map(|f| f.id).collect::<Vec<_>>()
};
let newest = FlowFilter { limit: Some(2), ..Default::default() };
assert_eq!(page(newest), vec!["fl_e", "fl_d"]);
let older = FlowFilter { before: Some("fl_d".into()), limit: Some(2), ..Default::default() };
assert_eq!(page(older), vec!["fl_c", "fl_b"]);
let oldest = FlowFilter { before: Some("fl_b".into()), limit: Some(2), ..Default::default() };
assert_eq!(page(oldest), vec!["fl_a"]);
// The limit counts flows the filter keeps.
let ok = FlowFilter {
before: Some("fl_e".into()),
status: Some("2xx".into()),
limit: Some(2),
..Default::default()
};
assert_eq!(page(ok), vec!["fl_d", "fl_b"]);
let missing = FlowFilter { before: Some("fl_gone".into()), ..Default::default() };
assert_eq!(list(&db, &missing).unwrap_err(), "No flow fl_gone");
}
#[test]
fn clear_deletes_flows_and_their_bodies() {
use yaak_database::UpdateSource;
use yaak_models::blob_manager::BodyChunkWriter;
let dir = tempfile::tempdir().unwrap();
let db = ProxyQueryManager::new(&dir.path().join("proxy.db")).unwrap();
let blobs = yaak_models::init_blob_store(dir.path().join("blobs.sqlite")).unwrap();
let write_body = |id: &str, which| {
let mut writer = BodyChunkWriter::new(blobs.clone(), Flow::body_id(id, which));
writer.write(b"body").unwrap();
writer.finish().unwrap();
};
for id in ["fl_a", "fl_b"] {
write_body(id, FlowBody::Request);
write_body(id, FlowBody::Response);
let flow = Flow { id: id.into(), ..Default::default() };
db.with_tx(|tx| tx.upsert(&flow, &UpdateSource::Background)).unwrap();
}
// A flow still in flight has written a body but not its row.
write_body("fl_live", FlowBody::Request);
assert_eq!(clear(&db, &blobs).unwrap(), 2);
assert_eq!(count(&db).unwrap(), 0);
let body_ids = blobs.connect().list_body_ids().unwrap();
assert_eq!(body_ids, vec![Flow::body_id("fl_live", FlowBody::Request)]);
assert_eq!(clear(&db, &blobs).unwrap(), 0);
}
#[test]
fn query_round_trip() {
let filter = FlowFilter {
+35 -12
View File
@@ -329,6 +329,14 @@ impl ProxyCtx {
);
Ok(saved)
}
/// Deletes every flow and its bodies, and tells the app so its list empties. Returns how
/// many there were.
pub fn clear_flows(&self) -> Result<usize, String> {
let cleared = flows::clear(&self.db, &self.blobs)?;
self.events.emit("flows_cleared", &FlowsClearedPayload {});
Ok(cleared)
}
}
/// Something accepts connections on `127.0.0.1:<port>`.
@@ -365,17 +373,25 @@ pub struct ListActionsResponse {
pub actions: Vec<(ActionInvocation, ActionMetadata)>,
}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct ListModelsRequest {}
#[derive(Serialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
#[serde(rename_all = "camelCase")]
pub struct ListModelsResponse {
pub struct ListFlowsResponse {
/// Newest first.
pub flows: Vec<Flow>,
/// Flows in the database, whatever the filter.
#[ts(type = "number")]
pub total: usize,
}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct ClearFlowsRequest {}
#[derive(Serialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct FlowsClearedPayload {}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct GetProxyStateRequest {}
@@ -469,6 +485,9 @@ fn execute_action(ctx: &ProxyCtx, invocation: ActionInvocation) -> Result<bool,
ActionInvocation::Global { action } => match action {
GlobalAction::ProxyStart => ctx.start().map_err(|message| RpcError { message })?,
GlobalAction::ProxyStop => ctx.stop().map_err(|message| RpcError { message })?,
GlobalAction::FlowsClear => {
ctx.clear_flows().map_err(|message| RpcError { message })?;
}
},
}
Ok(true)
@@ -587,12 +606,14 @@ fn list_actions(
Ok(ListActionsResponse { actions: crate::actions::all_global_actions() })
}
fn list_models(ctx: &ProxyCtx, _req: ListModelsRequest) -> Result<ListModelsResponse, RpcError> {
ctx.db.with_conn(|db| {
Ok(ListModelsResponse {
flows: db.find_all::<Flow>().map_err(|e| RpcError { message: e.to_string() })?,
})
})
fn list_flows(ctx: &ProxyCtx, req: flows::FlowFilter) -> Result<ListFlowsResponse, RpcError> {
let flows = flows::list(&ctx.db, &req).map_err(rpc_error)?;
let total = flows::count(&ctx.db).map_err(rpc_error)?;
Ok(ListFlowsResponse { flows, total })
}
async fn clear_flows(ctx: ProxyCtx, _req: ClearFlowsRequest) -> Result<usize, RpcError> {
blocking(move || ctx.clear_flows()).await
}
// -- Event loop --
@@ -746,17 +767,19 @@ define_rpc! {
format_body(FormatBodyRequest) -> String,
get_proxy_state(GetProxyStateRequest) -> GetProxyStateResponse,
list_actions(ListActionsRequest) -> ListActionsResponse,
list_models(ListModelsRequest) -> ListModelsResponse,
list_flows(flows::FlowFilter) -> ListFlowsResponse,
}
async_commands {
ca_status(CaStatusRequest) -> CaStatus,
ca_trust(CaTrustRequest) -> CaStatus,
clear_flows(ClearFlowsRequest) -> usize,
filter_body(FilterBodyRequest) -> FilterBodyResponse,
get_flow_body(GetFlowBodyRequest) -> GetFlowBodyResponse,
system_proxy_set(SystemProxySetRequest) -> SystemProxyStatus,
system_proxy_status(SystemProxyStatusRequest) -> SystemProxyStatus,
}
events {
flows_cleared(FlowsClearedPayload),
model_write(ModelPayload),
proxy_state_changed(ProxyStatePayload),
}