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

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
+108
View File
@@ -0,0 +1,108 @@
; ============================================================================
; BakaShrot Server - CLI entry point
;
; Usage: BakaShrot_Server [ConfigFile]
; ConfigFile Path to the server's ini config, defaults to "config.ini".
; See Config/schema.ini for its layout.
;
; Loads the config, opens and sets up the database at [BakaShrot.Server]
; DatabasePath, listens on [BakaShrot.Server] Host:Port, and links to every
; [BakaShrot.Peer.<name>]. Then reads commands from the console:
; (empty), quit Stops the server.
; restart Stops every worker, reloads the config, starts again.
; vacuum Stops every worker, VACUUMs the database, starts again.
; names Lists every topic and node with its id and name.
; help Lists the commands.
; See Root.pbi for how the workers are stopped.
; Exits with 0 on success, 1 on failure.
;
; Compile as a thread-safe console program.
; ============================================================================
EnableExplicit
XIncludeFile "Root.pbi"
#BakaShrot_Server_DefaultConfigPath = "config.ini"
Procedure PrintCommands()
PrintN("Commands: quit (or an empty line), restart, vacuum, names, help")
EndProcedure
Define Root.BakaShrot_Root
Define Command.s, ExitCode.i
OpenConsole("BakaShrot Server")
Root\ConfigPath = #BakaShrot_Server_DefaultConfigPath
If CountProgramParameters() > 0
Root\ConfigPath = ProgramParameter(0)
EndIf
If Not BakaShrot_Root_LoadConfig(@Root)
End 1
EndIf
If Not BakaShrot_Root_OpenDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
If Not BakaShrot_Root_StartWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
PrintN("Running.")
PrintCommands()
ExitCode = 0
Repeat
Command = LCase(Trim(Input()))
; Once there's no more input (no console, closed standard input), every
; Input() returns Chr(4) right away. Without this, it would loop forever.
If FindString(Command, Chr(4))
PrintN("No more input, stopping")
Break
EndIf
Select Command
Case "", "quit"
Break
Case "restart"
If Not BakaShrot_Root_Restart(@Root)
PrintN("[Root] Restart failed, stopping")
ExitCode = 1
Break
EndIf
Case "vacuum"
If Not BakaShrot_Root_Vacuum(@Root)
PrintN("[Root] Couldn't start again after vacuuming, stopping")
ExitCode = 1
Break
EndIf
Case "names"
BakaShrot_Names_Print()
Case "help"
PrintCommands()
Default
PrintN("Unknown command '" + Command + "'")
PrintCommands()
EndSelect
ForEver
PrintN("Stopping...")
BakaShrot_Root_StopWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End ExitCode
+8
View File
@@ -0,0 +1,8 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
CursorPosition = 15
FirstLine = 23
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 1
EnableBuildCount = 0
+893
View File
@@ -0,0 +1,893 @@
; ============================================================================
; BakaShrot Server Config
;
; Loads and saves the server node's configuration from/to an ini file via
; PureBasic's native Preferences library.
;
; Section layout:
; [BakaShrot] -> BakaShrot_CoreConfig
; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server
; [BakaShrot.Topics] -> topic names, "name = id" lines
; [BakaShrot.Nodes] -> node names, "name = id" lines
; [BakaShrot.Peer.<name>] -> one BakaShrot_CoreConfig\Peers() entry per
; section.
; [BakaShrot.Client.<name>] -> one BakaShrot_CoreConfig\Clients() entry per
; section.
;
; <name> of a peer or client section is only a key for this file, it is never
; sent on the wire. Topic and node names are: they're what other servers know
; them by, see Commons/Networking/Names.pbi.
;
; Everywhere else, a topic or node is a "ref": a name from those sections,
; or an id in digits. Topic and node lists ("0;logs;100-150;sensors.*") also
; take ranges of ids, patterns like file names ("sensors.*", "kitchen-??",
; see Commons/Networking/Names.pbi), and "*" for every one. In a peer's
; AcceptTopics / AcceptNodes, "*" and patterns also take names this server
; doesn't have: they're added with an id of their own, see
; Server/Storage/Names.pbi.
;
; LoadConfig() returns 0 on any mistake, with the reason in
; BakaShrot_ConfigError.
; ============================================================================
XIncludeFile "../../Commons/Networking/Names.pbi"
; Some topics or nodes, or all of them: what a topic list (or node list)
; in the config holds, see the top of this file.
Structure BakaShrot_NameSet
; Every one, named or not, known or not ("*").
All.i
; Every one that has a name on this server: the default of AcceptNodes.
Known.i
; Str(Id) -> #True, from ids, ranges and names in the list.
Map Ids.i()
; Patterns ("sensors.*"), matched against names, known here or not:
; a peer's topics and nodes it doesn't name are taken if they match.
List Patterns.s()
EndStructure
; Ini Section: [BakaShrot.Peer.<name>] (one section per known peer)
; The server links to every peer on start, see Server/Networking/Peers.pbi.
; The peer must register this server in one of its [BakaShrot.Client.<name>].
; PublicKey is the peer's: a link to it only goes through if the peer
; proves it holds the matching private key (Commons/Networking/Connections.pbi).
; Topic and Node are only checked when the peer links to here.
Structure BakaShrot_PeerConfig
; Remote address of the peer
; Can be a domain name, IPV4, IPV6
Host.s
; Remote port of the peer
; 0-65535
Port.u
; Topic, Node: the remote node's topic and node, refs, resolved to this
; server's ids. The peer authenticates with them when it links to here.
TopicId.u
NodeId.u
; This peer's Ed25519 public key (Base64): the Hello of a link to it is
; sealed for it, and the peer must sign the handshake with the matching
; private key. It also authenticates with it when it links to here.
PublicKey.s
; SendTopics: the topics this server sends to the peer (if the peer
; takes them). AcceptTopics: the topics it takes from the peer.
; Both default to [BakaShrot.Server] ReplicatingTopics.
SendTopics.BakaShrot_NameSet
AcceptTopics.BakaShrot_NameSet
; SendNodes: the nodes whose messages this server sends to the peer.
; Default: every one (*). AcceptNodes: the nodes whose messages it takes
; from the peer. Default: every one named here, no other.
SendNodes.BakaShrot_NameSet
AcceptNodes.BakaShrot_NameSet
; As written in the ini, for SaveConfig(). Chr(1) when missing.
SendTopicsText.s
AcceptTopicsText.s
SendNodesText.s
AcceptNodesText.s
TopicText.s
NodeText.s
EndStructure
; One "Topic:Node" entry of BakaShrot_ClientConfig\Identities().
Structure BakaShrot_ClientIdentity
TopicId.u
NodeId.u
EndStructure
; What a client is allowed to do once authenticated.
; Ini keys of [BakaShrot.Client.<name>], 1 to allow, 0 to deny.
Structure BakaShrot_ClientPermissions
; AllowRead: GetLatestMessage. Defaults to 1.
Read.i
; AllowWrite: PushMessage. Defaults to 1.
Write.i
; AllowQuery: raw read-only SQL queries. Defaults to 0, they can read
; every topic's data.
Query.i
EndStructure
#BakaShrot_Config_DefaultAllowRead = 1
#BakaShrot_Config_DefaultAllowWrite = 1
#BakaShrot_Config_DefaultAllowQuery = 0
; Ini Section: [BakaShrot.Client.<name>] (one section per registered client)
Structure BakaShrot_ClientConfig
; Ed25519 public keys (Base64) the client is allowed to authenticate with.
; Format: Key;Key;...
List PublicKeys.s()
; Topic and node pairs the client is allowed to authenticate as, once it
; has authenticated with one of its PublicKeys.
; Format: Topic:Node;Topic:Node;... each a name or an id.
List Identities.BakaShrot_ClientIdentity()
; AllowRead, AllowWrite, AllowQuery
Permissions.BakaShrot_ClientPermissions
; PushTopics: the topics it may push to, under its own node.
; ReadTopics: the topics it may read the latest messages of.
; Both default to the topics of its Identities.
PushTopics.BakaShrot_NameSet
ReadTopics.BakaShrot_NameSet
; As written in the ini, for SaveConfig(). Chr(1) when missing.
IdentitiesText.s
PushTopicsText.s
ReadTopicsText.s
EndStructure
; Ini Section: [BakaShrot.Server]
Structure BakaShrot_ServerConfig
; IPV4 that it will be bound to
Host.s
; Used port
Port.u
; ReplicatingTopics: the topics replicated with every peer that doesn't
; say otherwise (SendTopics, AcceptTopics).
; Format: 0;logs;100-150;200;... or * for every topic.
ReplicatingTopics.BakaShrot_NameSet
ReplicatingTopicsText.s
; Amount of threads used for networking-related tasks
NetThreadPoolSize.i
; SQLite database file holding the messages.
DatabasePath.s
; Seconds to wait before connecting to a peer again, after failing to
; connect or losing the connection.
PeerRetryDelay.i
; Seconds between two check-ins with a linked peer, where it's sent the
; messages it's missing.
PeerSyncInterval.i
; Most messages sent to a peer per packet when it's missing some, 1-10000.
; A batch is also cut short to fit in one packet (64 KB).
PeerBatchSize.i
EndStructure
; Ini Section: [BakaShrot]
Structure BakaShrot_CoreConfig
; This node's Ed25519 private key (Base64), used to sign every packet it
; sends. Its matching public key must be handed to peers, who store it
; as PublicKey in the relevant [BakaShrot.Peer.<name>] section of THEIR
; own config. See Commons/Cryptography/Libsodium.pbi.
PrivateKey.s
; Topic, Node: the topic and node this server authenticates as when it
; links to its peers, refs. Peers must know them by the same names.
TopicId.u
NodeId.u
TopicText.s
NodeText.s
; [BakaShrot.Server]
Server.BakaShrot_ServerConfig
; [BakaShrot.Topics] and [BakaShrot.Nodes]:
; LCase(name) -> id, and Str(id) -> name as written.
Map TopicIds.i()
Map TopicNames.s()
Map NodeIds.i()
Map NodeNames.s()
; Str(id) -> #True for every id the config mentions, named or not, so
; the database knows them all (Server/Storage/Names.pbi).
Map UsedTopicIds.i()
Map UsedNodeIds.i()
; One [BakaShrot.Peer.<name>] entry per map key.
Map Peers.BakaShrot_PeerConfig()
; One [BakaShrot.Client.<name>] entry per map key.
Map Clients.BakaShrot_ClientConfig()
EndStructure
Macro Ptr_BakaShrot_CoreConfig : i : EndMacro
#BakaShrot_Config_DefaultNetThreadPoolSize = 4
#BakaShrot_Config_DefaultDatabasePath = "./test.sqlite"
#BakaShrot_Config_DefaultPeerRetryDelay = 10
#BakaShrot_Config_DefaultPeerSyncInterval = 5
#BakaShrot_Config_DefaultPeerBatchSize = 100
; What ReadPreferenceString() returns for a missing key, to tell it from an
; empty one: an empty PushTopics allows nothing, a missing one the default.
#BakaShrot_Config_Missing = Chr(1)
; Why the last LoadConfig() failed.
Global BakaShrot_ConfigError.s = ""
; Reads Key, or OldKey if Key is missing: Topic, Node and ReplicatingTopics
; were TopicId, NodeId and ReplicatingTopicIds before they took names, and
; configs written then still work.
Procedure.s ReadConfigKey(Key.s, OldKey.s, DefaultValue.s)
Protected Value.s = ReadPreferenceString(Key, #BakaShrot_Config_Missing)
If Value = #BakaShrot_Config_Missing
Value = ReadPreferenceString(OldKey, DefaultValue)
EndIf
ProcedureReturn Value
EndProcedure
; #True if *Set holds the topic or node Id named Name: Name is its name
; ("" if it has none), Id is -1 for a name this server doesn't know.
; Not thread-safe, it moves the set's current map and list elements: give
; each thread its own copy (CopyStructure()).
Procedure.i NameSetHas(*Set.BakaShrot_NameSet, Id.i, Name.s)
If *Set\All
ProcedureReturn #True
EndIf
If Id >= 0 And FindMapElement(*Set\Ids(), Str(Id))
ProcedureReturn #True
EndIf
If Name <> ""
If *Set\Known And Id >= 0
ProcedureReturn #True
EndIf
ForEach *Set\Patterns()
If BakaShrot_GlobMatch(*Set\Patterns(), Name)
ProcedureReturn #True
EndIf
Next
EndIf
ProcedureReturn #False
EndProcedure
; #True if *Set has anything that can take names this server doesn't know
; ("*" or a pattern).
Procedure.i NameSetTakesUnknown(*Set.BakaShrot_NameSet)
ProcedureReturn Bool(*Set\All Or ListSize(*Set\Patterns()) > 0)
EndProcedure
; The id a topic ref stands for in *Config, -1 if it's neither an id nor one
; of its [BakaShrot.Topics].
; An empty ref is 0, like an empty key always was.
Procedure.i ResolveConfigTopic(*Config.BakaShrot_CoreConfig, Ref.s)
Protected Id.i
If Ref = ""
Ref = "0"
EndIf
Id = BakaShrot_RefToId(Ref)
If Id >= 0
ProcedureReturn Id
EndIf
If BakaShrot_IsValidName(Ref) And FindMapElement(*Config\TopicIds(), LCase(Ref))
ProcedureReturn *Config\TopicIds()
EndIf
ProcedureReturn -1
EndProcedure
; Same for a node ref and [BakaShrot.Nodes].
Procedure.i ResolveConfigNode(*Config.BakaShrot_CoreConfig, Ref.s)
Protected Id.i
If Ref = ""
Ref = "0"
EndIf
Id = BakaShrot_RefToId(Ref)
If Id >= 0
ProcedureReturn Id
EndIf
If BakaShrot_IsValidName(Ref) And FindMapElement(*Config\NodeIds(), LCase(Ref))
ProcedureReturn *Config\NodeIds()
EndIf
ProcedureReturn -1
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.
Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s())
Protected Name.s, Value.s, Id.i
If Not PreferenceGroup(Section)
ProcedureReturn #True
EndIf
If ExaminePreferenceKeys()
While NextPreferenceKey()
Name = Trim(PreferenceKeyName())
Value = Trim(PreferenceKeyValue())
If Not BakaShrot_IsValidName(Name)
BakaShrot_ConfigError = "[" + Section + "] '" + Name + "' isn't a valid " + Kind + " name: 1-" + Str(#BakaShrot_MaxNameLength) + " of A-Z a-z 0-9 _ . -, not only digits"
ProcedureReturn #False
EndIf
Id = BakaShrot_RefToId(Value)
If Id < 0
BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId)
ProcedureReturn #False
EndIf
If FindMapElement(Ids(), LCase(Name))
BakaShrot_ConfigError = "[" + Section + "] " + Kind + " '" + Name + "' is given twice"
ProcedureReturn #False
EndIf
If FindMapElement(Names(), Str(Id))
BakaShrot_ConfigError = "[" + Section + "] " + Kind + " id " + Str(Id) + " is given to both '" + Names() + "' and '" + Name + "'"
ProcedureReturn #False
EndIf
Ids(LCase(Name)) = Id
Names(Str(Id)) = Name
Wend
EndIf
ProcedureReturn #True
EndProcedure
; Parses a topic list (IsNodes #False) or node list into *Set: refs,
; patterns and ranges of ids separated by ";", "*" for every one, see the
; top of this file. Where is for the errors.
; Returns #False on an unknown name, an invalid pattern or range.
Procedure.i ParseNameSet(*Config.BakaShrot_CoreConfig, Text.s, *Set.BakaShrot_NameSet, IsNodes.i, Where.s)
Protected i.i, Part.s, DashPos.i, FromId.i, ToId.i, Id.i, Kind.s, Section.s
Kind = "topic" : Section = "[BakaShrot.Topics]"
If IsNodes
Kind = "node" : Section = "[BakaShrot.Nodes]"
EndIf
ClearMap(*Set\Ids())
ClearList(*Set\Patterns())
*Set\All = #False
*Set\Known = #False
For i = 1 To CountString(Text, ";") + 1
Part = Trim(StringField(Text, i, ";"))
If Part = ""
Continue
EndIf
If Part = "*"
*Set\All = #True
Continue
EndIf
If FindString(Part, "*") Or FindString(Part, "?")
If Not BakaShrot_IsValidPattern(Part)
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't a valid pattern, * and ? among A-Z a-z 0-9 _ . -"
ProcedureReturn #False
EndIf
AddElement(*Set\Patterns())
*Set\Patterns() = Part
Continue
EndIf
; Names can have dashes too, only digits on both sides make a range.
DashPos = FindString(Part, "-")
If DashPos And BakaShrot_IsDigits(Trim(Left(Part, DashPos - 1))) And BakaShrot_IsDigits(Trim(Mid(Part, DashPos + 1)))
FromId = BakaShrot_RefToId(Trim(Left(Part, DashPos - 1)))
ToId = BakaShrot_RefToId(Trim(Mid(Part, DashPos + 1)))
If FromId < 0 Or ToId < 0 Or FromId > ToId
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't a valid range of ids"
ProcedureReturn #False
EndIf
For Id = FromId To ToId
*Set\Ids(Str(Id)) = #True
If IsNodes
*Config\UsedNodeIds(Str(Id)) = #True
Else
*Config\UsedTopicIds(Str(Id)) = #True
EndIf
Next
Else
If IsNodes
Id = ResolveConfigNode(*Config, Part)
Else
Id = ResolveConfigTopic(*Config, Part)
EndIf
If Id < 0
BakaShrot_ConfigError = Where + ": unknown " + Kind + " '" + Part + "', not an id, a pattern, nor in " + Section
ProcedureReturn #False
EndIf
*Set\Ids(Str(Id)) = #True
If IsNodes
*Config\UsedNodeIds(Str(Id)) = #True
Else
*Config\UsedTopicIds(Str(Id)) = #True
EndIf
EndIf
Next
ProcedureReturn #True
EndProcedure
; A topic list, see ParseNameSet().
Procedure.i ParseTopicSet(*Config.BakaShrot_CoreConfig, Text.s, *Set.BakaShrot_NameSet, Where.s)
ProcedureReturn ParseNameSet(*Config, Text, *Set, #False, Where)
EndProcedure
; Parses a "Key;Key;..." list into a list of Base64 public keys.
Procedure ParsePublicKeyList(KeysString.s, List Keys.s())
Protected i, Part.s
ClearList(Keys())
For i = 1 To CountString(KeysString, ";") + 1
Part = Trim(StringField(KeysString, i, ";"))
If Part = ""
Continue
EndIf
AddElement(Keys())
Keys() = Part
Next
EndProcedure
; Serializes a list of Base64 public keys back into "Key;Key;..." form.
Procedure.s FormatPublicKeyList(List Keys.s())
Protected Result.s
ForEach Keys()
If Result <> ""
Result + ";"
EndIf
Result + Keys()
Next
ProcedureReturn Result
EndProcedure
; Parses a "Topic:Node;Topic:Node;..." list into a list of identities.
; Returns #False if an entry isn't exactly "Topic:Node" with known refs,
; since silently turning a typo into a 0:0 identity would grant an identity
; nobody asked for.
Procedure.i ParseIdentityList(*Config.BakaShrot_CoreConfig, IdentitiesString.s, List Identities.BakaShrot_ClientIdentity(), Where.s)
Protected i, Part.s, TopicPart.s, NodePart.s, TopicId.i, NodeId.i
ClearList(Identities())
For i = 1 To CountString(IdentitiesString, ";") + 1
Part = Trim(StringField(IdentitiesString, i, ";"))
If Part = ""
Continue
EndIf
If CountString(Part, ":") <> 1
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node"
ProcedureReturn #False
EndIf
TopicPart = Trim(StringField(Part, 1, ":"))
NodePart = Trim(StringField(Part, 2, ":"))
If TopicPart = "" Or NodePart = ""
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node"
ProcedureReturn #False
EndIf
TopicId = ResolveConfigTopic(*Config, TopicPart)
NodeId = ResolveConfigNode(*Config, NodePart)
If TopicId < 0
BakaShrot_ConfigError = Where + ": unknown topic '" + TopicPart + "', not an id nor in [BakaShrot.Topics]"
ProcedureReturn #False
EndIf
If NodeId < 0
BakaShrot_ConfigError = Where + ": unknown node '" + NodePart + "', not an id nor in [BakaShrot.Nodes]"
ProcedureReturn #False
EndIf
AddElement(Identities())
Identities()\TopicId = TopicId
Identities()\NodeId = NodeId
*Config\UsedTopicIds(Str(TopicId)) = #True
*Config\UsedNodeIds(Str(NodeId)) = #True
Next
ProcedureReturn #True
EndProcedure
; Returns the name of the [BakaShrot.Client.<name>] section allowing both
; PublicKey and the TopicId:NodeId identity, or "" if none does.
; Not thread-safe, it moves *Config\Clients()' current element.
Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i)
Protected KeyAllowed.i, IdentityAllowed.i
ForEach *Config\Clients()
KeyAllowed = #False
ForEach *Config\Clients()\PublicKeys()
If *Config\Clients()\PublicKeys() = PublicKey
KeyAllowed = #True
Break
EndIf
Next
IdentityAllowed = #False
ForEach *Config\Clients()\Identities()
If *Config\Clients()\Identities()\TopicId = TopicId And *Config\Clients()\Identities()\NodeId = NodeId
IdentityAllowed = #True
Break
EndIf
Next
If KeyAllowed And IdentityAllowed
ProcedureReturn MapKey(*Config\Clients())
EndIf
Next
ProcedureReturn ""
EndProcedure
; Returns the name of the [BakaShrot.Peer.<name>] section with exactly this
; public key and TopicId:NodeId identity, or "" if none has.
; Not thread-safe, it moves *Config\Peers()' current element.
Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i)
ForEach *Config\Peers()
If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\TopicId = TopicId And *Config\Peers()\NodeId = NodeId
ProcedureReturn MapKey(*Config\Peers())
EndIf
Next
ProcedureReturn ""
EndProcedure
Procedure FreeConfig(*Config.BakaShrot_CoreConfig)
FreeStructure(*Config)
EndProcedure
; Loads IniFilePath. Returns 0 on failure, with the reason in BakaShrot_ConfigError.
Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
Protected *Config.BakaShrot_CoreConfig
Protected GroupName.s, PeerName.s, ClientName.s, Text.s, Id.i
Protected NewList PeerNames.s(), NewList ClientNames.s()
Protected Failed.i = #False
BakaShrot_ConfigError = ""
If Not OpenPreferences(IniFilePath)
BakaShrot_ConfigError = "can't open '" + IniFilePath + "'"
ProcedureReturn 0
EndIf
*Config = AllocateStructure(BakaShrot_CoreConfig)
If Not *Config
ClosePreferences()
BakaShrot_ConfigError = "out of memory"
ProcedureReturn 0
EndIf
; Names first, everything else can refer to them.
If Not ParseNameSection("BakaShrot.Topics", "topic", *Config\TopicIds(), *Config\TopicNames()) Or
Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames())
Goto LoadFailed
EndIf
ForEach *Config\TopicNames()
*Config\UsedTopicIds(MapKey(*Config\TopicNames())) = #True
Next
ForEach *Config\NodeNames()
*Config\UsedNodeIds(MapKey(*Config\NodeNames())) = #True
Next
PreferenceGroup("BakaShrot")
*Config\PrivateKey = ReadPreferenceString("PrivateKey", "")
*Config\TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0"))
*Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0"))
Id = ResolveConfigTopic(*Config, *Config\TopicText)
If Id < 0
BakaShrot_ConfigError = "[BakaShrot] Topic: unknown topic '" + *Config\TopicText + "'"
Goto LoadFailed
EndIf
*Config\TopicId = Id
Id = ResolveConfigNode(*Config, *Config\NodeText)
If Id < 0
BakaShrot_ConfigError = "[BakaShrot] Node: unknown node '" + *Config\NodeText + "'"
Goto LoadFailed
EndIf
*Config\NodeId = Id
*Config\UsedTopicIds(Str(*Config\TopicId)) = #True
*Config\UsedNodeIds(Str(*Config\NodeId)) = #True
PreferenceGroup("BakaShrot.Server")
*Config\Server\Host = ReadPreferenceString("Host", "")
*Config\Server\Port = ReadPreferenceLong("Port", 0)
*Config\Server\NetThreadPoolSize = ReadPreferenceLong("NetThreadPoolSize", #BakaShrot_Config_DefaultNetThreadPoolSize)
*Config\Server\DatabasePath = ReadPreferenceString("DatabasePath", #BakaShrot_Config_DefaultDatabasePath)
*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\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "")
If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics")
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
; would lose the walk's place.
If ExaminePreferenceGroups()
While NextPreferenceGroup()
GroupName = PreferenceGroupName()
If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.")
AddElement(PeerNames())
PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1)
EndIf
If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.")
AddElement(ClientNames())
ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1)
EndIf
Wend
EndIf
ForEach PeerNames()
PeerName = PeerNames()
PreferenceGroup("BakaShrot.Peer." + PeerName)
AddMapElement(*Config\Peers(), PeerName)
With *Config\Peers()
\Host = ReadPreferenceString("Host", "")
\Port = ReadPreferenceLong("Port", 0)
\PublicKey = ReadPreferenceString("PublicKey", "")
\TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0"))
\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0"))
Id = ResolveConfigTopic(*Config, \TopicText)
If Id < 0
BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Topic: unknown topic '" + \TopicText + "'"
Failed = #True : Break
EndIf
\TopicId = Id
Id = ResolveConfigNode(*Config, \NodeText)
If Id < 0
BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: unknown node '" + \NodeText + "'"
Failed = #True : Break
EndIf
\NodeId = Id
*Config\UsedTopicIds(Str(\TopicId)) = #True
*Config\UsedNodeIds(Str(\NodeId)) = #True
\SendTopicsText = ReadPreferenceString("SendTopics", #BakaShrot_Config_Missing)
If \SendTopicsText = #BakaShrot_Config_Missing
CopyStructure(@*Config\Server\ReplicatingTopics, @\SendTopics, BakaShrot_NameSet)
ElseIf Not ParseTopicSet(*Config, \SendTopicsText, @\SendTopics, "[BakaShrot.Peer." + PeerName + "] SendTopics")
Failed = #True : Break
EndIf
\AcceptTopicsText = ReadPreferenceString("AcceptTopics", #BakaShrot_Config_Missing)
If \AcceptTopicsText = #BakaShrot_Config_Missing
CopyStructure(@*Config\Server\ReplicatingTopics, @\AcceptTopics, BakaShrot_NameSet)
ElseIf Not ParseTopicSet(*Config, \AcceptTopicsText, @\AcceptTopics, "[BakaShrot.Peer." + PeerName + "] AcceptTopics")
Failed = #True : Break
EndIf
\SendNodesText = ReadPreferenceString("SendNodes", #BakaShrot_Config_Missing)
If \SendNodesText = #BakaShrot_Config_Missing
\SendNodes\All = #True
ElseIf Not ParseNameSet(*Config, \SendNodesText, @\SendNodes, #True, "[BakaShrot.Peer." + PeerName + "] SendNodes")
Failed = #True : Break
EndIf
\AcceptNodesText = ReadPreferenceString("AcceptNodes", #BakaShrot_Config_Missing)
If \AcceptNodesText = #BakaShrot_Config_Missing
\AcceptNodes\Known = #True
ElseIf Not ParseNameSet(*Config, \AcceptNodesText, @\AcceptNodes, #True, "[BakaShrot.Peer." + PeerName + "] AcceptNodes")
Failed = #True : Break
EndIf
EndWith
Next
If Failed
Goto LoadFailed
EndIf
ForEach ClientNames()
ClientName = ClientNames()
PreferenceGroup("BakaShrot.Client." + ClientName)
AddMapElement(*Config\Clients(), ClientName)
With *Config\Clients()
ParsePublicKeyList(ReadPreferenceString("PublicKeys", ""), \PublicKeys())
\IdentitiesText = ReadPreferenceString("Identities", "")
If Not ParseIdentityList(*Config, \IdentitiesText, \Identities(), "[BakaShrot.Client." + ClientName + "] Identities")
Failed = #True : Break
EndIf
\Permissions\Read = Bool(ReadPreferenceLong("AllowRead", #BakaShrot_Config_DefaultAllowRead) <> 0)
\Permissions\Write = Bool(ReadPreferenceLong("AllowWrite", #BakaShrot_Config_DefaultAllowWrite) <> 0)
\Permissions\Query = Bool(ReadPreferenceLong("AllowQuery", #BakaShrot_Config_DefaultAllowQuery) <> 0)
; By default, only the topics it authenticates in, like before.
\PushTopicsText = ReadPreferenceString("PushTopics", #BakaShrot_Config_Missing)
\ReadTopicsText = ReadPreferenceString("ReadTopics", #BakaShrot_Config_Missing)
If \PushTopicsText = #BakaShrot_Config_Missing
ForEach \Identities()
\PushTopics\Ids(Str(\Identities()\TopicId)) = #True
Next
ElseIf Not ParseTopicSet(*Config, \PushTopicsText, @\PushTopics, "[BakaShrot.Client." + ClientName + "] PushTopics")
Failed = #True : Break
EndIf
If \ReadTopicsText = #BakaShrot_Config_Missing
ForEach \Identities()
\ReadTopics\Ids(Str(\Identities()\TopicId)) = #True
Next
ElseIf Not ParseTopicSet(*Config, \ReadTopicsText, @\ReadTopics, "[BakaShrot.Client." + ClientName + "] ReadTopics")
Failed = #True : Break
EndIf
EndWith
Next
If Failed
Goto LoadFailed
EndIf
ClosePreferences()
ProcedureReturn *Config
LoadFailed:
ClosePreferences()
FreeConfig(*Config)
ProcedureReturn 0
EndProcedure
; Writes a key, unless its text is #BakaShrot_Config_Missing.
Procedure WriteConfigText(Key.s, Text.s)
If Text <> #BakaShrot_Config_Missing
WritePreferenceString(Key, Text)
EndIf
EndProcedure
; Saves *Config back, lists and refs as they were written in the ini.
Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
If Not CreatePreferences(IniFilePath)
ProcedureReturn #False
EndIf
PreferenceGroup("BakaShrot")
WritePreferenceString("PrivateKey", *Config\PrivateKey)
WritePreferenceString("Topic", *Config\TopicText)
WritePreferenceString("Node", *Config\NodeText)
PreferenceGroup("BakaShrot.Server")
WritePreferenceString("Host", *Config\Server\Host)
WritePreferenceLong("Port", *Config\Server\Port)
WritePreferenceString("ReplicatingTopics", *Config\Server\ReplicatingTopicsText)
WritePreferenceLong("NetThreadPoolSize", *Config\Server\NetThreadPoolSize)
WritePreferenceString("DatabasePath", *Config\Server\DatabasePath)
WritePreferenceLong("PeerRetryDelay", *Config\Server\PeerRetryDelay)
WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval)
WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize)
PreferenceGroup("BakaShrot.Topics")
ForEach *Config\TopicNames()
WritePreferenceString(*Config\TopicNames(), MapKey(*Config\TopicNames()))
Next
PreferenceGroup("BakaShrot.Nodes")
ForEach *Config\NodeNames()
WritePreferenceString(*Config\NodeNames(), MapKey(*Config\NodeNames()))
Next
ForEach *Config\Peers()
PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers()))
WritePreferenceString("Host", *Config\Peers()\Host)
WritePreferenceLong("Port", *Config\Peers()\Port)
WritePreferenceString("Topic", *Config\Peers()\TopicText)
WritePreferenceString("Node", *Config\Peers()\NodeText)
WritePreferenceString("PublicKey", *Config\Peers()\PublicKey)
WriteConfigText("SendTopics", *Config\Peers()\SendTopicsText)
WriteConfigText("AcceptTopics", *Config\Peers()\AcceptTopicsText)
WriteConfigText("SendNodes", *Config\Peers()\SendNodesText)
WriteConfigText("AcceptNodes", *Config\Peers()\AcceptNodesText)
Next
ForEach *Config\Clients()
PreferenceGroup("BakaShrot.Client." + MapKey(*Config\Clients()))
WritePreferenceString("PublicKeys", FormatPublicKeyList(*Config\Clients()\PublicKeys()))
WritePreferenceString("Identities", *Config\Clients()\IdentitiesText)
WritePreferenceLong("AllowRead", *Config\Clients()\Permissions\Read)
WritePreferenceLong("AllowWrite", *Config\Clients()\Permissions\Write)
WritePreferenceLong("AllowQuery", *Config\Clients()\Permissions\Query)
WriteConfigText("PushTopics", *Config\Clients()\PushTopicsText)
WriteConfigText("ReadTopics", *Config\Clients()\ReadTopicsText)
Next
ClosePreferences()
ProcedureReturn #True
EndProcedure
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
CompilerIf #PB_Compiler_IsMainFile
Define *Config.BakaShrot_CoreConfig = LoadConfig("schema.ini")
If *Config
Debug "PrivateKey: " + *Config\PrivateKey
Debug "TopicId: " + Str(*Config\TopicId)
Debug "NodeId: " + Str(*Config\NodeId)
Debug "Server: " + *Config\Server\Host + ":" + Str(*Config\Server\Port)
Debug " NetThreadPoolSize: " + Str(*Config\Server\NetThreadPoolSize)
Debug " Replicating: " + *Config\Server\ReplicatingTopicsText
ForEach *Config\TopicNames()
Debug "Topic " + *Config\TopicNames() + " = " + MapKey(*Config\TopicNames())
Next
ForEach *Config\NodeNames()
Debug "Node " + *Config\NodeNames() + " = " + MapKey(*Config\NodeNames())
Next
ForEach *Config\Peers()
Debug "Peer '" + MapKey(*Config\Peers()) + "': " + *Config\Peers()\Host + ":" + Str(*Config\Peers()\Port) + " PublicKey=" + *Config\Peers()\PublicKey
Next
ForEach *Config\Clients()
Debug "Client '" + MapKey(*Config\Clients()) + "':"
ForEach *Config\Clients()\PublicKeys()
Debug " PublicKey: " + *Config\Clients()\PublicKeys()
Next
ForEach *Config\Clients()\Identities()
Debug " Identity: " + Str(*Config\Clients()\Identities()\TopicId) + ":" + Str(*Config\Clients()\Identities()\NodeId)
Next
Next
SaveConfig("schema_out.ini", *Config)
FreeConfig(*Config)
Else
Debug "Failed to load schema.ini: " + BakaShrot_ConfigError
EndIf
CompilerEndIf
+8
View File
@@ -0,0 +1,8 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
CursorPosition = 135
Folding = --
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 1
EnableBuildCount = 0
+149
View File
@@ -0,0 +1,149 @@
; BakaShrot server config file.
; Section names are literal strings as far as PureBasic's Preferences
; library is concerned — the dots below are just part of the name.
;
; Topics and nodes: each has an id (0-65535) on this server, and can have a
; name, in [BakaShrot.Topics] and [BakaShrot.Nodes]. Names are what's shared
; between servers: replication sends them, and each server stores the
; messages under its own ids for them ("logs" can be 1 here and 200 on a
; peer).
; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a
; name, or whose name the other server doesn't have, is dropped. Unnamed
; ones still work locally, by id.
; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter.
; The server's "names" command and the ListNames tool list them all.
;
; Topic, Node and ReplicatingTopics were TopicId, NodeId and
; ReplicatingTopicIds before: the old names are still read.
;
; Everywhere below, a topic or node can be written as a name or an id.
; Topic lists (and a peer's node lists): names and ids separated by ";",
; ranges of ids (100-150), wildcards like file names (sensors.*, kitchen-??:
; * any characters, ? one, they only match names), or * for every one.
; In a peer's AcceptTopics / AcceptNodes, * and wildcards also take names
; this server doesn't have: they get an id here by themselves, the highest
; free one counting down from 65535 (see them with the "names" command).
[BakaShrot]
; Config shared by every type of config.
; This node's Ed25519 private key (Base64), from KeyGen.exe. It proves who
; this server is: clients seal their Hello for its public key and check
; that it signed the handshake, so they need that public key (client.ini's
; ServerPublicKey, peers' PublicKey below in THEIR own config). The server
; logs it when it starts. See Commons/Networking/Connections.pbi.
PrivateKey =
; The topic and node this server authenticates as when it links to its
; peers, a name or an id. Its peers must register it under the same names.
Topic =
Node =
[BakaShrot.Topics]
; One line per named topic: name = this server's id for it.
; logs = 1
; sensors = 2
[BakaShrot.Nodes]
; One line per named node (a client's or a server's), same as topics. Every
; server that should get a node's messages must name it too.
; Once a name has messages, keep its id: the server refuses to start if the
; config moves it to another one, and says which id to use.
; kitchen = 2
[BakaShrot.Server]
; IPV4 that the server will be bound to.
Host =
; Used port.
Port =
; The topics replicated with every peer that doesn't say otherwise
; (SendTopics, AcceptTopics below).
; Format: logs;0;100-150;... or * for every topic.
ReplicatingTopics =
; Amount of threads used for networking-related tasks.
NetThreadPoolSize = 4
; SQLite database file holding the messages.
DatabasePath = ./test.sqlite
; Seconds to wait before connecting to a peer again, after failing to
; connect or losing the connection.
PeerRetryDelay = 10
; Seconds between two check-ins with a linked peer, where it's sent the
; messages it's missing.
PeerSyncInterval = 5
; Most messages sent to a peer per packet when it's missing some, 1-10000.
; A batch is also cut short at about 64 KB, a bigger message goes alone.
PeerBatchSize = 100
; 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.
[BakaShrot.Peer.example]
; Remote address of the peer. Can be a domain name, IPV4 or IPV6.
Host =
; Remote port of the peer (0-65535).
Port =
; The server links to every peer on start, and retries every PeerRetryDelay.
; The peer must register this server in one of its [BakaShrot.Client.<name>].
; The link only goes through if the peer proves it holds the private key
; of PublicKey below, and it's encrypted.
; Remote node's topic and node, names or ids. The peer authenticates with
; them when it links to here.
Topic =
Node =
; The topics sent to this peer (if it takes them), and the topics taken
; from it. Both default to ReplicatingTopics.
; SendTopics = logs;sensors.*
; AcceptTopics = logs;sensors.*
; The nodes whose messages are sent to this peer (default: every one), and
; the nodes whose messages are taken from it (default: the ones named in
; [BakaShrot.Nodes], no other). AcceptNodes = kitchen-* takes every
; kitchen-something the peer sends, named here or not.
; SendNodes = *
; AcceptNodes = kitchen-*;garage
; This peer's Ed25519 public key (Base64), required: the link's Hello is
; sealed for it, and the peer must sign the handshake with its private key.
; It's also the key the peer authenticates with when it links to here.
PublicKey =
; One [BakaShrot.Client.<name>] section per client allowed to connect.
; <name> is only a key for this file; it is never sent on the wire.
[BakaShrot.Client.example]
; Ed25519 public keys (Base64) this client is allowed to authenticate with.
; Format: Key;Key;...
PublicKeys =
; Topic and node pairs this client is allowed to authenticate as, names or ids.
; Format: Topic:Node;Topic:Node;...
Identities =
; The topics it may push to (always under its own node), and the topics it
; may read the latest messages of. Both default to the topics of its
; Identities, empty allows none.
; PushTopics = logs;sensors
; ReadTopics = *
; What this client may do once authenticated, 1 to allow, 0 to deny.
; Read: GetLatestMessage. Write: PushMessage.
; Query: raw read-only SQL, which can read every topic's data, whatever
; ReadTopics says. The "messages" view has the names:
; SELECT * FROM messages WHERE topic = 'logs' AND node = 'kitchen'
AllowRead = 1
AllowWrite = 1
AllowQuery = 0
+14
View File
@@ -0,0 +1,14 @@
[BakaShrot]
PrivateKey =
TopicId = 0
NodeId = 0
[BakaShrot.Server]
Host =
Port = 0
ReplicatingTopicIds =
[BakaShrot.Peer.example]
Host =
Port = 0
TopicId = 0
NodeId = 0
File diff suppressed because it is too large Load Diff
+7
View File
@@ -0,0 +1,7 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
EnableThread
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 0
EnableBuildCount = 0
+568
View File
@@ -0,0 +1,568 @@
; ============================================================================
; BakaShrot Server Peers
;
; Links this server to the other servers in its config's
; [BakaShrot.Peer.<name>] sections, one thread per peer. Each thread:
; 1. Connects to the peer and authenticates with this server's own identity
; ([BakaShrot] PrivateKey/TopicId/NodeId), like a client would. The peer
; must have it registered in one of its [BakaShrot.Client.<name>].
; 2. Stays connected until the link drops.
; 3. Waits [BakaShrot.Server] PeerRetryDelay seconds, then starts over.
; Same after a failed attempt.
;
; Once linked, it checks in with the peer every [BakaShrot.Server]
; PeerSyncInterval seconds, starting right away:
; 1. Asks the peer for its sync state: the topics it takes from this
; server, and the highest message id it has for each of their
; topic/node ids, in its own ids, with their names.
; 2. Compares it with this server's own (GetSyncState() in Storage.pbi),
; matching topics and nodes by name: each server has its own ids, see
; Server/Storage/Names.pbi. Only what's named on both sides replicates:
; an unnamed one, or one whose name the peer doesn't list, is dropped
; (BakaShrot_Names_NoteDropped()).
; 3. For every topic/node the peer takes, this server sends it
; (the peer section's SendTopics), and the peer is behind on, sends it
; the missing messages in order, in batches of up to
; [BakaShrot.Server] PeerBatchSize messages, about 64 KB at most (a
; bigger message goes alone, see ReplicateMessagesPacket.pbi), each
; batch stored in one transaction and answered before the next. The
; batches carry the names, the peer stores them under its own ids.
; The peer does the same over its own link to this server, which covers the
; other direction. Any packet from the peer outside of a check-in drops the
; link as unexpected.
; Known issues, like two servers drifting apart: Design/ReplicationIssues.md.
;
; Each link thread opens its own database connection when it starts, and
; closes it when it ends. See the top of Storage/Storage.pbi.
;
; The peer proves itself in the handshake: the Hello is sealed for the peer
; section's PublicKey and the peer must sign the handshake with the matching
; private key, so a link only reaches the real peer, and is encrypted
; (Commons/Networking/Connections.pbi).
;
; Logs with PrintN(), so the program must have a console open.
; Must be compiled with the thread-safe option enabled.
; ============================================================================
CompilerIf Not #PB_Compiler_Thread
CompilerError "Peers.pbi needs the thread-safe option (Compiler Options > Create threadsafe executable)."
CompilerEndIf
XIncludeFile "../../Commons/Networking/Outbound.pbi"
XIncludeFile "../Config/Config.pbi"
XIncludeFile "../Storage/Storage.pbi"
XIncludeFile "../Storage/Names.pbi"
Structure BakaShrot_PeerLink
*Links
; [BakaShrot.Peer.<name>]
Name.s
Host.s
Port.i
; The peer section's PublicKey: who the peer must prove to be.
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
ThreadId.i
; Only used by the link's thread.
Outbound.BakaShrot_Outbound
DbId.i
; The peer section's SendTopics and SendNodes, copied for the link's thread.
SendTopics.BakaShrot_NameSet
SendNodes.BakaShrot_NameSet
EndStructure
Structure BakaShrot_PeerLinks
; Set by BakaShrot_PeerLinks_Stop(), makes every link's thread return.
StopRequested.i
RetryDelayMs.i
SyncIntervalMs.i
; Most messages sent per ReplicateMessages packet.
BatchSize.i
; Every link's thread opens its own connection to it.
DatabasePath.s
; This server's identity, read by every link's thread.
Identity.BakaShrot_OutboundIdentity
PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize]
PublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
List Links.BakaShrot_PeerLink()
EndStructure
; Waits the retry delay, returns early if stopping.
Procedure BakaShrot_PeerLink_WaitRetry(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected StartTime.i
StartTime = ElapsedMilliseconds()
While Not *Links\StopRequested And ElapsedMilliseconds() - StartTime < *Links\RetryDelayMs
Delay(100)
Wend
EndProcedure
; Sends a request to the peer and waits for its answer.
; Returns the answer (free it with FreeMemory) with its size in *OutSize\i,
; or 0 if the link failed.
Procedure.i BakaShrot_PeerLink_Request(*Link.BakaShrot_PeerLink, *Request, RequestSize.i, *OutSize.Integer)
If Not BakaShrot_Outbound_Send(@*Link\Outbound, *Request, RequestSize)
ProcedureReturn 0
EndIf
ProcedureReturn BakaShrot_Outbound_WaitPacket(@*Link\Outbound, *OutSize, #BakaShrot_Outbound_Timeout)
EndProcedure
; Logs a RequestRefused answer from the peer.
; Returns #False if it's malformed, the link must then be dropped.
Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, AnswerSize.i)
Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused
*Refused = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize)
If *View
*Refused = BakaShrot_RequestRefusedPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
If Not *Refused
ProcedureReturn #False
EndIf
PrintN("[Peer] '" + *Link\Name + "' refused: " + *Refused\Reason)
FreeStructure(*Refused)
ProcedureReturn #True
EndProcedure
; Sends a batch of messages the peer is missing and checks its answer.
; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the
; link must be dropped.
Procedure.i BakaShrot_PeerLink_SendBatch(*Link.BakaShrot_PeerLink, *Batch.BakaShrot_ReplicateMessages)
Protected *Pushed.BakaShrot_MessagePushed
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
Protected *View.MsgPackData, IsRefusal.i, IsAcknowledged.i, LastMessageId.q
LastElement(*Batch\Messages())
LastMessageId = *Batch\Messages()\MessageId
*Packet = BakaShrot_ReplicateMessagesPacket_Encode(*Batch, @PacketSize)
If Not *Packet
ProcedureReturn -1
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
ProcedureReturn -1
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
If Not IsRefusal
ProcedureReturn -1
EndIf
ProcedureReturn 0
EndIf
*Pushed = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*Pushed = BakaShrot_MessagePushedPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *Pushed
ProcedureReturn -1
EndIf
; An acknowledgement for anything but the batch's last message is out of order.
IsAcknowledged = Bool(*Pushed\MessageId = LastMessageId)
FreeStructure(*Pushed)
If Not IsAcknowledged
ProcedureReturn -1
EndIf
ProcedureReturn 1
EndProcedure
; Sends every message of a topic/node id above AfterMessageId, in order, in
; batches of up to [BakaShrot.Server] PeerBatchSize messages, each one cut
; short at about #BakaShrot_ReplicateBatchBytes (a bigger message alone). TopicRef and NodeRef are what they
; go by on the wire: their names, or their ids in digits.
; Stops at the first refusal, or if the server is stopping.
; Returns how many were stored, or -1 if the link must be dropped.
Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, AfterMessageId.q)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected NewList Messages.BakaShrot_Message()
Protected Batch.BakaShrot_ReplicateMessages
Protected SentCount.i, Result.i, BatchSize.i, MessageSize.i
Batch\Topic = TopicRef
Batch\Node = NodeRef
Repeat
If *Links\StopRequested
ProcedureReturn SentCount
EndIf
If Not GetMessagesAfter(*Link\DbId, TopicId, NodeId, AfterMessageId, *Links\BatchSize, #BakaShrot_ReplicateBatchBytes, Messages())
PrintN("[Peer] Failed to read the messages to send to '" + *Link\Name + "': " + DatabaseError())
ProcedureReturn SentCount
EndIf
If ListSize(Messages()) = 0
ProcedureReturn SentCount
EndIf
; As many as fit in #BakaShrot_ReplicateBatchBytes, the rest goes in the
; next batch. A bigger message goes alone, if it fits in a packet.
ClearList(Batch\Messages())
BatchSize = #BakaShrot_ReplicateBatchOverhead
ForEach Messages()
MessageSize = #BakaShrot_ReplicateMessageOverhead + StringByteLength(Messages()\JsonData, #PB_UTF8)
If ListSize(Batch\Messages()) > 0 And BatchSize + MessageSize > #BakaShrot_ReplicateBatchBytes
Break
EndIf
If BatchSize + MessageSize > #BakaShrot_MaxPacketSize
Break
EndIf
BatchSize + MessageSize
AddElement(Batch\Messages())
Batch\Messages()\MessageId = Messages()\MessageId
Batch\Messages()\JsonData = Messages()\JsonData
Next
If ListSize(Batch\Messages()) = 0
FirstElement(Messages())
PrintN("[Peer] Message " + TopicRef + ":" + NodeRef + "#" + Str(Messages()\MessageId) + " is too big to replicate to '" + *Link\Name + "', skipping the rest of this pair")
ProcedureReturn SentCount
EndIf
Result = BakaShrot_PeerLink_SendBatch(*Link, @Batch)
If Result = -1
ProcedureReturn -1
EndIf
If Result = 0
ProcedureReturn SentCount
EndIf
SentCount + ListSize(Batch\Messages())
LastElement(Batch\Messages())
AfterMessageId = Batch\Messages()\MessageId
ForEver
EndProcedure
; #True if Name matches one of Patterns() (Commons/Networking/Names.pbi).
Procedure.i BakaShrot_MatchesAny(List Patterns.s(), Name.s)
ForEach Patterns()
If BakaShrot_GlobMatch(Patterns(), Name)
ProcedureReturn #True
EndIf
Next
ProcedureReturn #False
EndProcedure
; Asks the peer where it's at, and sends it the messages it's missing.
; Returns #False if the link must be dropped.
Procedure.i BakaShrot_PeerLink_CheckIn(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected Request.BakaShrot_SyncStateRequest
Protected *State.BakaShrot_SyncState
Protected NewList LocalPairs.BakaShrot_SyncPair()
Protected NewMap RemoteTopics.i(), NewMap RemoteNodes.i()
Protected NewList RemoteTopicPatterns.s(), NewList RemoteNodePatterns.s()
Protected NewMap RemoteMessageIds.q()
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
Protected *View.MsgPackData, IsRefusal.i, Key.s, RemoteMessageId.q, SentCount.i, StartTime.i
Protected TopicRef.s, NodeRef.s, RemoteTopicId.i, RemoteNodeId.i
; 1. The peer's state
*Packet = BakaShrot_SyncStateRequestPacket_Encode(@Request, @PacketSize)
If Not *Packet
ProcedureReturn #False
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
PrintN("[Peer] '" + *Link\Name + "' didn't answer the check-in")
ProcedureReturn #False
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
ProcedureReturn IsRefusal
EndIf
*State = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*State = BakaShrot_SyncStatePacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *State
PrintN("[Peer] '" + *Link\Name + "' sent an invalid sync state")
ProcedureReturn #False
EndIf
; The peer's ids, by LCase(name): every name it knows.
ForEach *State\Topics()
RemoteTopics(LCase(*State\Topics()\Name)) = *State\Topics()\Id
Next
ForEach *State\Nodes()
RemoteNodes(LCase(*State\Nodes()\Name)) = *State\Nodes()\Id
Next
; And what it takes without having it yet.
CopyList(*State\TopicPatterns(), RemoteTopicPatterns())
CopyList(*State\NodePatterns(), RemoteNodePatterns())
ForEach *State\Pairs()
RemoteMessageIds(Str(*State\Pairs()\TopicId) + ":" + Str(*State\Pairs()\NodeId)) = *State\Pairs()\MessageId
Next
FreeStructure(*State)
; 2. This server's state
If Not GetSyncState(*Link\DbId, LocalPairs())
PrintN("[Peer] Failed to read the sync state for '" + *Link\Name + "': " + DatabaseError())
ProcedureReturn #True
EndIf
; 3. The delta, matching this server's topics and nodes to the peer's by
; name. Anything not named on both sides is dropped, unless a wildcard
; of the peer takes it.
ForEach LocalPairs()
TopicRef = BakaShrot_Names_TopicName(LocalPairs()\TopicId)
NodeRef = BakaShrot_Names_NodeName(LocalPairs()\NodeId)
If Not NameSetHas(@*Link\SendTopics, LocalPairs()\TopicId, TopicRef) Or Not NameSetHas(@*Link\SendNodes, LocalPairs()\NodeId, NodeRef)
Continue
EndIf
If TopicRef = ""
BakaShrot_Names_NoteDropped(*Link\Name, "topic", Str(LocalPairs()\TopicId), "unnamed here")
Continue
EndIf
If NodeRef = ""
BakaShrot_Names_NoteDropped(*Link\Name, "node", Str(LocalPairs()\NodeId), "unnamed here")
Continue
EndIf
; -1: the peer doesn't have it yet, but a wildcard of its takes it.
RemoteTopicId = -1
If FindMapElement(RemoteTopics(), LCase(TopicRef))
RemoteTopicId = RemoteTopics()
ElseIf Not BakaShrot_MatchesAny(RemoteTopicPatterns(), TopicRef)
BakaShrot_Names_NoteDropped(*Link\Name, "topic", TopicRef, "not taken by the peer")
Continue
EndIf
RemoteNodeId = -1
If FindMapElement(RemoteNodes(), LCase(NodeRef))
RemoteNodeId = RemoteNodes()
ElseIf Not BakaShrot_MatchesAny(RemoteNodePatterns(), NodeRef)
BakaShrot_Names_NoteDropped(*Link\Name, "node", NodeRef, "not taken by the peer")
Continue
EndIf
RemoteMessageId = 0
If RemoteTopicId >= 0 And RemoteNodeId >= 0 And FindMapElement(RemoteMessageIds(), Str(RemoteTopicId) + ":" + Str(RemoteNodeId))
RemoteMessageId = RemoteMessageIds()
EndIf
Key = TopicRef + ":" + NodeRef
If LocalPairs()\MessageId > RemoteMessageId
StartTime = ElapsedMilliseconds()
SentCount = BakaShrot_PeerLink_SendMissing(*Link, LocalPairs()\TopicId, LocalPairs()\NodeId, TopicRef, NodeRef, RemoteMessageId)
If SentCount < 0
ProcedureReturn #False
EndIf
If SentCount > 0
PrintN("[Peer] Sent " + Str(SentCount) + " messages of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, it had up to #" + Str(RemoteMessageId))
EndIf
EndIf
Next
ProcedureReturn #True
EndProcedure
; Keeps a linked peer's connection, checking in every sync interval, until it
; drops, a check-in fails, the peer sends something unasked, or the server is
; stopping. The connection is closed when it returns.
Procedure BakaShrot_PeerLink_StayLinked(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected LastCheckIn.i
; Checks in right away.
LastCheckIn = ElapsedMilliseconds() - *Links\SyncIntervalMs
While Not *Links\StopRequested
If ElapsedMilliseconds() - LastCheckIn >= *Links\SyncIntervalMs
If Not BakaShrot_PeerLink_CheckIn(*Link)
PrintN("[Peer] Dropping the link to '" + *Link\Name + "', the check-in failed")
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Aborted)
ProcedureReturn
EndIf
LastCheckIn = ElapsedMilliseconds()
EndIf
Select NetworkClientEvent(*Link\Outbound\ConnectionId)
Case #PB_NetworkEvent_Data
PrintN("[Peer] '" + *Link\Name + "' sent a packet it wasn't asked for")
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Aborted)
ProcedureReturn
Case #PB_NetworkEvent_Disconnect
PrintN("[Peer] Lost the link to '" + *Link\Name + "'")
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
ProcedureReturn
Default
Delay(50)
EndSelect
Wend
BakaShrot_Outbound_Close(@*Link\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
EndProcedure
Procedure BakaShrot_PeerLink_Thread(*Link.BakaShrot_PeerLink)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected Target.s = "'" + *Link\Name + "' (" + *Link\Host + ":" + Str(*Link\Port) + ")"
*Link\DbId = OpenStorageDatabase(*Links\DatabasePath)
If Not *Link\DbId
PrintN("[Peer] Failed to open the database for " + Target + ", not linking to it: " + DatabaseError())
ProcedureReturn
EndIf
; Waits for the peer's answers stop early when the server is stopping.
*Link\Outbound\StopRequested = @*Links\StopRequested
While Not *Links\StopRequested
If BakaShrot_Outbound_Connect(@*Link\Outbound, *Link\Host, *Link\Port, @*Links\Identity, @*Link\ServerPublicKey[0])
PrintN("[Peer] Linked to " + Target)
BakaShrot_PeerLink_StayLinked(*Link)
Else
PrintN("[Peer] Failed to link to " + Target + ", unreachable, or the handshake failed (is its PublicKey right?)")
EndIf
If Not *Links\StopRequested
PrintN("[Peer] Retrying " + Target + " in " + Str(*Links\RetryDelayMs / 1000) + "s")
BakaShrot_PeerLink_WaitRetry(*Link)
EndIf
Wend
CloseDatabase(*Link\DbId)
*Link\DbId = 0
EndProcedure
; Stops every link's thread, closes their connections and frees *Links.
; Once it returns, no link thread is left, so none holds a database
; connection either.
; Waits for a peer's answer stop within a few ms, but a thread opening a
; connection is blocked in OpenNetworkConnection() until it succeeds or
; fails.
Procedure BakaShrot_PeerLinks_Stop(*Links.BakaShrot_PeerLinks)
*Links\StopRequested = #True
ForEach *Links\Links()
If *Links\Links()\ThreadId
WaitThread(*Links\Links()\ThreadId)
EndIf
Next
; Don't leave the private key lying around in freed memory.
FillMemory(@*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize, 0)
FreeStructure(*Links)
EndProcedure
; Starts a link to every [BakaShrot.Peer.<name>] in *Config, replicating
; the messages in its [BakaShrot.Server] DatabasePath. *Config must outlive
; the links.
; Returns 0 if *Config's PrivateKey is invalid or a thread couldn't start,
; stop the returned links with BakaShrot_PeerLinks_Stop().
Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig)
Protected *Links.BakaShrot_PeerLinks
If Not InitCryptography()
ProcedureReturn 0
EndIf
*Links = AllocateStructure(BakaShrot_PeerLinks)
If Not *Links
ProcedureReturn 0
EndIf
; Identity
If Not DecodeKeyFromString(*Config\PrivateKey, @*Links\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
FreeStructure(*Links)
ProcedureReturn 0
EndIf
GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0])
; By name: the peer has its own ids for them.
*Links\Identity\Topic = BakaShrot_Names_TopicRef(*Config\TopicId)
*Links\Identity\Node = BakaShrot_Names_NodeRef(*Config\NodeId)
*Links\Identity\PublicKey = EncodeKeyToString(@*Links\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
*Links\Identity\PrivateKey = @*Links\PrivateKey[0]
*Links\DatabasePath = *Config\Server\DatabasePath
*Links\RetryDelayMs = *Config\Server\PeerRetryDelay * 1000
If *Links\RetryDelayMs < 1000
*Links\RetryDelayMs = 1000
EndIf
*Links\SyncIntervalMs = *Config\Server\PeerSyncInterval * 1000
If *Links\SyncIntervalMs < 1000
*Links\SyncIntervalMs = 1000
EndIf
*Links\BatchSize = *Config\Server\PeerBatchSize
If *Links\BatchSize < 1
*Links\BatchSize = 1
EndIf
If *Links\BatchSize > #BakaShrot_MaxReplicateBatch
*Links\BatchSize = #BakaShrot_MaxReplicateBatch
EndIf
; Links
ForEach *Config\Peers()
AddElement(*Links\Links())
*Links\Links()\Links = *Links
*Links\Links()\Name = MapKey(*Config\Peers())
*Links\Links()\Host = *Config\Peers()\Host
*Links\Links()\Port = *Config\Peers()\Port
If Not DecodeKeyFromString(*Config\Peers()\PublicKey, @*Links\Links()\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
PrintN("[Peer] [BakaShrot.Peer." + MapKey(*Config\Peers()) + "] PublicKey is missing or invalid")
BakaShrot_PeerLinks_Stop(*Links)
ProcedureReturn 0
EndIf
CopyStructure(@*Config\Peers()\SendTopics, @*Links\Links()\SendTopics, BakaShrot_NameSet)
CopyStructure(@*Config\Peers()\SendNodes, @*Links\Links()\SendNodes, BakaShrot_NameSet)
; List elements never move, so the thread can keep this pointer.
*Links\Links()\ThreadId = CreateThread(@BakaShrot_PeerLink_Thread(), @*Links\Links())
If Not *Links\Links()\ThreadId
BakaShrot_PeerLinks_Stop(*Links)
ProcedureReturn 0
EndIf
Next
ProcedureReturn *Links
EndProcedure
+207
View File
@@ -0,0 +1,207 @@
; ============================================================================
; BakaShrot Server Root
;
; What the main ("root") thread owns and does:
; - The config.
; - Its own database connection: setup, and maintenance while the workers
; are stopped.
; - The workers: the network server (its listener and one thread per
; client, see Networking/Networking.pbi) and the peer links (one thread
; per peer, see Networking/Peers.pbi).
;
; Stopping the workers is the root's signal to every other thread.
; BakaShrot_Root_StopWorkers() sets the StopRequested flag of the network
; server and the peer links, which every one of their threads checks within a
; few ms, then waits until each of those threads has exited. Each one closes
; its own database connection on its way out. So once it returns, the root's
; connection is the only one left, and the root can:
; - BakaShrot_Root_Restart(): reload the config, reopen the database, start
; again. Picks up config changes, like a client's permissions.
; - BakaShrot_Root_Vacuum(): VACUUM the database, start again.
; - Anything else that needs the database or the config to itself.
; Clients and peer links are dropped meanwhile. Peers relink on their own,
; clients have to reconnect.
;
; Only call these from the root thread.
; ============================================================================
XIncludeFile "Config/Config.pbi"
XIncludeFile "Storage/Storage.pbi"
XIncludeFile "Storage/Names.pbi"
XIncludeFile "Networking/Networking.pbi"
XIncludeFile "Networking/Peers.pbi"
Structure BakaShrot_Root
ConfigPath.s
*Config.BakaShrot_CoreConfig
; The root's own connection, only used for setup, and while the workers
; are stopped.
DbId.i
; Both 0 while the workers are stopped.
*Server.BakaShrot_NetServer
*Peers.BakaShrot_PeerLinks
EndStructure
; Loads *Root\ConfigPath into *Root\Config, replacing the current one.
; Returns #False if it can't be loaded, the current one is then kept.
; Only while the workers are stopped, they use the config.
Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root)
Protected *Config.BakaShrot_CoreConfig
*Config = LoadConfig(*Root\ConfigPath)
If Not *Config
PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError)
ProcedureReturn #False
EndIf
If *Root\Config
FreeConfig(*Root\Config)
EndIf
*Root\Config = *Config
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Topic=" + *Config\TopicText + ", Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)")
ProcedureReturn #True
EndProcedure
; Opens the root's connection to the config's database, sets it up, and
; reconciles the config's topic and node names with it (Storage/Names.pbi).
; Returns #False if it can't be opened or set up, or if the names conflict.
Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root)
Protected DatabasePath.s = *Root\Config\Server\DatabasePath
Protected NamesError.String
*Root\DbId = OpenStorageDatabase(DatabasePath)
If Not *Root\DbId
PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError())
ProcedureReturn #False
EndIf
If Not SetupStorageDatabase(*Root\DbId)
PrintN("[Root] Failed to set up the database '" + DatabasePath + "': " + DatabaseError())
CloseDatabase(*Root\DbId)
*Root\DbId = 0
ProcedureReturn #False
EndIf
If Not BakaShrot_Names_Load(*Root\DbId, *Root\Config, @NamesError)
PrintN("[Root] The config's names don't match the database '" + DatabasePath + "': " + NamesError\s)
CloseDatabase(*Root\DbId)
*Root\DbId = 0
ProcedureReturn #False
EndIf
PrintN("[Root] Database '" + DatabasePath + "' is ready")
ProcedureReturn #True
EndProcedure
Procedure BakaShrot_Root_CloseDatabase(*Root.BakaShrot_Root)
If *Root\DbId
CloseDatabase(*Root\DbId)
*Root\DbId = 0
EndIf
EndProcedure
; Starts the network server and the peer links.
; Returns #False if either can't start, nothing is left running then.
Procedure.i BakaShrot_Root_StartWorkers(*Root.BakaShrot_Root)
Protected *Config.BakaShrot_CoreConfig = *Root\Config
Protected WriterError.String
; Every write goes through it, see Storage/Writer.pbi.
If Not OpenStorageWriter(*Config\Server\DatabasePath, @WriterError)
PrintN("[Root] Failed to open the storage writer: " + WriterError\s)
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) + "'")
CloseStorageWriter()
ProcedureReturn #False
EndIf
PrintN("[Root] Listening on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'")
*Root\Peers = BakaShrot_PeerLinks_Start(*Config)
If Not *Root\Peers
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
CloseStorageWriter()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; The signal: stops every worker thread and waits until they've all exited,
; which closes every database connection but the root's own.
; Peer links first, so they don't relink to a server that's going away.
Procedure BakaShrot_Root_StopWorkers(*Root.BakaShrot_Root)
Protected StartTime.i = ElapsedMilliseconds()
If *Root\Peers
BakaShrot_PeerLinks_Stop(*Root\Peers)
*Root\Peers = 0
EndIf
If *Root\Server
BakaShrot_NetServer_Stop(*Root\Server)
*Root\Server = 0
EndIf
; Nothing writes anymore. Checkpoints the WAL into the database file.
CloseStorageWriter()
PrintN("[Root] Workers stopped in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
EndProcedure
; Stops the workers, reloads the config (keeping the current one if the new
; one can't be loaded), reopens the database, and starts the workers again.
; Returns #False if the database can't be reopened or the workers can't
; start again, the server is then left stopped.
Procedure.i BakaShrot_Root_Restart(*Root.BakaShrot_Root)
PrintN("[Root] Restarting")
BakaShrot_Root_StopWorkers(*Root)
If Not BakaShrot_Root_LoadConfig(*Root)
PrintN("[Root] Keeping the current config")
EndIf
; The database path may have changed.
BakaShrot_Root_CloseDatabase(*Root)
If Not BakaShrot_Root_OpenDatabase(*Root)
ProcedureReturn #False
EndIf
ProcedureReturn BakaShrot_Root_StartWorkers(*Root)
EndProcedure
; Stops the workers, VACUUMs the database, and starts the workers again.
; Returns #False if the workers can't start again, a failed VACUUM is only
; logged.
Procedure.i BakaShrot_Root_Vacuum(*Root.BakaShrot_Root)
Protected StartTime.i
PrintN("[Root] Vacuuming the database")
BakaShrot_Root_StopWorkers(*Root)
StartTime = ElapsedMilliseconds()
If VacuumStorageDatabase(*Root\DbId)
PrintN("[Root] Vacuumed in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
Else
PrintN("[Root] Failed to vacuum: " + DatabaseError())
EndIf
ProcedureReturn BakaShrot_Root_StartWorkers(*Root)
EndProcedure
+484
View File
@@ -0,0 +1,484 @@
; ============================================================================
; BakaShrot Storage Names
;
; Which name every topic and node id has on this server. Names are what's
; shared between servers (Commons/Networking/Names.pbi): replication sends
; them, and each server stores the messages under its own ids for them. Say
; topic "logs" is 1 here and 200 on a peer: the peer sends "logs", this
; server stores it under 1. Hand-written configs drift, the names keep them
; matching anyway.
;
; Only what's named on BOTH servers replicates: a topic or node without a
; name, or with a name the other server doesn't know, is dropped. Unless the
; receiver takes it by a wildcard: "*" or a pattern ("sensors.*") in that
; peer's AcceptTopics / AcceptNodes takes matching names it doesn't have,
; and adds them (BakaShrot_Names_Ingest(), origin "peer") under the highest
; free id counting down from 65535, out of the way of the ids picked in the
; config. To not be refused over and over, each check-in's sync state lists
; every name the receiver knows and takes, and its patterns, and the sender
; only sends those. Every drop goes through BakaShrot_Names_NoteDropped().
;
; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can
; join on them (the "messages" view), and in memory for the server, guarded
; by BakaShrot_Names_Mutex. Every id in "data" has a row:
; origin "config" named in [BakaShrot.Topics] / [BakaShrot.Nodes]
; origin "id" unnamed, its name is its id in digits
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
;
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
; on restart). The config wins, except when it would give a name to another
; id than the one the database has it under (or rename a "peer" one): that
; would relabel stored messages, so the server refuses to start and says
; which id to use.
;
; Lock order: BakaShrot_Names_Mutex, then the write mutex (Writer.pbi).
; ============================================================================
XIncludeFile "../Config/Config.pbi"
XIncludeFile "Storage.pbi"
XIncludeFile "../../Commons/Networking/Packets/NamesListPacket.pbi"
#BakaShrot_Names_OriginConfig = "config"
#BakaShrot_Names_OriginPeer = "peer"
#BakaShrot_Names_OriginId = "id"
; One of the two tables, in memory.
Structure BakaShrot_NameTable
Table.s
IdColumn.s
Kind.s
; LCase(name) -> id, named ones only.
Map IdByName.i()
; Str(id) -> name, "" if unnamed. Every id with a row.
Map NameById.s()
; Str(id) -> origin.
Map OriginById.s()
EndStructure
Global BakaShrot_Names_Mutex.i = CreateMutex()
Global BakaShrot_Names_Topics.BakaShrot_NameTable
Global BakaShrot_Names_Nodes.BakaShrot_NameTable
BakaShrot_Names_Topics\Table = "topics"
BakaShrot_Names_Topics\IdColumn = "topic_id"
BakaShrot_Names_Topics\Kind = "topic"
BakaShrot_Names_Nodes\Table = "nodes"
BakaShrot_Names_Nodes\IdColumn = "node_id"
BakaShrot_Names_Nodes\Kind = "node"
; --- Loading -----------------------------------------------------------------
; Reconciles one table with the config's names (ConfigNames: Str(id) ->
; name) and the ids it uses (UsedIds), plus every id already in "data"
; (node_heads), then fills *Names from it.
; Runs inside the transaction of BakaShrot_Names_Load().
Procedure.i BakaShrot_Names_LoadTable(DbId.i, *Names.BakaShrot_NameTable, Map ConfigNames.s(), Map UsedIds.i(), *Error.String)
Protected NewMap DbName.s(), NewMap DbOrigin.s(), NewMap DbIdByName.i(), NewMap AllIds.i()
Protected Id.i, Name.s, Key.s, Section.s
If *Names = @BakaShrot_Names_Topics
Section = "[BakaShrot.Topics]"
Else
Section = "[BakaShrot.Nodes]"
EndIf
; What the database has.
If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table)
*Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Key = Str(GetDatabaseLong(DbId, 0))
DbName(Key) = GetDatabaseString(DbId, 1)
DbOrigin(Key) = GetDatabaseString(DbId, 2)
If Not BakaShrot_IsDigits(DbName(Key))
DbIdByName(LCase(DbName(Key))) = Val(Key)
EndIf
Wend
FinishDatabaseQuery(DbId)
; The config's names.
ForEach ConfigNames()
Key = MapKey(ConfigNames())
Name = ConfigNames()
Id = Val(Key)
If FindMapElement(DbIdByName(), LCase(Name)) And DbIdByName() <> Id
*Error\s = *Names\Kind + " '" + Name + "' is id " + Str(Id) + " in " + Section + ", but its messages are stored under id " +
Str(DbIdByName()) + ": give it id " + Str(DbIdByName()) + " in the config"
ProcedureReturn #False
EndIf
If FindMapElement(DbName(), Key)
If DbName(Key) = Name And DbOrigin(Key) = #BakaShrot_Names_OriginConfig
Continue
EndIf
If DbOrigin(Key) = #BakaShrot_Names_OriginPeer And LCase(DbName(Key)) <> LCase(Name)
*Error\s = *Names\Kind + " id " + Str(Id) + " is '" + DbName(Key) + "', added by a peer, " + Section + " can't rename it to '" + Name +
"': give '" + Name + "' another id, or name id " + Str(Id) + " '" + DbName(Key) + "'"
ProcedureReturn #False
EndIf
If LCase(DbName(Key)) <> LCase(Name) And DbOrigin(Key) = #BakaShrot_Names_OriginConfig
PrintN("[Names] Renaming " + *Names\Kind + " " + Key + " from '" + DbName(Key) + "' to '" + Name + "'")
EndIf
EndIf
SetDatabaseLong(DbId, 0, Id)
SetDatabaseString(DbId, 1, Name)
SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginConfig)
If Not DatabaseUpdate(DbId, "INSERT INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?) " +
"ON CONFLICT (" + *Names\IdColumn + ") DO UPDATE SET name = excluded.name, origin = excluded.origin")
*Error\s = "can't store " + *Names\Kind + " '" + Name + "': " + DatabaseError()
ProcedureReturn #False
EndIf
Next
; Every id the config uses, and every one already in "data", gets a row.
ForEach UsedIds()
AllIds(MapKey(UsedIds())) = #True
Next
If Not DatabaseQuery(DbId, "SELECT DISTINCT " + *Names\IdColumn + " FROM node_heads")
*Error\s = "can't read node_heads: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AllIds(Str(GetDatabaseLong(DbId, 0))) = #True
Wend
FinishDatabaseQuery(DbId)
ForEach AllIds()
Key = MapKey(AllIds())
If FindMapElement(ConfigNames(), Key) Or FindMapElement(DbName(), Key)
Continue
EndIf
SetDatabaseLong(DbId, 0, Val(Key))
SetDatabaseString(DbId, 1, Key)
SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginId)
If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?)")
*Error\s = "can't store " + *Names\Kind + " id " + Key + ": " + DatabaseError()
ProcedureReturn #False
EndIf
Next
; In memory, from what the table now holds.
ClearMap(*Names\IdByName())
ClearMap(*Names\NameById())
ClearMap(*Names\OriginById())
If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table)
*Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Names\OriginById(Str(Id)) = GetDatabaseString(DbId, 2)
If BakaShrot_IsDigits(Name)
*Names\NameById(Str(Id)) = ""
Else
*Names\NameById(Str(Id)) = Name
*Names\IdByName(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Reconciles the config's names with the database, see the top of this
; file. Only from the root, with the workers stopped, on its own connection.
; Returns #False with the reason in *Error\s, nothing is changed then.
Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.String)
Protected Loaded.i
LockMutex(BakaShrot_Names_Mutex)
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
*Error\s = DatabaseError()
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn #False
EndIf
Loaded = Bool(BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Topics, *Config\TopicNames(), *Config\UsedTopicIds(), *Error) And
BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Nodes, *Config\NodeNames(), *Config\UsedNodeIds(), *Error))
If Loaded And Not DatabaseUpdate(DbId, "COMMIT")
*Error\s = DatabaseError()
Loaded = #False
EndIf
If Not Loaded
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Loaded
EndProcedure
; --- Lookups -----------------------------------------------------------------
; The id Ref stands for: an id in digits is that id, a name must be known.
; -1 if it's neither. Holding the names mutex.
Procedure.i BakaShrot_Names_ResolveIn(*Names.BakaShrot_NameTable, Ref.s)
Protected Id.i = BakaShrot_RefToId(Ref)
If Id >= 0
ProcedureReturn Id
EndIf
If BakaShrot_IsValidName(Ref) And FindMapElement(*Names\IdByName(), LCase(Ref))
ProcedureReturn *Names\IdByName()
EndIf
ProcedureReturn -1
EndProcedure
; Its name, "" if it has none. Holding the names mutex.
Procedure.s BakaShrot_Names_NameIn(*Names.BakaShrot_NameTable, Id.i)
If FindMapElement(*Names\NameById(), Str(Id))
ProcedureReturn *Names\NameById()
EndIf
ProcedureReturn ""
EndProcedure
; The topic id Ref stands for here, -1 if none.
Procedure.i BakaShrot_Names_ResolveTopic(Ref.s)
Protected Id.i
LockMutex(BakaShrot_Names_Mutex)
Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Topics, Ref)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndProcedure
; The node id Ref stands for here, -1 if none.
Procedure.i BakaShrot_Names_ResolveNode(Ref.s)
Protected Id.i
LockMutex(BakaShrot_Names_Mutex)
Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Nodes, Ref)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndProcedure
; The topic id of a known name (never an id in digits), -1 if none: what
; replication goes by.
Procedure.i BakaShrot_Names_TopicByName(Name.s)
If Not BakaShrot_IsValidName(Name)
ProcedureReturn -1
EndIf
ProcedureReturn BakaShrot_Names_ResolveTopic(Name)
EndProcedure
; Same for a node.
Procedure.i BakaShrot_Names_NodeByName(Name.s)
If Not BakaShrot_IsValidName(Name)
ProcedureReturn -1
EndIf
ProcedureReturn BakaShrot_Names_ResolveNode(Name)
EndProcedure
; A topic's name, "" if it has none.
Procedure.s BakaShrot_Names_TopicName(Id.i)
Protected Name.s
LockMutex(BakaShrot_Names_Mutex)
Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Topics, Id)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Name
EndProcedure
; A node's name, "" if it has none.
Procedure.s BakaShrot_Names_NodeName(Id.i)
Protected Name.s
LockMutex(BakaShrot_Names_Mutex)
Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Nodes, Id)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Name
EndProcedure
; What a topic goes by in answers and logs: its name, or its id in digits.
Procedure.s BakaShrot_Names_TopicRef(Id.i)
Protected Name.s = BakaShrot_Names_TopicName(Id)
If Name = ""
ProcedureReturn Str(Id)
EndIf
ProcedureReturn Name
EndProcedure
; Same for a node.
Procedure.s BakaShrot_Names_NodeRef(Id.i)
Protected Name.s = BakaShrot_Names_NodeName(Id)
If Name = ""
ProcedureReturn Str(Id)
EndIf
ProcedureReturn Name
EndProcedure
; Fills Names() with every named topic (Kind #BakaShrot_NameKind_Topic) or
; node, by id, for the sync state. *Filter: only the ones it holds, 0 for
; all of them.
Procedure BakaShrot_Names_GetNamed(Kind.i, List Names.BakaShrot_SyncName(), *Filter.BakaShrot_NameSet = 0)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
ClearList(Names())
LockMutex(BakaShrot_Names_Mutex)
ForEach *Names\IdByName()
Id = *Names\IdByName()
If *Filter And Not NameSetHas(*Filter, Id, BakaShrot_Names_NameIn(*Names, Id))
Continue
EndIf
AddElement(Names())
Names()\Id = Id
Names()\Name = BakaShrot_Names_NameIn(*Names, Id)
Next
UnlockMutex(BakaShrot_Names_Mutex)
SortStructuredList(Names(), #PB_Sort_Ascending, OffsetOf(BakaShrot_SyncName\Id), #PB_Long)
EndProcedure
; Fills Entries() with every topic or node (Kind), named or not, by id, with
; where its name comes from. *Filter: only the topics it holds, 0 for all.
Procedure BakaShrot_Names_GetAll(Kind.i, List Entries.BakaShrot_NameEntry(), *Filter.BakaShrot_NameSet = 0)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
ClearList(Entries())
LockMutex(BakaShrot_Names_Mutex)
ForEach *Names\NameById()
Id = Val(MapKey(*Names\NameById()))
If *Filter And Not NameSetHas(*Filter, Id, *Names\NameById())
Continue
EndIf
AddElement(Entries())
Entries()\Id = Id
Entries()\Name = *Names\NameById()
Entries()\Origin = *Names\OriginById(Str(Id))
Next
UnlockMutex(BakaShrot_Names_Mutex)
SortStructuredList(Entries(), #PB_Sort_Ascending, OffsetOf(BakaShrot_NameEntry\Id), #PB_Long)
EndProcedure
; Prints every topic and node with its id, for the server's "names" command.
Procedure BakaShrot_Names_Print()
Protected NewList Entries.BakaShrot_NameEntry()
Protected Kind.i, Label.s, Name.s
For Kind = #BakaShrot_NameKind_Topic To #BakaShrot_NameKind_Node
BakaShrot_Names_GetAll(Kind, Entries())
If Kind = #BakaShrot_NameKind_Topic
Label = "Topics"
Else
Label = "Nodes"
EndIf
PrintN(Label + " (" + Str(ListSize(Entries())) + "):")
ForEach Entries()
Name = Entries()\Name
If Name = ""
Name = "(unnamed, not replicated)"
EndIf
PrintN(" " + RSet(Str(Entries()\Id), 5) + " " + LSet(Name, 30) + " " + Entries()\Origin)
Next
Next
EndProcedure
; --- Adding ------------------------------------------------------------------
; Makes sure Id has a row, as unnamed if it's new: for messages stored under
; an id the database didn't know yet (a push to a topic allowed by "*").
; Holding the names mutex. Returns #False with the reason in *Error\s.
Procedure.i BakaShrot_Names_EnsureIdIn(*Names.BakaShrot_NameTable, Id.i, *Error.String)
If FindMapElement(*Names\NameById(), Str(Id))
ProcedureReturn #True
EndIf
If Not RegisterStorageName(*Names\Table, Id, Str(Id), #BakaShrot_Names_OriginId, *Error)
ProcedureReturn #False
EndIf
*Names\NameById(Str(Id)) = ""
*Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginId
ProcedureReturn #True
EndProcedure
Procedure.i BakaShrot_Names_EnsureTopicId(Id.i, *Error.String)
Protected Done.i
LockMutex(BakaShrot_Names_Mutex)
Done = BakaShrot_Names_EnsureIdIn(@BakaShrot_Names_Topics, Id, *Error)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Done
EndProcedure
; The id of a topic (Kind #BakaShrot_NameKind_Topic) or node a peer sent,
; by its name, which a wildcard in that peer's AcceptTopics / AcceptNodes
; took (the caller checks): a name this server doesn't have yet is added,
; under the highest free id counting down from 65535 (origin "peer").
; Returns -1 with the reason in *Error\s.
Procedure.i BakaShrot_Names_Ingest(Kind.i, Name.s, *Error.String)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
If Not BakaShrot_IsValidName(Name)
*Error\s = "'" + Name + "' isn't a valid " + *Names\Kind + " name"
ProcedureReturn -1
EndIf
LockMutex(BakaShrot_Names_Mutex)
If FindMapElement(*Names\IdByName(), LCase(Name))
Id = *Names\IdByName()
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndIf
For Id = #BakaShrot_MaxId To 0 Step -1
If Not FindMapElement(*Names\NameById(), Str(Id))
Break
EndIf
Next
If Id < 0
UnlockMutex(BakaShrot_Names_Mutex)
*Error\s = "no " + *Names\Kind + " id left for '" + Name + "'"
ProcedureReturn -1
EndIf
If Not RegisterStorageName(*Names\Table, Id, Name, #BakaShrot_Names_OriginPeer, *Error)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn -1
EndIf
*Names\NameById(Str(Id)) = Name
*Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginPeer
*Names\IdByName(LCase(Name)) = Id
UnlockMutex(BakaShrot_Names_Mutex)
PrintN("[Names] New " + *Names\Kind + " '" + Name + "' from a peer, id " + Str(Id) + " here")
ProcedureReturn Id
EndProcedure
; --- Drops -------------------------------------------------------------------
; Called whenever a topic or node isn't replicated because one side doesn't
; know it: Peer is the peer section's name, Kind "topic" or "node", Ref what
; it goes by on the side that has it, Reason why it was dropped.
; !!! Does nothing for now, on purpose: it's called at every check-in for
; !!! every such pair, so logging each one would spam. Later: warn once per
; !!! peer and name (and again only if it changes), see Notes.md.
Procedure BakaShrot_Names_NoteDropped(Peer.s, Kind.s, Ref.s, Reason.s)
EndProcedure
+751
View File
@@ -0,0 +1,751 @@
; ============================================================================
; BakaShrot Storage
;
; 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.
;
; 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
; sqlite3.dll is used instead, it must be next to the program. Build.ps1
; extracts it from Libs/sqlite-dll-win-*.zip and copies it.
;
; Threads: ONE CONNECTION PER THREAD, never share a handle.
; The SetDatabase*() parameters and query results belong to a handle, so two
; threads using the same one overwrite each other's. Every thread that touches
; the database opens its own with OpenStorageDatabase() and closes it when it
; ends: each client thread, each peer link thread, each raw query, and the
; root's own one (setup and maintenance, see Server/Root.pbi).
; The one exception: every write goes through the writer (Writer.pbi), a
; single connection only used while holding BakaShrot_Storage_WriteMutex.
; SQLite still serializes writes from other processes
; (#BakaShrot_Storage_BusyTimeout). WAL mode lets reads run alongside them.
; See Design/StorageConcurrency.md.
; ============================================================================
; For BakaShrot_SyncPair and BakaShrot_ReplicatedMessage.
XIncludeFile "../../Commons/Networking/Packets/SyncStatePacket.pbi"
XIncludeFile "../../Commons/Networking/Packets/ReplicateMessagesPacket.pbi"
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
UseSQLiteDatabase("sqlite3.dll")
CompilerElse
UseSQLiteDatabase()
CompilerEndIf
; One row of the "data" table (see db_schema_v5.dbml).
Structure BakaShrot_Message
MessageId.q
JsonData.s
EndStructure
; How long a connection waits for another one's lock before a statement
; fails with "database is locked", in ms.
#BakaShrot_Storage_BusyTimeout = 5000
; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in
; the file): readers and the writer don't block each other anymore, so a
; long raw query no longer stalls every push.
; With WAL, NORMAL only syncs to disk at checkpoints instead of on every
; commit, which is most of what a push used to cost. The database can't get
; corrupted, but the last commits before a power loss or an OS crash (not a
; crash of the server itself) can be lost. Those messages were acknowledged,
; and maybe replicated already, so their ids could then be handed out again
; for other messages: drift, see Design/ReplicationIssues.md #1.
; FULL syncs every commit, like before, but still lets reads and writes run
; side by side.
#BakaShrot_Storage_Synchronous = "NORMAL"
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
; new connection for the calling thread only.
; Returns the PureBasic database number, or 0 if the file could not be opened.
Procedure.i OpenStorageDatabase(DatabasePath.s)
Protected FileId.i, DbId.i
; PureBasic's SQLite driver refuses to open a file that doesn't exist,
; so an empty one has to be created first.
If FileSize(DatabasePath) = -1
FileId = CreateFile(#PB_Any, DatabasePath)
If Not FileId
ProcedureReturn 0
EndIf
CloseFile(FileId)
EndIf
DbId = OpenDatabase(#PB_Any, DatabasePath, "", "")
If Not DbId
ProcedureReturn 0
EndIf
; Without it, a write fails right away while another connection writes.
If Not DatabaseUpdate(DbId, "PRAGMA busy_timeout = " + Str(#BakaShrot_Storage_BusyTimeout))
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
; Per connection, see #BakaShrot_Storage_Synchronous.
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + #BakaShrot_Storage_Synchronous)
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
ProcedureReturn DbId
EndProcedure
; Rebuilds the database file, reclaiming the space of deleted rows.
; Only run it from the root while every worker is stopped: it needs every
; other connection to be idle. See BakaShrot_Root_Vacuum() in Server/Root.pbi.
Procedure.i VacuumStorageDatabase(DbId.i)
ProcedureReturn DatabaseUpdate(DbId, "VACUUM")
EndProcedure
; #True if Table has a column named Column, #False if not (or no such table),
; -1 on failure.
Procedure.i StorageHasColumn(DbId.i, Table.s, Column.s)
Protected Found.i = #False
SetDatabaseString(DbId, 0, Table)
SetDatabaseString(DbId, 1, Column)
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?")
ProcedureReturn -1
EndIf
If NextDatabaseRow(DbId)
Found = Bool(GetDatabaseLong(DbId, 0) > 0)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; v3 -> v4: "group_id" became "topic_id" in every table. Renames the
; columns of a database made before, in one transaction. The trigger and the
; attachements index are dropped, SetupStorageDatabase() makes them again
; with the new names. The UNIQUE and PRIMARY KEY indexes follow the columns.
; Nothing to do on a new or already renamed database.
Procedure.i MigrateStorageTopicIds(DbId.i)
Protected Table.s, Has.i, i.i
Has = StorageHasColumn(DbId, "data", "group_id")
If Has = -1
ProcedureReturn #False
ElseIf Not Has
ProcedureReturn #True
EndIf
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "DROP TRIGGER IF EXISTS trg_data_node_heads") Or
Not DatabaseUpdate(DbId, "DROP INDEX IF EXISTS idx_attachements_group_node")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
For i = 1 To 3
Table = StringField("data,node_heads,attachements", i, ",")
Has = StorageHasColumn(DbId, Table, "group_id")
If Has = -1 Or (Has And Not DatabaseUpdate(DbId, "ALTER TABLE " + Table + " RENAME COLUMN group_id TO topic_id"))
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
Next
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Creates the tables and indexes described by db_schema_v5.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.
Procedure.i SetupStorageDatabase(DbId.i)
Protected JournalMode.s, HeadsExist.i
; Stored in the file, every later connection uses it. Fails while another
; connection has the database open, so only the root does it, at start.
If Not DatabaseQuery(DbId, "PRAGMA journal_mode = WAL")
ProcedureReturn #False
EndIf
If NextDatabaseRow(DbId)
JournalMode = LCase(GetDatabaseString(DbId, 0))
EndIf
FinishDatabaseQuery(DbId)
If JournalMode <> "wal"
ProcedureReturn #False
EndIf
; Before anything below, which uses the new names.
If Not MigrateStorageTopicIds(DbId)
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" +
"delete_by INTEGER NOT NULL, " +
"message_data TEXT NOT NULL)")
ProcedureReturn #False
EndIf
; is_json is set by SQLite on insert, and can't be written.
; 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, " +
"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))")
ProcedureReturn #False
EndIf
; An older "data" table is kept by CREATE IF NOT EXISTS, its lack of
; is_json gives it away. Fails with "no such column: is_json".
If Not DatabaseQuery(DbId, "SELECT is_json FROM data LIMIT 0")
ProcedureReturn #False
EndIf
FinishDatabaseQuery(DbId)
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_message_id ON data (message_id)")
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 (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"message_id INTEGER NOT NULL, " +
"attachement_data BLOB NOT NULL)")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_topic_node ON attachements (topic_id, node_id)")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)")
ProcedureReturn #False
EndIf
; The highest message id of every topic/node id, kept by a trigger on
; 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.
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'")
ProcedureReturn #False
EndIf
HeadsExist = #False
If NextDatabaseRow(DbId)
HeadsExist = Bool(GetDatabaseLong(DbId, 0) > 0)
EndIf
FinishDatabaseQuery(DbId)
If Not HeadsExist
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE TABLE node_heads (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"max_message_id INTEGER NOT NULL, " +
"PRIMARY KEY (topic_id, node_id)) WITHOUT ROWID") Or
Not DatabaseUpdate(DbId, "INSERT INTO node_heads (topic_id, node_id, max_message_id) " +
"SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
EndIf
; Only fires for rows actually inserted, not the ones INSERT OR IGNORE drops.
If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_node_heads AFTER INSERT ON data BEGIN " +
"INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (NEW.topic_id, NEW.node_id, NEW.message_id) " +
"ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id); " +
"END")
ProcedureReturn #False
EndIf
; Every topic and node id in "data" has a row, with its name, or its id
; in digits if it has none. origin: "config" (named in the config),
; "peer" (a node a peer sent messages of, given an id here), "id"
; (unnamed). Kept up to date by Server/Storage/Names.pbi.
; No foreign keys from "data": see Notes.md, a replicated batch would
; fail as a whole on an unknown id.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS topics (" +
"topic_id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL UNIQUE COLLATE NOCASE, " +
"origin TEXT NOT NULL)") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS nodes (" +
"node_id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL UNIQUE COLLATE NOCASE, " +
"origin TEXT NOT NULL)")
ProcedureReturn #False
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 " +
"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
ProcedureReturn #True
EndProcedure
; Inserts one JSON message into the "data" table.
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)
ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)")
EndProcedure
; Gets every message stored for a given topic_id/node_id pair - the
; "(topic_id, node_id)" index - ordered by message_id.
Procedure.i GetMessagesByTopicAndNode(DbId.i, TopicId.i, NodeId.i, List Messages.BakaShrot_Message())
ClearList(Messages())
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")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Messages())
Messages()\MessageId = GetDatabaseLong(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Gets every message stored under a given message_id, regardless of which
; topic/node it belongs to - the standalone "message_id" index.
Procedure.i GetMessagesByMessageId(DbId.i, MessageId.i, List Messages.BakaShrot_Message())
ClearList(Messages())
SetDatabaseLong(DbId, 0, MessageId)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE message_id = ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Messages())
Messages()\MessageId = GetDatabaseLong(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Test helper: scans every stored message and collects the value found at
; JsonPath (e.g. "$.messageData.MsgType"), skipping messages where it's
; missing or null, and those that aren't JSON (is_json = 0: ->> fails the
; whole query on one). Kept basic on purpose - no paging, no topic/node filter.
Procedure.i GetValuesAtJsonPath(DbId.i, JsonPath.s, List Values.s())
ClearList(Values())
SetDatabaseString(DbId, 0, JsonPath)
SetDatabaseString(DbId, 1, JsonPath)
If Not DatabaseQuery(DbId, "SELECT message_data ->> ? FROM data WHERE is_json = 1 AND message_data ->> ? IS NOT NULL")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Values())
Values() = GetDatabaseString(DbId, 0)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Returns the highest message_id stored for a given topic_id/node_id pair,
; or -1 if there's none yet. Will likely grow into a cached counter later.
Procedure.i GetLatestMessageId(DbId.i, TopicId.i, NodeId.i)
Protected MessageId.i = -1
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If DatabaseQuery(DbId, "SELECT COALESCE(MAX(message_id), -1) FROM data WHERE topic_id = ? AND node_id = ?")
If NextDatabaseRow(DbId)
MessageId = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
ProcedureReturn MessageId
EndProcedure
; Fills *Message with the message that has the highest message_id for a
; topic_id/node_id pair.
; Returns #False if there's none, or if the query failed.
Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Message)
Protected Found.i
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")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Message\MessageId = GetDatabaseQuad(DbId, 0)
*Message\JsonData = GetDatabaseString(DbId, 1)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; --- Raw queries -------------------------------------------------------------
; Most rows a raw query can return.
#BakaShrot_Query_MaxRows = 10000
; Telling the end of a query's rows from an error that cut them short.
; PureBasic's NextDatabaseRow() returns #False for both, and DatabaseError()
; stays empty after such an error: a JSON function (->>, json_extract())
; reaching a row that isn't JSON stops the query with "malformed JSON", and
; the query looked like it simply had no (more) rows. So once the rows end,
; SQLite itself is asked: sqlite3_errcode() on the connection is SQLITE_DONE
; (or SQLITE_ROW/SQLITE_OK) if they really ended, the error otherwise, with
; sqlite3_errmsg16() telling which. Same sqlite3.dll as PureBasic's
; (DatabaseID() is its sqlite3 handle), like Writer.pbi.
; Elsewhere than Windows, PureBasic's own SQLite is linked in and not
; reachable this way: DatabaseError() is checked instead, which misses it.
#BakaShrot_Query_SqliteOk = 0
#BakaShrot_Query_SqliteRow = 100
#BakaShrot_Query_SqliteDone = 101
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
PrototypeC.l BakaShrot_Query_SqliteErrCode(Db.i)
PrototypeC.i BakaShrot_Query_SqliteErrMsg16(Db.i)
Structure BakaShrot_Query_SqliteApi
Library.i
ErrCode.BakaShrot_Query_SqliteErrCode
ErrMsg16.BakaShrot_Query_SqliteErrMsg16
EndStructure
Global BakaShrot_Query_Sqlite.BakaShrot_Query_SqliteApi
; Queries run on every client's thread, the first one loads it.
Global BakaShrot_Query_SqliteMutex.i = CreateMutex()
; Returns #False if sqlite3.dll or its functions can't be found.
Procedure.i BakaShrot_Query_LoadSqlite()
Protected Loaded.i
LockMutex(BakaShrot_Query_SqliteMutex)
With BakaShrot_Query_Sqlite
If Not \Library
\Library = OpenLibrary(#PB_Any, "sqlite3.dll")
If \Library
\ErrCode = GetFunction(\Library, "sqlite3_errcode")
\ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16")
If Not \ErrCode Or Not \ErrMsg16
CloseLibrary(\Library)
\Library = 0
EndIf
EndIf
EndIf
Loaded = Bool(\Library)
EndWith
UnlockMutex(BakaShrot_Query_SqliteMutex)
ProcedureReturn Loaded
EndProcedure
CompilerEndIf
; Runs a raw SQL query from a client, read-only, and fills *Result\s with its
; rows as JSON: {"columns": ["name", ...], "rows": [["value", ...], ...]}.
; Every value is a string, or null for NULL: PureBasic reports no column
; types for SQLite. Wrap a blob in hex() to read it.
;
; Read-only, enforced three ways:
; 1. It must start with SELECT or WITH.
; 2. It runs on its own connection to DatabasePath, opened just for it,
; with PRAGMA query_only = ON. Writes fail, even WITH ... DELETE, and a
; query that turns the pragma off only does so for its own connection.
; 3. Only the first statement runs, anything after a ";" is ignored.
;
; An error while reading the rows fails the whole query, with SQLite's
; message: a JSON function on a row that isn't JSON gives "malformed JSON",
; add "is_json = 1" to the WHERE. Never a partial or empty result instead.
;
; Thread-safe, since it never touches a shared handle.
; Returns #False with *Error\s set if it's refused, fails, or has more than
; #BakaShrot_Query_MaxRows rows.
Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.String)
Protected DbId.i, JsonId.i, *Root, *Columns, *Rows, *Row
Protected Column.i, RowCount.i, Start.s, ErrorCode.l
Start = UCase(Trim(ReplaceString(ReplaceString(ReplaceString(Sql, #CR$, " "), #LF$, " "), #TAB$, " ")))
If Left(Start, 6) <> "SELECT" And Left(Start, 4) <> "WITH"
*Error\s = "Only SELECT and WITH queries are allowed"
ProcedureReturn #False
EndIf
; Without it, errors in the rows would go unnoticed: refused instead.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
If Not BakaShrot_Query_LoadSqlite()
*Error\s = "Queries can't be checked for errors: sqlite3_errcode() not found"
ProcedureReturn #False
EndIf
CompilerEndIf
DbId = OpenStorageDatabase(DatabasePath)
If Not DbId
*Error\s = "The database couldn't be opened"
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "PRAGMA query_only = ON")
*Error\s = "The database couldn't be made read-only"
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
If Not DatabaseQuery(DbId, Sql)
*Error\s = DatabaseError()
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
; WITH ... DELETE and the likes have no columns. query_only stops them
; anyway, but PureBasic doesn't report that, they'd look like no rows.
If DatabaseColumns(DbId) = 0
*Error\s = "The query doesn't return any column, only SELECT queries are allowed"
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
JsonId = CreateJSON(#PB_Any)
If Not JsonId
*Error\s = "Out of memory"
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
*Root = SetJSONObject(JSONValue(JsonId))
*Columns = SetJSONArray(AddJSONMember(*Root, "columns"))
For Column = 0 To DatabaseColumns(DbId) - 1
SetJSONString(AddJSONElement(*Columns), DatabaseColumnName(DbId, Column))
Next
*Rows = SetJSONArray(AddJSONMember(*Root, "rows"))
While NextDatabaseRow(DbId)
RowCount + 1
If RowCount > #BakaShrot_Query_MaxRows
*Error\s = "More than " + Str(#BakaShrot_Query_MaxRows) + " rows, add a LIMIT"
FreeJSON(JsonId)
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
*Row = SetJSONArray(AddJSONElement(*Rows))
For Column = 0 To DatabaseColumns(DbId) - 1
If CheckDatabaseNull(DbId, Column)
SetJSONNull(AddJSONElement(*Row))
Else
SetJSONString(AddJSONElement(*Row), GetDatabaseString(DbId, Column))
EndIf
Next
Wend
; Did the rows end, or did an error end them? (see above): "malformed
; JSON", a write stopped by query_only (DELETE ... RETURNING), ...
; Asked before FinishDatabaseQuery(), while the failed step is the last
; thing done on this connection. A false alarm would refuse a good
; query, it can't hide a bad one.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId))
If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone
*Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode)
If *Error\s = ""
*Error\s = "SQLite error " + Str(ErrorCode)
EndIf
If FindString(*Error\s, "JSON", 1, #PB_String_NoCase)
*Error\s + " (a row isn't JSON: add is_json = 1 to the WHERE)"
EndIf
FreeJSON(JsonId)
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
CompilerEndIf
FinishDatabaseQuery(DbId)
; Elsewhere than Windows, the only check there is. It misses errors in the
; rows: PureBasic doesn't report them.
; !!! DatabaseError() may be shared by every thread, see
; !!! Design/StorageConcurrency.md, another thread's error could show up here.
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
If DatabaseError() <> ""
*Error\s = DatabaseError()
FreeJSON(JsonId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
CompilerEndIf
*Result\s = ComposeJSON(JsonId)
FreeJSON(JsonId)
CloseDatabase(DbId)
ProcedureReturn #True
EndProcedure
; --- Replication -------------------------------------------------------------
; Fills Pairs() with where this node is at: the highest message id it has for
; every topic/node id combination, ordered by topic then node id. Read from
; node_heads, kept up to date by a trigger, see SetupStorageDatabase().
; Returns #False if the query failed.
Procedure.i GetSyncState(DbId.i, List Pairs.BakaShrot_SyncPair())
ClearList(Pairs())
If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Pairs())
Pairs()\TopicId = GetDatabaseLong(DbId, 0)
Pairs()\NodeId = GetDatabaseLong(DbId, 1)
Pairs()\MessageId = GetDatabaseQuad(DbId, 2)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Fills Messages() with up to Limit messages of a topic/node id combination
; whose message_id is above AfterMessageId, in message_id order. Stops early
; once their JSON adds up to MaxChars characters or more (0: no such limit),
; the one that got there included, so big messages aren't all read at once.
; If *More is given, *More\i is set to #True if more messages follow the
; last one read.
; Returns #False if the query failed.
Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limit.i, MaxChars.i, List Messages.BakaShrot_Message(), *More.Integer = 0)
Protected Chars.i, More.i
ClearList(Messages())
; One more than asked for, to tell if more follow.
SetDatabaseLong(DbId, 0, TopicId)
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 ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
If ListSize(Messages()) >= Limit Or (MaxChars > 0 And Chars >= MaxChars)
More = #True
Break
EndIf
AddElement(Messages())
Messages()\MessageId = GetDatabaseQuad(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Chars + Len(Messages()\JsonData)
Wend
FinishDatabaseQuery(DbId)
If *More
*More\i = More
EndIf
ProcedureReturn #True
EndProcedure
; Stores a message replicated from a peer, under the ids it has on its origin.
; If that topic/node/message id is already stored, it's kept as is, and the
; 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.
; Returns #False if the insert failed.
Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s)
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 (?, ?, ?, ?)")
EndProcedure
; Every write: pushes (group commit), replicated batches, the WAL checkpoints.
XIncludeFile "Writer.pbi"
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
CompilerIf #PB_Compiler_IsMainFile
Define DbId = OpenStorageDatabase("storage.sqlite")
If DbId
If SetupStorageDatabase(DbId)
Insert(DbId, 1, 1, 1, ~"{\"messageData\": {\"MsgType\": \"hello\"}}")
Insert(DbId, 1, 1, 2, ~"{\"messageData\": {\"MsgType\": \"world\"}}")
NewList Messages.BakaShrot_Message()
GetMessagesByTopicAndNode(DbId, 1, 1, Messages())
ForEach Messages()
Debug "Message #" + Str(Messages()\MessageId) + ": " + Messages()\JsonData
Next
NewList MsgTypes.s()
GetValuesAtJsonPath(DbId, "$.messageData.MsgType", MsgTypes())
ForEach MsgTypes()
Debug "MsgType: " + MsgTypes()
Next
Debug "Latest message id: " + Str(GetLatestMessageId(DbId, 1, 1))
Else
Debug "Failed to set up database: " + DatabaseError()
EndIf
CloseDatabase(DbId)
Else
Debug "Failed to open database: " + DatabaseError()
EndIf
CompilerEndIf
+783
View File
@@ -0,0 +1,783 @@
; ============================================================================
; BakaShrot Storage Writer
;
; Every write the server does to its database goes through here:
; InsertNextMessage() pushes, grouped (group commit)
; InsertReplicatedMessages() batches from peers
; 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
; Server/Root.pbi). The exception to "one connection per thread" (see
; Storage.pbi): it's shared, but never by two threads at once.
;
; What makes it fast, see Design/StorageConcurrency.md:
; - Group commit: each push queues itself, then takes the write mutex.
; Whoever holds it writes every queued push in one transaction, the ones
; that were waiting find theirs done. The busier, the bigger the groups.
; - Prepared statements, kept for as long as the writer is open, through
; SQLite's own API: PureBasic prepares a statement again on every call.
; Same sqlite3.dll as PureBasic's (DatabaseID() is its sqlite3 handle).
; Elsewhere than Windows, PureBasic's own SQLite is linked in, so its
; functions are used instead (slower, same behaviour).
; - 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
; 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
; itself past #BakaShrot_Storage_WalBackstopFrames, a background thread
; checkpoints every
; #BakaShrot_Storage_CheckpointInterval ms on its own connection, in
; PASSIVE rounds that don't block anything, finishing with a short one
; under the write mutex so the WAL can start over (see
; BakaShrot_Writer_CheckpointThread()).
;
; Logs a [Storage] line every #BakaShrot_Storage_StatsInterval ms while
; pushes come in: pushes/s, per transaction, write time per push, how busy.
; ============================================================================
; Most pushes in one transaction.
#BakaShrot_Storage_MaxGroupSize = 1000
#BakaShrot_Storage_CheckpointInterval = 1000
; A checkpoint finishes under the write mutex once at most this many WAL
; frames (4 KB pages) are left to copy, see BakaShrot_Writer_CheckpointThread().
#BakaShrot_Storage_CheckpointFinishFrames = 2000
#BakaShrot_Storage_StatsInterval = 10000
; The writer still checkpoints by itself (like SQLite does by default, at
; 1000) once the WAL reaches this many frames, when the checkpoint thread
; can't keep up: flat out, ~25,000 frames/s per server. Without it the WAL
; grew to 170,000 frames (700 MB) and Windows started throttling the writes,
; up to 5 s for a push.
#BakaShrot_Storage_WalBackstopFrames = 10000
; Once a checkpoint let the WAL start over, its file is truncated to this.
#BakaShrot_Storage_WalSizeLimit = 67108864
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
#BakaShrot_Storage_RawSqlite = #True
CompilerElse
#BakaShrot_Storage_RawSqlite = #False
CompilerEndIf
#BakaShrot_Sqlite_Done = 101
#BakaShrot_Sqlite_Row = 100
#BakaShrot_Sqlite_Static = 0
CompilerIf #BakaShrot_Storage_RawSqlite
PrototypeC.l BakaShrot_Sqlite_Prepare16(Db.i, *Sql, Bytes.l, *Statement, *Tail)
PrototypeC.l BakaShrot_Sqlite_BindInt64(Statement.i, Index.l, Value.q)
PrototypeC.l BakaShrot_Sqlite_BindText16(Statement.i, Index.l, *Text, Bytes.l, Destructor.i)
PrototypeC.l BakaShrot_Sqlite_Step(Statement.i)
PrototypeC.l BakaShrot_Sqlite_Reset(Statement.i)
PrototypeC.l BakaShrot_Sqlite_Finalize(Statement.i)
PrototypeC.q BakaShrot_Sqlite_ColumnInt64(Statement.i, Column.l)
PrototypeC.l BakaShrot_Sqlite_Changes(Db.i)
PrototypeC.i BakaShrot_Sqlite_ErrMsg16(Db.i)
PrototypeC.i BakaShrot_Sqlite_DbFilename(Db.i, *Name)
Structure BakaShrot_SqliteApi
Library.i
Prepare16.BakaShrot_Sqlite_Prepare16
BindInt64.BakaShrot_Sqlite_BindInt64
BindText16.BakaShrot_Sqlite_BindText16
Step_.BakaShrot_Sqlite_Step
Reset.BakaShrot_Sqlite_Reset
Finalize.BakaShrot_Sqlite_Finalize
ColumnInt64.BakaShrot_Sqlite_ColumnInt64
Changes.BakaShrot_Sqlite_Changes
ErrMsg16.BakaShrot_Sqlite_ErrMsg16
DbFilename.BakaShrot_Sqlite_DbFilename
EndStructure
Global BakaShrot_Sqlite.BakaShrot_SqliteApi
CompilerEndIf
; A queued push, on the stack of the thread that pushed it, which waits for
; it on the write mutex.
Structure BakaShrot_PushJob
TopicId.i
NodeId.i
JsonData.s
; Filled in by whoever writes it, under the write mutex.
MessageId.q
Error.s
Done.i
EndStructure
Structure BakaShrot_StorageStats
LastLog.i
Groups.q
Pushes.q
Ticks.q
EndStructure
Structure BakaShrot_StorageWriter
DatabasePath.s
; PureBasic database, and its sqlite3 handle.
DbId.i
Handle.i
; Prepared once (or the SQL, without the raw API).
Begin.i
Commit.i
Rollback.i
Insert.i
InsertOrIgnore.i
MaxId.i
; "TopicId:NodeId" -> the next message id to hand out.
Map NextIds.q()
; Set by the last failed statement.
LastError.s
CheckpointThread.i
StopRequested.i
CheckpointCount.i
CheckpointTicks.q
; The part of it holding the write mutex.
CheckpointLockedTicks.q
; Frames in the WAL at the last checkpoint, 4 KB each by default.
WalFrames.i
Stats.BakaShrot_StorageStats
EndStructure
; Taken around every write. SQLite already allows a single writer, but one
; that finds the database locked sleeps and retries (1, 2, 5, 10... ms):
; queued here instead, each one gets it the moment it's free. Only covers
; this process, the busy timeout still handles any other one.
Global BakaShrot_Storage_WriteMutex.i = CreateMutex()
; Guards BakaShrot_Storage_Queue(), *BakaShrot_PushJob in arrival order.
Global BakaShrot_Storage_QueueMutex.i = CreateMutex()
Global NewList BakaShrot_Storage_Queue.i()
Global BakaShrot_Storage_Writer.BakaShrot_StorageWriter
Global BakaShrot_Storage_TicksPerMs.d = 1
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
Define BakaShrot_Storage_Frequency.q
QueryPerformanceFrequency_(@BakaShrot_Storage_Frequency)
BakaShrot_Storage_TicksPerMs = BakaShrot_Storage_Frequency / 1000.0
CompilerEndIf
Procedure.q BakaShrot_Storage_Ticks()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
Protected Ticks.q
QueryPerformanceCounter_(@Ticks)
ProcedureReturn Ticks
CompilerElse
ProcedureReturn ElapsedMilliseconds()
CompilerEndIf
EndProcedure
; --- Statements --------------------------------------------------------------
; Everything below the "Statements" line runs holding the write mutex.
Procedure.s BakaShrot_Writer_Error()
CompilerIf #BakaShrot_Storage_RawSqlite
If BakaShrot_Storage_Writer\Handle
ProcedureReturn PeekS(BakaShrot_Sqlite\ErrMsg16(BakaShrot_Storage_Writer\Handle), -1, #PB_Unicode)
EndIf
CompilerEndIf
ProcedureReturn DatabaseError()
EndProcedure
CompilerIf Not #BakaShrot_Storage_RawSqlite
Procedure.i BakaShrot_Writer_AllocateString(Text.s)
Protected *Buffer = AllocateMemory(StringByteLength(Text) + 2)
If *Buffer
PokeS(*Buffer, Text)
EndIf
ProcedureReturn *Buffer
EndProcedure
CompilerEndIf
; Returns the prepared statement (the SQL itself without the raw API), or 0.
Procedure.i BakaShrot_Writer_Prepare(Sql.s)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Statement.i
If BakaShrot_Sqlite\Prepare16(BakaShrot_Storage_Writer\Handle, @Sql, -1, @Statement, 0) <> 0
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
ProcedureReturn 0
EndIf
ProcedureReturn Statement
CompilerElse
ProcedureReturn BakaShrot_Writer_AllocateString(Sql)
CompilerEndIf
EndProcedure
Procedure BakaShrot_Writer_Finalize(*Statement.Integer)
If *Statement\i
CompilerIf #BakaShrot_Storage_RawSqlite
BakaShrot_Sqlite\Finalize(*Statement\i)
CompilerElse
FreeMemory(*Statement\i)
CompilerEndIf
*Statement\i = 0
EndIf
EndProcedure
; Runs a statement without parameters (BEGIN, COMMIT, ROLLBACK).
Procedure.i BakaShrot_Writer_Run(Statement.i)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Result.l = BakaShrot_Sqlite\Step_(Statement)
If Result <> #BakaShrot_Sqlite_Done And Result <> #BakaShrot_Sqlite_Row
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn #False
EndIf
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn #True
CompilerElse
If Not DatabaseUpdate(BakaShrot_Storage_Writer\DbId, PeekS(Statement))
BakaShrot_Storage_Writer\LastError = DatabaseError()
ProcedureReturn #False
EndIf
ProcedureReturn #True
CompilerEndIf
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)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Result.l
BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId)
BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId)
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)
Result = BakaShrot_Sqlite\Step_(Statement)
If Result <> #BakaShrot_Sqlite_Done
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn -1
EndIf
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn BakaShrot_Sqlite\Changes(BakaShrot_Storage_Writer\Handle)
CompilerElse
Protected DbId.i = BakaShrot_Storage_Writer\DbId
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
If Not DatabaseUpdate(DbId, PeekS(Statement))
BakaShrot_Storage_Writer\LastError = DatabaseError()
ProcedureReturn -1
EndIf
ProcedureReturn AffectedDatabaseRows(DbId)
CompilerEndIf
EndProcedure
; The highest message id stored for a topic/node id, 0 if none, -1 on failure.
Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i)
Protected MaxId.q = -1
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Statement.i = BakaShrot_Storage_Writer\MaxId
BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId)
BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId)
If BakaShrot_Sqlite\Step_(Statement) = #BakaShrot_Sqlite_Row
MaxId = BakaShrot_Sqlite\ColumnInt64(Statement, 0)
Else
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
EndIf
BakaShrot_Sqlite\Reset(Statement)
CompilerElse
Protected DbId.i = BakaShrot_Storage_Writer\DbId
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If DatabaseQuery(DbId, PeekS(BakaShrot_Storage_Writer\MaxId))
If NextDatabaseRow(DbId)
MaxId = GetDatabaseQuad(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
Else
BakaShrot_Storage_Writer\LastError = DatabaseError()
EndIf
CompilerEndIf
ProcedureReturn MaxId
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
If FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
ProcedureReturn BakaShrot_Storage_Writer\NextIds()
EndIf
MaxId = BakaShrot_Writer_ReadMaxId(TopicId, NodeId)
If MaxId < 0
ProcedureReturn -1
EndIf
BakaShrot_Storage_Writer\NextIds(Key) = MaxId + 1
ProcedureReturn MaxId + 1
EndProcedure
; --- Opening and closing -----------------------------------------------------
CompilerIf #BakaShrot_Storage_RawSqlite
Procedure.i BakaShrot_Writer_LoadSqlite()
With BakaShrot_Sqlite
If \Library
ProcedureReturn #True
EndIf
; The one PureBasic's SQLite driver already loaded.
\Library = OpenLibrary(#PB_Any, "sqlite3.dll")
If Not \Library
ProcedureReturn #False
EndIf
\Prepare16 = GetFunction(\Library, "sqlite3_prepare16_v2")
\BindInt64 = GetFunction(\Library, "sqlite3_bind_int64")
\BindText16 = GetFunction(\Library, "sqlite3_bind_text16")
\Step_ = GetFunction(\Library, "sqlite3_step")
\Reset = GetFunction(\Library, "sqlite3_reset")
\Finalize = GetFunction(\Library, "sqlite3_finalize")
\ColumnInt64 = GetFunction(\Library, "sqlite3_column_int64")
\Changes = GetFunction(\Library, "sqlite3_changes")
\ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16")
\DbFilename = GetFunction(\Library, "sqlite3_db_filename")
If Not \Prepare16 Or Not \BindInt64 Or Not \BindText16 Or Not \Step_ Or Not \Reset Or Not \Finalize Or Not \ColumnInt64 Or Not \Changes Or Not \ErrMsg16 Or Not \DbFilename
CloseLibrary(\Library)
\Library = 0
ProcedureReturn #False
EndIf
EndWith
ProcedureReturn #True
EndProcedure
CompilerEndIf
; One PASSIVE checkpoint: copies what it can of the WAL into the database,
; without waiting for the writer nor the readers. Fills *Frames\i with how
; many frames the WAL has, *Left\i with how many it couldn't copy yet.
Procedure BakaShrot_Writer_CheckpointOnce(DbId.i, *Frames.Integer, *Left.Integer)
*Frames\i = 0
*Left\i = 0
; It only runs on the first NextDatabaseRow(). Its row: busy, frames in
; the WAL, frames checkpointed.
If DatabaseQuery(DbId, "PRAGMA wal_checkpoint(PASSIVE)")
If NextDatabaseRow(DbId)
*Frames\i = GetDatabaseLong(DbId, 1)
*Left\i = *Frames\i - GetDatabaseLong(DbId, 2)
EndIf
FinishDatabaseQuery(DbId)
EndIf
EndProcedure
; Every #BakaShrot_Storage_CheckpointInterval ms, copies the WAL into the
; database in PASSIVE rounds, without the write mutex: they copy far faster
; than the pushes write, so each round leaves less behind. Once few enough
; frames are left, finishes under the write mutex, which takes a few ms: a
; checkpoint that's complete when the next transaction starts is what makes
; SQLite start the WAL over, otherwise it grows forever under steady writes.
; A long read can keep it from completing, it's tried again next time.
Procedure BakaShrot_Writer_CheckpointThread(Unused.i)
Protected DbId.i, LastCheckpoint.i, StartTicks.q, LockedTicks.q, Round.i
Protected Frames.Integer, Left.Integer
DbId = OpenStorageDatabase(BakaShrot_Storage_Writer\DatabasePath)
If Not DbId
PrintN("[Storage] Can't open the database for the checkpoints, the WAL file will keep growing: " + DatabaseError())
ProcedureReturn
EndIf
LastCheckpoint = ElapsedMilliseconds()
While Not BakaShrot_Storage_Writer\StopRequested
Delay(50)
If ElapsedMilliseconds() - LastCheckpoint < #BakaShrot_Storage_CheckpointInterval
Continue
EndIf
StartTicks = BakaShrot_Storage_Ticks()
Round = 0
Repeat
BakaShrot_Writer_CheckpointOnce(DbId, @Frames, @Left)
Round + 1
Until Left\i <= #BakaShrot_Storage_CheckpointFinishFrames Or Round >= 4 Or BakaShrot_Storage_Writer\StopRequested
If Frames\i > 0 And Left\i <= #BakaShrot_Storage_CheckpointFinishFrames
LockMutex(BakaShrot_Storage_WriteMutex)
LockedTicks = BakaShrot_Storage_Ticks()
BakaShrot_Writer_CheckpointOnce(DbId, @Frames, @Left)
BakaShrot_Storage_Writer\CheckpointLockedTicks + BakaShrot_Storage_Ticks() - LockedTicks
UnlockMutex(BakaShrot_Storage_WriteMutex)
EndIf
BakaShrot_Storage_Writer\WalFrames = Frames\i
BakaShrot_Storage_Writer\CheckpointTicks + BakaShrot_Storage_Ticks() - StartTicks
BakaShrot_Storage_Writer\CheckpointCount + 1
LastCheckpoint = ElapsedMilliseconds()
Wend
CloseDatabase(DbId)
EndProcedure
; Holding the write mutex.
Procedure BakaShrot_Writer_Release()
With BakaShrot_Storage_Writer
BakaShrot_Writer_Finalize(@\Begin)
BakaShrot_Writer_Finalize(@\Commit)
BakaShrot_Writer_Finalize(@\Rollback)
BakaShrot_Writer_Finalize(@\Insert)
BakaShrot_Writer_Finalize(@\InsertOrIgnore)
BakaShrot_Writer_Finalize(@\MaxId)
If \DbId
CloseDatabase(\DbId)
EndIf
\DbId = 0
\Handle = 0
ClearMap(\NextIds())
EndWith
EndProcedure
; Opens the writer on DatabasePath, already set up by SetupStorageDatabase(),
; and starts the checkpoints. Returns #False with the reason in *Error\s.
Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String)
Protected *Main
LockMutex(BakaShrot_Storage_WriteMutex)
With BakaShrot_Storage_Writer
\DatabasePath = DatabasePath
\DbId = OpenStorageDatabase(DatabasePath)
If Not \DbId
*Error\s = "can't open it: " + DatabaseError()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
; The checkpoint thread does them, see the top of this file. This is
; only the backstop for when it can't keep up.
If Not DatabaseUpdate(\DbId, "PRAGMA wal_autocheckpoint = " + Str(#BakaShrot_Storage_WalBackstopFrames)) Or
Not DatabaseUpdate(\DbId, "PRAGMA journal_size_limit = " + Str(#BakaShrot_Storage_WalSizeLimit))
*Error\s = "can't set it up: " + DatabaseError()
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
CompilerIf #BakaShrot_Storage_RawSqlite
If Not BakaShrot_Writer_LoadSqlite()
*Error\s = "sqlite3.dll doesn't have the functions needed"
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
\Handle = DatabaseID(\DbId)
*Main = UTF8("main")
If Not \Handle Or Not BakaShrot_Sqlite\DbFilename(\Handle, *Main)
FreeMemory(*Main)
*Error\s = "DatabaseID() didn't give a sqlite3 handle"
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
FreeMemory(*Main)
CompilerEndIf
\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
*Error\s = "can't prepare its statements: " + \LastError
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
\StopRequested = #False
\CheckpointThread = CreateThread(@BakaShrot_Writer_CheckpointThread(), 0)
If Not \CheckpointThread
*Error\s = "can't start the checkpoint thread"
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
EndWith
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #True
EndProcedure
; Stops the checkpoints, checkpoints everything (emptying the WAL file) and
; closes the writer. Once nothing writes anymore: the workers are stopped.
Procedure CloseStorageWriter()
With BakaShrot_Storage_Writer
If \CheckpointThread
\StopRequested = #True
WaitThread(\CheckpointThread)
\CheckpointThread = 0
EndIf
LockMutex(BakaShrot_Storage_WriteMutex)
If \DbId
If DatabaseQuery(\DbId, "PRAGMA wal_checkpoint(TRUNCATE)")
NextDatabaseRow(\DbId)
FinishDatabaseQuery(\DbId)
EndIf
EndIf
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
EndWith
EndProcedure
; --- Writes ------------------------------------------------------------------
; Holding the write mutex.
Procedure BakaShrot_Writer_LogStats()
Protected Now.i = ElapsedMilliseconds(), Seconds.d, Checkpoints.s
With BakaShrot_Storage_Writer\Stats
If \LastLog = 0
\LastLog = Now
ProcedureReturn
EndIf
If Now - \LastLog < #BakaShrot_Storage_StatsInterval
ProcedureReturn
EndIf
Seconds = (Now - \LastLog) / 1000.0
If \Groups > 0
If BakaShrot_Storage_Writer\CheckpointCount > 0
Checkpoints = ", " + Str(BakaShrot_Storage_Writer\CheckpointCount) + " checkpoints of " +
StrD(BakaShrot_Storage_Writer\CheckpointTicks / BakaShrot_Storage_TicksPerMs / BakaShrot_Storage_Writer\CheckpointCount, 1) + " ms (" +
StrD(BakaShrot_Storage_Writer\CheckpointLockedTicks / BakaShrot_Storage_TicksPerMs / BakaShrot_Storage_Writer\CheckpointCount, 1) + " ms of it holding the writes), " +
Str(BakaShrot_Storage_Writer\WalFrames) + " frames in the WAL"
EndIf
PrintN("[Storage] " + Str(\Pushes) + " pushes in " + StrD(Seconds, 1) + " s (" + StrD(\Pushes / Seconds, 0) + "/s), " +
Str(\Groups) + " transactions of " + StrD(\Pushes / \Groups, 1) + " on average, " +
StrD(\Ticks / BakaShrot_Storage_TicksPerMs / \Groups, 3) + " ms each, " +
StrD(\Ticks / BakaShrot_Storage_TicksPerMs / \Pushes, 3) + " ms per push, writing " +
StrD(100.0 * \Ticks / BakaShrot_Storage_TicksPerMs / (Seconds * 1000.0), 0) + " % of the time" + Checkpoints)
EndIf
\LastLog = Now
\Groups = 0
\Pushes = 0
\Ticks = 0
BakaShrot_Storage_Writer\CheckpointCount = 0
BakaShrot_Storage_Writer\CheckpointTicks = 0
BakaShrot_Storage_Writer\CheckpointLockedTicks = 0
EndWith
EndProcedure
; Writes queued pushes in one transaction, filling in their MessageId (-1 and
; Error if that one failed) and setting Done. Holding the write mutex.
Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
Protected *Job.BakaShrot_PushJob, InTransaction.i, Key.s, MessageId.q, JsonData.s
; If it can't start (another process writing past the busy timeout),
; every insert still runs, each in its own transaction.
InTransaction = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin)
; One failed insert is only that statement's, SQLite keeps the others.
ForEach Jobs()
*Job = Jobs()
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
*Job\MessageId = MessageId
BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1
Else
*Job\MessageId = -1
*Job\Error = BakaShrot_Storage_Writer\LastError
EndIf
Next
If InTransaction And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit)
ForEach Jobs()
*Job = Jobs()
*Job\MessageId = -1
*Job\Error = BakaShrot_Storage_Writer\LastError
Next
BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Rollback)
; Some ids were handed out and rolled back.
ClearMap(BakaShrot_Storage_Writer\NextIds())
EndIf
ForEach Jobs()
*Job = Jobs()
*Job\Done = #True
Next
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
; the reason in *Error\s.
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
Protected Job.BakaShrot_PushJob
Protected NewList Jobs.i()
Protected StartTicks.q
Job\TopicId = TopicId
Job\NodeId = NodeId
Job\JsonData = JsonData
Job\MessageId = -1
LockMutex(BakaShrot_Storage_QueueMutex)
AddElement(BakaShrot_Storage_Queue())
BakaShrot_Storage_Queue() = @Job
UnlockMutex(BakaShrot_Storage_QueueMutex)
; Whoever gets the mutex writes everything queued so far, this one's
; included unless an earlier holder already did. The queue is first in,
; first out, so a capped group still gets to it eventually.
LockMutex(BakaShrot_Storage_WriteMutex)
If Not BakaShrot_Storage_Writer\DbId
; Closed: the workers are stopping.
LockMutex(BakaShrot_Storage_QueueMutex)
ForEach BakaShrot_Storage_Queue()
If BakaShrot_Storage_Queue() = @Job
DeleteElement(BakaShrot_Storage_Queue())
Break
EndIf
Next
UnlockMutex(BakaShrot_Storage_QueueMutex)
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
While Not Job\Done
ClearList(Jobs())
LockMutex(BakaShrot_Storage_QueueMutex)
ForEach BakaShrot_Storage_Queue()
If ListSize(Jobs()) >= #BakaShrot_Storage_MaxGroupSize
Break
EndIf
AddElement(Jobs())
Jobs() = BakaShrot_Storage_Queue()
DeleteElement(BakaShrot_Storage_Queue())
Next
UnlockMutex(BakaShrot_Storage_QueueMutex)
StartTicks = BakaShrot_Storage_Ticks()
BakaShrot_Writer_WriteJobs(Jobs())
With BakaShrot_Storage_Writer\Stats
\Ticks + BakaShrot_Storage_Ticks() - StartTicks
\Groups + 1
\Pushes + ListSize(Jobs())
EndWith
Wend
BakaShrot_Writer_LogStats()
UnlockMutex(BakaShrot_Storage_WriteMutex)
If Job\MessageId < 1
*Error\s = Job\Error
EndIf
ProcedureReturn Job\MessageId
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:
; 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).
; 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
Key = Str(TopicId) + ":" + Str(NodeId)
LockMutex(BakaShrot_Storage_WriteMutex)
If Not BakaShrot_Storage_Writer\DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn #False
EndIf
; IMMEDIATE takes the write lock up front, instead of failing midway if
; another process started writing first.
Stored = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin)
If Stored
ForEach Messages()
JsonData = Messages()\JsonData
Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData)
If Inserted < 0
Stored = #False
Break
EndIf
; A pair pushed to here too (drift): the next push goes after it.
If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds()
BakaShrot_Storage_Writer\NextIds() = Messages()\MessageId + 1
EndIf
EndIf
Next
If Stored And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit)
Stored = #False
EndIf
If Not Stored
*Error\s = BakaShrot_Storage_Writer\LastError
BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Rollback)
ClearMap(BakaShrot_Storage_Writer\NextIds())
EndIf
Else
*Error\s = BakaShrot_Storage_Writer\LastError
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Stored
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.
; Returns #False with the reason in *Error\s.
Procedure.i RegisterStorageName(Table.s, Id.i, Name.s, Origin.s, *Error.String)
Protected DbId.i, Stored.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn #False
EndIf
SetDatabaseLong(DbId, 0, Id)
SetDatabaseString(DbId, 1, Name)
SetDatabaseString(DbId, 2, Origin)
Stored = DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + Table + " VALUES (?, ?, ?)")
If Not Stored
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Stored
EndProcedure
+32
View File
@@ -0,0 +1,32 @@
table archives {
# UTC Unix Timestamp after which this archived message should be deleted.
delete_by ??? [NOT NULL]
message_data TEXT [NOT NULL]
}
table data {
group_id INTEGER [NOT NULL]
node_id INTEGER [NOT NULL]
message_id INTEGER [NOT NULL]
message_data TEXT [NOT NULL]
}
# Create it, but we'll implement this later.
table attachements {
group_id INTEGER [NOT NULL]
node_id INTEGER [NOT NULL]
message_id INTEGER [NOT NULL]
attachement_data BLOB [NOT NULL]
}
index {
data, on combined group_id/node_id
data, on message_id
attachements, on combined group_id/node_id
attachements, on message_id
}
# Note, ignore it
# msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+34
View File
@@ -0,0 +1,34 @@
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Create it, but we'll implement this later.
table attachements {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+45
View File
@@ -0,0 +1,45 @@
// Changes from v1, on "data" only:
// - UNIQUE (group_id, node_id, message_id), so a message id can't be stored twice.
// Its index also serves (group_id, node_id) lookups, replacing v1's index on them.
// - is_json, set by SQLite on insert, for JSON queries on message_data.
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
group_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']
indexes {
(group_id, node_id, message_id) [unique]
message_id
}
}
// Create it, but we'll implement this later.
table attachements {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+62
View File
@@ -0,0 +1,62 @@
// Changes from v2:
// - node_heads, the highest message id of every group/node id, kept by the
// trg_data_node_heads trigger on every insert into data. The sync state
// (GetSyncState()) reads it instead of a GROUP BY over every message.
// Filled from data when it's created on an existing database.
// Nothing deletes from data yet, whatever does must update it too.
//
// 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 archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
group_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']
indexes {
(group_id, node_id, message_id) [unique]
message_id
}
}
// One row per group/node id that has messages.
// 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'] {
group_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(group_id, node_id) [pk]
}
}
// Create it, but we'll implement this later.
table attachements {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+61
View File
@@ -0,0 +1,61 @@
// Changes from v3:
// - group_id is now topic_id, in every table. MigrateStorageTopicIds()
// (Storage.pbi) renames the columns of an older database on start, and
// the trigger and the attachements index are made again with the new
// names (idx_attachements_group_node -> idx_attachements_topic_node).
//
// 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 archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
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']
indexes {
(topic_id, node_id, message_id) [unique]
message_id
}
}
// One row per topic/node id that has messages.
// 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
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+88
View File
@@ -0,0 +1,88 @@
// Changes from v4:
// - topics and nodes: every topic and node id in data, with its name (its
// id in digits if it has none) and where that comes from. Kept by
// Server/Storage/Names.pbi from the config. Only names on both servers
// replicate. Names are shared between servers, ids aren't.
// - messages: a view of data with the names, for queries by name.
// - No foreign keys from data to them (Notes.md): an unknown id would fail
// a whole replicated batch.
//
// 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 archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
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']
indexes {
(topic_id, node_id, message_id) [unique]
message_id
}
}
// One row per topic/node id that has messages.
// 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
// 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