diff --git a/Commons/Networking/Connections.pbi b/Commons/Networking/Connections.pbi index d501c6f..f16c359 100644 --- a/Commons/Networking/Connections.pbi +++ b/Commons/Networking/Connections.pbi @@ -218,6 +218,11 @@ EndProcedure ; next packets. #BakaShrot_InboxKeptCapacity = 256 * 1024 +; How long a send waits for the other end to make room, without a single +; byte going out, before it gives up. Same as how long a client waits for +; each packet (#BakaShrot_Outbound_Timeout). +#BakaShrot_SendStallTimeout = 10000 + Enumeration BakaShrot_InboxResults #BakaShrot_Inbox_Incomplete #BakaShrot_Inbox_Packet @@ -264,8 +269,13 @@ EndProcedure ; *Cipher is 0: only the Hello (sealed on its own) and the ChallengeRequest. ; Returns #False if the packet is too big, *Cipher isn't set up, or the data ; couldn't be sent. +; PureBasic's sockets don't block: SendNetworkData() returns -1 once the +; system's send buffer is full (EAGAIN on Linux, a few hundred KB), so -1 is +; retried until nothing went out for #BakaShrot_SendStallTimeout. PureBasic +; doesn't tell that from a broken connection, which then takes that long to +; give up on. Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher) - Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i + Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i, LastProgress.i If PacketSize < 1 Or PacketSize > #BakaShrot_MaxPacketSize ProcedureReturn #False @@ -294,13 +304,19 @@ Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher. CopyMemory(*Packet, *Frame + #BakaShrot_FrameHeaderSize, PacketSize) EndIf + LastProgress = ElapsedMilliseconds() While Offset < FrameSize Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset) - If Sent <= 0 + If Sent > 0 + Offset + Sent + LastProgress = ElapsedMilliseconds() + ElseIf ElapsedMilliseconds() - LastProgress > #BakaShrot_SendStallTimeout FreeMemory(*Frame) ProcedureReturn #False + Else + ; Full, until the other end reads some of it. + Delay(1) EndIf - Offset + Sent Wend FreeMemory(*Frame) diff --git a/Server/Storage/Storage.pbi b/Server/Storage/Storage.pbi index 36a5da0..37fc094 100644 --- a/Server/Storage/Storage.pbi +++ b/Server/Storage/Storage.pbi @@ -10,6 +10,11 @@ ; bundled with PureBasic 5.73 (3.33.0) doesn't have. On Windows, the official ; sqlite3.dll is used instead, it must be next to the program. Build.ps1 ; extracts it from Libs/sqlite-dll-win-*.zip and copies it. +; On Linux, the system's libsqlite3.so.0 (libsqlite3-0 on Debian/Ubuntu, +; sqlite-libs on Fedora) is used, whatever the compiler, it must be 3.38+. +; Either way it's #BakaShrot_Storage_SqliteLibrary, which RunReadOnlyQuery() +; and the writer (Writer.pbi) also call directly. Elsewhere, PureBasic's own +; SQLite is linked in, and they make do without it. ; ; Threads: ONE CONNECTION PER THREAD, never share a handle. ; The SetDatabase*() parameters and query results belong to a handle, so two @@ -30,8 +35,20 @@ XIncludeFile "../../Commons/Networking/Packets/SyncStatePacket.pbi" XIncludeFile "../../Commons/Networking/Packets/ReplicateMessagesPacket.pbi" -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - UseSQLiteDatabase("sqlite3.dll") +CompilerSelect #PB_Compiler_OS + CompilerCase #PB_OS_Windows + #BakaShrot_Storage_ExternalSqlite = #True + #BakaShrot_Storage_SqliteLibrary = "sqlite3.dll" + CompilerCase #PB_OS_Linux + #BakaShrot_Storage_ExternalSqlite = #True + #BakaShrot_Storage_SqliteLibrary = "libsqlite3.so.0" + CompilerDefault + #BakaShrot_Storage_ExternalSqlite = #False + #BakaShrot_Storage_SqliteLibrary = "" +CompilerEndSelect + +CompilerIf #BakaShrot_Storage_ExternalSqlite + UseSQLiteDatabase(#BakaShrot_Storage_SqliteLibrary) CompilerElse UseSQLiteDatabase() CompilerEndIf @@ -67,7 +84,7 @@ Procedure.q BakaShrot_NowUtcMs() GetSystemTimeAsFileTime_(@FileTime) ProcedureReturn (FileTime - 116444736000000000) / 10000 CompilerElse - ; Untested: Linux isn't built yet. struct timeval, 64-bit. + ; struct timeval, 64-bit (checked on Linux x64 by Tests/Retention-Test.ps1). Protected Dim TimeVal.q(1) BakaShrot_GetTimeOfDay(@TimeVal(0), 0) ProcedureReturn TimeVal(0) * 1000 + TimeVal(1) / 1000 @@ -616,15 +633,16 @@ EndProcedure ; the query looked like it simply had no (more) rows. So once the rows end, ; SQLite itself is asked: sqlite3_errcode() on the connection is SQLITE_DONE ; (or SQLITE_ROW/SQLITE_OK) if they really ended, the error otherwise, with -; sqlite3_errmsg16() telling which. Same sqlite3.dll as PureBasic's -; (DatabaseID() is its sqlite3 handle), like Writer.pbi. -; Elsewhere than Windows, PureBasic's own SQLite is linked in and not -; reachable this way: DatabaseError() is checked instead, which misses it. +; sqlite3_errmsg16() telling which. Same #BakaShrot_Storage_SqliteLibrary as +; PureBasic's (DatabaseID() is its sqlite3 handle), like Writer.pbi. +; Without #BakaShrot_Storage_ExternalSqlite, PureBasic's own SQLite is linked +; in and not reachable this way: DatabaseError() is checked instead, which +; misses it. #BakaShrot_Query_SqliteOk = 0 #BakaShrot_Query_SqliteRow = 100 #BakaShrot_Query_SqliteDone = 101 -CompilerIf #PB_Compiler_OS = #PB_OS_Windows +CompilerIf #BakaShrot_Storage_ExternalSqlite PrototypeC.l BakaShrot_Query_SqliteErrCode(Db.i) PrototypeC.i BakaShrot_Query_SqliteErrMsg16(Db.i) @@ -638,14 +656,14 @@ CompilerIf #PB_Compiler_OS = #PB_OS_Windows ; Queries run on every client's thread, the first one loads it. Global BakaShrot_Query_SqliteMutex.i = CreateMutex() - ; Returns #False if sqlite3.dll or its functions can't be found. + ; Returns #False if the SQLite library or its functions can't be found. Procedure.i BakaShrot_Query_LoadSqlite() Protected Loaded.i LockMutex(BakaShrot_Query_SqliteMutex) With BakaShrot_Query_Sqlite If Not \Library - \Library = OpenLibrary(#PB_Any, "sqlite3.dll") + \Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary) If \Library \ErrCode = GetFunction(\Library, "sqlite3_errcode") \ErrMsg16 = GetFunction(\Library, "sqlite3_errmsg16") @@ -693,7 +711,7 @@ Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.Strin EndIf ; Without it, errors in the rows would go unnoticed: refused instead. - CompilerIf #PB_Compiler_OS = #PB_OS_Windows + CompilerIf #BakaShrot_Storage_ExternalSqlite If Not BakaShrot_Query_LoadSqlite() *Error\s = "Queries can't be checked for errors: sqlite3_errcode() not found" ProcedureReturn #False @@ -767,7 +785,7 @@ Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.Strin ; Asked before FinishDatabaseQuery(), while the failed step is the last ; thing done on this connection. A false alarm would refuse a good ; query, it can't hide a bad one. - CompilerIf #PB_Compiler_OS = #PB_OS_Windows + CompilerIf #BakaShrot_Storage_ExternalSqlite ErrorCode = BakaShrot_Query_Sqlite\ErrCode(DatabaseID(DbId)) If ErrorCode <> #BakaShrot_Query_SqliteOk And ErrorCode <> #BakaShrot_Query_SqliteRow And ErrorCode <> #BakaShrot_Query_SqliteDone *Error\s = PeekS(BakaShrot_Query_Sqlite\ErrMsg16(DatabaseID(DbId)), -1, #PB_Unicode) @@ -785,11 +803,11 @@ Procedure.i RunReadOnlyQuery(DatabasePath.s, Sql.s, *Result.String, *Error.Strin CompilerEndIf FinishDatabaseQuery(DbId) - ; Elsewhere than Windows, the only check there is. It misses errors in the - ; rows: PureBasic doesn't report them. + ; Without #BakaShrot_Storage_ExternalSqlite, the only check there is. It + ; misses errors in the rows: PureBasic doesn't report them. ; !!! DatabaseError() may be shared by every thread, see ; !!! Design/StorageConcurrency.md, another thread's error could show up here. - CompilerIf #PB_Compiler_OS <> #PB_OS_Windows + CompilerIf Not #BakaShrot_Storage_ExternalSqlite If DatabaseError() <> "" *Error\s = DatabaseError() FreeJSON(JsonId) diff --git a/Server/Storage/Writer.pbi b/Server/Storage/Writer.pbi index 3ef561b..f833496 100644 --- a/Server/Storage/Writer.pbi +++ b/Server/Storage/Writer.pbi @@ -19,9 +19,10 @@ ; that were waiting find theirs done. The busier, the bigger the groups. ; - Prepared statements, kept for as long as the writer is open, through ; SQLite's own API: PureBasic prepares a statement again on every call. -; Same sqlite3.dll as PureBasic's (DatabaseID() is its sqlite3 handle). -; Elsewhere than Windows, PureBasic's own SQLite is linked in, so its -; functions are used instead (slower, same behaviour). +; Same #BakaShrot_Storage_SqliteLibrary as PureBasic's (DatabaseID() is +; its sqlite3 handle). Without #BakaShrot_Storage_ExternalSqlite (see +; Storage.pbi), PureBasic's own SQLite is linked in, so its 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 (node_heads, which deleting messages leaves as is: @@ -62,11 +63,7 @@ #BakaShrot_Storage_WalSizeLimit = 67108864 -CompilerIf #PB_Compiler_OS = #PB_OS_Windows - #BakaShrot_Storage_RawSqlite = #True -CompilerElse - #BakaShrot_Storage_RawSqlite = #False -CompilerEndIf +#BakaShrot_Storage_RawSqlite = #BakaShrot_Storage_ExternalSqlite #BakaShrot_Sqlite_Done = 101 #BakaShrot_Sqlite_Row = 100 @@ -387,7 +384,7 @@ CompilerIf #BakaShrot_Storage_RawSqlite ProcedureReturn #True EndIf ; The one PureBasic's SQLite driver already loaded. - \Library = OpenLibrary(#PB_Any, "sqlite3.dll") + \Library = OpenLibrary(#PB_Any, #BakaShrot_Storage_SqliteLibrary) If Not \Library ProcedureReturn #False EndIf @@ -527,7 +524,7 @@ Procedure.i OpenStorageWriter(DatabasePath.s, *Error.String) CompilerIf #BakaShrot_Storage_RawSqlite If Not BakaShrot_Writer_LoadSqlite() - *Error\s = "sqlite3.dll doesn't have the functions needed" + *Error\s = #BakaShrot_Storage_SqliteLibrary + " doesn't have the functions needed" BakaShrot_Writer_Release() UnlockMutex(BakaShrot_Storage_WriteMutex) ProcedureReturn #False diff --git a/Tests/AttachmentEdges-Test.ps1 b/Tests/AttachmentEdges-Test.ps1 index d9c3cfc..d372532 100644 --- a/Tests/AttachmentEdges-Test.ps1 +++ b/Tests/AttachmentEdges-Test.ps1 @@ -270,7 +270,9 @@ db.commit(); print("flipped") $Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s" Expect "B doesn't serve it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1 - $R = Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB + # A sends it again at every check-in, so B can be receiving (1) it + # again when asked: back to missing once that copy is dropped too. + $R = Wait-Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB '\[\["0","0"\]\]' 5 Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]' "INFO A sends it again at every check-in: $Drops times in 6 s (PeerSyncInterval 1)" diff --git a/Tests/Attachments-Test.ps1 b/Tests/Attachments-Test.ps1 index 263a386..9cbd8bb 100644 --- a/Tests/Attachments-Test.ps1 +++ b/Tests/Attachments-Test.ps1 @@ -283,8 +283,18 @@ finally { } "--- Logs" -$LogA = Get-Content (Join-Path $Dir "a.log") -Raw -$LogB = Get-Content (Join-Path $Dir "b.log") -Raw +# A and B start together: until its first link, the other one may not be +# listening yet. Refused at once on Linux, while Windows retries the connect +# for about a second, by which time it usually is. Those attempts are left out. +function Skip-EarlyLinkFailures([string[]]$Lines) { + $Linked = $false + foreach ($Line in $Lines) { + if ($Line -match "^\[Peer\] Linked to") { $Linked = $true } + if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line } + } +} +$LogA = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "a.log"))) -join "`n" +$LogB = @(Skip-EarlyLinkFailures (Get-Content (Join-Path $Dir "b.log"))) -join "`n" Check "A sent B the attachments it takes" ($LogA -match "Sent the attachment of logs:kitchen#1 to 'b'" -and $LogA -match "Sent the attachment of logs:kitchen#3 to 'b'") "checked" Check "A never sent #2 (not kept by B)" (-not ($LogA -match "Sent the attachment of logs:kitchen#2")) "checked" Check "B sent A its photo" ($LogB -match "Sent the attachment of photos:garage#1 to 'a'") "checked" diff --git a/Tests/BigMessages-Test.ps1 b/Tests/BigMessages-Test.ps1 index 36b8c78..ccd9ca9 100644 --- a/Tests/BigMessages-Test.ps1 +++ b/Tests/BigMessages-Test.ps1 @@ -299,12 +299,22 @@ try { "--- Logs" # Up to the last real activity: whichever stops first, the other loses its # link to it. +# A and B start together: until its first link, the other one may not be +# listening yet. Refused at once on Linux, while Windows retries the connect +# for about a second, by which time it usually is. Those attempts are left out. +function Skip-EarlyLinkFailures([string[]]$Lines) { + $Linked = $false + foreach ($Line in $Lines) { + if ($Line -match "^\[Peer\] Linked to") { $Linked = $true } + if ($Linked -or $Line -notmatch "^\[Peer\] (Failed to link|Retrying)") { $Line } + } +} function Read-Log($Name) { $L = @(Get-Content (Join-Path $Dir "$Name.log")) $End = [array]::IndexOf($L, "Stopping...") if ($End -lt 0) { $End = $L.Count } while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Dropping the link|Retrying|disconnected|aborted|didn't answer") { $End-- } - ($L[0..([math]::Max($End - 1, 0))]) -join "`n" + @(Skip-EarlyLinkFailures $L[0..([math]::Max($End - 1, 0))]) -join "`n" } $LogA = Read-Log "a" $LogB = Read-Log "b" diff --git a/Tests/Restart-Test.ps1 b/Tests/Restart-Test.ps1 index da97026..6cc521b 100644 --- a/Tests/Restart-Test.ps1 +++ b/Tests/Restart-Test.ps1 @@ -212,7 +212,9 @@ try { Start-Sleep -Seconds 3 # A goes on alone Stop-Pusher $PK $KSeen = Read-Pusher $PK - Check "the garage pusher noticed B was gone: ConnectionLostError, code 104" ($PG.P.HasExited -and (Read-Pusher $PG).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PG).End + # 104 (ConnectionLost) if killed during a push, 100 (NotConnected) if + # between two: the next push finds the connection already gone. + Check "the garage pusher noticed B was gone: ConnectionLostError, code 104 or 100" ($PG.P.HasExited -and (Read-Pusher $PG).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PG).End Check "kitchen kept pushing on A meanwhile" ($KSeen.Count -gt 100 -and $KSeen.End -eq "STOPPED") ("{0} acknowledged" -f $KSeen.Count) $SB = Start-Srv "b"; Wait-Port 12416 $SB @@ -256,7 +258,7 @@ try { Start-Sleep -Seconds 3 # B goes on alone Stop-Pusher $PG $GSeen = Read-Pusher $PG - Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104" ($PK.P.HasExited -and (Read-Pusher $PK).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PK).End + Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104 or 100" ($PK.P.HasExited -and (Read-Pusher $PK).End -match "^ERR 10[04] ConnectionLostError") (Read-Pusher $PK).End $SA = Start-Srv "a"; Wait-Port 12415 $SA Check-Survived "A" "kitchen" $PK $OnA diff --git a/Tests/Retention-Test.ps1 b/Tests/Retention-Test.ps1 index 64c13fd..b347916 100644 --- a/Tests/Retention-Test.ps1 +++ b/Tests/Retention-Test.ps1 @@ -315,10 +315,20 @@ finally { "--- Logs" $LogA = Get-Content (Join-Path $Dir "a.log") -Raw $LogB = Get-Content (Join-Path $Dir "b.log") -Raw +# How many messages of Topic a log says were deleted. Pushed a few ms apart, +# they can fall on both sides of a retention check (every 1 s), and be +# deleted over two of them. +function Count-Deleted($Log, $Topic) { + $N = 0 + foreach ($M in [regex]::Matches($Log, "Retention: deleted (\d+) messages of topic '$Topic' pushed before \d{4}-")) { $N += [int]$M.Groups[1].Value } + $N +} Check "A logged its rule" ($LogA -match "Retention: short = 3s") "checked" -Check "A logged what it deleted" ($LogA -match "Retention: deleted 3 messages of topic 'short' pushed before \d{4}-") "checked" +$N = Count-Deleted $LogA "short" +Check "A logged what it deleted: short #1-#3, maybe #4 since" ($N -ge 3) "$N deleted" Check "B logged its rules" ($LogB -match "Retention: ke\* = 4s" -and $LogB -match "Retention: \* = 1h") "checked" -Check "B deleted keep" ($LogB -match "Retention: deleted 2 messages of topic 'keep'") "checked" +$N = Count-Deleted $LogB "keep" +Check "B deleted keep: #1-#2, maybe #3 since" ($N -ge 2) "$N deleted" Check "B never sent A short messages (A is ahead, deleted or not)" (-not ($LogB -match "Sent \d+ messages of short")) "checked" Check "A sent B late once each: #1-#2, then #3 alone" (([regex]::Matches($LogA, "Sent 2 messages of late:kitchen")).Count -eq 1 -and ([regex]::Matches($LogA, "Sent 1 messages of late:kitchen")).Count -eq 1) "checked" Check "B never stored late #1-#2" (-not ($LogB -match "deleted [23] messages of topic 'late'")) "checked" diff --git a/Tests/restart_pusher.py b/Tests/restart_pusher.py index 15323e6..91c2ff2 100644 --- a/Tests/restart_pusher.py +++ b/Tests/restart_pusher.py @@ -4,7 +4,8 @@ Usage: restart_pusher.py " to the out file once each push is acknowledged. Ends with "STOPPED", or "ERR " when the server -goes away (the test kills it; code 104, ConnectionLost): what was +goes away (the test kills it; code 104, ConnectionLost, during a push, or +100, NotConnected, between two): what was acknowledged before is what must survive. """