From 9caf816dca9ff017c755d2e822e4eea835976c06 Mon Sep 17 00:00:00 2001 From: Herwin Bozet Date: Sun, 8 Nov 2026 17:01:48 +0100 Subject: [PATCH 1/5] Add pushed_at timestamps and per-topic retention - Every message is stamped with the time its push arrived (UTC ms since 1970, the server's clock), carried as is by replication. Exposed in LatestMessage and Messages, BakaShrot_GetMessagePushedAt() in the DLL, Message.pushed_at / .pushed in Python, GetMessages --time, GetLatestMessage, and the messages view (pushed_at, pushed_utc). - [BakaShrot.Retention] in each server's config: a max age per topic, by name, id, pattern or *, ages like 30d or 1d12h. A background pass (Server/Storage/Retention.pbi, every RetentionInterval seconds) deletes what's older, in batches through the writer. node_heads is left as is, so ids never go back and peers don't resend what was deleted. - Replicated messages already past the receiver's max age are skipped on arrival, their head still raised so they aren't sent again. - Schema v6: data.pushed_at (older databases stamped at upgrade time), a (topic_id, pushed_at) index, the unused archives table dropped. The writer takes the next id from node_heads. - Folded into protocol 3, not released yet. - Tests/Retention-Test.ps1 (52 checks), Python checks for pushed_at. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP --- Client/BakaShrot_Client.pbi | 14 + Client/BakaShrot_Client_Prototypes.pbi | 5 +- Commons/Networking/Packets.pbi | 13 +- .../Packets/LatestMessagePacket.pbi | 14 + Commons/Networking/Packets/MessagesPacket.pbi | 16 +- .../Packets/ReplicateMessagesPacket.pbi | 18 +- Design/Packets.md | 23 +- Design/Release.md | 2 +- Interactors/Python/bakashrot.py | 15 +- Interactors/Python/check_bakashrot.py | 9 + Notes.md | 93 ++++- Server/Config/Config.pbi | 198 ++++++++++ Server/Config/schema.ini | 21 ++ Server/Networking/Networking.pbi | 20 +- Server/Networking/Peers.pbi | 2 + Server/Root.pbi | 12 + Server/Storage/Retention.pbi | 173 +++++++++ Server/Storage/Storage.pbi | 118 +++++- Server/Storage/Writer.pbi | 150 +++++++- Server/Storage/db_schema_v6.dbml | 89 +++++ Tests/Bench/BenchSeed.pb | 2 +- Tests/Names-Test.ps1 | 2 +- Tests/Retention-Test.ps1 | 343 ++++++++++++++++++ Tools/Common/ToolClient.pbi | 7 + Tools/GetLatestMessage/GetLatestMessage.pb | 5 +- Tools/GetMessages/GetMessages.pb | 17 +- 26 files changed, 1327 insertions(+), 54 deletions(-) create mode 100644 Server/Storage/Retention.pbi create mode 100644 Server/Storage/db_schema_v6.dbml create mode 100644 Tests/Retention-Test.ps1 diff --git a/Client/BakaShrot_Client.pbi b/Client/BakaShrot_Client.pbi index d2d9cf4..a92e6a0 100644 --- a/Client/BakaShrot_Client.pbi +++ b/Client/BakaShrot_Client.pbi @@ -17,6 +17,7 @@ ; BakaShrot_GetLatestMessageOf(Topic, Node), or ; BakaShrot_GetLatestMessage(TopicId, NodeId), then ; BakaShrot_GetMessageId(), BakaShrot_GetMessageData(), +; BakaShrot_GetMessagePushedAt() (ms since 1970 UTC), ; BakaShrot_GetMessageTopic() / BakaShrot_GetMessageNode() (names) ; and BakaShrot_GetMessageTopicId() / BakaShrot_GetMessageNodeId() ; BakaShrot_GetMessages(Topic, Node, AfterMessageId, Limit): the @@ -86,6 +87,7 @@ Global BakaShrot_Outbound.BakaShrot_Outbound ; Filled by the requests, see BakaShrot_GetLatestMessage() and BakaShrot_GetRefusalReasonA/W(). Global BakaShrot_MessageId.q = 0 +Global BakaShrot_MessagePushedAt.q = 0 Global BakaShrot_MessageData.s = "" Global BakaShrot_MessageTopicId.l = -1 Global BakaShrot_MessageNodeId.l = -1 @@ -511,6 +513,7 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) BakaShrot_RefusalReason = "" BakaShrot_MessageId = 0 + BakaShrot_MessagePushedAt = 0 BakaShrot_MessageData = "" BakaShrot_MessageTopicId = -1 BakaShrot_MessageNodeId = -1 @@ -564,6 +567,7 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) IsExpected = Bool(BakaShrot_RefMatches(Topic, *Latest\TopicId, *Latest\TopicName) And BakaShrot_RefMatches(Node, *Latest\NodeId, *Latest\NodeName)) If IsExpected BakaShrot_MessageId = *Latest\MessageId + BakaShrot_MessagePushedAt = *Latest\PushedAt BakaShrot_MessageData = *Latest\JsonData BakaShrot_MessageTopicId = *Latest\TopicId BakaShrot_MessageNodeId = *Latest\NodeId @@ -571,6 +575,7 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) BakaShrot_MessageNode = *Latest\NodeName AddElement(BakaShrot_Messages()) BakaShrot_Messages()\MessageId = *Latest\MessageId + BakaShrot_Messages()\PushedAt = *Latest\PushedAt BakaShrot_Messages()\JsonData = *Latest\JsonData EndIf FreeStructure(*Latest) @@ -627,6 +632,7 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit BakaShrot_RefusalReason = "" BakaShrot_MessageId = 0 + BakaShrot_MessagePushedAt = 0 BakaShrot_MessageData = "" BakaShrot_MessageTopicId = -1 BakaShrot_MessageNodeId = -1 @@ -709,6 +715,7 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit If FirstElement(BakaShrot_Messages()) BakaShrot_MessageId = BakaShrot_Messages()\MessageId + BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt BakaShrot_MessageData = BakaShrot_Messages()\JsonData EndIf ProcedureReturn Count @@ -743,6 +750,7 @@ ProcedureCDLL.i BakaShrot_SelectMessage(Index.l) EndIf SelectElement(BakaShrot_Messages(), Index) BakaShrot_MessageId = BakaShrot_Messages()\MessageId + BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt BakaShrot_MessageData = BakaShrot_Messages()\JsonData ProcedureReturn #True EndProcedure @@ -759,6 +767,12 @@ ProcedureCDLL.q BakaShrot_GetMessageId() ProcedureReturn BakaShrot_MessageId EndProcedure +; When that message was pushed, to whichever server it was pushed to: in +; milliseconds since 1970-01-01 00:00:00 UTC. 0 if none. +ProcedureCDLL.q BakaShrot_GetMessagePushedAt() + ProcedureReturn BakaShrot_MessagePushedAt +EndProcedure + ; The server's topic and node ids of that message, -1 if none. ProcedureCDLL.l BakaShrot_GetMessageTopicId() ProcedureReturn BakaShrot_MessageTopicId diff --git a/Client/BakaShrot_Client_Prototypes.pbi b/Client/BakaShrot_Client_Prototypes.pbi index eea6fa0..e711375 100644 --- a/Client/BakaShrot_Client_Prototypes.pbi +++ b/Client/BakaShrot_Client_Prototypes.pbi @@ -31,6 +31,7 @@ PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unico PrototypeC.i BakaShrot_GetLatestMessage_Prototype(TopicId.l, NodeId.l) PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) PrototypeC.q BakaShrot_GetMessageId_Prototype() +PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) PrototypeC.l BakaShrot_GetMessageTopicId_Prototype() PrototypeC.l BakaShrot_GetMessageNodeId_Prototype() @@ -66,6 +67,7 @@ Global BakaShrot_PushMessageTo.BakaShrot_PushMessageTo_Prototype Global BakaShrot_GetLatestMessage.BakaShrot_GetLatestMessage_Prototype Global BakaShrot_GetLatestMessageOf.BakaShrot_GetLatestMessageOf_Prototype Global BakaShrot_GetMessageId.BakaShrot_GetMessageId_Prototype +Global BakaShrot_GetMessagePushedAt.BakaShrot_GetMessagePushedAt_Prototype Global BakaShrot_GetMessageData.BakaShrot_GetMessageData_Prototype Global BakaShrot_GetMessageTopicId.BakaShrot_GetMessageTopicId_Prototype Global BakaShrot_GetMessageNodeId.BakaShrot_GetMessageNodeId_Prototype @@ -123,6 +125,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_PushMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageW") BakaShrot_GetLatestMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLatestMessage") BakaShrot_GetMessageId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageId") + BakaShrot_GetMessagePushedAt = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessagePushedAt") BakaShrot_GetMessageData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageDataW") BakaShrot_GetRefusalReason = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetRefusalReasonW") BakaShrot_Query = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_QueryW") @@ -149,7 +152,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) ProcedureReturn #False EndIf - If Not BakaShrot_PushMessage Or Not BakaShrot_GetLatestMessage Or Not BakaShrot_GetMessageId Or Not BakaShrot_GetMessageData Or Not BakaShrot_GetRefusalReason + If Not BakaShrot_PushMessage Or Not BakaShrot_GetLatestMessage Or Not BakaShrot_GetMessageId Or Not BakaShrot_GetMessagePushedAt Or Not BakaShrot_GetMessageData Or Not BakaShrot_GetRefusalReason BakaShrot_UnloadClient() ProcedureReturn #False EndIf diff --git a/Commons/Networking/Packets.pbi b/Commons/Networking/Packets.pbi index fba749e..00deffe 100644 --- a/Commons/Networking/Packets.pbi +++ b/Commons/Networking/Packets.pbi @@ -18,7 +18,8 @@ EndStructure #BakaShrot_ProtocolMagic = $42534854 ; "BSHT" ; 2: topics and nodes by name (Commons/Networking/Names.pbi), see Design/Packets.md. ; 3: the Hello sealed for the server, a key per connection, everything after -; the ChallengeRequest encrypted (Connections.pbi). +; the ChallengeRequest encrypted (Connections.pbi). Messages carry when +; they were pushed (PushedAt). #BakaShrot_ProtocolVersion = 3 ; Size in bytes of the nonce sent in a challenge request and echoed in its response. @@ -39,6 +40,16 @@ EndStructure ; (#BakaShrot_Ed25519_SignatureSize). #BakaShrot_HandshakeSignatureSize = 64 +; When a message was pushed: milliseconds since 1970-01-01 00:00:00 UTC, set +; by the server it was pushed to, and kept as is by every server it's +; replicated to. Anything outside 1 to #BakaShrot_MaxTimestamp (9999-12-31) +; is invalid on the wire. +#BakaShrot_MaxTimestamp = 253402300799999 + +Procedure.i BakaShrot_IsValidTimestamp(Timestamp.q) + ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp) +EndProcedure + ; Biggest packet accepted on the wire once authenticated, anything bigger ; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize ; (Connections.pbi). diff --git a/Commons/Networking/Packets/LatestMessagePacket.pbi b/Commons/Networking/Packets/LatestMessagePacket.pbi index 3232016..933cb47 100644 --- a/Commons/Networking/Packets/LatestMessagePacket.pbi +++ b/Commons/Networking/Packets/LatestMessagePacket.pbi @@ -8,12 +8,14 @@ XIncludeFile "../Packets.pbi" ; S2C, answers a GetLatestMessage with the latest message of that topic/node combination. ; TopicId, NodeId: the server's own ids for them. ; TopicName, NodeName: their names, or their ids in digits if they have none. +; PushedAt: when it was pushed, see Packets.pbi. Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase TopicId.l NodeId.l TopicName.s NodeName.s MessageId.q + PushedAt.q JsonData.s EndStructure @@ -56,6 +58,9 @@ Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage If MsgPackWriteInteger(*MsgPackData, *Latest\MessageId) <> #MsgPack_Error_Success Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Latest\PushedAt) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success Goto EncodeFailed @@ -139,6 +144,15 @@ Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData) Goto DecodeFailed EndIf + ; PushedAt + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Latest\PushedAt = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Latest\PushedAt) + Goto DecodeFailed + EndIf + ; JsonData If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String Goto DecodeFailed diff --git a/Commons/Networking/Packets/MessagesPacket.pbi b/Commons/Networking/Packets/MessagesPacket.pbi index 376224b..2eafad1 100644 --- a/Commons/Networking/Packets/MessagesPacket.pbi +++ b/Commons/Networking/Packets/MessagesPacket.pbi @@ -9,6 +9,8 @@ XIncludeFile "GetMessagesPacket.pbi" ; One message of a Messages answer. Structure BakaShrot_MessagesEntry MessageId.q + ; When it was pushed, see Packets.pbi. + PushedAt.q JsonData.s EndStructure @@ -19,7 +21,7 @@ EndStructure ; Encoded size of the answer's own fields, and of each message on top of its ; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize. #BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2) -#BakaShrot_MessagesMessageOverhead = 16 +#BakaShrot_MessagesMessageOverhead = 25 ; S2C, answers a GetMessages with the messages of that topic/node combination ; stored after the asked id, in message id order: as many as were asked for, @@ -91,6 +93,9 @@ Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\MessageId) <> #MsgPack_Error_Success Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\PushedAt) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success Goto EncodeFailed EndIf @@ -200,6 +205,15 @@ Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData) EndIf PreviousMessageId = *Answer\Messages()\MessageId + ; PushedAt + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Answer\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Answer\Messages()\PushedAt) + Goto DecodeFailed + EndIf + ; JsonData If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String Goto DecodeFailed diff --git a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi index fe8c19e..6b564fa 100644 --- a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi +++ b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi @@ -6,8 +6,10 @@ XIncludeFile "../Packets.pbi" ; One message of a ReplicateMessages batch. +; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is. Structure BakaShrot_ReplicatedMessage MessageId.q + PushedAt.q JsonData.s EndStructure @@ -24,14 +26,14 @@ EndStructure ; Encoded size of a batch's own fields, and of each message on top of its ; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize. #BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2) -#BakaShrot_ReplicateMessageOverhead = 16 +#BakaShrot_ReplicateMessageOverhead = 25 ; Peer -> Server, messages the server is missing for one topic/node, in ; message id order, with the message ids they were stored under on their ; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi): ; the server stores them under its own ids for those names, and refuses ; names it doesn't know. -; On the wire: topic, node, message count, then each message's id and JSON. +; On the wire: topic, node, message count, then each message's id, PushedAt and JSON. ; Answered with a MessagePushed carrying the last message's id, or a RequestRefused. Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase Topic.s @@ -79,6 +81,9 @@ Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateM If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\MessageId) <> #MsgPack_Error_Success Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\PushedAt) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success Goto EncodeFailed EndIf @@ -158,6 +163,15 @@ Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData) EndIf PreviousMessageId = *Batch\Messages()\MessageId + ; PushedAt + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Batch\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Batch\Messages()\PushedAt) + Goto DecodeFailed + EndIf + ; JsonData If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String Goto DecodeFailed diff --git a/Design/Packets.md b/Design/Packets.md index a90b298..db7bb81 100644 --- a/Design/Packets.md +++ b/Design/Packets.md @@ -122,11 +122,11 @@ over its own link to another server. | 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str | MessagePushed / RequestRefused | | 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | | | 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused | -| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `JsonData` str | | +| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str | | | 12 | RequestRefused | S→C | `Reason` str, for logs and humans | | | 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused | | 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | | -| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing) and `JsonData` str | MessagePushed (last id) / RequestRefused | +| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin) and `JsonData` str | MessagePushed (last id) / RequestRefused | | 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused | | 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | | | 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused | @@ -134,7 +134,12 @@ over its own link to another server. | 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList | | 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | | | 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused | -| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`) and `JsonData` str | | +| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int and `JsonData` str | | + +**Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to +`#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is +stamped by the server it's pushed to, when the push arrives (its clock, not +the client's), and keeps that time on every server it's replicated to. ## Rules @@ -204,7 +209,8 @@ PushMessage(t, json) AllowWrite, t in PushTopics ("" = own topic), at most #BakaShrot_MaxMessageSize. JSON or not: stored as is, SQLite flags it in is_json -> stored under t and the authenticated node with the - next message id -> MessagePushed(id) + next message id, stamped with now (pushed_at) + -> MessagePushed(id) GetLatestMessage(t, n) AllowRead, t in ReadTopics -> LatestMessage GetMessages(t, n, after, AllowRead, t in ReadTopics -> Messages: those above limit) after, in id order, at most limit, fewer once they @@ -253,7 +259,7 @@ S -> P SyncState every name S takes from P (its AcceptTopics and yet): P -> S ReplicateMessages the topic and node names, the next missing messages of that pair, in id order, with their original - message ids: up to PeerBatchSize of them, cut short + message ids and pushed_at: up to PeerBatchSize of them, cut short at about 64 KB (a bigger message goes alone) S: resolves the names to its own ids, adds the ones a wildcard took, refuses what it doesn't take (only if its config changed since @@ -279,6 +285,13 @@ S -> P MessagePushed(id) the batch stored in one transaction with or ReplicateMessages is refused with `Only peers can replicate`. - **Unexpected packets:** a packet on a link outside a check-in drops the link. +- **Retention:** each server deletes a topic's messages past its own + `[BakaShrot.Retention]` max age (`Server/Storage/Retention.pbi`), by their + pushed_at. The sync state comes from `node_heads`, which deleting leaves + alone: a server still says it has what it deleted, so peers don't send it + again. What a peer sends already past this server's max age isn't + stored, but counts as received the same way (still acknowledged). A + peer that links later only gets what the others still have. ## Code conventions diff --git a/Design/Release.md b/Design/Release.md index 73a6c9d..578bfd7 100644 --- a/Design/Release.md +++ b/Design/Release.md @@ -210,7 +210,7 @@ Notes for when the builds move to a pipeline. - `Build.ps1` ends by running the server, which waits on its console: needs a `-NoRun` switch. It also writes private keys into `Build\`, which must never be published as an artifact. - - The tests use fixed ports (12399 for the release, 12401-12407 for + - The tests use fixed ports (12399 for the release, 12401-12409 for `Tests/`): parallel jobs on one runner collide, make them parameters or pick free ones. - One entry point that runs every test (`Tests/*.ps1`, the handshake diff --git a/Interactors/Python/bakashrot.py b/Interactors/Python/bakashrot.py index 2bfaf7d..9fc533f 100644 --- a/Interactors/Python/bakashrot.py +++ b/Interactors/Python/bakashrot.py @@ -39,6 +39,7 @@ import os import threading import time from dataclasses import dataclass, field +from datetime import datetime, timezone from typing import Any, Iterator, Optional, Union __all__ = [ @@ -73,7 +74,9 @@ class ConnectionLostError(BakaShrotError): @dataclass(frozen=True) class Message: """A stored message. data is as stored: JSON or not (the server's - is_json column tells which, json() parses it).""" + is_json column tells which, json() parses it). pushed_at: when it was + pushed, to whichever server it was pushed to, in milliseconds since + 1970-01-01 UTC (pushed is the same as a datetime).""" id: int topic: str @@ -81,11 +84,17 @@ class Message: topic_id: int node_id: int data: str + pushed_at: int = 0 def json(self) -> Any: """The data parsed as JSON, raises ValueError if it isn't.""" return json.loads(self.data) + @property + def pushed(self) -> datetime: + """When it was pushed, as an aware datetime in UTC.""" + return datetime.fromtimestamp(self.pushed_at / 1000, tz=timezone.utc) + @dataclass(frozen=True) class MessagesPage: @@ -181,6 +190,7 @@ class _Dll: "BakaShrot_SelectMessage": (I, [L]), "BakaShrot_HasMoreMessages": (I, []), "BakaShrot_GetMessageId": (Q, []), + "BakaShrot_GetMessagePushedAt": (Q, []), "BakaShrot_GetMessageTopicId": (L, []), "BakaShrot_GetMessageNodeId": (L, []), "BakaShrot_GetMessageTopicA": (I, [S, I]), @@ -334,7 +344,8 @@ class Client: def _current(self) -> Message: dll = self._dll return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), - dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA)) + dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA), + dll.GetMessagePushedAt()) def latest(self, topic: Ref, node: Ref) -> Optional[Message]: """The latest message of topic/node, None if there's none yet.""" diff --git a/Interactors/Python/check_bakashrot.py b/Interactors/Python/check_bakashrot.py index c2d2759..43e0d72 100644 --- a/Interactors/Python/check_bakashrot.py +++ b/Interactors/Python/check_bakashrot.py @@ -57,6 +57,12 @@ with kitchen: latest = kitchen.latest("logs", "kitchen") check("latest(): #250", latest is not None and latest.id == 250 and latest.json() == {"i": 250}, latest) + now_ms = int(time.time() * 1000) + check("latest().pushed_at: just now, UTC ms", latest is not None and now_ms - 60000 < latest.pushed_at <= now_ms + 1000, + f"{latest.pushed_at if latest else None} vs {now_ms}") + check("latest().pushed: the same, an aware datetime in UTC", + latest is not None and latest.pushed.tzinfo is not None and latest.pushed.utcoffset().total_seconds() == 0 + and int(latest.pushed.timestamp() * 1000) == latest.pushed_at, latest.pushed if latest else None) topic_id, topic_name = kitchen.resolve_topic("logs") node_id, node_name = kitchen.resolve_node("kitchen") @@ -70,6 +76,9 @@ with kitchen: first = page.messages[0] check("A message's fields", (first.topic, first.node, first.topic_id, first.node_id, first.data, first.json()) == ("logs", "kitchen", 1, 5, '{"i":1}', {"i": 1}), first) + stamps = [m.pushed_at for m in page] + check("Each message of a page has its pushed_at, in push order", all(stamps) and stamps == sorted(stamps), + f"{stamps[0]} .. {stamps[-1]}") page = kitchen.get_messages("logs", "kitchen", after=200, limit=100) check("Last page: 201-250, no more", [m.id for m in page] == list(range(201, 251)) and not page.more, diff --git a/Notes.md b/Notes.md index 7376d72..c1c4ccf 100644 --- a/Notes.md +++ b/Notes.md @@ -32,6 +32,9 @@ Where things stand and what's next, as of 2026-11-08. The detailed docs are in `ReadTopics`. Topics and nodes by name or id, see below. - Links to its peers, retries when that fails, and replicates the missing messages in batches (`PeerBatchSize`). + - Stamps every push with the time it arrived (`pushed_at`, UTC ms), which + replication carries as is, and deletes each topic's messages past its + max age (`[BakaShrot.Retention]`, per server). - One thread per client and per peer, each with its own SQLite connection. - The root thread can stop every worker (restart, vacuum). - **Client:** a DLL with A/W string exports, PureBasic prototypes in @@ -249,6 +252,94 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs. - **Left:** see `Design/Cryptography.md`'s "What's NOT done": per-message signatures for replication, keys in plain-text inis, rotation. +## State on 2026-11-08: good, mid, bad + +As judged for the threat model below (internal tool, trusted machines). + +**Good** +- The core works and is tested end to end: push, latest, runs of messages + and `--follow`, names and ids, filters and wildcards, raw read-only SQL, + per-client permissions; five suites, two `.pb` tests, the release's smoke + test (PB 6.40 C), all passing. +- Fast: ~40,800 msg/s pushed across 4 servers (10 nodes each, PB 5.73), + fully replicated; ~9,000 msg/s from one Python connection. +- Replication by name, each server with its own ids; restart catch-up is + designed in (nothing it needs lives only in memory). +- Security beyond what's needed here: encrypted connections, both ends + proven, peer links verified. +- Data: 16 MB messages, anything stored (`is_json`), errors of queries + surfaced; pushed times; retention per topic and server. +- Clients: DLL for any language, CLI tools, dependency-free Python. +- Packaging (runtime included) and docs that match the code. + +**Mid** +- Replication: gaps aren't detected; two servers writing the same + topic/node pair can drift (fine with one writer per pair, a rule to + state); the sync state must fit in one packet. +- `synchronous = NORMAL`: a power loss can lose the last commits (a killed + process loses nothing committed). Often fine internally, to decide. +- Client: one connection per process, `--follow` polls, no reconnect. +- Tests run by hand, on fixed ports, no runner, no CI. +- Linux untested; keys in plain-text inis (file permissions are enough + here). + +**Bad** +- The server can't run unattended: it needs a console, stops at once + without one, can't be stopped cleanly from a script, so no service. The + main blocker for deploying it. +- Never run from the extracted zip, on a clean Windows, nor with two + release servers, nor restarted after a kill: designed to work, unchecked. +- Nothing committed: everything since the initial commit (the deleted + `Core/` included) lives only in the working tree. + +Suggested order: commit; a stop file and running as a service; smoke-test +items 1-3 (`Design/Release.md`); a single test runner, then CI. + +## Done: pushed times, retention (2026-11-08) + +- **`pushed_at`:** every message has the time it was pushed, in + milliseconds since 1970 UTC, set by the server it was pushed to when the + push arrived (its clock), and kept as is on every server it's replicated + to (`ReplicateMessages` carries it). Clients get it in `LatestMessage` + and `Messages`: `BakaShrot_GetMessagePushedAt()` in the DLL, + `Message.pushed_at` / `.pushed` (a UTC datetime) in Python, + `GetMessages --time`, and `GetLatestMessage` shows it. In SQL: + `data.pushed_at`, and `pushed_at` / `pushed_utc` (text) in the + `messages` view. +- **Upgrade:** a database from before gets the column, every message + stamped with the time of the upgrade (their real time is unknown), so a + max age counts from then for them (schema v6, `db_schema_v6.dbml`). +- **Protocol:** folded into version 3 (not released yet, like the + encryption); a v3 build from before today can't talk to this one. +- **Retention:** `[BakaShrot.Retention]` in each server's config, + `topic = age` by name or id, pattern (`sensors.* = 12h`), or `*`; ages + like `30d`, `1d12h`, `forever`. Every `RetentionInterval` seconds + (`[BakaShrot.Server]`, default 60), `Server/Storage/Retention.pbi` + deletes what was pushed before now minus the age, 5000 at a time through + the writer, so pushes go on. Each server applies its own: a peer keeps + its copies by its own rules. An age without a unit refuses to start. +- **What deleting keeps:** `node_heads`, so ids never go back (the writer's + next id now comes from it), and peers aren't sent again what a server + deleted. +- **Skipped on arrival:** what a peer replicates already past this + server's max age for the topic isn't stored, but its head still goes up + to it, so the peer doesn't send it again (`InsertReplicatedMessages()`'s + `SkipBeforeMs`). Each peer's thread has its own copy of the rules. The file doesn't shrink, SQLite reuses the space; `vacuum` + gives it back. +- **Cost:** a column and a `(topic_id, pushed_at)` index entry per message; + no slowdown measured (40,817 msg/s for 4 servers, PB 5.73, + `Tests/Bench/Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`). +- **Tested:** `Tests/Retention-Test.ps1` (52 checks, ports 12408-12409): + the upgrade of an old database (needs Python), stamps within the push's + time, `--time`, the same `pushed_at` on both servers, deleting by name, + pattern and `*` on one server only, ids going on after it, nothing sent + again, skipped on arrival (B started late: its head goes up, nothing + stored, nothing sent again), the bad age refused. Python checks + `pushed_at` too. +- **By topic only, on purpose:** no per-node max age. +- **Removed:** the `archives` table, a leftover of the first schemas that + nothing ever used, dropped from existing databases at start. + ## Threat model (2026-11-08) BakaShrot is an **internal tool, on trusted machines and a trusted @@ -287,7 +378,7 @@ network**, not exposed to the internet. So: writer; document that as the rule. (`Design/ReplicationIssues.md` #1) 5. **Gaps in a pair's ids aren't detected** on replication. (`Design/ReplicationIssues.md` #5) -6. **No single test runner**, and fixed ports (12399, 12401-12407): every +6. **No single test runner**, and fixed ports (12399, 12401-12409): every `Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI. (`Design/Release.md`, "For CI/CD") 7. **Is `DatabaseError()` per thread?** Messages could land in the wrong diff --git a/Server/Config/Config.pbi b/Server/Config/Config.pbi index db428db..e23169b 100644 --- a/Server/Config/Config.pbi +++ b/Server/Config/Config.pbi @@ -9,6 +9,9 @@ ; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server ; [BakaShrot.Topics] -> topic names, "name = id" lines ; [BakaShrot.Nodes] -> node names, "name = id" lines +; [BakaShrot.Retention] -> how long each topic's messages are kept +; here, "topic = max age" lines, see +; BakaShrot_RetentionRule ; [BakaShrot.Peer.] -> one BakaShrot_CoreConfig\Peers() entry per ; section. ; [BakaShrot.Client.] -> one BakaShrot_CoreConfig\Clients() entry per @@ -157,6 +160,37 @@ Structure BakaShrot_ClientConfig EndStructure +; One line of [BakaShrot.Retention]: messages of the topics it matches may +; be deleted from this server once they were pushed MaxAgeMs ago (see +; Server/Storage/Retention.pbi). Only this server's: each server keeps its +; own, a peer keeps what it was sent as long as its own rules say. +; logs = 30d one topic, by name (known here or not) or id +; sensors.* = 12h a pattern, matching names (Commons/Networking/Names.pbi) +; * = 365d every other topic +; Ages: numbers with a unit, s m h d w, added up ("1d12h"); "forever" (or +; 0) keeps them. A topic takes its id's line, else its name's, else the +; first pattern matching it, in the file's order, else "*"'s. Without any +; line, messages are kept forever. +Enumeration BakaShrot_RetentionKinds + #BakaShrot_Retention_Id = 1 + #BakaShrot_Retention_Name = 2 + #BakaShrot_Retention_Pattern = 3 + #BakaShrot_Retention_Default = 4 +EndEnumeration + +Structure BakaShrot_RetentionRule + Kind.i + ; As written: the topic's name or id, the pattern, or "*". + Ref.s + ; For #BakaShrot_Retention_Id. + TopicId.i + ; 0: kept forever. + MaxAgeMs.q + ; The age as written, for SaveConfig() and the logs. + AgeText.s +EndStructure + + ; Ini Section: [BakaShrot.Server] Structure BakaShrot_ServerConfig @@ -190,6 +224,10 @@ Structure BakaShrot_ServerConfig ; A batch is also cut short to fit in one packet (64 KB). PeerBatchSize.i + ; Seconds between two passes deleting the messages past their topic's + ; max age ([BakaShrot.Retention]). Default 60. + RetentionInterval.i + EndStructure @@ -224,6 +262,9 @@ Structure BakaShrot_CoreConfig Map UsedTopicIds.i() Map UsedNodeIds.i() + ; [BakaShrot.Retention], in the file's order. + List Retention.BakaShrot_RetentionRule() + ; One [BakaShrot.Peer.] entry per map key. Map Peers.BakaShrot_PeerConfig() @@ -241,6 +282,7 @@ Macro Ptr_BakaShrot_CoreConfig : i : EndMacro #BakaShrot_Config_DefaultPeerRetryDelay = 10 #BakaShrot_Config_DefaultPeerSyncInterval = 5 #BakaShrot_Config_DefaultPeerBatchSize = 100 +#BakaShrot_Config_DefaultRetentionInterval = 60 ; What ReadPreferenceString() returns for a missing key, to tell it from an ; empty one: an empty PushTopics allows nothing, a missing one the default. @@ -333,6 +375,145 @@ Procedure.i ResolveConfigNode(*Config.BakaShrot_CoreConfig, Ref.s) EndProcedure +; An age as [BakaShrot.Retention] writes it ("30d", "1d12h", "forever") in +; milliseconds, 0 for forever, -1 if it isn't one. +Procedure.q ParseRetentionAge(Text.s) + Protected i.i, c.s, Digits.s, Total.q, Unit.q, Seen.i + + Text = LCase(Trim(Text)) + If Text = "forever" Or Text = "0" + ProcedureReturn 0 + EndIf + If Text = "" + ProcedureReturn -1 + EndIf + + For i = 1 To Len(Text) + c = Mid(Text, i, 1) + If c >= "0" And c <= "9" + Digits + c + If Len(Digits) > 9 + ProcedureReturn -1 + EndIf + Continue + EndIf + Select c + Case "s" : Unit = 1000 + Case "m" : Unit = 60 * 1000 + Case "h" : Unit = 3600 * 1000 + Case "d" : Unit = 86400 * 1000 + Case "w" : Unit = 7 * 86400 * 1000 + Default : ProcedureReturn -1 + EndSelect + ; A unit needs its number: "d" or "1dd" isn't an age. + If Digits = "" + ProcedureReturn -1 + EndIf + Total + Val(Digits) * Unit + Digits = "" + Seen = #True + Next + + ; A number without a unit: seconds or days? Refused rather than guessed. + If Digits <> "" Or Not Seen + ProcedureReturn -1 + EndIf + ProcedureReturn Total +EndProcedure + + +; Reads [BakaShrot.Retention] into *Config\Retention(). +; Returns #False on an invalid line, with the reason in BakaShrot_ConfigError. +Procedure.i ParseRetentionSection(*Config.BakaShrot_CoreConfig) + Protected Ref.s, Value.s, MaxAge.q, Id.i + + If Not PreferenceGroup("BakaShrot.Retention") + ProcedureReturn #True + EndIf + + If ExaminePreferenceKeys() + While NextPreferenceKey() + Ref = Trim(PreferenceKeyName()) + Value = Trim(PreferenceKeyValue()) + MaxAge = ParseRetentionAge(Value) + If MaxAge < 0 + BakaShrot_ConfigError = "[BakaShrot.Retention] " + Ref + " = '" + Value + "' isn't an age: numbers with a unit (s m h d w), like 30d or 1d12h, or 'forever'" + ProcedureReturn #False + EndIf + + AddElement(*Config\Retention()) + *Config\Retention()\Ref = Ref + *Config\Retention()\MaxAgeMs = MaxAge + *Config\Retention()\AgeText = Value + *Config\Retention()\TopicId = -1 + Id = BakaShrot_RefToId(Ref) + If Ref = "*" + *Config\Retention()\Kind = #BakaShrot_Retention_Default + ElseIf Id >= 0 + *Config\Retention()\Kind = #BakaShrot_Retention_Id + *Config\Retention()\TopicId = Id + ElseIf BakaShrot_IsValidName(Ref) + ; A name this config doesn't have may still come from a peer. + *Config\Retention()\Kind = #BakaShrot_Retention_Name + ElseIf BakaShrot_IsValidPattern(Ref) + *Config\Retention()\Kind = #BakaShrot_Retention_Pattern + Else + BakaShrot_ConfigError = "[BakaShrot.Retention] '" + Ref + "' isn't a topic name, id, pattern or *" + ProcedureReturn #False + EndIf + Wend + EndIf + + ; Two lines for the same topic: the second would silently lose. + Protected NewMap Seen.i() + ForEach *Config\Retention() + Ref = LCase(*Config\Retention()\Ref) + If FindMapElement(Seen(), Ref) + BakaShrot_ConfigError = "[BakaShrot.Retention] '" + *Config\Retention()\Ref + "' is given twice" + ProcedureReturn #False + EndIf + Seen(Ref) = #True + Next + + ProcedureReturn #True +EndProcedure + + +; How long a topic's messages are kept by *Config's [BakaShrot.Retention], +; in ms, 0 for forever. Name is "" for an unnamed topic. +Procedure.q RetentionMaxAgeMs(List Rules.BakaShrot_RetentionRule(), TopicId.i, Name.s) + Protected *Default.BakaShrot_RetentionRule, *Named.BakaShrot_RetentionRule, *Matched.BakaShrot_RetentionRule + + ForEach Rules() + Select Rules()\Kind + Case #BakaShrot_Retention_Id + If Rules()\TopicId = TopicId + ProcedureReturn Rules()\MaxAgeMs + EndIf + Case #BakaShrot_Retention_Name + If Not *Named And Name <> "" And LCase(Rules()\Ref) = LCase(Name) + *Named = @Rules() + EndIf + Case #BakaShrot_Retention_Pattern + If Not *Matched And Name <> "" And BakaShrot_GlobMatch(Rules()\Ref, Name) + *Matched = @Rules() + EndIf + Case #BakaShrot_Retention_Default + *Default = @Rules() + EndSelect + Next + + If *Named + ProcedureReturn *Named\MaxAgeMs + ElseIf *Matched + ProcedureReturn *Matched\MaxAgeMs + ElseIf *Default + ProcedureReturn *Default\MaxAgeMs + EndIf + ProcedureReturn 0 +EndProcedure + + ; Reads a "name = id" section into Ids() (LCase(name) -> id) and Names() ; (Str(id) -> name). Kind is "topic" or "node", for the errors. ; Returns #False on an invalid name or id, or one given twice. @@ -649,11 +830,20 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) *Config\Server\PeerRetryDelay = ReadPreferenceLong("PeerRetryDelay", #BakaShrot_Config_DefaultPeerRetryDelay) *Config\Server\PeerSyncInterval = ReadPreferenceLong("PeerSyncInterval", #BakaShrot_Config_DefaultPeerSyncInterval) *Config\Server\PeerBatchSize = ReadPreferenceLong("PeerBatchSize", #BakaShrot_Config_DefaultPeerBatchSize) + *Config\Server\RetentionInterval = ReadPreferenceLong("RetentionInterval", #BakaShrot_Config_DefaultRetentionInterval) + If *Config\Server\RetentionInterval < 1 + BakaShrot_ConfigError = "[BakaShrot.Server] RetentionInterval must be 1 second or more" + Goto LoadFailed + EndIf *Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "") If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics") Goto LoadFailed EndIf + If Not ParseRetentionSection(*Config) + Goto LoadFailed + EndIf + ; Every [BakaShrot.Peer.] and [BakaShrot.Client.], found ; dynamically so adding one never needs a second "list of names" kept in ; sync by hand. Read once the walk is done: PreferenceGroup() inside it @@ -806,6 +996,7 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) WritePreferenceLong("PeerRetryDelay", *Config\Server\PeerRetryDelay) WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval) WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize) + WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval) PreferenceGroup("BakaShrot.Topics") ForEach *Config\TopicNames() @@ -817,6 +1008,13 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) WritePreferenceString(*Config\NodeNames(), MapKey(*Config\NodeNames())) Next + If ListSize(*Config\Retention()) + PreferenceGroup("BakaShrot.Retention") + ForEach *Config\Retention() + WritePreferenceString(*Config\Retention()\Ref, *Config\Retention()\AgeText) + Next + EndIf + ForEach *Config\Peers() PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers())) WritePreferenceString("Host", *Config\Peers()\Host) diff --git a/Server/Config/schema.ini b/Server/Config/schema.ini index 16f041f..be86091 100644 --- a/Server/Config/schema.ini +++ b/Server/Config/schema.ini @@ -54,6 +54,23 @@ Node = ; kitchen = 2 +[BakaShrot.Retention] +; How long this server keeps each topic's messages, counted from when they +; were pushed (to whichever server they were first pushed to). Past that, +; they may be deleted: checked every RetentionInterval seconds. Each server +; has its own: a peer keeps its copies as long as its own config says. +; One line per topic: name or id = age, a pattern (sensors.*), or * for +; every topic not listed. A topic takes its id's line, else its name's, +; else the first pattern matching it, else *'s. +; Ages: numbers with a unit, s m h d w, added up (1d12h), or forever. +; Without any line, everything is kept forever. +; Deleting doesn't shrink the file, SQLite reuses the space for new +; messages; the "vacuum" console command gives it back to the disk. +; logs = 30d +; sensors.* = 12h +; * = 365d + + [BakaShrot.Server] ; IPV4 that the server will be bound to. Host = @@ -84,6 +101,10 @@ PeerSyncInterval = 5 ; A batch is also cut short at about 64 KB, a bigger message goes alone. PeerBatchSize = 100 +; Seconds between two passes deleting the messages past their topic's age +; ([BakaShrot.Retention] above). Only runs if a topic has one. +RetentionInterval = 60 + ; One [BakaShrot.Peer.] section per peer this node talks to. ; is only a key for this file; it is never sent on the wire. diff --git a/Server/Networking/Networking.pbi b/Server/Networking/Networking.pbi index 804e2e6..d73f24b 100644 --- a/Server/Networking/Networking.pbi +++ b/Server/Networking/Networking.pbi @@ -122,6 +122,11 @@ Structure BakaShrot_NetClient AcceptTopics.BakaShrot_NameSet AcceptNodes.BakaShrot_NameSet + ; [BakaShrot.Retention], for peers only: what they send that's already + ; past its max age isn't stored. A copy, lists aren't safe to walk from + ; several threads. + List Retention.BakaShrot_RetentionRule() + ; This thread's own database connection, opened once authenticated. DbId.i EndStructure @@ -259,6 +264,7 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) If *Client\PeerName <> "" And FindMapElement(*Server\Config\Peers(), *Client\PeerName) CopyStructure(@*Server\Config\Peers()\AcceptTopics, @*Client\AcceptTopics, BakaShrot_NameSet) CopyStructure(@*Server\Config\Peers()\AcceptNodes, @*Client\AcceptNodes, BakaShrot_NameSet) + CopyList(*Server\Config\Retention(), *Client\Retention()) EndIf UnlockMutex(*Server\Mutex) If ClientName = "" @@ -543,6 +549,7 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie Latest\TopicName = BakaShrot_Names_TopicRef(TopicId) Latest\NodeName = BakaShrot_Names_NodeRef(NodeId) Latest\MessageId = Message\MessageId + Latest\PushedAt = Message\PushedAt Latest\JsonData = Message\JsonData *Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize) If Not *Answer @@ -627,6 +634,7 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, * AddElement(Answer\Messages()) Answer\Messages()\MessageId = Messages()\MessageId + Answer\Messages()\PushedAt = Messages()\PushedAt Answer\Messages()\JsonData = Messages()\JsonData Next ClearList(Messages()) @@ -907,11 +915,14 @@ EndProcedure ; replicates, unless a wildcard there takes a name this server doesn't have, ; which is then added, see Storage/Names.pbi. The sync state tells the peer ; what's taken here, so it doesn't send the rest in the first place. +; Messages already past the topic's max age here ([BakaShrot.Retention]) are +; skipped, but acknowledged like the others. ; Returns #False if the client must be aborted. Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) Protected *View.MsgPackData, *Batch.BakaShrot_ReplicateMessages Protected Pushed.BakaShrot_MessagePushed Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, LastMessageId.q, IsStored.i, StoreError.String + Protected MaxAge.q, SkipBefore.q, Skipped.Integer Protected *Answer, AnswerSize.Integer, Sent.i *Batch = 0 @@ -960,8 +971,15 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored") EndIf - IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError) + MaxAge = RetentionMaxAgeMs(*Client\Retention(), TopicId, TopicRef) + If MaxAge > 0 + SkipBefore = BakaShrot_NowUtcMs() - MaxAge + EndIf + IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped) FreeStructure(*Batch) + If #BakaShrot_Net_LogRequests And Skipped\i > 0 + PrintN("[Net] Skipped " + Str(Skipped\i) + " messages of " + TopicRef + ":" + NodeRef + " from peer '" + *Client\PeerName + "', past their max age here") + EndIf If Not IsStored PrintN("[Net] Failed to store messages from peer '" + *Client\PeerName + "': " + StoreError\s) ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored") diff --git a/Server/Networking/Peers.pbi b/Server/Networking/Peers.pbi index 214d65d..831b1c9 100644 --- a/Server/Networking/Peers.pbi +++ b/Server/Networking/Peers.pbi @@ -239,6 +239,8 @@ Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i, AddElement(Batch\Messages()) Batch\Messages()\MessageId = Messages()\MessageId + ; As stored: when it was pushed to its origin, whichever server that was. + Batch\Messages()\PushedAt = Messages()\PushedAt Batch\Messages()\JsonData = Messages()\JsonData Next diff --git a/Server/Root.pbi b/Server/Root.pbi index 9336113..ba5b8ea 100644 --- a/Server/Root.pbi +++ b/Server/Root.pbi @@ -28,6 +28,7 @@ XIncludeFile "Config/Config.pbi" XIncludeFile "Storage/Storage.pbi" XIncludeFile "Storage/Names.pbi" +XIncludeFile "Storage/Retention.pbi" XIncludeFile "Networking/Networking.pbi" XIncludeFile "Networking/Peers.pbi" @@ -121,9 +122,17 @@ Procedure.i BakaShrot_Root_StartWorkers(*Root.BakaShrot_Root) ProcedureReturn #False EndIf + ; Deletes the messages past their topic's max age, see Storage/Retention.pbi. + If Not StartStorageRetention(*Config) + PrintN("[Root] Failed to start the retention thread") + CloseStorageWriter() + ProcedureReturn #False + EndIf + *Root\Server = BakaShrot_NetServer_Start(*Config\Server\Host, *Config\Server\Port, *Config) If Not *Root\Server PrintN("[Root] Failed to listen on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'") + StopStorageRetention() CloseStorageWriter() ProcedureReturn #False EndIf @@ -134,6 +143,7 @@ Procedure.i BakaShrot_Root_StartWorkers(*Root.BakaShrot_Root) PrintN("[Root] Failed to start the peer links, are [BakaShrot] PrivateKey and every peer's PublicKey valid?") BakaShrot_NetServer_Stop(*Root\Server) *Root\Server = 0 + StopStorageRetention() CloseStorageWriter() ProcedureReturn #False EndIf @@ -158,6 +168,8 @@ Procedure BakaShrot_Root_StopWorkers(*Root.BakaShrot_Root) *Root\Server = 0 EndIf + StopStorageRetention() + ; Nothing writes anymore. Checkpoints the WAL into the database file. CloseStorageWriter() diff --git a/Server/Storage/Retention.pbi b/Server/Storage/Retention.pbi new file mode 100644 index 0000000..e740605 --- /dev/null +++ b/Server/Storage/Retention.pbi @@ -0,0 +1,173 @@ +; ============================================================================ +; BakaShrot Storage Retention +; +; Deletes the messages past their topic's max age, so a server's database +; stops growing: [BakaShrot.Retention] in its config, see +; BakaShrot_RetentionRule in Server/Config/Config.pbi. +; +; A thread, started with the workers (StartStorageRetention(), see +; Server/Root.pbi), runs a pass right away then every [BakaShrot.Server] +; RetentionInterval seconds: +; - every topic of the database (node_heads), with its name (topics); +; - its max age from the rules; kept forever (0) is skipped; +; - deletes its messages pushed (pushed_at) before now minus that age, +; #BakaShrot_Retention_BatchSize at a time through the writer +; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between +; the batches. +; +; Messages "may be" deleted past their max age: up to RetentionInterval +; later. Those a peer replicates here already past it aren't stored at all +; (InsertReplicatedMessages() in Writer.pbi), only counted as received. pushed_at is the time the message was pushed to its origin, kept as +; is by replication, so a server deletes a replicated message by when it +; was first pushed, not when it got it. +; +; What deleting doesn't change: +; - node_heads: a pair's head stays its highest id ever. The next push +; still gets the next id, and the sync state still tells peers this +; server had those messages: they aren't sent again. +; - The file's size: SQLite reuses the freed pages for new messages, so +; it stops growing once deletions keep up with pushes. VACUUM (the +; "vacuum" console command) gives the space back to the disk. +; ============================================================================ + +; Most messages deleted in one statement, under the write mutex: a few ms. +#BakaShrot_Retention_BatchSize = 5000 + + +Structure BakaShrot_RetentionTopic + TopicId.i + Name.s +EndStructure + +Structure BakaShrot_RetentionState + ThreadId.i + StopRequested.i + IntervalMs.i + DatabasePath.s + List Rules.BakaShrot_RetentionRule() +EndStructure + +Global BakaShrot_Retention.BakaShrot_RetentionState + + +; Ms (since 1970 UTC) as "2026-11-08T14:03:59Z", for the logs. +Procedure.s BakaShrot_Retention_FormatUtc(Ms.q) + ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ssZ", Ms / 1000) +EndProcedure + + +; Deletes what's past its max age in every topic. DbId is the thread's own +; connection, only read from (the deletes go through the writer). +; Returns how many messages were deleted. +Procedure.q BakaShrot_Retention_Pass(DbId.i) + Protected NewList Topics.BakaShrot_RetentionTopic() + Protected MaxAge.q, Before.q, Deleted.i, TopicDeleted.q, Total.q, Error.String + + If Not DatabaseQuery(DbId, "SELECT DISTINCT h.topic_id, COALESCE(t.name, '') FROM node_heads h LEFT JOIN topics t ON t.topic_id = h.topic_id") + PrintN("[Storage] Retention: can't list the topics: " + DatabaseError()) + ProcedureReturn 0 + EndIf + While NextDatabaseRow(DbId) + AddElement(Topics()) + Topics()\TopicId = GetDatabaseLong(DbId, 0) + Topics()\Name = GetDatabaseString(DbId, 1) + Wend + FinishDatabaseQuery(DbId) + + ForEach Topics() + MaxAge = RetentionMaxAgeMs(BakaShrot_Retention\Rules(), Topics()\TopicId, Topics()\Name) + If MaxAge <= 0 + Continue + EndIf + + Before = BakaShrot_NowUtcMs() - MaxAge + TopicDeleted = 0 + Repeat + Deleted = DeleteStorageMessagesBefore(Topics()\TopicId, Before, #BakaShrot_Retention_BatchSize, @Error) + If Deleted < 0 + PrintN("[Storage] Retention: failed to delete from topic " + Str(Topics()\TopicId) + ": " + Error\s) + Break + EndIf + TopicDeleted + Deleted + Until Deleted < #BakaShrot_Retention_BatchSize Or BakaShrot_Retention\StopRequested + + If TopicDeleted > 0 + If Topics()\Name <> "" + PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic '" + Topics()\Name + "' pushed before " + BakaShrot_Retention_FormatUtc(Before)) + Else + PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic " + Str(Topics()\TopicId) + " pushed before " + BakaShrot_Retention_FormatUtc(Before)) + EndIf + EndIf + Total + TopicDeleted + + If BakaShrot_Retention\StopRequested + Break + EndIf + Next + + ProcedureReturn Total +EndProcedure + + +Procedure BakaShrot_Retention_Thread(Unused.i) + Protected DbId.i, LastPass.i + + DbId = OpenStorageDatabase(BakaShrot_Retention\DatabasePath) + If Not DbId + PrintN("[Storage] Retention: can't open the database, nothing will be deleted: " + DatabaseError()) + ProcedureReturn + EndIf + + BakaShrot_Retention_Pass(DbId) + LastPass = ElapsedMilliseconds() + While Not BakaShrot_Retention\StopRequested + Delay(100) + If ElapsedMilliseconds() - LastPass >= BakaShrot_Retention\IntervalMs + BakaShrot_Retention_Pass(DbId) + LastPass = ElapsedMilliseconds() + EndIf + Wend + + CloseDatabase(DbId) +EndProcedure + + +; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, once +; the writer is open. Nothing to do (no thread) if every topic is kept +; forever. Returns #False if the thread can't start. +Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig) + Protected Deletes.i + + With BakaShrot_Retention + ClearList(\Rules()) + CopyList(*Config\Retention(), \Rules()) + ForEach \Rules() + If \Rules()\MaxAgeMs > 0 + Deletes = #True + PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s") + EndIf + Next + If Not Deletes + ProcedureReturn #True + EndIf + + \DatabasePath = *Config\Server\DatabasePath + \IntervalMs = *Config\Server\RetentionInterval * 1000 + \StopRequested = #False + \ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0) + ProcedureReturn Bool(\ThreadId) + EndWith +EndProcedure + + +; Stops it, before the writer closes. Waits for a pass under way to end its +; current batch. +Procedure StopStorageRetention() + With BakaShrot_Retention + If \ThreadId + \StopRequested = #True + WaitThread(\ThreadId) + \ThreadId = 0 + EndIf + EndWith +EndProcedure diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi index 5fcf804..7d53245 100644 --- a/Server/Storage/Storage.pbi +++ b/Server/Storage/Storage.pbi @@ -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_v5.dbml in this same folder. +; Schema: see db_schema_v6.dbml in this same folder. ; ; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one ; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official @@ -36,13 +36,38 @@ CompilerElse CompilerEndIf -; One row of the "data" table (see db_schema_v5.dbml). +; One row of the "data" table (see db_schema_v6.dbml). +; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi). Structure BakaShrot_Message MessageId.q + PushedAt.q JsonData.s EndStructure +CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + ImportC "" + BakaShrot_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday" + EndImport +CompilerEndIf + +; Now, in milliseconds since 1970-01-01 00:00:00 UTC: what a pushed message +; is stamped with (pushed_at). +Procedure.q BakaShrot_NowUtcMs() + CompilerIf #PB_Compiler_OS = #PB_OS_Windows + ; 100 ns intervals since 1601-01-01 UTC. + Protected FileTime.q + GetSystemTimeAsFileTime_(@FileTime) + ProcedureReturn (FileTime - 116444736000000000) / 10000 + CompilerElse + ; Untested: Linux isn't built yet. struct timeval, 64-bit. + Protected Dim TimeVal.q(1) + BakaShrot_GetTimeOfDay(@TimeVal(0), 0) + ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000 + CompilerEndIf +EndProcedure + + ; How long a connection waits for another one's lock before a statement ; fails with "database is locked", in ms. #BakaShrot_Storage_BusyTimeout = 5000 @@ -165,7 +190,42 @@ Procedure.i MigrateStorageTopicIds(DbId.i) EndProcedure -; Creates the tables and indexes described by db_schema_v5.dbml, if they +; v5 -> v6: "data" got pushed_at. Adds it to a database made before, every +; message stamped with the time of the upgrade (their real one is unknown), +; in one transaction. Nothing to do on a new or already upgraded database. +Procedure.i MigrateStoragePushedAt(DbId.i) + Protected Has.i + + Has = StorageHasColumn(DbId, "data", "pushed_at") + If Has = -1 + ProcedureReturn #False + ElseIf Has + ProcedureReturn #True + EndIf + + If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "ALTER TABLE data ADD COLUMN pushed_at INTEGER NOT NULL DEFAULT 0") + DatabaseUpdate(DbId, "ROLLBACK") + ProcedureReturn #False + EndIf + ; Bound for the next statement run, so right before it. + SetDatabaseQuad(DbId, 0, BakaShrot_NowUtcMs()) + If Not DatabaseUpdate(DbId, "UPDATE data SET pushed_at = ?") + DatabaseUpdate(DbId, "ROLLBACK") + ProcedureReturn #False + EndIf + If Not DatabaseUpdate(DbId, "COMMIT") + DatabaseUpdate(DbId, "ROLLBACK") + ProcedureReturn #False + EndIf + + ProcedureReturn #True +EndProcedure + + +; Creates the tables and indexes described by db_schema_v6.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. @@ -190,13 +250,15 @@ Procedure.i SetupStorageDatabase(DbId.i) ProcedureReturn #False EndIf - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" + - "delete_by INTEGER NOT NULL, " + - "message_data TEXT NOT NULL)") + ; A leftover of the first schemas, never used: the retention deletes + ; instead (Retention.pbi). + If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS archives") ProcedureReturn #False EndIf ; is_json is set by SQLite on insert, and can't be written. + ; pushed_at: when it was pushed to its origin, ms since 1970 UTC, kept as + ; is when replicated. Last, like the ALTER TABLE below adds it. ; The UNIQUE constraint's index also serves (topic_id, node_id) lookups. If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" + "topic_id INTEGER NOT NULL, " + @@ -204,6 +266,7 @@ Procedure.i SetupStorageDatabase(DbId.i) "message_id INTEGER NOT NULL, " + "message_data TEXT NOT NULL, " + "is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, " + + "pushed_at INTEGER NOT NULL DEFAULT 0, " + "UNIQUE (topic_id, node_id, message_id))") ProcedureReturn #False EndIf @@ -218,6 +281,18 @@ Procedure.i SetupStorageDatabase(DbId.i) ProcedureReturn #False EndIf + ; A database from before pushed_at: its messages get the time of this + ; upgrade, so a topic's max age (Server/Storage/Retention.pbi) counts + ; from now for them instead of deleting them all at once. + If Not MigrateStoragePushedAt(DbId) + ProcedureReturn #False + EndIf + + ; What the retention deletes by: a topic's messages pushed before a time. + If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_topic_pushed_at ON data (topic_id, pushed_at)") + ProcedureReturn #False + EndIf + ; Not used yet, but created now so the on-disk schema already matches ; db_schema_v1.dbml. If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" + @@ -238,7 +313,9 @@ Procedure.i SetupStorageDatabase(DbId.i) ; every insert, whoever does it. The sync state comes from it instead of ; a GROUP BY over every message (131 ms at 1.9M rows, on every check-in). ; Filled from "data" when it's created on an existing database. - ; !!! Nothing deletes from "data" yet: whatever does must update it too. + ; Deleting from "data" (the retention) leaves it alone, on purpose: a + ; pair's head stays its highest id ever, so the next push still gets the + ; id after it, and peers aren't sent again what was deleted here. If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'") ProcedureReturn #False EndIf @@ -294,9 +371,13 @@ Procedure.i SetupStorageDatabase(DbId.i) EndIf ; For queries by name: SELECT * FROM messages WHERE topic = 'logs' AND - ; node = 'kitchen' still goes through the indexes. - If Not DatabaseUpdate(DbId, "CREATE VIEW IF NOT EXISTS messages AS " + - "SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id " + + ; node = 'kitchen' still goes through the indexes. pushed_utc is + ; pushed_at as text, "2026-11-08T14:03:59.123Z". + ; Made again on every start, so an older one gets the newer columns. + If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS messages") Or + Not DatabaseUpdate(DbId, "CREATE VIEW messages AS " + + "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") ProcedureReturn #False EndIf @@ -305,14 +386,15 @@ Procedure.i SetupStorageDatabase(DbId.i) EndProcedure -; Inserts one JSON message into the "data" table. +; Inserts one JSON message into the "data" table, pushed now. Procedure.i Insert(DbId.i, TopicId.i, NodeId.i, MessageId.i, JsonData.s) SetDatabaseLong(DbId, 0, TopicId) SetDatabaseLong(DbId, 1, NodeId) SetDatabaseLong(DbId, 2, MessageId) SetDatabaseString(DbId, 3, JsonData) + SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs()) - ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)") + ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)") EndProcedure @@ -413,7 +495,7 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes SetDatabaseLong(DbId, 0, TopicId) SetDatabaseLong(DbId, 1, NodeId) - If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1") + If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1") ProcedureReturn #False EndIf @@ -421,6 +503,7 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes If Found *Message\MessageId = GetDatabaseQuad(DbId, 0) *Message\JsonData = GetDatabaseString(DbId, 1) + *Message\PushedAt = GetDatabaseQuad(DbId, 2) EndIf FinishDatabaseQuery(DbId) @@ -672,7 +755,7 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi SetDatabaseLong(DbId, 1, NodeId) SetDatabaseQuad(DbId, 2, AfterMessageId) SetDatabaseLong(DbId, 3, Limit + 1) - If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?") + If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?") ProcedureReturn #False EndIf @@ -684,6 +767,7 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi AddElement(Messages()) Messages()\MessageId = GetDatabaseQuad(DbId, 0) Messages()\JsonData = GetDatabaseString(DbId, 1) + Messages()\PushedAt = GetDatabaseQuad(DbId, 2) Chars + Len(Messages()\JsonData) Wend FinishDatabaseQuery(DbId) @@ -700,13 +784,15 @@ EndProcedure ; new one is dropped, even if it differs. See Design/ReplicationIssues.md. ; On its own connection: for tools writing while the server is stopped ; (BenchSeed). The server itself writes through Writer.pbi. +; PushedAt: when it was pushed to its origin, ms since 1970 UTC. ; Returns #False if the insert failed. -Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s) +Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q) SetDatabaseLong(DbId, 0, TopicId) SetDatabaseLong(DbId, 1, NodeId) SetDatabaseQuad(DbId, 2, MessageId) SetDatabaseString(DbId, 3, JsonData) - ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)") + SetDatabaseQuad(DbId, 4, PushedAt) + ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)") EndProcedure diff --git a/Server/Storage/Writer.pbi b/Server/Storage/Writer.pbi index ce1dc51..dd7bfe4 100644 --- a/Server/Storage/Writer.pbi +++ b/Server/Storage/Writer.pbi @@ -2,8 +2,11 @@ ; BakaShrot Storage Writer ; ; Every write the server does to its database goes through here: -; InsertNextMessage() pushes, grouped (group commit) -; InsertReplicatedMessages() batches from peers +; InsertNextMessage() pushes, grouped (group commit), stamped +; with the time they arrived (pushed_at) +; InsertReplicatedMessages() batches from peers, with their pushed_at, +; skipping those already past their max age +; DeleteStorageMessagesBefore() the retention (Retention.pbi) ; on ONE connection, the writer, only ever used while holding ; BakaShrot_Storage_WriteMutex. Opened by OpenStorageWriter() when the ; workers start, closed by CloseStorageWriter() once they're stopped (see @@ -21,7 +24,8 @@ ; functions are used instead (slower, same behaviour). ; - The next message id of every topic/node id kept in memory, instead of ; a MAX(message_id) on every push. Read from the database the first time -; a pair is pushed to, raised by the replicated messages, forgotten on a +; a pair is pushed to (node_heads, which deleting messages leaves as is: +; ids never go back), raised by the replicated messages, forgotten on a ; rollback. Only right as long as this writer is the only one writing, ; which the write mutex ensures within the server. ; - Checkpoints mostly off the write path: the writer only checkpoints by @@ -104,6 +108,8 @@ Structure BakaShrot_PushJob TopicId.i NodeId.i JsonData.s + ; When it arrived, ms since 1970 UTC. + PushedAt.q ; Filled in by whoever writes it, under the write mutex. MessageId.q @@ -132,6 +138,8 @@ Structure BakaShrot_StorageWriter Insert.i InsertOrIgnore.i MaxId.i + Delete.i + RaiseHead.i ; "TopicId:NodeId" -> the next message id to hand out. Map NextIds.q() @@ -255,7 +263,7 @@ EndProcedure ; Inserts one row with Statement (Insert or InsertOrIgnore). ; Returns 1 if inserted, 0 if ignored, -1 if it failed. -Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s) +Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q) CompilerIf #BakaShrot_Storage_RawSqlite Protected Result.l @@ -264,6 +272,7 @@ Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, Message BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId) ; Static: JsonData outlives the step, the next insert binds it again. BakaShrot_Sqlite\BindText16(Statement, 4, @JsonData, -1, #BakaShrot_Sqlite_Static) + BakaShrot_Sqlite\BindInt64(Statement, 5, PushedAt) Result = BakaShrot_Sqlite\Step_(Statement) If Result <> #BakaShrot_Sqlite_Done BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() @@ -278,6 +287,7 @@ Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, Message SetDatabaseLong(DbId, 1, NodeId) SetDatabaseQuad(DbId, 2, MessageId) SetDatabaseString(DbId, 3, JsonData) + SetDatabaseQuad(DbId, 4, PushedAt) If Not DatabaseUpdate(DbId, PeekS(Statement)) BakaShrot_Storage_Writer\LastError = DatabaseError() ProcedureReturn -1 @@ -287,7 +297,8 @@ Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, Message EndProcedure -; The highest message id stored for a topic/node id, 0 if none, -1 on failure. +; The highest message id ever stored for a topic/node id, 0 if none, -1 on +; failure. Still there once deleted: node_heads keeps it. Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i) Protected MaxId.q = -1 @@ -319,6 +330,35 @@ Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i) EndProcedure +; Raises a topic/node id's head (node_heads) to MessageId, if it's lower, +; like inserting that message would. Returns #False if it failed. +Procedure.i BakaShrot_Writer_RaiseHead(TopicId.i, NodeId.i, MessageId.q) + CompilerIf #BakaShrot_Storage_RawSqlite + Protected Statement.i = BakaShrot_Storage_Writer\RaiseHead + BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId) + BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId) + BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId) + If BakaShrot_Sqlite\Step_(Statement) <> #BakaShrot_Sqlite_Done + BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error() + BakaShrot_Sqlite\Reset(Statement) + ProcedureReturn #False + EndIf + BakaShrot_Sqlite\Reset(Statement) + ProcedureReturn #True + CompilerElse + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + If Not DatabaseUpdate(DbId, PeekS(BakaShrot_Storage_Writer\RaiseHead)) + BakaShrot_Storage_Writer\LastError = DatabaseError() + ProcedureReturn #False + EndIf + ProcedureReturn #True + CompilerEndIf +EndProcedure + + ; The next message id to hand out for a topic/node id, -1 on failure. Procedure.q BakaShrot_Writer_NextId(Key.s, TopicId.i, NodeId.i) Protected MaxId.q @@ -446,6 +486,8 @@ Procedure BakaShrot_Writer_Release() BakaShrot_Writer_Finalize(@\Insert) BakaShrot_Writer_Finalize(@\InsertOrIgnore) BakaShrot_Writer_Finalize(@\MaxId) + BakaShrot_Writer_Finalize(@\Delete) + BakaShrot_Writer_Finalize(@\RaiseHead) If \DbId CloseDatabase(\DbId) EndIf @@ -503,10 +545,18 @@ Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String) \Begin = BakaShrot_Writer_Prepare("BEGIN IMMEDIATE") \Commit = BakaShrot_Writer_Prepare("COMMIT") \Rollback = BakaShrot_Writer_Prepare("ROLLBACK") - \Insert = BakaShrot_Writer_Prepare("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)") - \InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)") - \MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(message_id), 0) FROM data WHERE topic_id = ?1 AND node_id = ?2") - If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId + \Insert = BakaShrot_Writer_Prepare("INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?1, ?2, ?3, ?4, ?5)") + \InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?1, ?2, ?3, ?4, ?5)") + ; node_heads first: it outlives the deleted messages. data too, in + ; case a database was written to by something without the trigger. + \MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(m), 0) FROM (SELECT max_message_id AS m FROM node_heads WHERE topic_id = ?1 AND node_id = ?2 " + + "UNION ALL SELECT MAX(message_id) FROM data WHERE topic_id = ?1 AND node_id = ?2)") + ; Some at a time (?3), so pushes get the write mutex in between. + \Delete = BakaShrot_Writer_Prepare("DELETE FROM data WHERE rowid IN (SELECT rowid FROM data WHERE topic_id = ?1 AND pushed_at < ?2 LIMIT ?3)") + ; What the trigger does on an insert, for the messages skipped instead. + \RaiseHead = BakaShrot_Writer_Prepare("INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (?1, ?2, ?3) " + + "ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id)") + If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId Or Not \Delete Or Not \RaiseHead *Error\s = "can't prepare its statements: " + \LastError BakaShrot_Writer_Release() UnlockMutex(BakaShrot_Storage_WriteMutex) @@ -606,7 +656,7 @@ Procedure BakaShrot_Writer_WriteJobs(List Jobs.i()) Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId) MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId) JsonData = *Job\JsonData - If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData) = 1 + If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1 *Job\MessageId = MessageId BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1 Else @@ -635,7 +685,7 @@ EndProcedure ; Inserts one JSON message for a topic_id/node_id pair, with the next ; message_id for that pair, starting at 1, grouped with the other pushes -; arriving meanwhile. Returns the new message's id once committed, or -1 with +; arriving meanwhile. Stamped with the time it got here (pushed_at). Returns the new message's id once committed, or -1 with ; the reason in *Error\s. Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String) Protected Job.BakaShrot_PushJob @@ -645,6 +695,7 @@ Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String) Job\TopicId = TopicId Job\NodeId = NodeId Job\JsonData = JsonData + Job\PushedAt = BakaShrot_NowUtcMs() Job\MessageId = -1 LockMutex(BakaShrot_Storage_QueueMutex) @@ -703,12 +754,16 @@ EndProcedure ; Stores a batch of messages replicated from a peer, all of one topic/node -; id, under the ids they have on their origin, in a single transaction: +; id, under the ids and pushed_at they have on their origin, in a single transaction: ; either all of them are stored, or none. An id that's already stored is kept ; as is, the new one is dropped, even if it differs (Design/ReplicationIssues.md). +; Messages pushed before SkipBeforeMs (ms since 1970 UTC, 0 for none) are +; past this server's max age for the topic already: not stored, but the +; pair's head still goes up to them, so the peer doesn't send them again. +; *Skipped\i, if given, gets how many. ; Returns #False with the reason in *Error\s, the transaction is rolled back. -Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String) - Protected Stored.i, Inserted.i, Key.s, JsonData.s +Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0) + Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q Key = Str(TopicId) + ":" + Str(NodeId) @@ -724,8 +779,13 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro Stored = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin) If Stored ForEach Messages() + LastMessageId = Messages()\MessageId + If SkipBeforeMs > 0 And Messages()\PushedAt < SkipBeforeMs + Skipped + 1 + Continue + EndIf JsonData = Messages()\JsonData - Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData) + Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData, Messages()\PushedAt) If Inserted < 0 Stored = #False Break @@ -738,6 +798,20 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro EndIf Next + ; The skipped ones count as received: the head covers the whole batch, + ; and the next push goes after it. + If Stored And Skipped > 0 + If BakaShrot_Writer_RaiseHead(TopicId, NodeId, LastMessageId) + If FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key) + If LastMessageId + 1 > BakaShrot_Storage_Writer\NextIds() + BakaShrot_Storage_Writer\NextIds() = LastMessageId + 1 + EndIf + EndIf + Else + Stored = #False + EndIf + EndIf + If Stored And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit) Stored = #False EndIf @@ -751,10 +825,56 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro EndIf UnlockMutex(BakaShrot_Storage_WriteMutex) + If *Skipped + *Skipped\i = Skipped + EndIf ProcedureReturn Stored EndProcedure +; Deletes up to Limit messages of TopicId pushed before BeforeMs (ms since +; 1970 UTC), in one statement under the write mutex: call it again while it +; deletes Limit, pushes get their turn in between. node_heads is left as is +; (see SetupStorageDatabase()). +; Returns how many were deleted, -1 with the reason in *Error\s. +Procedure.i DeleteStorageMessagesBefore(TopicId.i, BeforeMs.q, Limit.i, *Error.String) + Protected Deleted.i = -1 + + LockMutex(BakaShrot_Storage_WriteMutex) + If Not BakaShrot_Storage_Writer\DbId + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn -1 + EndIf + + CompilerIf #BakaShrot_Storage_RawSqlite + Protected Statement.i = BakaShrot_Storage_Writer\Delete + BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId) + BakaShrot_Sqlite\BindInt64(Statement, 2, BeforeMs) + BakaShrot_Sqlite\BindInt64(Statement, 3, Limit) + If BakaShrot_Sqlite\Step_(Statement) = #BakaShrot_Sqlite_Done + Deleted = BakaShrot_Sqlite\Changes(BakaShrot_Storage_Writer\Handle) + Else + *Error\s = BakaShrot_Writer_Error() + EndIf + BakaShrot_Sqlite\Reset(Statement) + CompilerElse + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseQuad(DbId, 1, BeforeMs) + SetDatabaseLong(DbId, 2, Limit) + If DatabaseUpdate(DbId, PeekS(BakaShrot_Storage_Writer\Delete)) + Deleted = AffectedDatabaseRows(DbId) + Else + *Error\s = DatabaseError() + EndIf + CompilerEndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Deleted +EndProcedure + + ; Adds a row to the "topics" or "nodes" table (Table), for Id, named Name ; (its id in digits if it has none), Origin "peer" or "id", see ; Server/Storage/Names.pbi. A row already there for that id is kept. diff --git a/Server/Storage/db_schema_v6.dbml b/Server/Storage/db_schema_v6.dbml new file mode 100644 index 0000000..0497d83 --- /dev/null +++ b/Server/Storage/db_schema_v6.dbml @@ -0,0 +1,89 @@ +// Changes from v5: +// - data.pushed_at: when the message was pushed to its origin, ms since +// 1970-01-01 UTC, kept as is when replicated. A v5 database gets it with +// the time of the upgrade (MigrateStoragePushedAt() in Storage.pbi). +// - Index (topic_id, pushed_at): what the retention deletes by +// (Retention.pbi, [BakaShrot.Retention] in the config). +// - messages: the view also has pushed_at, and pushed_utc as text. +// - node_heads outlives deleted messages: a pair's highest id ever. Also +// raised for replicated messages skipped as already past their max age. +// - archives is gone: never used, dropped from older databases. +// +// 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] + } +} + +// Create it, but we'll implement this later. +table attachements { + topic_id integer [not null] + node_id integer [not null] + message_id integer [not null] + attachement_data blob [not null] + + indexes { + (topic_id, node_id) + message_id + } +} + +// origin: "config" (named in [BakaShrot.Topics]), "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]), "id" (unnamed), "peer" +// (only in databases from the short-lived version that added peer nodes). +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. + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Tests/Bench/BenchSeed.pb b/Tests/Bench/BenchSeed.pb index 40f296c..d871194 100644 --- a/Tests/Bench/BenchSeed.pb +++ b/Tests/Bench/BenchSeed.pb @@ -159,7 +159,7 @@ ForEach Nodes() While Count < #Seed_BatchSize And Id < StartId + RowsPerNode Id + 1 Count + 1 - If Not InsertReplicatedMessage(Dbs(), TopicId, LocalIds(d), Id, Seed_Json(Nodes(), Id, Pad)) + If Not InsertReplicatedMessage(Dbs(), TopicId, LocalIds(d), Id, Seed_Json(Nodes(), Id, Pad), BakaShrot_NowUtcMs()) PrintN("Insert failed: " + DatabaseError()) End 1 EndIf diff --git a/Tests/Names-Test.ps1 b/Tests/Names-Test.ps1 index b03c014..e72d19f 100644 --- a/Tests/Names-Test.ps1 +++ b/Tests/Names-Test.ps1 @@ -244,7 +244,7 @@ try { Expect "B's unnamed node 9 pushes into logs" (Tool "PushMessage.exe" @($M3, $Anon)) "message #1" Expect "B's bsecret pushes into logs" (Tool "PushMessage.exe" @($M3, $BSecret)) "message #1" Start-Sleep -Seconds 4 - Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\) \| \{"from":"b-local"\}' + Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}' Expect "A didn't get sensors:blocal (not accepted)" (Tool "GetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1 Expect "A didn't get logs:9 (unnamed)" (Tool "GetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1 Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "GetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1 diff --git a/Tests/Retention-Test.ps1 b/Tests/Retention-Test.ps1 new file mode 100644 index 0000000..38c1226 --- /dev/null +++ b/Tests/Retention-Test.ps1 @@ -0,0 +1,343 @@ +# End-to-end test of pushed_at and [BakaShrot.Retention]: +# - a database from before pushed_at gets it (the time of the upgrade), and +# its ids go on; +# - a push is stamped with the time it arrived (UTC), GetMessages --time +# and GetLatestMessage show it, replication carries it as is; +# - each server deletes a topic's messages past its own max age (by name, +# by pattern, "*"), only its own: the peer keeps its copies; +# - after deleting, ids go on, and the peer doesn't send them again; +# - what a peer replicates already past the max age isn't stored, but +# counts as received: not sent again; +# - an age without a unit is refused at start. +# Two linked servers, A (port 12408) and B (12409). +# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (or compile +# Tests\Bench\BenchServer.pb into it), and Python 3 for the old database +# (skipped without it). +# Usage: powershell -ExecutionPolicy Bypass -File Tests\Retention-Test.ps1 [-Python ] +param( + [string]$Build = (Join-Path $PSScriptRoot "..\Build"), + [string]$Python = "python" +) +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_retentiontest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Fails = 0 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +function Tool([string]$Name, [string[]]$A) { + $O = & (Join-Path $Build $Name) @A 2>&1 + @{ Code = $LASTEXITCODE; Out = ($O -join " | "); Lines = @($O | Where-Object { "$_" -ne "" }) } +} +function Check([string]$What, [bool]$Ok, [string]$Detail) { + if (-not $Ok) { $script:Fails++ } + "{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail +} +function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { + Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out) +} +function Start-Srv($Name) { + $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Stop -ErrorAction SilentlyContinue + $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Stop = $Stop; Name = $Name } +} +function Stop-Srv($S) { + if ($S.P.HasExited) { return } + Set-Content $S.Stop "x" + if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force } +} +function Wait-Port($Port, $S) { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" } + if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } + Start-Sleep -Milliseconds 100 + } +} +function Query($Sql, $Ini) { + $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql + Tool "Query.exe" @("@$F", $Ini) +} +# Waits until Sql answers something matching Pattern, for up to Seconds. +function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { + $D = (Get-Date).AddSeconds($Seconds) + do { + $R = Query $Sql $Ini + if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $D) + $R +} +function Count($Topic, $Where = "") { + "SELECT COUNT(*) AS n FROM messages WHERE topic = '$Topic' AND node = 'kitchen' $Where" +} +function NowMs { [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() } +# Pushes Data from a file (PowerShell 5 strips the quotes of an argument). +function Push($Data, $Ini, [string]$Topic = "") { + $F = Join-Path $Dir "push.txt" + [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) + $A = @() + if ($Topic) { $A += @("-t", $Topic) } + Tool "PushMessage.exe" ($A + @("@$F", $Ini)) +} + +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair + +# A: short is kept 3 s here, everything else forever. Checked every second. +Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($A.Priv) +Topic = logs +Node = serverA + +[BakaShrot.Topics] +logs = 1 +short = 2 +keep = 3 +late = 4 + +[BakaShrot.Nodes] +serverA = 10 +serverB = 11 +kitchen = 2 + +[BakaShrot.Retention] +short = 3s + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12408 +ReplicatingTopics = logs;short;keep;late +DatabasePath = $(Join-Path $Dir "a.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +RetentionInterval = 1 + +[BakaShrot.Peer.b] +Host = 127.0.0.1 +Port = 12409 +Topic = logs +Node = serverB +PublicKey = $($B.Pub) + +[BakaShrot.Client.b] +PublicKeys = $($B.Pub) +Identities = logs:serverB + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +PushTopics = logs;short;keep;late +ReadTopics = * +AllowQuery = 1 +"@ + +# B: other ids. short forever, keep by a pattern (4 s), the rest 1 h. +Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($B.Priv) +Topic = logs +Node = serverB + +[BakaShrot.Topics] +logs = 300 +short = 301 +keep = 302 +late = 303 + +[BakaShrot.Nodes] +serverA = 1 +serverB = 2 +kitchen = 30 + +[BakaShrot.Retention] +short = forever +ke* = 4s +late = 3s +* = 1h + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12409 +ReplicatingTopics = logs;short;keep;late +DatabasePath = $(Join-Path $Dir "b.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +RetentionInterval = 1 + +[BakaShrot.Peer.a] +Host = 127.0.0.1 +Port = 12408 +Topic = logs +Node = serverA +PublicKey = $($A.Pub) + +[BakaShrot.Client.a] +PublicKeys = $($A.Pub) +Identities = logs:serverA + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +ReadTopics = * +AllowQuery = 1 +"@ + +$ServerKeys = @{ 12408 = $A.Pub; 12409 = $B.Pub } +function Client-Ini($Name, $Port) { + $P = Join-Path $Dir "$Name.ini" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + $P +} +$OnA = Client-Ini "kitchen-a" 12408 +$OnB = Client-Ini "kitchen-b" 12409 + +# A database from before pushed_at, for A: one message, logs:kitchen #1. +$HasOld = $false +$Seed = @" +import sqlite3, sys +db = sqlite3.connect(sys.argv[1]) +db.execute("CREATE TABLE data (topic_id INTEGER NOT NULL, node_id INTEGER NOT NULL, message_id INTEGER NOT NULL, message_data TEXT NOT NULL, is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, UNIQUE (topic_id, node_id, message_id))") +db.execute("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (1, 2, 1, '{\"old\":1}')") +db.commit() +"@ +Set-Content (Join-Path $Dir "seed.py") -Encoding Ascii -Value $Seed +try { + & $Python -B (Join-Path $Dir "seed.py") (Join-Path $Dir "a.sqlite") 2>&1 | Out-Null + $HasOld = ($LASTEXITCODE -eq 0) +} catch { $HasOld = $false } +if (-not $HasOld) { "SKIP the old database: no Python ($Python)" ; Remove-Item (Join-Path $Dir "a.sqlite") -ErrorAction SilentlyContinue } + +foreach ($Port in 12408, 12409) { if (Test-Port $Port) { throw "Port $Port is already in use" } } +$Before = NowMs +$SA = Start-Srv "a"; $SB = $null +try { + Wait-Port 12408 $SA + "--- Before B starts: late #1-#2 on A, past B's 3 s once B gets them" + foreach ($i in 1..2) { Expect "push late #$i" (Push "{`"late`":$i}" $OnA "late") "message #$i" } + Start-Sleep -Seconds 5 + $SB = Start-Srv "b" + Wait-Port 12409 $SB + Start-Sleep -Seconds 2 + + "--- The old database" + if ($HasOld) { + $R = Query "SELECT message_id, pushed_at FROM data WHERE topic_id = 1 AND node_id = 2" $OnA + $Stamp = 0; if ($R.Out -match '\[\["1","(\d+)"\]\]') { $Stamp = [int64]$Matches[1] } + Check "the old message got pushed_at: the time of the upgrade" ($Stamp -ge $Before - 1000 -and $Stamp -le (NowMs)) $R.Out + Expect "its ids go on: the next push is #2" (Push '{"n":"after upgrade"}' $OnA) "message #2" + } else { + Expect "first push" (Push '{"n":"first"}' $OnA) "message #1" + Expect "second push" (Push '{"n":"after upgrade"}' $OnA) "message #2" + } + + "--- pushed_at" + $PushedFrom = NowMs + Expect "push logs #3" (Push '{"n":"stamped"}' $OnA) "message #3" + $PushedTo = NowMs + $R = Query "SELECT pushed_at, pushed_utc FROM messages WHERE topic = 'logs' AND node = 'kitchen' AND message_id = 3" $OnA + $Stamp = 0; if ($R.Out -match '\[\["(\d+)","([^"]+)"\]\]') { $Stamp = [int64]$Matches[1]; $Utc = $Matches[2] } + Check "stamped with the time it arrived, in UTC ms" ($Stamp -ge $PushedFrom - 50 -and $Stamp -le $PushedTo + 50) "$Stamp in [$PushedFrom, $PushedTo]" + $Expected = [DateTimeOffset]::FromUnixTimeMilliseconds($Stamp).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") + Check "the view's pushed_utc is the same, as text" ($Utc -eq $Expected) "$Utc, expected $Expected" + + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA) + Check "GetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out + $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA) + Check "GetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out + Expect "GetLatestMessage shows it" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected)) + + $Sql = "SELECT message_id, pushed_at FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" + $OnAStamps = (Query $Sql $OnA).Out + $R = Wait-Query $Sql $OnB '"3","\d+"' + Check "replicated with the same pushed_at, every one" ($R.Out -eq $OnAStamps) "A $OnAStamps | B $($R.Out)" + Expect "GetLatestMessage on B: the same time" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected)) + + "--- Retention on A (short = 3s), not on B (short = forever)" + foreach ($i in 1..3) { Expect "push short #$i" (Push "{`"short`":$i}" $OnA "short") "message #$i" } + $R = Wait-Query (Count "short") $OnB '\[\["3"\]\]' 10 + Check "B got the 3 short ones" ($R.Out -match '\[\["3"\]\]') $R.Out + $R = Wait-Query (Count "short") $OnA '\[\["0"\]\]' 10 + Check "A deleted them past 3 s" ($R.Out -match '\[\["0"\]\]') $R.Out + Expect "A kept logs (no max age)" (Query (Count "logs") $OnA) '\[\["3"\]\]' + Expect "B kept them (its own rules)" (Query (Count "short") $OnB) '\[\["3"\]\]' + Expect "A: no message left in short" (Tool "GetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1 + Expect "A's ids go on after deleting: #4" (Push '{"short":4}' $OnA "short") "message #4" + $R = Wait-Query (Count "short") $OnB '\[\["4"\]\]' 10 + Check "B got #4" ($R.Out -match '\[\["4"\]\]') $R.Out + Start-Sleep -Seconds 3 + Expect "B didn't send A back what A deleted" (Query (Count "short" "AND message_id <= 3") $OnA) '\[\["0"\]\]' + + "--- Retention on B by pattern (ke* = 4s), not on A" + foreach ($i in 1..2) { Expect "push keep #$i" (Push "{`"keep`":$i}" $OnA "keep") "message #$i" } + $R = Wait-Query (Count "keep") $OnB '\[\["2"\]\]' 10 + Check "B got the 2 keep ones" ($R.Out -match '\[\["2"\]\]') $R.Out + $R = Wait-Query (Count "keep") $OnB '\[\["0"\]\]' 10 + Check "B deleted them past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out + Expect "A kept them" (Query (Count "keep") $OnA) '\[\["2"\]\]' + Expect "push keep #3" (Push '{"keep":3}' $OnA "keep") "message #3" + $R = Wait-Query (Count "keep") $OnB '\[\["1"\]\]' 10 + Check "B only got #3, not #1 and #2 again" ($R.Out -match '\[\["1"\]\]') $R.Out + Expect "B: it's #3" (Tool "GetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3" + Expect "B's * = 1h keeps logs" (Query (Count "logs") $OnB) '\[\["3"\]\]' + + "--- Replicated already past the max age (B: late = 3s)" + $Head = "SELECT h.max_message_id FROM node_heads h JOIN topics t ON t.topic_id = h.topic_id WHERE t.name = 'late'" + $R = Wait-Query $Head $OnB '\[\["2"\]\]' 10 + Check "B counts late #1-#2 as received (its head is 2)" ($R.Out -match '\[\["2"\]\]') $R.Out + Expect "but didn't store them" (Query (Count "late") $OnB) '\[\["0"\]\]' + Expect "A has them" (Query (Count "late") $OnA) '\[\["2"\]\]' + Expect "push late #3, fresh" (Push '{"late":3}' $OnA "late") "message #3" + $R = Wait-Query $Head $OnB '\[\["3"\]\]' 10 + Check "B got #3" ($R.Out -match '\[\["3"\]\]') $R.Out + # Stored, then deleted 3 s later by the pass, alone: #1-#2 never were. + $D = (Get-Date).AddSeconds(10) + while ((Get-Date) -lt $D -and -not ((Get-Content (Join-Path $Dir "b.log") -Raw) -match "deleted 1 messages of topic 'late'")) { Start-Sleep -Milliseconds 250 } + Check "B stored #3, and deleted it alone past 3 s" ((Get-Content (Join-Path $Dir "b.log") -Raw) -match "deleted 1 messages of topic 'late'") "checked" + Start-Sleep -Seconds 2 +} +finally { + Stop-Srv $SA; if ($SB) { Stop-Srv $SB } +} + +"--- Logs" +$LogA = Get-Content (Join-Path $Dir "a.log") -Raw +$LogB = Get-Content (Join-Path $Dir "b.log") -Raw +Check "A logged its rule" ($LogA -match "Retention: short = 3s") "checked" +Check "A logged what it deleted" ($LogA -match "Retention: deleted 3 messages of topic 'short' pushed before \d{4}-") "checked" +Check "B logged its rules" ($LogB -match "Retention: ke\* = 4s" -and $LogB -match "Retention: \* = 1h") "checked" +Check "B deleted keep" ($LogB -match "Retention: deleted 2 messages of topic 'keep'") "checked" +Check "B never sent A short messages (A is ahead, deleted or not)" (-not ($LogB -match "Sent \d+ messages of short")) "checked" +Check "A sent B late once each: #1-#2, then #3 alone" (([regex]::Matches($LogA, "Sent 2 messages of late:kitchen")).Count -eq 1 -and ([regex]::Matches($LogA, "Sent 1 messages of late:kitchen")).Count -eq 1) "checked" +Check "B never stored late #1-#2" (-not ($LogB -match "deleted [23] messages of topic 'late'")) "checked" +Check "A sent B keep twice: #1-#2, then #3 alone" ($LogA -match "Sent 2 messages of keep:kitchen" -and $LogA -match "Sent 1 messages of keep:kitchen" -and -not ($LogA -match "Sent 3 messages of keep")) "checked" +# A tries to link to B in the 5 s before B starts: those are expected. +$LinkTries = @([regex]::Matches($LogA, "Failed to link to 'b'")).Count +Check "A only failed to link to B before B started" ($LinkTries -le 8) "$LinkTries tries" +$LogAOther = ($LogA -split "`r?`n" | Where-Object { $_ -notmatch "Failed to link to 'b'|Retrying 'b'" }) -join "`n" +foreach ($P in @("Failed", "invalid", "unexpected", "doesn't decrypt")) { + Check "no '$P' in A's or B's log" (-not ($LogAOther -match [regex]::Escape($P)) -and -not ($LogB -match [regex]::Escape($P))) "checked" +} + +"--- An age without a unit" +(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "short = 3s", "short = 30" | Set-Content (Join-Path $Dir "bad.ini") -Encoding Ascii +$SBad = Start-Srv "bad" +$Exited = $SBad.P.WaitForExit(10000) +if (-not $Exited) { Stop-Srv $SBad } +$LogBad = Get-Content (Join-Path $Dir "bad.log") -Raw +Check "refused at start" ($Exited -and $SBad.P.ExitCode -ne 0 -and $LogBad -match "short = '30' isn't an age") $LogBad.Trim() + +"" +if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tools/Common/ToolClient.pbi b/Tools/Common/ToolClient.pbi index aa36e3f..af868d2 100644 --- a/Tools/Common/ToolClient.pbi +++ b/Tools/Common/ToolClient.pbi @@ -78,6 +78,13 @@ Procedure.i ToolClient_Connect(IniPath.s) EndProcedure +; Ms (milliseconds since 1970 UTC, as BakaShrot_GetMessagePushedAt() gives +; it) as "2026-11-08T14:03:59.123Z". +Procedure.s ToolClient_FormatUtc(Ms.q) + ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ss", Ms / 1000) + "." + RSet(Str(Ms % 1000), 3, "0") + "Z" +EndProcedure + + ; Disconnects and unloads the DLL. Procedure ToolClient_Close() BakaShrot_Disconnect() diff --git a/Tools/GetLatestMessage/GetLatestMessage.pb b/Tools/GetLatestMessage/GetLatestMessage.pb index 7d2a4c4..acb964b 100644 --- a/Tools/GetLatestMessage/GetLatestMessage.pb +++ b/Tools/GetLatestMessage/GetLatestMessage.pb @@ -5,7 +5,8 @@ ; Topic, Node Whose latest message to get, each a name or an id. ; ClientIni Identity and server to use, defaults to "client.ini". ; -; Prints the latest message stored for that topic/node, the server refuses +; Prints the latest message stored for that topic/node, and when it was +; pushed (UTC), then its data. The server refuses ; if the client's ReadTopics don't allow the topic, if either is unknown, or ; if there's no message. ; Compile as a console program, exits with 0 on success, 1 on failure. @@ -55,7 +56,7 @@ If Not BakaShrot_GetLatestMessageOf(Topic, Node) EndIf PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) + - " (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + ")") + " (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + "), pushed " + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt())) PrintN(BakaShrot_GetMessageDataString()) ToolClient_Close() diff --git a/Tools/GetMessages/GetMessages.pb b/Tools/GetMessages/GetMessages.pb index 8bb353d..6eadf76 100644 --- a/Tools/GetMessages/GetMessages.pb +++ b/Tools/GetMessages/GetMessages.pb @@ -12,10 +12,12 @@ ; every --interval ms, until stopped (Ctrl+C) or the ; connection fails. ; --interval How often --follow checks, defaults to 500. +; --time, -t Also prints when each message was pushed, in UTC. ; ClientIni Identity and server to use, defaults to "client.ini". ; ; Prints each message on its own line, in message id order, as its id, a -; tab, and its data as stored (JSON or not, a message with line breaks spans +; tab (with --time: when it was pushed, "2026-11-08T14:03:59.123Z", and +; another tab), and its data as stored (JSON or not, a message with line breaks spans ; several lines). The server refuses if the client's ReadTopics don't allow ; the topic, or if either is unknown. ; Compile as a console program, exits with 0 on success, 1 on failure. @@ -31,7 +33,7 @@ XIncludeFile "../../Commons/Networking/Names.pbi" #GetMessages_BatchLimit = 10000 Define Topic.s, Node.s, IniPath.s = "client.ini", AfterText.s = "0" -Define Limit.q = -1, Follow.i = #False, IntervalMs.i = 500 +Define Limit.q = -1, Follow.i = #False, IntervalMs.i = 500, ShowTime.i = #False Define i.i, Argument.s, Value.s, Positional.i Define AfterMessageId.q, Printed.q, Asked.l, Count.l, n.l @@ -39,8 +41,9 @@ OpenConsole() ; Prints the usage and exits. Procedure Usage() - PrintN("Usage: GetMessages [--after ] [--limit ] [--follow] [--interval ] [ClientIni]") + PrintN("Usage: GetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni]") PrintN(" Topic and Node are names or ids. Prints each message as its id, a tab, and its data.") + PrintN(" --time also prints when it was pushed (UTC) between them.") End 1 EndProcedure @@ -89,6 +92,8 @@ While i < CountProgramParameters() EndIf IntervalMs = Val(Value) EndSelect + Case "--time", "-t" + ShowTime = #True Case "--follow", "-f" Follow = #True Default @@ -161,7 +166,11 @@ Repeat For n = 0 To Count - 1 BakaShrot_SelectMessage(n) AfterMessageId = BakaShrot_GetMessageId() - PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString()) + If ShowTime + PrintN(Str(AfterMessageId) + #TAB$ + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()) + #TAB$ + BakaShrot_GetMessageDataString()) + Else + PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString()) + EndIf Next Printed + Count From df61ef9719fb1f7028f17f050dd013a0073ebac4 Mon Sep 17 00:00:00 2001 From: Herwin Bozet Date: Sun, 8 Nov 2026 18:56:15 +0100 Subject: [PATCH 2/5] Add attachments (protocol 4), their edge-case tests, and handoff docs - One optional attachment per message, any size up to the server's MaxAttachmentSize (default 1G), sent and stored in 1 MB parts, checked with its SHA-256. Uploaded before its message (UploadStart, UploadChunk), then attached by the PushMessage in the same transaction; uploads never pushed expire after UploadTimeout. Read back a part at a time (GetAttachment). - Replicated separately, after the messages: the message carries the size and SHA-256, then each check-in lists what the peer is missing (MissingAttachments) and sends the parts from where it stopped. Over the receiver's limit, the attachment is marked not kept. - Deleted with its message by the retention, parts cleaned up in the background. Schema v7 (attachments, blobs, blob_chunks), replacing the unused attachements table. - DLL: PushMessageWithFile/WithData, SaveAttachment, LoadAttachment, GetMessageAttachmentSize, IsMessageAttachmentReady. Python: push(..., attachment=), get_attachment(), save_attachment(). Tools: PushMessage -a, GetAttachment. The release smoke test round-trips one. - Tests/Attachments-Test.ps1 (39 checks) and Tests/AttachmentEdges-Test.ps1 (51 checks, with a raw protocol client): wrong SHA-256, bad parts, others' uploads, expiry, replication resuming after a kill, a corrupted stored copy. Found: a corrupted copy is re-sent to peers forever, noted as open item 3 in Notes.md with a proposed fix. - CLAUDE.md: how to build, test, the traps and working rules, for the next session. Notes.md and the Design docs updated. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP --- Build.ps1 | 4 +- CLAUDE.md | 99 ++++ Client/BakaShrot_Client.pbi | 476 +++++++++++++++++- Client/BakaShrot_Client_Prototypes.pbi | 29 ++ Commons/Cryptography/Libsodium.pbi | 36 ++ Commons/Networking/Connections.pbi | 16 + Commons/Networking/Packets.pbi | 43 +- .../Packets/AttachmentChunkPacket.pbi | 195 +++++++ .../Networking/Packets/ChunkStoredPacket.pbi | 104 ++++ .../Packets/GetAttachmentPacket.pbi | 134 +++++ .../Packets/LatestMessagePacket.pbi | 27 + Commons/Networking/Packets/MessagesPacket.pbi | 29 +- .../Packets/MissingAttachmentsPacket.pbi | 156 ++++++ .../MissingAttachmentsRequestPacket.pbi | 71 +++ .../Networking/Packets/PushMessagePacket.pbi | 15 + .../ReplicateAttachmentChunkPacket.pbi | 164 ++++++ .../Packets/ReplicateMessagesPacket.pbi | 40 +- .../Networking/Packets/UploadChunkPacket.pbi | 134 +++++ .../Networking/Packets/UploadStartPacket.pbi | 121 +++++ .../Packets/UploadStartedPacket.pbi | 103 ++++ Design/Attachments.md | 162 ++++++ Design/Packets.md | 40 +- Design/Release.md | 11 +- Interactors/Python/bakashrot.py | 75 ++- Interactors/Python/check_bakashrot.py | 41 ++ Notes.md | 167 ++++-- Release.ps1 | 23 +- Server/Config/Config.pbi | 59 +++ Server/Config/schema.ini | 11 +- Server/Networking/Networking.pbi | 398 ++++++++++++++- Server/Networking/Peers.pbi | 149 +++++- Server/Storage/Attachments.pbi | 450 +++++++++++++++++ Server/Storage/Retention.pbi | 48 +- Server/Storage/Storage.pbi | 95 +++- Server/Storage/Writer.pbi | 113 ++++- Server/Storage/db_schema_v7.dbml | 126 +++++ Tests/AttachmentEdgeClient.pb | 373 ++++++++++++++ Tests/AttachmentEdges-Test.ps1 | 287 +++++++++++ Tests/Attachments-Test.ps1 | 296 +++++++++++ Tools/GetAttachment/GetAttachment.pb | 68 +++ Tools/GetLatestMessage/GetLatestMessage.pb | 10 +- Tools/PushMessage/PushMessage.pb | 28 +- 42 files changed, 4920 insertions(+), 106 deletions(-) create mode 100644 CLAUDE.md create mode 100644 Commons/Networking/Packets/AttachmentChunkPacket.pbi create mode 100644 Commons/Networking/Packets/ChunkStoredPacket.pbi create mode 100644 Commons/Networking/Packets/GetAttachmentPacket.pbi create mode 100644 Commons/Networking/Packets/MissingAttachmentsPacket.pbi create mode 100644 Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi create mode 100644 Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi create mode 100644 Commons/Networking/Packets/UploadChunkPacket.pbi create mode 100644 Commons/Networking/Packets/UploadStartPacket.pbi create mode 100644 Commons/Networking/Packets/UploadStartedPacket.pbi create mode 100644 Design/Attachments.md create mode 100644 Server/Storage/Attachments.pbi create mode 100644 Server/Storage/db_schema_v7.dbml create mode 100644 Tests/AttachmentEdgeClient.pb create mode 100644 Tests/AttachmentEdges-Test.ps1 create mode 100644 Tests/Attachments-Test.ps1 create mode 100644 Tools/GetAttachment/GetAttachment.pb diff --git a/Build.ps1 b/Build.ps1 index 52ae66a..a9f73fb 100644 --- a/Build.ps1 +++ b/Build.ps1 @@ -172,12 +172,14 @@ try { # Example app using the DLL, run it from ./Build while the server runs. Invoke-Compiler "Client\BakaShrot_Client_Prototypes.pbi" "ClientExample.exe" @("/CONSOLE") # Tools using the DLL, same as the example: - # PushMessage [-t ] [ClientIni] + # PushMessage [-t ] [-a ] [ClientIni] # GetLatestMessage [ClientIni] Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE") Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE") # GetMessages [--after ] [--limit ] [--follow] [ClientIni] Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE") + # GetAttachment [ClientIni] + Invoke-Compiler "Tools\GetAttachment\GetAttachment.pb" "GetAttachment.exe" @("/CONSOLE") # Query [ClientIni] Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE") # Resolve [ClientIni] diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..dfe9b84 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,99 @@ +# BakaShrot - start here + +A message store with replication, in PureBasic: servers take JSON (or any) +messages per topic/node from authenticated clients, store them in SQLite, +and replicate them between peers by name. Clients: a DLL, CLI tools, a +Python module. An **internal tool on trusted machines**: correctness and +operations come before security hardening (`Notes.md`, "Threat model"). + +## Read first + +1. `Notes.md`: where things stand, "Open items, by importance" (the to-do + list, item 3 is the next known bug), "Testing tips". +2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives, + code conventions), `Attachments.md`, `Cryptography.md`, + `StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`, + `Suggestions.md`. +3. `git log --oneline` and `git status`: what's committed. Work happens on + branches off `master` (`timestamps-retention` at this writing). + +## Build + +- Dev compiler, PureBasic 5.73: `C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe /EXE [flags]`. + Release compiler, 6.40 C backend: `C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe /OUTPUT /OPTIMIZER`. + Code must compile with both (`Release.ps1` checks the 6.40 side). +- `Build.ps1` builds everything into `Build\`, **regenerates keys and + configs, then runs a server waiting on its console**: don't run it from + an automated shell. To rebuild after a change, compile what changed: + +| Source | Output | Flags | +|---|---|---| +| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` | +| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` | +| `Tools\\.pb` (PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, Resolve, ListNames, KeyGen) | `Build\.exe` | `/CONSOLE` | +| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` | +| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` | +| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` | +| `Tests\HandshakeTest.pb`, `Tests\CipherTest.pb` | `Build\` | `/CONSOLE` | +| `Tests\AttachmentEdgeClient.pb` | `Build\AttachmentEdgeClient.exe` | `/CONSOLE /THREAD` | + +- `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and + smoke-tests it (`-Force` replaces an existing folder of the same name). + +## Test + +Each suite starts its own servers (`BenchServer.exe`) on fixed ports, in a +fresh folder under `Build\`, and prints PASS/FAIL lines; exit code 0 means +all passed. `powershell -ExecutionPolicy Bypass -File Tests\.ps1`: + +| Suite | Ports | Covers | +|---|---|---| +| `Names-Test.ps1` | 12401-12402 | names/ids, filters, wildcards, replication by name | +| `BigMessages-Test.ps1` | 12403-12404 | 16 MB messages, handshake frame limit, `is_json`, query errors | +| `GetMessages-Test.ps1` | 12405 | runs of messages, `--follow` | +| `Python-Test.ps1` | 12406-12407 | `bakashrot.py` (`check_bakashrot.py`), the wire is encrypted (`wire_check.py`) | +| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) | +| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits | +| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) | + +Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and +the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp` +(push ceiling, ~40,800 msg/s for 4 servers). After a change, run every +suite: they take a few minutes in all. + +## Traps + +- **Run exes from `Build\`**: the antivirus blocks them in temp folders. +- **`Build\` holds private keys**: git-ignored, never publish it. +- **PureBasic is single pass**: constants, structures and procedures must + be declared before use, so include order matters (e.g. `Config.pbi` + includes `Packets.pbi` for its constants). +- **`SetDatabase*()` binds the next statement run on that connection**, not + a specific one: set them right before their `DatabaseUpdate/Query`. +- **PureBasic lists aren't safe to walk from several threads** (`ForEach` + moves the shared current element): give each thread its own copy. +- **Files mix CRLF and LF**: edits must keep each file's line endings. +- **PowerShell 5**: JSON passed as an argument loses its double quotes + (tests write it to a file, `@file`), and `@()` can't be passed through + `-File`. +- **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields: + write edit scripts to files, or use the Edit tool. +- **The real server needs a console** (it stops at once without input): + tests use `BenchServer.exe` and its stop file instead. + +## Working rules + +- **Commit only when the owner asks**, on a branch, not `master`. +- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 4 at + this writing); any difference refuses the connection. +- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v7 at this + writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`), + existing databases must keep working. +- **Packets** follow `Design/Packets.md` "Code conventions": one file per + packet in `Commons/Networking/Packets/`, `_Encode` / `_Decode` (and + `_Free` when it holds data), every field validated on decode. +- **Every write goes through the writer** (`Server/Storage/Writer.pbi`, + under its mutex); reads use the thread's own connection. +- **Docs follow the code**: a finished piece gets a "Done: ... (date)" + section in `Notes.md`, what's left goes to its open items, and the + `Design/` doc of that area is updated with it. diff --git a/Client/BakaShrot_Client.pbi b/Client/BakaShrot_Client.pbi index a92e6a0..0fd680e 100644 --- a/Client/BakaShrot_Client.pbi +++ b/Client/BakaShrot_Client.pbi @@ -18,6 +18,8 @@ ; BakaShrot_GetLatestMessage(TopicId, NodeId), then ; BakaShrot_GetMessageId(), BakaShrot_GetMessageData(), ; BakaShrot_GetMessagePushedAt() (ms since 1970 UTC), +; BakaShrot_GetMessageAttachmentSize() (0 for none) and +; BakaShrot_IsMessageAttachmentReady(), ; BakaShrot_GetMessageTopic() / BakaShrot_GetMessageNode() (names) ; and BakaShrot_GetMessageTopicId() / BakaShrot_GetMessageNodeId() ; BakaShrot_GetMessages(Topic, Node, AfterMessageId, Limit): the @@ -32,6 +34,13 @@ ; id and name, then BakaShrot_GetNamesList() as JSON ; BakaShrot_Query(Sql), raw read-only SQL, then ; BakaShrot_GetQueryResult() +; Attachments, one per message at most (Design/Attachments.md): +; BakaShrot_PushMessageWithFile(Topic, JsonData, FilePath) or +; BakaShrot_PushMessageWithData(Topic, JsonData, *Data, Size): the +; attachment is uploaded first, the message stored once it all is +; BakaShrot_SaveAttachment(Topic, Node, MessageId, FilePath), or +; BakaShrot_LoadAttachment(Topic, Node, MessageId) then +; BakaShrot_GetAttachmentData(*Buffer, Size): checked with its SHA-256 ; If the server refuses a request, the connection stays open and ; BakaShrot_GetRefusalReason() tells why. ; 4. BakaShrot_IsConnected(), BakaShrot_Disconnect() @@ -88,6 +97,8 @@ Global BakaShrot_Outbound.BakaShrot_Outbound ; Filled by the requests, see BakaShrot_GetLatestMessage() and BakaShrot_GetRefusalReasonA/W(). Global BakaShrot_MessageId.q = 0 Global BakaShrot_MessagePushedAt.q = 0 +Global BakaShrot_MessageAttachmentSize.q = 0 +Global BakaShrot_MessageAttachmentReady.i = #False Global BakaShrot_MessageData.s = "" Global BakaShrot_MessageTopicId.l = -1 Global BakaShrot_MessageNodeId.l = -1 @@ -394,10 +405,11 @@ EndProcedure ; is_json column) into Topic (a name or an id, "" for the client's own ; topic), the server stores it under that topic and this client's node, with ; the next message id. The client's PushTopics on the server must allow it. +; UploadId: its attachment, uploaded with BakaShrot_Upload(), 0 for none. ; Returns the new message's id (1 or more), or -1 on failure. ; On -1, BakaShrot_IsConnected() tells if the server refused it (still ; connected, see BakaShrot_GetRefusalReason()) or if the connection failed. -Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s) +Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0) Protected Push.BakaShrot_PushMessage Protected *Pushed.BakaShrot_MessagePushed Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer @@ -421,6 +433,7 @@ Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s) Push\Topic = Topic Push\JsonData = JsonData + Push\UploadId = UploadId *Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize) If Not *Request ProcedureReturn -1 @@ -514,6 +527,8 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) BakaShrot_RefusalReason = "" BakaShrot_MessageId = 0 BakaShrot_MessagePushedAt = 0 + BakaShrot_MessageAttachmentSize = 0 + BakaShrot_MessageAttachmentReady = #False BakaShrot_MessageData = "" BakaShrot_MessageTopicId = -1 BakaShrot_MessageNodeId = -1 @@ -568,6 +583,8 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) If IsExpected BakaShrot_MessageId = *Latest\MessageId BakaShrot_MessagePushedAt = *Latest\PushedAt + BakaShrot_MessageAttachmentSize = *Latest\AttachmentSize + BakaShrot_MessageAttachmentReady = *Latest\AttachmentReady BakaShrot_MessageData = *Latest\JsonData BakaShrot_MessageTopicId = *Latest\TopicId BakaShrot_MessageNodeId = *Latest\NodeId @@ -576,6 +593,8 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) AddElement(BakaShrot_Messages()) BakaShrot_Messages()\MessageId = *Latest\MessageId BakaShrot_Messages()\PushedAt = *Latest\PushedAt + BakaShrot_Messages()\AttachmentSize = *Latest\AttachmentSize + BakaShrot_Messages()\AttachmentReady = *Latest\AttachmentReady BakaShrot_Messages()\JsonData = *Latest\JsonData EndIf FreeStructure(*Latest) @@ -633,6 +652,8 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit BakaShrot_RefusalReason = "" BakaShrot_MessageId = 0 BakaShrot_MessagePushedAt = 0 + BakaShrot_MessageAttachmentSize = 0 + BakaShrot_MessageAttachmentReady = #False BakaShrot_MessageData = "" BakaShrot_MessageTopicId = -1 BakaShrot_MessageNodeId = -1 @@ -716,6 +737,8 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit If FirstElement(BakaShrot_Messages()) BakaShrot_MessageId = BakaShrot_Messages()\MessageId BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt + BakaShrot_MessageAttachmentSize = BakaShrot_Messages()\AttachmentSize + BakaShrot_MessageAttachmentReady = BakaShrot_Messages()\AttachmentReady BakaShrot_MessageData = BakaShrot_Messages()\JsonData EndIf ProcedureReturn Count @@ -751,6 +774,8 @@ ProcedureCDLL.i BakaShrot_SelectMessage(Index.l) SelectElement(BakaShrot_Messages(), Index) BakaShrot_MessageId = BakaShrot_Messages()\MessageId BakaShrot_MessagePushedAt = BakaShrot_Messages()\PushedAt + BakaShrot_MessageAttachmentSize = BakaShrot_Messages()\AttachmentSize + BakaShrot_MessageAttachmentReady = BakaShrot_Messages()\AttachmentReady BakaShrot_MessageData = BakaShrot_Messages()\JsonData ProcedureReturn #True EndProcedure @@ -1110,3 +1135,452 @@ EndProcedure ProcedureCDLL.i BakaShrot_GetQueryResultW(*Buffer, BufferSize.i) ProcedureReturn BakaShrot_CopyString(BakaShrot_QueryResult, *Buffer, BufferSize, #PB_Unicode) EndProcedure + + +; --- Attachments ----------------------------------------------------------------- +; At most one per message, of any size the server takes (its +; MaxAttachmentSize), sent and read in parts of 1 MB, checked with their +; SHA-256 (Design/Attachments.md). The message is only stored once all of its +; attachment is: readers never see it without. + +; What BakaShrot_LoadAttachment() read, for BakaShrot_GetAttachmentData(). +Global *BakaShrot_AttachmentData = 0 +Global BakaShrot_AttachmentDataSize.q = 0 + + +; Sends *Request and returns the answer if it's a packet of AnswerType, its +; size in *AnswerSize\i. Returns 0 if the server refused it (the reason in +; BakaShrot_RefusalReason, still connected), or anything else went wrong +; (the connection is closed then). +Procedure.i BakaShrot_RequestExpecting(*Request, RequestSize.i, AnswerType.i, *AnswerSize.Integer) + Protected *Answer, Type.i, IsRefusal.i + + *Answer = BakaShrot_SendRequest(*Request, RequestSize, *AnswerSize) + If Not *Answer + ProcedureReturn 0 + EndIf + + Type = BakaShrot_GetPacketType(*Answer, *AnswerSize\i) + If Type = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_ReadRefusal(*Answer, *AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + BakaShrot_AbortConnection() + EndIf + ProcedureReturn 0 + EndIf + If Type <> AnswerType + FreeMemory(*Answer) + BakaShrot_AbortConnection() + ProcedureReturn 0 + EndIf + ProcedureReturn *Answer +EndProcedure + + +; Uploads Size bytes, read from FileId (from its start) or else from *Memory, +; as the attachment of a message about to be pushed to Topic ("" for the +; client's own). Its SHA-256 is computed first, so the file is read twice. +; Returns the upload id for BakaShrot_PushMessageToString(), 0 on failure. +Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) + Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted + Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored + Protected Hash.BakaShrot_Sha256, *Buffer, Index.q, Count.q, Bytes.i, UploadId.q, Received.q, Complete.i + Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData + + BakaShrot_RefusalReason = "" + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn 0 + EndIf + If Topic <> "" And Not BakaShrot_IsValidRef(Topic) + ProcedureReturn 0 + EndIf + If Size < 1 + BakaShrot_RefusalReason = "The attachment is empty" + ProcedureReturn 0 + EndIf + If Size > #BakaShrot_MaxAttachmentSize + BakaShrot_RefusalReason = "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(#BakaShrot_MaxAttachmentSize) + ProcedureReturn 0 + EndIf + + *Buffer = AllocateMemory(#BakaShrot_AttachmentChunkSize, #PB_Memory_NoClear) + If Not *Buffer Or Not BakaShrot_Sha256_Start(@Hash) + If *Buffer : FreeMemory(*Buffer) : EndIf + ProcedureReturn 0 + EndIf + Count = BakaShrot_AttachmentChunkCount(Size) + + ; 1. Its SHA-256. + If FileId + FileSeek(FileId, 0) + For Index = 0 To Count - 1 + Bytes = BakaShrot_AttachmentChunkBytes(Size, Index) + If ReadData(FileId, *Buffer, Bytes) <> Bytes + BakaShrot_RefusalReason = "The file couldn't be read" + FreeMemory(*Buffer) + ProcedureReturn 0 + EndIf + BakaShrot_Sha256_Add(@Hash, *Buffer, Bytes) + Next + FileSeek(FileId, 0) + Else + BakaShrot_Sha256_Add(@Hash, *Memory, Size) + EndIf + BakaShrot_Sha256_Finish(@Hash, @Start\Sha256[0]) + + ; 2. The server makes room for it. + Start\Topic = Topic + Start\Size = Size + *Request = BakaShrot_UploadStartPacket_Encode(@Start, @RequestSize) + If Not *Request + FreeMemory(*Buffer) + ProcedureReturn 0 + EndIf + *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_UploadStarted, @AnswerSize) + FreeMemory(*Request) + If Not *Answer + FreeMemory(*Buffer) + ProcedureReturn 0 + EndIf + *Started = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Started = BakaShrot_UploadStartedPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Started Or *Started\ChunkSize <> #BakaShrot_AttachmentChunkSize + If *Started : FreeStructure(*Started) : EndIf + FreeMemory(*Buffer) + BakaShrot_AbortConnection() + ProcedureReturn 0 + EndIf + UploadId = *Started\UploadId + FreeStructure(*Started) + + ; 3. Its parts, in order. + Chunk\UploadId = UploadId + For Index = 0 To Count - 1 + Bytes = BakaShrot_AttachmentChunkBytes(Size, Index) + If FileId + If ReadData(FileId, *Buffer, Bytes) <> Bytes + BakaShrot_RefusalReason = "The file couldn't be read" + FreeMemory(*Buffer) + ProcedureReturn 0 + EndIf + Chunk\Data = *Buffer + Else + Chunk\Data = *Memory + Index * #BakaShrot_AttachmentChunkSize + EndIf + Chunk\ChunkIndex = Index + Chunk\DataSize = Bytes + *Request = BakaShrot_UploadChunkPacket_Encode(@Chunk, @RequestSize) + If Not *Request + FreeMemory(*Buffer) + ProcedureReturn 0 + EndIf + *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_ChunkStored, @AnswerSize) + FreeMemory(*Request) + If Not *Answer + FreeMemory(*Buffer) + ProcedureReturn 0 + EndIf + *Stored = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Stored = BakaShrot_ChunkStoredPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Stored + FreeMemory(*Buffer) + BakaShrot_AbortConnection() + ProcedureReturn 0 + EndIf + Received = *Stored\Received + Complete = *Stored\Complete + FreeStructure(*Stored) + ; Complete exactly with the last part. + If Received <> Index * #BakaShrot_AttachmentChunkSize + Bytes Or Bool(Complete) <> Bool(Index = Count - 1) + FreeMemory(*Buffer) + BakaShrot_AbortConnection() + ProcedureReturn 0 + EndIf + Next + + FreeMemory(*Buffer) + ProcedureReturn UploadId +EndProcedure + + +; Pushes a message with the file at FilePath as its attachment, see +; BakaShrot_PushMessageToString(): the file is uploaded first, the message +; only stored once all of it is on the server. +; Returns the new message's id, or -1 on failure (refused, see +; BakaShrot_GetRefusalReason(), or the connection failed). +Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s) + Protected FileId.i, UploadId.q + + BakaShrot_RefusalReason = "" + If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize + BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) + ProcedureReturn -1 + EndIf + FileId = ReadFile(#PB_Any, FilePath, #PB_File_SharedRead) + If Not FileId + BakaShrot_RefusalReason = "Can't open '" + FilePath + "'" + ProcedureReturn -1 + EndIf + UploadId = BakaShrot_Upload(Topic, FileId, 0, Lof(FileId)) + CloseFile(FileId) + If Not UploadId + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId) +EndProcedure + +; A null *Topic is the client's own topic, a null *JsonData an empty message. +ProcedureCDLL.q BakaShrot_PushMessageWithFileA(*Topic, *JsonData, *FilePath) + Protected Topic.s, JsonData.s + If Not *FilePath + ProcedureReturn -1 + EndIf + If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf + If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf + ProcedureReturn BakaShrot_PushMessageWithFileString(Topic, JsonData, PeekS(*FilePath, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.q BakaShrot_PushMessageWithFileW(*Topic, *JsonData, *FilePath) + Protected Topic.s, JsonData.s + If Not *FilePath + ProcedureReturn -1 + EndIf + If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf + If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf + ProcedureReturn BakaShrot_PushMessageWithFileString(Topic, JsonData, PeekS(*FilePath, -1, #PB_Unicode)) +EndProcedure + + +; Same, the attachment being Size bytes at *Data. +Procedure.q BakaShrot_PushMessageWithDataString(Topic.s, JsonData.s, *Data, Size.q) + Protected UploadId.q + + BakaShrot_RefusalReason = "" + If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize + BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) + ProcedureReturn -1 + EndIf + If Not *Data + BakaShrot_RefusalReason = "The attachment is empty" + ProcedureReturn -1 + EndIf + UploadId = BakaShrot_Upload(Topic, 0, *Data, Size) + If Not UploadId + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId) +EndProcedure + +ProcedureCDLL.q BakaShrot_PushMessageWithDataA(*Topic, *JsonData, *Data, Size.q) + Protected Topic.s, JsonData.s + If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf + If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf + ProcedureReturn BakaShrot_PushMessageWithDataString(Topic, JsonData, *Data, Size) +EndProcedure + +ProcedureCDLL.q BakaShrot_PushMessageWithDataW(*Topic, *JsonData, *Data, Size.q) + Protected Topic.s, JsonData.s + If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf + If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf + ProcedureReturn BakaShrot_PushMessageWithDataString(Topic, JsonData, *Data, Size) +EndProcedure + + +; Reads the attachment of Topic:Node#MessageId, a part at a time, into FileId +; (from its start) or else into memory (*BakaShrot_AttachmentData), and +; checks its SHA-256. +; Returns its size, -1 on failure: refused (no attachment, not on this server +; yet...), a SHA-256 mismatch (refusal reason set), or the connection failed. +Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) + Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk + Protected Hash.BakaShrot_Sha256, Index.q, Count.q, Size.q, *Memory, IsValid.i + Protected Dim Expected.a(#BakaShrot_Sha256Size - 1), Dim Result.a(#BakaShrot_Sha256Size - 1) + Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData + + BakaShrot_RefusalReason = "" + If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated + ProcedureReturn -1 + EndIf + If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) Or MessageId < 1 Or Not BakaShrot_Sha256_Start(@Hash) + ProcedureReturn -1 + EndIf + + Request\Topic = Topic + Request\Node = Node + Request\MessageId = MessageId + Index = 0 + Count = 1 + While Index < Count + Request\ChunkIndex = Index + *Request = BakaShrot_GetAttachmentPacket_Encode(@Request, @RequestSize) + If Not *Request + Goto DownloadFailed + EndIf + *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_AttachmentChunk, @AnswerSize) + FreeMemory(*Request) + If Not *Answer + Goto DownloadFailed + EndIf + *Chunk = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Chunk + BakaShrot_AbortConnection() + Goto DownloadFailed + EndIf + + ; The first part tells the size and SHA-256, every other must agree. + If Index = 0 + Size = *Chunk\Size + Count = BakaShrot_AttachmentChunkCount(Size) + CopyMemory(@*Chunk\Sha256[0], @Expected(0), #BakaShrot_Sha256Size) + If Not FileId + *Memory = AllocateMemory(Size, #PB_Memory_NoClear) + If Not *Memory + BakaShrot_AttachmentChunkPacket_Free(*Chunk) + BakaShrot_RefusalReason = "Out of memory for " + Str(Size) + " bytes" + Goto DownloadFailed + EndIf + EndIf + EndIf + If *Chunk\MessageId <> MessageId Or *Chunk\ChunkIndex <> Index Or *Chunk\Size <> Size Or Not CompareMemory(@*Chunk\Sha256[0], @Expected(0), #BakaShrot_Sha256Size) Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Size, Index) + BakaShrot_AttachmentChunkPacket_Free(*Chunk) + BakaShrot_AbortConnection() + Goto DownloadFailed + EndIf + + BakaShrot_Sha256_Add(@Hash, *Chunk\Data, *Chunk\DataSize) + If FileId + If WriteData(FileId, *Chunk\Data, *Chunk\DataSize) <> *Chunk\DataSize + BakaShrot_AttachmentChunkPacket_Free(*Chunk) + BakaShrot_RefusalReason = "The file couldn't be written" + Goto DownloadFailed + EndIf + Else + CopyMemory(*Chunk\Data, *Memory + Index * #BakaShrot_AttachmentChunkSize, *Chunk\DataSize) + EndIf + BakaShrot_AttachmentChunkPacket_Free(*Chunk) + Index + 1 + Wend + + BakaShrot_Sha256_Finish(@Hash, @Result(0)) + If Not CompareMemory(@Result(0), @Expected(0), #BakaShrot_Sha256Size) + BakaShrot_RefusalReason = "The attachment doesn't match its SHA-256" + Goto DownloadFailed + EndIf + + If Not FileId + If *BakaShrot_AttachmentData + FreeMemory(*BakaShrot_AttachmentData) + EndIf + *BakaShrot_AttachmentData = *Memory + BakaShrot_AttachmentDataSize = Size + EndIf + ProcedureReturn Size + + DownloadFailed: + If *Memory + FreeMemory(*Memory) + EndIf + ProcedureReturn -1 +EndProcedure + + +; Saves the attachment of Topic:Node#MessageId to FilePath (replaced), +; checked with its SHA-256. A failed one leaves no file. +; Returns its size, -1 on failure, see BakaShrot_Download(). +Procedure.q BakaShrot_SaveAttachmentString(Topic.s, Node.s, MessageId.q, FilePath.s) + Protected FileId.i, Size.q + + FileId = CreateFile(#PB_Any, FilePath) + If Not FileId + BakaShrot_RefusalReason = "Can't create '" + FilePath + "'" + ProcedureReturn -1 + EndIf + Size = BakaShrot_Download(Topic, Node, MessageId, FileId) + CloseFile(FileId) + If Size < 0 + DeleteFile(FilePath) + EndIf + ProcedureReturn Size +EndProcedure + +ProcedureCDLL.q BakaShrot_SaveAttachmentA(*Topic, *Node, MessageId.q, *FilePath) + If Not *Topic Or Not *Node Or Not *FilePath + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, PeekS(*FilePath, -1, #PB_UTF8)) +EndProcedure + +ProcedureCDLL.q BakaShrot_SaveAttachmentW(*Topic, *Node, MessageId.q, *FilePath) + If Not *Topic Or Not *Node Or Not *FilePath + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, PeekS(*FilePath, -1, #PB_Unicode)) +EndProcedure + + +; Reads the attachment of Topic:Node#MessageId into memory, checked with its +; SHA-256, for BakaShrot_GetAttachmentData(). All of it is held at once: +; BakaShrot_SaveAttachment() for big ones. +; Returns its size, -1 on failure, see BakaShrot_Download(). +ProcedureCDLL.q BakaShrot_LoadAttachmentA(*Topic, *Node, MessageId.q) + If Not *Topic Or Not *Node + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, 0) +EndProcedure + +ProcedureCDLL.q BakaShrot_LoadAttachmentW(*Topic, *Node, MessageId.q) + If Not *Topic Or Not *Node + ProcedureReturn -1 + EndIf + ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, 0) +EndProcedure + +; Copies what the last successful BakaShrot_LoadAttachment() read into +; *Buffer, if BufferSize is enough. Returns its size (0 if none): call it +; with a null *Buffer first. +ProcedureCDLL.q BakaShrot_GetAttachmentData(*Buffer, BufferSize.q) + If *Buffer And *BakaShrot_AttachmentData And BufferSize >= BakaShrot_AttachmentDataSize + CopyMemory(*BakaShrot_AttachmentData, *Buffer, BakaShrot_AttachmentDataSize) + EndIf + ProcedureReturn BakaShrot_AttachmentDataSize +EndProcedure + +; Frees what BakaShrot_LoadAttachment() read. +ProcedureCDLL.i BakaShrot_FreeAttachmentData() + If *BakaShrot_AttachmentData + FreeMemory(*BakaShrot_AttachmentData) + EndIf + *BakaShrot_AttachmentData = 0 + BakaShrot_AttachmentDataSize = 0 + ProcedureReturn #True +EndProcedure + + +; Size in bytes of the selected message's attachment, 0 if it has none. +ProcedureCDLL.q BakaShrot_GetMessageAttachmentSize() + ProcedureReturn BakaShrot_MessageAttachmentSize +EndProcedure + +; #True if all of the selected message's attachment is on this server: a +; replicated one comes after its message. +ProcedureCDLL.i BakaShrot_IsMessageAttachmentReady() + ProcedureReturn BakaShrot_MessageAttachmentReady +EndProcedure diff --git a/Client/BakaShrot_Client_Prototypes.pbi b/Client/BakaShrot_Client_Prototypes.pbi index e711375..de23765 100644 --- a/Client/BakaShrot_Client_Prototypes.pbi +++ b/Client/BakaShrot_Client_Prototypes.pbi @@ -50,6 +50,14 @@ PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, Af PrototypeC.l BakaShrot_GetMessageCount_Prototype() PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) PrototypeC.i BakaShrot_HasMoreMessages_Prototype() +PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) +PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) +PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) +PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) +PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) +PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() +PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() +PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype @@ -86,6 +94,14 @@ Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype Global BakaShrot_GetMessageCount.BakaShrot_GetMessageCount_Prototype Global BakaShrot_SelectMessage.BakaShrot_SelectMessage_Prototype Global BakaShrot_HasMoreMessages.BakaShrot_HasMoreMessages_Prototype +Global BakaShrot_PushMessageWithFile.BakaShrot_PushMessageWithFile_Prototype +Global BakaShrot_PushMessageWithData.BakaShrot_PushMessageWithData_Prototype +Global BakaShrot_SaveAttachment.BakaShrot_SaveAttachment_Prototype +Global BakaShrot_LoadAttachment.BakaShrot_LoadAttachment_Prototype +Global BakaShrot_GetAttachmentData.BakaShrot_GetAttachmentData_Prototype +Global BakaShrot_FreeAttachmentData.BakaShrot_FreeAttachmentData_Prototype +Global BakaShrot_GetMessageAttachmentSize.BakaShrot_GetMessageAttachmentSize_Prototype +Global BakaShrot_IsMessageAttachmentReady.BakaShrot_IsMessageAttachmentReady_Prototype Global BakaShrot_ClientLibrary.i = 0 @@ -146,6 +162,14 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_GetMessageCount = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageCount") BakaShrot_SelectMessage = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SelectMessage") BakaShrot_HasMoreMessages = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_HasMoreMessages") + BakaShrot_PushMessageWithFile = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithFileW") + BakaShrot_PushMessageWithData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageWithDataW") + BakaShrot_SaveAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SaveAttachmentW") + BakaShrot_LoadAttachment = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_LoadAttachmentW") + BakaShrot_GetAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetAttachmentData") + BakaShrot_FreeAttachmentData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_FreeAttachmentData") + BakaShrot_GetMessageAttachmentSize = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageAttachmentSize") + BakaShrot_IsMessageAttachmentReady = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsMessageAttachmentReady") If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetTopicId Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect BakaShrot_UnloadClient() @@ -175,6 +199,11 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) ProcedureReturn #False EndIf + If Not BakaShrot_PushMessageWithFile Or Not BakaShrot_PushMessageWithData Or Not BakaShrot_SaveAttachment Or Not BakaShrot_LoadAttachment Or Not BakaShrot_GetAttachmentData Or Not BakaShrot_FreeAttachmentData Or Not BakaShrot_GetMessageAttachmentSize Or Not BakaShrot_IsMessageAttachmentReady + BakaShrot_UnloadClient() + ProcedureReturn #False + EndIf + ProcedureReturn #True EndProcedure diff --git a/Commons/Cryptography/Libsodium.pbi b/Commons/Cryptography/Libsodium.pbi index 398bbae..09bb490 100644 --- a/Commons/Cryptography/Libsodium.pbi +++ b/Commons/Cryptography/Libsodium.pbi @@ -135,6 +135,14 @@ CompilerEndIf crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey) crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey) + ; SHA-256, a piece at a time: _init() a state (crypto_hash_sha256_statebytes() + ; bytes), _update() it with each piece, _final() writes the 32-byte hash. + ; For the attachments' checksums, see BakaShrot_Sha256_* below. + crypto_hash_sha256_statebytes.i() + crypto_hash_sha256_init.l(*State) + crypto_hash_sha256_update.l(*State, *Data, DataLength.q) + crypto_hash_sha256_final.l(*State, *Hash) + EndImport @@ -183,6 +191,34 @@ Procedure.i DecodeData(*Data, DataLength.i, *PublicKey, *Signature) EndProcedure +; SHA-256 of data given a piece at a time (an attachment's parts): Start, Add +; each piece, then Finish writes the 32-byte hash. +#BakaShrot_Sha256_HashSize = 32 + +Structure BakaShrot_Sha256 + ; crypto_hash_sha256_state is 104 bytes, checked by Start. + State.a[128] +EndStructure + +; Returns #False if libsodium's state doesn't fit (a libsodium change). +Procedure.i BakaShrot_Sha256_Start(*Hash.BakaShrot_Sha256) + If crypto_hash_sha256_statebytes() > SizeOf(BakaShrot_Sha256) + ProcedureReturn #False + EndIf + ProcedureReturn Bool(crypto_hash_sha256_init(*Hash) = 0) +EndProcedure + +Procedure BakaShrot_Sha256_Add(*Hash.BakaShrot_Sha256, *Data, Size.i) + If Size > 0 + crypto_hash_sha256_update(*Hash, *Data, Size) + EndIf +EndProcedure + +Procedure BakaShrot_Sha256_Finish(*Hash.BakaShrot_Sha256, *Out) + crypto_hash_sha256_final(*Hash, *Out) +EndProcedure + + ; Encodes KeySize raw bytes at *Key as a Base64 string, for storing a key in ; the ini file (PrivateKey / PublicKey fields in Config.pbi). Procedure.s EncodeKeyToString(*Key, KeySize.i) diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi index 3a7957a..be4945a 100644 --- a/Commons/Networking/Connections.pbi +++ b/Commons/Networking/Connections.pbi @@ -31,6 +31,10 @@ ; C->S QueryRequest -> S->C QueryResult or RequestRefused ; C->S ResolveName -> S->C NameResolved or RequestRefused ; C->S ListNames -> S->C NamesList +; C->S UploadStart -> S->C UploadStarted or RequestRefused +; C->S UploadChunk -> S->C ChunkStored or RequestRefused +; then a PushMessage with the UploadId attaches it to the message +; C->S GetAttachment -> S->C AttachmentChunk or RequestRefused ; Topics and nodes are given by name or id, see Names.pbi. ; A refusal keeps the connection open, a malformed or unexpected packet ; still aborts it. @@ -39,6 +43,9 @@ ; link it opened to the server: ; P->S SyncStateRequest -> S->P SyncState or RequestRefused ; P->S ReplicateMessages -> S->P MessagePushed (last id) or RequestRefused +; once the messages are caught up: +; P->S MissingAttachmentsRequest -> S->P MissingAttachments or RequestRefused +; P->S ReplicateAttachmentChunk -> S->P ChunkStored or RequestRefused ; ; ; Framing: every packet is sent as its size (4 bytes, little-endian), @@ -73,6 +80,15 @@ XIncludeFile "Packets/ListNamesPacket.pbi" XIncludeFile "Packets/NamesListPacket.pbi" XIncludeFile "Packets/GetMessagesPacket.pbi" XIncludeFile "Packets/MessagesPacket.pbi" +XIncludeFile "Packets/UploadStartPacket.pbi" +XIncludeFile "Packets/UploadStartedPacket.pbi" +XIncludeFile "Packets/UploadChunkPacket.pbi" +XIncludeFile "Packets/ChunkStoredPacket.pbi" +XIncludeFile "Packets/GetAttachmentPacket.pbi" +XIncludeFile "Packets/AttachmentChunkPacket.pbi" +XIncludeFile "Packets/MissingAttachmentsRequestPacket.pbi" +XIncludeFile "Packets/MissingAttachmentsPacket.pbi" +XIncludeFile "Packets/ReplicateAttachmentChunkPacket.pbi" ; Reads the type of a received packet, to know which decoder to use. diff --git a/Commons/Networking/Packets.pbi b/Commons/Networking/Packets.pbi index 00deffe..d9810ce 100644 --- a/Commons/Networking/Packets.pbi +++ b/Commons/Networking/Packets.pbi @@ -20,7 +20,8 @@ EndStructure ; 3: the Hello sealed for the server, a key per connection, everything after ; the ChallengeRequest encrypted (Connections.pbi). Messages carry when ; they were pushed (PushedAt). -#BakaShrot_ProtocolVersion = 3 +; 4: attachments (Design/Attachments.md). +#BakaShrot_ProtocolVersion = 4 ; Size in bytes of the nonce sent in a challenge request and echoed in its response. ; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the @@ -50,6 +51,32 @@ Procedure.i BakaShrot_IsValidTimestamp(Timestamp.q) ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp) EndProcedure +; Attachments (Design/Attachments.md): at most one per message, sent and +; stored in parts of #BakaShrot_AttachmentChunkSize bytes (the last one what's +; left), checked with their SHA-256. #BakaShrot_MaxAttachmentSize is the +; protocol's limit, each server sets its own ([BakaShrot.Server] +; MaxAttachmentSize). +#BakaShrot_AttachmentChunkSize = 1048576 +#BakaShrot_MaxAttachmentSize = 1099511627776 +#BakaShrot_MaxAttachmentChunks = #BakaShrot_MaxAttachmentSize / #BakaShrot_AttachmentChunkSize +#BakaShrot_Sha256Size = 32 + +; How many parts Size bytes take. +Procedure.q BakaShrot_AttachmentChunkCount(Size.q) + ProcedureReturn (Size + #BakaShrot_AttachmentChunkSize - 1) / #BakaShrot_AttachmentChunkSize +EndProcedure + +; How big part Index of Size bytes is, 0 if there's no such part. +Procedure.i BakaShrot_AttachmentChunkBytes(Size.q, Index.q) + Protected Left.q = Size - Index * #BakaShrot_AttachmentChunkSize + If Index < 0 Or Left <= 0 + ProcedureReturn 0 + ElseIf Left > #BakaShrot_AttachmentChunkSize + ProcedureReturn #BakaShrot_AttachmentChunkSize + EndIf + ProcedureReturn Left +EndProcedure + ; Biggest packet accepted on the wire once authenticated, anything bigger ; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize ; (Connections.pbi). @@ -97,6 +124,20 @@ Enumeration BakaShrot_PacketTypes ; A run of messages of a topic/node, only accepted once authenticated. #BakaShrot_PacketType_GetMessages = 22 #BakaShrot_PacketType_Messages = 23 + + ; Attachments, only accepted once authenticated: uploading one (before + ; its PushMessage), and reading one, in parts. + #BakaShrot_PacketType_UploadStart = 24 + #BakaShrot_PacketType_UploadStarted = 25 + #BakaShrot_PacketType_UploadChunk = 26 + #BakaShrot_PacketType_ChunkStored = 27 + #BakaShrot_PacketType_GetAttachment = 28 + #BakaShrot_PacketType_AttachmentChunk = 29 + + ; Replicating attachments, only accepted from peers, once their messages are. + #BakaShrot_PacketType_MissingAttachmentsRequest = 30 + #BakaShrot_PacketType_MissingAttachments = 31 + #BakaShrot_PacketType_ReplicateAttachmentChunk = 32 EndEnumeration diff --git a/Commons/Networking/Packets/AttachmentChunkPacket.pbi b/Commons/Networking/Packets/AttachmentChunkPacket.pbi new file mode 100644 index 0000000..d4fbcd6 --- /dev/null +++ b/Commons/Networking/Packets/AttachmentChunkPacket.pbi @@ -0,0 +1,195 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; S2C, answers a GetAttachment: part ChunkIndex of the attachment of +; TopicId:NodeId#MessageId (the server's ids), Size bytes in all, in parts of +; #BakaShrot_AttachmentChunkSize, whose SHA-256 is Sha256. +Structure BakaShrot_AttachmentChunk Extends BakaShrot_PacketBase + TopicId.l + NodeId.l + MessageId.q + Size.q + Sha256.a[#BakaShrot_Sha256Size] + ChunkIndex.l + *Data + DataSize.l +EndStructure + + +; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_AttachmentChunkPacket_Encode(*Chunk.BakaShrot_AttachmentChunk, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Chunk\Magic = #BakaShrot_ProtocolMagic + *Chunk\Version = #BakaShrot_ProtocolVersion + *Chunk\PacketType = #BakaShrot_PacketType_AttachmentChunk + + If *Chunk\TopicId < 0 Or *Chunk\TopicId > #BakaShrot_MaxId Or *Chunk\NodeId < 0 Or *Chunk\NodeId > #BakaShrot_MaxId Or *Chunk\MessageId < 1 Or *Chunk\Size < 1 Or *Chunk\Size > #BakaShrot_MaxAttachmentSize Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\TopicId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\NodeId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\Size) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Frees a decoded *Chunk and the data it holds. +Procedure BakaShrot_AttachmentChunkPacket_Free(*Chunk.BakaShrot_AttachmentChunk) + If Not *Chunk + ProcedureReturn + EndIf + If *Chunk\Data + FreeMemory(*Chunk\Data) + EndIf + FreeStructure(*Chunk) +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_AttachmentChunkPacket_Free(). +Procedure.i BakaShrot_AttachmentChunkPacket_Decode(*MsgPackData.MsgPackData) + Protected *Chunk.BakaShrot_AttachmentChunk, Value.q, ReadSize.q + + *Chunk = AllocateStructure(BakaShrot_AttachmentChunk) + If Not *Chunk + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_AttachmentChunk + Goto DecodeFailed + EndIf + + ; TopicId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId + Goto DecodeFailed + EndIf + *Chunk\TopicId = Value + + ; NodeId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId + Goto DecodeFailed + EndIf + *Chunk\NodeId = Value + + ; MessageId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 + Goto DecodeFailed + EndIf + *Chunk\MessageId = Value + + ; Size + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize + Goto DecodeFailed + EndIf + *Chunk\Size = Value + + ; Sha256 + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary + Goto DecodeFailed + EndIf + ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. + ReadSize = MsgPackReadBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size + Goto DecodeFailed + EndIf + + ; ChunkIndex + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks + Goto DecodeFailed + EndIf + *Chunk\ChunkIndex = Value + + ; Data + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary + Goto DecodeFailed + EndIf + ; A copy, freed with the packet (_Free()). + *Chunk\Data = MsgPackCopyBinary(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data + Goto DecodeFailed + EndIf + *Chunk\DataSize = MemorySize(*Chunk\Data) + If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize + Goto DecodeFailed + EndIf + + ProcedureReturn *Chunk + + ; Everything read so far is tainted, drop it. + DecodeFailed: + BakaShrot_AttachmentChunkPacket_Free(*Chunk) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/ChunkStoredPacket.pbi b/Commons/Networking/Packets/ChunkStoredPacket.pbi new file mode 100644 index 0000000..f2923fd --- /dev/null +++ b/Commons/Networking/Packets/ChunkStoredPacket.pbi @@ -0,0 +1,104 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; S2C (and S2P), answers an UploadChunk (or a ReplicateAttachmentChunk): Received +; bytes are stored so far. Complete is 1 once they all are, and their SHA-256 +; checked out. +Structure BakaShrot_ChunkStored Extends BakaShrot_PacketBase + Received.q + Complete.l +EndStructure + + +; Encodes *Stored into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_ChunkStoredPacket_Encode(*Stored.BakaShrot_ChunkStored, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Stored\Magic = #BakaShrot_ProtocolMagic + *Stored\Version = #BakaShrot_ProtocolVersion + *Stored\PacketType = #BakaShrot_PacketType_ChunkStored + + If *Stored\Received < 0 Or *Stored\Received > #BakaShrot_MaxAttachmentSize Or *Stored\Complete < 0 Or *Stored\Complete > 1 + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(64) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Stored, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Stored\Received) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Stored\Complete) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. +Procedure.i BakaShrot_ChunkStoredPacket_Decode(*MsgPackData.MsgPackData) + Protected *Stored.BakaShrot_ChunkStored, Value.q + + *Stored = AllocateStructure(BakaShrot_ChunkStored) + If Not *Stored + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Stored, *MsgPackData) Or *Stored\PacketType <> #BakaShrot_PacketType_ChunkStored + Goto DecodeFailed + EndIf + + ; Received + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentSize + Goto DecodeFailed + EndIf + *Stored\Received = Value + + ; Complete + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1 + Goto DecodeFailed + EndIf + *Stored\Complete = Value + + ProcedureReturn *Stored + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Stored) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/GetAttachmentPacket.pbi b/Commons/Networking/Packets/GetAttachmentPacket.pbi new file mode 100644 index 0000000..f329691 --- /dev/null +++ b/Commons/Networking/Packets/GetAttachmentPacket.pbi @@ -0,0 +1,134 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; C2S, asks for part ChunkIndex (0 for the first) of the attachment of a message. +; Topic, Node: each a name or an id in digits, as GetMessages'. ReadTopics must +; allow the topic. +; Answered with an AttachmentChunk, or a RequestRefused (no such message, no +; attachment, or not here yet: replicated attachments come after their message). +Structure BakaShrot_GetAttachment Extends BakaShrot_PacketBase + Topic.s + Node.s + MessageId.q + ChunkIndex.l +EndStructure + + +; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_GetAttachmentPacket_Encode(*Request.BakaShrot_GetAttachment, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Request\Magic = #BakaShrot_ProtocolMagic + *Request\Version = #BakaShrot_ProtocolVersion + *Request\PacketType = #BakaShrot_PacketType_GetAttachment + + If *Request\MessageId < 1 Or *Request\ChunkIndex < 0 Or *Request\ChunkIndex > #BakaShrot_MaxAttachmentChunks + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(64) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Request\MessageId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Request\ChunkIndex) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. +Procedure.i BakaShrot_GetAttachmentPacket_Decode(*MsgPackData.MsgPackData) + Protected *Request.BakaShrot_GetAttachment, Value.q + + *Request = AllocateStructure(BakaShrot_GetAttachment) + If Not *Request + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetAttachment + Goto DecodeFailed + EndIf + + ; Topic + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Request\Topic = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success + Goto DecodeFailed + EndIf + + ; Node + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Request\Node = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success + Goto DecodeFailed + EndIf + + ; MessageId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 + Goto DecodeFailed + EndIf + *Request\MessageId = Value + + ; ChunkIndex + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks + Goto DecodeFailed + EndIf + *Request\ChunkIndex = Value + + ProcedureReturn *Request + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Request) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/LatestMessagePacket.pbi b/Commons/Networking/Packets/LatestMessagePacket.pbi index 933cb47..fe6a3ac 100644 --- a/Commons/Networking/Packets/LatestMessagePacket.pbi +++ b/Commons/Networking/Packets/LatestMessagePacket.pbi @@ -17,6 +17,10 @@ Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase MessageId.q PushedAt.q JsonData.s + ; Its attachment's size in bytes, 0 for none, and whether this server has + ; all of it yet (a replicated one comes after its message). + AttachmentSize.q + AttachmentReady.l EndStructure @@ -65,6 +69,12 @@ Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentReady) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf ; Frees *MsgPackData on success, leaves it untouched on failure. *Buffer = MsgPackFinalize(*MsgPackData) @@ -161,6 +171,23 @@ Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData) If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Goto DecodeFailed EndIf + ; AttachmentSize + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Latest\AttachmentSize = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentSize < 0 Or *Latest\AttachmentSize > #BakaShrot_MaxAttachmentSize + Goto DecodeFailed + EndIf + + ; AttachmentReady + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Latest\AttachmentReady = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentReady < 0 Or *Latest\AttachmentReady > 1 + Goto DecodeFailed + EndIf ProcedureReturn *Latest diff --git a/Commons/Networking/Packets/MessagesPacket.pbi b/Commons/Networking/Packets/MessagesPacket.pbi index 2eafad1..651ffd4 100644 --- a/Commons/Networking/Packets/MessagesPacket.pbi +++ b/Commons/Networking/Packets/MessagesPacket.pbi @@ -11,6 +11,10 @@ Structure BakaShrot_MessagesEntry MessageId.q ; When it was pushed, see Packets.pbi. PushedAt.q + ; Its attachment's size in bytes, 0 for none, and whether this server has + ; all of it yet (a replicated one comes after its message). + AttachmentSize.q + AttachmentReady.l JsonData.s EndStructure @@ -21,7 +25,7 @@ EndStructure ; Encoded size of the answer's own fields, and of each message on top of its ; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize. #BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2) -#BakaShrot_MessagesMessageOverhead = 25 +#BakaShrot_MessagesMessageOverhead = 40 ; S2C, answers a GetMessages with the messages of that topic/node combination ; stored after the asked id, in message id order: as many as were asked for, @@ -99,6 +103,12 @@ Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentReady) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf Next ; Frees *MsgPackData on success, leaves it untouched on failure. @@ -222,6 +232,23 @@ Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData) If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Goto DecodeFailed EndIf + ; AttachmentSize + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Answer\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentSize < 0 Or *Answer\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize + Goto DecodeFailed + EndIf + + ; AttachmentReady + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Answer\Messages()\AttachmentReady = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentReady < 0 Or *Answer\Messages()\AttachmentReady > 1 + Goto DecodeFailed + EndIf Next ProcedureReturn *Answer diff --git a/Commons/Networking/Packets/MissingAttachmentsPacket.pbi b/Commons/Networking/Packets/MissingAttachmentsPacket.pbi new file mode 100644 index 0000000..58e5947 --- /dev/null +++ b/Commons/Networking/Packets/MissingAttachmentsPacket.pbi @@ -0,0 +1,156 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; Most attachments one MissingAttachments lists, the next check-in asks again. +#BakaShrot_MaxMissingAttachments = 256 + +; One attachment the server is missing: of Topic:Node#MessageId (names, never +; digits), from part NextChunk on (0 if it has none of it yet). +Structure BakaShrot_MissingAttachment + Topic.s + Node.s + MessageId.q + NextChunk.l +EndStructure + +; S2P, answers a MissingAttachmentsRequest: attachments of messages the server +; has, that it takes from this peer, and doesn't have all of yet. Maybe none. +; On the wire: the count, then each one's topic, node, message id and next chunk. +Structure BakaShrot_MissingAttachments Extends BakaShrot_PacketBase + List Attachments.BakaShrot_MissingAttachment() +EndStructure + + +; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_MissingAttachmentsPacket_Encode(*Answer.BakaShrot_MissingAttachments, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Answer\Magic = #BakaShrot_ProtocolMagic + *Answer\Version = #BakaShrot_ProtocolVersion + *Answer\PacketType = #BakaShrot_PacketType_MissingAttachments + + If ListSize(*Answer\Attachments()) > #BakaShrot_MaxMissingAttachments + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(256) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Attachments())) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + ForEach *Answer\Attachments() + If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Topic) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Node) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\MessageId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\NextChunk) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + Next + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. +Procedure.i BakaShrot_MissingAttachmentsPacket_Decode(*MsgPackData.MsgPackData) + Protected *Answer.BakaShrot_MissingAttachments + Protected Value.q, Count.q, i.q + + *Answer = AllocateStructure(BakaShrot_MissingAttachments) + If Not *Answer + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_MissingAttachments + Goto DecodeFailed + EndIf + + ; Count + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Count = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxMissingAttachments + Goto DecodeFailed + EndIf + + For i = 1 To Count + AddElement(*Answer\Attachments()) + + ; Topic + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Answer\Attachments()\Topic = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Topic) + Goto DecodeFailed + EndIf + + ; Node + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Answer\Attachments()\Node = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Node) + Goto DecodeFailed + EndIf + + ; MessageId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Answer\Attachments()\MessageId = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Attachments()\MessageId < 1 + Goto DecodeFailed + EndIf + + ; NextChunk + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks + Goto DecodeFailed + EndIf + *Answer\Attachments()\NextChunk = Value + Next + + ProcedureReturn *Answer + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Answer) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi b/Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi new file mode 100644 index 0000000..fa3640f --- /dev/null +++ b/Commons/Networking/Packets/MissingAttachmentsRequestPacket.pbi @@ -0,0 +1,71 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; P2S, asks which attachments the server is still missing from this peer, once +; the messages are caught up. Only the base fields. +; Answered with a MissingAttachments, or a RequestRefused. +Structure BakaShrot_MissingAttachmentsRequest Extends BakaShrot_PacketBase + +EndStructure + + +; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Encode(*Request.BakaShrot_MissingAttachmentsRequest, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Request\Magic = #BakaShrot_ProtocolMagic + *Request\Version = #BakaShrot_ProtocolVersion + *Request\PacketType = #BakaShrot_PacketType_MissingAttachmentsRequest + + *MsgPackData = MsgPackCreate(64) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Request, *MsgPackData) + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. +Procedure.i BakaShrot_MissingAttachmentsRequestPacket_Decode(*MsgPackData.MsgPackData) + Protected *Request.BakaShrot_MissingAttachmentsRequest + + *Request = AllocateStructure(BakaShrot_MissingAttachmentsRequest) + If Not *Request + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_MissingAttachmentsRequest + Goto DecodeFailed + EndIf + + ProcedureReturn *Request + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Request) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/PushMessagePacket.pbi b/Commons/Networking/Packets/PushMessagePacket.pbi index 71e9128..ec4de42 100644 --- a/Commons/Networking/Packets/PushMessagePacket.pbi +++ b/Commons/Networking/Packets/PushMessagePacket.pbi @@ -10,10 +10,12 @@ XIncludeFile "../Packets.pbi" ; "" for the topic of the client's authenticated identity. The client's ; [BakaShrot.Client.] PushTopics must allow it. ; The node is always the client's authenticated one, the client can't pick it. +; UploadId: the attachment uploaded for it (UploadStart, all of it stored), 0 for none. ; Answered with a MessagePushed or a RequestRefused. Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase Topic.s JsonData.s + UploadId.q EndStructure @@ -44,6 +46,10 @@ Procedure.i BakaShrot_PushMessagePacket_Encode(*Push.BakaShrot_PushMessage, *Out Goto EncodeFailed EndIf + If *Push\UploadId < 0 Or MsgPackWriteInteger(*MsgPackData, *Push\UploadId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + ; Frees *MsgPackData on success, leaves it untouched on failure. *Buffer = MsgPackFinalize(*MsgPackData) If Not *Buffer @@ -92,6 +98,15 @@ Procedure.i BakaShrot_PushMessagePacket_Decode(*MsgPackData.MsgPackData) Goto DecodeFailed EndIf + ; UploadId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Push\UploadId = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Push\UploadId < 0 + Goto DecodeFailed + EndIf + ProcedureReturn *Push ; Everything read so far is tainted, drop it. diff --git a/Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi b/Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi new file mode 100644 index 0000000..639f2be --- /dev/null +++ b/Commons/Networking/Packets/ReplicateAttachmentChunkPacket.pbi @@ -0,0 +1,164 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; P2S, part ChunkIndex of the attachment of Topic:Node#MessageId (names, never +; digits), a message the server already has, as MissingAttachments asked for. +; The size and SHA-256 came with the message (ReplicateMessages). +; Answered with a ChunkStored, or a RequestRefused. +Structure BakaShrot_ReplicateAttachmentChunk Extends BakaShrot_PacketBase + Topic.s + Node.s + MessageId.q + ChunkIndex.l + *Data + DataSize.l +EndStructure + + +; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Encode(*Chunk.BakaShrot_ReplicateAttachmentChunk, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Chunk\Magic = #BakaShrot_ProtocolMagic + *Chunk\Version = #BakaShrot_ProtocolVersion + *Chunk\PacketType = #BakaShrot_PacketType_ReplicateAttachmentChunk + + If Not BakaShrot_IsValidName(*Chunk\Topic) Or Not BakaShrot_IsValidName(*Chunk\Node) Or *Chunk\MessageId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteString(*MsgPackData, *Chunk\Topic) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteString(*MsgPackData, *Chunk\Node) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Frees a decoded *Chunk and the data it holds. +Procedure BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk.BakaShrot_ReplicateAttachmentChunk) + If Not *Chunk + ProcedureReturn + EndIf + If *Chunk\Data + FreeMemory(*Chunk\Data) + EndIf + FreeStructure(*Chunk) +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_ReplicateAttachmentChunkPacket_Free(). +Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Decode(*MsgPackData.MsgPackData) + Protected *Chunk.BakaShrot_ReplicateAttachmentChunk, Value.q + + *Chunk = AllocateStructure(BakaShrot_ReplicateAttachmentChunk) + If Not *Chunk + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_ReplicateAttachmentChunk + Goto DecodeFailed + EndIf + + ; Topic + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Chunk\Topic = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Topic) + Goto DecodeFailed + EndIf + + ; Node + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Chunk\Node = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Node) + Goto DecodeFailed + EndIf + + ; MessageId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 + Goto DecodeFailed + EndIf + *Chunk\MessageId = Value + + ; ChunkIndex + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks + Goto DecodeFailed + EndIf + *Chunk\ChunkIndex = Value + + ; Data + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary + Goto DecodeFailed + EndIf + ; A copy, freed with the packet (_Free()). + *Chunk\Data = MsgPackCopyBinary(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data + Goto DecodeFailed + EndIf + *Chunk\DataSize = MemorySize(*Chunk\Data) + If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize + Goto DecodeFailed + EndIf + + ProcedureReturn *Chunk + + ; Everything read so far is tainted, drop it. + DecodeFailed: + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi index 6b564fa..53667ff 100644 --- a/Commons/Networking/Packets/ReplicateMessagesPacket.pbi +++ b/Commons/Networking/Packets/ReplicateMessagesPacket.pbi @@ -7,10 +7,15 @@ XIncludeFile "../Packets.pbi" ; One message of a ReplicateMessages batch. ; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is. +; AttachmentSize, AttachmentSha256: its attachment's, 0 for none. The data +; itself follows on its own, once the messages are caught up +; (MissingAttachments, ReplicateAttachmentChunk). Structure BakaShrot_ReplicatedMessage MessageId.q PushedAt.q JsonData.s + AttachmentSize.q + AttachmentSha256.a[#BakaShrot_Sha256Size] EndStructure ; Most messages a batch may carry, whatever the sender's PeerBatchSize. @@ -26,14 +31,15 @@ EndStructure ; Encoded size of a batch's own fields, and of each message on top of its ; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize. #BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2) -#BakaShrot_ReplicateMessageOverhead = 25 +#BakaShrot_ReplicateMessageOverhead = 70 ; Peer -> Server, messages the server is missing for one topic/node, in ; message id order, with the message ids they were stored under on their ; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi): ; the server stores them under its own ids for those names, and refuses ; names it doesn't know. -; On the wire: topic, node, message count, then each message's id, PushedAt and JSON. +; On the wire: topic, node, message count, then each message's id, PushedAt, +; JSON, attachment size and SHA-256. ; Answered with a MessagePushed carrying the last message's id, or a RequestRefused. Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase Topic.s @@ -87,6 +93,17 @@ Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateM If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\AttachmentSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + ; Empty without an attachment. + If *Batch\Messages()\AttachmentSize > 0 + If MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + ElseIf MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], 0) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf Next ; Frees *MsgPackData on success, leaves it untouched on failure. @@ -109,7 +126,7 @@ EndProcedure ; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData) Protected *Batch.BakaShrot_ReplicateMessages - Protected Value.q, Count.q, i.q, PreviousMessageId.q + Protected Value.q, Count.q, i.q, PreviousMessageId.q, ReadSize.q *Batch = AllocateStructure(BakaShrot_ReplicateMessages) If Not *Batch @@ -180,6 +197,23 @@ Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData) If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Goto DecodeFailed EndIf + ; AttachmentSize + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + *Batch\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\AttachmentSize < 0 Or *Batch\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize + Goto DecodeFailed + EndIf + + ; AttachmentSha256: 32 bytes with an attachment, empty without. + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary + Goto DecodeFailed + EndIf + ReadSize = MsgPackReadBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (ReadSize <> #BakaShrot_Sha256Size And *Batch\Messages()\AttachmentSize > 0) Or (ReadSize <> 0 And *Batch\Messages()\AttachmentSize = 0) + Goto DecodeFailed + EndIf Next ProcedureReturn *Batch diff --git a/Commons/Networking/Packets/UploadChunkPacket.pbi b/Commons/Networking/Packets/UploadChunkPacket.pbi new file mode 100644 index 0000000..5ca8c9c --- /dev/null +++ b/Commons/Networking/Packets/UploadChunkPacket.pbi @@ -0,0 +1,134 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; C2S, the next part of an upload: ChunkIndex (0 for the first) of UploadId. +; Answered with a ChunkStored, or a RequestRefused (the upload is then dropped). +Structure BakaShrot_UploadChunk Extends BakaShrot_PacketBase + UploadId.q + ChunkIndex.l + *Data + DataSize.l +EndStructure + + +; Encodes *Chunk into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_UploadChunkPacket_Encode(*Chunk.BakaShrot_UploadChunk, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Chunk\Magic = #BakaShrot_ProtocolMagic + *Chunk\Version = #BakaShrot_ProtocolVersion + *Chunk\PacketType = #BakaShrot_PacketType_UploadChunk + + If *Chunk\UploadId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\UploadId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Frees a decoded *Chunk and the data it holds. +Procedure BakaShrot_UploadChunkPacket_Free(*Chunk.BakaShrot_UploadChunk) + If Not *Chunk + ProcedureReturn + EndIf + If *Chunk\Data + FreeMemory(*Chunk\Data) + EndIf + FreeStructure(*Chunk) +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with BakaShrot_UploadChunkPacket_Free(). +Procedure.i BakaShrot_UploadChunkPacket_Decode(*MsgPackData.MsgPackData) + Protected *Chunk.BakaShrot_UploadChunk, Value.q + + *Chunk = AllocateStructure(BakaShrot_UploadChunk) + If Not *Chunk + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_UploadChunk + Goto DecodeFailed + EndIf + + ; UploadId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 + Goto DecodeFailed + EndIf + *Chunk\UploadId = Value + + ; ChunkIndex + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxAttachmentChunks + Goto DecodeFailed + EndIf + *Chunk\ChunkIndex = Value + + ; Data + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary + Goto DecodeFailed + EndIf + ; A copy, freed with the packet (_Free()). + *Chunk\Data = MsgPackCopyBinary(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data + Goto DecodeFailed + EndIf + *Chunk\DataSize = MemorySize(*Chunk\Data) + If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize + Goto DecodeFailed + EndIf + + ProcedureReturn *Chunk + + ; Everything read so far is tainted, drop it. + DecodeFailed: + BakaShrot_UploadChunkPacket_Free(*Chunk) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/UploadStartPacket.pbi b/Commons/Networking/Packets/UploadStartPacket.pbi new file mode 100644 index 0000000..d3c5034 --- /dev/null +++ b/Commons/Networking/Packets/UploadStartPacket.pbi @@ -0,0 +1,121 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; C2S, starts uploading an attachment, before pushing the message it goes with +; (PushMessage's UploadId): Size bytes (1 to #BakaShrot_MaxAttachmentSize, and the +; server's [BakaShrot.Server] MaxAttachmentSize), whose SHA-256 is Sha256. +; Topic: where the message will be pushed, as PushMessage's: "" for the client's +; own. The client's PushTopics must allow it. +; Answered with an UploadStarted, or a RequestRefused. +Structure BakaShrot_UploadStart Extends BakaShrot_PacketBase + Topic.s + Size.q + Sha256.a[#BakaShrot_Sha256Size] +EndStructure + + +; Encodes *Start into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_UploadStartPacket_Encode(*Start.BakaShrot_UploadStart, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Start\Magic = #BakaShrot_ProtocolMagic + *Start\Version = #BakaShrot_ProtocolVersion + *Start\PacketType = #BakaShrot_PacketType_UploadStart + + If *Start\Size < 1 Or *Start\Size > #BakaShrot_MaxAttachmentSize + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(64) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Start, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteString(*MsgPackData, *Start\Topic) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Start\Size) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. +Procedure.i BakaShrot_UploadStartPacket_Decode(*MsgPackData.MsgPackData) + Protected *Start.BakaShrot_UploadStart, Value.q, ReadSize.q + + *Start = AllocateStructure(BakaShrot_UploadStart) + If Not *Start + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Start, *MsgPackData) Or *Start\PacketType <> #BakaShrot_PacketType_UploadStart + Goto DecodeFailed + EndIf + + ; Topic + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String + Goto DecodeFailed + EndIf + *Start\Topic = MsgPackReadString(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success + Goto DecodeFailed + EndIf + + ; Size + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxAttachmentSize + Goto DecodeFailed + EndIf + *Start\Size = Value + + ; Sha256 + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary + Goto DecodeFailed + EndIf + ; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check. + ReadSize = MsgPackReadBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size + Goto DecodeFailed + EndIf + + ProcedureReturn *Start + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Start) + ProcedureReturn 0 +EndProcedure diff --git a/Commons/Networking/Packets/UploadStartedPacket.pbi b/Commons/Networking/Packets/UploadStartedPacket.pbi new file mode 100644 index 0000000..d0eeac9 --- /dev/null +++ b/Commons/Networking/Packets/UploadStartedPacket.pbi @@ -0,0 +1,103 @@ +; ============================================================================ +; ... +; ============================================================================ + + +XIncludeFile "../Packets.pbi" + +; S2C, answers an UploadStart: send the data with UploadChunks for UploadId, in +; order, ChunkSize bytes each (the last one what's left). +Structure BakaShrot_UploadStarted Extends BakaShrot_PacketBase + UploadId.q + ChunkSize.l +EndStructure + + +; Encodes *Started into a freshly allocated buffer, its base fields are set by this procedure. +; *OutSize receives its size in bytes. +; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory. +Procedure.i BakaShrot_UploadStartedPacket_Encode(*Started.BakaShrot_UploadStarted, *OutSize.Integer) + Protected *MsgPackData.MsgPackData, *Buffer + + *Started\Magic = #BakaShrot_ProtocolMagic + *Started\Version = #BakaShrot_ProtocolVersion + *Started\PacketType = #BakaShrot_PacketType_UploadStarted + + If *Started\UploadId < 1 Or *Started\ChunkSize < 1 Or *Started\ChunkSize > #BakaShrot_AttachmentChunkSize + ProcedureReturn 0 + EndIf + + *MsgPackData = MsgPackCreate(64) + If Not *MsgPackData + ProcedureReturn 0 + EndIf + + If Not BakaShrot_WritePacketBase(*Started, *MsgPackData) + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Started\UploadId) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + If MsgPackWriteInteger(*MsgPackData, *Started\ChunkSize) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + + ; Frees *MsgPackData on success, leaves it untouched on failure. + *Buffer = MsgPackFinalize(*MsgPackData) + If Not *Buffer + Goto EncodeFailed + EndIf + + *OutSize\i = MemorySize(*Buffer) + ProcedureReturn *Buffer + + EncodeFailed: + MsgPackFree(*MsgPackData, #True) + ProcedureReturn 0 +EndProcedure + +; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct. +; *MsgPackData stays owned by the caller, and should be discarded on failure. +; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. +Procedure.i BakaShrot_UploadStartedPacket_Decode(*MsgPackData.MsgPackData) + Protected *Started.BakaShrot_UploadStarted, Value.q + + *Started = AllocateStructure(BakaShrot_UploadStarted) + If Not *Started + ProcedureReturn 0 + EndIf + + ; The base parser doesn't check which packet it is, that's on us. + If Not BakaShrot_ReadPacketBase(*Started, *MsgPackData) Or *Started\PacketType <> #BakaShrot_PacketType_UploadStarted + Goto DecodeFailed + EndIf + + ; UploadId + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 + Goto DecodeFailed + EndIf + *Started\UploadId = Value + + ; ChunkSize + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_AttachmentChunkSize + Goto DecodeFailed + EndIf + *Started\ChunkSize = Value + + ProcedureReturn *Started + + ; Everything read so far is tainted, drop it. + DecodeFailed: + FreeStructure(*Started) + ProcedureReturn 0 +EndProcedure diff --git a/Design/Attachments.md b/Design/Attachments.md new file mode 100644 index 0000000..26b68bc --- /dev/null +++ b/Design/Attachments.md @@ -0,0 +1,162 @@ +# Attachments + +A message can have **one attachment**: any bytes (a file, a photo, a dump), +of any size up to the server's `MaxAttachmentSize` (default 1 GB, at most +1 TB). Most messages have none. The message's JSON can say what it is: the +attachment itself has no name or type, only its size and SHA-256. + +Protocol version 4. Code: `Server/Storage/Attachments.pbi` (storage), +`Server/Networking/Networking.pbi` (requests), `Server/Networking/Peers.pbi` +(replication), `Client/BakaShrot_Client.pbi` (DLL). + +## The rules + +- **Sent and stored in parts** of 1 MB (`#BakaShrot_AttachmentChunkSize`, the + last one what's left), one request each: neither end ever holds a whole + attachment in memory (a 512 MB one: the server peaked at 15 MB). +- **Checked with its SHA-256**, given before the first part: the server + checks it once all parts are in (uploads and replicated ones alike), the + client when it reads one back. +- **A message is only stored once all of its attachment is.** The client + uploads it first, then pushes the message with the upload's id: readers + never see a message whose attachment is missing on the server it was + pushed to. Messages stay immutable. +- **Replicated after the messages**, separately: a peer gets the message + first (with the attachment's size and SHA-256), then its data once the + messages are caught up. So on the other servers, a message can be there + before its attachment: `AttachmentReady` tells. +- **Deleted with its message** (the retention): its parts go a few at a + time, in the background. + +## Pushing one + +``` +C -> S UploadStart(topic, size, sha256) same permissions as pushing to that + topic, size <= MaxAttachmentSize +S -> C UploadStarted(upload id, 1 MB) +C -> S UploadChunk(upload id, 0, data) in order, each the right size +S -> C ChunkStored(received, complete 0) + ... +C -> S UploadChunk(upload id, last, data) + server: reads all of it back, checks the SHA-256 (or drops it, refused) +S -> C ChunkStored(received = size, complete 1) +C -> S PushMessage(topic, json, upload id) + server: the upload must be this client's (its node), for that topic, + complete: the message and its attachment are stored together +S -> C MessagePushed(id) +``` + +- An upload belongs to the client's node and the topic it was started for. +- One not pushed within `UploadTimeout` seconds (default 3600) is deleted. +- A refused part doesn't drop the upload; a SHA-256 mismatch does. +- The DLL does all of it in `BakaShrot_PushMessageWithFile()` / + `_WithData()`; it reads a file twice (the SHA-256 first). + +## Reading one + +``` +C -> S GetAttachment(topic, node, message id, part) same permissions as reading +S -> C AttachmentChunk(ids, message id, size, sha256, part, data) +``` + +Any part, in any order (the DLL reads them in order). Refused if the +message has none, or if it isn't all on this server yet (replicated after +its message), or isn't kept here (bigger than this server's +`MaxAttachmentSize`). + +## Replicating + +On its link to a peer, at every check-in, once the messages are sent +(`Design/Packets.md`, Replication): + +``` +P -> S MissingAttachmentsRequest +S -> P MissingAttachments([(topic, node, message id, next part)]) + up to 256 attachments of messages S has, + from what it takes from P, not all here + P: for each one it has, all of it, and sends S (SendTopics/SendNodes): +P -> S ReplicateAttachmentChunk(topic, node, message id, part, data) +S -> P ChunkStored(received, complete) + ... from the part S asked for: resumes after a dropped link + S: once all of it is in, checks the SHA-256 its message came with: + ready, or dropped and asked for again from the start +``` + +- A server relays what it has: an attachment that isn't on P either is + skipped, S asks again at the next check-in, maybe of another peer. +- An attachment bigger than S's `MaxAttachmentSize` is marked not kept + when its message arrives: S never asks for it. +- A message skipped on arrival (past S's max age) has no attachment row: + never asked for either. + +## Storage (schema v7, `db_schema_v7.dbml`) + +| Table | What | +|---|---| +| `attachments` | A message's: size, SHA-256, its blob once any of it is here, state: 0 missing, 1 receiving, 2 ready, 3 not kept. | +| `blobs` | The data of one attachment: whose (topic, node), size, SHA-256, bytes received, state: 0 receiving, 1 complete (an upload waiting for its message), 2 attached, 3 to delete. | +| `blob_chunks` | Its parts, 1 MB each, by (blob, index). | + +- Triggers: deleting a message deletes its `attachments` row, which marks + its blob to delete. The retention thread (`Retention.pbi`) deletes those + parts 32 at a time, along with uploads past `UploadTimeout`, every + `RetentionInterval` seconds, retention rules or not. +- Parts are written through the writer (each one its own transaction), read + on each thread's own connection. +- SQLite reuses the freed pages; `vacuum` gives the space back to the disk. + +## In the clients + +| | DLL | Python | Tools | +|---|---|---|---| +| Push with one | `BakaShrot_PushMessageWithFile(Topic, Json, Path)`, `_WithData(Topic, Json, *Data, Size)` | `push(data, topic, attachment=bytes or path)` | `PushMessage -a ` | +| Does a message have one | `BakaShrot_GetMessageAttachmentSize()`, `BakaShrot_IsMessageAttachmentReady()` | `Message.attachment_size`, `.attachment_ready` | `GetLatestMessage` prints it | +| Read one | `BakaShrot_SaveAttachment(Topic, Node, Id, Path)`, `_LoadAttachment()` + `_GetAttachmentData()` | `save_attachment()`, `get_attachment()` | `GetAttachment ` | + +## Speed + +On one machine (i5-13500, localhost, PB 5.73): 5 MB up in ~80 ms and down +in ~65 ms through the tools; 512 MB up in 8.5 s (SHA-256 on both ends +included) and down in 3.9 s. One part per round trip: over a slow link, +latency adds up (1000 round trips per GB). + +## Tested + +- `Tests/Attachments-Test.ps1` (39 checks, two servers, ports 12410-12411): + one part, several, an exact multiple, one byte; none; replicated + identical; not kept past the other server's limit; too big to push; + deleted with its message, parts included. +- `Tests/AttachmentEdges-Test.ps1` (51 checks, ports 12413-12414), with a + raw protocol client (`Tests/AttachmentEdgeClient.pb`) for what the DLL + never sends: + - a wrong SHA-256: refused at the last part, the upload dropped, pushing + with it refused; + - parts out of order, of the wrong size, repeated, past the end, from + another client: refused, the upload goes on; + - someone else's upload, the wrong topic, attached twice, an unknown id, + too big, a topic the client may not push to or read: refused, the + connection stays up; + - uploads left behind (half sent, complete but never pushed): kept within + `UploadTimeout`, deleted past it (10.7 s for 10), then refused; + - replication resuming: the receiver killed at ~45 MB of 400 MB, + restarted: what it had committed is still there, the sender goes on + from that part, the result is identical; + - a byte flipped in the sender's database: the client refuses it + (SHA-256), the peer drops it, serves nothing, and asks again. +- `check_bakashrot.py` (Python): bytes and files, round trips, refusals. + +## Not done + +- **Resuming an upload** after a dropped connection: the parts are kept + until `UploadTimeout`, but the DLL starts over. (Replication resumes.) +- **Several parts in flight**, for links with high latency. +- **A corrupted copy is sent again and again.** If a server's own stored + copy is damaged (disk, a bug), its peers drop it at every check-in and + ask again: the whole attachment is re-sent every `PeerSyncInterval` + (6 times in 6 s in the test). The server itself never notices, it serves + the damaged parts to clients too (they refuse them, by their SHA-256). + Fix: when a peer answers "doesn't match", the sender checks its own copy + (`HashStorageBlob()`); if it's damaged, it marks it missing, so it gets a + good one back from another peer, and stops sending it. Details, and how + the test should change: `Notes.md`, open item 3. +- **No deduplication**: the same file attached twice is stored twice. diff --git a/Design/Packets.md b/Design/Packets.md index db7bb81..9208a00 100644 --- a/Design/Packets.md +++ b/Design/Packets.md @@ -20,13 +20,17 @@ Reference for working on BakaShrot's networking. Related docs: | Sealed Hello, key exchange; encrypting a buffer | `Commons/Cryptography/Session.pbi`, `Commons/Cryptography/Cipher.pbi` | | Client side of the handshake, on any connection | `Commons/Networking/Outbound.pbi` | | Server: listener, one thread per client, request handlers | `Server/Networking/Networking.pbi` | -| Server: links to peers, check-ins, sending missing messages | `Server/Networking/Peers.pbi` | +| Server: links to peers, check-ins, sending missing messages and attachments | `Server/Networking/Peers.pbi` | +| Server: storing messages (the writer), attachments, deleting old ones | `Server/Storage/Writer.pbi`, `Attachments.pbi`, `Retention.pbi` | +| Server: its config, and the example one | `Server/Config/Config.pbi`, `Server/Config/schema.ini` | | Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` | | Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` | | Python client, over the DLL | `Interactors/Python/bakashrot.py` | | Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` | | Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` | | What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` | +| A raw protocol client, for what the DLL never sends | `Tests/AttachmentEdgeClient.pb`, run by `Tests/AttachmentEdges-Test.ps1` | +| Every end-to-end suite | `Tests/*.ps1`, listed in `CLAUDE.md` | ## Transport and framing @@ -70,10 +74,10 @@ Reference for working on BakaShrot's networking. Related docs: array, read in order with PB-MessagePack: 1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`, "BSHT"). - 2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (3: the - Hello sealed, a key per connection, everything after the - ChallengeRequest encrypted; 2 had topics and nodes by name, in plain - text; 1 had ids only). + 2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (4: + attachments; 3: the Hello sealed, a key per connection, everything + after the ChallengeRequest encrypted, times; 2 had topics and nodes by + name, in plain text; 1 had ids only). 3. `PacketType` (integer), one of the ids below. 4. The packet's own fields, in the order listed. - **Encodings:** strings are UTF-8 MessagePack strings, the nonce a @@ -119,14 +123,14 @@ over its own link to another server. | 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse | | 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted | | 7 | AuthAccepted | S→C | None. | | -| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str | MessagePushed / RequestRefused | +| 8 | PushMessage | C→S | `Topic` str (ref, "" for the client's own), `JsonData` str, `UploadId` int (its attachment, 0 for none) | MessagePushed / RequestRefused | | 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | | | 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused | -| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str | | +| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | | | 12 | RequestRefused | S→C | `Reason` str, for logs and humans | | | 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused | | 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | | -| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin) and `JsonData` str | MessagePushed (last id) / RequestRefused | +| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused | | 16 | QueryRequest | C→S | `Sql` str | QueryResult / RequestRefused | | 17 | QueryResult | S→C | `JsonResult` str: `{"columns":[...],"rows":[[...],...]}`, every value a string or null | | | 18 | ResolveName | C→S | `Kind` int (1 topic, 2 node), `Ref` str | NameResolved / RequestRefused | @@ -134,7 +138,20 @@ over its own link to another server. | 20 | ListNames | C→S | `Kind` int (1 topics, 2 nodes) | NamesList | | 21 | NamesList | S→C | `Kind` int, `Truncated` int 0/1, `Count` int, then each entry's `Id` int, `Name` str ("" if unnamed), `Origin` str ("config", "id") | | | 22 | GetMessages | C→S | `Topic` str (ref), `Node` str (ref), `AfterMessageId` int ≥ 0, `Limit` int 1-10000 | Messages / RequestRefused | -| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int and `JsonData` str | | +| 23 | Messages | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `More` int 0/1, `Count` int 0-10000, then each message's `MessageId` int (≥ 1, strictly increasing, above `AfterMessageId`), `PushedAt` int, `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentReady` int 0/1 | | +| 24 | UploadStart | C→S | `Topic` str (ref, "" for the client's own), `Size` int 1-MaxAttachmentSize, `Sha256` bin (32 bytes) | UploadStarted / RequestRefused | +| 25 | UploadStarted | S→C | `UploadId` int ≥ 1, `ChunkSize` int (1 MB) | | +| 26 | UploadChunk | C→S | `UploadId` int, `ChunkIndex` int ≥ 0 (the next one), `Data` bin (1 MB, the last one what's left) | ChunkStored / RequestRefused | +| 27 | ChunkStored | S→C, S→P | `Received` int (bytes so far), `Complete` int 0/1 (all of it, SHA-256 checked) | | +| 28 | GetAttachment | C→S | `Topic`, `Node` str (refs), `MessageId` int ≥ 1, `ChunkIndex` int ≥ 0 | AttachmentChunk / RequestRefused | +| 29 | AttachmentChunk | S→C | `TopicId`, `NodeId` int (the server's), `MessageId` int, `Size` int, `Sha256` bin (32 bytes), `ChunkIndex` int, `Data` bin | | +| 30 | MissingAttachmentsRequest | P→S | None. | MissingAttachments / RequestRefused | +| 31 | MissingAttachments | S→P | `Count` int 0-256, then each one's `Topic`, `Node` str (names), `MessageId` int, `NextChunk` int | | +| 32 | ReplicateAttachmentChunk | P→S | `Topic`, `Node` str (names), `MessageId` int, `ChunkIndex` int (the next one), `Data` bin | ChunkStored / RequestRefused | + +**Attachments** (24-32, and the attachment fields): see +`Design/Attachments.md`. At most one per message, in parts of 1 MB, checked +with their SHA-256, replicated after their message. **Times** (`PushedAt`): milliseconds since 1970-01-01 00:00:00 UTC, 1 to `#BakaShrot_MaxTimestamp` (9999-12-31), anything else aborts. A message is @@ -267,6 +284,11 @@ P -> S ReplicateMessages the topic and node names, the next missing messages S -> P MessagePushed(id) the batch stored in one transaction with INSERT OR IGNORE, the last id echoed ... until caught up, or the first refusal for that pair + then the attachments of the messages S now has: +P -> S MissingAttachmentsRequest +S -> P MissingAttachments what S lacks, among what it takes from P +P -> S ReplicateAttachmentChunk ... -> S -> P ChunkStored, per part + (Design/Attachments.md) ``` - **Batch size:** `PeerBatchSize` is set on the sending side, in diff --git a/Design/Release.md b/Design/Release.md index 578bfd7..ad5bbed 100644 --- a/Design/Release.md +++ b/Design/Release.md @@ -24,11 +24,14 @@ database: view with `is_json = 1`; - if `python` is on the PATH, reads them and pushes one with `python\bakashrot.py`; +- pushes a 3 MB attachment with `PushMessage.exe -a` and reads it back + identical with `GetAttachment.exe`; - then force-kills the server and deletes everything. The end-to-end tests in `Tests/` cover much more (names, replication, big -messages, GetMessages, the Python client), but against `Build\` (PB 5.73) -and `BenchServer.exe`, not the release. +messages, GetMessages, the Python client, retention, attachments and their +edge cases), but against `Build\` (PB 5.73) and `BenchServer.exe`, not the +release. The list is in `CLAUDE.md`. ## Fixed: the release needed the Visual C++ runtime @@ -110,7 +113,7 @@ in `Tests/` already, to be pointed at the release instead. 10. **Version hygiene**: - `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`; - the release commit is tagged (`v1.0.0`), the version comes from it; - - `VERSION.txt` gives the protocol version (3) and the runtime needed; + - `VERSION.txt` gives the protocol version (4) and the runtime needed; - the Python client is checked on the oldest version it claims (3.8), not only on the latest (3.14 here). @@ -210,7 +213,7 @@ Notes for when the builds move to a pipeline. - `Build.ps1` ends by running the server, which waits on its console: needs a `-NoRun` switch. It also writes private keys into `Build\`, which must never be published as an artifact. - - The tests use fixed ports (12399 for the release, 12401-12409 for + - The tests use fixed ports (12399 for the release, 12401-12414 for `Tests/`): parallel jobs on one runner collide, make them parameters or pick free ones. - One entry point that runs every test (`Tests/*.ps1`, the handshake diff --git a/Interactors/Python/bakashrot.py b/Interactors/Python/bakashrot.py index 9fc533f..101a987 100644 --- a/Interactors/Python/bakashrot.py +++ b/Interactors/Python/bakashrot.py @@ -13,10 +13,16 @@ to the app (Message.json() helps). print(message.id, message.data) for message in client.follow("logs", "kitchen"): # until stopped print(message.id, message.json()) + photo_id = client.push({"kind": "photo"}, attachment="photo.jpg") + client.save_attachment("logs", "kitchen", photo_id, "copy.jpg") Topics and nodes are "refs": a name ("logs") or an id (12, or "12"), ids being the server's own. +A message can have one attachment (a file, or bytes), of any size the +server takes: uploaded in parts before the message is stored, read back in +parts, checked with its SHA-256 (Design/Attachments.md). + The connection only goes through to the server holding the private key of server_public_key (client.ini's ServerPublicKey, the server logs it when it starts), and everything on it is encrypted. @@ -76,7 +82,10 @@ class Message: """A stored message. data is as stored: JSON or not (the server's is_json column tells which, json() parses it). pushed_at: when it was pushed, to whichever server it was pushed to, in milliseconds since - 1970-01-01 UTC (pushed is the same as a datetime).""" + 1970-01-01 UTC (pushed is the same as a datetime). attachment_size: its + attachment's, 0 for none; attachment_ready: whether all of it is on + this server (a replicated one comes after its message), see + Client.get_attachment() and save_attachment().""" id: int topic: str @@ -85,6 +94,8 @@ class Message: node_id: int data: str pushed_at: int = 0 + attachment_size: int = 0 + attachment_ready: bool = False def json(self) -> Any: """The data parsed as JSON, raises ValueError if it isn't.""" @@ -191,6 +202,14 @@ class _Dll: "BakaShrot_HasMoreMessages": (I, []), "BakaShrot_GetMessageId": (Q, []), "BakaShrot_GetMessagePushedAt": (Q, []), + "BakaShrot_GetMessageAttachmentSize": (Q, []), + "BakaShrot_IsMessageAttachmentReady": (I, []), + "BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), + "BakaShrot_PushMessageWithDataA": (Q, [P, P, S, Q]), + "BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), + "BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), + "BakaShrot_GetAttachmentData": (Q, [S, Q]), + "BakaShrot_FreeAttachmentData": (I, []), "BakaShrot_GetMessageTopicId": (L, []), "BakaShrot_GetMessageNodeId": (L, []), "BakaShrot_GetMessageTopicA": (I, [S, I]), @@ -325,27 +344,73 @@ class Client: # --- Requests ---------------------------------------------------------- - def push(self, data: Any, topic: Optional[Ref] = None) -> int: + def push(self, data: Any, topic: Optional[Ref] = None, + attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int: """Pushes a message into topic (default: the client's own), under the client's node. data is stored as is if it's a str (JSON or not), - anything else is turned into JSON first. Returns its message id.""" + anything else is turned into JSON first. Returns its message id. + + attachment: bytes, or the path of a file, uploaded first (in parts, + any size the server's MaxAttachmentSize allows): the message is only + stored once all of it is.""" if not isinstance(data, str): data = json.dumps(data, separators=(",", ":"), ensure_ascii=False) encoded = data.encode("utf-8") if len(encoded) > MAX_MESSAGE_SIZE: raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}") + topic_ref = b"" if topic is None else _ref(topic) with self._lock: self._check_connected() - message_id = self._dll.PushMessageToA(b"" if topic is None else _ref(topic), encoded) + if attachment is None: + message_id = self._dll.PushMessageToA(topic_ref, encoded) + elif isinstance(attachment, (bytes, bytearray, memoryview)): + raw = bytes(attachment) + if not raw: + raise BakaShrotError("The attachment is empty") + buffer = ctypes.create_string_buffer(raw, len(raw)) + message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw)) + else: + path = os.fspath(attachment) + if not os.path.isfile(path) or os.path.getsize(path) == 0: + raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty") + message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8")) if message_id < 1: raise self._failed("Push") return message_id + def get_attachment(self, topic: Ref, node: Ref, message_id: int) -> bytes: + """The attachment of topic:node#message_id, all of it in memory + (save_attachment() for big ones), checked with its SHA-256. Raises + RefusedError if the message has none, or it isn't on this server + yet.""" + with self._lock: + self._check_connected() + size = self._dll.LoadAttachmentA(_ref(topic), _ref(node), int(message_id)) + if size < 0: + raise self._failed("Attachment") + try: + buffer = ctypes.create_string_buffer(size) + self._dll.GetAttachmentData(ctypes.cast(buffer, ctypes.c_void_p), size) + return buffer.raw[:size] + finally: + self._dll.FreeAttachmentData() + + def save_attachment(self, topic: Ref, node: Ref, message_id: int, path: Union[str, os.PathLike]) -> int: + """Saves the attachment of topic:node#message_id to path (replaced), + a part at a time, checked with its SHA-256. Returns its size. A + failed one leaves no file.""" + with self._lock: + self._check_connected() + size = self._dll.SaveAttachmentA(_ref(topic), _ref(node), int(message_id), os.fspath(path).encode("utf-8")) + if size < 0: + raise self._failed("Attachment") + return size + def _current(self) -> Message: dll = self._dll return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), dll.GetMessageTopicId(), dll.GetMessageNodeId(), dll.string(dll.GetMessageDataA), - dll.GetMessagePushedAt()) + dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), bool(dll.IsMessageAttachmentReady())) def latest(self, topic: Ref, node: Ref) -> Optional[Message]: """The latest message of topic/node, None if there's none yet.""" diff --git a/Interactors/Python/check_bakashrot.py b/Interactors/Python/check_bakashrot.py index 43e0d72..797ee93 100644 --- a/Interactors/Python/check_bakashrot.py +++ b/Interactors/Python/check_bakashrot.py @@ -6,7 +6,10 @@ Usage: python check_bakashrot.py Expects an empty database. Prints PASS/FAIL per check, exits 1 if any failed. """ +import hashlib +import os import sys +import tempfile import threading import time @@ -159,6 +162,44 @@ with kitchen: not thread.is_alive() and not errors and [m.id for m in followed] == new_ids, f"{[m.id for m in followed]} vs {new_ids}, errors {errors}") + # --- Attachments (in secret, the other checks count logs) ------------------- + blob = os.urandom(3 * 1024 * 1024 + 7) + started = time.perf_counter() + blob_id = kitchen.push({"kind": "blob"}, topic="secret", attachment=blob) + up = time.perf_counter() - started + message = kitchen.latest("secret", "kitchen") + check("push(attachment=bytes): the message has it, ready", + message is not None and message.id == blob_id and message.attachment_size == len(blob) and message.attachment_ready, + message) + started = time.perf_counter() + data = kitchen.get_attachment("secret", "kitchen", blob_id) + down = time.perf_counter() - started + check("get_attachment(): the same bytes", data == blob, f"{len(data)} bytes, {up * 1000:.0f} ms up, {down * 1000:.0f} ms down") + + folder = tempfile.mkdtemp() + source = os.path.join(folder, "source.bin") + with open(source, "wb") as file: + file.write(os.urandom(1500 * 1024)) + file_id = kitchen.push("from a file", topic="secret", attachment=source) + copy = os.path.join(folder, "copy.bin") + size = kitchen.save_attachment("secret", "kitchen", file_id, copy) + with open(source, "rb") as a, open(copy, "rb") as b: + same = hashlib.sha256(a.read()).digest() == hashlib.sha256(b.read()).digest() + check("push(attachment=path), save_attachment(): the same file", size == os.path.getsize(source) and same, size) + + plain_id = kitchen.push("no attachment", topic="secret") + page = kitchen.get_messages("secret", "kitchen", after=blob_id - 1) + sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page] + check("get_messages(): each message's attachment", + sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes) + ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment") + check("get_attachment() of a message without: RefusedError", ok, detail) + ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty") + check("An empty attachment: refused before sending", ok, detail) + ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file") + check("A missing file: refused before sending", ok, detail) + check("Still connected", kitchen.connected) + check("close(): disconnected", not kitchen.connected) ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError) check("A request once closed: ConnectionLostError", ok, detail) diff --git a/Notes.md b/Notes.md index c1c4ccf..a271196 100644 --- a/Notes.md +++ b/Notes.md @@ -1,11 +1,13 @@ # BakaShrot - working notes -Where things stand and what's next, as of 2026-11-08. The detailed docs are in -`Design/`: +Where things stand and what's next, as of 2026-11-08. A new session: read +`CLAUDE.md` first (how to build, test, and the traps), then "Open items" +below. The detailed docs are in `Design/`: | Doc | About | |---|---| | `Design/Packets.md` | The protocol: framing, every packet, flows, conventions, how to add a packet. | +| `Design/Attachments.md` | Attachments: one per message, in 1 MB parts, uploaded before the message, replicated after it. | | `Design/Cryptography.md` | What libsodium is used for: the handshake proving both ends, the connections' encryption. What isn't done, and ideas for abstracting it. | | `Design/ReplicationIssues.md` | Known replication problems, with benchmarks. | | `Design/StorageConcurrency.md` | One connection per thread, WAL, the write mutex and the writer (done), and what's left. | @@ -24,7 +26,8 @@ Where things stand and what's next, as of 2026-11-08. The detailed docs are in - **Server:** - Every connection is encrypted, and both ends prove who they are: the client with an Ed25519 challenge, the server by signing the handshake - with the key its clients know (protocol 3, `Design/Cryptography.md`). + with the key its clients know (since protocol 3, `Design/Cryptography.md`; + the protocol is at 4, with attachments). - Clients can push messages (usually JSON, anything is stored, flagged in `is_json`), read the latest one of a topic/node pair or a run of them after an id, resolve names, and run raw read-only SQL, each depending on @@ -35,12 +38,16 @@ Where things stand and what's next, as of 2026-11-08. The detailed docs are in - Stamps every push with the time it arrived (`pushed_at`, UTC ms), which replication carries as is, and deletes each topic's messages past its max age (`[BakaShrot.Retention]`, per server). + - A message can have one attachment of any size up to `MaxAttachmentSize` + (default 1G), sent in 1 MB parts, replicated after its message + (`Design/Attachments.md`). - One thread per client and per peer, each with its own SQLite connection. - The root thread can stop every worker (restart, vacuum). - **Client:** a DLL with A/W string exports, PureBasic prototypes in `Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`: - `PushMessage`, `GetLatestMessage`, `GetMessages` (with `--follow`), - `Resolve`, `ListNames`, `Query`, `KeyGen`. + `PushMessage` (`-a` to attach a file), `GetLatestMessage`, `GetMessages` + (with `--follow`), `GetAttachment`, `Resolve`, `ListNames`, `Query`, + `KeyGen`. - **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes, no dependencies, and `example.py`. - **Release:** `Release.ps1` builds with PB 6.40's C backend into @@ -174,9 +181,8 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs. s), over it refused, non-JSON stored with is_json = 0 (10 edge cases), replicated intact to the other server, a 16 MB read back from it (0.5 s), small ones still batched. `Names-Test.ps1` and the handshake test still pass. -- **Left:** attachments for real files (the unused `attachements` table: - the message references a blob sent in chunks, only when wanted), if more - than 16 MB is ever needed. Memory: an authenticated connection can hold +- **Left:** attachments for real files, if more than 16 MB is ever needed: + done since, see `Design/Attachments.md`. Memory: an authenticated connection can hold up to ~32 MB of inbox (64 MB in the worst case of the growth), plus the packet being handled. @@ -259,8 +265,9 @@ As judged for the threat model below (internal tool, trusted machines). **Good** - The core works and is tested end to end: push, latest, runs of messages and `--follow`, names and ids, filters and wildcards, raw read-only SQL, - per-client permissions; five suites, two `.pb` tests, the release's smoke - test (PB 6.40 C), all passing. + per-client permissions, retention, attachments; eight `Tests/*.ps1` + suites, two `.pb` tests, the release's smoke test (PB 6.40 C), all + passing (see `CLAUDE.md` for the list). - Fast: ~40,800 msg/s pushed across 4 servers (10 nodes each, PB 5.73), fully replicated; ~9,000 msg/s from one Python connection. - Replication by name, each server with its own ids; restart catch-up is @@ -268,7 +275,8 @@ As judged for the threat model below (internal tool, trusted machines). - Security beyond what's needed here: encrypted connections, both ends proven, peer links verified. - Data: 16 MB messages, anything stored (`is_json`), errors of queries - surfaced; pushed times; retention per topic and server. + surfaced; pushed times; retention per topic and server; one attachment + per message, any size, flat memory (512 MB with the server at 15 MB). - Clients: DLL for any language, CLI tools, dependency-free Python. - Packaging (runtime included) and docs that match the code. @@ -289,11 +297,16 @@ As judged for the threat model below (internal tool, trusted machines). main blocker for deploying it. - Never run from the extracted zip, on a clean Windows, nor with two release servers, nor restarted after a kill: designed to work, unchecked. -- Nothing committed: everything since the initial commit (the deleted - `Core/` included) lives only in the working tree. +- A corrupted stored attachment is re-sent to peers forever (open item 3). -Suggested order: commit; a stop file and running as a service; smoke-test -items 1-3 (`Design/Release.md`); a single test runner, then CI. +Commits (at this writing, check `git log`): `master` has everything up to +protocol 3 (`12fbe5f`); branch `timestamps-retention` adds timestamps and +retention (`9caf816`); attachments and their tests were left uncommitted on +that branch, waiting for the owner to ask. + +Suggested order: a stop file and running as a service; smoke-test items +1-3 (`Design/Release.md`); the corrupted-attachment fix; a single test +runner, then CI. ## Done: pushed times, retention (2026-11-08) @@ -340,6 +353,48 @@ items 1-3 (`Design/Release.md`); a single test runner, then CI. - **Removed:** the `archives` table, a leftover of the first schemas that nothing ever used, dropped from existing databases at start. +## Done: attachments (2026-11-08) + +- **One per message**, optional: bytes of any size up to the server's + `MaxAttachmentSize` (default 1G, at most 1T), no name or type (the JSON + says what it is), a size and a SHA-256. Protocol version 4, schema v7. +- **Pushing:** uploaded first in 1 MB parts (UploadStart, UploadChunk), the + server checks the SHA-256, then the PushMessage carries the upload's id: + the message and its attachment are stored in the same transaction, so + readers never see one without the other. Uploads not pushed within + `UploadTimeout` (default 3600 s) are deleted. +- **Reading:** a part per request (GetAttachment), checked by the client. + Messages tell `AttachmentSize` and `AttachmentReady`. +- **Replication:** separate from the messages, after them: the message + carries the size and SHA-256, then at each check-in the peer lists what + it's missing (MissingAttachments), the sender sends the parts, from where + the peer stopped. Over the receiver's `MaxAttachmentSize`: the message + comes, the attachment is marked not kept and never asked for. +- **Deleted with its message** (retention): triggers mark the data, the + retention thread deletes its parts 32 at a time. It now always runs. +- **Clients:** DLL `BakaShrot_PushMessageWithFile/WithData()`, + `_SaveAttachment()`, `_LoadAttachment()` + `_GetAttachmentData()`, + `_GetMessageAttachmentSize()`, `_IsMessageAttachmentReady()`; Python + `push(..., attachment=bytes or path)`, `get_attachment()`, + `save_attachment()`, `Message.attachment_size/_ready`; tools + `PushMessage -a`, `GetAttachment`. +- **Measured:** 512 MB up in 8.5 s, down in 3.9 s, identical, the server + peaking at 15 MB of memory. The push benchmark isn't affected (messages + without attachments only gain a LEFT JOIN on reads). +- **Tested:** `Tests/Attachments-Test.ps1` (39 checks, ports 12410-12411), + Python's checks (55 in all now); every other suite still passes. +- **Edge cases tested:** `Tests/AttachmentEdges-Test.ps1` (51 checks, a raw + protocol client): wrong SHA-256, parts out of order / wrong size / + repeated, others' uploads, wrong topic, attached twice, too big, uploads + expiring past `UploadTimeout`, replication resuming after the receiver + was killed mid-transfer, a corrupted stored copy. All hold. +- **Found:** a server whose own copy is corrupted re-sends it to its peers + at every check-in, forever, and serves it to clients (who refuse it). + Not fixed: open item 3 below has the details and the proposed fix. +- **Left:** resuming an upload after a dropped connection (replication + does resume); several parts in flight for high-latency links. + See `Design/Attachments.md`. + ## Threat model (2026-11-08) BakaShrot is an **internal tool, on trusted machines and a trusted @@ -370,58 +425,92 @@ network**, not exposed to the internet. So: replication between two release servers, restart catch-up (designed to work, never tested: kill a server, check ids continue and peers catch up). (`Design/Release.md`, items 1-3) -3. **`synchronous = NORMAL`:** the last commits can be lost on a power loss +3. **A corrupted stored attachment is re-sent to peers forever.** Found + by `Tests/AttachmentEdges-Test.ps1` part 4 (a byte flipped in the + sender's `blob_chunks`, `flip.py`). + - What happens: the peer checks the SHA-256 once all parts are in, + drops its copy (`FinishReplicatedAttachment(..., #False)`), refuses the + last part ("The attachment doesn't match its SHA-256, send it again"), + and lists it as missing again. At the next check-in the sender sends + all of it again: every `PeerSyncInterval` (6 times in 6 s in the test), + 1 GB each time for a 1 GB attachment. Forever. + - The sender never notices: it also serves the damaged parts to clients + (`GetAttachment`), who refuse them by their SHA-256 (the DLL checks at + the end of `BakaShrot_Download()`). + - Proposed fix, in `BakaShrot_PeerLink_SendAttachment()` + (`Server/Networking/Peers.pbi`): when the peer refuses with "doesn't + match", check this server's own copy with `HashStorageBlob()` + (`Server/Storage/Attachments.pbi`, the link's own `DbId`). If it's + damaged, `FinishReplicatedAttachment(TopicId, NodeId, MessageId, + BlobId, #False)` already does the rest: drops the blob, marks the + attachment missing (state 0), so this server stops sending it and asks + its own peers for a good copy (`MissingAttachments`), and stops + serving it. Log it loudly. If its copy is fine (the damage was in + transit), sending again is right. + - Better than matching the refusal's text: a distinct answer for "the + data doesn't match", e.g. a `ChunkStored` with `Complete = 0` and + `Received = 0` after the last part, or a new field. + - The origin (where it was pushed) has no other source: its attachment + then stays missing ("isn't here yet"), better than serving bad data; + maybe a "lost" state (4) so `GetAttachment` says so. + - Optional, to catch it on reads too: a SHA-256 per part in + `blob_chunks`, checked by `ReadStorageBlobChunk()`, at ~3 s/GB. + - Test: part 4 of `AttachmentEdges-Test.ps1` then expects the sender to + log its copy as damaged and the re-sends to stop (today it only prints + an INFO line with the count); its own `attachments` row goes to 0. +4. **`synchronous = NORMAL`:** the last commits can be lost on a power loss or OS crash (not on a killed process). Decide, or switch to `FULL`. (`Design/StorageConcurrency.md`) -4. **Drift between servers** when one topic/node pair is written to on two +5. **Drift between servers** when one topic/node pair is written to on two servers: only partially resynced. Accepted while each pair has a single writer; document that as the rule. (`Design/ReplicationIssues.md` #1) -5. **Gaps in a pair's ids aren't detected** on replication. +6. **Gaps in a pair's ids aren't detected** on replication. (`Design/ReplicationIssues.md` #5) -6. **No single test runner**, and fixed ports (12399, 12401-12409): every +7. **No single test runner**, and fixed ports (12399, 12401-12414): every `Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI. (`Design/Release.md`, "For CI/CD") -7. **Is `DatabaseError()` per thread?** Messages could land in the wrong +8. **Is `DatabaseError()` per thread?** Messages could land in the wrong thread's log or refusal; Windows queries no longer depend on it. (`Design/StorageConcurrency.md`) -8. **Limits:** the sync state must fit in one packet (65536 topic/node +9. **Limits:** the sync state must fit in one packet (65536 topic/node pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover. (`Design/ReplicationIssues.md` #7) ### Client side -9. **One connection per process** (the DLL's globals): a handle-based API +10. **One connection per process** (the DLL's globals): a handle-based API for several. No reconnect in `GetMessages --follow` / `follow()`, polling rather than server-pushed subscriptions. -10. **Breaking with protocol 3:** every client config needs - `ServerPublicKey`; older clients can't connect. Fine while it's all +11. **Breaking with protocols 3 and 4:** every client config needs + `ServerPublicKey`; older clients and servers can't connect (any + version difference refuses the connection). Fine while it's all built from this repo, worth a line in the release notes of the first real release. ### Security, low priority under the threat model -11. **Peers are trusted completely:** messages aren't signed by the node +12. **Peers are trusted completely:** messages aren't signed by the node that first wrote them, a peer can replicate anything in what we accept from it. (`Design/ReplicationIssues.md` #3) -12. **Private keys sit in plain-text ini files**, readable by whoever can +13. **Private keys sit in plain-text ini files**, readable by whoever can read the config. On trusted machines: file permissions are enough. -13. **No key rotation or revocation**, other than editing configs and +14. **No key rotation or revocation**, other than editing configs and restarting; a server can't announce a new key, clients pin one. -14. **The handshake costs the server work before the client proved +15. **The handshake costs the server work before the client proved anything** (a sealed box, a key pair, a signature): no rate limit, only the 4 KB handshake limit and the 10 s timeout. -15. **Small ones:** the DLL doesn't wipe its private key; one identity key +16. **Small ones:** the DLL doesn't wipe its private key; one identity key both signs and opens sealed boxes; `EncodeData`/`DecodeData` are misnamed (they sign/verify). (`Design/Cryptography.md`) ### Housekeeping -16. **Review.md rules** not checked against the newer code (`.i` in +17. **Review.md rules** not checked against the newer code (`.i` in networking structures, explicit enumeration values), see below. The file itself says to ignore it for now. -17. **Linux is untested** (libsodium via `-lsodium`, the query error check +18. **Linux is untested** (libsodium via `-lsodium`, the query error check falls back to `DatabaseError()`). -18. **Console commands can't be scripted** (see 1). +19. **Console commands can't be scripted** (see 1). ### Done recently (details in the sections above and `Design/`) @@ -432,6 +521,10 @@ network**, not exposed to the internet. So: - GetMessages, `--follow`, the Python client; big messages (16 MB) and `is_json`; names, filters and wildcards; speed: ~34,300 msg/s for 4 servers (2026-11-07/08). +- `pushed_at` timestamps, carried by replication; retention per topic and + server, skipping on arrival what's past its age (2026-11-08). +- Attachments, protocol 4: one per message, in 1 MB parts, replicated after + their message, resumable; edge cases tested (2026-11-08). ## To check against Review.md @@ -457,3 +550,13 @@ network**, not exposed to the internet. So: - **Don't trust timestamps** from PowerShell's `Register-ObjectEvent`: lines queue up during `Start-Sleep`. PureBasic's console output into a pipe is also buffered until exit. Trust the order, not the times. +- **JSON on a tool's command line loses its double quotes** (PowerShell 5 + and PureBasic's `ProgramParameter()`): the tests write it to a file and + pass `@file`. +- **Things only a raw client can do** (a wrong SHA-256, abandoned uploads): + `Tests/AttachmentEdgeClient.pb`, over `Commons/Networking/Outbound.pbi`. + Copy its `Exchange()` / `Refusal()` helpers for new protocol tests. +- **Corrupting or seeding a database** from a test: Python's `sqlite3`, + with the server stopped through its stop file (its WAL is checkpointed + then), see `Retention-Test.ps1` (an old schema) and + `AttachmentEdges-Test.ps1` (`flip.py`). diff --git a/Release.ps1 b/Release.ps1 index 00f3028..688afa0 100644 --- a/Release.ps1 +++ b/Release.ps1 @@ -6,8 +6,8 @@ # BakaShrot_Server.exe the server # BakaShrot_Client.dll the client DLL, with # BakaShrot_Client_Prototypes.pbi its PureBasic prototypes -# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, Query.exe, -# Resolve.exe, ListNames.exe, KeyGen.exe the tools +# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, GetAttachment.exe, +# Query.exe, Resolve.exe, ListNames.exe, KeyGen.exe the tools # libsodium.dll, sqlite3.dll what they need next to them # vcruntime140.dll what libsodium.dll needs (Libs\redist) # python\bakashrot.py, example.py the Python client, over the DLL @@ -115,6 +115,7 @@ $Targets = @( @("Tools\PushMessage\PushMessage.pb", "PushMessage.exe", @("/CONSOLE")), @("Tools\GetLatestMessage\GetLatestMessage.pb", "GetLatestMessage.exe", @("/CONSOLE")), @("Tools\GetMessages\GetMessages.pb", "GetMessages.exe", @("/CONSOLE")), + @("Tools\GetAttachment\GetAttachment.pb", "GetAttachment.exe", @("/CONSOLE")), @("Tools\Query\Query.pb", "Query.exe", @("/CONSOLE")), @("Tools\Resolve\Resolve.pb", "Resolve.exe", @("/CONSOLE")), @("Tools\ListNames\ListNames.pb", "ListNames.exe", @("/CONSOLE")), @@ -169,9 +170,10 @@ Run the server: BakaShrot_Server.exe config.ini Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id, each server has its own ids for the same names. Tools, next to BakaShrot_Client.dll, with a client.ini: - PushMessage [-t ] [ClientIni] + PushMessage [-t ] [-a ] [ClientIni] GetLatestMessage [ClientIni] - GetMessages [--after ] [--limit ] [--follow] [--interval ] [ClientIni] + GetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni] + GetAttachment [ClientIni] Resolve [ClientIni] ListNames [topics|nodes|all] [ClientIni] [--json] Query [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs' @@ -310,6 +312,19 @@ ServerPublicKey = $($ServerKeys.PublicKey) else { Write-Host " No python on the PATH, the Python client wasn't checked" } + + # An attachment of 3 parts and a bit, up and back. + $Attach = Join-Path $TestDir "attach.bin" + $Bytes = New-Object byte[] (3 * 1024 * 1024 + 17) + (New-Object System.Random 5).NextBytes($Bytes) + [IO.File]::WriteAllBytes($Attach, $Bytes) + $Pushed = Invoke-Tool "PushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni) + if ($Pushed -notmatch "message #(\d+), with an attachment of 3145745 bytes") { throw "Unexpected push with an attachment: $Pushed" } + $AttachedId = $Matches[1] + $Copy = Join-Path $TestDir "attach-copy.bin" + $Saved = Invoke-Tool "GetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni) + if ($Saved -notmatch "Saved 3145745 bytes" -or (Get-FileHash $Attach).Hash -ne (Get-FileHash $Copy).Hash) { throw "Unexpected attachment read back: $Saved" } + Write-Host " Pushed and read back an attachment: OK" } finally { if ($Server -and -not $Server.HasExited) { diff --git a/Server/Config/Config.pbi b/Server/Config/Config.pbi index e23169b..785bd1d 100644 --- a/Server/Config/Config.pbi +++ b/Server/Config/Config.pbi @@ -34,6 +34,8 @@ ; ============================================================================ XIncludeFile "../../Commons/Networking/Names.pbi" +; #BakaShrot_MaxAttachmentSize. +XIncludeFile "../../Commons/Networking/Packets.pbi" ; Some topics or nodes, or all of them: what a topic list (or node list) @@ -228,6 +230,16 @@ Structure BakaShrot_ServerConfig ; max age ([BakaShrot.Retention]). Default 60. RetentionInterval.i + ; Biggest attachment this server takes, in bytes: pushed with a message, + ; or replicated (a bigger one's message is kept, not its attachment). + ; Written with a unit: 500M, 1G (K M G T, 1024-based). Default 1G. + MaxAttachmentSize.q + MaxAttachmentSizeText.s + + ; Seconds an upload may take, before it's pushed with its message: past + ; that it's deleted. Default 3600. + UploadTimeout.i + EndStructure @@ -283,6 +295,8 @@ Macro Ptr_BakaShrot_CoreConfig : i : EndMacro #BakaShrot_Config_DefaultPeerSyncInterval = 5 #BakaShrot_Config_DefaultPeerBatchSize = 100 #BakaShrot_Config_DefaultRetentionInterval = 60 +#BakaShrot_Config_DefaultMaxAttachmentSize = "1G" +#BakaShrot_Config_DefaultUploadTimeout = 3600 ; What ReadPreferenceString() returns for a missing key, to tell it from an ; empty one: an empty PushTopics allows nothing, a missing one the default. @@ -422,6 +436,38 @@ Procedure.q ParseRetentionAge(Text.s) EndProcedure +; A size as MaxAttachmentSize writes it ("500M", "1G", "1048576") in bytes, +; -1 if it isn't one. Units are 1024-based: K M G T. +Procedure.q ParseConfigSize(Text.s) + Protected Unit.q = 1, Digits.s, Last.s, i.i + + Text = UCase(Trim(Text)) + If Text = "" + ProcedureReturn -1 + EndIf + Last = Right(Text, 1) + Select Last + Case "K" : Unit = 1024 + Case "M" : Unit = 1024 * 1024 + Case "G" : Unit = 1024 * 1024 * 1024 + Case "T" : Unit = 1024 * 1024 * 1024 * 1024 + EndSelect + Digits = Text + If Unit > 1 + Digits = Left(Text, Len(Text) - 1) + EndIf + If Digits = "" Or Len(Digits) > 13 + ProcedureReturn -1 + EndIf + For i = 1 To Len(Digits) + If Mid(Digits, i, 1) < "0" Or Mid(Digits, i, 1) > "9" + ProcedureReturn -1 + EndIf + Next + ProcedureReturn Val(Digits) * Unit +EndProcedure + + ; Reads [BakaShrot.Retention] into *Config\Retention(). ; Returns #False on an invalid line, with the reason in BakaShrot_ConfigError. Procedure.i ParseRetentionSection(*Config.BakaShrot_CoreConfig) @@ -835,6 +881,17 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) BakaShrot_ConfigError = "[BakaShrot.Server] RetentionInterval must be 1 second or more" Goto LoadFailed EndIf + *Config\Server\MaxAttachmentSizeText = Trim(ReadPreferenceString("MaxAttachmentSize", #BakaShrot_Config_DefaultMaxAttachmentSize)) + *Config\Server\MaxAttachmentSize = ParseConfigSize(*Config\Server\MaxAttachmentSizeText) + If *Config\Server\MaxAttachmentSize < 0 Or *Config\Server\MaxAttachmentSize > #BakaShrot_MaxAttachmentSize + BakaShrot_ConfigError = "[BakaShrot.Server] MaxAttachmentSize = '" + *Config\Server\MaxAttachmentSizeText + "' isn't a size up to 1T: bytes, or a number with K, M, G or T, like 500M (0: no attachments)" + Goto LoadFailed + EndIf + *Config\Server\UploadTimeout = ReadPreferenceLong("UploadTimeout", #BakaShrot_Config_DefaultUploadTimeout) + If *Config\Server\UploadTimeout < 10 + BakaShrot_ConfigError = "[BakaShrot.Server] UploadTimeout must be 10 seconds or more" + Goto LoadFailed + EndIf *Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "") If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics") Goto LoadFailed @@ -997,6 +1054,8 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval) WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize) WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval) + WritePreferenceString("MaxAttachmentSize", *Config\Server\MaxAttachmentSizeText) + WritePreferenceLong("UploadTimeout", *Config\Server\UploadTimeout) PreferenceGroup("BakaShrot.Topics") ForEach *Config\TopicNames() diff --git a/Server/Config/schema.ini b/Server/Config/schema.ini index be86091..999aae5 100644 --- a/Server/Config/schema.ini +++ b/Server/Config/schema.ini @@ -102,9 +102,18 @@ PeerSyncInterval = 5 PeerBatchSize = 100 ; Seconds between two passes deleting the messages past their topic's age -; ([BakaShrot.Retention] above). Only runs if a topic has one. +; ([BakaShrot.Retention] above), and the attachments' leftovers. RetentionInterval = 60 +; Biggest attachment this server takes (one per message, see +; Design/Attachments.md): pushed to it, or replicated (a bigger one's message +; is kept, its attachment isn't). Bytes, or K M G T (1024-based). 0: none. +MaxAttachmentSize = 1G + +; Seconds a client may take to upload an attachment and push its message, +; after which the upload is deleted. +UploadTimeout = 3600 + ; One [BakaShrot.Peer.] section per peer this node talks to. ; is only a key for this file; it is never sent on the wire. diff --git a/Server/Networking/Networking.pbi b/Server/Networking/Networking.pbi index d73f24b..024f143 100644 --- a/Server/Networking/Networking.pbi +++ b/Server/Networking/Networking.pbi @@ -17,10 +17,12 @@ ; ; Once authenticated, a client's thread answers its requests one at a time ; until it disconnects: PushMessage, GetLatestMessage, GetMessages, -; QueryRequest, ResolveName and ListNames, each one only if its +; QueryRequest, ResolveName and ListNames, UploadStart, UploadChunk and +; GetAttachment (Design/Attachments.md), each one only if its ; [BakaShrot.Client.] allows it (AllowWrite and PushTopics, AllowRead ; and ReadTopics, AllowQuery), and for -; peers, SyncStateRequest and ReplicateMessages, refused for regular clients, +; peers, SyncStateRequest and ReplicateMessages, then MissingAttachmentsRequest +; and ReplicateAttachmentChunk, refused for regular clients, ; within the peer's AcceptTopics and AcceptNodes. Any other packet aborts it. ; ; Topics and nodes come by name or id (Commons/Networking/Names.pbi), and @@ -421,7 +423,8 @@ EndProcedure Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) Protected *View.MsgPackData, *Push.BakaShrot_PushMessage Protected Pushed.BakaShrot_MessagePushed - Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String + Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String, UploadId.q + Protected Blob.BakaShrot_StorageBlob Protected *Answer, AnswerSize.Integer, Sent.i *Push = 0 @@ -436,6 +439,7 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, * EndIf JsonData = *Push\JsonData TopicRef = *Push\Topic + UploadId = *Push\UploadId FreeStructure(*Push) ; The node is the authenticated one, the client never sends it here. @@ -473,7 +477,20 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, * ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored") EndIf - MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError) + ; Its attachment: one of this client's complete uploads, for that topic. + If UploadId + If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload") + EndIf + If Blob\State <> #BakaShrot_Blob_Complete + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload isn't complete, or is attached already") + EndIf + If Blob\TopicId <> TopicId + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") + EndIf + EndIf + + MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId) If MessageId < 1 PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s) ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored") @@ -551,6 +568,8 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie Latest\MessageId = Message\MessageId Latest\PushedAt = Message\PushedAt Latest\JsonData = Message\JsonData + Latest\AttachmentSize = Message\AttachmentSize + Latest\AttachmentReady = Message\AttachmentReady *Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize) If Not *Answer ProcedureReturn #False @@ -636,6 +655,8 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, * Answer\Messages()\MessageId = Messages()\MessageId Answer\Messages()\PushedAt = Messages()\PushedAt Answer\Messages()\JsonData = Messages()\JsonData + Answer\Messages()\AttachmentSize = Messages()\AttachmentSize + Answer\Messages()\AttachmentReady = Messages()\AttachmentReady Next ClearList(Messages()) @@ -975,7 +996,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli If MaxAge > 0 SkipBefore = BakaShrot_NowUtcMs() - MaxAge EndIf - IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped) + IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped, *Client\Server\Config\Server\MaxAttachmentSize) FreeStructure(*Batch) If #BakaShrot_Net_LogRequests And Skipped\i > 0 PrintN("[Net] Skipped " + Str(Skipped\i) + " messages of " + TopicRef + ":" + NodeRef + " from peer '" + *Client\PeerName + "', past their max age here") @@ -996,6 +1017,358 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli ProcedureReturn Sent EndProcedure +; --- Attachments ----------------------------------------------------------------- +; See Design/Attachments.md and Storage/Attachments.pbi. + +; Sends a ChunkStored. Returns #False if it couldn't be sent. +Procedure.i BakaShrot_NetClient_SendChunkStored(*Client.BakaShrot_NetClient, Received.q, Complete.i) + Protected Stored.BakaShrot_ChunkStored, *Answer, AnswerSize.Integer, Sent.i + + Stored\Received = Received + Stored\Complete = Complete + *Answer = BakaShrot_ChunkStoredPacket_Encode(@Stored, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + ProcedureReturn Sent +EndProcedure + + +; Starts an upload, for a message the client will push to that topic. +; Same permissions as pushing, and at most MaxAttachmentSize bytes. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Start.BakaShrot_UploadStart + Protected Started.BakaShrot_UploadStarted + Protected TopicRef.s, TopicId.i, Size.q, MaxSize.q, BlobId.q, StoreError.String + Protected Dim Sha256.a(#BakaShrot_Sha256Size - 1) + Protected *Answer, AnswerSize.Integer, Sent.i + + *Start = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Start = BakaShrot_UploadStartPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Start + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload start") + ProcedureReturn #False + EndIf + TopicRef = *Start\Topic + Size = *Start\Size + CopyMemory(@*Start\Sha256[0], @Sha256(0), #BakaShrot_Sha256Size) + FreeStructure(*Start) + + If Not *Client\Permissions\Write + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write") + EndIf + If TopicRef = "" + TopicId = *Client\Metadata\TopicId + Else + TopicId = BakaShrot_Names_ResolveTopic(TopicRef) + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + EndIf + EndIf + If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + EndIf + + MaxSize = *Client\Server\Config\Server\MaxAttachmentSize + If Size > MaxSize + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here") + EndIf + + BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError) + If Not BlobId + PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be started") + EndIf + + Started\UploadId = BlobId + Started\ChunkSize = #BakaShrot_AttachmentChunkSize + *Answer = BakaShrot_UploadStartedPacket_Encode(@Started, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + ProcedureReturn Sent +EndProcedure + + +; Stores the next part of one of this client's uploads. Once all of it is +; here, checks its SHA-256: complete, or dropped and refused. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Chunk.BakaShrot_UploadChunk + Protected Blob.BakaShrot_StorageBlob, Received.q, StoreError.String, Expected.i + + *Chunk = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Chunk = BakaShrot_UploadChunkPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Chunk + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload chunk") + ProcedureReturn #False + EndIf + + ; Only its own uploads: same node, a topic it may still push to. + If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving + BakaShrot_UploadChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload in progress") + EndIf + If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId)) + BakaShrot_UploadChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") + EndIf + Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex) + If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected + BakaShrot_UploadChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes") + EndIf + + Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError) + BakaShrot_UploadChunkPacket_Free(*Chunk) + If Received < 0 + PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored") + EndIf + + If Received < Blob\Size + ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False) + EndIf + + ; All of it: the SHA-256 given at the start must match. + If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0]) + SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload doesn't match its SHA-256, it's dropped") + EndIf + If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be stored") + EndIf + ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True) +EndProcedure + + +; Answers with a part of a message's attachment, same permissions as +; reading the message. Refuses one that isn't all here yet. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_GetAttachment + Protected Chunk.BakaShrot_AttachmentChunk, Attachment.BakaShrot_StorageAttachment + Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, Index.q, DataSize.Integer + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_GetAttachmentPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment request") + ProcedureReturn #False + EndIf + TopicRef = *Request\Topic + NodeRef = *Request\Node + MessageId = *Request\MessageId + Index = *Request\ChunkIndex + FreeStructure(*Request) + + If Not *Client\Permissions\Read + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read") + EndIf + TopicId = BakaShrot_Names_ResolveTopic(TopicRef) + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + EndIf + If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + EndIf + NodeId = BakaShrot_Names_ResolveNode(NodeRef) + If NodeId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'") + EndIf + + If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId)) + EndIf + Select Attachment\State + Case #BakaShrot_Attachment_NotKept + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize") + Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes") + EndSelect + If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts") + EndIf + + Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize) + If Not Chunk\Data + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be read") + EndIf + Chunk\DataSize = DataSize\i + Chunk\TopicId = TopicId + Chunk\NodeId = NodeId + Chunk\MessageId = MessageId + Chunk\Size = Attachment\Size + Chunk\ChunkIndex = Index + CopyMemory(@Attachment\Sha256[0], @Chunk\Sha256[0], #BakaShrot_Sha256Size) + *Answer = BakaShrot_AttachmentChunkPacket_Encode(@Chunk, @AnswerSize) + FreeMemory(Chunk\Data) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + ProcedureReturn Sent +EndProcedure + + +; Tells a peer which attachments this server is missing, among what it +; takes from it (AcceptTopics, AcceptNodes): the peer sends what it has. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Request.BakaShrot_MissingAttachmentsRequest + Protected Answer.BakaShrot_MissingAttachments + Protected NewList Missing.BakaShrot_StorageMissingAttachment() + Protected *Answer, AnswerSize.Integer, Sent.i + + *Request = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Request = BakaShrot_MissingAttachmentsRequestPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Request + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid missing attachments request") + ProcedureReturn #False + EndIf + FreeStructure(*Request) + + If *Client\PeerName = "" + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + EndIf + + ; More than one answer holds, some of them may be someone else's. + If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing()) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The missing attachments couldn't be read") + EndIf + ForEach Missing() + If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments + Break + EndIf + If Not NameSetHas(@*Client\AcceptTopics, Missing()\TopicId, Missing()\Topic) Or Not NameSetHas(@*Client\AcceptNodes, Missing()\NodeId, Missing()\Node) + Continue + EndIf + If Not BakaShrot_IsValidName(Missing()\Topic) Or Not BakaShrot_IsValidName(Missing()\Node) + Continue + EndIf + AddElement(Answer\Attachments()) + Answer\Attachments()\Topic = Missing()\Topic + Answer\Attachments()\Node = Missing()\Node + Answer\Attachments()\MessageId = Missing()\MessageId + Answer\Attachments()\NextChunk = Missing()\Received / #BakaShrot_AttachmentChunkSize + Next + + *Answer = BakaShrot_MissingAttachmentsPacket_Encode(@Answer, @AnswerSize) + If Not *Answer + ProcedureReturn #False + EndIf + Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher) + FreeMemory(*Answer) + ProcedureReturn Sent +EndProcedure + + +; Stores a part of an attachment a peer replicates, of a message this server +; already has: in order, resuming where a previous link stopped. Once all of +; it is here, checks its SHA-256 (the one its message came with): ready, or +; dropped to be sent again. +; Returns #False if the client must be aborted. +Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i) + Protected *View.MsgPackData, *Chunk.BakaShrot_ReplicateAttachmentChunk + Protected Attachment.BakaShrot_StorageAttachment + Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, BlobId.q, Received.q, IsValid.i, StoreError.String + + *Chunk = 0 + *View = MsgPackWrapMsgBuffer(*Packet, PacketSize) + If *View + *Chunk = BakaShrot_ReplicateAttachmentChunkPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + If Not *Chunk + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment chunk") + ProcedureReturn #False + EndIf + TopicRef = *Chunk\Topic + NodeRef = *Chunk\Node + MessageId = *Chunk\MessageId + + If *Client\PeerName = "" + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + EndIf + TopicId = BakaShrot_Names_TopicByName(TopicRef) + NodeId = BakaShrot_Names_NodeByName(NodeRef) + If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef) + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here") + EndIf + + If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment) + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId)) + EndIf + If Attachment\State = #BakaShrot_Attachment_Ready + ; Someone else's link was faster: done. + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Attachment\Size, #True) + EndIf + If Attachment\State = #BakaShrot_Attachment_NotKept + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here") + EndIf + If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex) + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize)) + EndIf + + BlobId = Attachment\BlobId + If Not BlobId + BlobId = StartReplicatedAttachment(TopicId, NodeId, MessageId, @StoreError) + EndIf + If BlobId + Received = StoreStorageBlobChunk(BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError) + Else + Received = -1 + EndIf + BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) + If Received < 0 + PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored") + EndIf + + If Received < Attachment\Size + ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False) + EndIf + + IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0]) + If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be stored") + EndIf + If Not IsValid + PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment doesn't match its SHA-256, send it again") + EndIf + ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True) +EndProcedure + ; Handles one request from an authenticated client. ; Returns #False if the client must be aborted. @@ -1024,6 +1397,21 @@ Procedure.i BakaShrot_NetClient_HandleRequest(*Client.BakaShrot_NetClient, *Pack Case #BakaShrot_PacketType_ReplicateMessages ProcedureReturn BakaShrot_NetClient_HandleReplicateMessages(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_UploadStart + ProcedureReturn BakaShrot_NetClient_HandleUploadStart(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_UploadChunk + ProcedureReturn BakaShrot_NetClient_HandleUploadChunk(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_GetAttachment + ProcedureReturn BakaShrot_NetClient_HandleGetAttachment(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_MissingAttachmentsRequest + ProcedureReturn BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client, *Packet, PacketSize) + + Case #BakaShrot_PacketType_ReplicateAttachmentChunk + ProcedureReturn BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client, *Packet, PacketSize) EndSelect PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unexpected packet") diff --git a/Server/Networking/Peers.pbi b/Server/Networking/Peers.pbi index 831b1c9..d6ce543 100644 --- a/Server/Networking/Peers.pbi +++ b/Server/Networking/Peers.pbi @@ -27,6 +27,10 @@ ; bigger message goes alone, see ReplicateMessagesPacket.pbi), each ; batch stored in one transaction and answered before the next. The ; batches carry the names, the peer stores them under its own ids. +; A message's attachment only has its size and SHA-256 in the batch. +; 4. Once the messages are caught up, asks the peer which attachments it's +; missing (MissingAttachmentsRequest) and sends those it has, a part +; (1 MB) per request, from where the peer stopped (Design/Attachments.md). ; The peer does the same over its own link to this server, which covers the ; other direction. Any packet from the peer outside of a check-in drops the ; link as unexpected. @@ -143,6 +147,144 @@ Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, Ans EndProcedure +; Sends the peer the attachment it's missing, *Missing, from the part it +; asked for on, if this server has all of it and sends that topic/node to it. +; Returns 1 once the peer has it, 0 if it's skipped (not here, not sent to +; that peer, refused: logged), -1 if the link must be dropped. +Procedure.i BakaShrot_PeerLink_SendAttachment(*Link.BakaShrot_PeerLink, *Missing.BakaShrot_MissingAttachment) + Protected *Links.BakaShrot_PeerLinks = *Link\Links + Protected Attachment.BakaShrot_StorageAttachment, Chunk.BakaShrot_ReplicateAttachmentChunk + Protected *Stored.BakaShrot_ChunkStored + Protected TopicId.i, NodeId.i, Index.q, Count.q, DataSize.Integer, Complete.i + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i + + TopicId = BakaShrot_Names_TopicByName(*Missing\Topic) + NodeId = BakaShrot_Names_NodeByName(*Missing\Node) + If TopicId < 0 Or NodeId < 0 + ProcedureReturn 0 + EndIf + If Not NameSetHas(@*Link\SendTopics, TopicId, *Missing\Topic) Or Not NameSetHas(@*Link\SendNodes, NodeId, *Missing\Node) + ProcedureReturn 0 + EndIf + ; Not here either (yet, or not kept): another server may have it. + If Not GetStorageAttachment(*Link\DbId, TopicId, NodeId, *Missing\MessageId, @Attachment) Or Attachment\State <> #BakaShrot_Attachment_Ready + ProcedureReturn 0 + EndIf + + Count = BakaShrot_AttachmentChunkCount(Attachment\Size) + Chunk\Topic = *Missing\Topic + Chunk\Node = *Missing\Node + Chunk\MessageId = *Missing\MessageId + For Index = *Missing\NextChunk To Count - 1 + If *Links\StopRequested + ProcedureReturn -1 + EndIf + + Chunk\ChunkIndex = Index + Chunk\Data = ReadStorageBlobChunk(*Link\DbId, Attachment\BlobId, Index, @DataSize) + If Not Chunk\Data + PrintN("[Peer] Can't read part " + Str(Index) + " of the attachment of " + *Missing\Topic + ":" + *Missing\Node + "#" + Str(*Missing\MessageId) + " for '" + *Link\Name + "'") + ProcedureReturn 0 + EndIf + Chunk\DataSize = DataSize\i + *Packet = BakaShrot_ReplicateAttachmentChunkPacket_Encode(@Chunk, @PacketSize) + FreeMemory(Chunk\Data) + Chunk\Data = 0 + If Not *Packet + ProcedureReturn -1 + EndIf + *Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *Answer + ProcedureReturn -1 + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i) + FreeMemory(*Answer) + If Not IsRefusal + ProcedureReturn -1 + EndIf + ProcedureReturn 0 + EndIf + + *Stored = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Stored = BakaShrot_ChunkStoredPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Stored + PrintN("[Peer] '" + *Link\Name + "' sent an invalid answer to an attachment's part") + ProcedureReturn -1 + EndIf + Complete = *Stored\Complete + FreeStructure(*Stored) + If Complete + ProcedureReturn 1 + EndIf + Next + + ; All sent, and the peer didn't say it's complete: it'll ask again. + ProcedureReturn 0 +EndProcedure + + +; Once the messages are caught up: asks the peer which attachments it's +; missing, and sends those this server has, one after the other. +; Returns #False if the link must be dropped. +Procedure.i BakaShrot_PeerLink_SendAttachments(*Link.BakaShrot_PeerLink) + Protected Request.BakaShrot_MissingAttachmentsRequest, *Missing.BakaShrot_MissingAttachments + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i + Protected Result.i, StartTime.i, Attachment.BakaShrot_StorageAttachment, Key.s + + *Packet = BakaShrot_MissingAttachmentsRequestPacket_Encode(@Request, @PacketSize) + If Not *Packet + ProcedureReturn #False + EndIf + *Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize) + FreeMemory(*Packet) + If Not *Answer + PrintN("[Peer] '" + *Link\Name + "' didn't answer which attachments it's missing") + ProcedureReturn #False + EndIf + + If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused + IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i) + FreeMemory(*Answer) + ProcedureReturn IsRefusal + EndIf + + *Missing = 0 + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + If *View + *Missing = BakaShrot_MissingAttachmentsPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + If Not *Missing + PrintN("[Peer] '" + *Link\Name + "' sent an invalid list of missing attachments") + ProcedureReturn #False + EndIf + + ForEach *Missing\Attachments() + StartTime = ElapsedMilliseconds() + Result = BakaShrot_PeerLink_SendAttachment(*Link, @*Missing\Attachments()) + If Result < 0 + FreeStructure(*Missing) + ProcedureReturn #False + EndIf + If Result > 0 + Key = *Missing\Attachments()\Topic + ":" + *Missing\Attachments()\Node + "#" + Str(*Missing\Attachments()\MessageId) + PrintN("[Peer] Sent the attachment of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, from part " + Str(*Missing\Attachments()\NextChunk)) + EndIf + Next + FreeStructure(*Missing) + ProcedureReturn #True +EndProcedure + + ; Sends a batch of messages the peer is missing and checks its answer. ; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the ; link must be dropped. @@ -242,6 +384,10 @@ Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i, ; As stored: when it was pushed to its origin, whichever server that was. Batch\Messages()\PushedAt = Messages()\PushedAt Batch\Messages()\JsonData = Messages()\JsonData + ; Its attachment's size and SHA-256 only: the data goes once the + ; messages are caught up (BakaShrot_PeerLink_SendAttachments()). + Batch\Messages()\AttachmentSize = Messages()\AttachmentSize + CopyMemory(@Messages()\AttachmentSha256[0], @Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) Next If ListSize(Batch\Messages()) = 0 @@ -394,7 +540,8 @@ Procedure.i BakaShrot_PeerLink_CheckIn(*Link.BakaShrot_PeerLink) EndIf Next - ProcedureReturn #True + ; 4. Then the attachments: only for messages the peer has now. + ProcedureReturn BakaShrot_PeerLink_SendAttachments(*Link) EndProcedure diff --git a/Server/Storage/Attachments.pbi b/Server/Storage/Attachments.pbi new file mode 100644 index 0000000..11afd55 --- /dev/null +++ b/Server/Storage/Attachments.pbi @@ -0,0 +1,450 @@ +; ============================================================================ +; BakaShrot Storage Attachments +; +; A message has at most one attachment, of any size up to the server's +; MaxAttachmentSize, stored in parts (Design/Attachments.md): +; blobs the data of one attachment, being received or stored +; blob_chunks its parts, #BakaShrot_AttachmentChunkSize bytes each, the +; last one what's left +; attachments a message's: its size and SHA-256, and its blob once any +; of it is here +; See SetupStorageDatabase() in Storage.pbi for the columns and states. +; +; Pushed with a message: +; CreateStorageBlob() an upload starts (state 0), owned by the +; client's topic and node +; StoreStorageBlobChunk() each part, in order +; HashStorageBlob() once all of it is here, checked against the +; SHA-256 given at the start: complete (1), or +; dropped (3) +; then InsertNextMessage() (Writer.pbi) with its blob id attaches it to +; the message, in the same transaction (2). +; Replicated: the message comes first (ReplicateMessages), its attachments +; row in state 0, then once the messages are caught up: +; GetMissingStorageAttachments() what's missing, or started +; StartReplicatedAttachment() the first part makes its blob +; StoreStorageBlobChunk() each part, resuming where it stopped +; FinishReplicatedAttachment() ready (2), or back to missing if its +; SHA-256 doesn't match +; Deleting a message (the retention) deletes its attachments row (trigger), +; which marks its blob (3); CleanUpStorageBlobs() deletes it a part at a +; time, along with uploads never completed or never attached. +; +; Writes go through the writer (Writer.pbi), under its mutex; reads take +; the caller's own connection. +; ============================================================================ + +; SHA-256 (BakaShrot_Sha256_*). +XIncludeFile "../../Commons/Cryptography/Libsodium.pbi" + + +Structure BakaShrot_StorageBlob + BlobId.q + TopicId.i + NodeId.i + Size.q + Sha256.a[#BakaShrot_Sha256Size] + Received.q + State.i +EndStructure + +Structure BakaShrot_StorageAttachment + Size.q + Sha256.a[#BakaShrot_Sha256Size] + ; 0 while none of it is here. + BlobId.q + ; 0 missing, 1 receiving, 2 ready, 3 not kept here. + State.i + ; Of its blob, 0 without one. + Received.q +EndStructure + +Structure BakaShrot_StorageMissingAttachment + TopicId.i + NodeId.i + Topic.s + Node.s + MessageId.q + Received.q +EndStructure + +#BakaShrot_Blob_Receiving = 0 +#BakaShrot_Blob_Complete = 1 +#BakaShrot_Blob_Attached = 2 +#BakaShrot_Blob_Deleted = 3 + +#BakaShrot_Attachment_Missing = 0 +#BakaShrot_Attachment_Receiving = 1 +#BakaShrot_Attachment_Ready = 2 +#BakaShrot_Attachment_NotKept = 3 + + +; --- Reads, on the caller's connection ----------------------------------------- + +; Fills *Blob with blob BlobId. Returns #False if there's none. +Procedure.i GetStorageBlob(DbId.i, BlobId.q, *Blob.BakaShrot_StorageBlob) + Protected Found.i + + SetDatabaseQuad(DbId, 0, BlobId) + If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, size, sha256, received, state FROM blobs WHERE blob_id = ?") + ProcedureReturn #False + EndIf + Found = NextDatabaseRow(DbId) + If Found + *Blob\BlobId = BlobId + *Blob\TopicId = GetDatabaseLong(DbId, 0) + *Blob\NodeId = GetDatabaseLong(DbId, 1) + *Blob\Size = GetDatabaseQuad(DbId, 2) + FillMemory(@*Blob\Sha256[0], #BakaShrot_Sha256Size, 0) + If DatabaseColumnSize(DbId, 3) = #BakaShrot_Sha256Size + GetDatabaseBlob(DbId, 3, @*Blob\Sha256[0], #BakaShrot_Sha256Size) + EndIf + *Blob\Received = GetDatabaseQuad(DbId, 4) + *Blob\State = GetDatabaseLong(DbId, 5) + EndIf + FinishDatabaseQuery(DbId) + ProcedureReturn Found +EndProcedure + + +; Fills *Attachment with the attachment of TopicId:NodeId#MessageId. +; Returns #False if that message has none (or doesn't exist). +Procedure.i GetStorageAttachment(DbId.i, TopicId.i, NodeId.i, MessageId.q, *Attachment.BakaShrot_StorageAttachment) + Protected Found.i + + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + If Not DatabaseQuery(DbId, "SELECT a.size, a.sha256, COALESCE(a.blob_id, 0), a.state, COALESCE(b.received, 0) " + + "FROM attachments a LEFT JOIN blobs b ON b.blob_id = a.blob_id " + + "WHERE a.topic_id = ? AND a.node_id = ? AND a.message_id = ?") + ProcedureReturn #False + EndIf + Found = NextDatabaseRow(DbId) + If Found + *Attachment\Size = GetDatabaseQuad(DbId, 0) + FillMemory(@*Attachment\Sha256[0], #BakaShrot_Sha256Size, 0) + If DatabaseColumnSize(DbId, 1) = #BakaShrot_Sha256Size + GetDatabaseBlob(DbId, 1, @*Attachment\Sha256[0], #BakaShrot_Sha256Size) + EndIf + *Attachment\BlobId = GetDatabaseQuad(DbId, 2) + *Attachment\State = GetDatabaseLong(DbId, 3) + *Attachment\Received = GetDatabaseQuad(DbId, 4) + EndIf + FinishDatabaseQuery(DbId) + ProcedureReturn Found +EndProcedure + + +; Part Index of blob BlobId, in a freshly allocated buffer, its size in +; *OutSize\i. Returns 0 if it isn't stored. The caller frees it. +Procedure.i ReadStorageBlobChunk(DbId.i, BlobId.q, Index.q, *OutSize.Integer) + Protected *Data, Size.i + + SetDatabaseQuad(DbId, 0, BlobId) + SetDatabaseQuad(DbId, 1, Index) + If Not DatabaseQuery(DbId, "SELECT chunk_data FROM blob_chunks WHERE blob_id = ? AND chunk_index = ?") + ProcedureReturn 0 + EndIf + If NextDatabaseRow(DbId) + Size = DatabaseColumnSize(DbId, 0) + If Size > 0 + *Data = AllocateMemory(Size, #PB_Memory_NoClear) + If *Data + GetDatabaseBlob(DbId, 0, *Data, Size) + *OutSize\i = Size + EndIf + EndIf + EndIf + FinishDatabaseQuery(DbId) + ProcedureReturn *Data +EndProcedure + + +; Reads all of blob BlobId back (Size bytes, in parts) and checks its SHA-256 +; is *Sha256. Returns #False if it isn't, or a part is missing or the wrong +; size. ~3 s per GB. +Procedure.i HashStorageBlob(DbId.i, BlobId.q, Size.q, *Sha256) + Protected Hash.BakaShrot_Sha256, Index.q, Count.q, *Data, DataSize.Integer + Protected Dim Result.a(#BakaShrot_Sha256Size - 1) + + If Not BakaShrot_Sha256_Start(@Hash) + ProcedureReturn #False + EndIf + Count = BakaShrot_AttachmentChunkCount(Size) + For Index = 0 To Count - 1 + *Data = ReadStorageBlobChunk(DbId, BlobId, Index, @DataSize) + If Not *Data + ProcedureReturn #False + EndIf + If DataSize\i <> BakaShrot_AttachmentChunkBytes(Size, Index) + FreeMemory(*Data) + ProcedureReturn #False + EndIf + BakaShrot_Sha256_Add(@Hash, *Data, DataSize\i) + FreeMemory(*Data) + Next + BakaShrot_Sha256_Finish(@Hash, @Result(0)) + ProcedureReturn CompareMemory(@Result(0), *Sha256, #BakaShrot_Sha256Size) +EndProcedure + + +; Fills Missing() with attachments of messages here that aren't all here +; yet (missing or receiving), with their topic and node names, up to Limit. +; Unnamed topics or nodes are left out: replication goes by name. +; Returns #False if the query failed. +Procedure.i GetMissingStorageAttachments(DbId.i, Limit.i, List Missing.BakaShrot_StorageMissingAttachment()) + ClearList(Missing()) + SetDatabaseLong(DbId, 0, Limit) + If Not DatabaseQuery(DbId, "SELECT a.topic_id, a.node_id, t.name, n.name, a.message_id, COALESCE(b.received, 0) " + + "FROM attachments a JOIN topics t ON t.topic_id = a.topic_id JOIN nodes n ON n.node_id = a.node_id " + + "LEFT JOIN blobs b ON b.blob_id = a.blob_id " + + "WHERE a.state IN (0, 1) ORDER BY a.topic_id, a.node_id, a.message_id LIMIT ?") + ProcedureReturn #False + EndIf + While NextDatabaseRow(DbId) + AddElement(Missing()) + Missing()\TopicId = GetDatabaseLong(DbId, 0) + Missing()\NodeId = GetDatabaseLong(DbId, 1) + Missing()\Topic = GetDatabaseString(DbId, 2) + Missing()\Node = GetDatabaseString(DbId, 3) + Missing()\MessageId = GetDatabaseQuad(DbId, 4) + Missing()\Received = GetDatabaseQuad(DbId, 5) + Wend + FinishDatabaseQuery(DbId) + ProcedureReturn #True +EndProcedure + + +; --- Writes, through the writer ------------------------------------------------ + +; Starts an upload for TopicId/NodeId: Size bytes whose SHA-256 is *Sha256. +; Returns its blob id, 0 with the reason in *Error\s. +Procedure.q CreateStorageBlob(TopicId.i, NodeId.i, Size.q, *Sha256, *Error.String) + Protected DbId.i, BlobId.q + + LockMutex(BakaShrot_Storage_WriteMutex) + DbId = BakaShrot_Storage_Writer\DbId + If Not DbId + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn 0 + EndIf + + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, Size) + SetDatabaseBlob(DbId, 3, *Sha256, #BakaShrot_Sha256Size) + SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs()) + If DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) VALUES (?, ?, ?, ?, 0, 0, ?)") + If DatabaseQuery(DbId, "SELECT last_insert_rowid()") + If NextDatabaseRow(DbId) + BlobId = GetDatabaseQuad(DbId, 0) + EndIf + FinishDatabaseQuery(DbId) + EndIf + EndIf + If Not BlobId + *Error\s = DatabaseError() + EndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn BlobId +EndProcedure + + +; Stores part Index (DataSize bytes at *Data) of blob BlobId, which must be +; the next one: Index * #BakaShrot_AttachmentChunkSize bytes received so far. +; Returns how many are received now, -1 with the reason in *Error\s (nothing +; stored then). +Procedure.q StoreStorageBlobChunk(BlobId.q, Index.q, *Data, DataSize.i, *Error.String) + Protected DbId.i, Received.q = -1, Ok.i + + LockMutex(BakaShrot_Storage_WriteMutex) + DbId = BakaShrot_Storage_Writer\DbId + If Not DbId + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn -1 + EndIf + + If DatabaseUpdate(DbId, "BEGIN IMMEDIATE") + ; Only if it's the next one, and the blob is still being received. + SetDatabaseQuad(DbId, 0, DataSize) + SetDatabaseQuad(DbId, 1, BlobId) + SetDatabaseQuad(DbId, 2, Index * #BakaShrot_AttachmentChunkSize) + Ok = DatabaseUpdate(DbId, "UPDATE blobs SET received = received + ? WHERE blob_id = ? AND received = ? AND state = 0") + If Ok And AffectedDatabaseRows(DbId) <> 1 + Ok = #False + *Error\s = "not the next part, or not being received" + ElseIf Not Ok + *Error\s = DatabaseError() + EndIf + If Ok + SetDatabaseQuad(DbId, 0, BlobId) + SetDatabaseQuad(DbId, 1, Index) + SetDatabaseBlob(DbId, 2, *Data, DataSize) + Ok = DatabaseUpdate(DbId, "INSERT INTO blob_chunks (blob_id, chunk_index, chunk_data) VALUES (?, ?, ?)") + If Not Ok + *Error\s = DatabaseError() + EndIf + EndIf + If Ok And DatabaseUpdate(DbId, "COMMIT") + Received = Index * #BakaShrot_AttachmentChunkSize + DataSize + Else + If Ok + *Error\s = DatabaseError() + EndIf + DatabaseUpdate(DbId, "ROLLBACK") + EndIf + Else + *Error\s = DatabaseError() + EndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Received +EndProcedure + + +; Sets blob BlobId's state (#BakaShrot_Blob_*). Returns #False if it failed. +Procedure.i SetStorageBlobState(BlobId.q, State.i) + Protected DbId.i, Ok.i + + LockMutex(BakaShrot_Storage_WriteMutex) + DbId = BakaShrot_Storage_Writer\DbId + If DbId + SetDatabaseLong(DbId, 0, State) + SetDatabaseQuad(DbId, 1, BlobId) + Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = ? WHERE blob_id = ?") + EndIf + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Ok +EndProcedure + + +; Makes the blob of a replicated attachment that's still missing (state 0), +; from its row's size and SHA-256, and links it: receiving (1). +; Returns its blob id, 0 with the reason in *Error\s. +Procedure.q StartReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, *Error.String) + Protected DbId.i, BlobId.q, Ok.i + + LockMutex(BakaShrot_Storage_WriteMutex) + DbId = BakaShrot_Storage_Writer\DbId + If Not DbId + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn 0 + EndIf + + If DatabaseUpdate(DbId, "BEGIN IMMEDIATE") + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, BakaShrot_NowUtcMs()) + SetDatabaseLong(DbId, 3, TopicId) + SetDatabaseLong(DbId, 4, NodeId) + SetDatabaseQuad(DbId, 5, MessageId) + Ok = DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) " + + "SELECT ?, ?, size, sha256, 0, 0, ? FROM attachments WHERE topic_id = ? AND node_id = ? AND message_id = ? AND state = 0 AND blob_id IS NULL") + If Ok And AffectedDatabaseRows(DbId) = 1 And DatabaseQuery(DbId, "SELECT last_insert_rowid()") + If NextDatabaseRow(DbId) + BlobId = GetDatabaseQuad(DbId, 0) + EndIf + FinishDatabaseQuery(DbId) + EndIf + If BlobId + SetDatabaseQuad(DbId, 0, BlobId) + SetDatabaseLong(DbId, 1, TopicId) + SetDatabaseLong(DbId, 2, NodeId) + SetDatabaseQuad(DbId, 3, MessageId) + Ok = DatabaseUpdate(DbId, "UPDATE attachments SET blob_id = ?, state = 1 WHERE topic_id = ? AND node_id = ? AND message_id = ?") + EndIf + If BlobId And Ok And DatabaseUpdate(DbId, "COMMIT") + ; Done. + Else + *Error\s = DatabaseError() + If *Error\s = "" + *Error\s = "the attachment isn't missing" + EndIf + DatabaseUpdate(DbId, "ROLLBACK") + BlobId = 0 + EndIf + Else + *Error\s = DatabaseError() + EndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn BlobId +EndProcedure + + +; A replicated attachment is all here: ready (2) if its SHA-256 checked out +; (IsValid), else its blob is dropped and it's missing again (0), to be sent +; again from the start. Returns #False if it failed. +Procedure.i FinishReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, BlobId.q, IsValid.i) + Protected DbId.i, Ok.i + + LockMutex(BakaShrot_Storage_WriteMutex) + DbId = BakaShrot_Storage_Writer\DbId + If DbId And DatabaseUpdate(DbId, "BEGIN IMMEDIATE") + SetDatabaseQuad(DbId, 0, BlobId) + If IsValid + Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ?") + Else + Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE blob_id = ?") + EndIf + If Ok + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + If IsValid + Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 2 WHERE topic_id = ? AND node_id = ? AND message_id = ?") + Else + Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 0, blob_id = NULL WHERE topic_id = ? AND node_id = ? AND message_id = ?") + EndIf + EndIf + If Ok + Ok = DatabaseUpdate(DbId, "COMMIT") + EndIf + If Not Ok + DatabaseUpdate(DbId, "ROLLBACK") + EndIf + EndIf + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Ok +EndProcedure + + +; Marks uploads never completed nor attached, started before BeforeMs (ms +; since 1970 UTC), to delete, then deletes up to Limit parts of what's to +; delete, and the blobs left with none. Call it again while it returns +; Limit. Returns how many parts were deleted, -1 with the reason in *Error\s. +Procedure.i CleanUpStorageBlobs(BeforeMs.q, Limit.i, *Error.String) + Protected DbId.i, Deleted.i = -1 + + LockMutex(BakaShrot_Storage_WriteMutex) + DbId = BakaShrot_Storage_Writer\DbId + If Not DbId + UnlockMutex(BakaShrot_Storage_WriteMutex) + *Error\s = "the storage writer isn't open" + ProcedureReturn -1 + EndIf + + ; Uploads (no attachments row points to them) left behind. + SetDatabaseQuad(DbId, 0, BeforeMs) + If DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE state IN (0, 1) AND created_at < ? " + + "AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.blob_id = blobs.blob_id)") + SetDatabaseLong(DbId, 0, Limit) + If DatabaseUpdate(DbId, "DELETE FROM blob_chunks WHERE rowid IN (SELECT c.rowid FROM blob_chunks c JOIN blobs b ON b.blob_id = c.blob_id WHERE b.state = 3 LIMIT ?)") + Deleted = AffectedDatabaseRows(DbId) + If Deleted < Limit + DatabaseUpdate(DbId, "DELETE FROM blobs WHERE state = 3 AND NOT EXISTS (SELECT 1 FROM blob_chunks c WHERE c.blob_id = blobs.blob_id)") + EndIf + EndIf + EndIf + If Deleted < 0 + *Error\s = DatabaseError() + EndIf + + UnlockMutex(BakaShrot_Storage_WriteMutex) + ProcedureReturn Deleted +EndProcedure diff --git a/Server/Storage/Retention.pbi b/Server/Storage/Retention.pbi index e740605..122d7c8 100644 --- a/Server/Storage/Retention.pbi +++ b/Server/Storage/Retention.pbi @@ -13,7 +13,12 @@ ; - deletes its messages pushed (pushed_at) before now minus that age, ; #BakaShrot_Retention_BatchSize at a time through the writer ; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between -; the batches. +; the batches; +; - then the attachments' leftovers (CleanUpStorageBlobs(), +; Attachments.pbi): those of the deleted messages, and uploads not +; pushed with a message within [BakaShrot.Server] UploadTimeout, +; #BakaShrot_Retention_ChunkBatchSize parts at a time. +; It runs without any [BakaShrot.Retention] too, for the leftovers. ; ; Messages "may be" deleted past their max age: up to RetentionInterval ; later. Those a peer replicates here already past it aren't stored at all @@ -33,6 +38,9 @@ ; Most messages deleted in one statement, under the write mutex: a few ms. #BakaShrot_Retention_BatchSize = 5000 +; Most attachment parts (1 MB each) deleted in one statement. +#BakaShrot_Retention_ChunkBatchSize = 32 + Structure BakaShrot_RetentionTopic TopicId.i @@ -43,6 +51,7 @@ Structure BakaShrot_RetentionState ThreadId.i StopRequested.i IntervalMs.i + UploadTimeoutMs.q DatabasePath.s List Rules.BakaShrot_RetentionRule() EndStructure @@ -56,6 +65,25 @@ Procedure.s BakaShrot_Retention_FormatUtc(Ms.q) EndProcedure +; Deletes the attachments' leftovers, a few parts at a time. +Procedure BakaShrot_Retention_CleanUp() + Protected Deleted.i, Total.q, Error.String + + Repeat + Deleted = CleanUpStorageBlobs(BakaShrot_NowUtcMs() - BakaShrot_Retention\UploadTimeoutMs, #BakaShrot_Retention_ChunkBatchSize, @Error) + If Deleted < 0 + PrintN("[Storage] Retention: failed to delete the attachments' leftovers: " + Error\s) + Break + EndIf + Total + Deleted + Until Deleted < #BakaShrot_Retention_ChunkBatchSize Or BakaShrot_Retention\StopRequested + + If Total > 0 + PrintN("[Storage] Retention: deleted " + Str(Total) + " attachment parts (of deleted messages, or uploads never pushed)") + EndIf +EndProcedure + + ; Deletes what's past its max age in every topic. DbId is the thread's own ; connection, only read from (the deletes go through the writer). ; Returns how many messages were deleted. @@ -105,6 +133,7 @@ Procedure.q BakaShrot_Retention_Pass(DbId.i) EndIf Next + BakaShrot_Retention_CleanUp() ProcedureReturn Total EndProcedure @@ -132,27 +161,22 @@ Procedure BakaShrot_Retention_Thread(Unused.i) EndProcedure -; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, once -; the writer is open. Nothing to do (no thread) if every topic is kept -; forever. Returns #False if the thread can't start. +; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, and +; the attachments' leftovers, once the writer is open. +; Returns #False if the thread can't start. Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig) - Protected Deletes.i - With BakaShrot_Retention ClearList(\Rules()) CopyList(*Config\Retention(), \Rules()) ForEach \Rules() If \Rules()\MaxAgeMs > 0 - Deletes = #True PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s") EndIf Next - If Not Deletes - ProcedureReturn #True - EndIf - \DatabasePath = *Config\Server\DatabasePath - \IntervalMs = *Config\Server\RetentionInterval * 1000 + \DatabasePath = *Config\Server\DatabasePath + \IntervalMs = *Config\Server\RetentionInterval * 1000 + \UploadTimeoutMs = *Config\Server\UploadTimeout * 1000 \StopRequested = #False \ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0) ProcedureReturn Bool(\ThreadId) diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi index 7d53245..bf2f8c5 100644 --- a/Server/Storage/Storage.pbi +++ b/Server/Storage/Storage.pbi @@ -3,7 +3,8 @@ ; ; 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_v6.dbml in this same folder. +; Schema: see db_schema_v7.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 ; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official @@ -36,12 +37,18 @@ CompilerElse CompilerEndIf -; One row of the "data" table (see db_schema_v6.dbml). +; One row of the "data" table (see db_schema_v7.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 +; SHA-256. Structure BakaShrot_Message MessageId.q PushedAt.q JsonData.s + AttachmentSize.q + AttachmentReady.i + AttachmentSha256.a[#BakaShrot_Sha256Size] EndStructure @@ -225,7 +232,7 @@ Procedure.i MigrateStoragePushedAt(DbId.i) EndProcedure -; Creates the tables and indexes described by db_schema_v6.dbml, if they +; Creates the tables and indexes described by db_schema_v7.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. @@ -293,19 +300,60 @@ Procedure.i SetupStorageDatabase(DbId.i) ProcedureReturn #False EndIf - ; Not used yet, but created now so the on-disk schema already matches - ; db_schema_v1.dbml. - If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" + + ; The first schemas' placeholder, never used (and misspelled), replaced + ; by the three tables below. Its indexes go with it. + If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS attachements") + ProcedureReturn #False + EndIf + + ; Attachments, see Attachments.pbi and Design/Attachments.md. + ; blobs: an attachment's data, being uploaded or replicated, or stored. + ; topic_id, node_id: an upload's, who may attach it (or the message's). + ; received: bytes stored so far, in blob_chunks. + ; state: 0 receiving, 1 complete (an upload waiting for its message), + ; 2 attached to its message, 3 to delete (Retention.pbi deletes it). + ; created_at: ms since 1970 UTC, uploads left incomplete expire. + ; blob_chunks: its parts, #BakaShrot_AttachmentChunkSize bytes each. + ; attachments: a message's (one at most), with its size and SHA-256 + ; from the start, its data in blob_id once any is here. + ; state: 0 missing (a replicated message, none of it here yet), + ; 1 receiving, 2 ready, 3 not kept (bigger than this server takes). + If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blobs (" + + "blob_id INTEGER PRIMARY KEY, " + + "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)") Or + Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blob_chunks (" + + "blob_id INTEGER NOT NULL, " + + "chunk_index INTEGER NOT NULL, " + + "chunk_data BLOB NOT NULL, " + + "PRIMARY KEY (blob_id, chunk_index))") Or + Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachments (" + "topic_id INTEGER NOT NULL, " + "node_id INTEGER NOT NULL, " + "message_id INTEGER NOT NULL, " + - "attachement_data BLOB NOT NULL)") + "size INTEGER NOT NULL, " + + "sha256 BLOB NOT NULL, " + + "blob_id INTEGER, " + + "state INTEGER NOT NULL, " + + "PRIMARY KEY (topic_id, node_id, message_id)) WITHOUT ROWID") Or + Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_blobs_state ON blobs (state)") Or + Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments (state)") ProcedureReturn #False EndIf - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_topic_node ON attachements (topic_id, node_id)") - ProcedureReturn #False - EndIf - If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)") + + ; A message deleted (the retention) takes its attachment with it, and an + ; attachment its data: marked, Retention.pbi deletes it a bit at a time. + If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_attachments AFTER DELETE ON data BEGIN " + + "DELETE FROM attachments WHERE topic_id = OLD.topic_id AND node_id = OLD.node_id AND message_id = OLD.message_id; " + + "END") Or + Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_attachments_blobs AFTER DELETE ON attachments WHEN OLD.blob_id IS NOT NULL BEGIN " + + "UPDATE blobs SET state = 3 WHERE blob_id = OLD.blob_id; " + + "END") ProcedureReturn #False EndIf @@ -487,6 +535,18 @@ EndProcedure +; Reads the attachment's size, state and SHA-256 (COALESCE(a.size, 0), +; COALESCE(a.state, 0), a.sha256) from Column on into *Message. +Procedure BakaShrot_ReadAttachmentColumns(DbId.i, Column.i, *Message.BakaShrot_Message) + *Message\AttachmentSize = GetDatabaseQuad(DbId, Column) + *Message\AttachmentReady = Bool(*Message\AttachmentSize > 0 And GetDatabaseLong(DbId, Column + 1) = 2) + FillMemory(@*Message\AttachmentSha256[0], #BakaShrot_Sha256Size, 0) + If *Message\AttachmentSize > 0 And DatabaseColumnSize(DbId, Column + 2) = #BakaShrot_Sha256Size + GetDatabaseBlob(DbId, Column + 2, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size) + EndIf +EndProcedure + + ; Fills *Message with the message that has the highest message_id for a ; topic_id/node_id pair. ; Returns #False if there's none, or if the query failed. @@ -495,7 +555,9 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes SetDatabaseLong(DbId, 0, TopicId) SetDatabaseLong(DbId, 1, NodeId) - If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1") + If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " + + "FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " + + "WHERE d.topic_id = ? AND d.node_id = ? ORDER BY d.message_id DESC LIMIT 1") ProcedureReturn #False EndIf @@ -504,6 +566,7 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes *Message\MessageId = GetDatabaseQuad(DbId, 0) *Message\JsonData = GetDatabaseString(DbId, 1) *Message\PushedAt = GetDatabaseQuad(DbId, 2) + BakaShrot_ReadAttachmentColumns(DbId, 3, *Message) EndIf FinishDatabaseQuery(DbId) @@ -755,7 +818,9 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi SetDatabaseLong(DbId, 1, NodeId) SetDatabaseQuad(DbId, 2, AfterMessageId) SetDatabaseLong(DbId, 3, Limit + 1) - If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?") + If Not DatabaseQuery(DbId, "SELECT d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " + + "FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " + + "WHERE d.topic_id = ? AND d.node_id = ? AND d.message_id > ? ORDER BY d.message_id LIMIT ?") ProcedureReturn #False EndIf @@ -768,6 +833,7 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi Messages()\MessageId = GetDatabaseQuad(DbId, 0) Messages()\JsonData = GetDatabaseString(DbId, 1) Messages()\PushedAt = GetDatabaseQuad(DbId, 2) + BakaShrot_ReadAttachmentColumns(DbId, 3, @Messages()) Chars + Len(Messages()\JsonData) Wend FinishDatabaseQuery(DbId) @@ -800,6 +866,9 @@ EndProcedure ; Every write: pushes (group commit), replicated batches, the WAL checkpoints. XIncludeFile "Writer.pbi" +; Attachments: uploads, parts, reading them back, the replicated ones. +XIncludeFile "Attachments.pbi" + ; Usage example. Only compiled when this file is run directly (F5 in the ; IDE), not when it's included as a module by the rest of the project. diff --git a/Server/Storage/Writer.pbi b/Server/Storage/Writer.pbi index dd7bfe4..3ef561b 100644 --- a/Server/Storage/Writer.pbi +++ b/Server/Storage/Writer.pbi @@ -110,6 +110,8 @@ Structure BakaShrot_PushJob JsonData.s ; When it arrived, ms since 1970 UTC. PushedAt.q + ; Its attachment, a complete upload (blobs), 0 for none. + BlobId.q ; Filled in by whoever writes it, under the write mutex. MessageId.q @@ -641,6 +643,77 @@ Procedure BakaShrot_Writer_LogStats() EndProcedure +; Claims a complete upload (blobs state 1) of TopicId/NodeId for a message: +; state 2. Returns #False if it isn't one, someone else's, or attached already. +Procedure.i BakaShrot_Writer_ClaimBlob(BlobId.q, TopicId.i, NodeId.i) + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseQuad(DbId, 0, BlobId) + SetDatabaseLong(DbId, 1, TopicId) + SetDatabaseLong(DbId, 2, NodeId) + If Not DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ? AND topic_id = ? AND node_id = ? AND state = 1") + BakaShrot_Storage_Writer\LastError = DatabaseError() + ProcedureReturn #False + EndIf + If AffectedDatabaseRows(DbId) <> 1 + BakaShrot_Storage_Writer\LastError = "the upload isn't complete, or isn't this client's for that topic" + ProcedureReturn #False + EndIf + ProcedureReturn #True +EndProcedure + +; Gives a claimed upload back (state 1), its message couldn't be stored. +Procedure BakaShrot_Writer_UnclaimBlob(BlobId.q) + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseQuad(DbId, 0, BlobId) + DatabaseUpdate(DbId, "UPDATE blobs SET state = 1 WHERE blob_id = ?") +EndProcedure + +; The attachments row of a pushed message, from its claimed upload. +Procedure.i BakaShrot_Writer_LinkBlob(TopicId.i, NodeId.i, MessageId.q, BlobId.q) + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + SetDatabaseQuad(DbId, 3, BlobId) + If Not DatabaseUpdate(DbId, "INSERT INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) " + + "SELECT ?, ?, ?, size, sha256, blob_id, 2 FROM blobs WHERE blob_id = ?") Or AffectedDatabaseRows(DbId) <> 1 + BakaShrot_Storage_Writer\LastError = "can't attach the upload: " + DatabaseError() + ProcedureReturn #False + EndIf + ProcedureReturn #True +EndProcedure + +; Deletes a message just inserted in this transaction, its attachment failed. +Procedure BakaShrot_Writer_DropMessage(TopicId.i, NodeId.i, MessageId.q) + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, MessageId) + DatabaseUpdate(DbId, "DELETE FROM data WHERE topic_id = ? AND node_id = ? AND message_id = ?") +EndProcedure + +; The attachments row of a replicated message: its data comes later +; (Attachments.pbi), state 0 (missing), or 3 (not kept here) past MaxSize. +Procedure.i BakaShrot_Writer_AddReplicatedAttachment(TopicId.i, NodeId.i, *Message.BakaShrot_ReplicatedMessage, MaxSize.q) + Protected DbId.i = BakaShrot_Storage_Writer\DbId + SetDatabaseLong(DbId, 0, TopicId) + SetDatabaseLong(DbId, 1, NodeId) + SetDatabaseQuad(DbId, 2, *Message\MessageId) + SetDatabaseQuad(DbId, 3, *Message\AttachmentSize) + SetDatabaseBlob(DbId, 4, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size) + If *Message\AttachmentSize > MaxSize + SetDatabaseLong(DbId, 5, 3) + Else + SetDatabaseLong(DbId, 5, 0) + EndIf + If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) VALUES (?, ?, ?, ?, ?, NULL, ?)") + BakaShrot_Storage_Writer\LastError = DatabaseError() + ProcedureReturn #False + EndIf + ProcedureReturn #True +EndProcedure + + ; Writes queued pushes in one transaction, filling in their MessageId (-1 and ; Error if that one failed) and setting Done. Holding the write mutex. Procedure BakaShrot_Writer_WriteJobs(List Jobs.i()) @@ -656,12 +729,28 @@ Procedure BakaShrot_Writer_WriteJobs(List Jobs.i()) Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId) MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId) JsonData = *Job\JsonData + *Job\MessageId = -1 + + ; Its upload first: nothing is stored if it can't be claimed. + If MessageId > 0 And *Job\BlobId And Not BakaShrot_Writer_ClaimBlob(*Job\BlobId, *Job\TopicId, *Job\NodeId) + MessageId = -1 + EndIf + If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1 - *Job\MessageId = MessageId + If *Job\BlobId And Not BakaShrot_Writer_LinkBlob(*Job\TopicId, *Job\NodeId, MessageId, *Job\BlobId) + BakaShrot_Writer_DropMessage(*Job\TopicId, *Job\NodeId, MessageId) + BakaShrot_Writer_UnclaimBlob(*Job\BlobId) + Else + *Job\MessageId = MessageId + EndIf + ; Taken either way: node_heads went up. BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1 - Else - *Job\MessageId = -1 - *Job\Error = BakaShrot_Storage_Writer\LastError + ElseIf MessageId > 0 And *Job\BlobId + BakaShrot_Writer_UnclaimBlob(*Job\BlobId) + EndIf + + If *Job\MessageId < 1 + *Job\Error = BakaShrot_Storage_Writer\LastError EndIf Next @@ -685,9 +774,12 @@ EndProcedure ; Inserts one JSON message for a topic_id/node_id pair, with the next ; message_id for that pair, starting at 1, grouped with the other pushes -; arriving meanwhile. Stamped with the time it got here (pushed_at). Returns the new message's id once committed, or -1 with +; arriving meanwhile. Stamped with the time it got here (pushed_at). +; BlobId: its attachment, a complete upload of this topic and node +; (Attachments.pbi), 0 for none: attached in the same transaction. +; Returns the new message's id once committed, or -1 with ; the reason in *Error\s. -Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String) +Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String, BlobId.q = 0) Protected Job.BakaShrot_PushJob Protected NewList Jobs.i() Protected StartTicks.q @@ -696,6 +788,7 @@ Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String) Job\NodeId = NodeId Job\JsonData = JsonData Job\PushedAt = BakaShrot_NowUtcMs() + Job\BlobId = BlobId Job\MessageId = -1 LockMutex(BakaShrot_Storage_QueueMutex) @@ -761,8 +854,10 @@ EndProcedure ; past this server's max age for the topic already: not stored, but the ; pair's head still goes up to them, so the peer doesn't send them again. ; *Skipped\i, if given, gets how many. +; A message's attachment gets its row, its data comes later (Attachments.pbi), +; unless it's bigger than MaxAttachmentSize: not kept here then. ; Returns #False with the reason in *Error\s, the transaction is rolled back. -Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0) +Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0, MaxAttachmentSize.q = #BakaShrot_MaxAttachmentSize) Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q Key = Str(TopicId) + ":" + Str(NodeId) @@ -790,6 +885,10 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro Stored = #False Break EndIf + If Inserted = 1 And Messages()\AttachmentSize > 0 And Not BakaShrot_Writer_AddReplicatedAttachment(TopicId, NodeId, @Messages(), MaxAttachmentSize) + Stored = #False + Break + EndIf ; A pair pushed to here too (drift): the next push goes after it. If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key) If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds() diff --git a/Server/Storage/db_schema_v7.dbml b/Server/Storage/db_schema_v7.dbml new file mode 100644 index 0000000..dfbef56 --- /dev/null +++ b/Server/Storage/db_schema_v7.dbml @@ -0,0 +1,126 @@ +// Changes from v6 (Design/Attachments.md): +// - attachments, blobs, blob_chunks: a message's attachment (one at most), +// its data, in 1 MB parts. Replace the placeholder "attachements" table, +// dropped. +// - Triggers: deleting a message deletes its attachment row, which marks +// its blob to delete (Retention.pbi deletes the parts). +// +// 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]), "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]), "id" (unnamed), "peer" +// (only in databases from the short-lived version that added peer nodes). +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. + +// Note, ignore it +// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL diff --git a/Tests/AttachmentEdgeClient.pb b/Tests/AttachmentEdgeClient.pb new file mode 100644 index 0000000..b24d2b4 --- /dev/null +++ b/Tests/AttachmentEdgeClient.pb @@ -0,0 +1,373 @@ +; ============================================================================ +; A raw protocol client for the attachment cases the DLL never produces, run +; by Tests/AttachmentEdges-Test.ps1 against a running server. +; +; Usage: +; AttachmentEdgeClient edge +; Wrong SHA-256, parts out of order / of the wrong size / repeated, +; someone else's upload, the wrong topic, an upload attached twice, too +; big, a part out of range. Then starts two uploads it leaves behind +; (one half sent, one complete but never pushed) and prints +; "LEFT ". +; AttachmentEdgeClient late +; Once they expired: both refused. +; The inis are client.ini's: PrivateKey, PublicKey, ServerPublicKey, Topic, +; Node, ServerHost, ServerPort. Kitchen may push to logs and other, garage +; to logs; the server's MaxAttachmentSize must be under 1G. +; Compile as a thread-safe console program into Build\. Exits with 0 if +; every check passed, 1 otherwise. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Commons/Networking/Outbound.pbi" + +Structure EdgeClient + Outbound.BakaShrot_Outbound + Identity.BakaShrot_OutboundIdentity + PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize] + ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize] +EndStructure + +Global Fails.i = 0 + +Procedure Check(What.s, Ok.i, Detail.s = "") + If Ok + PrintN("PASS " + What) + Else + PrintN("FAIL " + What) + Fails + 1 + EndIf + PrintN(" -> " + Detail) +EndProcedure + +Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s) + Protected Host.s, Port.i, Ok.i + + If Not OpenPreferences(IniPath) + ProcedureReturn #False + EndIf + PreferenceGroup("BakaShrot") + Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) + Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)) + *Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "") + *Client\Identity\Topic = ReadPreferenceString("Topic", "") + *Client\Identity\Node = ReadPreferenceString("Node", "") + *Client\Identity\PrivateKey = @*Client\PrivateKey[0] + Host = ReadPreferenceString("ServerHost", "127.0.0.1") + Port = ReadPreferenceLong("ServerPort", 0) + ClosePreferences() + If Not Ok + ProcedureReturn #False + EndIf + ProcedureReturn BakaShrot_Outbound_Connect(@*Client\Outbound, Host, Port, @*Client\Identity, @*Client\ServerPublicKey[0]) +EndProcedure + +; Sends *Packet (freed), returns the answer with its type, 0 if the link failed. +Procedure.i Exchange(*Client.EdgeClient, *Packet, Size.i, *Type.Integer, *AnswerSize.Integer) + Protected *Answer + *Type\i = 0 + If Not *Packet + ProcedureReturn 0 + EndIf + If Not BakaShrot_Outbound_Send(@*Client\Outbound, *Packet, Size) + FreeMemory(*Packet) + ProcedureReturn 0 + EndIf + FreeMemory(*Packet) + *Answer = BakaShrot_Outbound_WaitPacket(@*Client\Outbound, *AnswerSize, 20000) + If *Answer + *Type\i = BakaShrot_GetPacketType(*Answer, *AnswerSize\i) + EndIf + ProcedureReturn *Answer +EndProcedure + +Procedure.s Refusal(*Answer, Size.i) + Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s + *View = MsgPackWrapMsgBuffer(*Answer, Size) + If *View + *Refused = BakaShrot_RequestRefusedPacket_Decode(*View) + MsgPackFree(*View, #False) + If *Refused + Reason = *Refused\Reason + FreeStructure(*Refused) + EndIf + EndIf + ProcedureReturn Reason +EndProcedure + +; Starts an upload. Returns its id, 0 if refused (reason in *Reason\s). +Procedure.q StartUpload(*Client.EdgeClient, Topic.s, Size.q, *Sha256, *Reason.String) + Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q + + *Reason\s = "" + Start\Topic = Topic + Start\Size = Size + CopyMemory(*Sha256, @Start\Sha256[0], #BakaShrot_Sha256Size) + *Packet = BakaShrot_UploadStartPacket_Encode(@Start, @PacketSize) + *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) + If Not *Answer + *Reason\s = "the link failed" + ProcedureReturn 0 + EndIf + If Type\i = #BakaShrot_PacketType_RequestRefused + *Reason\s = Refusal(*Answer, AnswerSize\i) + ElseIf Type\i = #BakaShrot_PacketType_UploadStarted + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + *Started = BakaShrot_UploadStartedPacket_Decode(*View) + MsgPackFree(*View, #False) + If *Started + Id = *Started\UploadId + FreeStructure(*Started) + EndIf + EndIf + FreeMemory(*Answer) + ProcedureReturn Id +EndProcedure + +; Sends a part. Returns 1 if stored (*Complete\i set), 0 if refused (reason), -1 if the link failed. +Procedure.i SendChunk(*Client.EdgeClient, UploadId.q, Index.i, *Data, Size.i, *Complete.Integer, *Reason.String) + Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Result.i = -1 + + *Reason\s = "" + Chunk\UploadId = UploadId + Chunk\ChunkIndex = Index + Chunk\Data = *Data + Chunk\DataSize = Size + *Packet = BakaShrot_UploadChunkPacket_Encode(@Chunk, @PacketSize) + *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) + If Not *Answer + ProcedureReturn -1 + EndIf + If Type\i = #BakaShrot_PacketType_RequestRefused + *Reason\s = Refusal(*Answer, AnswerSize\i) + Result = 0 + ElseIf Type\i = #BakaShrot_PacketType_ChunkStored + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + *Stored = BakaShrot_ChunkStoredPacket_Decode(*View) + MsgPackFree(*View, #False) + If *Stored + *Complete\i = *Stored\Complete + FreeStructure(*Stored) + Result = 1 + EndIf + EndIf + FreeMemory(*Answer) + ProcedureReturn Result +EndProcedure + +; Pushes a message with UploadId. Returns its id, 0 if refused (reason). +Procedure.q Push(*Client.EdgeClient, Topic.s, Json.s, UploadId.q, *Reason.String) + Protected Push.BakaShrot_PushMessage, *Pushed.BakaShrot_MessagePushed + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q + + *Reason\s = "" + Push\Topic = Topic + Push\JsonData = Json + Push\UploadId = UploadId + *Packet = BakaShrot_PushMessagePacket_Encode(@Push, @PacketSize) + *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) + If Not *Answer + *Reason\s = "the link failed" + ProcedureReturn 0 + EndIf + If Type\i = #BakaShrot_PacketType_RequestRefused + *Reason\s = Refusal(*Answer, AnswerSize\i) + ElseIf Type\i = #BakaShrot_PacketType_MessagePushed + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + *Pushed = BakaShrot_MessagePushedPacket_Decode(*View) + MsgPackFree(*View, #False) + If *Pushed + Id = *Pushed\MessageId + FreeStructure(*Pushed) + EndIf + EndIf + FreeMemory(*Answer) + ProcedureReturn Id +EndProcedure + +; Asks for a part. Returns it (free with _Free), 0 if refused (reason). +Procedure.i GetChunk(*Client.EdgeClient, Topic.s, Node.s, MessageId.q, Index.i, *Reason.String) + Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk + Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData + + *Reason\s = "" + Request\Topic = Topic + Request\Node = Node + Request\MessageId = MessageId + Request\ChunkIndex = Index + *Packet = BakaShrot_GetAttachmentPacket_Encode(@Request, @PacketSize) + *Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize) + If Not *Answer + *Reason\s = "the link failed" + ProcedureReturn 0 + EndIf + If Type\i = #BakaShrot_PacketType_RequestRefused + *Reason\s = Refusal(*Answer, AnswerSize\i) + ElseIf Type\i = #BakaShrot_PacketType_AttachmentChunk + *View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i) + *Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View) + MsgPackFree(*View, #False) + EndIf + FreeMemory(*Answer) + ProcedureReturn *Chunk +EndProcedure + +; Size random bytes. +Procedure.i RandomBytes(Size.i) + Protected *Data = AllocateMemory(Size) + RandomData(*Data, Size) + ProcedureReturn *Data +EndProcedure + +Procedure Sha256Of(*Data, Size.q, *Out) + Protected Hash.BakaShrot_Sha256 + BakaShrot_Sha256_Start(@Hash) + BakaShrot_Sha256_Add(@Hash, *Data, Size) + BakaShrot_Sha256_Finish(@Hash, *Out) +EndProcedure + +; Uploads Size bytes of *Data properly. Returns the upload id, 0 on failure. +Procedure.q UploadAll(*Client.EdgeClient, Topic.s, *Data, Size.q) + Protected Dim Sha.a(31), Id.q, Index.i, Complete.Integer, Reason.String + Sha256Of(*Data, Size, @Sha(0)) + Id = StartUpload(*Client, Topic, Size, @Sha(0), @Reason) + If Not Id + ProcedureReturn 0 + EndIf + For Index = 0 To BakaShrot_AttachmentChunkCount(Size) - 1 + If SendChunk(*Client, Id, Index, *Data + Index * #BakaShrot_AttachmentChunkSize, BakaShrot_AttachmentChunkBytes(Size, Index), @Complete, @Reason) <> 1 + ProcedureReturn 0 + EndIf + Next + If Not Complete\i + ProcedureReturn 0 + EndIf + ProcedureReturn Id +EndProcedure + + +Define Kitchen.EdgeClient, Garage.EdgeClient, Reason.String, Complete.Integer +Define Dim Sha.a(31), Dim WrongSha.a(31) +Define *Data, *Other, Id.q, Id2.q, MessageId.q, Result.i, *Chunk.BakaShrot_AttachmentChunk, Size.q +Define PartialId.q, CompleteId.q + +OpenConsole() +If CountProgramParameters() < 3 + PrintN("Usage: AttachmentEdgeClient edge | late ") + End 1 +EndIf +If Not ConnectIni(@Kitchen, ProgramParameter(1)) + PrintN("FAIL can't connect with " + ProgramParameter(1)) + End 1 +EndIf + +If LCase(ProgramParameter(0)) = "late" + PartialId = Val(ProgramParameter(2)) + CompleteId = Val(ProgramParameter(3)) + *Data = RandomBytes(#BakaShrot_AttachmentChunkSize) + Result = SendChunk(@Kitchen, PartialId, 1, *Data, 1000, @Complete, @Reason) + Check("An expired upload: its next part refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s) + MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "late" + Chr(34) + ":1}", CompleteId, @Reason) + Check("An expired complete upload: pushing with it refused", Bool(MessageId = 0 And (FindString(Reason\s, "No such upload") Or FindString(Reason\s, "isn't complete"))), Reason\s) + Check("Still connected after the refusals", BakaShrot_Outbound_IsConnected(@Kitchen\Outbound)) + BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected) + PrintN("") + If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf + PrintN("All passed") + End 0 +EndIf + +If Not ConnectIni(@Garage, ProgramParameter(2)) + PrintN("FAIL can't connect with " + ProgramParameter(2)) + End 1 +EndIf + +; --- A wrong SHA-256 -------------------------------------------------------------- +Size = #BakaShrot_AttachmentChunkSize + 500000 +*Data = RandomBytes(Size) +*Other = RandomBytes(Size) +Sha256Of(*Other, Size, @WrongSha(0)) +Id = StartUpload(@Kitchen, "logs", Size, @WrongSha(0), @Reason) +Check("Upload with a wrong SHA-256: started", Bool(Id > 0), Reason\s) +Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +Check(" part 0 stored, not complete", Bool(Result = 1 And Complete\i = 0), Reason\s) +Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason) +Check(" the last part: refused, doesn't match", Bool(Result = 0 And FindString(Reason\s, "doesn't match its SHA-256")), Reason\s) +MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "bad" + Chr(34) + ":1}", Id, @Reason) +Check(" pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "isn't complete")), Reason\s) +Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason) +Check(" sending the last part again: refused, it's dropped", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s) + +; --- Parts out of order, wrong size, repeated --------------------------------------- +Size = 2 * #BakaShrot_AttachmentChunkSize + 1234 +FreeMemory(*Data) : *Data = RandomBytes(Size) +Sha256Of(*Data, Size, @Sha(0)) +Id = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason) +Check("Upload of 3 parts: started", Bool(Id > 0), Reason\s) +Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +Check(" part 1 first: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 0 of 3")), Reason\s) +Result = SendChunk(@Kitchen, Id, 0, *Data, 1000, @Complete, @Reason) +Check(" part 0 too short: refused", Bool(Result = 0 And FindString(Reason\s, "1048576 bytes")), Reason\s) +Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +Check(" part 0 right: stored, the refusals didn't drop the upload", Bool(Result = 1 And Complete\i = 0), Reason\s) +Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +Check(" part 0 again: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 1")), Reason\s) +Result = SendChunk(@Garage, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +Check(" part 1 from another client: refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s) +Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +Check(" part 1: stored", Bool(Result = 1 And Complete\i = 0), Reason\s) +Result = SendChunk(@Kitchen, Id, 2, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234, @Complete, @Reason) +Check(" part 2, the last: complete", Bool(Result = 1 And Complete\i = 1), Reason\s) +Result = SendChunk(@Kitchen, Id, 3, *Data, 10, @Complete, @Reason) +Check(" a part past the end: refused", Bool(Result = 0), Reason\s) + +; --- Whose, which topic, how many times ------------------------------------------------- +MessageId = Push(@Garage, "logs", "{" + Chr(34) + "theirs" + Chr(34) + ":1}", Id, @Reason) +Check("Another client pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "No such upload")), Reason\s) +MessageId = Push(@Kitchen, "other", "{" + Chr(34) + "topic" + Chr(34) + ":1}", Id, @Reason) +Check("Pushing it to another topic: refused", Bool(MessageId = 0 And FindString(Reason\s, "is for topic 'logs'")), Reason\s) +MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":1}", Id, @Reason) +Check("Pushing it: stored", Bool(MessageId > 0), "message #" + Str(MessageId) + " " + Reason\s) +Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":2}", Id, @Reason) +Check("Pushing it again: refused, attached already", Bool(Id2 = 0 And FindString(Reason\s, "attached already")), Reason\s) +Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":3}", 999999, @Reason) +Check("An upload id that doesn't exist: refused", Bool(Id2 = 0 And FindString(Reason\s, "No such upload")), Reason\s) + +; --- Reading it back, part by part --------------------------------------------------------- +*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 2, @Reason) +Check("GetAttachment part 2 first: the right bytes", Bool(*Chunk And *Chunk\DataSize = 1234 And *Chunk\Size = Size And CompareMemory(*Chunk\Data, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234) And CompareMemory(@*Chunk\Sha256[0], @Sha(0), 32)), Reason\s) +BakaShrot_AttachmentChunkPacket_Free(*Chunk) +*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 0, @Reason) +Check(" part 0: the right bytes", Bool(*Chunk And *Chunk\DataSize = #BakaShrot_AttachmentChunkSize And CompareMemory(*Chunk\Data, *Data, #BakaShrot_AttachmentChunkSize)), Reason\s) +BakaShrot_AttachmentChunkPacket_Free(*Chunk) +*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 3, @Reason) +Check(" part 3, past the end: refused", Bool(Not *Chunk And FindString(Reason\s, "has 3 parts")), Reason\s) +*Chunk = GetChunk(@Garage, "secret", "kitchen", MessageId, 0, @Reason) +Check(" from a topic garage may not read: refused", Bool(Not *Chunk And FindString(Reason\s, "Not allowed to read topic")), Reason\s) + +; --- Limits ------------------------------------------------------------------------------------ +Id = StartUpload(@Kitchen, "logs", 1024 * 1024 * 1024, @Sha(0), @Reason) +Check("Upload of 1 GB (over MaxAttachmentSize): refused", Bool(Id = 0 And FindString(Reason\s, "too big")), Reason\s) +Id = StartUpload(@Garage, "other", 1000, @Sha(0), @Reason) +Check("Upload to a topic garage may not push to: refused", Bool(Id = 0 And FindString(Reason\s, "Not allowed to push")), Reason\s) +Check("Both still connected after every refusal", Bool(BakaShrot_Outbound_IsConnected(@Kitchen\Outbound) And BakaShrot_Outbound_IsConnected(@Garage\Outbound))) + +; --- Left behind, for the expiry --------------------------------------------------------------------- +Size = 2 * #BakaShrot_AttachmentChunkSize +FreeMemory(*Data) : *Data = RandomBytes(Size) +Sha256Of(*Data, Size, @Sha(0)) +PartialId = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason) +Result = SendChunk(@Kitchen, PartialId, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason) +CompleteId = UploadAll(@Kitchen, "logs", *Data, 5000) +Check("Two uploads left behind: half sent, and complete but never pushed", Bool(PartialId > 0 And Result = 1 And CompleteId > 0), Str(PartialId) + ", " + Str(CompleteId)) + +BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected) +BakaShrot_Outbound_Close(@Garage\Outbound, #BakaShrot_ConnectionStatus_Disconnected) +PrintN("LEFT " + Str(PartialId) + " " + Str(CompleteId)) +PrintN("") +If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf +PrintN("All passed") +End 0 diff --git a/Tests/AttachmentEdges-Test.ps1 b/Tests/AttachmentEdges-Test.ps1 new file mode 100644 index 0000000..f53cf19 --- /dev/null +++ b/Tests/AttachmentEdges-Test.ps1 @@ -0,0 +1,287 @@ +# The attachment cases the regular clients never produce (Design/Attachments.md): +# 1. Through a raw client (Tests/AttachmentEdgeClient.pb): a wrong SHA-256, +# parts out of order / of the wrong size / repeated, someone else's +# upload, the wrong topic, an upload attached twice, too big, a part +# out of range. +# 2. Uploads left behind: kept within UploadTimeout, deleted past it, then +# refused. +# 3. Replication resuming: the receiving server killed in the middle of a +# 400 MB attachment, restarted, the sender goes on from where it stopped. +# 4. A corrupted attachment (bytes flipped in the sender's database): the +# client refuses it, the peer drops it and doesn't keep it. +# Two servers, A (port 12413) and B (12414). Needs Build\ (Build.ps1), +# Build\Bench\BenchServer.exe, Build\AttachmentEdgeClient.exe (compile +# Tests\AttachmentEdgeClient.pb, thread-safe console), and Python 3 for 4. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\AttachmentEdges-Test.ps1 [-Python ] +param( + [string]$Build = (Join-Path $PSScriptRoot "..\Build"), + [string]$Python = "python" +) +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_attachedges" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Fails = 0 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +function Tool([string]$Name, [string[]]$A) { + $O = & (Join-Path $Build $Name) @A 2>&1 + @{ Code = $LASTEXITCODE; Out = ($O -join " | "); Lines = @($O) } +} +function Check([string]$What, [bool]$Ok, [string]$Detail) { + if (-not $Ok) { $script:Fails++ } + "{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail +} +function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { + Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out) +} +function Start-Srv($Name) { + $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Stop -ErrorAction SilentlyContinue + # Each run its own log: a restart doesn't overwrite the last one's. + $script:Runs[$Name]++ + $Log = Join-Path $Dir "$Name.$($script:Runs[$Name]).log" + $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput $Log -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Stop = $Stop; Name = $Name; Log = $Log } +} +$Runs = @{ a = 0; b = 0 } +function Stop-Srv($S) { + if (-not $S -or $S.P.HasExited) { return } + Set-Content $S.Stop "x" + if (-not $S.P.WaitForExit(30000)) { Stop-Process -Id $S.P.Id -Force } +} +function Wait-Port($Port, $S) { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content $S.Log -Raw)" } + if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } + Start-Sleep -Milliseconds 100 + } +} +function Query($Sql, $Ini) { + $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql + Tool "Query.exe" @("@$F", $Ini) +} +function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { + $D = (Get-Date).AddSeconds($Seconds) + do { + $R = Query $Sql $Ini + if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $D) + $R +} +function Push($Data, $Ini, [string]$Attach = "") { + $F = Join-Path $Dir "push.txt" + [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) + $A = @() + if ($Attach) { $A += @("-a", $Attach) } + Tool "PushMessage.exe" ($A + @("@$F", $Ini)) +} +function New-File($Name, [int64]$Size, [int]$Seed) { + $P = Join-Path $Dir $Name + $R = New-Object System.Random $Seed + $Buf = New-Object byte[] ([math]::Min($Size, 16MB)) + $F = [IO.File]::OpenWrite($P) + $Left = $Size + while ($Left -gt 0) { $R.NextBytes($Buf); $N = [math]::Min($Left, $Buf.Length); $F.Write($Buf, 0, $N); $Left -= $N } + $F.Close() + $P +} +function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } } +function Num($Out) { if ($Out -match '\[\["(\d+)"\]\]') { [int64]$Matches[1] } else { -1 } } + +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair + +foreach ($Name in "a", "b") { + $Me = @{ a = $A; b = $B }[$Name]; $Peer = @{ a = $B; b = $A }[$Name] + $PeerName = @{ a = "b"; b = "a" }[$Name] + $Port = @{ a = 12413; b = 12414 }[$Name]; $PeerPort = @{ a = 12414; b = 12413 }[$Name] + $Base = @{ a = 1; b = 100 }[$Name] + Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($Me.Priv) +Topic = logs +Node = server$Name + +[BakaShrot.Topics] +logs = $Base +other = $($Base + 1) +secret = $($Base + 2) + +[BakaShrot.Nodes] +servera = $($Base + 10) +serverb = $($Base + 11) +kitchen = $($Base + 2) +garage = $($Base + 3) + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = $Port +ReplicatingTopics = logs +DatabasePath = $(Join-Path $Dir "$Name.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +RetentionInterval = 1 +MaxAttachmentSize = 512M +UploadTimeout = 10 + +[BakaShrot.Peer.$PeerName] +Host = 127.0.0.1 +Port = $PeerPort +Topic = logs +Node = server$PeerName +PublicKey = $($Peer.Pub) + +[BakaShrot.Client.$PeerName] +PublicKeys = $($Peer.Pub) +Identities = logs:server$PeerName + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +PushTopics = logs;other;secret +ReadTopics = * +AllowQuery = 1 + +[BakaShrot.Client.garage] +PublicKeys = $($G.Pub) +Identities = logs:garage +PushTopics = logs +ReadTopics = logs +"@ +} +$ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub } +function Client-Ini($Name, $Keys, $Node, $Port) { + $P = Join-Path $Dir "$Name.ini" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + $P +} +$KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413 +$GarageA = Client-Ini "garage-a" $G "garage" 12413 +$KitchenB = Client-Ini "kitchen-b" $K "kitchen" 12414 + +foreach ($Port in 12413, 12414) { if (Test-Port $Port) { throw "Port $Port is already in use" } } +$SA = Start-Srv "a"; $SB = $null +try { + Wait-Port 12413 $SA + + "--- 1. Through the raw client" + $R = Tool "AttachmentEdgeClient.exe" @("edge", $KitchenA, $GarageA) + $R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" } + $Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count + Check "the raw client ran to the end" ($R.Code -ne $null -and ($R.Out -match "LEFT (\d+) (\d+)")) $R.Lines[-1] + $Partial = $Matches[1]; $Complete = $Matches[2] + $LeftAt = Get-Date + + "--- 2. Uploads left behind (UploadTimeout = 10)" + $Sql = "SELECT blob_id, state, received FROM blobs WHERE blob_id IN ($Partial, $Complete) ORDER BY blob_id" + $R = Query $Sql $KitchenA + Check "within UploadTimeout: both kept, receiving (0) and complete (1)" ($R.Out -match "\[\[`"$Partial`",`"0`",`"1048576`"\],\[`"$Complete`",`"1`",`"5000`"\]\]") $R.Out + $R = Wait-Query "SELECT COUNT(*) FROM blobs WHERE blob_id IN ($Partial, $Complete)" $KitchenA '\[\["0"\]\]' 25 + $After = ((Get-Date) - $LeftAt).TotalSeconds + Check "past it: both deleted" ($R.Out -match '\[\["0"\]\]') ("{0:N1} s after they were left" -f $After) + Check " not before 10 s" ($After -ge 8) ("{0:N1} s" -f $After) + Expect " their parts too" (Query "SELECT COUNT(*) FROM blob_chunks WHERE blob_id IN ($Partial, $Complete)" $KitchenA) '\[\["0"\]\]' + Expect " and the one with the wrong SHA-256 (dropped at once)" (Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenA) '\[\["0"\]\]' + Expect " the attached one is kept" (Query "SELECT COUNT(*) FROM blobs WHERE state = 2" $KitchenA) '\[\["1"\]\]' + $R = Tool "AttachmentEdgeClient.exe" @("late", $KitchenA, $Partial, $Complete) + $R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" } + $Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count + + "--- 3. Replication resuming (B killed in the middle of 400 MB)" + $Big = New-File "big.bin" 400MB 9 + $R = Push '{"big":1}' $KitchenA $Big + Check "push 400 MB to A" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out + $BigId = $Matches[1] + $SB = Start-Srv "b" + Wait-Port 12414 $SB + $Received = "SELECT COALESCE(MAX(b.received), 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id LEFT JOIN blobs b ON b.blob_id = a.blob_id WHERE t.name = 'logs' AND a.message_id = $BigId" + $KilledAt = -1 + $D = (Get-Date).AddSeconds(60) + while ((Get-Date) -lt $D) { + $N = Num (Query $Received $KitchenB).Out + if ($N -ge 40MB) { Stop-Process -Id $SB.P.Id -Force; $SB.P.WaitForExit(10000) | Out-Null; $KilledAt = $N; break } + Start-Sleep -Milliseconds 50 + } + Check "B killed in the middle" ($KilledAt -gt 0 -and $KilledAt -lt 400MB) ("{0:N0} MB of 400 received" -f ($KilledAt / 1MB)) + $SB = Start-Srv "b" + Wait-Port 12414 $SB + $AfterRestart = Num (Query $Received $KitchenB).Out + Check "after the restart, what it had is still there" ($AfterRestart -ge $KilledAt) ("{0:N0} MB" -f ($AfterRestart / 1MB)) + $Copy = Join-Path $Dir "big-from-b.bin" + $D = (Get-Date).AddSeconds(90) + do { + $R = Tool "GetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB) + if ($R.Code -eq 0) { break } + Start-Sleep -Milliseconds 500 + } while ((Get-Date) -lt $D) + Check "B ends up with all of it, identical" ($R.Code -eq 0 -and (Hash $Copy) -eq (Hash $Big)) $R.Out + $LogA = (Get-ChildItem $Dir -Filter "a.*.log" | ForEach-Object { Get-Content $_.FullName -Raw }) -join "`n" + $Resumed = [regex]::Matches($LogA, "Sent the attachment of logs:kitchen#$BigId to 'b' in \d+ ms, from part (\d+)") + $From = if ($Resumed.Count) { [int]$Resumed[$Resumed.Count - 1].Groups[1].Value } else { -1 } + Check "A went on from where B stopped, not from 0" ($From -gt 0 -and $From * 1MB -le $AfterRestart) ("from part $From, B had {0:N0} MB" -f ($AfterRestart / 1MB)) + Remove-Item $Copy, $Big -ErrorAction SilentlyContinue + + "--- 4. A corrupted attachment" + $HasPython = $false + try { & $Python -c "import sqlite3" 2>&1 | Out-Null; $HasPython = ($LASTEXITCODE -eq 0) } catch { } + if (-not $HasPython) { + "SKIP no Python ($Python)" + } else { + Stop-Srv $SB; $SB = $null + $Small = New-File "small.bin" (3MB + 99) 10 + $R = Push '{"corrupt":1}' $KitchenA $Small + Check "push 3 MB to A, B stopped" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out + $BadId = $Matches[1] + Stop-Srv $SA + $Flip = @" +import sqlite3, sys +db = sqlite3.connect(sys.argv[1]) +row = db.execute("SELECT c.rowid, c.chunk_data FROM blob_chunks c JOIN attachments a ON a.blob_id = c.blob_id WHERE a.message_id = ? AND a.topic_id = 1 AND c.chunk_index = 1", (int(sys.argv[2]),)).fetchone() +data = bytearray(row[1]); data[1000] ^= 0xFF +db.execute("UPDATE blob_chunks SET chunk_data = ? WHERE rowid = ?", (bytes(data), row[0])) +db.commit(); print("flipped") +"@ + Set-Content (Join-Path $Dir "flip.py") -Encoding Ascii -Value $Flip + $Out = & $Python -B (Join-Path $Dir "flip.py") (Join-Path $Dir "a.sqlite") $BadId 2>&1 + Check "a byte flipped in A's database, part 1" ("$Out" -eq "flipped") "$Out" + $SA = Start-Srv "a" + Wait-Port 12413 $SA + $Copy = Join-Path $Dir "bad-from-a.bin" + Expect "reading it from A: the client refuses it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1 + Check " and leaves no file" (-not (Test-Path $Copy)) "checked" + $SB = Start-Srv "b" + Wait-Port 12414 $SB + Start-Sleep -Seconds 6 + $LogB = Get-Content $SB.Log -Raw + $Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count + Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s" + Expect "B doesn't serve it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1 + $R = Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB + Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out + Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]' + "INFO A sends it again at every check-in: $Drops times in 6 s (PeerSyncInterval 1)" + } +} +finally { + Stop-Srv $SA; Stop-Srv $SB +} + +"--- Logs" +$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -match "invalid|unexpected|doesn't decrypt" } +Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ") + +"" +if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/Attachments-Test.ps1 b/Tests/Attachments-Test.ps1 new file mode 100644 index 0000000..74e2968 --- /dev/null +++ b/Tests/Attachments-Test.ps1 @@ -0,0 +1,296 @@ +# End-to-end test of attachments (Design/Attachments.md), through the tools +# (PushMessage -a, GetAttachment, GetLatestMessage): +# - pushed with a message, read back identical (100 KB, 5 MB + a bit, +# exactly 2 MB: one part, several, a whole number of them); +# - a message without one: refused when asked for it; +# - replicated after their messages, identical on the other server; +# - bigger than the other server's MaxAttachmentSize: its message comes, +# the attachment is refused there as not kept; +# - too big to push: refused, and the message isn't stored; +# - deleted with their message by the retention, parts included. +# Two linked servers, A (port 12410, MaxAttachmentSize 64M) and B (12411, 3M). +# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\Attachments-Test.ps1 +param([string]$Build = (Join-Path $PSScriptRoot "..\Build")) +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_attachtest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Fails = 0 + +function New-KeyPair { + $L = & (Join-Path $Build "KeyGen.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +function Tool([string]$Name, [string[]]$A) { + $O = & (Join-Path $Build $Name) @A 2>&1 + @{ Code = $LASTEXITCODE; Out = ($O -join " | ") } +} +function Check([string]$What, [bool]$Ok, [string]$Detail) { + if (-not $Ok) { $script:Fails++ } + "{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail +} +function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { + Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out) +} +function Start-Srv($Name) { + $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Stop -ErrorAction SilentlyContinue + $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Stop = $Stop; Name = $Name } +} +function Stop-Srv($S) { + if ($S.P.HasExited) { return } + Set-Content $S.Stop "x" + if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force } +} +function Wait-Port($Port, $S) { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" } + if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } + Start-Sleep -Milliseconds 100 + } +} +function Query($Sql, $Ini) { + $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql + Tool "Query.exe" @("@$F", $Ini) +} +function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { + $D = (Get-Date).AddSeconds($Seconds) + do { + $R = Query $Sql $Ini + if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $D) + $R +} +function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") { + $F = Join-Path $Dir "push.txt" + [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) + $A = @() + if ($Topic) { $A += @("-t", $Topic) } + if ($Attach) { $A += @("-a", $Attach) } + Tool "PushMessage.exe" ($A + @("@$F", $Ini)) +} +# A file of Size random bytes. +function New-File($Name, [int]$Size, [int]$Seed) { + $P = Join-Path $Dir $Name + $B = New-Object byte[] $Size + (New-Object System.Random $Seed).NextBytes($B) + [IO.File]::WriteAllBytes($P, $B) + $P +} +function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } } +# Saves an attachment and compares it with the original. +function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) { + $Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin") + $R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) + $Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original)) + Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out) +} +# Retries GetAttachment until it works: replicated ones come after their message. +function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) { + $Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin") + $D = (Get-Date).AddSeconds($Seconds) + do { + $R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) + if ($R.Code -eq 0) { break } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $D) + Check $What (($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))) ("[{0}] {1}" -f $R.Code, $R.Out) +} + +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair + +Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($A.Priv) +Topic = logs +Node = serverA + +[BakaShrot.Topics] +logs = 1 +short = 2 +photos = 3 + +[BakaShrot.Nodes] +serverA = 10 +serverB = 11 +kitchen = 2 +garage = 3 + +[BakaShrot.Retention] +short = 4s + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12410 +ReplicatingTopics = logs;short;photos +DatabasePath = $(Join-Path $Dir "a.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +RetentionInterval = 1 +MaxAttachmentSize = 64M + +[BakaShrot.Peer.b] +Host = 127.0.0.1 +Port = 12411 +Topic = logs +Node = serverB +PublicKey = $($B.Pub) + +[BakaShrot.Client.b] +PublicKeys = $($B.Pub) +Identities = logs:serverB + +[BakaShrot.Client.kitchen] +PublicKeys = $($K.Pub) +Identities = logs:kitchen +PushTopics = logs;short +ReadTopics = * +AllowQuery = 1 +"@ + +Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($B.Priv) +Topic = logs +Node = serverB + +[BakaShrot.Topics] +logs = 300 +short = 301 +photos = 302 + +[BakaShrot.Nodes] +serverA = 1 +serverB = 2 +kitchen = 30 +garage = 31 + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12411 +ReplicatingTopics = logs;short;photos +DatabasePath = $(Join-Path $Dir "b.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +RetentionInterval = 1 +MaxAttachmentSize = 3M + +[BakaShrot.Peer.a] +Host = 127.0.0.1 +Port = 12410 +Topic = logs +Node = serverA +PublicKey = $($A.Pub) + +[BakaShrot.Client.a] +PublicKeys = $($A.Pub) +Identities = logs:serverA + +[BakaShrot.Client.garage] +PublicKeys = $($K.Pub) +Identities = photos:garage +PushTopics = photos +ReadTopics = * +AllowQuery = 1 +"@ + +$ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub } +function Client-Ini($Name, $Topic, $Node, $Port) { + $P = Join-Path $Dir "$Name.ini" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = $Topic`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + $P +} +$OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410 +$OnB = Client-Ini "garage-b" "photos" "garage" 12411 + +$Small = New-File "small.bin" (100 * 1024) 1 +$Mid = New-File "mid.bin" (5 * 1024 * 1024 + 123) 2 +$Exact = New-File "exact.bin" (2 * 1024 * 1024) 3 +$Tiny = New-File "tiny.bin" 1 4 + +foreach ($Port in 12410, 12411) { if (Test-Port $Port) { throw "Port $Port is already in use" } } +$SA = Start-Srv "a"; $SB = Start-Srv "b" +try { + Wait-Port 12410 $SA; Wait-Port 12411 $SB + Start-Sleep -Seconds 1 + + "--- Pushed with their message, read back" + Expect "push #1 with 100 KB" (Push '{"n":1}' $OnA "" $Small) "message #1, with an attachment of 102400 bytes" + $Started = Get-Date + Expect "push #2 with 5 MB + 123 bytes (6 parts)" (Push '{"n":2}' $OnA "" $Mid) "message #2, with an attachment of 5243003 bytes" + $UploadMs = ((Get-Date) - $Started).TotalMilliseconds + Expect "push #3 with exactly 2 MB (2 parts)" (Push '{"n":3}' $OnA "" $Exact) "message #3, with an attachment of 2097152 bytes" + Expect "push #4 with 1 byte" (Push '{"n":4}' $OnA "" $Tiny) "message #4" + Expect "push #5 without" (Push '{"n":5}' $OnA) "message #5$" + Expect-Same "#1 read back identical" "logs" "kitchen" 1 $Small $OnA + $Started = Get-Date + Expect-Same "#2 read back identical" "logs" "kitchen" 2 $Mid $OnA + $DownloadMs = ((Get-Date) - $Started).TotalMilliseconds + Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs) + Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA + Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA + Expect "#5 has none: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1 + Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked" + Expect "a message that doesn't exist: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1 + Expect "GetLatestMessage: #5, no attachment line" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$" + $R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA + Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out + Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]' + + "--- Replicated after their messages (B takes up to 3M)" + $R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'logs' AND node = 'kitchen'" $OnB '\[\["5"\]\]' + Check "B got the 5 messages" ($R.Out -match '\[\["5"\]\]') $R.Out + Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB + Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB + Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB + Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "GetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1 + $R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB + Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out + Expect "B: GetLatestMessage logs:kitchen, #5 has none" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}" + + "--- Pushed on B, too big there, then replicated to A" + Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1 + Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment" + Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA + Expect "A: the latest of photos:garage" (Tool "GetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}" + + "--- Deleted with their message (A: short = 4s)" + $Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out + Expect "push short #1 with 2 MB" (Push '{"s":1}' $OnA "short" $Exact) "message #1, with an attachment" + Expect "A has 2 more parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["13"\]\]' + $R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'short'" $OnA '\[\["0"\]\]' 15 + Check "the message is deleted past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out + $R = Wait-Query "SELECT COUNT(*) FROM blob_chunks" $OnA '\[\["11"\]\]' 10 + Check "and its 2 parts" ($R.Out -match '\[\["11"\]\]') "before $Before, now $($R.Out)" + Expect "and its attachments row" (Query "SELECT COUNT(*) FROM attachments WHERE topic_id = 2" $OnA) '\[\["0"\]\]' + Expect "and its blob" (Query "SELECT COUNT(*) FROM blobs WHERE state = 3" $OnA) '\[\["0"\]\]' + Wait-Same "B kept short#1 (no max age there)" "short" "kitchen" 1 $Exact $OnB +} +finally { + Stop-Srv $SA; Stop-Srv $SB +} + +"--- Logs" +$LogA = Get-Content (Join-Path $Dir "a.log") -Raw +$LogB = Get-Content (Join-Path $Dir "b.log") -Raw +Check "A sent B the attachments it takes" ($LogA -match "Sent the attachment of logs:kitchen#1 to 'b'" -and $LogA -match "Sent the attachment of logs:kitchen#3 to 'b'") "checked" +Check "A never sent #2 (not kept by B)" (-not ($LogA -match "Sent the attachment of logs:kitchen#2")) "checked" +Check "B sent A its photo" ($LogB -match "Sent the attachment of photos:garage#1 to 'a'") "checked" +Check "A logged deleting the parts" ($LogA -match "deleted 2 attachment parts") "checked" +$Other = ($LogA + "`n" + $LogB) -split "`r?`n" | Where-Object { $_ -match "Failed|invalid|unexpected|doesn't decrypt|SHA-256" -and $_ -notmatch "Refused a request" } +Check "no failure in A's or B's log" ($Other.Count -eq 0) ($Other -join " / ") + +"" +if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tools/GetAttachment/GetAttachment.pb b/Tools/GetAttachment/GetAttachment.pb new file mode 100644 index 0000000..7384e32 --- /dev/null +++ b/Tools/GetAttachment/GetAttachment.pb @@ -0,0 +1,68 @@ +; ============================================================================ +; BakaShrot GetAttachment +; +; Usage: GetAttachment [ClientIni] +; Topic, Node Whose message, each a name or an id. +; MessageId Which message. +; OutFile Where to save its attachment (replaced). +; ClientIni Identity and server to use, defaults to "client.ini". +; +; Saves the attachment of a message, read from the server a part at a time +; and checked with its SHA-256, and prints its size. The server refuses if +; the client's ReadTopics don't allow the topic, if the message has none, or +; if it isn't on that server yet (a replicated one comes after its message). +; A failed one leaves no file. See Design/Attachments.md. +; Compile as a console program, exits with 0 on success, 1 on failure. +; ============================================================================ + +EnableExplicit + +XIncludeFile "../Common/ToolClient.pbi" +XIncludeFile "../../Commons/Networking/Names.pbi" + + +Define Topic.s, Node.s, MessageText.s, OutFile.s, IniPath.s, MessageId.q, Size.q, StartTime.i + +OpenConsole() + +If CountProgramParameters() < 4 + PrintN("Usage: GetAttachment [ClientIni]") + PrintN(" Topic and Node are names or ids.") + End 1 +EndIf + +Topic = ProgramParameter(0) +Node = ProgramParameter(1) +If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) + PrintN("Invalid topic or node, expected names or ids 0-65535") + End 1 +EndIf +MessageText = ProgramParameter(2) +MessageId = Val(MessageText) +If MessageId < 1 Or Str(MessageId) <> MessageText + PrintN("Invalid message id '" + MessageText + "'") + End 1 +EndIf +OutFile = ProgramParameter(3) + +IniPath = "client.ini" +If CountProgramParameters() > 4 + IniPath = ProgramParameter(4) +EndIf + +If Not ToolClient_Connect(IniPath) + End 1 +EndIf + +StartTime = ElapsedMilliseconds() +Size = BakaShrot_SaveAttachment(Topic, Node, MessageId, OutFile) +If Size < 0 + ToolClient_PrintFailure() + ToolClient_Close() + End 1 +EndIf + +PrintN("Saved " + Str(Size) + " bytes to '" + OutFile + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms") + +ToolClient_Close() +End 0 diff --git a/Tools/GetLatestMessage/GetLatestMessage.pb b/Tools/GetLatestMessage/GetLatestMessage.pb index acb964b..6beb573 100644 --- a/Tools/GetLatestMessage/GetLatestMessage.pb +++ b/Tools/GetLatestMessage/GetLatestMessage.pb @@ -6,7 +6,8 @@ ; ClientIni Identity and server to use, defaults to "client.ini". ; ; Prints the latest message stored for that topic/node, and when it was -; pushed (UTC), then its data. The server refuses +; pushed (UTC), its attachment if it has one (GetAttachment saves it), then +; its data. The server refuses ; if the client's ReadTopics don't allow the topic, if either is unknown, or ; if there's no message. ; Compile as a console program, exits with 0 on success, 1 on failure. @@ -57,6 +58,13 @@ EndIf PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) + " (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + "), pushed " + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt())) +If BakaShrot_GetMessageAttachmentSize() > 0 + If BakaShrot_IsMessageAttachmentReady() + PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes") + Else + PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes, not on this server yet") + EndIf +EndIf PrintN(BakaShrot_GetMessageDataString()) ToolClient_Close() diff --git a/Tools/PushMessage/PushMessage.pb b/Tools/PushMessage/PushMessage.pb index 2b8136f..c1a7706 100644 --- a/Tools/PushMessage/PushMessage.pb +++ b/Tools/PushMessage/PushMessage.pb @@ -1,10 +1,13 @@ ; ============================================================================ ; BakaShrot PushMessage ; -; Usage: PushMessage [-t ] [ClientIni] +; Usage: PushMessage [-t ] [-a ] [ClientIni] ; -t Topic The topic to push to, a name or an id. Defaults to the ; client's own topic (its TopicId). The client's PushTopics on ; the server must allow it. +; -a File Attaches File to the message (any size up to the server's +; MaxAttachmentSize): uploaded first, the message is only +; stored once all of it is. See Design/Attachments.md. ; Json The message to push, or @ followed by a file holding it. ; Usually JSON, but anything goes: the server flags it in is_json. ; PureBasic's ProgramParameter() drops double quotes and @@ -23,7 +26,7 @@ XIncludeFile "../Common/ToolClient.pbi" XIncludeFile "../../Commons/Networking/Names.pbi" -Define JsonData.s, IniPath.s, Topic.s, FileText.String, MessageId.q, i.i, Argument.s +Define JsonData.s, IniPath.s, Topic.s, AttachPath.s, FileText.String, MessageId.q, i.i, Argument.s Define NewList Arguments.s() OpenConsole() @@ -37,6 +40,13 @@ For i = 0 To CountProgramParameters() - 1 PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") End 1 EndIf + ElseIf (Argument = "-a" Or Argument = "--attach") And i < CountProgramParameters() - 1 + i + 1 + AttachPath = ProgramParameter(i) + If FileSize(AttachPath) < 1 + PrintN("Can't attach '" + AttachPath + "': no such file, or empty") + End 1 + EndIf Else AddElement(Arguments()) Arguments() = Argument @@ -44,7 +54,7 @@ For i = 0 To CountProgramParameters() - 1 Next If ListSize(Arguments()) < 1 - PrintN("Usage: PushMessage [-t ] [ClientIni]") + PrintN("Usage: PushMessage [-t ] [-a ] [ClientIni]") PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.") End 1 EndIf @@ -67,14 +77,22 @@ If Not ToolClient_Connect(IniPath) End 1 EndIf -MessageId = BakaShrot_PushMessageTo(Topic, JsonData) +If AttachPath <> "" + MessageId = BakaShrot_PushMessageWithFile(Topic, JsonData, AttachPath) +Else + MessageId = BakaShrot_PushMessageTo(Topic, JsonData) +EndIf If MessageId < 1 ToolClient_PrintFailure() ToolClient_Close() End 1 EndIf -PrintN("Pushed as message #" + Str(MessageId)) +If AttachPath <> "" + PrintN("Pushed as message #" + Str(MessageId) + ", with an attachment of " + Str(FileSize(AttachPath)) + " bytes") +Else + PrintN("Pushed as message #" + Str(MessageId)) +EndIf ToolClient_Close() End 0 From 488ffe4bc8a0dbe37524fa888678a251a4e9fd4b Mon Sep 17 00:00:00 2001 From: Herwin Bozet Date: Mon, 9 Nov 2026 23:57:55 +0100 Subject: [PATCH 3/5] 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, 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 Claude-Session: https://claude.ai/code/session_01RwFeVQrLqMQPw9AZnsHqQH --- .gitignore | 5 + Build.ps1 | 69 ++- CLAUDE.md | 22 +- Client/BakaShrot_Client.pbi | 286 +++++---- Client/BakaShrot_Client_Prototypes.pbi | 28 +- Client/BakaShrot_ErrorCodes.pbi | 128 ++++ Commons/Networking/Connections.pbi | 8 +- Commons/Networking/Outbound.pbi | 36 +- Commons/Networking/Packets.pbi | 7 +- Commons/Networking/Packets/HelloPacket.pbi | 19 +- .../Packets/RequestRefusedPacket.pbi | 25 +- Design/Cryptography.md | 15 +- Design/Packets.md | 48 +- Design/Release.md | 29 +- Design/ReplicationIssues.md | 16 +- Design/StorageConcurrency.md | 63 +- Design/Suggestions.md | 8 +- Examples/README.md | 12 + Examples/SingleServer/README.md | 136 +++++ Examples/SingleServer/Run-Client.ps1 | 101 ++++ Examples/SingleServer/Start-Server.ps1 | 67 +++ Examples/SingleServer/client.ini | 26 + Examples/SingleServer/messages/hello.json | 1 + Examples/SingleServer/messages/query.sql | 1 + Examples/SingleServer/messages/reading.json | 1 + Examples/SingleServer/messages/report.json | 1 + Examples/SingleServer/messages/report.txt | 5 + Examples/SingleServer/server.ini | 67 +++ Interactors/Python/bakashrot.py | 168 ++++-- Interactors/Python/check_bakashrot.py | 47 +- Interactors/Python/example.py | 4 +- Notes.md | 361 +++++++++-- Release.ps1 | 100 ++-- Server/Config/Config.pbi | 558 ++++++++++++------ Server/Config/schema.ini | 95 ++- Server/Networking/Networking.pbi | 165 +++--- Server/Networking/Peers.pbi | 3 +- Server/Root.pbi | 26 +- Server/Storage/Names.pbi | 49 +- Server/Storage/Storage.pbi | 58 +- Server/Storage/db_schema_v8.dbml | 148 +++++ Tests/AttachmentEdgeClient.pb | 1 - Tests/AttachmentEdges-Test.ps1 | 29 +- Tests/Attachments-Test.ps1 | 44 +- Tests/Bench/Bench-Replication.ps1 | 36 +- Tests/Bench/BenchClient.pb | 3 +- Tests/BigMessages-Test.ps1 | 50 +- Tests/GetMessages-Test.ps1 | 59 +- Tests/HandshakeTest.pb | 2 - Tests/Names-Test.ps1 | 309 ++++++++-- Tests/Python-Test.ps1 | 15 +- Tests/Restart-Test.ps1 | 278 +++++++++ Tests/Retention-Test.ps1 | 44 +- Tests/restart_pusher.py | 35 ++ Tests/wire_check.py | 13 +- .../BakaShrotGenerateKeyPairs.pb} | 11 +- .../BakaShrotGetAttachment.pb} | 18 +- .../BakaShrotGetLatestMessage.pb} | 20 +- .../BakaShrotGetMessages.pb} | 31 +- .../BakaShrotList.pb} | 10 +- Tools/BakaShrotList/BakaShrotList.pb.cfg | 6 + .../BakaShrotPushMessage.pb} | 20 +- .../BakaShrotQuery.pb} | 16 +- .../BakaShrotResolveIds.pb} | 18 +- .../BakaShrotResolveIds.pb.cfg | 5 + Tools/Common/ToolClient.pbi | 51 +- Tools/Common/ToolConsole.pbi | 56 ++ 67 files changed, 3163 insertions(+), 1029 deletions(-) create mode 100644 Client/BakaShrot_ErrorCodes.pbi create mode 100644 Examples/README.md create mode 100644 Examples/SingleServer/README.md create mode 100644 Examples/SingleServer/Run-Client.ps1 create mode 100644 Examples/SingleServer/Start-Server.ps1 create mode 100644 Examples/SingleServer/client.ini create mode 100644 Examples/SingleServer/messages/hello.json create mode 100644 Examples/SingleServer/messages/query.sql create mode 100644 Examples/SingleServer/messages/reading.json create mode 100644 Examples/SingleServer/messages/report.json create mode 100644 Examples/SingleServer/messages/report.txt create mode 100644 Examples/SingleServer/server.ini create mode 100644 Server/Storage/db_schema_v8.dbml create mode 100644 Tests/Restart-Test.ps1 create mode 100644 Tests/restart_pusher.py rename Tools/{KeyGen/KeyGen.pb => BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb} (90%) rename Tools/{GetAttachment/GetAttachment.pb => BakaShrotGetAttachment/BakaShrotGetAttachment.pb} (86%) rename Tools/{GetLatestMessage/GetLatestMessage.pb => BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb} (84%) rename Tools/{GetMessages/GetMessages.pb => BakaShrotGetMessages/BakaShrotGetMessages.pb} (89%) rename Tools/{ListNames/ListNames.pb => BakaShrotList/BakaShrotList.pb} (94%) create mode 100644 Tools/BakaShrotList/BakaShrotList.pb.cfg rename Tools/{PushMessage/PushMessage.pb => BakaShrotPushMessage/BakaShrotPushMessage.pb} (89%) rename Tools/{Query/Query.pb => BakaShrotQuery/BakaShrotQuery.pb} (86%) rename Tools/{Resolve/Resolve.pb => BakaShrotResolveIds/BakaShrotResolveIds.pb} (84%) create mode 100644 Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg create mode 100644 Tools/Common/ToolConsole.pbi diff --git a/.gitignore b/.gitignore index a311434..4b71ce2 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,8 @@ Release/ # Python __pycache__/ + +# The examples run their server in their own folder: its database, and +# what their client scripts write +Examples/**/*.sqlite* +Examples/**/out/ diff --git a/Build.ps1 b/Build.ps1 index a9f73fb..557b9fc 100644 --- a/Build.ps1 +++ b/Build.ps1 @@ -4,9 +4,10 @@ # 0. Extracts libsodium's dynamic build from Libs/libsodium-*-msvc.zip, and # sqlite3.dll from the latest Libs/sqlite-dll-win-*.zip, if not done yet. # Delete Libs/libsodium/x64 or Libs/sqlite/x64 to extract them again. -# 1. Compiles KeyGen, the server, the client DLL, its example app and the -# tools (PushMessage, GetLatestMessage, GetMessages, Query, Resolve, -# ListNames) into ./Build, next to copies of +# 1. Compiles BakaShrotGenerateKeyPairs, the server, the client DLL, its +# example app and the tools (BakaShrotPushMessage, +# BakaShrotGetLatestMessage, BakaShrotGetMessages, BakaShrotGetAttachment, +# BakaShrotQuery, BakaShrotResolveIds, BakaShrotList) into ./Build, next to copies of # libsodium.dll and sqlite3.dll # 2. Generates a keypair for two servers and one for a client # 3. Writes the servers' configs and the client's keys. Topics and nodes @@ -21,11 +22,11 @@ # run raw queries # client2.ini logs:local2 through server2, same client key, may not query # Both servers replicate logs and sensors to each other, e.g.: -# .\PushMessage.exe -t sensors @msg.json client.ini -# .\GetLatestMessage.exe sensors local client2.ini -# .\GetMessages.exe logs local --follow client2.ini -# .\Resolve.exe topic sensors client2.ini (201 there, 2 on server) -# .\Query.exe "SELECT topic, node, message_id FROM messages" client.ini +# .\BakaShrotPushMessage.exe -t sensors @msg.json client.ini +# .\BakaShrotGetLatestMessage.exe sensors local client2.ini +# .\BakaShrotGetMessages.exe logs local --follow client2.ini +# .\BakaShrotResolveIds.exe topic sensors client2.ini (201 there, 2 on server) +# .\BakaShrotQuery.exe "SELECT topic, node, message_id FROM messages" client.ini # 4. Runs the first server, type "quit" or an empty line to stop it, or # "restart" / "vacuum" / "help". Run the second one in # another terminal to see them link: .\BakaShrot_Server.exe server2.ini @@ -137,10 +138,10 @@ function Invoke-Compiler($Source, $Executable, $Flags) { } function New-KeyPair { - # KeyGen prints "PrivateKey = ..." then "PublicKey = ...". - $Lines = & (Join-Path $Output "KeyGen.exe") + # BakaShrotGenerateKeyPairs prints "PrivateKey = ..." then "PublicKey = ...". + $Lines = & (Join-Path $Output "BakaShrotGenerateKeyPairs.exe") if ($LASTEXITCODE -ne 0) { - throw "KeyGen failed: $Lines" + throw "BakaShrotGenerateKeyPairs failed: $Lines" } return @{ PrivateKey = $Lines[0] -replace "^PrivateKey = ", "" @@ -166,26 +167,26 @@ try { Copy-Item (Join-Path $SqliteDir "sqlite3.dll") $Output -Force # 1. Compile - Invoke-Compiler "Tools\KeyGen\KeyGen.pb" "KeyGen.exe" @("/CONSOLE") + Invoke-Compiler "Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb" "BakaShrotGenerateKeyPairs.exe" @("/CONSOLE") Invoke-Compiler "Server\BakaShrot_Server.pb" "BakaShrot_Server.exe" @("/CONSOLE", "/THREAD") Invoke-Compiler "Client\BakaShrot_Client.pbi" "BakaShrot_Client.dll" @("/DLL", "/THREAD") # Example app using the DLL, run it from ./Build while the server runs. Invoke-Compiler "Client\BakaShrot_Client_Prototypes.pbi" "ClientExample.exe" @("/CONSOLE") # Tools using the DLL, same as the example: - # PushMessage [-t ] [-a ] [ClientIni] - # GetLatestMessage [ClientIni] - Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE") - Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE") - # GetMessages [--after ] [--limit ] [--follow] [ClientIni] - Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE") - # GetAttachment [ClientIni] - Invoke-Compiler "Tools\GetAttachment\GetAttachment.pb" "GetAttachment.exe" @("/CONSOLE") - # Query [ClientIni] - Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE") - # Resolve [ClientIni] - Invoke-Compiler "Tools\Resolve\Resolve.pb" "Resolve.exe" @("/CONSOLE") - # ListNames [topics|nodes|all] [ClientIni] [--json] - Invoke-Compiler "Tools\ListNames\ListNames.pb" "ListNames.exe" @("/CONSOLE") + # BakaShrotPushMessage [-t ] [-a ] [ClientIni] + Invoke-Compiler "Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb" "BakaShrotPushMessage.exe" @("/CONSOLE") + # BakaShrotGetLatestMessage [ClientIni] + Invoke-Compiler "Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb" "BakaShrotGetLatestMessage.exe" @("/CONSOLE") + # BakaShrotGetMessages [--after ] [--limit ] [--follow] [ClientIni] + Invoke-Compiler "Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb" "BakaShrotGetMessages.exe" @("/CONSOLE") + # BakaShrotGetAttachment [ClientIni] + Invoke-Compiler "Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb" "BakaShrotGetAttachment.exe" @("/CONSOLE") + # BakaShrotQuery [ClientIni] + Invoke-Compiler "Tools\BakaShrotQuery\BakaShrotQuery.pb" "BakaShrotQuery.exe" @("/CONSOLE") + # BakaShrotResolveIds [ClientIni] + Invoke-Compiler "Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb" "BakaShrotResolveIds.exe" @("/CONSOLE") + # BakaShrotList [topics|nodes|all] [ClientIni] [--json] + Invoke-Compiler "Tools\BakaShrotList\BakaShrotList.pb" "BakaShrotList.exe" @("/CONSOLE") # 2. Keys Write-Host "Generating keys" @@ -199,7 +200,6 @@ try { $ServerConfig = @" [BakaShrot] PrivateKey = $($ServerKeys.PrivateKey) -Topic = logs Node = server1 ; This server's ids for the names every server shares. @@ -221,13 +221,13 @@ PeerBatchSize = $PeerBatchSize [BakaShrot.Peer.server2] Host = $ServerHost Port = $Server2Port -Topic = logs Node = server2 PublicKey = $($Server2Keys.PublicKey) [BakaShrot.Client.local] PublicKeys = $($ClientKeys.PublicKey) -Identities = logs:local +Node = local +DefaultTopic = logs PushTopics = logs;sensors ReadTopics = * AllowRead = 1 @@ -237,7 +237,7 @@ AllowQuery = 1 ; The peer only replicates, it has no business reading or writing as a client. [BakaShrot.Client.server2] PublicKeys = $($Server2Keys.PublicKey) -Identities = logs:server2 +Node = server2 AllowRead = 0 AllowWrite = 0 AllowQuery = 0 @@ -247,7 +247,6 @@ AllowQuery = 0 $Server2Config = @" [BakaShrot] PrivateKey = $($Server2Keys.PrivateKey) -Topic = logs Node = server2 ; Other ids than server's, same names: replication goes by name. @@ -269,14 +268,13 @@ PeerBatchSize = $PeerBatchSize [BakaShrot.Peer.server] Host = $ServerHost Port = $ServerPort -Topic = logs Node = server1 PublicKey = $($ServerKeys.PublicKey) ; The peer only replicates, it has no business reading or writing as a client. [BakaShrot.Client.server] PublicKeys = $($ServerKeys.PublicKey) -Identities = logs:server1 +Node = server1 AllowRead = 0 AllowWrite = 0 AllowQuery = 0 @@ -284,7 +282,8 @@ AllowQuery = 0 ; No raw queries through this server. [BakaShrot.Client.local] PublicKeys = $($ClientKeys.PublicKey) -Identities = logs:local2 +Node = local2 +DefaultTopic = logs PushTopics = logs;sensors ReadTopics = * AllowRead = 1 @@ -297,7 +296,6 @@ AllowQuery = 0 [BakaShrot] PrivateKey = $($ClientKeys.PrivateKey) PublicKey = $($ClientKeys.PublicKey) -Topic = logs Node = local2 ServerHost = $ServerHost ServerPort = $Server2Port @@ -310,7 +308,6 @@ ServerPublicKey = $($Server2Keys.PublicKey) [BakaShrot] PrivateKey = $($ClientKeys.PrivateKey) PublicKey = $($ClientKeys.PublicKey) -Topic = logs Node = local ServerHost = $ServerHost ServerPort = $ServerPort diff --git a/CLAUDE.md b/CLAUDE.md index dfe9b84..db95797 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,8 +8,8 @@ operations come before security hardening (`Notes.md`, "Threat model"). ## Read first -1. `Notes.md`: where things stand, "Open items, by importance" (the to-do - list, item 3 is the next known bug), "Testing tips". +1. `Notes.md`: "Right now" (what's committed, what's next), where things + stand, "Open items, by importance" (the to-do list), "Testing tips". 2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives, code conventions), `Attachments.md`, `Cryptography.md`, `StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`, @@ -30,7 +30,7 @@ operations come before security hardening (`Notes.md`, "Threat model"). |---|---|---| | `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` | | `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` | -| `Tools\\.pb` (PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, Resolve, ListNames, KeyGen) | `Build\.exe` | `/CONSOLE` | +| `Tools\\.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\.exe` | `/CONSOLE` | | `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` | | `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` | | `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` | @@ -55,21 +55,29 @@ all passed. `powershell -ExecutionPolicy Bypass -File Tests\.ps1`: | `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) | | `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits | | `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) | +| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) | Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp` -(push ceiling, ~40,800 msg/s for 4 servers). After a change, run every +(push ceiling for 4 servers: ~17,000 msg/s with the default `Synchronous = +FULL`, ~34,000-40,000 with `-Synchronous NORMAL`). After a change, run every suite: they take a few minutes in all. ## Traps - **Run exes from `Build\`**: the antivirus blocks them in temp folders. -- **`Build\` holds private keys**: git-ignored, never publish it. +- **`Build\` holds private keys**: git-ignored, never publish it. The one + exception: `Examples/*/` commit their configs, keys included, on purpose + (public, example-only, marked so); don't copy those keys anywhere else. - **PureBasic is single pass**: constants, structures and procedures must be declared before use, so include order matters (e.g. `Config.pbi` includes `Packets.pbi` for its constants). - **`SetDatabase*()` binds the next statement run on that connection**, not a specific one: set them right before their `DatabaseUpdate/Query`. +- **Never `Goto` out of a `Select`**: 5.73's ASM backend keeps the value on + the stack, the jump corrupts it (a config error crashed the server with + 0xC0000005). Set the error, leave the `Select`, then jump. Out of + `For`/`ForEach`/`While` loops is fine (checked on both compilers). - **PureBasic lists aren't safe to walk from several threads** (`ForEach` moves the shared current element): give each thread its own copy. - **Files mix CRLF and LF**: edits must keep each file's line endings. @@ -84,9 +92,9 @@ suite: they take a few minutes in all. ## Working rules - **Commit only when the owner asks**, on a branch, not `master`. -- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 4 at +- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 6 at this writing); any difference refuses the connection. -- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v7 at this +- **Schema changes** add a `Server/Storage/db_schema_vN.dbml` (v8 at this writing) and a migration in `SetupStorageDatabase()` (`Storage.pbi`), existing databases must keep working. - **Packets** follow `Design/Packets.md` "Code conventions": one file per diff --git a/Client/BakaShrot_Client.pbi b/Client/BakaShrot_Client.pbi index 0fd680e..d423564 100644 --- a/Client/BakaShrot_Client.pbi +++ b/Client/BakaShrot_Client.pbi @@ -4,14 +4,16 @@ ; Lets an app connect to a BakaShrot server, one step at a time: ; 1. BakaShrot_SetPrivateKey(), BakaShrot_SetPublicKey(), ; BakaShrot_SetServerPublicKey() (the server's, from its log or its -; KeyGen output), BakaShrot_SetTopic() and BakaShrot_SetNode() (names -; or ids), or BakaShrot_SetTopicId() and BakaShrot_SetNodeId() +; BakaShrotGenerateKeyPairs output), and BakaShrot_SetNode() (a name +; or an id) or BakaShrot_SetNodeId(): the node it writes as, which the +; server must allow for its key. Its default topic is the server's to +; say (DefaultTopic in its client section). ; 2. BakaShrot_Connect(Host, Port), connects and authenticates, see the ; handshake in Commons/Networking/Connections.pbi: only to the server ; holding the private key of BakaShrot_SetServerPublicKey()'s, and ; everything is encrypted ; 3. Requests, once connected: -; BakaShrot_PushMessage(JsonData), into the client's own topic, or +; BakaShrot_PushMessage(JsonData), into the client's default topic, or ; BakaShrot_PushMessageTo(Topic, JsonData), returns the new ; message's id ; BakaShrot_GetLatestMessageOf(Topic, Node), or @@ -45,6 +47,15 @@ ; BakaShrot_GetRefusalReason() tells why. ; 4. BakaShrot_IsConnected(), BakaShrot_Disconnect() ; +; After a failed call, BakaShrot_GetLastError() tells what failed: a +; refusal's code (1-99, the connection still open), or the client's own +; (100+: not connected, the connection lost, a bad argument...), see +; BakaShrot_ErrorCodes.pbi for each and what to do about it. 0 after a call +; that succeeded. Nothing reconnects by itself: on NotConnected, +; ConnectionLost or ProtocolError, call BakaShrot_Connect() again. +; A push whose answer was lost (ConnectionLost) may have been stored all +; the same: pushed again, it's stored twice. Delivery is at least once. +; ; Topics and nodes are "refs": a name, or an id in digits, see ; Commons/Networking/Names.pbi. Ids are the server's own, each server can ; have different ones for the same names. @@ -88,7 +99,6 @@ Global BakaShrot_HasPrivateKey.i = #False Global BakaShrot_PublicKey.s = "" Global BakaShrot_ServerPublicKey.BakaShrot_ClientServerKey Global BakaShrot_HasServerPublicKey.i = #False -Global BakaShrot_Topic.s = "" Global BakaShrot_Node.s = "" ; The connection, see Commons/Networking/Outbound.pbi. @@ -115,16 +125,42 @@ Global BakaShrot_NamesList.s = "" Global NewList BakaShrot_Messages.BakaShrot_MessagesEntry() Global BakaShrot_MessagesMore.i = #False +; Why the last call failed, a code of BakaShrot_ErrorCodes.pbi, 0 if it +; succeeded. See BakaShrot_GetLastError(). +Global BakaShrot_LastError.l = #BakaShrot_Error_None + + +; Sets BakaShrot_LastError to Code and returns Value, for the failures: +; ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False). +Procedure.q BakaShrot_Fail(Code.l, Value.q) + BakaShrot_LastError = Code + ProcedureReturn Value +EndProcedure + +; At the start of every call that can fail: no error, no refusal yet. +Procedure BakaShrot_ResetError() + BakaShrot_LastError = #BakaShrot_Error_None + BakaShrot_RefusalReason = "" +EndProcedure + +; The code of what made the last call fail, 0 if it succeeded, see +; BakaShrot_ErrorCodes.pbi. Only the calls that can fail set it (not the +; getters of a message). +ProcedureCDLL.l BakaShrot_GetLastError() + ProcedureReturn BakaShrot_LastError +EndProcedure + ; Sets the Ed25519 private key (Base64) used to answer the server's challenge. ; Must be done before connecting. Procedure.i BakaShrot_SetPrivateKeyString(PrivateKey.s) + BakaShrot_ResetError() If BakaShrot_Outbound\ConnectionId - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) EndIf If Not DecodeKeyFromString(PrivateKey, @BakaShrot_PrivateKey\Bytes[0], #BakaShrot_Ed25519_PrivateKeySize) - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf BakaShrot_HasPrivateKey = #True @@ -133,14 +169,14 @@ EndProcedure ProcedureCDLL.i BakaShrot_SetPrivateKeyA(*PrivateKey) If Not *PrivateKey - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.i BakaShrot_SetPrivateKeyW(*PrivateKey) If Not *PrivateKey - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_Unicode)) EndProcedure @@ -149,12 +185,13 @@ EndProcedure ; Sets the Ed25519 public key (Base64) sent to the server in the Hello. ; Must be done before connecting. Procedure.i BakaShrot_SetPublicKeyString(PublicKey.s) + BakaShrot_ResetError() If BakaShrot_Outbound\ConnectionId - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) EndIf If PublicKey = "" - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf BakaShrot_PublicKey = PublicKey @@ -163,14 +200,14 @@ EndProcedure ProcedureCDLL.i BakaShrot_SetPublicKeyA(*PublicKey) If Not *PublicKey - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.i BakaShrot_SetPublicKeyW(*PublicKey) If Not *PublicKey - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode)) EndProcedure @@ -180,12 +217,13 @@ EndProcedure ; and the server must prove it holds the matching private key. ; Must be done before connecting. Procedure.i BakaShrot_SetServerPublicKeyString(PublicKey.s) + BakaShrot_ResetError() If BakaShrot_Outbound\ConnectionId - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) EndIf If Not DecodeKeyFromString(PublicKey, @BakaShrot_ServerPublicKey\Bytes[0], #BakaShrot_Ed25519_PublicKeySize) - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf BakaShrot_HasServerPublicKey = #True @@ -194,57 +232,28 @@ EndProcedure ProcedureCDLL.i BakaShrot_SetServerPublicKeyA(*PublicKey) If Not *PublicKey - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.i BakaShrot_SetServerPublicKeyW(*PublicKey) If Not *PublicKey - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode)) EndProcedure -; Sets the topic the client identifies as, a name or an id in digits. -; Must be done before connecting. -Procedure.i BakaShrot_SetTopicString(Topic.s) - If BakaShrot_Outbound\ConnectionId Or Not BakaShrot_IsValidRef(Topic) - ProcedureReturn #False - EndIf - BakaShrot_Topic = Topic - ProcedureReturn #True -EndProcedure - -ProcedureCDLL.i BakaShrot_SetTopicA(*Topic) - If Not *Topic - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_SetTopicString(PeekS(*Topic, -1, #PB_UTF8)) -EndProcedure - -ProcedureCDLL.i BakaShrot_SetTopicW(*Topic) - If Not *Topic - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_SetTopicString(PeekS(*Topic, -1, #PB_Unicode)) -EndProcedure - -; Same, by id, 0-65535. -ProcedureCDLL.i BakaShrot_SetTopicId(TopicId.l) - If TopicId < 0 Or TopicId > 65535 - ProcedureReturn #False - EndIf - ProcedureReturn BakaShrot_SetTopicString(Str(TopicId)) -EndProcedure - - ; Sets the node the client identifies as, a name or an id in digits. ; Must be done before connecting. Procedure.i BakaShrot_SetNodeString(Node.s) - If BakaShrot_Outbound\ConnectionId Or Not BakaShrot_IsValidRef(Node) - ProcedureReturn #False + BakaShrot_ResetError() + If BakaShrot_Outbound\ConnectionId + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) + EndIf + If Not BakaShrot_IsValidRef(Node) + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf BakaShrot_Node = Node ProcedureReturn #True @@ -252,14 +261,14 @@ EndProcedure ProcedureCDLL.i BakaShrot_SetNodeA(*Node) If Not *Node - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.i BakaShrot_SetNodeW(*Node) If Not *Node - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_Unicode)) EndProcedure @@ -267,7 +276,7 @@ EndProcedure ; Same, by id, 0-65535. ProcedureCDLL.i BakaShrot_SetNodeId(NodeId.l) If NodeId < 0 Or NodeId > 65535 - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_SetNodeString(Str(NodeId)) EndProcedure @@ -279,34 +288,36 @@ EndProcedure ; handshake is out of order or unexpected, in which case the connection is ; closed. Procedure.i BakaShrot_ConnectString(Host.s, Port.l) - Protected Identity.BakaShrot_OutboundIdentity + Protected Identity.BakaShrot_OutboundIdentity, Connected.i + BakaShrot_ResetError() If BakaShrot_Outbound\ConnectionId - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False) EndIf - If Not BakaShrot_HasPrivateKey Or BakaShrot_PublicKey = "" Or Not BakaShrot_HasServerPublicKey Or BakaShrot_Topic = "" Or BakaShrot_Node = "" - ProcedureReturn #False + If Not BakaShrot_HasPrivateKey Or BakaShrot_PublicKey = "" Or Not BakaShrot_HasServerPublicKey Or BakaShrot_Node = "" + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf - Identity\Topic = BakaShrot_Topic Identity\Node = BakaShrot_Node Identity\PublicKey = BakaShrot_PublicKey Identity\PrivateKey = @BakaShrot_PrivateKey\Bytes[0] - ProcedureReturn BakaShrot_Outbound_Connect(@BakaShrot_Outbound, Host, Port, @Identity, @BakaShrot_ServerPublicKey\Bytes[0]) + Connected = BakaShrot_Outbound_Connect(@BakaShrot_Outbound, Host, Port, @Identity, @BakaShrot_ServerPublicKey\Bytes[0]) + BakaShrot_LastError = BakaShrot_Outbound\LastError + ProcedureReturn Connected EndProcedure ProcedureCDLL.i BakaShrot_ConnectA(*Host, Port.l) If Not *Host - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_UTF8), Port) EndProcedure ProcedureCDLL.i BakaShrot_ConnectW(*Host, Port.l) If Not *Host - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_Unicode), Port) EndProcedure @@ -332,8 +343,12 @@ EndProcedure ; --- Requests ---------------------------------------------------------------- -; Closes the connection after something went wrong in a request. +; Closes the connection after something went wrong in a request: an +; unexpected or malformed answer, unless the caller said otherwise first. Procedure BakaShrot_AbortConnection() + If BakaShrot_LastError = #BakaShrot_Error_None + BakaShrot_LastError = #BakaShrot_Error_ProtocolError + EndIf BakaShrot_Outbound_Close(@BakaShrot_Outbound, #BakaShrot_ConnectionStatus_Aborted) EndProcedure @@ -346,12 +361,14 @@ Procedure.i BakaShrot_SendRequest(*Request, RequestSize.i, *OutSize.Integer) Protected *Answer If Not BakaShrot_Outbound_Send(@BakaShrot_Outbound, *Request, RequestSize) + BakaShrot_LastError = #BakaShrot_Error_ConnectionLost BakaShrot_AbortConnection() ProcedureReturn 0 EndIf *Answer = BakaShrot_Outbound_WaitPacket(@BakaShrot_Outbound, *OutSize, #BakaShrot_Outbound_Timeout) If Not *Answer + BakaShrot_LastError = #BakaShrot_Error_ConnectionLost BakaShrot_AbortConnection() ProcedureReturn 0 EndIf @@ -376,6 +393,7 @@ Procedure.i BakaShrot_ReadRefusal(*Answer, AnswerSize.i) EndIf BakaShrot_RefusalReason = *Refused\Reason + BakaShrot_LastError = *Refused\Code FreeStructure(*Refused) ProcedureReturn #True EndProcedure @@ -402,8 +420,8 @@ EndProcedure ; Pushes a message (JSON or anything else, the server flags which in its -; is_json column) into Topic (a name or an id, "" for the client's own -; topic), the server stores it under that topic and this client's node, with +; is_json column) into Topic (a name or an id, "" for the client's default +; topic, its server config's DefaultTopic), the server stores it under that topic and this client's node, with ; the next message id. The client's PushTopics on the server must allow it. ; UploadId: its attachment, uploaded with BakaShrot_Upload(), 0 for none. ; Returns the new message's id (1 or more), or -1 on failure. @@ -415,20 +433,20 @@ Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0) Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer Protected *View.MsgPackData, IsRefusal.i, MessageId.q - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) EndIf If Topic <> "" And Not BakaShrot_IsValidRef(Topic) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ; Refused here rather than sent for nothing, same reason as the server's. If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf Push\Topic = Topic @@ -436,7 +454,7 @@ Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0) Push\UploadId = UploadId *Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize) If Not *Request - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) EndIf *Answer = BakaShrot_SendRequest(*Request, RequestSize\i, @AnswerSize) FreeMemory(*Request) @@ -486,7 +504,7 @@ ProcedureCDLL.q BakaShrot_PushMessageW(*JsonData) ProcedureReturn BakaShrot_PushMessageToString("", PeekS(*JsonData, -1, #PB_Unicode)) EndProcedure -; A null *Topic is the client's own topic, like "", and a null *JsonData an +; A null *Topic is the client's default topic, like "", and a null *JsonData an ; empty message: PureBasic passes empty strings to a DLL as null pointers. ProcedureCDLL.q BakaShrot_PushMessageToA(*Topic, *JsonData) Protected Topic.s, JsonData.s @@ -524,7 +542,7 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer Protected *View.MsgPackData, IsRefusal.i, IsExpected.i - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() BakaShrot_MessageId = 0 BakaShrot_MessagePushedAt = 0 BakaShrot_MessageAttachmentSize = 0 @@ -538,18 +556,18 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s) BakaShrot_MessagesMore = #False If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, #False) EndIf If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf Request\Topic = Topic Request\Node = Node *Packet = BakaShrot_GetLatestMessagePacket_Encode(@Request, @PacketSize) If Not *Packet - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, #False) EndIf *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) FreeMemory(*Packet) @@ -609,14 +627,14 @@ EndProcedure ProcedureCDLL.i BakaShrot_GetLatestMessageOfA(*Topic, *Node) If Not *Topic Or Not *Node - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.i BakaShrot_GetLatestMessageOfW(*Topic, *Node) If Not *Topic Or Not *Node - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode)) EndProcedure @@ -624,7 +642,7 @@ EndProcedure ; Same, by ids, 0-65535. ProcedureCDLL.i BakaShrot_GetLatestMessage(TopicId.l, NodeId.l) If TopicId < 0 Or TopicId > 65535 Or NodeId < 0 Or NodeId > 65535 - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_GetLatestMessageOfString(Str(TopicId), Str(NodeId)) EndProcedure @@ -649,7 +667,7 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit Protected *Packet, PacketSize.Integer, *AnswerPacket, AnswerSize.Integer Protected *View.MsgPackData, IsRefusal.i, IsExpected.i, Count.l - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() BakaShrot_MessageId = 0 BakaShrot_MessagePushedAt = 0 BakaShrot_MessageAttachmentSize = 0 @@ -663,14 +681,14 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit BakaShrot_MessagesMore = #False If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) EndIf If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf If AfterMessageId < 0 Or Limit < 1 Or Limit > #BakaShrot_MaxGetMessages - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf Request\Topic = Topic @@ -679,7 +697,7 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit Request\Limit = Limit *Packet = BakaShrot_GetMessagesPacket_Encode(@Request, @PacketSize) If Not *Packet - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) EndIf *AnswerPacket = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) FreeMemory(*Packet) @@ -746,14 +764,14 @@ EndProcedure ProcedureCDLL.l BakaShrot_GetMessagesA(*Topic, *Node, AfterMessageId.q, Limit.l) If Not *Topic Or Not *Node - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), AfterMessageId, Limit) EndProcedure ProcedureCDLL.l BakaShrot_GetMessagesW(*Topic, *Node, AfterMessageId.q, Limit.l) If Not *Topic Or Not *Node - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), AfterMessageId, Limit) EndProcedure @@ -768,8 +786,9 @@ EndProcedure ; last answer, for BakaShrot_GetMessageId() and BakaShrot_GetMessageData(). ; Returns #False if there's none at Index, the selection doesn't change then. ProcedureCDLL.i BakaShrot_SelectMessage(Index.l) + BakaShrot_LastError = #BakaShrot_Error_None If Index < 0 Or Index >= ListSize(BakaShrot_Messages()) - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf SelectElement(BakaShrot_Messages(), Index) BakaShrot_MessageId = BakaShrot_Messages()\MessageId @@ -837,22 +856,22 @@ Procedure.l BakaShrot_ResolveString(Kind.i, Ref.s) Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer Protected *View.MsgPackData, IsRefusal.i, Id.l - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() BakaShrot_ResolvedName = "" If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) EndIf If Not BakaShrot_IsValidRef(Ref) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf Request\Kind = Kind Request\Ref = Ref *Packet = BakaShrot_ResolveNamePacket_Encode(@Request, @PacketSize) If Not *Packet - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) EndIf *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) FreeMemory(*Packet) @@ -896,28 +915,28 @@ EndProcedure ProcedureCDLL.l BakaShrot_ResolveTopicA(*Ref) If Not *Ref - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Topic, PeekS(*Ref, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.l BakaShrot_ResolveTopicW(*Ref) If Not *Ref - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Topic, PeekS(*Ref, -1, #PB_Unicode)) EndProcedure ProcedureCDLL.l BakaShrot_ResolveNodeA(*Ref) If Not *Ref - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.l BakaShrot_ResolveNodeW(*Ref) If Not *Ref - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_Unicode)) EndProcedure @@ -937,17 +956,17 @@ Procedure.l BakaShrot_ListNamesOf(Kind.i) Protected *View.MsgPackData, IsRefusal.i, Count.l Protected Json.i, Root.i, Items.i, Item.i - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() BakaShrot_NamesList = "" If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) EndIf Request\Kind = Kind *Packet = BakaShrot_ListNamesPacket_Encode(@Request, @PacketSize) If Not *Packet - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) EndIf *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) FreeMemory(*Packet) @@ -982,7 +1001,7 @@ Procedure.l BakaShrot_ListNamesOf(Kind.i) Json = CreateJSON(#PB_Any) If Not Json FreeStructure(*List) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1) EndIf Root = SetJSONObject(JSONValue(Json)) If Kind = #BakaShrot_NameKind_Topic @@ -1068,17 +1087,17 @@ Procedure.i BakaShrot_QueryString(Sql.s) Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer Protected *View.MsgPackData, IsRefusal.i - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() BakaShrot_QueryResult = "" If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, #False) EndIf Request\Sql = Sql *Packet = BakaShrot_QueryRequestPacket_Encode(@Request, @PacketSize) If Not *Packet - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, #False) EndIf *Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize) FreeMemory(*Packet) @@ -1114,14 +1133,14 @@ EndProcedure ProcedureCDLL.i BakaShrot_QueryA(*Sql) If Not *Sql - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.i BakaShrot_QueryW(*Sql) If Not *Sql - ProcedureReturn #False + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False) EndIf ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_Unicode)) EndProcedure @@ -1180,7 +1199,7 @@ EndProcedure ; Uploads Size bytes, read from FileId (from its start) or else from *Memory, ; as the attachment of a message about to be pushed to Topic ("" for the -; client's own). Its SHA-256 is computed first, so the file is read twice. +; client's default one). Its SHA-256 is computed first, so the file is read twice. ; Returns the upload id for BakaShrot_PushMessageToString(), 0 on failure. Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted @@ -1188,26 +1207,26 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) Protected Hash.BakaShrot_Sha256, *Buffer, Index.q, Count.q, Bytes.i, UploadId.q, Received.q, Complete.i Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, 0) EndIf If Topic <> "" And Not BakaShrot_IsValidRef(Topic) - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0) EndIf If Size < 1 BakaShrot_RefusalReason = "The attachment is empty" - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0) EndIf If Size > #BakaShrot_MaxAttachmentSize BakaShrot_RefusalReason = "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(#BakaShrot_MaxAttachmentSize) - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0) EndIf *Buffer = AllocateMemory(#BakaShrot_AttachmentChunkSize, #PB_Memory_NoClear) If Not *Buffer Or Not BakaShrot_Sha256_Start(@Hash) If *Buffer : FreeMemory(*Buffer) : EndIf - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0) EndIf Count = BakaShrot_AttachmentChunkCount(Size) @@ -1219,7 +1238,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) If ReadData(FileId, *Buffer, Bytes) <> Bytes BakaShrot_RefusalReason = "The file couldn't be read" FreeMemory(*Buffer) - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, 0) EndIf BakaShrot_Sha256_Add(@Hash, *Buffer, Bytes) Next @@ -1235,7 +1254,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) *Request = BakaShrot_UploadStartPacket_Encode(@Start, @RequestSize) If Not *Request FreeMemory(*Buffer) - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0) EndIf *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_UploadStarted, @AnswerSize) FreeMemory(*Request) @@ -1267,7 +1286,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) If ReadData(FileId, *Buffer, Bytes) <> Bytes BakaShrot_RefusalReason = "The file couldn't be read" FreeMemory(*Buffer) - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, 0) EndIf Chunk\Data = *Buffer Else @@ -1278,7 +1297,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q) *Request = BakaShrot_UploadChunkPacket_Encode(@Chunk, @RequestSize) If Not *Request FreeMemory(*Buffer) - ProcedureReturn 0 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0) EndIf *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_ChunkStored, @AnswerSize) FreeMemory(*Request) @@ -1322,15 +1341,15 @@ EndProcedure Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s) Protected FileId.i, UploadId.q - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf FileId = ReadFile(#PB_Any, FilePath, #PB_File_SharedRead) If Not FileId BakaShrot_RefusalReason = "Can't open '" + FilePath + "'" - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, -1) EndIf UploadId = BakaShrot_Upload(Topic, FileId, 0, Lof(FileId)) CloseFile(FileId) @@ -1340,11 +1359,11 @@ Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s) ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId) EndProcedure -; A null *Topic is the client's own topic, a null *JsonData an empty message. +; A null *Topic is the client's default topic, a null *JsonData an empty message. ProcedureCDLL.q BakaShrot_PushMessageWithFileA(*Topic, *JsonData, *FilePath) Protected Topic.s, JsonData.s If Not *FilePath - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf If *Topic : Topic = PeekS(*Topic, -1, #PB_UTF8) : EndIf If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_UTF8) : EndIf @@ -1354,7 +1373,7 @@ EndProcedure ProcedureCDLL.q BakaShrot_PushMessageWithFileW(*Topic, *JsonData, *FilePath) Protected Topic.s, JsonData.s If Not *FilePath - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf If *Topic : Topic = PeekS(*Topic, -1, #PB_Unicode) : EndIf If *JsonData : JsonData = PeekS(*JsonData, -1, #PB_Unicode) : EndIf @@ -1366,14 +1385,14 @@ EndProcedure Procedure.q BakaShrot_PushMessageWithDataString(Topic.s, JsonData.s, *Data, Size.q) Protected UploadId.q - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() If StringByteLength(JsonData, #PB_UTF8) > #BakaShrot_MaxMessageSize BakaShrot_RefusalReason = "The message is too big: " + Str(StringByteLength(JsonData, #PB_UTF8)) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf If Not *Data BakaShrot_RefusalReason = "The attachment is empty" - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf UploadId = BakaShrot_Upload(Topic, 0, *Data, Size) If Not UploadId @@ -1408,12 +1427,12 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) Protected Dim Expected.a(#BakaShrot_Sha256Size - 1), Dim Result.a(#BakaShrot_Sha256Size - 1) Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData - BakaShrot_RefusalReason = "" + BakaShrot_ResetError() If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1) EndIf If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) Or MessageId < 1 Or Not BakaShrot_Sha256_Start(@Hash) - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf Request\Topic = Topic @@ -1425,6 +1444,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) Request\ChunkIndex = Index *Request = BakaShrot_GetAttachmentPacket_Encode(@Request, @RequestSize) If Not *Request + BakaShrot_LastError = #BakaShrot_Error_Internal Goto DownloadFailed EndIf *Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_AttachmentChunk, @AnswerSize) @@ -1454,6 +1474,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) If Not *Memory BakaShrot_AttachmentChunkPacket_Free(*Chunk) BakaShrot_RefusalReason = "Out of memory for " + Str(Size) + " bytes" + BakaShrot_LastError = #BakaShrot_Error_Internal Goto DownloadFailed EndIf EndIf @@ -1469,6 +1490,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) If WriteData(FileId, *Chunk\Data, *Chunk\DataSize) <> *Chunk\DataSize BakaShrot_AttachmentChunkPacket_Free(*Chunk) BakaShrot_RefusalReason = "The file couldn't be written" + BakaShrot_LastError = #BakaShrot_Error_FileError Goto DownloadFailed EndIf Else @@ -1481,6 +1503,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i) BakaShrot_Sha256_Finish(@Hash, @Result(0)) If Not CompareMemory(@Result(0), @Expected(0), #BakaShrot_Sha256Size) BakaShrot_RefusalReason = "The attachment doesn't match its SHA-256" + BakaShrot_LastError = #BakaShrot_Error_AttachmentMismatch Goto DownloadFailed EndIf @@ -1507,10 +1530,11 @@ EndProcedure Procedure.q BakaShrot_SaveAttachmentString(Topic.s, Node.s, MessageId.q, FilePath.s) Protected FileId.i, Size.q + BakaShrot_ResetError() FileId = CreateFile(#PB_Any, FilePath) If Not FileId BakaShrot_RefusalReason = "Can't create '" + FilePath + "'" - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, -1) EndIf Size = BakaShrot_Download(Topic, Node, MessageId, FileId) CloseFile(FileId) @@ -1522,14 +1546,14 @@ EndProcedure ProcedureCDLL.q BakaShrot_SaveAttachmentA(*Topic, *Node, MessageId.q, *FilePath) If Not *Topic Or Not *Node Or Not *FilePath - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, PeekS(*FilePath, -1, #PB_UTF8)) EndProcedure ProcedureCDLL.q BakaShrot_SaveAttachmentW(*Topic, *Node, MessageId.q, *FilePath) If Not *Topic Or Not *Node Or Not *FilePath - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_SaveAttachmentString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, PeekS(*FilePath, -1, #PB_Unicode)) EndProcedure @@ -1541,14 +1565,14 @@ EndProcedure ; Returns its size, -1 on failure, see BakaShrot_Download(). ProcedureCDLL.q BakaShrot_LoadAttachmentA(*Topic, *Node, MessageId.q) If Not *Topic Or Not *Node - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_UTF8), PeekS(*Node, -1, #PB_UTF8), MessageId, 0) EndProcedure ProcedureCDLL.q BakaShrot_LoadAttachmentW(*Topic, *Node, MessageId.q) If Not *Topic Or Not *Node - ProcedureReturn -1 + ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1) EndIf ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, 0) EndProcedure diff --git a/Client/BakaShrot_Client_Prototypes.pbi b/Client/BakaShrot_Client_Prototypes.pbi index de23765..91655f2 100644 --- a/Client/BakaShrot_Client_Prototypes.pbi +++ b/Client/BakaShrot_Client_Prototypes.pbi @@ -13,15 +13,18 @@ ; ; See BakaShrot_Client.pbi for what each function does. ; The string functions are mapped to the DLL's W (UTF-16) variants. +; After a failed call, BakaShrot_GetLastError() tells why: the codes and +; what to do about each are in BakaShrot_ErrorCodes.pbi, next to this file +; (included below), BakaShrot_ErrorName() names them. ; ============================================================================ +XIncludeFile "BakaShrot_ErrorCodes.pbi" + PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) PrototypeC.i BakaShrot_SetPublicKey_Prototype(PublicKey.p-unicode) PrototypeC.i BakaShrot_SetServerPublicKey_Prototype(PublicKey.p-unicode) -PrototypeC.i BakaShrot_SetTopicId_Prototype(TopicId.l) PrototypeC.i BakaShrot_SetNodeId_Prototype(NodeId.l) -PrototypeC.i BakaShrot_SetTopic_Prototype(Topic.p-unicode) PrototypeC.i BakaShrot_SetNode_Prototype(Node.p-unicode) PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) PrototypeC.i BakaShrot_IsConnected_Prototype() @@ -44,6 +47,7 @@ PrototypeC.l BakaShrot_ListTopics_Prototype() PrototypeC.l BakaShrot_ListNodes_Prototype() PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i) PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) +PrototypeC.l BakaShrot_GetLastError_Prototype() PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode) PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) @@ -63,9 +67,7 @@ PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() Global BakaShrot_SetPrivateKey.BakaShrot_SetPrivateKey_Prototype Global BakaShrot_SetPublicKey.BakaShrot_SetPublicKey_Prototype Global BakaShrot_SetServerPublicKey.BakaShrot_SetServerPublicKey_Prototype -Global BakaShrot_SetTopicId.BakaShrot_SetTopicId_Prototype Global BakaShrot_SetNodeId.BakaShrot_SetNodeId_Prototype -Global BakaShrot_SetTopic.BakaShrot_SetTopic_Prototype Global BakaShrot_SetNode.BakaShrot_SetNode_Prototype Global BakaShrot_Connect.BakaShrot_Connect_Prototype Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype @@ -88,6 +90,7 @@ Global BakaShrot_ListTopics.BakaShrot_ListTopics_Prototype Global BakaShrot_ListNodes.BakaShrot_ListNodes_Prototype Global BakaShrot_GetNamesList.BakaShrot_GetNamesList_Prototype Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype +Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype Global BakaShrot_Query.BakaShrot_Query_Prototype Global BakaShrot_GetQueryResult.BakaShrot_GetQueryResult_Prototype Global BakaShrot_GetMessages.BakaShrot_GetMessages_Prototype @@ -131,9 +134,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_SetPrivateKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPrivateKeyW") BakaShrot_SetPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPublicKeyW") BakaShrot_SetServerPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetServerPublicKeyW") - BakaShrot_SetTopicId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetTopicId") BakaShrot_SetNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeId") - BakaShrot_SetTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetTopicW") BakaShrot_SetNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeW") BakaShrot_Connect = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ConnectW") BakaShrot_IsConnected = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsConnected") @@ -144,6 +145,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_GetMessagePushedAt = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessagePushedAt") BakaShrot_GetMessageData = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageDataW") BakaShrot_GetRefusalReason = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetRefusalReasonW") + BakaShrot_GetLastError = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetLastError") BakaShrot_Query = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_QueryW") BakaShrot_GetQueryResult = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetQueryResultW") BakaShrot_PushMessageTo = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_PushMessageToW") @@ -171,12 +173,12 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_GetMessageAttachmentSize = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_GetMessageAttachmentSize") BakaShrot_IsMessageAttachmentReady = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsMessageAttachmentReady") - If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetTopicId Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect + If Not BakaShrot_SetPrivateKey Or Not BakaShrot_SetPublicKey Or Not BakaShrot_SetServerPublicKey Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect BakaShrot_UnloadClient() ProcedureReturn #False EndIf - If Not BakaShrot_PushMessage Or Not BakaShrot_GetLatestMessage Or Not BakaShrot_GetMessageId Or Not BakaShrot_GetMessagePushedAt Or Not BakaShrot_GetMessageData Or Not BakaShrot_GetRefusalReason + If Not BakaShrot_PushMessage Or Not BakaShrot_GetLatestMessage Or Not BakaShrot_GetMessageId Or Not BakaShrot_GetMessagePushedAt Or Not BakaShrot_GetMessageData Or Not BakaShrot_GetRefusalReason Or Not BakaShrot_GetLastError BakaShrot_UnloadClient() ProcedureReturn #False EndIf @@ -186,7 +188,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) ProcedureReturn #False EndIf - If Not BakaShrot_SetTopic Or Not BakaShrot_SetNode Or Not BakaShrot_PushMessageTo Or Not BakaShrot_GetLatestMessageOf Or + If Not BakaShrot_SetNode Or Not BakaShrot_PushMessageTo Or Not BakaShrot_GetLatestMessageOf Or Not BakaShrot_GetMessageTopicId Or Not BakaShrot_GetMessageNodeId Or Not BakaShrot_GetMessageTopic Or Not BakaShrot_GetMessageNode Or Not BakaShrot_ResolveTopic Or Not BakaShrot_ResolveNode Or Not BakaShrot_GetResolvedName Or Not BakaShrot_ListTopics Or Not BakaShrot_ListNodes Or Not BakaShrot_GetNamesList @@ -301,7 +303,7 @@ EndProcedure ; run it from the Build folder while BakaShrot_Server.exe is running. CompilerIf #PB_Compiler_IsMainFile - Define PrivateKey.s, PublicKey.s, ServerPublicKey.s, Topic.s, Node.s, ServerHost.s, ServerPort.l + Define PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l OpenConsole() @@ -313,7 +315,6 @@ CompilerIf #PB_Compiler_IsMainFile PrivateKey = ReadPreferenceString("PrivateKey", "") PublicKey = ReadPreferenceString("PublicKey", "") ServerPublicKey = ReadPreferenceString("ServerPublicKey", "") - Topic = ReadPreferenceString("Topic", ReadPreferenceString("TopicId", "")) Node = ReadPreferenceString("Node", ReadPreferenceString("NodeId", "")) ServerHost = ReadPreferenceString("ServerHost", "") ServerPort = ReadPreferenceLong("ServerPort", 0) @@ -339,11 +340,6 @@ CompilerIf #PB_Compiler_IsMainFile End 1 EndIf - If Not BakaShrot_SetTopic(Topic) - PrintN("Failed to set the topic") - End 1 - EndIf - If Not BakaShrot_SetNode(Node) PrintN("Failed to set the node") End 1 diff --git a/Client/BakaShrot_ErrorCodes.pbi b/Client/BakaShrot_ErrorCodes.pbi new file mode 100644 index 0000000..0554404 --- /dev/null +++ b/Client/BakaShrot_ErrorCodes.pbi @@ -0,0 +1,128 @@ +; ============================================================================ +; BakaShrot error codes +; +; What BakaShrot_GetLastError() returns after a failed call of the client DLL +; (BakaShrot_Client.pbi), and the code a server sends with each refusal +; (RequestRefused, protocol 6). The Python client has the same numbers in +; bakashrot.ErrorCode. Shipped next to BakaShrot_Client_Prototypes.pbi, +; which includes it. +; +; 0 no error (the last call succeeded) +; 1-99 refused by the server: the connection is still open, see +; BakaShrot_GetRefusalReason() for the details +; 100+ the client's own: the connection, the arguments, the files +; +; What to do about each: +; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost, +; ProtocolError (the connection is closed) +; retry later: NotReady (an attachment still on its way), +; ServerError (the server's storage failed) +; fix the config: AuthRejected, ServerNotVerified, NotAllowed, +; UnknownName, NoDefaultTopic +; fix the call: InvalidArgument, InvalidRequest, TooBig, +; QueryFailed, FileError +; gone, or not yet there: NotFound +; sent again by itself: DataMismatch (an upload that doesn't match its +; SHA-256: upload it again), AttachmentMismatch (a +; downloaded one that doesn't: read it again) +; +; A push whose answer was lost (ConnectionLost) may still have been stored: +; pushing it again can store it twice, under the next id. Delivery is at +; least once; check the latest message first if a duplicate matters. +; ============================================================================ + +; --- Refused by the server (RequestRefused's Code) ---------------------------- + +; Not allowed to this client: AllowRead / AllowWrite / AllowQuery, its +; PushTopics / ReadTopics, or a request only peers may make. +#BakaShrot_Refused_NotAllowed = 1 +; A topic or node name (or id) this server doesn't know. +#BakaShrot_Refused_UnknownName = 2 +; No such message, attachment or upload. +#BakaShrot_Refused_NotFound = 3 +; The attachment isn't on this server yet (still being replicated). +#BakaShrot_Refused_NotReady = 4 +; A message, attachment or query result over a limit, or an attachment +; bigger than this server keeps. +#BakaShrot_Refused_TooBig = 5 +; A push without a topic, and no DefaultTopic for this client. +#BakaShrot_Refused_NoDefaultTopic = 6 +; A request that doesn't fit: parts out of order, an upload for another +; topic or already attached, a part that doesn't exist... +#BakaShrot_Refused_InvalidRequest = 7 +; An uploaded attachment that doesn't match its SHA-256: dropped. +#BakaShrot_Refused_DataMismatch = 8 +; The SQL of a query failed (its error in the reason). +#BakaShrot_Refused_QueryFailed = 9 +; The server couldn't store or read something: its database failed. +#BakaShrot_Refused_ServerError = 10 + +; The highest a refusal can have, anything above is the client's own. +#BakaShrot_Refused_Max = 99 + +; --- The client's own (BakaShrot_GetLastError()) -------------------------------- + +#BakaShrot_Error_None = 0 +; Not connected: never, or the connection was closed or lost before. +#BakaShrot_Error_NotConnected = 100 +; The server couldn't be reached at that host and port. +#BakaShrot_Error_ConnectFailed = 101 +; The server closed the connection during the handshake: wrong +; ServerPublicKey, a key or node it doesn't allow, or another protocol +; version (its log says which). +#BakaShrot_Error_AuthRejected = 102 +; The server couldn't prove it holds ServerPublicKey's private key. +#BakaShrot_Error_ServerNotVerified = 103 +; The connection broke during a request (it's closed now). A push may +; still have been stored. +#BakaShrot_Error_ConnectionLost = 104 +; The server answered something unexpected or malformed: the connection is +; closed. +#BakaShrot_Error_ProtocolError = 105 +; A bad argument: a ref that's neither a name nor an id, a null pointer, a +; message or attachment over the limits, a setting missing before connecting. +#BakaShrot_Error_InvalidArgument = 106 +; A file couldn't be opened, read or written. +#BakaShrot_Error_FileError = 107 +; A downloaded attachment doesn't match its SHA-256. +#BakaShrot_Error_AttachmentMismatch = 108 +; Already connected: disconnect first. +#BakaShrot_Error_AlreadyConnected = 109 +; Out of memory, or another failure inside the client. +#BakaShrot_Error_Internal = 110 + + +; The name of an error code, as the constants have it ("NotFound"), or +; "Error " for an unknown one. +Procedure.s BakaShrot_ErrorName(Code.l) + Select Code + Case #BakaShrot_Error_None : ProcedureReturn "None" + Case #BakaShrot_Refused_NotAllowed : ProcedureReturn "NotAllowed" + Case #BakaShrot_Refused_UnknownName : ProcedureReturn "UnknownName" + Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound" + Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady" + Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig" + Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic" + Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest" + Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch" + Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed" + Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError" + Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected" + Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed" + Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected" + Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "ServerNotVerified" + Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "ConnectionLost" + Case #BakaShrot_Error_ProtocolError : ProcedureReturn "ProtocolError" + Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "InvalidArgument" + Case #BakaShrot_Error_FileError : ProcedureReturn "FileError" + Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch" + Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected" + Case #BakaShrot_Error_Internal : ProcedureReturn "Internal" + EndSelect + ProcedureReturn "Error " + Str(Code) +EndProcedure + +; #True for a code a server sends with a refusal (1-99). +Procedure.i BakaShrot_IsRefusalCode(Code.l) + ProcedureReturn Bool(Code >= 1 And Code <= #BakaShrot_Refused_Max) +EndProcedure diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi index be4945a..d501c6f 100644 --- a/Commons/Networking/Connections.pbi +++ b/Commons/Networking/Connections.pbi @@ -129,9 +129,11 @@ CompilerEndIf Structure BakaShrot_ConnectionMetadata Status.i - ; Identity from the Hello, as the server's own ids (unused on the client - ; side), only trusted once Status is Authenticated. - TopicId.u + ; Server side only, trusted once Status is Authenticated: the node from + ; the Hello, and the default topic of its pushes from its client + ; section's DefaultTopic (-1 without one: pushes must name their topic), + ; both as the server's own ids. + DefaultTopicId.l NodeId.u ; The client's Ed25519 public key, on both sides. PublicKey.a[#BakaShrot_Ed25519_PublicKeySize] diff --git a/Commons/Networking/Outbound.pbi b/Commons/Networking/Outbound.pbi index 60498ac..1352e79 100644 --- a/Commons/Networking/Outbound.pbi +++ b/Commons/Networking/Outbound.pbi @@ -22,8 +22,8 @@ XIncludeFile "SocketWait.pbi" ; Who to authenticate as. Structure BakaShrot_OutboundIdentity - ; Each a name or an id in digits (Names.pbi), resolved by the server. - Topic.s + ; The node it writes as, a name or an id in digits (Names.pbi), resolved + ; by the server, which must allow it for this key. Node.s ; Ed25519 public key (Base64), sent in the Hello. @@ -45,6 +45,10 @@ Structure BakaShrot_Outbound ; for the server's packets give up right away, as if they timed out. ; Lets a server stop its peer links without waiting out their timeouts. *StopRequested.Integer + + ; Why BakaShrot_Outbound_Connect() failed, a #BakaShrot_Error_* of + ; Client/BakaShrot_ErrorCodes.pbi, 0 once it succeeded. + LastError.l EndStructure @@ -158,22 +162,27 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por Protected KeyPair.BakaShrot_SessionKeyPair Protected ChallengeDecoded.i, ServerProved.i - If *Outbound\ConnectionId Or Not *ServerPublicKey + *Outbound\LastError = #BakaShrot_Error_None + If *Outbound\ConnectionId + *Outbound\LastError = #BakaShrot_Error_AlreadyConnected ProcedureReturn #False EndIf - If Port < 1 Or Port > 65535 + If Not *ServerPublicKey Or Port < 1 Or Port > 65535 + *Outbound\LastError = #BakaShrot_Error_InvalidArgument ProcedureReturn #False EndIf ; Only needed before PureBasic 6.00. CompilerIf #PB_Compiler_Version < 600 If Not InitNetwork() + *Outbound\LastError = #BakaShrot_Error_Internal ProcedureReturn #False EndIf CompilerEndIf If Not InitCryptography() + *Outbound\LastError = #BakaShrot_Error_Internal ProcedureReturn #False EndIf @@ -181,6 +190,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por ClearStructure(@*Outbound\Metadata, BakaShrot_ConnectionMetadata) If Not DecodeKeyFromString(*Identity\PublicKey, @*Outbound\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted + *Outbound\LastError = #BakaShrot_Error_InvalidArgument ProcedureReturn #False EndIf CopyMemory(*ServerPublicKey, @*Outbound\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize) @@ -188,6 +198,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por *Outbound\ConnectionId = OpenNetworkConnection(Host, Port, #PB_Network_TCP | #PB_Network_IPv4) If Not *Outbound\ConnectionId *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted + *Outbound\LastError = #BakaShrot_Error_ConnectFailed ProcedureReturn #False EndIf *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_New @@ -198,11 +209,11 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por ; 1. Hello, sealed for the server - Hello\ClientTopic = *Identity\Topic Hello\ClientNode = *Identity\Node Hello\ClientPubKeyB64 = *Identity\PublicKey CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) + *Outbound\LastError = #BakaShrot_Error_Internal *Packet = BakaShrot_HelloPacket_Encode(@Hello, @PacketSize) If Not *Packet Goto ConnectFailed @@ -212,6 +223,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por If Not *Sealed Goto ConnectFailed EndIf + *Outbound\LastError = #BakaShrot_Error_ConnectFailed Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0) FreeMemory(*Sealed) If Not Sent @@ -219,12 +231,17 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por EndIf - ; 2. Challenge request, in plain text + ; 2. Challenge request, in plain text. No answer: the server closed the + ; connection, it couldn't open the Hello or doesn't allow this key and + ; node (or speaks another protocol version). + *Outbound\LastError = #BakaShrot_Error_AuthRejected *Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout) If Not *Packet Goto ConnectFailed EndIf + *Outbound\LastError = #BakaShrot_Error_ProtocolError + *Request = 0 *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) If *View @@ -250,10 +267,12 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptServerLabel, @Proof) ServerProved = BakaShrot_VerifyHandshake(@Proof, *ServerPublicKey) If Not ServerProved + *Outbound\LastError = #BakaShrot_Error_ServerNotVerified Goto ConnectFailed EndIf ; Every packet is encrypted from now on. + *Outbound\LastError = #BakaShrot_Error_Internal If Not BakaShrot_Session_StartClient(@*Outbound\Metadata\Cipher, @KeyPair, @*Outbound\Metadata\ServerSessionKey[0]) Goto ConnectFailed EndIf @@ -274,6 +293,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por If Not *Packet Goto ConnectFailed EndIf + *Outbound\LastError = #BakaShrot_Error_AuthRejected Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i) FreeMemory(*Packet) If Not Sent @@ -281,11 +301,12 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por EndIf - ; 4. Accepted + ; 4. Accepted. No answer: the server didn't accept this key's signature. *Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout) If Not *Packet Goto ConnectFailed EndIf + *Outbound\LastError = #BakaShrot_Error_ProtocolError *Accepted = 0 *View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i) @@ -302,6 +323,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por ; The server's answers may be big from now on. BakaShrot_Inbox_Lift(@*Outbound\Inbox) *Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated + *Outbound\LastError = #BakaShrot_Error_None ProcedureReturn #True diff --git a/Commons/Networking/Packets.pbi b/Commons/Networking/Packets.pbi index d9810ce..d8f9c8b 100644 --- a/Commons/Networking/Packets.pbi +++ b/Commons/Networking/Packets.pbi @@ -1,6 +1,8 @@ XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi" XIncludeFile "Names.pbi" +; The refusal codes (RequestRefused) and the client's error codes. +XIncludeFile "../../Client/BakaShrot_ErrorCodes.pbi" ; Represents the root of all BakaShrot packets. @@ -21,7 +23,10 @@ EndStructure ; the ChallengeRequest encrypted (Connections.pbi). Messages carry when ; they were pushed (PushedAt). ; 4: attachments (Design/Attachments.md). -#BakaShrot_ProtocolVersion = 4 +; 5: the Hello carries the client's node only: its default topic is the +; server's to say (DefaultTopic in its client section). +; 6: RequestRefused carries a Code (Client/BakaShrot_ErrorCodes.pbi). +#BakaShrot_ProtocolVersion = 6 ; Size in bytes of the nonce sent in a challenge request and echoed in its response. ; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the diff --git a/Commons/Networking/Packets/HelloPacket.pbi b/Commons/Networking/Packets/HelloPacket.pbi index e8ba060..4ed90c0 100644 --- a/Commons/Networking/Packets/HelloPacket.pbi +++ b/Commons/Networking/Packets/HelloPacket.pbi @@ -6,12 +6,12 @@ XIncludeFile "../Packets.pbi" ; C2S auth request, sent sealed for the server's public key (Connections.pbi). -; ClientTopic, ClientNode: who the client is, each a name or an id in digits -; (Commons/Networking/Names.pbi), resolved by the server in its own names. +; ClientNode: who the client is, the node it writes as, a name or an id in +; digits (Commons/Networking/Names.pbi), resolved by the server in its own +; names. Its default topic is the server's to say, not the client's. ; ClientSessionKey: the public half of the client's key pair for this ; connection (Commons/Cryptography/Session.pbi). Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase - ClientTopic.s ClientNode.s ClientPubKeyB64.s ClientSessionKey.a[#BakaShrot_SessionKeySize] @@ -37,10 +37,6 @@ Procedure.i BakaShrot_HelloPacket_Encode(*Hello.BakaShrot_AuthHello, *OutSize.In Goto EncodeFailed EndIf - If MsgPackWriteString(*MsgPackData, *Hello\ClientTopic) <> #MsgPack_Error_Success - Goto EncodeFailed - EndIf - If MsgPackWriteString(*MsgPackData, *Hello\ClientNode) <> #MsgPack_Error_Success Goto EncodeFailed EndIf @@ -84,15 +80,6 @@ Procedure.i BakaShrot_HelloPacket_Decode(*MsgPackData.MsgPackData) Goto DecodeFailed EndIf - ; ClientTopic - If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String - Goto DecodeFailed - EndIf - *Hello\ClientTopic = MsgPackReadString(*MsgPackData) - If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success - Goto DecodeFailed - EndIf - ; ClientNode If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String Goto DecodeFailed diff --git a/Commons/Networking/Packets/RequestRefusedPacket.pbi b/Commons/Networking/Packets/RequestRefusedPacket.pbi index 2fa4311..df5f08b 100644 --- a/Commons/Networking/Packets/RequestRefusedPacket.pbi +++ b/Commons/Networking/Packets/RequestRefusedPacket.pbi @@ -6,8 +6,11 @@ XIncludeFile "../Packets.pbi" ; S2C, answers a request the server won't fulfill, the connection stays open. -; Reason is only meant for logs and humans. +; Code: what kind of refusal, 1-#BakaShrot_Refused_Max, one of the +; #BakaShrot_Refused_* in Client/BakaShrot_ErrorCodes.pbi: what clients act +; on (protocol 6). Reason is only meant for logs and humans. Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase + Code.l Reason.s EndStructure @@ -22,6 +25,10 @@ Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefu *Refused\Version = #BakaShrot_ProtocolVersion *Refused\PacketType = #BakaShrot_PacketType_RequestRefused + If Not BakaShrot_IsRefusalCode(*Refused\Code) + ProcedureReturn 0 + EndIf + *MsgPackData = MsgPackCreate(64) If Not *MsgPackData ProcedureReturn 0 @@ -31,6 +38,10 @@ Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefu Goto EncodeFailed EndIf + If MsgPackWriteInteger(*MsgPackData, *Refused\Code) <> #MsgPack_Error_Success + Goto EncodeFailed + EndIf + If MsgPackWriteString(*MsgPackData, *Refused\Reason) <> #MsgPack_Error_Success Goto EncodeFailed EndIf @@ -53,7 +64,7 @@ EndProcedure ; *MsgPackData stays owned by the caller, and should be discarded on failure. ; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure. Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData) - Protected *Refused.BakaShrot_RequestRefused + Protected *Refused.BakaShrot_RequestRefused, Value.q *Refused = AllocateStructure(BakaShrot_RequestRefused) If Not *Refused @@ -65,6 +76,16 @@ Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData) Goto DecodeFailed EndIf + ; Code + If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer + Goto DecodeFailed + EndIf + Value = MsgPackReadInteger(*MsgPackData) + If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsRefusalCode(Value) + Goto DecodeFailed + EndIf + *Refused\Code = Value + ; Reason If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String Goto DecodeFailed diff --git a/Design/Cryptography.md b/Design/Cryptography.md index 0673bcb..2f216b9 100644 --- a/Design/Cryptography.md +++ b/Design/Cryptography.md @@ -33,7 +33,7 @@ keys sit in plain-text ini files (see the end). | libsodium | Wrapper | Notes | |---|---|---| | `sodium_init` | `InitCryptography()` | Called before any use; repeated calls are fine. | -| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/KeyGen`. | +| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/BakaShrotGenerateKeyPairs`. | | `crypto_sign_detached` | `EncodeData()`, `BakaShrot_SignHandshake()` | **Signs**, the name `EncodeData` is wrong. | | `crypto_sign_verify_detached` | `DecodeData()`, `BakaShrot_VerifyHandshake()` | **Verifies**, the name `DecodeData` is wrong. | | `crypto_sign_ed25519_sk_to_pk` | `GetPublicKeyFromPrivateKey()` | Lets a server only keep its private key in its config. | @@ -69,9 +69,10 @@ keys sit in plain-text ini files (see the end). - **Connection keys: X25519**, made for each connection by both ends, the secrets wiped once the cipher has its keys. So a recorded connection can't be decrypted later, even with both identity keys (forward secrecy). -- **Generated** by `Tools/KeyGen`, which `Build.ps1` runs on every build. +- **Generated** by `Tools/BakaShrotGenerateKeyPairs`, which `Build.ps1` runs + on every build. - **Wiping:** - - Wiped from memory after use: KeyGen; a server's key when it stops, and + - Wiped from memory after use: BakaShrotGenerateKeyPairs; a server's key when it stops, and its peer links'; every connection's keys when it ends. - Not wiped: the client DLL's global copy of its private key, and the config structures holding the Base64 text. @@ -91,11 +92,11 @@ See `Design/Packets.md` for the packets, `Connections.pbi` for the code. The client knows the server's public key beforehand. 1. **Hello, sealed** (`crypto_box_seal` for the server's key): the client's - identity (topic, node), its Base64 public key, and the public half of a - key pair it made for this connection. + node (the one it writes as), its Base64 public key, and the public half + of a key pair it made for this connection. 2. The server opens it (another server can't: abort), decodes the key and - checks that a `[BakaShrot.Client.]` lists both this key and this - identity. + checks that a `[BakaShrot.Client.]` has this `Node` and lists this + key. 3. **ChallengeRequest, in plain text:** a fresh random challenge and nonce, the public half of the server's own pair for this connection, and the server's signature of the transcript. diff --git a/Design/Packets.md b/Design/Packets.md index 9208a00..43c558f 100644 --- a/Design/Packets.md +++ b/Design/Packets.md @@ -26,6 +26,8 @@ Reference for working on BakaShrot's networking. Related docs: | Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` | | Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` | | Python client, over the DLL | `Interactors/Python/bakashrot.py` | +| Ready-to-run setups (configs, start scripts, a README each) | `Examples/`, listed in `Examples/README.md` | +| Tools: connecting through the DLL from an ini; ending (waits for Enter when started from Explorer) | `Tools/Common/ToolClient.pbi`, `Tools/Common/ToolConsole.pbi` | | Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` | | Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` | | What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` | @@ -74,8 +76,9 @@ Reference for working on BakaShrot's networking. Related docs: array, read in order with PB-MessagePack: 1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`, "BSHT"). - 2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (4: - attachments; 3: the Hello sealed, a key per connection, everything + 2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (6: + refusals carry a code; 5: the Hello carries the node only, the default + topic is the server's; 4: attachments; 3: the Hello sealed, a key per connection, everything after the ChallengeRequest encrypted, times; 2 had topics and nodes by name, in plain text; 1 had ids only). 3. `PacketType` (integer), one of the ids below. @@ -90,10 +93,13 @@ Reference for working on BakaShrot's networking. Related docs: ### Topics and nodes: names and ids -- **Each server has its own ids** (0-65535) for topics and nodes, and the - config can name them (`[BakaShrot.Topics]`, `[BakaShrot.Nodes]`). The - **name is what's shared**: "logs" can be 1 on one server and 200 on - another. +- **Each server has its own ids** (0-65535) for topics and nodes, and + gives them to the names: the config lists the topics + (`[BakaShrot.Topics]`), the nodes come from the sections that define + them (its own, its peers', its clients') and optionally + `[BakaShrot.Nodes]`; a name keeps the id the database has for it, a new + one gets the lowest free one (`Server/Storage/Names.pbi`). The **name is + what's shared**: "logs" can be 1 on one server and 200 on another. - **A ref** is how a packet gives a topic or node: a name (1-64 of `A-Z a-z 0-9 _ . -`, not only digits, any case), or an id in digits, which always means that id on the receiving server. An unnamed topic or @@ -105,7 +111,7 @@ Reference for working on BakaShrot's networking. Related docs: - **Only what's named on both servers replicates.** Unnamed topics and nodes, and names the other server doesn't have, are dropped, unless the receiver's `AcceptTopics` / `AcceptNodes` for that peer has a wildcard - (`*`, `sensors.*`) matching it: it's then added there with an id of its + (`*`, `sensors.*`; `AcceptNodes` is `*` by default) matching it: it's then added there with an id of its own. The sync state lists every name the receiver takes, and its wildcards, so the sender only sends those and nothing gets refused at every check-in. @@ -119,7 +125,7 @@ over its own link to another server. |---|---|---|---|---| | 0 | None | | Never valid. | | | 1-3 | | | Used by the removed `AuthenticationPacket.pbi`, don't reuse. | | -| 4 | ClientHello | C→S | `ClientTopic` str (ref), `ClientNode` str (ref), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest | +| 4 | ClientHello | C→S | `ClientNode` str (ref, the node it writes as), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest | | 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse | | 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted | | 7 | AuthAccepted | S→C | None. | | @@ -127,7 +133,7 @@ over its own link to another server. | 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | | | 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused | | 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | | -| 12 | RequestRefused | S→C | `Reason` str, for logs and humans | | +| 12 | RequestRefused | S→C | `Code` int 1-99 (what kind, `#BakaShrot_Refused_*` in `Client/BakaShrot_ErrorCodes.pbi`: what clients act on), `Reason` str, for logs and humans | | | 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused | | 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | | | 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused | @@ -165,7 +171,13 @@ the client's), and keeps that time on every server it's replicated to. - **Refuse or abort:** - **Refuse** (RequestRefused, the connection stays open) for things that are valid but not allowed: permissions, no message found, too big, - a failed query, a regular client sending replication packets. + a failed query, a regular client sending replication packets. Each with + a code (`Client/BakaShrot_ErrorCodes.pbi`): NotAllowed, UnknownName, + NotFound, NotReady, TooBig, NoDefaultTopic, InvalidRequest, + DataMismatch, QueryFailed, ServerError. Clients get them from + `BakaShrot_GetLastError()` (the DLL) or `error.code` (Python), with + their own codes (100+) for what never reached the server or broke the + connection. - **Abort** (the connection is closed) for anything malformed or out of order: an invalid frame or packet, a packet type that isn't expected at that point, an answer to a different request, a timeout during the @@ -187,12 +199,12 @@ the client's), and keeps that time on every server it's replicated to. ``` client: knows the server's Ed25519 public key (ServerPublicKey), makes a key pair for this connection -C -> S ClientHello identity (topic and node refs) + Base64 public key +C -> S ClientHello node (ref, the one it writes as) + Base64 public key + the public half of the client's pair, sealed for the server's public key - server: opens it (or aborts: not for this server), the refs must - resolve to its ids, the key must decode to 32 bytes, and one - [BakaShrot.Client.] must list both this key and this identity + server: opens it (or aborts: not for this server), the node must + resolve to its id, the key must decode to 32 bytes, and one + [BakaShrot.Client.] must have this Node and list this key S -> C ChallengeRequest fresh random challenge + nonce, the public half of the server's pair, and the server's signature of the transcript (in plain text) @@ -215,14 +227,16 @@ server's session halves, the challenge, the nonce. connection: - Its **permissions**, from the matching client section: `AllowRead`, `AllowWrite`, `AllowQuery`, and the `PushTopics` / `ReadTopics` filters - (default: the topics of its `Identities`). - - Whether it's a **peer**: its key and identity match a + (default: its `DefaultTopic`, nothing without one), and that + `DefaultTopic`: the topic of its pushes that don't name one. + - Whether it's a **peer**: its key and node match a `[BakaShrot.Peer.]`, and then its `AcceptTopics`. ### Client requests ``` -PushMessage(t, json) AllowWrite, t in PushTopics ("" = own topic), at most +PushMessage(t, json) AllowWrite, t in PushTopics ("" = its DefaultTopic, + refused without one), at most #BakaShrot_MaxMessageSize. JSON or not: stored as is, SQLite flags it in is_json -> stored under t and the authenticated node with the diff --git a/Design/Release.md b/Design/Release.md index ad5bbed..24afbc6 100644 --- a/Design/Release.md +++ b/Design/Release.md @@ -18,14 +18,14 @@ warning, not an error). Its smoke test, from the release folder, on one server with a throwaway database: -- generates keys with `KeyGen.exe`, writes a server and a client config; +- generates keys with `BakaShrotGenerateKeyPairs.exe`, writes a server and a client config; - pushes two messages, reads the latest back by name, reads both with - `GetMessages.exe`, resolves a name, queries them through the `messages` + `BakaShrotGetMessages.exe`, resolves a name, queries them through the `messages` view with `is_json = 1`; - if `python` is on the PATH, reads them and pushes one with `python\bakashrot.py`; -- pushes a 3 MB attachment with `PushMessage.exe -a` and reads it back - identical with `GetAttachment.exe`; +- pushes a 3 MB attachment with `BakaShrotPushMessage.exe -a` and reads it back + identical with `BakaShrotGetAttachment.exe`; - then force-kills the server and deletes everything. The end-to-end tests in `Tests/` cover much more (names, replication, big @@ -79,10 +79,12 @@ in `Tests/` already, to be pointed at the release instead. first time a pair is pushed to (`Writer.pbi`), `node_heads` is kept by a trigger in the same transaction as the messages, and every check-in with a peer starts from both sync states, read from the databases. A - killed process loses nothing committed, even with `synchronous = - NORMAL` (only a power loss or an OS crash can). **Not tested against - the release yet**, `Names-Test.ps1` restarts a server but doesn't check - these. + killed process loses nothing committed, whatever `Synchronous` says + (with `NORMAL`, a power loss or an OS crash can lose the last second). **Tested** by + `Tests/Restart-Test.ps1` (2026-11-09): kills with traffic in flight, + once in the middle of a catch-up, both directions, all hold. With + `BenchServer.exe` (the same server code plus a stop file), not the + release's exe itself. 4. **A clean shutdown**: the release server only stops from its console (`quit`), so the test force-kills it, and the clean path never runs. Needs a way to stop it without a console: a stop file like @@ -108,12 +110,12 @@ in `Tests/` already, to be pointed at the release instead. - a 1 MB message reads back whole, on both servers; - a JSON query over non-JSON rows without `is_json = 1` is refused with SQLite's error, not answered with no rows (fixed, see below). -9. **Every shipped tool runs once**: `ListNames`, `GetMessages --follow` +9. **Every shipped tool runs once**: `BakaShrotList`, `BakaShrotGetMessages --follow` (picks up a new push, exits 1 once the server is gone) aren't yet. 10. **Version hygiene**: - `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`; - the release commit is tagged (`v1.0.0`), the version comes from it; - - `VERSION.txt` gives the protocol version (4) and the runtime needed; + - `VERSION.txt` gives the protocol version (5 now) and the runtime needed; - the Python client is checked on the oldest version it claims (3.8), not only on the latest (3.14 here). @@ -189,8 +191,9 @@ Not smoke-test items, but what the "1.0" label would promise. From Fixed (protocol 3). - Messages aren't signed by the node that first wrote them: a peer is trusted with what it replicates (`Design/ReplicationIssues.md` #3). -- `synchronous = NORMAL`: the last commits can be lost on a power loss, - decide if that's fine (`Design/StorageConcurrency.md`). +- ~~`synchronous = NORMAL`: the last commits can be lost on a power loss.~~ + Decided: `[BakaShrot.Server] Synchronous`, `FULL` by default + (`Design/StorageConcurrency.md`). Either they're fixed, or they're documented limits of 1.0 (or it's a 0.9). @@ -213,7 +216,7 @@ Notes for when the builds move to a pipeline. - `Build.ps1` ends by running the server, which waits on its console: needs a `-NoRun` switch. It also writes private keys into `Build\`, which must never be published as an artifact. - - The tests use fixed ports (12399 for the release, 12401-12414 for + - The tests use fixed ports (12399 for the release, 12401-12416 for `Tests/`): parallel jobs on one runner collide, make them parameters or pick free ones. - One entry point that runs every test (`Tests/*.ps1`, the handshake diff --git a/Design/ReplicationIssues.md b/Design/ReplicationIssues.md index 73efc46..38c6a51 100644 --- a/Design/ReplicationIssues.md +++ b/Design/ReplicationIssues.md @@ -7,12 +7,18 @@ behind on, with their original ids. Each peer does the same over its own link. Issues below are roughly ordered by how much they matter. -## 1. Drift: the same message id with different content (accepted for now) +## 1. Drift: the same message id with different content (ruled out by config) -**When:** the same topic/node id is written to on two servers, for example -when a client identity is registered on both and pushes to each while they -can't reach each other. This is a configuration issue that """shouldn't""" -happen in real use. +**The rule: a node pushes to one server.** Each client node has its +`[BakaShrot.Client.]` section (its `Node`) on one server only, the +one it pushes to; the other servers get its messages by replication. Then +every topic/node pair has a single writer and this can't happen. Reading +from any server is fine, only pushing matters. Breaking the rule isn't +detected: it's the config's to keep. + +**When it would happen:** the same topic/node id written to on two +servers, for example a client node registered on both, pushing to each +while they can't reach each other. **What happens:** both servers are at `1:2#1`, the link drops, then: diff --git a/Design/StorageConcurrency.md b/Design/StorageConcurrency.md index 09b64c1..176cefa 100644 --- a/Design/StorageConcurrency.md +++ b/Design/StorageConcurrency.md @@ -37,15 +37,47 @@ not done yet: `Design/Suggestions.md`. ## WAL and the write mutex (2026-11-07) - **WAL mode,** set by `SetupStorageDatabase()` (stored in the file), with - `synchronous = NORMAL` on every connection (`#BakaShrot_Storage_Synchronous` - in `Storage.pbi`). Readers no longer block the writer: a 0.5 s raw query - used to stall pushes for seconds and once made one fail with "database is - locked", now pushes run next to it at full speed. -- **The tradeoff of NORMAL:** commits are only synced at checkpoints. The - file can't get corrupted, but the last commits before a power loss or an - OS crash can be lost. Those messages were acknowledged and maybe already - replicated, so their ids could be handed out again: drift - (`ReplicationIssues.md` #1). Set it to `FULL` to sync every commit again. + the config's `synchronous` on every connection (see below). Readers no + longer block the writer: a 0.5 s raw query used to stall pushes for + seconds and once made one fail with "database is locked", now pushes run + next to it at full speed. +- **`synchronous` is `[BakaShrot.Server] Synchronous`** since 2026-11-09, + `FULL` by default (it was `NORMAL`, fixed). The root sets + `BakaShrot_Storage_Synchronous` (`Storage.pbi`) before it opens any + connection. `OFF` is refused (a power loss could corrupt the file), + `EXTRA` too (the same as `FULL` in WAL mode, it only adds a directory + sync for the other journal modes). + - `FULL`: every commit flushes the WAL. An acknowledged push survives a + power loss or an OS crash. The flush is per transaction, so a group + commit's pushes share it. + - `NORMAL`: the WAL is only flushed at checkpoints (about every second, + `Writer.pbi`). The file can't get corrupted, but the last second or so + of commits before a power loss or an OS crash can be lost. Those + messages were acknowledged and maybe already replicated, so their ids + could be handed out again: drift (`ReplicationIssues.md` #1). + +### Measured (2026-11-09) + +`Bench-Replication.ps1 -Ramp "1x0,10x0,10x20" -Parts Ramp -Synchronous ...`, +4 servers in a Y, totals of the 4, one run each (±5-10%). On a VM whose +virtual disk flushes in 0.60 ms (p99 0.78 ms). + +| | OFF | NORMAL | FULL | EXTRA | +|---|---|---|---|---| +| 1 pusher per server, flat out: msg/s | 28,785 | 22,595 | 5,100 | 5,026 | +| ... push p50 / p99 | 0.1 / 0.8 ms | 0.1 / 0.8 ms | 0.7 / 5.3 ms | 0.7 / 3.3 ms | +| 10 pushers per server, flat out: msg/s | 42,854 | 33,870 | 17,207 | 17,763 | +| ... push p50 / p99 / max | 0.6 / 4.8 / 95 ms | 0.5 / 3.3 / 1,113 ms | 1.6 / 9.3 / 123 ms | 1.6 / 8.7 / 129 ms | +| 800 msg/s steady: push p50 / p99 | 0.2 / 0.5 ms | 0.2 / 0.9 ms | 0.9 / 5.0 ms | 0.8 / 4.6 ms | +| Lost on a power loss / OS crash | the file may be corrupted | ~1 s of acknowledged pushes | nothing acknowledged | same as FULL | + +No failed pushes, replication kept up in every case. `FULL`'s cost is the +disk's flush time: one client pushing one message at a time gets about +1 / (flush + 0.15 ms) pushes/s, ~1,300/s here; many clients share flushes +through the group commit, so the total drops much less (half here). On a +server SSD with power-loss protection a flush is far under 0.1 ms (close +to `NORMAL`), on a consumer SSD 1-5 ms, on a hard disk ~10 ms (~100/s for +one sequential client): time one on the target machine to know. - **`BakaShrot_Storage_WriteMutex`** around every write. A connection that finds the database locked sleeps in SQLite's busy handler (1, 2, 5, 10... ms) and retries; with 10+ threads pushing, that's where the time went, and @@ -137,12 +169,11 @@ ids exactly 1-800 on both servers. the push or batch is refused and retried at the next check-in for replication. Fine at current loads; decide later whether pushes should retry. -- **Whether PureBasic's `DatabaseError()` is per thread** in thread-safe - mode. If it's shared by the whole program, an error message could show up - in the wrong thread's log or refusal. The data isn't affected. - `RunReadOnlyQuery()` only checks it after reading the rows on Linux, where - it could refuse a valid query because of another thread's error. On - Windows it asks SQLite instead (`sqlite3_errcode()` on its own - connection), see `Design/Release.md`. +- ~~**Whether PureBasic's `DatabaseError()` is per thread**~~: it is, in + thread-safe mode (`/THREAD`), checked 2026-11-09 with 5.73 and 6.40: two + threads failing on their own connections 20,000 times each never saw the + other's message. `sqlite3_errmsg16()` on the connection gives the same + text. (`RunReadOnlyQuery()` still asks SQLite on Windows, for the errors + `DatabaseError()` doesn't report at all, see `Design/Release.md`.) - **A single storage thread with a job queue,** only if writes ever become the bottleneck. SQLite only has one writer anyway. diff --git a/Design/Suggestions.md b/Design/Suggestions.md index d474471..fc83c23 100644 --- a/Design/Suggestions.md +++ b/Design/Suggestions.md @@ -104,11 +104,9 @@ protocol change). ## 3. Smaller ones -- **Decide on `synchronous = NORMAL`** (`#BakaShrot_Storage_Synchronous`): - the last commits before a power loss or an OS crash can be lost, and their - ids handed out again (drift). With group commit, `FULL` costs one sync per - transaction, not per push, so it may cost much less than it used to: worth - one benchmark run before deciding. +- ~~**Decide on `synchronous = NORMAL`**~~: done 2026-11-09, a config + option (`Synchronous`), `FULL` by default, measured in + `Design/StorageConcurrency.md`. - **`Build.ps1`:** the compiler path and `-Compiler` are fixed (2026-11-07), but the `Libs\` zips for libsodium and SQLite are gone: it only works while the extracted DLLs are still in `Libs\*d`. diff --git a/Examples/README.md b/Examples/README.md new file mode 100644 index 0000000..9b01642 --- /dev/null +++ b/Examples/README.md @@ -0,0 +1,12 @@ +# Examples + +Ready-to-run setups, each in its own folder with its configs, scripts to +start it, and a README. Build first (`Build.ps1` at the root): the scripts +take the exes from `Build\`, or from a release folder with `-BinDir`. + +| Example | What it shows | +|---|---| +| [`SingleServer`](SingleServer/README.md) | One server, one client: pushing, reading, attachments, names, SQL, with the tools. | + +Their keys are in the repository, so public: they're only for trying the +examples locally, never reuse them. diff --git a/Examples/SingleServer/README.md b/Examples/SingleServer/README.md new file mode 100644 index 0000000..744ed66 --- /dev/null +++ b/Examples/SingleServer/README.md @@ -0,0 +1,136 @@ +# One server, one client + +The smallest BakaShrot setup: one server on `127.0.0.1:12360`, one client +that pushes and reads messages with the tools. + +> **The keys in `server.ini` and `client.ini` are public, they're in the +> repository.** They're only for trying this example on your own machine +> (the server only listens on 127.0.0.1). Never reuse them: make your own +> with `BakaShrotGenerateKeyPairs.exe`. + +## Running it + +Build first, `Build.ps1` at the root, or use a release folder (`-BinDir +Release\` on both scripts). Then, from this folder: + +```powershell +powershell -ExecutionPolicy Bypass -File Start-Server.ps1 +powershell -ExecutionPolicy Bypass -File Run-Client.ps1 +``` + +- `Start-Server.ps1` opens the server in its own window and waits until it + listens. Type `quit` in that window to stop it (`help` lists the other + commands). `-Here` runs it in the current console instead, `-Reset` + deletes its database first, so the ids start from 1 again. +- `Run-Client.ps1` goes through what a client does, printing each command + before its output. The commands can be pasted as they are from this + folder: + +```text +== Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo +> ..\..\Build\BakaShrotPushMessage.exe @messages\hello.json client.ini + Pushed as message #1 +... +== Read the latest message of logs:demo (topic:node, by name) +> ..\..\Build\BakaShrotGetLatestMessage.exe logs demo client.ini + Message logs:demo#2 (ids 1:2), pushed 2026-11-08T21:23:53.590Z + Attachment: 159 bytes + {"level":"info","text":"Daily report, attached"} +``` + +The server's database (`example.sqlite`) and what the client saves +(`out\`) stay in this folder, git ignores them. + +## What's in here + +| File | What it is | +|---|---| +| `server.ini` | The server: its key, its names, where it listens, the one client it accepts and what that client may do. Every option is documented in `Server/Config/schema.ini`. | +| `client.ini` | The client: its key pair, the node it writes as (`demo`), and the server's address and public key. Every tool takes it as its last argument. | +| `Start-Server.ps1` | Starts the server with `server.ini`. | +| `Run-Client.ps1` | The client's steps, below. | +| `messages\` | What the client pushes (`hello.json`, `reading.json`, `report.json` with `report.txt` attached) and the SQL it runs (`query.sql`). | + +## How the two configs fit together + +- **Keys:** each side has a key pair. The server lists the client's public + key in `[BakaShrot.Client.demo] PublicKeys`; the client has the server's + in `ServerPublicKey`. Every connection is encrypted, and only reaches the + server holding the matching private key. +- **Names:** messages are filed under a topic and a node. The topics are + listed in `[BakaShrot.Topics]`, the nodes come from the sections that + define them (`server`, `demo`). The server gives each name an id of its + own; clients use the names. +- **Who the client is:** its node, `demo`, in both configs (`Node`). + Every message it pushes is stored under it. That's why the server + checks it: the key proves who's connecting, the server's `Node` for that + key says which node it may write as, so no client can push as another's + node. +- **Where its pushes go:** the server's `DefaultTopic = logs`, unless a + push names another topic in `PushTopics` (`-t sensors`). Only the server + has it: `client.ini` has no topic. +- **What it may do:** read every topic (`ReadTopics = *`, `AllowRead`), + push (`AllowWrite`), run read-only SQL (`AllowQuery`). +- **Retention:** `sensors` messages are kept a day, `logs` ones forever. +- **Durability:** `Synchronous = FULL` (the default): every message the + server acknowledges is flushed to disk first, so it survives a power cut. + `NORMAL` pushes faster but can lose the last second or so of messages + then; see `Server/Config/schema.ini`. + +## What the client does + +`Run-Client.ps1`, step by step: + +1. **Pushes** `hello.json` to `logs`, its default topic: `BakaShrotPushMessage @messages\hello.json`. + JSON goes in a file (`@file`): PowerShell drops the double quotes of an + argument. +2. **Pushes** `reading.json` to `sensors`: `-t sensors`. +3. **Pushes** `report.json` with `report.txt` attached: `-a messages\report.txt`. +4. **Reads the latest** message of `logs:demo`: `BakaShrotGetLatestMessage logs demo`. +5. **Saves the attachment** back to `out\report-copy.txt` and checks it's + the same: `BakaShrotGetAttachment logs demo out\report-copy.txt`. +6. **Reads every** message of `logs:demo`, one per line (id, time, data): + `BakaShrotGetMessages logs demo --time`. +7. **Reads** `sensors:demo`'s latest. +8. **Shows the ids** the server has for the names: `BakaShrotResolveIds topic sensors`, `BakaShrotList`. +9. **Queries** with SQL: `BakaShrotQuery @messages\query.sql`, on the + `messages` view, which has the names. + +To watch messages arrive, leave this running and push from another +terminal: + +```powershell +..\..\Build\BakaShrotGetMessages.exe logs demo --after latest --follow client.ini +``` + +## Looking at the database + +`example.sqlite` is a plain SQLite file, the `messages` view has the +names. To browse one topic in a tool like SQLiteStudio: + +1. Open the `browse` table: one row. Pick a topic in its `topic` cell (a + dropdown of the topics, from its foreign key), and a node in `node` to + narrow it, or leave it NULL for every node. Commit. +2. Open the `browse_messages` view: that topic's messages, newest first, + with their node, id, time (UTC), data and attachment size. + +The server never writes `browse`, so it's safe to change while it runs. +Close the tool when done: an open grid keeps the server from finishing +its checkpoints, and its WAL file grows meanwhile. + +## From Python + +The same `client.ini` works with the Python client +(`Interactors/Python/bakashrot.py`, over the DLL). From the repository's +root: + +```python +import sys +sys.path.insert(0, r"Interactors\Python") +from bakashrot import Client + +with Client.from_ini(r"Examples\SingleServer\client.ini", r"Build\BakaShrot_Client.dll") as client: + print("pushed", client.push({"from": "python"})) + for message in client.get_messages("logs", "demo").messages: + print(message.id, message.json()) +``` diff --git a/Examples/SingleServer/Run-Client.ps1 b/Examples/SingleServer/Run-Client.ps1 new file mode 100644 index 0000000..b8a662c --- /dev/null +++ b/Examples/SingleServer/Run-Client.ps1 @@ -0,0 +1,101 @@ +# ============================================================================ +# BakaShrot example: what a client does, with the tools and client.ini. +# +# Start the server first (Start-Server.ps1). Each step prints the command +# it runs, then its output: run from this folder, the commands can be +# pasted as they are. Every run pushes 3 more messages, the ids go on from +# the last run's (Start-Server.ps1 -Reset starts over). +# +# Usage: powershell -ExecutionPolicy Bypass -File Run-Client.ps1 [-BinDir ] +# -BinDir Where the tools are, with BakaShrot_Client.dll next to them: +# Build\ by default (Build.ps1), or a Release\\. +# ============================================================================ + +param( + [string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build") +) + +$ErrorActionPreference = "Stop" + +$Port = 12360 + +function Test-Port($Port) { + $Client = New-Object System.Net.Sockets.TcpClient + try { + $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) + return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) + } catch { return $false } + finally { $Client.Close() } +} + +function Write-Step($Text) { + Write-Host "" + Write-Host "== $Text" -ForegroundColor Cyan +} + +# Runs a tool, shows the command and what it printed, stops if it failed. +# client.ini is always the last argument. +function Invoke-Tool($Name, [string[]]$Arguments) { + $Arguments += "client.ini" + $Shown = $Arguments | ForEach-Object { if ($_ -match " ") { "`"$_`"" } else { $_ } } + Write-Host ("> " + (Join-Path $Bin "$Name.exe") + " " + ($Shown -join " ")) -ForegroundColor DarkGray + $Output = & (Join-Path $Bin "$Name.exe") @Arguments 2>&1 + $Code = $LASTEXITCODE + $Output | ForEach-Object { Write-Host " $_" } + if ($Code -ne 0) { throw "$Name failed with code $Code" } + return ($Output -join "`n") +} + +if (-not (Test-Path (Join-Path $BinDir "BakaShrot_Client.dll"))) { + throw "No BakaShrot_Client.dll in ${BinDir}: build it first (Build.ps1), or pass -BinDir" +} +if (-not (Test-Port $Port)) { + throw "Nothing listens on port ${Port}: start the server first (Start-Server.ps1)" +} + +# From this folder, so every path is short: client.ini, messages\... +Push-Location $PSScriptRoot +try { + $Bin = Resolve-Path -Relative $BinDir + New-Item -ItemType Directory -Force "out" | Out-Null + + Write-Step "Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo" + # JSON goes in a file (@file): PowerShell drops the double quotes of an argument. + $null = Invoke-Tool "BakaShrotPushMessage" @("@messages\hello.json") + + Write-Step "Push one to another topic it may push to (sensors)" + $null = Invoke-Tool "BakaShrotPushMessage" @("-t", "sensors", "@messages\reading.json") + + Write-Step "Push one with a file attached" + $Pushed = Invoke-Tool "BakaShrotPushMessage" @("-a", "messages\report.txt", "@messages\report.json") + if ($Pushed -notmatch "message #(\d+)") { throw "Unexpected answer: $Pushed" } + $ReportId = $Matches[1] + + Write-Step "Read the latest message of logs:demo (topic:node, by name)" + $null = Invoke-Tool "BakaShrotGetLatestMessage" @("logs", "demo") + + Write-Step "Read the attachment back" + $null = Invoke-Tool "BakaShrotGetAttachment" @("logs", "demo", $ReportId, "out\report-copy.txt") + if ((Get-FileHash "out\report-copy.txt").Hash -ne (Get-FileHash "messages\report.txt").Hash) { throw "The attachment came back different" } + Write-Host " Same bytes as messages\report.txt" + + Write-Step "Read every message of logs:demo, with when they were pushed (UTC)" + $null = Invoke-Tool "BakaShrotGetMessages" @("logs", "demo", "--time") + + Write-Step "Read the sensors one" + $null = Invoke-Tool "BakaShrotGetLatestMessage" @("sensors", "demo") + + Write-Step "What the server calls the names: their ids there" + $null = Invoke-Tool "BakaShrotResolveIds" @("topic", "sensors") + $null = Invoke-Tool "BakaShrotList" @() + + Write-Step "A raw SQL query (needs AllowQuery = 1), from messages\query.sql" + $null = Invoke-Tool "BakaShrotQuery" @("@messages\query.sql") + + Write-Host "" + Write-Host "Done. To follow new messages as they come, from this folder:" -ForegroundColor Green + Write-Host " $(Join-Path $Bin 'BakaShrotGetMessages.exe') logs demo --after latest --follow client.ini" +} +finally { + Pop-Location +} diff --git a/Examples/SingleServer/Start-Server.ps1 b/Examples/SingleServer/Start-Server.ps1 new file mode 100644 index 0000000..866ebe2 --- /dev/null +++ b/Examples/SingleServer/Start-Server.ps1 @@ -0,0 +1,67 @@ +# ============================================================================ +# BakaShrot example: starts the server with server.ini. +# +# In a window of its own by default (the server needs a console: it reads +# its commands there, and stops at once without one), then waits until it +# listens. Type "quit" in that window to stop it, "help" for the others. +# +# Usage: powershell -ExecutionPolicy Bypass -File Start-Server.ps1 [-BinDir ] [-Here] [-Reset] +# -BinDir Where BakaShrot_Server.exe is, with libsodium.dll and +# sqlite3.dll: Build\ by default (Build.ps1), or a Release\\. +# -Here Runs it in this console instead, until "quit". +# -Reset Deletes the example's database first: no messages, ids from 1. +# +# Its database, example.sqlite, goes next to this script. +# ============================================================================ + +param( + [string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build"), + [switch]$Here, + [switch]$Reset +) + +$ErrorActionPreference = "Stop" + +$Server = Join-Path $BinDir "BakaShrot_Server.exe" +$Ini = Join-Path $PSScriptRoot "server.ini" +$Port = 12360 + +function Test-Port($Port) { + $Client = New-Object System.Net.Sockets.TcpClient + try { + $Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null) + return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) + } catch { return $false } + finally { $Client.Close() } +} + +if (-not (Test-Path $Server)) { + throw "No ${Server}: build it first (Build.ps1), or pass -BinDir" +} +if (Test-Port $Port) { + throw "Something already listens on port $Port, the example server may already run" +} + +if ($Reset) { + Get-ChildItem $PSScriptRoot -Filter "example.sqlite*" | Remove-Item -Confirm:$false + Write-Host "Deleted the example's database" +} + +if ($Here) { + Push-Location $PSScriptRoot + try { & $Server $Ini } + finally { Pop-Location } + exit $LASTEXITCODE +} + +$Process = Start-Process -FilePath $Server -ArgumentList "`"$Ini`"" -WorkingDirectory $PSScriptRoot -PassThru +$Deadline = (Get-Date).AddSeconds(15) +while (-not (Test-Port $Port)) { + if ($Process.HasExited) { throw "The server stopped with code $($Process.ExitCode), see its log above" } + if ((Get-Date) -gt $Deadline) { throw "The server isn't listening on $Port after 15 s" } + Start-Sleep -Milliseconds 100 +} + +Write-Host "The server runs in its own window (process $($Process.Id)), on 127.0.0.1:$Port." +Write-Host "Try it with: powershell -ExecutionPolicy Bypass -File `"$(Join-Path $PSScriptRoot 'Run-Client.ps1')`"" +Write-Host "Stop it by typing quit in its window." diff --git a/Examples/SingleServer/client.ini b/Examples/SingleServer/client.ini new file mode 100644 index 0000000..5a32cf6 --- /dev/null +++ b/Examples/SingleServer/client.ini @@ -0,0 +1,26 @@ +; ============================================================================ +; BakaShrot example: the client's config, read by every tool (their last +; argument), the client DLL and the Python client. +; +; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real. +; Make your own with BakaShrotGenerateKeyPairs.exe. +; ============================================================================ + +[BakaShrot] +; This client's key pair. The server lists the public key in +; [BakaShrot.Client.demo] PublicKeys. +PrivateKey = zDA8o6hp7zkIatlumOKFWqV8j3yYON8QFpIkMAEnpJnKv4FbbX4SmshWDRJp9ds5qpEDVYRHSnE7exw2pkQK1w== +PublicKey = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc= + +; The node it writes as: the server checks its section for this key says +; Node = demo. Every message it pushes is stored as "demo". +; No topic here: where its pushes go when they don't name one is the +; server's DefaultTopic, which topics it may push to and read its +; PushTopics and ReadTopics. +Node = demo + +; Where the server is, and its public key: the client only talks to the +; server holding the matching private key. +ServerHost = 127.0.0.1 +ServerPort = 12360 +ServerPublicKey = k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4= diff --git a/Examples/SingleServer/messages/hello.json b/Examples/SingleServer/messages/hello.json new file mode 100644 index 0000000..5cf49bd --- /dev/null +++ b/Examples/SingleServer/messages/hello.json @@ -0,0 +1 @@ +{"level":"info","text":"Hello from the example client"} \ No newline at end of file diff --git a/Examples/SingleServer/messages/query.sql b/Examples/SingleServer/messages/query.sql new file mode 100644 index 0000000..bdcd7a3 --- /dev/null +++ b/Examples/SingleServer/messages/query.sql @@ -0,0 +1 @@ +SELECT topic, node, message_id, pushed_utc, message_data ->> '$.text' FROM messages WHERE topic = 'logs' AND is_json = 1 ORDER BY message_id \ No newline at end of file diff --git a/Examples/SingleServer/messages/reading.json b/Examples/SingleServer/messages/reading.json new file mode 100644 index 0000000..214d764 --- /dev/null +++ b/Examples/SingleServer/messages/reading.json @@ -0,0 +1 @@ +{"sensor":"kitchen-temperature","celsius":21.5} \ No newline at end of file diff --git a/Examples/SingleServer/messages/report.json b/Examples/SingleServer/messages/report.json new file mode 100644 index 0000000..0ef839f --- /dev/null +++ b/Examples/SingleServer/messages/report.json @@ -0,0 +1 @@ +{"level":"info","text":"Daily report, attached"} \ No newline at end of file diff --git a/Examples/SingleServer/messages/report.txt b/Examples/SingleServer/messages/report.txt new file mode 100644 index 0000000..e36a398 --- /dev/null +++ b/Examples/SingleServer/messages/report.txt @@ -0,0 +1,5 @@ +Daily report +============ + +Any file can be attached to a message: bytes of any kind, up to the +server's MaxAttachmentSize. The message's JSON says what it is. diff --git a/Examples/SingleServer/server.ini b/Examples/SingleServer/server.ini new file mode 100644 index 0000000..6aac1ac --- /dev/null +++ b/Examples/SingleServer/server.ini @@ -0,0 +1,67 @@ +; ============================================================================ +; BakaShrot example: the server's config (one server, one client). +; +; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real. +; Make your own with BakaShrotGenerateKeyPairs.exe. +; +; Every option is documented in Server/Config/schema.ini. +; ============================================================================ + +[BakaShrot] +; This server's private key. Its public key, which the client needs, is +; k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4= (the server logs it too). +PrivateKey = KymGH/iJFcqE0JtGmRmWIsQnKTEl49Zq+qYEsfLHtWOTfZA2JNcv2UDsOF3AFC/2NBei4AO6NyJo5ZVm4DckTg== + +; The node this server authenticates as when it links to peers. It has +; none here. +Node = server + + +; The topics this server has. It gives each an id of its own (they keep it +; across restarts); clients and other servers use the names. +[BakaShrot.Topics] +logs +sensors + +; No [BakaShrot.Nodes]: the nodes come from the sections that define them, +; "server" above and "demo" below (and the ones peers send, as they come). + + +; Sensor readings are kept a day, logs forever (no line for them). +[BakaShrot.Retention] +sensors = 1d + + +[BakaShrot.Server] +; Only reachable from this machine. +Host = 127.0.0.1 +Port = 12360 +ReplicatingTopics = logs;sensors +NetThreadPoolSize = 4 +; Next to this file: Start-Server.ps1 runs the server from this folder. +DatabasePath = ./example.sqlite +MaxAttachmentSize = 64M +; Every acknowledged push is on disk, even through a power loss (the +; default). NORMAL is faster but can lose the last second of messages then. +Synchronous = FULL + + +; The one client: Run-Client.ps1's tools, with client.ini. +[BakaShrot.Client.demo] +; client.ini's PublicKey. +PublicKeys = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc= +; The node this key writes as, fixed: every message it pushes is stored +; under it, so no client can push as another's node. client.ini's Node +; must say the same. +Node = demo +; Where its pushes go when they don't name a topic (BakaShrotPushMessage +; without -t). Only a default: it may push to any topic in PushTopics. +DefaultTopic = logs +; The topics it may push to (always as "demo"), and read from. Without +; these two lines: only its DefaultTopic. +PushTopics = logs;sensors +ReadTopics = * +AllowRead = 1 +AllowWrite = 1 +; Raw read-only SQL, for BakaShrotQuery.exe. +AllowQuery = 1 diff --git a/Interactors/Python/bakashrot.py b/Interactors/Python/bakashrot.py index 101a987..0476c7b 100644 --- a/Interactors/Python/bakashrot.py +++ b/Interactors/Python/bakashrot.py @@ -27,6 +27,18 @@ The connection only goes through to the server holding the private key of server_public_key (client.ini's ServerPublicKey, the server logs it when it starts), and everything on it is encrypted. +Errors are exceptions with a code (`error.code`, an ErrorCode, the same +numbers as the DLL's BakaShrot_GetLastError(), see +Client/BakaShrot_ErrorCodes.pbi): + RefusedError the server refused (codes 1-99), still connected + ConnectionLostError not connected, unreachable, the connection lost or + broken: connect() again (nothing reconnects by itself) + AuthError the server rejected the handshake or couldn't prove + its key: fix the config, retrying won't help + BakaShrotError the rest: a bad argument, a file, the DLL itself +A push whose answer was lost (ConnectionLostError) may have been stored all +the same: pushed again, it's stored twice. Delivery is at least once. + The DLL holds a single connection per process: only one Client may be connected at a time. Calls are serialized with a lock, so a Client can be shared between threads, one request at a time. @@ -40,6 +52,7 @@ from __future__ import annotations import configparser import ctypes +import enum import json import os import threading @@ -50,7 +63,7 @@ from typing import Any, Iterator, Optional, Union __all__ = [ "Client", "Message", "MessagesPage", "NameEntry", "NamesList", - "BakaShrotError", "RefusedError", "ConnectionLostError", + "BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode", "MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE", ] @@ -61,20 +74,75 @@ MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096 Ref = Union[str, int] +class ErrorCode(enum.IntEnum): + """What failed: Client/BakaShrot_ErrorCodes.pbi, the same numbers. + 1-99: refused by the server, 100+: the client's own.""" + NONE = 0 + # Refused by the server, the connection still open. + NOT_ALLOWED = 1 # AllowRead/Write/Query, PushTopics/ReadTopics + UNKNOWN_NAME = 2 # a topic or node this server doesn't know + NOT_FOUND = 3 # no such message, attachment or upload + NOT_READY = 4 # the attachment isn't on this server yet: retry later + TOO_BIG = 5 # over a limit, or more than this server keeps + NO_DEFAULT_TOPIC = 6 # a push without a topic, and no DefaultTopic + INVALID_REQUEST = 7 # parts out of order, an upload for another topic... + DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256 + QUERY_FAILED = 9 # the SQL failed + SERVER_ERROR = 10 # the server's database failed: retry later + # The client's own. + NOT_CONNECTED = 100 # never connected, or closed or lost before + CONNECT_FAILED = 101 # nothing answers at that host and port + AUTH_REJECTED = 102 # the server closed the handshake: wrong ServerPublicKey, + # a key or node it doesn't allow, another version + SERVER_NOT_VERIFIED = 103 # the server couldn't prove its key + CONNECTION_LOST = 104 # broke during a request (a push may still be stored) + PROTOCOL_ERROR = 105 # an unexpected answer, the connection is closed + INVALID_ARGUMENT = 106 + FILE_ERROR = 107 + ATTACHMENT_MISMATCH = 108 # a downloaded attachment that doesn't match its SHA-256 + ALREADY_CONNECTED = 109 + INTERNAL = 110 # out of memory, the DLL missing or too old... + + @property + def is_refusal(self) -> bool: + return 1 <= self.value <= 99 + + +def _error_code(value: int): + """An ErrorCode, or the int itself if this module doesn't know it.""" + try: + return ErrorCode(value) + except ValueError: + return value + + class BakaShrotError(Exception): - """Something failed: the DLL couldn't be loaded, a bad argument, ...""" + """Something failed: code (an ErrorCode) tells what, see ErrorCode.""" + + def __init__(self, message: str, code: int = ErrorCode.INTERNAL): + super().__init__(message) + self.code = _error_code(code) class RefusedError(BakaShrotError): - """The server refused the request, the connection is still open.""" + """The server refused the request, the connection is still open. code + says why (1-99, e.g. ErrorCode.NOT_FOUND), reason in the server's words.""" - def __init__(self, reason: str): - super().__init__(reason or "Refused") + def __init__(self, reason: str, code: int): + super().__init__(reason or "Refused", code) self.reason = reason class ConnectionLostError(BakaShrotError): - """The connection failed or was closed, connect() again to go on.""" + """Not connected, or the connection failed or was closed (code: + NOT_CONNECTED, CONNECT_FAILED, CONNECTION_LOST, PROTOCOL_ERROR): + connect() again to go on.""" + + +class AuthError(BakaShrotError): + """The server rejected the handshake (AUTH_REJECTED) or couldn't prove it + holds server_public_key's private key (SERVER_NOT_VERIFIED): a config to + fix, connecting again won't help.""" @dataclass(frozen=True) @@ -186,10 +254,10 @@ class _Dll: I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p signatures = { + "BakaShrot_GetLastError": (L, []), "BakaShrot_SetPrivateKeyA": (I, [P]), "BakaShrot_SetPublicKeyA": (I, [P]), "BakaShrot_SetServerPublicKeyA": (I, [P]), - "BakaShrot_SetTopicA": (I, [P]), "BakaShrot_SetNodeA": (I, [P]), "BakaShrot_ConnectA": (I, [P, L]), "BakaShrot_IsConnected": (I, []), @@ -229,7 +297,7 @@ class _Dll: try: function = getattr(self.lib, name) except AttributeError as error: - raise BakaShrotError(f"{path} has no {name}, is it an older build?") from error + raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error function.restype = restype function.argtypes = argtypes setattr(self, name[len("BakaShrot_"):], function) @@ -247,23 +315,24 @@ class _Dll: class Client: """A connection to a BakaShrot server, through the DLL. - private_key, public_key: the client's Ed25519 keys in Base64 (KeyGen.exe). + private_key, public_key: the client's Ed25519 keys in Base64 (BakaShrotGenerateKeyPairs.exe). server_public_key: the server's Ed25519 public key in Base64, it must prove it holds the matching private key. - topic, node: who the client is, names or ids, as the server's - [BakaShrot.Client.] Identities lists them. + node: the node the client writes as, a name or an id, which the + server's [BakaShrot.Client.] must give its key (Node). Its + default topic, for pushes that don't name one, is the server's to say + (that section's DefaultTopic). """ _connected_client: Optional["Client"] = None - def __init__(self, private_key: str, public_key: str, server_public_key: str, topic: Ref, node: Ref, + def __init__(self, private_key: str, public_key: str, server_public_key: str, node: Ref, host: str = "127.0.0.1", port: int = 12345, dll_path: Optional[str] = None): self._dll = _Dll.get(dll_path) self._lock = threading.RLock() self.private_key = private_key self.public_key = public_key self.server_public_key = server_public_key - self.topic = topic self.node = node self.host = host self.port = int(port) @@ -271,45 +340,48 @@ class Client: @classmethod def from_ini(cls, path: str, dll_path: Optional[str] = None) -> "Client": """From a client.ini as the tools read it: [BakaShrot] PrivateKey, - PublicKey, ServerPublicKey, Topic, Node, ServerHost, ServerPort.""" + PublicKey, ServerPublicKey, Node, ServerHost, ServerPort (a Topic + left in it is ignored).""" parser = configparser.ConfigParser(interpolation=None) if not parser.read(path, encoding="utf-8-sig"): - raise BakaShrotError(f"Failed to open '{path}'") + raise BakaShrotError(f"Failed to open '{path}'", ErrorCode.FILE_ERROR) section = parser["BakaShrot"] if parser.has_section("BakaShrot") else {} def get(key, fallback=None): value = section.get(key, fallback) if value is None: - raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}") + raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}", ErrorCode.INVALID_ARGUMENT) return value.strip() return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"), - get("Topic", section.get("TopicId")), get("Node", section.get("NodeId")), + get("Node", section.get("NodeId")), get("ServerHost"), int(get("ServerPort")), dll_path) # --- Connection -------------------------------------------------------- def connect(self) -> "Client": - """Connects and authenticates, raises BakaShrotError on failure.""" + """Connects and authenticates. Raises ConnectionLostError when the + server can't be reached (CONNECT_FAILED), AuthError when it rejects + the handshake or can't prove its key, BakaShrotError on a bad setting + (INVALID_ARGUMENT) or another Client holding the DLL's connection + (ALREADY_CONNECTED).""" with self._lock: owner = Client._connected_client if owner is not None and owner is not self and owner.connected: - raise BakaShrotError("The DLL holds one connection, another Client is connected") + raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED) if self.connected: return self dll = self._dll if not dll.SetPrivateKeyA(self.private_key.encode("ascii")): - raise BakaShrotError("Invalid private key") + raise BakaShrotError("Invalid private key", dll.GetLastError()) if not dll.SetPublicKeyA(self.public_key.encode("ascii")): - raise BakaShrotError("Invalid public key") + raise BakaShrotError("Invalid public key", dll.GetLastError()) if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")): - raise BakaShrotError("Invalid server public key") - if not dll.SetTopicA(_ref(self.topic)): - raise BakaShrotError(f"Invalid topic {self.topic!r}") + raise BakaShrotError("Invalid server public key", dll.GetLastError()) if not dll.SetNodeA(_ref(self.node)): - raise BakaShrotError(f"Invalid node {self.node!r}") + raise BakaShrotError(f"Invalid node {self.node!r}", dll.GetLastError()) if not dll.ConnectA(self.host.encode("utf-8"), self.port): - raise ConnectionLostError(f"Failed to connect and authenticate to {self.host}:{self.port}") + raise self._failed(f"Connect to {self.host}:{self.port}") Client._connected_client = self return self @@ -331,22 +403,39 @@ class Client: def _check_connected(self) -> None: if not self.connected: - raise ConnectionLostError("Not connected") + raise ConnectionLostError("Not connected", ErrorCode.NOT_CONNECTED) + + _MESSAGES = { + ErrorCode.NOT_CONNECTED: "not connected", + ErrorCode.CONNECT_FAILED: "nothing answers there", + ErrorCode.AUTH_REJECTED: "the server closed the connection during the handshake: wrong server public key, " + "a key or node it doesn't allow, or another version (its log says which)", + ErrorCode.SERVER_NOT_VERIFIED: "the server couldn't prove it holds the server public key's private key", + ErrorCode.CONNECTION_LOST: "the connection to the server failed", + ErrorCode.PROTOCOL_ERROR: "the server answered something unexpected, the connection is closed", + } def _failed(self, what: str) -> BakaShrotError: - """The error for a failed request: refused, or the connection is gone.""" - if self._dll.IsConnected(): - reason = self._dll.string(self._dll.GetRefusalReasonA) - return RefusedError(reason) if reason else BakaShrotError(f"{what} failed") - if Client._connected_client is self: + """The error for a failed call, by the DLL's BakaShrot_GetLastError().""" + code = _error_code(self._dll.GetLastError()) + reason = self._dll.string(self._dll.GetRefusalReasonA) + if isinstance(code, int) and 1 <= int(code) <= 99: + return RefusedError(reason, code) + if not self._dll.IsConnected() and Client._connected_client is self: Client._connected_client = None - return ConnectionLostError(f"{what}: the connection to the server failed") + name = code.name if isinstance(code, ErrorCode) else str(code) + message = f"{what} ({name}): {reason or self._MESSAGES.get(code, 'failed')}" + if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR): + return ConnectionLostError(message, code) + if code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED): + return AuthError(message, code) + return BakaShrotError(message, code if code else ErrorCode.INTERNAL) # --- Requests ---------------------------------------------------------- def push(self, data: Any, topic: Optional[Ref] = None, attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int: - """Pushes a message into topic (default: the client's own), under + """Pushes a message into topic (default: the client's default one, its server's DefaultTopic), under the client's node. data is stored as is if it's a str (JSON or not), anything else is turned into JSON first. Returns its message id. @@ -357,7 +446,7 @@ class Client: data = json.dumps(data, separators=(",", ":"), ensure_ascii=False) encoded = data.encode("utf-8") if len(encoded) > MAX_MESSAGE_SIZE: - raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}") + raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT) topic_ref = b"" if topic is None else _ref(topic) with self._lock: self._check_connected() @@ -366,13 +455,13 @@ class Client: elif isinstance(attachment, (bytes, bytearray, memoryview)): raw = bytes(attachment) if not raw: - raise BakaShrotError("The attachment is empty") + raise BakaShrotError("The attachment is empty", ErrorCode.INVALID_ARGUMENT) buffer = ctypes.create_string_buffer(raw, len(raw)) message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw)) else: path = os.fspath(attachment) if not os.path.isfile(path) or os.path.getsize(path) == 0: - raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty") + raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty", ErrorCode.FILE_ERROR) message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8")) if message_id < 1: raise self._failed("Push") @@ -418,7 +507,7 @@ class Client: self._check_connected() if not self._dll.GetLatestMessageOfA(_ref(topic), _ref(node)): error = self._failed("Latest message") - if isinstance(error, RefusedError) and error.reason.startswith("No message for"): + if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND: return None raise error return self._current() @@ -460,7 +549,8 @@ class Client: """Every message of topic/node after `after`, then new ones as they come, checking every `interval` seconds once caught up. Forever: stop iterating to stop. after="latest" starts with the next new one. - Raises ConnectionLostError if the connection fails.""" + Raises ConnectionLostError if the connection fails: nothing + reconnects by itself, connect() again and follow from the last id.""" if after == "latest": latest = self.latest(topic, node) after = latest.id if latest else 0 diff --git a/Interactors/Python/check_bakashrot.py b/Interactors/Python/check_bakashrot.py index 797ee93..81b9722 100644 --- a/Interactors/Python/check_bakashrot.py +++ b/Interactors/Python/check_bakashrot.py @@ -14,7 +14,7 @@ import threading import time import bakashrot -from bakashrot import BakaShrotError, Client, ConnectionLostError, RefusedError +from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError dll_path, kitchen_ini, lounge_ini = sys.argv[1:4] fails = 0 @@ -30,11 +30,12 @@ def check(what, ok, detail=""): print(f"{'PASS' if ok else 'FAIL'} {what}\n -> {detail}", flush=True) -def raises(function, error_type, contains=""): +def raises(function, error_type, contains="", code=None): try: function() except error_type as error: - return contains in str(error), f"{type(error).__name__}: {error}" + got = getattr(error, "code", None) + return contains in str(error) and (code is None or got == code), f"{type(error).__name__} [{got!r}]: {error}" except Exception as error: # noqa: BLE001 - reported as a failure return False, f"{type(error).__name__}: {error}" return False, "didn't raise" @@ -111,6 +112,8 @@ with kitchen: rows = kitchen.query("SELECT is_json, COUNT(*) AS n FROM data GROUP BY is_json ORDER BY is_json") check("query(): is_json flags 3 non-JSON, 250 JSON", rows == [{"is_json": "0", "n": "3"}, {"is_json": "1", "n": "250"}], rows) + ok, detail = raises(lambda: kitchen.query("SELECT nope FROM data"), RefusedError, "nope", ErrorCode.QUERY_FAILED) + check("A query that fails: RefusedError, QUERY_FAILED", ok, detail) # --- Answers split at ~1 MB ---------------------------------------------- big = "x" * (700 * 1024) @@ -123,18 +126,18 @@ with kitchen: [len(m.data) for m in every]) # --- Refusals ------------------------------------------------------------ - ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'") - check("Unknown node: RefusedError", ok, detail) + ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'", ErrorCode.UNKNOWN_NAME) + check("Unknown node: RefusedError, UNKNOWN_NAME", ok, detail) check("Still connected after a refusal", kitchen.connected and kitchen.latest("logs", "kitchen").id == big_ids[-1]) ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", limit=0), ValueError) check("limit 0: ValueError, before asking", ok, detail) ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", after=-1), ValueError) check("after -1: ValueError", ok, detail) - ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic") - check("Push to an unknown topic: RefusedError", ok, detail) + ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic", ErrorCode.UNKNOWN_NAME) + check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail) secret_id = kitchen.push({"s": 1}, topic="secret") check("Push to another allowed topic", secret_id == 1, secret_id) - ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection") + ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED) check("A second Client can't connect while one is", ok and not lounge.connected, detail) topics = kitchen.list_topics() @@ -192,26 +195,34 @@ with kitchen: sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page] check("get_messages(): each message's attachment", sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes) - ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment") - check("get_attachment() of a message without: RefusedError", ok, detail) - ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty") + ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment", ErrorCode.NOT_FOUND) + check("get_attachment() of a message without: RefusedError, NOT_FOUND", ok, detail) + ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty", ErrorCode.INVALID_ARGUMENT) check("An empty attachment: refused before sending", ok, detail) - ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file") + ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file", ErrorCode.FILE_ERROR) check("A missing file: refused before sending", ok, detail) check("Still connected", kitchen.connected) check("close(): disconnected", not kitchen.connected) -ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError) -check("A request once closed: ConnectionLostError", ok, detail) +ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) +check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) + +# --- Connecting: unreachable, rejected --------------------------------------- +nowhere = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, kitchen.node, "127.0.0.1", 1, dll_path) +ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED) +check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail) +stranger = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, "nobody", kitchen.host, kitchen.port, dll_path) +ok, detail = raises(stranger.connect, AuthError, code=ErrorCode.AUTH_REJECTED) +check("A node the server doesn't give this key: AuthError, AUTH_REJECTED", ok, detail) with lounge: page = lounge.get_messages("logs", "kitchen", after=245, limit=3) check("Another identity once the first closed: reads logs", [m.id for m in page] == [246, 247, 248] and page.more, f"{[m.id for m in page]}, more={page.more}") - ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'") - check("A topic not in its ReadTopics: RefusedError", ok, detail) - ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query") - check("Not allowed to query: RefusedError", ok, detail) + ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'", ErrorCode.NOT_ALLOWED) + check("A topic not in its ReadTopics: RefusedError, NOT_ALLOWED", ok, detail) + ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query", ErrorCode.NOT_ALLOWED) + check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail) print() print("All checks passed" if fails == 0 else f"{fails} check(s) failed") diff --git a/Interactors/Python/example.py b/Interactors/Python/example.py index 89cbb9d..aa02751 100644 --- a/Interactors/Python/example.py +++ b/Interactors/Python/example.py @@ -4,7 +4,7 @@ Usage: python example.py [--from-start] Run it from Build\\ (Build.ps1) while BakaShrot_Server.exe runs, e.g.: python ..\\Interactors\\Python\\example.py client.ini logs local and push from another terminal: - .\\PushMessage.exe @msg.json client.ini + .\\BakaShrotPushMessage.exe @msg.json client.ini Ctrl+C to stop. """ @@ -27,7 +27,7 @@ dll = os.environ.get("BAKASHROT_DLL") or os.path.join(os.path.dirname(os.path.ab try: with Client.from_ini(ini, dll) as client: - print(f"Connected to {client.host}:{client.port} as {client.topic}:{client.node}, following {topic}:{node}") + print(f"Connected to {client.host}:{client.port} as node {client.node}, following {topic}:{node}") for message in client.follow(topic, node, after=after): # Parsing is the app's business: the server stores anything. try: diff --git a/Notes.md b/Notes.md index a271196..e18f57c 100644 --- a/Notes.md +++ b/Notes.md @@ -1,8 +1,8 @@ # BakaShrot - working notes -Where things stand and what's next, as of 2026-11-08. A new session: read -`CLAUDE.md` first (how to build, test, and the traps), then "Open items" -below. The detailed docs are in `Design/`: +Where things stand and what's next, as of 2026-11-09. A new session: read +`CLAUDE.md` first (how to build, test, and the traps), then "Right now" and +"Open items" below. The detailed docs are in `Design/`: | Doc | About | |---|---| @@ -14,6 +14,21 @@ below. The detailed docs are in `Design/`: | `Design/Suggestions.md` | Improvements not done yet: pipelined pushes, faster replication, smaller ones. | | `Design/Release.md` | The release smoke test, what's missing for 1.0.0, the (fixed) silent query failure, notes for CI/CD. | +## Right now (2026-11-09) + +- **Nothing since `df61ef9` is committed**, on `timestamps-retention`: the + tool renames, protocols 5 and 6 (node identities, error codes), names-only + configs, `Synchronous`, schema v8 (`browse`), `Examples/`, + `Restart-Test.ps1`. Every suite passes on it (8, see `CLAUDE.md`), it + compiles with 5.73 and 6.40, the push bench gives ~17,000 msg/s for 4 + servers with `Synchronous = FULL`. +- **`Release\20261109-df61ef9-dirty\` is out of date** (before + `Synchronous`, `browse` and the error codes): commit, then + `Release.ps1` again. +- **Suggested next** (not decided by the owner): the server without a + console (item 1), then whatever the real-world test shows. The run on a + clean Windows is the owner's, not an item here. + ## Where things stand - **Build:** `powershell -ExecutionPolicy Bypass -File Build.ps1` @@ -27,7 +42,18 @@ below. The detailed docs are in `Design/`: - Every connection is encrypted, and both ends prove who they are: the client with an Ed25519 challenge, the server by signing the handshake with the key its clients know (since protocol 3, `Design/Cryptography.md`; - the protocol is at 4, with attachments). + the protocol is at 6: attachments in 4, node-only identities in 5, + refusal codes in 6). + - A client authenticates as a node (`[BakaShrot.Client.] Node`, + one per section, a key may be in several); its pushes go to that + section's `DefaultTopic` unless they name one. + - Topics are listed by name (`[BakaShrot.Topics]`), the server gives the + ids and keeps them; nodes come from the sections that use them, + `[BakaShrot.Nodes]` is optional, peers' nodes are taken as they come + (`AcceptNodes = *` by default). + - `[BakaShrot.Server] Synchronous = FULL` (default, every acknowledged + push on disk) or `NORMAL` (faster, a power loss can lose the last + second). - Clients can push messages (usually JSON, anything is stored, flagged in `is_json`), read the latest one of a topic/node pair or a run of them after an id, resolve names, and run raw read-only SQL, each depending on @@ -43,11 +69,20 @@ below. The detailed docs are in `Design/`: (`Design/Attachments.md`). - One thread per client and per peer, each with its own SQLite connection. - The root thread can stop every worker (restart, vacuum). +- **Errors:** every refusal carries a code, every client failure too + (`Client/BakaShrot_ErrorCodes.pbi`): `BakaShrot_GetLastError()` in the + DLL, `error.code` in Python, the name in the tools' messages. Nothing + reconnects by itself; delivery is at least once. +- **Database tools:** the `messages` view (by names), and `browse` / + `browse_messages` to pick a topic from a dropdown in SQLiteStudio. +- **Example:** `Examples/SingleServer/`, a server and a client with scripts + (its keys committed on purpose, public). - **Client:** a DLL with A/W string exports, PureBasic prototypes in `Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`: - `PushMessage` (`-a` to attach a file), `GetLatestMessage`, `GetMessages` - (with `--follow`), `GetAttachment`, `Resolve`, `ListNames`, `Query`, - `KeyGen`. + `BakaShrotPushMessage` (`-a` to attach a file), + `BakaShrotGetLatestMessage`, `BakaShrotGetMessages` (with `--follow`), + `BakaShrotGetAttachment`, `BakaShrotResolveIds`, `BakaShrotList`, + `BakaShrotQuery`, `BakaShrotGenerateKeyPairs`. - **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes, no dependencies, and `example.py`. - **Release:** `Release.ps1` builds with PB 6.40's C backend into @@ -88,8 +123,9 @@ below. The detailed docs are in `Design/`: (`BakaShrot_Names_Ingest()`): highest free id counting down from 65535, origin "peer". So `AcceptNodes = kitchen-*` saves listing every kitchen node on every server. Clients still can't create topics by name. -- **A peer authenticates by name:** its own topic and node must be named the - same on the servers it links to (it sends its name when it has one). +- **A peer authenticates by name:** its own node must be named the same + on the servers it links to (it sends its name when it has one). It sent + a topic too before protocol 5. - **Everywhere a topic or node goes, a name or an id:** config, the Hello, requests, tools, client.ini. Keys: `Topic`, `Node`, `ReplicatingTopics` (`TopicId`, `NodeId`, `ReplicatingTopicIds` still read when the new ones @@ -97,13 +133,13 @@ below. The detailed docs are in `Design/`: - **Filters:** per client `PushTopics` / `ReadTopics` (default: its identities' topics, as before), per peer `SendTopics` / `AcceptTopics` (default: `ReplicatingTopics`). `*` = every topic. A push picks its topic - (`PushMessage -t sensors`), never its node. + (`BakaShrotPushMessage -t sensors`), never its node. - **The config wins at start,** except when it would move a name to another id than the one its messages are under: the server then refuses to start and says which id to use (`Server/Storage/Names.pbi`). - **Seeing the names:** the server's `names` console command, the - `ListNames` tool (`BakaShrot_ListTopics/Nodes()` + `BakaShrot_GetNamesList()` - as JSON, request `ListNames`), `Resolve` for one. + `BakaShrotList` tool (`BakaShrot_ListTopics/Nodes()` + `BakaShrot_GetNamesList()` + as JSON, request `ListNames`), `BakaShrotResolveIds` for one. - **Clients:** `BakaShrot_ResolveTopic/Node()`, `BakaShrot_PushMessageTo()`, `BakaShrot_GetLatestMessageOf()`, the answer's names and ids. Raw queries: `SELECT * FROM messages WHERE topic = 'logs' AND node = @@ -204,8 +240,8 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs. `BakaShrot_HasMoreMessages()`. GetLatestMessage fills the same list (one message). The DLL checks the answer is about what it asked, no more than asked, after the asked id. -- **Tool:** `GetMessages [--after ] [--limit ] - [--follow] [--interval ] [ClientIni]`: one line per message, id, tab, +- **Tool:** `BakaShrotGetMessages [--after ] + [--limit ] [--follow] [--interval ] [ClientIni]`: one line per message, id, tab, data as stored. `--follow` polls every 500 ms once caught up, exits 1 when the connection fails. Polling, not pushed by the server: fine for a few followers, a subscription would be the next step if many follow. @@ -217,8 +253,8 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs. `ConnectionLostError`. Uses the DLL's UTF-8 exports, a lock serializes calls. **One connection per process** (the DLL's globals): a second Client can't connect while one is. ~9,600 pushes/s on one connection, - against ~75/s launching `PushMessage.exe` each time. -- **Released:** `GetMessages.exe` and `python\` (bakashrot.py, example.py), + against ~75/s launching `BakaShrotPushMessage.exe` each time. +- **Released:** `BakaShrotGetMessages.exe` and `python\` (bakashrot.py, example.py), the smoke test reads both messages back with the tool and with Python (if `python` is on the PATH). - **Tested:** `Tests/GetMessages-Test.ps1` (27 checks: limits, after an id / @@ -316,7 +352,7 @@ runner, then CI. to (`ReplicateMessages` carries it). Clients get it in `LatestMessage` and `Messages`: `BakaShrot_GetMessagePushedAt()` in the DLL, `Message.pushed_at` / `.pushed` (a UTC datetime) in Python, - `GetMessages --time`, and `GetLatestMessage` shows it. In SQL: + `BakaShrotGetMessages --time`, and `BakaShrotGetLatestMessage` shows it. In SQL: `data.pushed_at`, and `pushed_at` / `pushed_utc` (text) in the `messages` view. - **Upgrade:** a database from before gets the column, every message @@ -377,7 +413,7 @@ runner, then CI. `_GetMessageAttachmentSize()`, `_IsMessageAttachmentReady()`; Python `push(..., attachment=bytes or path)`, `get_attachment()`, `save_attachment()`, `Message.attachment_size/_ready`; tools - `PushMessage -a`, `GetAttachment`. + `BakaShrotPushMessage -a`, `BakaShrotGetAttachment`. - **Measured:** 512 MB up in 8.5 s, down in 3.9 s, identical, the server peaking at 15 MB of memory. The push benchmark isn't affected (messages without attachments only gain a LEFT JOIN on reads). @@ -395,6 +431,219 @@ runner, then CI. does resume); several parts in flight for high-latency links. See `Design/Attachments.md`. +## Renamed: the tools (2026-11-08) + +Every tool is prefixed with `BakaShrot` (no `_`, the server keeps +`BakaShrot_Server`), folder, source and exe alike, three renamed too: + +| Before | Now | +|---|---| +| KeyGen | BakaShrotGenerateKeyPairs | +| ListNames | BakaShrotList | +| Resolve | BakaShrotResolveIds | +| PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query | BakaShrotPushMessage, BakaShrotGetLatestMessage, ... | + +The packets and DLL functions keep their names (`ListNames`, +`GetMessages`, `BakaShrot_ResolveTopic()`...). Older sections below +still say the old names where they tell what was done then. + +## Done: tools wait for Enter when started from Explorer (2026-11-08) + +- **Every tool** ends through `ToolConsole_End()` (`Tools/Common/ToolConsole.pbi`, + included by `ToolClient.pbi`, and by BakaShrotGenerateKeyPairs directly): started directly + (a double-click, a shortcut), it prints "Press Enter to close..." and + waits, so what it printed (the usage, BakaShrotGenerateKeyPairs' keys) can be read before + its console closes. +- **Started directly** = alone on its console (`GetConsoleProcessList`, as + [PB-Template-Win32-CliApp](https://github.com/aziascreations/PB-Template-Win32-CliApp) + does it) **and** its input and output are a console: a redirected tool + never waits, even alone on a new hidden console (the `--follow` test's + `Start-Process -WindowStyle Hidden -RedirectStandardOutput`). Never + waits outside of Windows. +- **Checked:** from a shell, from Python's `subprocess`, hidden and + redirected: no wait; `Start-Process` in a new window: waits. Every suite + still passes; compiles with 5.73 and 6.40. + +## Done: error codes, protocol 6 (2026-11-09) + +- **Every failure has a code**, in `Client/BakaShrot_ErrorCodes.pbi` + (shipped next to the prototypes, which include it), with what to do about + each in its header: + - 1-99, sent by the server with each refusal (`RequestRefused` got a + `Code`, protocol 5 -> 6): NotAllowed, UnknownName, NotFound, NotReady, + TooBig, NoDefaultTopic, InvalidRequest, DataMismatch, QueryFailed, + ServerError. Each of the server's 64 refusals has one. + - 100+, the client's own: NotConnected, ConnectFailed, AuthRejected, + ServerNotVerified, ConnectionLost, ProtocolError, InvalidArgument, + FileError, AttachmentMismatch, AlreadyConnected, Internal. The + handshake (`Outbound.pbi`) tells where it failed: unreachable, closed + by the server (wrong ServerPublicKey, key or node not allowed, another + version), the server's signature wrong. +- **DLL:** `BakaShrot_GetLastError()` after any call that can fail (0 when + it succeeded); `BakaShrot_ErrorName()` names a code. Set where it + happens (`BakaShrot_Fail()`), the lost connection, refusals and + unexpected answers in one place each. +- **Python:** `ErrorCode` (IntEnum, the same numbers), `error.code` on every + exception; `RefusedError` (1-99), `ConnectionLostError` (not connected, + unreachable, lost, protocol error: connect again), the new `AuthError` + (rejected or unverified: fix the config). `latest()` tells "no message" + by its code, not its text. +- **Tools:** failures print the code's name, "Refused by the server + (UnknownName): Unknown topic 'nope'", "Failed to connect and + authenticate to host:port (AuthRejected): ..."; exit codes unchanged (1). + `BakaShrotGetMessages --after latest` only starts from the start on + NotFound, any other refusal is told. +- **Nothing reconnects by itself**, decided: apps act on the codes. A push + whose answer was lost may be stored twice if retried: at least once, + accepted (11b). +- **Tested:** the Python client's checks (UNKNOWN_NAME, NOT_FOUND, + NOT_ALLOWED, QUERY_FAILED, INVALID_ARGUMENT, FILE_ERROR, + ALREADY_CONNECTED, NOT_CONNECTED, CONNECT_FAILED, AUTH_REJECTED), + `Names-Test.ps1` (the tools' code names), `Restart-Test.ps1` (a killed + server gives the pushers CONNECTION_LOST). + +## Done: restart catch-up tested (2026-11-09) + +- **`Tests/Restart-Test.ps1`** (15 checks, ports 12415-12416, 26 s): two + servers, a client node pushing on each through `Tests/restart_pusher.py` + (as fast as answers come, logging every acknowledged id), servers killed + with `Stop-Process -Force` (TerminateProcess, like a crash): + 1. B killed while both push, A goes on alone for 3 s, B restarted. + 2. B killed again partway through catching up (9,376 -> 10,806 of 22,064 + kitchen messages when killed), restarted. + 3. A killed while both push (the other direction), restarted. +- **All hold:** every acknowledged push survived, ids 1..n without a gap + on both servers, the last acknowledged message is the one pushed, the + next push gets the next id, and both servers end with the same messages + (counts, ids, data and pushed_at sums equal), each catching up on what + the other got meanwhile. The logs show nothing but the links lost and + retried while a server was down. +- **Found:** a push committed but not answered before the kill (#26272 + stored, #26271 the last answered): a client retrying it stores it twice + (open item 11b). +- With `Synchronous = FULL`, the default; a killed process loses nothing + committed with `NORMAL` either (only a power loss or an OS crash would). + +## Done: browsing a topic from a database tool, schema v8 (2026-11-09) + +- **A view can't take a parameter**, and SQLiteStudio has no dropdown for + one. It does show a dropdown for a column with a foreign key (its + `FkComboBox`, in the installed copy), so: +- **`browse`**: one row (`id = 1`), `topic` referencing `topics(name)` and + `node` referencing `nodes(name)` (NULL: every node). Set them from the + dropdowns, commit, open **`browse_messages`**: that topic's messages, + newest first, with `node`, `message_id`, `pushed_utc`, `message_data`, + `is_json`, `attachment_size`. Index searches all the way (by name, then + `(topic_id, pushed_at)`). +- **The server never writes `browse`** nor turns foreign keys on, so the + references never get in its way; a topic renamed in the config only + leaves a stale name there. Made by `SetupStorageDatabase()`, so every + database gets them at its next start (`db_schema_v8.dbml`). +- **Writing to it while the server runs** is a short write next to the + server's (it waits up to its 5 s busy timeout). A database tool left + open on a table holds a read snapshot, which keeps checkpoints from + finishing: the WAL grows until it's closed. +- **Tested:** `Names-Test.ps1` sets it with Python's `sqlite3` (foreign + keys on, like SQLiteStudio): a topic lists its messages, a node narrows + them, a name that isn't a topic is refused. Not tested by hand in + SQLiteStudio itself. + +## Done: Synchronous, FULL by default (2026-11-09) + +- **`[BakaShrot.Server] Synchronous`**: `FULL` (default, every commit + flushed: an acknowledged push survives a power loss) or `NORMAL` + (flushed at checkpoints, about every second: faster, but a power loss + can lose the last second and hand its ids out again). `OFF` and `EXTRA` + are refused, saying why. The server logs it ("ready (synchronous FULL)"). +- **Measured** (`Design/StorageConcurrency.md`): `FULL` halves the push + ceiling here (17,200 msg/s for 4 servers instead of 33,900), a single + sequential client gets ~1/flush pushes/s (1,300/s on this VM's 0.6 ms + flush), and a steady load only gets ~0.7 ms more per push. +- **The bench takes `-Synchronous`** (`FULL` by default, like the server), + `-Synchronous NORMAL` to compare with the numbers from before. +- **Before:** the release smoke test passed on the release built with + protocol 5 and names-only configs, and the example ran from its + extracted zip (2026-11-09). Not done: a run on a clean Windows. +- **Tested:** `Names-Test.ps1` checks the C server starts with `NORMAL` + and logs it, and that `OFF` is refused; every suite passes with the + `FULL` default. + +## Done: the server picks the ids, nodes come from their sections (2026-11-08) + +- **`[BakaShrot.Topics]` is a list of names**, one per line. The server + gives each its id: the one its database already has for the name, else + the lowest free one (`AssignConfigId()`, `Config.pbi`), so the order + doesn't matter and ids never move. `name = id` still pins one: every + existing config works as it is (the tests and `Build.ps1` keep their + pinned ids, they check the translation between servers). +- **`[BakaShrot.Nodes]` is optional:** `[BakaShrot] Node`, every peer's and + client's `Node` name their node by themselves (`DeclareConfigNode()`), + before any node list is read. List only the others to know by name. +- **The root reads the database's names before the config** + (`BakaShrot_Names_ReadKnown()`, `Root.pbi`), from `DatabasePath` read + ahead. `BakaShrot_Names_Load()` then reconciles as before. +- **A peer's `AcceptNodes` defaults to `*`** (was: the named ones only): + other servers' clients come as they come, under ids of this server's + counting down from 65535. `AcceptNodes` still narrows it per peer. +- **Found: the Preferences library misreads LF files** with keys without + `=`: it takes the next line for the value, a section header too, losing + that whole section. The config is now opened through a CRLF copy in the + temporary folder when it has LF line endings (`OpenConfigPreferences()`), + deleted once read. +- **Tested:** `Names-Test.ps1` (55 checks): two servers with names-only + topics and no nodes listed (C's in an LF file), ids in order, the nodes + from the sections, D taking a node it never named, C restarted with its + topics reordered and a new one: same ids. Every suite and the push bench + (35,600 msg/s) pass; compiles with 5.73 and 6.40. The example's + `server.ini` lists names only. + +## Done: protocol 5, a client's node and default topic apart (2026-11-08) + +- **Client sections** (`[BakaShrot.Client.]`): `Node` (required, the + node that key writes as) and `DefaultTopic` (optional, where its pushes + go when they don't name a topic) instead of `Identities = Topic:Node;...`. + `PushTopics` / `ReadTopics` default to `DefaultTopic`, nothing without + one. A key that writes as several nodes is in a section per node. +- **Why the node:** every push is stored under the authenticated node, so + the server decides which node each key writes as. The topic was only + ever the default one, and mixing the two made it look like more. +- **The Hello carries the node only** (protocol 4 -> 5): `client.ini`, + the DLL (`BakaShrot_SetTopic*()` removed), the tools and Python + (`Client(...)` lost its `topic` argument) have no topic any more. A push + without one and no `DefaultTopic` is refused ("No default topic for this + client"). +- **Servers too:** `[BakaShrot] Topic` and peers' `Topic` aren't read any + more (ignored if left), a server links to its peers by node only. +- **Old configs:** `Identities` makes the server refuse to start, saying + what to write (`Node = garage and DefaultTopic = logs instead of + Identities = logs:garage`). +- **Tested:** `Names-Test.ps1` (now 49 checks): no `DefaultTopic` means a + push must name its topic, a key can't write as another section's node + (and the log says why), the old `Identities` refused. Every suite and + the push bench (36,400 msg/s, no failures) pass; compiles with 5.73 and + 6.40. + +## Done: examples, one server and one client (2026-11-08) + +- **`Examples/`**, one folder per setup with its README, indexed in + `Examples/README.md`. The first, `Examples/SingleServer/`: one server on + 127.0.0.1:12360, one client (`logs:demo`, may push to logs and sensors, + read all, query), retention on sensors. +- **Its configs are committed, keys included** (a fixed key pair each, + marked as public and example-only in the files and the README). Every + other config with keys stays out of git. +- **`Start-Server.ps1`** opens the server in its own window and waits until + it listens (`-Here` in the current console, `-Reset` deletes its + database). **`Run-Client.ps1`** pushes (to its topic, another topic, with + an attachment), reads back (latest, every message with `--time`, the + attachment, checked), resolves and lists names, runs a SQL query; it + prints each command, pasteable from the example's folder. Both take + `-BinDir`, `Build\` by default. +- **Git ignores** what they write: `Examples/**/*.sqlite*`, `Examples/**/out/`. +- **Checked:** both scripts, twice in a row (the ids go on), the + double-start guard, the README's Python snippet. `Start-Server.ps1 -Here` + wasn't (it needs an interactive console). + ## Threat model (2026-11-08) BakaShrot is an **internal tool, on trusted machines and a trusted @@ -420,11 +669,12 @@ network**, not exposed to the internet. So: no clean stop from a script (tests force-kill it). Fix: a stop file like `BenchServer.exe`'s, and/or a local admin connection, then a way to run it as a service. (`Design/Release.md` smoke test #4) -2. **The 1.0.0 smoke test isn't done:** a run from the extracted zip on a - clean Windows (the shipped runtime has never been checked there), - replication between two release servers, restart catch-up (designed to - work, never tested: kill a server, check ids continue and peers catch - up). (`Design/Release.md`, items 1-3) +2. **The 1.0.0 smoke test, what's left:** replication between two servers + built by `Release.ps1` (the suites use `BenchServer.exe`, the same server + code). Done: the release's own smoke test and the example from its zip + (2026-11-09), restart catch-up (`Restart-Test.ps1`, 2026-11-09). The run + on a clean Windows is the owner's, as needed: not an open item here. + (`Design/Release.md`, items 1-3) 3. **A corrupted stored attachment is re-sent to peers forever.** Found by `Tests/AttachmentEdges-Test.ps1` part 4 (a byte flipped in the sender's `blob_chunks`, `flip.py`). @@ -447,31 +697,31 @@ network**, not exposed to the internet. So: its own peers for a good copy (`MissingAttachments`), and stops serving it. Log it loudly. If its copy is fine (the damage was in transit), sending again is right. - - Better than matching the refusal's text: a distinct answer for "the - data doesn't match", e.g. a `ChunkStored` with `Complete = 0` and - `Received = 0` after the last part, or a new field. + - The refusal now has its own code (DataMismatch, protocol 6): match + that rather than the text. - The origin (where it was pushed) has no other source: its attachment then stays missing ("isn't here yet"), better than serving bad data; - maybe a "lost" state (4) so `GetAttachment` says so. + maybe a "lost" state (4) so `BakaShrotGetAttachment` says so. - Optional, to catch it on reads too: a SHA-256 per part in `blob_chunks`, checked by `ReadStorageBlobChunk()`, at ~3 s/GB. - Test: part 4 of `AttachmentEdges-Test.ps1` then expects the sender to log its copy as damaged and the re-sends to stop (today it only prints an INFO line with the count); its own `attachments` row goes to 0. -4. **`synchronous = NORMAL`:** the last commits can be lost on a power loss - or OS crash (not on a killed process). Decide, or switch to `FULL`. - (`Design/StorageConcurrency.md`) -5. **Drift between servers** when one topic/node pair is written to on two - servers: only partially resynced. Accepted while each pair has a single - writer; document that as the rule. (`Design/ReplicationIssues.md` #1) +4. ~~**`synchronous = NORMAL`**~~: done, `[BakaShrot.Server] Synchronous`, + `FULL` by default (see "Done: Synchronous" above). +5. ~~**Drift between servers**~~: ruled out by config, a node pushes to + one server (written in `schema.ini` and `Design/ReplicationIssues.md` + #1). Not an open item: nothing to do unless that rule has to go. 6. **Gaps in a pair's ids aren't detected** on replication. (`Design/ReplicationIssues.md` #5) -7. **No single test runner**, and fixed ports (12399, 12401-12414): every +7. **No single test runner**, and fixed ports (12399, 12401-12416): every `Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI. (`Design/Release.md`, "For CI/CD") -8. **Is `DatabaseError()` per thread?** Messages could land in the wrong - thread's log or refusal; Windows queries no longer depend on it. - (`Design/StorageConcurrency.md`) +8. ~~**Is `DatabaseError()` per thread?**~~ Yes, checked (2026-11-09): + two threads failing on their own connections 20,000 times each, never + once the other's message, with 5.73 and 6.40 (`/THREAD`). + `sqlite3_errmsg16()` on the connection gives the same messages, kept as + is. Linux untested (item 18). 9. **Limits:** the sync state must fit in one packet (65536 topic/node pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover. (`Design/ReplicationIssues.md` #7) @@ -479,13 +729,19 @@ network**, not exposed to the internet. So: ### Client side 10. **One connection per process** (the DLL's globals): a handle-based API - for several. No reconnect in `GetMessages --follow` / `follow()`, polling - rather than server-pushed subscriptions. -11. **Breaking with protocols 3 and 4:** every client config needs - `ServerPublicKey`; older clients and servers can't connect (any - version difference refuses the connection). Fine while it's all - built from this repo, worth a line in the release notes of the first - real release. + for several. Polling rather than server-pushed subscriptions. Nothing + reconnects by itself, on purpose: the error codes tell the app when to + (see "Done: error codes" above). +11. ~~**Breaking with protocols 3 to 6**~~: in the release notes now + (`VERSION.txt`, "Compatibility", written by `Release.ps1`): servers and + clients from the same release only, what old configs need. +11b. ~~**A push whose answer was lost can be stored twice if retried.**~~ + Accepted, the way it is: delivery is at least once. A server killed + between committing a push and answering it keeps it (`Restart-Test.ps1` + saw #26272 stored, #26271 the last answered), the client gets + ConnectionLost; pushing it again stores it twice. Documented in + `BakaShrot_ErrorCodes.pbi`, the DLL's header and `bakashrot.py`; a + client that minds checks the latest message before retrying. ### Security, low priority under the threat model @@ -525,6 +781,17 @@ network**, not exposed to the internet. So: server, skipping on arrival what's past its age (2026-11-08). - Attachments, protocol 4: one per message, in 1 MB parts, replicated after their message, resumable; edge cases tested (2026-11-08). +- Tools renamed `BakaShrot`, waiting for Enter when started from + Explorer; `Examples/SingleServer/` (2026-11-08). +- Protocol 5: a client is a node, its default topic the server's + (`Node`, `DefaultTopic`); names-only topics, ids picked by the server, + nodes from their sections, `AcceptNodes = *` (2026-11-08). +- `Synchronous`, `FULL` by default, measured (2026-11-09). +- Schema v8: `browse` / `browse_messages` for database tools (2026-11-09). +- Restart catch-up tested: kills mid-traffic and mid-catch-up, nothing + acknowledged lost (`Restart-Test.ps1`, 2026-11-09). +- Protocol 6: error codes everywhere, at-least-once delivery accepted + (2026-11-09). ## To check against Review.md @@ -556,6 +823,12 @@ network**, not exposed to the internet. So: - **Things only a raw client can do** (a wrong SHA-256, abandoned uploads): `Tests/AttachmentEdgeClient.pb`, over `Commons/Networking/Outbound.pbi`. Copy its `Exchange()` / `Refusal()` helpers for new protocol tests. +- **Log scans in the tests skip "Refused a request" lines:** refusals are + expected, and their codes' names (`InvalidRequest`, `QueryFailed`) hold + the words the scans look for. PowerShell's `-match` ignores case. +- **Traffic while a server is killed:** `Tests/restart_pusher.py` pushes as + fast as answers come and logs every acknowledged id, then the error's + code; `Restart-Test.ps1` shows how to read it back. - **Corrupting or seeding a database** from a test: Python's `sqlite3`, with the server stopped through its stop file (its WAL is checkpointed then), see `Retention-Test.ps1` (an old schema) and diff --git a/Release.ps1 b/Release.ps1 index 688afa0..2880d06 100644 --- a/Release.ps1 +++ b/Release.ps1 @@ -5,9 +5,12 @@ # Release\\, ready to copy to a server or hand to a client: # BakaShrot_Server.exe the server # BakaShrot_Client.dll the client DLL, with -# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes -# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, GetAttachment.exe, -# Query.exe, Resolve.exe, ListNames.exe, KeyGen.exe the tools +# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes, and +# BakaShrot_ErrorCodes.pbi the error codes they include +# BakaShrotPushMessage.exe, BakaShrotGetLatestMessage.exe, +# BakaShrotGetMessages.exe, BakaShrotGetAttachment.exe, BakaShrotQuery.exe, +# BakaShrotResolveIds.exe, BakaShrotList.exe, +# BakaShrotGenerateKeyPairs.exe the tools # libsodium.dll, sqlite3.dll what they need next to them # vcruntime140.dll what libsodium.dll needs (Libs\redist) # python\bakashrot.py, example.py the Python client, over the DLL @@ -15,7 +18,7 @@ # VERSION.txt commit, date, compiler, libraries # and Release\BakaShrot-.zip of it, unless -NoZip. # -# No keys and no configs with keys in it: generate them with KeyGen.exe. +# No keys and no configs with keys in it: generate them with BakaShrotGenerateKeyPairs.exe. # # Then checks the build works, unless -SkipTest: generates keys, runs the # server from the release folder on a spare port with a throwaway database, @@ -110,16 +113,16 @@ $Common = @("/QUIET") if (-not $NoOptimizer) { $Common += "/OPTIMIZER" } $Targets = @( - @("Server\BakaShrot_Server.pb", "BakaShrot_Server.exe", @("/CONSOLE", "/THREAD")), - @("Client\BakaShrot_Client.pbi", "BakaShrot_Client.dll", @("/DLL", "/THREAD")), - @("Tools\PushMessage\PushMessage.pb", "PushMessage.exe", @("/CONSOLE")), - @("Tools\GetLatestMessage\GetLatestMessage.pb", "GetLatestMessage.exe", @("/CONSOLE")), - @("Tools\GetMessages\GetMessages.pb", "GetMessages.exe", @("/CONSOLE")), - @("Tools\GetAttachment\GetAttachment.pb", "GetAttachment.exe", @("/CONSOLE")), - @("Tools\Query\Query.pb", "Query.exe", @("/CONSOLE")), - @("Tools\Resolve\Resolve.pb", "Resolve.exe", @("/CONSOLE")), - @("Tools\ListNames\ListNames.pb", "ListNames.exe", @("/CONSOLE")), - @("Tools\KeyGen\KeyGen.pb", "KeyGen.exe", @("/CONSOLE")) + @("Server\BakaShrot_Server.pb", "BakaShrot_Server.exe", @("/CONSOLE", "/THREAD")), + @("Client\BakaShrot_Client.pbi", "BakaShrot_Client.dll", @("/DLL", "/THREAD")), + @("Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb", "BakaShrotPushMessage.exe", @("/CONSOLE")), + @("Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb", "BakaShrotGetLatestMessage.exe", @("/CONSOLE")), + @("Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb", "BakaShrotGetMessages.exe", @("/CONSOLE")), + @("Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb", "BakaShrotGetAttachment.exe", @("/CONSOLE")), + @("Tools\BakaShrotQuery\BakaShrotQuery.pb", "BakaShrotQuery.exe", @("/CONSOLE")), + @("Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb", "BakaShrotResolveIds.exe", @("/CONSOLE")), + @("Tools\BakaShrotList\BakaShrotList.pb", "BakaShrotList.exe", @("/CONSOLE")), + @("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE")) ) Push-Location $Root @@ -142,6 +145,7 @@ Copy-Item $Sodium $OutDir foreach ($File in $Redist) { Copy-Item $File.FullName $OutDir } Copy-Item $SqliteDll (Join-Path $OutDir "sqlite3.dll") Copy-Item (Join-Path $Root "Client\BakaShrot_Client_Prototypes.pbi") $OutDir +Copy-Item (Join-Path $Root "Client\BakaShrot_ErrorCodes.pbi") $OutDir New-Item -ItemType Directory -Force (Join-Path $OutDir "python") | Out-Null foreach ($File in @("bakashrot.py", "example.py")) { Copy-Item (Join-Path $Root "Interactors\Python\$File") (Join-Path $OutDir "python") @@ -160,8 +164,8 @@ VC++ runtime: $RedistVersion (vcruntime140.dll, for libsodium.dll) Needs Windows 10 or later, 64-bit. Keep the DLLs next to the exes. Run the server: BakaShrot_Server.exe config.ini - Its config: config.example.ini. Keys: KeyGen.exe, the private key goes in - [BakaShrot] PrivateKey, the public key in the configs that trust it, and + Its config: config.example.ini. Keys: BakaShrotGenerateKeyPairs.exe, the + private key goes in [BakaShrot] PrivateKey, the public key in the configs that trust it, and in its clients' client.ini as ServerPublicKey (it logs it when it starts). Every connection is encrypted, and only reaches the server holding the private key of the ServerPublicKey (or peer PublicKey) it was given. @@ -169,19 +173,40 @@ Run the server: BakaShrot_Server.exe config.ini needs one: it stops right away without console input. Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id, each server has its own ids for the same names. + [BakaShrot.Server] Synchronous = FULL (default) flushes every push to disk + before answering it; NORMAL is faster but a power loss can lose the last + second of messages. See config.example.ini. Tools, next to BakaShrot_Client.dll, with a client.ini: - PushMessage [-t ] [-a ] [ClientIni] - GetLatestMessage [ClientIni] - GetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni] - GetAttachment [ClientIni] - Resolve [ClientIni] - ListNames [topics|nodes|all] [ClientIni] [--json] - Query [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs' - client.ini: [BakaShrot] PrivateKey, PublicKey, Topic, Node (names or - ids), ServerHost, ServerPort, ServerPublicKey. + BakaShrotPushMessage [-t ] [-a ] [ClientIni] + BakaShrotGetLatestMessage [ClientIni] + BakaShrotGetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni] + BakaShrotGetAttachment [ClientIni] + BakaShrotResolveIds [ClientIni] + BakaShrotList [topics|nodes|all] [ClientIni] [--json] + BakaShrotQuery [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs' + client.ini: [BakaShrot] PrivateKey, PublicKey, Node (the node it writes + as, a name or an id), ServerHost, ServerPort, ServerPublicKey. Where its + pushes go by default is the server's DefaultTopic for it. Python (3.8+, 64-bit): python\bakashrot.py, no dependencies, uses BakaShrot_Client.dll (set BAKASHROT_DLL, or pass dll_path). See its docstring, and python\example.py . +Compatibility: protocol 6. Servers and clients (the DLL, the tools, the + Python client) must come from the same release: any other version + refuses the connection, there's no mixing. From an older release: + - server configs: [BakaShrot.Client.] Identities = topic:node is + refused at start, write Node = node and DefaultTopic = topic (the + server's message says which); [BakaShrot] and peer sections' Topic is + ignored; [BakaShrot.Topics] can be names alone, [BakaShrot.Nodes] can + go; Synchronous = FULL is the default now (NORMAL was); + - client.ini: Topic is ignored, ServerPublicKey is required; + - apps: BakaShrot_ErrorCodes.pbi next to the prototypes, SetTopic() is + gone, and a database made before is upgraded in place at the first + start (keep a copy). +Errors: every failure has a code, BakaShrot_GetLastError() in the DLL, + error.code in Python (bakashrot.ErrorCode), the name in the tools' + messages. BakaShrot_ErrorCodes.pbi lists them, and what to do about each. + Nothing reconnects by itself. A push whose answer was lost may have been + stored: pushed again, it's stored twice (at least once delivery). "@ Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encoding UTF8 @@ -189,8 +214,8 @@ Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encodin # --- Test ------------------------------------------------------------------- function New-KeyPair { - $Lines = & (Join-Path $OutDir "KeyGen.exe") - if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" } + $Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe") + if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" } return @{ PrivateKey = $Lines[0] -replace "^PrivateKey = ", "" PublicKey = $Lines[1] -replace "^PublicKey = ", "" @@ -229,7 +254,6 @@ if (-not $SkipTest) { Set-Content -Path (Join-Path $TestDir "server.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($ServerKeys.PrivateKey) -Topic = releasetest Node = server [BakaShrot.Topics] @@ -247,7 +271,8 @@ DatabasePath = $(Join-Path $TestDir "test.sqlite") [BakaShrot.Client.test] PublicKeys = $($ClientKeys.PublicKey) -Identities = releasetest:tester +Node = tester +DefaultTopic = releasetest AllowRead = 1 AllowWrite = 1 AllowQuery = 1 @@ -256,7 +281,6 @@ AllowQuery = 1 [BakaShrot] PrivateKey = $($ClientKeys.PrivateKey) PublicKey = $($ClientKeys.PublicKey) -Topic = releasetest Node = tester ServerHost = 127.0.0.1 ServerPort = $TestPort @@ -276,26 +300,26 @@ ServerPublicKey = $($ServerKeys.PublicKey) } $ClientIni = Join-Path $TestDir "client.ini" - $Pushed = Invoke-Tool "PushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) + $Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) if ($Pushed -notmatch "message #1") { throw "Unexpected push answer: $Pushed" } - $Latest = Invoke-Tool "GetLatestMessage.exe" @("releasetest", "tester", $ClientIni) + $Latest = Invoke-Tool "BakaShrotGetLatestMessage.exe" @("releasetest", "tester", $ClientIni) if ($Latest -notmatch '"release"\s*:\s*"test"' -or $Latest -notmatch '\(ids 7:2\)') { throw "Unexpected latest message: $Latest" } - $Pushed = Invoke-Tool "PushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) + $Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni) if ($Pushed -notmatch "message #2") { throw "Unexpected second push answer: $Pushed" } # message.json ends with a line break, kept in the data: one empty line after each. - $Messages = @(& (Join-Path $OutDir "GetMessages.exe") "releasetest" "tester" $ClientIni | Where-Object { $_ -ne "" }) + $Messages = @(& (Join-Path $OutDir "BakaShrotGetMessages.exe") "releasetest" "tester" $ClientIni | Where-Object { $_ -ne "" }) if ($LASTEXITCODE -ne 0 -or $Messages.Count -ne 2 -or $Messages[0] -notmatch '^1\t\{"release"' -or $Messages[1] -notmatch '^2\t') { throw "Unexpected messages: $($Messages -join ' | ')" } - $Resolved = Invoke-Tool "Resolve.exe" @("topic", "releasetest", $ClientIni) + $Resolved = Invoke-Tool "BakaShrotResolveIds.exe" @("topic", "releasetest", $ClientIni) if ($Resolved -notmatch "topic releasetest = 7") { throw "Unexpected resolved topic: $Resolved" } $Sql = Join-Path $TestDir "query.sql" Set-Content -Path $Sql -Encoding Ascii -Value "SELECT message_data ->> '$.value', is_json, topic_id FROM messages WHERE topic = 'releasetest' AND node = 'tester' AND is_json = 1" - $Queried = Invoke-Tool "Query.exe" @("@$Sql", $ClientIni) + $Queried = Invoke-Tool "BakaShrotQuery.exe" @("@$Sql", $ClientIni) if ($Queried -notmatch '\[\["42","1","7"\],\["42","1","7"\]\]') { throw "Unexpected query result: $Queried" } Write-Host " Pushed, read back by name, resolved and queried messages: OK" @@ -318,11 +342,11 @@ ServerPublicKey = $($ServerKeys.PublicKey) $Bytes = New-Object byte[] (3 * 1024 * 1024 + 17) (New-Object System.Random 5).NextBytes($Bytes) [IO.File]::WriteAllBytes($Attach, $Bytes) - $Pushed = Invoke-Tool "PushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni) + $Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni) if ($Pushed -notmatch "message #(\d+), with an attachment of 3145745 bytes") { throw "Unexpected push with an attachment: $Pushed" } $AttachedId = $Matches[1] $Copy = Join-Path $TestDir "attach-copy.bin" - $Saved = Invoke-Tool "GetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni) + $Saved = Invoke-Tool "BakaShrotGetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni) if ($Saved -notmatch "Saved 3145745 bytes" -or (Get-FileHash $Attach).Hash -ne (Get-FileHash $Copy).Hash) { throw "Unexpected attachment read back: $Saved" } Write-Host " Pushed and read back an attachment: OK" } diff --git a/Server/Config/Config.pbi b/Server/Config/Config.pbi index 785bd1d..e5a63a3 100644 --- a/Server/Config/Config.pbi +++ b/Server/Config/Config.pbi @@ -7,8 +7,11 @@ ; Section layout: ; [BakaShrot] -> BakaShrot_CoreConfig ; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server -; [BakaShrot.Topics] -> topic names, "name = id" lines -; [BakaShrot.Nodes] -> node names, "name = id" lines +; [BakaShrot.Topics] -> topic names, one per line, this server +; gives them their ids ("name = id" pins one) +; [BakaShrot.Nodes] -> node names, the same, optional: the nodes of +; [BakaShrot], the peers and the clients are +; named by their sections ; [BakaShrot.Retention] -> how long each topic's messages are kept ; here, "topic = max age" lines, see ; BakaShrot_RetentionRule @@ -44,7 +47,7 @@ Structure BakaShrot_NameSet ; Every one, named or not, known or not ("*"). All.i - ; Every one that has a name on this server: the default of AcceptNodes. + ; Every one that has a name on this server. Known.i ; Str(Id) -> #True, from ids, ranges and names in the list. @@ -61,7 +64,7 @@ EndStructure ; The peer must register this server in one of its [BakaShrot.Client.]. ; PublicKey is the peer's: a link to it only goes through if the peer ; proves it holds the matching private key (Commons/Networking/Connections.pbi). -; Topic and Node are only checked when the peer links to here. +; Node is only checked when the peer links to here. Structure BakaShrot_PeerConfig ; Remote address of the peer @@ -72,9 +75,8 @@ Structure BakaShrot_PeerConfig ; 0-65535 Port.u - ; Topic, Node: the remote node's topic and node, refs, resolved to this - ; server's ids. The peer authenticates with them when it links to here. - TopicId.u + ; Node: the remote server's node, a ref resolved to this server's id. + ; The peer authenticates as it when it links to here. NodeId.u ; This peer's Ed25519 public key (Base64): the Hello of a link to it is @@ -90,7 +92,8 @@ Structure BakaShrot_PeerConfig ; SendNodes: the nodes whose messages this server sends to the peer. ; Default: every one (*). AcceptNodes: the nodes whose messages it takes - ; from the peer. Default: every one named here, no other. + ; from the peer. Default: every one (*), the ones it doesn't name yet + ; are added as they come (Server/Storage/Names.pbi). SendNodes.BakaShrot_NameSet AcceptNodes.BakaShrot_NameSet @@ -99,19 +102,11 @@ Structure BakaShrot_PeerConfig AcceptTopicsText.s SendNodesText.s AcceptNodesText.s - TopicText.s NodeText.s EndStructure -; One "Topic:Node" entry of BakaShrot_ClientConfig\Identities(). -Structure BakaShrot_ClientIdentity - TopicId.u - NodeId.u -EndStructure - - ; What a client is allowed to do once authenticated. ; Ini keys of [BakaShrot.Client.], 1 to allow, 0 to deny. Structure BakaShrot_ClientPermissions @@ -140,22 +135,27 @@ Structure BakaShrot_ClientConfig ; Format: Key;Key;... List PublicKeys.s() - ; Topic and node pairs the client is allowed to authenticate as, once it - ; has authenticated with one of its PublicKeys. - ; Format: Topic:Node;Topic:Node;... each a name or an id. - List Identities.BakaShrot_ClientIdentity() + ; Node: the node it writes as, a ref, required. It sends it in its + ; Hello, which must come with one of PublicKeys. A key listed in several + ; sections may write as each of their nodes. + NodeId.u + + ; DefaultTopic: the topic of its pushes that don't name one, a ref, -1 + ; without one (they're refused then). + DefaultTopicId.l ; AllowRead, AllowWrite, AllowQuery Permissions.BakaShrot_ClientPermissions ; PushTopics: the topics it may push to, under its own node. ; ReadTopics: the topics it may read the latest messages of. - ; Both default to the topics of its Identities. + ; Both default to its DefaultTopic, nothing without one. PushTopics.BakaShrot_NameSet ReadTopics.BakaShrot_NameSet ; As written in the ini, for SaveConfig(). Chr(1) when missing. - IdentitiesText.s + NodeText.s + DefaultTopicText.s PushTopicsText.s ReadTopicsText.s @@ -240,6 +240,10 @@ Structure BakaShrot_ServerConfig ; that it's deleted. Default 3600. UploadTimeout.i + ; PRAGMA synchronous, FULL (default) or NORMAL, see + ; BakaShrot_Storage_Synchronous in Server/Storage/Storage.pbi. + Synchronous.s + EndStructure @@ -252,18 +256,17 @@ Structure BakaShrot_CoreConfig ; own config. See Commons/Cryptography/Libsodium.pbi. PrivateKey.s - ; Topic, Node: the topic and node this server authenticates as when it - ; links to its peers, refs. Peers must know them by the same names. - TopicId.u + ; Node: the node this server authenticates as when it links to its + ; peers, a ref. Peers must know it by the same name. NodeId.u - TopicText.s NodeText.s ; [BakaShrot.Server] Server.BakaShrot_ServerConfig - ; [BakaShrot.Topics] and [BakaShrot.Nodes]: - ; LCase(name) -> id, and Str(id) -> name as written. + ; [BakaShrot.Topics] and [BakaShrot.Nodes], plus the nodes the other + ; sections define: LCase(name) -> id, and Str(id) -> name as written. + ; Ids pinned in the config, or given by LoadConfig() (AssignConfigId()). Map TopicIds.i() Map TopicNames.s() Map NodeIds.i() @@ -297,18 +300,34 @@ Macro Ptr_BakaShrot_CoreConfig : i : EndMacro #BakaShrot_Config_DefaultRetentionInterval = 60 #BakaShrot_Config_DefaultMaxAttachmentSize = "1G" #BakaShrot_Config_DefaultUploadTimeout = 3600 +#BakaShrot_Config_DefaultSynchronous = "FULL" ; What ReadPreferenceString() returns for a missing key, to tell it from an ; empty one: an empty PushTopics allows nothing, a missing one the default. #BakaShrot_Config_Missing = Chr(1) +; What the database already has (BakaShrot_Names_ReadKnown(), Storage/ +; Names.pbi), for LoadConfig() to give a name listed without an id the id +; it already has: LCase(name) -> id, and Str(id) -> #True for every id it +; has a row or messages for, named or not. +Structure BakaShrot_KnownNames + Map TopicIds.i() + Map TopicUsed.i() + Map NodeIds.i() + Map NodeUsed.i() +EndStructure + +; The one LoadConfig() was given, while it runs. +Global *BakaShrot_ConfigKnown.BakaShrot_KnownNames + + ; Why the last LoadConfig() failed. Global BakaShrot_ConfigError.s = "" -; Reads Key, or OldKey if Key is missing: Topic, Node and ReplicatingTopics -; were TopicId, NodeId and ReplicatingTopicIds before they took names, and +; Reads Key, or OldKey if Key is missing: Node and ReplicatingTopics were +; NodeId and ReplicatingTopicIds before they took names, and ; configs written then still work. Procedure.s ReadConfigKey(Key.s, OldKey.s, DefaultValue.s) Protected Value.s = ReadPreferenceString(Key, #BakaShrot_Config_Missing) @@ -389,6 +408,50 @@ Procedure.i ResolveConfigNode(*Config.BakaShrot_CoreConfig, Ref.s) EndProcedure +; Gives Name an id in Ids() / Names(): the one the database already has for +; it (KnownIds()), unless another of the config's names has it, else the +; lowest free one, used neither by the config nor by the database +; (KnownUsed()). Names a peer adds get theirs counting down from 65535. +; Returns the id, -1 if none is left. +Procedure.i AssignConfigId(Name.s, Map Ids.i(), Map Names.s(), Map KnownIds.i(), Map KnownUsed.i()) + Protected Id.i = -1 + + If FindMapElement(KnownIds(), LCase(Name)) + Id = KnownIds() + If FindMapElement(Names(), Str(Id)) + Id = -1 + EndIf + EndIf + If Id < 0 + For Id = 1 To #BakaShrot_MaxId + If Not FindMapElement(Names(), Str(Id)) And Not FindMapElement(KnownUsed(), Str(Id)) + Break + EndIf + Next + If Id > #BakaShrot_MaxId + ProcedureReturn -1 + EndIf + EndIf + + Ids(LCase(Name)) = Id + Names(Str(Id)) = Name + ProcedureReturn Id +EndProcedure + +; A node ref that defines a node: [BakaShrot] Node, a peer's or a client's. +; Resolved like ResolveConfigNode(), and a name [BakaShrot.Nodes] doesn't +; list is named all the same, its id given like one listed without an id. +; -1 if it's neither an id nor a valid name. +Procedure.i DeclareConfigNode(*Config.BakaShrot_CoreConfig, Ref.s) + Protected Id.i = ResolveConfigNode(*Config, Ref) + + If Id >= 0 Or Not BakaShrot_IsValidName(Ref) + ProcedureReturn Id + EndIf + ProcedureReturn AssignConfigId(Ref, *Config\NodeIds(), *Config\NodeNames(), *BakaShrot_ConfigKnown\NodeIds(), *BakaShrot_ConfigKnown\NodeUsed()) +EndProcedure + + ; An age as [BakaShrot.Retention] writes it ("30d", "1d12h", "forever") in ; milliseconds, 0 for forever, -1 if it isn't one. Procedure.q ParseRetentionAge(Text.s) @@ -560,41 +623,57 @@ Procedure.q RetentionMaxAgeMs(List Rules.BakaShrot_RetentionRule(), TopicId.i, N EndProcedure -; Reads a "name = id" section into Ids() (LCase(name) -> id) and Names() -; (Str(id) -> name). Kind is "topic" or "node", for the errors. +; Reads a names section into Ids() (LCase(name) -> id) and Names() (Str(id) +; -> name). A line is a name, its id given by AssignConfigId() once the +; pinned ones are known (the database's for it, else a free one), or +; "name = id" to pin it. Kind is "topic" or "node", for the errors. +; The file must be open with OpenConfigPreferences(), see why there. ; Returns #False on an invalid name or id, or one given twice. -Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s()) +Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s(), Map KnownIds.i(), Map KnownUsed.i()) Protected Name.s, Value.s, Id.i + Protected NewList Unpinned.s() - If Not PreferenceGroup(Section) + If Not PreferenceGroup(Section) Or Not ExaminePreferenceKeys() ProcedureReturn #True EndIf - If ExaminePreferenceKeys() - While NextPreferenceKey() - Name = Trim(PreferenceKeyName()) - Value = Trim(PreferenceKeyValue()) - If Not BakaShrot_IsValidName(Name) - BakaShrot_ConfigError = "[" + Section + "] '" + Name + "' isn't a valid " + Kind + " name: 1-" + Str(#BakaShrot_MaxNameLength) + " of A-Z a-z 0-9 _ . -, not only digits" - ProcedureReturn #False - EndIf - Id = BakaShrot_RefToId(Value) - If Id < 0 - BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId) - ProcedureReturn #False - EndIf - If FindMapElement(Ids(), LCase(Name)) - BakaShrot_ConfigError = "[" + Section + "] " + Kind + " '" + Name + "' is given twice" - ProcedureReturn #False - EndIf - If FindMapElement(Names(), Str(Id)) - BakaShrot_ConfigError = "[" + Section + "] " + Kind + " id " + Str(Id) + " is given to both '" + Names() + "' and '" + Name + "'" - ProcedureReturn #False - EndIf - Ids(LCase(Name)) = Id - Names(Str(Id)) = Name - Wend - EndIf + While NextPreferenceKey() + Name = Trim(PreferenceKeyName()) + Value = Trim(PreferenceKeyValue()) + If Not BakaShrot_IsValidName(Name) + BakaShrot_ConfigError = "[" + Section + "] '" + Name + "' isn't a valid " + Kind + " name: 1-" + Str(#BakaShrot_MaxNameLength) + " of A-Z a-z 0-9 _ . -, not only digits" + ProcedureReturn #False + EndIf + If FindMapElement(Ids(), LCase(Name)) + BakaShrot_ConfigError = "[" + Section + "] " + Kind + " '" + Name + "' is given twice" + ProcedureReturn #False + EndIf + If Value = "" + ; Its id once every pinned one is known, -1 until then. + Ids(LCase(Name)) = -1 + AddElement(Unpinned()) : Unpinned() = Name + Continue + EndIf + Id = BakaShrot_RefToId(Value) + If Id < 0 + BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId) + " (or leave it out, the server gives it one)" + ProcedureReturn #False + EndIf + If FindMapElement(Names(), Str(Id)) + BakaShrot_ConfigError = "[" + Section + "] " + Kind + " id " + Str(Id) + " is given to both '" + Names() + "' and '" + Name + "'" + ProcedureReturn #False + EndIf + Ids(LCase(Name)) = Id + Names(Str(Id)) = Name + Wend + + ForEach Unpinned() + DeleteMapElement(Ids(), LCase(Unpinned())) + If AssignConfigId(Unpinned(), Ids(), Names(), KnownIds(), KnownUsed()) < 0 + BakaShrot_ConfigError = "[" + Section + "] no " + Kind + " id left for '" + Unpinned() + "'" + ProcedureReturn #False + EndIf + Next ProcedureReturn #True EndProcedure @@ -717,79 +796,68 @@ Procedure.s FormatPublicKeyList(List Keys.s()) EndProcedure -; Parses a "Topic:Node;Topic:Node;..." list into a list of identities. -; Returns #False if an entry isn't exactly "Topic:Node" with known refs, -; since silently turning a typo into a 0:0 identity would grant an identity -; nobody asked for. -Procedure.i ParseIdentityList(*Config.BakaShrot_CoreConfig, IdentitiesString.s, List Identities.BakaShrot_ClientIdentity(), Where.s) - Protected i, Part.s, TopicPart.s, NodePart.s, TopicId.i, NodeId.i +; Reads a client section's Node and DefaultTopic into *Client, in the +; current preference group. Where: "[BakaShrot.Client.]". +; Returns #False with BakaShrot_ConfigError set: Node missing or unknown, +; DefaultTopic unknown, or the old Identities still there. That one is +; refused rather than guessed at: a "Topic:Node" list could grant several +; nodes, and the topic was only ever the default one. +Procedure.i ParseClientIdentity(*Config.BakaShrot_CoreConfig, *Client.BakaShrot_ClientConfig, Where.s) + Protected Old.s, Pair.s, Id.i - ClearList(Identities()) - - For i = 1 To CountString(IdentitiesString, ";") + 1 - Part = Trim(StringField(IdentitiesString, i, ";")) - If Part = "" - Continue + Old = Trim(ReadPreferenceString("Identities", #BakaShrot_Config_Missing)) + If Old <> #BakaShrot_Config_Missing + Pair = Trim(StringField(Old, 1, ";")) + If CountString(Old, ";") = 0 And CountString(Pair, ":") = 1 + BakaShrot_ConfigError = Where + " Identities isn't used any more (protocol 5): write Node = " + Trim(StringField(Pair, 2, ":")) + + " and DefaultTopic = " + Trim(StringField(Pair, 1, ":")) + " instead of Identities = " + Old + Else + BakaShrot_ConfigError = Where + " Identities isn't used any more (protocol 5): write the node it writes as in Node, and the topic of its pushes that don't name one in DefaultTopic, one section per node (a key may be in several)" EndIf + ProcedureReturn #False + EndIf - If CountString(Part, ":") <> 1 - BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node" + *Client\NodeText = Trim(ReadPreferenceString("Node", "")) + If *Client\NodeText = "" + BakaShrot_ConfigError = Where + " Node is missing: the node this client writes as, a name or an id" + ProcedureReturn #False + EndIf + Id = DeclareConfigNode(*Config, *Client\NodeText) + If Id < 0 + BakaShrot_ConfigError = Where + " Node: '" + *Client\NodeText + "' isn't a node name or an id" + ProcedureReturn #False + EndIf + *Client\NodeId = Id + *Config\UsedNodeIds(Str(Id)) = #True + + *Client\DefaultTopicId = -1 + *Client\DefaultTopicText = ReadPreferenceString("DefaultTopic", #BakaShrot_Config_Missing) + If *Client\DefaultTopicText <> #BakaShrot_Config_Missing And Trim(*Client\DefaultTopicText) <> "" + *Client\DefaultTopicText = Trim(*Client\DefaultTopicText) + Id = ResolveConfigTopic(*Config, *Client\DefaultTopicText) + If Id < 0 + BakaShrot_ConfigError = Where + " DefaultTopic: unknown topic '" + *Client\DefaultTopicText + "', not an id nor in [BakaShrot.Topics]" ProcedureReturn #False EndIf - - TopicPart = Trim(StringField(Part, 1, ":")) - NodePart = Trim(StringField(Part, 2, ":")) - If TopicPart = "" Or NodePart = "" - BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node" - ProcedureReturn #False - EndIf - TopicId = ResolveConfigTopic(*Config, TopicPart) - NodeId = ResolveConfigNode(*Config, NodePart) - If TopicId < 0 - BakaShrot_ConfigError = Where + ": unknown topic '" + TopicPart + "', not an id nor in [BakaShrot.Topics]" - ProcedureReturn #False - EndIf - If NodeId < 0 - BakaShrot_ConfigError = Where + ": unknown node '" + NodePart + "', not an id nor in [BakaShrot.Nodes]" - ProcedureReturn #False - EndIf - - AddElement(Identities()) - Identities()\TopicId = TopicId - Identities()\NodeId = NodeId - *Config\UsedTopicIds(Str(TopicId)) = #True - *Config\UsedNodeIds(Str(NodeId)) = #True - Next + *Client\DefaultTopicId = Id + *Config\UsedTopicIds(Str(Id)) = #True + EndIf ProcedureReturn #True EndProcedure -; Returns the name of the [BakaShrot.Client.] section allowing both -; PublicKey and the TopicId:NodeId identity, or "" if none does. +; Returns the name of the [BakaShrot.Client.] section with this Node +; and PublicKey in its PublicKeys, or "" if none has. ; Not thread-safe, it moves *Config\Clients()' current element. -Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i) - Protected KeyAllowed.i, IdentityAllowed.i - +Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, NodeId.i) ForEach *Config\Clients() - KeyAllowed = #False - ForEach *Config\Clients()\PublicKeys() - If *Config\Clients()\PublicKeys() = PublicKey - KeyAllowed = #True - Break - EndIf - Next - - IdentityAllowed = #False - ForEach *Config\Clients()\Identities() - If *Config\Clients()\Identities()\TopicId = TopicId And *Config\Clients()\Identities()\NodeId = NodeId - IdentityAllowed = #True - Break - EndIf - Next - - If KeyAllowed And IdentityAllowed - ProcedureReturn MapKey(*Config\Clients()) + If *Config\Clients()\NodeId = NodeId + ForEach *Config\Clients()\PublicKeys() + If *Config\Clients()\PublicKeys() = PublicKey + ProcedureReturn MapKey(*Config\Clients()) + EndIf + Next EndIf Next @@ -798,11 +866,11 @@ EndProcedure ; Returns the name of the [BakaShrot.Peer.] section with exactly this -; public key and TopicId:NodeId identity, or "" if none has. +; public key and node, or "" if none has. ; Not thread-safe, it moves *Config\Peers()' current element. -Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i) +Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, NodeId.i) ForEach *Config\Peers() - If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\TopicId = TopicId And *Config\Peers()\NodeId = NodeId + If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\NodeId = NodeId ProcedureReturn MapKey(*Config\Peers()) EndIf Next @@ -816,32 +884,167 @@ Procedure FreeConfig(*Config.BakaShrot_CoreConfig) EndProcedure +; Where OpenConfigPreferences() put its copy, "" when it opened the file. +Global BakaShrot_ConfigCopyPath.s + +; OpenPreferences(IniFilePath), through a copy with CRLF line endings when +; the file has LF ones: there, the Preferences library takes the line after +; a key without "=" for its value, a section header too ("logs" then +; "[BakaShrot.Server]" loses that whole section), and names are listed +; without "=". The copy goes in the temporary folder, CloseConfigPreferences() +; deletes it. Returns OpenPreferences()' result. +Procedure.i OpenConfigPreferences(IniFilePath.s) + Protected FileId.i, Format.i, HadBom.i, Size.q, *Data, Text.s, Copy.s, Opened.i + + BakaShrot_ConfigCopyPath = "" + FileId = ReadFile(#PB_Any, IniFilePath) + If Not FileId + ProcedureReturn #False + EndIf + Format = ReadStringFormat(FileId) + HadBom = Bool(Format <> #PB_Ascii) + If Not HadBom + Format = #PB_UTF8 + EndIf + Size = Lof(FileId) - Loc(FileId) + *Data = AllocateMemory(Size + 2) + If Not *Data + CloseFile(FileId) + ProcedureReturn #False + EndIf + ReadData(FileId, *Data, Size) + CloseFile(FileId) + Text = PeekS(*Data, Size, Format | #PB_ByteLength) + FreeMemory(*Data) + + If Not FindString(ReplaceString(Text, #CRLF$, ""), #LF$) + ProcedureReturn OpenPreferences(IniFilePath) + EndIf + + Text = ReplaceString(ReplaceString(Text, #CRLF$, #LF$), #LF$, #CRLF$) + Copy = GetTemporaryDirectory() + "BakaShrot-config-" + Str(Date()) + "-" + Str(Random(999999)) + ".ini" + FileId = CreateFile(#PB_Any, Copy) + If Not FileId + ProcedureReturn #False + EndIf + If HadBom + WriteStringFormat(FileId, Format) + EndIf + WriteString(FileId, Text, Format) + CloseFile(FileId) + + Opened = OpenPreferences(Copy) + If Opened + BakaShrot_ConfigCopyPath = Copy + Else + DeleteFile(Copy) + EndIf + ProcedureReturn Opened +EndProcedure + +; ClosePreferences(), and deletes OpenConfigPreferences()' copy if it made one. +Procedure CloseConfigPreferences() + ClosePreferences() + If BakaShrot_ConfigCopyPath <> "" + DeleteFile(BakaShrot_ConfigCopyPath) + BakaShrot_ConfigCopyPath = "" + EndIf +EndProcedure + + +; [BakaShrot.Server] DatabasePath of IniFilePath, "" if it can't be opened: +; where the root reads the names it already has from, before LoadConfig(). +Procedure.s ReadConfigDatabasePath(IniFilePath.s) + Protected Path.s + + If OpenConfigPreferences(IniFilePath) + PreferenceGroup("BakaShrot.Server") + Path = ReadPreferenceString("DatabasePath", #BakaShrot_Config_DefaultDatabasePath) + CloseConfigPreferences() + EndIf + ProcedureReturn Path +EndProcedure + + ; Loads IniFilePath. Returns 0 on failure, with the reason in BakaShrot_ConfigError. -Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) +; *Known: the names the database already has, so the ones listed without an +; id keep theirs (0: none, a new database). +Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s, *Known.BakaShrot_KnownNames = 0) Protected *Config.BakaShrot_CoreConfig Protected GroupName.s, PeerName.s, ClientName.s, Text.s, Id.i Protected NewList PeerNames.s(), NewList ClientNames.s() Protected Failed.i = #False + Protected NoneKnown.BakaShrot_KnownNames BakaShrot_ConfigError = "" + If Not *Known + *Known = @NoneKnown + EndIf + *BakaShrot_ConfigKnown = *Known - If Not OpenPreferences(IniFilePath) + If Not OpenConfigPreferences(IniFilePath) BakaShrot_ConfigError = "can't open '" + IniFilePath + "'" ProcedureReturn 0 EndIf *Config = AllocateStructure(BakaShrot_CoreConfig) If Not *Config - ClosePreferences() + CloseConfigPreferences() BakaShrot_ConfigError = "out of memory" ProcedureReturn 0 EndIf ; Names first, everything else can refer to them. - If Not ParseNameSection("BakaShrot.Topics", "topic", *Config\TopicIds(), *Config\TopicNames()) Or - Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames()) + If Not ParseNameSection("BakaShrot.Topics", "topic", *Config\TopicIds(), *Config\TopicNames(), *Known\TopicIds(), *Known\TopicUsed()) Or + Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames(), *Known\NodeIds(), *Known\NodeUsed()) Goto LoadFailed EndIf + + PreferenceGroup("BakaShrot") + *Config\PrivateKey = ReadPreferenceString("PrivateKey", "") + ; Topic (TopicId) isn't read any more: a server authenticates by node. + *Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) + Id = DeclareConfigNode(*Config, *Config\NodeText) + If Id < 0 + BakaShrot_ConfigError = "[BakaShrot] Node: '" + *Config\NodeText + "' isn't a node name or an id" + Goto LoadFailed + EndIf + *Config\NodeId = Id + *Config\UsedNodeIds(Str(*Config\NodeId)) = #True + + ; Every [BakaShrot.Peer.] and [BakaShrot.Client.], found + ; dynamically so adding one never needs a second "list of names" kept in + ; sync by hand. Read once the walk is done: PreferenceGroup() inside it + ; would lose the walk's place. + If ExaminePreferenceGroups() + While NextPreferenceGroup() + GroupName = PreferenceGroupName() + If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.") + AddElement(PeerNames()) + PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1) + EndIf + If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.") + AddElement(ClientNames()) + ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1) + EndIf + Wend + EndIf + + ; The nodes the peer and client sections define are named before any + ; node list (SendNodes, AcceptNodes) can refer to them. A bad one is + ; reported when its section is read below. + ForEach PeerNames() + PreferenceGroup("BakaShrot.Peer." + PeerNames()) + DeclareConfigNode(*Config, Trim(ReadConfigKey("Node", "NodeId", "0"))) + Next + ForEach ClientNames() + PreferenceGroup("BakaShrot.Client." + ClientNames()) + Text = Trim(ReadPreferenceString("Node", "")) + If Text <> "" + DeclareConfigNode(*Config, Text) + EndIf + Next + ForEach *Config\TopicNames() *Config\UsedTopicIds(MapKey(*Config\TopicNames())) = #True Next @@ -849,25 +1052,6 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) *Config\UsedNodeIds(MapKey(*Config\NodeNames())) = #True Next - PreferenceGroup("BakaShrot") - *Config\PrivateKey = ReadPreferenceString("PrivateKey", "") - *Config\TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0")) - *Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) - Id = ResolveConfigTopic(*Config, *Config\TopicText) - If Id < 0 - BakaShrot_ConfigError = "[BakaShrot] Topic: unknown topic '" + *Config\TopicText + "'" - Goto LoadFailed - EndIf - *Config\TopicId = Id - Id = ResolveConfigNode(*Config, *Config\NodeText) - If Id < 0 - BakaShrot_ConfigError = "[BakaShrot] Node: unknown node '" + *Config\NodeText + "'" - Goto LoadFailed - EndIf - *Config\NodeId = Id - *Config\UsedTopicIds(Str(*Config\TopicId)) = #True - *Config\UsedNodeIds(Str(*Config\NodeId)) = #True - PreferenceGroup("BakaShrot.Server") *Config\Server\Host = ReadPreferenceString("Host", "") *Config\Server\Port = ReadPreferenceLong("Port", 0) @@ -892,6 +1076,19 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) BakaShrot_ConfigError = "[BakaShrot.Server] UploadTimeout must be 10 seconds or more" Goto LoadFailed EndIf + *Config\Server\Synchronous = UCase(Trim(ReadPreferenceString("Synchronous", #BakaShrot_Config_DefaultSynchronous))) + ; An If chain, not a Select: a Goto out of a Select corrupts the stack + ; with 5.73's ASM backend (it keeps the value there). + If *Config\Server\Synchronous = "OFF" + BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = OFF isn't allowed: a power loss could corrupt the database. FULL, or NORMAL to only risk the last second of messages" + Goto LoadFailed + ElseIf *Config\Server\Synchronous = "EXTRA" + BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = EXTRA does nothing more than FULL in WAL mode: write FULL" + Goto LoadFailed + ElseIf *Config\Server\Synchronous <> "FULL" And *Config\Server\Synchronous <> "NORMAL" + BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = '" + *Config\Server\Synchronous + "' isn't FULL or NORMAL" + Goto LoadFailed + EndIf *Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "") If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics") Goto LoadFailed @@ -901,24 +1098,6 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) Goto LoadFailed EndIf - ; Every [BakaShrot.Peer.] and [BakaShrot.Client.], found - ; dynamically so adding one never needs a second "list of names" kept in - ; sync by hand. Read once the walk is done: PreferenceGroup() inside it - ; would lose the walk's place. - If ExaminePreferenceGroups() - While NextPreferenceGroup() - GroupName = PreferenceGroupName() - If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.") - AddElement(PeerNames()) - PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1) - EndIf - If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.") - AddElement(ClientNames()) - ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1) - EndIf - Wend - EndIf - ForEach PeerNames() PeerName = PeerNames() PreferenceGroup("BakaShrot.Peer." + PeerName) @@ -927,22 +1106,15 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) \Host = ReadPreferenceString("Host", "") \Port = ReadPreferenceLong("Port", 0) \PublicKey = ReadPreferenceString("PublicKey", "") - \TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0")) + ; Topic (TopicId) isn't read any more: a peer authenticates by node. \NodeText = Trim(ReadConfigKey("Node", "NodeId", "0")) - Id = ResolveConfigTopic(*Config, \TopicText) + Id = DeclareConfigNode(*Config, \NodeText) If Id < 0 - BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Topic: unknown topic '" + \TopicText + "'" - Failed = #True : Break - EndIf - \TopicId = Id - Id = ResolveConfigNode(*Config, \NodeText) - If Id < 0 - BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: unknown node '" + \NodeText + "'" + BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: '" + \NodeText + "' isn't a node name or an id" Failed = #True : Break EndIf \NodeId = Id - *Config\UsedTopicIds(Str(\TopicId)) = #True - *Config\UsedNodeIds(Str(\NodeId)) = #True + *Config\UsedNodeIds(Str(\NodeId)) = #True \SendTopicsText = ReadPreferenceString("SendTopics", #BakaShrot_Config_Missing) If \SendTopicsText = #BakaShrot_Config_Missing @@ -967,7 +1139,7 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) \AcceptNodesText = ReadPreferenceString("AcceptNodes", #BakaShrot_Config_Missing) If \AcceptNodesText = #BakaShrot_Config_Missing - \AcceptNodes\Known = #True + \AcceptNodes\All = #True ElseIf Not ParseNameSet(*Config, \AcceptNodesText, @\AcceptNodes, #True, "[BakaShrot.Peer." + PeerName + "] AcceptNodes") Failed = #True : Break EndIf @@ -983,28 +1155,27 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) AddMapElement(*Config\Clients(), ClientName) With *Config\Clients() ParsePublicKeyList(ReadPreferenceString("PublicKeys", ""), \PublicKeys()) - \IdentitiesText = ReadPreferenceString("Identities", "") - If Not ParseIdentityList(*Config, \IdentitiesText, \Identities(), "[BakaShrot.Client." + ClientName + "] Identities") + If Not ParseClientIdentity(*Config, @*Config\Clients(), "[BakaShrot.Client." + ClientName + "]") Failed = #True : Break EndIf \Permissions\Read = Bool(ReadPreferenceLong("AllowRead", #BakaShrot_Config_DefaultAllowRead) <> 0) \Permissions\Write = Bool(ReadPreferenceLong("AllowWrite", #BakaShrot_Config_DefaultAllowWrite) <> 0) \Permissions\Query = Bool(ReadPreferenceLong("AllowQuery", #BakaShrot_Config_DefaultAllowQuery) <> 0) - ; By default, only the topics it authenticates in, like before. + ; By default, only its default topic, nothing without one. \PushTopicsText = ReadPreferenceString("PushTopics", #BakaShrot_Config_Missing) \ReadTopicsText = ReadPreferenceString("ReadTopics", #BakaShrot_Config_Missing) If \PushTopicsText = #BakaShrot_Config_Missing - ForEach \Identities() - \PushTopics\Ids(Str(\Identities()\TopicId)) = #True - Next + If \DefaultTopicId >= 0 + \PushTopics\Ids(Str(\DefaultTopicId)) = #True + EndIf ElseIf Not ParseTopicSet(*Config, \PushTopicsText, @\PushTopics, "[BakaShrot.Client." + ClientName + "] PushTopics") Failed = #True : Break EndIf If \ReadTopicsText = #BakaShrot_Config_Missing - ForEach \Identities() - \ReadTopics\Ids(Str(\Identities()\TopicId)) = #True - Next + If \DefaultTopicId >= 0 + \ReadTopics\Ids(Str(\DefaultTopicId)) = #True + EndIf ElseIf Not ParseTopicSet(*Config, \ReadTopicsText, @\ReadTopics, "[BakaShrot.Client." + ClientName + "] ReadTopics") Failed = #True : Break EndIf @@ -1014,11 +1185,11 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s) Goto LoadFailed EndIf - ClosePreferences() + CloseConfigPreferences() ProcedureReturn *Config LoadFailed: - ClosePreferences() + CloseConfigPreferences() FreeConfig(*Config) ProcedureReturn 0 EndProcedure @@ -1041,7 +1212,6 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) PreferenceGroup("BakaShrot") WritePreferenceString("PrivateKey", *Config\PrivateKey) - WritePreferenceString("Topic", *Config\TopicText) WritePreferenceString("Node", *Config\NodeText) PreferenceGroup("BakaShrot.Server") @@ -1056,6 +1226,7 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval) WritePreferenceString("MaxAttachmentSize", *Config\Server\MaxAttachmentSizeText) WritePreferenceLong("UploadTimeout", *Config\Server\UploadTimeout) + WritePreferenceString("Synchronous", *Config\Server\Synchronous) PreferenceGroup("BakaShrot.Topics") ForEach *Config\TopicNames() @@ -1078,7 +1249,6 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers())) WritePreferenceString("Host", *Config\Peers()\Host) WritePreferenceLong("Port", *Config\Peers()\Port) - WritePreferenceString("Topic", *Config\Peers()\TopicText) WritePreferenceString("Node", *Config\Peers()\NodeText) WritePreferenceString("PublicKey", *Config\Peers()\PublicKey) WriteConfigText("SendTopics", *Config\Peers()\SendTopicsText) @@ -1090,7 +1260,8 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig) ForEach *Config\Clients() PreferenceGroup("BakaShrot.Client." + MapKey(*Config\Clients())) WritePreferenceString("PublicKeys", FormatPublicKeyList(*Config\Clients()\PublicKeys())) - WritePreferenceString("Identities", *Config\Clients()\IdentitiesText) + WritePreferenceString("Node", *Config\Clients()\NodeText) + WriteConfigText("DefaultTopic", *Config\Clients()\DefaultTopicText) WritePreferenceLong("AllowRead", *Config\Clients()\Permissions\Read) WritePreferenceLong("AllowWrite", *Config\Clients()\Permissions\Write) WritePreferenceLong("AllowQuery", *Config\Clients()\Permissions\Query) @@ -1112,7 +1283,6 @@ CompilerIf #PB_Compiler_IsMainFile If *Config Debug "PrivateKey: " + *Config\PrivateKey - Debug "TopicId: " + Str(*Config\TopicId) Debug "NodeId: " + Str(*Config\NodeId) Debug "Server: " + *Config\Server\Host + ":" + Str(*Config\Server\Port) @@ -1135,9 +1305,7 @@ CompilerIf #PB_Compiler_IsMainFile ForEach *Config\Clients()\PublicKeys() Debug " PublicKey: " + *Config\Clients()\PublicKeys() Next - ForEach *Config\Clients()\Identities() - Debug " Identity: " + Str(*Config\Clients()\Identities()\TopicId) + ":" + Str(*Config\Clients()\Identities()\NodeId) - Next + Debug " Node: " + Str(*Config\Clients()\NodeId) + ", DefaultTopic: " + Str(*Config\Clients()\DefaultTopicId) Next SaveConfig("schema_out.ini", *Config) diff --git a/Server/Config/schema.ini b/Server/Config/schema.ini index 999aae5..6d38e92 100644 --- a/Server/Config/schema.ini +++ b/Server/Config/schema.ini @@ -3,15 +3,17 @@ ; library is concerned — the dots below are just part of the name. ; ; Topics and nodes: each has an id (0-65535) on this server, and can have a -; name, in [BakaShrot.Topics] and [BakaShrot.Nodes]. Names are what's shared -; between servers: replication sends them, and each server stores the -; messages under its own ids for them ("logs" can be 1 here and 200 on a -; peer). +; name. Topics are named in [BakaShrot.Topics]; nodes by the sections that +; define them ([BakaShrot] Node, a peer's, a client's), [BakaShrot.Nodes] +; only names the others. The server gives every name its id, and keeps it. +; Names are what's shared between servers: replication sends them, and +; each server stores the messages under its own ids for them ("logs" can be +; 1 here and 200 on a peer). ; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a ; name, or whose name the other server doesn't have, is dropped. Unnamed ; ones still work locally, by id. ; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter. -; The server's "names" command and the ListNames tool list them all. +; The server's "names" command and the BakaShrotList tool list them all. ; ; Topic, Node and ReplicatingTopics were TopicId, NodeId and ; ReplicatingTopicIds before: the old names are still read. @@ -27,31 +29,37 @@ [BakaShrot] ; Config shared by every type of config. -; This node's Ed25519 private key (Base64), from KeyGen.exe. It proves who +; This node's Ed25519 private key (Base64), from BakaShrotGenerateKeyPairs.exe. It proves who ; this server is: clients seal their Hello for its public key and check ; that it signed the handshake, so they need that public key (client.ini's ; ServerPublicKey, peers' PublicKey below in THEIR own config). The server ; logs it when it starts. See Commons/Networking/Connections.pbi. PrivateKey = -; The topic and node this server authenticates as when it links to its -; peers, a name or an id. Its peers must register it under the same names. -Topic = +; The node this server authenticates as when it links to its peers, a name +; or an id. Its peers must register it under the same name: a client +; section with this Node and this server's public key. (A Topic left here +; from before protocol 5 is ignored.) Node = [BakaShrot.Topics] -; One line per named topic: name = this server's id for it. -; logs = 1 -; sensors = 2 +; One topic name per line. This server gives each its id: the one its +; database already has for it, or the lowest free one for a new one, so the +; order doesn't matter and they keep their ids. +; "name = id" pins one instead (configs from before work as they are). Once +; a name has messages, its id can't change: the server refuses to start if +; a pin moves it, and says which id to use. +; logs +; sensors [BakaShrot.Nodes] -; One line per named node (a client's or a server's), same as topics. Every -; server that should get a node's messages must name it too. -; Once a name has messages, keep its id: the server refuses to start if the -; config moves it to another one, and says which id to use. -; kitchen = 2 +; Optional. The nodes [BakaShrot] Node, the peers' and the clients' Node +; define are named already. List the others this server should know by name +; up front, like topics; peers add the ones they send as they come +; (AcceptNodes, below). +; kitchen [BakaShrot.Retention] @@ -114,6 +122,21 @@ MaxAttachmentSize = 1G ; after which the upload is deleted. UploadTimeout = 3600 +; How hard the database makes sure a push is on disk before answering it. +; FULL (default) every commit is flushed to disk: a message the server +; acknowledged survives a power loss or an OS crash. +; NORMAL flushed about once a second only (at the checkpoints): faster +; (twice the pushes under full load, measured), but a power loss +; or an OS crash loses the last second or so of acknowledged +; messages, and their ids are handed out again, which peers that +; already got them can't tell (Design/ReplicationIssues.md #1). +; A crash of the server alone loses nothing either way. +; The cost of FULL is the disk's flush time, once per group of pushes: well +; under a millisecond on a server SSD, ~10 ms on a hard disk, which then +; caps one client pushing one message at a time to ~100/s. +; See Design/StorageConcurrency.md for the numbers. +Synchronous = FULL + ; One [BakaShrot.Peer.] section per peer this node talks to. ; is only a key for this file; it is never sent on the wire. @@ -129,9 +152,8 @@ Port = ; The link only goes through if the peer proves it holds the private key ; of PublicKey below, and it's encrypted. -; Remote node's topic and node, names or ids. The peer authenticates with -; them when it links to here. -Topic = +; The peer's node, a name or an id: the one in its own [BakaShrot] Node. +; It authenticates as it when it links to here. Node = ; The topics sent to this peer (if it takes them), and the topics taken @@ -140,9 +162,9 @@ Node = ; AcceptTopics = logs;sensors.* ; The nodes whose messages are sent to this peer (default: every one), and -; the nodes whose messages are taken from it (default: the ones named in -; [BakaShrot.Nodes], no other). AcceptNodes = kitchen-* takes every -; kitchen-something the peer sends, named here or not. +; the nodes whose messages are taken from it (default: every one, the names +; this server doesn't have yet are added as they come). AcceptNodes = +; kitchen-*;garage only takes those, named here or not. ; SendNodes = * ; AcceptNodes = kitchen-*;garage @@ -159,13 +181,30 @@ PublicKey = ; Format: Key;Key;... PublicKeys = -; Topic and node pairs this client is allowed to authenticate as, names or ids. -; Format: Topic:Node;Topic:Node;... -Identities = +; The node this client writes as, a name or an id, required. Every message +; it pushes is stored under it, so the server decides which node each key +; writes as, and no client can push as another's node (or as a peer's). +; Its client.ini's Node must say the same. A key that writes as several +; nodes is listed in a section per node. +; ONE SERVER PER NODE: give a node a client section on the one server it +; pushes to, the others get its messages by replication. Two servers taking +; pushes for the same node end up with different messages under the same +; ids, which nothing detects (Design/ReplicationIssues.md #1). To read from +; another server, give the client another node there (or no write access: +; AllowWrite = 0). +Node = + +; Where its pushes go when they don't name a topic, a name or an id. +; Optional: without it, every push must name its topic. Only a default, it +; may push to any topic in PushTopics. +; DefaultTopic = logs + +; (Identities, the Topic:Node pairs before protocol 5, isn't read any more: +; the server refuses to start with it, saying what to write instead.) ; The topics it may push to (always under its own node), and the topics it -; may read the latest messages of. Both default to the topics of its -; Identities, empty allows none. +; may read the latest messages of. Both default to its DefaultTopic, +; nothing without one; empty allows none. ; PushTopics = logs;sensors ; ReadTopics = * diff --git a/Server/Networking/Networking.pbi b/Server/Networking/Networking.pbi index 024f143..ea53761 100644 --- a/Server/Networking/Networking.pbi +++ b/Server/Networking/Networking.pbi @@ -204,7 +204,7 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) Protected Accepted.BakaShrot_AuthAccepted Protected Proof.BakaShrot_ChallengeProof Protected KeyPair.BakaShrot_SessionKeyPair - Protected TopicId.i, NodeId.i, PublicKey.s, ClientName.s, TopicRef.s, NodeRef.s + Protected NodeId.i, DefaultTopicId.i, PublicKey.s, ClientName.s, NodeRef.s Protected NonceMatches.i, SignatureDecoded.i, Sent.i, CipherReady.i *Client\Metadata\Status = #BakaShrot_ConnectionStatus_New @@ -235,16 +235,14 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) ProcedureReturn #False EndIf - TopicRef = *Hello\ClientTopic NodeRef = *Hello\ClientNode PublicKey = *Hello\ClientPubKeyB64 CopyMemory(@*Hello\ClientSessionKey[0], @*Client\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize) FreeStructure(*Hello) - TopicId = BakaShrot_Names_ResolveTopic(TopicRef) - NodeId = BakaShrot_Names_ResolveNode(NodeRef) - If TopicId < 0 Or NodeId < 0 - PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown identity '" + Left(TopicRef, 80) + "':'" + Left(NodeRef, 80) + "'") + NodeId = BakaShrot_Names_ResolveNode(NodeRef) + If NodeId < 0 + PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown node '" + Left(NodeRef, 80) + "'") ProcedureReturn #False EndIf @@ -254,9 +252,11 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) EndIf LockMutex(*Server\Mutex) - ClientName = FindClientName(*Server\Config, PublicKey, TopicId, NodeId) - *Client\PeerName = FindPeerName(*Server\Config, PublicKey, TopicId, NodeId) + ClientName = FindClientName(*Server\Config, PublicKey, NodeId) + *Client\PeerName = FindPeerName(*Server\Config, PublicKey, NodeId) + DefaultTopicId = -1 If ClientName <> "" And FindMapElement(*Server\Config\Clients(), ClientName) + DefaultTopicId = *Server\Config\Clients()\DefaultTopicId *Client\Permissions\Read = *Server\Config\Clients()\Permissions\Read *Client\Permissions\Write = *Server\Config\Clients()\Permissions\Write *Client\Permissions\Query = *Server\Config\Clients()\Permissions\Query @@ -270,12 +270,12 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) EndIf UnlockMutex(*Server\Mutex) If ClientName = "" - PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to use " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + " with its public key") + PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to write as node " + BakaShrot_Names_NodeRef(NodeId) + " with its public key") ProcedureReturn #False EndIf - *Client\Metadata\TopicId = TopicId - *Client\Metadata\NodeId = NodeId + *Client\Metadata\DefaultTopicId = DefaultTopicId + *Client\Metadata\NodeId = NodeId ; 2. Challenge request, in plain text, signed by this server @@ -386,9 +386,9 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient) *Client\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated If *Client\PeerName = "" - PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId)) + PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId)) Else - PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'") + PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'") EndIf ProcedureReturn #True @@ -397,12 +397,13 @@ EndProcedure ; Encodes and sends a RequestRefused. ; Returns #False if it couldn't be sent, the client must then be aborted. -Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Reason.s) +Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Code.l, Reason.s) Protected Refused.BakaShrot_RequestRefused Protected *Packet, PacketSize.Integer, Sent.i - PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + ": " + Reason) + PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + " (" + BakaShrot_ErrorName(Code) + "): " + Reason) + Refused\Code = Code Refused\Reason = Reason *Packet = BakaShrot_RequestRefusedPacket_Encode(@Refused, @PacketSize) If Not *Packet @@ -449,51 +450,54 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, * EndIf If Not *Client\Permissions\Write - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write") EndIf If TopicRef = "" - TopicId = *Client\Metadata\TopicId + TopicId = *Client\Metadata\DefaultTopicId + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic") + EndIf Else TopicId = BakaShrot_Names_ResolveTopic(TopicRef) If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") EndIf EndIf If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") EndIf ; So it fits in every packet that carries it later, see Packets.pbi. JsonSize = StringByteLength(JsonData, #PB_UTF8) If JsonSize > #BakaShrot_MaxMessageSize - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize)) EndIf ; A topic allowed by "*" may be new here, it needs its row for the ; "messages" view. If Not BakaShrot_Names_EnsureTopicId(TopicId, @StoreError) PrintN("[Net] Failed to register topic " + Str(TopicId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored") EndIf ; Its attachment: one of this client's complete uploads, for that topic. If UploadId If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload") EndIf If Blob\State <> #BakaShrot_Blob_Complete - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload isn't complete, or is attached already") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload isn't complete, or is attached already") EndIf If Blob\TopicId <> TopicId - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") EndIf EndIf MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId) If MessageId < 1 PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored") EndIf Pushed\MessageId = MessageId @@ -542,23 +546,23 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie EndIf If Not *Client\Permissions\Read - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read") EndIf TopicId = BakaShrot_Names_ResolveTopic(TopicRef) If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") EndIf If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") EndIf NodeId = BakaShrot_Names_ResolveNode(NodeRef) If NodeId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'") EndIf If Not GetLatestMessage(*Client\DbId, TopicId, NodeId, @Message) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId)) EndIf Latest\TopicId = TopicId @@ -619,24 +623,24 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, * EndIf If Not *Client\Permissions\Read - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read") EndIf TopicId = BakaShrot_Names_ResolveTopic(TopicRef) If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") EndIf If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") EndIf NodeId = BakaShrot_Names_ResolveNode(NodeRef) If NodeId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'") EndIf ; In characters, the bytes are counted below: never less than that. If Not GetMessagesAfter(*Client\DbId, TopicId, NodeId, AfterMessageId, Limit, #BakaShrot_MessagesBatchBytes, Messages(), @More) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be read") EndIf ; As many as fit in #BakaShrot_MessagesBatchBytes, the rest is for the @@ -702,16 +706,16 @@ Procedure.i BakaShrot_NetClient_HandleQuery(*Client.BakaShrot_NetClient, *Packet FreeStructure(*Request) If Not *Client\Permissions\Query - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to query") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to query") EndIf If Not RunReadOnlyQuery(*Client\Server\DatabasePath, Sql, @JsonResult, @QueryError) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Query failed: " + QueryError\s) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_QueryFailed, "Query failed: " + QueryError\s) EndIf ; Leaves room for the packet's own fields. If StringByteLength(JsonResult\s, #PB_UTF8) > #BakaShrot_MaxPacketSize - 64 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The result is too big for one packet, add a LIMIT") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The result is too big for one packet, add a LIMIT") EndIf Result\JsonResult = JsonResult\s @@ -755,16 +759,16 @@ Procedure.i BakaShrot_NetClient_HandleResolveName(*Client.BakaShrot_NetClient, * If Kind = #BakaShrot_NameKind_Topic Id = BakaShrot_Names_ResolveTopic(Ref) If Id < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'") EndIf If Not *Client\Permissions\Query And Not NameSetHas(@*Client\PushTopics, Id, BakaShrot_Names_TopicName(Id)) And Not NameSetHas(@*Client\ReadTopics, Id, BakaShrot_Names_TopicName(Id)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'") EndIf Resolved\Name = BakaShrot_Names_TopicName(Id) Else Id = BakaShrot_Names_ResolveNode(Ref) If Id < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(Ref, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(Ref, 80) + "'") EndIf Resolved\Name = BakaShrot_Names_NodeName(Id) EndIf @@ -878,12 +882,12 @@ Procedure.i BakaShrot_NetClient_HandleSyncStateRequest(*Client.BakaShrot_NetClie FreeStructure(*Request) If *Client\PeerName = "" - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") EndIf If Not GetSyncState(*Client\DbId, AllPairs()) PrintN("[Net] Failed to read the sync state for peer '" + *Client\PeerName + "': " + DatabaseError()) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The sync state couldn't be read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The sync state couldn't be read") EndIf ; Every name this server knows, the peer only sends those. @@ -963,20 +967,20 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli If *Client\PeerName = "" FreeStructure(*Batch) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") EndIf TopicId = BakaShrot_Names_TopicByName(TopicRef) If Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) FreeStructure(*Batch) BakaShrot_Names_NoteDropped(*Client\PeerName, "topic", TopicRef, "not taken here") - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Topic '" + TopicRef + "' isn't replicated here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Topic '" + TopicRef + "' isn't replicated here") EndIf NodeId = BakaShrot_Names_NodeByName(NodeRef) If Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef) FreeStructure(*Batch) BakaShrot_Names_NoteDropped(*Client\PeerName, "node", NodeRef, "not taken here") - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Node '" + NodeRef + "' isn't replicated here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Node '" + NodeRef + "' isn't replicated here") EndIf ; Taken by a wildcard, new here. @@ -989,7 +993,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli If TopicId < 0 Or NodeId < 0 FreeStructure(*Batch) PrintN("[Net] Failed to add '" + TopicRef + "':'" + NodeRef + "' from peer '" + *Client\PeerName + "': " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored") EndIf MaxAge = RetentionMaxAgeMs(*Client\Retention(), TopicId, TopicRef) @@ -1003,7 +1007,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli EndIf If Not IsStored PrintN("[Net] Failed to store messages from peer '" + *Client\PeerName + "': " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored") EndIf Pushed\MessageId = LastMessageId @@ -1062,29 +1066,32 @@ Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, * FreeStructure(*Start) If Not *Client\Permissions\Write - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write") EndIf If TopicRef = "" - TopicId = *Client\Metadata\TopicId + TopicId = *Client\Metadata\DefaultTopicId + If TopicId < 0 + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic") + EndIf Else TopicId = BakaShrot_Names_ResolveTopic(TopicRef) If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") EndIf EndIf If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") EndIf MaxSize = *Client\Server\Config\Server\MaxAttachmentSize If Size > MaxSize - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here") EndIf BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError) If Not BlobId PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be started") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be started") EndIf Started\UploadId = BlobId @@ -1120,23 +1127,23 @@ Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, * ; Only its own uploads: same node, a topic it may still push to. If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload in progress") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload in progress") EndIf If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId)) BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'") EndIf Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex) If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected BakaShrot_UploadChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes") EndIf Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError) BakaShrot_UploadChunkPacket_Free(*Chunk) If Received < 0 PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored") EndIf If Received < Blob\Size @@ -1146,10 +1153,10 @@ Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, * ; All of it: the SHA-256 given at the start must match. If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0]) SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload doesn't match its SHA-256, it's dropped") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The upload doesn't match its SHA-256, it's dropped") EndIf If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be stored") EndIf ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True) EndProcedure @@ -1181,36 +1188,36 @@ Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient, FreeStructure(*Request) If Not *Client\Permissions\Read - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read") EndIf TopicId = BakaShrot_Names_ResolveTopic(TopicRef) If TopicId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'") EndIf If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId)) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'") EndIf NodeId = BakaShrot_Names_ResolveNode(NodeRef) If NodeId < 0 - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'") EndIf If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId)) EndIf Select Attachment\State Case #BakaShrot_Attachment_NotKept - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize") Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotReady, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes") EndSelect If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts") EndIf Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize) If Not Chunk\Data - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be read") EndIf Chunk\DataSize = DataSize\i Chunk\TopicId = TopicId @@ -1252,12 +1259,12 @@ Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShro FreeStructure(*Request) If *Client\PeerName = "" - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") EndIf ; More than one answer holds, some of them may be someone else's. If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing()) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The missing attachments couldn't be read") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The missing attachments couldn't be read") EndIf ForEach Missing() If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments @@ -1312,18 +1319,18 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot If *Client\PeerName = "" BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate") EndIf TopicId = BakaShrot_Names_TopicByName(TopicRef) NodeId = BakaShrot_Names_NodeByName(NodeRef) If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef) BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here") EndIf If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment) BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId)) EndIf If Attachment\State = #BakaShrot_Attachment_Ready ; Someone else's link was faster: done. @@ -1332,11 +1339,11 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot EndIf If Attachment\State = #BakaShrot_Attachment_NotKept BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here") EndIf If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex) BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize)) + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize)) EndIf BlobId = Attachment\BlobId @@ -1351,7 +1358,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk) If Received < 0 PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored") EndIf If Received < Attachment\Size @@ -1360,11 +1367,11 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0]) If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid) - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be stored") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be stored") EndIf If Not IsValid PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped") - ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment doesn't match its SHA-256, send it again") + ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The attachment doesn't match its SHA-256, send it again") EndIf ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True) EndProcedure diff --git a/Server/Networking/Peers.pbi b/Server/Networking/Peers.pbi index d6ce543..3c56418 100644 --- a/Server/Networking/Peers.pbi +++ b/Server/Networking/Peers.pbi @@ -141,7 +141,7 @@ Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, Ans ProcedureReturn #False EndIf - PrintN("[Peer] '" + *Link\Name + "' refused: " + *Refused\Reason) + PrintN("[Peer] '" + *Link\Name + "' refused (" + BakaShrot_ErrorName(*Refused\Code) + "): " + *Refused\Reason) FreeStructure(*Refused) ProcedureReturn #True EndProcedure @@ -665,7 +665,6 @@ Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig) GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0]) ; By name: the peer has its own ids for them. - *Links\Identity\Topic = BakaShrot_Names_TopicRef(*Config\TopicId) *Links\Identity\Node = BakaShrot_Names_NodeRef(*Config\NodeId) *Links\Identity\PublicKey = EncodeKeyToString(@*Links\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize) *Links\Identity\PrivateKey = @*Links\PrivateKey[0] diff --git a/Server/Root.pbi b/Server/Root.pbi index ba5b8ea..0e59e8d 100644 --- a/Server/Root.pbi +++ b/Server/Root.pbi @@ -52,8 +52,24 @@ EndStructure ; Only while the workers are stopped, they use the config. Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root) Protected *Config.BakaShrot_CoreConfig + Protected Known.BakaShrot_KnownNames, KnownError.String, DatabasePath.s, DbId.i - *Config = LoadConfig(*Root\ConfigPath) + ; The names the database has first, so the ones the config lists without + ; an id keep theirs (Storage/Names.pbi). Nothing to read on a new one. + DatabasePath = ReadConfigDatabasePath(*Root\ConfigPath) + If DatabasePath <> "" And FileSize(DatabasePath) > 0 + DbId = OpenStorageDatabase(DatabasePath) + If Not DbId Or Not SetupStorageDatabase(DbId) Or Not BakaShrot_Names_ReadKnown(DbId, @Known, @KnownError) + PrintN("[Root] Failed to read the names of the database '" + DatabasePath + "': " + KnownError\s + DatabaseError()) + If DbId + CloseDatabase(DbId) + EndIf + ProcedureReturn #False + EndIf + CloseDatabase(DbId) + EndIf + + *Config = LoadConfig(*Root\ConfigPath, @Known) If Not *Config PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError) ProcedureReturn #False @@ -64,7 +80,7 @@ Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root) EndIf *Root\Config = *Config - PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Topic=" + *Config\TopicText + ", Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " + + PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " + Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)") ProcedureReturn #True EndProcedure @@ -77,6 +93,10 @@ Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root) Protected DatabasePath.s = *Root\Config\Server\DatabasePath Protected NamesError.String + ; Every connection opened from here on, the workers' included (they're + ; stopped meanwhile), takes it. + BakaShrot_Storage_Synchronous = *Root\Config\Server\Synchronous + *Root\DbId = OpenStorageDatabase(DatabasePath) If Not *Root\DbId PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError()) @@ -97,7 +117,7 @@ Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root) ProcedureReturn #False EndIf - PrintN("[Root] Database '" + DatabasePath + "' is ready") + PrintN("[Root] Database '" + DatabasePath + "' is ready (synchronous " + BakaShrot_Storage_Synchronous + ")") ProcedureReturn #True EndProcedure diff --git a/Server/Storage/Names.pbi b/Server/Storage/Names.pbi index 70c1b0f..1efccbf 100644 --- a/Server/Storage/Names.pbi +++ b/Server/Storage/Names.pbi @@ -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. diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi index bf2f8c5..36a5da0 100644 --- a/Server/Storage/Storage.pbi +++ b/Server/Storage/Storage.pbi @@ -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 diff --git a/Server/Storage/db_schema_v8.dbml b/Server/Storage/db_schema_v8.dbml new file mode 100644 index 0000000..589357a --- /dev/null +++ b/Server/Storage/db_schema_v8.dbml @@ -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 diff --git a/Tests/AttachmentEdgeClient.pb b/Tests/AttachmentEdgeClient.pb index b24d2b4..c1410a4 100644 --- a/Tests/AttachmentEdgeClient.pb +++ b/Tests/AttachmentEdgeClient.pb @@ -51,7 +51,6 @@ Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s) Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize) Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)) *Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "") - *Client\Identity\Topic = ReadPreferenceString("Topic", "") *Client\Identity\Node = ReadPreferenceString("Node", "") *Client\Identity\PrivateKey = @*Client\PrivateKey[0] Host = ReadPreferenceString("ServerHost", "127.0.0.1") diff --git a/Tests/AttachmentEdges-Test.ps1 b/Tests/AttachmentEdges-Test.ps1 index f53cf19..d9c3cfc 100644 --- a/Tests/AttachmentEdges-Test.ps1 +++ b/Tests/AttachmentEdges-Test.ps1 @@ -26,7 +26,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe" $Fails = 0 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -71,7 +71,7 @@ function Wait-Port($Port, $S) { } function Query($Sql, $Ini) { $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql - Tool "Query.exe" @("@$F", $Ini) + Tool "BakaShrotQuery.exe" @("@$F", $Ini) } function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { $D = (Get-Date).AddSeconds($Seconds) @@ -87,7 +87,7 @@ function Push($Data, $Ini, [string]$Attach = "") { [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) $A = @() if ($Attach) { $A += @("-a", $Attach) } - Tool "PushMessage.exe" ($A + @("@$F", $Ini)) + Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) } function New-File($Name, [int64]$Size, [int]$Seed) { $P = Join-Path $Dir $Name @@ -112,7 +112,6 @@ foreach ($Name in "a", "b") { Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($Me.Priv) -Topic = logs Node = server$Name [BakaShrot.Topics] @@ -140,24 +139,26 @@ UploadTimeout = 10 [BakaShrot.Peer.$PeerName] Host = 127.0.0.1 Port = $PeerPort -Topic = logs Node = server$PeerName PublicKey = $($Peer.Pub) [BakaShrot.Client.$PeerName] PublicKeys = $($Peer.Pub) -Identities = logs:server$PeerName +Node = server$PeerName +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs PushTopics = logs;other;secret ReadTopics = * AllowQuery = 1 [BakaShrot.Client.garage] PublicKeys = $($G.Pub) -Identities = logs:garage +Node = garage +DefaultTopic = logs PushTopics = logs ReadTopics = logs "@ @@ -165,7 +166,7 @@ ReadTopics = logs $ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub } function Client-Ini($Name, $Keys, $Node, $Port) { $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" $P } $KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413 @@ -223,7 +224,7 @@ try { $Copy = Join-Path $Dir "big-from-b.bin" $D = (Get-Date).AddSeconds(90) do { - $R = Tool "GetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB) + $R = Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB) if ($R.Code -eq 0) { break } Start-Sleep -Milliseconds 500 } while ((Get-Date) -lt $D) @@ -260,7 +261,7 @@ db.commit(); print("flipped") $SA = Start-Srv "a" Wait-Port 12413 $SA $Copy = Join-Path $Dir "bad-from-a.bin" - Expect "reading it from A: the client refuses it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1 + Expect "reading it from A: the client refuses it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1 Check " and leaves no file" (-not (Test-Path $Copy)) "checked" $SB = Start-Srv "b" Wait-Port 12414 $SB @@ -268,7 +269,7 @@ db.commit(); print("flipped") $LogB = Get-Content $SB.Log -Raw $Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s" - Expect "B doesn't serve it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1 + Expect "B doesn't serve it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1 $R = Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]' @@ -280,7 +281,9 @@ finally { } "--- Logs" -$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -match "invalid|unexpected|doesn't decrypt" } +# Refusals are what this test asks for, their codes' names (InvalidRequest) +# aren't bad packets. +$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|doesn't decrypt" } Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ") "" diff --git a/Tests/Attachments-Test.ps1 b/Tests/Attachments-Test.ps1 index 74e2968..263a386 100644 --- a/Tests/Attachments-Test.ps1 +++ b/Tests/Attachments-Test.ps1 @@ -1,5 +1,5 @@ # End-to-end test of attachments (Design/Attachments.md), through the tools -# (PushMessage -a, GetAttachment, GetLatestMessage): +# (BakaShrotPushMessage -a, BakaShrotGetAttachment, BakaShrotGetLatestMessage): # - pushed with a message, read back identical (100 KB, 5 MB + a bit, # exactly 2 MB: one part, several, a whole number of them); # - a message without one: refused when asked for it; @@ -21,7 +21,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe" $Fails = 0 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -62,7 +62,7 @@ function Wait-Port($Port, $S) { } function Query($Sql, $Ini) { $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql - Tool "Query.exe" @("@$F", $Ini) + Tool "BakaShrotQuery.exe" @("@$F", $Ini) } function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { $D = (Get-Date).AddSeconds($Seconds) @@ -79,7 +79,7 @@ function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") { $A = @() if ($Topic) { $A += @("-t", $Topic) } if ($Attach) { $A += @("-a", $Attach) } - Tool "PushMessage.exe" ($A + @("@$F", $Ini)) + Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) } # A file of Size random bytes. function New-File($Name, [int]$Size, [int]$Seed) { @@ -93,16 +93,16 @@ function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA # Saves an attachment and compares it with the original. function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) { $Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin") - $R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) + $R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) $Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original)) Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out) } -# Retries GetAttachment until it works: replicated ones come after their message. +# Retries BakaShrotGetAttachment until it works: replicated ones come after their message. function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) { $Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin") $D = (Get-Date).AddSeconds($Seconds) do { - $R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) + $R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini) if ($R.Code -eq 0) { break } Start-Sleep -Milliseconds 250 } while ((Get-Date) -lt $D) @@ -114,7 +114,6 @@ $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($A.Priv) -Topic = logs Node = serverA [BakaShrot.Topics] @@ -144,17 +143,18 @@ MaxAttachmentSize = 64M [BakaShrot.Peer.b] Host = 127.0.0.1 Port = 12411 -Topic = logs Node = serverB PublicKey = $($B.Pub) [BakaShrot.Client.b] PublicKeys = $($B.Pub) -Identities = logs:serverB +Node = serverB +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs PushTopics = logs;short ReadTopics = * AllowQuery = 1 @@ -163,7 +163,6 @@ AllowQuery = 1 Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($B.Priv) -Topic = logs Node = serverB [BakaShrot.Topics] @@ -190,17 +189,18 @@ MaxAttachmentSize = 3M [BakaShrot.Peer.a] Host = 127.0.0.1 Port = 12410 -Topic = logs Node = serverA PublicKey = $($A.Pub) [BakaShrot.Client.a] PublicKeys = $($A.Pub) -Identities = logs:serverA +Node = serverA +DefaultTopic = logs [BakaShrot.Client.garage] PublicKeys = $($K.Pub) -Identities = photos:garage +Node = garage +DefaultTopic = photos PushTopics = photos ReadTopics = * AllowQuery = 1 @@ -209,7 +209,7 @@ AllowQuery = 1 $ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub } function Client-Ini($Name, $Topic, $Node, $Port) { $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = $Topic`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" $P } $OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410 @@ -241,10 +241,10 @@ try { Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs) Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA - Expect "#5 has none: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1 + Expect "#5 has none: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1 Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked" - Expect "a message that doesn't exist: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1 - Expect "GetLatestMessage: #5, no attachment line" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$" + Expect "a message that doesn't exist: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1 + Expect "BakaShrotGetLatestMessage: #5, no attachment line" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$" $R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]' @@ -255,16 +255,16 @@ try { Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB - Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "GetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1 + Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1 $R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out - Expect "B: GetLatestMessage logs:kitchen, #5 has none" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}" + Expect "B: BakaShrotGetLatestMessage logs:kitchen, #5 has none" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}" "--- Pushed on B, too big there, then replicated to A" Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1 Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment" Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA - Expect "A: the latest of photos:garage" (Tool "GetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}" + Expect "A: the latest of photos:garage" (Tool "BakaShrotGetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}" "--- Deleted with their message (A: short = 4s)" $Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out diff --git a/Tests/Bench/Bench-Replication.ps1 b/Tests/Bench/Bench-Replication.ps1 index d6c79ee..f314314 100644 --- a/Tests/Bench/Bench-Replication.ps1 +++ b/Tests/Bench/Bench-Replication.ps1 @@ -34,6 +34,7 @@ # powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1 # ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run # ... -Topology Mesh -PeerSyncInterval 1 variations +# ... -Synchronous NORMAL the servers' Synchronous (FULL by default) # ... -Names Wildcard each server only names its own nodes, and # takes the others' by AcceptNodes = n* # ... -Parts Ramp only part 1 @@ -62,6 +63,10 @@ param( [int]$PushSeconds = 30, [int]$PeerSyncInterval = 5, [int]$PeerBatchSize = 100, + # The servers' [BakaShrot.Server] Synchronous: FULL like their default, + # NORMAL to compare with the runs from before 2026-11-09. + [ValidateSet("FULL", "NORMAL")] + [string]$Synchronous = "FULL", [int]$PortBase = 13001, [string]$Ramp = "5x5,5x20,5x50,5x100,5x0,10x20,10x50,10x100,10x0", [int[]]$SeedTotals = @(250000, 1000000), @@ -138,7 +143,7 @@ function Invoke-Build { @("Tests\Bench\BenchServer.pb", "BenchServer.exe", @("/CONSOLE", "/THREAD")), @("Tests\Bench\BenchClient.pb", "BenchClient.exe", @("/CONSOLE", "/THREAD")), @("Tests\Bench\BenchSeed.pb", "BenchSeed.exe", @("/CONSOLE")), - @("Tools\KeyGen\KeyGen.pb", "KeyGen.exe", @("/CONSOLE")))) { + @("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE")))) { Write-Host "Compiling $($Item[0])" $Flags = $Item[2] + $Extra & $Pb (Join-Path $Root $Item[0]) @Flags /QUIET $OutputFlag (Join-Path $OutDir $Item[1]) @@ -147,8 +152,8 @@ function Invoke-Build { } function New-KeyPair { - $Lines = & (Join-Path $OutDir "KeyGen.exe") - if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" } + $Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe") + if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" } return @{ PrivateKey = $Lines[0] -replace "^PrivateKey = ", "" PublicKey = $Lines[1] -replace "^PublicKey = ", "" @@ -203,7 +208,17 @@ function New-Servers { function Write-ServerConfig($Server, $Servers, $ClientKeys) { $LastNode = $Server.FirstNode + $MaxNodesPerServer - 1 - $Identities = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { "${TopicId}:$_" }) -join ";" + # The bench's one key writes as every node: a client section per node. + $ClientSections = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { @" +[BakaShrot.Client.bench$_] +PublicKeys = $($ClientKeys.PublicKey) +Node = $_ +DefaultTopic = $TopicId +AllowRead = 1 +AllowWrite = 1 +AllowQuery = 1 + +"@ }) -join "`r`n" # Only named topics and nodes replicate, and they must be named on both # ends (Declared): every server names every node of every server, with @@ -224,7 +239,6 @@ function Write-ServerConfig($Server, $Servers, $ClientKeys) { $Text = @" [BakaShrot] PrivateKey = $($Server.PrivateKey) -Topic = $TopicId Node = $($Server.NodeId) [BakaShrot.Topics] @@ -241,14 +255,9 @@ DatabasePath = $($Server.DatabasePath) PeerRetryDelay = 2 PeerSyncInterval = $PeerSyncInterval PeerBatchSize = $PeerBatchSize +Synchronous = $Synchronous -[BakaShrot.Client.bench] -PublicKeys = $($ClientKeys.PublicKey) -Identities = $Identities -AllowRead = 1 -AllowWrite = 1 -AllowQuery = 1 - +$ClientSections "@ foreach ($PeerIndex in $Server.Peers) { $Peer = $Servers[$PeerIndex] @@ -256,14 +265,13 @@ AllowQuery = 1 [BakaShrot.Peer.$($Peer.Name)] Host = 127.0.0.1 Port = $($Peer.Port) -Topic = $TopicId Node = $($Peer.NodeId) PublicKey = $($Peer.PublicKey) $(if ($Names -eq "Wildcard") { "AcceptNodes = n*" }) [BakaShrot.Client.$($Peer.Name)] PublicKeys = $($Peer.PublicKey) -Identities = ${TopicId}:$($Peer.NodeId) +Node = $($Peer.NodeId) AllowRead = 0 AllowWrite = 0 AllowQuery = 0 diff --git a/Tests/Bench/BenchClient.pb b/Tests/Bench/BenchClient.pb index 9d07018..f456788 100644 --- a/Tests/Bench/BenchClient.pb +++ b/Tests/Bench/BenchClient.pb @@ -35,7 +35,7 @@ ; FirstNode, MaxNodes Its nodes are FirstNode to FirstNode+MaxNodes-1, ; all of them are monitored. ; NodeCount How many of them push in this stage, from FirstNode. -; MonitorNode, QueryNode Identities used by the sampler and the queries. +; MonitorNode, QueryNode Nodes used by the sampler and the queries. ; QueryLoad, Query 0/1, see above. ; ; Query file: one query per line, "Name | SQL", # starts a comment. @@ -312,7 +312,6 @@ EndProcedure Procedure.i Bench_Connect(*Outbound.BakaShrot_Outbound, *Server.BenchServer, NodeId.i) Protected Identity.BakaShrot_OutboundIdentity - Identity\Topic = Str(Bench_TopicId) Identity\Node = Str(NodeId) Identity\PublicKey = Bench_PublicKey Identity\PrivateKey = @Bench_PrivateKey(0) diff --git a/Tests/BigMessages-Test.ps1 b/Tests/BigMessages-Test.ps1 index 9dcf3f3..36b8c78 100644 --- a/Tests/BigMessages-Test.ps1 +++ b/Tests/BigMessages-Test.ps1 @@ -21,7 +21,7 @@ $MaxPacketSize = 16 * 1024 * 1024 $MaxMessageSize = $MaxPacketSize - 4096 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -63,7 +63,7 @@ function Wait-Port($Port, $S) { } function Query($Sql, $Ini) { $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql - Tool "Query.exe" @("@$F", $Ini) + Tool "BakaShrotQuery.exe" @("@$F", $Ini) } # Waits until Sql answers something matching Pattern, for up to Seconds. function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) { @@ -75,7 +75,7 @@ function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) { } while ((Get-Date) -lt $D) $R } -# A JSON message of exactly Size bytes, in a file, as PushMessage's @File. +# A JSON message of exactly Size bytes, in a file, as BakaShrotPushMessage's @File. function New-Message($Name, [int]$Size) { $P = Join-Path $Dir "$Name.json" $Head = '{"n":"' + $Name + '","pad":"' @@ -112,7 +112,6 @@ $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($A.Priv) -Topic = logs Node = serverA [BakaShrot.Topics] @@ -134,17 +133,18 @@ PeerRetryDelay = 1 [BakaShrot.Peer.b] Host = 127.0.0.1 Port = 12404 -Topic = logs Node = serverB PublicKey = $($B.Pub) [BakaShrot.Client.b] PublicKeys = $($B.Pub) -Identities = logs:serverB +Node = serverB +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs ReadTopics = * AllowQuery = 1 "@ @@ -152,7 +152,6 @@ AllowQuery = 1 Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($B.Priv) -Topic = logs Node = serverB [BakaShrot.Topics] @@ -174,17 +173,18 @@ PeerRetryDelay = 1 [BakaShrot.Peer.a] Host = 127.0.0.1 Port = 12403 -Topic = logs Node = serverA PublicKey = $($A.Pub) [BakaShrot.Client.a] PublicKeys = $($A.Pub) -Identities = logs:serverA +Node = serverA +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs ReadTopics = * AllowQuery = 1 "@ @@ -192,7 +192,7 @@ AllowQuery = 1 $ServerKeys = @{ 12403 = $A.Pub; 12404 = $B.Pub } function Client-Ini($Name, $Port) { $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" $P } $OnA = Client-Ini "kitchen-a" 12403 @@ -222,15 +222,15 @@ try { $Id = 0 foreach ($N in $Sizes.Keys) { $Id++ - $T = Measure-Command { $R = Tool "PushMessage.exe" @($Files[$N], $OnA) } + $T = Measure-Command { $R = Tool "BakaShrotPushMessage.exe" @($Files[$N], $OnA) } Expect ("push of {0:N0} bytes ({1:N0} ms)" -f $Sizes[$N], $T.TotalMilliseconds) $R "message #$Id" } - Expect "a push 1 byte over the cap is refused" (Tool "PushMessage.exe" @($Over, $OnA)) "too big" 1 + Expect "a push 1 byte over the cap is refused" (Tool "BakaShrotPushMessage.exe" @($Over, $OnA)) "too big" 1 $Id++ - Expect "a small push after them" (Tool "PushMessage.exe" @($Small, $OnA)) "message #$Id" + Expect "a small push after them" (Tool "BakaShrotPushMessage.exe" @($Small, $OnA)) "message #$Id" "--- Read back" - $T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 } + $T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 } $Code = $LASTEXITCODE Check "latest is the small one" ($Code -eq 0 -and ($O -join "") -match '"n":"small"') ($O -join " | ") $R = Query "SELECT message_id, length(message_data) FROM data WHERE node_id = 2 ORDER BY message_id" $OnA @@ -245,25 +245,25 @@ try { "--- Read back the biggest, from B" # Pushed after the small one, so it's the latest. $Id++ - Expect "push the biggest again" (Tool "PushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id" + Expect "push the biggest again" (Tool "BakaShrotPushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id" $null = Wait-Query "SELECT max(message_id) FROM data WHERE node_id = 30" $OnB "`"$Id`"" 60 - $T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 } + $T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 } $Code = $LASTEXITCODE $Json = if ($O.Count -ge 2) { [string]$O[1] } else { "" } - Check ("GetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars") + Check ("BakaShrotGetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars") "--- Many small ones still go in batches" - 1..30 | ForEach-Object { $null = Tool "PushMessage.exe" @($Small, $OnA) } + 1..30 | ForEach-Object { $null = Tool "BakaShrotPushMessage.exe" @($Small, $OnA) } $R = Wait-Query "SELECT count(*) FROM data WHERE node_id = 30" $OnB '"35"' 30 Expect "35 on B" $R '\[\["35"\]\]' "--- Not JSON: stored as is, flagged" - Expect "1 MB of broken JSON is stored" (Tool "PushMessage.exe" @("@$Broken", $OnA)) "message #36" - Expect "plain text is stored" (Tool "PushMessage.exe" @("@$Text", $OnA)) "message #37" + Expect "1 MB of broken JSON is stored" (Tool "BakaShrotPushMessage.exe" @("@$Broken", $OnA)) "message #36" + Expect "plain text is stored" (Tool "BakaShrotPushMessage.exe" @("@$Text", $OnA)) "message #37" Expect "flagged is_json = 0 on A, the rest 1" (Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 2 AND message_id >= 35 ORDER BY message_id" $OnA) '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]' $R = Wait-Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 30 AND message_id >= 35 ORDER BY message_id" $OnB '"37"' 30 Expect "replicated and flagged the same on B" $R '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]' - $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 + $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 Check "read back as is from B" ($LASTEXITCODE -eq 0 -and [string]$O[1] -eq "just some text, not JSON") ($O -join " | ") "--- is_json for the edge cases (SQLite's json_valid(), RFC 8259)" @@ -275,7 +275,7 @@ try { $Id++ $F = Join-Path $Dir "case$Id.txt" [IO.File]::WriteAllText($F, $C[0]) - $R = Tool "PushMessage.exe" @("@$F", $OnA) + $R = Tool "BakaShrotPushMessage.exe" @("@$F", $OnA) $Q = Query "SELECT is_json FROM data WHERE node_id = 2 AND message_id = $Id" $OnA Check ("'{0}' stored, is_json = {1}" -f $C[0], $C[1]) ($R.Out -match "message #$Id" -and $Q.Out -match ('"rows":\[\["{0}"\]\]' -f $C[1])) ($R.Out + " / " + $Q.Out) } @@ -303,7 +303,7 @@ function Read-Log($Name) { $L = @(Get-Content (Join-Path $Dir "$Name.log")) $End = [array]::IndexOf($L, "Stopping...") if ($End -lt 0) { $End = $L.Count } - while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Retrying|disconnected|aborted|didn't answer") { $End-- } + while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Dropping the link|Retrying|disconnected|aborted|didn't answer") { $End-- } ($L[0..([math]::Max($End - 1, 0))]) -join "`n" } $LogA = Read-Log "a" diff --git a/Tests/GetMessages-Test.ps1 b/Tests/GetMessages-Test.ps1 index bb715be..ed5662f 100644 --- a/Tests/GetMessages-Test.ps1 +++ b/Tests/GetMessages-Test.ps1 @@ -1,6 +1,6 @@ # End-to-end test of reading runs of messages: the GetMessages request # (Commons/Networking/Packets/GetMessagesPacket.pbi), through the client DLL -# and Tools\GetMessages: from the start, after an id, after the latest one, +# and Tools\BakaShrotGetMessages: from the start, after an id, after the latest one, # with a limit, answers split at ~1 MB, data that isn't JSON or spans lines, # refusals, and --follow picking up new pushes. # Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1, @@ -17,7 +17,7 @@ $Port = 12405 $Fails = 0 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -37,7 +37,7 @@ function Check([string]$What, [bool]$Ok, [string]$Detail) { function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) { Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out) } -# The ids GetMessages printed, in order. +# The ids BakaShrotGetMessages printed, in order. function Ids($Result) { @($Result.Lines | Where-Object { $_ -match "^\d+`t" } | ForEach-Object { [long]($_ -split "`t", 2)[0] }) } @@ -51,7 +51,7 @@ function Push($Data, $Ini, [string]$Topic = "") { [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) $A = @() if ($Topic) { $A += @("-t", $Topic) } - Tool "PushMessage.exe" ($A + @("@$F", $Ini)) + Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) } $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair @@ -59,7 +59,6 @@ $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($S.Priv) -Topic = logs Node = server [BakaShrot.Topics] @@ -79,20 +78,22 @@ DatabasePath = $(Join-Path $Dir "server.sqlite") [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs PushTopics = logs;secret ReadTopics = * AllowQuery = 1 [BakaShrot.Client.lounge] PublicKeys = $($L.Pub) -Identities = logs:lounge +Node = lounge +DefaultTopic = logs ReadTopics = logs "@ function Client-Ini($Name, $Keys) { $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)" $P } $Kitchen = Client-Ini "kitchen" $K @@ -114,10 +115,10 @@ try { # --- Nothing yet ---------------------------------------------------------- - $R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen) Check "No messages yet: nothing printed, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen) Check "--after latest with no messages yet: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) # --- 120 small ones ------------------------------------------------------- @@ -130,50 +131,50 @@ try { } Check "120 pushes" ($Pushed -eq 120) ("{0} pushed in {1:N1} s" -f $Pushed, ((Get-Date) - $Started).TotalSeconds) - $R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen) $Ids = Ids $R Check "Default: the first 100, in order" ($R.Code -eq 0 -and (Is-Run $Ids 1 100)) ("[{0}] {1} ids, {2}..{3}" -f $R.Code, $Ids.Count, $Ids[0], $Ids[-1]) Check "Each line is the id, a tab and the data as stored" ($R.Lines[0] -eq "1`t{`"i`":1}" -and $R.Lines[99] -eq "100`t{`"i`":100}") ("'{0}' / '{1}'" -f $R.Lines[0], $R.Lines[99]) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen) Check "--limit 0: all 120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen) Check "--after 115: 116-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 116 120)) ("[{0}] {1}" -f $R.Code, $R.Out) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen) Check "--after 10 --limit 7: 11-17" ($R.Code -eq 0 -and (Is-Run (Ids $R) 11 17)) ("[{0}] {1}" -f $R.Code, $R.Out) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen) Check "--after the last one: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen) Check "--after latest: nothing" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) - $R = Tool "GetMessages.exe" @("1", "5", "--after", "118", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("1", "5", "--after", "118", $Kitchen) Check "By ids (1, 5): 119-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 119 120)) ("[{0}] {1}" -f $R.Code, $R.Out) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge) Check "Another client allowed to read logs: 101-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 101 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count) # --- Refusals ------------------------------------------------------------- $null = Push '{"s":1}' $Kitchen "secret" - $R = Tool "GetMessages.exe" @("secret", "kitchen", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Kitchen) Check "A topic in ReadTopics (*): read" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 1)) ("[{0}] {1}" -f $R.Code, $R.Out) - Expect "A topic not in ReadTopics: refused" (Tool "GetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1 - Expect "Unknown node: refused" (Tool "GetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1 - Expect "Unknown topic: refused" (Tool "GetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1 - $R = Tool "GetMessages.exe" @("logs", "empty", $Kitchen) + Expect "A topic not in ReadTopics: refused" (Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1 + Expect "Unknown node: refused" (Tool "BakaShrotGetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1 + Expect "Unknown topic: refused" (Tool "BakaShrotGetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1 + $R = Tool "BakaShrotGetMessages.exe" @("logs", "empty", $Kitchen) Check "A known node with no messages: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out) - Expect "Bad --after: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1 - Expect "Unknown option: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1 + Expect "Bad --after: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1 + Expect "Unknown option: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1 # --- Data that isn't one line of JSON ------------------------------------- $null = Push "plain text, not JSON" $Kitchen $null = Push "two`nlines" $Kitchen - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen) Check "Non-JSON data printed as stored, a line break spans lines" ( $R.Code -eq 0 -and $R.Lines.Count -eq 3 -and $R.Lines[0] -eq "121`tplain text, not JSON" -and $R.Lines[1] -eq "122`ttwo" -and $R.Lines[2] -eq "lines" ) ($R.Lines -join " / ") @@ -189,7 +190,7 @@ try { } Check "6 big pushes (5 x 600 KB, 3 MB)" ($BigOk -eq 6) "$BigOk pushed" - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen) $Ids = Ids $R $Lengths = @($R.Lines | ForEach-Object { (($_ -split "`t", 2)[1]).Length }) $WantLengths = @($Sizes | ForEach-Object { $_ }) @@ -197,13 +198,13 @@ try { $R.Code -eq 0 -and (Is-Run $Ids 123 128) -and (($Lengths -join ",") -eq ($WantLengths -join ",")) ) ("[{0}] ids {1}, lengths {2}" -f $R.Code, ($Ids -join ","), ($Lengths -join ",")) - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen) Check "--limit 2 over big ones: 123-124" ($R.Code -eq 0 -and (Is-Run (Ids $R) 123 124)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count) # --- --follow --------------------------------------------------------------- $FollowOut = Join-Path $Dir "follow.out" - $Follower = Start-Process -FilePath (Join-Path $Build "GetMessages.exe") ` + $Follower = Start-Process -FilePath (Join-Path $Build "BakaShrotGetMessages.exe") ` -ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" ` -WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru $null = $Follower.Handle diff --git a/Tests/HandshakeTest.pb b/Tests/HandshakeTest.pb index ba85666..afa62cd 100644 --- a/Tests/HandshakeTest.pb +++ b/Tests/HandshakeTest.pb @@ -54,7 +54,6 @@ Check(Bool(OpenCryptRandom()), "Opened the secure random generator") ; --- 1. Client -> Server: Hello --------------------------------------------- -ClientHello\ClientTopic = "logs" ClientHello\ClientNode = "34" ClientHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5" Check(Bool(CryptRandomData(@ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize)), "Client made a session key") @@ -69,7 +68,6 @@ MsgPackFree(*View, #False) FreeMemory(*Wire) Check(Bool(*ServerHello), "Server decoded the hello") -Check(Bool(*ServerHello\ClientTopic = "logs"), "Hello's ClientTopic survived") Check(Bool(*ServerHello\ClientNode = "34"), "Hello's ClientNode survived") Check(Bool(*ServerHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"), "Hello's ClientPubKeyB64 survived") Check(CompareMemory(@*ServerHello\ClientSessionKey[0], @ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize), "Hello's ClientSessionKey survived") diff --git a/Tests/Names-Test.ps1 b/Tests/Names-Test.ps1 index e72d19f..b408476 100644 --- a/Tests/Names-Test.ps1 +++ b/Tests/Names-Test.ps1 @@ -14,7 +14,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe" $Fails = 0 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -52,16 +52,15 @@ function Wait-Port($Port, $S) { } function Query($Sql, $Ini) { $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql - Tool "Query.exe" @("@$F", $Ini) + Tool "BakaShrotQuery.exe" @("@$F", $Ini) } -$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair; $R = New-KeyPair # --- Server A: new keys, logs = 1, sensors = 2 ----------------------------- Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($A.Priv) -Topic = logs Node = serverA [BakaShrot.Topics] @@ -78,6 +77,7 @@ garage = 5 kitchen-2 = 6 blocal = 20 bsecret = 21 +reader = 30 [BakaShrot.Server] Host = 127.0.0.1 @@ -90,30 +90,39 @@ PeerRetryDelay = 1 [BakaShrot.Peer.b] Host = 127.0.0.1 Port = 12402 -Topic = logs Node = serverB PublicKey = $($B.Pub) AcceptTopics = logs [BakaShrot.Client.b] PublicKeys = $($B.Pub) -Identities = logs:serverB +Node = serverB +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs PushTopics = logs;sensors* ReadTopics = * AllowQuery = 1 [BakaShrot.Client.kitchen2] PublicKeys = $($K2.Pub) -Identities = logs:kitchen-2 +Node = kitchen-2 +DefaultTopic = logs PushTopics = logs;sensors.temp [BakaShrot.Client.garage] PublicKeys = $($G.Pub) -Identities = logs:garage +Node = garage +DefaultTopic = logs + +; No DefaultTopic: its pushes must name their topic. +[BakaShrot.Client.reader] +PublicKeys = $($R.Pub) +Node = reader +PushTopics = logs "@ # --- Server B: the old key names, logs = 200, sensors = 201 ---------------- @@ -125,7 +134,6 @@ function Write-B([string]$Kitchen) { Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($B.Priv) -TopicId = logs NodeId = serverB [BakaShrot.Topics] @@ -151,7 +159,6 @@ PeerRetryDelay = 1 [BakaShrot.Peer.a] Host = 127.0.0.1 Port = 12401 -TopicId = logs NodeId = serverA PublicKey = $($A.Pub) AcceptTopics = logs;sensors;sensors.* @@ -160,11 +167,30 @@ SendNodes = blocal;9 [BakaShrot.Client.a] PublicKeys = $($A.Pub) -Identities = logs:serverA +Node = serverA +DefaultTopic = logs +; One key, three nodes: a section each. [BakaShrot.Client.local] PublicKeys = $($BC.Pub) -Identities = sensors:blocal;logs:9;logs:bsecret +Node = blocal +DefaultTopic = sensors +PushTopics = sensors;logs;extra +ReadTopics = * +AllowQuery = 1 + +[BakaShrot.Client.local9] +PublicKeys = $($BC.Pub) +Node = 9 +DefaultTopic = logs +PushTopics = sensors;logs;extra +ReadTopics = * +AllowQuery = 1 + +[BakaShrot.Client.localsecret] +PublicKeys = $($BC.Pub) +Node = bsecret +DefaultTopic = logs PushTopics = sensors;logs;extra ReadTopics = * AllowQuery = 1 @@ -172,13 +198,14 @@ AllowQuery = 1 } Write-B "7" -# New key names, except garage's (TopicId / NodeId, by ids). +# New key names, except garage's (NodeId, by id). No Topic: the server's +# DefaultTopic for each client says where its pushes go. $ServerKeys = @{ 12401 = $A.Pub; 12402 = $B.Pub } function Client-Ini($Name, $Keys, $Topic, $Node, $Port, [switch]$OldKeys) { $P = Join-Path $Dir "$Name.ini" - $TK = "Topic"; $NK = "Node" - if ($OldKeys) { $TK = "TopicId"; $NK = "NodeId" } - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$TK = $Topic`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + $NK = "Node" + if ($OldKeys) { $NK = "NodeId" } + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" $P } $Kitchen = Client-Ini "kitchen" $K "logs" "kitchen" 12401 @@ -187,6 +214,9 @@ $Local = Client-Ini "local" $BC "sensors" "blocal" 12402 $Anon = Client-Ini "anon" $BC "logs" "9" 12402 $BSecret = Client-Ini "bsecret" $BC "logs" "bsecret" 12402 $Kitchen2 = Client-Ini "kitchen2" $K2 "logs" "kitchen-2" 12401 +$Reader = Client-Ini "reader" $R "logs" "reader" 12401 +# reader's key, but kitchen's node: its section only gives it reader. +$Impostor = Client-Ini "impostor" $R "logs" "kitchen" 12401 Set-Content (Join-Path $Dir "m1.json") -Encoding Ascii -Value '{"temp":21}' Set-Content (Join-Path $Dir "m2.json") -Encoding Ascii -Value '{"temp":22,"where":"kitchen"}' Set-Content (Join-Path $Dir "m3.json") -Encoding Ascii -Value '{"from":"b-local"}' @@ -196,59 +226,64 @@ $SA = Start-Srv "a"; $SB = Start-Srv "b" try { Wait-Port 12401 $SA; Wait-Port 12402 $SB "--- Server A: pushes and the push filter" - Expect "kitchen pushes into its own topic (logs)" (Tool "PushMessage.exe" @($M1, $Kitchen)) "message #1" - Expect "kitchen pushes into sensors by name" (Tool "PushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1" - Expect "kitchen pushes into logs by id" (Tool "PushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2" - Expect "kitchen can't push into secret" (Tool "PushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1 - Expect "unknown topic refused" (Tool "PushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "Unknown topic 'nope'" 1 - Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "PushMessage.exe" @($M1, $Garage)) "message #1" - Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1" - Expect "kitchen-2 pushes into logs" (Tool "PushMessage.exe" @($M1, $Kitchen2)) "message #1" - Expect "kitchen-2 pushes into sensors.temp" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1" - Expect "kitchen-2 can't push into sensors" (Tool "PushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1 + Expect "kitchen pushes into its own topic (logs)" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen)) "message #1" + Expect "kitchen pushes into sensors by name" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1" + Expect "kitchen pushes into logs by id" (Tool "BakaShrotPushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2" + Expect "kitchen can't push into secret" (Tool "BakaShrotPushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1 + Expect "unknown topic refused, with its code" (Tool "BakaShrotPushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "\(UnknownName\): Unknown topic 'nope'" 1 + Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Garage)) "message #1" + Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1" + Expect "kitchen-2 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen2)) "message #1" + Expect "kitchen-2 pushes into sensors.temp" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1" + Expect "kitchen-2 can't push into sensors" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1 + + "--- Server A: identities (a node per key, the default topic the server's)" + Expect "reader (no DefaultTopic) can't push without naming a topic" (Tool "BakaShrotPushMessage.exe" @($M1, $Reader)) "\(NoDefaultTopic\): No default topic for this client" 1 + Expect "reader pushes when it names one" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Reader)) "message #1" + Expect "reader's key can't write as kitchen" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Impostor)) "Failed to connect and authenticate to [^ ]+ \(AuthRejected\)" 1 "--- Server A: reads and the read filter" - Expect "garage reads logs:kitchen by name" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)" - Expect "garage reads it by ids, case-insensitive name" (Tool "GetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2" - Expect "garage can't read sensors (default ReadTopics)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1 - Expect "kitchen reads sensors (ReadTopics = *)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)" + Expect "garage reads logs:kitchen by name" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)" + Expect "garage reads it by ids, case-insensitive name" (Tool "BakaShrotGetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2" + Expect "garage can't read sensors (default ReadTopics)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1 + Expect "kitchen reads sensors (ReadTopics = *)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)" "--- Server A: resolving and listing" - Expect "kitchen resolves topic sensors" (Tool "Resolve.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2" - Expect "kitchen resolves topic id 1" (Tool "Resolve.exe" @("topic", "1", $Kitchen)) "topic logs = 1" - Expect "kitchen resolves node garage" (Tool "Resolve.exe" @("node", "garage", $Kitchen)) "node garage = 5" - Expect "garage can't resolve sensors (no access)" (Tool "Resolve.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1 - Expect "kitchen can resolve secret (it may query)" (Tool "Resolve.exe" @("topic", "secret", $Kitchen)) "topic secret = 3" - Expect "kitchen lists every topic (it may query)" (Tool "ListNames.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config" - Expect "garage lists only the topics it can use" (Tool "ListNames.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs" - Expect "the nodes, as JSON" (Tool "ListNames.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])' + Expect "kitchen resolves topic sensors" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2" + Expect "kitchen resolves topic id 1" (Tool "BakaShrotResolveIds.exe" @("topic", "1", $Kitchen)) "topic logs = 1" + Expect "kitchen resolves node garage" (Tool "BakaShrotResolveIds.exe" @("node", "garage", $Kitchen)) "node garage = 5" + Expect "garage can't resolve sensors (no access)" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1 + Expect "kitchen can resolve secret (it may query)" (Tool "BakaShrotResolveIds.exe" @("topic", "secret", $Kitchen)) "topic secret = 3" + Expect "kitchen lists every topic (it may query)" (Tool "BakaShrotList.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config" + Expect "garage lists only the topics it can use" (Tool "BakaShrotList.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs" + Expect "the nodes, as JSON" (Tool "BakaShrotList.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])' "--- Server A: queries by name through the view" Expect "messages view, by names" (Query "SELECT topic, node, message_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $Kitchen) '\[\["logs","kitchen","1"\],\["logs","kitchen","2"\]\]' "--- Replication, A -> B, translated (logs 1 -> 200, kitchen 2 -> 7)" Start-Sleep -Seconds 4 - Expect "B has logs:kitchen, under its own ids" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)" - Expect "B has sensors:kitchen" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)" - Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "GetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1 - Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)" - Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "GetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)" - Expect "B: both new ones" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)" + Expect "B has logs:kitchen, under its own ids" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)" + Expect "B has sensors:kitchen" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)" + Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1 + Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)" + Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)" + Expect "B: both new ones" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)" Expect "B: added from the peer, nothing else" (Query "SELECT 'topic', name, topic_id FROM topics WHERE origin = 'peer' UNION ALL SELECT 'node', name, node_id FROM nodes WHERE origin = 'peer'" $Local) '\[\["topic","sensors.temp","65535"\],\["node","kitchen-2","65535"\]\]' Expect "B's view: same messages by name" (Query "SELECT topic, node, message_id, topic_id, node_id FROM messages WHERE topic = 'sensors'" $Local) '\[\["sensors","kitchen","1","201","7"\]\]' "--- Replication, B -> A: only what A names and takes (AcceptTopics = logs)" - Expect "B's local pushes into sensors" (Tool "PushMessage.exe" @($M3, $Local)) "message #1" - Expect "B's local pushes into logs" (Tool "PushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1" - Expect "B's local pushes into extra" (Tool "PushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1" - Expect "B's unnamed node 9 pushes into logs" (Tool "PushMessage.exe" @($M3, $Anon)) "message #1" - Expect "B's bsecret pushes into logs" (Tool "PushMessage.exe" @($M3, $BSecret)) "message #1" + Expect "B's local pushes into sensors" (Tool "BakaShrotPushMessage.exe" @($M3, $Local)) "message #1" + Expect "B's local pushes into logs" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1" + Expect "B's local pushes into extra" (Tool "BakaShrotPushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1" + Expect "B's unnamed node 9 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $Anon)) "message #1" + Expect "B's bsecret pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $BSecret)) "message #1" Start-Sleep -Seconds 4 - Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}' - Expect "A didn't get sensors:blocal (not accepted)" (Tool "GetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1 - Expect "A didn't get logs:9 (unnamed)" (Tool "GetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1 - Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "GetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1 - Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]' + Expect "A got logs:blocal (ids 1:20)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}' + Expect "A didn't get sensors:blocal (not accepted)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1 + Expect "A didn't get logs:9 (unnamed)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1 + Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1 + Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["logs","reader","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]' } finally { Stop-Srv $SA; Stop-Srv $SB } @@ -258,6 +293,9 @@ $Refusals = @(Get-Content (Join-Path $Dir "a.log"), (Join-Path $Dir "b.log") | S $Ok = $Refusals.Count -eq 0 if (-not $Ok) { $Fails++ } "{0} no replication refusals in either log`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $(if ($Ok) { "none" } else { $Refusals -join " | " }) +$Ok = (Get-Content (Join-Path $Dir "a.log") -Raw) -match "isn't allowed to write as node kitchen with its public key" +if (-not $Ok) { $Fails++ } +"{0} A logged why the impostor was refused" -f $(if ($Ok) { "PASS" } else { "FAIL" }) "A:"; Get-Content (Join-Path $Dir "a.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" } "B:"; Get-Content (Join-Path $Dir "b.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" } @@ -276,8 +314,165 @@ Write-B "7" $SB = Start-Srv "b" try { Wait-Port 12402 $SB - Expect "B starts, kitchen still 7" (Tool "ListNames.exe" @("nodes", $Local)) "\s+7 kitchen\s+config" + Expect "B starts, kitchen still 7" (Tool "BakaShrotList.exe" @("nodes", $Local)) "\s+7 kitchen\s+config" } finally { Stop-Srv $SB } +"--- The old Identities (before protocol 5): refused at start, saying what to write" +(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "Node = garage\r?\nDefaultTopic = logs", "Identities = logs:garage" | Set-Content (Join-Path $Dir "old.ini") -Encoding Ascii +$SO = Start-Srv "old" +$Exited = $SO.P.WaitForExit(10000) +if (-not $Exited) { Stop-Srv $SO } +$Log = Get-Content (Join-Path $Dir "old.log") -Raw +$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "write Node = garage and DefaultTopic = logs instead of Identities = logs:garage" +if (-not $Ok) { $Fails++ } +"{0} refused, with what to write instead`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Identities" | Select-Object -First 1) + +# --- C and D: topics listed without ids, no nodes listed at all ------------ +# The servers pick the ids, the nodes come from the sections (C's own, its +# peer's, its client's), D takes the client's node from C as it comes. +$C = New-KeyPair; $D = New-KeyPair; $KC = New-KeyPair +# LF line endings on purpose: the names sections are read by hand, the +# Preferences library misreads a bare name there (Config.pbi). +function Write-C([string]$Topics, [string]$Sync = "NORMAL") { +$Text = @" +[BakaShrot] +PrivateKey = $($C.Priv) +Node = serverC + +[BakaShrot.Topics] +$Topics + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12401 +ReplicatingTopics = logs +DatabasePath = $(Join-Path $Dir "c.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +Synchronous = $Sync + +[BakaShrot.Peer.d] +Host = 127.0.0.1 +Port = 12402 +Node = serverD +PublicKey = $($D.Pub) + +[BakaShrot.Client.d] +PublicKeys = $($D.Pub) +Node = serverD +AllowWrite = 0 + +[BakaShrot.Client.kitchen] +PublicKeys = $($KC.Pub) +Node = kitchen +DefaultTopic = logs +ReadTopics = * +"@ +[IO.File]::WriteAllText((Join-Path $Dir "c.ini"), ($Text -replace "`r`n", "`n")) +} +Write-C "logs`nsensors" +Set-Content (Join-Path $Dir "d.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($D.Priv) +Node = serverD + +[BakaShrot.Topics] +logs + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = 12402 +ReplicatingTopics = logs +DatabasePath = $(Join-Path $Dir "d.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 + +[BakaShrot.Peer.c] +Host = 127.0.0.1 +Port = 12401 +Node = serverC +PublicKey = $($C.Pub) + +[BakaShrot.Client.c] +PublicKeys = $($C.Pub) +Node = serverC +AllowWrite = 0 + +[BakaShrot.Client.watcher] +PublicKeys = $($KC.Pub) +Node = watcher +ReadTopics = * +"@ +$ServerKeys[12401] = $C.Pub; $ServerKeys[12402] = $D.Pub +$KitchenC = Client-Ini "kitchen-c" $KC "logs" "kitchen" 12401 +$Watcher = Client-Ini "watcher" $KC "logs" "watcher" 12402 + +"--- C and D: names without ids" +$SC = Start-Srv "c"; $SD = Start-Srv "d" +try { + Wait-Port 12401 $SC; Wait-Port 12402 $SD + Expect "C gives the listed topics ids, in order" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config" + Expect "C names its own, its peer's and its client's nodes" (Tool "BakaShrotList.exe" @("nodes", $KitchenC)) "\s1 serverC\s+config.*\s2 serverD\s+config.*\s3 kitchen\s+config" + Expect "kitchen pushes to its DefaultTopic" (Tool "BakaShrotPushMessage.exe" @($M1, $KitchenC)) "message #1" + $Deadline = (Get-Date).AddSeconds(15) + do { + $R = Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Watcher) + if ($R.Code -eq 0) { break } + Start-Sleep -Milliseconds 300 + } while ((Get-Date) -lt $Deadline) + Expect "D took logs:kitchen though it never named kitchen (AcceptNodes = * by default)" $R "logs:kitchen#1 \(ids 1:65535\)" +} finally { + Stop-Srv $SC; Stop-Srv $SD +} + +"--- C again, its topics reordered and a new one first: the ids stay" +Write-C "alpha`nsensors`nlogs" +$SC = Start-Srv "c" +try { + Wait-Port 12401 $SC + Expect "logs and sensors keep 1 and 2, alpha gets 3" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config.*\s3 alpha\s+config" + Expect "kitchen's message still under logs" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $KitchenC)) "logs:kitchen#1 \(ids 1:3\)" +} finally { Stop-Srv $SC } + +"--- Synchronous: C ran with NORMAL, D with the default FULL, OFF is refused" +$Ok = ((Get-Content (Join-Path $Dir "c.log") -Raw) -match "is ready \(synchronous NORMAL\)") -and ((Get-Content (Join-Path $Dir "d.log") -Raw) -match "is ready \(synchronous FULL\)") +if (-not $Ok) { $Fails++ } +"{0} C logged NORMAL, D FULL" -f $(if ($Ok) { "PASS" } else { "FAIL" }) +Write-C "logs" "OFF" +$SO = Start-Srv "c" +$Exited = $SO.P.WaitForExit(10000) +if (-not $Exited) { Stop-Srv $SO } +$Log = Get-Content (Join-Path $Dir "c.log") -Raw +$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "Synchronous = OFF isn't allowed" +if (-not $Ok) { $Fails++ } +"{0} Synchronous = OFF refused at start`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Synchronous" | Select-Object -First 1) + +"--- browse / browse_messages, as a database tool uses them (C stopped)" +$PythonExe = Get-Command python -ErrorAction SilentlyContinue +if ($PythonExe) { + Set-Content (Join-Path $Dir "browse.py") -Encoding Ascii -Value @' +import sqlite3, sys +db = sqlite3.connect(sys.argv[1]) +db.execute("PRAGMA foreign_keys = ON") # like SQLiteStudio +print("rows", db.execute("SELECT COUNT(*) FROM browse").fetchone()[0]) +db.execute("UPDATE browse SET topic = 'logs', node = NULL"); db.commit() +print("logs", db.execute("SELECT node, message_id, attachment_size FROM browse_messages").fetchall()) +db.execute("UPDATE browse SET topic = 'LOGS', node = 'kitchen'"); db.commit() +print("kitchen", db.execute("SELECT node, message_id FROM browse_messages").fetchall()) +try: + db.execute("UPDATE browse SET topic = 'nope'"); db.commit(); print("bad accepted") +except sqlite3.IntegrityError: + print("bad refused") +db.execute("UPDATE browse SET topic = 'sensors', node = NULL"); db.commit() +print("sensors", db.execute("SELECT COUNT(*) FROM browse_messages").fetchone()[0]) +'@ + $Out = (& $PythonExe.Source -B (Join-Path $Dir "browse.py") (Join-Path $Dir "c.sqlite") 2>&1) -join " | " + $Ok = $Out -eq "rows 1 | logs [('kitchen', 1, None)] | kitchen [('kitchen', 1)] | bad refused | sensors 0" + if (-not $Ok) { $Fails++ } + "{0} one row, a topic shows its messages, a node narrows them, an unknown topic is refused`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $Out +} else { + "SKIP browse: no python on the PATH" +} + "" -if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED" } +if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED"; exit 1 } diff --git a/Tests/Python-Test.ps1 b/Tests/Python-Test.ps1 index 9ffde68..d8518e3 100644 --- a/Tests/Python-Test.ps1 +++ b/Tests/Python-Test.ps1 @@ -20,7 +20,7 @@ $Port = 12406 $ProxyPort = 12407 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -33,7 +33,6 @@ $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($S.Priv) -Topic = logs Node = server [BakaShrot.Topics] @@ -52,20 +51,22 @@ DatabasePath = $(Join-Path $Dir "server.sqlite") [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs PushTopics = logs;secret ReadTopics = * AllowQuery = 1 [BakaShrot.Client.lounge] PublicKeys = $($L.Pub) -Identities = logs:lounge +Node = lounge +DefaultTopic = logs ReadTopics = logs "@ function Client-Ini($Name, $Keys) { $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)" $P } $Kitchen = Client-Ini "kitchen" $K @@ -89,7 +90,9 @@ try { & $Python (Join-Path $PSScriptRoot "..\Interactors\Python\check_bakashrot.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $Lounge $Code = $LASTEXITCODE - $Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -match "invalid|unexpected|Failed|decrypt|sealed" }) + # Refusals are expected (the checks ask for them), their codes' names + # (QueryFailed, InvalidRequest) aren't problems. + $Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|Failed|decrypt|sealed" }) if ($Bad.Count) { "FAIL Server log: $($Bad -join ' / ')"; $Code = 1 } else { "PASS Server log: no invalid or unexpected packets" } # The wire: encrypted, tampering and a wrong server key refused. Another diff --git a/Tests/Restart-Test.ps1 b/Tests/Restart-Test.ps1 new file mode 100644 index 0000000..da97026 --- /dev/null +++ b/Tests/Restart-Test.ps1 @@ -0,0 +1,278 @@ +# End-to-end test of a server killed mid-traffic and restarted (a crash, +# not a clean stop): what it acknowledged survives, its ids carry on where +# they stopped, and the two servers catch up with each other both ways. +# +# Two linked servers, A and B, each with its own client node pushing +# (kitchen on A, garage on B: one writer per topic/node pair) through +# Tests/restart_pusher.py, as fast as acknowledgements come back: +# 1. B killed while both push; A keeps pushing while B is down; B +# restarted: every push it acknowledged is there, no gap, its next id +# follows, and both servers end up with the same messages. +# 2. B killed again a fraction of a second into that catch-up, restarted: +# still converges. +# 3. A killed while both push (the other direction), restarted: same. +# The servers are killed with Stop-Process -Force (TerminateProcess), like +# a crash. Synchronous is the default (FULL); a killed process loses +# nothing committed with NORMAL either, only a power loss would. +# +# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe, and Python 3 on the +# PATH (the pushers use Interactors/Python/bakashrot.py). Uses ports +# 12415-12416. +# Usage: powershell -ExecutionPolicy Bypass -File Tests\Restart-Test.ps1 + +param([string]$Build = (Join-Path $PSScriptRoot "..\Build"), [string]$Python = "python") + +$ErrorActionPreference = "Stop" +$Build = (Resolve-Path $Build).Path +$Dir = Join-Path $Build "_restarttest" +Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue +New-Item -ItemType Directory $Dir | Out-Null +$Server = Join-Path $Build "Bench\BenchServer.exe" +$Dll = Join-Path $Build "BakaShrot_Client.dll" +$Pusher = Join-Path $PSScriptRoot "restart_pusher.py" +$Fails = 0 + +$PythonExe = (Get-Command $Python -ErrorAction SilentlyContinue) +if (-not $PythonExe) { "FAIL no Python ($Python), the pushers need it"; exit 1 } +$PythonExe = $PythonExe.Source + +function New-KeyPair { + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") + @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } +} +function Test-Port($P) { + $C = New-Object System.Net.Sockets.TcpClient + try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() } +} +function Tool([string]$Name, [string[]]$A) { + $O = & (Join-Path $Build $Name) @A 2>&1 + @{ Code = $LASTEXITCODE; Out = ($O -join " | ") } +} +function Check([string]$What, [bool]$Ok, [string]$Detail) { + if (-not $Ok) { $script:Fails++ } + "{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail +} +function Start-Srv($Name) { + $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Stop -ErrorAction SilentlyContinue + # Each run its own log, the previous ones are kept for a look. + $script:Runs[$Name] = 1 + [int]$script:Runs[$Name] + $P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir ` + -RedirectStandardOutput (Join-Path $Dir ("{0}.{1}.log" -f $Name, $script:Runs[$Name])) -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Stop = $Stop; Name = $Name } +} +function Stop-Srv($S) { + if ($S.P.HasExited) { return } + Set-Content $S.Stop "x" + if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force } +} +function Kill-Srv($S) { + Stop-Process -Id $S.P.Id -Force + $null = $S.P.WaitForExit(10000) +} +function Wait-Port($Port, $S) { + $D = (Get-Date).AddSeconds(15) + while (-not (Test-Port $Port)) { + if ($S.P.HasExited) { throw "$($S.Name) exited" } + if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" } + Start-Sleep -Milliseconds 100 + } +} +function Query($Sql, $Ini) { + $F = Join-Path $Dir ("q-" + [guid]::NewGuid().ToString("N") + ".sql"); Set-Content $F -Encoding Ascii -Value $Sql + $R = Tool "BakaShrotQuery.exe" @("@$F", $Ini) + Remove-Item $F + $R +} + +# A pusher in the background: Name's out file gets " " per +# acknowledged push, then STOPPED or ERR. +function Start-Pusher($Name, $Ini) { + $Out = Join-Path $Dir "$Name.out"; $Stop = Join-Path $Dir "$Name.stop" + Remove-Item $Out, $Stop -ErrorAction SilentlyContinue + $P = Start-Process -FilePath $PythonExe -ArgumentList "-B", "`"$Pusher`"", "`"$Dll`"", "`"$Ini`"", "`"$Stop`"", "`"$Out`"", $Name ` + -WorkingDirectory $Build -WindowStyle Hidden -PassThru + $null = $P.Handle + @{ P = $P; Out = $Out; Stop = $Stop; Name = $Name } +} +function Stop-Pusher($Pu) { + Set-Content $Pu.Stop "x" + if (-not $Pu.P.WaitForExit(15000)) { Stop-Process -Id $Pu.P.Id -Force } +} +# What a pusher saw: how many acknowledged, the last id and seq, how it ended. +function Read-Pusher($Pu) { + $Lines = @(Get-Content $Pu.Out -ErrorAction SilentlyContinue) + $Acked = @($Lines | Where-Object { $_ -match "^\d+ \d+$" }) + $Last = if ($Acked.Count) { $Acked[-1] -split " " } else { @("0", "0") } + @{ Count = $Acked.Count; LastId = [int64]$Last[0]; LastSeq = [int]$Last[1]; End = [string]($Lines | Select-Object -Last 1) } +} + +# Every node of logs on a server: count, first and last id, and sums over +# the data and the push times, to compare two servers. +$StatsSql = "SELECT node, COUNT(*), MIN(message_id), MAX(message_id), SUM(length(message_data)), SUM(pushed_at % 1000003), SUM(message_id * length(message_data)) FROM messages WHERE topic = 'logs' GROUP BY node ORDER BY node" +function Stats($Ini) { + $R = Query $StatsSql $Ini + if ($R.Code -ne 0) { return "query failed: " + $R.Out } + ($R.Out -replace '^.*"rows":', '') +} +# The highest id and the count of a node on a server. +function Head($Node, $Ini) { + $R = Query "SELECT COUNT(*), COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'logs' AND node = '$Node'" $Ini + if ($R.Out -match '\[\["(\d+)","(\d+)"\]\]') { @{ Count = [int64]$Matches[1]; Max = [int64]$Matches[2] } } else { @{ Count = -1; Max = -1; Out = $R.Out } } +} +# Waits until A and B have the same messages, and at least Kitchen and +# Garage messages of each node. Returns the stats, and whether they matched. +function Wait-Converged($Kitchen, $Garage, $Seconds = 60) { + $D = (Get-Date).AddSeconds($Seconds) + do { + $SA = Stats $OnA; $SB = Stats $OnB + $HK = Head "kitchen" $OnB; $HG = Head "garage" $OnA + if ($SA -eq $SB -and $HK.Count -ge $Kitchen -and $HG.Count -ge $Garage) { return @{ Ok = $true; A = $SA; B = $SB } } + Start-Sleep -Milliseconds 250 + } while ((Get-Date) -lt $D) + @{ Ok = $false; A = $SA; B = $SB } +} +# What a restarted server must show for the node its pusher wrote to: every +# acknowledged push there (ids 1..max without a gap, max at least the last +# acknowledged one, its data the one acknowledged), and at most one more +# (committed, the answer lost with the kill). Leaves the node's head in +# $Survived: a function's return value would take its PASS/FAIL lines too. +function Check-Survived($What, $Node, $Pu, $Ini) { + $Seen = Read-Pusher $Pu + $H = Head $Node $Ini + Check "$What`: every acknowledged push survived, ids without a gap" ` + ($Seen.LastId -gt 0 -and $H.Count -eq $H.Max -and $H.Max -ge $Seen.LastId -and $H.Max -le $Seen.LastId + 1) ` + ("{0} acknowledged, last #{1}; stored {2}, last #{3}; pusher: {4}" -f $Seen.Count, $Seen.LastId, $H.Count, $H.Max, $Seen.End) + $R = Query "SELECT message_data FROM messages WHERE topic = 'logs' AND node = '$Node' AND message_id = $($Seen.LastId)" $Ini + Check "$What`: the last acknowledged one is the one pushed" ($R.Out -match ('\\"seq\\":' + $Seen.LastSeq + '[,}]')) $R.Out + $script:Survived = $H +} + +$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair +$Runs = @{} + +# Topics listed by name, nodes from the sections: a restart must give every +# name its id back, by the database. +function Write-Config($Name, $Keys, $Port, $Node, $PeerName, $PeerPort, $PeerNode, $PeerKey, $ClientNode, $ClientKey) { + Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @" +[BakaShrot] +PrivateKey = $($Keys.Priv) +Node = $Node + +[BakaShrot.Topics] +logs + +[BakaShrot.Server] +Host = 127.0.0.1 +Port = $Port +ReplicatingTopics = logs +DatabasePath = $(Join-Path $Dir "$Name.sqlite") +PeerSyncInterval = 1 +PeerRetryDelay = 1 +PeerBatchSize = 10 + +[BakaShrot.Peer.$PeerName] +Host = 127.0.0.1 +Port = $PeerPort +Node = $PeerNode +PublicKey = $PeerKey + +[BakaShrot.Client.$PeerName] +PublicKeys = $PeerKey +Node = $PeerNode +AllowWrite = 0 + +[BakaShrot.Client.$ClientNode] +PublicKeys = $ClientKey +Node = $ClientNode +DefaultTopic = logs +ReadTopics = * +AllowQuery = 1 +"@ +} +Write-Config "a" $A 12415 "serverA" "b" 12416 "serverB" $B.Pub "kitchen" $K.Pub +Write-Config "b" $B 12416 "serverB" "a" 12415 "serverA" $A.Pub "garage" $G.Pub +Set-Content (Join-Path $Dir "kitchen.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = 12415`r`nServerPublicKey = $($A.Pub)" +Set-Content (Join-Path $Dir "garage.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($G.Priv)`r`nPublicKey = $($G.Pub)`r`nNode = garage`r`nServerHost = 127.0.0.1`r`nServerPort = 12416`r`nServerPublicKey = $($B.Pub)" +$OnA = Join-Path $Dir "kitchen.ini"; $OnB = Join-Path $Dir "garage.ini" +Set-Content (Join-Path $Dir "next.json") -Encoding Ascii -Value '{"after":"restart"}' +$Next = "@" + (Join-Path $Dir "next.json") + +$SA = Start-Srv "a"; $SB = Start-Srv "b" +$Pushers = @() +try { + Wait-Port 12415 $SA; Wait-Port 12416 $SB + + "--- 1. B killed while both push, A keeps pushing, B restarted" + $PK = Start-Pusher "kitchen-1" $OnA; $PG = Start-Pusher "garage-1" $OnB; $Pushers += $PK, $PG + Start-Sleep -Seconds 3 + Kill-Srv $SB + $null = $PG.P.WaitForExit(15000) + Start-Sleep -Seconds 3 # A goes on alone + Stop-Pusher $PK + $KSeen = Read-Pusher $PK + Check "the garage pusher noticed B was gone: ConnectionLostError, code 104" ($PG.P.HasExited -and (Read-Pusher $PG).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PG).End + Check "kitchen kept pushing on A meanwhile" ($KSeen.Count -gt 100 -and $KSeen.End -eq "STOPPED") ("{0} acknowledged" -f $KSeen.Count) + + $SB = Start-Srv "b"; Wait-Port 12416 $SB + Check-Survived "B" "garage" $PG $OnB + $HG = $Survived + $R = Tool "BakaShrotPushMessage.exe" @($Next, $OnB) + Check "B: the next push carries on from the last id" ($R.Out -match "message #$($HG.Max + 1)\b") ("after #{0}: {1}" -f $HG.Max, $R.Out) + $C = Wait-Converged $KSeen.LastId ($HG.Max + 1) + Check "A and B converged (B caught up on kitchen, A on garage)" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B) + + "--- 2. B killed again in the middle of its catch-up" + $Before = (Head "kitchen" $OnB).Count + $PK = Start-Pusher "kitchen-2" $OnA; $Pushers += $PK + Start-Sleep -Seconds 1 + Kill-Srv $SB + Start-Sleep -Seconds 6 # a backlog for B + Stop-Pusher $PK + $Total = (Head "kitchen" $OnA).Max + $SB = Start-Srv "b"; Wait-Port 12416 $SB + # Killed as soon as some of the backlog is in, not all of it. + $D = (Get-Date).AddSeconds(30) + do { + $Mid = Head "kitchen" $OnB + if ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) { Kill-Srv $SB; break } + Start-Sleep -Milliseconds 20 + } while ($Mid.Count -lt $Total -and (Get-Date) -lt $D) + Check "B killed partway through its catch-up" ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) ` + ("B had {0} kitchen messages before, {1} when killed, A {2}" -f $Before, $Mid.Count, $Total) + if (-not $SB.P.HasExited) { Kill-Srv $SB } + $SB = Start-Srv "b"; Wait-Port 12416 $SB + $C = Wait-Converged $Total 0 + Check "B restarted, still converged" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B) + $H = Head "kitchen" $OnB + Check "B's copy of kitchen has no gap" ($H.Count -eq $H.Max -and $H.Max -eq $Total) ("{0} stored, last #{1}, A's last #{2}" -f $H.Count, $H.Max, $Total) + + "--- 3. A killed while both push, B keeps pushing, A restarted" + $PK = Start-Pusher "kitchen-3" $OnA; $PG = Start-Pusher "garage-3" $OnB; $Pushers += $PK, $PG + Start-Sleep -Seconds 3 + Kill-Srv $SA + $null = $PK.P.WaitForExit(15000) + Start-Sleep -Seconds 3 # B goes on alone + Stop-Pusher $PG + $GSeen = Read-Pusher $PG + Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104" ($PK.P.HasExited -and (Read-Pusher $PK).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PK).End + + $SA = Start-Srv "a"; Wait-Port 12415 $SA + Check-Survived "A" "kitchen" $PK $OnA + $HK = $Survived + $R = Tool "BakaShrotPushMessage.exe" @($Next, $OnA) + Check "A: the next push carries on from the last id" ($R.Out -match "message #$($HK.Max + 1)\b") ("after #{0}: {1}" -f $HK.Max, $R.Out) + $C = Wait-Converged ($HK.Max + 1) $GSeen.LastId + Check "A and B converged again" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B) + + "--- Logs" + $Bad = @(Get-ChildItem $Dir -Filter "*.log" | Select-String "Failed|refused|corrupt|malformed" | Where-Object { $_.Line -notmatch "Failed to connect|Lost the link|link to .* failed" }) + Check "no failure in either server's logs, other than the links lost to the kills" ($Bad.Count -eq 0) $(if ($Bad.Count) { ($Bad | Select-Object -First 5 | ForEach-Object { "$($_.Filename): $($_.Line)" }) -join " | " } else { "none" }) +} finally { + foreach ($Pu in $Pushers) { if (-not $Pu.P.HasExited) { Stop-Process -Id $Pu.P.Id -Force } } + Stop-Srv $SA; Stop-Srv $SB +} + +"" +if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" } diff --git a/Tests/Retention-Test.ps1 b/Tests/Retention-Test.ps1 index 38c1226..64c13fd 100644 --- a/Tests/Retention-Test.ps1 +++ b/Tests/Retention-Test.ps1 @@ -1,8 +1,8 @@ # End-to-end test of pushed_at and [BakaShrot.Retention]: # - a database from before pushed_at gets it (the time of the upgrade), and # its ids go on; -# - a push is stamped with the time it arrived (UTC), GetMessages --time -# and GetLatestMessage show it, replication carries it as is; +# - a push is stamped with the time it arrived (UTC), BakaShrotGetMessages +# --time and BakaShrotGetLatestMessage show it, replication carries it as is; # - each server deletes a topic's messages past its own max age (by name, # by pattern, "*"), only its own: the peer keeps its copies; # - after deleting, ids go on, and the peer doesn't send them again; @@ -27,7 +27,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe" $Fails = 0 function New-KeyPair { - $L = & (Join-Path $Build "KeyGen.exe") + $L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe") @{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" } } function Test-Port($P) { @@ -68,7 +68,7 @@ function Wait-Port($Port, $S) { } function Query($Sql, $Ini) { $F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql - Tool "Query.exe" @("@$F", $Ini) + Tool "BakaShrotQuery.exe" @("@$F", $Ini) } # Waits until Sql answers something matching Pattern, for up to Seconds. function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) { @@ -90,7 +90,7 @@ function Push($Data, $Ini, [string]$Topic = "") { [IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false)) $A = @() if ($Topic) { $A += @("-t", $Topic) } - Tool "PushMessage.exe" ($A + @("@$F", $Ini)) + Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini)) } $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair @@ -99,7 +99,6 @@ $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($A.Priv) -Topic = logs Node = serverA [BakaShrot.Topics] @@ -128,17 +127,18 @@ RetentionInterval = 1 [BakaShrot.Peer.b] Host = 127.0.0.1 Port = 12409 -Topic = logs Node = serverB PublicKey = $($B.Pub) [BakaShrot.Client.b] PublicKeys = $($B.Pub) -Identities = logs:serverB +Node = serverB +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs PushTopics = logs;short;keep;late ReadTopics = * AllowQuery = 1 @@ -148,7 +148,6 @@ AllowQuery = 1 Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @" [BakaShrot] PrivateKey = $($B.Priv) -Topic = logs Node = serverB [BakaShrot.Topics] @@ -180,17 +179,18 @@ RetentionInterval = 1 [BakaShrot.Peer.a] Host = 127.0.0.1 Port = 12408 -Topic = logs Node = serverA PublicKey = $($A.Pub) [BakaShrot.Client.a] PublicKeys = $($A.Pub) -Identities = logs:serverA +Node = serverA +DefaultTopic = logs [BakaShrot.Client.kitchen] PublicKeys = $($K.Pub) -Identities = logs:kitchen +Node = kitchen +DefaultTopic = logs ReadTopics = * AllowQuery = 1 "@ @@ -198,7 +198,7 @@ AllowQuery = 1 $ServerKeys = @{ 12408 = $A.Pub; 12409 = $B.Pub } function Client-Ini($Name, $Port) { $P = Join-Path $Dir "$Name.ini" - Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" + Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])" $P } $OnA = Client-Ini "kitchen-a" 12408 @@ -253,17 +253,17 @@ try { $Expected = [DateTimeOffset]::FromUnixTimeMilliseconds($Stamp).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ") Check "the view's pushed_utc is the same, as text" ($Utc -eq $Expected) "$Utc, expected $Expected" - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA) - Check "GetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out - $R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA) - Check "GetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out - Expect "GetLatestMessage shows it" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected)) + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA) + Check "BakaShrotGetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out + $R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA) + Check "BakaShrotGetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out + Expect "BakaShrotGetLatestMessage shows it" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected)) $Sql = "SELECT message_id, pushed_at FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $OnAStamps = (Query $Sql $OnA).Out $R = Wait-Query $Sql $OnB '"3","\d+"' Check "replicated with the same pushed_at, every one" ($R.Out -eq $OnAStamps) "A $OnAStamps | B $($R.Out)" - Expect "GetLatestMessage on B: the same time" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected)) + Expect "BakaShrotGetLatestMessage on B: the same time" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected)) "--- Retention on A (short = 3s), not on B (short = forever)" foreach ($i in 1..3) { Expect "push short #$i" (Push "{`"short`":$i}" $OnA "short") "message #$i" } @@ -273,7 +273,7 @@ try { Check "A deleted them past 3 s" ($R.Out -match '\[\["0"\]\]') $R.Out Expect "A kept logs (no max age)" (Query (Count "logs") $OnA) '\[\["3"\]\]' Expect "B kept them (its own rules)" (Query (Count "short") $OnB) '\[\["3"\]\]' - Expect "A: no message left in short" (Tool "GetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1 + Expect "A: no message left in short" (Tool "BakaShrotGetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1 Expect "A's ids go on after deleting: #4" (Push '{"short":4}' $OnA "short") "message #4" $R = Wait-Query (Count "short") $OnB '\[\["4"\]\]' 10 Check "B got #4" ($R.Out -match '\[\["4"\]\]') $R.Out @@ -290,7 +290,7 @@ try { Expect "push keep #3" (Push '{"keep":3}' $OnA "keep") "message #3" $R = Wait-Query (Count "keep") $OnB '\[\["1"\]\]' 10 Check "B only got #3, not #1 and #2 again" ($R.Out -match '\[\["1"\]\]') $R.Out - Expect "B: it's #3" (Tool "GetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3" + Expect "B: it's #3" (Tool "BakaShrotGetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3" Expect "B's * = 1h keeps logs" (Query (Count "logs") $OnB) '\[\["3"\]\]' "--- Replicated already past the max age (B: late = 3s)" diff --git a/Tests/restart_pusher.py b/Tests/restart_pusher.py new file mode 100644 index 0000000..15323e6 --- /dev/null +++ b/Tests/restart_pusher.py @@ -0,0 +1,35 @@ +"""Pushes as fast as the server acknowledges, for Tests/Restart-Test.ps1. + +Usage: restart_pusher.py +Pushes {"by": tag, "seq": n} to the client's DefaultTopic until the stop +file exists, writing " " to the out file once each push is +acknowledged. Ends with "STOPPED", or "ERR " when the server +goes away (the test kills it; code 104, ConnectionLost): what was +acknowledged before is what must survive. +""" + +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python")) +from bakashrot import BakaShrotError, Client # noqa: E402 + +dll_path, ini_path, stop_path, out_path, tag = sys.argv[1:6] + +client = Client.from_ini(ini_path, dll_path) +with open(out_path, "a", buffering=1) as out: + try: + client.connect() + seq = 0 + while not os.path.exists(stop_path): + seq += 1 + message_id = client.push({"by": tag, "seq": seq}) + out.write(f"{message_id} {seq}\n") + out.write("STOPPED\n") + except BakaShrotError as error: + out.write(f"ERR {int(error.code)} {type(error).__name__}: {error}\n") + finally: + try: + client.close() + except BakaShrotError: + pass diff --git a/Tests/wire_check.py b/Tests/wire_check.py index 2356e02..0bb2f2b 100644 --- a/Tests/wire_check.py +++ b/Tests/wire_check.py @@ -84,18 +84,21 @@ class Proxy: base = Client.from_ini(ini_path, dll_path) proxy = Proxy(proxy_port, base.host, base.port) marker = "wire-marker-7f3a91" +# The client's DefaultTopic in Python-Test.ps1's server config: its pushes +# land there, and it reads them back from there. +topic = "logs" -client = Client(base.private_key, base.public_key, base.server_public_key, base.topic, base.node, +client = Client(base.private_key, base.public_key, base.server_public_key, base.node, "127.0.0.1", proxy_port, dll_path) # Through the proxy, all of it recorded. try: client.connect() message_id = client.push({"note": marker}) - latest = client.latest(base.topic, base.node) + latest = client.latest(topic, base.node) check("Pushed and read back through the proxy", latest is not None and marker in latest.data, latest.data if latest else "nothing") - pages = client.get_messages(base.topic, base.node, after=message_id - 1, limit=10) + pages = client.get_messages(topic, base.node, after=message_id - 1, limit=10) check("Read as a run of messages too", any(marker in m.data for m in pages.messages)) client.close() except BakaShrotError as error: @@ -104,7 +107,7 @@ except BakaShrotError as error: wire_up, wire_down = bytes(proxy.to_server), bytes(proxy.to_client) check("Something went through both ways", len(wire_up) > 200 and len(wire_down) > 200, f"{len(wire_up)} bytes up, {len(wire_down)} down") -for needle in (marker, str(base.node), str(base.topic), base.public_key): +for needle in (marker, str(base.node), topic, base.public_key): shown = needle.encode("utf-8") check(f"'{needle[:20]}' never in plain text on the wire", shown not in wire_up and shown not in wire_down) @@ -122,7 +125,7 @@ except BakaShrotError as error: check("A tampered request drops the connection", False, "couldn't connect: " + str(error)) # Another server's key: the server can't open the Hello, nor sign for it. -impostor = Client(base.private_key, base.public_key, other_key, base.topic, base.node, +impostor = Client(base.private_key, base.public_key, other_key, base.node, base.host, base.port, dll_path) try: impostor.connect() diff --git a/Tools/KeyGen/KeyGen.pb b/Tools/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb similarity index 90% rename from Tools/KeyGen/KeyGen.pb rename to Tools/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb index 7ce6253..88dae0a 100644 --- a/Tools/KeyGen/KeyGen.pb +++ b/Tools/BakaShrotGenerateKeyPairs/BakaShrotGenerateKeyPairs.pb @@ -1,5 +1,5 @@ ; ============================================================================ -; BakaShrot KeyGen +; BakaShrotGenerateKeyPairs ; ; Generates a new Ed25519 keypair and prints it as two ini-style lines: ; PrivateKey = @@ -13,6 +13,7 @@ EnableExplicit +XIncludeFile "../Common/ToolConsole.pbi" XIncludeFile "../../Commons/Cryptography/Libsodium.pbi" @@ -22,19 +23,19 @@ OpenConsole() If Not InitCryptography() PrintN("Failed to initialize libsodium") - End 1 + ToolConsole_End(1) EndIf *PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize) If Not *PublicKey PrintN("Failed to allocate the public key") - End 1 + ToolConsole_End(1) EndIf *PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize) If Not *PrivateKey PrintN("Failed to allocate the private key") - End 1 + ToolConsole_End(1) EndIf GenerateKeyPair(*PublicKey, *PrivateKey) @@ -47,4 +48,4 @@ FillMemory(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize, 0) FreeMemory(*PrivateKey) FreeMemory(*PublicKey) -End 0 +ToolConsole_End(0) diff --git a/Tools/GetAttachment/GetAttachment.pb b/Tools/BakaShrotGetAttachment/BakaShrotGetAttachment.pb similarity index 86% rename from Tools/GetAttachment/GetAttachment.pb rename to Tools/BakaShrotGetAttachment/BakaShrotGetAttachment.pb index 7384e32..5b05bd1 100644 --- a/Tools/GetAttachment/GetAttachment.pb +++ b/Tools/BakaShrotGetAttachment/BakaShrotGetAttachment.pb @@ -1,7 +1,7 @@ ; ============================================================================ -; BakaShrot GetAttachment +; BakaShrotGetAttachment ; -; Usage: GetAttachment [ClientIni] +; Usage: BakaShrotGetAttachment [ClientIni] ; Topic, Node Whose message, each a name or an id. ; MessageId Which message. ; OutFile Where to save its attachment (replaced). @@ -26,22 +26,22 @@ Define Topic.s, Node.s, MessageText.s, OutFile.s, IniPath.s, MessageId.q, Size.q OpenConsole() If CountProgramParameters() < 4 - PrintN("Usage: GetAttachment [ClientIni]") + PrintN("Usage: BakaShrotGetAttachment [ClientIni]") PrintN(" Topic and Node are names or ids.") - End 1 + ToolConsole_End(1) EndIf Topic = ProgramParameter(0) Node = ProgramParameter(1) If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node) PrintN("Invalid topic or node, expected names or ids 0-65535") - End 1 + ToolConsole_End(1) EndIf MessageText = ProgramParameter(2) MessageId = Val(MessageText) If MessageId < 1 Or Str(MessageId) <> MessageText PrintN("Invalid message id '" + MessageText + "'") - End 1 + ToolConsole_End(1) EndIf OutFile = ProgramParameter(3) @@ -51,7 +51,7 @@ If CountProgramParameters() > 4 EndIf If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf StartTime = ElapsedMilliseconds() @@ -59,10 +59,10 @@ Size = BakaShrot_SaveAttachment(Topic, Node, MessageId, OutFile) If Size < 0 ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf PrintN("Saved " + Str(Size) + " bytes to '" + OutFile + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms") ToolClient_Close() -End 0 +ToolConsole_End(0) diff --git a/Tools/GetLatestMessage/GetLatestMessage.pb b/Tools/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb similarity index 84% rename from Tools/GetLatestMessage/GetLatestMessage.pb rename to Tools/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb index 6beb573..5b58929 100644 --- a/Tools/GetLatestMessage/GetLatestMessage.pb +++ b/Tools/BakaShrotGetLatestMessage/BakaShrotGetLatestMessage.pb @@ -1,12 +1,12 @@ ; ============================================================================ -; BakaShrot GetLatestMessage +; BakaShrotGetLatestMessage ; -; Usage: GetLatestMessage [ClientIni] +; Usage: BakaShrotGetLatestMessage [ClientIni] ; Topic, Node Whose latest message to get, each a name or an id. ; ClientIni Identity and server to use, defaults to "client.ini". ; ; Prints the latest message stored for that topic/node, and when it was -; pushed (UTC), its attachment if it has one (GetAttachment saves it), then +; pushed (UTC), its attachment if it has one (BakaShrotGetAttachment saves it), then ; its data. The server refuses ; if the client's ReadTopics don't allow the topic, if either is unknown, or ; if there's no message. @@ -24,21 +24,21 @@ Define Topic.s, Node.s, IniPath.s OpenConsole() If CountProgramParameters() < 2 - PrintN("Usage: GetLatestMessage [ClientIni]") + PrintN("Usage: BakaShrotGetLatestMessage [ClientIni]") PrintN(" Topic and Node are names or ids.") - End 1 + ToolConsole_End(1) EndIf Topic = ProgramParameter(0) If Not BakaShrot_IsValidRef(Topic) PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") - End 1 + ToolConsole_End(1) EndIf Node = ProgramParameter(1) If Not BakaShrot_IsValidRef(Node) PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535") - End 1 + ToolConsole_End(1) EndIf IniPath = "client.ini" @@ -47,13 +47,13 @@ If CountProgramParameters() > 2 EndIf If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf If Not BakaShrot_GetLatestMessageOf(Topic, Node) ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) + @@ -68,4 +68,4 @@ EndIf PrintN(BakaShrot_GetMessageDataString()) ToolClient_Close() -End 0 +ToolConsole_End(0) diff --git a/Tools/GetMessages/GetMessages.pb b/Tools/BakaShrotGetMessages/BakaShrotGetMessages.pb similarity index 89% rename from Tools/GetMessages/GetMessages.pb rename to Tools/BakaShrotGetMessages/BakaShrotGetMessages.pb index 6eadf76..5cb7233 100644 --- a/Tools/GetMessages/GetMessages.pb +++ b/Tools/BakaShrotGetMessages/BakaShrotGetMessages.pb @@ -1,7 +1,7 @@ ; ============================================================================ -; BakaShrot GetMessages +; BakaShrotGetMessages ; -; Usage: GetMessages [options] [ClientIni] +; Usage: BakaShrotGetMessages [options] [ClientIni] ; Topic, Node Whose messages to get, each a name or an id. ; --after Starts after that message id, defaults to 0: from the ; first one. "latest" starts after the latest one, @@ -41,10 +41,10 @@ OpenConsole() ; Prints the usage and exits. Procedure Usage() - PrintN("Usage: GetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni]") + PrintN("Usage: BakaShrotGetMessages [--after ] [--limit ] [--follow] [--interval ] [--time] [ClientIni]") PrintN(" Topic and Node are names or ids. Prints each message as its id, a tab, and its data.") PrintN(" --time also prints when it was pushed (UTC) between them.") - End 1 + ToolConsole_End(1) EndProcedure ; Whether Text is a whole number of digits, 0 or more. @@ -68,7 +68,7 @@ While i < CountProgramParameters() Case "--after", "--limit", "--interval" If i + 1 >= CountProgramParameters() PrintN("Missing the value of " + Argument) - End 1 + ToolConsole_End(1) EndIf i + 1 Value = ProgramParameter(i) @@ -76,19 +76,19 @@ While i < CountProgramParameters() Case "--after" If LCase(Value) <> "latest" And Not IsNumber(Value) PrintN("Invalid --after '" + Value + "', expected a message id or 'latest'") - End 1 + ToolConsole_End(1) EndIf AfterText = LCase(Value) Case "--limit" If Not IsNumber(Value) PrintN("Invalid --limit '" + Value + "', expected a number") - End 1 + ToolConsole_End(1) EndIf Limit = Val(Value) Case "--interval" If Not IsNumber(Value) Or Val(Value) < 10 Or Val(Value) > 3600000 PrintN("Invalid --interval '" + Value + "', expected 10 to 3600000 ms") - End 1 + ToolConsole_End(1) EndIf IntervalMs = Val(Value) EndSelect @@ -118,11 +118,11 @@ If Positional < 2 EndIf If Not BakaShrot_IsValidRef(Topic) PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") - End 1 + ToolConsole_End(1) EndIf If Not BakaShrot_IsValidRef(Node) PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535") - End 1 + ToolConsole_End(1) EndIf If Limit < 0 If Follow @@ -133,17 +133,18 @@ If Limit < 0 EndIf If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf ; "latest": after the latest message, or from the start if there's none yet. If AfterText = "latest" If BakaShrot_GetLatestMessageOf(Topic, Node) AfterMessageId = BakaShrot_GetMessageId() - ElseIf Not BakaShrot_IsConnected() + ElseIf BakaShrot_GetLastError() <> #BakaShrot_Refused_NotFound + ; Only "no message yet" starts from the start, anything else is told. ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf Else AfterMessageId = Val(AfterText) @@ -160,7 +161,7 @@ Repeat If Count < 0 ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf For n = 0 To Count - 1 @@ -186,4 +187,4 @@ Repeat ForEver ToolClient_Close() -End 0 +ToolConsole_End(0) diff --git a/Tools/ListNames/ListNames.pb b/Tools/BakaShrotList/BakaShrotList.pb similarity index 94% rename from Tools/ListNames/ListNames.pb rename to Tools/BakaShrotList/BakaShrotList.pb index 68b01ac..d431673 100644 --- a/Tools/ListNames/ListNames.pb +++ b/Tools/BakaShrotList/BakaShrotList.pb @@ -1,7 +1,7 @@ ; ============================================================================ -; BakaShrot ListNames +; BakaShrotList ; -; Usage: ListNames [topics|nodes|all] [ClientIni] [--json] +; Usage: BakaShrotList [topics|nodes|all] [ClientIni] [--json] ; topics|nodes|all What to list, defaults to all. ; ClientIni Identity and server to use, defaults to "client.ini". ; --json Prints the DLL's JSON instead of a table. @@ -36,7 +36,7 @@ For i = 0 To CountProgramParameters() - 1 Next If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf ; Prints one list, from the DLL's JSON. @@ -91,6 +91,6 @@ EndIf ToolClient_Close() If Failed - End 1 + ToolConsole_End(1) EndIf -End 0 +ToolConsole_End(0) diff --git a/Tools/BakaShrotList/BakaShrotList.pb.cfg b/Tools/BakaShrotList/BakaShrotList.pb.cfg new file mode 100644 index 0000000..4a6f50c --- /dev/null +++ b/Tools/BakaShrotList/BakaShrotList.pb.cfg @@ -0,0 +1,6 @@ +IDE Options = PureBasic 6.41 (Windows - x64) +CursorPosition = 7 +Folding = - +EnableXP +DPIAware +CompileSourceDirectory diff --git a/Tools/PushMessage/PushMessage.pb b/Tools/BakaShrotPushMessage/BakaShrotPushMessage.pb similarity index 89% rename from Tools/PushMessage/PushMessage.pb rename to Tools/BakaShrotPushMessage/BakaShrotPushMessage.pb index c1a7706..446d0f4 100644 --- a/Tools/PushMessage/PushMessage.pb +++ b/Tools/BakaShrotPushMessage/BakaShrotPushMessage.pb @@ -1,7 +1,7 @@ ; ============================================================================ -; BakaShrot PushMessage +; BakaShrotPushMessage ; -; Usage: PushMessage [-t ] [-a ] [ClientIni] +; Usage: BakaShrotPushMessage [-t ] [-a ] [ClientIni] ; -t Topic The topic to push to, a name or an id. Defaults to the ; client's own topic (its TopicId). The client's PushTopics on ; the server must allow it. @@ -38,14 +38,14 @@ For i = 0 To CountProgramParameters() - 1 Topic = ProgramParameter(i) If Not BakaShrot_IsValidRef(Topic) PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535") - End 1 + ToolConsole_End(1) EndIf ElseIf (Argument = "-a" Or Argument = "--attach") And i < CountProgramParameters() - 1 i + 1 AttachPath = ProgramParameter(i) If FileSize(AttachPath) < 1 PrintN("Can't attach '" + AttachPath + "': no such file, or empty") - End 1 + ToolConsole_End(1) EndIf Else AddElement(Arguments()) @@ -54,16 +54,16 @@ For i = 0 To CountProgramParameters() - 1 Next If ListSize(Arguments()) < 1 - PrintN("Usage: PushMessage [-t ] [-a ] [ClientIni]") + PrintN("Usage: BakaShrotPushMessage [-t ] [-a ] [ClientIni]") PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.") - End 1 + ToolConsole_End(1) EndIf FirstElement(Arguments()) JsonData = Arguments() If Left(JsonData, 1) = "@" If Not ToolClient_ReadTextFile(Mid(JsonData, 2), @FileText) - End 1 + ToolConsole_End(1) EndIf JsonData = FileText\s EndIf @@ -74,7 +74,7 @@ If NextElement(Arguments()) EndIf If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf If AttachPath <> "" @@ -85,7 +85,7 @@ EndIf If MessageId < 1 ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf If AttachPath <> "" @@ -95,4 +95,4 @@ Else EndIf ToolClient_Close() -End 0 +ToolConsole_End(0) diff --git a/Tools/Query/Query.pb b/Tools/BakaShrotQuery/BakaShrotQuery.pb similarity index 86% rename from Tools/Query/Query.pb rename to Tools/BakaShrotQuery/BakaShrotQuery.pb index 99a97a4..ffee09c 100644 --- a/Tools/Query/Query.pb +++ b/Tools/BakaShrotQuery/BakaShrotQuery.pb @@ -1,7 +1,7 @@ ; ============================================================================ -; BakaShrot Query +; BakaShrotQuery ; -; Usage: Query [ClientIni] +; Usage: BakaShrotQuery [ClientIni] ; Sql A single read-only SELECT (or WITH ... SELECT), or @ followed ; by a file holding it. Command-line arguments lose their ; double quotes, use single quotes or @SqlFile. @@ -24,15 +24,15 @@ Define Sql.s, IniPath.s, FileText.String OpenConsole() If CountProgramParameters() < 1 - PrintN("Usage: Query [ClientIni]") + PrintN("Usage: BakaShrotQuery [ClientIni]") PrintN(" Command-line arguments lose their double quotes, use single quotes or @SqlFile.") - End 1 + ToolConsole_End(1) EndIf Sql = ProgramParameter(0) If Left(Sql, 1) = "@" If Not ToolClient_ReadTextFile(Mid(Sql, 2), @FileText) - End 1 + ToolConsole_End(1) EndIf Sql = FileText\s EndIf @@ -43,16 +43,16 @@ If CountProgramParameters() > 1 EndIf If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf If Not BakaShrot_Query(Sql) ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf PrintN(BakaShrot_GetQueryResultString()) ToolClient_Close() -End 0 +ToolConsole_End(0) diff --git a/Tools/Resolve/Resolve.pb b/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb similarity index 84% rename from Tools/Resolve/Resolve.pb rename to Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb index acc6103..d4bac57 100644 --- a/Tools/Resolve/Resolve.pb +++ b/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb @@ -1,7 +1,7 @@ ; ============================================================================ -; BakaShrot Resolve +; BakaShrotResolveIds ; -; Usage: Resolve [ClientIni] +; Usage: BakaShrotResolveIds [ClientIni] ; topic|node What to look up. ; NameOrId A name, to get its id on the server, or an id, to get its name. ; ClientIni Identity and server to use, defaults to "client.ini". @@ -23,20 +23,20 @@ Define Kind.s, Ref.s, IniPath.s, Id.l, Name.s OpenConsole() If CountProgramParameters() < 2 - PrintN("Usage: Resolve [ClientIni]") - End 1 + PrintN("Usage: BakaShrotResolveIds [ClientIni]") + ToolConsole_End(1) EndIf Kind = LCase(ProgramParameter(0)) If Kind <> "topic" And Kind <> "node" PrintN("Expected 'topic' or 'node', not '" + ProgramParameter(0) + "'") - End 1 + ToolConsole_End(1) EndIf Ref = ProgramParameter(1) If Not BakaShrot_IsValidRef(Ref) PrintN("Invalid " + Kind + " '" + Ref + "', expected a name or an id 0-65535") - End 1 + ToolConsole_End(1) EndIf IniPath = "client.ini" @@ -45,7 +45,7 @@ If CountProgramParameters() > 2 EndIf If Not ToolClient_Connect(IniPath) - End 1 + ToolConsole_End(1) EndIf If Kind = "topic" @@ -56,7 +56,7 @@ EndIf If Id < 0 ToolClient_PrintFailure() ToolClient_Close() - End 1 + ToolConsole_End(1) EndIf Name = BakaShrot_GetResolvedNameString() @@ -66,4 +66,4 @@ EndIf PrintN(Kind + " " + Name + " = " + Str(Id)) ToolClient_Close() -End 0 +ToolConsole_End(0) diff --git a/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg b/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg new file mode 100644 index 0000000..7683a01 --- /dev/null +++ b/Tools/BakaShrotResolveIds/BakaShrotResolveIds.pb.cfg @@ -0,0 +1,5 @@ +IDE Options = PureBasic 6.41 (Windows - x64) +CursorPosition = 7 +EnableXP +DPIAware +CompileSourceDirectory diff --git a/Tools/Common/ToolClient.pbi b/Tools/Common/ToolClient.pbi index af868d2..676f145 100644 --- a/Tools/Common/ToolClient.pbi +++ b/Tools/Common/ToolClient.pbi @@ -5,19 +5,41 @@ ; The DLL must be next to the tool, the identity and server come from an ini ; file laid out like the client.ini Build.ps1 writes: ; [BakaShrot] -; PrivateKey, PublicKey, Topic, Node, ServerHost, ServerPort, +; PrivateKey, PublicKey, Node, ServerHost, ServerPort, ; ServerPublicKey (the server's, it logs it when it starts) -; Topic and Node can be names or ids (Commons/Networking/Names.pbi). They -; were TopicId and NodeId before, still read when Topic and Node are missing. +; Node is the node the client writes as, a name or an id +; (Commons/Networking/Names.pbi); NodeId before, still read when Node is +; missing. A Topic (TopicId) left in it is ignored: the client's default +; topic is in the server's config (DefaultTopic). ; ============================================================================ XIncludeFile "../../Client/BakaShrot_Client_Prototypes.pbi" +XIncludeFile "ToolConsole.pbi" + + +; What a client error code (100+, BakaShrot_ErrorCodes.pbi) means, for the +; tools' messages. +Procedure.s ToolClient_Explain(Code.l) + Select Code + Case #BakaShrot_Error_NotConnected : ProcedureReturn "not connected" + Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "nothing answers there" + Case #BakaShrot_Error_AuthRejected : ProcedureReturn "the server closed the connection: wrong ServerPublicKey, a key or node it doesn't allow, or another version (its log says which)" + Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "the server couldn't prove it holds ServerPublicKey's private key" + Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "the connection to the server failed" + Case #BakaShrot_Error_ProtocolError : ProcedureReturn "the server answered something unexpected, the connection is closed" + Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "an invalid argument" + Case #BakaShrot_Error_FileError : ProcedureReturn "a file couldn't be opened, read or written" + Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "the attachment doesn't match its SHA-256" + Case #BakaShrot_Error_Internal : ProcedureReturn "out of memory, or another failure in the client" + EndSelect + ProcedureReturn BakaShrot_ErrorName(Code) +EndProcedure ; Loads the DLL, reads IniPath and connects to its server with its identity. ; Prints what failed and returns #False on failure, the DLL is then unloaded. Procedure.i ToolClient_Connect(IniPath.s) - Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Topic.s, Node.s, ServerHost.s, ServerPort.l + Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l If Not OpenPreferences(IniPath) PrintN("Failed to open '" + IniPath + "'") @@ -27,7 +49,6 @@ Procedure.i ToolClient_Connect(IniPath.s) PrivateKey = ReadPreferenceString("PrivateKey", "") PublicKey = ReadPreferenceString("PublicKey", "") ServerPublicKey = ReadPreferenceString("ServerPublicKey", "") - Topic = Trim(ReadPreferenceString("Topic", ReadPreferenceString("TopicId", ""))) Node = Trim(ReadPreferenceString("Node", ReadPreferenceString("NodeId", ""))) ServerHost = ReadPreferenceString("ServerHost", "") ServerPort = ReadPreferenceLong("ServerPort", 0) @@ -56,12 +77,6 @@ Procedure.i ToolClient_Connect(IniPath.s) ProcedureReturn #False EndIf - If Not BakaShrot_SetTopic(Topic) - PrintN("Invalid Topic '" + Topic + "' in '" + IniPath + "', expected a name or an id") - BakaShrot_UnloadClient() - ProcedureReturn #False - EndIf - If Not BakaShrot_SetNode(Node) PrintN("Invalid Node '" + Node + "' in '" + IniPath + "', expected a name or an id") BakaShrot_UnloadClient() @@ -69,7 +84,7 @@ Procedure.i ToolClient_Connect(IniPath.s) EndIf If Not BakaShrot_Connect(ServerHost, ServerPort) - PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort)) + PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort) + " (" + BakaShrot_ErrorName(BakaShrot_GetLastError()) + "): " + ToolClient_Explain(BakaShrot_GetLastError())) BakaShrot_UnloadClient() ProcedureReturn #False EndIf @@ -93,11 +108,17 @@ EndProcedure ; Prints why the last request failed. +; With its code's name (BakaShrot_ErrorCodes.pbi), for scripts to match on. Procedure ToolClient_PrintFailure() - If BakaShrot_IsConnected() - PrintN("Refused by the server: " + BakaShrot_GetRefusalReasonString()) + Protected Code.l = BakaShrot_GetLastError() + + If BakaShrot_IsRefusalCode(Code) + PrintN("Refused by the server (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString()) + ElseIf BakaShrot_GetRefusalReasonString() <> "" + ; The client's own refusals: a message or attachment over the limits... + PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString()) Else - PrintN("The connection to the server failed") + PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + ToolClient_Explain(Code)) EndIf EndProcedure diff --git a/Tools/Common/ToolConsole.pbi b/Tools/Common/ToolConsole.pbi new file mode 100644 index 0000000..7fe32e9 --- /dev/null +++ b/Tools/Common/ToolConsole.pbi @@ -0,0 +1,56 @@ +; ============================================================================ +; BakaShrot Tools - Console +; +; Shared by every tool. Started from Explorer (a double-click, a shortcut), +; a console program gets a console of its own that closes as soon as it +; ends, before what it printed can be read: ToolConsole_End() waits for +; Enter then, and ends at once otherwise. +; As https://github.com/aziascreations/PB-Template-Win32-CliApp does it: a +; program started from a shell shares the shell's console, one started +; directly is alone in its own. +; ============================================================================ + +CompilerIf #PB_Compiler_OS = #PB_OS_Windows + ; Not in PureBasic 5.73's API functions, named so it can't clash with a + ; compiler that has it. + Import "kernel32.lib" + CompilerIf #PB_Compiler_Processor = #PB_Processor_x86 + ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "_GetConsoleProcessList@8" + CompilerElse + ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "GetConsoleProcessList" + CompilerEndIf + EndImport +CompilerEndIf + + +; #True if the tool was started directly rather than from a shell: it is the +; only process on its console. Input or output redirected is #False, someone +; else reads it (a test starting it with Start-Process gets a new hidden +; console too, alone on it). Always #False outside of Windows. +Procedure.i ToolConsole_IsRunDirectly() + CompilerIf #PB_Compiler_OS = #PB_OS_Windows + Protected Mode.l, ProcessList.q ; ProcessList: room for 2 process ids + + If Not GetConsoleMode_(GetStdHandle_(#STD_INPUT_HANDLE), @Mode) + ProcedureReturn #False + EndIf + If Not GetConsoleMode_(GetStdHandle_(#STD_OUTPUT_HANDLE), @Mode) + ProcedureReturn #False + EndIf + ProcedureReturn Bool(ToolConsole_GetConsoleProcessList(@ProcessList, 2) <= 1) + CompilerElse + ProcedureReturn #False + CompilerEndIf +EndProcedure + + +; Ends the tool with ExitCode, after waiting for Enter if it was started +; directly (ToolConsole_IsRunDirectly()). +Procedure ToolConsole_End(ExitCode.i) + If ToolConsole_IsRunDirectly() + PrintN("") + Print("Press Enter to close...") + Input() + EndIf + End ExitCode +EndProcedure From 5270f25ac18ff322b0236cebcc7fa36cf16be03e Mon Sep 17 00:00:00 2001 From: Herwin Date: Tue, 10 Nov 2026 15:32:22 +0100 Subject: [PATCH 4/5] Fix the server on Linux, and test races it showed Server: - Storage: #BakaShrot_Storage_SqliteLibrary, the SQLite the server loads: sqlite3.dll on Windows, the system's libsqlite3.so.0 on Linux (PB 5.73's bundled 3.33 has no JSON functions). The query error check and the writer's prepared statements use it too, so a JSON function on a row that isn't JSON is refused on Linux as well, not answered with no rows. - SendPacket: SendNetworkData() returns -1 once the send buffer is full (EAGAIN on Linux), which aborted clients reading big answers. Retried until nothing goes out for #BakaShrot_SendStallTimeout (10 s). Tests, timing they relied on: - Attachments, BigMessages: link failures before the first link are expected, Linux refuses at once where Windows retries for ~1 s. - Restart: a pusher whose server is killed between two pushes sees 100 (NotConnected), during one 104 (ConnectionLost): both accepted. - Retention: deletions counted over every retention check, a batch can be split over two. - AttachmentEdges: waits for B's corrupted attachment to be dropped, A sends it again at every check-in. All tests pass on Linux with PB 6.41 (asm and C backends). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RwFeVQCBfcPDfAPqX8z2TF --- Commons/Networking/Connections.pbi | 22 ++++++++++++-- Server/Storage/Storage.pbi | 48 ++++++++++++++++++++---------- Server/Storage/Writer.pbi | 17 +++++------ Tests/AttachmentEdges-Test.ps1 | 4 ++- Tests/Attachments-Test.ps1 | 14 +++++++-- Tests/BigMessages-Test.ps1 | 12 +++++++- Tests/Restart-Test.ps1 | 6 ++-- Tests/Retention-Test.ps1 | 14 +++++++-- Tests/restart_pusher.py | 3 +- 9 files changed, 103 insertions(+), 37 deletions(-) diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi index d501c6f..f16c359 100644 --- a/Commons/Networking/Connections.pbi +++ b/Commons/Networking/Connections.pbi @@ -218,6 +218,11 @@ EndProcedure ; next packets. #BakaShrot_InboxKeptCapacity = 256 * 1024 +; How long a send waits for the other end to make room, without a single +; byte going out, before it gives up. Same as how long a client waits for +; each packet (#BakaShrot_Outbound_Timeout). +#BakaShrot_SendStallTimeout = 10000 + Enumeration BakaShrot_InboxResults #BakaShrot_Inbox_Incomplete #BakaShrot_Inbox_Packet @@ -264,8 +269,13 @@ EndProcedure ; *Cipher is 0: only the Hello (sealed on its own) and the ChallengeRequest. ; Returns #False if the packet is too big, *Cipher isn't set up, or the data ; couldn't be sent. +; PureBasic's sockets don't block: SendNetworkData() returns -1 once the +; system's send buffer is full (EAGAIN on Linux, a few hundred KB), so -1 is +; retried until nothing went out for #BakaShrot_SendStallTimeout. PureBasic +; doesn't tell that from a broken connection, which then takes that long to +; give up on. Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher) - Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i + Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i, LastProgress.i If PacketSize < 1 Or PacketSize > #BakaShrot_MaxPacketSize ProcedureReturn #False @@ -294,13 +304,19 @@ Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher. CopyMemory(*Packet, *Frame + #BakaShrot_FrameHeaderSize, PacketSize) EndIf + LastProgress = ElapsedMilliseconds() While Offset < FrameSize Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset) - If Sent <= 0 + If Sent > 0 + Offset + Sent + LastProgress = ElapsedMilliseconds() + ElseIf ElapsedMilliseconds() - LastProgress > #BakaShrot_SendStallTimeout FreeMemory(*Frame) ProcedureReturn #False + Else + ; Full, until the other end reads some of it. + Delay(1) EndIf - Offset + Sent Wend FreeMemory(*Frame) diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi index 36a5da0..37fc094 100644 --- a/Server/Storage/Storage.pbi +++ b/Server/Storage/Storage.pbi @@ -10,6 +10,11 @@ ; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official ; sqlite3.dll is used instead, it must be next to the program. Build.ps1 ; extracts it from Libs/sqlite-dll-win-*.zip and copies it. +; On Linux, the system's libsqlite3.so.0 (libsqlite3-0 on Debian/Ubuntu, +; sqlite-libs on Fedora) is used, whatever the compiler, it must be 3.38+. +; Either way it's #BakaShrot_Storage_SqliteLibrary, which RunReadOnlyQuery() +; and the writer (Writer.pbi) also call directly. Elsewhere, PureBasic's own +; SQLite is linked in, and they make do without it. ; ; Threads: ONE CONNECTION PER THREAD, never share a handle. ; The SetDatabase*() parameters and query results belong to a handle, so two @@ -30,8 +35,20 @@ XIncludeFile "../../Commons/Networking/Packets/SyncStatePacket.pbi" XIncludeFile "../../Commons/Networking/Packets/ReplicateMessagesPacket.pbi" -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - UseSQLiteDatabase("sqlite3.dll") +CompilerSelect #PB_Compiler_OS + CompilerCase #PB_OS_Windows + #BakaShrot_Storage_ExternalSqlite = #True + #BakaShrot_Storage_SqliteLibrary = "sqlite3.dll" + CompilerCase #PB_OS_Linux + #BakaShrot_Storage_ExternalSqlite = #True + #BakaShrot_Storage_SqliteLibrary = "libsqlite3.so.0" + CompilerDefault + #BakaShrot_Storage_ExternalSqlite = #False + #BakaShrot_Storage_SqliteLibrary = "" +CompilerEndSelect + +CompilerIf #BakaShrot_Storage_ExternalSqlite + UseSQLiteDatabase(#BakaShrot_Storage_SqliteLibrary) CompilerElse UseSQLiteDatabase() CompilerEndIf @@ -67,7 +84,7 @@ Procedure.q BakaShrot_NowUtcMs() GetSystemTimeAsFileTime_(@FileTime) ProcedureReturn (FileTime - 116444736000000000) / 10000 CompilerElse - ; Untested: Linux isn't built yet. struct timeval, 64-bit. + ; struct timeval, 64-bit (checked on Linux x64 by Tests/Retention-Test.ps1). Protected Dim TimeVal.q(1) BakaShrot_GetTimeOfDay(@TimeVal(0), 0) ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000 @@ -616,15 +633,16 @@ EndProcedure ; the query looked like it simply had no (more) rows. So once the rows end, ; SQLite itself is asked: sqlite3_errcode() on the connection is SQLITE_DONE ; (or SQLITE_ROW/SQLITE_OK) if they really ended, the error otherwise, with -; sqlite3_errmsg16() telling which. Same sqlite3.dll as PureBasic's -; (DatabaseID() is its sqlite3 handle), like Writer.pbi. -; Elsewhere than Windows, PureBasic's own SQLite is linked in and not -; reachable this way: DatabaseError() is checked instead, which misses it. +; sqlite3_errmsg16() telling which. Same #BakaShrot_Storage_SqliteLibrary as +; PureBasic's (DatabaseID() is its sqlite3 handle), like Writer.pbi. +; Without #BakaShrot_Storage_ExternalSqlite, PureBasic's own SQLite is linked +; in and not reachable this way: DatabaseError() is checked instead, which +; misses it. #BakaShrot_Query_SqliteOk = 0 #BakaShrot_Query_SqliteRow = 100 #BakaShrot_Query_SqliteDone = 101 -CompilerIf #PB_Compiler_OS = #PB_OS_Windows +CompilerIf #BakaShrot_Storage_ExternalSqlite PrototypeC.l BakaShrot_Query_SqliteErrCode(Db.i) PrototypeC.i BakaShrot_Query_SqliteErrMsg16(Db.i) @@ -638,14 +656,14 @@ CompilerIf #PB_Compiler_OS = #PB_OS_Windows ; Queries run on every client's thread, the first one loads it. Global BakaShrot_Query_SqliteMutex.i = CreateMutex() - ; Returns #False if sqlite3.dll or its functions can't be found. + ; Returns #False if the SQLite library or its functions can't be found. Procedure.i BakaShrot_Query_LoadSqlite() Protected Loaded.i LockMutex(BakaShrot_Query_SqliteMutex) With BakaShrot_Query_Sqlite If Not \Library - \Library = OpenLibrary(#PB_Any, "sqlite3.dll") + \Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary) If \Library \ErrCode = GetFunction(\Library, "sqlite3_errcode") \ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16") @@ -693,7 +711,7 @@ Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.Strin EndIf ; Without it, errors in the rows would go unnoticed: refused instead. - CompilerIf #PB_Compiler_OS = #PB_OS_Windows + CompilerIf #BakaShrot_Storage_ExternalSqlite If Not BakaShrot_Query_LoadSqlite() *Error\s = "Queries can't be checked for errors: sqlite3_errcode() not found" ProcedureReturn #False @@ -767,7 +785,7 @@ Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.Strin ; Asked before FinishDatabaseQuery(), while the failed step is the last ; thing done on this connection. A false alarm would refuse a good ; query, it can't hide a bad one. - CompilerIf #PB_Compiler_OS = #PB_OS_Windows + CompilerIf #BakaShrot_Storage_ExternalSqlite ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId)) If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone *Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode) @@ -785,11 +803,11 @@ Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.Strin CompilerEndIf FinishDatabaseQuery(DbId) - ; Elsewhere than Windows, the only check there is. It misses errors in the - ; rows: PureBasic doesn't report them. + ; Without #BakaShrot_Storage_ExternalSqlite, the only check there is. It + ; misses errors in the rows: PureBasic doesn't report them. ; !!! DatabaseError() may be shared by every thread, see ; !!! Design/StorageConcurrency.md, another thread's error could show up here. - CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + CompilerIf Not #BakaShrot_Storage_ExternalSqlite If DatabaseError() <> "" *Error\s = DatabaseError() FreeJSON(JsonId) diff --git a/Server/Storage/Writer.pbi b/Server/Storage/Writer.pbi index 3ef561b..f833496 100644 --- a/Server/Storage/Writer.pbi +++ b/Server/Storage/Writer.pbi @@ -19,9 +19,10 @@ ; that were waiting find theirs done. The busier, the bigger the groups. ; - Prepared statements, kept for as long as the writer is open, through ; SQLite's own API: PureBasic prepares a statement again on every call. -; Same sqlite3.dll as PureBasic's (DatabaseID() is its sqlite3 handle). -; Elsewhere than Windows, PureBasic's own SQLite is linked in, so its -; functions are used instead (slower, same behaviour). +; Same #BakaShrot_Storage_SqliteLibrary as PureBasic's (DatabaseID() is +; its sqlite3 handle). Without #BakaShrot_Storage_ExternalSqlite (see +; Storage.pbi), PureBasic's own SQLite is linked in, so its functions +; are used instead (slower, same behaviour). ; - The next message id of every topic/node id kept in memory, instead of ; a MAX(message_id) on every push. Read from the database the first time ; a pair is pushed to (node_heads, which deleting messages leaves as is: @@ -62,11 +63,7 @@ #BakaShrot_Storage_WalSizeLimit = 67108864 -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - #BakaShrot_Storage_RawSqlite = #True -CompilerElse - #BakaShrot_Storage_RawSqlite = #False -CompilerEndIf +#BakaShrot_Storage_RawSqlite = #BakaShrot_Storage_ExternalSqlite #BakaShrot_Sqlite_Done = 101 #BakaShrot_Sqlite_Row = 100 @@ -387,7 +384,7 @@ CompilerIf #BakaShrot_Storage_RawSqlite ProcedureReturn #True EndIf ; The one PureBasic's SQLite driver already loaded. - \Library = OpenLibrary(#PB_Any, "sqlite3.dll") + \Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary) If Not \Library ProcedureReturn #False EndIf @@ -527,7 +524,7 @@ Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String) CompilerIf #BakaShrot_Storage_RawSqlite If Not BakaShrot_Writer_LoadSqlite() - *Error\s = "sqlite3.dll doesn't have the functions needed" + *Error\s = #BakaShrot_Storage_SqliteLibrary + " doesn't have the functions needed" BakaShrot_Writer_Release() UnlockMutex(BakaShrot_Storage_WriteMutex) ProcedureReturn #False diff --git a/Tests/AttachmentEdges-Test.ps1 b/Tests/AttachmentEdges-Test.ps1 index d9c3cfc..d372532 100644 --- a/Tests/AttachmentEdges-Test.ps1 +++ b/Tests/AttachmentEdges-Test.ps1 @@ -270,7 +270,9 @@ db.commit(); print("flipped") $Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s" Expect "B doesn't serve it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1 - $R = Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB + # A sends it again at every check-in, so B can be receiving (1) it + # again when asked: back to missing once that copy is dropped too. + $R = Wait-Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB '\[\["0","0"\]\]' 5 Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]' "INFO A sends it again at every check-in: $Drops times in 6 s (PeerSyncInterval 1)" diff --git a/Tests/Attachments-Test.ps1 b/Tests/Attachments-Test.ps1 index 263a386..9cbd8bb 100644 --- a/Tests/Attachments-Test.ps1 +++ b/Tests/Attachments-Test.ps1 @@ -283,8 +283,18 @@ finally { } "--- Logs" -$LogA = Get-Content (Join-Path $Dir "a.log") -Raw -$LogB = Get-Content (Join-Path $Dir "b.log") -Raw +# A and B start together: until its first link, the other one may not be +# listening yet. Refused at once on Linux, while Windows retries the connect +# for about a second, by which time it usually is. Those attempts are left out. +function Skip-EarlyLinkFailures([string[]]$Lines) { + $Linked = $false + foreach ($Line in $Lines) { + if ($Line -match "^\[Peer\] Linked to") { $Linked = $true } + if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line } + } +} +$LogA = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "a.log"))) -join "`n" +$LogB = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "b.log"))) -join "`n" Check "A sent B the attachments it takes" ($LogA -match "Sent the attachment of logs:kitchen#1 to 'b'" -and $LogA -match "Sent the attachment of logs:kitchen#3 to 'b'") "checked" Check "A never sent #2 (not kept by B)" (-not ($LogA -match "Sent the attachment of logs:kitchen#2")) "checked" Check "B sent A its photo" ($LogB -match "Sent the attachment of photos:garage#1 to 'a'") "checked" diff --git a/Tests/BigMessages-Test.ps1 b/Tests/BigMessages-Test.ps1 index 36b8c78..ccd9ca9 100644 --- a/Tests/BigMessages-Test.ps1 +++ b/Tests/BigMessages-Test.ps1 @@ -299,12 +299,22 @@ try { "--- Logs" # Up to the last real activity: whichever stops first, the other loses its # link to it. +# A and B start together: until its first link, the other one may not be +# listening yet. Refused at once on Linux, while Windows retries the connect +# for about a second, by which time it usually is. Those attempts are left out. +function Skip-EarlyLinkFailures([string[]]$Lines) { + $Linked = $false + foreach ($Line in $Lines) { + if ($Line -match "^\[Peer\] Linked to") { $Linked = $true } + if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line } + } +} function Read-Log($Name) { $L = @(Get-Content (Join-Path $Dir "$Name.log")) $End = [array]::IndexOf($L, "Stopping...") if ($End -lt 0) { $End = $L.Count } while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Dropping the link|Retrying|disconnected|aborted|didn't answer") { $End-- } - ($L[0..([math]::Max($End - 1, 0))]) -join "`n" + @(Skip-EarlyLinkFailures $L[0..([math]::Max($End - 1, 0))]) -join "`n" } $LogA = Read-Log "a" $LogB = Read-Log "b" diff --git a/Tests/Restart-Test.ps1 b/Tests/Restart-Test.ps1 index da97026..6cc521b 100644 --- a/Tests/Restart-Test.ps1 +++ b/Tests/Restart-Test.ps1 @@ -212,7 +212,9 @@ try { Start-Sleep -Seconds 3 # A goes on alone Stop-Pusher $PK $KSeen = Read-Pusher $PK - Check "the garage pusher noticed B was gone: ConnectionLostError, code 104" ($PG.P.HasExited -and (Read-Pusher $PG).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PG).End + # 104 (ConnectionLost) if killed during a push, 100 (NotConnected) if + # between two: the next push finds the connection already gone. + Check "the garage pusher noticed B was gone: ConnectionLostError, code 104 or 100" ($PG.P.HasExited -and (Read-Pusher $PG).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PG).End Check "kitchen kept pushing on A meanwhile" ($KSeen.Count -gt 100 -and $KSeen.End -eq "STOPPED") ("{0} acknowledged" -f $KSeen.Count) $SB = Start-Srv "b"; Wait-Port 12416 $SB @@ -256,7 +258,7 @@ try { Start-Sleep -Seconds 3 # B goes on alone Stop-Pusher $PG $GSeen = Read-Pusher $PG - Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104" ($PK.P.HasExited -and (Read-Pusher $PK).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PK).End + Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104 or 100" ($PK.P.HasExited -and (Read-Pusher $PK).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PK).End $SA = Start-Srv "a"; Wait-Port 12415 $SA Check-Survived "A" "kitchen" $PK $OnA diff --git a/Tests/Retention-Test.ps1 b/Tests/Retention-Test.ps1 index 64c13fd..b347916 100644 --- a/Tests/Retention-Test.ps1 +++ b/Tests/Retention-Test.ps1 @@ -315,10 +315,20 @@ finally { "--- Logs" $LogA = Get-Content (Join-Path $Dir "a.log") -Raw $LogB = Get-Content (Join-Path $Dir "b.log") -Raw +# How many messages of Topic a log says were deleted. Pushed a few ms apart, +# they can fall on both sides of a retention check (every 1 s), and be +# deleted over two of them. +function Count-Deleted($Log, $Topic) { + $N = 0 + foreach ($M in [regex]::Matches($Log, "Retention: deleted (\d+) messages of topic '$Topic' pushed before \d{4}-")) { $N += [int]$M.Groups[1].Value } + $N +} Check "A logged its rule" ($LogA -match "Retention: short = 3s") "checked" -Check "A logged what it deleted" ($LogA -match "Retention: deleted 3 messages of topic 'short' pushed before \d{4}-") "checked" +$N = Count-Deleted $LogA "short" +Check "A logged what it deleted: short #1-#3, maybe #4 since" ($N -ge 3) "$N deleted" Check "B logged its rules" ($LogB -match "Retention: ke\* = 4s" -and $LogB -match "Retention: \* = 1h") "checked" -Check "B deleted keep" ($LogB -match "Retention: deleted 2 messages of topic 'keep'") "checked" +$N = Count-Deleted $LogB "keep" +Check "B deleted keep: #1-#2, maybe #3 since" ($N -ge 2) "$N deleted" Check "B never sent A short messages (A is ahead, deleted or not)" (-not ($LogB -match "Sent \d+ messages of short")) "checked" Check "A sent B late once each: #1-#2, then #3 alone" (([regex]::Matches($LogA, "Sent 2 messages of late:kitchen")).Count -eq 1 -and ([regex]::Matches($LogA, "Sent 1 messages of late:kitchen")).Count -eq 1) "checked" Check "B never stored late #1-#2" (-not ($LogB -match "deleted [23] messages of topic 'late'")) "checked" diff --git a/Tests/restart_pusher.py b/Tests/restart_pusher.py index 15323e6..91c2ff2 100644 --- a/Tests/restart_pusher.py +++ b/Tests/restart_pusher.py @@ -4,7 +4,8 @@ Usage: restart_pusher.py " to the out file once each push is acknowledged. Ends with "STOPPED", or "ERR " when the server -goes away (the test kills it; code 104, ConnectionLost): what was +goes away (the test kills it; code 104, ConnectionLost, during a push, or +100, NotConnected, between two): what was acknowledged before is what must survive. """ From 3d960bfa95ff0a024dc72d528cae3b6146cb5714 Mon Sep 17 00:00:00 2001 From: Herwin Date: Tue, 10 Nov 2026 19:04:03 +0100 Subject: [PATCH 5/5] Run the server headless on Linux, add Docker images for it The server no longer stops when it has no console input on Linux: it reads its own dup of stdin (taken before OpenConsole(), which closes fd 0; Input() returns "" at EOF there), and SIGTERM/SIGINT stop it like "quit". Windows is unchanged. Docker/Compiler: PureBasic 6.41 on debian:trixie-slim (the archive is copied in by hand and git-ignored). Docker/Server: multi-stage, built with the C backend and the optimizer, run on debian:trixie-slim with libsodium and SQLite only, as user bakashrot; config /etc/bakashrot/server.ini, volume /var/lib/bakashrot, port 12345. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RwFeVQCBfcPDfAPqX8z2TF --- CLAUDE.md | 8 +- Design/Release.md | 3 +- Docker/Compiler/.dockerignore | 3 + Docker/Compiler/.gitignore | 2 + Docker/Compiler/Dockerfile | 22 +++++ Docker/Server/Dockerfile | 65 +++++++++++++ Docker/Server/Dockerfile.dockerignore | 8 ++ Notes.md | 72 +++++++++++--- Server/BakaShrot_Server.pb | 132 +++++++++++++++++++++++++- 9 files changed, 293 insertions(+), 22 deletions(-) create mode 100644 Docker/Compiler/.dockerignore create mode 100644 Docker/Compiler/.gitignore create mode 100644 Docker/Compiler/Dockerfile create mode 100644 Docker/Server/Dockerfile create mode 100644 Docker/Server/Dockerfile.dockerignore diff --git a/CLAUDE.md b/CLAUDE.md index db95797..11036b9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,6 +39,9 @@ operations come before security hardening (`Notes.md`, "Threat model"). - `Release.ps1 [-Force]` builds the release with 6.40 into `Release\` and smoke-tests it (`-Force` replaces an existing folder of the same name). +- Linux: same sources and flags (`-t`, `-e`, `-so` for the DLL), with + `libsodium-dev`. `Docker/Compiler/` and `Docker/Server/` build the + compiler and server images, see their Dockerfiles. ## Test @@ -86,8 +89,9 @@ suite: they take a few minutes in all. `-File`. - **Bash tool heredocs collapse `\\`**, and PureBasic uses `\` for fields: write edit scripts to files, or use the Edit tool. -- **The real server needs a console** (it stops at once without input): - tests use `BenchServer.exe` and its stop file instead. +- **The real server needs a console on Windows** (it stops at once without + input): tests use `BenchServer.exe` and its stop file instead. On Linux + it runs on without one, SIGTERM/SIGINT stop it. ## Working rules diff --git a/Design/Release.md b/Design/Release.md index 24afbc6..e23b399 100644 --- a/Design/Release.md +++ b/Design/Release.md @@ -90,7 +90,8 @@ in `Tests/` already, to be pointed at the release instead. Needs a way to stop it without a console: a stop file like `BenchServer.exe`'s, or a local admin connection (`Notes.md`, console commands can't be scripted). Then check it stops within a few seconds, - with its last messages committed. + with its last messages committed. On Linux, SIGTERM does it (2026-11-10, + checked through `docker stop`). 5. **Refusals**: - an unknown public key, and a known one with the wrong private key: not authenticated; diff --git a/Docker/Compiler/.dockerignore b/Docker/Compiler/.dockerignore new file mode 100644 index 0000000..a28b0bd --- /dev/null +++ b/Docker/Compiler/.dockerignore @@ -0,0 +1,3 @@ +* +!Dockerfile +!*.tgz diff --git a/Docker/Compiler/.gitignore b/Docker/Compiler/.gitignore new file mode 100644 index 0000000..92c110c --- /dev/null +++ b/Docker/Compiler/.gitignore @@ -0,0 +1,2 @@ +# The PureBasic archive copied here to build the image: licensed, not shared. +*.tgz diff --git a/Docker/Compiler/Dockerfile b/Docker/Compiler/Dockerfile new file mode 100644 index 0000000..8e827ac --- /dev/null +++ b/Docker/Compiler/Dockerfile @@ -0,0 +1,22 @@ +# PureBasic compiler image, console programs only (no GUI libraries). +# +# PureBasic's Linux build needs glibc 2.38+, hence Debian 13 (glibc 2.41). +# The PureBasic archive isn't in git (it's licensed): copy it next to this +# file first, then: +# docker build -t purebasic:6.41 --build-arg PUREBASIC_ARCHIVE=PureBasic_Linux3_X64_6.41_xxxx.tgz Docker/Compiler +# docker run --rm -v "$PWD":/src -w /src purebasic:6.41 pbcompiler -t Server/BakaShrot_Server.pb -e Build/BakaShrot_Server +# Both backends are on the PATH: pbcompiler (asm) and pbcompilerc (C). + +FROM debian:trixie-slim + +# gcc links every program (and is the C backend), libssl-dev is for +# PureBasic's Network library. +RUN apt-get update \ + && apt-get install -y --no-install-recommends gcc libc6-dev libssl-dev \ + && rm -rf /var/lib/apt/lists/* + +ARG PUREBASIC_ARCHIVE +ADD ${PUREBASIC_ARCHIVE} /opt/ + +ENV PUREBASIC_HOME=/opt/purebasic +ENV PATH=/opt/purebasic/compilers:$PATH diff --git a/Docker/Server/Dockerfile b/Docker/Server/Dockerfile new file mode 100644 index 0000000..479d7f3 --- /dev/null +++ b/Docker/Server/Dockerfile @@ -0,0 +1,65 @@ +# BakaShrot server image. +# +# Built from the repository's root, with the compiler image (Docker/Compiler) +# already built, and the PB-MessagePack submodule checked out: +# git submodule update --init --recursive +# docker build -t bakashrot-server -f Docker/Server/Dockerfile . +# +# Run it with a config and a volume for the database: +# docker run -d --name bakashrot -p 12345:12345 \ +# -v ./server.ini:/etc/bakashrot/server.ini:ro \ +# -v bakashrot-data:/var/lib/bakashrot \ +# bakashrot-server +# In server.ini's [BakaShrot.Server]: Port = 12345, Host empty (every +# interface: 127.0.0.1 can't be reached from outside the container), and +# DatabasePath = /var/lib/bakashrot/server.sqlite (relative paths are from +# that folder too). +# +# `docker stop` stops it cleanly (SIGTERM). Console commands (names, vacuum, +# restart...): start it with -it, then `docker attach bakashrot`, and +# detach with Ctrl+P, Ctrl+Q. + + +# --- Build --------------------------------------------------------------------- + +ARG COMPILER_IMAGE=purebasic:6.41 +FROM ${COMPILER_IMAGE} AS build + +RUN apt-get update \ + && apt-get install -y --no-install-recommends libsodium-dev \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /src +# Everything Server/BakaShrot_Server.pb includes, and nothing else. +COPY Client/BakaShrot_ErrorCodes.pbi Client/ +COPY Commons Commons +COPY Includes Includes +COPY Server Server + +# The release build: C backend, optimized, thread-safe. +RUN mkdir /out && pbcompilerc --thread --optimizer Server/BakaShrot_Server.pb --executable /out/bakashrot-server + + +# --- Runtime ------------------------------------------------------------------- + +FROM debian:trixie-slim + +# libsodium for the cryptography, SQLite 3.38+ for the storage: the server +# loads libsqlite3.so.0 itself (Server/Storage/Storage.pbi). +RUN apt-get update \ + && apt-get install -y --no-install-recommends libsodium23 libsqlite3-0 \ + && rm -rf /var/lib/apt/lists/* + +RUN useradd --system --home-dir /var/lib/bakashrot --shell /usr/sbin/nologin bakashrot \ + && mkdir -p /etc/bakashrot /var/lib/bakashrot \ + && chown bakashrot:bakashrot /var/lib/bakashrot + +COPY --from=build /out/bakashrot-server /usr/local/bin/bakashrot-server + +USER bakashrot +WORKDIR /var/lib/bakashrot +VOLUME /var/lib/bakashrot +EXPOSE 12345 + +ENTRYPOINT ["/usr/local/bin/bakashrot-server"] +CMD ["/etc/bakashrot/server.ini"] diff --git a/Docker/Server/Dockerfile.dockerignore b/Docker/Server/Dockerfile.dockerignore new file mode 100644 index 0000000..d9396e1 --- /dev/null +++ b/Docker/Server/Dockerfile.dockerignore @@ -0,0 +1,8 @@ +# Only what the server is compiled from: Build/ alone can hold gigabytes of +# test databases, and private keys. +* +!Client/BakaShrot_ErrorCodes.pbi +!Commons +!Includes +!Server +**/.git diff --git a/Notes.md b/Notes.md index e18f57c..53ce6d4 100644 --- a/Notes.md +++ b/Notes.md @@ -14,19 +14,24 @@ Where things stand and what's next, as of 2026-11-09. A new session: read | `Design/Suggestions.md` | Improvements not done yet: pipelined pushes, faster replication, smaller ones. | | `Design/Release.md` | The release smoke test, what's missing for 1.0.0, the (fixed) silent query failure, notes for CI/CD. | -## Right now (2026-11-09) +## Right now (2026-11-10) -- **Nothing since `df61ef9` is committed**, on `timestamps-retention`: the - tool renames, protocols 5 and 6 (node identities, error codes), names-only - configs, `Synchronous`, schema v8 (`browse`), `Examples/`, - `Restart-Test.ps1`. Every suite passes on it (8, see `CLAUDE.md`), it - compiles with 5.73 and 6.40, the push bench gives ~17,000 msg/s for 4 - servers with `Synchronous = FULL`. +- **Everything is committed**, on `timestamps-retention`: protocol 6 and + the rest (`488ffe4`: the tool renames, protocols 5 and 6, node + identities, error codes, names-only configs, `Synchronous`, schema v8 + (`browse`), `Examples/`, `Restart-Test.ps1`), the Linux fixes + (`5270f25`), then the server without a console on Linux and `Docker/`. + Every suite passes on it (8, see `CLAUDE.md`), it compiles with 5.73 and + 6.40, the push bench gives ~17,000 msg/s for 4 servers with + `Synchronous = FULL`. - **`Release\20261109-df61ef9-dirty\` is out of date** (before `Synchronous`, `browse` and the error codes): commit, then `Release.ps1` again. +- **On Linux** (2026-11-10, `Done: Linux, Docker images`): every suite + passes, the server runs without a console (SIGTERM/SIGINT), `Docker/` + builds it into an image. - **Suggested next** (not decided by the owner): the server without a - console (item 1), then whatever the real-world test shows. The run on a + console on Windows (item 1), then whatever the real-world test shows. The run on a clean Windows is the owner's, not an item here. ## Where things stand @@ -324,8 +329,8 @@ As judged for the threat model below (internal tool, trusted machines). process loses nothing committed). Often fine internally, to decide. - Client: one connection per process, `--follow` polls, no reconnect. - Tests run by hand, on fixed ports, no runner, no CI. -- Linux untested; keys in plain-text inis (file permissions are enough - here). +- Linux tested, Docker images (2026-11-10); keys in plain-text inis (file + permissions are enough here). **Bad** - The server can't run unattended: it needs a console, stops at once @@ -644,6 +649,37 @@ still say the old names where they tell what was done then. double-start guard, the README's Python snippet. `Start-Server.ps1 -Here` wasn't (it needs an interactive console). +## Done: Linux, Docker images (2026-11-10) + +- **Every suite passes on Linux** (Ubuntu, x64) with 6.41's asm and C + backends: `Tests/*.ps1` through PowerShell 7, once `-WindowStyle Hidden` + is dropped (not supported there), the binaries named as on Windows + (`BakaShrot_Client.dll` is the `.so`), `-Build` given. 5.73 compiles and + passes the rest, but can't restart a server on the same port within + ~60 s (its listener doesn't set `SO_REUSEADDR`): Names, Restart and + AttachmentEdges. +- **Fixed on the way:** SQLite on Linux is the system's `libsqlite3.so.0` + (`#BakaShrot_Storage_SqliteLibrary`), so the query error check and the + writer's prepared statements work there too; `BakaShrot_SendPacket()` + retries when the send buffer is full (`EAGAIN`, it aborted clients + reading big answers); four tests that relied on Windows timing. +- **The server runs without a console on Linux** (item 1, there): SIGTERM + and SIGINT stop it like `quit`, and with no console input it runs on + until one comes. `Input()` can't do it: on Linux it returns `""` (quit) + at the end of the input, and PureBasic's console moves descriptor 0 + elsewhere, so `ReadCommand()` reads a `dup` of it taken before + `OpenConsole()`, `poll()`ing 250 ms at a time. Checked with no input, + piped commands (CRLF too), a terminal, `quit`, both signals, on 5.73 and + 6.41. +- **`Docker/`**: `Compiler/` (PureBasic 6.41 on `debian:trixie-slim`, the + archive copied in by hand, never committed) and `Server/` (multi-stage: + built with the C backend and the optimizer, run on `debian:trixie-slim` + with libsodium and SQLite only, as user `bakashrot`). Config + `/etc/bakashrot/server.ini`, data volume `/var/lib/bakashrot`, port 12345. + Checked: pushes, reads and queries through the port, `docker stop` clean + (~0.3 s, exit 0), data kept over a restart, commands with `-i`. Alpine was + tried: PureBasic needs glibc 2.38+. + ## Threat model (2026-11-08) BakaShrot is an **internal tool, on trusted machines and a trusted @@ -669,6 +705,8 @@ network**, not exposed to the internet. So: no clean stop from a script (tests force-kill it). Fix: a stop file like `BenchServer.exe`'s, and/or a local admin connection, then a way to run it as a service. (`Design/Release.md` smoke test #4) + Done on Linux (2026-11-10): SIGTERM/SIGINT stop it, it runs on without + console input (`Done: Linux, Docker images`). Windows still needs it. 2. **The 1.0.0 smoke test, what's left:** replication between two servers built by `Release.ps1` (the suites use `BenchServer.exe`, the same server code). Done: the release's own smoke test and the example from its zip @@ -721,7 +759,7 @@ network**, not exposed to the internet. So: two threads failing on their own connections 20,000 times each, never once the other's message, with 5.73 and 6.40 (`/THREAD`). `sqlite3_errmsg16()` on the connection gives the same messages, kept as - is. Linux untested (item 18). + is. Linux: not checked the same way, its suites pass (2026-11-10). 9. **Limits:** the sync state must fit in one packet (65536 topic/node pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover. (`Design/ReplicationIssues.md` #7) @@ -764,8 +802,8 @@ network**, not exposed to the internet. So: 17. **Review.md rules** not checked against the newer code (`.i` in networking structures, explicit enumeration values), see below. The file itself says to ignore it for now. -18. **Linux is untested** (libsodium via `-lsodium`, the query error check - falls back to `DatabaseError()`). +18. ~~**Linux is untested**~~ Done (2026-11-10): every suite passes, see + `Done: Linux, Docker images`. 19. **Console commands can't be scripted** (see 1). ### Done recently (details in the sections above and `Design/`) @@ -792,6 +830,8 @@ network**, not exposed to the internet. So: acknowledged lost (`Restart-Test.ps1`, 2026-11-09). - Protocol 6: error codes everywhere, at-least-once delivery accepted (2026-11-09). +- Linux: every suite passes, the server runs without a console there, + `Docker/` images for the compiler and the server (2026-11-10). ## To check against Review.md @@ -812,8 +852,10 @@ network**, not exposed to the internet. So: - **Test the server's console commands** with a small driver that includes `Server/Root.pbi` and calls `BakaShrot_Root_*` directly. Piping commands into the server doesn't work. -- **With no console input,** `Input()` returns `Chr(4)` on every call, and the - server stops on it. +- **With no console input,** `Input()` returns `Chr(4)` on every call on + Windows, and the server stops on it. On Linux it returns `""`, and the + server reads its commands itself (`ReadCommand()`): piping commands into + it works there. - **Don't trust timestamps** from PowerShell's `Register-ObjectEvent`: lines queue up during `Start-Sleep`. PureBasic's console output into a pipe is also buffered until exit. Trust the order, not the times. diff --git a/Server/BakaShrot_Server.pb b/Server/BakaShrot_Server.pb index 9afaef7..9722bf6 100644 --- a/Server/BakaShrot_Server.pb +++ b/Server/BakaShrot_Server.pb @@ -16,6 +16,10 @@ ; See Root.pbi for how the workers are stopped. ; Exits with 0 on success, 1 on failure. ; +; Windows: it stops once there's no more console input (no console, closed +; standard input). Elsewhere, it runs on without one (a container, a +; service) and SIGTERM or SIGINT stops it the same way as "quit". +; ; Compile as a thread-safe console program. ; ============================================================================ @@ -32,11 +36,113 @@ Procedure PrintCommands() EndProcedure +CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + ; Same numbers on Linux and macOS. + #BakaShrot_Server_SigInt = 2 + #BakaShrot_Server_SigTerm = 15 + #BakaShrot_Server_PollIn = $0001 + #BakaShrot_Server_FDupFd = 0 + + ; struct pollfd + Structure BakaShrot_Server_PollFd + Fd.l + Events.w + REvents.w + EndStructure + + ImportC "" + BakaShrot_Server_Signal.i(Signal.l, *Handler) As "signal" + BakaShrot_Server_Poll.l(*Fds, Count.i, TimeoutMs.l) As "poll" + BakaShrot_Server_Read.i(Fd.l, *Buffer, Size.i) As "read" + ; dup() itself can't be imported: fasm reserves the name. + BakaShrot_Server_Fcntl.l(Fd.l, Command.l, Argument.i) As "fcntl" + EndImport + + ; Longest command line kept, the rest of a longer one is dropped. + #BakaShrot_Server_MaxCommandSize = 256 + + ; The signal that asked to stop, 0 until then. Only ever set by the + ; handler (all a handler may safely do), read by ReadCommand(). + Global BakaShrot_Server_StopSignal.l = 0 + + ; #True once standard input is closed: commands can't come any more. + Global BakaShrot_Server_NoInput.i = #False + + ; Standard input, taken before OpenConsole(): it moves descriptor 0 + ; elsewhere and closes it (then reused by the next file opened). + Global BakaShrot_Server_InputFd.l = -1 + + ProcedureC BakaShrot_Server_OnSignal(Signal.l) + BakaShrot_Server_StopSignal = Signal + EndProcedure +CompilerEndIf + + +; Waits for the next command, Chr(4) once there's no more input. +; Windows: Input(). Elsewhere, Input() returns "" (quit) at the end of the +; input and blocks until a whole line came, so standard input is read here +; instead: never blocking for more than 250 ms without checking for a stop +; signal (it then returns "", see BakaShrot_Server_StopSignal). +Procedure.s ReadCommand() + CompilerIf #PB_Compiler_OS = #PB_OS_Windows + ProcedureReturn Input() + CompilerElse + Protected Fd.BakaShrot_Server_PollFd, Byte.a, BytesRead.i, Size.i + Protected Dim Chars.a(#BakaShrot_Server_MaxCommandSize) + + Repeat + If BakaShrot_Server_StopSignal + ProcedureReturn "" + EndIf + If BakaShrot_Server_NoInput + Delay(250) + Continue + EndIf + If BakaShrot_Server_InputFd < 0 + ProcedureReturn Chr(4) + EndIf + + Fd\Fd = BakaShrot_Server_InputFd + Fd\Events = #BakaShrot_Server_PollIn + Fd\REvents = 0 + If BakaShrot_Server_Poll(@Fd, 1, 250) <= 0 + Continue + EndIf + + ; Readable, or closed: one byte, so nothing is read past the line. + BytesRead = BakaShrot_Server_Read(BakaShrot_Server_InputFd, @Byte, 1) + If BytesRead = 0 Or (BytesRead < 0 And Not BakaShrot_Server_StopSignal) + ProcedureReturn Chr(4) + EndIf + If BytesRead = 1 + If Byte = 10 + ProcedureReturn PeekS(@Chars(0), Size, #PB_UTF8 | #PB_ByteLength) + EndIf + ; CR of a CRLF skipped. + If Byte <> 13 And Size < #BakaShrot_Server_MaxCommandSize + Chars(Size) = Byte + Size + 1 + EndIf + EndIf + ForEver + CompilerEndIf +EndProcedure + + Define Root.BakaShrot_Root Define Command.s, ExitCode.i +CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + BakaShrot_Server_InputFd = BakaShrot_Server_Fcntl(0, #BakaShrot_Server_FDupFd, 0) +CompilerEndIf + OpenConsole("BakaShrot Server") +CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + BakaShrot_Server_Signal(#BakaShrot_Server_SigTerm, @BakaShrot_Server_OnSignal()) + BakaShrot_Server_Signal(#BakaShrot_Server_SigInt, @BakaShrot_Server_OnSignal()) +CompilerEndIf + Root\ConfigPath = #BakaShrot_Server_DefaultConfigPath If CountProgramParameters() > 0 Root\ConfigPath = ProgramParameter(0) @@ -62,13 +168,31 @@ PrintCommands() ExitCode = 0 Repeat - Command = LCase(Trim(Input())) + Command = LCase(Trim(ReadCommand())) + + CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + If BakaShrot_Server_StopSignal + If BakaShrot_Server_StopSignal = #BakaShrot_Server_SigTerm + PrintN("Got SIGTERM, stopping") + Else + PrintN("Got SIGINT, stopping") + EndIf + Break + EndIf + CompilerEndIf ; Once there's no more input (no console, closed standard input), every - ; Input() returns Chr(4) right away. Without this, it would loop forever. + ; ReadCommand() returns Chr(4) right away. Without this, it would loop + ; forever. If FindString(Command, Chr(4)) - PrintN("No more input, stopping") - Break + CompilerIf #PB_Compiler_OS = #PB_OS_Windows + PrintN("No more input, stopping") + Break + CompilerElse + PrintN("No console input, running until SIGTERM or SIGINT") + BakaShrot_Server_NoInput = #True + Continue + CompilerEndIf EndIf Select Command