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

Protocol 6: node identities, error codes, Synchronous, schema v8, examples

- Protocol 5: a client authenticates as a node (Node), its pushes go to the
  section's DefaultTopic unless they name one; old Identities refused at
  start with what to write instead.
- Topics listed by name, ids picked and kept by the server; nodes come from
  client sections, [BakaShrot.Nodes] optional, AcceptNodes = * by default.
- Protocol 6: every refusal carries a code, every client failure too
  (BakaShrot_ErrorCodes.pbi, BakaShrot_GetLastError(), ErrorCode in Python);
  nothing reconnects by itself, delivery is at least once.
- [BakaShrot.Server] Synchronous = FULL (default) or NORMAL, benchmarked.
- Schema v8: browse table and browse_messages view for database tools.
- Tools renamed BakaShrot<Name>, wait for Enter when started from Explorer.
- Examples/SingleServer: a server and a client with scripts (example keys,
  public on purpose).
- Restart-Test.ps1: servers killed mid-traffic and mid-catch-up.
- Docs: one server per node rule, DatabaseError() checked per thread,
  release notes' Compatibility section, Notes "Right now".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVQrLqMQPw9AZnsHqQH
This commit is contained in:
2026-11-09 23:57:55 +01:00
parent df61ef9719
commit 488ffe4bc8
67 changed files with 3163 additions and 1029 deletions
-1
View File
@@ -51,7 +51,6 @@ Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s)
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")
+16 -13
View File
@@ -26,7 +26,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -71,7 +71,7 @@ function Wait-Port($Port, $S) {
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
@@ -87,7 +87,7 @@ function Push($Data, $Ini, [string]$Attach = "") {
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Attach) { $A += @("-a", $Attach) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
function New-File($Name, [int64]$Size, [int]$Seed) {
$P = Join-Path $Dir $Name
@@ -112,7 +112,6 @@ foreach ($Name in "a", "b") {
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($Me.Priv)
Topic = logs
Node = server$Name
[BakaShrot.Topics]
@@ -140,24 +139,26 @@ 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
Node = server$PeerName
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
PushTopics = logs;other;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.garage]
PublicKeys = $($G.Pub)
Identities = logs:garage
Node = garage
DefaultTopic = logs
PushTopics = logs
ReadTopics = logs
"@
@@ -165,7 +166,7 @@ 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])"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`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
@@ -223,7 +224,7 @@ try {
$Copy = Join-Path $Dir "big-from-b.bin"
$D = (Get-Date).AddSeconds(90)
do {
$R = Tool "GetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
$R = Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 500
} while ((Get-Date) -lt $D)
@@ -260,7 +261,7 @@ db.commit(); print("flipped")
$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
Expect "reading it from A: the client refuses it" (Tool "BakaShrotGetAttachment.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
@@ -268,7 +269,7 @@ db.commit(); print("flipped")
$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
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
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"\]\]'
@@ -280,7 +281,9 @@ finally {
}
"--- Logs"
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -match "invalid|unexpected|doesn't decrypt" }
# Refusals are what this test asks for, their codes' names (InvalidRequest)
# aren't bad packets.
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|doesn't decrypt" }
Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ")
""
+22 -22
View File
@@ -1,5 +1,5 @@
# End-to-end test of attachments (Design/Attachments.md), through the tools
# (PushMessage -a, GetAttachment, GetLatestMessage):
# (BakaShrotPushMessage -a, BakaShrotGetAttachment, BakaShrotGetLatestMessage):
# - 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;
@@ -21,7 +21,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -62,7 +62,7 @@ function Wait-Port($Port, $S) {
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
$D = (Get-Date).AddSeconds($Seconds)
@@ -79,7 +79,7 @@ function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") {
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
if ($Attach) { $A += @("-a", $Attach) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
# A file of Size random bytes.
function New-File($Name, [int]$Size, [int]$Seed) {
@@ -93,16 +93,16 @@ function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA
# 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)
$R = Tool "BakaShrotGetAttachment.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.
# Retries BakaShrotGetAttachment 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)
$R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
@@ -114,7 +114,6 @@ $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]
@@ -144,17 +143,18 @@ 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
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
PushTopics = logs;short
ReadTopics = *
AllowQuery = 1
@@ -163,7 +163,6 @@ AllowQuery = 1
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Topic = logs
Node = serverB
[BakaShrot.Topics]
@@ -190,17 +189,18 @@ 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
Node = serverA
DefaultTopic = logs
[BakaShrot.Client.garage]
PublicKeys = $($K.Pub)
Identities = photos:garage
Node = garage
DefaultTopic = photos
PushTopics = photos
ReadTopics = *
AllowQuery = 1
@@ -209,7 +209,7 @@ 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])"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`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
@@ -241,10 +241,10 @@ try {
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
Expect "#5 has none: refused" (Tool "BakaShrotGetAttachment.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\}$"
Expect "a message that doesn't exist: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1
Expect "BakaShrotGetLatestMessage: #5, no attachment line" (Tool "BakaShrotGetLatestMessage.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"\]\]'
@@ -255,16 +255,16 @@ try {
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
Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "BakaShrotGetAttachment.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\}"
Expect "B: BakaShrotGetLatestMessage logs:kitchen, #5 has none" (Tool "BakaShrotGetLatestMessage.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\}"
Expect "A: the latest of photos:garage" (Tool "BakaShrotGetLatestMessage.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
+22 -14
View File
@@ -34,6 +34,7 @@
# powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1
# ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run
# ... -Topology Mesh -PeerSyncInterval 1 variations
# ... -Synchronous NORMAL the servers' Synchronous (FULL by default)
# ... -Names Wildcard each server only names its own nodes, and
# takes the others' by AcceptNodes = n*
# ... -Parts Ramp only part 1
@@ -62,6 +63,10 @@ param(
[int]$PushSeconds = 30,
[int]$PeerSyncInterval = 5,
[int]$PeerBatchSize = 100,
# The servers' [BakaShrot.Server] Synchronous: FULL like their default,
# NORMAL to compare with the runs from before 2026-11-09.
[ValidateSet("FULL", "NORMAL")]
[string]$Synchronous = "FULL",
[int]$PortBase = 13001,
[string]$Ramp = "5x5,5x20,5x50,5x100,5x0,10x20,10x50,10x100,10x0",
[int[]]$SeedTotals = @(250000, 1000000),
@@ -138,7 +143,7 @@ function Invoke-Build {
@("Tests\Bench\BenchServer.pb", "BenchServer.exe", @("/CONSOLE", "/THREAD")),
@("Tests\Bench\BenchClient.pb", "BenchClient.exe", @("/CONSOLE", "/THREAD")),
@("Tests\Bench\BenchSeed.pb", "BenchSeed.exe", @("/CONSOLE")),
@("Tools\KeyGen\KeyGen.pb", "KeyGen.exe", @("/CONSOLE")))) {
@("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE")))) {
Write-Host "Compiling $($Item[0])"
$Flags = $Item[2] + $Extra
& $Pb (Join-Path $Root $Item[0]) @Flags /QUIET $OutputFlag (Join-Path $OutDir $Item[1])
@@ -147,8 +152,8 @@ function Invoke-Build {
}
function New-KeyPair {
$Lines = & (Join-Path $OutDir "KeyGen.exe")
if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" }
$Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe")
if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" }
return @{
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
@@ -203,7 +208,17 @@ function New-Servers {
function Write-ServerConfig($Server, $Servers, $ClientKeys) {
$LastNode = $Server.FirstNode + $MaxNodesPerServer - 1
$Identities = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { "${TopicId}:$_" }) -join ";"
# The bench's one key writes as every node: a client section per node.
$ClientSections = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { @"
[BakaShrot.Client.bench$_]
PublicKeys = $($ClientKeys.PublicKey)
Node = $_
DefaultTopic = $TopicId
AllowRead = 1
AllowWrite = 1
AllowQuery = 1
"@ }) -join "`r`n"
# Only named topics and nodes replicate, and they must be named on both
# ends (Declared): every server names every node of every server, with
@@ -224,7 +239,6 @@ function Write-ServerConfig($Server, $Servers, $ClientKeys) {
$Text = @"
[BakaShrot]
PrivateKey = $($Server.PrivateKey)
Topic = $TopicId
Node = $($Server.NodeId)
[BakaShrot.Topics]
@@ -241,14 +255,9 @@ DatabasePath = $($Server.DatabasePath)
PeerRetryDelay = 2
PeerSyncInterval = $PeerSyncInterval
PeerBatchSize = $PeerBatchSize
Synchronous = $Synchronous
[BakaShrot.Client.bench]
PublicKeys = $($ClientKeys.PublicKey)
Identities = $Identities
AllowRead = 1
AllowWrite = 1
AllowQuery = 1
$ClientSections
"@
foreach ($PeerIndex in $Server.Peers) {
$Peer = $Servers[$PeerIndex]
@@ -256,14 +265,13 @@ AllowQuery = 1
[BakaShrot.Peer.$($Peer.Name)]
Host = 127.0.0.1
Port = $($Peer.Port)
Topic = $TopicId
Node = $($Peer.NodeId)
PublicKey = $($Peer.PublicKey)
$(if ($Names -eq "Wildcard") { "AcceptNodes = n*" })
[BakaShrot.Client.$($Peer.Name)]
PublicKeys = $($Peer.PublicKey)
Identities = ${TopicId}:$($Peer.NodeId)
Node = $($Peer.NodeId)
AllowRead = 0
AllowWrite = 0
AllowQuery = 0
+1 -2
View File
@@ -35,7 +35,7 @@
; FirstNode, MaxNodes Its nodes are FirstNode to FirstNode+MaxNodes-1,
; all of them are monitored.
; NodeCount How many of them push in this stage, from FirstNode.
; MonitorNode, QueryNode Identities used by the sampler and the queries.
; MonitorNode, QueryNode Nodes used by the sampler and the queries.
; QueryLoad, Query 0/1, see above.
;
; Query file: one query per line, "Name | SQL", # starts a comment.
@@ -312,7 +312,6 @@ EndProcedure
Procedure.i Bench_Connect(*Outbound.BakaShrot_Outbound, *Server.BenchServer, NodeId.i)
Protected Identity.BakaShrot_OutboundIdentity
Identity\Topic = Str(Bench_TopicId)
Identity\Node = Str(NodeId)
Identity\PublicKey = Bench_PublicKey
Identity\PrivateKey = @Bench_PrivateKey(0)
+25 -25
View File
@@ -21,7 +21,7 @@ $MaxPacketSize = 16 * 1024 * 1024
$MaxMessageSize = $MaxPacketSize - 4096
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -63,7 +63,7 @@ function Wait-Port($Port, $S) {
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
# Waits until Sql answers something matching Pattern, for up to Seconds.
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) {
@@ -75,7 +75,7 @@ function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) {
} while ((Get-Date) -lt $D)
$R
}
# A JSON message of exactly Size bytes, in a file, as PushMessage's @File.
# A JSON message of exactly Size bytes, in a file, as BakaShrotPushMessage's @File.
function New-Message($Name, [int]$Size) {
$P = Join-Path $Dir "$Name.json"
$Head = '{"n":"' + $Name + '","pad":"'
@@ -112,7 +112,6 @@ $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]
@@ -134,17 +133,18 @@ PeerRetryDelay = 1
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12404
Topic = logs
Node = serverB
PublicKey = $($B.Pub)
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Identities = logs:serverB
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
@@ -152,7 +152,6 @@ AllowQuery = 1
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Topic = logs
Node = serverB
[BakaShrot.Topics]
@@ -174,17 +173,18 @@ PeerRetryDelay = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12403
Topic = logs
Node = serverA
PublicKey = $($A.Pub)
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Identities = logs:serverA
Node = serverA
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
@@ -192,7 +192,7 @@ AllowQuery = 1
$ServerKeys = @{ 12403 = $A.Pub; 12404 = $B.Pub }
function Client-Ini($Name, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$OnA = Client-Ini "kitchen-a" 12403
@@ -222,15 +222,15 @@ try {
$Id = 0
foreach ($N in $Sizes.Keys) {
$Id++
$T = Measure-Command { $R = Tool "PushMessage.exe" @($Files[$N], $OnA) }
$T = Measure-Command { $R = Tool "BakaShrotPushMessage.exe" @($Files[$N], $OnA) }
Expect ("push of {0:N0} bytes ({1:N0} ms)" -f $Sizes[$N], $T.TotalMilliseconds) $R "message #$Id"
}
Expect "a push 1 byte over the cap is refused" (Tool "PushMessage.exe" @($Over, $OnA)) "too big" 1
Expect "a push 1 byte over the cap is refused" (Tool "BakaShrotPushMessage.exe" @($Over, $OnA)) "too big" 1
$Id++
Expect "a small push after them" (Tool "PushMessage.exe" @($Small, $OnA)) "message #$Id"
Expect "a small push after them" (Tool "BakaShrotPushMessage.exe" @($Small, $OnA)) "message #$Id"
"--- Read back"
$T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 }
$T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 }
$Code = $LASTEXITCODE
Check "latest is the small one" ($Code -eq 0 -and ($O -join "") -match '"n":"small"') ($O -join " | ")
$R = Query "SELECT message_id, length(message_data) FROM data WHERE node_id = 2 ORDER BY message_id" $OnA
@@ -245,25 +245,25 @@ try {
"--- Read back the biggest, from B"
# Pushed after the small one, so it's the latest.
$Id++
Expect "push the biggest again" (Tool "PushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id"
Expect "push the biggest again" (Tool "BakaShrotPushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id"
$null = Wait-Query "SELECT max(message_id) FROM data WHERE node_id = 30" $OnB "`"$Id`"" 60
$T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 }
$T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 }
$Code = $LASTEXITCODE
$Json = if ($O.Count -ge 2) { [string]$O[1] } else { "" }
Check ("GetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars")
Check ("BakaShrotGetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars")
"--- Many small ones still go in batches"
1..30 | ForEach-Object { $null = Tool "PushMessage.exe" @($Small, $OnA) }
1..30 | ForEach-Object { $null = Tool "BakaShrotPushMessage.exe" @($Small, $OnA) }
$R = Wait-Query "SELECT count(*) FROM data WHERE node_id = 30" $OnB '"35"' 30
Expect "35 on B" $R '\[\["35"\]\]'
"--- Not JSON: stored as is, flagged"
Expect "1 MB of broken JSON is stored" (Tool "PushMessage.exe" @("@$Broken", $OnA)) "message #36"
Expect "plain text is stored" (Tool "PushMessage.exe" @("@$Text", $OnA)) "message #37"
Expect "1 MB of broken JSON is stored" (Tool "BakaShrotPushMessage.exe" @("@$Broken", $OnA)) "message #36"
Expect "plain text is stored" (Tool "BakaShrotPushMessage.exe" @("@$Text", $OnA)) "message #37"
Expect "flagged is_json = 0 on A, the rest 1" (Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 2 AND message_id >= 35 ORDER BY message_id" $OnA) '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]'
$R = Wait-Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 30 AND message_id >= 35 ORDER BY message_id" $OnB '"37"' 30
Expect "replicated and flagged the same on B" $R '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]'
$O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1
$O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1
Check "read back as is from B" ($LASTEXITCODE -eq 0 -and [string]$O[1] -eq "just some text, not JSON") ($O -join " | ")
"--- is_json for the edge cases (SQLite's json_valid(), RFC 8259)"
@@ -275,7 +275,7 @@ try {
$Id++
$F = Join-Path $Dir "case$Id.txt"
[IO.File]::WriteAllText($F, $C[0])
$R = Tool "PushMessage.exe" @("@$F", $OnA)
$R = Tool "BakaShrotPushMessage.exe" @("@$F", $OnA)
$Q = Query "SELECT is_json FROM data WHERE node_id = 2 AND message_id = $Id" $OnA
Check ("'{0}' stored, is_json = {1}" -f $C[0], $C[1]) ($R.Out -match "message #$Id" -and $Q.Out -match ('"rows":\[\["{0}"\]\]' -f $C[1])) ($R.Out + " / " + $Q.Out)
}
@@ -303,7 +303,7 @@ 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|Retrying|disconnected|aborted|didn't answer") { $End-- }
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"
}
$LogA = Read-Log "a"
+30 -29
View File
@@ -1,6 +1,6 @@
# End-to-end test of reading runs of messages: the GetMessages request
# (Commons/Networking/Packets/GetMessagesPacket.pbi), through the client DLL
# and Tools\GetMessages: from the start, after an id, after the latest one,
# and Tools\BakaShrotGetMessages: from the start, after an id, after the latest one,
# with a limit, answers split at ~1 MB, data that isn't JSON or spans lines,
# refusals, and --follow picking up new pushes.
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
@@ -17,7 +17,7 @@ $Port = 12405
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -37,7 +37,7 @@ function Check([string]$What, [bool]$Ok, [string]$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)
}
# The ids GetMessages printed, in order.
# The ids BakaShrotGetMessages printed, in order.
function Ids($Result) {
@($Result.Lines | Where-Object { $_ -match "^\d+`t" } | ForEach-Object { [long]($_ -split "`t", 2)[0] })
}
@@ -51,7 +51,7 @@ function Push($Data, $Ini, [string]$Topic = "") {
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
$S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
@@ -59,7 +59,6 @@ $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($S.Priv)
Topic = logs
Node = server
[BakaShrot.Topics]
@@ -79,20 +78,22 @@ DatabasePath = $(Join-Path $Dir "server.sqlite")
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
PushTopics = logs;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.lounge]
PublicKeys = $($L.Pub)
Identities = logs:lounge
Node = lounge
DefaultTopic = logs
ReadTopics = logs
"@
function Client-Ini($Name, $Keys) {
$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 = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
$P
}
$Kitchen = Client-Ini "kitchen" $K
@@ -114,10 +115,10 @@ try {
# --- Nothing yet ----------------------------------------------------------
$R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen)
Check "No messages yet: nothing printed, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
Check "--after latest with no messages yet: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
# --- 120 small ones -------------------------------------------------------
@@ -130,50 +131,50 @@ try {
}
Check "120 pushes" ($Pushed -eq 120) ("{0} pushed in {1:N1} s" -f $Pushed, ((Get-Date) - $Started).TotalSeconds)
$R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen)
$Ids = Ids $R
Check "Default: the first 100, in order" ($R.Code -eq 0 -and (Is-Run $Ids 1 100)) ("[{0}] {1} ids, {2}..{3}" -f $R.Code, $Ids.Count, $Ids[0], $Ids[-1])
Check "Each line is the id, a tab and the data as stored" ($R.Lines[0] -eq "1`t{`"i`":1}" -and $R.Lines[99] -eq "100`t{`"i`":100}") ("'{0}' / '{1}'" -f $R.Lines[0], $R.Lines[99])
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen)
Check "--limit 0: all 120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen)
Check "--after 115: 116-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 116 120)) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen)
Check "--after 10 --limit 7: 11-17" ($R.Code -eq 0 -and (Is-Run (Ids $R) 11 17)) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
Check "--after the last one: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
Check "--after latest: nothing" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "GetMessages.exe" @("1", "5", "--after", "118", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("1", "5", "--after", "118", $Kitchen)
Check "By ids (1, 5): 119-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 119 120)) ("[{0}] {1}" -f $R.Code, $R.Out)
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge)
Check "Another client allowed to read logs: 101-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 101 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
# --- Refusals -------------------------------------------------------------
$null = Push '{"s":1}' $Kitchen "secret"
$R = Tool "GetMessages.exe" @("secret", "kitchen", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Kitchen)
Check "A topic in ReadTopics (*): read" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 1)) ("[{0}] {1}" -f $R.Code, $R.Out)
Expect "A topic not in ReadTopics: refused" (Tool "GetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1
Expect "Unknown node: refused" (Tool "GetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1
Expect "Unknown topic: refused" (Tool "GetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1
$R = Tool "GetMessages.exe" @("logs", "empty", $Kitchen)
Expect "A topic not in ReadTopics: refused" (Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1
Expect "Unknown node: refused" (Tool "BakaShrotGetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1
Expect "Unknown topic: refused" (Tool "BakaShrotGetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1
$R = Tool "BakaShrotGetMessages.exe" @("logs", "empty", $Kitchen)
Check "A known node with no messages: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
Expect "Bad --after: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1
Expect "Unknown option: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1
Expect "Bad --after: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1
Expect "Unknown option: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1
# --- Data that isn't one line of JSON -------------------------------------
$null = Push "plain text, not JSON" $Kitchen
$null = Push "two`nlines" $Kitchen
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
Check "Non-JSON data printed as stored, a line break spans lines" (
$R.Code -eq 0 -and $R.Lines.Count -eq 3 -and $R.Lines[0] -eq "121`tplain text, not JSON" -and $R.Lines[1] -eq "122`ttwo" -and $R.Lines[2] -eq "lines"
) ($R.Lines -join " / ")
@@ -189,7 +190,7 @@ try {
}
Check "6 big pushes (5 x 600 KB, 3 MB)" ($BigOk -eq 6) "$BigOk pushed"
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen)
$Ids = Ids $R
$Lengths = @($R.Lines | ForEach-Object { (($_ -split "`t", 2)[1]).Length })
$WantLengths = @($Sizes | ForEach-Object { $_ })
@@ -197,13 +198,13 @@ try {
$R.Code -eq 0 -and (Is-Run $Ids 123 128) -and (($Lengths -join ",") -eq ($WantLengths -join ","))
) ("[{0}] ids {1}, lengths {2}" -f $R.Code, ($Ids -join ","), ($Lengths -join ","))
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen)
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen)
Check "--limit 2 over big ones: 123-124" ($R.Code -eq 0 -and (Is-Run (Ids $R) 123 124)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
# --- --follow ---------------------------------------------------------------
$FollowOut = Join-Path $Dir "follow.out"
$Follower = Start-Process -FilePath (Join-Path $Build "GetMessages.exe") `
$Follower = Start-Process -FilePath (Join-Path $Build "BakaShrotGetMessages.exe") `
-ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" `
-WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru
$null = $Follower.Handle
-2
View File
@@ -54,7 +54,6 @@ Check(Bool(OpenCryptRandom()), "Opened the secure random generator")
; --- 1. Client -> Server: Hello ---------------------------------------------
ClientHello\ClientTopic = "logs"
ClientHello\ClientNode = "34"
ClientHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"
Check(Bool(CryptRandomData(@ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize)), "Client made a session key")
@@ -69,7 +68,6 @@ MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(*ServerHello), "Server decoded the hello")
Check(Bool(*ServerHello\ClientTopic = "logs"), "Hello's ClientTopic survived")
Check(Bool(*ServerHello\ClientNode = "34"), "Hello's ClientNode survived")
Check(Bool(*ServerHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"), "Hello's ClientPubKeyB64 survived")
Check(CompareMemory(@*ServerHello\ClientSessionKey[0], @ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize), "Hello's ClientSessionKey survived")
+252 -57
View File
@@ -14,7 +14,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -52,16 +52,15 @@ function Wait-Port($Port, $S) {
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair; $R = New-KeyPair
# --- Server A: new keys, logs = 1, sensors = 2 -----------------------------
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Topic = logs
Node = serverA
[BakaShrot.Topics]
@@ -78,6 +77,7 @@ garage = 5
kitchen-2 = 6
blocal = 20
bsecret = 21
reader = 30
[BakaShrot.Server]
Host = 127.0.0.1
@@ -90,30 +90,39 @@ PeerRetryDelay = 1
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12402
Topic = logs
Node = serverB
PublicKey = $($B.Pub)
AcceptTopics = logs
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Identities = logs:serverB
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
PushTopics = logs;sensors*
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.kitchen2]
PublicKeys = $($K2.Pub)
Identities = logs:kitchen-2
Node = kitchen-2
DefaultTopic = logs
PushTopics = logs;sensors.temp
[BakaShrot.Client.garage]
PublicKeys = $($G.Pub)
Identities = logs:garage
Node = garage
DefaultTopic = logs
; No DefaultTopic: its pushes must name their topic.
[BakaShrot.Client.reader]
PublicKeys = $($R.Pub)
Node = reader
PushTopics = logs
"@
# --- Server B: the old key names, logs = 200, sensors = 201 ----------------
@@ -125,7 +134,6 @@ function Write-B([string]$Kitchen) {
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
TopicId = logs
NodeId = serverB
[BakaShrot.Topics]
@@ -151,7 +159,6 @@ PeerRetryDelay = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12401
TopicId = logs
NodeId = serverA
PublicKey = $($A.Pub)
AcceptTopics = logs;sensors;sensors.*
@@ -160,11 +167,30 @@ SendNodes = blocal;9
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Identities = logs:serverA
Node = serverA
DefaultTopic = logs
; One key, three nodes: a section each.
[BakaShrot.Client.local]
PublicKeys = $($BC.Pub)
Identities = sensors:blocal;logs:9;logs:bsecret
Node = blocal
DefaultTopic = sensors
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.local9]
PublicKeys = $($BC.Pub)
Node = 9
DefaultTopic = logs
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.localsecret]
PublicKeys = $($BC.Pub)
Node = bsecret
DefaultTopic = logs
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
@@ -172,13 +198,14 @@ AllowQuery = 1
}
Write-B "7"
# New key names, except garage's (TopicId / NodeId, by ids).
# New key names, except garage's (NodeId, by id). No Topic: the server's
# DefaultTopic for each client says where its pushes go.
$ServerKeys = @{ 12401 = $A.Pub; 12402 = $B.Pub }
function Client-Ini($Name, $Keys, $Topic, $Node, $Port, [switch]$OldKeys) {
$P = Join-Path $Dir "$Name.ini"
$TK = "Topic"; $NK = "Node"
if ($OldKeys) { $TK = "TopicId"; $NK = "NodeId" }
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$TK = $Topic`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$NK = "Node"
if ($OldKeys) { $NK = "NodeId" }
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$Kitchen = Client-Ini "kitchen" $K "logs" "kitchen" 12401
@@ -187,6 +214,9 @@ $Local = Client-Ini "local" $BC "sensors" "blocal" 12402
$Anon = Client-Ini "anon" $BC "logs" "9" 12402
$BSecret = Client-Ini "bsecret" $BC "logs" "bsecret" 12402
$Kitchen2 = Client-Ini "kitchen2" $K2 "logs" "kitchen-2" 12401
$Reader = Client-Ini "reader" $R "logs" "reader" 12401
# reader's key, but kitchen's node: its section only gives it reader.
$Impostor = Client-Ini "impostor" $R "logs" "kitchen" 12401
Set-Content (Join-Path $Dir "m1.json") -Encoding Ascii -Value '{"temp":21}'
Set-Content (Join-Path $Dir "m2.json") -Encoding Ascii -Value '{"temp":22,"where":"kitchen"}'
Set-Content (Join-Path $Dir "m3.json") -Encoding Ascii -Value '{"from":"b-local"}'
@@ -196,59 +226,64 @@ $SA = Start-Srv "a"; $SB = Start-Srv "b"
try {
Wait-Port 12401 $SA; Wait-Port 12402 $SB
"--- Server A: pushes and the push filter"
Expect "kitchen pushes into its own topic (logs)" (Tool "PushMessage.exe" @($M1, $Kitchen)) "message #1"
Expect "kitchen pushes into sensors by name" (Tool "PushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1"
Expect "kitchen pushes into logs by id" (Tool "PushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2"
Expect "kitchen can't push into secret" (Tool "PushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1
Expect "unknown topic refused" (Tool "PushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "Unknown topic 'nope'" 1
Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "PushMessage.exe" @($M1, $Garage)) "message #1"
Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1"
Expect "kitchen-2 pushes into logs" (Tool "PushMessage.exe" @($M1, $Kitchen2)) "message #1"
Expect "kitchen-2 pushes into sensors.temp" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1"
Expect "kitchen-2 can't push into sensors" (Tool "PushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1
Expect "kitchen pushes into its own topic (logs)" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen)) "message #1"
Expect "kitchen pushes into sensors by name" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1"
Expect "kitchen pushes into logs by id" (Tool "BakaShrotPushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2"
Expect "kitchen can't push into secret" (Tool "BakaShrotPushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1
Expect "unknown topic refused, with its code" (Tool "BakaShrotPushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "\(UnknownName\): Unknown topic 'nope'" 1
Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Garage)) "message #1"
Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1"
Expect "kitchen-2 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen2)) "message #1"
Expect "kitchen-2 pushes into sensors.temp" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1"
Expect "kitchen-2 can't push into sensors" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1
"--- Server A: identities (a node per key, the default topic the server's)"
Expect "reader (no DefaultTopic) can't push without naming a topic" (Tool "BakaShrotPushMessage.exe" @($M1, $Reader)) "\(NoDefaultTopic\): No default topic for this client" 1
Expect "reader pushes when it names one" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Reader)) "message #1"
Expect "reader's key can't write as kitchen" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Impostor)) "Failed to connect and authenticate to [^ ]+ \(AuthRejected\)" 1
"--- Server A: reads and the read filter"
Expect "garage reads logs:kitchen by name" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)"
Expect "garage reads it by ids, case-insensitive name" (Tool "GetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2"
Expect "garage can't read sensors (default ReadTopics)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1
Expect "kitchen reads sensors (ReadTopics = *)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)"
Expect "garage reads logs:kitchen by name" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)"
Expect "garage reads it by ids, case-insensitive name" (Tool "BakaShrotGetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2"
Expect "garage can't read sensors (default ReadTopics)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1
Expect "kitchen reads sensors (ReadTopics = *)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)"
"--- Server A: resolving and listing"
Expect "kitchen resolves topic sensors" (Tool "Resolve.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2"
Expect "kitchen resolves topic id 1" (Tool "Resolve.exe" @("topic", "1", $Kitchen)) "topic logs = 1"
Expect "kitchen resolves node garage" (Tool "Resolve.exe" @("node", "garage", $Kitchen)) "node garage = 5"
Expect "garage can't resolve sensors (no access)" (Tool "Resolve.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1
Expect "kitchen can resolve secret (it may query)" (Tool "Resolve.exe" @("topic", "secret", $Kitchen)) "topic secret = 3"
Expect "kitchen lists every topic (it may query)" (Tool "ListNames.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config"
Expect "garage lists only the topics it can use" (Tool "ListNames.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs"
Expect "the nodes, as JSON" (Tool "ListNames.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])'
Expect "kitchen resolves topic sensors" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2"
Expect "kitchen resolves topic id 1" (Tool "BakaShrotResolveIds.exe" @("topic", "1", $Kitchen)) "topic logs = 1"
Expect "kitchen resolves node garage" (Tool "BakaShrotResolveIds.exe" @("node", "garage", $Kitchen)) "node garage = 5"
Expect "garage can't resolve sensors (no access)" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1
Expect "kitchen can resolve secret (it may query)" (Tool "BakaShrotResolveIds.exe" @("topic", "secret", $Kitchen)) "topic secret = 3"
Expect "kitchen lists every topic (it may query)" (Tool "BakaShrotList.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config"
Expect "garage lists only the topics it can use" (Tool "BakaShrotList.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs"
Expect "the nodes, as JSON" (Tool "BakaShrotList.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])'
"--- Server A: queries by name through the view"
Expect "messages view, by names" (Query "SELECT topic, node, message_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $Kitchen) '\[\["logs","kitchen","1"\],\["logs","kitchen","2"\]\]'
"--- Replication, A -> B, translated (logs 1 -> 200, kitchen 2 -> 7)"
Start-Sleep -Seconds 4
Expect "B has logs:kitchen, under its own ids" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)"
Expect "B has sensors:kitchen" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)"
Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "GetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1
Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)"
Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "GetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)"
Expect "B: both new ones" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)"
Expect "B has logs:kitchen, under its own ids" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)"
Expect "B has sensors:kitchen" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)"
Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1
Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)"
Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)"
Expect "B: both new ones" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)"
Expect "B: added from the peer, nothing else" (Query "SELECT 'topic', name, topic_id FROM topics WHERE origin = 'peer' UNION ALL SELECT 'node', name, node_id FROM nodes WHERE origin = 'peer'" $Local) '\[\["topic","sensors.temp","65535"\],\["node","kitchen-2","65535"\]\]'
Expect "B's view: same messages by name" (Query "SELECT topic, node, message_id, topic_id, node_id FROM messages WHERE topic = 'sensors'" $Local) '\[\["sensors","kitchen","1","201","7"\]\]'
"--- Replication, B -> A: only what A names and takes (AcceptTopics = logs)"
Expect "B's local pushes into sensors" (Tool "PushMessage.exe" @($M3, $Local)) "message #1"
Expect "B's local pushes into logs" (Tool "PushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1"
Expect "B's local pushes into extra" (Tool "PushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1"
Expect "B's unnamed node 9 pushes into logs" (Tool "PushMessage.exe" @($M3, $Anon)) "message #1"
Expect "B's bsecret pushes into logs" (Tool "PushMessage.exe" @($M3, $BSecret)) "message #1"
Expect "B's local pushes into sensors" (Tool "BakaShrotPushMessage.exe" @($M3, $Local)) "message #1"
Expect "B's local pushes into logs" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1"
Expect "B's local pushes into extra" (Tool "BakaShrotPushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1"
Expect "B's unnamed node 9 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $Anon)) "message #1"
Expect "B's bsecret pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $BSecret)) "message #1"
Start-Sleep -Seconds 4
Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}'
Expect "A didn't get sensors:blocal (not accepted)" (Tool "GetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1
Expect "A didn't get logs:9 (unnamed)" (Tool "GetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1
Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "GetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1
Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]'
Expect "A got logs:blocal (ids 1:20)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}'
Expect "A didn't get sensors:blocal (not accepted)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1
Expect "A didn't get logs:9 (unnamed)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1
Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1
Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["logs","reader","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]'
} finally {
Stop-Srv $SA; Stop-Srv $SB
}
@@ -258,6 +293,9 @@ $Refusals = @(Get-Content (Join-Path $Dir "a.log"), (Join-Path $Dir "b.log") | S
$Ok = $Refusals.Count -eq 0
if (-not $Ok) { $Fails++ }
"{0} no replication refusals in either log`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $(if ($Ok) { "none" } else { $Refusals -join " | " })
$Ok = (Get-Content (Join-Path $Dir "a.log") -Raw) -match "isn't allowed to write as node kitchen with its public key"
if (-not $Ok) { $Fails++ }
"{0} A logged why the impostor was refused" -f $(if ($Ok) { "PASS" } else { "FAIL" })
"A:"; Get-Content (Join-Path $Dir "a.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" }
"B:"; Get-Content (Join-Path $Dir "b.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" }
@@ -276,8 +314,165 @@ Write-B "7"
$SB = Start-Srv "b"
try {
Wait-Port 12402 $SB
Expect "B starts, kitchen still 7" (Tool "ListNames.exe" @("nodes", $Local)) "\s+7 kitchen\s+config"
Expect "B starts, kitchen still 7" (Tool "BakaShrotList.exe" @("nodes", $Local)) "\s+7 kitchen\s+config"
} finally { Stop-Srv $SB }
"--- The old Identities (before protocol 5): refused at start, saying what to write"
(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "Node = garage\r?\nDefaultTopic = logs", "Identities = logs:garage" | Set-Content (Join-Path $Dir "old.ini") -Encoding Ascii
$SO = Start-Srv "old"
$Exited = $SO.P.WaitForExit(10000)
if (-not $Exited) { Stop-Srv $SO }
$Log = Get-Content (Join-Path $Dir "old.log") -Raw
$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "write Node = garage and DefaultTopic = logs instead of Identities = logs:garage"
if (-not $Ok) { $Fails++ }
"{0} refused, with what to write instead`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Identities" | Select-Object -First 1)
# --- C and D: topics listed without ids, no nodes listed at all ------------
# The servers pick the ids, the nodes come from the sections (C's own, its
# peer's, its client's), D takes the client's node from C as it comes.
$C = New-KeyPair; $D = New-KeyPair; $KC = New-KeyPair
# LF line endings on purpose: the names sections are read by hand, the
# Preferences library misreads a bare name there (Config.pbi).
function Write-C([string]$Topics, [string]$Sync = "NORMAL") {
$Text = @"
[BakaShrot]
PrivateKey = $($C.Priv)
Node = serverC
[BakaShrot.Topics]
$Topics
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12401
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "c.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
Synchronous = $Sync
[BakaShrot.Peer.d]
Host = 127.0.0.1
Port = 12402
Node = serverD
PublicKey = $($D.Pub)
[BakaShrot.Client.d]
PublicKeys = $($D.Pub)
Node = serverD
AllowWrite = 0
[BakaShrot.Client.kitchen]
PublicKeys = $($KC.Pub)
Node = kitchen
DefaultTopic = logs
ReadTopics = *
"@
[IO.File]::WriteAllText((Join-Path $Dir "c.ini"), ($Text -replace "`r`n", "`n"))
}
Write-C "logs`nsensors"
Set-Content (Join-Path $Dir "d.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($D.Priv)
Node = serverD
[BakaShrot.Topics]
logs
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12402
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "d.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.c]
Host = 127.0.0.1
Port = 12401
Node = serverC
PublicKey = $($C.Pub)
[BakaShrot.Client.c]
PublicKeys = $($C.Pub)
Node = serverC
AllowWrite = 0
[BakaShrot.Client.watcher]
PublicKeys = $($KC.Pub)
Node = watcher
ReadTopics = *
"@
$ServerKeys[12401] = $C.Pub; $ServerKeys[12402] = $D.Pub
$KitchenC = Client-Ini "kitchen-c" $KC "logs" "kitchen" 12401
$Watcher = Client-Ini "watcher" $KC "logs" "watcher" 12402
"--- C and D: names without ids"
$SC = Start-Srv "c"; $SD = Start-Srv "d"
try {
Wait-Port 12401 $SC; Wait-Port 12402 $SD
Expect "C gives the listed topics ids, in order" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config"
Expect "C names its own, its peer's and its client's nodes" (Tool "BakaShrotList.exe" @("nodes", $KitchenC)) "\s1 serverC\s+config.*\s2 serverD\s+config.*\s3 kitchen\s+config"
Expect "kitchen pushes to its DefaultTopic" (Tool "BakaShrotPushMessage.exe" @($M1, $KitchenC)) "message #1"
$Deadline = (Get-Date).AddSeconds(15)
do {
$R = Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Watcher)
if ($R.Code -eq 0) { break }
Start-Sleep -Milliseconds 300
} while ((Get-Date) -lt $Deadline)
Expect "D took logs:kitchen though it never named kitchen (AcceptNodes = * by default)" $R "logs:kitchen#1 \(ids 1:65535\)"
} finally {
Stop-Srv $SC; Stop-Srv $SD
}
"--- C again, its topics reordered and a new one first: the ids stay"
Write-C "alpha`nsensors`nlogs"
$SC = Start-Srv "c"
try {
Wait-Port 12401 $SC
Expect "logs and sensors keep 1 and 2, alpha gets 3" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config.*\s3 alpha\s+config"
Expect "kitchen's message still under logs" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $KitchenC)) "logs:kitchen#1 \(ids 1:3\)"
} finally { Stop-Srv $SC }
"--- Synchronous: C ran with NORMAL, D with the default FULL, OFF is refused"
$Ok = ((Get-Content (Join-Path $Dir "c.log") -Raw) -match "is ready \(synchronous NORMAL\)") -and ((Get-Content (Join-Path $Dir "d.log") -Raw) -match "is ready \(synchronous FULL\)")
if (-not $Ok) { $Fails++ }
"{0} C logged NORMAL, D FULL" -f $(if ($Ok) { "PASS" } else { "FAIL" })
Write-C "logs" "OFF"
$SO = Start-Srv "c"
$Exited = $SO.P.WaitForExit(10000)
if (-not $Exited) { Stop-Srv $SO }
$Log = Get-Content (Join-Path $Dir "c.log") -Raw
$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "Synchronous = OFF isn't allowed"
if (-not $Ok) { $Fails++ }
"{0} Synchronous = OFF refused at start`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Synchronous" | Select-Object -First 1)
"--- browse / browse_messages, as a database tool uses them (C stopped)"
$PythonExe = Get-Command python -ErrorAction SilentlyContinue
if ($PythonExe) {
Set-Content (Join-Path $Dir "browse.py") -Encoding Ascii -Value @'
import sqlite3, sys
db = sqlite3.connect(sys.argv[1])
db.execute("PRAGMA foreign_keys = ON") # like SQLiteStudio
print("rows", db.execute("SELECT COUNT(*) FROM browse").fetchone()[0])
db.execute("UPDATE browse SET topic = 'logs', node = NULL"); db.commit()
print("logs", db.execute("SELECT node, message_id, attachment_size FROM browse_messages").fetchall())
db.execute("UPDATE browse SET topic = 'LOGS', node = 'kitchen'"); db.commit()
print("kitchen", db.execute("SELECT node, message_id FROM browse_messages").fetchall())
try:
db.execute("UPDATE browse SET topic = 'nope'"); db.commit(); print("bad accepted")
except sqlite3.IntegrityError:
print("bad refused")
db.execute("UPDATE browse SET topic = 'sensors', node = NULL"); db.commit()
print("sensors", db.execute("SELECT COUNT(*) FROM browse_messages").fetchone()[0])
'@
$Out = (& $PythonExe.Source -B (Join-Path $Dir "browse.py") (Join-Path $Dir "c.sqlite") 2>&1) -join " | "
$Ok = $Out -eq "rows 1 | logs [('kitchen', 1, None)] | kitchen [('kitchen', 1)] | bad refused | sensors 0"
if (-not $Ok) { $Fails++ }
"{0} one row, a topic shows its messages, a node narrows them, an unknown topic is refused`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $Out
} else {
"SKIP browse: no python on the PATH"
}
""
if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED" }
if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED"; exit 1 }
+9 -6
View File
@@ -20,7 +20,7 @@ $Port = 12406
$ProxyPort = 12407
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -33,7 +33,6 @@ $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($S.Priv)
Topic = logs
Node = server
[BakaShrot.Topics]
@@ -52,20 +51,22 @@ DatabasePath = $(Join-Path $Dir "server.sqlite")
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
PushTopics = logs;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.lounge]
PublicKeys = $($L.Pub)
Identities = logs:lounge
Node = lounge
DefaultTopic = logs
ReadTopics = logs
"@
function Client-Ini($Name, $Keys) {
$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 = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
$P
}
$Kitchen = Client-Ini "kitchen" $K
@@ -89,7 +90,9 @@ try {
& $Python (Join-Path $PSScriptRoot "..\Interactors\Python\check_bakashrot.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $Lounge
$Code = $LASTEXITCODE
$Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -match "invalid|unexpected|Failed|decrypt|sealed" })
# Refusals are expected (the checks ask for them), their codes' names
# (QueryFailed, InvalidRequest) aren't problems.
$Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|Failed|decrypt|sealed" })
if ($Bad.Count) { "FAIL Server log: $($Bad -join ' / ')"; $Code = 1 } else { "PASS Server log: no invalid or unexpected packets" }
# The wire: encrypted, tampering and a wrong server key refused. Another
+278
View File
@@ -0,0 +1,278 @@
# End-to-end test of a server killed mid-traffic and restarted (a crash,
# not a clean stop): what it acknowledged survives, its ids carry on where
# they stopped, and the two servers catch up with each other both ways.
#
# Two linked servers, A and B, each with its own client node pushing
# (kitchen on A, garage on B: one writer per topic/node pair) through
# Tests/restart_pusher.py, as fast as acknowledgements come back:
# 1. B killed while both push; A keeps pushing while B is down; B
# restarted: every push it acknowledged is there, no gap, its next id
# follows, and both servers end up with the same messages.
# 2. B killed again a fraction of a second into that catch-up, restarted:
# still converges.
# 3. A killed while both push (the other direction), restarted: same.
# The servers are killed with Stop-Process -Force (TerminateProcess), like
# a crash. Synchronous is the default (FULL); a killed process loses
# nothing committed with NORMAL either, only a power loss would.
#
# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe, and Python 3 on the
# PATH (the pushers use Interactors/Python/bakashrot.py). Uses ports
# 12415-12416.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Restart-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"), [string]$Python = "python")
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_restarttest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Dll = Join-Path $Build "BakaShrot_Client.dll"
$Pusher = Join-Path $PSScriptRoot "restart_pusher.py"
$Fails = 0
$PythonExe = (Get-Command $Python -ErrorAction SilentlyContinue)
if (-not $PythonExe) { "FAIL no Python ($Python), the pushers need it"; exit 1 }
$PythonExe = $PythonExe.Source
function New-KeyPair {
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.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 Start-Srv($Name) {
$Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Stop -ErrorAction SilentlyContinue
# Each run its own log, the previous ones are kept for a look.
$script:Runs[$Name] = 1 + [int]$script:Runs[$Name]
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir ("{0}.{1}.log" -f $Name, $script:Runs[$Name])) -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 Kill-Srv($S) {
Stop-Process -Id $S.P.Id -Force
$null = $S.P.WaitForExit(10000)
}
function Wait-Port($Port, $S) {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($S.P.HasExited) { throw "$($S.Name) exited" }
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
Start-Sleep -Milliseconds 100
}
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir ("q-" + [guid]::NewGuid().ToString("N") + ".sql"); Set-Content $F -Encoding Ascii -Value $Sql
$R = Tool "BakaShrotQuery.exe" @("@$F", $Ini)
Remove-Item $F
$R
}
# A pusher in the background: Name's out file gets "<id> <seq>" per
# acknowledged push, then STOPPED or ERR.
function Start-Pusher($Name, $Ini) {
$Out = Join-Path $Dir "$Name.out"; $Stop = Join-Path $Dir "$Name.stop"
Remove-Item $Out, $Stop -ErrorAction SilentlyContinue
$P = Start-Process -FilePath $PythonExe -ArgumentList "-B", "`"$Pusher`"", "`"$Dll`"", "`"$Ini`"", "`"$Stop`"", "`"$Out`"", $Name `
-WorkingDirectory $Build -WindowStyle Hidden -PassThru
$null = $P.Handle
@{ P = $P; Out = $Out; Stop = $Stop; Name = $Name }
}
function Stop-Pusher($Pu) {
Set-Content $Pu.Stop "x"
if (-not $Pu.P.WaitForExit(15000)) { Stop-Process -Id $Pu.P.Id -Force }
}
# What a pusher saw: how many acknowledged, the last id and seq, how it ended.
function Read-Pusher($Pu) {
$Lines = @(Get-Content $Pu.Out -ErrorAction SilentlyContinue)
$Acked = @($Lines | Where-Object { $_ -match "^\d+ \d+$" })
$Last = if ($Acked.Count) { $Acked[-1] -split " " } else { @("0", "0") }
@{ Count = $Acked.Count; LastId = [int64]$Last[0]; LastSeq = [int]$Last[1]; End = [string]($Lines | Select-Object -Last 1) }
}
# Every node of logs on a server: count, first and last id, and sums over
# the data and the push times, to compare two servers.
$StatsSql = "SELECT node, COUNT(*), MIN(message_id), MAX(message_id), SUM(length(message_data)), SUM(pushed_at % 1000003), SUM(message_id * length(message_data)) FROM messages WHERE topic = 'logs' GROUP BY node ORDER BY node"
function Stats($Ini) {
$R = Query $StatsSql $Ini
if ($R.Code -ne 0) { return "query failed: " + $R.Out }
($R.Out -replace '^.*"rows":', '')
}
# The highest id and the count of a node on a server.
function Head($Node, $Ini) {
$R = Query "SELECT COUNT(*), COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'logs' AND node = '$Node'" $Ini
if ($R.Out -match '\[\["(\d+)","(\d+)"\]\]') { @{ Count = [int64]$Matches[1]; Max = [int64]$Matches[2] } } else { @{ Count = -1; Max = -1; Out = $R.Out } }
}
# Waits until A and B have the same messages, and at least Kitchen and
# Garage messages of each node. Returns the stats, and whether they matched.
function Wait-Converged($Kitchen, $Garage, $Seconds = 60) {
$D = (Get-Date).AddSeconds($Seconds)
do {
$SA = Stats $OnA; $SB = Stats $OnB
$HK = Head "kitchen" $OnB; $HG = Head "garage" $OnA
if ($SA -eq $SB -and $HK.Count -ge $Kitchen -and $HG.Count -ge $Garage) { return @{ Ok = $true; A = $SA; B = $SB } }
Start-Sleep -Milliseconds 250
} while ((Get-Date) -lt $D)
@{ Ok = $false; A = $SA; B = $SB }
}
# What a restarted server must show for the node its pusher wrote to: every
# acknowledged push there (ids 1..max without a gap, max at least the last
# acknowledged one, its data the one acknowledged), and at most one more
# (committed, the answer lost with the kill). Leaves the node's head in
# $Survived: a function's return value would take its PASS/FAIL lines too.
function Check-Survived($What, $Node, $Pu, $Ini) {
$Seen = Read-Pusher $Pu
$H = Head $Node $Ini
Check "$What`: every acknowledged push survived, ids without a gap" `
($Seen.LastId -gt 0 -and $H.Count -eq $H.Max -and $H.Max -ge $Seen.LastId -and $H.Max -le $Seen.LastId + 1) `
("{0} acknowledged, last #{1}; stored {2}, last #{3}; pusher: {4}" -f $Seen.Count, $Seen.LastId, $H.Count, $H.Max, $Seen.End)
$R = Query "SELECT message_data FROM messages WHERE topic = 'logs' AND node = '$Node' AND message_id = $($Seen.LastId)" $Ini
Check "$What`: the last acknowledged one is the one pushed" ($R.Out -match ('\\"seq\\":' + $Seen.LastSeq + '[,}]')) $R.Out
$script:Survived = $H
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair
$Runs = @{}
# Topics listed by name, nodes from the sections: a restart must give every
# name its id back, by the database.
function Write-Config($Name, $Keys, $Port, $Node, $PeerName, $PeerPort, $PeerNode, $PeerKey, $ClientNode, $ClientKey) {
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($Keys.Priv)
Node = $Node
[BakaShrot.Topics]
logs
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "$Name.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
PeerBatchSize = 10
[BakaShrot.Peer.$PeerName]
Host = 127.0.0.1
Port = $PeerPort
Node = $PeerNode
PublicKey = $PeerKey
[BakaShrot.Client.$PeerName]
PublicKeys = $PeerKey
Node = $PeerNode
AllowWrite = 0
[BakaShrot.Client.$ClientNode]
PublicKeys = $ClientKey
Node = $ClientNode
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
}
Write-Config "a" $A 12415 "serverA" "b" 12416 "serverB" $B.Pub "kitchen" $K.Pub
Write-Config "b" $B 12416 "serverB" "a" 12415 "serverA" $A.Pub "garage" $G.Pub
Set-Content (Join-Path $Dir "kitchen.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = 12415`r`nServerPublicKey = $($A.Pub)"
Set-Content (Join-Path $Dir "garage.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($G.Priv)`r`nPublicKey = $($G.Pub)`r`nNode = garage`r`nServerHost = 127.0.0.1`r`nServerPort = 12416`r`nServerPublicKey = $($B.Pub)"
$OnA = Join-Path $Dir "kitchen.ini"; $OnB = Join-Path $Dir "garage.ini"
Set-Content (Join-Path $Dir "next.json") -Encoding Ascii -Value '{"after":"restart"}'
$Next = "@" + (Join-Path $Dir "next.json")
$SA = Start-Srv "a"; $SB = Start-Srv "b"
$Pushers = @()
try {
Wait-Port 12415 $SA; Wait-Port 12416 $SB
"--- 1. B killed while both push, A keeps pushing, B restarted"
$PK = Start-Pusher "kitchen-1" $OnA; $PG = Start-Pusher "garage-1" $OnB; $Pushers += $PK, $PG
Start-Sleep -Seconds 3
Kill-Srv $SB
$null = $PG.P.WaitForExit(15000)
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
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
Check-Survived "B" "garage" $PG $OnB
$HG = $Survived
$R = Tool "BakaShrotPushMessage.exe" @($Next, $OnB)
Check "B: the next push carries on from the last id" ($R.Out -match "message #$($HG.Max + 1)\b") ("after #{0}: {1}" -f $HG.Max, $R.Out)
$C = Wait-Converged $KSeen.LastId ($HG.Max + 1)
Check "A and B converged (B caught up on kitchen, A on garage)" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
"--- 2. B killed again in the middle of its catch-up"
$Before = (Head "kitchen" $OnB).Count
$PK = Start-Pusher "kitchen-2" $OnA; $Pushers += $PK
Start-Sleep -Seconds 1
Kill-Srv $SB
Start-Sleep -Seconds 6 # a backlog for B
Stop-Pusher $PK
$Total = (Head "kitchen" $OnA).Max
$SB = Start-Srv "b"; Wait-Port 12416 $SB
# Killed as soon as some of the backlog is in, not all of it.
$D = (Get-Date).AddSeconds(30)
do {
$Mid = Head "kitchen" $OnB
if ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) { Kill-Srv $SB; break }
Start-Sleep -Milliseconds 20
} while ($Mid.Count -lt $Total -and (Get-Date) -lt $D)
Check "B killed partway through its catch-up" ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) `
("B had {0} kitchen messages before, {1} when killed, A {2}" -f $Before, $Mid.Count, $Total)
if (-not $SB.P.HasExited) { Kill-Srv $SB }
$SB = Start-Srv "b"; Wait-Port 12416 $SB
$C = Wait-Converged $Total 0
Check "B restarted, still converged" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
$H = Head "kitchen" $OnB
Check "B's copy of kitchen has no gap" ($H.Count -eq $H.Max -and $H.Max -eq $Total) ("{0} stored, last #{1}, A's last #{2}" -f $H.Count, $H.Max, $Total)
"--- 3. A killed while both push, B keeps pushing, A restarted"
$PK = Start-Pusher "kitchen-3" $OnA; $PG = Start-Pusher "garage-3" $OnB; $Pushers += $PK, $PG
Start-Sleep -Seconds 3
Kill-Srv $SA
$null = $PK.P.WaitForExit(15000)
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
$SA = Start-Srv "a"; Wait-Port 12415 $SA
Check-Survived "A" "kitchen" $PK $OnA
$HK = $Survived
$R = Tool "BakaShrotPushMessage.exe" @($Next, $OnA)
Check "A: the next push carries on from the last id" ($R.Out -match "message #$($HK.Max + 1)\b") ("after #{0}: {1}" -f $HK.Max, $R.Out)
$C = Wait-Converged ($HK.Max + 1) $GSeen.LastId
Check "A and B converged again" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
"--- Logs"
$Bad = @(Get-ChildItem $Dir -Filter "*.log" | Select-String "Failed|refused|corrupt|malformed" | Where-Object { $_.Line -notmatch "Failed to connect|Lost the link|link to .* failed" })
Check "no failure in either server's logs, other than the links lost to the kills" ($Bad.Count -eq 0) $(if ($Bad.Count) { ($Bad | Select-Object -First 5 | ForEach-Object { "$($_.Filename): $($_.Line)" }) -join " | " } else { "none" })
} finally {
foreach ($Pu in $Pushers) { if (-not $Pu.P.HasExited) { Stop-Process -Id $Pu.P.Id -Force } }
Stop-Srv $SA; Stop-Srv $SB
}
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+22 -22
View File
@@ -1,8 +1,8 @@
# End-to-end test of pushed_at and [BakaShrot.Retention]:
# - a database from before pushed_at gets it (the time of the upgrade), and
# its ids go on;
# - a push is stamped with the time it arrived (UTC), GetMessages --time
# and GetLatestMessage show it, replication carries it as is;
# - a push is stamped with the time it arrived (UTC), BakaShrotGetMessages
# --time and BakaShrotGetLatestMessage show it, replication carries it as is;
# - each server deletes a topic's messages past its own max age (by name,
# by pattern, "*"), only its own: the peer keeps its copies;
# - after deleting, ids go on, and the peer doesn't send them again;
@@ -27,7 +27,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
function New-KeyPair {
$L = & (Join-Path $Build "KeyGen.exe")
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
}
function Test-Port($P) {
@@ -68,7 +68,7 @@ function Wait-Port($Port, $S) {
}
function Query($Sql, $Ini) {
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
Tool "Query.exe" @("@$F", $Ini)
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
}
# Waits until Sql answers something matching Pattern, for up to Seconds.
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
@@ -90,7 +90,7 @@ function Push($Data, $Ini, [string]$Topic = "") {
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
@@ -99,7 +99,6 @@ $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]
@@ -128,17 +127,18 @@ RetentionInterval = 1
[BakaShrot.Peer.b]
Host = 127.0.0.1
Port = 12409
Topic = logs
Node = serverB
PublicKey = $($B.Pub)
[BakaShrot.Client.b]
PublicKeys = $($B.Pub)
Identities = logs:serverB
Node = serverB
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
PushTopics = logs;short;keep;late
ReadTopics = *
AllowQuery = 1
@@ -148,7 +148,6 @@ AllowQuery = 1
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($B.Priv)
Topic = logs
Node = serverB
[BakaShrot.Topics]
@@ -180,17 +179,18 @@ RetentionInterval = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12408
Topic = logs
Node = serverA
PublicKey = $($A.Pub)
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Identities = logs:serverA
Node = serverA
DefaultTopic = logs
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
Node = kitchen
DefaultTopic = logs
ReadTopics = *
AllowQuery = 1
"@
@@ -198,7 +198,7 @@ AllowQuery = 1
$ServerKeys = @{ 12408 = $A.Pub; 12409 = $B.Pub }
function Client-Ini($Name, $Port) {
$P = Join-Path $Dir "$Name.ini"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
$P
}
$OnA = Client-Ini "kitchen-a" 12408
@@ -253,17 +253,17 @@ try {
$Expected = [DateTimeOffset]::FromUnixTimeMilliseconds($Stamp).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
Check "the view's pushed_utc is the same, as text" ($Utc -eq $Expected) "$Utc, expected $Expected"
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA)
Check "GetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA)
Check "GetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out
Expect "GetLatestMessage shows it" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected))
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA)
Check "BakaShrotGetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA)
Check "BakaShrotGetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out
Expect "BakaShrotGetLatestMessage shows it" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected))
$Sql = "SELECT message_id, pushed_at FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id"
$OnAStamps = (Query $Sql $OnA).Out
$R = Wait-Query $Sql $OnB '"3","\d+"'
Check "replicated with the same pushed_at, every one" ($R.Out -eq $OnAStamps) "A $OnAStamps | B $($R.Out)"
Expect "GetLatestMessage on B: the same time" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected))
Expect "BakaShrotGetLatestMessage on B: the same time" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected))
"--- Retention on A (short = 3s), not on B (short = forever)"
foreach ($i in 1..3) { Expect "push short #$i" (Push "{`"short`":$i}" $OnA "short") "message #$i" }
@@ -273,7 +273,7 @@ try {
Check "A deleted them past 3 s" ($R.Out -match '\[\["0"\]\]') $R.Out
Expect "A kept logs (no max age)" (Query (Count "logs") $OnA) '\[\["3"\]\]'
Expect "B kept them (its own rules)" (Query (Count "short") $OnB) '\[\["3"\]\]'
Expect "A: no message left in short" (Tool "GetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1
Expect "A: no message left in short" (Tool "BakaShrotGetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1
Expect "A's ids go on after deleting: #4" (Push '{"short":4}' $OnA "short") "message #4"
$R = Wait-Query (Count "short") $OnB '\[\["4"\]\]' 10
Check "B got #4" ($R.Out -match '\[\["4"\]\]') $R.Out
@@ -290,7 +290,7 @@ try {
Expect "push keep #3" (Push '{"keep":3}' $OnA "keep") "message #3"
$R = Wait-Query (Count "keep") $OnB '\[\["1"\]\]' 10
Check "B only got #3, not #1 and #2 again" ($R.Out -match '\[\["1"\]\]') $R.Out
Expect "B: it's #3" (Tool "GetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3"
Expect "B: it's #3" (Tool "BakaShrotGetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3"
Expect "B's * = 1h keeps logs" (Query (Count "logs") $OnB) '\[\["3"\]\]'
"--- Replicated already past the max age (B: late = 3s)"
+35
View File
@@ -0,0 +1,35 @@
"""Pushes as fast as the server acknowledges, for Tests/Restart-Test.ps1.
Usage: restart_pusher.py <BakaShrot_Client.dll> <client.ini> <stop file> <out file> <tag>
Pushes {"by": tag, "seq": n} to the client's DefaultTopic until the stop
file exists, writing "<message id> <seq>" to the out file once each push is
acknowledged. Ends with "STOPPED", or "ERR <code> <why>" when the server
goes away (the test kills it; code 104, ConnectionLost): what was
acknowledged before is what must survive.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python"))
from bakashrot import BakaShrotError, Client # noqa: E402
dll_path, ini_path, stop_path, out_path, tag = sys.argv[1:6]
client = Client.from_ini(ini_path, dll_path)
with open(out_path, "a", buffering=1) as out:
try:
client.connect()
seq = 0
while not os.path.exists(stop_path):
seq += 1
message_id = client.push({"by": tag, "seq": seq})
out.write(f"{message_id} {seq}\n")
out.write("STOPPED\n")
except BakaShrotError as error:
out.write(f"ERR {int(error.code)} {type(error).__name__}: {error}\n")
finally:
try:
client.close()
except BakaShrotError:
pass
+8 -5
View File
@@ -84,18 +84,21 @@ class Proxy:
base = Client.from_ini(ini_path, dll_path)
proxy = Proxy(proxy_port, base.host, base.port)
marker = "wire-marker-7f3a91"
# The client's DefaultTopic in Python-Test.ps1's server config: its pushes
# land there, and it reads them back from there.
topic = "logs"
client = Client(base.private_key, base.public_key, base.server_public_key, base.topic, base.node,
client = Client(base.private_key, base.public_key, base.server_public_key, base.node,
"127.0.0.1", proxy_port, dll_path)
# Through the proxy, all of it recorded.
try:
client.connect()
message_id = client.push({"note": marker})
latest = client.latest(base.topic, base.node)
latest = client.latest(topic, base.node)
check("Pushed and read back through the proxy", latest is not None and marker in latest.data,
latest.data if latest else "nothing")
pages = client.get_messages(base.topic, base.node, after=message_id - 1, limit=10)
pages = client.get_messages(topic, base.node, after=message_id - 1, limit=10)
check("Read as a run of messages too", any(marker in m.data for m in pages.messages))
client.close()
except BakaShrotError as error:
@@ -104,7 +107,7 @@ except BakaShrotError as error:
wire_up, wire_down = bytes(proxy.to_server), bytes(proxy.to_client)
check("Something went through both ways", len(wire_up) > 200 and len(wire_down) > 200,
f"{len(wire_up)} bytes up, {len(wire_down)} down")
for needle in (marker, str(base.node), str(base.topic), base.public_key):
for needle in (marker, str(base.node), topic, base.public_key):
shown = needle.encode("utf-8")
check(f"'{needle[:20]}' never in plain text on the wire", shown not in wire_up and shown not in wire_down)
@@ -122,7 +125,7 @@ except BakaShrotError as error:
check("A tampered request drops the connection", False, "couldn't connect: " + str(error))
# Another server's key: the server can't open the Hello, nor sign for it.
impostor = Client(base.private_key, base.public_key, other_key, base.topic, base.node,
impostor = Client(base.private_key, base.public_key, other_key, base.node,
base.host, base.port, dll_path)
try:
impostor.connect()