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
+173
View File
@@ -0,0 +1,173 @@
; ============================================================================
; 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.
;
; 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
Structure BakaShrot_RetentionTopic
TopicId.i
Name.s
EndStructure
Structure BakaShrot_RetentionState
ThreadId.i
StopRequested.i
IntervalMs.i
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 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
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, once
; the writer is open. Nothing to do (no thread) if every topic is kept
; forever. 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
\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
+102 -16
View File
@@ -3,7 +3,7 @@
;
; 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_v5.dbml in this same folder.
; Schema: see db_schema_v6.dbml in this same folder.
;
; 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,13 +36,38 @@ CompilerElse
CompilerEndIf
; One row of the "data" table (see db_schema_v5.dbml).
; One row of the "data" table (see db_schema_v6.dbml).
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
Structure BakaShrot_Message
MessageId.q
PushedAt.q
JsonData.s
EndStructure
CompilerIf #PB_Compiler_OS <> #PB_OS_Windows
ImportC ""
BakaShrot_GetTimeOfDay.l(*TimeVal, *TimeZone) As "gettimeofday"
EndImport
CompilerEndIf
; Now, in milliseconds since 1970-01-01 00:00:00 UTC: what a pushed message
; is stamped with (pushed_at).
Procedure.q BakaShrot_NowUtcMs()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; 100 ns intervals since 1601-01-01 UTC.
Protected FileTime.q
GetSystemTimeAsFileTime_(@FileTime)
ProcedureReturn (FileTime - 116444736000000000) / 10000
CompilerElse
; Untested: Linux isn't built yet. struct timeval, 64-bit.
Protected Dim TimeVal.q(1)
BakaShrot_GetTimeOfDay(@TimeVal(0), 0)
ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000
CompilerEndIf
EndProcedure
; How long a connection waits for another one's lock before a statement
; fails with "database is locked", in ms.
#BakaShrot_Storage_BusyTimeout = 5000
@@ -165,7 +190,42 @@ Procedure.i MigrateStorageTopicIds(DbId.i)
EndProcedure
; Creates the tables and indexes described by db_schema_v5.dbml, if they
; v5 -> v6: "data" got pushed_at. Adds it to a database made before, every
; message stamped with the time of the upgrade (their real one is unknown),
; in one transaction. Nothing to do on a new or already upgraded database.
Procedure.i MigrateStoragePushedAt(DbId.i)
Protected Has.i
Has = StorageHasColumn(DbId, "data", "pushed_at")
If Has = -1
ProcedureReturn #False
ElseIf Has
ProcedureReturn #True
EndIf
If Not DatabaseUpdate(DbId, "BEGIN IMMEDIATE")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "ALTER TABLE data ADD COLUMN pushed_at INTEGER NOT NULL DEFAULT 0")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
; Bound for the next statement run, so right before it.
SetDatabaseQuad(DbId, 0, BakaShrot_NowUtcMs())
If Not DatabaseUpdate(DbId, "UPDATE data SET pushed_at = ?")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "COMMIT")
DatabaseUpdate(DbId, "ROLLBACK")
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Creates the tables and indexes described by db_schema_v6.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.
@@ -190,13 +250,15 @@ Procedure.i SetupStorageDatabase(DbId.i)
ProcedureReturn #False
EndIf
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS archives (" +
"delete_by INTEGER NOT NULL, " +
"message_data TEXT NOT NULL)")
; A leftover of the first schemas, never used: the retention deletes
; instead (Retention.pbi).
If Not DatabaseUpdate(DbId, "DROP TABLE IF EXISTS archives")
ProcedureReturn #False
EndIf
; is_json is set by SQLite on insert, and can't be written.
; pushed_at: when it was pushed to its origin, ms since 1970 UTC, kept as
; is when replicated. Last, like the ALTER TABLE below adds it.
; The UNIQUE constraint's index also serves (topic_id, node_id) lookups.
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS data (" +
"topic_id INTEGER NOT NULL, " +
@@ -204,6 +266,7 @@ Procedure.i SetupStorageDatabase(DbId.i)
"message_id INTEGER NOT NULL, " +
"message_data TEXT NOT NULL, " +
"is_json INTEGER NOT NULL GENERATED ALWAYS AS (json_valid(message_data)) STORED, " +
"pushed_at INTEGER NOT NULL DEFAULT 0, " +
"UNIQUE (topic_id, node_id, message_id))")
ProcedureReturn #False
EndIf
@@ -218,6 +281,18 @@ Procedure.i SetupStorageDatabase(DbId.i)
ProcedureReturn #False
EndIf
; A database from before pushed_at: its messages get the time of this
; upgrade, so a topic's max age (Server/Storage/Retention.pbi) counts
; from now for them instead of deleting them all at once.
If Not MigrateStoragePushedAt(DbId)
ProcedureReturn #False
EndIf
; What the retention deletes by: a topic's messages pushed before a time.
If Not DatabaseUpdate(DbId, "CREATE INDEX IF NOT EXISTS idx_data_topic_pushed_at ON data (topic_id, pushed_at)")
ProcedureReturn #False
EndIf
; 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 (" +
@@ -238,7 +313,9 @@ Procedure.i SetupStorageDatabase(DbId.i)
; every insert, whoever does it. The sync state comes from it instead of
; a GROUP BY over every message (131 ms at 1.9M rows, on every check-in).
; Filled from "data" when it's created on an existing database.
; !!! Nothing deletes from "data" yet: whatever does must update it too.
; Deleting from "data" (the retention) leaves it alone, on purpose: a
; pair's head stays its highest id ever, so the next push still gets the
; id after it, and peers aren't sent again what was deleted here.
If Not DatabaseQuery(DbId, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'node_heads'")
ProcedureReturn #False
EndIf
@@ -294,9 +371,13 @@ Procedure.i SetupStorageDatabase(DbId.i)
EndIf
; For queries by name: SELECT * FROM messages WHERE topic = 'logs' AND
; node = 'kitchen' still goes through the indexes.
If Not DatabaseUpdate(DbId, "CREATE VIEW IF NOT EXISTS messages AS " +
"SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id " +
; node = 'kitchen' still goes through the indexes. pushed_utc is
; pushed_at as text, "2026-11-08T14:03:59.123Z".
; Made again on every start, so an older one gets the newer columns.
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS messages") Or
Not DatabaseUpdate(DbId, "CREATE VIEW messages AS " +
"SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data, d.is_json, d.topic_id, d.node_id, " +
"d.pushed_at, strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc " +
"FROM data d JOIN topics t ON t.topic_id = d.topic_id JOIN nodes n ON n.node_id = d.node_id")
ProcedureReturn #False
EndIf
@@ -305,14 +386,15 @@ Procedure.i SetupStorageDatabase(DbId.i)
EndProcedure
; Inserts one JSON message into the "data" table.
; Inserts one JSON message into the "data" table, pushed now.
Procedure.i Insert(DbId.i, TopicId.i, NodeId.i, MessageId.i, JsonData.s)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseLong(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
SetDatabaseQuad(DbId, 4, BakaShrot_NowUtcMs())
ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)")
ProcedureReturn DatabaseUpdate(DbId, "INSERT INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)")
EndProcedure
@@ -413,7 +495,7 @@ 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 FROM data WHERE topic_id = ? AND node_id = ? ORDER BY message_id DESC LIMIT 1")
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")
ProcedureReturn #False
EndIf
@@ -421,6 +503,7 @@ Procedure.i GetLatestMessage(DbId.i, TopicId.i, NodeId.i, *Message.BakaShrot_Mes
If Found
*Message\MessageId = GetDatabaseQuad(DbId, 0)
*Message\JsonData = GetDatabaseString(DbId, 1)
*Message\PushedAt = GetDatabaseQuad(DbId, 2)
EndIf
FinishDatabaseQuery(DbId)
@@ -672,7 +755,7 @@ 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 FROM data WHERE topic_id = ? AND node_id = ? AND message_id > ? ORDER BY message_id LIMIT ?")
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 ?")
ProcedureReturn #False
EndIf
@@ -684,6 +767,7 @@ Procedure.i GetMessagesAfter(DbId.i, TopicId.i, NodeId.i, AfterMessageId.q, Limi
AddElement(Messages())
Messages()\MessageId = GetDatabaseQuad(DbId, 0)
Messages()\JsonData = GetDatabaseString(DbId, 1)
Messages()\PushedAt = GetDatabaseQuad(DbId, 2)
Chars + Len(Messages()\JsonData)
Wend
FinishDatabaseQuery(DbId)
@@ -700,13 +784,15 @@ EndProcedure
; new one is dropped, even if it differs. See Design/ReplicationIssues.md.
; On its own connection: for tools writing while the server is stopped
; (BenchSeed). The server itself writes through Writer.pbi.
; PushedAt: when it was pushed to its origin, ms since 1970 UTC.
; Returns #False if the insert failed.
Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s)
Procedure.i InsertReplicatedMessage(DbId.i, TopicId.i, NodeId.i, MessageId.q, JsonData.s, PushedAt.q)
SetDatabaseLong(DbId, 0, TopicId)
SetDatabaseLong(DbId, 1, NodeId)
SetDatabaseQuad(DbId, 2, MessageId)
SetDatabaseString(DbId, 3, JsonData)
ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data) VALUES (?, ?, ?, ?)")
SetDatabaseQuad(DbId, 4, PushedAt)
ProcedureReturn DatabaseUpdate(DbId, "INSERT OR IGNORE INTO data (topic_id, node_id, message_id, message_data, pushed_at) VALUES (?, ?, ?, ?, ?)")
EndProcedure
+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.
+89
View File
@@ -0,0 +1,89 @@
// Changes from v5:
// - data.pushed_at: when the message was pushed to its origin, ms since
// 1970-01-01 UTC, kept as is when replicated. A v5 database gets it with
// the time of the upgrade (MigrateStoragePushedAt() in Storage.pbi).
// - Index (topic_id, pushed_at): what the retention deletes by
// (Retention.pbi, [BakaShrot.Retention] in the config).
// - messages: the view also has pushed_at, and pushed_utc as text.
// - node_heads outlives deleted messages: a pair's highest id ever. Also
// raised for replicated messages skipped as already past their max age.
// - archives is gone: never used, dropped from older databases.
//
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
table data {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
message_data text [not null]
// 1 if message_data is well-formed JSON, 0 otherwise.
// Can't be written, SQLite computes it on insert and stores it.
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
// When it was pushed to its origin, ms since 1970-01-01 UTC.
pushed_at integer [not null, default: 0]
indexes {
(topic_id, node_id, message_id) [unique]
message_id
(topic_id, pushed_at)
}
}
// One row per topic/node id that has ever had messages: deleting messages
// (the retention) leaves it as is, so ids never go back.
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
// max_message_id = MAX(max_message_id, excluded.max_message_id)
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
table node_heads [note: 'WITHOUT ROWID'] {
topic_id integer [not null]
node_id integer [not null]
max_message_id integer [not null]
indexes {
(topic_id, node_id) [pk]
}
}
// Create it, but we'll implement this later.
table attachements {
topic_id integer [not null]
node_id integer [not null]
message_id integer [not null]
attachement_data blob [not null]
indexes {
(topic_id, node_id)
message_id
}
}
// origin: "config" (named in [BakaShrot.Topics]), "id" (unnamed, name is
// the id in digits).
table topics {
topic_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// origin: "config" (named in [BakaShrot.Nodes]), "id" (unnamed), "peer"
// (only in databases from the short-lived version that added peer nodes).
table nodes {
node_id integer [pk]
name text [not null, unique, note: 'COLLATE NOCASE']
origin text [not null]
}
// View messages:
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
// JOIN nodes n ON n.node_id = d.node_id
// WHERE topic = ... AND node = ... goes through the name indexes, then
// data's (topic_id, node_id, message_id) one.
// Note, ignore it
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL