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
+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