mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+18
-5
@@ -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
|
||||
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.<name>] -> one BakaShrot_CoreConfig\Peers() entry per
|
||||
; section.
|
||||
; [BakaShrot.Client.<name>] -> 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.<name>] 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.<name>] and [BakaShrot.Client.<name>], 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)
|
||||
|
||||
@@ -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.<name>] section per peer this node talks to.
|
||||
; <name> is only a key for this file; it is never sent on the wire.
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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
|
||||
+102
-16
@@ -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
|
||||
|
||||
|
||||
|
||||
+135
-15
@@ -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.
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <python.exe>]
|
||||
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" }
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -12,10 +12,12 @@
|
||||
; every --interval ms, until stopped (Ctrl+C) or the
|
||||
; connection fails.
|
||||
; --interval <Ms> 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 <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [ClientIni]")
|
||||
PrintN("Usage: GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--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()
|
||||
If ShowTime
|
||||
PrintN(Str(AfterMessageId) + #TAB$ + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()) + #TAB$ + BakaShrot_GetMessageDataString())
|
||||
Else
|
||||
PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString())
|
||||
EndIf
|
||||
Next
|
||||
Printed + Count
|
||||
|
||||
|
||||
Reference in New Issue
Block a user