1
0
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:
2026-11-08 18:56:15 +01:00
parent 9caf816dca
commit df61ef9719
42 changed files with 4920 additions and 106 deletions
+373
View File
@@ -0,0 +1,373 @@
; ============================================================================
; A raw protocol client for the attachment cases the DLL never produces, run
; by Tests/AttachmentEdges-Test.ps1 against a running server.
;
; Usage:
; AttachmentEdgeClient edge <KitchenIni> <GarageIni>
; Wrong SHA-256, parts out of order / of the wrong size / repeated,
; someone else's upload, the wrong topic, an upload attached twice, too
; big, a part out of range. Then starts two uploads it leaves behind
; (one half sent, one complete but never pushed) and prints
; "LEFT <PartialId> <CompleteId>".
; AttachmentEdgeClient late <KitchenIni> <PartialId> <CompleteId>
; Once they expired: both refused.
; The inis are client.ini's: PrivateKey, PublicKey, ServerPublicKey, Topic,
; Node, ServerHost, ServerPort. Kitchen may push to logs and other, garage
; to logs; the server's MaxAttachmentSize must be under 1G.
; Compile as a thread-safe console program into Build\. Exits with 0 if
; every check passed, 1 otherwise.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Networking/Outbound.pbi"
Structure EdgeClient
Outbound.BakaShrot_Outbound
Identity.BakaShrot_OutboundIdentity
PrivateKey.a[#BakaShrot_Ed25519_PrivateKeySize]
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
EndStructure
Global Fails.i = 0
Procedure Check(What.s, Ok.i, Detail.s = "")
If Ok
PrintN("PASS " + What)
Else
PrintN("FAIL " + What)
Fails + 1
EndIf
PrintN(" -> " + Detail)
EndProcedure
Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s)
Protected Host.s, Port.i, Ok.i
If Not OpenPreferences(IniPath)
ProcedureReturn #False
EndIf
PreferenceGroup("BakaShrot")
Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize))
*Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "")
*Client\Identity\Topic = ReadPreferenceString("Topic", "")
*Client\Identity\Node = ReadPreferenceString("Node", "")
*Client\Identity\PrivateKey = @*Client\PrivateKey[0]
Host = ReadPreferenceString("ServerHost", "127.0.0.1")
Port = ReadPreferenceLong("ServerPort", 0)
ClosePreferences()
If Not Ok
ProcedureReturn #False
EndIf
ProcedureReturn BakaShrot_Outbound_Connect(@*Client\Outbound, Host, Port, @*Client\Identity, @*Client\ServerPublicKey[0])
EndProcedure
; Sends *Packet (freed), returns the answer with its type, 0 if the link failed.
Procedure.i Exchange(*Client.EdgeClient, *Packet, Size.i, *Type.Integer, *AnswerSize.Integer)
Protected *Answer
*Type\i = 0
If Not *Packet
ProcedureReturn 0
EndIf
If Not BakaShrot_Outbound_Send(@*Client\Outbound, *Packet, Size)
FreeMemory(*Packet)
ProcedureReturn 0
EndIf
FreeMemory(*Packet)
*Answer = BakaShrot_Outbound_WaitPacket(@*Client\Outbound, *AnswerSize, 20000)
If *Answer
*Type\i = BakaShrot_GetPacketType(*Answer, *AnswerSize\i)
EndIf
ProcedureReturn *Answer
EndProcedure
Procedure.s Refusal(*Answer, Size.i)
Protected *View.MsgPackData, *Refused.BakaShrot_RequestRefused, Reason.s
*View = MsgPackWrapMsgBuffer(*Answer, Size)
If *View
*Refused = BakaShrot_RequestRefusedPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Refused
Reason = *Refused\Reason
FreeStructure(*Refused)
EndIf
EndIf
ProcedureReturn Reason
EndProcedure
; Starts an upload. Returns its id, 0 if refused (reason in *Reason\s).
Procedure.q StartUpload(*Client.EdgeClient, Topic.s, Size.q, *Sha256, *Reason.String)
Protected Start.BakaShrot_UploadStart, *Started.BakaShrot_UploadStarted
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q
*Reason\s = ""
Start\Topic = Topic
Start\Size = Size
CopyMemory(*Sha256, @Start\Sha256[0], #BakaShrot_Sha256Size)
*Packet = BakaShrot_UploadStartPacket_Encode(@Start, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
*Reason\s = "the link failed"
ProcedureReturn 0
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
ElseIf Type\i = #BakaShrot_PacketType_UploadStarted
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Started = BakaShrot_UploadStartedPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Started
Id = *Started\UploadId
FreeStructure(*Started)
EndIf
EndIf
FreeMemory(*Answer)
ProcedureReturn Id
EndProcedure
; Sends a part. Returns 1 if stored (*Complete\i set), 0 if refused (reason), -1 if the link failed.
Procedure.i SendChunk(*Client.EdgeClient, UploadId.q, Index.i, *Data, Size.i, *Complete.Integer, *Reason.String)
Protected Chunk.BakaShrot_UploadChunk, *Stored.BakaShrot_ChunkStored
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Result.i = -1
*Reason\s = ""
Chunk\UploadId = UploadId
Chunk\ChunkIndex = Index
Chunk\Data = *Data
Chunk\DataSize = Size
*Packet = BakaShrot_UploadChunkPacket_Encode(@Chunk, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
ProcedureReturn -1
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
Result = 0
ElseIf Type\i = #BakaShrot_PacketType_ChunkStored
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Stored = BakaShrot_ChunkStoredPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Stored
*Complete\i = *Stored\Complete
FreeStructure(*Stored)
Result = 1
EndIf
EndIf
FreeMemory(*Answer)
ProcedureReturn Result
EndProcedure
; Pushes a message with UploadId. Returns its id, 0 if refused (reason).
Procedure.q Push(*Client.EdgeClient, Topic.s, Json.s, UploadId.q, *Reason.String)
Protected Push.BakaShrot_PushMessage, *Pushed.BakaShrot_MessagePushed
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData, Id.q
*Reason\s = ""
Push\Topic = Topic
Push\JsonData = Json
Push\UploadId = UploadId
*Packet = BakaShrot_PushMessagePacket_Encode(@Push, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
*Reason\s = "the link failed"
ProcedureReturn 0
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
ElseIf Type\i = #BakaShrot_PacketType_MessagePushed
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Pushed = BakaShrot_MessagePushedPacket_Decode(*View)
MsgPackFree(*View, #False)
If *Pushed
Id = *Pushed\MessageId
FreeStructure(*Pushed)
EndIf
EndIf
FreeMemory(*Answer)
ProcedureReturn Id
EndProcedure
; Asks for a part. Returns it (free with _Free), 0 if refused (reason).
Procedure.i GetChunk(*Client.EdgeClient, Topic.s, Node.s, MessageId.q, Index.i, *Reason.String)
Protected Request.BakaShrot_GetAttachment, *Chunk.BakaShrot_AttachmentChunk
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer, Type.Integer, *View.MsgPackData
*Reason\s = ""
Request\Topic = Topic
Request\Node = Node
Request\MessageId = MessageId
Request\ChunkIndex = Index
*Packet = BakaShrot_GetAttachmentPacket_Encode(@Request, @PacketSize)
*Answer = Exchange(*Client, *Packet, PacketSize\i, @Type, @AnswerSize)
If Not *Answer
*Reason\s = "the link failed"
ProcedureReturn 0
EndIf
If Type\i = #BakaShrot_PacketType_RequestRefused
*Reason\s = Refusal(*Answer, AnswerSize\i)
ElseIf Type\i = #BakaShrot_PacketType_AttachmentChunk
*View = MsgPackWrapMsgBuffer(*Answer, AnswerSize\i)
*Chunk = BakaShrot_AttachmentChunkPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Answer)
ProcedureReturn *Chunk
EndProcedure
; Size random bytes.
Procedure.i RandomBytes(Size.i)
Protected *Data = AllocateMemory(Size)
RandomData(*Data, Size)
ProcedureReturn *Data
EndProcedure
Procedure Sha256Of(*Data, Size.q, *Out)
Protected Hash.BakaShrot_Sha256
BakaShrot_Sha256_Start(@Hash)
BakaShrot_Sha256_Add(@Hash, *Data, Size)
BakaShrot_Sha256_Finish(@Hash, *Out)
EndProcedure
; Uploads Size bytes of *Data properly. Returns the upload id, 0 on failure.
Procedure.q UploadAll(*Client.EdgeClient, Topic.s, *Data, Size.q)
Protected Dim Sha.a(31), Id.q, Index.i, Complete.Integer, Reason.String
Sha256Of(*Data, Size, @Sha(0))
Id = StartUpload(*Client, Topic, Size, @Sha(0), @Reason)
If Not Id
ProcedureReturn 0
EndIf
For Index = 0 To BakaShrot_AttachmentChunkCount(Size) - 1
If SendChunk(*Client, Id, Index, *Data + Index * #BakaShrot_AttachmentChunkSize, BakaShrot_AttachmentChunkBytes(Size, Index), @Complete, @Reason) <> 1
ProcedureReturn 0
EndIf
Next
If Not Complete\i
ProcedureReturn 0
EndIf
ProcedureReturn Id
EndProcedure
Define Kitchen.EdgeClient, Garage.EdgeClient, Reason.String, Complete.Integer
Define Dim Sha.a(31), Dim WrongSha.a(31)
Define *Data, *Other, Id.q, Id2.q, MessageId.q, Result.i, *Chunk.BakaShrot_AttachmentChunk, Size.q
Define PartialId.q, CompleteId.q
OpenConsole()
If CountProgramParameters() < 3
PrintN("Usage: AttachmentEdgeClient edge <KitchenIni> <GarageIni> | late <KitchenIni> <PartialId> <CompleteId>")
End 1
EndIf
If Not ConnectIni(@Kitchen, ProgramParameter(1))
PrintN("FAIL can't connect with " + ProgramParameter(1))
End 1
EndIf
If LCase(ProgramParameter(0)) = "late"
PartialId = Val(ProgramParameter(2))
CompleteId = Val(ProgramParameter(3))
*Data = RandomBytes(#BakaShrot_AttachmentChunkSize)
Result = SendChunk(@Kitchen, PartialId, 1, *Data, 1000, @Complete, @Reason)
Check("An expired upload: its next part refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "late" + Chr(34) + ":1}", CompleteId, @Reason)
Check("An expired complete upload: pushing with it refused", Bool(MessageId = 0 And (FindString(Reason\s, "No such upload") Or FindString(Reason\s, "isn't complete"))), Reason\s)
Check("Still connected after the refusals", BakaShrot_Outbound_IsConnected(@Kitchen\Outbound))
BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
PrintN("")
If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf
PrintN("All passed")
End 0
EndIf
If Not ConnectIni(@Garage, ProgramParameter(2))
PrintN("FAIL can't connect with " + ProgramParameter(2))
End 1
EndIf
; --- A wrong SHA-256 --------------------------------------------------------------
Size = #BakaShrot_AttachmentChunkSize + 500000
*Data = RandomBytes(Size)
*Other = RandomBytes(Size)
Sha256Of(*Other, Size, @WrongSha(0))
Id = StartUpload(@Kitchen, "logs", Size, @WrongSha(0), @Reason)
Check("Upload with a wrong SHA-256: started", Bool(Id > 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 0 stored, not complete", Bool(Result = 1 And Complete\i = 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason)
Check(" the last part: refused, doesn't match", Bool(Result = 0 And FindString(Reason\s, "doesn't match its SHA-256")), Reason\s)
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "bad" + Chr(34) + ":1}", Id, @Reason)
Check(" pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "isn't complete")), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, 500000, @Complete, @Reason)
Check(" sending the last part again: refused, it's dropped", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
; --- Parts out of order, wrong size, repeated ---------------------------------------
Size = 2 * #BakaShrot_AttachmentChunkSize + 1234
FreeMemory(*Data) : *Data = RandomBytes(Size)
Sha256Of(*Data, Size, @Sha(0))
Id = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason)
Check("Upload of 3 parts: started", Bool(Id > 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 1 first: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 0 of 3")), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, 1000, @Complete, @Reason)
Check(" part 0 too short: refused", Bool(Result = 0 And FindString(Reason\s, "1048576 bytes")), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 0 right: stored, the refusals didn't drop the upload", Bool(Result = 1 And Complete\i = 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 0 again: refused", Bool(Result = 0 And FindString(Reason\s, "Expected part 1")), Reason\s)
Result = SendChunk(@Garage, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 1 from another client: refused", Bool(Result = 0 And FindString(Reason\s, "No such upload in progress")), Reason\s)
Result = SendChunk(@Kitchen, Id, 1, *Data + #BakaShrot_AttachmentChunkSize, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
Check(" part 1: stored", Bool(Result = 1 And Complete\i = 0), Reason\s)
Result = SendChunk(@Kitchen, Id, 2, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234, @Complete, @Reason)
Check(" part 2, the last: complete", Bool(Result = 1 And Complete\i = 1), Reason\s)
Result = SendChunk(@Kitchen, Id, 3, *Data, 10, @Complete, @Reason)
Check(" a part past the end: refused", Bool(Result = 0), Reason\s)
; --- Whose, which topic, how many times -------------------------------------------------
MessageId = Push(@Garage, "logs", "{" + Chr(34) + "theirs" + Chr(34) + ":1}", Id, @Reason)
Check("Another client pushing with it: refused", Bool(MessageId = 0 And FindString(Reason\s, "No such upload")), Reason\s)
MessageId = Push(@Kitchen, "other", "{" + Chr(34) + "topic" + Chr(34) + ":1}", Id, @Reason)
Check("Pushing it to another topic: refused", Bool(MessageId = 0 And FindString(Reason\s, "is for topic 'logs'")), Reason\s)
MessageId = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":1}", Id, @Reason)
Check("Pushing it: stored", Bool(MessageId > 0), "message #" + Str(MessageId) + " " + Reason\s)
Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":2}", Id, @Reason)
Check("Pushing it again: refused, attached already", Bool(Id2 = 0 And FindString(Reason\s, "attached already")), Reason\s)
Id2 = Push(@Kitchen, "logs", "{" + Chr(34) + "edge" + Chr(34) + ":3}", 999999, @Reason)
Check("An upload id that doesn't exist: refused", Bool(Id2 = 0 And FindString(Reason\s, "No such upload")), Reason\s)
; --- Reading it back, part by part ---------------------------------------------------------
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 2, @Reason)
Check("GetAttachment part 2 first: the right bytes", Bool(*Chunk And *Chunk\DataSize = 1234 And *Chunk\Size = Size And CompareMemory(*Chunk\Data, *Data + 2 * #BakaShrot_AttachmentChunkSize, 1234) And CompareMemory(@*Chunk\Sha256[0], @Sha(0), 32)), Reason\s)
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 0, @Reason)
Check(" part 0: the right bytes", Bool(*Chunk And *Chunk\DataSize = #BakaShrot_AttachmentChunkSize And CompareMemory(*Chunk\Data, *Data, #BakaShrot_AttachmentChunkSize)), Reason\s)
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
*Chunk = GetChunk(@Kitchen, "logs", "kitchen", MessageId, 3, @Reason)
Check(" part 3, past the end: refused", Bool(Not *Chunk And FindString(Reason\s, "has 3 parts")), Reason\s)
*Chunk = GetChunk(@Garage, "secret", "kitchen", MessageId, 0, @Reason)
Check(" from a topic garage may not read: refused", Bool(Not *Chunk And FindString(Reason\s, "Not allowed to read topic")), Reason\s)
; --- Limits ------------------------------------------------------------------------------------
Id = StartUpload(@Kitchen, "logs", 1024 * 1024 * 1024, @Sha(0), @Reason)
Check("Upload of 1 GB (over MaxAttachmentSize): refused", Bool(Id = 0 And FindString(Reason\s, "too big")), Reason\s)
Id = StartUpload(@Garage, "other", 1000, @Sha(0), @Reason)
Check("Upload to a topic garage may not push to: refused", Bool(Id = 0 And FindString(Reason\s, "Not allowed to push")), Reason\s)
Check("Both still connected after every refusal", Bool(BakaShrot_Outbound_IsConnected(@Kitchen\Outbound) And BakaShrot_Outbound_IsConnected(@Garage\Outbound)))
; --- Left behind, for the expiry ---------------------------------------------------------------------
Size = 2 * #BakaShrot_AttachmentChunkSize
FreeMemory(*Data) : *Data = RandomBytes(Size)
Sha256Of(*Data, Size, @Sha(0))
PartialId = StartUpload(@Kitchen, "logs", Size, @Sha(0), @Reason)
Result = SendChunk(@Kitchen, PartialId, 0, *Data, #BakaShrot_AttachmentChunkSize, @Complete, @Reason)
CompleteId = UploadAll(@Kitchen, "logs", *Data, 5000)
Check("Two uploads left behind: half sent, and complete but never pushed", Bool(PartialId > 0 And Result = 1 And CompleteId > 0), Str(PartialId) + ", " + Str(CompleteId))
BakaShrot_Outbound_Close(@Kitchen\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
BakaShrot_Outbound_Close(@Garage\Outbound, #BakaShrot_ConnectionStatus_Disconnected)
PrintN("LEFT " + Str(PartialId) + " " + Str(CompleteId))
PrintN("")
If Fails : PrintN(Str(Fails) + " FAILED") : End 1 : EndIf
PrintN("All passed")
End 0
+287
View File
@@ -0,0 +1,287 @@
# The attachment cases the regular clients never produce (Design/Attachments.md):
# 1. Through a raw client (Tests/AttachmentEdgeClient.pb): a wrong SHA-256,
# parts out of order / of the wrong size / repeated, someone else's
# upload, the wrong topic, an upload attached twice, too big, a part
# out of range.
# 2. Uploads left behind: kept within UploadTimeout, deleted past it, then
# refused.
# 3. Replication resuming: the receiving server killed in the middle of a
# 400 MB attachment, restarted, the sender goes on from where it stopped.
# 4. A corrupted attachment (bytes flipped in the sender's database): the
# client refuses it, the peer drops it and doesn't keep it.
# Two servers, A (port 12413) and B (12414). Needs Build\ (Build.ps1),
# Build\Bench\BenchServer.exe, Build\AttachmentEdgeClient.exe (compile
# Tests\AttachmentEdgeClient.pb, thread-safe console), and Python 3 for 4.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\AttachmentEdges-Test.ps1 [-Python <python.exe>]
param(
[string]$Build = (Join-Path $PSScriptRoot "..\Build"),
[string]$Python = "python"
)
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_attachedges"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | "); Lines = @($O) }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
# Each run its own log: a restart doesn't overwrite the last one's.
$script:Runs[$Name]++
$Log = Join-Path $Dir "$Name.$($script:Runs[$Name]).log"
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput $Log -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name; Log = $Log }
}
$Runs = @{ a = 0; b = 0 }
function Stop-Srv($S) {
if (-not $S -or $S.P.HasExited) { return }
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(30000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content $S.Log -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
}
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Query $Sql $Ini
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
$R
}
function Push($Data, $Ini, [string]$Attach = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Attach) { $A += @("-a", $Attach) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
}
function New-File($Name, [int64]$Size, [int]$Seed) {
$P = Join-Path $Dir $Name
$R = New-Object System.Random $Seed
$Buf = New-Object byte[] ([math]::Min($Size, 16MB))
$F = [IO.File]::OpenWrite($P)
$Left = $Size
while ($Left -gt 0) { $R.NextBytes($Buf); $N = [math]::Min($Left, $Buf.Length); $F.Write($Buf, 0, $N); $Left -= $N }
$F.Close()
$P
}
function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } }
function Num($Out) { if ($Out -match '\[\["(\d+)"\]\]') { [int64]$Matches[1] } else { -1 } }
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair
foreach ($Name in "a", "b") {
$Me = @{ a = $A; b = $B }[$Name]; $Peer = @{ a = $B; b = $A }[$Name]
$PeerName = @{ a = "b"; b = "a" }[$Name]
$Port = @{ a = 12413; b = 12414 }[$Name]; $PeerPort = @{ a = 12414; b = 12413 }[$Name]
$Base = @{ a = 1; b = 100 }[$Name]
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($Me.Priv)
Topic = logs
Node = server$Name
[BakaShrot.Topics]
logs = $Base
other = $($Base + 1)
secret = $($Base + 2)
[BakaShrot.Nodes]
servera = $($Base + 10)
serverb = $($Base + 11)
kitchen = $($Base + 2)
garage = $($Base + 3)
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "$Name.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
MaxAttachmentSize = 512M
UploadTimeout = 10
[BakaShrot.Peer.$PeerName]
Host = 127.0.0.1
Port = $PeerPort
Topic = logs
Node = server$PeerName
PublicKey = $($Peer.Pub)
[BakaShrot.Client.$PeerName]
PublicKeys = $($Peer.Pub)
Identities = logs:server$PeerName
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
PushTopics = logs;other;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.garage]
PublicKeys = $($G.Pub)
Identities = logs:garage
PushTopics = logs
ReadTopics = logs
"@
}
$ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub }
function Client-Ini($Name, $Keys, $Node, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413
$GarageA = Client-Ini "garage-a" $G "garage" 12413
$KitchenB = Client-Ini "kitchen-b" $K "kitchen" 12414
foreach ($Port in 12413, 12414) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
$SA = Start-Srv "a"; $SB = $null
try {
Wait-Port 12413 $SA
"--- 1. Through the raw client"
$R = Tool "AttachmentEdgeClient.exe" @("edge", $KitchenA, $GarageA)
$R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" }
$Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count
Check "the raw client ran to the end" ($R.Code -ne $null -and ($R.Out -match "LEFT (\d+) (\d+)")) $R.Lines[-1]
$Partial = $Matches[1]; $Complete = $Matches[2]
$LeftAt = Get-Date
"--- 2. Uploads left behind (UploadTimeout = 10)"
$Sql = "SELECT blob_id, state, received FROM blobs WHERE blob_id IN ($Partial, $Complete) ORDER BY blob_id"
$R = Query $Sql $KitchenA
Check "within UploadTimeout: both kept, receiving (0) and complete (1)" ($R.Out -match "\[\[`"$Partial`",`"0`",`"1048576`"\],\[`"$Complete`",`"1`",`"5000`"\]\]") $R.Out
$R = Wait-Query "SELECT COUNT(*) FROM blobs WHERE blob_id IN ($Partial, $Complete)" $KitchenA '\[\["0"\]\]' 25
$After = ((Get-Date) - $LeftAt).TotalSeconds
Check "past it: both deleted" ($R.Out -match '\[\["0"\]\]') ("{0:N1} s after they were left" -f $After)
Check " not before 10 s" ($After -ge 8) ("{0:N1} s" -f $After)
Expect " their parts too" (Query "SELECT COUNT(*) FROM blob_chunks WHERE blob_id IN ($Partial, $Complete)" $KitchenA) '\[\["0"\]\]'
Expect " and the one with the wrong SHA-256 (dropped at once)" (Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenA) '\[\["0"\]\]'
Expect " the attached one is kept" (Query "SELECT COUNT(*) FROM blobs WHERE state = 2" $KitchenA) '\[\["1"\]\]'
$R = Tool "AttachmentEdgeClient.exe" @("late", $KitchenA, $Partial, $Complete)
$R.Lines | Where-Object { $_ -match "^(PASS|FAIL| ->)" }
$Script:Fails += @($R.Lines | Where-Object { $_ -match "^FAIL" }).Count
"--- 3. Replication resuming (B killed in the middle of 400 MB)"
$Big = New-File "big.bin" 400MB 9
$R = Push '{"big":1}' $KitchenA $Big
Check "push 400 MB to A" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out
$BigId = $Matches[1]
$SB = Start-Srv "b"
Wait-Port 12414 $SB
$Received = "SELECT COALESCE(MAX(b.received), 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id LEFT JOIN blobs b ON b.blob_id = a.blob_id WHERE t.name = 'logs' AND a.message_id = $BigId"
$KilledAt = -1
$D = (Get-Date).AddSeconds(60)
while ((Get-Date) -lt $D) {
$N = Num (Query $Received $KitchenB).Out
if ($N -ge 40MB) { Stop-Process -Id $SB.P.Id -Force; $SB.P.WaitForExit(10000) | Out-Null; $KilledAt = $N; break }
Start-Sleep -Milliseconds 50
}
Check "B killed in the middle" ($KilledAt -gt 0 -and $KilledAt -lt 400MB) ("{0:N0} MB of 400 received" -f ($KilledAt / 1MB))
$SB = Start-Srv "b"
Wait-Port 12414 $SB
$AfterRestart = Num (Query $Received $KitchenB).Out
Check "after the restart, what it had is still there" ($AfterRestart -ge $KilledAt) ("{0:N0} MB" -f ($AfterRestart / 1MB))
$Copy = Join-Path $Dir "big-from-b.bin"
$D = (Get-Date).AddSeconds(90)
do {
$R = Tool "GetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 500
} while ((Get-Date) -lt $D)
Check "B ends up with all of it, identical" ($R.Code -eq 0 -and (Hash $Copy) -eq (Hash $Big)) $R.Out
$LogA = (Get-ChildItem $Dir -Filter "a.*.log" | ForEach-Object { Get-Content $_.FullName -Raw }) -join "`n"
$Resumed = [regex]::Matches($LogA, "Sent the attachment of logs:kitchen#$BigId to 'b' in \d+ ms, from part (\d+)")
$From = if ($Resumed.Count) { [int]$Resumed[$Resumed.Count - 1].Groups[1].Value } else { -1 }
Check "A went on from where B stopped, not from 0" ($From -gt 0 -and $From * 1MB -le $AfterRestart) ("from part $From, B had {0:N0} MB" -f ($AfterRestart / 1MB))
Remove-Item $Copy, $Big -ErrorAction SilentlyContinue
"--- 4. A corrupted attachment"
$HasPython = $false
try { & $Python -c "import sqlite3" 2>&1 | Out-Null; $HasPython = ($LASTEXITCODE -eq 0) } catch { }
if (-not $HasPython) {
"SKIP no Python ($Python)"
} else {
Stop-Srv $SB; $SB = $null
$Small = New-File "small.bin" (3MB + 99) 10
$R = Push '{"corrupt":1}' $KitchenA $Small
Check "push 3 MB to A, B stopped" ($R.Code -eq 0 -and $R.Out -match "message #(\d+), with an attachment") $R.Out
$BadId = $Matches[1]
Stop-Srv $SA
$Flip = @"
import sqlite3, sys
db = sqlite3.connect(sys.argv[1])
row = db.execute("SELECT c.rowid, c.chunk_data FROM blob_chunks c JOIN attachments a ON a.blob_id = c.blob_id WHERE a.message_id = ? AND a.topic_id = 1 AND c.chunk_index = 1", (int(sys.argv[2]),)).fetchone()
data = bytearray(row[1]); data[1000] ^= 0xFF
db.execute("UPDATE blob_chunks SET chunk_data = ? WHERE rowid = ?", (bytes(data), row[0]))
db.commit(); print("flipped")
"@
Set-Content (Join-Path $Dir "flip.py") -Encoding Ascii -Value $Flip
$Out = & $Python -B (Join-Path $Dir "flip.py") (Join-Path $Dir "a.sqlite") $BadId 2>&1
Check "a byte flipped in A's database, part 1" ("$Out" -eq "flipped") "$Out"
$SA = Start-Srv "a"
Wait-Port 12413 $SA
$Copy = Join-Path $Dir "bad-from-a.bin"
Expect "reading it from A: the client refuses it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1
Check " and leaves no file" (-not (Test-Path $Copy)) "checked"
$SB = Start-Srv "b"
Wait-Port 12414 $SB
Start-Sleep -Seconds 6
$LogB = Get-Content $SB.Log -Raw
$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 "GetAttachment.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
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)"
}
}
finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- Logs"
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -match "invalid|unexpected|doesn't decrypt" }
Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ")
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+296
View File
@@ -0,0 +1,296 @@
# End-to-end test of attachments (Design/Attachments.md), through the tools
# (PushMessage -a, GetAttachment, GetLatestMessage):
# - pushed with a message, read back identical (100 KB, 5 MB + a bit,
# exactly 2 MB: one part, several, a whole number of them);
# - a message without one: refused when asked for it;
# - replicated after their messages, identical on the other server;
# - bigger than the other server's MaxAttachmentSize: its message comes,
# the attachment is refused there as not kept;
# - too big to push: refused, and the message isn't stored;
# - deleted with their message by the retention, parts included.
# Two linked servers, A (port 12410, MaxAttachmentSize 64M) and B (12411, 3M).
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Attachments-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_attachtest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
$C = New-Object System.Net.Sockets.TcpClient
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
}
function Tool([string]$Name, [string[]]$A) {
$O = & (Join-Path $Build $Name) @A 2>&1
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
}
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
}
function Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "$Name.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Stop = $Stop; Name = $Name }
}
function Stop-Srv($S) {
if ($S.P.HasExited) { return }
Set-Content $S.Stop "x"
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited: $(Get-Content (Join-Path $Dir "$($S.Name).log") -Raw)" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
}
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Query $Sql $Ini
if ($R.Code -eq 0 -and $R.Out -match $Pattern) { return $R }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
$R
}
function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
if ($Attach) { $A += @("-a", $Attach) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
}
# A file of Size random bytes.
function New-File($Name, [int]$Size, [int]$Seed) {
$P = Join-Path $Dir $Name
$B = New-Object byte[] $Size
(New-Object System.Random $Seed).NextBytes($B)
[IO.File]::WriteAllBytes($P, $B)
$P
}
function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA256).Hash } else { "no file" } }
# Saves an attachment and compares it with the original.
function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) {
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
$R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
$Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))
Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out)
}
# Retries GetAttachment until it works: replicated ones come after their message.
function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) {
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
$D = (Get-Date).AddSeconds($Seconds)
do {
$R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
Check $What (($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))) ("[{0}] {1}" -f $R.Code, $R.Out)
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Topic = logs
Node = serverA
[BakaShrot.Topics]
logs = 1
short = 2
photos = 3
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
garage = 3
[BakaShrot.Retention]
short = 4s
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12410
ReplicatingTopics = logs;short;photos
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
MaxAttachmentSize = 64M
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12411
Topic = logs
Node = serverB
PublicKey = $($B.Pub)
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Identities = logs:serverB
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
PushTopics = logs;short
ReadTopics = *
AllowQuery = 1
"@
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Topic = logs
Node = serverB
[BakaShrot.Topics]
logs = 300
short = 301
photos = 302
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = 30
garage = 31
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12411
ReplicatingTopics = logs;short;photos
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
RetentionInterval = 1
MaxAttachmentSize = 3M
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12410
Topic = logs
Node = serverA
PublicKey = $($A.Pub)
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Identities = logs:serverA
[BakaShrot.Client.garage]
PublicKeys = $($K.Pub)
Identities = photos:garage
PushTopics = photos
ReadTopics = *
AllowQuery = 1
"@
$ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub }
function Client-Ini($Name, $Topic, $Node, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = $Topic`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410
$OnB = Client-Ini "garage-b" "photos" "garage" 12411
$Small = New-File "small.bin" (100 * 1024) 1
$Mid = New-File "mid.bin" (5 * 1024 * 1024 + 123) 2
$Exact = New-File "exact.bin" (2 * 1024 * 1024) 3
$Tiny = New-File "tiny.bin" 1 4
foreach ($Port in 12410, 12411) { if (Test-Port $Port) { throw "Port $Port is already in use" } }
$SA = Start-Srv "a"; $SB = Start-Srv "b"
try {
Wait-Port 12410 $SA; Wait-Port 12411 $SB
Start-Sleep -Seconds 1
"--- Pushed with their message, read back"
Expect "push #1 with 100 KB" (Push '{"n":1}' $OnA "" $Small) "message #1, with an attachment of 102400 bytes"
$Started = Get-Date
Expect "push #2 with 5 MB + 123 bytes (6 parts)" (Push '{"n":2}' $OnA "" $Mid) "message #2, with an attachment of 5243003 bytes"
$UploadMs = ((Get-Date) - $Started).TotalMilliseconds
Expect "push #3 with exactly 2 MB (2 parts)" (Push '{"n":3}' $OnA "" $Exact) "message #3, with an attachment of 2097152 bytes"
Expect "push #4 with 1 byte" (Push '{"n":4}' $OnA "" $Tiny) "message #4"
Expect "push #5 without" (Push '{"n":5}' $OnA) "message #5$"
Expect-Same "#1 read back identical" "logs" "kitchen" 1 $Small $OnA
$Started = Get-Date
Expect-Same "#2 read back identical" "logs" "kitchen" 2 $Mid $OnA
$DownloadMs = ((Get-Date) - $Started).TotalMilliseconds
Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs)
Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA
Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA
Expect "#5 has none: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1
Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked"
Expect "a message that doesn't exist: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1
Expect "GetLatestMessage: #5, no attachment line" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$"
$R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA
Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out
Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]'
"--- Replicated after their messages (B takes up to 3M)"
$R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'logs' AND node = 'kitchen'" $OnB '\[\["5"\]\]'
Check "B got the 5 messages" ($R.Out -match '\[\["5"\]\]') $R.Out
Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB
Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB
Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB
Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "GetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1
$R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB
Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out
Expect "B: GetLatestMessage logs:kitchen, #5 has none" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}"
"--- Pushed on B, too big there, then replicated to A"
Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1
Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment"
Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA
Expect "A: the latest of photos:garage" (Tool "GetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}"
"--- Deleted with their message (A: short = 4s)"
$Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out
Expect "push short #1 with 2 MB" (Push '{"s":1}' $OnA "short" $Exact) "message #1, with an attachment"
Expect "A has 2 more parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["13"\]\]'
$R = Wait-Query "SELECT COUNT(*) FROM messages WHERE topic = 'short'" $OnA '\[\["0"\]\]' 15
Check "the message is deleted past 4 s" ($R.Out -match '\[\["0"\]\]') $R.Out
$R = Wait-Query "SELECT COUNT(*) FROM blob_chunks" $OnA '\[\["11"\]\]' 10
Check "and its 2 parts" ($R.Out -match '\[\["11"\]\]') "before $Before, now $($R.Out)"
Expect "and its attachments row" (Query "SELECT COUNT(*) FROM attachments WHERE topic_id = 2" $OnA) '\[\["0"\]\]'
Expect "and its blob" (Query "SELECT COUNT(*) FROM blobs WHERE state = 3" $OnA) '\[\["0"\]\]'
Wait-Same "B kept short#1 (no max age there)" "short" "kitchen" 1 $Exact $OnB
}
finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- Logs"
$LogA = Get-Content (Join-Path $Dir "a.log") -Raw
$LogB = Get-Content (Join-Path $Dir "b.log") -Raw
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"
Check "A logged deleting the parts" ($LogA -match "deleted 2 attachment parts") "checked"
$Other = ($LogA + "`n" + $LogB) -split "`r?`n" | Where-Object { $_ -match "Failed|invalid|unexpected|doesn't decrypt|SHA-256" -and $_ -notmatch "Refused a request" }
Check "no failure in A's or B's log" ($Other.Count -eq 0) ($Other -join " / ")
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }