1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00
Files
BakaShrot/Server/Storage/Retention.pbi
T
aziascreations df61ef9719 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
2026-11-08 18:56:15 +01:00

198 lines
7.0 KiB
Plaintext

; ============================================================================
; BakaShrot Storage Retention
;
; Deletes the messages past their topic's max age, so a server's database
; stops growing: [BakaShrot.Retention] in its config, see
; BakaShrot_RetentionRule in Server/Config/Config.pbi.
;
; A thread, started with the workers (StartStorageRetention(), see
; Server/Root.pbi), runs a pass right away then every [BakaShrot.Server]
; RetentionInterval seconds:
; - every topic of the database (node_heads), with its name (topics);
; - its max age from the rules; kept forever (0) is skipped;
; - deletes its messages pushed (pushed_at) before now minus that age,
; #BakaShrot_Retention_BatchSize at a time through the writer
; (DeleteStorageMessagesBefore(), Writer.pbi), so pushes go on between
; the batches;
; - then the attachments' leftovers (CleanUpStorageBlobs(),
; Attachments.pbi): those of the deleted messages, and uploads not
; pushed with a message within [BakaShrot.Server] UploadTimeout,
; #BakaShrot_Retention_ChunkBatchSize parts at a time.
; It runs without any [BakaShrot.Retention] too, for the leftovers.
;
; Messages "may be" deleted past their max age: up to RetentionInterval
; later. Those a peer replicates here already past it aren't stored at all
; (InsertReplicatedMessages() in Writer.pbi), only counted as received. pushed_at is the time the message was pushed to its origin, kept as
; is by replication, so a server deletes a replicated message by when it
; was first pushed, not when it got it.
;
; What deleting doesn't change:
; - node_heads: a pair's head stays its highest id ever. The next push
; still gets the next id, and the sync state still tells peers this
; server had those messages: they aren't sent again.
; - The file's size: SQLite reuses the freed pages for new messages, so
; it stops growing once deletions keep up with pushes. VACUUM (the
; "vacuum" console command) gives the space back to the disk.
; ============================================================================
; Most messages deleted in one statement, under the write mutex: a few ms.
#BakaShrot_Retention_BatchSize = 5000
; Most attachment parts (1 MB each) deleted in one statement.
#BakaShrot_Retention_ChunkBatchSize = 32
Structure BakaShrot_RetentionTopic
TopicId.i
Name.s
EndStructure
Structure BakaShrot_RetentionState
ThreadId.i
StopRequested.i
IntervalMs.i
UploadTimeoutMs.q
DatabasePath.s
List Rules.BakaShrot_RetentionRule()
EndStructure
Global BakaShrot_Retention.BakaShrot_RetentionState
; Ms (since 1970 UTC) as "2026-11-08T14:03:59Z", for the logs.
Procedure.s BakaShrot_Retention_FormatUtc(Ms.q)
ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ssZ", Ms / 1000)
EndProcedure
; Deletes the attachments' leftovers, a few parts at a time.
Procedure BakaShrot_Retention_CleanUp()
Protected Deleted.i, Total.q, Error.String
Repeat
Deleted = CleanUpStorageBlobs(BakaShrot_NowUtcMs() - BakaShrot_Retention\UploadTimeoutMs, #BakaShrot_Retention_ChunkBatchSize, @Error)
If Deleted < 0
PrintN("[Storage] Retention: failed to delete the attachments' leftovers: " + Error\s)
Break
EndIf
Total + Deleted
Until Deleted < #BakaShrot_Retention_ChunkBatchSize Or BakaShrot_Retention\StopRequested
If Total > 0
PrintN("[Storage] Retention: deleted " + Str(Total) + " attachment parts (of deleted messages, or uploads never pushed)")
EndIf
EndProcedure
; Deletes what's past its max age in every topic. DbId is the thread's own
; connection, only read from (the deletes go through the writer).
; Returns how many messages were deleted.
Procedure.q BakaShrot_Retention_Pass(DbId.i)
Protected NewList Topics.BakaShrot_RetentionTopic()
Protected MaxAge.q, Before.q, Deleted.i, TopicDeleted.q, Total.q, Error.String
If Not DatabaseQuery(DbId, "SELECT DISTINCT h.topic_id, COALESCE(t.name, '') FROM node_heads h LEFT JOIN topics t ON t.topic_id = h.topic_id")
PrintN("[Storage] Retention: can't list the topics: " + DatabaseError())
ProcedureReturn 0
EndIf
While NextDatabaseRow(DbId)
AddElement(Topics())
Topics()\TopicId = GetDatabaseLong(DbId, 0)
Topics()\Name = GetDatabaseString(DbId, 1)
Wend
FinishDatabaseQuery(DbId)
ForEach Topics()
MaxAge = RetentionMaxAgeMs(BakaShrot_Retention\Rules(), Topics()\TopicId, Topics()\Name)
If MaxAge <= 0
Continue
EndIf
Before = BakaShrot_NowUtcMs() - MaxAge
TopicDeleted = 0
Repeat
Deleted = DeleteStorageMessagesBefore(Topics()\TopicId, Before, #BakaShrot_Retention_BatchSize, @Error)
If Deleted < 0
PrintN("[Storage] Retention: failed to delete from topic " + Str(Topics()\TopicId) + ": " + Error\s)
Break
EndIf
TopicDeleted + Deleted
Until Deleted < #BakaShrot_Retention_BatchSize Or BakaShrot_Retention\StopRequested
If TopicDeleted > 0
If Topics()\Name <> ""
PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic '" + Topics()\Name + "' pushed before " + BakaShrot_Retention_FormatUtc(Before))
Else
PrintN("[Storage] Retention: deleted " + Str(TopicDeleted) + " messages of topic " + Str(Topics()\TopicId) + " pushed before " + BakaShrot_Retention_FormatUtc(Before))
EndIf
EndIf
Total + TopicDeleted
If BakaShrot_Retention\StopRequested
Break
EndIf
Next
BakaShrot_Retention_CleanUp()
ProcedureReturn Total
EndProcedure
Procedure BakaShrot_Retention_Thread(Unused.i)
Protected DbId.i, LastPass.i
DbId = OpenStorageDatabase(BakaShrot_Retention\DatabasePath)
If Not DbId
PrintN("[Storage] Retention: can't open the database, nothing will be deleted: " + DatabaseError())
ProcedureReturn
EndIf
BakaShrot_Retention_Pass(DbId)
LastPass = ElapsedMilliseconds()
While Not BakaShrot_Retention\StopRequested
Delay(100)
If ElapsedMilliseconds() - LastPass >= BakaShrot_Retention\IntervalMs
BakaShrot_Retention_Pass(DbId)
LastPass = ElapsedMilliseconds()
EndIf
Wend
CloseDatabase(DbId)
EndProcedure
; Starts deleting what's past *Config's [BakaShrot.Retention] max ages, and
; the attachments' leftovers, once the writer is open.
; Returns #False if the thread can't start.
Procedure.i StartStorageRetention(*Config.BakaShrot_CoreConfig)
With BakaShrot_Retention
ClearList(\Rules())
CopyList(*Config\Retention(), \Rules())
ForEach \Rules()
If \Rules()\MaxAgeMs > 0
PrintN("[Storage] Retention: " + \Rules()\Ref + " = " + \Rules()\AgeText + ", checked every " + Str(*Config\Server\RetentionInterval) + " s")
EndIf
Next
\DatabasePath = *Config\Server\DatabasePath
\IntervalMs = *Config\Server\RetentionInterval * 1000
\UploadTimeoutMs = *Config\Server\UploadTimeout * 1000
\StopRequested = #False
\ThreadId = CreateThread(@BakaShrot_Retention_Thread(), 0)
ProcedureReturn Bool(\ThreadId)
EndWith
EndProcedure
; Stops it, before the writer closes. Waits for a pass under way to end its
; current batch.
Procedure StopStorageRetention()
With BakaShrot_Retention
If \ThreadId
\StopRequested = #True
WaitThread(\ThreadId)
\ThreadId = 0
EndIf
EndWith
EndProcedure