Files
Warp/docs/development.md
T
tajniak81andClaude Opus 5 d187ad0d17
CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s
Phase 4: sync
Implements PLAN.md Phase 4: the read model. /sync, /messages and /context,
the filters that narrow them, and the streams a response carries that are
not room events — typing, receipts, presence and to-device messages. With
this a client can be used against Warp, which is milestone M1.

The one architectural choice is that the syncapi has no copy of the rooms:
it reads them through the roomserver. Dendrite gives its syncapi its own
tables and feeds them from the output stream, which is right for a design
where the two can be separate processes, and Dendrite's could be. Warp is
one process by decision, and there the copy buys nothing and costs the
hardest class of bug a homeserver has — a read model that disagrees with
the room, where a client is shown a message that was rejected and the only
way to find out is to compare two tables. So the roomserver grew a read
model (stream.go, roomsync.go, visibility.go) rather than exporting its
store: reading an event means parsing it under its room's version, and a
second copy of the version registry, the parser and the client projection
would be a second place for them to disagree.

syncapi: stream tokens naming a position in each of five independent
streams, so a client that has seen receipt 7 but only event 4 can say so in
one opaque string. A token with fewer positions than this build writes is
accepted and the rest read as zero, which is what lets a token stored
before a stream existed go on working. The PDU position comes from
MAX(stream_ordering) and not from the counter row the other four use: the
counter is advanced inside the writing transaction, so a token taken from
it would name a position whose event no reader can see yet, and the event
would be skipped for good once that transaction committed.

Long polling goes through a notifier that wakes by room and by user rather
than globally — an event wakes the listeners of its room, a membership
event also wakes the user it names, so an invite reaches a client that is
not in the room yet. A wake-up is only ever a hint: the listener re-reads
the streams and decides for itself what changed, which is what makes it
safe for the notifier to hold no state about what each client has seen. The
listener registers before the read, so an event landing in between leaves
the channel signalled and the sync reads again rather than blocking on a
change it just missed. EventPersisted must not block, because it is called
with the room's write lock still held.

"Something happened" is not "a token moved". A stream can move without this
user being concerned by it, and returning on every such move would turn a
long poll back into a busy loop. The same trap caught presence twice over:
a client says it is still online by syncing, so ?set_presence= makes every
sync a presence write, and a stream that moved each time would wake every
peer, which would sync, which would move it again. SetPresence therefore
reports whether anything a peer would notice actually changed, and a write
that only refreshes the last-active timestamp leaves the stream alone.

Timeline windows are named by their two ends and a direction, Low exclusive
and High inclusive in both directions, rather than by "from" and "to" as
the wire format spells them. Each of those would otherwise be the low bound
in one direction and the high bound in the other, which is exactly the
off-by-one every pagination bug is made of; the handlers translate once and
nothing below them thinks about it again. A sync's timeline is read
backwards and reported forwards, because a client wants the newest events
of the window it missed — a forward read with a limit hands it the oldest
and then calls the rest a gap.

visibility: history visibility is now a span rather than a yes or no, which
is what Phase 3 deferred here. A user who has left a room is served the
room as it was when they left — their state reads, their members and their
timeline — instead of being refused, and is bounded above at their own
membership event so a kicked client cannot go on streaming. Their span is
found from their own member events, so a user who joined, left and rejoined
sees their latest span. ?at= on /members is honoured for the same reason.
What is left is that the span is computed from the room's current
history_visibility where the spec judges each event by the one in force
when it was sent; that is a state read per event and belongs with open
question 1.

Typing is held in memory and nowhere else: notifications expire in seconds,
are worthless across a restart, and arrive one per keystroke-burst per
room, so persisting them would be the busiest table in the database holding
the least valuable data in it. Receipts only ever advance, compared on the
position of the event acknowledged rather than on arrival, because two of a
user's clients read at different speeds and the slower one must not drag
the marker backwards. To-device queues are per device and drained by the
next sync rather than by the one that delivered them, so a client that
crashes in between gets the batch again — the right way round, since a lost
key share leaves a message permanently undecryptable and a duplicate is
ignored. A wildcard addressee is expanded when sent, not stored, because
"every device" means the ones that existed then.

