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

Add pushed_at timestamps and per-topic retention

- Every message is stamped with the time its push arrived (UTC ms since
  1970, the server's clock), carried as is by replication. Exposed in
  LatestMessage and Messages, BakaShrot_GetMessagePushedAt() in the DLL,
  Message.pushed_at / .pushed in Python, GetMessages --time,
  GetLatestMessage, and the messages view (pushed_at, pushed_utc).
- [BakaShrot.Retention] in each server's config: a max age per topic, by
  name, id, pattern or *, ages like 30d or 1d12h. A background pass
  (Server/Storage/Retention.pbi, every RetentionInterval seconds) deletes
  what's older, in batches through the writer. node_heads is left as is,
  so ids never go back and peers don't resend what was deleted.
- Replicated messages already past the receiver's max age are skipped on
  arrival, their head still raised so they aren't sent again.
- Schema v6: data.pushed_at (older databases stamped at upgrade time),
  a (topic_id, pushed_at) index, the unused archives table dropped. The
  writer takes the next id from node_heads.
- Folded into protocol 3, not released yet.
- Tests/Retention-Test.ps1 (52 checks), Python checks for pushed_at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVPXGLs3KK1MAQn3ouP
This commit is contained in:
2026-11-08 17:01:48 +01:00
parent 12fbe5f4da
commit 9caf816dca
26 changed files with 1327 additions and 54 deletions
+135 -15
View File
@@ -2,8 +2,11 @@
; BakaShrot Storage Writer
;
; Every write the server does to its database goes through here:
; InsertNextMessage() pushes, grouped (group commit)
; InsertReplicatedMessages() batches from peers
; InsertNextMessage() pushes, grouped (group commit), stamped
; with the time they arrived (pushed_at)
; InsertReplicatedMessages() batches from peers, with their pushed_at,
; skipping those already past their max age
; DeleteStorageMessagesBefore() the retention (Retention.pbi)
; on ONE connection, the writer, only ever used while holding
; BakaShrot_Storage_WriteMutex. Opened by OpenStorageWriter() when the
; workers start, closed by CloseStorageWriter() once they're stopped (see
@@ -21,7 +24,8 @@
; functions are used instead (slower, same behaviour).
; - The next message id of every topic/node id kept in memory, instead of
; a MAX(message_id) on every push. Read from the database the first time
; a pair is pushed to, raised by the replicated messages, forgotten on a
; a pair is pushed to (node_heads, which deleting messages leaves as is:
; ids never go back), raised by the replicated messages, forgotten on a
; rollback. Only right as long as this writer is the only one writing,
; which the write mutex ensures within the server.
; - Checkpoints mostly off the write path: the writer only checkpoints by
@@ -104,6 +108,8 @@ Structure BakaShrot_PushJob
TopicId.i
NodeId.i
JsonData.s
; When it arrived, ms since 1970 UTC.
PushedAt.q
; Filled in by whoever writes it, under the write mutex.
MessageId.q
@@ -132,6 +138,8 @@ Structure BakaShrot_StorageWriter
Insert.i
InsertOrIgnore.i
MaxId.i
Delete.i
RaiseHead.i
; "TopicId:NodeId" -> the next message id to hand out.
Map NextIds.q()
@@ -255,7 +263,7 @@ EndProcedure
; Inserts one row with Statement (Insert or InsertOrIgnore).
; Returns 1 if inserted, 0 if ignored, -1 if it failed.
Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s)
Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Result.l
@@ -264,6 +272,7 @@ Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, Message
BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId)
; Static: JsonData outlives the step, the next insert binds it again.
BakaShrot_Sqlite\BindText16(Statement, 4, @JsonData, -1, #BakaShrot_Sqlite_Static)
BakaShrot_Sqlite\BindInt64(Statement, 5, PushedAt)
Result = BakaShrot_Sqlite\Step_(Statement)
If Result <> #BakaShrot_Sqlite_Done
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
@@ -278,6 +287,7 @@ Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, Message
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
SetDatabaseQuad(DbId, 4, PushedAt)
If Not DatabaseUpdate(DbId, PeekS(Statement))
BakaShrot_Storage_Writer\LastError = DatabaseError()
ProcedureReturn -1
@@ -287,7 +297,8 @@ Procedure.i BakaShrot_Writer_InsertRow(Statement.i, TopicId.i, NodeId.i, Message
EndProcedure
; The highest message id stored for a topic/node id, 0 if none, -1 on failure.
; The highest message id ever stored for a topic/node id, 0 if none, -1 on
; failure. Still there once deleted: node_heads keeps it.
Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i)
Protected MaxId.q = -1
@@ -319,6 +330,35 @@ Procedure.q BakaShrot_Writer_ReadMaxId(TopicId.i, NodeId.i)
EndProcedure
; Raises a topic/node id's head (node_heads) to MessageId, if it's lower,
; like inserting that message would. Returns #False if it failed.
Procedure.i BakaShrot_Writer_RaiseHead(TopicId.i, NodeId.i, MessageId.q)
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Statement.i = BakaShrot_Storage_Writer\RaiseHead
BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId)
BakaShrot_Sqlite\BindInt64(Statement, 2, NodeId)
BakaShrot_Sqlite\BindInt64(Statement, 3, MessageId)
If BakaShrot_Sqlite\Step_(Statement) <> #BakaShrot_Sqlite_Done
BakaShrot_Storage_Writer\LastError = BakaShrot_Writer_Error()
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn #False
EndIf
BakaShrot_Sqlite\Reset(Statement)
ProcedureReturn #True
CompilerElse
Protected DbId.i = BakaShrot_Storage_Writer\DbId
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
If Not DatabaseUpdate(DbId, PeekS(BakaShrot_Storage_Writer\RaiseHead))
BakaShrot_Storage_Writer\LastError = DatabaseError()
ProcedureReturn #False
EndIf
ProcedureReturn #True
CompilerEndIf
EndProcedure
; The next message id to hand out for a topic/node id, -1 on failure.
Procedure.q BakaShrot_Writer_NextId(Key.s, TopicId.i, NodeId.i)
Protected MaxId.q
@@ -446,6 +486,8 @@ Procedure BakaShrot_Writer_Release()
BakaShrot_Writer_Finalize(@\Insert)
BakaShrot_Writer_Finalize(@\InsertOrIgnore)
BakaShrot_Writer_Finalize(@\MaxId)
BakaShrot_Writer_Finalize(@\Delete)
BakaShrot_Writer_Finalize(@\RaiseHead)
If \DbId
CloseDatabase(\DbId)
EndIf
@@ -503,10 +545,18 @@ Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String)
\Begin = BakaShrot_Writer_Prepare("BEGIN IMMEDIATE")
\Commit = BakaShrot_Writer_Prepare("COMMIT")
\Rollback = BakaShrot_Writer_Prepare("ROLLBACK")
\Insert = BakaShrot_Writer_Prepare("INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)")
\InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?1, ?2, ?3, ?4)")
\MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(message_id), 0) FROM data WHERE topic_id = ?1 AND node_id = ?2")
If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId
\Insert = BakaShrot_Writer_Prepare("INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?1, ?2, ?3, ?4, ?5)")
\InsertOrIgnore = BakaShrot_Writer_Prepare("INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?1, ?2, ?3, ?4, ?5)")
; node_heads first: it outlives the deleted messages. data too, in
; case a database was written to by something without the trigger.
\MaxId = BakaShrot_Writer_Prepare("SELECT COALESCE(MAX(m), 0) FROM (SELECT max_message_id AS m FROM node_heads WHERE topic_id = ?1 AND node_id = ?2 " +
"UNION ALL SELECT MAX(message_id) FROM data WHERE topic_id = ?1 AND node_id = ?2)")
; Some at a time (?3), so pushes get the write mutex in between.
\Delete = BakaShrot_Writer_Prepare("DELETE FROM data WHERE rowid IN (SELECT rowid FROM data WHERE topic_id = ?1 AND pushed_at < ?2 LIMIT ?3)")
; What the trigger does on an insert, for the messages skipped instead.
\RaiseHead = BakaShrot_Writer_Prepare("INSERT INTO node_heads (topic_id, node_id, max_message_id) VALUES (?1, ?2, ?3) " +
"ON CONFLICT (topic_id, node_id) DO UPDATE SET max_message_id = MAX(max_message_id, excluded.max_message_id)")
If Not \Begin Or Not \Commit Or Not \Rollback Or Not \Insert Or Not \InsertOrIgnore Or Not \MaxId Or Not \Delete Or Not \RaiseHead
*Error\s = "can't prepare its statements: " + \LastError
BakaShrot_Writer_Release()
UnlockMutex(BakaShrot_Storage_WriteMutex)
@@ -606,7 +656,7 @@ 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
If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData) = 1
If MessageId > 0 And BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\Insert, *Job\TopicId, *Job\NodeId, MessageId, JsonData, *Job\PushedAt) = 1
*Job\MessageId = MessageId
BakaShrot_Storage_Writer\NextIds(Key) = MessageId + 1
Else
@@ -635,7 +685,7 @@ EndProcedure
; Inserts one JSON message for a topic_id/node_id pair, with the next
; message_id for that pair, starting at 1, grouped with the other pushes
; arriving meanwhile. Returns the new message's id once committed, or -1 with
; arriving meanwhile. Stamped with the time it got here (pushed_at). Returns the new message's id once committed, or -1 with
; the reason in *Error\s.
Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
Protected Job.BakaShrot_PushJob
@@ -645,6 +695,7 @@ Procedure.q InsertNextMessage(TopicId.i, NodeId.i, JsonData.s, *Error.String)
Job\TopicId = TopicId
Job\NodeId = NodeId
Job\JsonData = JsonData
Job\PushedAt = BakaShrot_NowUtcMs()
Job\MessageId = -1
LockMutex(BakaShrot_Storage_QueueMutex)
@@ -703,12 +754,16 @@ EndProcedure
; Stores a batch of messages replicated from a peer, all of one topic/node
; id, under the ids they have on their origin, in a single transaction:
; id, under the ids and pushed_at they have on their origin, in a single transaction:
; either all of them are stored, or none. An id that's already stored is kept
; as is, the new one is dropped, even if it differs (Design/ReplicationIssues.md).
; Messages pushed before SkipBeforeMs (ms since 1970 UTC, 0 for none) are
; 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.
; Returns #False with the reason in *Error\s, the transaction is rolled back.
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String)
Protected Stored.i, Inserted.i, Key.s, JsonData.s
Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShrot_ReplicatedMessage(), *Error.String, SkipBeforeMs.q = 0, *Skipped.Integer = 0)
Protected Stored.i, Inserted.i, Key.s, JsonData.s, Skipped.i, LastMessageId.q
Key = Str(TopicId) + ":" + Str(NodeId)
@@ -724,8 +779,13 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro
Stored = BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Begin)
If Stored
ForEach Messages()
LastMessageId = Messages()\MessageId
If SkipBeforeMs > 0 And Messages()\PushedAt < SkipBeforeMs
Skipped + 1
Continue
EndIf
JsonData = Messages()\JsonData
Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData)
Inserted = BakaShrot_Writer_InsertRow(BakaShrot_Storage_Writer\InsertOrIgnore, TopicId, NodeId, Messages()\MessageId, JsonData, Messages()\PushedAt)
If Inserted < 0
Stored = #False
Break
@@ -738,6 +798,20 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro
EndIf
Next
; The skipped ones count as received: the head covers the whole batch,
; and the next push goes after it.
If Stored And Skipped > 0
If BakaShrot_Writer_RaiseHead(TopicId, NodeId, LastMessageId)
If FindMapElement(BakaShrot_Storage_Writer\NextIds(), Key)
If LastMessageId + 1 > BakaShrot_Storage_Writer\NextIds()
BakaShrot_Storage_Writer\NextIds() = LastMessageId + 1
EndIf
EndIf
Else
Stored = #False
EndIf
EndIf
If Stored And Not BakaShrot_Writer_Run(BakaShrot_Storage_Writer\Commit)
Stored = #False
EndIf
@@ -751,10 +825,56 @@ Procedure.i InsertReplicatedMessages(TopicId.i, NodeId.i, List Messages.BakaShro
EndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
If *Skipped
*Skipped\i = Skipped
EndIf
ProcedureReturn Stored
EndProcedure
; Deletes up to Limit messages of TopicId pushed before BeforeMs (ms since
; 1970 UTC), in one statement under the write mutex: call it again while it
; deletes Limit, pushes get their turn in between. node_heads is left as is
; (see SetupStorageDatabase()).
; Returns how many were deleted, -1 with the reason in *Error\s.
Procedure.i DeleteStorageMessagesBefore(TopicId.i, BeforeMs.q, Limit.i, *Error.String)
Protected Deleted.i = -1
LockMutex(BakaShrot_Storage_WriteMutex)
If Not BakaShrot_Storage_Writer\DbId
UnlockMutex(BakaShrot_Storage_WriteMutex)
*Error\s = "the storage writer isn't open"
ProcedureReturn -1
EndIf
CompilerIf #BakaShrot_Storage_RawSqlite
Protected Statement.i = BakaShrot_Storage_Writer\Delete
BakaShrot_Sqlite\BindInt64(Statement, 1, TopicId)
BakaShrot_Sqlite\BindInt64(Statement, 2, BeforeMs)
BakaShrot_Sqlite\BindInt64(Statement, 3, Limit)
If BakaShrot_Sqlite\Step_(Statement) = #BakaShrot_Sqlite_Done
Deleted = BakaShrot_Sqlite\Changes(BakaShrot_Storage_Writer\Handle)
Else
*Error\s = BakaShrot_Writer_Error()
EndIf
BakaShrot_Sqlite\Reset(Statement)
CompilerElse
Protected DbId.i = BakaShrot_Storage_Writer\DbId
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseQuad(DbId, 1, BeforeMs)
SetDatabaseLong(DbId, 2, Limit)
If DatabaseUpdate(DbId, PeekS(BakaShrot_Storage_Writer\Delete))
Deleted = AffectedDatabaseRows(DbId)
Else
*Error\s = DatabaseError()
EndIf
CompilerEndIf
UnlockMutex(BakaShrot_Storage_WriteMutex)
ProcedureReturn Deleted
EndProcedure
; Adds a row to the "topics" or "nodes" table (Table), for Id, named Name
; (its id in digits if it has none), Origin "peer" or "id", see
; Server/Storage/Names.pbi. A row already there for that id is kept.