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

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
+261
View File
@@ -0,0 +1,261 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrot_Server.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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.
;
; Windows: it stops once there's no more console input (no console, closed
; standard input). Elsewhere, it runs on without one (a container, a
; service) and SIGTERM or SIGINT stops it the same way as "quit".
;
; Compile as a thread-safe console program.
; ============================================================================
; ------------------------------------------------------------------------------
;- Compiler directive
CompilerIf Not #PB_Compiler_IsMainFile
CompilerError "The server's main file was included !"
CompilerEndIf
CompilerIf Not #PB_Compiler_Thread
CompilerError "The server must be compiled in thread-safe mode !"
CompilerEndIf
EnableExplicit
XIncludeFile "Root.pbi"
#BakaShrot_Server_DefaultConfigPath = "config.ini"
Procedure PrintCommands()
PrintN("Commands: quit (or an empty line), restart, vacuum, names, help")
EndProcedure
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
; Same numbers on Linux and macOS.
#BakaShrot_Server_SigInt = 2
#BakaShrot_Server_SigTerm = 15
#BakaShrot_Server_PollIn = $0001
#BakaShrot_Server_FDupFd = 0
; struct pollfd
Structure BakaShrot_Server_PollFd
Fd.l
Events.w
REvents.w
EndStructure
ImportC ""
BakaShrot_Server_Signal.i(Signal.l, *Handler) As "signal"
BakaShrot_Server_Poll.l(*Fds, Count.i, TimeoutMs.l) As "poll"
BakaShrot_Server_Read.i(Fd.l, *Buffer, Size.i) As "read"
; dup() itself can't be imported: fasm reserves the name.
BakaShrot_Server_Fcntl.l(Fd.l, Command.l, Argument.i) As "fcntl"
EndImport
; Longest command line kept, the rest of a longer one is dropped.
#BakaShrot_Server_MaxCommandSize = 256
; The signal that asked to stop, 0 until then. Only ever set by the
; handler (all a handler may safely do), read by ReadCommand().
Global BakaShrot_Server_StopSignal.l = 0
; #True once standard input is closed: commands can't come any more.
Global BakaShrot_Server_NoInput.i = #False
; Standard input, taken before OpenConsole(): it moves descriptor 0
; elsewhere and closes it (then reused by the next file opened).
Global BakaShrot_Server_InputFd.l = -1
ProcedureC BakaShrot_Server_OnSignal(Signal.l)
BakaShrot_Server_StopSignal = Signal
EndProcedure
CompilerEndIf
; Waits for the next command, Chr(4) once there's no more input.
; Windows: Input(). Elsewhere, Input() returns "" (quit) at the end of the
; input and blocks until a whole line came, so standard input is read here
; instead: never blocking for more than 250 ms without checking for a stop
; signal (it then returns "", see BakaShrot_Server_StopSignal).
Procedure.s ReadCommand()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
ProcedureReturn Input()
CompilerElse
Protected Fd.BakaShrot_Server_PollFd, Byte.a, BytesRead.i, Size.i
Protected Dim Chars.a(#BakaShrot_Server_MaxCommandSize)
Repeat
If BakaShrot_Server_StopSignal
ProcedureReturn ""
EndIf
If BakaShrot_Server_NoInput
Delay(250)
Continue
EndIf
If BakaShrot_Server_InputFd < 0
ProcedureReturn Chr(4)
EndIf
Fd\Fd = BakaShrot_Server_InputFd
Fd\Events = #BakaShrot_Server_PollIn
Fd\REvents = 0
If BakaShrot_Server_Poll(@Fd, 1, 250) <= 0
Continue
EndIf
; Readable, or closed: one byte, so nothing is read past the line.
BytesRead = BakaShrot_Server_Read(BakaShrot_Server_InputFd, @Byte, 1)
If BytesRead = 0 Or (BytesRead < 0 And Not BakaShrot_Server_StopSignal)
ProcedureReturn Chr(4)
EndIf
If BytesRead = 1
If Byte = 10
ProcedureReturn PeekS(@Chars(0), Size, #PB_UTF8 | #PB_ByteLength)
EndIf
; CR of a CRLF skipped.
If Byte <> 13 And Size < #BakaShrot_Server_MaxCommandSize
Chars(Size) = Byte
Size + 1
EndIf
EndIf
ForEver
CompilerEndIf
EndProcedure
Define Root.BakaShrot_Root
Define Command.s, ExitCode.i
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
BakaShrot_Server_InputFd = BakaShrot_Server_Fcntl(0, #BakaShrot_Server_FDupFd, 0)
CompilerEndIf
OpenConsole("BakaShrot Server")
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
BakaShrot_Server_Signal(#BakaShrot_Server_SigTerm, @BakaShrot_Server_OnSignal())
BakaShrot_Server_Signal(#BakaShrot_Server_SigInt, @BakaShrot_Server_OnSignal())
CompilerEndIf
Root\ConfigPath = #BakaShrot_Server_DefaultConfigPath
If CountProgramParameters() > 0
Root\ConfigPath = ProgramParameter(0)
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(ReadCommand()))
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
If BakaShrot_Server_StopSignal
If BakaShrot_Server_StopSignal = #BakaShrot_Server_SigTerm
PrintN("Got SIGTERM, stopping")
Else
PrintN("Got SIGINT, stopping")
EndIf
Break
EndIf
CompilerEndIf
; Once there's no more input (no console, closed standard input), every
; ReadCommand() returns Chr(4) right away. Without this, it would loop
; forever.
If FindString(Command, Chr(4))
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
PrintN("No more input, stopping")
Break
CompilerElse
PrintN("No console input, running until SIGTERM or SIGINT")
BakaShrot_Server_NoInput = #True
Continue
CompilerEndIf
EndIf
Select Command
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
File diff suppressed because it is too large Load Diff
+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
+218
View File
@@ -0,0 +1,218 @@
; 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. Topics are named in [BakaShrot.Topics]; nodes by the sections that
; define them ([BakaShrot] Node, a peer's, a client's), [BakaShrot.Nodes]
; only names the others. The server gives every name its id, and keeps it.
; Names are what's shared between servers: replication sends them, and
; each server stores the messages under its own ids for them ("logs" can be
; 1 here and 200 on a peer).
; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a
; name, or whose name the other server doesn't have, is dropped. Unnamed
; ones still work locally, by id.
; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter.
; The server's "names" command and the BakaShrotList 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 BakaShrotGenerateKeyPairs.exe. It proves who
; this server is: clients seal their Hello for its public key and check
; that it signed the handshake, so they need that public key (client.ini's
; ServerPublicKey, peers' PublicKey below in THEIR own config). The server
; logs it when it starts. See Commons/Networking/Connections.pbi.
PrivateKey =
; The node this server authenticates as when it links to its peers, a name
; or an id. Its peers must register it under the same name: a client
; section with this Node and this server's public key. (A Topic left here
; from before protocol 5 is ignored.)
Node =
[BakaShrot.Topics]
; One topic name per line. This server gives each its id: the one its
; database already has for it, or the lowest free one for a new one, so the
; order doesn't matter and they keep their ids.
; "name = id" pins one instead (configs from before work as they are). Once
; a name has messages, its id can't change: the server refuses to start if
; a pin moves it, and says which id to use.
; logs
; sensors
[BakaShrot.Nodes]
; Optional. The nodes [BakaShrot] Node, the peers' and the clients' Node
; define are named already. List the others this server should know by name
; up front, like topics; peers add the ones they send as they come
; (AcceptNodes, below).
; kitchen
[BakaShrot.Retention]
; How long this server keeps each topic's messages, counted from when they
; were pushed (to whichever server they were first pushed to). Past that,
; they may be deleted: checked every RetentionInterval seconds. Each server
; has its own: a peer keeps its copies as long as its own config says.
; One line per topic: name or id = age, a pattern (sensors.*), or * for
; every topic not listed. A topic takes its id's line, else its name's,
; else the first pattern matching it, else *'s.
; Ages: numbers with a unit, s m h d w, added up (1d12h), or forever.
; Without any line, everything is kept forever.
; Deleting doesn't shrink the file, SQLite reuses the space for new
; messages; the "vacuum" console command gives it back to the disk.
; logs = 30d
; sensors.* = 12h
; * = 365d
[BakaShrot.Server]
; IPV4 that the server will be bound to.
Host =
; 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
; Seconds between two passes deleting the messages past their topic's age
; ([BakaShrot.Retention] above), and the attachments' leftovers.
RetentionInterval = 60
; Biggest attachment this server takes (one per message, see
; Design/Attachments.md): pushed to it, or replicated (a bigger one's message
; is kept, its attachment isn't). Bytes, or K M G T (1024-based). 0: none.
MaxAttachmentSize = 1G
; Seconds a client may take to upload an attachment and push its message,
; after which the upload is deleted.
UploadTimeout = 3600
; How hard the database makes sure a push is on disk before answering it.
; FULL (default) every commit is flushed to disk: a message the server
; acknowledged survives a power loss or an OS crash.
; NORMAL flushed about once a second only (at the checkpoints): faster
; (twice the pushes under full load, measured), but a power loss
; or an OS crash loses the last second or so of acknowledged
; messages, and their ids are handed out again, which peers that
; already got them can't tell (Design/ReplicationIssues.md #1).
; A crash of the server alone loses nothing either way.
; The cost of FULL is the disk's flush time, once per group of pushes: well
; under a millisecond on a server SSD, ~10 ms on a hard disk, which then
; caps one client pushing one message at a time to ~100/s.
; See Design/StorageConcurrency.md for the numbers.
Synchronous = FULL
; One [BakaShrot.Peer.<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.
; The peer's node, a name or an id: the one in its own [BakaShrot] Node.
; It authenticates as it when it links to here.
Node =
; The topics sent to this peer (if it takes them), and the topics taken
; 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: every one, the names
; this server doesn't have yet are added as they come). AcceptNodes =
; kitchen-*;garage only takes those, named here or not.
; SendNodes = *
; AcceptNodes = kitchen-*;garage
; 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 =
; The node this client writes as, a name or an id, required. Every message
; it pushes is stored under it, so the server decides which node each key
; writes as, and no client can push as another's node (or as a peer's).
; Its client.ini's Node must say the same. A key that writes as several
; nodes is listed in a section per node.
; ONE SERVER PER NODE: give a node a client section on the one server it
; pushes to, the others get its messages by replication. Two servers taking
; pushes for the same node end up with different messages under the same
; ids, which nothing detects (Design/ReplicationIssues.md #1). To read from
; another server, give the client another node there (or no write access:
; AllowWrite = 0).
Node =
; Where its pushes go when they don't name a topic, a name or an id.
; Optional: without it, every push must name its topic. Only a default, it
; may push to any topic in PushTopics.
; DefaultTopic = logs
; (Identities, the Topic:Node pairs before protocol 5, isn't read any more:
; the server refuses to start with it, saying what to write instead.)
; The topics it may push to (always under its own node), and the topics it
; may read the latest messages of. Both default to its DefaultTopic,
; nothing without one; 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
@@ -0,0 +1,7 @@
IDE Options = PureBasic 6.41 beta 2 (Windows - x64)
EnableThread
EnableXP
DPIAware
CompileSourceDirectory
EnableCompileCount = 0
EnableBuildCount = 0
+733
View File
@@ -0,0 +1,733 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Peers.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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.
; A message's attachment only has its size and SHA-256 in the batch.
; 4. Once the messages are caught up, asks the peer which attachments it's
; missing (MissingAttachmentsRequest) and sends those it has, a part
; (1 MB) per request, from where the peer stopped (Design/Attachments.md).
; The peer does the same over its own link to this server, which covers the
; other direction. Any packet from the peer outside of a check-in drops the
; link as unexpected.
; 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 (" + BakaShrot_ErrorName(*Refused\Code) + "): " + *Refused\Reason)
FreeStructure(*Refused)
ProcedureReturn #True
EndProcedure
; Sends the peer the attachment it's missing, *Missing, from the part it
; asked for on, if this server has all of it and sends that topic/node to it.
; Returns 1 once the peer has it, 0 if it's skipped (not here, not sent to
; that peer, refused: logged), -1 if the link must be dropped.
Procedure.i BakaShrot_PeerLink_SendAttachment(*Link.BakaShrot_PeerLink, *Missing.BakaShrot_MissingAttachment)
Protected *Links.BakaShrot_PeerLinks = *Link\Links
Protected Attachment.BakaShrot_StorageAttachment, Chunk.BakaShrot_ReplicateAttachmentChunk
Protected *Stored.BakaShrot_ChunkStored
Protected TopicId.i, NodeId.i, Index.q, Count.q, DataSize.Integer, Complete.i
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
TopicId = BakaShrot_Names_TopicByName(*Missing\Topic)
NodeId = BakaShrot_Names_NodeByName(*Missing\Node)
If TopicId < 0 Or NodeId < 0
ProcedureReturn 0
EndIf
If Not NameSetHas(@*Link\SendTopics, TopicId, *Missing\Topic) Or Not NameSetHas(@*Link\SendNodes, NodeId, *Missing\Node)
ProcedureReturn 0
EndIf
; Not here either (yet, or not kept): another server may have it.
If Not GetStorageAttachment(*Link\DbId, TopicId, NodeId, *Missing\MessageId, @Attachment) Or Attachment\State <> #BakaShrot_Attachment_Ready
ProcedureReturn 0
EndIf
Count = BakaShrot_AttachmentChunkCount(Attachment\Size)
Chunk\Topic = *Missing\Topic
Chunk\Node = *Missing\Node
Chunk\MessageId = *Missing\MessageId
For Index = *Missing\NextChunk To Count - 1
If *Links\StopRequested
ProcedureReturn -1
EndIf
Chunk\ChunkIndex = Index
Chunk\Data = ReadStorageBlobChunk(*Link\DbId, Attachment\BlobId, Index, @DataSize)
If Not Chunk\Data
PrintN("[Peer] Can't read part " + Str(Index) + " of the attachment of " + *Missing\Topic + ":" + *Missing\Node + "#" + Str(*Missing\MessageId) + " for '" + *Link\Name + "'")
ProcedureReturn 0
EndIf
Chunk\DataSize = DataSize\i
*Packet = BakaShrot_ReplicateAttachmentChunkPacket_Encode(@Chunk, @PacketSize)
FreeMemory(Chunk\Data)
Chunk\Data = 0
If Not *Packet
ProcedureReturn -1
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
ProcedureReturn -1
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
If Not IsRefusal
ProcedureReturn -1
EndIf
ProcedureReturn 0
EndIf
*Stored = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *Stored
PrintN("[Peer] '" + *Link\Name + "' sent an invalid answer to an attachment's part")
ProcedureReturn -1
EndIf
Complete = *Stored\Complete
FreeStructure(*Stored)
If Complete
ProcedureReturn 1
EndIf
Next
; All sent, and the peer didn't say it's complete: it'll ask again.
ProcedureReturn 0
EndProcedure
; Once the messages are caught up: asks the peer which attachments it's
; missing, and sends those this server has, one after the other.
; Returns #False if the link must be dropped.
Procedure.i BakaShrot_PeerLink_SendAttachments(*Link.BakaShrot_PeerLink)
Protected Request.BakaShrot_MissingAttachmentsRequest, *Missing.BakaShrot_MissingAttachments
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
Protected Result.i, StartTime.i, Attachment.BakaShrot_StorageAttachment, Key.s
*Packet = BakaShrot_MissingAttachmentsRequestPacket_Encode(@Request, @PacketSize)
If Not *Packet
ProcedureReturn #False
EndIf
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
FreeMemory(*Packet)
If Not *Answer
PrintN("[Peer] '" + *Link\Name + "' didn't answer which attachments it's missing")
ProcedureReturn #False
EndIf
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
FreeMemory(*Answer)
ProcedureReturn IsRefusal
EndIf
*Missing = 0
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
If *View
*Missing = BakaShrot_MissingAttachmentsPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
If Not *Missing
PrintN("[Peer] '" + *Link\Name + "' sent an invalid list of missing attachments")
ProcedureReturn #False
EndIf
ForEach *Missing\Attachments()
StartTime = ElapsedMilliseconds()
Result = BakaShrot_PeerLink_SendAttachment(*Link, @*Missing\Attachments())
If Result < 0
FreeStructure(*Missing)
ProcedureReturn #False
EndIf
If Result > 0
Key = *Missing\Attachments()\Topic + ":" + *Missing\Attachments()\Node + "#" + Str(*Missing\Attachments()\MessageId)
PrintN("[Peer] Sent the attachment of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, from part " + Str(*Missing\Attachments()\NextChunk))
EndIf
Next
FreeStructure(*Missing)
ProcedureReturn #True
EndProcedure
; Sends a batch of messages the peer is missing and checks its answer.
; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the
; link must be dropped.
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
; As stored: when it was pushed to its origin, whichever server that was.
Batch\Messages()\PushedAt = Messages()\PushedAt
Batch\Messages()\JsonData = Messages()\JsonData
; Its attachment's size and SHA-256 only: the data goes once the
; messages are caught up (BakaShrot_PeerLink_SendAttachments()).
Batch\Messages()\AttachmentSize = Messages()\AttachmentSize
CopyMemory(@Messages()\AttachmentSha256[0], @Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
Next
If ListSize(Batch\Messages()) = 0
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
; 4. Then the attachments: only for messages the peer has now.
ProcedureReturn BakaShrot_PeerLink_SendAttachments(*Link)
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\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
+256
View File
@@ -0,0 +1,256 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Root.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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 "Storage/Retention.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
Protected Known.BakaShrot_KnownNames, KnownError.String, DatabasePath.s, DbId.i
; The names the database has first, so the ones the config lists without
; an id keep theirs (Storage/Names.pbi). Nothing to read on a new one.
DatabasePath = ReadConfigDatabasePath(*Root\ConfigPath)
If DatabasePath <> "" And FileSize(DatabasePath) > 0
DbId = OpenStorageDatabase(DatabasePath)
If Not DbId Or Not SetupStorageDatabase(DbId) Or Not BakaShrot_Names_ReadKnown(DbId, @Known, @KnownError)
PrintN("[Root] Failed to read the names of the database '" + DatabasePath + "': " + KnownError\s + DatabaseError())
If DbId
CloseDatabase(DbId)
EndIf
ProcedureReturn #False
EndIf
CloseDatabase(DbId)
EndIf
*Config = LoadConfig(*Root\ConfigPath, @Known)
If Not *Config
PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError)
ProcedureReturn #False
EndIf
If *Root\Config
FreeConfig(*Root\Config)
EndIf
*Root\Config = *Config
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)")
ProcedureReturn #True
EndProcedure
; 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
; Every connection opened from here on, the workers' included (they're
; stopped meanwhile), takes it.
BakaShrot_Storage_Synchronous = *Root\Config\Server\Synchronous
*Root\DbId = OpenStorageDatabase(DatabasePath)
If Not *Root\DbId
PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError())
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 (synchronous " + BakaShrot_Storage_Synchronous + ")")
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
; Deletes the messages past their topic's max age, see Storage/Retention.pbi.
If Not StartStorageRetention(*Config)
PrintN("[Root] Failed to start the retention thread")
CloseStorageWriter()
ProcedureReturn #False
EndIf
*Root\Server = BakaShrot_NetServer_Start(*Config\Server\Host, *Config\Server\Port, *Config)
If Not *Root\Server
PrintN("[Root] Failed to listen on '" + *Config\Server\Host + ":" + Str(*Config\Server\Port) + "'")
StopStorageRetention()
CloseStorageWriter()
ProcedureReturn #False
EndIf
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
StopStorageRetention()
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
StopStorageRetention()
; 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
+467
View File
@@ -0,0 +1,467 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Attachments.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Storage Attachments
;
; A message has at most one attachment, of any size up to the server's
; MaxAttachmentSize, stored in parts (Design/Attachments.md):
; blobs the data of one attachment, being received or stored
; blob_chunks its parts, #BakaShrot_AttachmentChunkSize bytes each, the
; last one what's left
; attachments a message's: its size and SHA-256, and its blob once any
; of it is here
; See SetupStorageDatabase() in Storage.pbi for the columns and states.
;
; Pushed with a message:
; CreateStorageBlob() an upload starts (state 0), owned by the
; client's topic and node
; StoreStorageBlobChunk() each part, in order
; HashStorageBlob() once all of it is here, checked against the
; SHA-256 given at the start: complete (1), or
; dropped (3)
; then InsertNextMessage() (Writer.pbi) with its blob id attaches it to
; the message, in the same transaction (2).
; Replicated: the message comes first (ReplicateMessages), its attachments
; row in state 0, then once the messages are caught up:
; GetMissingStorageAttachments() what's missing, or started
; StartReplicatedAttachment() the first part makes its blob
; StoreStorageBlobChunk() each part, resuming where it stopped
; FinishReplicatedAttachment() ready (2), or back to missing if its
; SHA-256 doesn't match
; Deleting a message (the retention) deletes its attachments row (trigger),
; which marks its blob (3); CleanUpStorageBlobs() deletes it a part at a
; time, along with uploads never completed or never attached.
;
; Writes go through the writer (Writer.pbi), under its mutex; reads take
; the caller's own connection.
; ============================================================================
; SHA-256 (BakaShrot_Sha256_*).
XIncludeFile "../../Commons/Cryptography/Libsodium.pbi"
Structure BakaShrot_StorageBlob
BlobId.q
TopicId.i
NodeId.i
Size.q
Sha256.a[#BakaShrot_Sha256Size]
Received.q
State.i
EndStructure
Structure BakaShrot_StorageAttachment
Size.q
Sha256.a[#BakaShrot_Sha256Size]
; 0 while none of it is here.
BlobId.q
; 0 missing, 1 receiving, 2 ready, 3 not kept here.
State.i
; Of its blob, 0 without one.
Received.q
EndStructure
Structure BakaShrot_StorageMissingAttachment
TopicId.i
NodeId.i
Topic.s
Node.s
MessageId.q
Received.q
EndStructure
#BakaShrot_Blob_Receiving = 0
#BakaShrot_Blob_Complete = 1
#BakaShrot_Blob_Attached = 2
#BakaShrot_Blob_Deleted = 3
#BakaShrot_Attachment_Missing = 0
#BakaShrot_Attachment_Receiving = 1
#BakaShrot_Attachment_Ready = 2
#BakaShrot_Attachment_NotKept = 3
; --- Reads, on the caller's connection -----------------------------------------
; Fills *Blob with blob BlobId. Returns #False if there's none.
Procedure.i GetStorageBlob(DbId.i, BlobId.q, *Blob.BakaShrot_StorageBlob)
Protected Found.i
SetDatabaseQuad(DbId, 0, BlobId)
If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, size, sha256, received, state FROM blobs WHERE blob_id = ?")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Blob\BlobId = BlobId
*Blob\TopicId = GetDatabaseLong(DbId, 0)
*Blob\NodeId = GetDatabaseLong(DbId, 1)
*Blob\Size = GetDatabaseQuad(DbId, 2)
FillMemory(@*Blob\Sha256[0], #BakaShrot_Sha256Size, 0)
If DatabaseColumnSize(DbId, 3) = #BakaShrot_Sha256Size
GetDatabaseBlob(DbId, 3, @*Blob\Sha256[0], #BakaShrot_Sha256Size)
EndIf
*Blob\Received = GetDatabaseQuad(DbId, 4)
*Blob\State = GetDatabaseLong(DbId, 5)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; Fills *Attachment with the attachment of TopicId:NodeId#MessageId.
; Returns #False if that message has none (or doesn't exist).
Procedure.i GetStorageAttachment(DbId.i, TopicId.i, NodeId.i, MessageId.q, *Attachment.BakaShrot_StorageAttachment)
Protected Found.i
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
If Not DatabaseQuery(DbId, "SELECT a.size, a.sha256, COALESCE(a.blob_id, 0), a.state, COALESCE(b.received, 0) " +
"FROM attachments a LEFT JOIN blobs b ON b.blob_id = a.blob_id " +
"WHERE a.topic_id = ? AND a.node_id = ? AND a.message_id = ?")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Attachment\Size = GetDatabaseQuad(DbId, 0)
FillMemory(@*Attachment\Sha256[0], #BakaShrot_Sha256Size, 0)
If DatabaseColumnSize(DbId, 1) = #BakaShrot_Sha256Size
GetDatabaseBlob(DbId, 1, @*Attachment\Sha256[0], #BakaShrot_Sha256Size)
EndIf
*Attachment\BlobId = GetDatabaseQuad(DbId, 2)
*Attachment\State = GetDatabaseLong(DbId, 3)
*Attachment\Received = GetDatabaseQuad(DbId, 4)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; Part Index of blob BlobId, in a freshly allocated buffer, its size in
; *OutSize\i. Returns 0 if it isn't stored. The caller frees it.
Procedure.i ReadStorageBlobChunk(DbId.i, BlobId.q, Index.q, *OutSize.Integer)
Protected *Data, Size.i
SetDatabaseQuad(DbId, 0, BlobId)
SetDatabaseQuad(DbId, 1, Index)
If Not DatabaseQuery(DbId, "SELECT chunk_data FROM blob_chunks WHERE blob_id = ? AND chunk_index = ?")
ProcedureReturn 0
EndIf
If NextDatabaseRow(DbId)
Size = DatabaseColumnSize(DbId, 0)
If Size > 0
*Data = AllocateMemory(Size, #PB_Memory_NoClear)
If *Data
GetDatabaseBlob(DbId, 0, *Data, Size)
*OutSize\i = Size
EndIf
EndIf
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn *Data
EndProcedure
; Reads all of blob BlobId back (Size bytes, in parts) and checks its SHA-256
; is *Sha256. Returns #False if it isn't, or a part is missing or the wrong
; size. ~3 s per GB.
Procedure.i HashStorageBlob(DbId.i, BlobId.q, Size.q, *Sha256)
Protected Hash.BakaShrot_Sha256, Index.q, Count.q, *Data, DataSize.Integer
Protected Dim Result.a(#BakaShrot_Sha256Size - 1)
If Not BakaShrot_Sha256_Start(@Hash)
ProcedureReturn #False
EndIf
Count = BakaShrot_AttachmentChunkCount(Size)
For Index = 0 To Count - 1
*Data = ReadStorageBlobChunk(DbId, BlobId, Index, @DataSize)
If Not *Data
ProcedureReturn #False
EndIf
If DataSize\i <> BakaShrot_AttachmentChunkBytes(Size, Index)
FreeMemory(*Data)
ProcedureReturn #False
EndIf
BakaShrot_Sha256_Add(@Hash, *Data, DataSize\i)
FreeMemory(*Data)
Next
BakaShrot_Sha256_Finish(@Hash, @Result(0))
ProcedureReturn CompareMemory(@Result(0), *Sha256, #BakaShrot_Sha256Size)
EndProcedure
; Fills Missing() with attachments of messages here that aren't all here
; yet (missing or receiving), with their topic and node names, up to Limit.
; Unnamed topics or nodes are left out: replication goes by name.
; Returns #False if the query failed.
Procedure.i GetMissingStorageAttachments(DbId.i, Limit.i, List Missing.BakaShrot_StorageMissingAttachment())
ClearList(Missing())
SetDatabaseLong(DbId, 0, Limit)
If Not DatabaseQuery(DbId, "SELECT a.topic_id, a.node_id, t.name, n.name, a.message_id, COALESCE(b.received, 0) " +
"FROM attachments a JOIN topics t ON t.topic_id = a.topic_id JOIN nodes n ON n.node_id = a.node_id " +
"LEFT JOIN blobs b ON b.blob_id = a.blob_id " +
"WHERE a.state IN (0, 1) ORDER BY a.topic_id, a.node_id, a.message_id LIMIT ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Missing())
Missing()\TopicId = GetDatabaseLong(DbId, 0)
Missing()\NodeId = GetDatabaseLong(DbId, 1)
Missing()\Topic = GetDatabaseString(DbId, 2)
Missing()\Node = GetDatabaseString(DbId, 3)
Missing()\MessageId = GetDatabaseQuad(DbId, 4)
Missing()\Received = GetDatabaseQuad(DbId, 5)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; --- Writes, through the writer ------------------------------------------------
; Starts an upload for TopicId/NodeId: Size bytes whose SHA-256 is *Sha256.
; Returns its blob id, 0 with the reason in *Error\s.
Procedure.q CreateStorageBlob(TopicId.i, NodeId.i, Size.q, *Sha256, *Error.String)
Protected DbId.i, BlobId.q
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn 0
EndIf
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, Size)
SetDatabaseBlob(DbId, 3, *Sha256, #BakaShrot_Sha256Size)
SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs())
If DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) VALUES (?, ?, ?, ?, 0, 0, ?)")
If DatabaseQuery(DbId, "SELECT last_insert_rowid()")
If NextDatabaseRow(DbId)
BlobId = GetDatabaseQuad(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
EndIf
If Not BlobId
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn BlobId
EndProcedure
; Stores part Index (DataSize bytes at *Data) of blob BlobId, which must be
; the next one: Index * #BakaShrot_AttachmentChunkSize bytes received so far.
; Returns how many are received now, -1 with the reason in *Error\s (nothing
; stored then).
Procedure.q StoreStorageBlobChunk(BlobId.q, Index.q, *Data, DataSize.i, *Error.String)
Protected DbId.i, Received.q = -1, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
If DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
; Only if it's the next one, and the blob is still being received.
SetDatabaseQuad(DbId, 0, DataSize)
SetDatabaseQuad(DbId, 1, BlobId)
SetDatabaseQuad(DbId, 2, Index * #BakaShrot_AttachmentChunkSize)
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET received = received + ? WHERE blob_id = ? AND received = ? AND state = 0")
If Ok And AffectedDatabaseRows(DbId) <> 1
Ok = #False
*Error\s = "not the next part, or not being received"
ElseIf Not Ok
*Error\s = DatabaseError()
EndIf
If Ok
SetDatabaseQuad(DbId, 0, BlobId)
SetDatabaseQuad(DbId, 1, Index)
SetDatabaseBlob(DbId, 2, *Data, DataSize)
Ok = DatabaseUpdate(DbId, "INSERT INTO blob_chunks (blob_id, chunk_index, chunk_data) VALUES (?, ?, ?)")
If Not Ok
*Error\s = DatabaseError()
EndIf
EndIf
If Ok And DatabaseUpdate(DbId, "COMMIT")
Received = Index * #BakaShrot_AttachmentChunkSize + DataSize
Else
If Ok
*Error\s = DatabaseError()
EndIf
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
Else
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Received
EndProcedure
; Sets blob BlobId's state (#BakaShrot_Blob_*). Returns #False if it failed.
Procedure.i SetStorageBlobState(BlobId.q, State.i)
Protected DbId.i, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If DbId
SetDatabaseLong(DbId, 0, State)
SetDatabaseQuad(DbId, 1, BlobId)
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = ? WHERE blob_id = ?")
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Ok
EndProcedure
; Makes the blob of a replicated attachment that's still missing (state 0),
; from its row's size and SHA-256, and links it: receiving (1).
; Returns its blob id, 0 with the reason in *Error\s.
Procedure.q StartReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, *Error.String)
Protected DbId.i, BlobId.q, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn 0
EndIf
If DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, BakaShrot_NowUtcMs())
SetDatabaseLong(DbId, 3, TopicId)
SetDatabaseLong(DbId, 4, NodeId)
SetDatabaseQuad(DbId, 5, MessageId)
Ok = DatabaseUpdate(DbId, "INSERT INTO blobs (topic_id, node_id, size, sha256, received, state, created_at) " +
"SELECT ?, ?, size, sha256, 0, 0, ? FROM attachments WHERE topic_id = ? AND node_id = ? AND message_id = ? AND state = 0 AND blob_id IS NULL")
If Ok And AffectedDatabaseRows(DbId) = 1 And DatabaseQuery(DbId, "SELECT last_insert_rowid()")
If NextDatabaseRow(DbId)
BlobId = GetDatabaseQuad(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
If BlobId
SetDatabaseQuad(DbId, 0, BlobId)
SetDatabaseLong(DbId, 1, TopicId)
SetDatabaseLong(DbId, 2, NodeId)
SetDatabaseQuad(DbId, 3, MessageId)
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET blob_id = ?, state = 1 WHERE topic_id = ? AND node_id = ? AND message_id = ?")
EndIf
If BlobId And Ok And DatabaseUpdate(DbId, "COMMIT")
; Done.
Else
*Error\s = DatabaseError()
If *Error\s = ""
*Error\s = "the attachment isn't missing"
EndIf
DatabaseUpdate(DbId, "ROLLBACK")
BlobId = 0
EndIf
Else
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn BlobId
EndProcedure
; A replicated attachment is all here: ready (2) if its SHA-256 checked out
; (IsValid), else its blob is dropped and it's missing again (0), to be sent
; again from the start. Returns #False if it failed.
Procedure.i FinishReplicatedAttachment(TopicId.i, NodeId.i, MessageId.q, BlobId.q, IsValid.i)
Protected DbId.i, Ok.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If DbId And DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
SetDatabaseQuad(DbId, 0, BlobId)
If IsValid
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ?")
Else
Ok = DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE blob_id = ?")
EndIf
If Ok
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
If IsValid
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 2 WHERE topic_id = ? AND node_id = ? AND message_id = ?")
Else
Ok = DatabaseUpdate(DbId, "UPDATE attachments SET state = 0, blob_id = NULL WHERE topic_id = ? AND node_id = ? AND message_id = ?")
EndIf
EndIf
If Ok
Ok = DatabaseUpdate(DbId, "COMMIT")
EndIf
If Not Ok
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Ok
EndProcedure
; Marks uploads never completed nor attached, started before BeforeMs (ms
; since 1970 UTC), to delete, then deletes up to Limit parts of what's to
; delete, and the blobs left with none. Call it again while it returns
; Limit. Returns how many parts were deleted, -1 with the reason in *Error\s.
Procedure.i CleanUpStorageBlobs(BeforeMs.q, Limit.i, *Error.String)
Protected DbId.i, Deleted.i = -1
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
; Uploads (no attachments row points to them) left behind.
SetDatabaseQuad(DbId, 0, BeforeMs)
If DatabaseUpdate(DbId, "UPDATE blobs SET state = 3 WHERE state IN (0, 1) AND created_at < ? " +
"AND NOT EXISTS (SELECT 1 FROM attachments a WHERE a.blob_id = blobs.blob_id)")
SetDatabaseLong(DbId, 0, Limit)
If DatabaseUpdate(DbId, "DELETE FROM blob_chunks WHERE rowid IN (SELECT c.rowid FROM blob_chunks c JOIN blobs b ON b.blob_id = c.blob_id WHERE b.state = 3 LIMIT ?)")
Deleted = AffectedDatabaseRows(DbId)
If Deleted < Limit
DatabaseUpdate(DbId, "DELETE FROM blobs WHERE state = 3 AND NOT EXISTS (SELECT 1 FROM blob_chunks c WHERE c.blob_id = blobs.blob_id)")
EndIf
EndIf
EndIf
If Deleted < 0
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Deleted
EndProcedure
+548
View File
@@ -0,0 +1,548 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Names.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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 by the config: in [BakaShrot.Topics] /
; [BakaShrot.Nodes], or a peer's or client's Node
; origin "id" unnamed, its name is its id in digits
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
;
; Ids are this server's to pick: a name the config lists without one keeps
; the one these tables have for it, a new one gets the lowest free one
; (LoadConfig(), after BakaShrot_Names_ReadKnown()). The config may still
; pin one ("logs = 1").
;
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
; on restart). The config wins, except when it would give a name to another
; id than the one the database has it under (or rename a "peer" one): that
; 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
; Fills *Known with what the database has, for LoadConfig() (Config.pbi):
; the id of every name, and every id with a row or messages. Before the
; config is loaded, on a connection of its own, the database set up.
; Returns #False with the reason in *Error\s.
Procedure.i BakaShrot_Names_ReadKnown(DbId.i, *Known.BakaShrot_KnownNames, *Error.String)
Protected Name.s, Id.i
; Topics
If Not DatabaseQuery(DbId, "SELECT topic_id, name FROM topics UNION SELECT DISTINCT topic_id, '' FROM node_heads")
*Error\s = "can't read the topics: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Known\TopicUsed(Str(Id)) = #True
If Name <> "" And Not BakaShrot_IsDigits(Name)
*Known\TopicIds(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
; Nodes
If Not DatabaseQuery(DbId, "SELECT node_id, name FROM nodes UNION SELECT DISTINCT node_id, '' FROM node_heads")
*Error\s = "can't read the nodes: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Known\NodeUsed(Str(Id)) = #True
If Name <> "" And Not BakaShrot_IsDigits(Name)
*Known\NodeIds(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; --- Lookups -----------------------------------------------------------------
; The id Ref stands for: an id in digits is that id, a name must be known.
; -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
+214
View File
@@ -0,0 +1,214 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Retention.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Storage Retention
;
; Deletes the messages past their topic's max age, so a server's database
; stops growing: [BakaShrot.Retention] in its config, see
; BakaShrot_RetentionRule in Server/Config/Config.pbi.
;
; A thread, started with the workers (StartStorageRetention(), see
; Server/Root.pbi), runs a pass right away then every [BakaShrot.Server]
; RetentionInterval seconds:
; - every topic of the database (node_heads), with its name (topics);
; - its max age from the rules; kept forever (0) is skipped;
; - deletes its messages pushed (pushed_at) before now minus that age,
; #BakaShrot_Retention_BatchSize at a time through the writer
; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between
; the batches;
; - then the attachments' leftovers (CleanUpStorageBlobs(),
; Attachments.pbi): those of the deleted messages, and uploads not
; pushed with a message within [BakaShrot.Server] UploadTimeout,
; #BakaShrot_Retention_ChunkBatchSize parts at a time.
; It runs without any [BakaShrot.Retention] too, for the leftovers.
;
; Messages "may be" deleted past their max age: up to RetentionInterval
; later. Those a peer replicates here already past it aren't stored at all
; (InsertReplicatedMessages() in Writer.pbi), only counted as received. pushed_at is the time the message was pushed to its origin, kept as
; is by replication, so a server deletes a replicated message by when it
; was first pushed, not when it got it.
;
; What deleting doesn't change:
; - node_heads: a pair's head stays its highest id ever. The next push
; still gets the next id, and the sync state still tells peers this
; server had those messages: they aren't sent again.
; - The file's size: SQLite reuses the freed pages for new messages, so
; it stops growing once deletions keep up with pushes. VACUUM (the
; "vacuum" console command) gives the space back to the disk.
; ============================================================================
; Most messages deleted in one statement, under the write mutex: a few ms.
#BakaShrot_Retention_BatchSize = 5000
; Most attachment parts (1 MB each) deleted in one statement.
#BakaShrot_Retention_ChunkBatchSize = 32
Structure BakaShrot_RetentionTopic
TopicId.i
Name.s
EndStructure
Structure BakaShrot_RetentionState
ThreadId.i
StopRequested.i
IntervalMs.i
UploadTimeoutMs.q
DatabasePath.s
List Rules.BakaShrot_RetentionRule()
EndStructure
Global BakaShrot_Retention.BakaShrot_RetentionState
; Ms (since 1970 UTC) as "2026-11-08T14:03:59Z", for the logs.
Procedure.s BakaShrot_Retention_FormatUtc(Ms.q)
ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ssZ", Ms / 1000)
EndProcedure
; Deletes the attachments' leftovers, a few parts at a time.
Procedure BakaShrot_Retention_CleanUp()
Protected Deleted.i, Total.q, Error.String
Repeat
Deleted = CleanUpStorageBlobs(BakaShrot_NowUtcMs() - BakaShrot_Retention\UploadTimeoutMs, #BakaShrot_Retention_ChunkBatchSize, @Error)
If Deleted < 0
PrintN("[Storage] Retention: failed to delete the attachments' leftovers: " + Error\s)
Break
EndIf
Total + Deleted
Until Deleted < #BakaShrot_Retention_ChunkBatchSize Or BakaShrot_Retention\StopRequested
If Total > 0
PrintN("[Storage] Retention: deleted " + Str(Total) + " attachment parts (of deleted messages, or uploads never pushed)")
EndIf
EndProcedure
; Deletes what's past its max age in every topic. DbId is the thread's own
; connection, only read from (the deletes go through the writer).
; Returns how many messages were deleted.
Procedure.q BakaShrot_Retention_Pass(DbId.i)
Protected NewList Topics.BakaShrot_RetentionTopic()
Protected MaxAge.q, Before.q, Deleted.i, TopicDeleted.q, Total.q, Error.String
If Not DatabaseQuery(DbId, "SELECT DISTINCT h.topic_id, COALESCE(t.name, '') FROM node_heads h LEFT JOIN topics t ON t.topic_id = h.topic_id")
PrintN("[Storage] Retention: can't list the topics: " + DatabaseError())
ProcedureReturn 0
EndIf
While NextDatabaseRow(DbId)
AddElement(Topics())
Topics()\TopicId = GetDatabaseLong(DbId, 0)
Topics()\Name = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ForEach Topics()
MaxAge = RetentionMaxAgeMs(BakaShrot_Retention\Rules(), Topics()\TopicId, Topics()\Name)
If MaxAge <= 0
Continue
EndIf
Before = BakaShrot_NowUtcMs() - MaxAge
TopicDeleted = 0
Repeat
Deleted = DeleteStorageMessagesBefore(Topics()\TopicId, Before, #BakaShrot_Retention_BatchSize, @Error)
If Deleted < 0
PrintN("[Storage] Retention: failed to delete from topic " + Str(Topics()\TopicId) + ": " + Error\s)
Break
EndIf
TopicDeleted + Deleted
Until Deleted < #BakaShrot_Retention_BatchSize Or BakaShrot_Retention\StopRequested
If TopicDeleted > 0
If Topics()\Name <> ""
PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic '" + Topics()\Name + "' pushed before " + BakaShrot_Retention_FormatUtc(Before))
Else
PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic " + Str(Topics()\TopicId) + " pushed before " + BakaShrot_Retention_FormatUtc(Before))
EndIf
EndIf
Total + TopicDeleted
If BakaShrot_Retention\StopRequested
Break
EndIf
Next
BakaShrot_Retention_CleanUp()
ProcedureReturn Total
EndProcedure
Procedure BakaShrot_Retention_Thread(Unused.i)
Protected DbId.i, LastPass.i
DbId = OpenStorageDatabase(BakaShrot_Retention\DatabasePath)
If Not DbId
PrintN("[Storage] Retention: can't open the database, nothing will be deleted: " + DatabaseError())
ProcedureReturn
EndIf
BakaShrot_Retention_Pass(DbId)
LastPass = ElapsedMilliseconds()
While Not BakaShrot_Retention\StopRequested
Delay(100)
If ElapsedMilliseconds() - LastPass >= BakaShrot_Retention\IntervalMs
BakaShrot_Retention_Pass(DbId)
LastPass = ElapsedMilliseconds()
EndIf
Wend
CloseDatabase(DbId)
EndProcedure
; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, and
; the attachments' leftovers, once the writer is open.
; Returns #False if the thread can't start.
Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig)
With BakaShrot_Retention
ClearList(\Rules())
CopyList(*Config\Retention(), \Rules())
ForEach \Rules()
If \Rules()\MaxAgeMs > 0
PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s")
EndIf
Next
\DatabasePath = *Config\Server\DatabasePath
\IntervalMs = *Config\Server\RetentionInterval * 1000
\UploadTimeoutMs = *Config\Server\UploadTimeout * 1000
\StopRequested = #False
\ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0)
ProcedureReturn Bool(\ThreadId)
EndWith
EndProcedure
; Stops it, before the writer closes. Waits for a pass under way to end its
; current batch.
Procedure StopStorageRetention()
With BakaShrot_Retention
If \ThreadId
\StopRequested = #True
WaitThread(\ThreadId)
\ThreadId = 0
EndIf
EndWith
EndProcedure
+971
View File
@@ -0,0 +1,971 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Storage.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; 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_v8.dbml in this same folder. Attachments: see
; Attachments.pbi and Design/Attachments.md.
;
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official
; sqlite3.dll is used instead, it must be next to the program. Build.ps1
; extracts it from Libs/sqlite-dll-win-*.zip and copies it.
; On Linux, the system's libsqlite3.so.0 (libsqlite3-0 on Debian/Ubuntu,
; sqlite-libs on Fedora) is used, whatever the compiler, it must be 3.38+.
; Either way it's #BakaShrot_Storage_SqliteLibrary, which RunReadOnlyQuery()
; and the writer (Writer.pbi) also call directly. Elsewhere, PureBasic's own
; SQLite is linked in, and they make do without it.
;
; Threads: ONE CONNECTION PER THREAD, never share a handle.
; The SetDatabase*() parameters and query results belong to a handle, so two
; 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"
CompilerSelect #PB_Compiler_OS
CompilerCase #PB_OS_Windows
#BakaShrot_Storage_ExternalSqlite = #True
#BakaShrot_Storage_SqliteLibrary = "sqlite3.dll"
CompilerCase #PB_OS_Linux
#BakaShrot_Storage_ExternalSqlite = #True
#BakaShrot_Storage_SqliteLibrary = "libsqlite3.so.0"
CompilerDefault
#BakaShrot_Storage_ExternalSqlite = #False
#BakaShrot_Storage_SqliteLibrary = ""
CompilerEndSelect
CompilerIf #BakaShrot_Storage_ExternalSqlite
UseSQLiteDatabase(#BakaShrot_Storage_SqliteLibrary)
CompilerElse
UseSQLiteDatabase()
CompilerEndIf
; One row of the "data" table (see db_schema_v8.dbml).
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
; AttachmentSize: its attachment's size, 0 for none (the "attachments"
; table), AttachmentReady #True once all of it is here, AttachmentSha256 its
; SHA-256.
Structure BakaShrot_Message
MessageId.q
PushedAt.q
JsonData.s
AttachmentSize.q
AttachmentReady.i
AttachmentSha256.a[#BakaShrot_Sha256Size]
EndStructure
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
ImportC ""
BakaShrot_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday"
EndImport
CompilerEndIf
; Now, in milliseconds since 1970-01-01 00:00:00 UTC: what a pushed message
; is stamped with (pushed_at).
Procedure.q BakaShrot_NowUtcMs()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; 100 ns intervals since 1601-01-01 UTC.
Protected FileTime.q
GetSystemTimeAsFileTime_(@FileTime)
ProcedureReturn (FileTime - 116444736000000000) / 10000
CompilerElse
; struct timeval, 64-bit (checked on Linux x64 by Tests/Retention-Test.ps1).
Protected Dim TimeVal.q(1)
BakaShrot_GetTimeOfDay(@TimeVal(0), 0)
ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000
CompilerEndIf
EndProcedure
; How long a connection waits for another one's lock before a statement
; fails with "database is locked", in ms.
#BakaShrot_Storage_BusyTimeout = 5000
; 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.
; PRAGMA synchronous of every connection: [BakaShrot.Server] Synchronous,
; set by the root before it opens any (Server/Root.pbi). FULL by default.
; FULL syncs the WAL on every commit: an acknowledged push is on disk. It
; costs one flush per transaction, shared by a group commit's pushes.
; NORMAL only syncs at checkpoints (about every second, Writer.pbi): the
; database can't get corrupted, but the last commits before a power loss or
; an OS crash (not a crash of the server itself) can be lost. Those messages
; were acknowledged, and maybe replicated already, so their ids could then
; be handed out again for other messages: drift, see
; Design/ReplicationIssues.md #1. Measured: Design/StorageConcurrency.md.
#BakaShrot_Storage_DefaultSynchronous = "FULL"
Global BakaShrot_Storage_Synchronous.s = #BakaShrot_Storage_DefaultSynchronous
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
; 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
; v5 -> v6: "data" got pushed_at. Adds it to a database made before, every
; message stamped with the time of the upgrade (their real one is unknown),
; in one transaction. Nothing to do on a new or already upgraded database.
Procedure.i MigrateStoragePushedAt(DbId.i)
Protected Has.i
Has = StorageHasColumn(DbId, "data", "pushed_at")
If Has = -1
ProcedureReturn #False
ElseIf Has
ProcedureReturn #True
EndIf
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "ALTER TABLE data ADD COLUMN pushed_at INTEGER NOT NULL DEFAULT 0")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
; Bound for the next statement run, so right before it.
SetDatabaseQuad(DbId, 0, BakaShrot_NowUtcMs())
If Not DatabaseUpdate(DbId, "UPDATE data SET pushed_at = ?")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Creates the tables and indexes described by db_schema_v8.dbml, if they
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
; upgrade mechanism (DbUpdater) will replace this later.
; Fails on a database made with an older schema, since it would be left as is.
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
; A leftover of the first schemas, never used: the retention deletes
; instead (Retention.pbi).
If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS archives")
ProcedureReturn #False
EndIf
; is_json is set by SQLite on insert, and can't be written.
; pushed_at: when it was pushed to its origin, ms since 1970 UTC, kept as
; is when replicated. Last, like the ALTER TABLE below adds it.
; The UNIQUE constraint's index also serves (topic_id, node_id) lookups.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" +
"topic_id INTEGER NOT NULL, " +
"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, " +
"pushed_at INTEGER NOT NULL DEFAULT 0, " +
"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
; A database from before pushed_at: its messages get the time of this
; upgrade, so a topic's max age (Server/Storage/Retention.pbi) counts
; from now for them instead of deleting them all at once.
If Not MigrateStoragePushedAt(DbId)
ProcedureReturn #False
EndIf
; What the retention deletes by: a topic's messages pushed before a time.
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_topic_pushed_at ON data (topic_id, pushed_at)")
ProcedureReturn #False
EndIf
; The first schemas' placeholder, never used (and misspelled), replaced
; by the three tables below. Its indexes go with it.
If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS attachements")
ProcedureReturn #False
EndIf
; Attachments, see Attachments.pbi and Design/Attachments.md.
; blobs: an attachment's data, being uploaded or replicated, or stored.
; topic_id, node_id: an upload's, who may attach it (or the message's).
; received: bytes stored so far, in blob_chunks.
; state: 0 receiving, 1 complete (an upload waiting for its message),
; 2 attached to its message, 3 to delete (Retention.pbi deletes it).
; created_at: ms since 1970 UTC, uploads left incomplete expire.
; blob_chunks: its parts, #BakaShrot_AttachmentChunkSize bytes each.
; attachments: a message's (one at most), with its size and SHA-256
; from the start, its data in blob_id once any is here.
; state: 0 missing (a replicated message, none of it here yet),
; 1 receiving, 2 ready, 3 not kept (bigger than this server takes).
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blobs (" +
"blob_id INTEGER PRIMARY KEY, " +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"size INTEGER NOT NULL, " +
"sha256 BLOB NOT NULL, " +
"received INTEGER NOT NULL DEFAULT 0, " +
"state INTEGER NOT NULL, " +
"created_at INTEGER NOT NULL)") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS blob_chunks (" +
"blob_id INTEGER NOT NULL, " +
"chunk_index INTEGER NOT NULL, " +
"chunk_data BLOB NOT NULL, " +
"PRIMARY KEY (blob_id, chunk_index))") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachments (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"message_id INTEGER NOT NULL, " +
"size INTEGER NOT NULL, " +
"sha256 BLOB NOT NULL, " +
"blob_id INTEGER, " +
"state INTEGER NOT NULL, " +
"PRIMARY KEY (topic_id, node_id, message_id)) WITHOUT ROWID") Or
Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_blobs_state ON blobs (state)") Or
Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachments_state ON attachments (state)")
ProcedureReturn #False
EndIf
; A message deleted (the retention) takes its attachment with it, and an
; attachment its data: marked, Retention.pbi deletes it a bit at a time.
If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_attachments AFTER DELETE ON data BEGIN " +
"DELETE FROM attachments WHERE topic_id = OLD.topic_id AND node_id = OLD.node_id AND message_id = OLD.message_id; " +
"END") Or
Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_attachments_blobs AFTER DELETE ON attachments WHEN OLD.blob_id IS NOT NULL BEGIN " +
"UPDATE blobs SET state = 3 WHERE blob_id = OLD.blob_id; " +
"END")
ProcedureReturn #False
EndIf
; 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.
; Deleting from "data" (the retention) leaves it alone, on purpose: a
; pair's head stays its highest id ever, so the next push still gets the
; id after it, and peers aren't sent again what was deleted here.
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'")
ProcedureReturn #False
EndIf
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. pushed_utc is
; pushed_at as text, "2026-11-08T14:03:59.123Z".
; Made again on every start, so an older one gets the newer columns.
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS messages") Or
Not DatabaseUpdate(DbId, "CREATE VIEW messages AS " +
"SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id, " +
"d.pushed_at, strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc " +
"FROM data d JOIN topics t ON t.topic_id = d.topic_id JOIN nodes n ON n.node_id = d.node_id")
ProcedureReturn #False
EndIf
; For browsing with a database tool: set browse's one row to a topic
; (and optionally a node), open browse_messages. The foreign keys are
; only there for the tools: SQLiteStudio shows a dropdown of the names
; for a column that references them. The server never turns foreign keys
; on, so they never get in its way (a topic renamed in the config only
; leaves a stale name here). The server never writes to browse either.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS browse (" +
"id INTEGER PRIMARY KEY CHECK (id = 1), " +
"topic TEXT COLLATE NOCASE REFERENCES topics (name), " +
"node TEXT COLLATE NOCASE REFERENCES nodes (name))") Or
Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO browse (id) VALUES (1)")
ProcedureReturn #False
EndIf
; Newest first, by the (topic_id, pushed_at) index. Made again on every
; start, like messages.
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS browse_messages") Or
Not DatabaseUpdate(DbId, "CREATE VIEW browse_messages AS " +
"SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, " +
"a.size AS attachment_size, m.topic " +
"FROM browse b JOIN messages m ON m.topic = b.topic " +
"LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id AND a.message_id = m.message_id " +
"WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) " +
"ORDER BY m.pushed_at DESC, m.node, m.message_id DESC")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Inserts one JSON message into the "data" table, pushed now.
Procedure.i Insert(DbId.i, TopicId.i, NodeId.i, MessageId.i, JsonData.s)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseLong(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs())
ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) 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
; Reads the attachment's size, state and SHA-256 (COALESCE(a.size, 0),
; COALESCE(a.state, 0), a.sha256) from Column on into *Message.
Procedure BakaShrot_ReadAttachmentColumns(DbId.i, Column.i, *Message.BakaShrot_Message)
*Message\AttachmentSize = GetDatabaseQuad(DbId, Column)
*Message\AttachmentReady = Bool(*Message\AttachmentSize > 0 And GetDatabaseLong(DbId, Column + 1) = 2)
FillMemory(@*Message\AttachmentSha256[0], #BakaShrot_Sha256Size, 0)
If *Message\AttachmentSize > 0 And DatabaseColumnSize(DbId, Column + 2) = #BakaShrot_Sha256Size
GetDatabaseBlob(DbId, Column + 2, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size)
EndIf
EndProcedure
; Fills *Message with the message that has the highest message_id for a
; topic_id/node_id pair.
; Returns #False if there's none, or if the query failed.
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 d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " +
"FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " +
"WHERE d.topic_id = ? AND d.node_id = ? ORDER BY d.message_id DESC LIMIT 1")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Message\MessageId = GetDatabaseQuad(DbId, 0)
*Message\JsonData = GetDatabaseString(DbId, 1)
*Message\PushedAt = GetDatabaseQuad(DbId, 2)
BakaShrot_ReadAttachmentColumns(DbId, 3, *Message)
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 #BakaShrot_Storage_SqliteLibrary as
; PureBasic's (DatabaseID() is its sqlite3 handle), like Writer.pbi.
; Without #BakaShrot_Storage_ExternalSqlite, PureBasic's own SQLite is linked
; in and not reachable this way: DatabaseError() is checked instead, which
; misses it.
#BakaShrot_Query_SqliteOk = 0
#BakaShrot_Query_SqliteRow = 100
#BakaShrot_Query_SqliteDone = 101
CompilerIf #BakaShrot_Storage_ExternalSqlite
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 the SQLite library or its functions can't be found.
Procedure.i BakaShrot_Query_LoadSqlite()
Protected Loaded.i
LockMutex(BakaShrot_Query_SqliteMutex)
With BakaShrot_Query_Sqlite
If Not \Library
\Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary)
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 #BakaShrot_Storage_ExternalSqlite
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 #BakaShrot_Storage_ExternalSqlite
ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId))
If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone
*Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode)
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)
; Without #BakaShrot_Storage_ExternalSqlite, the only check there is. It
; misses errors in the rows: PureBasic doesn't report them.
; !!! DatabaseError() may be shared by every thread, see
; !!! Design/StorageConcurrency.md, another thread's error could show up here.
CompilerIf Not #BakaShrot_Storage_ExternalSqlite
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 d.message_id, d.message_data, d.pushed_at, COALESCE(a.size, 0), COALESCE(a.state, 0), a.sha256 " +
"FROM data d LEFT JOIN attachments a ON a.topic_id = d.topic_id AND a.node_id = d.node_id AND a.message_id = d.message_id " +
"WHERE d.topic_id = ? AND d.node_id = ? AND d.message_id > ? ORDER BY d.message_id LIMIT ?")
ProcedureReturn #False
EndIf
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)
Messages()\PushedAt = GetDatabaseQuad(DbId, 2)
BakaShrot_ReadAttachmentColumns(DbId, 3, @Messages())
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.
; PushedAt: when it was pushed to its origin, ms since 1970 UTC.
; Returns #False if the insert failed.
Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
SetDatabaseQuad(DbId, 4, PushedAt)
ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)")
EndProcedure
; Every write: pushes (group commit), replicated batches, the WAL checkpoints.
XIncludeFile "Writer.pbi"
; Attachments: uploads, parts, reading them back, the replicated ones.
XIncludeFile "Attachments.pbi"
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
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
File diff suppressed because it is too large Load Diff
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -0,0 +1,89 @@
// Changes from v5:
// - data.pushed_at: when the message was pushed to its origin, ms since
// 1970-01-01 UTC, kept as is when replicated. A v5 database gets it with
// the time of the upgrade (MigrateStoragePushedAt() in Storage.pbi).
// - Index (topic_id, pushed_at): what the retention deletes by
// (Retention.pbi, [BakaShrot.Retention] in the config).
// - messages: the view also has pushed_at, and pushed_utc as text.
// - node_heads outlives deleted messages: a pair's highest id ever. Also
// raised for replicated messages skipped as already past their max age.
// - archives is gone: never used, dropped from older databases.
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
// When it was pushed to its origin, ms since 1970-01-01 UTC.
pushed_at integer [not null, default: 0]
indexes {
(topic_id, node_id, message_id) [unique]
message_id
(topic_id, pushed_at)
}
}
// One row per topic/node id that has ever had messages: deleting messages
// (the retention) leaves it as is, so ids never go back.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// Create it, but we'll implement this later.
table attachements {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(topic_id, node_id)
message_id
}
}
// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is
// the id in digits).
table topics {
topic_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer"
// (only in databases from the short-lived version that added peer nodes).
table nodes {
node_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// View messages:
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
// JOIN nodes n ON n.node_id = d.node_id
// WHERE topic = ... AND node = ... goes through the name indexes, then
// data's (topic_id, node_id, message_id) one.
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+126
View File
@@ -0,0 +1,126 @@
// Changes from v6 (Design/Attachments.md):
// - attachments, blobs, blob_chunks: a message's attachment (one at most),
// its data, in 1 MB parts. Replace the placeholder "attachements" table,
// dropped.
// - Triggers: deleting a message deletes its attachment row, which marks
// its blob to delete (Retention.pbi deletes the parts).
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
// When it was pushed to its origin, ms since 1970-01-01 UTC.
pushed_at integer [not null, default: 0]
indexes {
(topic_id, node_id, message_id) [unique]
message_id
(topic_id, pushed_at)
}
}
// One row per topic/node id that has ever had messages: deleting messages
// (the retention) leaves it as is, so ids never go back.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// A message's attachment (Design/Attachments.md). Its size and SHA-256 come
// with it (pushed, or replicated), its data in blob_id once any is here.
// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready,
// 3 not kept (bigger than this server's MaxAttachmentSize).
// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its
// blob to delete (state 3).
table attachments [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
size integer [not null]
sha256 blob [not null]
blob_id integer
state integer [not null]
indexes {
(topic_id, node_id, message_id) [pk]
state
}
}
// The data of one attachment, being received (an upload, or replicated) or
// stored. topic_id, node_id: an upload's owner, or the message's pair.
// received: bytes stored so far. created_at: ms since 1970 UTC, an upload
// not pushed with its message within UploadTimeout is deleted.
// state: 0 receiving, 1 complete (an upload waiting for its message),
// 2 attached, 3 to delete.
table blobs {
blob_id integer [pk]
topic_id integer [not null]
node_id integer [not null]
size integer [not null]
sha256 blob [not null]
received integer [not null, default: 0]
state integer [not null]
created_at integer [not null]
indexes {
state
}
}
// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one
// what's left.
table blob_chunks {
blob_id integer [not null]
chunk_index integer [not null]
chunk_data blob [not null]
indexes {
(blob_id, chunk_index) [pk]
}
}
// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is
// the id in digits).
table topics {
topic_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer"
// (only in databases from the short-lived version that added peer nodes).
table nodes {
node_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// View messages:
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
// JOIN nodes n ON n.node_id = d.node_id
// WHERE topic = ... AND node = ... goes through the name indexes, then
// data's (topic_id, node_id, message_id) one.
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+148
View File
@@ -0,0 +1,148 @@
// Changes from v7:
// - browse: one row (id 1), the topic and optionally the node to browse,
// referencing topics and nodes by name so database tools (SQLiteStudio)
// show a dropdown of them. Never written by the server, its foreign keys
// never turned on by it.
// - browse_messages: the view of what browse selects, newest first.
// - The origins of topics and nodes: "config" also covers the nodes the
// config's sections define, "peer" the names peers sent (AcceptTopics /
// AcceptNodes wildcards).
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
// When it was pushed to its origin, ms since 1970-01-01 UTC.
pushed_at integer [not null, default: 0]
indexes {
(topic_id, node_id, message_id) [unique]
message_id
(topic_id, pushed_at)
}
}
// One row per topic/node id that has ever had messages: deleting messages
// (the retention) leaves it as is, so ids never go back.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// A message's attachment (Design/Attachments.md). Its size and SHA-256 come
// with it (pushed, or replicated), its data in blob_id once any is here.
// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready,
// 3 not kept (bigger than this server's MaxAttachmentSize).
// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its
// blob to delete (state 3).
table attachments [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
size integer [not null]
sha256 blob [not null]
blob_id integer
state integer [not null]
indexes {
(topic_id, node_id, message_id) [pk]
state
}
}
// The data of one attachment, being received (an upload, or replicated) or
// stored. topic_id, node_id: an upload's owner, or the message's pair.
// received: bytes stored so far. created_at: ms since 1970 UTC, an upload
// not pushed with its message within UploadTimeout is deleted.
// state: 0 receiving, 1 complete (an upload waiting for its message),
// 2 attached, 3 to delete.
table blobs {
blob_id integer [pk]
topic_id integer [not null]
node_id integer [not null]
size integer [not null]
sha256 blob [not null]
received integer [not null, default: 0]
state integer [not null]
created_at integer [not null]
indexes {
state
}
}
// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one
// what's left.
table blob_chunks {
blob_id integer [not null]
chunk_index integer [not null]
chunk_data blob [not null]
indexes {
(blob_id, chunk_index) [pk]
}
}
// origin: "config" (named in [BakaShrot.Topics]), "peer" (taken from a
// peer by a wildcard), "id" (unnamed, name is the id in digits).
table topics {
topic_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// origin: "config" (named in [BakaShrot.Nodes], or a node the config's
// [BakaShrot], peer or client sections define), "peer" (taken from a peer:
// AcceptNodes is * by default), "id" (unnamed).
table nodes {
node_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// View messages:
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
// JOIN nodes n ON n.node_id = d.node_id
// WHERE topic = ... AND node = ... goes through the name indexes, then
// data's (topic_id, node_id, message_id) one.
// What to browse with a database tool: set topic (and node, NULL for every
// one) in its one row, open browse_messages. The references are for the
// tools' dropdowns only: the server doesn't turn foreign keys on.
table browse {
id integer [pk, note: 'CHECK (id = 1)']
topic text [ref: > topics.name, note: 'COLLATE NOCASE']
node text [ref: > nodes.name, note: 'COLLATE NOCASE']
}
// View browse_messages:
// SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json,
// a.size AS attachment_size, m.topic
// FROM browse b JOIN messages m ON m.topic = b.topic
// LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id
// AND a.message_id = m.message_id
// WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node)
// ORDER BY m.pushed_at DESC, m.node, m.message_id DESC
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL