13 KiB
13 KiB
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 APIrefs/tags/0.4.8). Repo isguzba/mummy, nottreeform/mummyas the ticket says (nimbleurl= 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 aresrc/mummy.nim:Nunless noted. - mummy at main
01deb1ff(devbox cache):mummy.nimis 54023 B, same size as the tag copy. q20 doc says only.github/workflowsdiffer. 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(nimblespecialVersions0.1.0;srcDir = "src"). Read from local cacheprototype-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 assrc/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|atomicArcand--threads:onrequired, 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
websocketClaimedflag,:483-500). Different sockets run concurrently. - Single IO thread:
loopForever(:1150). - Handler exception: logged;
respond(500)if not yet responded (:471-478). - The
Requestis freed after the handler returns:`=destroy`(task.request[])+deallocShared(:479-480). Do not retain aRequestpast the handler. respondedflag is handler-thread only (docstring:1540-1543). 1xx responses do not set it.
HTTP request access
RequestObjfields:httpVersion, httpMethod, uri, path(decoded),queryParams: QueryParams,pathParams,headers: HttpHeaders,body,remoteAddress(:46-58).path/queryParamsset fromparseUrl(uri)(:847-849); copied inpopRequest(: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 underresponseQueueLock. AddsContent-Lengthif absent. HonorsConnectionheader. Gzip/deflate-compresses bodies >860 B whenAccept-Encodingmatches and noContent-Encodingset.- Set-Cookie / multi-value:
HttpHeaders[]=replaces the first match or appends (webby httpheaders.nim:30-38).encodeHeadersemits every pair (src/mummy/internal.nim:39-70). TwoSet-Cookielines 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 overmaxBodyLen→ 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)
Routerwithget/post/put/delete/head/options/patchandaddRoute(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)orrespond(4xx). Prototype refuses withrespond(403)(server.nim:287-288). upgradeToWebSocketraisesMummyErrorif:ConnectionlacksUpgrade,Upgradelackswebsocket,Sec-WebSocket-Keyempty,Sec-WebSocket-Version != "13"(:412-438). It returns aWebSocketand queues the 101 (:455-461). Origin is not checked.send()before the 101 is flushed is queued (sendsWaitingForUpgrade,:1217-1223).OpenEventis posted after the 101 is queued (:1213). If the client is gone before the 101, noOpenEvent(docstring:418-420).
WebSocket identity
WebSocket = objectwith private fieldsserver,clientSocket: SocketHandle,clientId: uint64(:63-66).clientId = server.rand.next()per accepted socket (:1312).- No explicit
hash/==in mummy.hashis the generichash[T: tuple | object]in Nim stdlib, which hashes all fields (hashes.nim:667-669).$websocketuses it (:178-179). Mummy keys its own tables byWebSocket(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 undersendQueueLock, 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:
ErrorEventis posted only if no close frame was sent, thenCloseEvent(: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(rawsqlite3*) (db_sqlite.nim:183). No lock, no thread-ownership check. Module never callssqlite3_threadsafeorsqlite3_busy_timeout(grep). Busy handling is left to the caller;SQLITE_BUSYsurfaces asDbError. - Library:
libsqlite3.so(|.0)dynlib, or static with-d:staticSqlite(sqlite3.nim:22-31). - Open / close:
open(connection, user, password, database). Onlyconnectionis used. Raises on failure (:784-805).close(db)(:774-782). - Errors:
DbError* = object of IOError(db_common.nim:17).dbError(db)raisesref DbErrorwithsqlite3_errmsgtext only; no error code exposed (:198-211). - exec:
exec(db, sql"...", args...)with?placeholders. Args are$-stringified and escaped bydbQuote(:267-285). Raises on failure. - tryExec: returns
bool; acceptsSQLITE_ROWas success (:235-256). Soexec(sql"PRAGMA journal_mode=WAL")works (prototype usedgetAllRowsfor it,server.nim:330). - Transactions: no API. No begin/commit/rollback proc. Manual
db.exec(sql"BEGIN")/COMMIT(doc example:83; prototypeserver.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). Templateexec(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)returnsstringand copies BLOB bytes raw (:618-656, BLOB branch:648-650).Row = seq[string]: NULL →""(:183-185).setRowcopies BLOB viacolumn_bytes(:325-335).InstantRow[]returnsstring(: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 withexecof 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 systemlibsqlite3is not checked here.
Gotchas for our design
DESIGN §3.2 (auth, origin, cookies)
- Origin is not checked by mummy. Read
request.headers["Origin"]beforeupgradeToWebSocket. Missing header returns"", so compare for equality with the configured origin and refuse on mismatch. Refusal isrespond(403), not an exception.upgradeToWebSocketraises only on malformed upgrade headers. - Cookie:
headers["Cookie"]returns only the firstCookieheader. 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/SameSiteare 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.
maxMessageLenis inbound only (:658). Matches DESIGN §4.3 (no depth API, bounded outbox needed app-side). sendaftercloseor after disconnect is silently dropped. Do not rely on send success for correctness.- Inbound Ping/Pong reach the handler as
MessageEventwith kindPing/Pong(:734-737). Server-side Ping issend(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. WebSocketfields are private.clientIdis a random uint64 per accepted socket (:1312). Keying byWebSocketworks via generic hash (hashes.nim:667-669), but DESIGN §4.3 already plans an appconnId.Requestpointer is freed after handler returns (:479-480). Never store it past the handler.respond()from another thread: queue is locked, butrequest.respondedis not. Only call from the handler thread.
DESIGN §4.4 (persistence)
- Single raw
DbConnunder the global lock matches the module (no internal lock). - No
busy_timeoutset. Any second connection (e.g. an external tool on the same WAL file) can makeexecraiseDbErrorwith a busy message. SetPRAGMA busy_timeoutviaexecif needed. - Transactions are manual. An exception between
BEGINandCOMMITleaves the transaction open on the single connection. Need explicitROLLBACKin the error path. - BLOB write:
bindParams(stmt, bytesSeq)withopenArray[byte]. Passing astringwrites TEXT. Read viagetValuereturns astringof raw bytes; convert as needed. PRAGMA synchronous=NORMALandjournal_mode=WALviaexec(prototypeserver.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_versionread/write isgetValue/exec(see above). Enforce "refuse newer DB" in app code.
Open / unverified
==forWebSocket: Nim built-in structural equality assumed, not read from source.- SQLite threading mode of the system
libsqlite3: not checked. PRAGMA user_versionwith bound parameter: SQLite docs, not verified in source.- Upstream db_connector path (
src/db_connector/db_sqlite.nim) inferred from nimblesrcDir. - Two
Set-Cookielines on the wire: not tested with a running server.