Presence is off by default, which answers PLAN.md open question 3. It is
the noisiest thing in Matrix and the one genuinely fan-out notification
here; a private homeserver gains little from it. With it off the endpoints
refuse rather than disappearing, because a client that gets a 404 from
/presence concludes the server is too old to have it and stops asking.

storage: one migration per driver adding the receipt, to-device, presence
and filter tables with a counter row each, and a stream position on the
existing account data table rather than a parallel one — there is exactly
one current value per (user, room, type), and a second table would be a
second thing to keep in step. Account data is reported in an event list but
is not an event, so it gets its own response type: a room event with an
empty sender and no timestamp would make a client decide what that meant.

Deliberately missing, each named in docs/sync.md: notification counts (they
need push rules, Phase 8), device lists (the keyserver, Phase 7), anything
remote (Phase 5), threads (Phase 10). device_lists is sent as two empty
lists because a client reads a missing one as malformed; the notification
counts are left out entirely, because a zero there is a claim and an absent
field is not.

Tested through HTTP rather than against the builder, because what is worth
pinning down is the response a client sees — which section a room lands in,
whether a token handed back can be handed in again, whether paging
terminates and loses nothing. The storage tests run against both SQL
drivers; the notifier has its own tests for the concurrent case. A live
server was driven end to end, which is what caught the two bugs the unit
tests had missed: a backwards /messages page must be in reverse
chronological order, and `start` must name where the page began rather than
position zero when ?from= was omitted.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-16 11:55:27 +02:00

188 lines
7.4 KiB
Markdown

