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:
@@ -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
|
||||
Reference in New Issue
Block a user