Files
FFF_vtt_frozen/docs/research/m3-mummy-db-connector.md
T
2026-11-10 16:54:03 +01:00

13 KiB
Raw Blame History

M3 research: mummy 0.4.8 and db_connector API facts (#10)

Date: 2026-11-10. Parent: map #2. Scope: facts + source refs only. No decisions.

Sources read (primary)

  • mummy tag 0.4.8 = commit 77a7563e87a1045e4e407a3a68731e299fa3507e (GitHub API refs/tags/0.4.8). Repo is guzba/mummy, not treeform/mummy as the ticket says (nimble url = github.com/guzba/mummy). Files fetched raw from that commit: src/mummy.nim (1561 L), src/mummy/{common,internal,routers,multipart}.nim. Link base: https://github.com/guzba/mummy/blob/77a7563e87a1045e4e407a3a68731e299fa3507e/. Refs below are src/mummy.nim:N unless noted.
  • mummy at main 01deb1ff (devbox cache): mummy.nim is 54023 B, same size as the tag copy. q20 doc says only .github/workflows differ. Not re-diffed here.
  • webby 0.2.1 (treeformwebby), local pkgcache /home/davide/.nimble/pkgcache/githubcom_treeformwebby_021/src/webby/: httpheaders.nim, queryparams.nim. Upstream tag not fetched.
  • db_connector commit 29450a2063970712422e1ab857695c12d80112a6 (nimble specialVersions 0.1.0; srcDir = "src"). Read from local cache prototype-server-vision/.devbox/nimble/pkgs2/db_connector-0.1.0-4f2e67d0e4b61af9ac5575509305660b473f01a4/db_connector/ (db_sqlite.nim, db_common.nim, sqlite3.nim). Upstream file path inferred as src/db_connector/db_sqlite.nim. Not fetched from GitHub.
  • Nim stdlib hashes.nim (devbox Nim 2.2.12): /nix/store/274jzpwhdklcga24bd9cxywba9apvpic-nim-unwrapped-2.2.12/nim/lib/pure/hashes.nim.
  • Repo: prototype-server-vision/src/server.nim, docs/DESIGN.md §3.2, §4.2–4.4, §6.2, docs/research/q20-nix-packaging.md.

mummy 0.4.8: facts

Build / config

  • Compile guards: --mm:arc|orc|atomicArc and --threads:on required, else {.error.} (src/mummy.nim:1-6).
  • newServer(handler, websocketHandler, logHandler, workerThreads = max(countProcessors()*10,1), maxHeadersLen = 8 KB, maxBodyLen = 1 MB, maxMessageLen = 64 KB, ...) (:1472-1479).
  • serve(port, address = "localhost") (:1414). close(server): in-flight handler calls finish, queued ones not dispatched (:1405-1412).

Threading model

  • RequestHandler = proc(request: Request) {.gcsafe.}; Request = ptr RequestObj (:45-61, :78).
  • Handlers and WS handler run on a worker pool (workerProc, :464). Docstring: "Calls to the HTTP, WebSocket and log handlers are made from worker threads" (:1484). HTTP handler calls run concurrently across requests.
  • WS events for one socket are serialized (per-socket websocketClaimed flag, :483-500). Different sockets run concurrently.
  • Single IO thread: loopForever (:1150).
  • Handler exception: logged; respond(500) if not yet responded (:471-478).
  • The Request is freed after the handler returns: `=destroy`(task.request[]) + deallocShared (:479-480). Do not retain a Request past the handler.
  • responded flag is handler-thread only (docstring :1540-1543). 1xx responses do not set it.

HTTP request access

  • RequestObj fields: httpVersion, httpMethod, uri, path (decoded), queryParams: QueryParams, pathParams, headers: HttpHeaders, body, remoteAddress (:46-58).
  • path/queryParams set from parseUrl(uri) (:847-849); copied in popRequest (:754-776).
  • HttpHeaders = distinct seq[(string,string)]. [] is case-insensitive and returns the first match, "" if absent (webby httpheaders.nim:24-29).
  • QueryParams[key] returns first match, "" if absent (webby queryparams.nim:44-46).
  • No header-name or Origin/Cookie logic in mummy. Grep for Origin/Cookie: none.

Response

  • respond(request, statusCode, headers: sink HttpHeaders, body) (:313-411). Queues under responseQueueLock. Adds Content-Length if absent. Honors Connection header. Gzip/deflate-compresses bodies >860 B when Accept-Encoding matches and no Content-Encoding set.
  • Set-Cookie / multi-value: HttpHeaders[]= replaces the first match or appends (webby httpheaders.nim:30-38). encodeHeaders emits every pair (src/mummy/internal.nim:39-70). Two Set-Cookie lines need a direct append to the underlying seq (toBase, httpheaders.nim:5). Not tested empirically.
  • Redirect: no helper; respond(302, headers with Location). Prototype does this (server.nim:281-285).
  • X-Accel-Redirect: no special handling, plain header passthrough. Prototype uses it (server.nim:301-304).
  • Limits: headers over maxHeadersLen → connection closed, no HTTP status (:799-806). Body over maxBodyLen → connection closed, no 413 (:1004-1006, :1041-1043). Data received while a request is outstanding is logged and not parsed (:783-784).

Routing (src/mummy/routers.nim)

  • Router with get/post/put/delete/head/options/patch and addRoute(method, route, handler) (:23, :80-134).
  • Named path params (pathParams) and partial wildcards *foo, foo* (:160-170).
  • toHandler (:199). Default 404 and 405 bodies are HTML (:136-158).

WebSocket upgrade

  • No upgrade hook. The HTTP handler decides: read headers, then either upgradeToWebSocket(request) or respond(4xx). Prototype refuses with respond(403) (server.nim:287-288).
  • upgradeToWebSocket raises MummyError if: Connection lacks Upgrade, Upgrade lacks websocket, Sec-WebSocket-Key empty, Sec-WebSocket-Version != "13" (:412-438). It returns a WebSocket and queues the 101 (:455-461). Origin is not checked.
  • send() before the 101 is flushed is queued (sendsWaitingForUpgrade, :1217-1223). OpenEvent is posted after the 101 is queued (:1213). If the client is gone before the 101, no OpenEvent (docstring :418-420).

WebSocket identity

  • WebSocket = object with private fields server, clientSocket: SocketHandle, clientId: uint64 (:63-66).
  • clientId = server.rand.next() per accepted socket (:1312).
  • No explicit hash/== in mummy. hash is the generic hash[T: tuple | object] in Nim stdlib, which hashes all fields (hashes.nim:667-669). $websocket uses it (:178-179). Mummy keys its own tables by WebSocket (websocketClaimed, websocketQueues, :107-108).
  • ==: no explicit proc in mummy; relies on Nim's built-in structural equality. Not checked in source.

WebSocket send / close / events

  • WebSocketEvent = OpenEvent | MessageEvent | ErrorEvent | CloseEvent (:72-73).
  • MessageKind = TextMessage | BinaryMessage | Ping | Pong (:75-76). Inbound Ping/Pong are delivered to the handler as messages (:734-737). No auto-Pong reply in source.
  • send(ws, data, kind = TextMessage): enqueues one frame under sendQueueLock, triggers the IO thread (:262-291). Thread-safe by lock.
  • close(ws): enqueues a close frame behind already-queued messages (:293-311). Does not discard the queue.
  • Sends to a disconnected or already-closed socket are dropped with a debug log, no error returned (loopForever :1186-1250; "Dropped message after WebSocket close").
  • Peer close: mummy replies with a close frame and closes (:725-733). If our close frame is sent and no reply in 10 s, force-close (:596-598).
  • Errors and close: ErrorEvent is posted only if no close frame was sent, then CloseEvent (:1399-1404).
  • maxMessageLen (default 64 KB) is checked on inbound frames only, cumulative across fragments (:658-660). Violation closes the TCP connection with no close frame. Outbound sends are not capped by it.
  • Control frames: fragmented or >125 B payload → close (:650-655). Unmasked frame → close (:618-619).

db_connector (db_sqlite) at 29450a2: facts

  • Handle: DbConn* = PSqlite3 (raw sqlite3*) (db_sqlite.nim:183). No lock, no thread-ownership check. Module never calls sqlite3_threadsafe or sqlite3_busy_timeout (grep). Busy handling is left to the caller; SQLITE_BUSY surfaces as DbError.
  • Library: libsqlite3.so(|.0) dynlib, or static with -d:staticSqlite (sqlite3.nim:22-31).
  • Open / close: open(connection, user, password, database). Only connection is used. Raises on failure (:784-805). close(db) (:774-782).
  • Errors: DbError* = object of IOError (db_common.nim:17). dbError(db) raises ref DbError with sqlite3_errmsg text only; no error code exposed (:198-211).
  • exec: exec(db, sql"...", args...) with ? placeholders. Args are $-stringified and escaped by dbQuote (:267-285). Raises on failure.
  • tryExec: returns bool; accepts SQLITE_ROW as success (:235-256). So exec(sql"PRAGMA journal_mode=WAL") works (prototype used getAllRows for it, server.nim:330).
  • Transactions: no API. No begin/commit/rollback proc. Manual db.exec(sql"BEGIN") / COMMIT (doc example :83; prototype server.nim:203-206). No auto-rollback on exception.
  • Prepared statements: prepare(db, q): SqlPrepared (:229-233; finalizes and raises on failure). SqlPrepared = distinct PStmt (:188). bindParams(ps, args...) macro (:287-299). Template exec(db, stmt, args...) does reset + clear_bindings + bind + step (:301-309). finalize(stmt) (:819-820) is manual; the type has no destructor.
  • Bind overloads: int32/int64/int/float64, bindNull, string (bind_text, copy → SQLITE_TRANSIENT, :857-861), openArray[byte] (bind_blob, :863-869). A string binds TEXT, not BLOB.
  • Read: getValue(db, query) returns string and copies BLOB bytes raw (:618-656, BLOB branch :648-650). Row = seq[string]: NULL → "" (:183-185). setRow copies BLOB via column_bytes (:325-335). InstantRow[] returns string (:499-505).
  • Insert id / counts: insertID/tryInsertID (:675-716); execAffectedRows (:745-772).
  • user_version: no API. Read with getValue(db, sql"PRAGMA user_version"); write with exec of a literal. SQLite does not accept bound ? for PRAGMA values. That last point is from SQLite docs, not checked in source here.
  • Thread safety: none in the module. Caller must serialize access to one DbConn. Threading mode of the system libsqlite3 is not checked here.

Gotchas for our design

DESIGN §3.2 (auth, origin, cookies)

  • Origin is not checked by mummy. Read request.headers["Origin"] before upgradeToWebSocket. Missing header returns "", so compare for equality with the configured origin and refuse on mismatch. Refusal is respond(403), not an exception. upgradeToWebSocket raises only on malformed upgrade headers.
  • Cookie: headers["Cookie"] returns only the first Cookie header. Iterate all pairs as prototype does (server.nim:267-272).
  • Setting a session cookie plus a clear/other cookie on one response requires appending to the header seq (see Set-Cookie above). []= silently replaces.
  • Secure/HttpOnly/SameSite are plain strings. mummy adds nothing.

DESIGN §4.2–4.3 (pipeline, threading, outbox)

  • send() is a short lock-and-enqueue; safe to call under our global lock.
  • Outbound frames are unbounded in mummy. maxMessageLen is inbound only (:658). Matches DESIGN §4.3 (no depth API, bounded outbox needed app-side).
  • send after close or after disconnect is silently dropped. Do not rely on send success for correctness.
  • Inbound Ping/Pong reach the handler as MessageEvent with kind Ping/Pong (:734-737). Server-side Ping is send(ws, payload, kind = Ping). Our payload must be ≤125 B.
  • Oversize inbound message → abrupt TCP close, no close frame, no 1009 (:658-660). Client sees a drop, not an error code.
  • No inbound rate limiting in mummy (grep). DESIGN §4.3 plans it in websocketHandler.
  • Prototype runs 8 workers (server.nim:363). Each handler call holds the global lock while doing I/O, so workers block behind it. No backpressure in mummy.
  • WebSocket fields are private. clientId is a random uint64 per accepted socket (:1312). Keying by WebSocket works via generic hash (hashes.nim:667-669), but DESIGN §4.3 already plans an app connId.
  • Request pointer is freed after handler returns (:479-480). Never store it past the handler.
  • respond() from another thread: queue is locked, but request.responded is not. Only call from the handler thread.

DESIGN §4.4 (persistence)

  • Single raw DbConn under the global lock matches the module (no internal lock).
  • No busy_timeout set. Any second connection (e.g. an external tool on the same WAL file) can make exec raise DbError with a busy message. Set PRAGMA busy_timeout via exec if needed.
  • Transactions are manual. An exception between BEGIN and COMMIT leaves the transaction open on the single connection. Need explicit ROLLBACK in the error path.
  • BLOB write: bindParams(stmt, bytesSeq) with openArray[byte]. Passing a string writes TEXT. Read via getValue returns a string of raw bytes; convert as needed.
  • PRAGMA synchronous=NORMAL and journal_mode=WAL via exec (prototype server.nim:330-331).

DESIGN §6.2 (versioning)

  • /ws?proto=N: request.queryParams["proto"] returns "" if absent or not parsed. Query is percent-decoded by webby. Parse the int and check.
  • user_version read/write is getValue/exec (see above). Enforce "refuse newer DB" in app code.

Open / unverified

  • == for WebSocket: Nim built-in structural equality assumed, not read from source.
  • SQLite threading mode of the system libsqlite3: not checked.
  • PRAGMA user_version with bound parameter: SQLite docs, not verified in source.
  • Upstream db_connector path (src/db_connector/db_sqlite.nim) inferred from nimble srcDir.
  • Two Set-Cookie lines on the wire: not tested with a running server.