mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Add attachments (protocol 4), their edge-case tests, and handoff docs
- One optional attachment per message, any size up to the server's MaxAttachmentSize (default 1G), sent and stored in 1 MB parts, checked with its SHA-256. Uploaded before its message (UploadStart, UploadChunk), then attached by the PushMessage in the same transaction; uploads never pushed expire after UploadTimeout. Read back a part at a time (GetAttachment). - Replicated separately, after the messages: the message carries the size and SHA-256, then each check-in lists what the peer is missing (MissingAttachments) and sends the parts from where it stopped. Over the receiver's limit, the attachment is marked not kept. - Deleted with its message by the retention, parts cleaned up in the background. Schema v7 (attachments, blobs, blob_chunks), replacing the unused attachements table. - DLL: PushMessageWithFile/WithData, SaveAttachment, LoadAttachment, GetMessageAttachmentSize, IsMessageAttachmentReady. Python: push(..., attachment=), get_attachment(), save_attachment(). Tools: PushMessage -a, GetAttachment. The release smoke test round-trips one. - Tests/Attachments-Test.ps1 (39 checks) and Tests/AttachmentEdges-Test.ps1 (51 checks, with a raw protocol client): wrong SHA-256, bad parts, others' uploads, expiry, replication resuming after a kill, a corrupted stored copy. Found: a corrupted copy is re-sent to peers forever, noted as open item 3 in Notes.md with a proposed fix. - CLAUDE.md: how to build, test, the traps and working rules, for the next session. Notes.md and the Design docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP
This commit is contained in:
@@ -0,0 +1,450 @@
|
||||
; ============================================================================
|
||||
; 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
|
||||
@@ -13,7 +13,12 @@
|
||||
; - 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.
|
||||
; 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
|
||||
@@ -33,6 +38,9 @@
|
||||
; 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
|
||||
@@ -43,6 +51,7 @@ Structure BakaShrot_RetentionState
|
||||
ThreadId.i
|
||||
StopRequested.i
|
||||
IntervalMs.i
|
||||
UploadTimeoutMs.q
|
||||
DatabasePath.s
|
||||
List Rules.BakaShrot_RetentionRule()
|
||||
EndStructure
|
||||
@@ -56,6 +65,25 @@ Procedure.s BakaShrot_Retention_FormatUtc(Ms.q)
|
||||
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.
|
||||
@@ -105,6 +133,7 @@ Procedure.q BakaShrot_Retention_Pass(DbId.i)
|
||||
EndIf
|
||||
Next
|
||||
|
||||
BakaShrot_Retention_CleanUp()
|
||||
ProcedureReturn Total
|
||||
EndProcedure
|
||||
|
||||
@@ -132,27 +161,22 @@ Procedure BakaShrot_Retention_Thread(Unused.i)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, once
|
||||
; the writer is open. Nothing to do (no thread) if every topic is kept
|
||||
; forever. Returns #False if the thread can't start.
|
||||
; 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)
|
||||
Protected Deletes.i
|
||||
|
||||
With BakaShrot_Retention
|
||||
ClearList(\Rules())
|
||||
CopyList(*Config\Retention(), \Rules())
|
||||
ForEach \Rules()
|
||||
If \Rules()\MaxAgeMs > 0
|
||||
Deletes = #True
|
||||
PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s")
|
||||
EndIf
|
||||
Next
|
||||
If Not Deletes
|
||||
ProcedureReturn #True
|
||||
EndIf
|
||||
|
||||
\DatabasePath = *Config\Server\DatabasePath
|
||||
\IntervalMs = *Config\Server\RetentionInterval * 1000
|
||||
\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)
|
||||
|
||||
+82
-13
@@ -3,7 +3,8 @@
|
||||
;
|
||||
; 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_v6.dbml in this same folder.
|
||||
; Schema: see db_schema_v7.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
|
||||
@@ -36,12 +37,18 @@ CompilerElse
|
||||
CompilerEndIf
|
||||
|
||||
|
||||
; One row of the "data" table (see db_schema_v6.dbml).
|
||||
; One row of the "data" table (see db_schema_v7.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
|
||||
|
||||
|
||||
@@ -225,7 +232,7 @@ Procedure.i MigrateStoragePushedAt(DbId.i)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Creates the tables and indexes described by db_schema_v6.dbml, if they
|
||||
; Creates the tables and indexes described by db_schema_v7.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.
|
||||
@@ -293,19 +300,60 @@ Procedure.i SetupStorageDatabase(DbId.i)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; Not used yet, but created now so the on-disk schema already matches
|
||||
; db_schema_v1.dbml.
|
||||
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS attachements (" +
|
||||
; 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, " +
|
||||
"attachement_data BLOB 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
|
||||
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_topic_node ON attachements (topic_id, node_id)")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_attachements_message_id ON attachements (message_id)")
|
||||
|
||||
; 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
|
||||
|
||||
@@ -487,6 +535,18 @@ 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.
|
||||
@@ -495,7 +555,9 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes
|
||||
|
||||
SetDatabaseLong(DbId, 0, TopicId)
|
||||
SetDatabaseLong(DbId, 1, NodeId)
|
||||
If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC 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 = ? ORDER BY d.message_id DESC LIMIT 1")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
@@ -504,6 +566,7 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes
|
||||
*Message\MessageId = GetDatabaseQuad(DbId, 0)
|
||||
*Message\JsonData = GetDatabaseString(DbId, 1)
|
||||
*Message\PushedAt = GetDatabaseQuad(DbId, 2)
|
||||
BakaShrot_ReadAttachmentColumns(DbId, 3, *Message)
|
||||
EndIf
|
||||
FinishDatabaseQuery(DbId)
|
||||
|
||||
@@ -755,7 +818,9 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi
|
||||
SetDatabaseLong(DbId, 1, NodeId)
|
||||
SetDatabaseQuad(DbId, 2, AfterMessageId)
|
||||
SetDatabaseLong(DbId, 3, Limit + 1)
|
||||
If Not DatabaseQuery(DbId, "SELECT message_id, message_data, pushed_at FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?")
|
||||
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
|
||||
|
||||
@@ -768,6 +833,7 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi
|
||||
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)
|
||||
@@ -800,6 +866,9 @@ 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.
|
||||
|
||||
+106
-7
@@ -110,6 +110,8 @@ Structure BakaShrot_PushJob
|
||||
JsonData.s
|
||||
; When it arrived, ms since 1970 UTC.
|
||||
PushedAt.q
|
||||
; Its attachment, a complete upload (blobs), 0 for none.
|
||||
BlobId.q
|
||||
|
||||
; Filled in by whoever writes it, under the write mutex.
|
||||
MessageId.q
|
||||
@@ -641,6 +643,77 @@ Procedure BakaShrot_Writer_LogStats()
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Claims a complete upload (blobs state 1) of TopicId/NodeId for a message:
|
||||
; state 2. Returns #False if it isn't one, someone else's, or attached already.
|
||||
Procedure.i BakaShrot_Writer_ClaimBlob(BlobId.q, TopicId.i, NodeId.i)
|
||||
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||
SetDatabaseQuad(DbId, 0, BlobId)
|
||||
SetDatabaseLong(DbId, 1, TopicId)
|
||||
SetDatabaseLong(DbId, 2, NodeId)
|
||||
If Not DatabaseUpdate(DbId, "UPDATE blobs SET state = 2 WHERE blob_id = ? AND topic_id = ? AND node_id = ? AND state = 1")
|
||||
BakaShrot_Storage_Writer\LastError = DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If AffectedDatabaseRows(DbId) <> 1
|
||||
BakaShrot_Storage_Writer\LastError = "the upload isn't complete, or isn't this client's for that topic"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
; Gives a claimed upload back (state 1), its message couldn't be stored.
|
||||
Procedure BakaShrot_Writer_UnclaimBlob(BlobId.q)
|
||||
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||
SetDatabaseQuad(DbId, 0, BlobId)
|
||||
DatabaseUpdate(DbId, "UPDATE blobs SET state = 1 WHERE blob_id = ?")
|
||||
EndProcedure
|
||||
|
||||
; The attachments row of a pushed message, from its claimed upload.
|
||||
Procedure.i BakaShrot_Writer_LinkBlob(TopicId.i, NodeId.i, MessageId.q, BlobId.q)
|
||||
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||
SetDatabaseLong(DbId, 0, TopicId)
|
||||
SetDatabaseLong(DbId, 1, NodeId)
|
||||
SetDatabaseQuad(DbId, 2, MessageId)
|
||||
SetDatabaseQuad(DbId, 3, BlobId)
|
||||
If Not DatabaseUpdate(DbId, "INSERT INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) " +
|
||||
"SELECT ?, ?, ?, size, sha256, blob_id, 2 FROM blobs WHERE blob_id = ?") Or AffectedDatabaseRows(DbId) <> 1
|
||||
BakaShrot_Storage_Writer\LastError = "can't attach the upload: " + DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
; Deletes a message just inserted in this transaction, its attachment failed.
|
||||
Procedure BakaShrot_Writer_DropMessage(TopicId.i, NodeId.i, MessageId.q)
|
||||
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||
SetDatabaseLong(DbId, 0, TopicId)
|
||||
SetDatabaseLong(DbId, 1, NodeId)
|
||||
SetDatabaseQuad(DbId, 2, MessageId)
|
||||
DatabaseUpdate(DbId, "DELETE FROM data WHERE topic_id = ? AND node_id = ? AND message_id = ?")
|
||||
EndProcedure
|
||||
|
||||
; The attachments row of a replicated message: its data comes later
|
||||
; (Attachments.pbi), state 0 (missing), or 3 (not kept here) past MaxSize.
|
||||
Procedure.i BakaShrot_Writer_AddReplicatedAttachment(TopicId.i, NodeId.i, *Message.BakaShrot_ReplicatedMessage, MaxSize.q)
|
||||
Protected DbId.i = BakaShrot_Storage_Writer\DbId
|
||||
SetDatabaseLong(DbId, 0, TopicId)
|
||||
SetDatabaseLong(DbId, 1, NodeId)
|
||||
SetDatabaseQuad(DbId, 2, *Message\MessageId)
|
||||
SetDatabaseQuad(DbId, 3, *Message\AttachmentSize)
|
||||
SetDatabaseBlob(DbId, 4, @*Message\AttachmentSha256[0], #BakaShrot_Sha256Size)
|
||||
If *Message\AttachmentSize > MaxSize
|
||||
SetDatabaseLong(DbId, 5, 3)
|
||||
Else
|
||||
SetDatabaseLong(DbId, 5, 0)
|
||||
EndIf
|
||||
If Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO attachments (topic_id, node_id, message_id, size, sha256, blob_id, state) VALUES (?, ?, ?, ?, ?, NULL, ?)")
|
||||
BakaShrot_Storage_Writer\LastError = DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Writes queued pushes in one transaction, filling in their MessageId (-1 and
|
||||
; Error if that one failed) and setting Done. Holding the write mutex.
|
||||
Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
|
||||
@@ -656,12 +729,28 @@ Procedure BakaShrot_Writer_WriteJobs(List Jobs.i())
|
||||
Key = Str(*Job\TopicId) + ":" + Str(*Job\NodeId)
|
||||
MessageId = BakaShrot_Writer_NextId(Key, *Job\TopicId, *Job\NodeId)
|
||||
JsonData = *Job\JsonData
|
||||
*Job\MessageId = -1
|
||||
|
||||
; Its upload first: nothing is stored if it can't be claimed.
|
||||
If MessageId > 0 And *Job\BlobId And Not BakaShrot_Writer_ClaimBlob(*Job\BlobId, *Job\TopicId, *Job\NodeId)
|
||||
MessageId = -1
|
||||
EndIf
|
||||
|
||||
If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1
|
||||
*Job\MessageId = MessageId
|
||||
If *Job\BlobId And Not BakaShrot_Writer_LinkBlob(*Job\TopicId, *Job\NodeId, MessageId, *Job\BlobId)
|
||||
BakaShrot_Writer_DropMessage(*Job\TopicId, *Job\NodeId, MessageId)
|
||||
BakaShrot_Writer_UnclaimBlob(*Job\BlobId)
|
||||
Else
|
||||
*Job\MessageId = MessageId
|
||||
EndIf
|
||||
; Taken either way: node_heads went up.
|
||||
BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1
|
||||
Else
|
||||
*Job\MessageId = -1
|
||||
*Job\Error = BakaShrot_Storage_Writer\LastError
|
||||
ElseIf MessageId > 0 And *Job\BlobId
|
||||
BakaShrot_Writer_UnclaimBlob(*Job\BlobId)
|
||||
EndIf
|
||||
|
||||
If *Job\MessageId < 1
|
||||
*Job\Error = BakaShrot_Storage_Writer\LastError
|
||||
EndIf
|
||||
Next
|
||||
|
||||
@@ -685,9 +774,12 @@ EndProcedure
|
||||
|
||||
; Inserts one JSON message for a topic_id/node_id pair, with the next
|
||||
; message_id for that pair, starting at 1, grouped with the other pushes
|
||||
; arriving meanwhile. Stamped with the time it got here (pushed_at). Returns the new message's id once committed, or -1 with
|
||||
; arriving meanwhile. Stamped with the time it got here (pushed_at).
|
||||
; BlobId: its attachment, a complete upload of this topic and node
|
||||
; (Attachments.pbi), 0 for none: attached in the same transaction.
|
||||
; Returns the new message's id once committed, or -1 with
|
||||
; the reason in *Error\s.
|
||||
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
|
||||
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String, BlobId.q = 0)
|
||||
Protected Job.BakaShrot_PushJob
|
||||
Protected NewList Jobs.i()
|
||||
Protected StartTicks.q
|
||||
@@ -696,6 +788,7 @@ Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
|
||||
Job\NodeId = NodeId
|
||||
Job\JsonData = JsonData
|
||||
Job\PushedAt = BakaShrot_NowUtcMs()
|
||||
Job\BlobId = BlobId
|
||||
Job\MessageId = -1
|
||||
|
||||
LockMutex(BakaShrot_Storage_QueueMutex)
|
||||
@@ -761,8 +854,10 @@ EndProcedure
|
||||
; past this server's max age for the topic already: not stored, but the
|
||||
; pair's head still goes up to them, so the peer doesn't send them again.
|
||||
; *Skipped\i, if given, gets how many.
|
||||
; A message's attachment gets its row, its data comes later (Attachments.pbi),
|
||||
; unless it's bigger than MaxAttachmentSize: not kept here then.
|
||||
; Returns #False with the reason in *Error\s, the transaction is rolled back.
|
||||
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0)
|
||||
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0, MaxAttachmentSize.q = #BakaShrot_MaxAttachmentSize)
|
||||
Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q
|
||||
|
||||
Key = Str(TopicId) + ":" + Str(NodeId)
|
||||
@@ -790,6 +885,10 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro
|
||||
Stored = #False
|
||||
Break
|
||||
EndIf
|
||||
If Inserted = 1 And Messages()\AttachmentSize > 0 And Not BakaShrot_Writer_AddReplicatedAttachment(TopicId, NodeId, @Messages(), MaxAttachmentSize)
|
||||
Stored = #False
|
||||
Break
|
||||
EndIf
|
||||
; A pair pushed to here too (drift): the next push goes after it.
|
||||
If Inserted = 1 And FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
|
||||
If Messages()\MessageId + 1 > BakaShrot_Storage_Writer\NextIds()
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user