# Development
## Prerequisites
- Go 1.26+. Nothing else for the default build: the SQLite driver is pure
Go and `CGO_ENABLED=0` works everywhere.
- A C toolchain only if you want `go test -race`.
- PostgreSQL only to run the storage tests against it.
- `golangci-lint` v2 for `make lint`:
`go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@latest`
## Everyday commands
```sh
make build # bin/warp
make test # go test ./... in server/
make check # vet + test
make lint
make cover # coverage.html
make clean
```
Each one is a two-line shell command if you would rather not use `make`;
look at the [Makefile](../Makefile).
## Running a server locally
```sh
cp warp.yaml.example warp.yaml # set global.server_name
make build
./bin/warp generate-keys
./bin/warp serve
```
The SQLite file, the signing key and (later) the media store are written
relative to the working directory. They are in `.gitignore`.
For a throwaway server with no config file at all:
```sh
WARP_SERVER_NAME=dev.local WARP_PRIVATE_KEY=./keys/dev.key ./bin/warp generate-keys
WARP_SERVER_NAME=dev.local WARP_PRIVATE_KEY=./keys/dev.key ./bin/warp serve
```
## Adding a database migration
1. Write the same change twice, once per SQL dialect:
`server/internal/storage/sqlite/migrations/NNNN_name.sql` and
`server/internal/storage/postgres/migrations/NNNN_name.sql`.
Use the next free number; `NNNN` is zero-padded to four digits.
2. The files are embedded with `embed.FS`, so a rebuild picks them up.
3. `./bin/warp migrate --status` lists what would run, `./bin/warp migrate`
applies it. A server started with `database.auto_migrate: true` (the
default) runs them itself.
Rules the runner enforces:
- One transaction per migration. A failure rolls that file back entirely
and leaves the following ones unapplied.
- A migration that has already been applied and whose file has since
changed is an error. Write a new migration instead of editing an old
one; the checksum of every applied file is recorded.
- A database that has migrations this binary does not know about refuses
to start, so an old binary cannot run against a newer schema.
## Long-polling endpoints
`/sync` holds a request open until something happens, which has two
consequences worth knowing about when running a server locally.
`listen.write_timeout` must stay above `sync.long_poll_timeout`, or the
listener cuts off a blocked sync before it can answer. The defaults
(`120s` and `30s`) leave room; a proxy in front of the server needs the same
check.
A blocked sync is woken through `syncapi.Notifier`, not by polling, so a
test that sends an event and then expects a blocked sync to return has to
make sure the sync is actually blocked first — otherwise it finds the event
without ever having waited, and passes without testing anything.
`Notifier.Listeners()` exists for that, and
`internal/clientapi/sync_test.go` shows the pattern.
## Adding an endpoint
Routes are registered in `server/internal/setup/routes.go` on an
`httputil.Router`, which is `http.ServeMux` plus per-route metrics:
```go
r.HandleFunc("GET /_matrix/client/v3/profile/{userID}/displayname", s.handleGetDisplayName)
```
Handlers have the signature `func(http.ResponseWriter, *http.Request) error`
and return Matrix errors directly:
```go
func (s *Server) handleThing(w http.ResponseWriter, r *http.Request) error {
if somethingWrong {
return httputil.Forbidden("You are not allowed to do that")
}
httputil.WriteJSON(w, http.StatusOK, response{})
return nil
}
```
Anything returned that is not a `*httputil.MatrixError` is logged in full
and reported to the client as `M_UNKNOWN`, so internal detail never leaks.
Endpoints that belong to the federation surface are registered through the
gate instead, so they disappear when federation is switched off:
```go
r.Handle("GET /_matrix/federation/v1/version", s.federation.ProtectFunc(s.handleFederationVersion))
```
A Client-Server endpoint that would need federation to answer returns
`federation.RejectClientRequest("...")`, which is an `M_FORBIDDEN` that
says why.
## Tests
- Unit tests live next to the code. Each API package holds its own
HTTP-level tests, built on a throwaway SQLite database with the real
components behind them rather than fakes; `internal/setup` holds the
smaller set that goes through the whole wrapped handler, to catch a route
that was written but never registered.
- Storage tests run against every driver that is available:
SQLite always, PostgreSQL when `WARP_TEST_POSTGRES_DSN` is set. The
PostgreSQL tests share one database, so each group of them truncates the
tables it owns first; add a table to `resetRoomTables` or
`resetSyncTables` when you add one, or the second test to insert the same
row will collide — and only in CI, where PostgreSQL exists.
- The event core under `internal/matrix` is tested against the spec's own
cryptographic and canonical JSON test vectors, and has fuzz targets for
the two functions that read bytes straight off the network. `make test`
runs the unit tests; the fuzzers are opt-in. See
[event-core.md](event-core.md).
- CI runs `gofmt -l`, `go mod tidy` (as a diff check), `go vet`, the tests
on Linux and Windows, the race detector on Linux, `golangci-lint`, and a
smoke test that boots the real binary and curls it.
## Complement
[Complement](https://github.com/matrix-org/complement) is the official Matrix
integration suite. It runs a container per homeserver per test and drives it
over the real HTTP API, which makes its pass count the honest measure of how
far along the server is — PLAN.md section 9 treats it as the primary progress
metric.
```sh
make complement # the current target set
server/test/complement/run.sh TestLogin # one test
COMPLEMENT_DEBUG=1 make complement # with the container logs
```
It needs Docker. The script builds the image, clones Complement into
`.complement/` (ignored by git) and runs the subset for the phases that are
done — the account, room and stream tests, with federation off. Extend
`COMPLEMENT_TESTS` in
[run.sh](../server/test/complement/run.sh) as each phase lands, rather than
switching to the whole suite: a pass count that drops because a later phase
is missing is noise.
The image is [server/test/complement/Dockerfile](../server/test/complement/Dockerfile)
and the deployment is entirely `WARP_*` environment variables — see
[entrypoint.sh](../server/test/complement/entrypoint.sh). Two things there
are worth knowing: rate limiting is off, because the whole suite comes from
one address and would otherwise spend its time reading `M_LIMIT_EXCEEDED`;
and port 8448 is exposed but nothing listens on it yet. The federation
profile needs a TLS listener signed by the CA that Complement mounts at
`/complement/ca`, which arrives with federation in Phase 5.
## Creating the first account
A new install has registration off, so the first account is made from the
command line against the database directly — no server needs to be running:
```sh
./bin/warp create-account --username you --admin
```
It prompts for the password twice. `--password-file` reads it from a file and
`--password` takes it inline, for scripts that have already thought about the
shell history. From there, the admin API can turn registration on:
```sh
curl -X PUT http://localhost:8008/_warp/admin/v1/registration -H "Authorization: Bearer $TOKEN" -d '{"enabled": true}'
```