mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-11-27 10:20:54 +08:00
perf(traffic): write the full-text index off the request path
The proxy records an exchange in its Response hook, before the client gets the response, and recordViews wrote the trigram index of each body (up to 4 MiB) inside its transaction while holding wmu. That is almost all of the recording cost: a 1 MB minified script takes ~163 ms with the index and ~1 ms without, and every other request being recorded waits on wmu behind it. Queue the index write instead and let one background worker do it. Searches that use the index wait for everything queued before them, so a body search still finds an exchange recorded before it. The worker only writes an entry whose exchange still exists with the same rowid and id, so a delete in between can't leave an entry that matches a later exchange. The queue holds at most 16 bodies; a recorder waits when it is full. Fixes #542.
This commit is contained in:
@@ -14,6 +14,7 @@ All notable changes to this project are documented in this file. The format is b
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, under the recorder's global lock, so a 1 MB script added about 160 ms to its own response and to every response recorded behind it. The index is now written by a background worker. Body searches wait for entries queued before them, so they still find every exchange recorded before the search. An entry whose exchange was deleted in the meantime is dropped.
|
||||
- **Missing Docker buildx is reported before the build**: without the buildx plugin, Compose only warns and falls back to the legacy builder, which fails on the Dockerfile's first `FROM --platform=$BUILDPLATFORM` with `failed to parse platform`. `install.sh` (all-Docker) and `update.sh` (Docker update) now check `docker buildx version` first and stop with an install hint, and the automatic Docker install on apt-based distros not covered by get.docker.com installs the buildx package as well. The README Docker section names buildx as a requirement.
|
||||
- **A goal URL followed by punctuation is still seeded**: a goal such as `Assess http://juiceshop:3000.` no longer logs `could not parse a target host/IP` and skips the site. Trailing punctuation, including full-width `。` and a closing bracket that has no matching opener, is trimmed from the URL before it is parsed, so `http://[::1]` is left alone. The scheme the goal names is kept and a final period does not end up in the host.
|
||||
- **Task timeout triggers fire for every task**: `on_task_timeout` used the task id as a watermark, but tasks time out in deadline order. Once a newer task timed out first, an older task that timed out later was never fired for. Fired timeouts are now kept in a persisted set, like met goals; on first start the set is seeded with the tasks already timed out, so nothing replays.
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package traffic
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ftsQueueMax bounds the bodies waiting for the indexer. A recorder that finds
|
||||
// the queue full waits, so memory stays bounded under a burst of large bodies.
|
||||
const ftsQueueMax = 16
|
||||
|
||||
type ftsJob struct {
|
||||
rowid int64
|
||||
id string
|
||||
text string
|
||||
}
|
||||
|
||||
// ftsQueue writes the full-text index on one background goroutine. Trigram
|
||||
// indexing is almost all of the cost of recording a large text body, and the
|
||||
// proxy records before it replies, so inline indexing held the client and every
|
||||
// other recorder (on wmu) for it. ftsFilter calls wait, so a search still sees
|
||||
// every exchange recorded before it.
|
||||
type ftsQueue struct {
|
||||
t *Traffic
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
jobs []ftsJob
|
||||
queued int64
|
||||
done int64
|
||||
closed bool
|
||||
exited chan struct{}
|
||||
}
|
||||
|
||||
func newFTSQueue(t *Traffic) *ftsQueue {
|
||||
q := &ftsQueue{t: t, exited: make(chan struct{})}
|
||||
q.cond = sync.NewCond(&q.mu)
|
||||
go q.run()
|
||||
return q
|
||||
}
|
||||
|
||||
// add queues a job. It must not be called with wmu held: the worker needs wmu
|
||||
// to drain a full queue.
|
||||
func (q *ftsQueue) add(j ftsJob) {
|
||||
q.mu.Lock()
|
||||
for len(q.jobs) >= ftsQueueMax && !q.closed {
|
||||
q.cond.Wait()
|
||||
}
|
||||
if q.closed {
|
||||
q.mu.Unlock()
|
||||
q.index(j)
|
||||
return
|
||||
}
|
||||
q.jobs = append(q.jobs, j)
|
||||
q.queued++
|
||||
q.cond.Broadcast()
|
||||
q.mu.Unlock()
|
||||
}
|
||||
|
||||
// wait returns once every job queued before the call has been indexed.
|
||||
func (q *ftsQueue) wait() {
|
||||
q.mu.Lock()
|
||||
for target := q.queued; q.done < target; {
|
||||
q.cond.Wait()
|
||||
}
|
||||
q.mu.Unlock()
|
||||
}
|
||||
|
||||
// close indexes what is still queued and stops the worker.
|
||||
func (q *ftsQueue) close() {
|
||||
q.mu.Lock()
|
||||
q.closed = true
|
||||
q.cond.Broadcast()
|
||||
q.mu.Unlock()
|
||||
<-q.exited
|
||||
}
|
||||
|
||||
func (q *ftsQueue) run() {
|
||||
defer close(q.exited)
|
||||
for {
|
||||
q.mu.Lock()
|
||||
for len(q.jobs) == 0 && !q.closed {
|
||||
q.cond.Wait()
|
||||
}
|
||||
if len(q.jobs) == 0 {
|
||||
q.mu.Unlock()
|
||||
return
|
||||
}
|
||||
j := q.jobs[0]
|
||||
q.jobs = q.jobs[1:]
|
||||
q.mu.Unlock()
|
||||
|
||||
q.index(j)
|
||||
|
||||
q.mu.Lock()
|
||||
q.done++
|
||||
q.cond.Broadcast()
|
||||
q.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// index writes one entry, skipping it when the exchange was deleted (or its
|
||||
// rowid reused by another exchange) after it was queued.
|
||||
func (q *ftsQueue) index(j ftsJob) {
|
||||
q.t.wmu.Lock()
|
||||
defer q.t.wmu.Unlock()
|
||||
if _, err := q.t.db.Exec(`INSERT INTO ex_fts(rowid,content)
|
||||
SELECT ?, ? WHERE EXISTS(SELECT 1 FROM exchanges WHERE rowid=? AND id=?)`, j.rowid, j.text, j.rowid, j.id); err != nil {
|
||||
slog.Error("[traffic] failed to write full-text index", "exchange", j.id, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package traffic
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A body search right after recording finds the exchange, though indexing
|
||||
// now happens on the background queue.
|
||||
func TestBodySearchSeesJustRecordedExchange(t *testing.T) {
|
||||
tr, _ := openTraffic(t)
|
||||
if tr.ftsq == nil {
|
||||
t.Skip("no full-text index in this build")
|
||||
}
|
||||
for i := range 20 {
|
||||
body := bytes.Repeat([]byte("filler text "), 5000)
|
||||
if i == 19 {
|
||||
body = append(body, "apiKey=AKIAEXAMPLE123"...)
|
||||
}
|
||||
tr.record(newFlow("app.example", "GET", "/static/app.js", nil, body))
|
||||
}
|
||||
got, err := tr.query("", "", "AKIAEXAMPLE123", 0, 10)
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("body search = %d results, %v; want 1", len(got), err)
|
||||
}
|
||||
}
|
||||
|
||||
// A queued entry whose exchange was deleted before the worker reached it is
|
||||
// dropped, so it cannot attach to a later exchange that reuses the rowid.
|
||||
func TestQueuedIndexSkipsDeletedExchange(t *testing.T) {
|
||||
tr, _ := openTraffic(t)
|
||||
if tr.ftsq == nil {
|
||||
t.Skip("no full-text index in this build")
|
||||
}
|
||||
tr.ftsq.index(ftsJob{rowid: 4242, id: "gone", text: "orphan-marker-xyz"})
|
||||
var n int
|
||||
if err := tr.db.QueryRow(`SELECT count(*) FROM ex_fts WHERE ex_fts MATCH '"orphan-marker-xyz"'`).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatalf("orphan index rows = %d, %v; want 0", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkRecordScript is the time the proxy holds a response for, recording a
|
||||
// 1 MiB script body with the indexer idle.
|
||||
func BenchmarkRecordScript(b *testing.B) {
|
||||
tr, err := Open(b.TempDir(), "127.0.0.1:0")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer tr.Close()
|
||||
body := bytes.Repeat([]byte("function a(b){return b.c+\"x\"};var q=1;"), 1<<20/40)
|
||||
for b.Loop() {
|
||||
f := newFlow("app.example", "GET", "/static/app.js", nil, body)
|
||||
f.Response.Header = http.Header{"Content-Type": []string{"application/javascript"}}
|
||||
tr.record(f)
|
||||
b.StopTimer()
|
||||
if tr.ftsq != nil {
|
||||
tr.ftsq.wait()
|
||||
}
|
||||
b.StartTimer()
|
||||
}
|
||||
}
|
||||
+34
-9
@@ -245,6 +245,9 @@ type Traffic struct {
|
||||
// build without FTS5: recording and metadata search still work, body search
|
||||
// degrades to unsupported rather than erroring.
|
||||
fts bool
|
||||
// ftsq writes the full-text index off the request path (fts_queue.go). Nil
|
||||
// when fts is off, and on a zero value, where recording indexes inline.
|
||||
ftsq *ftsQueue
|
||||
// reaping tracks background reclamation of legacy trees and index space, so
|
||||
// shutdown and tests can wait for it instead of racing it.
|
||||
reaping sync.WaitGroup
|
||||
@@ -326,6 +329,9 @@ func Open(dir, addr string) (*Traffic, error) {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
if t.fts {
|
||||
t.ftsq = newFTSQueue(t)
|
||||
}
|
||||
|
||||
p, err := mproxy.NewProxy(&mproxy.Options{
|
||||
Addr: addr,
|
||||
@@ -582,6 +588,9 @@ func (t *Traffic) Close() error {
|
||||
}
|
||||
t.reaping.Wait()
|
||||
t.sweeping.Wait()
|
||||
if t.ftsq != nil {
|
||||
t.ftsq.close()
|
||||
}
|
||||
return t.db.Close()
|
||||
}
|
||||
|
||||
@@ -711,6 +720,14 @@ const unavailableMarker = "[original request unavailable]\n"
|
||||
// so there is never a rewritten exchange without its trace. Without trace
|
||||
// lines this is exactly what record always wrote.
|
||||
func (t *Traffic) recordViews(rq requestView, rs responseView, lines []rewrite.TraceLine) {
|
||||
// The index job is queued after writeViews releases wmu: the indexer needs
|
||||
// wmu, and a full queue makes add wait for it.
|
||||
if job := t.writeViews(rq, rs, lines); job != nil {
|
||||
t.ftsq.add(*job)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Traffic) writeViews(rq requestView, rs responseView, lines []rewrite.TraceLine) *ftsJob {
|
||||
// The write lock covers blob + index writes, so DeleteHost (and its blob GC)
|
||||
// can run under the same lock without racing a concurrent record.
|
||||
t.wmu.Lock()
|
||||
@@ -749,7 +766,7 @@ func (t *Traffic) recordViews(rq requestView, rs responseView, lines []rewrite.T
|
||||
tx, err := t.db.Begin()
|
||||
if err != nil {
|
||||
fail("beginning transaction", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
defer tx.Rollback() //nolint:errcheck // no-op once committed
|
||||
|
||||
@@ -757,7 +774,7 @@ func (t *Traffic) recordViews(rq requestView, rs responseView, lines []rewrite.T
|
||||
// exchange it replaces must not stay attached to this one.
|
||||
if _, err := tx.Exec(`DELETE FROM exchange_rewrites WHERE exchange_id=?`, id); err != nil {
|
||||
fail("clearing rewrite trace", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
// path stays empty for db-resident exchanges; a non-empty path marks a legacy
|
||||
// row whose bodies still live in the old on-disk tree (see Get).
|
||||
@@ -767,19 +784,19 @@ VALUES(?,?,?,?,?,?,?,?,?,?,'')`,
|
||||
len(rq.body), len(rs.body))
|
||||
if err != nil {
|
||||
fail("writing index", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
rowid, err := res.LastInsertId()
|
||||
if err != nil {
|
||||
fail("fetching rowid", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(`INSERT OR REPLACE INTO exchange_bodies(id,req_head,req_body,req_blob,resp_head,resp_body,resp_blob)
|
||||
VALUES(?,?,?,?,?,?,?)`,
|
||||
id, reqHead, reqB.inline, nullIfEmpty(reqB.hash), respHead, respB.inline, nullIfEmpty(respB.hash)); err != nil {
|
||||
fail("writing body", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, h := range []string{reqB.hash, respB.hash} {
|
||||
@@ -788,7 +805,7 @@ VALUES(?,?,?,?,?,?,?)`,
|
||||
}
|
||||
if _, err := tx.Exec(`INSERT OR IGNORE INTO blob_refs(hash,exchange_id) VALUES(?,?)`, h, id); err != nil {
|
||||
fail("registering blob reference", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -796,23 +813,28 @@ VALUES(?,?,?,?,?,?,?)`,
|
||||
var re *recordError
|
||||
errors.As(err, &re)
|
||||
fail(re.step, re.err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
|
||||
var job *ftsJob
|
||||
if t.fts {
|
||||
// The index is fed from memory, so a body that spilled to _blobs is still
|
||||
// fully searchable even though only its preview is stored inline. Only the
|
||||
// recorded views are indexed, never a value a rule wrote.
|
||||
idx := strings.Join([]string{url, reqHead, reqB.index, respHead, respB.index}, "\n")
|
||||
if _, err := tx.Exec(`INSERT INTO ex_fts(rowid,content) VALUES(?,?)`, rowid, idx); err != nil {
|
||||
if t.ftsq != nil {
|
||||
job = &ftsJob{rowid: rowid, id: id, text: idx}
|
||||
} else if _, err := tx.Exec(`INSERT INTO ex_fts(rowid,content) VALUES(?,?)`, rowid, idx); err != nil {
|
||||
fail("writing full-text index", err)
|
||||
return
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
fail("committing", err)
|
||||
return nil
|
||||
}
|
||||
return job
|
||||
}
|
||||
|
||||
// appliedRules reports whether a trace rewrote its exchange, with the ids of
|
||||
@@ -1252,6 +1274,9 @@ func (t *Traffic) ftsFilter(term string) (cond string, arg any, ok bool) {
|
||||
if !t.fts || utf8.RuneCountInString(term) < minTrigram {
|
||||
return "", nil, false
|
||||
}
|
||||
if t.ftsq != nil {
|
||||
t.ftsq.wait()
|
||||
}
|
||||
return `rowid IN (SELECT rowid FROM ex_fts WHERE ex_fts MATCH ?)`, ftsQuote(term), true
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user