Flow list columns, multi-column sorting and header and cell menus (#833)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-11-10 00:24:03 -07:00
1 parent a43c3f7c2c
commit b5951b36ae
38 files changed
+3073 -479

No files matched your search

+22 -21
View File
@@ -177,7 +177,7 @@ fn request_body(
};
if mime == "application/json" || mime.ends_with("+json") {
if let Some(graphql) = graphql_body(flow, text) {
if let Some(graphql) = graphql_body(flow, content_type, text) {
return (Some(BODY_TYPE_GRAPHQL.into()), graphql);
}
return text_body(BODY_TYPE_JSON, text);
@@ -206,26 +206,23 @@ fn text_body(body_type: &str, text: &str) -> (Option<String>, BTreeMap<String, V
(Some(body_type.into()), BTreeMap::from([("text".into(), json!(text))]))
}
/// A JSON body posted to a GraphQL endpoint, as the client's GraphQL body.
fn graphql_body(flow: &Flow, text: &str) -> Option<BTreeMap<String, Value>> {
let path = flow.url.split('?').next().unwrap_or_default();
if !path.to_ascii_lowercase().ends_with("/graphql") {
return None;
/// A JSON body that is a GraphQL request, as the client's GraphQL body. Detected as the proxy
/// detects it at capture (`yaak_http::graphql`), which leaves out bodies with fields a GraphQL
/// body cannot hold, such as persisted-query `extensions`.
fn graphql_body(flow: &Flow, content_type: &str, text: &str) -> Option<BTreeMap<String, Value>> {
let body = yaak_http::graphql::parse_json_body(Some(content_type), text, &flow.url)?;
let mut fields = BTreeMap::from([("query".to_string(), json!(body.query))]);
match body.variables {
Some(Value::String(variables)) => {
fields.insert("variables".into(), json!(variables));
}
Some(variables) => {
let pretty = serde_json::to_string_pretty(&variables).ok()?;
fields.insert("variables".into(), json!(pretty));
}
None => {}
}
let Value::Object(body) = serde_json::from_str::<Value>(text).ok()? else {
return None;
};
// Anything else, such as persisted-query `extensions`, would be lost in a GraphQL body.
if body.keys().any(|k| !matches!(k.as_str(), "query" | "variables" | "operationName")) {
return None;
}
let query = body.get("query")?.as_str()?;
let mut fields = BTreeMap::from([("query".to_string(), json!(query))]);
if let Some(variables) = body.get("variables").filter(|v| !v.is_null()) {
let pretty = serde_json::to_string_pretty(variables).ok()?;
fields.insert("variables".into(), json!(pretty));
}
if let Some(name) = body.get("operationName").and_then(Value::as_str) {
if let Some(name) = body.operation_name {
fields.insert("operationName".into(), json!(name));
}
Some(fields)
@@ -355,10 +352,14 @@ mod tests {
let c = flow_to_request(&f, &body(persisted));
assert_eq!(c.request.body_type.as_deref(), Some("application/json"));
// The same body anywhere else is plain JSON.
// A `query` that is no GraphQL document is plain JSON.
let f = flow("POST", "https://x.test/api", &[("Content-Type", "application/json")]);
let c = flow_to_request(&f, &body(r#"{"query":"q"}"#));
assert_eq!(c.request.body_type.as_deref(), Some("application/json"));
// A GraphQL document is GraphQL on any path, as capture reads it.
let c = flow_to_request(&f, &body(r#"{"query":"mutation Save { save { id } }"}"#));
assert_eq!(c.request.body_type.as_deref(), Some("graphql"));
}
#[test]
+2 -1
View File
@@ -543,6 +543,7 @@ mod tests {
"grpc_method",
"grpc_status",
"grpc_message",
"graphql_operation",
"agent_read",
] {
assert!(flow_columns.contains(&column.to_string()), "{column} in {flow_columns:?}");
@@ -614,7 +615,7 @@ mod tests {
assert_eq!(
&applied[6..],
[
"00000007", "00000008", "00000009", "00000010", "00000011", "00000012"
"00000007", "00000008", "00000009", "00000010", "00000011", "00000012", "00000013"
]
);
let mark_columns = columns(&conn, "flow_clear_mark");
+281 -16
View File
@@ -34,6 +34,152 @@ pub struct FlowFilter {
/// through older traffic.
#[ts(optional)]
pub before: Option<String>,
/// The order to list in, the list's column sort: each key in turn, then by start and id,
/// oldest first. Empty lists newest first, as without it. With keys, `before` does not
/// apply; `cursor` pages instead.
#[ts(optional, as = "Option<Vec<FlowSortKey>>")]
pub sort: Vec<FlowSortKey>,
/// Only flows after these values in `sort`'s order, for paging through a sort: the `cursor`
/// of the page before, the sort values of its last flow as it was read, so a change to that
/// flow since does not move where the next page starts.
#[ts(optional, as = "Option<Vec<SortValue>>")]
pub cursor: Option<Vec<SortValue>>,
}
/// One of a flow's sort values, as the database sorted it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(untagged)]
#[ts(export, export_to = "gen_rpc.ts")]
pub enum SortValue {
Int(#[ts(type = "number")] i64),
Text(String),
}
impl SortValue {
fn from_sql(value: Value) -> Self {
match value {
Value::Integer(i) => Self::Int(i),
Value::Real(f) => Self::Int(f as i64),
Value::Text(t) => Self::Text(t),
Value::Null | Value::Blob(_) => Self::Text(String::new()),
}
}
fn to_sql(&self) -> Value {
match self {
Self::Int(i) => Value::Integer(*i),
Self::Text(t) => Value::Text(t.clone()),
}
}
}
/// A column the list sorts by.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub enum SortColumn {
Number,
App,
Method,
Host,
Path,
Query,
Status,
Type,
Size,
RequestSize,
Time,
Latency,
Started,
Remote,
Version,
Tls,
Operation,
}
/// One key of a sort.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct FlowSortKey {
pub column: SortColumn,
pub descending: bool,
}
/// What an empty number sorts as: below every value, as an empty text's `''` is.
const EMPTY_NUMBER: &str = "-1000000000000000000";
impl SortColumn {
/// The value the column sorts by, in SQL, never NULL: empty values (none, `''` or `0`)
/// lowest, text without regard to ASCII case. `columnSortKey` in the app's
/// `lib/columns.ts` makes the same values for flows it places itself.
fn sql(self, columns: &FlowColumns) -> String {
let c = |n: &str| columns.col(n);
let number = |v: &str| format!("coalesce(nullif({v}, 0), {EMPTY_NUMBER})");
let text = |v: &str| format!("(coalesce({v}, '') COLLATE NOCASE)");
match self {
Self::Number => "flows.rowid".into(),
Self::App => text(&format!(
"coalesce({}, {}, {})",
c("client_name"),
c("client_bundle_id"),
c("client_path")
)),
Self::Method => text("method"),
Self::Host => text("url_authority(url)"),
Self::Path => text("url_path(url)"),
Self::Query => text("url_query_string(url)"),
Self::Status => {
format!("CASE WHEN error IS NOT NULL THEN -1 ELSE {} END", number("status"))
}
Self::Type => text("content_type"),
Self::Size => format!(
"CASE WHEN error IS NOT NULL AND status IS NULL THEN {EMPTY_NUMBER} ELSE {} END",
number("response_size")
),
Self::RequestSize => number("request_size"),
Self::Time => number("elapsed_ms"),
Self::Latency => number("elapsed_headers_ms"),
Self::Started => "started_at".into(),
Self::Remote => text("remote_addr"),
Self::Version => text("coalesce(upstream_http_version, client_http_version)"),
Self::Tls => text(&c("upstream_tls_version")),
Self::Operation => {
let (service, method) = (c("grpc_service"), c("grpc_method"));
text(&format!(
"CASE WHEN {service} IS NOT NULL AND {method} IS NOT NULL \
THEN {service} || '/' || {method} ELSE {} END",
c("graphql_operation")
))
}
}
}
}
/// A sort's keys in SQL, each with whether it descends, then start and id, ascending.
fn sort_terms(sort: &[FlowSortKey], columns: &FlowColumns) -> Vec<(String, bool)> {
sort.iter()
.map(|k| (k.column.sql(columns), k.descending))
.chain([
("started_at".to_string(), false),
("flows.id".to_string(), false),
])
.collect()
}
/// The `ORDER BY` for a sort, and the condition for the flows after `cursor`'s values in it:
/// each key equal up to one that is past the cursor's.
fn sort_after(terms: &[(String, bool)], cursor: &[Value]) -> (String, Vec<Value>) {
let mut params = Vec::new();
let mut alternatives = Vec::new();
for (i, (term, descending)) in terms.iter().enumerate() {
let mut parts: Vec<String> = terms[..i].iter().map(|(t, _)| format!("{t} = ?")).collect();
params.extend(cursor[..i].iter().cloned());
parts.push(format!("{term} {} ?", if *descending { "<" } else { ">" }));
params.push(cursor[i].clone());
alternatives.push(format!("({})", parts.join(" AND ")));
}
(format!("({})", alternatives.join(" OR ")), params)
}
impl FlowFilter {
@@ -197,20 +343,50 @@ pub fn page(
db: &ProxyQueryManager,
filter: &FlowFilter,
) -> Result<(Vec<Flow>, usize, Option<usize>), String> {
let page = sorted_page(db, filter)?;
Ok((page.flows, page.total, page.matching))
}
/// A page of flows, as [`page`] reads it, with where a sort's next page starts.
pub struct Page {
pub flows: Vec<Flow>,
pub total: usize,
pub matching: Option<usize>,
/// The sort values of the last flow, for the next page's `cursor`. None without a sort.
pub cursor: Option<Vec<SortValue>>,
}
/// [`page`], with the cursor for a sort's next page.
pub fn sorted_page(db: &ProxyQueryManager, filter: &FlowFilter) -> Result<Page, String> {
db.with_conn(|c| {
let tx = c.conn().resolve().unchecked_transaction().map_err(|e| e.to_string())?;
let flows = list_in(&tx, filter)?;
let (flows, cursor) = list_and_cursor(&tx, filter)?;
let total = count_in(&tx)?;
let matching = if filter.narrows() { Some(count_matching(&tx, filter)?) } else { None };
tx.commit().map_err(|e| e.to_string())?;
Ok((flows, total, matching))
Ok(Page { flows, total, matching, cursor })
})
}
fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>, String> {
list_and_cursor(conn, filter).map(|(flows, _)| flows)
}
/// The flows `filter` covers and, sorted, the sort values of the last one.
fn list_and_cursor(
conn: &rusqlite::Connection,
filter: &FlowFilter,
) -> Result<(Vec<Flow>, Option<Vec<SortValue>>), String> {
let (condition, mut params) = filter.condition_in(conn);
// The rowid, for the flow's number.
let mut sql = format!("SELECT rowid, * FROM flows WHERE {condition}");
let terms = if filter.sort.is_empty() {
Vec::new()
} else {
sort_terms(&filter.sort, &FlowColumns::of(conn))
};
// The rowid, for the flow's number, and a sort's values, for its cursor.
let keys: String =
terms.iter().enumerate().map(|(i, (t, _))| format!(", {t} AS sort_{i}")).collect();
let mut sql = format!("SELECT rowid, *{keys} FROM flows WHERE {condition}");
push_clear_mark(conn, &mut sql, &mut params);
if let Some(id) = &filter.after {
// By rowid, which only grows as flows are written.
@@ -220,24 +396,53 @@ fn list_in(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<Vec<Flow>
sql.push_str(" AND rowid > ?");
params.push(rowid.into());
}
if let Some(id) = &filter.before {
let started_at: 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());
if !terms.is_empty() {
if let Some(cursor) = &filter.cursor {
if cursor.len() != terms.len() {
return Err("The cursor is not for this sort".into());
}
let cursor: Vec<Value> = cursor.iter().map(SortValue::to_sql).collect();
let (after, after_params) = sort_after(&terms, &cursor);
sql.push_str(" AND ");
sql.push_str(&after);
params.extend(after_params);
}
let order: Vec<String> = terms
.iter()
.map(|(t, descending)| format!("{t} {}", if *descending { "DESC" } else { "ASC" }))
.collect();
sql.push_str(" ORDER BY ");
sql.push_str(&order.join(", "));
} else {
if let Some(id) = &filter.before {
let started_at: 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");
}
sql.push_str(" ORDER BY started_at DESC, id DESC");
if let Some(limit) = filter.limit {
sql.push_str(" LIMIT ?");
params.push((limit.min(i64::MAX as usize) as i64).into());
}
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())?;
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
let mut cursor = None;
let mut flows = Vec::new();
let mut rows = stmt.query(rusqlite::params_from_iter(params)).map_err(|e| e.to_string())?;
while let Some(row) = rows.next().map_err(|e| e.to_string())? {
flows.push(Flow::from_row(row).map_err(|e| e.to_string())?);
if !terms.is_empty() {
let values = (0..terms.len())
.map(|i| row.get::<_, Value>(format!("sort_{i}").as_str()).map(SortValue::from_sql))
.collect::<Result<Vec<_>, _>>()
.map_err(|e| e.to_string())?;
cursor = Some(values);
}
}
Ok((flows, cursor))
}
fn count_matching(conn: &rusqlite::Connection, filter: &FlowFilter) -> Result<usize, String> {
@@ -1035,6 +1240,66 @@ mod tests {
assert_eq!(matching, None);
}
/// A sort on several columns orders by each in turn, text without regard to case, empty
/// values lowest and start as the last tiebreak, and pages through that order from a cursor.
#[test]
fn a_sort_on_several_columns_pages_in_its_order() {
let (_dir, db) = db_of(vec![
flow("https://B.com/x", "GET", Some(200), None),
flow("https://a.com/y", "GET", Some(404), None),
flow("https://a.com/z", "GET", None, None),
flow("https://c.com/", "GET", Some(200), None),
flow("https://a.com/", "GET", None, Some("boom")),
flow("https://b.com/q", "GET", Some(200), None),
flow("https://A.com/", "GET", Some(404), None),
flow("https://c.com/", "GET", Some(200), None),
]);
let key = |column, descending| FlowSortKey { column, descending };
let read = |sort: &[FlowSortKey], cursor: Option<Vec<SortValue>>, limit| {
let filter = FlowFilter {
sort: sort.to_vec(),
cursor,
limit: Some(limit),
..Default::default()
};
let page = sorted_page(&db, &filter).unwrap();
let ids: Vec<String> = page.flows.iter().map(|f| f.id[3..].to_string()).collect();
(ids, page.cursor)
};
let sorted = |sort: &[FlowSortKey]| read(sort, None, 100).0;
let by_status = [key(SortColumn::Status, true), key(SortColumn::Host, false)];
let all = sorted(&by_status);
assert_eq!(all, ["001", "006", "000", "005", "003", "007", "004", "002"]);
let mut paged: Vec<String> = Vec::new();
let mut cursor = None;
loop {
let (page, next) = read(&by_status, cursor.clone(), 3);
if page.is_empty() {
break;
}
cursor = next;
paged.extend(page);
}
assert_eq!(paged, all);
// The last flow of a page changing does not move where the next page starts.
let (first, cursor) = read(&by_status, None, 3);
assert_eq!(first, ["001", "006", "000"]);
db.with_conn(|c| {
c.conn().resolve().execute("UPDATE flows SET status = 100 WHERE id = 'fl_000'", [])
})
.unwrap();
let (next, _) = read(&by_status, cursor, 3);
assert_eq!(next, ["005", "003", "007"]);
let ascending = [key(SortColumn::Status, false), key(SortColumn::Host, false)];
assert_eq!(sorted(&ascending), ["002", "004", "000", "005", "003", "007", "001", "006"]);
// Query alone: the flows without one first, in start order.
let all = sorted(&[key(SortColumn::Query, true)]);
assert_eq!(all, ["000", "001", "002", "003", "004", "005", "006", "007"]);
}
#[test]
fn a_search_reads_the_newest_page_through_the_index() {
let (_dir, db) = db_of(vec![]);
+151 -2
View File
@@ -1655,6 +1655,9 @@ pub struct ListFlowsResponse {
/// Flows the filter covers, whatever the limit, when it narrows to fewer than all of them.
#[ts(type = "number | null")]
pub matching: Option<usize>,
/// Sorted, the next page's `cursor`: the last flow's sort values, as read. None without a
/// sort or a flow.
pub cursor: Option<Vec<flows::SortValue>>,
}
#[derive(Deserialize, TS)]
@@ -2689,8 +2692,9 @@ fn list_actions(
}
fn list_flows(ctx: &ProxyCtx, req: flows::FlowFilter) -> Result<ListFlowsResponse, RpcError> {
let (flows, total, matching) = flows::page(&ctx.db()?, &req).map_err(rpc_error)?;
Ok(ListFlowsResponse { flows, total, matching })
let flows::Page { flows, total, matching, cursor } =
flows::sorted_page(&ctx.db()?, &req).map_err(rpc_error)?;
Ok(ListFlowsResponse { flows, total, matching, cursor })
}
async fn clear_flows(ctx: ProxyCtx, _req: ClearFlowsRequest) -> Result<usize, RpcError> {
@@ -2827,9 +2831,52 @@ struct InFlight {
/// Changed since it was last written, by a message or a status.
dirty: bool,
last_write: Option<std::time::Instant>,
/// The request body's first bytes, while it may be a GraphQL request whose operation is
/// read once it is whole. None once it can't be: not JSON, encoded, or too long.
graphql_scan: Option<Vec<u8>>,
}
/// Most request body bytes read for a GraphQL operation; a longer body is not looked at.
const GRAPHQL_SCAN_LIMIT: usize = 64 * 1024;
impl InFlight {
/// Keeps a request body chunk for reading a GraphQL operation from, when the body may be
/// one: JSON, not encoded, and short. `len` is the chunk's size on the wire, `data` what of
/// it was captured.
fn scan_graphql(&mut self, first: bool, len: usize, data: &[u8]) {
if first {
let headers = &self.flow.request_headers;
let json = find_header(headers, "content-type")
.and_then(|t| t.split(';').next())
.is_some_and(|t| t.trim().eq_ignore_ascii_case("application/json"));
let encoded = find_header(headers, "content-encoding")
.is_some_and(|e| !e.trim().eq_ignore_ascii_case("identity"));
let stream = self.flow.stream_kind.is_some();
self.graphql_scan = (json && !encoded && !stream).then(Vec::new);
}
let Some(buf) = &mut self.graphql_scan else {
return;
};
if data.len() < len || buf.len() + len > GRAPHQL_SCAN_LIMIT {
self.graphql_scan = None;
return;
}
buf.extend_from_slice(data);
}
/// Reads the GraphQL operation from the request body kept by [`Self::scan_graphql`].
fn finish_graphql_scan(&mut self) {
let Some(body) = self.graphql_scan.take() else {
return;
};
let content_type = find_header(&self.flow.request_headers, "content-type");
if let Some(op) =
yaak_http::graphql::detect(&self.flow.method, &self.flow.url, content_type, Some(&body))
{
self.flow.graphql_operation = Some(op.label());
}
}
/// Stops writing the bodies its stream's messages carry, which are read back from them.
/// A request's bytes are kept while it uploads, as a call can end before its upload does,
/// with a message still partway in: they are dropped once the upload ends, or kept as its
@@ -3079,6 +3126,12 @@ impl FlowSink {
let flow_id = Flow::generate_id();
let request_body = Flow::body_id(&flow_id, FlowBody::Request);
let response_body = Flow::body_id(&flow_id, FlowBody::Response);
// GraphQL over GET is all in its URL; a body's operation is read once it is whole.
let graphql_operation = method
.eq_ignore_ascii_case("GET")
.then(|| yaak_http::graphql::detect(&method, &url, None, None))
.flatten()
.map(|op| op.label());
let flow = Flow {
id: flow_id,
started_at: DateTime::<Utc>::from(started_at).naive_utc(),
@@ -3086,6 +3139,7 @@ impl FlowSink {
url,
client_http_version: http_version,
client_addr: Some(client_addr.to_string()),
graphql_operation,
..Default::default()
};
in_flight.insert(
@@ -3100,6 +3154,7 @@ impl FlowSink {
next_seq: 0,
dirty: false,
last_write: None,
graphql_scan: None,
},
);
}
@@ -3128,6 +3183,7 @@ impl FlowSink {
next_seq: 0,
dirty: false,
last_write: None,
graphql_scan: None,
};
// Shown while it is open, as tunnels often stay open for minutes.
self.write_stream_flow(&mut f);
@@ -3179,6 +3235,7 @@ impl FlowSink {
// upload does.
ProxyEvent::RequestBodyChunk { id, len, data } => {
if let Some(f) = in_flight.get_mut(&id) {
f.scan_graphql(f.flow.request_size == 0, len, &data);
f.flow.request_size += len as i64;
if f.keeps_bytes(FlowBody::Request) {
f.flow.request_truncated |= data.len() < len;
@@ -3191,6 +3248,7 @@ impl FlowSink {
if let Some(f) = in_flight.get_mut(&id) {
f.flow.request_size = size as i64;
f.flow.elapsed_request_ms = Some(clamp_ms(elapsed_ms));
f.finish_graphql_scan();
if f.keeps_bytes(FlowBody::Request) {
f.flow.request_truncated = truncated;
finish_body(f.request_body.take());
@@ -4487,6 +4545,96 @@ mod tests {
.unwrap();
}
/// A GraphQL request's operation is stored with the flow: from a JSON body sent in chunks,
/// and from a GET's URL. A JSON body that is not GraphQL, and one over the scan limit, store
/// none.
#[test]
fn graphql_operations_are_stored_at_capture() {
let dir = tempfile::tempdir().unwrap();
let (events, _rx) = RpcEventEmitter::new();
let ctx = ProxyCtx::new(dir.path(), events, MasterKeySource::memory()).unwrap();
let (tx, event_loop) = event_loop(&ctx);
let send = |event| tx.send(event).unwrap();
let post = |id: u64, url: &str, chunks: &[&[u8]]| {
send(ProxyEvent::RequestStart {
id,
started_at: SystemTime::now(),
method: "POST".into(),
url: url.into(),
http_version: "HTTP/1.1".into(),
connection: 1,
client_addr: "127.0.0.1:1".parse().unwrap(),
});
send(ProxyEvent::RequestHeader {
id,
name: "Content-Type".into(),
value: "application/json; charset=utf-8".into(),
});
let mut size = 0;
for chunk in chunks {
size += chunk.len();
send(ProxyEvent::RequestBodyChunk {
id,
len: chunk.len(),
data: bytes::Bytes::copy_from_slice(chunk),
});
}
send(ProxyEvent::RequestBodyComplete {
id,
size: size as u64,
truncated: false,
elapsed_ms: 1,
});
send(ProxyEvent::ResponseStart {
id,
status: 200,
http_version: "HTTP/1.1".into(),
remote_addr: None,
elapsed_ms: 2,
});
send(ProxyEvent::ResponseBodyComplete {
id,
size: 0,
truncated: false,
elapsed_ms: 3,
error: None,
cancelled: false,
});
};
post(
1,
"https://api.example.com/graphql",
&[
br#"{"query":"query GetUser($id: ID!) "#,
br#"{ user(id: $id) { id } }"}"#,
],
);
post(2, "https://api.example.com/users", &[br#"{"query":"red shoes"}"#]);
let long = format!(
r#"{{"query":"query Big {{ a }}","variables":{{"pad":"{}"}}}}"#,
"x".repeat(GRAPHQL_SCAN_LIMIT)
);
post(3, "https://api.example.com/big/graphql", &[long.as_bytes()]);
send_flow(&tx, 4, "https://api.example.com/graphql?query=query%20Feed%20%7B%20a%20%7D");
drop(tx);
event_loop.join().unwrap();
let flows = flows::list(&ctx.db().unwrap(), &Default::default()).unwrap();
assert_eq!(flows.len(), 4);
let operation = |url: &str| {
let flow = flows.iter().find(|f| f.url == url).unwrap();
flow.graphql_operation.clone()
};
assert_eq!(operation("https://api.example.com/graphql").as_deref(), Some("GetUser"));
assert_eq!(operation("https://api.example.com/users"), None);
assert_eq!(operation("https://api.example.com/big/graphql"), None);
assert_eq!(
operation("https://api.example.com/graphql?query=query%20Feed%20%7B%20a%20%7D")
.as_deref(),
Some("Feed")
);
}
/// Flows that end together are written together, and every one the engine sent is written
/// when it stops, mid-batch or not, each with its body.
#[test]
@@ -4545,6 +4693,7 @@ mod tests {
next_seq: 0,
dirty: false,
last_write: None,
graphql_scan: None,
};
sink.finish_flow(f);
assert!(!sink.finished_due(), "the clock stands still");
@@ -103,6 +103,9 @@ pub struct Flow {
pub grpc_status: Option<i32>,
/// A gRPC call's `grpc-message`, decoded.
pub grpc_message: Option<String>,
/// A GraphQL request's operation, from its body or URL: `GetUser`, `GetUser +2` for a
/// batch, empty for an anonymous one. None when the request is not GraphQL.
pub graphql_operation: Option<String>,
/// An HTTPS connection passed through undecrypted, as the decrypt list leaves it out or its
/// client rejected the proxy's certificate: method `CONNECT`, its URL the host, its sizes
/// the bytes each way, and no headers or bodies. Open until `elapsedMs` or `error` is set.
@@ -273,6 +276,7 @@ impl UpsertModelInfo for Flow {
(GrpcMethod, self.grpc_method.into()),
(GrpcStatus, self.grpc_status.into()),
(GrpcMessage, self.grpc_message.into()),
(GraphqlOperation, self.graphql_operation.into()),
(Tunnelled, self.tunnelled.into()),
(ElapsedConnectMs, self.elapsed_connect_ms.into()),
(ElapsedTlsMs, self.elapsed_tls_ms.into()),
@@ -316,6 +320,7 @@ impl UpsertModelInfo for Flow {
FlowIden::GrpcMethod,
FlowIden::GrpcStatus,
FlowIden::GrpcMessage,
FlowIden::GraphqlOperation,
FlowIden::Tunnelled,
FlowIden::ElapsedConnectMs,
FlowIden::ElapsedTlsMs,
@@ -374,6 +379,7 @@ impl UpsertModelInfo for Flow {
grpc_method: added_column(r, "grpc_method")?,
grpc_status: added_column(r, "grpc_status")?,
grpc_message: added_column(r, "grpc_message")?,
graphql_operation: added_column(r, "graphql_operation")?,
tunnelled: added_column(r, "tunnelled")?.unwrap_or_default(),
agent_read: added_column(r, "agent_read")?.unwrap_or_default(),
})
+60 -4
View File
@@ -37,6 +37,7 @@ pub const FLAGS: &[&str] = &[
"ws",
"sse",
"grpc",
"graphql",
];
/// Flags `@is:` will take once flows have what they need. Valid, matching nothing.
@@ -100,6 +101,14 @@ pub fn schema() -> &'static Schema {
field("id", number(), "Flow number", "@id:>1200"),
field("cwd", text(), "Working folder", "@cwd:myapp"),
field("pid", number(), "Process id", "@pid:4121"),
field(
"graphql.operation",
text(),
"GraphQL operation name",
"@graphql.operation:GetUser",
),
field("grpc.service", text(), "gRPC service", "@grpc.service:pkg.Greeter"),
field("grpc.method", text(), "gRPC method", "@grpc.method:SayHello"),
field("body", text(), "Not yet", ""),
field("req.body", text(), "Not yet", ""),
field("res.body", text(), "Not yet", ""),
@@ -471,9 +480,10 @@ const SEEN_VALUES: i64 = 200;
const HEADER_VALUES: i64 = 20;
/// The values seen for a field path, for completing it, most recent first: hosts, methods,
/// statuses, content types, protocols, schemes, apps, working folders, `@is` flags, and header
/// names, or a header's values when it has had few. Nothing for fields whose values are
/// near-unique (URLs, paths, ids, sizes, times, query parameters).
/// statuses, content types, protocols, schemes, apps, working folders, GraphQL operations, gRPC
/// services and methods, `@is` flags, header names, or a header's values when it has had few,
/// and query parameter names. Nothing for fields whose values are near-unique (URLs, paths, ids,
/// sizes, times, query parameter values).
pub fn seen_values(db: &crate::db::ProxyQueryManager, path: &str) -> Result<Vec<String>, String> {
let path = path.to_lowercase();
let column = match path.as_str() {
@@ -486,6 +496,10 @@ pub fn seen_values(db: &crate::db::ProxyQueryManager, path: &str) -> Result<Vec<
"scheme" => "url_scheme(url)",
"app" => "client_name",
"cwd" => "folder_name(client_cwd)",
"graphql.operation" => "graphql_operation",
"grpc.service" => "grpc_service",
"grpc.method" => "grpc_method",
"query" => return seen_query_names(db),
"header" | "req.header" | "res.header" => {
return seen_headers(db, &path, None);
}
@@ -524,6 +538,17 @@ fn newest_flows() -> String {
)
}
/// The names of the query parameters seen, for completing `@query.`.
fn seen_query_names(db: &crate::db::ProxyQueryManager) -> Result<Vec<String>, String> {
let sql = format!(
"SELECT q_lower(json_extract(kv.value, '$.name')) AS name FROM ({}) AS f, \
json_each(url_query_json(f.url)) AS kv WHERE name IS NOT NULL AND name != '' \
GROUP BY name ORDER BY max(f.rid) DESC LIMIT {SEEN_VALUES}",
newest_flows()
);
select_strings(db, &sql, None)
}
/// Header names under a map, or one header's values when it has had few.
fn seen_headers(
db: &crate::db::ProxyQueryManager,
@@ -723,6 +748,16 @@ pub fn url_sidebar_path(url: &str) -> Option<String> {
(normalized != path && !path.is_empty()).then_some(normalized)
}
/// The authority as written, user info and port included: the list's Host column.
pub fn url_authority(url: &str) -> &str {
url_parts(url).authority
}
/// The query string as written, without its `?`: the list's Query column.
pub fn url_query_string(url: &str) -> Option<&str> {
url_parts(url).query
}
/// The query's parameters, decoded, their names lowercased.
pub fn url_query(url: &str) -> Vec<(String, String)> {
let Some(query) = url_parts(url).query else {
@@ -784,6 +819,7 @@ fn flags(flow: &Flow) -> Vec<&'static str> {
"ws" => stream == Some("websocket"),
"sse" => stream == Some("sse"),
"grpc" => matches!(stream, Some("grpc" | "grpc_web")),
"graphql" => flow.graphql_operation.is_some(),
_ => false,
};
FLAGS.iter().copied().filter(|f| set(f)).collect()
@@ -862,6 +898,16 @@ pub fn document(flow: &Flow) -> Document {
if let Some(pid) = flow.client_pid {
add("pid", num(f64::from(pid)));
}
// An anonymous operation is GraphQL with no name: `@is:graphql`, not `@graphql.operation:*`.
if let Some(op) = flow.graphql_operation.as_deref().filter(|op| !op.is_empty()) {
add("graphql.operation", text(op));
}
if let Some(service) = &flow.grpc_service {
add("grpc.service", text(service));
}
if let Some(method) = &flow.grpc_method {
add("grpc.method", text(method));
}
for (side, headers) in [
("req", &flow.request_headers),
("res", &flow.response_headers),
@@ -919,7 +965,7 @@ impl FlowColumns {
}
/// `name`, or what the model reads in its place when the table lacks it.
fn col(&self, name: &str) -> String {
pub(crate) fn col(&self, name: &str) -> String {
if self.0.contains(name) {
return name.to_string();
}
@@ -1005,6 +1051,9 @@ impl Sql<'_> {
"req.size" => (vec!["request_size".into()], true),
"duration" => (vec!["elapsed_ms".into()], true),
"pid" => (vec![c("client_pid")], true),
"graphql.operation" => (vec![format!("nullif({}, '')", c("graphql_operation"))], false),
"grpc.service" => (vec![c("grpc_service")], false),
"grpc.method" => (vec![c("grpc_method")], false),
"app" => {
let (bundle, path, name) =
(c("client_bundle_id"), c("client_path"), c("client_name"));
@@ -1103,6 +1152,7 @@ impl Sql<'_> {
"ws" => format!("{} = 'websocket'", c("stream_kind")),
"sse" => format!("{} = 'sse'", c("stream_kind")),
"grpc" => format!("{} IN ('grpc', 'grpc_web')", c("stream_kind")),
"graphql" => format!("{} IS NOT NULL", c("graphql_operation")),
_ => "0".into(),
}
}
@@ -1214,6 +1264,12 @@ pub(crate) fn add_functions(conn: &rusqlite::Connection) -> rusqlite::Result<()>
conn.create_scalar_function("url_path", 1, flags, move |ctx| {
Ok(url_path(&text_arg(ctx, 0)?.unwrap_or_default()).map(str::to_string))
})?;
conn.create_scalar_function("url_authority", 1, flags, move |ctx| {
Ok(url_authority(&text_arg(ctx, 0)?.unwrap_or_default()).to_string())
})?;
conn.create_scalar_function("url_query_string", 1, flags, move |ctx| {
Ok(url_query_string(&text_arg(ctx, 0)?.unwrap_or_default()).map(str::to_string))
})?;
conn.create_scalar_function("url_sidebar_path", 1, flags, move |ctx| {
Ok(url_sidebar_path(&text_arg(ctx, 0)?.unwrap_or_default()))
})?;
+67 -1
View File
@@ -690,6 +690,13 @@ fn sample(count: usize) -> Vec<Flow> {
client_pid: rng.chance(50).then(|| (rng.next() % 1000) as i32),
stream_kind: *rng.pick(&streams),
grpc_status: *rng.pick(&[None, Some(0), Some(5)]),
grpc_service: rng
.chance(20)
.then(|| rng.pick(&["pkg.Greeter", "Users"]).to_string()),
grpc_method: rng.chance(20).then(|| rng.pick(&["SayHello", "getUser"]).to_string()),
graphql_operation: rng
.chance(25)
.then(|| rng.pick(&["GetUser", "", "Feed +2", "createÉtat"]).to_string()),
error: rng.chance(15).then(|| "connection reset".to_string()),
cancelled: rng.chance(10),
saved_request_id: rng.chance(15).then(|| "rq_x".to_string()),
@@ -859,6 +866,18 @@ const BATTERY: &[&str] = &[
"@is:ws",
"@is:sse",
"@is:grpc",
"@is:graphql",
"-@is:graphql",
"@graphql.operation:getuser",
"@graphql.operation:feed*",
"@graphql.operation:*",
"-@graphql.operation:*",
"@graphql.operation:createétat",
"@grpc.service:pkg.greeter",
"@grpc.service:*",
"@grpc.method:SayHello",
"-@grpc.method:*",
"@grpc.service:users @grpc.method:get*",
"@is:*",
"-@is:*",
"@is:s*",
@@ -961,11 +980,58 @@ fn seen_values_for_completion() {
"size",
"duration",
"time",
"query",
"query.page",
] {
assert!(values(path).is_empty(), "{path}");
}
// A query parameter's names, for `@query.`, but not its values
let mut params = values("query");
params.sort();
assert_eq!(params, vec!["page", "sort"]);
}
/// GraphQL operations and gRPC calls, by name and by flag, and offered for completion.
#[test]
fn graphql_and_grpc_fields() {
let base = |id: &str, url: &str| Flow {
id: id.into(),
url: url.into(),
method: "POST".into(),
started_at: now().naive_utc(),
..Default::default()
};
let flows = vec![
Flow {
graphql_operation: Some("GetUser".into()),
..base("fl_named", "https://api.example.com/graphql")
},
Flow {
graphql_operation: Some(String::new()),
..base("fl_anonymous", "https://api.example.com/graphql")
},
Flow {
grpc_service: Some("pkg.Greeter".into()),
grpc_method: Some("SayHello".into()),
..base("fl_call", "https://grpc.example.com/pkg.Greeter/SayHello")
},
base("fl_plain", "https://example.com/"),
];
let (_dir, db, all) = db_of(flows);
let finds = |query: &str| {
let prepared = FlowQuery::at(query, false, now());
let sql = sql_ids(&db, &prepared);
assert_eq!(sql, memory_ids(&all, &prepared), "the two disagree on {query:?}");
sql
};
assert_eq!(finds("@is:graphql"), ids(&["fl_anonymous", "fl_named"]));
assert_eq!(finds("@graphql.operation:getuser"), ids(&["fl_named"]));
assert_eq!(finds("@graphql.operation:*"), ids(&["fl_named"]));
assert_eq!(finds("@grpc.service:pkg.Greeter"), ids(&["fl_call"]));
assert_eq!(finds("@grpc.method:say*"), ids(&["fl_call"]));
assert_eq!(finds("-@grpc.method:*"), ids(&["fl_anonymous", "fl_named", "fl_plain"]));
assert_eq!(seen_values(&db, "graphql.operation").unwrap(), vec!["GetUser"]);
assert_eq!(seen_values(&db, "grpc.service").unwrap(), vec!["pkg.Greeter"]);
assert_eq!(seen_values(&db, "grpc.method").unwrap(), vec!["SayHello"]);
}
#[test]