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:
@@ -34,6 +34,8 @@
|
||||
; ============================================================================
|
||||
|
||||
XIncludeFile "../../Commons/Networking/Names.pbi"
|
||||
; #BakaShrot_MaxAttachmentSize.
|
||||
XIncludeFile "../../Commons/Networking/Packets.pbi"
|
||||
|
||||
|
||||
; Some topics or nodes, or all of them: what a topic list (or node list)
|
||||
@@ -228,6 +230,16 @@ Structure BakaShrot_ServerConfig
|
||||
; max age ([BakaShrot.Retention]). Default 60.
|
||||
RetentionInterval.i
|
||||
|
||||
; Biggest attachment this server takes, in bytes: pushed with a message,
|
||||
; or replicated (a bigger one's message is kept, not its attachment).
|
||||
; Written with a unit: 500M, 1G (K M G T, 1024-based). Default 1G.
|
||||
MaxAttachmentSize.q
|
||||
MaxAttachmentSizeText.s
|
||||
|
||||
; Seconds an upload may take, before it's pushed with its message: past
|
||||
; that it's deleted. Default 3600.
|
||||
UploadTimeout.i
|
||||
|
||||
EndStructure
|
||||
|
||||
|
||||
@@ -283,6 +295,8 @@ Macro Ptr_BakaShrot_CoreConfig : i : EndMacro
|
||||
#BakaShrot_Config_DefaultPeerSyncInterval = 5
|
||||
#BakaShrot_Config_DefaultPeerBatchSize = 100
|
||||
#BakaShrot_Config_DefaultRetentionInterval = 60
|
||||
#BakaShrot_Config_DefaultMaxAttachmentSize = "1G"
|
||||
#BakaShrot_Config_DefaultUploadTimeout = 3600
|
||||
|
||||
; What ReadPreferenceString() returns for a missing key, to tell it from an
|
||||
; empty one: an empty PushTopics allows nothing, a missing one the default.
|
||||
@@ -422,6 +436,38 @@ Procedure.q ParseRetentionAge(Text.s)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; A size as MaxAttachmentSize writes it ("500M", "1G", "1048576") in bytes,
|
||||
; -1 if it isn't one. Units are 1024-based: K M G T.
|
||||
Procedure.q ParseConfigSize(Text.s)
|
||||
Protected Unit.q = 1, Digits.s, Last.s, i.i
|
||||
|
||||
Text = UCase(Trim(Text))
|
||||
If Text = ""
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
Last = Right(Text, 1)
|
||||
Select Last
|
||||
Case "K" : Unit = 1024
|
||||
Case "M" : Unit = 1024 * 1024
|
||||
Case "G" : Unit = 1024 * 1024 * 1024
|
||||
Case "T" : Unit = 1024 * 1024 * 1024 * 1024
|
||||
EndSelect
|
||||
Digits = Text
|
||||
If Unit > 1
|
||||
Digits = Left(Text, Len(Text) - 1)
|
||||
EndIf
|
||||
If Digits = "" Or Len(Digits) > 13
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
For i = 1 To Len(Digits)
|
||||
If Mid(Digits, i, 1) < "0" Or Mid(Digits, i, 1) > "9"
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
Next
|
||||
ProcedureReturn Val(Digits) * Unit
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Reads [BakaShrot.Retention] into *Config\Retention().
|
||||
; Returns #False on an invalid line, with the reason in BakaShrot_ConfigError.
|
||||
Procedure.i ParseRetentionSection(*Config.BakaShrot_CoreConfig)
|
||||
@@ -835,6 +881,17 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] RetentionInterval must be 1 second or more"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\Server\MaxAttachmentSizeText = Trim(ReadPreferenceString("MaxAttachmentSize", #BakaShrot_Config_DefaultMaxAttachmentSize))
|
||||
*Config\Server\MaxAttachmentSize = ParseConfigSize(*Config\Server\MaxAttachmentSizeText)
|
||||
If *Config\Server\MaxAttachmentSize < 0 Or *Config\Server\MaxAttachmentSize > #BakaShrot_MaxAttachmentSize
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] MaxAttachmentSize = '" + *Config\Server\MaxAttachmentSizeText + "' isn't a size up to 1T: bytes, or a number with K, M, G or T, like 500M (0: no attachments)"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\Server\UploadTimeout = ReadPreferenceLong("UploadTimeout", #BakaShrot_Config_DefaultUploadTimeout)
|
||||
If *Config\Server\UploadTimeout < 10
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] UploadTimeout must be 10 seconds or more"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "")
|
||||
If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics")
|
||||
Goto LoadFailed
|
||||
@@ -997,6 +1054,8 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
|
||||
WritePreferenceLong("PeerSyncInterval", *Config\Server\PeerSyncInterval)
|
||||
WritePreferenceLong("PeerBatchSize", *Config\Server\PeerBatchSize)
|
||||
WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval)
|
||||
WritePreferenceString("MaxAttachmentSize", *Config\Server\MaxAttachmentSizeText)
|
||||
WritePreferenceLong("UploadTimeout", *Config\Server\UploadTimeout)
|
||||
|
||||
PreferenceGroup("BakaShrot.Topics")
|
||||
ForEach *Config\TopicNames()
|
||||
|
||||
@@ -102,9 +102,18 @@ PeerSyncInterval = 5
|
||||
PeerBatchSize = 100
|
||||
|
||||
; Seconds between two passes deleting the messages past their topic's age
|
||||
; ([BakaShrot.Retention] above). Only runs if a topic has one.
|
||||
; ([BakaShrot.Retention] above), and the attachments' leftovers.
|
||||
RetentionInterval = 60
|
||||
|
||||
; Biggest attachment this server takes (one per message, see
|
||||
; Design/Attachments.md): pushed to it, or replicated (a bigger one's message
|
||||
; is kept, its attachment isn't). Bytes, or K M G T (1024-based). 0: none.
|
||||
MaxAttachmentSize = 1G
|
||||
|
||||
; Seconds a client may take to upload an attachment and push its message,
|
||||
; after which the upload is deleted.
|
||||
UploadTimeout = 3600
|
||||
|
||||
|
||||
; One [BakaShrot.Peer.<name>] section per peer this node talks to.
|
||||
; <name> is only a key for this file; it is never sent on the wire.
|
||||
|
||||
@@ -17,10 +17,12 @@
|
||||
;
|
||||
; Once authenticated, a client's thread answers its requests one at a time
|
||||
; until it disconnects: PushMessage, GetLatestMessage, GetMessages,
|
||||
; QueryRequest, ResolveName and ListNames, each one only if its
|
||||
; QueryRequest, ResolveName and ListNames, UploadStart, UploadChunk and
|
||||
; GetAttachment (Design/Attachments.md), each one only if its
|
||||
; [BakaShrot.Client.<name>] allows it (AllowWrite and PushTopics, AllowRead
|
||||
; and ReadTopics, AllowQuery), and for
|
||||
; peers, SyncStateRequest and ReplicateMessages, refused for regular clients,
|
||||
; peers, SyncStateRequest and ReplicateMessages, then MissingAttachmentsRequest
|
||||
; and ReplicateAttachmentChunk, refused for regular clients,
|
||||
; within the peer's AcceptTopics and AcceptNodes. Any other packet aborts it.
|
||||
;
|
||||
; Topics and nodes come by name or id (Commons/Networking/Names.pbi), and
|
||||
@@ -421,7 +423,8 @@ EndProcedure
|
||||
Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||
Protected *View.MsgPackData, *Push.BakaShrot_PushMessage
|
||||
Protected Pushed.BakaShrot_MessagePushed
|
||||
Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String
|
||||
Protected JsonData.s, TopicRef.s, TopicId.i, JsonSize.i, MessageId.q, StoreError.String, UploadId.q
|
||||
Protected Blob.BakaShrot_StorageBlob
|
||||
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||
|
||||
*Push = 0
|
||||
@@ -436,6 +439,7 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *
|
||||
EndIf
|
||||
JsonData = *Push\JsonData
|
||||
TopicRef = *Push\Topic
|
||||
UploadId = *Push\UploadId
|
||||
FreeStructure(*Push)
|
||||
|
||||
; The node is the authenticated one, the client never sends it here.
|
||||
@@ -473,7 +477,20 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||
EndIf
|
||||
|
||||
MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError)
|
||||
; Its attachment: one of this client's complete uploads, for that topic.
|
||||
If UploadId
|
||||
If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload")
|
||||
EndIf
|
||||
If Blob\State <> #BakaShrot_Blob_Complete
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload isn't complete, or is attached already")
|
||||
EndIf
|
||||
If Blob\TopicId <> TopicId
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
|
||||
MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId)
|
||||
If MessageId < 1
|
||||
PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||
@@ -551,6 +568,8 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie
|
||||
Latest\MessageId = Message\MessageId
|
||||
Latest\PushedAt = Message\PushedAt
|
||||
Latest\JsonData = Message\JsonData
|
||||
Latest\AttachmentSize = Message\AttachmentSize
|
||||
Latest\AttachmentReady = Message\AttachmentReady
|
||||
*Answer = BakaShrot_LatestMessagePacket_Encode(@Latest, @AnswerSize)
|
||||
If Not *Answer
|
||||
ProcedureReturn #False
|
||||
@@ -636,6 +655,8 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, *
|
||||
Answer\Messages()\MessageId = Messages()\MessageId
|
||||
Answer\Messages()\PushedAt = Messages()\PushedAt
|
||||
Answer\Messages()\JsonData = Messages()\JsonData
|
||||
Answer\Messages()\AttachmentSize = Messages()\AttachmentSize
|
||||
Answer\Messages()\AttachmentReady = Messages()\AttachmentReady
|
||||
Next
|
||||
ClearList(Messages())
|
||||
|
||||
@@ -975,7 +996,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
If MaxAge > 0
|
||||
SkipBefore = BakaShrot_NowUtcMs() - MaxAge
|
||||
EndIf
|
||||
IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped)
|
||||
IsStored = InsertReplicatedMessages(TopicId, NodeId, *Batch\Messages(), @StoreError, SkipBefore, @Skipped, *Client\Server\Config\Server\MaxAttachmentSize)
|
||||
FreeStructure(*Batch)
|
||||
If #BakaShrot_Net_LogRequests And Skipped\i > 0
|
||||
PrintN("[Net] Skipped " + Str(Skipped\i) + " messages of " + TopicRef + ":" + NodeRef + " from peer '" + *Client\PeerName + "', past their max age here")
|
||||
@@ -996,6 +1017,358 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
ProcedureReturn Sent
|
||||
EndProcedure
|
||||
|
||||
; --- Attachments -----------------------------------------------------------------
|
||||
; See Design/Attachments.md and Storage/Attachments.pbi.
|
||||
|
||||
; Sends a ChunkStored. Returns #False if it couldn't be sent.
|
||||
Procedure.i BakaShrot_NetClient_SendChunkStored(*Client.BakaShrot_NetClient, Received.q, Complete.i)
|
||||
Protected Stored.BakaShrot_ChunkStored, *Answer, AnswerSize.Integer, Sent.i
|
||||
|
||||
Stored\Received = Received
|
||||
Stored\Complete = Complete
|
||||
*Answer = BakaShrot_ChunkStoredPacket_Encode(@Stored, @AnswerSize)
|
||||
If Not *Answer
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||
FreeMemory(*Answer)
|
||||
ProcedureReturn Sent
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Starts an upload, for a message the client will push to that topic.
|
||||
; Same permissions as pushing, and at most MaxAttachmentSize bytes.
|
||||
; Returns #False if the client must be aborted.
|
||||
Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||
Protected *View.MsgPackData, *Start.BakaShrot_UploadStart
|
||||
Protected Started.BakaShrot_UploadStarted
|
||||
Protected TopicRef.s, TopicId.i, Size.q, MaxSize.q, BlobId.q, StoreError.String
|
||||
Protected Dim Sha256.a(#BakaShrot_Sha256Size - 1)
|
||||
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||
|
||||
*Start = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||
If *View
|
||||
*Start = BakaShrot_UploadStartPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
If Not *Start
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload start")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
TopicRef = *Start\Topic
|
||||
Size = *Start\Size
|
||||
CopyMemory(@*Start\Sha256[0], @Sha256(0), #BakaShrot_Sha256Size)
|
||||
FreeStructure(*Start)
|
||||
|
||||
If Not *Client\Permissions\Write
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write")
|
||||
EndIf
|
||||
If TopicRef = ""
|
||||
TopicId = *Client\Metadata\TopicId
|
||||
Else
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
|
||||
MaxSize = *Client\Server\Config\Server\MaxAttachmentSize
|
||||
If Size > MaxSize
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here")
|
||||
EndIf
|
||||
|
||||
BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError)
|
||||
If Not BlobId
|
||||
PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be started")
|
||||
EndIf
|
||||
|
||||
Started\UploadId = BlobId
|
||||
Started\ChunkSize = #BakaShrot_AttachmentChunkSize
|
||||
*Answer = BakaShrot_UploadStartedPacket_Encode(@Started, @AnswerSize)
|
||||
If Not *Answer
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||
FreeMemory(*Answer)
|
||||
ProcedureReturn Sent
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Stores the next part of one of this client's uploads. Once all of it is
|
||||
; here, checks its SHA-256: complete, or dropped and refused.
|
||||
; Returns #False if the client must be aborted.
|
||||
Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||
Protected *View.MsgPackData, *Chunk.BakaShrot_UploadChunk
|
||||
Protected Blob.BakaShrot_StorageBlob, Received.q, StoreError.String, Expected.i
|
||||
|
||||
*Chunk = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||
If *View
|
||||
*Chunk = BakaShrot_UploadChunkPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
If Not *Chunk
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid upload chunk")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; Only its own uploads: same node, a topic it may still push to.
|
||||
If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload in progress")
|
||||
EndIf
|
||||
If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId))
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
EndIf
|
||||
Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex)
|
||||
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes")
|
||||
EndIf
|
||||
|
||||
Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError)
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
If Received < 0
|
||||
PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||
EndIf
|
||||
|
||||
If Received < Blob\Size
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False)
|
||||
EndIf
|
||||
|
||||
; All of it: the SHA-256 given at the start must match.
|
||||
If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0])
|
||||
SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload doesn't match its SHA-256, it's dropped")
|
||||
EndIf
|
||||
If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be stored")
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Answers with a part of a message's attachment, same permissions as
|
||||
; reading the message. Refuses one that isn't all here yet.
|
||||
; Returns #False if the client must be aborted.
|
||||
Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||
Protected *View.MsgPackData, *Request.BakaShrot_GetAttachment
|
||||
Protected Chunk.BakaShrot_AttachmentChunk, Attachment.BakaShrot_StorageAttachment
|
||||
Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, Index.q, DataSize.Integer
|
||||
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||
|
||||
*Request = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||
If *View
|
||||
*Request = BakaShrot_GetAttachmentPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
If Not *Request
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment request")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
TopicRef = *Request\Topic
|
||||
NodeRef = *Request\Node
|
||||
MessageId = *Request\MessageId
|
||||
Index = *Request\ChunkIndex
|
||||
FreeStructure(*Request)
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
EndIf
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId))
|
||||
EndIf
|
||||
Select Attachment\State
|
||||
Case #BakaShrot_Attachment_NotKept
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize")
|
||||
Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes")
|
||||
EndSelect
|
||||
If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts")
|
||||
EndIf
|
||||
|
||||
Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize)
|
||||
If Not Chunk\Data
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be read")
|
||||
EndIf
|
||||
Chunk\DataSize = DataSize\i
|
||||
Chunk\TopicId = TopicId
|
||||
Chunk\NodeId = NodeId
|
||||
Chunk\MessageId = MessageId
|
||||
Chunk\Size = Attachment\Size
|
||||
Chunk\ChunkIndex = Index
|
||||
CopyMemory(@Attachment\Sha256[0], @Chunk\Sha256[0], #BakaShrot_Sha256Size)
|
||||
*Answer = BakaShrot_AttachmentChunkPacket_Encode(@Chunk, @AnswerSize)
|
||||
FreeMemory(Chunk\Data)
|
||||
If Not *Answer
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||
FreeMemory(*Answer)
|
||||
ProcedureReturn Sent
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Tells a peer which attachments this server is missing, among what it
|
||||
; takes from it (AcceptTopics, AcceptNodes): the peer sends what it has.
|
||||
; Returns #False if the client must be aborted.
|
||||
Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||
Protected *View.MsgPackData, *Request.BakaShrot_MissingAttachmentsRequest
|
||||
Protected Answer.BakaShrot_MissingAttachments
|
||||
Protected NewList Missing.BakaShrot_StorageMissingAttachment()
|
||||
Protected *Answer, AnswerSize.Integer, Sent.i
|
||||
|
||||
*Request = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||
If *View
|
||||
*Request = BakaShrot_MissingAttachmentsRequestPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
If Not *Request
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid missing attachments request")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
FreeStructure(*Request)
|
||||
|
||||
If *Client\PeerName = ""
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
; More than one answer holds, some of them may be someone else's.
|
||||
If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing())
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The missing attachments couldn't be read")
|
||||
EndIf
|
||||
ForEach Missing()
|
||||
If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments
|
||||
Break
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\AcceptTopics, Missing()\TopicId, Missing()\Topic) Or Not NameSetHas(@*Client\AcceptNodes, Missing()\NodeId, Missing()\Node)
|
||||
Continue
|
||||
EndIf
|
||||
If Not BakaShrot_IsValidName(Missing()\Topic) Or Not BakaShrot_IsValidName(Missing()\Node)
|
||||
Continue
|
||||
EndIf
|
||||
AddElement(Answer\Attachments())
|
||||
Answer\Attachments()\Topic = Missing()\Topic
|
||||
Answer\Attachments()\Node = Missing()\Node
|
||||
Answer\Attachments()\MessageId = Missing()\MessageId
|
||||
Answer\Attachments()\NextChunk = Missing()\Received / #BakaShrot_AttachmentChunkSize
|
||||
Next
|
||||
|
||||
*Answer = BakaShrot_MissingAttachmentsPacket_Encode(@Answer, @AnswerSize)
|
||||
If Not *Answer
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Sent = BakaShrot_SendPacket(*Client\ClientId, *Answer, AnswerSize\i, @*Client\Metadata\Cipher)
|
||||
FreeMemory(*Answer)
|
||||
ProcedureReturn Sent
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Stores a part of an attachment a peer replicates, of a message this server
|
||||
; already has: in order, resuming where a previous link stopped. Once all of
|
||||
; it is here, checks its SHA-256 (the one its message came with): ready, or
|
||||
; dropped to be sent again.
|
||||
; Returns #False if the client must be aborted.
|
||||
Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot_NetClient, *Packet, PacketSize.i)
|
||||
Protected *View.MsgPackData, *Chunk.BakaShrot_ReplicateAttachmentChunk
|
||||
Protected Attachment.BakaShrot_StorageAttachment
|
||||
Protected TopicId.i, NodeId.i, TopicRef.s, NodeRef.s, MessageId.q, BlobId.q, Received.q, IsValid.i, StoreError.String
|
||||
|
||||
*Chunk = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
|
||||
If *View
|
||||
*Chunk = BakaShrot_ReplicateAttachmentChunkPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
If Not *Chunk
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an invalid attachment chunk")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
TopicRef = *Chunk\Topic
|
||||
NodeRef = *Chunk\Node
|
||||
MessageId = *Chunk\MessageId
|
||||
|
||||
If *Client\PeerName = ""
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
EndIf
|
||||
TopicId = BakaShrot_Names_TopicByName(TopicRef)
|
||||
NodeId = BakaShrot_Names_NodeByName(NodeRef)
|
||||
If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here")
|
||||
EndIf
|
||||
|
||||
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId))
|
||||
EndIf
|
||||
If Attachment\State = #BakaShrot_Attachment_Ready
|
||||
; Someone else's link was faster: done.
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Attachment\Size, #True)
|
||||
EndIf
|
||||
If Attachment\State = #BakaShrot_Attachment_NotKept
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here")
|
||||
EndIf
|
||||
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize))
|
||||
EndIf
|
||||
|
||||
BlobId = Attachment\BlobId
|
||||
If Not BlobId
|
||||
BlobId = StartReplicatedAttachment(TopicId, NodeId, MessageId, @StoreError)
|
||||
EndIf
|
||||
If BlobId
|
||||
Received = StoreStorageBlobChunk(BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError)
|
||||
Else
|
||||
Received = -1
|
||||
EndIf
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
If Received < 0
|
||||
PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||
EndIf
|
||||
|
||||
If Received < Attachment\Size
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #False)
|
||||
EndIf
|
||||
|
||||
IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0])
|
||||
If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be stored")
|
||||
EndIf
|
||||
If Not IsValid
|
||||
PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment doesn't match its SHA-256, send it again")
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Handles one request from an authenticated client.
|
||||
; Returns #False if the client must be aborted.
|
||||
@@ -1024,6 +1397,21 @@ Procedure.i BakaShrot_NetClient_HandleRequest(*Client.BakaShrot_NetClient, *Pack
|
||||
|
||||
Case #BakaShrot_PacketType_ReplicateMessages
|
||||
ProcedureReturn BakaShrot_NetClient_HandleReplicateMessages(*Client, *Packet, PacketSize)
|
||||
|
||||
Case #BakaShrot_PacketType_UploadStart
|
||||
ProcedureReturn BakaShrot_NetClient_HandleUploadStart(*Client, *Packet, PacketSize)
|
||||
|
||||
Case #BakaShrot_PacketType_UploadChunk
|
||||
ProcedureReturn BakaShrot_NetClient_HandleUploadChunk(*Client, *Packet, PacketSize)
|
||||
|
||||
Case #BakaShrot_PacketType_GetAttachment
|
||||
ProcedureReturn BakaShrot_NetClient_HandleGetAttachment(*Client, *Packet, PacketSize)
|
||||
|
||||
Case #BakaShrot_PacketType_MissingAttachmentsRequest
|
||||
ProcedureReturn BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client, *Packet, PacketSize)
|
||||
|
||||
Case #BakaShrot_PacketType_ReplicateAttachmentChunk
|
||||
ProcedureReturn BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client, *Packet, PacketSize)
|
||||
EndSelect
|
||||
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unexpected packet")
|
||||
|
||||
+148
-1
@@ -27,6 +27,10 @@
|
||||
; bigger message goes alone, see ReplicateMessagesPacket.pbi), each
|
||||
; batch stored in one transaction and answered before the next. The
|
||||
; batches carry the names, the peer stores them under its own ids.
|
||||
; A message's attachment only has its size and SHA-256 in the batch.
|
||||
; 4. Once the messages are caught up, asks the peer which attachments it's
|
||||
; missing (MissingAttachmentsRequest) and sends those it has, a part
|
||||
; (1 MB) per request, from where the peer stopped (Design/Attachments.md).
|
||||
; The peer does the same over its own link to this server, which covers the
|
||||
; other direction. Any packet from the peer outside of a check-in drops the
|
||||
; link as unexpected.
|
||||
@@ -143,6 +147,144 @@ Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, Ans
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Sends the peer the attachment it's missing, *Missing, from the part it
|
||||
; asked for on, if this server has all of it and sends that topic/node to it.
|
||||
; Returns 1 once the peer has it, 0 if it's skipped (not here, not sent to
|
||||
; that peer, refused: logged), -1 if the link must be dropped.
|
||||
Procedure.i BakaShrot_PeerLink_SendAttachment(*Link.BakaShrot_PeerLink, *Missing.BakaShrot_MissingAttachment)
|
||||
Protected *Links.BakaShrot_PeerLinks = *Link\Links
|
||||
Protected Attachment.BakaShrot_StorageAttachment, Chunk.BakaShrot_ReplicateAttachmentChunk
|
||||
Protected *Stored.BakaShrot_ChunkStored
|
||||
Protected TopicId.i, NodeId.i, Index.q, Count.q, DataSize.Integer, Complete.i
|
||||
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
|
||||
|
||||
TopicId = BakaShrot_Names_TopicByName(*Missing\Topic)
|
||||
NodeId = BakaShrot_Names_NodeByName(*Missing\Node)
|
||||
If TopicId < 0 Or NodeId < 0
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
If Not NameSetHas(@*Link\SendTopics, TopicId, *Missing\Topic) Or Not NameSetHas(@*Link\SendNodes, NodeId, *Missing\Node)
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
; Not here either (yet, or not kept): another server may have it.
|
||||
If Not GetStorageAttachment(*Link\DbId, TopicId, NodeId, *Missing\MessageId, @Attachment) Or Attachment\State <> #BakaShrot_Attachment_Ready
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
Count = BakaShrot_AttachmentChunkCount(Attachment\Size)
|
||||
Chunk\Topic = *Missing\Topic
|
||||
Chunk\Node = *Missing\Node
|
||||
Chunk\MessageId = *Missing\MessageId
|
||||
For Index = *Missing\NextChunk To Count - 1
|
||||
If *Links\StopRequested
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
|
||||
Chunk\ChunkIndex = Index
|
||||
Chunk\Data = ReadStorageBlobChunk(*Link\DbId, Attachment\BlobId, Index, @DataSize)
|
||||
If Not Chunk\Data
|
||||
PrintN("[Peer] Can't read part " + Str(Index) + " of the attachment of " + *Missing\Topic + ":" + *Missing\Node + "#" + Str(*Missing\MessageId) + " for '" + *Link\Name + "'")
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
Chunk\DataSize = DataSize\i
|
||||
*Packet = BakaShrot_ReplicateAttachmentChunkPacket_Encode(@Chunk, @PacketSize)
|
||||
FreeMemory(Chunk\Data)
|
||||
Chunk\Data = 0
|
||||
If Not *Packet
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
If Not *Answer
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
|
||||
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
|
||||
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
|
||||
FreeMemory(*Answer)
|
||||
If Not IsRefusal
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
*Stored = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||
If *View
|
||||
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
FreeMemory(*Answer)
|
||||
If Not *Stored
|
||||
PrintN("[Peer] '" + *Link\Name + "' sent an invalid answer to an attachment's part")
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
Complete = *Stored\Complete
|
||||
FreeStructure(*Stored)
|
||||
If Complete
|
||||
ProcedureReturn 1
|
||||
EndIf
|
||||
Next
|
||||
|
||||
; All sent, and the peer didn't say it's complete: it'll ask again.
|
||||
ProcedureReturn 0
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Once the messages are caught up: asks the peer which attachments it's
|
||||
; missing, and sends those this server has, one after the other.
|
||||
; Returns #False if the link must be dropped.
|
||||
Procedure.i BakaShrot_PeerLink_SendAttachments(*Link.BakaShrot_PeerLink)
|
||||
Protected Request.BakaShrot_MissingAttachmentsRequest, *Missing.BakaShrot_MissingAttachments
|
||||
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData, IsRefusal.i
|
||||
Protected Result.i, StartTime.i, Attachment.BakaShrot_StorageAttachment, Key.s
|
||||
|
||||
*Packet = BakaShrot_MissingAttachmentsRequestPacket_Encode(@Request, @PacketSize)
|
||||
If Not *Packet
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
*Answer = BakaShrot_PeerLink_Request(*Link, *Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
If Not *Answer
|
||||
PrintN("[Peer] '" + *Link\Name + "' didn't answer which attachments it's missing")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
If BakaShrot_GetPacketType(*Answer, AnswerSize\i) = #BakaShrot_PacketType_RequestRefused
|
||||
IsRefusal = BakaShrot_PeerLink_LogRefusal(*Link, *Answer, AnswerSize\i)
|
||||
FreeMemory(*Answer)
|
||||
ProcedureReturn IsRefusal
|
||||
EndIf
|
||||
|
||||
*Missing = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
|
||||
If *View
|
||||
*Missing = BakaShrot_MissingAttachmentsPacket_Decode(*View)
|
||||
MsgPackFree(*View, #False)
|
||||
EndIf
|
||||
FreeMemory(*Answer)
|
||||
If Not *Missing
|
||||
PrintN("[Peer] '" + *Link\Name + "' sent an invalid list of missing attachments")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
ForEach *Missing\Attachments()
|
||||
StartTime = ElapsedMilliseconds()
|
||||
Result = BakaShrot_PeerLink_SendAttachment(*Link, @*Missing\Attachments())
|
||||
If Result < 0
|
||||
FreeStructure(*Missing)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If Result > 0
|
||||
Key = *Missing\Attachments()\Topic + ":" + *Missing\Attachments()\Node + "#" + Str(*Missing\Attachments()\MessageId)
|
||||
PrintN("[Peer] Sent the attachment of " + Key + " to '" + *Link\Name + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms, from part " + Str(*Missing\Attachments()\NextChunk))
|
||||
EndIf
|
||||
Next
|
||||
FreeStructure(*Missing)
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Sends a batch of messages the peer is missing and checks its answer.
|
||||
; Returns 1 once stored, 0 if the peer refused it (logged), or -1 if the
|
||||
; link must be dropped.
|
||||
@@ -242,6 +384,10 @@ Procedure.i BakaShrot_PeerLink_SendMissing(*Link.BakaShrot_PeerLink, TopicId.i,
|
||||
; As stored: when it was pushed to its origin, whichever server that was.
|
||||
Batch\Messages()\PushedAt = Messages()\PushedAt
|
||||
Batch\Messages()\JsonData = Messages()\JsonData
|
||||
; Its attachment's size and SHA-256 only: the data goes once the
|
||||
; messages are caught up (BakaShrot_PeerLink_SendAttachments()).
|
||||
Batch\Messages()\AttachmentSize = Messages()\AttachmentSize
|
||||
CopyMemory(@Messages()\AttachmentSha256[0], @Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
|
||||
Next
|
||||
|
||||
If ListSize(Batch\Messages()) = 0
|
||||
@@ -394,7 +540,8 @@ Procedure.i BakaShrot_PeerLink_CheckIn(*Link.BakaShrot_PeerLink)
|
||||
EndIf
|
||||
Next
|
||||
|
||||
ProcedureReturn #True
|
||||
; 4. Then the attachments: only for messages the peer has now.
|
||||
ProcedureReturn BakaShrot_PeerLink_SendAttachments(*Link)
|
||||
EndProcedure
|
||||
|
||||
|
||||
|
||||
@@ -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