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

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
+484
View File
@@ -0,0 +1,484 @@
; ============================================================================
; BakaShrot Storage Names
;
; Which name every topic and node id has on this server. Names are what's
; shared between servers (Commons/Networking/Names.pbi): replication sends
; them, and each server stores the messages under its own ids for them. Say
; topic "logs" is 1 here and 200 on a peer: the peer sends "logs", this
; server stores it under 1. Hand-written configs drift, the names keep them
; matching anyway.
;
; Only what's named on BOTH servers replicates: a topic or node without a
; name, or with a name the other server doesn't know, is dropped. Unless the
; receiver takes it by a wildcard: "*" or a pattern ("sensors.*") in that
; peer's AcceptTopics / AcceptNodes takes matching names it doesn't have,
; and adds them (BakaShrot_Names_Ingest(), origin "peer") under the highest
; free id counting down from 65535, out of the way of the ids picked in the
; config. To not be refused over and over, each check-in's sync state lists
; every name the receiver knows and takes, and its patterns, and the sender
; only sends those. Every drop goes through BakaShrot_Names_NoteDropped().
;
; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can
; join on them (the "messages" view), and in memory for the server, guarded
; by BakaShrot_Names_Mutex. Every id in "data" has a row:
; origin "config" named in [BakaShrot.Topics] / [BakaShrot.Nodes]
; origin "id" unnamed, its name is its id in digits
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
;
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
; on restart). The config wins, except when it would give a name to another
; id than the one the database has it under (or rename a "peer" one): that
; would relabel stored messages, so the server refuses to start and says
; which id to use.
;
; Lock order: BakaShrot_Names_Mutex, then the write mutex (Writer.pbi).
; ============================================================================
XIncludeFile "../Config/Config.pbi"
XIncludeFile "Storage.pbi"
XIncludeFile "../../Commons/Networking/Packets/NamesListPacket.pbi"
#BakaShrot_Names_OriginConfig = "config"
#BakaShrot_Names_OriginPeer = "peer"
#BakaShrot_Names_OriginId = "id"
; One of the two tables, in memory.
Structure BakaShrot_NameTable
Table.s
IdColumn.s
Kind.s
; LCase(name) -> id, named ones only.
Map IdByName.i()
; Str(id) -> name, "" if unnamed. Every id with a row.
Map NameById.s()
; Str(id) -> origin.
Map OriginById.s()
EndStructure
Global BakaShrot_Names_Mutex.i = CreateMutex()
Global BakaShrot_Names_Topics.BakaShrot_NameTable
Global BakaShrot_Names_Nodes.BakaShrot_NameTable
BakaShrot_Names_Topics\Table = "topics"
BakaShrot_Names_Topics\IdColumn = "topic_id"
BakaShrot_Names_Topics\Kind = "topic"
BakaShrot_Names_Nodes\Table = "nodes"
BakaShrot_Names_Nodes\IdColumn = "node_id"
BakaShrot_Names_Nodes\Kind = "node"
; --- Loading -----------------------------------------------------------------
; Reconciles one table with the config's names (ConfigNames: Str(id) ->
; name) and the ids it uses (UsedIds), plus every id already in "data"
; (node_heads), then fills *Names from it.
; Runs inside the transaction of BakaShrot_Names_Load().
Procedure.i BakaShrot_Names_LoadTable(DbId.i, *Names.BakaShrot_NameTable, Map ConfigNames.s(), Map UsedIds.i(), *Error.String)
Protected NewMap DbName.s(), NewMap DbOrigin.s(), NewMap DbIdByName.i(), NewMap AllIds.i()
Protected Id.i, Name.s, Key.s, Section.s
If *Names = @BakaShrot_Names_Topics
Section = "[BakaShrot.Topics]"
Else
Section = "[BakaShrot.Nodes]"
EndIf
; What the database has.
If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table)
*Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Key = Str(GetDatabaseLong(DbId, 0))
DbName(Key) = GetDatabaseString(DbId, 1)
DbOrigin(Key) = GetDatabaseString(DbId, 2)
If Not BakaShrot_IsDigits(DbName(Key))
DbIdByName(LCase(DbName(Key))) = Val(Key)
EndIf
Wend
FinishDatabaseQuery(DbId)
; The config's names.
ForEach ConfigNames()
Key = MapKey(ConfigNames())
Name = ConfigNames()
Id = Val(Key)
If FindMapElement(DbIdByName(), LCase(Name)) And DbIdByName() <> Id
*Error\s = *Names\Kind + " '" + Name + "' is id " + Str(Id) + " in " + Section + ", but its messages are stored under id " +
Str(DbIdByName()) + ": give it id " + Str(DbIdByName()) + " in the config"
ProcedureReturn #False
EndIf
If FindMapElement(DbName(), Key)
If DbName(Key) = Name And DbOrigin(Key) = #BakaShrot_Names_OriginConfig
Continue
EndIf
If DbOrigin(Key) = #BakaShrot_Names_OriginPeer And LCase(DbName(Key)) <> LCase(Name)
*Error\s = *Names\Kind + " id " + Str(Id) + " is '" + DbName(Key) + "', added by a peer, " + Section + " can't rename it to '" + Name +
"': give '" + Name + "' another id, or name id " + Str(Id) + " '" + DbName(Key) + "'"
ProcedureReturn #False
EndIf
If LCase(DbName(Key)) <> LCase(Name) And DbOrigin(Key) = #BakaShrot_Names_OriginConfig
PrintN("[Names] Renaming " + *Names\Kind + " " + Key + " from '" + DbName(Key) + "' to '" + Name + "'")
EndIf
EndIf
SetDatabaseLong(DbId, 0, Id)
SetDatabaseString(DbId, 1, Name)
SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginConfig)
If Not DatabaseUpdate(DbId, "INSERT INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?) " +
"ON CONFLICT (" + *Names\IdColumn + ") DO UPDATE SET name = excluded.name, origin = excluded.origin")
*Error\s = "can't store " + *Names\Kind + " '" + Name + "': " + DatabaseError()
ProcedureReturn #False
EndIf
Next
; Every id the config uses, and every one already in "data", gets a row.
ForEach UsedIds()
AllIds(MapKey(UsedIds())) = #True
Next
If Not DatabaseQuery(DbId, "SELECT DISTINCT " + *Names\IdColumn + " FROM node_heads")
*Error\s = "can't read node_heads: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AllIds(Str(GetDatabaseLong(DbId, 0))) = #True
Wend
FinishDatabaseQuery(DbId)
ForEach AllIds()
Key = MapKey(AllIds())
If FindMapElement(ConfigNames(), Key) Or FindMapElement(DbName(), Key)
Continue
EndIf
SetDatabaseLong(DbId, 0, Val(Key))
SetDatabaseString(DbId, 1, Key)
SetDatabaseString(DbId, 2, #BakaShrot_Names_OriginId)
If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + *Names\Table + " (" + *Names\IdColumn + ", name, origin) VALUES (?, ?, ?)")
*Error\s = "can't store " + *Names\Kind + " id " + Key + ": " + DatabaseError()
ProcedureReturn #False
EndIf
Next
; In memory, from what the table now holds.
ClearMap(*Names\IdByName())
ClearMap(*Names\NameById())
ClearMap(*Names\OriginById())
If Not DatabaseQuery(DbId, "SELECT " + *Names\IdColumn + ", name, origin FROM " + *Names\Table)
*Error\s = "can't read the " + *Names\Table + " table: " + DatabaseError()
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
Name = GetDatabaseString(DbId, 1)
*Names\OriginById(Str(Id)) = GetDatabaseString(DbId, 2)
If BakaShrot_IsDigits(Name)
*Names\NameById(Str(Id)) = ""
Else
*Names\NameById(Str(Id)) = Name
*Names\IdByName(LCase(Name)) = Id
EndIf
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Reconciles the config's names with the database, see the top of this
; file. Only from the root, with the workers stopped, on its own connection.
; Returns #False with the reason in *Error\s, nothing is changed then.
Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.String)
Protected Loaded.i
LockMutex(BakaShrot_Names_Mutex)
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
*Error\s = DatabaseError()
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn #False
EndIf
Loaded = Bool(BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Topics, *Config\TopicNames(), *Config\UsedTopicIds(), *Error) And
BakaShrot_Names_LoadTable(DbId, @BakaShrot_Names_Nodes, *Config\NodeNames(), *Config\UsedNodeIds(), *Error))
If Loaded And Not DatabaseUpdate(DbId, "COMMIT")
*Error\s = DatabaseError()
Loaded = #False
EndIf
If Not Loaded
DatabaseUpdate(DbId, "ROLLBACK")
EndIf
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Loaded
EndProcedure
; --- Lookups -----------------------------------------------------------------
; The id Ref stands for: an id in digits is that id, a name must be known.
; -1 if it's neither. Holding the names mutex.
Procedure.i BakaShrot_Names_ResolveIn(*Names.BakaShrot_NameTable, Ref.s)
Protected Id.i = BakaShrot_RefToId(Ref)
If Id >= 0
ProcedureReturn Id
EndIf
If BakaShrot_IsValidName(Ref) And FindMapElement(*Names\IdByName(), LCase(Ref))
ProcedureReturn *Names\IdByName()
EndIf
ProcedureReturn -1
EndProcedure
; Its name, "" if it has none. Holding the names mutex.
Procedure.s BakaShrot_Names_NameIn(*Names.BakaShrot_NameTable, Id.i)
If FindMapElement(*Names\NameById(), Str(Id))
ProcedureReturn *Names\NameById()
EndIf
ProcedureReturn ""
EndProcedure
; The topic id Ref stands for here, -1 if none.
Procedure.i BakaShrot_Names_ResolveTopic(Ref.s)
Protected Id.i
LockMutex(BakaShrot_Names_Mutex)
Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Topics, Ref)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndProcedure
; The node id Ref stands for here, -1 if none.
Procedure.i BakaShrot_Names_ResolveNode(Ref.s)
Protected Id.i
LockMutex(BakaShrot_Names_Mutex)
Id = BakaShrot_Names_ResolveIn(@BakaShrot_Names_Nodes, Ref)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndProcedure
; The topic id of a known name (never an id in digits), -1 if none: what
; replication goes by.
Procedure.i BakaShrot_Names_TopicByName(Name.s)
If Not BakaShrot_IsValidName(Name)
ProcedureReturn -1
EndIf
ProcedureReturn BakaShrot_Names_ResolveTopic(Name)
EndProcedure
; Same for a node.
Procedure.i BakaShrot_Names_NodeByName(Name.s)
If Not BakaShrot_IsValidName(Name)
ProcedureReturn -1
EndIf
ProcedureReturn BakaShrot_Names_ResolveNode(Name)
EndProcedure
; A topic's name, "" if it has none.
Procedure.s BakaShrot_Names_TopicName(Id.i)
Protected Name.s
LockMutex(BakaShrot_Names_Mutex)
Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Topics, Id)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Name
EndProcedure
; A node's name, "" if it has none.
Procedure.s BakaShrot_Names_NodeName(Id.i)
Protected Name.s
LockMutex(BakaShrot_Names_Mutex)
Name = BakaShrot_Names_NameIn(@BakaShrot_Names_Nodes, Id)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Name
EndProcedure
; What a topic goes by in answers and logs: its name, or its id in digits.
Procedure.s BakaShrot_Names_TopicRef(Id.i)
Protected Name.s = BakaShrot_Names_TopicName(Id)
If Name = ""
ProcedureReturn Str(Id)
EndIf
ProcedureReturn Name
EndProcedure
; Same for a node.
Procedure.s BakaShrot_Names_NodeRef(Id.i)
Protected Name.s = BakaShrot_Names_NodeName(Id)
If Name = ""
ProcedureReturn Str(Id)
EndIf
ProcedureReturn Name
EndProcedure
; Fills Names() with every named topic (Kind #BakaShrot_NameKind_Topic) or
; node, by id, for the sync state. *Filter: only the ones it holds, 0 for
; all of them.
Procedure BakaShrot_Names_GetNamed(Kind.i, List Names.BakaShrot_SyncName(), *Filter.BakaShrot_NameSet = 0)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
ClearList(Names())
LockMutex(BakaShrot_Names_Mutex)
ForEach *Names\IdByName()
Id = *Names\IdByName()
If *Filter And Not NameSetHas(*Filter, Id, BakaShrot_Names_NameIn(*Names, Id))
Continue
EndIf
AddElement(Names())
Names()\Id = Id
Names()\Name = BakaShrot_Names_NameIn(*Names, Id)
Next
UnlockMutex(BakaShrot_Names_Mutex)
SortStructuredList(Names(), #PB_Sort_Ascending, OffsetOf(BakaShrot_SyncName\Id), #PB_Long)
EndProcedure
; Fills Entries() with every topic or node (Kind), named or not, by id, with
; where its name comes from. *Filter: only the topics it holds, 0 for all.
Procedure BakaShrot_Names_GetAll(Kind.i, List Entries.BakaShrot_NameEntry(), *Filter.BakaShrot_NameSet = 0)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
ClearList(Entries())
LockMutex(BakaShrot_Names_Mutex)
ForEach *Names\NameById()
Id = Val(MapKey(*Names\NameById()))
If *Filter And Not NameSetHas(*Filter, Id, *Names\NameById())
Continue
EndIf
AddElement(Entries())
Entries()\Id = Id
Entries()\Name = *Names\NameById()
Entries()\Origin = *Names\OriginById(Str(Id))
Next
UnlockMutex(BakaShrot_Names_Mutex)
SortStructuredList(Entries(), #PB_Sort_Ascending, OffsetOf(BakaShrot_NameEntry\Id), #PB_Long)
EndProcedure
; Prints every topic and node with its id, for the server's "names" command.
Procedure BakaShrot_Names_Print()
Protected NewList Entries.BakaShrot_NameEntry()
Protected Kind.i, Label.s, Name.s
For Kind = #BakaShrot_NameKind_Topic To #BakaShrot_NameKind_Node
BakaShrot_Names_GetAll(Kind, Entries())
If Kind = #BakaShrot_NameKind_Topic
Label = "Topics"
Else
Label = "Nodes"
EndIf
PrintN(Label + " (" + Str(ListSize(Entries())) + "):")
ForEach Entries()
Name = Entries()\Name
If Name = ""
Name = "(unnamed, not replicated)"
EndIf
PrintN(" " + RSet(Str(Entries()\Id), 5) + " " + LSet(Name, 30) + " " + Entries()\Origin)
Next
Next
EndProcedure
; --- Adding ------------------------------------------------------------------
; Makes sure Id has a row, as unnamed if it's new: for messages stored under
; an id the database didn't know yet (a push to a topic allowed by "*").
; Holding the names mutex. Returns #False with the reason in *Error\s.
Procedure.i BakaShrot_Names_EnsureIdIn(*Names.BakaShrot_NameTable, Id.i, *Error.String)
If FindMapElement(*Names\NameById(), Str(Id))
ProcedureReturn #True
EndIf
If Not RegisterStorageName(*Names\Table, Id, Str(Id), #BakaShrot_Names_OriginId, *Error)
ProcedureReturn #False
EndIf
*Names\NameById(Str(Id)) = ""
*Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginId
ProcedureReturn #True
EndProcedure
Procedure.i BakaShrot_Names_EnsureTopicId(Id.i, *Error.String)
Protected Done.i
LockMutex(BakaShrot_Names_Mutex)
Done = BakaShrot_Names_EnsureIdIn(@BakaShrot_Names_Topics, Id, *Error)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Done
EndProcedure
; The id of a topic (Kind #BakaShrot_NameKind_Topic) or node a peer sent,
; by its name, which a wildcard in that peer's AcceptTopics / AcceptNodes
; took (the caller checks): a name this server doesn't have yet is added,
; under the highest free id counting down from 65535 (origin "peer").
; Returns -1 with the reason in *Error\s.
Procedure.i BakaShrot_Names_Ingest(Kind.i, Name.s, *Error.String)
Protected *Names.BakaShrot_NameTable, Id.i
*Names = @BakaShrot_Names_Topics
If Kind = #BakaShrot_NameKind_Node
*Names = @BakaShrot_Names_Nodes
EndIf
If Not BakaShrot_IsValidName(Name)
*Error\s = "'" + Name + "' isn't a valid " + *Names\Kind + " name"
ProcedureReturn -1
EndIf
LockMutex(BakaShrot_Names_Mutex)
If FindMapElement(*Names\IdByName(), LCase(Name))
Id = *Names\IdByName()
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn Id
EndIf
For Id = #BakaShrot_MaxId To 0 Step -1
If Not FindMapElement(*Names\NameById(), Str(Id))
Break
EndIf
Next
If Id < 0
UnlockMutex(BakaShrot_Names_Mutex)
*Error\s = "no " + *Names\Kind + " id left for '" + Name + "'"
ProcedureReturn -1
EndIf
If Not RegisterStorageName(*Names\Table, Id, Name, #BakaShrot_Names_OriginPeer, *Error)
UnlockMutex(BakaShrot_Names_Mutex)
ProcedureReturn -1
EndIf
*Names\NameById(Str(Id)) = Name
*Names\OriginById(Str(Id)) = #BakaShrot_Names_OriginPeer
*Names\IdByName(LCase(Name)) = Id
UnlockMutex(BakaShrot_Names_Mutex)
PrintN("[Names] New " + *Names\Kind + " '" + Name + "' from a peer, id " + Str(Id) + " here")
ProcedureReturn Id
EndProcedure
; --- Drops -------------------------------------------------------------------
; Called whenever a topic or node isn't replicated because one side doesn't
; know it: Peer is the peer section's name, Kind "topic" or "node", Ref what
; it goes by on the side that has it, Reason why it was dropped.
; !!! Does nothing for now, on purpose: it's called at every check-in for
; !!! every such pair, so logging each one would spam. Later: warn once per
; !!! peer and name (and again only if it changes), see Notes.md.
Procedure BakaShrot_Names_NoteDropped(Peer.s, Kind.s, Ref.s, Reason.s)
EndProcedure
+751
View File
@@ -0,0 +1,751 @@
; ============================================================================
; BakaShrot Storage
;
; Opens the SQLite database file that backs the node's local storage, and
; provides the basic read/write operations on top of it.
; Schema: see db_schema_v5.dbml in this same folder.
;
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official
; sqlite3.dll is used instead, it must be next to the program. Build.ps1
; extracts it from Libs/sqlite-dll-win-*.zip and copies it.
;
; Threads: ONE CONNECTION PER THREAD, never share a handle.
; The SetDatabase*() parameters and query results belong to a handle, so two
; threads using the same one overwrite each other's. Every thread that touches
; the database opens its own with OpenStorageDatabase() and closes it when it
; ends: each client thread, each peer link thread, each raw query, and the
; root's own one (setup and maintenance, see Server/Root.pbi).
; The one exception: every write goes through the writer (Writer.pbi), a
; single connection only used while holding BakaShrot_Storage_WriteMutex.
; SQLite still serializes writes from other processes
; (#BakaShrot_Storage_BusyTimeout). WAL mode lets reads run alongside them.
; See Design/StorageConcurrency.md.
; ============================================================================
; For BakaShrot_SyncPair and BakaShrot_ReplicatedMessage.
XIncludeFile "../../Commons/Networking/Packets/SyncStatePacket.pbi"
XIncludeFile "../../Commons/Networking/Packets/ReplicateMessagesPacket.pbi"
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
UseSQLiteDatabase("sqlite3.dll")
CompilerElse
UseSQLiteDatabase()
CompilerEndIf
; One row of the "data" table (see db_schema_v5.dbml).
Structure BakaShrot_Message
MessageId.q
JsonData.s
EndStructure
; How long a connection waits for another one's lock before a statement
; fails with "database is locked", in ms.
#BakaShrot_Storage_BusyTimeout = 5000
; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in
; the file): readers and the writer don't block each other anymore, so a
; long raw query no longer stalls every push.
; With WAL, NORMAL only syncs to disk at checkpoints instead of on every
; commit, which is most of what a push used to cost. The database can't get
; corrupted, but the last commits before a power loss or an OS crash (not a
; crash of the server itself) can be lost. Those messages were acknowledged,
; and maybe replicated already, so their ids could then be handed out again
; for other messages: drift, see Design/ReplicationIssues.md #1.
; FULL syncs every commit, like before, but still lets reads and writes run
; side by side.
#BakaShrot_Storage_Synchronous = "NORMAL"
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
; new connection for the calling thread only.
; Returns the PureBasic database number, or 0 if the file could not be opened.
Procedure.i OpenStorageDatabase(DatabasePath.s)
Protected FileId.i, DbId.i
; PureBasic's SQLite driver refuses to open a file that doesn't exist,
; so an empty one has to be created first.
If FileSize(DatabasePath) = -1
FileId = CreateFile(#PB_Any, DatabasePath)
If Not FileId
ProcedureReturn 0
EndIf
CloseFile(FileId)
EndIf
DbId = OpenDatabase(#PB_Any, DatabasePath, "", "")
If Not DbId
ProcedureReturn 0
EndIf
; Without it, a write fails right away while another connection writes.
If Not DatabaseUpdate(DbId, "PRAGMA busy_timeout = " + Str(#BakaShrot_Storage_BusyTimeout))
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
; Per connection, see #BakaShrot_Storage_Synchronous.
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + #BakaShrot_Storage_Synchronous)
CloseDatabase(DbId)
ProcedureReturn 0
EndIf
ProcedureReturn DbId
EndProcedure
; Rebuilds the database file, reclaiming the space of deleted rows.
; Only run it from the root while every worker is stopped: it needs every
; other connection to be idle. See BakaShrot_Root_Vacuum() in Server/Root.pbi.
Procedure.i VacuumStorageDatabase(DbId.i)
ProcedureReturn DatabaseUpdate(DbId, "VACUUM")
EndProcedure
; #True if Table has a column named Column, #False if not (or no such table),
; -1 on failure.
Procedure.i StorageHasColumn(DbId.i, Table.s, Column.s)
Protected Found.i = #False
SetDatabaseString(DbId, 0, Table)
SetDatabaseString(DbId, 1, Column)
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM pragma_table_info(?) WHERE name = ?")
ProcedureReturn -1
EndIf
If NextDatabaseRow(DbId)
Found = Bool(GetDatabaseLong(DbId, 0) > 0)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; v3 -> v4: "group_id" became "topic_id" in every table. Renames the
; columns of a database made before, in one transaction. The trigger and the
; attachements index are dropped, SetupStorageDatabase() makes them again
; with the new names. The UNIQUE and PRIMARY KEY indexes follow the columns.
; Nothing to do on a new or already renamed database.
Procedure.i MigrateStorageTopicIds(DbId.i)
Protected Table.s, Has.i, i.i
Has = StorageHasColumn(DbId, "data", "group_id")
If Has = -1
ProcedureReturn #False
ElseIf Not Has
ProcedureReturn #True
EndIf
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "DROP TRIGGER IF EXISTS trg_data_node_heads") Or
Not DatabaseUpdate(DbId, "DROP INDEX IF EXISTS idx_attachements_group_node")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
For i = 1 To 3
Table = StringField("data,node_heads,attachements", i, ",")
Has = StorageHasColumn(DbId, Table, "group_id")
If Has = -1 Or (Has And Not DatabaseUpdate(DbId, "ALTER TABLE " + Table + " RENAME COLUMN group_id TO topic_id"))
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
Next
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Creates the tables and indexes described by db_schema_v5.dbml, if they
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
; upgrade mechanism (DbUpdater) will replace this later.
; Fails on a database made with an older schema, since it would be left as is.
Procedure.i SetupStorageDatabase(DbId.i)
Protected JournalMode.s, HeadsExist.i
; Stored in the file, every later connection uses it. Fails while another
; connection has the database open, so only the root does it, at start.
If Not DatabaseQuery(DbId, "PRAGMA journal_mode = WAL")
ProcedureReturn #False
EndIf
If NextDatabaseRow(DbId)
JournalMode = LCase(GetDatabaseString(DbId, 0))
EndIf
FinishDatabaseQuery(DbId)
If JournalMode <> "wal"
ProcedureReturn #False
EndIf
; Before anything below, which uses the new names.
If Not MigrateStorageTopicIds(DbId)
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" +
"delete_by INTEGER NOT NULL, " +
"message_data TEXT NOT NULL)")
ProcedureReturn #False
EndIf
; is_json is set by SQLite on insert, and can't be written.
; The UNIQUE constraint's index also serves (topic_id, node_id) lookups.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"message_id INTEGER NOT NULL, " +
"message_data TEXT NOT NULL, " +
"is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, " +
"UNIQUE (topic_id, node_id, message_id))")
ProcedureReturn #False
EndIf
; An older "data" table is kept by CREATE IF NOT EXISTS, its lack of
; is_json gives it away. Fails with "no such column: is_json".
If Not DatabaseQuery(DbId, "SELECT is_json FROM data LIMIT 0")
ProcedureReturn #False
EndIf
FinishDatabaseQuery(DbId)
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_message_id ON data (message_id)")
ProcedureReturn #False
EndIf
; Not used yet, but created now so the on-disk schema already matches
; db_schema_v1.dbml.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"message_id INTEGER NOT NULL, " +
"attachement_data BLOB NOT NULL)")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_topic_node ON attachements (topic_id, node_id)")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)")
ProcedureReturn #False
EndIf
; The highest message id of every topic/node id, kept by a trigger on
; every insert, whoever does it. The sync state comes from it instead of
; a GROUP BY over every message (131 ms at 1.9M rows, on every check-in).
; Filled from "data" when it's created on an existing database.
; !!! Nothing deletes from "data" yet: whatever does must update it too.
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'")
ProcedureReturn #False
EndIf
HeadsExist = #False
If NextDatabaseRow(DbId)
HeadsExist = Bool(GetDatabaseLong(DbId, 0) > 0)
EndIf
FinishDatabaseQuery(DbId)
If Not HeadsExist
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE TABLE node_heads (" +
"topic_id INTEGER NOT NULL, " +
"node_id INTEGER NOT NULL, " +
"max_message_id INTEGER NOT NULL, " +
"PRIMARY KEY (topic_id, node_id)) WITHOUT ROWID") Or
Not DatabaseUpdate(DbId, "INSERT INTO node_heads (topic_id, node_id, max_message_id) " +
"SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
EndIf
; Only fires for rows actually inserted, not the ones INSERT OR IGNORE drops.
If Not DatabaseUpdate(DbId, "CREATE TRIGGER IF NOT EXISTS trg_data_node_heads AFTER INSERT ON data BEGIN " +
"INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (NEW.topic_id, NEW.node_id, NEW.message_id) " +
"ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id); " +
"END")
ProcedureReturn #False
EndIf
; Every topic and node id in "data" has a row, with its name, or its id
; in digits if it has none. origin: "config" (named in the config),
; "peer" (a node a peer sent messages of, given an id here), "id"
; (unnamed). Kept up to date by Server/Storage/Names.pbi.
; No foreign keys from "data": see Notes.md, a replicated batch would
; fail as a whole on an unknown id.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS topics (" +
"topic_id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL UNIQUE COLLATE NOCASE, " +
"origin TEXT NOT NULL)") Or
Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS nodes (" +
"node_id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL UNIQUE COLLATE NOCASE, " +
"origin TEXT NOT NULL)")
ProcedureReturn #False
EndIf
; For queries by name: SELECT * FROM messages WHERE topic = 'logs' AND
; node = 'kitchen' still goes through the indexes.
If Not DatabaseUpdate(DbId, "CREATE VIEW IF NOT EXISTS messages AS " +
"SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id " +
"FROM data d JOIN topics t ON t.topic_id = d.topic_id JOIN nodes n ON n.node_id = d.node_id")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Inserts one JSON message into the "data" table.
Procedure.i Insert(DbId.i, TopicId.i, NodeId.i, MessageId.i, JsonData.s)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseLong(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)")
EndProcedure
; Gets every message stored for a given topic_id/node_id pair - the
; "(topic_id, node_id)" index - ordered by message_id.
Procedure.i GetMessagesByTopicAndNode(DbId.i, TopicId.i, NodeId.i, List Messages.BakaShrot_Message())
ClearList(Messages())
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Messages())
Messages()\MessageId = GetDatabaseLong(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Gets every message stored under a given message_id, regardless of which
; topic/node it belongs to - the standalone "message_id" index.
Procedure.i GetMessagesByMessageId(DbId.i, MessageId.i, List Messages.BakaShrot_Message())
ClearList(Messages())
SetDatabaseLong(DbId, 0, MessageId)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE message_id = ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Messages())
Messages()\MessageId = GetDatabaseLong(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Test helper: scans every stored message and collects the value found at
; JsonPath (e.g. "$.messageData.MsgType"), skipping messages where it's
; missing or null, and those that aren't JSON (is_json = 0: ->> fails the
; whole query on one). Kept basic on purpose - no paging, no topic/node filter.
Procedure.i GetValuesAtJsonPath(DbId.i, JsonPath.s, List Values.s())
ClearList(Values())
SetDatabaseString(DbId, 0, JsonPath)
SetDatabaseString(DbId, 1, JsonPath)
If Not DatabaseQuery(DbId, "SELECT message_data ->> ? FROM data WHERE is_json = 1 AND message_data ->> ? IS NOT NULL")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Values())
Values() = GetDatabaseString(DbId, 0)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Returns the highest message_id stored for a given topic_id/node_id pair,
; or -1 if there's none yet. Will likely grow into a cached counter later.
Procedure.i GetLatestMessageId(DbId.i, TopicId.i, NodeId.i)
Protected MessageId.i = -1
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If DatabaseQuery(DbId, "SELECT COALESCE(MAX(message_id), -1) FROM data WHERE topic_id = ? AND node_id = ?")
If NextDatabaseRow(DbId)
MessageId = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
ProcedureReturn MessageId
EndProcedure
; Fills *Message with the message that has the highest message_id for a
; topic_id/node_id pair.
; Returns #False if there's none, or if the query failed.
Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Message)
Protected Found.i
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1")
ProcedureReturn #False
EndIf
Found = NextDatabaseRow(DbId)
If Found
*Message\MessageId = GetDatabaseQuad(DbId, 0)
*Message\JsonData = GetDatabaseString(DbId, 1)
EndIf
FinishDatabaseQuery(DbId)
ProcedureReturn Found
EndProcedure
; --- Raw queries -------------------------------------------------------------
; Most rows a raw query can return.
#BakaShrot_Query_MaxRows = 10000
; Telling the end of a query's rows from an error that cut them short.
; PureBasic's NextDatabaseRow() returns #False for both, and DatabaseError()
; stays empty after such an error: a JSON function (->>, json_extract())
; reaching a row that isn't JSON stops the query with "malformed JSON", and
; the query looked like it simply had no (more) rows. So once the rows end,
; SQLite itself is asked: sqlite3_errcode() on the connection is SQLITE_DONE
; (or SQLITE_ROW/SQLITE_OK) if they really ended, the error otherwise, with
; sqlite3_errmsg16() telling which. Same sqlite3.dll as PureBasic's
; (DatabaseID() is its sqlite3 handle), like Writer.pbi.
; Elsewhere than Windows, PureBasic's own SQLite is linked in and not
; reachable this way: DatabaseError() is checked instead, which misses it.
#BakaShrot_Query_SqliteOk = 0
#BakaShrot_Query_SqliteRow = 100
#BakaShrot_Query_SqliteDone = 101
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
PrototypeC.l BakaShrot_Query_SqliteErrCode(Db.i)
PrototypeC.i BakaShrot_Query_SqliteErrMsg16(Db.i)
Structure BakaShrot_Query_SqliteApi
Library.i
ErrCode.BakaShrot_Query_SqliteErrCode
ErrMsg16.BakaShrot_Query_SqliteErrMsg16
EndStructure
Global BakaShrot_Query_Sqlite.BakaShrot_Query_SqliteApi
; Queries run on every client's thread, the first one loads it.
Global BakaShrot_Query_SqliteMutex.i = CreateMutex()
; Returns #False if sqlite3.dll or its functions can't be found.
Procedure.i BakaShrot_Query_LoadSqlite()
Protected Loaded.i
LockMutex(BakaShrot_Query_SqliteMutex)
With BakaShrot_Query_Sqlite
If Not \Library
\Library = OpenLibrary(#PB_Any, "sqlite3.dll")
If \Library
\ErrCode = GetFunction(\Library, "sqlite3_errcode")
\ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16")
If Not \ErrCode Or Not \ErrMsg16
CloseLibrary(\Library)
\Library = 0
EndIf
EndIf
EndIf
Loaded = Bool(\Library)
EndWith
UnlockMutex(BakaShrot_Query_SqliteMutex)
ProcedureReturn Loaded
EndProcedure
CompilerEndIf
; Runs a raw SQL query from a client, read-only, and fills *Result\s with its
; rows as JSON: {"columns": ["name", ...], "rows": [["value", ...], ...]}.
; Every value is a string, or null for NULL: PureBasic reports no column
; types for SQLite. Wrap a blob in hex() to read it.
;
; Read-only, enforced three ways:
; 1. It must start with SELECT or WITH.
; 2. It runs on its own connection to DatabasePath, opened just for it,
; with PRAGMA query_only = ON. Writes fail, even WITH ... DELETE, and a
; query that turns the pragma off only does so for its own connection.
; 3. Only the first statement runs, anything after a ";" is ignored.
;
; An error while reading the rows fails the whole query, with SQLite's
; message: a JSON function on a row that isn't JSON gives "malformed JSON",
; add "is_json = 1" to the WHERE. Never a partial or empty result instead.
;
; Thread-safe, since it never touches a shared handle.
; Returns #False with *Error\s set if it's refused, fails, or has more than
; #BakaShrot_Query_MaxRows rows.
Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.String)
Protected DbId.i, JsonId.i, *Root, *Columns, *Rows, *Row
Protected Column.i, RowCount.i, Start.s, ErrorCode.l
Start = UCase(Trim(ReplaceString(ReplaceString(ReplaceString(Sql, #CR$, " "), #LF$, " "), #TAB$, " ")))
If Left(Start, 6) <> "SELECT" And Left(Start, 4) <> "WITH"
*Error\s = "Only SELECT and WITH queries are allowed"
ProcedureReturn #False
EndIf
; Without it, errors in the rows would go unnoticed: refused instead.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
If Not BakaShrot_Query_LoadSqlite()
*Error\s = "Queries can't be checked for errors: sqlite3_errcode() not found"
ProcedureReturn #False
EndIf
CompilerEndIf
DbId = OpenStorageDatabase(DatabasePath)
If Not DbId
*Error\s = "The database couldn't be opened"
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "PRAGMA query_only = ON")
*Error\s = "The database couldn't be made read-only"
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
If Not DatabaseQuery(DbId, Sql)
*Error\s = DatabaseError()
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
; WITH ... DELETE and the likes have no columns. query_only stops them
; anyway, but PureBasic doesn't report that, they'd look like no rows.
If DatabaseColumns(DbId) = 0
*Error\s = "The query doesn't return any column, only SELECT queries are allowed"
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
JsonId = CreateJSON(#PB_Any)
If Not JsonId
*Error\s = "Out of memory"
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
*Root = SetJSONObject(JSONValue(JsonId))
*Columns = SetJSONArray(AddJSONMember(*Root, "columns"))
For Column = 0 To DatabaseColumns(DbId) - 1
SetJSONString(AddJSONElement(*Columns), DatabaseColumnName(DbId, Column))
Next
*Rows = SetJSONArray(AddJSONMember(*Root, "rows"))
While NextDatabaseRow(DbId)
RowCount + 1
If RowCount > #BakaShrot_Query_MaxRows
*Error\s = "More than " + Str(#BakaShrot_Query_MaxRows) + " rows, add a LIMIT"
FreeJSON(JsonId)
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
*Row = SetJSONArray(AddJSONElement(*Rows))
For Column = 0 To DatabaseColumns(DbId) - 1
If CheckDatabaseNull(DbId, Column)
SetJSONNull(AddJSONElement(*Row))
Else
SetJSONString(AddJSONElement(*Row), GetDatabaseString(DbId, Column))
EndIf
Next
Wend
; Did the rows end, or did an error end them? (see above): "malformed
; JSON", a write stopped by query_only (DELETE ... RETURNING), ...
; Asked before FinishDatabaseQuery(), while the failed step is the last
; thing done on this connection. A false alarm would refuse a good
; query, it can't hide a bad one.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId))
If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone
*Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode)
If *Error\s = ""
*Error\s = "SQLite error " + Str(ErrorCode)
EndIf
If FindString(*Error\s, "JSON", 1, #PB_String_NoCase)
*Error\s + " (a row isn't JSON: add is_json = 1 to the WHERE)"
EndIf
FreeJSON(JsonId)
FinishDatabaseQuery(DbId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
CompilerEndIf
FinishDatabaseQuery(DbId)
; Elsewhere than Windows, the only check there is. It misses errors in the
; rows: PureBasic doesn't report them.
; !!! DatabaseError() may be shared by every thread, see
; !!! Design/StorageConcurrency.md, another thread's error could show up here.
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
If DatabaseError() <> ""
*Error\s = DatabaseError()
FreeJSON(JsonId)
CloseDatabase(DbId)
ProcedureReturn #False
EndIf
CompilerEndIf
*Result\s = ComposeJSON(JsonId)
FreeJSON(JsonId)
CloseDatabase(DbId)
ProcedureReturn #True
EndProcedure
; --- Replication -------------------------------------------------------------
; Fills Pairs() with where this node is at: the highest message id it has for
; every topic/node id combination, ordered by topic then node id. Read from
; node_heads, kept up to date by a trigger, see SetupStorageDatabase().
; Returns #False if the query failed.
Procedure.i GetSyncState(DbId.i, List Pairs.BakaShrot_SyncPair())
ClearList(Pairs())
If Not DatabaseQuery(DbId, "SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
AddElement(Pairs())
Pairs()\TopicId = GetDatabaseLong(DbId, 0)
Pairs()\NodeId = GetDatabaseLong(DbId, 1)
Pairs()\MessageId = GetDatabaseQuad(DbId, 2)
Wend
FinishDatabaseQuery(DbId)
ProcedureReturn #True
EndProcedure
; Fills Messages() with up to Limit messages of a topic/node id combination
; whose message_id is above AfterMessageId, in message_id order. Stops early
; once their JSON adds up to MaxChars characters or more (0: no such limit),
; the one that got there included, so big messages aren't all read at once.
; If *More is given, *More\i is set to #True if more messages follow the
; last one read.
; Returns #False if the query failed.
Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limit.i, MaxChars.i, List Messages.BakaShrot_Message(), *More.Integer = 0)
Protected Chars.i, More.i
ClearList(Messages())
; One more than asked for, to tell if more follow.
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, AfterMessageId)
SetDatabaseLong(DbId, 3, Limit + 1)
If Not DatabaseQuery(DbId, "SELECT message_id, message_data FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?")
ProcedureReturn #False
EndIf
While NextDatabaseRow(DbId)
If ListSize(Messages()) >= Limit Or (MaxChars > 0 And Chars >= MaxChars)
More = #True
Break
EndIf
AddElement(Messages())
Messages()\MessageId = GetDatabaseQuad(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Chars + Len(Messages()\JsonData)
Wend
FinishDatabaseQuery(DbId)
If *More
*More\i = More
EndIf
ProcedureReturn #True
EndProcedure
; Stores a message replicated from a peer, under the ids it has on its origin.
; If that topic/node/message id is already stored, it's kept as is, and the
; new one is dropped, even if it differs. See Design/ReplicationIssues.md.
; On its own connection: for tools writing while the server is stopped
; (BenchSeed). The server itself writes through Writer.pbi.
; Returns #False if the insert failed.
Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)")
EndProcedure
; Every write: pushes (group commit), replicated batches, the WAL checkpoints.
XIncludeFile "Writer.pbi"
; Usage example. Only compiled when this file is run directly (F5 in the
; IDE), not when it's included as a module by the rest of the project.
CompilerIf #PB_Compiler_IsMainFile
Define DbId = OpenStorageDatabase("storage.sqlite")
If DbId
If SetupStorageDatabase(DbId)
Insert(DbId, 1, 1, 1, ~"{\"messageData\": {\"MsgType\": \"hello\"}}")
Insert(DbId, 1, 1, 2, ~"{\"messageData\": {\"MsgType\": \"world\"}}")
NewList Messages.BakaShrot_Message()
GetMessagesByTopicAndNode(DbId, 1, 1, Messages())
ForEach Messages()
Debug "Message #" + Str(Messages()\MessageId) + ": " + Messages()\JsonData
Next
NewList MsgTypes.s()
GetValuesAtJsonPath(DbId, "$.messageData.MsgType", MsgTypes())
ForEach MsgTypes()
Debug "MsgType: " + MsgTypes()
Next
Debug "Latest message id: " + Str(GetLatestMessageId(DbId, 1, 1))
Else
Debug "Failed to set up database: " + DatabaseError()
EndIf
CloseDatabase(DbId)
Else
Debug "Failed to open database: " + DatabaseError()
EndIf
CompilerEndIf
+783
View File
@@ -0,0 +1,783 @@
; ============================================================================
; BakaShrot Storage Writer
;
; Every write the server does to its database goes through here:
; InsertNextMessage() pushes, grouped (group commit)
; InsertReplicatedMessages() batches from peers
; on ONE connection, the writer, only ever used while holding
; BakaShrot_Storage_WriteMutex. Opened by OpenStorageWriter() when the
; workers start, closed by CloseStorageWriter() once they're stopped (see
; Server/Root.pbi). The exception to "one connection per thread" (see
; Storage.pbi): it's shared, but never by two threads at once.
;
; What makes it fast, see Design/StorageConcurrency.md:
; - Group commit: each push queues itself, then takes the write mutex.
; Whoever holds it writes every queued push in one transaction, the ones
; that were waiting find theirs done. The busier, the bigger the groups.
; - Prepared statements, kept for as long as the writer is open, through
; SQLite's own API: PureBasic prepares a statement again on every call.
; Same sqlite3.dll as PureBasic's (DatabaseID() is its sqlite3 handle).
; Elsewhere than Windows, PureBasic's own SQLite is linked in, so its
; functions are used instead (slower, same behaviour).
; - The next message id of every topic/node id kept in memory, instead of
; a MAX(message_id) on every push. Read from the database the first time
; a pair is pushed to, raised by the replicated messages, forgotten on a
; rollback. Only right as long as this writer is the only one writing,
; which the write mutex ensures within the server.
; - Checkpoints mostly off the write path: the writer only checkpoints by
; itself past #BakaShrot_Storage_WalBackstopFrames, a background thread
; checkpoints every
; #BakaShrot_Storage_CheckpointInterval ms on its own connection, in
; PASSIVE rounds that don't block anything, finishing with a short one
; under the write mutex so the WAL can start over (see
; BakaShrot_Writer_CheckpointThread()).
;
; Logs a [Storage] line every #BakaShrot_Storage_StatsInterval ms while
; pushes come in: pushes/s, per transaction, write time per push, how busy.
; ============================================================================
; Most pushes in one transaction.
#BakaShrot_Storage_MaxGroupSize = 1000
#BakaShrot_Storage_CheckpointInterval = 1000
; A checkpoint finishes under the write mutex once at most this many WAL
; frames (4 KB pages) are left to copy, see BakaShrot_Writer_CheckpointThread().
#BakaShrot_Storage_CheckpointFinishFrames = 2000
#BakaShrot_Storage_StatsInterval = 10000
; The writer still checkpoints by itself (like SQLite does by default, at
; 1000) once the WAL reaches this many frames, when the checkpoint thread
; can't keep up: flat out, ~25,000 frames/s per server. Without it the WAL
; grew to 170,000 frames (700 MB) and Windows started throttling the writes,
; up to 5 s for a push.
#BakaShrot_Storage_WalBackstopFrames = 10000
; Once a checkpoint let the WAL start over, its file is truncated to this.
#BakaShrot_Storage_WalSizeLimit = 67108864
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
#BakaShrot_Storage_RawSqlite = #True
CompilerElse
#BakaShrot_Storage_RawSqlite = #False
CompilerEndIf
#BakaShrot_Sqlite_Done = 101
#BakaShrot_Sqlite_Row = 100
#BakaShrot_Sqlite_Static = 0
CompilerIf #BakaShrot_Storage_RawSqlite
PrototypeC.l BakaShrot_Sqlite_Prepare16(Db.i, *Sql, Bytes.l, *Statement, *Tail)
PrototypeC.l BakaShrot_Sqlite_BindInt64(Statement.i, Index.l, Value.q)
PrototypeC.l BakaShrot_Sqlite_BindText16(Statement.i, Index.l, *Text, Bytes.l, Destructor.i)
PrototypeC.l BakaShrot_Sqlite_Step(Statement.i)
PrototypeC.l BakaShrot_Sqlite_Reset(Statement.i)
PrototypeC.l BakaShrot_Sqlite_Finalize(Statement.i)
PrototypeC.q BakaShrot_Sqlite_ColumnInt64(Statement.i, Column.l)
PrototypeC.l BakaShrot_Sqlite_Changes(Db.i)
PrototypeC.i BakaShrot_Sqlite_ErrMsg16(Db.i)
PrototypeC.i BakaShrot_Sqlite_DbFilename(Db.i, *Name)
Structure BakaShrot_SqliteApi
Library.i
Prepare16.BakaShrot_Sqlite_Prepare16
BindInt64.BakaShrot_Sqlite_BindInt64
BindText16.BakaShrot_Sqlite_BindText16
Step_.BakaShrot_Sqlite_Step
Reset.BakaShrot_Sqlite_Reset
Finalize.BakaShrot_Sqlite_Finalize
ColumnInt64.BakaShrot_Sqlite_ColumnInt64
Changes.BakaShrot_Sqlite_Changes
ErrMsg16.BakaShrot_Sqlite_ErrMsg16
DbFilename.BakaShrot_Sqlite_DbFilename
EndStructure
Global BakaShrot_Sqlite.BakaShrot_SqliteApi
CompilerEndIf
; A queued push, on the stack of the thread that pushed it, which waits for
; it on the write mutex.
Structure BakaShrot_PushJob
TopicId.i
NodeId.i
JsonData.s
; Filled in by whoever writes it, under the write mutex.
MessageId.q
Error.s
Done.i
EndStructure
Structure BakaShrot_StorageStats
LastLog.i
Groups.q
Pushes.q
Ticks.q
EndStructure
Structure BakaShrot_StorageWriter
DatabasePath.s
; PureBasic database, and its sqlite3 handle.
DbId.i
Handle.i
; Prepared once (or the SQL, without the raw API).
Begin.i
Commit.i
Rollback.i
Insert.i
InsertOrIgnore.i
MaxId.i
; "TopicId:NodeId" -> the next message id to hand out.
Map NextIds.q()
; Set by the last failed statement.
LastError.s
CheckpointThread.i
StopRequested.i
CheckpointCount.i
CheckpointTicks.q
; The part of it holding the write mutex.
CheckpointLockedTicks.q
; Frames in the WAL at the last checkpoint, 4 KB each by default.
WalFrames.i
Stats.BakaShrot_StorageStats
EndStructure
; Taken around every write. SQLite already allows a single writer, but one
; that finds the database locked sleeps and retries (1, 2, 5, 10... ms):
; queued here instead, each one gets it the moment it's free. Only covers
; this process, the busy timeout still handles any other one.
Global BakaShrot_Storage_WriteMutex.i = CreateMutex()
; Guards BakaShrot_Storage_Queue(), *BakaShrot_PushJob in arrival order.
Global BakaShrot_Storage_QueueMutex.i = CreateMutex()
Global NewList BakaShrot_Storage_Queue.i()
Global BakaShrot_Storage_Writer.BakaShrot_StorageWriter
Global BakaShrot_Storage_TicksPerMs.d = 1
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
Define BakaShrot_Storage_Frequency.q
QueryPerformanceFrequency_(@BakaShrot_Storage_Frequency)
BakaShrot_Storage_TicksPerMs = BakaShrot_Storage_Frequency / 1000.0
CompilerEndIf
Procedure.q BakaShrot_Storage_Ticks()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
Protected Ticks.q
QueryPerformanceCounter_(@Ticks)
ProcedureReturn Ticks
CompilerElse
ProcedureReturn ElapsedMilliseconds()
CompilerEndIf
EndProcedure
; --- Statements --------------------------------------------------------------
; Everything below the "Statements" line runs holding the write mutex.
Procedure.s BakaShrot_Writer_Error()
CompilerIf #BakaShrot_Storage_RawSqlite
If BakaShrot_Storage_Writer\Handle
ProcedureReturn PeekS(BakaShrot_Sqlite\ErrMsg16(BakaShrot_Storage_Writer\Handle), -1, #PB_Unicode)
EndIf
CompilerEndIf
ProcedureReturn DatabaseError()
EndProcedure
CompilerIf Not #BakaShrot_Storage_RawSqlite
Procedure.i BakaShrot_Writer_AllocateString(Text.s)
Protected *Buffer = AllocateMemory(StringByteLength(Text) + 2)
If *Buffer
PokeS(*Buffer, Text)
EndIf
ProcedureReturn *Buffer
EndProcedure
CompilerEndIf
; Returns the prepared statement (the SQL itself without the raw API), or 0.
Procedure.i BakaShrot_Writer_Prepare(Sql.s)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Statement.i
If BakaShrot_Sqlite\Prepare16(BakaShrot_Storage_Writer\Handle, @Sql, -1, @Statement, 0) <> 0
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
ProcedureReturn 0
EndIf
ProcedureReturn Statement
CompilerElse
ProcedureReturn BakaShrot_Writer_AllocateString(Sql)
CompilerEndIf
EndProcedure
Procedure BakaShrot_Writer_Finalize(*Statement.Integer)
If *Statement\i
CompilerIf #BakaShrot_Storage_RawSqlite
BakaShrot_Sqlite\Finalize(*Statement\i)
CompilerElse
FreeMemory(*Statement\i)
CompilerEndIf
*Statement\i = 0
EndIf
EndProcedure
; Runs a statement without parameters (BEGIN, COMMIT, ROLLBACK).
Procedure.i BakaShrot_Writer_Run(Statement.i)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Result.l = BakaShrot_Sqlite\Step_(Statement)
If Result <> #BakaShrot_Sqlite_Done And Result <> #BakaShrot_Sqlite_Row
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn #False
EndIf
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn #True
CompilerElse
If Not DatabaseUpdate(BakaShrot_Storage_Writer\DbId, PeekS(Statement))
BakaShrot_Storage_Writer\LastError = DatabaseError()
ProcedureReturn #False
EndIf
ProcedureReturn #True
CompilerEndIf
EndProcedure
; Inserts one row with Statement (Insert or InsertOrIgnore).
; Returns 1 if inserted, 0 if ignored, -1 if it failed.
Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Result.l
BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId)
BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId)
BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId)
; Static: JsonData outlives the step, the next insert binds it again.
BakaShrot_Sqlite\BindText16(Statement, 4, @JsonData, -1, #BakaShrot_Sqlite_Static)
Result = BakaShrot_Sqlite\Step_(Statement)
If Result <> #BakaShrot_Sqlite_Done
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn -1
EndIf
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn BakaShrot_Sqlite\Changes(BakaShrot_Storage_Writer\Handle)
CompilerElse
Protected DbId.i = BakaShrot_Storage_Writer\DbId
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
If Not DatabaseUpdate(DbId, PeekS(Statement))
BakaShrot_Storage_Writer\LastError = DatabaseError()
ProcedureReturn -1
EndIf
ProcedureReturn AffectedDatabaseRows(DbId)
CompilerEndIf
EndProcedure
; The highest message id stored for a topic/node id, 0 if none, -1 on failure.
Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i)
Protected MaxId.q = -1
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Statement.i = BakaShrot_Storage_Writer\MaxId
BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId)
BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId)
If BakaShrot_Sqlite\Step_(Statement) = #BakaShrot_Sqlite_Row
MaxId = BakaShrot_Sqlite\ColumnInt64(Statement, 0)
Else
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
EndIf
BakaShrot_Sqlite\Reset(Statement)
CompilerElse
Protected DbId.i = BakaShrot_Storage_Writer\DbId
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
If DatabaseQuery(DbId, PeekS(BakaShrot_Storage_Writer\MaxId))
If NextDatabaseRow(DbId)
MaxId = GetDatabaseQuad(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
Else
BakaShrot_Storage_Writer\LastError = DatabaseError()
EndIf
CompilerEndIf
ProcedureReturn MaxId
EndProcedure
; The next message id to hand out for a topic/node id, -1 on failure.
Procedure.q BakaShrot_Writer_NextId(Key.s, TopicId.i, NodeId.i)
Protected MaxId.q
If FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
ProcedureReturn BakaShrot_Storage_Writer\NextIds()
EndIf
MaxId = BakaShrot_Writer_ReadMaxId(TopicId, NodeId)
If MaxId < 0
ProcedureReturn -1
EndIf
BakaShrot_Storage_Writer\NextIds(Key) = MaxId + 1
ProcedureReturn MaxId + 1
EndProcedure
; --- Opening and closing -----------------------------------------------------
CompilerIf #BakaShrot_Storage_RawSqlite
Procedure.i BakaShrot_Writer_LoadSqlite()
With BakaShrot_Sqlite
If \Library
ProcedureReturn #True
EndIf
; The one PureBasic's SQLite driver already loaded.
\Library = OpenLibrary(#PB_Any, "sqlite3.dll")
If Not \Library
ProcedureReturn #False
EndIf
\Prepare16 = GetFunction(\Library, "sqlite3_prepare16_v2")
\BindInt64 = GetFunction(\Library, "sqlite3_bind_int64")
\BindText16 = GetFunction(\Library, "sqlite3_bind_text16")
\Step_ = GetFunction(\Library, "sqlite3_step")
\Reset = GetFunction(\Library, "sqlite3_reset")
\Finalize = GetFunction(\Library, "sqlite3_finalize")
\ColumnInt64 = GetFunction(\Library, "sqlite3_column_int64")
\Changes = GetFunction(\Library, "sqlite3_changes")
\ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16")
\DbFilename = GetFunction(\Library, "sqlite3_db_filename")
If Not \Prepare16 Or Not \BindInt64 Or Not \BindText16 Or Not \Step_ Or Not \Reset Or Not \Finalize Or Not \ColumnInt64 Or Not \Changes Or Not \ErrMsg16 Or Not \DbFilename
CloseLibrary(\Library)
\Library = 0
ProcedureReturn #False
EndIf
EndWith
ProcedureReturn #True
EndProcedure
CompilerEndIf
; One PASSIVE checkpoint: copies what it can of the WAL into the database,
; without waiting for the writer nor the readers. Fills *Frames\i with how
; many frames the WAL has, *Left\i with how many it couldn't copy yet.
Procedure BakaShrot_Writer_CheckpointOnce(DbId.i, *Frames.Integer, *Left.Integer)
*Frames\i = 0
*Left\i = 0
; It only runs on the first NextDatabaseRow(). Its row: busy, frames in
; the WAL, frames checkpointed.
If DatabaseQuery(DbId, "PRAGMA wal_checkpoint(PASSIVE)")
If NextDatabaseRow(DbId)
*Frames\i = GetDatabaseLong(DbId, 1)
*Left\i = *Frames\i - GetDatabaseLong(DbId, 2)
EndIf
FinishDatabaseQuery(DbId)
EndIf
EndProcedure
; Every #BakaShrot_Storage_CheckpointInterval ms, copies the WAL into the
; database in PASSIVE rounds, without the write mutex: they copy far faster
; than the pushes write, so each round leaves less behind. Once few enough
; frames are left, finishes under the write mutex, which takes a few ms: a
; checkpoint that's complete when the next transaction starts is what makes
; SQLite start the WAL over, otherwise it grows forever under steady writes.
; A long read can keep it from completing, it's tried again next time.
Procedure BakaShrot_Writer_CheckpointThread(Unused.i)
Protected DbId.i, LastCheckpoint.i, StartTicks.q, LockedTicks.q, Round.i
Protected Frames.Integer, Left.Integer
DbId = OpenStorageDatabase(BakaShrot_Storage_Writer\DatabasePath)
If Not DbId
PrintN("[Storage] Can't open the database for the checkpoints, the WAL file will keep growing: " + DatabaseError())
ProcedureReturn
EndIf
LastCheckpoint = ElapsedMilliseconds()
While Not BakaShrot_Storage_Writer\StopRequested
Delay(50)
If ElapsedMilliseconds() - LastCheckpoint < #BakaShrot_Storage_CheckpointInterval
Continue
EndIf
StartTicks = BakaShrot_Storage_Ticks()
Round = 0
Repeat
BakaShrot_Writer_CheckpointOnce(DbId, @Frames, @Left)
Round + 1
Until Left\i <= #BakaShrot_Storage_CheckpointFinishFrames Or Round >= 4 Or BakaShrot_Storage_Writer\StopRequested
If Frames\i > 0 And Left\i <= #BakaShrot_Storage_CheckpointFinishFrames
LockMutex(BakaShrot_Storage_WriteMutex)
LockedTicks = BakaShrot_Storage_Ticks()
BakaShrot_Writer_CheckpointOnce(DbId, @Frames, @Left)
BakaShrot_Storage_Writer\CheckpointLockedTicks + BakaShrot_Storage_Ticks() - LockedTicks
UnlockMutex(BakaShrot_Storage_WriteMutex)
EndIf
BakaShrot_Storage_Writer\WalFrames = Frames\i
BakaShrot_Storage_Writer\CheckpointTicks + BakaShrot_Storage_Ticks() - StartTicks
BakaShrot_Storage_Writer\CheckpointCount + 1
LastCheckpoint = ElapsedMilliseconds()
Wend
CloseDatabase(DbId)
EndProcedure
; Holding the write mutex.
Procedure BakaShrot_Writer_Release()
With BakaShrot_Storage_Writer
BakaShrot_Writer_Finalize(@\Begin)
BakaShrot_Writer_Finalize(@\Commit)
BakaShrot_Writer_Finalize(@\Rollback)
BakaShrot_Writer_Finalize(@\Insert)
BakaShrot_Writer_Finalize(@\InsertOrIgnore)
BakaShrot_Writer_Finalize(@\MaxId)
If \DbId
CloseDatabase(\DbId)
EndIf
\DbId = 0
\Handle = 0
ClearMap(\NextIds())
EndWith
EndProcedure
; Opens the writer on DatabasePath, already set up by SetupStorageDatabase(),
; and starts the checkpoints. Returns #False with the reason in *Error\s.
Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String)
Protected *Main
LockMutex(BakaShrot_Storage_WriteMutex)
With BakaShrot_Storage_Writer
\DatabasePath = DatabasePath
\DbId = OpenStorageDatabase(DatabasePath)
If Not \DbId
*Error\s = "can't open it: " + DatabaseError()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
; The checkpoint thread does them, see the top of this file. This is
; only the backstop for when it can't keep up.
If Not DatabaseUpdate(\DbId, "PRAGMA wal_autocheckpoint = " + Str(#BakaShrot_Storage_WalBackstopFrames)) Or
Not DatabaseUpdate(\DbId, "PRAGMA journal_size_limit = " + Str(#BakaShrot_Storage_WalSizeLimit))
*Error\s = "can't set it up: " + DatabaseError()
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
CompilerIf #BakaShrot_Storage_RawSqlite
If Not BakaShrot_Writer_LoadSqlite()
*Error\s = "sqlite3.dll doesn't have the functions needed"
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
\Handle = DatabaseID(\DbId)
*Main = UTF8("main")
If Not \Handle Or Not BakaShrot_Sqlite\DbFilename(\Handle, *Main)
FreeMemory(*Main)
*Error\s = "DatabaseID() didn't give a sqlite3 handle"
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
FreeMemory(*Main)
CompilerEndIf
\Begin = BakaShrot_Writer_Prepare("BEGIN IMMEDIATE")
\Commit = BakaShrot_Writer_Prepare("COMMIT")
\Rollback = BakaShrot_Writer_Prepare("ROLLBACK")
\Insert = BakaShrot_Writer_Prepare("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)")
\InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)")
\MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(message_id), 0) FROM data WHERE topic_id = ?1 AND node_id = ?2")
If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId
*Error\s = "can't prepare its statements: " + \LastError
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
\StopRequested = #False
\CheckpointThread = CreateThread(@BakaShrot_Writer_CheckpointThread(), 0)
If Not \CheckpointThread
*Error\s = "can't start the checkpoint thread"
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #False
EndIf
EndWith
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn #True
EndProcedure
; Stops the checkpoints, checkpoints everything (emptying the WAL file) and
; closes the writer. Once nothing writes anymore: the workers are stopped.
Procedure CloseStorageWriter()
With BakaShrot_Storage_Writer
If \CheckpointThread
\StopRequested = #True
WaitThread(\CheckpointThread)
\CheckpointThread = 0
EndIf
LockMutex(BakaShrot_Storage_WriteMutex)
If \DbId
If DatabaseQuery(\DbId, "PRAGMA wal_checkpoint(TRUNCATE)")
NextDatabaseRow(\DbId)
FinishDatabaseQuery(\DbId)
EndIf
EndIf
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
EndWith
EndProcedure
; --- Writes ------------------------------------------------------------------
; Holding the write mutex.
Procedure BakaShrot_Writer_LogStats()
Protected Now.i = ElapsedMilliseconds(), Seconds.d, Checkpoints.s
With BakaShrot_Storage_Writer\Stats
If \LastLog = 0
\LastLog = Now
ProcedureReturn
EndIf
If Now - \LastLog < #BakaShrot_Storage_StatsInterval
ProcedureReturn
EndIf
Seconds = (Now - \LastLog) / 1000.0
If \Groups > 0
If BakaShrot_Storage_Writer\CheckpointCount > 0
Checkpoints = ", " + Str(BakaShrot_Storage_Writer\CheckpointCount) + " checkpoints of " +
StrD(BakaShrot_Storage_Writer\CheckpointTicks / BakaShrot_Storage_TicksPerMs / BakaShrot_Storage_Writer\CheckpointCount, 1) + " ms (" +
StrD(BakaShrot_Storage_Writer\CheckpointLockedTicks / BakaShrot_Storage_TicksPerMs / BakaShrot_Storage_Writer\CheckpointCount, 1) + " ms of it holding the writes), " +
Str(BakaShrot_Storage_Writer\WalFrames) + " frames in the WAL"
EndIf
PrintN("[Storage] " + Str(\Pushes) + " pushes in " + StrD(Seconds, 1) + " s (" + StrD(\Pushes / Seconds, 0) + "/s), " +
Str(\Groups) + " transactions of " + StrD(\Pushes / \Groups, 1) + " on average, " +
StrD(\Ticks / BakaShrot_Storage_TicksPerMs / \Groups, 3) + " ms each, " +
StrD(\Ticks / BakaShrot_Storage_TicksPerMs / \Pushes, 3) + " ms per push, writing " +
StrD(100.0 * \Ticks / BakaShrot_Storage_TicksPerMs / (Seconds * 1000.0), 0) + " % of the time" + Checkpoints)
EndIf
\LastLog = Now
\Groups = 0
\Pushes = 0
\Ticks = 0
BakaShrot_Storage_Writer\CheckpointCount = 0
BakaShrot_Storage_Writer\CheckpointTicks = 0
BakaShrot_Storage_Writer\CheckpointLockedTicks = 0
EndWith
EndProcedure
; Writes queued pushes in one transaction, filling in their MessageId (-1 and
; Error if that one failed) and setting Done. Holding the write mutex.
Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
Protected *Job.BakaShrot_PushJob, InTransaction.i, Key.s, MessageId.q, JsonData.s
; If it can't start (another process writing past the busy timeout),
; every insert still runs, each in its own transaction.
InTransaction = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin)
; One failed insert is only that statement's, SQLite keeps the others.
ForEach Jobs()
*Job = Jobs()
Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId)
MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId)
JsonData = *Job\JsonData
If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData) = 1
*Job\MessageId = MessageId
BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1
Else
*Job\MessageId = -1
*Job\Error = BakaShrot_Storage_Writer\LastError
EndIf
Next
If InTransaction And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit)
ForEach Jobs()
*Job = Jobs()
*Job\MessageId = -1
*Job\Error = BakaShrot_Storage_Writer\LastError
Next
BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Rollback)
; Some ids were handed out and rolled back.
ClearMap(BakaShrot_Storage_Writer\NextIds())
EndIf
ForEach Jobs()
*Job = Jobs()
*Job\Done = #True
Next
EndProcedure
; Inserts one JSON message for a topic_id/node_id pair, with the next
; message_id for that pair, starting at 1, grouped with the other pushes
; arriving meanwhile. Returns the new message's id once committed, or -1 with
; the reason in *Error\s.
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
Protected Job.BakaShrot_PushJob
Protected NewList Jobs.i()
Protected StartTicks.q
Job\TopicId = TopicId
Job\NodeId = NodeId
Job\JsonData = JsonData
Job\MessageId = -1
LockMutex(BakaShrot_Storage_QueueMutex)
AddElement(BakaShrot_Storage_Queue())
BakaShrot_Storage_Queue() = @Job
UnlockMutex(BakaShrot_Storage_QueueMutex)
; Whoever gets the mutex writes everything queued so far, this one's
; included unless an earlier holder already did. The queue is first in,
; first out, so a capped group still gets to it eventually.
LockMutex(BakaShrot_Storage_WriteMutex)
If Not BakaShrot_Storage_Writer\DbId
; Closed: the workers are stopping.
LockMutex(BakaShrot_Storage_QueueMutex)
ForEach BakaShrot_Storage_Queue()
If BakaShrot_Storage_Queue() = @Job
DeleteElement(BakaShrot_Storage_Queue())
Break
EndIf
Next
UnlockMutex(BakaShrot_Storage_QueueMutex)
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
While Not Job\Done
ClearList(Jobs())
LockMutex(BakaShrot_Storage_QueueMutex)
ForEach BakaShrot_Storage_Queue()
If ListSize(Jobs()) >= #BakaShrot_Storage_MaxGroupSize
Break
EndIf
AddElement(Jobs())
Jobs() = BakaShrot_Storage_Queue()
DeleteElement(BakaShrot_Storage_Queue())
Next
UnlockMutex(BakaShrot_Storage_QueueMutex)
StartTicks = BakaShrot_Storage_Ticks()
BakaShrot_Writer_WriteJobs(Jobs())
With BakaShrot_Storage_Writer\Stats
\Ticks + BakaShrot_Storage_Ticks() - StartTicks
\Groups + 1
\Pushes + ListSize(Jobs())
EndWith
Wend
BakaShrot_Writer_LogStats()
UnlockMutex(BakaShrot_Storage_WriteMutex)
If Job\MessageId < 1
*Error\s = Job\Error
EndIf
ProcedureReturn Job\MessageId
EndProcedure
; Stores a batch of messages replicated from a peer, all of one topic/node
; id, under the ids they have on their origin, in a single transaction:
; either all of them are stored, or none. An id that's already stored is kept
; as is, the new one is dropped, even if it differs (Design/ReplicationIssues.md).
; Returns #False with the reason in *Error\s, the transaction is rolled back.
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String)
Protected Stored.i, Inserted.i, Key.s, JsonData.s
Key = Str(TopicId) + ":" + Str(NodeId)
LockMutex(BakaShrot_Storage_WriteMutex)
If Not BakaShrot_Storage_Writer\DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn #False
EndIf
; IMMEDIATE takes the write lock up front, instead of failing midway if
; another process started writing first.
Stored = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin)
If Stored
ForEach Messages()
JsonData = Messages()\JsonData
Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData)
If Inserted < 0
Stored = #False
Break
EndIf
; A pair pushed to here too (drift): the next push goes after it.
If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds()
BakaShrot_Storage_Writer\NextIds() = Messages()\MessageId + 1
EndIf
EndIf
Next
If Stored And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit)
Stored = #False
EndIf
If Not Stored
*Error\s = BakaShrot_Storage_Writer\LastError
BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Rollback)
ClearMap(BakaShrot_Storage_Writer\NextIds())
EndIf
Else
*Error\s = BakaShrot_Storage_Writer\LastError
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Stored
EndProcedure
; Adds a row to the "topics" or "nodes" table (Table), for Id, named Name
; (its id in digits if it has none), Origin "peer" or "id", see
; Server/Storage/Names.pbi. A row already there for that id is kept.
; Returns #False with the reason in *Error\s.
Procedure.i RegisterStorageName(Table.s, Id.i, Name.s, Origin.s, *Error.String)
Protected DbId.i, Stored.i
LockMutex(BakaShrot_Storage_WriteMutex)
DbId = BakaShrot_Storage_Writer\DbId
If Not DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn #False
EndIf
SetDatabaseLong(DbId, 0, Id)
SetDatabaseString(DbId, 1, Name)
SetDatabaseString(DbId, 2, Origin)
Stored = DatabaseUpdate(DbId, "INSERT OR IGNORE INTO " + Table + " VALUES (?, ?, ?)")
If Not Stored
*Error\s = DatabaseError()
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Stored
EndProcedure
+32
View File
@@ -0,0 +1,32 @@
table archives {
# UTC Unix Timestamp after which this archived message should be deleted.
delete_by ??? [NOT NULL]
message_data TEXT [NOT NULL]
}
table data {
group_id INTEGER [NOT NULL]
node_id INTEGER [NOT NULL]
message_id INTEGER [NOT NULL]
message_data TEXT [NOT NULL]
}
# Create it, but we'll implement this later.
table attachements {
group_id INTEGER [NOT NULL]
node_id INTEGER [NOT NULL]
message_id INTEGER [NOT NULL]
attachement_data BLOB [NOT NULL]
}
index {
data, on combined group_id/node_id
data, on message_id
attachements, on combined group_id/node_id
attachements, on message_id
}
# Note, ignore it
# msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+34
View File
@@ -0,0 +1,34 @@
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Create it, but we'll implement this later.
table attachements {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+45
View File
@@ -0,0 +1,45 @@
// Changes from v1, on "data" only:
// - UNIQUE (group_id, node_id, message_id), so a message id can't be stored twice.
// Its index also serves (group_id, node_id) lookups, replacing v1's index on them.
// - is_json, set by SQLite on insert, for JSON queries on message_data.
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
indexes {
(group_id, node_id, message_id) [unique]
message_id
}
}
// Create it, but we'll implement this later.
table attachements {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+62
View File
@@ -0,0 +1,62 @@
// Changes from v2:
// - node_heads, the highest message id of every group/node id, kept by the
// trg_data_node_heads trigger on every insert into data. The sync state
// (GetSyncState()) reads it instead of a GROUP BY over every message.
// Filled from data when it's created on an existing database.
// Nothing deletes from data yet, whatever does must update it too.
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
indexes {
(group_id, node_id, message_id) [unique]
message_id
}
}
// One row per group/node id that has messages.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
group_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(group_id, node_id) [pk]
}
}
// Create it, but we'll implement this later.
table attachements {
group_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(group_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+61
View File
@@ -0,0 +1,61 @@
// Changes from v3:
// - group_id is now topic_id, in every table. MigrateStorageTopicIds()
// (Storage.pbi) renames the columns of an older database on start, and
// the trigger and the attachements index are made again with the new
// names (idx_attachements_group_node -> idx_attachements_topic_node).
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
indexes {
(topic_id, node_id, message_id) [unique]
message_id
}
}
// One row per topic/node id that has messages.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// Create it, but we'll implement this later.
table attachements {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(topic_id, node_id)
message_id
}
}
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
+88
View File
@@ -0,0 +1,88 @@
// Changes from v4:
// - topics and nodes: every topic and node id in data, with its name (its
// id in digits if it has none) and where that comes from. Kept by
// Server/Storage/Names.pbi from the config. Only names on both servers
// replicate. Names are shared between servers, ids aren't.
// - messages: a view of data with the names, for queries by name.
// - No foreign keys from data to them (Notes.md): an unknown id would fail
// a whole replicated batch.
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table archives {
// UTC Unix Timestamp after which this archived message should be deleted.
delete_by integer [not null]
message_data text [not null]
}
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
indexes {
(topic_id, node_id, message_id) [unique]
message_id
}
}
// One row per topic/node id that has messages.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// Create it, but we'll implement this later.
table attachements {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(topic_id, node_id)
message_id
}
}
// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is
// the id in digits).
table topics {
topic_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer"
// (only in databases from the short-lived version that added peer nodes).
table nodes {
node_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// View messages:
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
// d.is_json, d.topic_id, d.node_id
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
// JOIN nodes n ON n.node_id = d.node_id
// WHERE topic = ... AND node = ... goes through the name indexes, then
// data's (topic_id, node_id, message_id) one.
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL