From c6a2c9d4eb0da280728c6b6bebb84da18d84e460 Mon Sep 17 00:00:00 2001 From: Ivan Husev Date: Fri, 27 Nov 2026 16:41:13 +0200 Subject: [PATCH] feat: each active project may hold only its part of the ingest queue by its disk share, at least 5%; over it only that project waits DevFo-OSS/17 --- CLAUDE.md | 2 +- docs/configuration.md | 2 + docs/deployment.md | 2 +- docs/ui.md | 4 +- docs/values_test.go | 3 + internal/ingest/dropped.go | 3 +- internal/ingest/handler.go | 4 +- internal/ingest/handler_test.go | 1 + internal/ingest/pipeline.go | 45 ++++-- internal/ingest/share.go | 119 ++++++++++++++++ internal/ingest/share_test.go | 130 ++++++++++++++++++ internal/platform/config/retention.go | 4 + .../storage/database/cleanup_live_test.go | 2 +- .../database/cleanup_share_size_test.go | 2 +- internal/storage/database/cleanup_test.go | 2 +- internal/storage/database/compaction_test.go | 2 +- internal/storage/database/inbox.go | 93 +++++++++++-- .../storage/database/project_usage_test.go | 6 +- internal/storage/database/projects.go | 29 +++- internal/storage/database/store.go | 5 +- internal/storage/database/store_test.go | 113 ++++++++++++++- internal/storage/database/write.go | 10 +- internal/storage/store/dropped.go | 2 + web/src/lib/api/catalog.gen.ts | 4 +- 24 files changed, 539 insertions(+), 50 deletions(-) create mode 100644 internal/ingest/share.go create mode 100644 internal/ingest/share_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 76383b0..71442ae 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -121,7 +121,7 @@ Where to look first: - `internal/ingest` (`truncate.go`): the size limits (`config.MaxLog*`, `config.MaxEvent*`), applied after scrubbing, so no secret is stored cut in half; cut, never dropped, a text ending with "…" (`textutil.ShortenBytes`). `limitLog` (in `parseItems`, after `ParseLogs` has read the span id): `trace_id`/`span_id` to 64 bytes, attribute names to 256 and types to 32, the body, at most 64 attributes (`compareAttributes`: `sentry.ParentSpanAttribute`, the other `sentry.*`, then the rest, each by name; `json.Marshal` sorts them anyway), each value (another type than string, that long, becomes its JSON text). `truncateEvent` (the end of `prepareEvent`): a token pass over the prepared event, `eventCutter`, that cuts every string value to 16 KB; while the event is over 1 MB it is tried again from the prepared event with one more cut (`cutBreadcrumbs` to the newest 10, `cutExtra`, `cutRequestData`, `cutContexts` but runtime/os/browser/trace, `cutFrameVars`, `cutFrameContext` (pre/post_context; `context_line` stays for grouping), `cutOther`: only `store.ErrorFields` (also what thinning keeps) and contexts), then `cutSize` (`fitted`: whatever is still over 1 MB keeps its smallest members and a list's newest elements whole, up to 8 levels deep; the cut `size`), so at most 9 linear passes and the fit; the names of the cuts that removed something go into `sentry.TruncatedField` (`_exceptic_truncated`, appended to the object); an event needing none comes back byte for byte (`TestNormalEventsAreNotCut`). The tree reference of `prepare_test.go` applies the same cuts (`referenceTruncate`), deciding on its own encoding's size; `TestLargeEventsStayLinear`. - `internal/ingest` (`scrub.go`): removes credentials from SDK payloads before they are parsed or stored (ingest calls it), so the web app, the API, notifications and stored records never hold the session cookies or tokens of the monitored app's users; only the inbox holds the envelope as it came until it is processed (and a backup taken meanwhile; its bytes stay in the files until a compaction, see the cleanup). Keys are read as words (`isSensitiveKey`, `namesSecret`: split at separators, camel case and digits, Unicode folded to ASCII, remembered in a bounded cache): a word that is a secret (`secretWords`: password, token, auth, cookie, session, sid, api key, dsn, jwt, ssn, cvv, iban, pin, otp, …), ends with one (`csrftoken`), or is one only after certain words (`card_number`, `recovery_codes`, `webhook_url`; `key` after any word but those of `plainKeys`, so `APP_KEY` but not `public_key`), unless a later word describes it (`session_count`, `token_expires_at`, `SessionNotFound`) or the key starts with `is`/`has`; so `author`, `className` or `tokenizer` stay; password in other languages counts (`пароль`, `mot_de_passe`), and the `number` of an object under a card's name (`card`, `billing_card`: `isCardKey`). Source lines (`context_line`, `pre_context`, `post_context`: `sourceFields`) are code (`scrubSourceText`): a pair's value goes only when it is a string literal, so grouping input and `token = sign(key)` stay. The whole value under such a key goes (an object with a `value` member becomes `{"type":"string","value":"[Filtered]"}`, so log attributes keep their shape); a `[name, value]` pair in a list too; cookies (`cookies`, a `Cookie` header, as an object, a string or pairs) one by one, keeping only `harmlessCookies` (theme, lang, …). A removed value becomes `[Filtered]` (`filteredText`, `%5BFiltered%5D` inside URLs); only values change, the rest stays byte for byte. Strings (`scrubText`): one that is a JSON object or array (a request body sent as text) is scrubbed by the payload's rules (`scrubJSONText`, one level: its own strings are free text, `TestNestedDocumentsInTextStayLinear`); free text (`scrubFreeText`) loses PEM private key bodies (BEGIN/END lines kept), the tokens chat services put into URL paths (`textutil.ReplaceServiceTokens`, shared with `agentprompt`: Telegram `bot:`, Slack `/services/…`, Discord `/api/webhooks/…`), the values of multipart form fields with a secret's name (`scrubMultipart`), the values of `"key": value` and `'key': value` pairs (`scrubQuotedPairs`: strings, numbers, and arrays or objects by one bracket count that skips strings, `collectionEnd`), the credentials of authorization schemes (Bearer, Basic (also `user:password`), Token, ApiKey, Digest, AWS4-HMAC-SHA256, Negotiate, NTLM; a token, not a word or a pair: `isSchemeToken`, after `token` 16+ characters with a digit, so `Unexpected token NumericLiteral` stays) and of curl's `-u`/`--user`, unquoted `key=value`, `key: value` and `key => value` pairs (`scrubKeyValues`: logfmt, env dumps, connection strings, header lines (Authorization keeps its scheme, Cookie its harmless cookies), the reprs of Python, Ruby, PHP, Java, Go, Node, GraphQL arguments; a key quoted, `[bracketed]` or escaped at any depth, so JSON encoded in JSON on any level or a body encoded twice is caught by its `\"key\": \"value\"` (`escapedQuote`, at most 64 backslashes); after `key: ` with a space the key must open a field (or the value be quoted) and the value look like a token (`looksLikeToken`: hyphenated lowercase names are words), so `Invalid token: expired` stays; an unquoted value also stays when it is a literal (`null`, `true`), a number of under 6 digits under a name that holds no numbers (`namesNumericSecret`: `session: 401`, `pass=118`, but `pin: 1234`), followed by prose after a spaced separator (`token: 3 retries left`), or a line number after a file name (`token.ts:42:13`); ends of values and lines are searched once per scan (`nextIndex`), so refused header lines in quotes stay linear), in URLs (absolute, relative such as `GET /reset?token=… 200`, bare query strings, each found inside text, nested ones in a query included) the userinfo password (it may hold `/?#@`; the user stays) and the parameters of the query, fragment and path (`;jsessionid=`) whose name names a secret or is `code` or `key` (`credentialParameters`, not in a bare `code=ERR_NETWORK` of one pair), and card numbers (13 to 19 digits, grouped or not, network length and Luhn; also JSON numbers). SDKs with `sendDefaultPii` send request cookies and the `Authorization` header, so the rules apply to every part of a payload. It is one pass over the JSON tokens (`encoding/json/jsontext`, `scrubValue`/`scrubObject`/`scrubValues`), no tree; only an array led by a secret's name is read as a tree, so deep nesting stays linear (`TestDeepNestingStaysLinear`); every text scan is one pass with bounded look-back (`*StayLinear` tests in `prepare_test.go`). Bare tokens without a key name stay (the agent prompt masks them, `agentprompt.Redact`). Data stored before it existed is not rewritten. - Levels to record: events (errors and messages) of every level are stored (issues group them, notification connections filter by level, SDKs filter noise themselves); only logs are filtered: each project may set its own log levels (`Project.LogLevels`; nil = the `RECORD_LOG_LEVELS` default, an empty list = none, kept apart through JSON by `keepNone`; the form stores the default as nil (`chosenLevels`) so a project follows it). `StoreSink` stores levels under their canonical names (`config.EventLevel`: critical = fatal, warn = warning, log = info, trace = debug, unknown = error; `config.LogLevelOf` for logs: a missing or unknown level from `severity_number` by the OpenTelemetry ranges, else info; `sentry.ParseLogs` leaves `Level` as sent), so filters, notifications and badges never translate them again, and drops logs of levels not recorded before storing. -- `internal/ingest`: `POST /api/{projectID}/envelope/`. Order matters: CORS (`applyCORS`: the project of the path, `config.Project.OriginAllowed`: its `AllowedOrigins`, exact or `scheme://*.domain`, none = any site; no Origin = a backend SDK, never checked; `ALLOWED_ORIGINS` is ignored with a warning at start) → public key (query `sentry_key`, `X-Sentry-Auth`/`Authorization`, or the envelope header `dsn` when sent via a tunnel: only the first line is decompressed for it (a br body, which can only be read whole, is refused there with 401: only sentry-python sends br, always with the key in the request), `requestBody.header`, at most `MaxHeaderBytes`, its buffer growing as bytes arrive; with the key in the request nothing of the body is read before project auth) → project auth (the first request with the key marks the project connected: `database.Store.MarkContact`, collection `project_contact`, written once, then only an in-memory check, `FirstContact`; whatever the items, a session at the SDK's start too) → read/decompress body (gzip, deflate, br (sentry-python); 20 MB cap before and after decompression; all bodies being read share `MaxReadingBytes`, 80 MB, one project at most half of it or `MaxProjectReadingBytes` (about 56 MB, one brotli body's worst case), whichever is larger (`readBudget`, counted as the buffers grow, a br body is read whole first, then the window its stream declares (up to 16 MB, which the decoder may fill before any output) is held while it is decoded in memory, so a stalled client holds only the bytes it sent; 429 with `Retry-After` beyond it), and a body must arrive within `BodyReadTimeout`, 10 s, else 408) → parse the envelope; one without `event` or `log` items gets 200 at once, neither counted nor stored (`storesItems`: spans, sessions and client reports are never limited) → the per-project rate limits (`limits.go`, `rateLimiter`, in memory, one fixed calendar-minute window per project of the registry: `RATE_LIMIT_EVENTS_PER_MINUTE` counts event items, `RATE_LIMIT_LOGS_PER_MINUTE` the logs of log items (`logsInItem` counts the `items` array, its name in any case as the parser reads it (`sentry.FoldedName`), never the SDK's `item_count`; a log item without logs counts once); an item that does not fit is dropped whole and its category stays closed until the minute ends; the envelope goes on without the limited items (`withoutLimited`, `sentry.Envelope.Encode` keeps the header lines as sent) with 200 and `X-Sentry-Rate-Limits: ::project` naming only the limited ones (`error;default;security` for events, as the JS SDK maps every event item to `error`; `log_item` for logs), so the SDK pauses only them; nothing left to store is a 429 with the same header and `Retry-After` (unlike Relay, which answers 429 to a partly accepted envelope too); what the inbox refuses is taken back (`refund`); the first limited envelope of a category in a minute logs one warning (`warnLimited`); only the busy answers (inbox full, read budget, a compaction part: `errCompacting`, `Retry-After: 5`) send `::project`, every category) → the inbox (`Pipeline.accept`: the envelope as it came (or as `Encode` rebuilt it), with the project and the receive time; 429 above `config.MaxInboxBytes`, 20% of `MAX_DATABASE_SIZE` (of its default when the limit is off), so a backlog can never crowd out stored data) and the answer. The queues to the processors carry an entry's sequence, project and size only (`Pending` reads no bodies); a processor reads the body (`InboxBody`, a slice of the engine's copy, `kv.Collection.GetValue`, so one copy, `TestInboxBodyCopiedOnce`) once its bytes fit `ParseBytes` (32 MB for the envelopes being parsed or waiting for the writer, freed when stored), and an entry already stored gives nothing, so one handed both from the fresh queue and by a scan of the inbox is stored once (`TestScanDoesNotStoreTwice`). A processor then runs `scrubJSON` on every log item and, for events, `prepareEvent` (`compactEvent` over the token decoder and encoder of `scrub.go`, one pass, then `truncateEvent`; `prepare_test.go` checks, also as a fuzz target, that it gives what the tree pass it replaced gave) → parse all items → the writer's batch, which also deletes the inbox entry (a batch failing on a record JSON cannot encode is written one envelope at a time and that envelope is dropped, `storeBatch`, since no retry would fix it); an entry whose processing panics is logged and dropped from the inbox (`processOrDrop`), and a panic while reporting a stored event loses only that report. All items are parsed before anything is stored, so a malformed item (not JSON, or not an object) drops the whole envelope. Only `event` and `log` items are stored; other types are dropped. `NewPipeline` builds the handler with its pipeline, so every envelope, the tests' too, goes through the inbox. `StoreSink` computes the grouping fingerprint, maps Sentry types to `store.NewEvent`/`store.NewLog` and reports what the writer stored (log lines, notifications). Rejections are logged at debug level (ingest is public, so warn-level logging would be a flood vector). `DropCounter` (`dropped.go`, `Pipeline.Dropped`, built before the services in `app.New`) counts per project, in memory, in hourly buckets of 24 h, what was refused after the key check (`countRefused`: rate limit by category, busy (429, a store failure), too large (413), invalid (400, 415), incomplete (408, or the client hung up: `requestError.incomplete`); items once parsed, else envelopes) and what `client_report` items say the SDK dropped (`sentry.ParseClientReport`; ratelimit_backoff, queue/buffer/cache overflows and backpressure; sampling, `beforeSend` and `network_error`/`send_error` not: SDKs report the server's refusals that way too, so they would count twice), with one warning per project an hour; reasons and their texts are `store.DropReasons`. +- `internal/ingest`: `POST /api/{projectID}/envelope/`. Order matters: CORS (`applyCORS`: the project of the path, `config.Project.OriginAllowed`: its `AllowedOrigins`, exact or `scheme://*.domain`, none = any site; no Origin = a backend SDK, never checked; `ALLOWED_ORIGINS` is ignored with a warning at start) → public key (query `sentry_key`, `X-Sentry-Auth`/`Authorization`, or the envelope header `dsn` when sent via a tunnel: only the first line is decompressed for it (a br body, which can only be read whole, is refused there with 401: only sentry-python sends br, always with the key in the request), `requestBody.header`, at most `MaxHeaderBytes`, its buffer growing as bytes arrive; with the key in the request nothing of the body is read before project auth) → project auth (the first request with the key marks the project connected: `database.Store.MarkContact`, collection `project_contact`, written once and only while the key is still the project's, so a request with a reset key connects nothing (a DSN reset, `RotateProjectKey`, deletes it), then only an in-memory check, `FirstContact`; whatever the items, a session at the SDK's start too) → read/decompress body (gzip, deflate, br (sentry-python); 20 MB cap before and after decompression; all bodies being read share `MaxReadingBytes`, 80 MB, one project at most half of it or `MaxProjectReadingBytes` (about 56 MB, one brotli body's worst case), whichever is larger (`readBudget`, counted as the buffers grow, a br body is read whole first, then the window its stream declares (up to 16 MB, which the decoder may fill before any output) is held while it is decoded in memory, so a stalled client holds only the bytes it sent; 429 with `Retry-After` beyond it), and a body must arrive within `BodyReadTimeout`, 10 s, else 408) → parse the envelope; one without `event` or `log` items gets 200 at once, neither counted nor stored (`storesItems`: spans, sessions and client reports are never limited) → the per-project rate limits (`limits.go`, `rateLimiter`, in memory, one fixed calendar-minute window per project of the registry: `RATE_LIMIT_EVENTS_PER_MINUTE` counts event items, `RATE_LIMIT_LOGS_PER_MINUTE` the logs of log items (`logsInItem` counts the `items` array, its name in any case as the parser reads it (`sentry.FoldedName`), never the SDK's `item_count`; a log item without logs counts once); an item that does not fit is dropped whole and its category stays closed until the minute ends; the envelope goes on without the limited items (`withoutLimited`, `sentry.Envelope.Encode` keeps the header lines as sent) with 200 and `X-Sentry-Rate-Limits: ::project` naming only the limited ones (`error;default;security` for events, as the JS SDK maps every event item to `error`; `log_item` for logs), so the SDK pauses only them; nothing left to store is a 429 with the same header and `Retry-After` (unlike Relay, which answers 429 to a partly accepted envelope too); what the inbox refuses is taken back (`refund`); the first limited envelope of a category in a minute logs one warning (`warnLimited`); only the busy answers (inbox full, read budget, a compaction part: `errCompacting`, `Retry-After: 5`) send `::project`, every category) → the inbox (`Pipeline.accept`: the envelope as it came (or as `Encode` rebuilt it), with the project and the receive time; 429 above `config.MaxInboxBytes`, 20% of `MAX_DATABASE_SIZE` (of its default when the limit is off), so a backlog can never crowd out stored data; before it each project's part (`share.go`, `inboxShare`: `MaxInboxBytes` split by disk share (`Share`, 100% weighs 1) among the active projects, not paused and connected (`FirstContact`, live) or holding an issue or log (`IssueProjects`, `LogProjects`, read every `shareRefresh`, a minute, by `refreshShares` in `Run`), itself always counted, at least `MinInboxShare` (`MaxBodyBytes`); counted only when the project has bytes queued: `database.Store.InboxBytesOf`, kept in memory by `AppendWithin` (both bounds, `InboxLimit`, checked and the bytes added under one lock before the write, given back if it fails, so concurrent requests never pass on one count, `TestAppendWithinHoldsTheShare`), `Write` (`Envelope.InboxProject`) and the count at open; over it `errOverShare`, 429 `Retry-After: 10` pausing every category, `store.DropQueueShare`), so a flood holds back only its own project) and the answer. The queues to the processors carry an entry's sequence, project and size only (`Pending` reads no bodies); a processor reads the body (`InboxBody`, a slice of the engine's copy, `kv.Collection.GetValue`, so one copy, `TestInboxBodyCopiedOnce`) once its bytes fit `ParseBytes` (32 MB for the envelopes being parsed or waiting for the writer, freed when stored), and an entry already stored gives nothing, so one handed both from the fresh queue and by a scan of the inbox is stored once (`TestScanDoesNotStoreTwice`). A processor then runs `scrubJSON` on every log item and, for events, `prepareEvent` (`compactEvent` over the token decoder and encoder of `scrub.go`, one pass, then `truncateEvent`; `prepare_test.go` checks, also as a fuzz target, that it gives what the tree pass it replaced gave) → parse all items → the writer's batch, which also deletes the inbox entry (a batch failing on a record JSON cannot encode is written one envelope at a time and that envelope is dropped, `storeBatch`, since no retry would fix it); an entry whose processing panics is logged and dropped from the inbox (`processOrDrop`), and a panic while reporting a stored event loses only that report. All items are parsed before anything is stored, so a malformed item (not JSON, or not an object) drops the whole envelope. Only `event` and `log` items are stored; other types are dropped. `NewPipeline` builds the handler with its pipeline, so every envelope, the tests' too, goes through the inbox. `StoreSink` computes the grouping fingerprint, maps Sentry types to `store.NewEvent`/`store.NewLog` and reports what the writer stored (log lines, notifications). Rejections are logged at debug level (ingest is public, so warn-level logging would be a flood vector). `DropCounter` (`dropped.go`, `Pipeline.Dropped`, built before the services in `app.New`) counts per project, in memory, in hourly buckets of 24 h, what was refused after the key check (`countRefused`: rate limit by category, busy (429, a store failure), queue share (`errOverShare`), too large (413), invalid (400, 415), incomplete (408, or the client hung up: `requestError.incomplete`); items once parsed, else envelopes) and what `client_report` items say the SDK dropped (`sentry.ParseClientReport`; ratelimit_backoff, queue/buffer/cache overflows and backpressure; sampling, `beforeSend` and `network_error`/`send_error` not: SDKs report the server's refusals that way too, so they would count twice), with one warning per project an hour; reasons and their texts are `store.DropReasons`. ### Projects and DSNs diff --git a/docs/configuration.md b/docs/configuration.md index 9ea2231..79ec817 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -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. diff --git a/docs/deployment.md b/docs/deployment.md index 93f008c..40f1f6e 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -109,7 +109,7 @@ Measured: 10 projects sending errors as fast as they could, each error with 5 lo |---|---|---|---|---| | Requests a second | 130 | 220 | 310 | 410 | -When the server cannot keep up, apps pause for a few seconds and then send again. What they drop meanwhile shows on the Projects page. +When the server cannot keep up, 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 diff --git a/docs/ui.md b/docs/ui.md index a9576b2..77af505 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -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 diff --git a/docs/values_test.go b/docs/values_test.go index a7af190..9a89b2a 100644 --- a/docs/values_test.go +++ b/docs/values_test.go @@ -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}, @@ -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}, diff --git a/internal/ingest/dropped.go b/internal/ingest/dropped.go index 4cfb8bf..4e4e3b3 100644 --- a/internal/ingest/dropped.go +++ b/internal/ingest/dropped.go @@ -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 diff --git a/internal/ingest/handler.go b/internal/ingest/handler.go index 7ef1bf6..b88539c 100644 --- a/internal/ingest/handler.go +++ b/internal/ingest/handler.go @@ -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 { @@ -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: diff --git a/internal/ingest/handler_test.go b/internal/ingest/handler_test.go index 2d0b33b..a54aac8 100644 --- a/internal/ingest/handler_test.go +++ b/internal/ingest/handler_test.go @@ -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{}) diff --git a/internal/ingest/pipeline.go b/internal/ingest/pipeline.go index 33dd12e..27a2863 100644 --- a/internal/ingest/pipeline.go +++ b/internal/ingest/pipeline.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "log/slog" - "net/http" "runtime" "sync" "sync/atomic" @@ -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 @@ -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 @@ -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 @@ -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 { @@ -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) } } @@ -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) @@ -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. @@ -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) { @@ -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 { @@ -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 diff --git a/internal/ingest/share.go b/internal/ingest/share.go new file mode 100644 index 0000000..88b0585 --- /dev/null +++ b/internal/ingest/share.go @@ -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) +} diff --git a/internal/ingest/share_test.go b/internal/ingest/share_test.go new file mode 100644 index 0000000..1f306cc --- /dev/null +++ b/internal/ingest/share_test.go @@ -0,0 +1,130 @@ +package ingest + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "testing" + "time" + + "github.com/devforth/exceptic/internal/fixtures" + "github.com/devforth/exceptic/internal/platform/config" + "github.com/devforth/exceptic/internal/storage/store" + "github.com/devforth/exceptic/internal/storage/storetest" +) + +// queueServer is the handler with a pipeline that does not run, so what it +// accepts stays in the inbox. +func queueServer(t *testing.T, projects config.Projects) *testServer { + t.Helper() + + db := storetest.Open(t) + storetest.AddProjects(t, db, projects) + pipeline := NewPipeline(slog.New(slog.DiscardHandler), testSettings(), projects, db, StoreSink{Logger: slog.New(slog.DiscardHandler)}) + pipeline.MinInboxShare = 0 + router := http.NewServeMux() + router.Handle("/api/{projectID}/envelope/{$}", pipeline.Handler()) + + return &testServer{t: t, handler: pipeline.Handler(), pipeline: pipeline, db: db, router: router} +} + +// A project flooding the queue is refused once it holds its share, while +// the other connected project is still accepted. +func TestFloodHoldsOnlyItsShare(t *testing.T) { + server := queueServer(t, fixtures.Projects()) + entry := int64(len(eventEnvelope()) + 20) // the body and the inbox header + server.pipeline.MaxInboxBytes = 10 * entry + + expectAnswer(t, server.post("2", fixtures.BrowserKey, eventEnvelope()), http.StatusOK, "", "") + + accepted := 0 + + for ; accepted < 20; accepted++ { + if response := server.post("1", fixtures.BackendKey, eventEnvelope()); response.Code != http.StatusOK { + expectAnswer(t, response, http.StatusTooManyRequests, pauseEverything(inboxFullRetry), inboxFullRetry) + + break + } + } + + if held := server.db.InboxBytesOf(1); accepted != 5 || held != 5*entry { + t.Errorf("the flooding project queued %d envelopes, %d bytes; want 5, %d", accepted, held, 5*entry) + } + + expectAnswer(t, server.post("2", fixtures.BrowserKey, eventEnvelope()), http.StatusOK, "", "") + + want := []store.Dropped{{Reason: store.DropQueueShare, Kind: "events", Count: 1}} + + if got := server.handler.dropped.Dropped(1); fmt.Sprint(got) != fmt.Sprint(want) { + t.Errorf("dropped %v, want %v", got, want) + } +} + +// The queue is split among the active projects by their disk shares. +func TestInboxShares(t *testing.T) { + projects := config.Projects{{ID: 1, Name: "one", PublicKey: "key1", DiskShare: 100}, {ID: 2, Name: "two", PublicKey: "key2", DiskShare: 50}, {ID: 3, Name: "three", PublicKey: "key3", Paused: true}, {ID: 4, Name: "four", PublicKey: "key4"}} + server := queueServer(t, projects) + pipeline := server.pipeline + pipeline.MaxInboxBytes = 3000 + now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC) + + expect := func(project config.Project, want int64) { + t.Helper() + + if got := pipeline.inboxShare(project); got != want { + t.Errorf("project %d: share %d, want %d", project.ID, got, want) + } + } + + // Alone (a paused project does not count), a project has the whole queue. + _, _ = server.db.MarkContact(1, "key1", now) + _, _ = server.db.MarkContact(3, "key3", now) + + expect(projects[0], 3000) + + // Connected, 50% weighs half as much as 100%. + _, _ = server.db.MarkContact(2, "key2", now) + + expect(projects[0], 2000) + expect(projects[1], 1000) + + // Data counts without a connection (a DSN reset), once read again. + if err := server.db.SaveLogs(context.Background(), []store.NewLog{{ProjectID: 4, Timestamp: now, Level: "info", Body: "hello", Attributes: []byte("{}")}}, 0); err != nil { + t.Fatal(err) + } + + expect(projects[0], 2000) + pipeline.readWithData(context.Background()) + expect(projects[0], 1200) + expect(projects[1], 600) + + // A small share still takes one largest envelope. + pipeline.MinInboxShare = 1000 + + expect(projects[1], 1000) + + // Among many, a small share keeps config.MinInboxSharePercent of the queue: + // 5% of 3000, more than its 5/255 of it. + pipeline.MinInboxShare = 0 + + expect(config.Project{ID: 5, Name: "five", PublicKey: "key5", DiskShare: 5}, 3000*config.MinInboxSharePercent/100) +} + +// Every byte a project queued is freed once the pipeline stored its envelopes. +func TestQueuedBytesReturnToZero(t *testing.T) { + server := newTestServer(t, testSettings()) + + for range 5 { + expectAnswer(t, server.post("1", fixtures.BackendKey, eventEnvelope()), http.StatusOK, "", "") + expectAnswer(t, server.post("2", fixtures.BrowserKey, logEnvelope(2, false)), http.StatusOK, "", "") + } + + server.waitStored() + + for _, project := range []int{0, 1, 2} { + if held := server.db.InboxBytesOf(project); held != 0 { + t.Errorf("project %d still holds %d bytes", project, held) + } + } +} diff --git a/internal/platform/config/retention.go b/internal/platform/config/retention.go index 38e8e5b..2633070 100644 --- a/internal/platform/config/retention.go +++ b/internal/platform/config/retention.go @@ -51,6 +51,10 @@ const MinDatabaseBytes = 500 << 20 // 500 MB // wait in the ingest queue; beyond it new envelopes get 429. const InboxPercent = 20 +// MinInboxSharePercent of the inbox is the least part any active project may +// hold, however many projects share it (ingest's inboxShare). +const MinInboxSharePercent = 5 + // MaxInboxBytes is the ingest queue's share of maxDatabaseBytes, or of the // default when the limit is off (0). func MaxInboxBytes(maxDatabaseBytes int64) int64 { diff --git a/internal/storage/database/cleanup_live_test.go b/internal/storage/database/cleanup_live_test.go index 8f0a536..a95c9d4 100644 --- a/internal/storage/database/cleanup_live_test.go +++ b/internal/storage/database/cleanup_live_test.go @@ -269,7 +269,7 @@ func storedEnvelopes(t *testing.T, database *Store) { t.Fatal(err) } - database.inboxBytes.Add(-int64(entry.Size)) + database.addInbox(entry.ProjectID, -int64(entry.Size)) } if err := database.db.Write(batch, false); err != nil { diff --git a/internal/storage/database/cleanup_share_size_test.go b/internal/storage/database/cleanup_share_size_test.go index a0fba5a..08e3f2a 100644 --- a/internal/storage/database/cleanup_share_size_test.go +++ b/internal/storage/database/cleanup_share_size_test.go @@ -333,7 +333,7 @@ func TestDiskShareLeavesOutTheInbox(t *testing.T) { t.Fatal(err) } - envelopes = append(envelopes, Envelope{Sequence: entry.Sequence, InboxSize: entry.Size}) + envelopes = append(envelopes, Envelope{Sequence: entry.Sequence, InboxSize: entry.Size, InboxProject: entry.ProjectID}) inbox += int64(entry.Size) } diff --git a/internal/storage/database/cleanup_test.go b/internal/storage/database/cleanup_test.go index f5ed77f..3f00981 100644 --- a/internal/storage/database/cleanup_test.go +++ b/internal/storage/database/cleanup_test.go @@ -506,7 +506,7 @@ func TestCompactInboxWhenQuiet(t *testing.T) { t.Fatal(err) } - if _, err := database.Write([]Envelope{{Sequence: entry.Sequence, InboxSize: entry.Size}}); err != nil { + if _, err := database.Write([]Envelope{{Sequence: entry.Sequence, InboxSize: entry.Size, InboxProject: entry.ProjectID}}); err != nil { t.Fatal(err) } diff --git a/internal/storage/database/compaction_test.go b/internal/storage/database/compaction_test.go index e02d46e..e53d291 100644 --- a/internal/storage/database/compaction_test.go +++ b/internal/storage/database/compaction_test.go @@ -346,7 +346,7 @@ func ingestLoad(t *testing.T, database *Store, stop <-chan struct{}, rate int64, Timestamp: database.now(), ReceivedAt: database.now(), Payload: fmt.Appendf(nil, `{"extra":{"note":%q}}`, scenarioText(random, 2000))}) } - if _, err := database.Write([]Envelope{{Sequence: entry.Sequence, InboxSize: entry.Size, Logs: logs, Events: events}}); err != nil { + if _, err := database.Write([]Envelope{{Sequence: entry.Sequence, InboxSize: entry.Size, InboxProject: entry.ProjectID, Logs: logs, Events: events}}); err != nil { t.Error(err) return diff --git a/internal/storage/database/inbox.go b/internal/storage/database/inbox.go index fe4ca8d..a8dfe9d 100644 --- a/internal/storage/database/inbox.go +++ b/internal/storage/database/inbox.go @@ -2,6 +2,7 @@ package database import ( "errors" + "math" "time" "github.com/devforth/exceptic/internal/storage/kv" @@ -10,9 +11,28 @@ import ( // ErrCompacting: a compaction part runs, during which ingest writes nothing; ingest answers 429. var ErrCompacting = errors.New("the database is compacting its files") -// Append writes without a sync: the writer's next synced batch takes it to disk. -// While a compaction part runs it refuses at once (ErrCompacting). +// ErrInboxFull and ErrOverShare: AppendWithin refused the envelope by its InboxLimit. +var ( + ErrInboxFull = errors.New("the inbox is full") + ErrOverShare = errors.New("the project holds its share of the inbox") +) + +// InboxLimit bounds what AppendWithin accepts: the inbox already holding +// more than Total, or a project holding something going over Own, refuses it. +type InboxLimit struct { + Total, Own int64 +} + +// Append writes an entry without a bound (AppendWithin). func (database *Store) Append(projectID int, received time.Time, body []byte) (InboxEntry, error) { + return database.AppendWithin(projectID, received, body, InboxLimit{Total: math.MaxInt64, Own: math.MaxInt64}) +} + +// AppendWithin writes without a sync: the writer's next synced batch takes it to disk. +// While a compaction part runs it refuses at once (ErrCompacting). Its bytes +// are counted before the write, checked against limit under one lock, so +// concurrent requests never all pass on one count. +func (database *Store) AppendWithin(projectID int, received time.Time, body []byte, limit InboxLimit) (entry InboxEntry, err error) { if !database.ingestWrites.TryRLock() { // Refused, it still counts as ingest: the next part waits for quiet. database.lastAppend.Store(time.Now().UnixNano()) @@ -22,13 +42,25 @@ func (database *Store) Append(projectID int, received time.Time, body []byte) (I defer database.ingestWrites.RUnlock() + size := int64(inboxHeader + len(body)) + + if err := database.reserveInbox(projectID, size, limit); err != nil { + return InboxEntry{}, err + } + + defer func() { + if err != nil { + database.addInbox(projectID, -size) + } + }() + sequence, err := database.db.Next() if err != nil { return InboxEntry{}, err } - entry := InboxEntry{Sequence: sequence, ProjectID: projectID, Received: received.UTC(), Size: inboxHeader + len(body)} + entry = InboxEntry{Sequence: sequence, ProjectID: projectID, Received: received.UTC(), Size: int(size)} batch := kv.NewBatch(database.db.Engine) if err := database.inbox.Insert(batch, inboxRecord{InboxEntry: entry, Body: body}); err != nil { @@ -39,12 +71,32 @@ func (database *Store) Append(projectID int, received time.Time, body []byte) (I return InboxEntry{}, err } - database.inboxBytes.Add(int64(entry.Size)) database.lastAppend.Store(time.Now().UnixNano()) return entry, nil } +// reserveInbox counts size bytes of the project's next entry unless limit refuses them. +func (database *Store) reserveInbox(projectID int, size int64, limit InboxLimit) error { + database.inboxMutex.Lock() + + defer database.inboxMutex.Unlock() + + queued := database.inboxProjects[projectID] + + switch { + case database.inboxBytes.Load() > limit.Total: + return ErrInboxFull + case queued > 0 && queued+size > limit.Own: + return ErrOverShare + } + + database.inboxBytes.Add(size) + database.inboxProjects[projectID] = queued + size + + return nil +} + // InboxBody returns the body of an entry; found is false once it is stored. func (database *Store) InboxBody(sequence uint64) (body []byte, found bool, err error) { value, err := database.inbox.GetValue(database.db, sequenceKey(sequence)) @@ -66,6 +118,29 @@ func (database *Store) InboxBytes() int64 { return database.inboxBytes.Load() } +// InboxBytesOf returns the size of a project's waiting envelopes. +func (database *Store) InboxBytesOf(projectID int) int64 { + database.inboxMutex.Lock() + + defer database.inboxMutex.Unlock() + + return database.inboxProjects[projectID] +} + +// addInbox counts bytes of a project's entries entering (size > 0) or leaving the inbox. +func (database *Store) addInbox(projectID int, size int64) { + database.inboxBytes.Add(size) + database.inboxMutex.Lock() + + defer database.inboxMutex.Unlock() + + if left := database.inboxProjects[projectID] + size; left != 0 { + database.inboxProjects[projectID] = left + } else { + delete(database.inboxProjects, projectID) + } +} + // Pending returns up to limit entries after the sequence number, oldest first, except skipped ones; bodies are not read. func (database *Store) Pending(after uint64, limit int, skip func(sequence uint64) bool) ([]InboxEntry, error) { var entries []InboxEntry @@ -84,15 +159,9 @@ func (database *Store) Pending(after uint64, limit int, skip func(sequence uint6 } func (database *Store) loadInboxSize() error { - var size int64 - - err := database.inbox.Primary().Head().Each(database.db, func(entry kv.Entry[inboxRecord]) (bool, error) { - size += int64(entry.Size) + return database.inbox.Primary().Head().Each(database.db, func(entry kv.Entry[inboxRecord]) (bool, error) { + database.addInbox(entry.Record.ProjectID, int64(entry.Record.Size)) return true, nil }) - - database.inboxBytes.Store(size) - - return err } diff --git a/internal/storage/database/project_usage_test.go b/internal/storage/database/project_usage_test.go index ae10961..fdd3a7f 100644 --- a/internal/storage/database/project_usage_test.go +++ b/internal/storage/database/project_usage_test.go @@ -123,7 +123,7 @@ func TestFirstContact(t *testing.T) { t.Fatal(err) } - if written, err := database.MarkContact(1, first); err != nil || !written { + if written, err := database.MarkContact(1, "0123456789abcdef", first); err != nil || !written { t.Fatalf("first mark: written %v, %v", written, err) } @@ -134,7 +134,7 @@ func TestFirstContact(t *testing.T) { t.Fatal(err) } - if written, err := database.MarkContact(1, first.Add(time.Hour)); err != nil || written { + if written, err := database.MarkContact(1, "0123456789abcdef", first.Add(time.Hour)); err != nil || written { t.Fatalf("second mark: written %v, %v", written, err) } @@ -147,7 +147,7 @@ func TestFirstContact(t *testing.T) { delete(database.contacted, 1) database.contactsMutex.Unlock() - if _, err := database.MarkContact(1, first); err != nil { + if _, err := database.MarkContact(1, "0123456789abcdef", first); err != nil { t.Fatal(err) } diff --git a/internal/storage/database/projects.go b/internal/storage/database/projects.go index e80617d..1d06e70 100644 --- a/internal/storage/database/projects.go +++ b/internal/storage/database/projects.go @@ -137,6 +137,17 @@ func (database *Store) RotateProjectKey(_ context.Context, id int, key string, n at := now.UTC() stored.PublicKey, stored.KeyChangedAt = key, &at + // The project is connected again by the first request with the new key. + if err := database.contacts.Delete(batch, projectContact{ProjectID: id}); err != nil { + return err + } + + batch.AfterWrite(func() { + database.contactsMutex.Lock() + delete(database.contacted, id) + database.contactsMutex.Unlock() + }) + return projectConflict(database.projects.Save(batch, stored)) }) } @@ -206,18 +217,30 @@ func (database *Store) FirstContact(projectID int) (at time.Time, ok bool) { } // MarkContact records the project's first contact at at, once: when it is -// known it neither reads nor writes the database. written says it was new. -func (database *Store) MarkContact(projectID int, at time.Time) (written bool, err error) { +// known in memory nothing is written. key is the one the request came with: +// a key the stored project no longer has (a DSN reset meanwhile) writes nothing. +func (database *Store) MarkContact(projectID int, key string, at time.Time) (written bool, err error) { if _, known := database.FirstContact(projectID); known { return false, nil } err = database.db.Update(true, func(batch *kv.Batch) error { - // Updates run one at a time: another may have marked it meanwhile. + // Updates run one at a time (RotateProjectKey too): another may have marked it meanwhile. if _, known := database.FirstContact(projectID); known || database.goneProjects[projectID] { return nil } + stored, err := database.projects.Get(batch, projectKey(projectID)) + + switch { + case errors.Is(err, kv.ErrNotFound): + return nil + case err != nil: + return err + case stored.PublicKey != key: + return nil + } + contact := projectContact{ProjectID: projectID, At: at.UTC()} written = true diff --git a/internal/storage/database/store.go b/internal/storage/database/store.go index 331566f..2a36a0e 100644 --- a/internal/storage/database/store.go +++ b/internal/storage/database/store.go @@ -24,6 +24,9 @@ type Store struct { formatKey kv.Key inboxBytes atomic.Int64 + // inboxProjects is inboxBytes per project (InboxBytesOf). + inboxMutex sync.Mutex + inboxProjects map[int]int64 // minute is the cap of events an issue stores a minute; used only inside updates. minute minuteCounts @@ -115,7 +118,7 @@ func open(engine kv.Engine) (*Store, error) { schema := kv.NewSchema() formatKey := schema.Reserve(formatName) database := &Store{schema: schema, collections: defineCollections(schema), formatKey: formatKey, now: time.Now, messageStart: map[string]uint64{}, - goneProjects: map[int]bool{}, contacted: map[int]time.Time{}, cleanupWake: make(chan struct{}, 1), + goneProjects: map[int]bool{}, contacted: map[int]time.Time{}, inboxProjects: map[int]int64{}, cleanupWake: make(chan struct{}, 1), compactionWake: make(chan struct{}, 1)} db, err := kv.OpenDB(engine, schema) diff --git a/internal/storage/database/store_test.go b/internal/storage/database/store_test.go index 15c23b3..e1527bf 100644 --- a/internal/storage/database/store_test.go +++ b/internal/storage/database/store_test.go @@ -5,9 +5,12 @@ import ( "context" "errors" "fmt" + "math" "runtime" "slices" "strings" + "sync" + "sync/atomic" "testing" "time" @@ -503,13 +506,121 @@ func TestInbox(t *testing.T) { t.Fatalf("body %q %v %v", body, found, err) } - if _, err := database.Write([]Envelope{{Sequence: first.Sequence, InboxSize: first.Size}}); err != nil { + if database.InboxBytesOf(1) != int64(first.Size) || database.InboxBytesOf(2) != int64(second.Size) { + t.Errorf("inbox bytes per project %d, %d", database.InboxBytesOf(1), database.InboxBytesOf(2)) + } + + if _, err := database.Write([]Envelope{{Sequence: first.Sequence, InboxSize: first.Size, InboxProject: 1}}); err != nil { t.Fatal(err) } if _, waiting, _ := database.InboxBody(first.Sequence); waiting || database.InboxBytes() != int64(second.Size) { t.Errorf("stored entry still waiting: %v, %d bytes", waiting, database.InboxBytes()) } + + if database.InboxBytesOf(1) != 0 || database.InboxBytesOf(2) != int64(second.Size) { + t.Errorf("inbox bytes per project after a write %d, %d", database.InboxBytesOf(1), database.InboxBytesOf(2)) + } +} + +// Concurrent appends of one project are checked and counted under one lock: +// none passes on a count another has already raised. +func TestAppendWithinHoldsTheShare(t *testing.T) { + database := openTest(t) + body := []byte("envelope") + size := int64(inboxHeader + len(body)) + limit := InboxLimit{Total: math.MaxInt64, Own: 5 * size} + + var ( + group sync.WaitGroup + accepted atomic.Int64 + ) + + for range 50 { + group.Add(1) + + go func() { + defer group.Done() + + _, err := database.AppendWithin(1, time.Now(), body, limit) + + switch { + case err == nil: + accepted.Add(1) + case !errors.Is(err, ErrOverShare): + t.Error(err) + } + }() + } + + group.Wait() + + if accepted.Load() != 5 || database.InboxBytesOf(1) != 5*size { + t.Errorf("accepted %d, %d bytes; want 5, %d", accepted.Load(), database.InboxBytesOf(1), 5*size) + } + + if _, err := database.AppendWithin(2, time.Now(), body, InboxLimit{Total: 5 * size, Own: math.MaxInt64}); err != nil { + t.Errorf("another project at the limit: %v", err) + } + + if _, err := database.AppendWithin(3, time.Now(), body, InboxLimit{Total: 5 * size, Own: math.MaxInt64}); !errors.Is(err, ErrInboxFull) || database.InboxBytesOf(3) != 0 { + t.Errorf("over the inbox: %v, %d bytes counted", err, database.InboxBytesOf(3)) + } +} + +// Entries left in the inbox at a restart count for their projects again. +func TestInboxBytesPerProjectAfterARestart(t *testing.T) { + dir := t.TempDir() + database := openOnDisk(t, dir) + received := time.Date(2026, 11, 10, 8, 0, 0, 0, time.UTC) + first, _ := database.Append(1, received, []byte("one")) + second, _ := database.Append(2, received, []byte("second")) + third, err := database.Append(2, received, []byte("third")) + + if err != nil { + t.Fatal(err) + } + + if err := database.Close(); err != nil { + t.Fatal(err) + } + + database = openOnDisk(t, dir) + + if database.InboxBytesOf(1) != int64(first.Size) || database.InboxBytesOf(2) != int64(second.Size+third.Size) { + t.Errorf("inbox bytes per project %d, %d", database.InboxBytesOf(1), database.InboxBytesOf(2)) + } +} + +// A new DSN key clears the project's first contact: the next request with it connects it again. +func TestRotatedKeyClearsTheContact(t *testing.T) { + database := openTest(t) + now := time.Date(2026, 11, 10, 8, 0, 0, 0, time.UTC) + + if err := database.AddProjects(context.Background(), now, store.Project{ID: 1, Name: "backend", PublicKey: "0123456789abcdef0123456789abcdef"}); err != nil { + t.Fatal(err) + } + + if _, err := database.MarkContact(1, "0123456789abcdef0123456789abcdef", now); err != nil { + t.Fatal(err) + } + + if err := database.RotateProjectKey(context.Background(), 1, "fedcba9876543210fedcba9876543210", now); err != nil { + t.Fatal(err) + } + + if _, connected := database.FirstContact(1); connected { + t.Error("connected after the key was replaced") + } + + // A request that came with the old key, done after the reset, connects nothing. + if written, err := database.MarkContact(1, "0123456789abcdef0123456789abcdef", now.Add(time.Minute)); err != nil || written { + t.Errorf("contact with the old key written %v, %v", written, err) + } + + if written, err := database.MarkContact(1, "fedcba9876543210fedcba9876543210", now.Add(time.Minute)); err != nil || !written { + t.Errorf("contact with the new key written %v, %v", written, err) + } } // Reading a body allocates it once (the engine's copy), not again for the decode. diff --git a/internal/storage/database/write.go b/internal/storage/database/write.go index d550b35..aa739d7 100644 --- a/internal/storage/database/write.go +++ b/internal/storage/database/write.go @@ -14,6 +14,7 @@ import ( type Envelope struct { Sequence uint64 InboxSize int // bytes of the inbox entry, freed once stored + InboxProject int // the project of the inbox entry (InboxBytesOf) Events []store.NewEvent Logs []store.NewLog LogsPerMessage int // keep the newest of a repeated message (0: all) @@ -23,7 +24,6 @@ type Envelope struct { // Write stores envelopes and deletes their inbox entries in one batch. func (database *Store) Write(envelopes []Envelope) ([][]store.SaveResult, error) { results := make([][]store.SaveResult, len(envelopes)) - freed := 0 // Copies of a repeated message this batch would delete are not written. copies := map[string]int{} @@ -76,8 +76,6 @@ func (database *Store) Write(envelopes []Envelope) ([][]store.SaveResult, error) if err := database.inbox.Delete(writer.batch, inboxRecord{InboxEntry: InboxEntry{Sequence: envelope.Sequence}}); err != nil { return err } - - freed += envelope.InboxSize } } @@ -88,7 +86,11 @@ func (database *Store) Write(envelopes []Envelope) ([][]store.SaveResult, error) return nil, err } - database.inboxBytes.Add(-int64(freed)) + for _, envelope := range envelopes { + if envelope.Sequence != 0 { + database.addInbox(envelope.InboxProject, -int64(envelope.InboxSize)) + } + } return results, nil } diff --git a/internal/storage/store/dropped.go b/internal/storage/store/dropped.go index b309127..4909b23 100644 --- a/internal/storage/store/dropped.go +++ b/internal/storage/store/dropped.go @@ -13,6 +13,7 @@ type Dropped struct { const ( DropRateLimit = "rate_limit" // over RATE_LIMIT_EVENTS_PER_MINUTE or RATE_LIMIT_LOGS_PER_MINUTE DropBusy = "busy" // the inbox full, the reading budget used up, a compaction part running, or the store failing + DropQueueShare = "queue_share" // the project held its part of the ingest queue DropTooLarge = "too_large" // over 20 MB (413) DropInvalid = "invalid" // not an envelope, or a body that cannot be decoded (400, 415) DropIncomplete = "incomplete" // not within 10 s (408), or the client hung up mid-body @@ -24,6 +25,7 @@ const ( var DropReasons = map[string]string{ DropRateLimit: "rate limit", DropBusy: "server busy", + DropQueueShare: "over its part of the queue", DropTooLarge: "too large", DropInvalid: "unreadable", DropIncomplete: "not received whole", diff --git a/web/src/lib/api/catalog.gen.ts b/web/src/lib/api/catalog.gen.ts index 102d268..6b813c2 100644 --- a/web/src/lib/api/catalog.gen.ts +++ b/web/src/lib/api/catalog.gen.ts @@ -1677,9 +1677,9 @@ export const help = { 'Projects': { '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.', '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.', '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.', - '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.', 'History kept': 'The oldest record of each kind still stored. When the database is full, the least useful data goes first (Retention).', 'Logs': 'Log levels to store; others are dropped. Errors of every level are always stored.', 'Paused': 'While paused, nothing the project\'s apps send is stored or notified.',