Skip to content
Open
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
2 changes: 1 addition & 1 deletion CLAUDE.md

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ Projects are added on the Projects page (or by a coding agent with `create_proje
| `RATE_LIMIT_LOGS_PER_MINUTE` | `10000` | Logs a project may send per minute. Keep it at least `100`, the most logs the JavaScript SDK sends at once. `0` = no limit. |
| `RECORD_LOG_LEVELS` | `all` | Log levels to store: `fatal`, `error`, `warn`, `info`, `debug`, `trace`, or `all`/`none`. A project can choose its own. Errors of every level are always stored. |

What the server accepted waits in a queue until it is stored, up to 20% of `MAX_DATABASE_SIZE`. Each active project (connected or holding data, not paused) may fill only its part of the queue, by its disk share: 4 projects at 100% get a quarter each, a project at 50% half as much as one at 100%. Every active project keeps at least 5% of the queue, and at least 20 MB. A project over its part is told to wait a few seconds (429) while the others are still accepted.

### Size limits

These are fixed.
Expand Down
2 changes: 1 addition & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ How much the server can take at most, by CPU: the most errors it stored while 10

Logs sent along take their share: with 5 logs per error, about a third fewer errors.

Above that, apps pause for a few seconds and then send again. What they drop meanwhile shows on the Projects page.
Above that, apps pause for a few seconds and then send again. What they drop meanwhile shows on the Projects page. A project that sends more than its part of the queue is paused alone ([Ingest](configuration.md#ingest)).

## Backup and restore

Expand Down
4 changes: 2 additions & 2 deletions docs/ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ A project is one service (backend, frontend, worker) with its own DSN. Deleting
| Field | |
|---|---|
| Color | The color of the project's badge in lists and emails. |
| DSN | The address the app's Sentry SDK sends to. Safe to put in browser code: it only allows sending to this project. Reset DSN on the Installation page gives a new one and stops the old one. |
| DSN | The address the app's Sentry SDK sends to. Safe to put in browser code: it only allows sending to this project. Reset DSN on the Installation page gives a new one and stops the old one; the project shows as connected again once an app sends with the new one. |
| Paused | While paused, nothing the project's apps send is stored or notified. |
| Logs | Log levels to store; others are dropped. Errors of every level are always stored. |
| Disk share | The part of MAX_DATABASE_SIZE the project may take. When it reaches 99% of it, the project's own oldest data is deleted down to 80% of its share, so a flood in one project does not push out the others. 100% means no limit of its own. |
| Allowed domains | Sites whose browsers may send to the project, e.g. `https://app.example.com` or `https://*.example.com`. Empty: any site. Backend apps are not checked. |
| History kept | The oldest record of each kind still stored. When the database is full, the least useful data goes first ([Retention](configuration.md#retention)). |
| Dropped | What the project sent in the last 24 hours that was not stored: over its rate limit, the server busy, too large or unreadable. Resets on restart. |
| Dropped | What the project sent in the last 24 hours that was not stored: over its rate limit, over its part of the queue, the server busy, too large or unreadable. Resets on restart. |

## Notifications

Expand Down
3 changes: 3 additions & 0 deletions docs/values_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func TestDocsValues(t *testing.T) {
value{Phrase: "REST API](api.md), at least {} characters", Value: config.MinAPITokenLength},
value{Phrase: "| `RATE_LIMIT_EVENTS_PER_MINUTE` | `{}` |", Value: config.DefaultRateLimitEventsPerMinute},
value{Phrase: "| `RATE_LIMIT_LOGS_PER_MINUTE` | `{}` |", Value: config.DefaultRateLimitLogsPerMinute},
value{Phrase: "until it is stored, up to {}% of `MAX_DATABASE_SIZE`", Value: config.InboxPercent},
value{Phrase: "Keep it at least `{}`, the most logs", Value: config.SDKLogBatch},
value{Phrase: "Log levels to store: {}, or `all`/`none`", Value: "`" + strings.Join(config.HighestFirst(config.LogLevels), "`, `") + "`"},
value{Phrase: "**Logs:** the body {} KB;", Value: config.MaxLogBodyBytes >> 10},
Expand All @@ -48,6 +49,8 @@ func TestDocsValues(t *testing.T) {
value{Phrase: "| `NOTIFY_RETRY_FOR` | `{}` |", Value: days(config.DefaultNotifyRetryFor)},
value{Phrase: "| `NOTIFY_KEEP_SENT` | `{}` |", Value: days(config.DefaultNotifyKeepSent)},
value{Phrase: "| `NOTIFY_KEEP_FAILED` | `{}` |", Value: days(config.DefaultNotifyKeepFailed)},
value{Phrase: "keeps at least {}% of the queue", Value: config.MinInboxSharePercent},
value{Phrase: "of the queue, and at least {} MB", Value: ingest.MaxBodyBytes >> 20},
value{Phrase: "| `MAX_DATABASE_SIZE` | `{}` |", Value: size(config.DefaultMaxDatabaseBytes)},
value{Phrase: "reaches {}% of it, the least useful", Value: config.CleanupStartPercent},
value{Phrase: "an email, up to {} characters", Value: config.MaxEmail},
Expand Down
3 changes: 2 additions & 1 deletion internal/ingest/dropped.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,14 @@ const (
var dropKindNames = [dropKindCount]string{"events", "logs", "envelopes"}

// dropReasons are store.DropReasons by index.
var dropReasons = []string{store.DropRateLimit, store.DropBusy, store.DropTooLarge, store.DropInvalid, store.DropIncomplete, store.DropSDKRateLimit, store.DropSDKOverflow}
var dropReasons = []string{store.DropRateLimit, store.DropBusy, store.DropQueueShare, store.DropTooLarge, store.DropInvalid, store.DropIncomplete, store.DropSDKRateLimit, store.DropSDKOverflow}

type dropReason int

const (
dropRateLimit dropReason = iota
dropBusy
dropQueueShare
dropTooLarge
dropInvalid
dropIncomplete
Expand Down
4 changes: 3 additions & 1 deletion internal/ingest/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func (handler *Handler) ingest(w http.ResponseWriter, r *http.Request) (response

// Any request with the key connects the project: SDKs send a session at
// start, long before an error.
handler.pipeline.markContact(project.ID, handler.now())
handler.pipeline.markContact(project.ID, key, handler.now())

if body == nil {
if body, err = openBody(w, r, handler.reading, projectID); err != nil {
Expand Down Expand Up @@ -273,6 +273,8 @@ func (handler *Handler) countRefused(project config.Project, err error, envelope
switch {
case rejection.rateLimits != "":
return
case rejection == errOverShare:
reason = dropQueueShare
case rejection.status == http.StatusRequestEntityTooLarge:
reason = dropTooLarge
case rejection.incomplete:
Expand Down
1 change: 1 addition & 0 deletions internal/ingest/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func startTestServer(t *testing.T, settings *config.Config, projects config.Proj
t.Helper()

db := storetest.Open(t)
storetest.AddProjects(t, db, projects)
pipeline := NewPipeline(slog.New(slog.DiscardHandler), settings, projects, db, sink)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
Expand Down
45 changes: 31 additions & 14 deletions internal/ingest/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"log/slog"
"net/http"
"runtime"
"sync"
"sync/atomic"
Expand All @@ -30,6 +29,8 @@ type Pipeline struct {

// MaxInboxBytes: beyond it new envelopes get 429.
MaxInboxBytes int64
// MinInboxShare is the least of the inbox a project may hold (inboxShare).
MinInboxShare int64
// BatchSize, BatchBytes and BatchWait bound one write.
BatchSize int
BatchBytes int
Expand All @@ -49,6 +50,8 @@ type Pipeline struct {
wake chan struct{}

stored atomic.Int64 // envelopes stored since start
// withData are the projects with an issue or a log, read every shareRefresh (inboxShare).
withData atomic.Pointer[map[int]bool]
// inFlight holds entries handed out and not stored yet.
inFlight sync.Map

Expand All @@ -71,7 +74,7 @@ func NewPipeline(logger *slog.Logger, settings *config.Config, projects config.P
handler := newHandler(logger, settings, projects)
pipeline := &Pipeline{
handler: handler, store: db, sink: sink, logger: logger,
MaxInboxBytes: config.MaxInboxBytes(config.DefaultMaxDatabaseBytes), LogsPerMessage: config.LogsPerMessage, EventsPerIssue: config.EventsPerIssuePerMinute, BatchSize: 512, BatchBytes: 4 << 20, BatchWait: 5 * time.Millisecond, ParseBytes: 32 << 20, Rescan: 10 * time.Second,
MaxInboxBytes: config.MaxInboxBytes(config.DefaultMaxDatabaseBytes), MinInboxShare: MaxBodyBytes, LogsPerMessage: config.LogsPerMessage, EventsPerIssue: config.EventsPerIssuePerMinute, BatchSize: 512, BatchBytes: 4 << 20, BatchWait: 5 * time.Millisecond, ParseBytes: 32 << 20, Rescan: 10 * time.Second,
fresh: make(chan database.InboxEntry, 4*runtime.GOMAXPROCS(0)), wake: make(chan struct{}, 1), progress: make(chan struct{}),
}
handler.pipeline = pipeline
Expand Down Expand Up @@ -123,14 +126,16 @@ func (pipeline *Pipeline) setWriting(writing bool) {
const inboxFullRetry = "10"

func (pipeline *Pipeline) accept(project config.Project, envelope *sentry.Envelope, body []byte) (map[string]string, error) {
if pipeline.store.InboxBytes() > pipeline.MaxInboxBytes {
return nil, &requestError{status: http.StatusTooManyRequests, message: "server busy", retryAfter: inboxFullRetry}
}

entry, err := pipeline.store.Append(project.ID, pipeline.handler.now(), body)
limit := database.InboxLimit{Total: pipeline.MaxInboxBytes, Own: pipeline.inboxShare(project)}
entry, err := pipeline.store.AppendWithin(project.ID, pipeline.handler.now(), body, limit)

if errors.Is(err, database.ErrCompacting) {
switch {
case errors.Is(err, database.ErrCompacting):
return nil, errCompacting
case errors.Is(err, database.ErrInboxFull):
return nil, errInboxFull
case errors.Is(err, database.ErrOverShare):
return nil, errOverShare
}

if err != nil {
Expand Down Expand Up @@ -159,8 +164,8 @@ func (pipeline *Pipeline) accept(project config.Project, envelope *sentry.Envelo

// markContact records the project's first request with its key, once; a
// failure only logs, since the envelope can still be stored.
func (pipeline *Pipeline) markContact(projectID int, at time.Time) {
if _, err := pipeline.store.MarkContact(projectID, at); err != nil {
func (pipeline *Pipeline) markContact(projectID int, key string, at time.Time) {
if _, err := pipeline.store.MarkContact(projectID, key, at); err != nil {
pipeline.logger.Error("mark project connected", "project", projectID, "err", err)
}
}
Expand All @@ -186,7 +191,13 @@ func (pipeline *Pipeline) Run(ctx context.Context) {
}()
}

writerDone := make(chan struct{})
writerDone, sharesDone := make(chan struct{}), make(chan struct{})

go func() {
defer close(sharesDone)

pipeline.refreshShares(ctx)
}()

go func() {
defer close(writerDone)
Expand All @@ -199,6 +210,7 @@ func (pipeline *Pipeline) Run(ctx context.Context) {
processors.Wait()
close(results)
<-writerDone
<-sharesDone
}

// dispatch hands fresh entries, and the inbox's at start, after a full queue and every Rescan.
Expand Down Expand Up @@ -304,13 +316,18 @@ func (pipeline *Pipeline) processOrDrop(entry database.InboxEntry) (result proce
if recovered := recover(); recovered != nil {
pipeline.logger.Error("envelope dropped: processing it panicked", "project_id", entry.ProjectID, "err", logging.PanicError(recovered))

result, ok = processed{Envelope: database.Envelope{Sequence: entry.Sequence, InboxSize: entry.Size}}, true
result, ok = processed{Envelope: inboxEnvelope(entry)}, true
}
}()

return pipeline.process(entry)
}

// inboxEnvelope is what deletes an entry from the inbox, with no records yet.
func inboxEnvelope(entry database.InboxEntry) database.Envelope {
return database.Envelope{Sequence: entry.Sequence, InboxSize: entry.Size, InboxProject: entry.ProjectID}
}

// process reads an entry's body and parses it; a malformed one only leaves the inbox.
// An entry already stored (handed again from fresh after a scan) gives nothing.
func (pipeline *Pipeline) process(entry database.InboxEntry) (processed, bool) {
Expand All @@ -324,7 +341,7 @@ func (pipeline *Pipeline) process(entry database.InboxEntry) (processed, bool) {
return processed{}, false
}

result := processed{Envelope: database.Envelope{Sequence: entry.Sequence, InboxSize: entry.Size}}
result := processed{Envelope: inboxEnvelope(entry)}
project, ok := pipeline.handler.projects.List().ByID(entry.ProjectID)

if !ok {
Expand Down Expand Up @@ -484,7 +501,7 @@ func (pipeline *Pipeline) storeOneByOne(ctx context.Context, batch []processed)
func (pipeline *Pipeline) drop(ctx context.Context, entry processed, reason error) ([][]store.SaveResult, bool) {
pipeline.logger.Error("envelope dropped: it cannot be stored", "project", entry.project.Name, "err", reason)

empty := processed{Envelope: database.Envelope{Sequence: entry.Sequence, InboxSize: entry.InboxSize}, project: entry.project}
empty := processed{Envelope: database.Envelope{Sequence: entry.Sequence, InboxSize: entry.InboxSize, InboxProject: entry.InboxProject}, project: entry.project}

if _, stored := pipeline.storeBatch(ctx, []processed{empty}); !stored {
return nil, false
Expand Down
119 changes: 119 additions & 0 deletions internal/ingest/share.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package ingest

import (
"context"
"net/http"
"time"

"github.com/devforth/exceptic/internal/platform/config"
"github.com/devforth/exceptic/internal/platform/logging"
"github.com/devforth/exceptic/internal/storage/store"
)

// shareRefresh is how often the projects with stored data are read again;
// a project whose data was all deleted counts as active for at most that long.
const shareRefresh = time.Minute

// errInboxFull: the inbox holds MaxInboxBytes; errOverShare: the project
// holds its share of it (inboxShare), while the other projects are still
// accepted. A project with nothing queued is always accepted, so the shares
// count only under load (database.InboxLimit, checked and added under one lock).
var (
errInboxFull = &requestError{status: http.StatusTooManyRequests, message: "server busy", retryAfter: inboxFullRetry}
errOverShare = &requestError{status: http.StatusTooManyRequests, message: "server busy: the project's share of the queue is full", retryAfter: inboxFullRetry}
)

// inboxShare is the bytes of the inbox a project may hold: MaxInboxBytes
// split among the active projects by their disk shares (100% weighs 1, 50%
// a half), the project itself always counted. Active: not paused, and
// connected (FirstContact, which a DSN reset clears) or holding data.
// The floor is config.MinInboxSharePercent of the inbox, and at least
// MinInboxShare (one largest envelope, MaxBodyBytes), so a project of a small
// share among many still queues enough, unless the whole inbox is smaller;
// the floors may add up to more than the inbox, whose own limit still holds.
func (pipeline *Pipeline) inboxShare(project config.Project) int64 {
active := pipeline.withData.Load()
own := shareWeight(project)
total := own

for _, other := range pipeline.handler.projects.List() {
if other.ID == project.ID || other.Paused {
continue
}

_, connected := pipeline.store.FirstContact(other.ID)

if connected || (active != nil && (*active)[other.ID]) {
total += shareWeight(other)
}
}

share := int64(float64(pipeline.MaxInboxBytes) * float64(own) / float64(total))

floor := max(pipeline.MinInboxShare, pipeline.MaxInboxBytes*config.MinInboxSharePercent/100)

return max(share, min(floor, pipeline.MaxInboxBytes))
}

// shareWeight is the project's disk share in percent.
func shareWeight(project config.Project) int64 {
return int64(store.Project{DiskShare: project.DiskShare}.Share())
}

// refreshShares reads the projects with data at once, then every shareRefresh until ctx ends.
func (pipeline *Pipeline) refreshShares(ctx context.Context) {
ticker := time.NewTicker(shareRefresh)

defer ticker.Stop()

for {
pipeline.readWithData(ctx)

select {
case <-ctx.Done():
return
case <-ticker.C:
}
}
}

// readWithData reads the projects with an issue (from the issue counts) or a
// log (one seek each); a failure, or a panic, keeps the last set.
func (pipeline *Pipeline) readWithData(ctx context.Context) {
defer func() {
if recovered := recover(); recovered != nil {
pipeline.logger.Error("read projects with data panicked", "err", logging.PanicError(recovered))
}
}()

projects := pipeline.handler.projects.List()
ids := make([]int, len(projects))

for index, project := range projects {
ids[index] = project.ID
}

issues, err := pipeline.store.IssueProjects(ctx)

if err != nil {
pipeline.logger.Error("read projects with issues", "err", err)

return
}

logs, err := pipeline.store.LogProjects(ctx, ids)

if err != nil {
pipeline.logger.Error("read projects with logs", "err", err)

return
}

active := map[int]bool{}

for _, id := range append(issues, logs...) {
active[id] = true
}

pipeline.withData.Store(&active)
}
Loading
Loading