UUIDv7 keys everywhere (Vigil.Schema), and the roadmap

78a7bd9 · gmorell · 2026-12-01 21:11

12 files +447 -9
Message
{commit_body(@commit)}

Files changed

modified AGENTS.md
+2 −0
@@ -2,6 +2,8 @@ This is a web application written using the Phoenix web framework.
2 2
3 3 ## Project guidelines
4 4
5 +- Every Vigil schema does `use Vigil.Schema` (UUIDv7 primary keys, generated app-side, and UUID foreign keys), **never** bare `use Ecto.Schema` with `:binary_id`. `mix phx.gen.*` output must be switched over. Migrations declare `add :id, :binary_id, primary_key: true` and `references(..., type: :binary_id)`. For an id made outside an insert, use `Vigil.Schema.uuid7/0`
6 +
5 7 - Use `mix precommit` alias when you are done with all changes and fix any pending issues
6 8 - Use the already included and available `:req` (`Req`) library for HTTP requests, **avoid** `:httpoison`, `:tesla`, and `:httpc`. Req is included by default and is the preferred HTTP client for Phoenix apps
7 9
added ROADMAP.md
+382 −0
@@ -0,0 +1,382 @@
1 +# Roadmap
2 +
3 +Vigil is a Sentry-compatible error tracker in the GlitchTip mould: the
4 +Sentry SDKs and `sentry-cli` talk to it unchanged. It is a Phoenix app with
5 +**Oban for every background and periodic job**, **LiveView for every
6 +screen**, **UUIDv7 keys everywhere** (`Vigil.Schema`), and **Rust NIFs** for
7 +format work, in the manner of gitgud's `native/` crates.
8 +
9 +The plan is grouped into slices. Each slice ships something usable and ends
10 +with `mix precommit` green. Sizes are estimates.
11 +
12 +---
13 +
14 +## References and licensing
15 +
16 +The reference code lives in `~/Development/local/sentry_oss_2019/`:
17 +
18 +| Repo | License | Used for |
19 +|---|---|---|
20 +| `glitchtip-backend` | MIT | The primary server reference: ingest, data model, alerts, uptime, maintenance |
21 +| `sentry` (2019-11-06, before the switch to BSL) | BSD-3-Clause | Grouping strategies, event normalisation, culprit and title rules |
22 +| `sentry-python`, `sentry-elixir` | MIT | What clients send and how they react to responses |
23 +| `sentry-cli` | BSD-3-Clause | The release, chunk-upload and assemble API |
24 +| `sentry-docs`, `snuba`, `onpremise` | Apache-2.0 | Protocol docs |
25 +
26 +- Logic ported from any of these keeps its copyright notice in `NOTICE.md`.
27 +- Never consult Sentry server code from after 2019-11, which is BSL.
28 +
29 +---
30 +
31 +## Wire contract
32 +
33 +These rules are not negotiable. The conformance tests in slice 1 pin them
34 +down.
35 +
36 +### Endpoints and auth
37 +- `POST /api/:project_id/envelope/` is the only endpoint current SDKs use.
38 + `/store/` (legacy SDKs), `/security/` (CSP `report-uri`) and
39 + `/minidump/` are secondary. Routes work with and without the trailing
40 + slash.
41 +- The key is read from, in order:
42 + 1. the `sentry_key` query parameter (also `glitchtip_key`);
43 + 2. the `X-Sentry-Auth` header;
44 + 3. the `Authorization` header;
45 + 4. the envelope header `dsn`, which GlitchTip ignores but tunnels rely on.
46 +- `sentry_version` 5 (Elixir) and 7 (Python) are both accepted.
47 + `sentry_timestamp` and `sentry_secret` are optional.
48 +- The key, the project, the organisation, and whether each is active and
49 + not deleted are checked before the body is read.
50 +
51 +### Request bodies
52 +- `Content-Type` is ignored. Elixir sends none; Python sends
53 + `application/x-sentry-envelope`.
54 +- `Content-Encoding` may be `gzip` or `deflate` (zlib-wrapped, or raw
55 + deflate as a fallback), both via `:zlib`; `zstd` via OTP 28's `:zstd`;
56 + or `br` via a NIF. **br is Python's default.**
57 +- Bodies are capped twice: raw at 20 MiB, decompressed at 100 MiB per
58 + envelope and 1 MiB per event item. Decompression stops at the cap rather
59 + than inflating the whole body and checking afterwards.
60 +
61 +### Envelope parsing
62 +- An item is length-prefixed when its header has `length`; otherwise it
63 + runs to the next newline. Elixir's `log` and `trace_metric` items have no
64 + `length`.
65 +- **Unknown item types are skipped and parsing continues.** GlitchTip
66 + stops at the first one; Vigil must not.
67 +- Payloads tolerate `null` anywhere. `exception`, `breadcrumbs` and
68 + `threads` may be bare arrays or `{"values": […]}`. `message` may be a
69 + string or an object. Timestamps may be ISO strings with or without `Z`,
70 + or unix ints or floats.
71 +
72 +### Responses
73 +- **Always `200` with a JSON object:** `{"id": "<envelope event_id>"}`, or
74 + `{}` when there is none.
75 + - sentry-elixir treats anything other than a 200 with a JSON object as a
76 + failure and retries it five times.
77 + - `send_result: :sync` returns that `id` to the caller.
78 +- `429` carries `Retry-After: <int>` and
79 + `X-Sentry-Rate-Limits: <int>:<categories>:<scope>[:<reason>]`. Use
80 + integers: Python silently drops float values.
81 +- `413` for oversize bodies; both SDKs drop the envelope and don't retry.
82 +- `403 {"detail": …}` for a bad key, with a short negative cache so that
83 + sentry-elixir's retries don't each hit the database.
84 +
85 +### CORS
86 +- `*` origins.
87 +- Allowed headers include `x-sentry-auth`, `sentry-trace`, `baggage` and
88 + `content-type`.
89 +- Exposed headers: `Retry-After`, `X-Sentry-Rate-Limits`, `X-Sentry-Error`.
90 +
91 +### Item types
92 +Every item type the SDKs send gets a 200, whether it is stored or dropped:
93 +
94 +| Item type | Handling |
95 +|---|---|
96 +| `event` | Stored |
97 +| `transaction` (Elixir) | Stored |
98 +| `span` v2 (Python 3.x) | Stored |
99 +| `check_in` | Stored |
100 +| `log` | Stored |
101 +| `client_report` | Stored as outcome counts |
102 +| `session`, `sessions` | Stored |
103 +| `user_report`, `feedback` | Stored |
104 +| `attachment` | Stored |
105 +| `trace_metric`, `profile_chunk`, `replay_*` | Accepted and dropped until a slice takes them |
106 +
107 +---
108 +
109 +## Architecture
110 +
111 +```
112 +SDK ──► Vigil.Ingest.Plug (in the Endpoint, ahead of Plug.Parsers and the
113 + │ session; ingest never touches cookies)
114 + ├─ auth: ETS cache of project keys, invalidated over PubSub
115 + ├─ rate limit: ETS counters per key and org, with outcome headers
116 + ├─ decode: zlib / zstd / brotli NIF, with output caps
117 + ├─ frame: Vigil.Ingest.Envelope (pure Elixir; split items, skip unknown)
118 + └─ buffer: INSERT into ingest_items, then Oban.insert of a unique
119 + Drain job. Respond 200 {"id"}.
120 + │
121 +Oban queue :ingest ▼
122 + Vigil.Ingest.Drain: claims up to 100 rows (FOR UPDATE SKIP LOCKED) and
123 + dispatches each by item type to a processor:
124 + Events.Process normalise ─► symbolicate ─► title/culprit ─► group
125 + ─► upsert issue ─► insert event ─► tags/stats
126 + ─► mark for alerts ─► PubSub
127 + Performance.Process, Crons.Process, Logs.Process, Sessions.Process,
128 + Outcomes.Process, Feedback.Process
129 +```
130 +
131 +**Why a buffer table instead of payloads in Oban args.** Envelope items can
132 +be megabytes. In `oban_jobs.args` they would bloat the jobs table and its
133 +pruner, and each event would cost its own job. A plain `ingest_items` table
134 +drained in batches behaves like GlitchTip's 100-item, 2-second batches.
135 +Oban still owns scheduling, retries, concurrency and telemetry. A Drain job
136 +is unique per project within a 1-second window, so a burst of envelopes
137 +queues one drain, not one per item.
138 +
139 +**Oban queues:**
140 +- `ingest`: the drains.
141 +- `processing`: symbolication and assemble.
142 +- `notify`: email and webhooks.
143 +- `checks`: uptime probes.
144 +- `maintenance`: partitions and retention.
145 +
146 +**Oban cron jobs:**
147 +
148 +| Job | Schedule |
149 +|---|---|
150 +| Alert evaluation | every minute |
151 +| Cron monitors: missed and timed-out check-ins | every minute |
152 +| Uptime reconciler: make sure each monitor has its next job scheduled | every minute |
153 +| Partition maintenance | daily |
154 +| Retention sweep | daily |
155 +| Stale-blob cleanup | daily |
156 +
157 +Oban's cron can't run more often than once a minute, so uptime checks are
158 +**self-rescheduling jobs**: each check inserts its successor at `now +
159 +interval`, unique per monitor. GlitchTip ticks a Valkey counter every
160 +second instead.
161 +
162 +**Storage.** Postgres only: no Valkey and no ClickHouse.
163 +- High-volume tables are range-partitioned by **UUIDv7 id per day**
164 + (`issue_events`, `log_events`, `spans`, `monitor_checks`, `outcomes`).
165 +- Stats tables are partitioned weekly by `date`.
166 +- `Vigil.Partitions` creates partitions ahead of time and drops whole
167 + partitions for retention. There are no DEFAULT partitions, so a missing
168 + partition fails loudly instead of silently filling one.
169 +
170 +**Live updates.** Processors broadcast on PubSub topics
171 +(`project:<id>:issues`, `issue:<id>`, `logs:<project>`). Issue lists and
172 +the log tail update in place. libcluster is added when it runs on more
173 +than one pod, as cartosnap does.
174 +
175 +---
176 +
177 +## NIF crates (`native/`, in gitgud's style)
178 +
179 +Each crate is a `cdylib` on rustler with a committed `Cargo.lock` and a thin
180 +`use Rustler` module. They are built from source with a pinned rustup
181 +toolchain in the Dockerfile and CI, and pass `clippy -D warnings`.
182 +Cargo.toml comments justify feature choices, and no crate may add system
183 +libraries to the images.
184 +
185 +| Crate | What | Slice |
186 +|---|---|---|
187 +| `vigil_codec` | Brotli decode with an output cap, on the `brotli` crate. ex_brotli (MIT) was considered, but its `decompress/1` reads to the end with no limit (a decompression bomb at the ingest edge) and fetches precompiled binaries by default, so the crate lives here | 1 |
188 +| `vigil_ua` | User-Agent to browser, OS and device contexts, on the `uaparser` crate with the uap-core regexes compiled in | 2 |
189 +| `vigil_sourcemap` | JS symbolication on the `sourcemap` crate (debug ids, index maps, `sourcesContent` context lines), plus zip and manifest reading for artifact bundles | 5 |
190 +| `vigil_symbolic` | Native, Proguard and minidump symbolication on `symbolic` and `minidump`. Optional; last | 12 |
191 +
192 +---
193 +
194 +## Slices
195 +
196 +### 0. Foundations: orgs, projects, keys, tokens · medium
197 +- Add Oban (Postgres engine, Pruner, Lifeline, Cron) and a `NOTICE.md`.
198 +- **Organizations:** slug unique, reserved words blocked; `accepting_events`; `scrub_ip`.
199 +- **Org members:** user, org, role. Roles are member, admin, manager and owner, each with a scope set as in GlitchTip.
200 +- **Org invites:** addressed and hashed, as registration invites already are. For someone without an account an org invite doubles as a registration invite, so it reuses `Vigil.Accounts.Invite`'s flow and NEIAM `link_pending`.
201 +- **Teams:** members and projects. Teams control which projects a member can see; admins and owners see everything.
202 +- **Projects:** slug unique per org, platform, `first_event_at`, `scrub_ip`.
203 +- **Project keys:** public key UUID, active flag, rate limit `{count, window}` that is actually enforced, and the DSN builder.
204 +- **API tokens:** per user, labelled, scopes, stored as a SHA-256 hash and shown once. A `Bearer` plug computes effective scopes as token scopes ∩ the user's role scopes in the target org (GlitchTip ignores the role).
205 +- **LiveView:** org switcher and create; org settings (members, invites, teams); project create (platform picker and a DSN snippet per SDK); project settings (keys); account → API tokens.
206 +- `Vigil.Partitions` and the maintenance cron job exist here, so later slices only declare their tables.
207 +- **Exit:** a user can create an org and project, copy a DSN, and mint a token.
208 +
209 +### 1. Ingest edge · large
210 +- `Vigil.Ingest.Plug` covering everything under **Wire contract**: auth with a negative cache, decoders with caps, envelope framing, CORS, rate limits with outcome headers, the buffer and the Drain job.
211 +- `/store/`, `/security/` and `/minidump/` route into the same pipeline. `/minidump/` stores the attachment for slice 12.
212 +- Items for later slices are kept in `ingest_items` with a `deferred` state, not discarded, so those slices can process the backlog when they land.
213 +- `client_report` becomes outcome counts (`outcomes`: org, project, category, reason, hour, quantity), shown later as "dropped by SDK".
214 +- **Conformance suite:**
215 + - Fixture envelopes captured from real sentry-python 3.x and sentry-elixir 14.x runs.
216 + - Hand-written edge cases: no `length`, unknown types, nulls, bare arrays, binary attachments, br/gzip/zstd bodies, bombs, auth in each of the four places.
217 + - Tests on the status code, the body and the headers.
218 +- An optional CI job runs the real sentry-python and sentry-elixir against a test server.
219 +- **Exit:** both SDKs report success, and nothing is retried or lost.
220 +
221 +### 2. Events into issues · large
222 +- **Normalisation:**
223 + - Tolerant per field, as GlitchTip: a bad interface becomes `nil` plus an entry in `errors[]`, never a rejection.
224 + - Bare arrays and `values` are unified, and `logentry` is formatted.
225 + - Request headers become a sorted list, and cookies are scrubbed.
226 + - Client IPs are set and anonymised per project.
227 + - `\u0000` is stripped.
228 +- **Threads:** an exception without a stacktrace borrows one from `threads`.
229 +- **Contexts:** browser, OS and device are filled from the User-Agent (`vigil_ua`).
230 +- **Title, culprit and metadata:** ported from 2019 Sentry and GlitchTip's `sentry/` subset. `culprit` is persisted, which GlitchTip forgets to do.
231 +- **Grouping** (a decision; see below). Recommended: port 2019 Sentry's `newstyle:2019-10-29` strategy (stacktrace components with in-app frames first, exception type, message fallback), with `fingerprint` and `{{ default }}`. Store `(config, hash)` on `issue_hashes` so a later strategy can add hashes without regrouping.
232 +- **Issues:**
233 + - Short id from a per-project counter upsert: `PROJ-1A`.
234 + - Status: unresolved, resolved, resolved-in-release, ignored.
235 + - **Regression:** a resolved issue reopens on a new event, or on an event from a different release when it was resolved in a release. Its alert dedupe resets.
236 + - Counts and first/last seen are updated in a single bulk statement per drain batch.
237 + - Releases and environments are created automatically.
238 +- **Events:** partitioned by day; the `data` JSON is trimmed to the interfaces; `event_id` is unique per project, which dedupes retries.
239 +- **Tags and stats:**
240 + - `tag_keys` and `tag_values` dictionaries.
241 + - `issue_tags` counts per day.
242 + - Hourly `issue_counts` and `project_counts`.
243 +- **Search:** a tsvector over title, culprit, transaction and frame filenames, plus a trigram index on title.
244 +- **User feedback:** `user_report` and `feedback` items are linked to the issue by `event_id`.
245 +- **Exit:** errors from both SDKs group sensibly and survive regression and resolve cycles.
246 +
247 +### 3. Issue UI · large
248 +- **Project issue list:**
249 + - Stream-backed with live inserts.
250 + - Filters for status, level, environment, release, assignee and time range.
251 + - Free-text and `key:value` tag search.
252 + - A sort selector.
253 + - A sparkline per row from the hourly counts.
254 + - Bulk resolve, ignore, delete and assign.
255 +- **Issue detail:**
256 + - A header with counts, first and last seen, releases, and a tag facet sidebar from `issue_tags`.
257 + - An event pager (newest, oldest, prev, next).
258 + - Stacktrace with in-app collapsing, frame vars and source context, and a raw/symbolicated toggle.
259 + - Chained exceptions, breadcrumbs, request, contexts, user, extra, SDK, and a JSON view.
260 + - Comments, assignee, user feedback, and a public share toggle.
261 +- **Org dashboard:** projects, recent issues across them, and an events-per-hour chart.
262 +- **Keyboard navigation** (j/k, e/r/i).
263 +- **Exit:** daily triage is possible without leaving Vigil.
264 +
265 +### 4. Alerts and notifications · medium
266 +- **Rules:** per project, "N events in M minutes", "new issue" and "regression". Recipients are email, a generic webhook (Slack-compatible), Discord, ntfy, Teams, Google Chat and Zulip, with GlitchTip's payload shapes.
267 +- **Evaluation:**
268 + - Processors record touched issues in an `alert_candidates` table (instead of a Valkey set).
269 + - A minutely Oban cron job evaluates the rules.
270 + - Delivery is one Oban job per recipient. Unlike GlitchTip it retries with backoff, and failures are visible in the UI.
271 +- **Dedupe:** once per issue per rule, until a regression. A "snooze for X" option re-notifies after time passes, which GlitchTip can't.
272 +- **Who gets email:** per-user project subscriptions with a subscribe-by-default setting; email goes through Swoosh.
273 +- **Exit:** new and regressed issues reach email and a webhook exactly once.
274 +
275 +### 5. Releases, sentry-cli and sourcemaps · large
276 +The `/api/0` API:
277 +- `GET /api/0/` returns user and token info.
278 +- **Releases:**
279 + - Create under both the org and project paths. It must be idempotent, which GlitchTip's org path isn't: it returns a 500.
280 + - Update, finalize and delete.
281 + - Get, returning 404 when missing.
282 + - List, with Link-header cursors.
283 + - `version` and `shortVersion` are both emitted.
284 + - `dateReleased` stays null until finalize; GlitchTip sets it on create.
285 +- **Deploys and commits:** deploys can be created and listed. The `commits` and `refs` sent in the release PUT are stored (GlitchTip drops them). `GET /repos/` returns `[]`, and `previous-with-commits` returns 404.
286 +- **Chunk upload:**
287 + - `GET` advertises `artifact_bundles` (and later `artifact_bundles_v2`).
288 + - `POST` takes multipart `file_gzip` parts. It **verifies each SHA-1**, which GlitchTip doesn't, and stores blobs per org rather than globally.
289 +- **Artifact-bundle assemble:**
290 + - `not_found` returns the missing chunks.
291 + - Otherwise an Oban assemble job runs, with status tracked per `(org, checksum)`.
292 + - It returns `created`, then `assembling`, then **`ok`** or `error`, so `--wait` works. GlitchTip never returns `ok`.
293 +- **Bundles:** extract the manifest and pair minified files with their maps by debug id or `Sourcemap` header, into `artifact_bundle_files`.
294 +- **JS symbolication with `vigil_sourcemap`:**
295 + - Match by debug id from `debug_meta.images`, falling back to release and filename.
296 + - `raw_stacktrace` is kept.
297 + - Handles `webpack:`, `app:` and `~/` prefixes, and sets `in_app`.
298 +- File storage behind a small behaviour, with local disk and S3 (Req's `aws_sigv4`, as cartosnap does).
299 +- **UI:** releases list and detail (new, resolved and regressed issues, deploys, artifacts). Issues gain "resolve in next release".
300 +- **Exit:** `sentry-cli releases new/finalize/deploys`, `sourcemaps upload --wait` and a minified-JS error together give a readable stacktrace.
301 +
302 +### 6. Performance · large
303 +- **Storage:**
304 + - Elixir sends `transaction` items with `spans[]`; Python 3.x sends `span` v2 items (`is_segment` marks the root).
305 + - Both normalise into one `spans` table, partitioned daily, with trace id, span id, parent, segment, op, name, status, start, duration and attributes.
306 + - Segment spans roll up into `transaction_groups` keyed by `(project, name, op, method)`.
307 + - Rollups keep count, error count, average duration and a 50-bucket histogram from which p50, p95 and p99 are computed, as in GlitchTip.
308 +- **UI:**
309 + - A transactions list with throughput, latency percentiles and error rate.
310 + - A transaction detail page with a duration histogram and sample traces.
311 + - A trace waterfall built from the spans.
312 + - Errors and spans linked through `contexts.trace.trace_id`.
313 +- **Later:** N+1 query detection (repeated `db` spans under one parent), as GlitchTip's MCP tools offer.
314 +- **Exit:** a Phoenix app with sentry-elixir tracing shows endpoints and waterfalls.
315 +
316 +### 7. Cron monitors · medium
317 +This is new: GlitchTip throws `check_in` items away.
318 +- **Monitors:**
319 + - Upserted from `monitor_config` (crontab or interval schedule, timezone, check-in margin, max runtime, failure and recovery thresholds), or created in the UI.
320 + - Slugs are unique per project.
321 + - Crontab parsing uses `crontab` or Oban's own cron expression parser.
322 +- **Check-ins:**
323 + - `in_progress`, then `ok` or `error`, matched by `check_in_id`; an unknown id is a new check-in.
324 + - Duration is taken from the payload or the pair.
325 + - sentry-elixir's Oban and Quantum integrations work unchanged.
326 +- **Minutely cron job:** marks expected-but-missing check-ins `missed`, and in-progress ones past `max_runtime` `timeout`. Missed, error and timeout states cross the thresholds into monitor incidents, which alert through slice 4's recipients.
327 +- **UI:** monitors list with a status timeline per monitor, and the next expected run.
328 +- `GET /api/0/organizations/{o}/monitors/` returns the shape sentry-cli expects.
329 +- **Exit:** Vigil's own Oban cron jobs, reported through sentry-elixir, show up and alert when they're missed.
330 +
331 +### 8. Uptime · medium
332 +- **Monitors:** HTTP GET, HTTP POST, ping, TCP, SSL expiry, and heartbeat (push to `/api/0/organizations/{o}/heartbeat_check/{uuid}/`).
333 +- **Checks:**
334 + - Self-rescheduling Oban jobs in the `checks` queue.
335 + - HTTP checks use Req, with expected status and body, a timeout, and an SSRF guard that blocks private addresses.
336 + - `monitor_checks` is partitioned daily; "up" heartbeats aren't stored.
337 +- **Alerts** on up/down changes, through slice 4.
338 +- **Status pages:** public or private, slugged, live via PubSub.
339 +- **Exit:** monitors flip state within one interval and alert once per change.
340 +
341 +### 9. Logs · medium
342 +- `log` items arrive from Python as `version: 2` and from Elixir with no version.
343 +- **Storage:** flattened attributes (service, environment, host, severity) in a partitioned `log_events` table. Logs more than a day off server time are rejected.
344 +- **UI:**
345 + - A live tail over PubSub.
346 + - Filters for level, service, environment and attributes.
347 + - Search.
348 + - Jumps to the trace or issue by `trace_id`.
349 +- **Exit:** sentry-elixir's logger handler streams into the tail.
350 +
351 +### 10. Release health · small-medium
352 +- `session` and `sessions` items roll up into per-release, per-environment, per-hour crash-free counts.
353 +- Release pages show crash-free users and sessions and adoption.
354 +
355 +### 11. Retention and operations · medium
356 +- **Retention** per type, settable per org: events and logs 90 days, releases 365 days. Old partitions are dropped. Orphaned issues, blobs and bundles are swept, and soft-deleted orgs and projects are removed by Oban jobs.
357 +- **Health:** `/_health/` and `/api/0/internal/health/`; `/metrics` for Prometheus via telemetry.
358 +- **Dogfooding:** Vigil reports its own errors, crons and traces to itself through sentry-elixir. A loop guard drops events about the ingest path itself.
359 +- **Packaging:**
360 + - Dockerfile with a pinned rustup toolchain for the NIFs.
361 + - Forgejo CI: precommit, clippy, audit.
362 + - rel overlays for `bin/invite`, `bin/migrate` and `bin/token`.
363 + - Mail through the siblings' setup (gen_smtp or mail-prism).
364 +- **Optional:**
365 + - An MCP endpoint with the same Bearer tokens, offering issue, event and log tools as GlitchTip's MCP server does.
366 + - The sentry-wizard endpoints.
367 + - The DSN-keys API.
368 +
369 +### 12. Native and mobile (optional) · large
370 +- Debug information file assemble (`/projects/{o}/{p}/files/difs/assemble/`), Proguard mappings, minidump processing, and native and JVM symbolication through `vigil_symbolic`.
371 +
372 +---
373 +
374 +## Decisions to make
375 +
376 +| # | Question | Recommendation |
377 +|---|---|---|
378 +| 1 | **Grouping:** GlitchTip's `md5(title + culprit + type)`, or 2019 Sentry's stacktrace grouping? | 2019 Sentry `newstyle` (BSD), versioned per hash. Title-based grouping merges unrelated errors that share a message, and splits one error whose message carries ids. Changing strategy later means regrouping, so choose before data arrives |
379 +| 3 | **Where ingest payloads wait:** a buffer table plus Drain jobs, or payloads in Oban args? | The buffer table (see Architecture) |
380 +| 4 | **Org invites and registration invites:** one table or two? | Two tables, one flow. An org invite to an address without an account behaves as an addressed registration invite |
381 +| 5 | **Span volume:** every span in Postgres? | Yes, partitioned daily with short retention (7 to 14 days) and rollups kept longer. Revisit cold storage (Parquet) only if volume demands it |
382 +| 6 | **Multi-node:** libcluster from the start? | Not until slice 11. Ingest is stateless apart from the ETS caches, which PubSub keeps coherent once clustered |
modified lib/vigil/accounts/invite.ex
+1 −3
@@ -19,13 +19,11 @@ defmodule Vigil.Accounts.Invite do
19 19 the link alone, and on the struct (the virtual `token`) only as it comes
20 20 back from creating or rotating, which is the one time to show the link.
21 21 """
22 − use Ecto.Schema
22 + use Vigil.Schema
23 23 import Ecto.Changeset
24 24
25 25 alias Vigil.Accounts.User
26 26
27 − @primary_key {:id, :binary_id, autogenerate: true}
28 − @foreign_key_type :binary_id
29 27 schema "user_invites" do
30 28 field :token, :string, virtual: true, redact: true
31 29 field :token_hash, :binary, redact: true
modified lib/vigil/accounts/user.ex
+1 −3
@@ -1,9 +1,7 @@
1 1 defmodule Vigil.Accounts.User do
2 − use Ecto.Schema
2 + use Vigil.Schema
3 3 import Ecto.Changeset
4 4
5 − @primary_key {:id, :binary_id, autogenerate: true}
6 − @foreign_key_type :binary_id
7 5 schema "users" do
8 6 field :email, :string
9 7 field :password, :string, virtual: true, redact: true
modified lib/vigil/accounts/user_token.ex
+1 −3
@@ -1,5 +1,5 @@
1 1 defmodule Vigil.Accounts.UserToken do
2 − use Ecto.Schema
2 + use Vigil.Schema
3 3 import Ecto.Query
4 4 alias Vigil.Accounts.UserToken
5 5
@@ -12,8 +12,6 @@ defmodule Vigil.Accounts.UserToken do
12 12 @change_email_validity_in_days 7
13 13 @session_validity_in_days 14
14 14
15 − @primary_key {:id, :binary_id, autogenerate: true}
16 − @foreign_key_type :binary_id
17 15 schema "users_tokens" do
18 16 field :token, :binary
19 17 field :context, :string
added lib/vigil/schema.ex
+34 −0
@@ -0,0 +1,34 @@
1 +defmodule Vigil.Schema do
2 + @moduledoc """
3 + Base schema for Vigil: UUIDv7 (time-ordered) primary keys, generated
4 + app-side, with UUID foreign keys. `use Vigil.Schema` in place of
5 + `use Ecto.Schema`, as the sibling apps do.
6 +
7 + UUIDv7 keys sort by creation time, so they index like a sequence (and
8 + can range-partition by time, as event tables will) without exposing a
9 + counter. `:monotonic` precision keeps keys made in the same millisecond
10 + on one node in insertion order.
11 +
12 + `mix phx.gen.*` still writes `@primary_key {:id, :binary_id, ...}`:
13 + swap that for `use Vigil.Schema` in anything generated.
14 + """
15 +
16 + @uuid7 [version: 7, precision: :monotonic]
17 +
18 + defmacro __using__(_opts) do
19 + quote do
20 + use Ecto.Schema
21 +
22 + @primary_key {:id, Ecto.UUID, autogenerate: unquote(@uuid7)}
23 + @foreign_key_type Ecto.UUID
24 + end
25 + end
26 +
27 + @doc "A new UUIDv7 string, for ids made outside an insert (an event id, say)."
28 + @spec uuid7() :: Ecto.UUID.t()
29 + def uuid7, do: Ecto.UUID.generate(@uuid7)
30 +
31 + @doc "When a UUIDv7 was made."
32 + @spec uuid7_time(Ecto.UUID.t()) :: DateTime.t()
33 + def uuid7_time(uuid), do: Ecto.UUID.to_datetime(uuid)
34 +end
added test/vigil/schema_test.exs
+26 −0
@@ -0,0 +1,26 @@
1 +defmodule Vigil.SchemaTest do
2 + use Vigil.DataCase, async: true
3 +
4 + import Vigil.AccountsFixtures
5 +
6 + alias Vigil.Accounts
7 +
8 + test "records get UUIDv7 keys, in creation order" do
9 + a = user_fixture()
10 + b = user_fixture()
11 + {:ok, invite} = Accounts.create_invite(a)
12 +
13 + for id <- [a.id, b.id, invite.id] do
14 + assert <<_::binary-size(14), "7", _::binary>> = id
15 + end
16 +
17 + assert a.id < b.id
18 + assert DateTime.diff(DateTime.utc_now(), Vigil.Schema.uuid7_time(a.id)) in 0..5
19 + end
20 +
21 + test "uuid7/0 makes ascending v7 ids" do
22 + ids = for _ <- 1..50, do: Vigil.Schema.uuid7()
23 + assert ids == Enum.sort(ids)
24 + assert Enum.all?(ids, &match?(<<_::binary-size(14), "7", _::binary>>, &1))
25 + end
26 +end

Parents: 5901e75