Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions CLAUDE.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ The same endpoints serve the REST API and the [MCP tools](mcp.md). Managing proj
| `GET list_projects` | all | ✓ | ✓ | `cursor`, `limit` | `items` [`id`, `name`, `dsn`, `log_levels`, `paused`, `unresolved_issues`, `dropped`], `next_cursor` | List the monitored projects with their unresolved issue counts, DSNs (what a Sentry SDK is configured with to report to the project) and the logs and events the server did not store since the first of them (dropped; missing when none was dropped for 7 days). Not needed before list_issues: issue rows name their project. |
| `POST update_issue_status` | all | ✓ | ✓ | `issue_ids`, `status`, `ignore_for`, `ignore_until_events` | `issues` [`id`, `project`, `title`, `location`, `level`, `status`, `event_count`, `not_stored`, `stored_events`, `first_seen`, `last_seen`, `resolved_at`, `ignored_until`, `ignore_events_left`, `mcp_reference`], `missing_issue_ids`, `forbidden_issue_ids` | Set the status of 1 to 100 issues in one atomic call: resolved (fixed, reopens if the error happens again), ignored (no notifications; for good, or until the time or number of events chosen when ignoring) or unresolved (still happening or not looked at yet). Returns the updated summaries. |
| `POST delete_issue` | admin | ✓ | ✓ | `issue_id` | `deleted` | Delete an issue with its events; if the error happens again it comes back as a new issue. Admins only. |
| `GET list_cleanups` | all | ✓ | | — | `start_percent`, `stop_percent`, `files_percent`, `stale_percent`, `compaction_attempts`, `kept`, `runs` [`id`, `project`, `started_at`, `status`, `limit`, `size_before`, `compacted`, `size_after`, `freed`, `before_files`, `arrived`, `size_now`, `files`, `stop`, `needed`, `deleted_steps`, `result`, `took`, `span`, `between`, `error`, `steps`, `compaction`] | The latest runs of the cleanup by size, newest first, with the time of every step they ran and what each deleted. |
| `GET list_cleanups` | all | ✓ | | — | `start_percent`, `stop_percent`, `files_percent`, `stale_percent`, `compaction_attempts`, `kept`, `runs` [`id`, `project`, `started_at`, `status`, `limit`, `size_before`, `compacted`, `size_after`, `freed`, `arrived`, `size_now`, `files`, `stop`, `needed`, `deleted_steps`, `result`, `took`, `span`, `between`, `error`, `steps`, `compaction`] | The latest runs of the cleanup by size, newest first, with the time of every step they ran and what each deleted. |
| `set_project_active` | all | | ✓ | `active`, `project` | `id`, `name`, `dsn`, `log_levels`, `paused` | Pause or resume recording a project: while paused, what its apps send is answered but not stored (errors and logs), and nothing is notified. |
| `GET get_event_payload` | all | ✓ | | `event_id`, `project` | `project_id`, `issue_id`, `event_id`, `timestamp`, `received_at`, `level`, `environment`, `release`, `trace_id`, `span_id`, `parent_span_id`, `thinned`, `payload` | An event with its JSON as stored: credentials and parts that do not help a fix removed; thinned marks an old event whose details were removed. |
| `GET list_trace` | all | ✓ | | `trace_id` | `trace_id`, `events` [`project_id`, `issue_id`, `event_id`, `timestamp`, `received_at`, `level`, `environment`, `release`, `trace_id`, `span_id`, `parent_span_id`, `thinned`], `logs` [`id`, `project_id`, `timestamp`, `level`, `severity_number`, `body`, `trace_id`, `span_id`, `attributes`], `stopped`, `searched_to` | Events (without payloads) and logs of one trace, up to 100 of each. |
Expand Down
4 changes: 2 additions & 2 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ Projects are added on the Projects page (or by a coding agent with `create_proje
| `GOOGLE_CLIENT_SECRET` | | The secret of that Google client. |
| `API_TOKEN` | | Token for the [REST API](api.md), at least 32 characters (`openssl rand -hex 32`). Without it the REST API is off. |
| `ALLOWED_IPS` | any | Addresses or networks (`203.0.113.7,10.0.0.0/8`) that may open the UI, REST API and MCP. Apps can always send errors. |
| `TRUSTED_PROXIES` | the proxy on this machine, with an https `PUBLIC_URL` | Reverse proxies whose `X-Forwarded-For` gives each person's address, for the login limit and `ALLOWED_IPS`. Not needed for a proxy on the same machine; `none` trusts no proxy. When to set it: [Other setups](deployment.md#other-setups). |
| `TRUSTED_PROXIES` | the proxy on this machine, with an https `PUBLIC_URL` | Reverse proxies whose `X-Forwarded-For` gives each person's address, for the login limit and `ALLOWED_IPS`. Not needed for a proxy on the host itself, compose.yml's Caddy included, when `PUBLIC_URL` is https (a proxy in a container of its own needs it); `none` trusts no proxy. When to set it: [Other setups](deployment.md#other-setups). |

## Ingest

Expand Down Expand Up @@ -59,7 +59,7 @@ Where notifications go is set on the **Notifications** page. Telegram and Slack

| Variable | Default | |
|---|---|---|
| `SECRET_KEY` | generated | At least 32 characters (`openssl rand -hex 32`). Encrypts chat tokens. Without it a key is created in `DATA_DIR/secret.key`. Do not lose or change it: saved chats would stop working. |
| `SECRET_KEY` | generated | At least 32 characters (`openssl rand -hex 32`). Encrypts chat tokens and signs the Unsubscribe links of emails and the browsers users logged in from. Without it a key is created in `DATA_DIR/secret.key`. Do not lose or change it: saved chats would stop working, links in emails already sent would fail, and every browser would count as new for the login limit. |
| `SMTP_HOST` | | Mail server, without the port. |
| `SMTP_PORT` | `587` | Port 465 uses TLS, others STARTTLS. |
| `SMTP_USERNAME`, `SMTP_PASSWORD` | | SMTP login. |
Expand Down
2 changes: 1 addition & 1 deletion internal/agentprompt/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,7 @@ func redactURLPath(path string) string {
return redactPath(path)
}

// redactServiceTokens hides the tokens of chat services anywhere in text
// redactServiceTokens hides the tokens of chat services and GitHub anywhere in text
// (textutil.ReplaceServiceTokens).
func redactServiceTokens(text string) string {
return textutil.ReplaceServiceTokens(text, func(path string) string {
Expand Down
12 changes: 12 additions & 0 deletions internal/agentprompt/prompt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ func TestBuildLeavesOutSensitiveData(t *testing.T) {
"hunter2-secret", "query-token-value", "header-token-value", "cookie-value", "breadcrumb-key", "eyJhbGci", "4111111111111111", // credentials and data
"slackhooksecret", "telegram-bot-secret", "k3x9Q2mfZ8a7B6c5D4e3", // tokens in URL paths
"AAEhBOweik6ad9r_QXMENQjcrGbqCr4K-x4", "slackpoolsecret", // in paths printed without a scheme
gitHubToken[4:], gitHubFineGrained[11:], // GitHub tokens anywhere
"vars-value-must-not-leak", "extra-value-must-not-leak", // free-form SDK data
"/home/deploy", "/home/runner", "redis-password",
"alice@example.com", "BOB@EXAMPLE.COM", "carol@example.com", "dave@example.com", "erin@example.com", "192.168.1.5", "10.1.2.3", // breadcrumb and mechanism fields
Expand All @@ -97,6 +98,12 @@ func TestBuildLeavesOutSensitiveData(t *testing.T) {
}
}

// GitHub tokens are built here, so no whole one sits in the repository.
var (
gitHubToken = "ghp_" + strings.Repeat("a1B2", 9)
gitHubFineGrained = "github_pat_" + strings.Repeat("A1b2", 5) + "c3_" + strings.Repeat("d4E5f", 11) + "g6h7"
)

func build(t *testing.T) string {
t.Helper()

Expand All @@ -114,6 +121,8 @@ func build(t *testing.T) string {
{Time: time.Now(), Level: "warn", Body: "pool exhausted, connecting to redis://:redis-password@127.0.0.1:6379"},
{Time: time.Now(), Level: "error", Body: "HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot123456789:AAEhBOweik6ad9r_QXMENQjcrGbqCr4K-x4/getUpdates"},
{Time: time.Now(), Level: "error", Body: "HTTPSConnectionPool(host='hooks.slack.com', port=443): Max retries exceeded with url: /services/T0AAAAAAA/B0BBBBBBB/slackpoolsecret"},
{Time: time.Now(), Level: "error", Body: "git push rejected for " + gitHubToken + " on main"},
{Time: time.Now(), Level: "error", Body: "clone /acme/app.git?ref=" + gitHubFineGrained + " failed"},
},
LogsFromRequest: true,
})
Expand Down Expand Up @@ -236,6 +245,9 @@ func TestRedact(t *testing.T) {
"open C:\\Users\\alice\\app\\main.go": "open ~\\app\\main.go",
"version 1.2.3 of lib": "version 1.2.3 of lib",
"token 123456789:AAEhBOweik6ad9r_QXMENQjcrGbqCr4K-x4 refused": "token <token> refused",
"push failed with " + gitHubToken + " as the remote": "push failed with <token> as the remote",
"githubpat=" + gitHubFineGrained + " on clone": "githubpat=<token> on clone",
"a ghost_story about ghp_abc": "a ghost_story about ghp_abc",
}

for input, want := range testCases {
Expand Down
2 changes: 1 addition & 1 deletion internal/api/audit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ func TestAuditActors(t *testing.T) {
// them, while their change of the viewer's issue stays in the log.
moved := store.OnlyProjects(2)

if err := server.database.UpdateUser(context.Background(), stranger.id, store.UserChange{Name: "Web user", Role: store.RoleUser, Access: &moved}); err != nil {
if err := server.database.UpdateUser(context.Background(), stranger.id, store.UserChange{Name: "Web user", Role: store.RoleUser, By: store.User{ID: admin.id, Role: store.RoleAdmin}, Access: &moved}); err != nil {
t.Fatal(err)
}

Expand Down
20 changes: 4 additions & 16 deletions internal/api/cleanups.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,6 @@ type cleanupRun struct {
// the difference, so data arriving meanwhile does not hide what it did.
SizeAfter string `json:"size_after"`
Freed string `json:"freed"`
// BeforeFiles: a run stored before the data held was measured apart;
// its sizes are the files', and after and freed are left out (empty).
BeforeFiles bool `json:"before_files,omitempty"`
// Arrived is the data that came meanwhile and SizeNow the data held at
// the end, both only when that is over arrivedPercent of the limit.
Arrived string `json:"arrived,omitempty"`
Expand Down Expand Up @@ -165,7 +162,6 @@ func cleanups(runs []services.ShownRun, projectName func(id int) string, now tim
}

view.SizeAfter, view.Freed, view.Arrived, view.SizeNow = cleanupSizes(shown)
view.BeforeFiles = run.Ratio == 0 && run.Reached > 0

if run.Files > 0 {
view.Files = config.FormatSize(run.Files)
Expand Down Expand Up @@ -252,17 +248,9 @@ const arrivedPercent = 1

// cleanupSizes reads a run from the data it started with: after, what it
// freed, and the data that arrived meanwhile with the data held at the end
// once sizable. A run stored before Ratio measured the files, so it has none.
// once sizable.
func cleanupSizes(shown services.ShownRun) (after, freed, arrived, now string) {
run, left, known := shown.Run, shown.Left, shown.Known

if !known {
if run.Reached == 0 {
return config.FormatSize(run.SizeAfter), config.FormatSize(max(run.SizeBefore-run.SizeAfter, 0)), "", ""
}

return "", "", "", ""
}
run, left := shown.Run, shown.Left

after, freed = config.FormatSize(left), config.FormatSize(max(run.SizeBefore-left, 0))

Expand Down Expand Up @@ -332,10 +320,10 @@ const othersFreed = "other deletes meanwhile freed the rest of what was needed"
// deletes beside it (a purged project, deleted issues or logs) brought the
// data down and it stopped early. The slack covers the goal's rounding.
func shortOf(shown services.ShownRun) bool {
run, left, known := shown.Run, shown.Left, shown.Known
run, left := shown.Run, shown.Left
need := run.Need(config.CleanupStopPercent)

return known && run.Compacted-left < need-need/1000-int64(run.Ratio)-2
return run.Compacted-left < need-need/1000-int64(run.Ratio)-2
}

// stepNumbers reads the steps that deleted something as "1, 4–7".
Expand Down
14 changes: 2 additions & 12 deletions internal/api/cleanups_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@ func TestCleanupResult(t *testing.T) {
fmt.Sprintf("every step ran, still above %d%%", stop)},
{"every step ran short of the files' goal", started(store.CleanupRun{Reached: store.CleanupSteps, Files: 1600, Steps: freed(enough)}),
"every step ran, still short of what was needed"},
{"stored before the ratio", store.CleanupRun{Status: store.CleanupDone, Reached: store.CleanupSteps}, "every step ran"},
{"compacting was enough", store.CleanupRun{Status: store.CleanupDone}, "compacting was enough, nothing deleted"},
{"running", store.CleanupRun{Status: store.CleanupRunning, Reached: 3}, "running, at step 3"},
{"failed", started(store.CleanupRun{Status: store.CleanupFailed, Reached: 5, Error: "the limit changed"}), "failed in step 5"},
Expand All @@ -83,8 +82,8 @@ func TestCleanupSizesFromTheStart(t *testing.T) {
SizeAfter: sizeNow, Reached: 6, Steps: []store.CleanupStep{{Number: 5, Freed: 300 * megabyte}, {Number: 6, Freed: 500 * megabyte}},
}
}
output := cleanups(shownToAll(run(1700*megabyte), run(1605*megabyte), store.CleanupRun{Status: store.CleanupDone, SizeBefore: 900, SizeAfter: 700, Reached: 6}), func(id int) string { return fmt.Sprint(id) }, time.Now())
flood, quiet, before := output.Runs[0], output.Runs[1], output.Runs[2]
output := cleanups(shownToAll(run(1700*megabyte), run(1605*megabyte)), func(id int) string { return fmt.Sprint(id) }, time.Now())
flood, quiet := output.Runs[0], output.Runs[1]

if flood.SizeBefore != config.FormatSize(2000*megabyte) || flood.SizeAfter != config.FormatSize(1600*megabyte) || flood.Freed != config.FormatSize(400*megabyte) {
t.Errorf("during a flood: %s → %s (−%s)", flood.SizeBefore, flood.SizeAfter, flood.Freed)
Expand All @@ -97,15 +96,6 @@ func TestCleanupSizesFromTheStart(t *testing.T) {
if quiet.SizeAfter != config.FormatSize(1600*megabyte) || quiet.Arrived != "" || quiet.SizeNow != "" {
t.Errorf("a few MB arrived: %+v", quiet)
}

// Stored before the ratio: its sizes are the files', and one left running across the upgrade ends with the data held, so after is left out.
if !before.BeforeFiles || before.SizeBefore != config.FormatSize(900) || before.SizeAfter != "" || before.Freed != "" || before.Arrived != "" {
t.Errorf("stored before: %+v", before)
}

if flood.BeforeFiles {
t.Error("a run with its ratio reads as the data held")
}
}

// Steps read as ranges, durations are rounded, and a deleted project is named by its ID.
Expand Down
3 changes: 1 addition & 2 deletions internal/api/logs_ui_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import (
"github.com/devforth/exceptic/internal/storage/store"
)

// The logs list deletes chosen lines, or every log like one (its project's
// copies of the same message), for admins only.
// The logs list deletes chosen lines, for admins only.
func TestUIDeleteLogs(t *testing.T) {
server := newRESTServer(t)
admin := server.webUser(store.RoleAdmin, false)
Expand Down
2 changes: 1 addition & 1 deletion internal/api/manage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func TestToolsFollowTheRole(t *testing.T) {
}

// Made an admin: the next request offers the admin tools.
if err := server.database.UpdateUser(context.Background(), userID, store.UserChange{Role: store.RoleAdmin}); err != nil {
if err := server.database.UpdateUser(context.Background(), userID, store.UserChange{Role: store.RoleAdmin, By: store.User{ID: "operator", Role: store.RoleAdmin}}); err != nil {
t.Fatal(err)
}

Expand Down
63 changes: 63 additions & 0 deletions internal/ingest/drain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,66 @@ func TestWriterStopsAtTheDrainDeadline(t *testing.T) {
t.Errorf("%d events counted as dropped, want %d", lost, waiting)
}
}

// endingContext ends after its first live checks, as the drain's deadline coming mid-batch.
type endingContext struct {
context.Context
live *int
}

func (ending endingContext) Err() error {
if *ending.live > 0 {
*ending.live--

return nil
}

return context.Canceled
}

// A batch written one envelope at a time (one of them cannot be encoded) and
// cut by the drain's deadline counts as dropped only what it did not store.
func TestCutBatchLosesOnlyWhatItDidNotStore(t *testing.T) {
db := storetest.Open(t)
storetest.AddProjects(t, db, fixtures.Projects())
pipeline := NewPipeline(slog.New(slog.DiscardHandler), testSettings(), fixtures.Projects(), db, StoreSink{Logger: slog.New(slog.DiscardHandler)})
budget := semaphore.NewWeighted(pipeline.ParseBytes)
results := make(chan processed, 3)

for index := range 3 {
entry, err := db.Append(1, time.Now(), eventEnvelope())

if err != nil {
t.Fatal(err)
}

db.TakeInbox(1)

_ = budget.Acquire(context.Background(), pipeline.weight(entry.Size))

result, ok := pipeline.process(entry)

if !ok {
t.Fatal("entry not processed")
}

if index == 1 {
result.Events[0].Timestamp = time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC) // JSON cannot encode it
}

results <- result
}

close(results)

live := 2 // the batch, then the first envelope alone
pipeline.write(endingContext{context.Background(), &live}, results, budget)

if counted := countedEvents(t, db); counted != 1 || pipeline.stored.Load() != 1 {
t.Fatalf("%d events stored, %d envelopes counted stored; want the first", counted, pipeline.stored.Load())
}

if lost := pipeline.Dropped().Unsaved()[1].Events; lost != 2 {
t.Errorf("%d events counted as dropped, want the 2 not stored", lost)
}
}
17 changes: 10 additions & 7 deletions internal/ingest/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -489,31 +489,33 @@ func (pipeline *Pipeline) write(ctx context.Context, results <-chan processed, b
// commit stores a batch, frees what its envelopes held and reports the stored events.
func (pipeline *Pipeline) commit(ctx context.Context, batch []processed, budget *semaphore.Weighted, lost *lostEnvelopes) {
saved, stored := pipeline.storeBatch(ctx, batch)
// Cut while written one envelope at a time, the batch stored its first ones.
done := batch[:len(saved)]

if !stored {
pipeline.lose(batch, lost)
pipeline.lose(batch[len(saved):], lost)
}

for _, envelope := range batch {
budget.Release(pipeline.weight(envelope.InboxSize))
pipeline.diskInFlight.Delete(envelope.Sequence)
}

if !stored {
if len(done) == 0 {
return
}

pipeline.stored.Add(int64(len(batch)))
pipeline.stored.Add(int64(len(done)))

var bytes int64

for _, envelope := range batch {
for _, envelope := range done {
bytes += int64(envelope.InboxSize)
}

pipeline.rate.add(pipeline.now(), bytes)

for index, envelope := range batch {
for index, envelope := range done {
for position, result := range saved[index] {
pipeline.report(envelope, position, result)
}
Expand Down Expand Up @@ -564,7 +566,8 @@ func (pipeline *Pipeline) report(envelope processed, position int, result store.
}

// storeBatch retries every second until ctx ends (a batch after it is not tried), then it is lost. A record
// that cannot be encoded fails every retry, so the batch is then written one envelope at a time, dropping that one.
// that cannot be encoded fails every retry, so the batch is then written one envelope at a time, dropping that one;
// cut by ctx, it returns the results of those stored before.
func (pipeline *Pipeline) storeBatch(ctx context.Context, batch []processed) ([][]store.SaveResult, bool) {
if ctx.Err() != nil {
return nil, false
Expand Down Expand Up @@ -608,7 +611,7 @@ func (pipeline *Pipeline) storeOneByOne(ctx context.Context, batch []processed)
saved, stored := pipeline.storeBatch(ctx, batch[index:index+1])

if !stored {
return nil, false
return results[:index], false
}

results[index] = saved[0]
Expand Down
1 change: 1 addition & 0 deletions internal/ingest/prepare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -817,6 +817,7 @@ func TestQuotesInTextStayLinear(t *testing.T) {
"escaped quotes": `"token": [` + strings.Repeat(`\\\"a`, size/5),
"service paths": strings.Repeat("/services/T1/B1/a bot1:a webhooks/1/a ", size/38),
"digits and colons": strings.Repeat("1:", size/2),
"github prefixes": strings.Repeat("ghp_a1 github_pat_"+strings.Repeat("a1", 11)+"_b2 ", size/48),
} {
started := time.Now()

Expand Down
Loading
Loading