1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Protocol 6: node identities, error codes, Synchronous, schema v8, examples

- Protocol 5: a client authenticates as a node (Node), its pushes go to the
  section's DefaultTopic unless they name one; old Identities refused at
  start with what to write instead.
- Topics listed by name, ids picked and kept by the server; nodes come from
  client sections, [BakaShrot.Nodes] optional, AcceptNodes = * by default.
- Protocol 6: every refusal carries a code, every client failure too
  (BakaShrot_ErrorCodes.pbi, BakaShrot_GetLastError(), ErrorCode in Python);
  nothing reconnects by itself, delivery is at least once.
- [BakaShrot.Server] Synchronous = FULL (default) or NORMAL, benchmarked.
- Schema v8: browse table and browse_messages view for database tools.
- Tools renamed BakaShrot<Name>, wait for Enter when started from Explorer.
- Examples/SingleServer: a server and a client with scripts (example keys,
  public on purpose).
- Restart-Test.ps1: servers killed mid-traffic and mid-catch-up.
- Docs: one server per node rule, DatabaseError() checked per thread,
  release notes' Compatibility section, Notes "Right now".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVQrLqMQPw9AZnsHqQH
This commit is contained in:
2026-11-09 23:57:55 +01:00
parent df61ef9719
commit 488ffe4bc8
67 changed files with 3163 additions and 1029 deletions
+48 -1
View File
@@ -21,10 +21,16 @@
; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can
; join on them (the "messages" view), and in memory for the server, guarded
; by BakaShrot_Names_Mutex. Every id in "data" has a row:
; origin "config" named in [BakaShrot.Topics] / [BakaShrot.Nodes]
; origin "config" named by the config: in [BakaShrot.Topics] /
; [BakaShrot.Nodes], or a peer's or client's Node
; origin "id" unnamed, its name is its id in digits
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
;
; Ids are this server's to pick: a name the config lists without one keeps
; the one these tables have for it, a new one gets the lowest free one
; (LoadConfig(), after BakaShrot_Names_ReadKnown()). The config may still
; pin one ("logs = 1").
;
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
; on restart). The config wins, except when it would give a name to another
; id than the one the database has it under (or rename a "peer" one): that
@@ -219,6 +225,47 @@ Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.St
EndProcedure
; Fills *Known with what the database has, for LoadConfig() (Config.pbi):
; the id of every name, and every id with a row or messages. Before the
; config is loaded, on a connection of its own, the database set up.
; Returns #False with the reason in *Error\s.
Procedure.i BakaShrot_Names_ReadKnown(DbId.i, *Known.BakaShrot_KnownNames, *Error.String)
Protected Name.s, Id.i
; Topics
If Not DatabaseQuery(DbId, "SELECT topic_id, name FROM topics UNION SELECT DISTINCT topic_id, '' FROM node_heads")
*Error\s = "can't read the topics: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Known\TopicUsed(Str(Id)) = #True
If Name <> "" And Not BakaShrot_IsDigits(Name)
*Known\TopicIds(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
; Nodes
If Not DatabaseQuery(DbId, "SELECT node_id, name FROM nodes UNION SELECT DISTINCT node_id, '' FROM node_heads")
*Error\s = "can't read the nodes: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Known\NodeUsed(Str(Id)) = #True
If Name <> "" And Not BakaShrot_IsDigits(Name)
*Known\NodeIds(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; --- Lookups -----------------------------------------------------------------
; The id Ref stands for: an id in digits is that id, a name must be known.
+44 -14
View File
@@ -3,7 +3,7 @@
;
; Opens the SQLite database file that backs the node's local storage, and
; provides the basic read/write operations on top of it.
; Schema: see db_schema_v7.dbml in this same folder. Attachments: see
; Schema: see db_schema_v8.dbml in this same folder. Attachments: see
; Attachments.pbi and Design/Attachments.md.
;
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
@@ -37,7 +37,7 @@ CompilerElse
CompilerEndIf
; One row of the "data" table (see db_schema_v7.dbml).
; One row of the "data" table (see db_schema_v8.dbml).
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
; AttachmentSize: its attachment's size, 0 for none (the "attachments"
; table), AttachmentReady #True once all of it is here, AttachmentSha256 its
@@ -82,15 +82,18 @@ EndProcedure
; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in
; the file): readers and the writer don't block each other anymore, so a
; long raw query no longer stalls every push.
; With WAL, NORMAL only syncs to disk at checkpoints instead of on every
; commit, which is most of what a push used to cost. The database can't get
; corrupted, but the last commits before a power loss or an OS crash (not a
; crash of the server itself) can be lost. Those messages were acknowledged,
; and maybe replicated already, so their ids could then be handed out again
; for other messages: drift, see Design/ReplicationIssues.md #1.
; FULL syncs every commit, like before, but still lets reads and writes run
; side by side.
#BakaShrot_Storage_Synchronous = "NORMAL"
; PRAGMA synchronous of every connection: [BakaShrot.Server] Synchronous,
; set by the root before it opens any (Server/Root.pbi). FULL by default.
; FULL syncs the WAL on every commit: an acknowledged push is on disk. It
; costs one flush per transaction, shared by a group commit's pushes.
; NORMAL only syncs at checkpoints (about every second, Writer.pbi): the
; database can't get corrupted, but the last commits before a power loss or
; an OS crash (not a crash of the server itself) can be lost. Those messages
; were acknowledged, and maybe replicated already, so their ids could then
; be handed out again for other messages: drift, see
; Design/ReplicationIssues.md #1. Measured: Design/StorageConcurrency.md.
#BakaShrot_Storage_DefaultSynchronous = "FULL"
Global BakaShrot_Storage_Synchronous.s = #BakaShrot_Storage_DefaultSynchronous
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
@@ -120,8 +123,8 @@ Procedure.i OpenStorageDatabase(DatabasePath.s)
ProcedureReturn 0
EndIf
; Per connection, see #BakaShrot_Storage_Synchronous.
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + #BakaShrot_Storage_Synchronous)
; Per connection, see BakaShrot_Storage_Synchronous.
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + BakaShrot_Storage_Synchronous)
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
@@ -232,7 +235,7 @@ Procedure.i MigrateStoragePushedAt(DbId.i)
EndProcedure
; Creates the tables and indexes described by db_schema_v7.dbml, if they
; Creates the tables and indexes described by db_schema_v8.dbml, if they
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
; upgrade mechanism (DbUpdater) will replace this later.
; Fails on a database made with an older schema, since it would be left as is.
@@ -430,6 +433,33 @@ Procedure.i SetupStorageDatabase(DbId.i)
ProcedureReturn #False
EndIf
; For browsing with a database tool: set browse's one row to a topic
; (and optionally a node), open browse_messages. The foreign keys are
; only there for the tools: SQLiteStudio shows a dropdown of the names
; for a column that references them. The server never turns foreign keys
; on, so they never get in its way (a topic renamed in the config only
; leaves a stale name here). The server never writes to browse either.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS browse (" +
"id INTEGER PRIMARY KEY CHECK (id = 1), " +
"topic TEXT COLLATE NOCASE REFERENCES topics (name), " +
"node TEXT COLLATE NOCASE REFERENCES nodes (name))") Or
Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO browse (id) VALUES (1)")
ProcedureReturn #False
EndIf
; Newest first, by the (topic_id, pushed_at) index. Made again on every
; start, like messages.
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS browse_messages") Or
Not DatabaseUpdate(DbId, "CREATE VIEW browse_messages AS " +
"SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, " +
"a.size AS attachment_size, m.topic " +
"FROM browse b JOIN messages m ON m.topic = b.topic " +
"LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id AND a.message_id = m.message_id " +
"WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) " +
"ORDER BY m.pushed_at DESC, m.node, m.message_id DESC")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
+148
View File
@@ -0,0 +1,148 @@
// Changes from v7:
// - browse: one row (id 1), the topic and optionally the node to browse,
// referencing topics and nodes by name so database tools (SQLiteStudio)
// show a dropdown of them. Never written by the server, its foreign keys
// never turned on by it.
// - browse_messages: the view of what browse selects, newest first.
// - The origins of topics and nodes: "config" also covers the nodes the
// config's sections define, "peer" the names peers sent (AcceptTopics /
// AcceptNodes wildcards).
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
// When it was pushed to its origin, ms since 1970-01-01 UTC.
pushed_at integer [not null, default: 0]
indexes {
(topic_id, node_id, message_id) [unique]
message_id
(topic_id, pushed_at)
}
}
// One row per topic/node id that has ever had messages: deleting messages
// (the retention) leaves it as is, so ids never go back.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// A message's attachment (Design/Attachments.md). Its size and SHA-256 come
// with it (pushed, or replicated), its data in blob_id once any is here.
// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready,
// 3 not kept (bigger than this server's MaxAttachmentSize).
// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its
// blob to delete (state 3).
table attachments [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
size integer [not null]
sha256 blob [not null]
blob_id integer
state integer [not null]
indexes {
(topic_id, node_id, message_id) [pk]
state
}
}
// The data of one attachment, being received (an upload, or replicated) or
// stored. topic_id, node_id: an upload's owner, or the message's pair.
// received: bytes stored so far. created_at: ms since 1970 UTC, an upload
// not pushed with its message within UploadTimeout is deleted.
// state: 0 receiving, 1 complete (an upload waiting for its message),
// 2 attached, 3 to delete.
table blobs {
blob_id integer [pk]
topic_id integer [not null]
node_id integer [not null]
size integer [not null]
sha256 blob [not null]
received integer [not null, default: 0]
state integer [not null]
created_at integer [not null]
indexes {
state
}
}
// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one
// what's left.
table blob_chunks {
blob_id integer [not null]
chunk_index integer [not null]
chunk_data blob [not null]
indexes {
(blob_id, chunk_index) [pk]
}
}
// origin: "config" (named in [BakaShrot.Topics]), "peer" (taken from a
// peer by a wildcard), "id" (unnamed, name is the id in digits).
table topics {
topic_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// origin: "config" (named in [BakaShrot.Nodes], or a node the config's
// [BakaShrot], peer or client sections define), "peer" (taken from a peer:
// AcceptNodes is * by default), "id" (unnamed).
table nodes {
node_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// View messages:
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
// JOIN nodes n ON n.node_id = d.node_id
// WHERE topic = ... AND node = ... goes through the name indexes, then
// data's (topic_id, node_id, message_id) one.
// What to browse with a database tool: set topic (and node, NULL for every
// one) in its one row, open browse_messages. The references are for the
// tools' dropdowns only: the server doesn't turn foreign keys on.
table browse {
id integer [pk, note: 'CHECK (id = 1)']
topic text [ref: > topics.name, note: 'COLLATE NOCASE']
node text [ref: > nodes.name, note: 'COLLATE NOCASE']
}
// View browse_messages:
// SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json,
// a.size AS attachment_size, m.topic
// FROM browse b JOIN messages m ON m.topic = b.topic
// LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id
// AND a.message_id = m.message_id
// WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node)
// ORDER BY m.pushed_at DESC, m.node, m.message_id DESC
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL