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

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
+658
View File
@@ -0,0 +1,658 @@
# ============================================================================
# BakaShrot replication benchmark
#
# Runs several servers linked as peers on localhost (by default 4 in a Y: one
# hub linked to 3 leaves), each with its own nodes pushing to it, and
# measures, stage by stage:
# - the push path: achieved vs offered rate, latency, failures
# - replication: lag on every server while pushing, whether it keeps up
# (trough slope, see Bench_TroughSlope() in BenchClient.pb), and how long
# it takes to drain once the pushes stop
# - every server's CPU and RAM, and its database's size
# - a query suite (queries.txt) after every stage, as the data grows
#
# Three parts:
# 1. Ramp: from an empty database, stages of -Ramp ("NodesxRate", Rate per
# node in msg/s, 0 = as fast as the server answers), to find where the
# push path and the replication saturate.
# 2. Scale: seeds every database up to each of -SeedTotals rows (identical
# on every server, see BenchSeed.pb), then runs -SteadyStage and the
# query suite at that size: how check-ins and queries hold up with
# lots of data.
# 3. Mixed: -MixedStage with queries_load.txt running in a loop against
# the hub meanwhile: reads under write load, and writes under reads.
#
# Results go into Build\Bench\runs\<timestamp>\: configs, per-stage samples
# (CSV, one row per sample), summaries (JSON), and report.md / results.json
# for the whole run.
# The databases and server logs go into -DataDir\<timestamp>\ instead, out of
# the repo: every push rewrites them, and file watchers on the repo (git
# caches, editors) otherwise burn a core or two reacting to it, skewing the
# CPU numbers. The databases are deleted at the end, unless -KeepData.
#
# Usage:
# powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1
# ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run
# ... -Topology Mesh -PeerSyncInterval 1 variations
# ... -Names Wildcard each server only names its own nodes, and
# takes the others' by AcceptNodes = n*
# ... -Parts Ramp only part 1
# Keep -PushSeconds at 6+ times PeerSyncInterval for the trough slope to mean
# something.
#
# ... -Compiler "C:\Program Files\PureBasic_640\Compilers\pbcompilerc.exe" `
# -CompilerFlags "/OPTIMIZER" PB 6.40, C backend
#
# Needs: PureBasic 5.73 x64 (found by itself, or -Compiler), libsodium
# extracted in Libs\libsodium\x64 (see Build.ps1), and a sqlite3.dll with
# the JSON functions (3.38+): Libs\sqlite\x64\sqlite3.dll by default, or
# -SqliteDll.
# Everything runs on one machine: the load generator competes with the
# servers for the CPU, its own CPU use is in the report.
# ============================================================================
param(
[ValidateSet("Y", "Chain", "Mesh")]
[string]$Topology = "Y",
[ValidateSet("Declared", "Wildcard")]
[string]$Names = "Declared",
[int]$ServerCount = 4,
[int]$MaxNodesPerServer = 10,
[int]$MessageSize = 200,
[int]$PushSeconds = 30,
[int]$PeerSyncInterval = 5,
[int]$PeerBatchSize = 100,
[int]$PortBase = 13001,
[string]$Ramp = "5x5,5x20,5x50,5x100,5x0,10x20,10x50,10x100,10x0",
[int[]]$SeedTotals = @(250000, 1000000),
[string]$SteadyStage = "10x10",
[string]$MixedStage = "10x10",
[string]$Parts = "Ramp,Scale,Mixed",
[int]$QueryRepeats = 3,
[int]$DrainTimeout = 180,
[string]$Compiler = "",
[string]$CompilerFlags = "",
[string]$SqliteDll = "",
[string]$DataDir = (Join-Path ([IO.Path]::GetTempPath()) "BakaShrot-Bench"),
[switch]$KeepData,
[switch]$SkipBuild
)
$ErrorActionPreference = "Stop"
# "Ramp,Scale" or "Ramp", "Scale", from -File or -Command alike.
$PartList = @($Parts -split "[, ]" | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($Part in $PartList) { if ($Part -notin @("Ramp", "Scale", "Mixed")) { throw "Unknown part $Part, use Ramp, Scale and/or Mixed" } }
$Stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$Root = Resolve-Path (Join-Path $PSScriptRoot "..\..")
$BenchDir = $PSScriptRoot
$OutDir = Join-Path $Root "Build\Bench"
$RunDir = Join-Path $OutDir "runs\$Stamp"
$RunData = Join-Path $DataDir $Stamp
$LogDir = Join-Path $RunData "logs"
$TopicId = 1
# --- Build ------------------------------------------------------------------
function Find-Compiler {
if ($Compiler) { return $Compiler }
foreach ($Candidate in @("C:\Program Files\PureBasic_573\Compilers\pbcompiler.exe",
"C:\Program Files\PureBasic573\Compilers\pbcompiler.exe")) {
if (Test-Path $Candidate) { return $Candidate }
}
throw "PureBasic 5.73 x64 not found, pass -Compiler"
}
function Copy-Dlls {
New-Item -ItemType Directory -Force $OutDir | Out-Null
$Sodium = Join-Path $Root "Libs\libsodium\x64\libsodium.dll"
if (-not (Test-Path $Sodium)) { throw "Missing $Sodium, run Build.ps1 once to extract it" }
Copy-Item $Sodium $OutDir -Force
$Sqlite = $SqliteDll
if (-not $Sqlite) { $Sqlite = Join-Path $Root "Libs\sqlite\x64\sqlite3.dll" }
if (-not (Test-Path $Sqlite)) { throw "Missing $Sqlite, run Build.ps1 once to extract it, or pass -SqliteDll" }
Copy-Item $Sqlite (Join-Path $OutDir "sqlite3.dll") -Force
Write-Host "Using SQLite $((Get-Item $Sqlite).VersionInfo.ProductVersion) from $Sqlite"
}
$script:CompilerName = "(not rebuilt, -SkipBuild)"
function Invoke-Build {
$Pb = Find-Compiler
New-Item -ItemType Directory -Force $OutDir | Out-Null
# "PureBasic 6.40 - C Backend (Windows - x64) - (c) ...", 5.73 takes /EXE,
# 6.x /OUTPUT.
$script:CompilerName = ((& $Pb /VERSION) | Select-Object -First 1) -replace " - \(c\).*$", ""
$OutputFlag = if ($script:CompilerName -match "PureBasic 5\.") { "/EXE" } else { "/OUTPUT" }
$Extra = @($CompilerFlags -split " " | Where-Object { $_ })
if ($Extra.Count -gt 0) { $script:CompilerName += " " + ($Extra -join " ") }
Write-Host "Compiler: $($script:CompilerName)"
foreach ($Item in @(
@("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")))) {
Write-Host "Compiling $($Item[0])"
$Flags = $Item[2] + $Extra
& $Pb (Join-Path $Root $Item[0]) @Flags /QUIET $OutputFlag (Join-Path $OutDir $Item[1])
if ($LASTEXITCODE -ne 0) { throw "Failed to compile $($Item[0])" }
}
}
function New-KeyPair {
$Lines = & (Join-Path $OutDir "KeyGen.exe")
if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" }
return @{
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
}
}
# --- Topology and configs -----------------------------------------------------
function Get-Edges {
$Edges = @()
switch ($Topology) {
"Y" { for ($i = 1; $i -lt $ServerCount; $i++) { $Edges += , @(0, $i) } }
"Chain" { for ($i = 0; $i -lt $ServerCount - 1; $i++) { $Edges += , @($i, ($i + 1)) } }
"Mesh" { for ($i = 0; $i -lt $ServerCount; $i++) { for ($j = $i + 1; $j -lt $ServerCount; $j++) { $Edges += , @($i, $j) } } }
}
return , $Edges
}
function New-Servers {
$Servers = @()
for ($i = 0; $i -lt $ServerCount; $i++) {
if ($Topology -eq "Y") {
if ($i -eq 0) { $Name = "hub" } else { $Name = "leaf$i" }
} else {
$Name = "s$($i + 1)"
}
$Keys = New-KeyPair
$Servers += [pscustomobject]@{
Index = $i
Name = $Name
NodeId = $i + 1
Port = $PortBase + $i
PrivateKey = $Keys.PrivateKey
PublicKey = $Keys.PublicKey
DatabasePath = Join-Path $RunData "$Name.sqlite"
ConfigPath = Join-Path $RunDir "$Name.ini"
StopFile = Join-Path $RunData "$Name.stop"
FirstNode = ($i + 1) * 100 + 1
MonitorNode = 900 + $i + 1
QueryNode = 950 + $i + 1
Peers = @()
Process = $null
}
}
foreach ($Edge in (Get-Edges)) {
$Servers[$Edge[0]].Peers += $Edge[1]
$Servers[$Edge[1]].Peers += $Edge[0]
}
return $Servers
}
function Write-ServerConfig($Server, $Servers, $ClientKeys) {
$LastNode = $Server.FirstNode + $MaxNodesPerServer - 1
$Identities = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { "${TopicId}:$_" }) -join ";"
# Only named topics and nodes replicate, and they must be named on both
# ends (Declared): every server names every node of every server, with
# the same ids. Wildcard: each server only names its own, the peers take
# them by AcceptNodes = n*, and give them ids of their own. The servers'
# own nodes are named everywhere either way: a peer authenticates by
# name, the others must know it.
$NodeNames = @()
foreach ($Other in $Servers) {
$NodeNames += "n$($Other.NodeId) = $($Other.NodeId)"
if ($Names -eq "Wildcard" -and $Other -ne $Server) { continue }
$OtherLast = $Other.FirstNode + $MaxNodesPerServer - 1
foreach ($Id in (@($Other.FirstNode..$OtherLast) + @($Other.MonitorNode, $Other.QueryNode))) {
$NodeNames += "n$Id = $Id"
}
}
$Text = @"
[BakaShrot]
PrivateKey = $($Server.PrivateKey)
Topic = $TopicId
Node = $($Server.NodeId)
[BakaShrot.Topics]
bench = $TopicId
[BakaShrot.Nodes]
$($NodeNames -join "`r`n")
[BakaShrot.Server]
Host = 127.0.0.1
Port = $($Server.Port)
ReplicatingTopics = $TopicId
DatabasePath = $($Server.DatabasePath)
PeerRetryDelay = 2
PeerSyncInterval = $PeerSyncInterval
PeerBatchSize = $PeerBatchSize
[BakaShrot.Client.bench]
PublicKeys = $($ClientKeys.PublicKey)
Identities = $Identities
AllowRead = 1
AllowWrite = 1
AllowQuery = 1
"@
foreach ($PeerIndex in $Server.Peers) {
$Peer = $Servers[$PeerIndex]
$Text += @"
[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)
AllowRead = 0
AllowWrite = 0
AllowQuery = 0
"@
}
Set-Content -Path $Server.ConfigPath -Value $Text -Encoding Ascii
}
# --- Servers ----------------------------------------------------------------
$script:StartCount = 0
function Test-Port($Port) {
$Client = New-Object System.Net.Sockets.TcpClient
try {
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
if ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected) { return $true }
return $false
} catch {
return $false
} finally {
$Client.Close()
}
}
function Start-Servers($Servers) {
$script:StartCount++
foreach ($Server in $Servers) {
Remove-Item $Server.StopFile -ErrorAction SilentlyContinue
$Log = Join-Path $LogDir "$($Server.Name)-$($script:StartCount).log"
$Server.Process = Start-Process -FilePath (Join-Path $OutDir "BenchServer.exe") `
-ArgumentList "`"$($Server.ConfigPath)`"", "`"$($Server.StopFile)`"" `
-WorkingDirectory $OutDir -NoNewWindow -PassThru `
-RedirectStandardOutput $Log -RedirectStandardError "$Log.err"
}
foreach ($Server in $Servers) {
$Deadline = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Server.Port)) {
if ($Server.Process.HasExited) { throw "$($Server.Name) exited, see its log in $LogDir" }
if ((Get-Date) -gt $Deadline) { throw "$($Server.Name) isn't listening on $($Server.Port)" }
Start-Sleep -Milliseconds 100
}
}
# Let the peers link (they retry every 2 s) and run their first check-in.
Start-Sleep -Seconds 4
Write-Host "Servers up: $(($Servers | ForEach-Object { "$($_.Name)=pid $($_.Process.Id)" }) -join ', ')"
}
function Stop-Servers($Servers) {
foreach ($Server in $Servers) {
if ($Server.Process -and -not $Server.Process.HasExited) {
Set-Content -Path $Server.StopFile -Value "stop"
}
}
foreach ($Server in $Servers) {
if ($Server.Process) {
if (-not $Server.Process.WaitForExit(30000)) {
Write-Warning "$($Server.Name) didn't stop, killing it"
$Server.Process.Kill()
}
$Server.Process = $null
}
}
}
# --- Stages -----------------------------------------------------------------
function ConvertTo-Stage($Spec) {
$Fields = $Spec.Trim().ToLower().Split("x")
return [pscustomobject]@{ Nodes = [int]$Fields[0]; Rate = [double]$Fields[1] }
}
function Write-Plan($Path, $Servers, $ClientKeys, $Stage, $Name, $QueryFile, $QueryLoad) {
$Text = @"
[Bench]
PrivateKey = $($ClientKeys.PrivateKey)
PublicKey = $($ClientKeys.PublicKey)
TopicId = $TopicId
ServerCount = $($Servers.Count)
PushSeconds = $PushSeconds
Rate = $($Stage.Rate)
MessageSize = $MessageSize
SampleMs = 1000
DrainSampleMs = 250
DrainTimeout = $DrainTimeout
PeerSyncInterval = $PeerSyncInterval
SamplesCsv = $(Join-Path $RunDir "$Name.samples.csv")
SummaryOut = $(Join-Path $RunDir "$Name.summary.json")
QueryFile = $QueryFile
QueryRepeats = $QueryRepeats
QueryOut = $(Join-Path $RunDir "$Name.queries.json")
"@
foreach ($Server in $Servers) {
$ProcId = 0
if ($Server.Process) { $ProcId = $Server.Process.Id }
# The query suite runs on the hub and the first leaf, the query load
# only on the hub.
$Text += @"
[Server$($Server.Index + 1)]
Name = $($Server.Name)
Host = 127.0.0.1
Port = $($Server.Port)
PublicKey = $($Server.PublicKey)
Pid = $ProcId
DatabasePath = $($Server.DatabasePath)
FirstNode = $($Server.FirstNode)
MaxNodes = $MaxNodesPerServer
NodeCount = $($Stage.Nodes)
MonitorNode = $($Server.MonitorNode)
QueryNode = $($Server.QueryNode)
QueryLoad = $([int]($QueryLoad -and $Server.Index -eq 0))
Query = $([int]($Server.Index -le 1))
"@
}
Set-Content -Path $Path -Value $Text -Encoding Ascii
}
function Invoke-BenchClient($Mode, $Plan) {
& (Join-Path $OutDir "BenchClient.exe") $Mode $Plan | ForEach-Object { Write-Host " $_" }
if ($LASTEXITCODE -ne 0) { throw "BenchClient $Mode failed" }
}
$script:Results = @()
$script:QueryResults = @()
function Invoke-Stage($Part, $Name, $Stage, $Servers, $ClientKeys, [switch]$QueryLoad) {
$Plan = Join-Path $RunDir "$Name.plan.ini"
$LoadFile = ""
if ($QueryLoad) { $LoadFile = Join-Path $BenchDir "queries_load.txt" }
Write-Plan $Plan $Servers $ClientKeys $Stage $Name $LoadFile $QueryLoad
$RateText = if ($Stage.Rate -gt 0) { "$($Stage.Rate) msg/s" } else { "max" }
Write-Host ""
Write-Host "=== $Name : $($Stage.Nodes) nodes/server x $RateText, $PushSeconds s ===" -ForegroundColor Cyan
# Other processes busy meanwhile (antivirus scanning the databases...),
# tick-based, only good enough to spot the big ones.
$Before = @{}
Get-Process | ForEach-Object { $Before[$_.Id] = $_.CPU }
$StartTime = Get-Date
Invoke-BenchClient "run" $Plan
$Seconds = ((Get-Date) - $StartTime).TotalSeconds
$Others = Get-Process | Where-Object { $_.Name -notin @("BenchServer", "BenchClient", "Idle") -and $null -ne $_.CPU } | ForEach-Object {
$Previous = 0
if ($Before.ContainsKey($_.Id)) { $Previous = $Before[$_.Id] }
[pscustomobject]@{ Name = $_.Name; Percent = 100 * ($_.CPU - $Previous) / $Seconds }
} | Sort-Object Percent -Descending | Select-Object -First 3
$Summary = Get-Content (Join-Path $RunDir "$Name.summary.json") -Raw | ConvertFrom-Json
$Summary | Add-Member -NotePropertyName OtherProcesses -NotePropertyValue (($Others | Where-Object Percent -ge 5 | ForEach-Object { "$($_.Name) $(Format-Num $_.Percent)" }) -join ", ")
$Summary | Add-Member -NotePropertyName Stage -NotePropertyValue $Name
$Summary | Add-Member -NotePropertyName Part -NotePropertyValue $Part
$Summary | Add-Member -NotePropertyName NodesPerServer -NotePropertyValue $Stage.Nodes
$script:Results += $Summary
# The query suite, on the idle servers.
Write-Plan $Plan $Servers $ClientKeys $Stage $Name (Join-Path $BenchDir "queries.txt") $false
Invoke-BenchClient "query" $Plan
$Rows = ($Summary.Servers | Measure-Object -Property Rows -Maximum).Maximum
foreach ($Query in (Get-Content (Join-Path $RunDir "$Name.queries.json") -Raw | ConvertFrom-Json)) {
$Query | Add-Member -NotePropertyName Stage -NotePropertyValue $Name
$Query | Add-Member -NotePropertyName DataRows -NotePropertyValue $Rows
$script:QueryResults += $Query
}
return $Summary
}
function Invoke-Seed($Servers, $TargetRows, $CurrentRows) {
$Nodes = $Servers.Count * $MaxNodesPerServer
$PerNode = [math]::Ceiling(($TargetRows - $CurrentRows) / $Nodes)
if ($PerNode -le 0) { return }
$Spec = ($Servers | ForEach-Object { "$($_.FirstNode)-$($_.FirstNode + $MaxNodesPerServer - 1)" }) -join ","
Write-Host ""
Write-Host "=== Seeding to ~$TargetRows rows per server ($PerNode more per node, in every database) ===" -ForegroundColor Cyan
Stop-Servers $Servers
$Dbs = $Servers | ForEach-Object { $_.DatabasePath }
& (Join-Path $OutDir "BenchSeed.exe") $TopicId $Spec $PerNode $MessageSize @Dbs | ForEach-Object { Write-Host " $_" }
if ($LASTEXITCODE -ne 0) { throw "BenchSeed failed" }
Start-Servers $Servers
}
# --- Report -----------------------------------------------------------------
function Format-Num($Value, $Decimals = 0) {
return ([double]$Value).ToString("N$Decimals", [Globalization.CultureInfo]::InvariantCulture)
}
function Get-Verdict($Summary) {
$Notes = @()
if ($Summary.Rate -gt 0 -and $Summary.PushRate -lt 0.9 * $Summary.OfferedRate) { $Notes += "push saturated" }
if ($Summary.Failed -gt 0) { $Notes += "$($Summary.Failed) failed pushes" }
# The trough slope is too noisy for a verdict (check-ins drift against the
# windows), the lag in seconds of pushes isn't: keeping up means about
# two check-ins' worth at most, through the hub.
$MaxLagSeconds = ($Summary.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum
if ($MaxLagSeconds -gt 2 * $PeerSyncInterval + 2) { $Notes += "replication lagging" }
if (-not $Summary.Drained) { $Notes += "NOT drained" }
elseif ($Summary.DrainSeconds -gt 2 * $PeerSyncInterval + 5) { $Notes += "slow drain" }
if ($Notes.Count -eq 0) { return "ok" }
return $Notes -join ", "
}
function Get-LogIssues($Servers) {
$Issues = @()
foreach ($Server in $Servers) {
$Logs = Get-ChildItem $LogDir -Filter "$($Server.Name)-*.log"
$Counts = [ordered]@{}
foreach ($Pattern in @("Refused", "Failed", "locked", "timed out", "Dropping", "Lost the link", "too big")) {
$Counts[$Pattern] = @($Logs | Select-String -SimpleMatch $Pattern).Count
}
$Sent = @($Logs | Select-String -Pattern "\[Peer\] Sent (\d+) messages .* in (\d+) ms")
$Messages = 0; $Ms = 0
foreach ($Match in $Sent) {
$Messages += [int]$Match.Matches[0].Groups[1].Value
$Ms += [int]$Match.Matches[0].Groups[2].Value
}
$Issues += [pscustomobject]@{
Server = $Server.Name; Counts = $Counts
ReplicatedOut = $Messages; ReplicateMs = $Ms; CatchUps = $Sent.Count
}
}
return $Issues
}
function Write-Report($Servers) {
$Lines = @()
$Lines += "# BakaShrot replication benchmark, $(Get-Date -Format 'yyyy-MM-dd HH:mm')"
$Lines += ""
$Cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim()
$Ram = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB)
$Lines += "- Machine: $Cpu, $Ram GB RAM, everything on localhost"
$Lines += "- Topology: $Topology, $ServerCount servers ($(($Servers | ForEach-Object { "$($_.Name) <-> " + (($_.Peers | ForEach-Object { $Servers[$_].Name }) -join '/') }) -join '; '))"
$Lines += "- Names: $Names ($(if ($Names -eq 'Wildcard') { 'each server names its own nodes, peers take them by AcceptNodes = n*' } else { 'every node named on every server' }))"
$Lines += "- Messages: ~$MessageSize bytes of JSON, PeerSyncInterval $PeerSyncInterval s, PeerBatchSize $PeerBatchSize, $PushSeconds s per stage"
$Lines += "- Built with: $($script:CompilerName), SQLite $((Get-Item (Join-Path $OutDir 'sqlite3.dll')).VersionInfo.ProductVersion)"
$Lines += "- CPU in % of one core (100 = one core busy), System = whole machine in %, Bench = the load generator itself (% of one core)"
$Lines += ""
$Lines += "## Stages"
$Lines += ""
$Lines += "- Max lag: most messages a server was missing while pushing. Trough: the lowest lag of the last check-in window, slope: how fast those troughs rise (~0 = keeps up)."
$Lines += ""
$Lines += "| Stage | Nodes | Offered msg/s | Pushed msg/s | Push p50 / p99 / max ms | Failed | Max lag msgs (s of pushes) | Last trough | Trough slope msg/s | Drain s | Verdict |"
$Lines += "|---|---|---|---|---|---|---|---|---|---|---|"
foreach ($R in $script:Results) {
$Offered = if ($R.Rate -gt 0) { Format-Num $R.OfferedRate } else { "max" }
$Lag = ($R.Servers | Measure-Object -Property LagMaxPush -Maximum).Maximum
$LagSeconds = ($R.Servers | Measure-Object -Property LagMaxSeconds -Maximum).Maximum
$Trough = ($R.Servers | Measure-Object -Property LagTroughLast -Maximum).Maximum
$Slope = ($R.Servers | Measure-Object -Property LagSlope -Maximum).Maximum
$Drain = if ($R.Drained) { Format-Num $R.DrainSeconds 1 } else { "> $DrainTimeout" }
$Lines += "| $($R.Stage) | $($R.NodesPerServer) x $ServerCount | $Offered | $(Format-Num $R.PushRate) | $(Format-Num $R.PushP50Ms 1) / $(Format-Num $R.PushP99Ms 1) / $(Format-Num $R.PushMaxMs 0) | $($R.Failed) | $(Format-Num $Lag) ($(Format-Num $LagSeconds 1)) | $(Format-Num $Trough) | $(Format-Num $Slope 1) | $Drain | $(Get-Verdict $R) |"
}
$Lines += ""
$Lines += "## Resources while pushing"
$Lines += ""
$Header = "| Stage | System CPU avg / max | Bench CPU |"
$Sep = "|---|---|---|"
foreach ($Server in $Servers) { $Header += " $($Server.Name) CPU avg / max | $($Server.Name) RAM WS / private MB |"; $Sep += "---|---|" }
$Header += " Other busy processes (% core) |"; $Sep += "---|"
$Lines += $Header
$Lines += $Sep
foreach ($R in $script:Results) {
$Row = "| $($R.Stage) | $(Format-Num $R.SystemCpuAvg) % / $(Format-Num $R.SystemCpuMax) % | $(Format-Num $R.BenchCpuAvg) |"
foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.CpuAvgPush) / $(Format-Num $S.CpuMaxPush) | $(Format-Num $S.WorkingSetMaxMb 1) / $(Format-Num $S.PrivateMaxMb 1) |" }
$Row += " $($R.OtherProcesses) |"
$Lines += $Row
}
$Lines += ""
$Lines += "## Per server, end of stage"
$Lines += ""
$Header = "| Stage |"
$Sep = "|---|"
foreach ($Server in $Servers) { $Header += " $($Server.Name) rows | DB MB | max lag | monitor query avg / max ms |"; $Sep += "---|---|---|---|" }
$Lines += $Header
$Lines += $Sep
foreach ($R in $script:Results) {
$Row = "| $($R.Stage) |"
foreach ($S in $R.Servers) { $Row += " $(Format-Num $S.Rows) | $(Format-Num $S.DbMb 1) | $(Format-Num $S.LagMaxPush) | $(Format-Num $S.MonitorAvgMs 1) / $(Format-Num $S.MonitorMaxMs 1) |" }
$Lines += $Row
}
$Lines += ""
$Lines += "## Queries, idle, median ms (on $($Servers[0].Name))"
$Lines += ""
$Stages = $script:QueryResults | Where-Object Server -eq $Servers[0].Name | Select-Object -ExpandProperty Stage -Unique
$Names = $script:QueryResults | Select-Object -ExpandProperty Name -Unique
$Header = "| Query |"
$Sep = "|---|"
foreach ($Stage in $Stages) {
$Rows = ($script:QueryResults | Where-Object { $_.Stage -eq $Stage } | Select-Object -First 1).DataRows
$Header += " $Stage ($(Format-Num $Rows) rows) |"; $Sep += "---|"
}
$Lines += $Header
$Lines += $Sep
foreach ($Name in $Names) {
$Row = "| $Name |"
foreach ($Stage in $Stages) {
$Q = $script:QueryResults | Where-Object { $_.Stage -eq $Stage -and $_.Name -eq $Name -and $_.Server -eq $Servers[0].Name } | Select-Object -First 1
if (-not $Q) { $Row += " |" }
elseif ($Q.Count -eq 0) { $Row += " FAIL: $($Q.LastError) |" }
else { $Row += " $(Format-Num $Q.P50Ms 1) |" }
}
$Lines += $Row
}
$Lines += ""
$Mixed = $script:Results | Where-Object { $_.QueriesUnderLoad.Count -gt 0 }
foreach ($R in $Mixed) {
$Lines += "## Queries under load ($($R.Stage), on $($Servers[0].Name), while pushing $(Format-Num $R.PushRate) msg/s)"
$Lines += ""
$Lines += "| Query | Runs | p50 ms | p90 ms | max ms | Failures |"
$Lines += "|---|---|---|---|---|---|"
foreach ($Q in $R.QueriesUnderLoad) {
$Lines += "| $($Q.Name) | $($Q.Count) | $(Format-Num $Q.P50Ms 1) | $(Format-Num $Q.P90Ms 1) | $(Format-Num $Q.MaxMs 1) | $($Q.Failures) $($Q.LastError) |"
}
$Lines += ""
}
$Lines += "## Server logs"
$Lines += ""
$Lines += "| Server | Catch-ups sent | Messages replicated out | ms spent sending | Refused | Failed | locked | timed out | Dropping | Lost the link | too big |"
$Lines += "|---|---|---|---|---|---|---|---|---|---|---|"
foreach ($I in (Get-LogIssues $Servers)) {
$Lines += "| $($I.Server) | $($I.CatchUps) | $(Format-Num $I.ReplicatedOut) | $(Format-Num $I.ReplicateMs) | $(($I.Counts.Values) -join ' | ') |"
}
$Lines += ""
$Report = Join-Path $RunDir "report.md"
Set-Content -Path $Report -Value ($Lines -join "`r`n") -Encoding UTF8
@{ Results = $script:Results; Queries = $script:QueryResults } | ConvertTo-Json -Depth 8 | Set-Content (Join-Path $RunDir "results.json") -Encoding UTF8
return $Report
}
# --- Main -------------------------------------------------------------------
if (-not $SkipBuild) { Invoke-Build }
Copy-Dlls
New-Item -ItemType Directory -Force $RunDir, $LogDir | Out-Null
Write-Host "Run folder: $RunDir"
$ClientKeys = New-KeyPair
$Servers = @(New-Servers)
foreach ($Server in $Servers) { Write-ServerConfig $Server $Servers $ClientKeys }
try {
Start-Servers $Servers
$Last = $null
if ($PartList -contains "Ramp") {
$i = 0
foreach ($Spec in $Ramp.Split(",")) {
$i++
$Stage = ConvertTo-Stage $Spec
$Last = Invoke-Stage "Ramp" ("ramp{0:D2}-{1}" -f $i, $Spec.Trim()) $Stage $Servers $ClientKeys
}
}
if ($PartList -contains "Scale") {
foreach ($Target in $SeedTotals) {
$Current = 0
if ($Last) { $Current = ($Last.Servers | Measure-Object -Property Rows -Minimum).Minimum }
Invoke-Seed $Servers $Target $Current
$Last = Invoke-Stage "Scale" ("scale-{0}k" -f [math]::Round($Target / 1000)) (ConvertTo-Stage $SteadyStage) $Servers $ClientKeys
}
}
if ($PartList -contains "Mixed") {
$Last = Invoke-Stage "Mixed" "mixed" (ConvertTo-Stage $MixedStage) $Servers $ClientKeys -QueryLoad
}
}
finally {
Stop-Servers $Servers
if ($script:Results.Count -gt 0) {
$Report = Write-Report $Servers
Write-Host ""
Write-Host "Report: $Report"
}
Write-Host "Server logs: $LogDir"
if (-not $KeepData) {
Get-ChildItem $RunData -Filter "*.sqlite*" | Remove-Item -Force
} else {
Write-Host "Databases kept in $RunData"
}
}
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
; ============================================================================
; BakaShrot Bench Seed
;
; Usage: BenchSeed <TopicId> <Nodes> <RowsPerNode> <MessageSize> <Db> [Db...]
; Nodes Node ids, "101-110,201-210".
;
; Adds RowsPerNode messages to every node, identical in every database, so
; servers that were in sync stay in sync without replicating anything: a
; quick way to get millions of rows for the query and check-in benchmarks.
; Each node continues from the highest message id any database has for it,
; and INSERT OR IGNORE keeps what's already there.
; Nodes go by name ("n" + id, like Bench-Replication.ps1 names them): each
; database stores a node under its own id for that name, and gets the name
; (origin "peer", as if a peer had sent it) if it doesn't have it yet, so
; servers that take nodes by wildcard (-Names Wildcard) see them as known.
; The servers must be stopped. Same JSON as BenchClient's pushes.
;
; Used by Tests/Bench/Bench-Replication.ps1, compile as a console program.
; ============================================================================
EnableExplicit
XIncludeFile "../../Server/Storage/Storage.pbi"
#Seed_BatchSize = 50000
; The id DbId has for node "n<Node>", given that name if it has none yet.
; Returns -1 on failure.
Procedure.i Seed_LocalNode(DbId.i, Node.i)
Protected Name.s = "n" + Str(Node), Id.i = -1
SetDatabaseString(DbId, 0, Name)
If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?")
If NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
If Id >= 0
ProcedureReturn Id
EndIf
; Its own id, unless something else is named there.
SetDatabaseLong(DbId, 0, Node)
SetDatabaseString(DbId, 1, Name)
If Not DatabaseUpdate(DbId, "INSERT INTO nodes (node_id, name, origin) VALUES (?, ?, 'peer') " +
"ON CONFLICT (node_id) DO UPDATE SET name = excluded.name, origin = 'peer' WHERE origin = 'id'")
ProcedureReturn -1
EndIf
SetDatabaseString(DbId, 0, Name)
If DatabaseQuery(DbId, "SELECT node_id FROM nodes WHERE name = ?")
If NextDatabaseRow(DbId)
Id = GetDatabaseLong(DbId, 0)
EndIf
FinishDatabaseQuery(DbId)
EndIf
ProcedureReturn Id
EndProcedure
Procedure.s Seed_Json(NodeId.i, Seq.q, Pad.s)
Protected Kind.s, Value.i
If Seq % 50 = 0
Kind = "alert"
Else
Select Seq % 4
Case 0 : Kind = "temp"
Case 1 : Kind = "humidity"
Case 2 : Kind = "pressure"
Default : Kind = "status"
EndSelect
EndIf
Value = (Seq * 7919 + NodeId) % 10000
ProcedureReturn ~"{\"kind\":\"" + Kind + ~"\",\"node\":" + Str(NodeId) + ~",\"seq\":" + Str(Seq) +
~",\"value\":" + StrD(Value / 100.0, 2) + ~",\"ts\":" + Str(1700000000 + Seq) +
~",\"pad\":\"" + Pad + ~"\"}"
EndProcedure
Define TopicId.i, NodesSpec.s, RowsPerNode.i, MessageSize.i, Pad.s
Define NewList Nodes.i(), NewList Dbs.i()
Define i.i, Part.s, First.i, Last.i, Node.i, StartId.q, Id.q, MaxId.q, Count.q, StartMs.i, Total.q, d.i
Define Dim LocalIds.i(0)
OpenConsole()
If CountProgramParameters() < 5
PrintN("Usage: BenchSeed <TopicId> <Nodes> <RowsPerNode> <MessageSize> <Db> [Db...]")
End 1
EndIf
TopicId = Val(ProgramParameter(0))
NodesSpec = ProgramParameter(1)
RowsPerNode = Val(ProgramParameter(2))
MessageSize = Val(ProgramParameter(3))
If MessageSize > 90
Pad = LSet("", MessageSize - 90, "x")
EndIf
For i = 1 To CountString(NodesSpec, ",") + 1
Part = Trim(StringField(NodesSpec, i, ","))
If Part = ""
Continue
EndIf
If FindString(Part, "-")
First = Val(StringField(Part, 1, "-"))
Last = Val(StringField(Part, 2, "-"))
Else
First = Val(Part)
Last = First
EndIf
For Node = First To Last
AddElement(Nodes())
Nodes() = Node
Next
Next
For i = 4 To CountProgramParameters() - 1
AddElement(Dbs())
Dbs() = OpenStorageDatabase(ProgramParameter(i))
If Not Dbs() Or Not SetupStorageDatabase(Dbs())
PrintN("Can't open '" + ProgramParameter(i) + "': " + DatabaseError())
End 1
EndIf
Next
StartMs = ElapsedMilliseconds()
ReDim LocalIds(ListSize(Dbs()) - 1)
ForEach Nodes()
; Where every database is at for this node, continue after the furthest.
StartId = 0
d = 0
ForEach Dbs()
LocalIds(d) = Seed_LocalNode(Dbs(), Nodes())
If LocalIds(d) < 0
PrintN("Can't name node " + Str(Nodes()) + ": " + DatabaseError())
End 1
EndIf
MaxId = GetLatestMessageId(Dbs(), TopicId, LocalIds(d))
If MaxId > StartId
StartId = MaxId
EndIf
d + 1
Next
d = -1
ForEach Dbs()
d + 1
Id = StartId
While Id < StartId + RowsPerNode
If Not DatabaseUpdate(Dbs(), "BEGIN IMMEDIATE")
PrintN("BEGIN failed: " + DatabaseError())
End 1
EndIf
Count = 0
While Count < #Seed_BatchSize And Id < StartId + RowsPerNode
Id + 1
Count + 1
If Not InsertReplicatedMessage(Dbs(), TopicId, LocalIds(d), Id, Seed_Json(Nodes(), Id, Pad))
PrintN("Insert failed: " + DatabaseError())
End 1
EndIf
Wend
If Not DatabaseUpdate(Dbs(), "COMMIT")
PrintN("COMMIT failed: " + DatabaseError())
End 1
EndIf
Total + Count
Wend
Next
Next
ForEach Dbs()
CloseDatabase(Dbs())
Next
PrintN("Seeded " + Str(Total) + " rows (" + Str(RowsPerNode) + " per node, " + Str(ListSize(Nodes())) + " nodes, " + Str(ListSize(Dbs())) + " databases) in " + StrD((ElapsedMilliseconds() - StartMs) / 1000.0, 1) + " s")
End 0
+58
View File
@@ -0,0 +1,58 @@
; ============================================================================
; BakaShrot Bench Server
;
; Usage: BenchServer <ConfigFile> <StopFile>
;
; The real server (Server/Root.pbi), without the console commands: it runs
; until StopFile exists, then stops its workers cleanly and exits.
; BakaShrot_Server.exe can't run headless, with no console input its
; Input() returns Chr(4) and it stops right away, see Notes.md.
;
; Used by Tests/Bench/Bench-Replication.ps1, compile as a thread-safe console
; program.
; ============================================================================
EnableExplicit
XIncludeFile "../../Server/Root.pbi"
Define Root.BakaShrot_Root
Define StopFile.s
OpenConsole("BakaShrot Bench Server")
If CountProgramParameters() < 2
PrintN("Usage: BenchServer <ConfigFile> <StopFile>")
End 1
EndIf
Root\ConfigPath = ProgramParameter(0)
StopFile = ProgramParameter(1)
If Not BakaShrot_Root_LoadConfig(@Root)
End 1
EndIf
If Not BakaShrot_Root_OpenDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
If Not BakaShrot_Root_StartWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End 1
EndIf
PrintN("Running until '" + StopFile + "' exists.")
While FileSize(StopFile) < 0
Delay(200)
Wend
PrintN("Stopping...")
BakaShrot_Root_StopWorkers(@Root)
BakaShrot_Root_CloseDatabase(@Root)
FreeConfig(Root\Config)
End 0
+106
View File
@@ -0,0 +1,106 @@
# ============================================================================
# Compares runs of Bench-Replication.ps1 side by side, as a markdown table.
#
# Usage:
# powershell -ExecutionPolicy Bypass -File Tests\Bench\Compare-Runs.ps1 `
# -Runs "Build\Bench\runs\20261107-123413,Build\Bench\runs\20261107-125334" `
# -Labels "Before,WAL + wake-ups" [-Out comparison.md]
#
# Picks the key numbers of each run's results.json: the push ceilings, the
# latencies, replication lag and drain, CPU and RAM, the queries at the
# biggest data size, and the mixed stage. Stages missing from a run show "-".
# ============================================================================
param(
[Parameter(Mandatory = $true)] [string[]]$Runs,
[string[]]$Labels = @(),
[string]$Out = ""
)
$ErrorActionPreference = "Stop"
# "powershell -File" passes "a,b" as one string.
$Runs = @($Runs | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$Labels = @($Labels | ForEach-Object { $_ -split "," } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$Culture = [Globalization.CultureInfo]::InvariantCulture
function Format-Num($Value, $Decimals = 0) {
if ($null -eq $Value) { return "-" }
return ([double]$Value).ToString("N$Decimals", $Culture)
}
$Data = @()
for ($i = 0; $i -lt $Runs.Count; $i++) {
$Json = Get-Content (Join-Path $Runs[$i] "results.json") -Raw | ConvertFrom-Json
$Label = if ($i -lt $Labels.Count) { $Labels[$i] } else { Split-Path $Runs[$i] -Leaf }
$Data += [pscustomobject]@{ Label = $Label; Results = @($Json.Results); Queries = @($Json.Queries) }
}
# A stage by the end of its name ("5x0" matches "ramp05-5x0").
function Get-Stage($Run, $Suffix) {
return $Run.Results | Where-Object { $_.Stage -like "*$Suffix" } | Select-Object -First 1
}
function Get-Max($Stage, $Property) {
if (-not $Stage) { return $null }
return ($Stage.Servers | Measure-Object -Property $Property -Maximum).Maximum
}
function Get-Avg($Stage, $Property) {
if (-not $Stage) { return $null }
return ($Stage.Servers | Measure-Object -Property $Property -Average).Average
}
# Median of a query on the first server, in the last stage that ran it.
function Get-Query($Run, $Name) {
$Q = $Run.Queries | Where-Object { $_.Name -eq $Name -and $_.Server -eq $Run.Results[0].Servers[0].Name } | Select-Object -Last 1
if (-not $Q -or $Q.Count -eq 0) { return $null }
return $Q.P50Ms
}
function Get-LoadQuery($Run, $Name) {
$Mixed = Get-Stage $Run "mixed"
if (-not $Mixed) { return $null }
$Q = $Mixed.QueriesUnderLoad | Where-Object Name -eq $Name | Select-Object -First 1
if (-not $Q) { return $null }
return $Q.P50Ms
}
$Rows = @(
@("**Push ceiling**, msg/s, 5 nodes/server", { param($R) Format-Num (Get-Stage $R "5x0").PushRate }),
@("**Push ceiling**, msg/s, 10 nodes/server", { param($R) Format-Num (Get-Stage $R "10x0").PushRate }),
@("Pushed of 2,000 offered (10 x 50)", { param($R) Format-Num (Get-Stage $R "10x50").PushRate }),
@("Pushed of 4,000 offered (10 x 100)", { param($R) Format-Num (Get-Stage $R "10x100").PushRate }),
@("Push p50 / p99 ms, 10 x 50", { param($R) $S = Get-Stage $R "10x50"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1)" } else { "-" } }),
@("Push p50 / p99 / max ms, flat out (10 nodes)", { param($R) $S = Get-Stage $R "10x0"; if ($S) { "$(Format-Num $S.PushP50Ms 1) / $(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }),
@("Replication lag, s of pushes, flat out", { param($R) Format-Num (Get-Max (Get-Stage $R "10x0") "LagMaxSeconds") 1 }),
@("Drain after the push, s, flat out", { param($R) Format-Num (Get-Stage $R "10x0").DrainSeconds 1 }),
@("Server CPU, % of a core, flat out (avg of the 4)", { param($R) Format-Num (Get-Avg (Get-Stage $R "10x0") "CpuAvgPush") }),
@("Machine CPU %, flat out", { param($R) Format-Num (Get-Stage $R "10x0").SystemCpuAvg }),
@("Hub RAM, working set MB, max", { param($R) Format-Num (($R.Results | ForEach-Object { $_.Servers[0].WorkingSetMaxMb } | Measure-Object -Maximum).Maximum) 1 }),
@("Rows per server at the end", { param($R) Format-Num $R.Results[-1].Servers[0].Rows }),
@("Query: latest message, ms (1M rows)", { param($R) Format-Num (Get-Query $R "latest_message") 1 }),
@("Query: last 50 of a node, ms", { param($R) Format-Num (Get-Query $R "last_50_of_node") 1 }),
@("Query: sync state (GROUP BY all), ms", { param($R) Format-Num (Get-Query $R "sync_state") 1 }),
@("Query: sync state from node_heads (what check-ins use now), ms", { param($R) Format-Num (Get-Query $R "sync_state_heads") 1 }),
@("Query: JSON count over all rows, ms", { param($R) Format-Num (Get-Query $R "json_count_all") 1 }),
@("Query: JSON aggregate over all rows, ms", { param($R) Format-Num (Get-Query $R "json_agg_all") 1 }),
@("**Mixed:** pushed of 400 msg/s with a query loop", { param($R) Format-Num (Get-Stage $R "mixed").PushRate }),
@("Mixed: push p99 / max ms", { param($R) $S = Get-Stage $R "mixed"; if ($S) { "$(Format-Num $S.PushP99Ms 1) / $(Format-Num $S.PushMaxMs)" } else { "-" } }),
@("Mixed: failed pushes", { param($R) $S = Get-Stage $R "mixed"; if ($S) { $S.Failed } else { "-" } }),
@("Mixed: JSON count over all rows, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "json_count_all") 1 }),
@("Mixed: latest message, ms, under load", { param($R) Format-Num (Get-LoadQuery $R "latest_message") 1 })
)
$Lines = @()
$Lines += "| | " + (($Data | ForEach-Object { $_.Label }) -join " | ") + " |"
$Lines += "|---|" + (($Data | ForEach-Object { "---" }) -join "|") + "|"
foreach ($Row in $Rows) {
$Cells = foreach ($Run in $Data) { & $Row[1] $Run }
$Lines += "| $($Row[0]) | " + ($Cells -join " | ") + " |"
}
$Text = $Lines -join "`r`n"
if ($Out) { Set-Content -Path $Out -Value $Text -Encoding UTF8 }
$Text
+182
View File
@@ -0,0 +1,182 @@
# Benchmark results, 2026-11-07
`Bench-Replication.ps1` with its defaults: 4 servers in a Y (a hub linked to
3 leaves), 5-10 nodes pushing to each, ~200-byte JSON messages, 30 s per
stage, `PeerSyncInterval = 5`, `PeerBatchSize = 100`. All on one machine
(i5-13500, 16 GB, NVMe), PureBasic 5.73 x64 unless said otherwise, SQLite
3.54.1. Table made with `Compare-Runs.ps1`.
| Version | What changed |
|---|---|
| Before | Rollback journal, a sync to disk per push, every wait a `Delay(5)` / `Delay(1)` loop |
| WAL + wake-ups | WAL with `synchronous = NORMAL`, threads woken by an event / `select()`, a write mutex instead of SQLite's busy-wait |
| + grouping | Pushes arriving together share one transaction (group commit) |
| + no per-push log | The `PrintN()` per push / read / query removed (`#BakaShrot_Net_LogRequests`) |
| + prepared/cache/checkpoints/heads | One writer connection with prepared statements (SQLite's own API), next ids cached in memory, WAL checkpoints in a background thread, the sync state from `node_heads` (`Server/Storage/Writer.pbi`) |
| same on PB 6.40 C | The same code, built with PureBasic 6.40's C backend and `/OPTIMIZER` (the load generator too) |
| | Before | WAL + wake-ups | + grouping | + no per-push log | + prepared/cache/checkpoints/heads (5.73) | same on PB 6.40 C |
|---|---|---|---|---|---|---|
| **Push ceiling**, msg/s, 5 nodes/server | 958 | 5,771 | 5,709 | 25,681 | 33,522 | 37,162 |
| **Push ceiling**, msg/s, 10 nodes/server | 904 | 5,726 | 5,814 | 25,707 | 34,345 | 38,358 |
| Pushed of 2,000 offered (10 x 50) | 924 | 1,999 | 2,000 | 2,000 | 2,000 | 1,999 |
| Pushed of 4,000 offered (10 x 100) | 899 | 4,000 | 4,000 | 4,000 | 4,000 | 4,000 |
| Push p50 / p99 ms, 10 x 50 | 18.0 / 491.5 | 0.4 / 5.1 | 0.5 / 7.2 | 0.5 / 13.6 | 0.3 / 0.8 | 0.2 / 0.9 |
| Push p50 / p99 / max ms, flat out (10 nodes) | 18.0 / 574.9 / 2,642 | 5.5 / 25.2 / 193 | 5.6 / 23.1 / 56 | 0.9 / 16.5 / 149 | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 |
| Replication lag, s of pushes, flat out | 8.9 | 5.1 | 5.0 | 8.9 | 9.9 | 8.3 |
| Drain after the push, s, flat out | 6.2 | 5.8 | 5.8 | 10.3 | 11.3 | 11.3 |
| Server CPU, % of a core, flat out (avg of the 4) | 45 | 65 | 66 | 130 | 120 | 121 |
| Machine CPU %, flat out | 41 | 33 | 34 | 67 | 65 | 65 |
| Hub RAM, working set MB, max | 34.6 | 42.9 | 44.6 | 45.2 | 38.8 | 40.1 |
| Rows per server at the end | 1,021,883 | 1,024,025 | 1,024,025 | 1,887,117 | 2,389,201 | 2,619,806 |
| Query: latest message, ms (1M rows) | 5.9 | 0.5 | 0.5 | 0.1 | 0.1 | 0.1 |
| Query: last 50 of a node, ms | 5.8 | 1.0 | 1.0 | 0.7 | 0.8 | 0.7 |
| Query: sync state (GROUP BY all), ms | 78.0 | 73.1 | 72.1 | 131.9 | 166.7 | 184.1 |
| Query: sync state from node_heads (what check-ins use now), ms | - | - | - | - | 0.6 | 0.5 |
| Query: JSON count over all rows, ms | 473.6 | 475.1 | 475.3 | 857.5 | 1,080.7 | 1,199.4 |
| Query: JSON aggregate over all rows, ms | 1,647.8 | 1,575.8 | 1,533.9 | 2,800.2 | 3,974.2 | 4,371.2 |
| **Mixed:** pushed of 400 msg/s with a query loop | 323 | 396 | 397 | 397 | 392 | 396 |
| Mixed: push p99 / max ms | 820.2 / 5,119 | 0.7 / 17 | 7.9 / 17 | 18.0 / 30 | 1.2 / 17 | 0.9 / 17 |
| Mixed: failed pushes | 1 | 0 | 0 | 0 | 0 | 0 |
| Mixed: JSON count over all rows, ms, under load | 545.4 | 502.3 | 506.5 | 925.0 | 1,148.2 | 1,265.6 |
| Mixed: latest message, ms, under load | 12.0 | 0.2 | 0.2 | 0.1 | 0.2 | 0.2 |
The full-table scans grow with the data, and the later runs' flat-out stages
wrote more of it: 1.9M, 2.4M, then 2.6M rows per server instead of ~1.02M.
Per row they cost the same (~0.45 ms per 1,000 rows for the JSON count).
PB 6.40 doesn't change them either, SQLite does the scanning.
## What limited each version
- **Before:** the sync to disk on every push, ~250 commits/s per database.
- **WAL + wake-ups:** not the database anymore. The `PrintN()` logging every
push takes ~0.4 ms and serializes every thread behind it: ~2,400 pushes/s
per server whatever the number of nodes, with the server mostly idle
(measured on a single server: the listener asleep in `select()` 91 % of
the time, the writes busy 33 %, 0.14 ms per push).
- **+ grouping:** same cap, so no gain yet: the pushes never piled up
behind the write mutex (1.0 per transaction on average). It did cut the
worst push from 193 to 56 ms.
- **+ no per-push log:** a single server went from ~2,400 to ~12,000
pushes/s, and grouping now kicks in: 2.5 pushes per transaction at 5
nodes, ~5-9 at 10-20, the database busy 70-90 % of the time at 0.07-0.11
ms per push. The cluster tops out at ~25,700 msg/s with the machine at
67 % CPU (the load generator itself ~85 % of a core). Next limits: each
server's write section, and running everything on one machine.
- **+ prepared/cache/checkpoints/heads:** ~25,700 -> ~34,300 msg/s. A push
costs ~0.05 ms of write time instead of 0.07-0.11, no statement is
prepared again, no MAX() per push. The p99 at moderate load is back under
1 ms (13.6 -> 0.8 ms at 10 x 50, 18 -> 1.2 ms in the mixed stage): the
checkpoints were what held the writes up. Flat out, the WAL grows faster
than the background checkpoints keep up with, so the writer checkpoints by
itself past 10,000 frames, and the worst push goes from 149 to 854 ms. The
sync state every check-in reads: 0.5 ms instead of a 167 ms GROUP BY.
- **Same on PB 6.40 C:** ~34,300 -> ~38,400 msg/s (+12 %), the same
latencies, slightly less lag. Both the servers and the load generator are
built with it, so part of it may be the generator. The SQLite side (the
write section, the queries) is the same DLL either way.
## Notes
- Ids checked after the last four runs: every node 1..N, no gap, no
duplicate, on all 4 servers, and `node_heads` exactly matching `data`.
- **p99 at moderate load went up with grouping** (0.7 -> 8-18 ms), and came
back down once the checkpoints left the write path (see above).
- Replication keeps up at every load: it drains within ~11 s even after
38,000 msg/s. The lag is the check-in wait (`PeerSyncInterval`) plus the
hub relaying to its leaves, see `Design/Suggestions.md` #2 to lower it.
- The worst push flat out (0.85-1.5 s) is the writer's backstop checkpoint,
see `Design/Suggestions.md` #3.
## Names and wildcards (evening)
Same benchmark, PureBasic 5.73, after topics and nodes got names, strict
"named on both sides" replication, and wildcards, run with `-Names
Wildcard`: each server only names its own nodes, and takes everyone else's
by `AcceptNodes = n*`, so each server adds the other servers' 30 nodes
under ids of its own (counting down from 65535), and the hub relays them on
by name. The worst case for the new code: every batch goes through a name
lookup and every check-in through the patterns. Run `20261107-220433`,
compared with `Compare-Runs.ps1` (`comparison.md` in the run's folder).
| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) |
|---|---|---|---|
| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 |
| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 |
| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 |
| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 |
| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 |
| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 |
| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 |
| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 |
| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 |
| Query: sync state from node_heads, ms | 0.6 | 0.5 | 0.7 |
| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 |
| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 |
| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 |
| Failed pushes, refusals between servers | 0 | 0 | 0 |
- **Same speed, within run-to-run noise.** Flat out at 10 nodes, the same
build gave 32,976 and 37,003 msg/s in two ramp-only runs (declared names)
earlier this evening: ±6 % between runs is usual on this machine. The push
path itself didn't change, only the check-ins and the batches' first
lines.
- **Server CPU +7 %** flat out (129 vs 120 % of a core), the name lookups
and the bigger sync states, possibly part of the noise too.
- **Replication** keeps up at every load and drains in the same time; no
batch refused anywhere, every server ended with the same rows.
- **Measuring changed slightly:** the lag monitor now asks for each node's
latest id by name through the `messages` view (ids differ between
servers in this mode), the old runs asked `data` by id. Both are index
lookups.
## Big messages, no JSON check on push, is_json clause (2026-11-08)
Same setup as the evening run (`-Names Wildcard`), after: packets up to
16 MB once authenticated (new inbox: growth by doubling, a read offset),
replication batches still ~64 KB, pushes no longer checked to be JSON
(`ParseJSON()` gone from the push path, `is_json` flags them), and
`is_json = 1` added to the JSON queries.
| | Before names (5.73) | Before names (PB 6.40 C) | Names + wildcards (5.73) | Big messages, no JSON check, is_json clause (5.73) |
|---|---|---|---|---|
| **Push ceiling**, msg/s, 5 nodes/server | 33,522 | 37,162 | 35,124 | **38,199** |
| **Push ceiling**, msg/s, 10 nodes/server | 34,345 | 38,358 | 32,846 | **37,745** |
| Pushed of 2,000 offered (10 x 50) | 2,000 | 1,999 | 1,999 | 2,001 |
| Pushed of 4,000 offered (10 x 100) | 4,000 | 4,000 | 4,000 | 4,000 |
| Push p50 / p99 ms, 10 x 50 | 0.3 / 0.8 | 0.2 / 0.9 | 0.3 / 1.1 | 0.3 / 1.0 |
| Push p50 / p99 / max ms, flat out (10 nodes) | 0.5 / 2.8 / 854 | 0.5 / 2.5 / 1,485 | 0.6 / 3.2 / 1,503 | 0.5 / 2.9 / 822 |
| Replication lag, s of pushes, flat out | 9.9 | 8.3 | 8.6 | 10.5 |
| Drain after the push, s, flat out | 11.3 | 11.3 | 11.8 | 13.8 |
| Server CPU, % of a core, flat out (avg of the 4) | 120 | 121 | 129 | 120 |
| Machine CPU %, flat out | 65 | 65 | 69 | 66 |
| Hub RAM, working set MB, max | 38.8 | 40.1 | 39.3 | 42.8 |
| Rows per server at the end | 2,389,201 | 2,619,806 | 2,395,509 | 2,628,001 |
| Query: latest message, ms | 0.1 | 0.1 | 0.1 | 0.1 |
| Query: last 50 of a node, ms | 0.8 | 0.7 | 0.8 | 0.8 |
| Query: sync state (GROUP BY all), ms | 166.7 | 184.1 | 170.5 | 187.9 |
| Query: sync state from node_heads (what check-ins use now), ms | 0.6 | 0.5 | 0.7 | 0.6 |
| Query: JSON count over all rows, ms | 1,080.7 | 1,199.4 | 1,105.8 | 1,233.6 |
| Query: JSON aggregate over all rows, ms | 3,974.2 | 4,371.2 | 4,084.2 | 4,464.4 |
| Same, per million rows: sync state / JSON count / JSON aggregate, ms | 69.8 / 452 / 1,663 | 70.3 / 458 / 1,669 | 71.2 / 462 / 1,705 | 71.5 / 469 / 1,699 |
| **Mixed:** pushed of 400 msg/s with a query loop | 392 | 396 | 397 | 384 |
| Mixed: push p99 / max ms | 1.2 / 17 | 0.9 / 17 | 0.9 / 18 | 1.0 / 15 |
| Mixed: failed pushes | 0 | 0 | 0 | 0 |
| Mixed: JSON count over all rows, ms, under load | 1,148.2 | 1,265.6 | 1,179.5 | 1,313.4 |
| Mixed: latest message, ms, under load | 0.2 | 0.2 | 0.2 | 0.2 |
Runs: `20261107-140556`, `20261107-141735`, `20261107-220433`, `20261108-033149` (all 4 servers in a Y, ~200-byte messages; the last two with `-Names Wildcard`). Query times are from the end of each run, so they scale with its row count: compare the per-million row.
- **Push ceiling up 9-15 %** (38,199 / 37,745 msg/s), the best yet on 5.73,
for the same server CPU (120 % of a core). Likely mostly `ParseJSON()`
leaving the push path, though runs of one build have spread 33-37k.
- **Lag and drain** are a bit higher in seconds, with 15 % more messages
pushed per second to relay (397,066 messages behind at most, vs 282,621).
- **The `is_json = 1` clause costs nothing measurable:** per million rows,
the JSON count is 469 ms vs 462, the aggregate 1,699 vs 1,705.
- **Mixed: 384 of 400 msg/s pushed** (397 before), with no failures and a
lower p99. The bench's pushers are paced by its own loop, and this run's
database was 10 % bigger, so the query loop beside them was slower. Worth
a second run before reading anything into it.
- 0 refused, failed or "too big" in the server logs, 2,628,001 rows on all
4 servers.
+30
View File
@@ -0,0 +1,30 @@
# Query suite, run by BenchClient's "query" mode after every stage, see
# Bench-Replication.ps1. One per line: Name | SQL
# {TOPIC} and {NODE} are replaced by the topic id and the server's first node.
# "@latest" is a GetLatestMessage of {NODE}, the regular read path.
# Results must fit in one packet (64 KB) and 10000 rows.
#
# The messages look like:
# {"kind":"temp","node":101,"seq":12,"value":42.17,"ts":1700000012,"pad":"xxx"}
# kind is "alert" for 1 in 50, the others are spread evenly.
# Indexed, should stay flat as the data grows.
latest_message | @latest
last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50
max_of_node | SELECT MAX(message_id) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE}
by_message_id | SELECT topic_id, node_id FROM data WHERE message_id = 100
recent_global | SELECT topic_id, node_id, message_id FROM data ORDER BY rowid DESC LIMIT 100
# Bounded JSON scan: newest alerts of one node, about 50 rows read per hit.
json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100
# Index scans, grow with the data.
count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE}
count_all | SELECT COUNT(*) FROM data
sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id
sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id
# Full table scans parsing every message's JSON, the ones that die first.
json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert'
json_agg_all | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE is_json = 1 GROUP BY 1
json_agg_node | SELECT message_data ->> '$.kind', COUNT(*), ROUND(AVG(message_data ->> '$.value'), 2) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 GROUP BY 1
+13
View File
@@ -0,0 +1,13 @@
# Queries run in a loop while pushing, in the "mixed" stage of
# Bench-Replication.ps1, to see how reads hold up under write load, and how
# much a long read slows the writes down (it used to block every commit,
# before WAL).
# Same format as queries.txt.
latest_message | @latest
last_50_of_node | SELECT message_id, message_data FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} ORDER BY message_id DESC LIMIT 50
json_alerts_node | SELECT message_id, message_data ->> '$.value' FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE} AND is_json = 1 AND message_data ->> '$.kind' = 'alert' ORDER BY message_id DESC LIMIT 100
count_node | SELECT COUNT(*) FROM data WHERE topic_id = {TOPIC} AND node_id = {NODE}
sync_state | SELECT topic_id, node_id, MAX(message_id) FROM data GROUP BY topic_id, node_id ORDER BY topic_id, node_id
sync_state_heads | SELECT topic_id, node_id, max_message_id FROM node_heads ORDER BY topic_id, node_id
json_count_all | SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.kind' = 'alert'
+336
View File
@@ -0,0 +1,336 @@
# End-to-end test of big messages: up to 16 MB once authenticated, 4 KB
# frames before that (Commons/Networking/Connections.pbi).
# Two linked servers: pushes of 100 KB, 1 MB and just under the cap, read
# back through the client DLL, replicated to the other server, small ones
# still batched, a push over the cap refused, and frames too big for the
# handshake cutting the connection right away.
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it). Uses ports 12403-12404.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\BigMessages-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_bigtest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Fails = 0
# Same as Packets.pbi.
$MaxPacketSize = 16 * 1024 * 1024
$MaxMessageSize = $MaxPacketSize - 4096
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) {
$Out = $Result.Out
if ($Out.Length -gt 300) { $Out = $Out.Substring(0, 300) + "... (" + $Result.Out.Length + " chars)" }
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $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) {
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)
}
# Waits until Sql answers something matching Pattern, for up to Seconds.
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) {
$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
}
# A JSON message of exactly Size bytes, in a file, as PushMessage's @File.
function New-Message($Name, [int]$Size) {
$P = Join-Path $Dir "$Name.json"
$Head = '{"n":"' + $Name + '","pad":"'
$Tail = '"}'
$Pad = $Size - $Head.Length - $Tail.Length
$B = New-Object System.Text.StringBuilder ($Size)
[void]$B.Append($Head)
[void]$B.Append(("0123456789abcdef" * [math]::Ceiling($Pad / 16)).Substring(0, $Pad))
[void]$B.Append($Tail)
[IO.File]::WriteAllText($P, $B.ToString(), (New-Object System.Text.UTF8Encoding $false))
"@$P"
}
# Connects, sends one frame header announcing Size bytes, then up to 64 KB of
# zeros, and tells whether the server closed (or reset) the connection
# within 3 s, rather than waiting for the rest.
function Test-RawFrame([int]$Port, [int]$Size) {
$C = New-Object System.Net.Sockets.TcpClient
$Start = Get-Date
try {
$C.Connect("127.0.0.1", $Port)
$S = $C.GetStream()
$S.ReadTimeout = 5000
$S.Write([BitConverter]::GetBytes([int]$Size), 0, 4)
try { $S.Write((New-Object byte[] ([math]::Min($Size, 65536))), 0, [math]::Min($Size, 65536)) } catch { }
$Buffer = New-Object byte[] 16
try { $Read = $S.Read($Buffer, 0, 16) } catch { $Read = -1 }
($Read -le 0) -and (((Get-Date) - $Start).TotalSeconds -lt 3)
} catch { ((Get-Date) - $Start).TotalSeconds -lt 3 } finally { $C.Close() }
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
# Same names on both, different ids.
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
[BakaShrot]
PrivateKey = $($A.Priv)
Topic = logs
Node = serverA
[BakaShrot.Topics]
logs = 1
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12403
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
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
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
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
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = 30
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12404
ReplicatingTopics = logs
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
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
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
ReadTopics = *
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])"
$P
}
$OnA = Client-Ini "kitchen-a" 12403
$OnB = Client-Ini "kitchen-b" 12404
$Sizes = [ordered]@{ "m100k" = 100 * 1024; "m1m" = 1024 * 1024; "mmax" = $MaxMessageSize }
$Files = @{}
foreach ($N in $Sizes.Keys) { $Files[$N] = New-Message $N $Sizes[$N] }
$Over = New-Message "over" ($MaxMessageSize + 1)
# Not JSON: 1 MB of it cut short, and plain text. Stored anyway, is_json = 0.
$Broken = Join-Path $Dir "broken.json"
[IO.File]::WriteAllText($Broken, ([IO.File]::ReadAllText($Files["m1m"].Substring(1))).Substring(0, 1000000))
$Text = Join-Path $Dir "text.txt"
[IO.File]::WriteAllText($Text, "just some text, not JSON")
$Small = New-Message "small" 40
$SA = Start-Srv "a"; $SB = Start-Srv "b"
try {
Wait-Port 12403 $SA; Wait-Port 12404 $SB
"--- Before authenticating"
Check "a frame over 4 KB is cut right away" (Test-RawFrame 12403 4097) "connection closed"
Check "a 16 MB frame too" (Test-RawFrame 12403 $MaxPacketSize) "connection closed"
Check "the server still serves after that" (Test-Port 12403) "listening"
"--- Pushes"
$Id = 0
foreach ($N in $Sizes.Keys) {
$Id++
$T = Measure-Command { $R = Tool "PushMessage.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
$Id++
Expect "a small push after them" (Tool "PushMessage.exe" @($Small, $OnA)) "message #$Id"
"--- Read back"
$T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.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
Expect "stored sizes on A" $R ('\[\["1","{0}"\],\["2","{1}"\],\["3","{2}"\],\["4","40"\]\]' -f $Sizes["m100k"], $Sizes["m1m"], $MaxMessageSize)
"--- Replicated to B (same names, B's ids)"
$R = Wait-Query "SELECT message_id, length(message_data), topic_id, node_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $OnB '"4","40"' 60
Expect "every one on B, under logs=300 kitchen=30" $R ('\[\["1","{0}","300","30"\],\["2","{1}","300","30"\],\["3","{2}","300","30"\],\["4","40","300","30"\]\]' -f $Sizes["m100k"], $Sizes["m1m"], $MaxMessageSize)
$R = Query "SELECT count(*) FROM data a WHERE node_id = 30 AND message_id = 3 AND substr(message_data, 1, 31) = '{`"n`":`"mmax`",`"pad`":`"0123456789ab' AND substr(message_data, -2) = '`"}' AND is_json = 1" $OnB
Expect "the biggest one is intact on B" $R '\[\["1"\]\]'
"--- 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"
$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 }
$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")
"--- Many small ones still go in batches"
1..30 | ForEach-Object { $null = Tool "PushMessage.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 "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
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)"
$Cases = @(
@("42", 1), @('"a string"', 1), @("null", 1), @("[1,2]", 1), @(' {"a":1} ', 1),
@("{a:1}", 0), @('{"a":1} x', 0), @("{'a':1}", 0), @('{"a":1', 0), @("", 0))
$Id = 37
foreach ($C in $Cases) {
$Id++
$F = Join-Path $Dir "case$Id.txt"
[IO.File]::WriteAllText($F, $C[0])
$R = Tool "PushMessage.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)
}
"--- JSON queries over mixed rows"
Expect "with is_json = 1, ->> works" (Query "SELECT COUNT(*) FROM data WHERE is_json = 1 AND message_data ->> '$.n' = 'small'" $OnA) '\[\["31"\]\]'
Expect "in the select list too" (Query "SELECT COUNT(message_data ->> '$.n') FROM data WHERE is_json = 1" $OnA) '\[\["35"\]\]'
# SQLite fails these with "malformed JSON" on the first non-JSON row.
# PureBasic's NextDatabaseRow() can't tell that from the end of the rows,
# RunReadOnlyQuery() asks SQLite: refused, never a partial or empty answer.
Expect "without it, an aggregate is refused with SQLite's error, not answered with no rows" (Query "SELECT COUNT(*) FROM data WHERE message_data ->> '$.n' = 'small'" $OnA) 'Query failed: malformed JSON \(a row isn''t JSON: add is_json = 1 to the WHERE\)' 1
Expect "rows read as they go are refused too, not cut short at the first non-JSON one" (Query "SELECT message_id, message_data ->> '$.n' FROM data WHERE node_id = 2 ORDER BY message_id" $OnA) 'Query failed: malformed JSON' 1
Expect "non-JSON rows without JSON functions: every row" (Query "SELECT COUNT(*), SUM(is_json = 0) FROM data" $OnA) '\[\["\d+","\d+"\]\]'
Expect "JSON functions guarded by CASE WHEN is_json: every row" (Query "SELECT COUNT(*), COUNT(CASE WHEN is_json THEN message_data ->> '$.n' END) FROM data" $OnA) '\[\["\d+","35"\]\]'
Expect "a query with really no rows: still an empty answer" (Query "SELECT message_id FROM data WHERE message_id < 0" $OnA) '"rows":\[\]'
Expect "and a query error still refused as before" (Query "SELECT nope FROM data" $OnA) 'Query failed: .*nope' 1
} finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- Logs"
# Up to the last real activity: whichever stops first, the other loses its
# link to it.
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-- }
($L[0..([math]::Max($End - 1, 0))]) -join "`n"
}
$LogA = Read-Log "a"
$LogB = Read-Log "b"
# The raw frames are cut as an invalid frame, or as too much data when the
# zeros after the header filled the inbox before its size was checked:
# either way right away, which one is down to timing.
# Client ids get reused, so whether each one is authenticated is followed
# line by line, from its "connected".
$Authenticated = @{}; $Cut = 0; $CutAuthenticated = 0
foreach ($Line in ($LogA -split "`n")) {
if ($Line -match "Client (\d+) connected") { $Authenticated[$Matches[1]] = $false }
elseif ($Line -match "Client (\d+) authenticated") { $Authenticated[$Matches[1]] = $true }
elseif ($Line -match "Client (\d+) sent (an invalid frame|too much data)") {
$Cut++
if ($Authenticated[$Matches[1]]) { $CutAuthenticated++ }
}
}
Check "A cut both raw frames (invalid frame or too much data)" ($Cut -ge 2) "$Cut times"
Check "none of them from an authenticated client" ($CutAuthenticated -eq 0) "$CutAuthenticated"
# Without the refusals this test asks for ("Query failed: malformed JSON", ...).
$UnrefusedA = ($LogA -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n"
$UnrefusedB = ($LogB -split "`n" | Where-Object { $_ -notmatch "Refused a request" }) -join "`n"
foreach ($P in @("too big", "Lost the link", "Failed")) {
Check "no '$P' in A's or B's log" (-not ($UnrefusedA -match [regex]::Escape($P)) -and -not ($UnrefusedB -match [regex]::Escape($P))) "checked"
}
Check "no 'sent too much data' in B's log" (-not ($LogB -match "sent too much data")) "checked"
""
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
+387
View File
@@ -0,0 +1,387 @@
; ============================================================================
; Tests of Commons/Cryptography/Cipher.pbi, no sockets: round trips in both
; directions, and everything that must be refused (tampering, replay,
; reordering, reflection, wrong key), empty and 16 MB buffers.
; And of Session.pbi: the sealed Hello (only its server opens it, tampering
; refused) and the key exchange (both ends agree, a swapped half or another
; connection's keys don't work, the key pairs are wiped).
; Compile as a console program into Build\ (libsodium.dll is there), run it
; from there. Exits with 0 if every check passed, 1 otherwise.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Cryptography/Session.pbi"
Global Fails.i = 0
Procedure Check(What.s, Ok.i, Detail.s = "")
If Ok
PrintN("PASS " + What)
Else
PrintN("FAIL " + What)
Fails + 1
EndIf
If Detail <> ""
PrintN(" -> " + Detail)
EndIf
EndProcedure
; Text as a UTF-8 buffer, its size in *Size\i.
Procedure.i ToUtf8(Text.s, *Size.Integer)
Protected *Buffer
*Size\i = StringByteLength(Text, #PB_UTF8)
*Buffer = AllocateMemory(*Size\i + 1)
PokeS(*Buffer, Text, -1, #PB_UTF8)
ProcedureReturn *Buffer
EndProcedure
; Encrypts Text with *From, decrypts it with *To, returns what came out ("" and
; *Ok\i #False if refused).
Procedure.s RoundTrip(*From.BakaShrot_Cipher, *To.BakaShrot_Cipher, Text.s, *Ok.Integer)
Protected *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Opened, OpenedSize.Integer, Result.s
*Ok\i = #False
*Plain = ToUtf8(Text, @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(*From, *Plain, PlainSize\i, @SealedSize)
FreeMemory(*Plain)
If Not *Sealed
ProcedureReturn ""
EndIf
*Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, SealedSize\i, @OpenedSize)
FreeMemory(*Sealed)
If Not *Opened
ProcedureReturn ""
EndIf
Result = PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength)
FreeMemory(*Opened)
*Ok\i = #True
ProcedureReturn Result
EndProcedure
; Whether Text's UTF-8 bytes appear anywhere in *Buffer (Size bytes).
Procedure.i ContainsText(*Buffer, Size.i, Text.s)
Protected *Needle, NeedleSize.Integer, i.i, Found.i
*Needle = ToUtf8(Text, @NeedleSize)
For i = 0 To Size - NeedleSize\i
If CompareMemory(*Buffer + i, *Needle, NeedleSize\i)
Found = #True
Break
EndIf
Next
FreeMemory(*Needle)
ProcedureReturn Found
EndProcedure
; Whether *Sealed (Size bytes) is refused by *To, without changing it.
Procedure.i IsRefused(*To.BakaShrot_Cipher, *Sealed, Size.i)
Protected *Opened, OpenedSize.Integer
*Opened = BakaShrot_Cipher_Decrypt(*To, *Sealed, Size, @OpenedSize)
If *Opened
FreeMemory(*Opened)
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; A copy of Size bytes at *Source.
Procedure.i Copy(*Source, Size.i)
Protected *Copy = AllocateMemory(Size)
CopyMemory(*Source, *Copy, Size)
ProcedureReturn *Copy
EndProcedure
Define *Key, *OtherKey
Define Client.BakaShrot_Cipher, Server.BakaShrot_Cipher, Other.BakaShrot_Cipher, Uninitialized.BakaShrot_Cipher
Define Ok.Integer, Text.s, i.i, Zero.i
Define *Plain, PlainSize.Integer, *Sealed, SealedSize.Integer, *Sealed2, Sealed2Size.Integer, *Opened, OpenedSize.Integer
Define *Tampered, Offset.i, Refused.i, StartTime.q, Elapsed.q
OpenConsole()
If Not InitCryptography()
PrintN("FAIL libsodium couldn't initialize")
End 1
EndIf
*Key = AllocateMemory(#BakaShrot_Cipher_KeySize)
*OtherKey = AllocateMemory(#BakaShrot_Cipher_KeySize)
BakaShrot_Cipher_GenerateKey(*Key)
BakaShrot_Cipher_GenerateKey(*OtherKey)
Check("Two generated keys differ", Bool(Not CompareMemory(*Key, *OtherKey, #BakaShrot_Cipher_KeySize)))
Check("Init as client", BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client))
Check("Init as server", BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server))
Check("Init with role 0 refused", Bool(Not BakaShrot_Cipher_Init(@Other, *Key, 0)))
; --- Round trips ---------------------------------------------------------------
Text = RoundTrip(@Client, @Server, "hello, server", @Ok)
Check("Client -> server", Bool(Ok\i And Text = "hello, server"), Text)
Text = RoundTrip(@Server, @Client, "hello, client", @Ok)
Check("Server -> client", Bool(Ok\i And Text = "hello, client"), Text)
For i = 1 To 100
Text = RoundTrip(@Client, @Server, "message " + Str(i), @Ok)
If Not Ok\i Or Text <> "message " + Str(i)
Break
EndIf
Next
Check("100 more in order", Bool(i = 101), Str(i - 1) + " went through")
Text = RoundTrip(@Client, @Server, "héllo wörld, 🌍", @Ok)
Check("Non-ASCII data", Bool(Ok\i And Text = "héllo wörld, 🌍"), Text)
; --- What a sealed buffer looks like ------------------------------------------
*Plain = ToUtf8("same text", @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size)
Check("Sealed size is the data + " + Str(#BakaShrot_Cipher_Overhead), Bool(SealedSize\i = PlainSize\i + #BakaShrot_Cipher_Overhead), Str(SealedSize\i) + " bytes for " + Str(PlainSize\i))
Check("The data doesn't appear in it", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Plain, PlainSize\i)))
Check("The same data twice seals differently", Bool(Not CompareMemory(*Sealed + #BakaShrot_Cipher_SequenceSize, *Sealed2 + #BakaShrot_Cipher_SequenceSize, PlainSize\i)))
Check("Each carries its sequence number", Bool(PeekQ(*Sealed2) = PeekQ(*Sealed) + 1), Str(PeekQ(*Sealed)) + ", " + Str(PeekQ(*Sealed2)))
; --- Refused ---------------------------------------------------------------------
; Reordered: the second one first.
Check("The next-but-one first: refused (reordered)", IsRefused(@Server, *Sealed2, Sealed2Size\i))
; Tampered anywhere: the sequence number, the data, the tag.
Refused = 0
For Offset = 0 To SealedSize\i - 1
*Tampered = Copy(*Sealed, SealedSize\i)
PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01)
If IsRefused(@Server, *Tampered, SealedSize\i)
Refused + 1
EndIf
FreeMemory(*Tampered)
Next
Check("One bit flipped anywhere: refused, at every one of its " + Str(SealedSize\i) + " bytes", Bool(Refused = SealedSize\i), Str(Refused) + " refused")
Check("Cut short by one byte: refused", IsRefused(@Server, *Sealed, SealedSize\i - 1))
Check("Shorter than the overhead: refused", IsRefused(@Server, *Sealed, #BakaShrot_Cipher_Overhead - 1))
; None of that moved the receiver on: the genuine ones still go through, in order.
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize)
Check("After all that, the genuine one still decrypts", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i)))
If *Opened : FreeMemory(*Opened) : EndIf
Check("Replayed: refused", IsRefused(@Server, *Sealed, SealedSize\i))
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed2, Sealed2Size\i, @OpenedSize)
Check("Then the next one", Bool(*Opened <> 0))
If *Opened : FreeMemory(*Opened) : EndIf
; Reflected: sent back to its sender, or to another client with the same key.
*Sealed2 = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @Sealed2Size)
BakaShrot_Cipher_Init(@Other, *Key, #BakaShrot_Cipher_Client)
; Same sequence number, so only the direction differs.
Other\ReceiveSequence = PeekQ(*Sealed2)
Check("Reflected to a client with the same key, same sequence number: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i))
; Another key.
BakaShrot_Cipher_Init(@Other, *OtherKey, #BakaShrot_Cipher_Server)
Other\ReceiveSequence = PeekQ(*Sealed2)
Check("Another key: refused", IsRefused(@Other, *Sealed2, Sealed2Size\i))
FreeMemory(*Sealed)
FreeMemory(*Sealed2)
FreeMemory(*Plain)
Check("Not set up: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Uninitialized, @Zero, 4, @SealedSize) = 0))
; --- Sizes ---------------------------------------------------------------------
BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client)
BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, 0, 0, @SealedSize)
*Opened = 0
If *Sealed
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize)
EndIf
Check("Empty data: sealed in " + Str(#BakaShrot_Cipher_Overhead) + " bytes, opens to 0 bytes", Bool(*Sealed And SealedSize\i = #BakaShrot_Cipher_Overhead And *Opened And OpenedSize\i = 0))
If *Sealed : FreeMemory(*Sealed) : EndIf
If *Opened : FreeMemory(*Opened) : EndIf
PlainSize\i = 16 * 1024 * 1024
*Plain = AllocateMemory(PlainSize\i)
RandomData(*Plain, PlainSize\i)
StartTime = ElapsedMilliseconds()
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, SealedSize\i, @OpenedSize)
Elapsed = ElapsedMilliseconds() - StartTime
Check("16 MB both ways, intact", Bool(*Opened And OpenedSize\i = PlainSize\i And CompareMemory(*Opened, *Plain, PlainSize\i)), Str(Elapsed) + " ms to encrypt and decrypt")
FreeMemory(*Plain)
If *Sealed : FreeMemory(*Sealed) : EndIf
If *Opened : FreeMemory(*Opened) : EndIf
; --- A key per direction -----------------------------------------------------
Check("Two keys: the same one twice refused", Bool(Not BakaShrot_Cipher_InitWithKeys(@Client, *Key, *Key)))
Check("Two keys: client sends with A, receives with B", BakaShrot_Cipher_InitWithKeys(@Client, *Key, *OtherKey))
Check("Two keys: server the other way around", BakaShrot_Cipher_InitWithKeys(@Server, *OtherKey, *Key))
Text = RoundTrip(@Client, @Server, "with two keys", @Ok)
Check("Two keys: client -> server", Bool(Ok\i And Text = "with two keys"), Text)
Text = RoundTrip(@Server, @Client, "and back", @Ok)
Check("Two keys: server -> client", Bool(Ok\i And Text = "and back"), Text)
BakaShrot_Cipher_InitWithKeys(@Other, *Key, *OtherKey)
*Plain = ToUtf8("to myself", @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(@Other, *Plain, PlainSize\i, @SealedSize)
Check("Two keys: reflected to its sender, refused", IsRefused(@Other, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
FreeMemory(*Plain)
; --- Clear -------------------------------------------------------------------------
BakaShrot_Cipher_Clear(@Client)
Zero = #True
For i = 0 To #BakaShrot_Cipher_KeySize - 1
If Client\SendKey[i] Or Client\ReceiveKey[i]
Zero = #False
EndIf
Next
Check("Clear wipes both keys", Zero)
Check("Cleared: refuses to encrypt", Bool(BakaShrot_Cipher_Encrypt(@Client, @Zero, 4, @SealedSize) = 0))
sodium_memzero(*Key, #BakaShrot_Cipher_KeySize)
sodium_memzero(*OtherKey, #BakaShrot_Cipher_KeySize)
; --- Into a given buffer ---------------------------------------------------------
BakaShrot_Cipher_Init(@Client, *Key, #BakaShrot_Cipher_Client)
BakaShrot_Cipher_Init(@Server, *Key, #BakaShrot_Cipher_Server)
*Plain = ToUtf8("in place", @PlainSize)
*Sealed = AllocateMemory(PlainSize\i + #BakaShrot_Cipher_Overhead)
Check("EncryptTo writes a sealed buffer", BakaShrot_Cipher_EncryptTo(@Client, *Plain, PlainSize\i, *Sealed))
*Opened = BakaShrot_Cipher_Decrypt(@Server, *Sealed, PlainSize\i + #BakaShrot_Cipher_Overhead, @OpenedSize)
Check("EncryptTo's buffer decrypts", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "in place"))
If *Opened : FreeMemory(*Opened) : EndIf
Check("EncryptTo refuses without a cipher", Bool(Not BakaShrot_Cipher_EncryptTo(@Uninitialized, *Plain, PlainSize\i, *Sealed)))
FreeMemory(*Sealed)
FreeMemory(*Plain)
BakaShrot_Cipher_Clear(@Client)
BakaShrot_Cipher_Clear(@Server)
; --- Session: the sealed Hello ---------------------------------------------------
Define *ServerPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
Define *ServerPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
Define *OtherPublic = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
Define *OtherPrivate = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
Define *ZeroKey = AllocateMemory(32)
Define HelloKeys.BakaShrot_HelloKeys, OtherHelloKeys.BakaShrot_HelloKeys
Define ClientPair.BakaShrot_SessionKeyPair, ServerPair.BakaShrot_SessionKeyPair, MiddlePair.BakaShrot_SessionKeyPair
Define ClientHalf.BakaShrot_SessionKey, ServerHalf.BakaShrot_SessionKey, MiddleHalf.BakaShrot_SessionKey
GenerateKeyPair(*ServerPublic, *ServerPrivate)
GenerateKeyPair(*OtherPublic, *OtherPrivate)
Check("Hello keys from a server's private key", BakaShrot_Session_LoadHelloKeys(@HelloKeys, *ServerPrivate))
BakaShrot_Session_LoadHelloKeys(@OtherHelloKeys, *OtherPrivate)
*Plain = ToUtf8("hello, I'm logs:kitchen", @PlainSize)
*Sealed = BakaShrot_Session_SealHello(*ServerPublic, *Plain, PlainSize\i, @SealedSize)
Check("Hello sealed, 48 bytes more", Bool(*Sealed And SealedSize\i = PlainSize\i + #BakaShrot_SealedBoxOverhead))
Check("The sealed hello doesn't show the identity", Bool(*Sealed And Not ContainsText(*Sealed, SealedSize\i, "kitchen")))
*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, SealedSize\i, @OpenedSize)
Check("The server opens it", Bool(*Opened And PeekS(*Opened, OpenedSize\i, #PB_UTF8 | #PB_ByteLength) = "hello, I'm logs:kitchen"))
If *Opened : FreeMemory(*Opened) : EndIf
*Opened = BakaShrot_Session_OpenHello(@OtherHelloKeys, *Sealed, SealedSize\i, @OpenedSize)
Check("Another server can't open it", Bool(Not *Opened))
If *Opened : FreeMemory(*Opened) : EndIf
Refused = #True
For Offset = 0 To SealedSize\i - 1 Step 7
*Tampered = Copy(*Sealed, SealedSize\i)
PokeA(*Tampered + Offset, PeekA(*Tampered + Offset) ! $01)
*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Tampered, SealedSize\i, @OpenedSize)
If *Opened
Refused = #False
FreeMemory(*Opened)
EndIf
FreeMemory(*Tampered)
Next
Check("A tampered hello isn't opened", Refused)
*Opened = BakaShrot_Session_OpenHello(@HelloKeys, *Sealed, #BakaShrot_SealedBoxOverhead, @OpenedSize)
Check("A hello cut short isn't opened", Bool(Not *Opened))
FreeMemory(*Sealed)
*Sealed = BakaShrot_Session_SealHello(*ZeroKey, *Plain, PlainSize\i, @SealedSize)
Check("Sealing for an invalid server key refused", Bool(Not *Sealed))
If *Sealed : FreeMemory(*Sealed) : EndIf
FreeMemory(*Plain)
; --- Session: the key exchange ---------------------------------------------------
BakaShrot_Session_NewKeyPair(@ClientPair)
BakaShrot_Session_NewKeyPair(@ServerPair)
CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32)
CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32)
Check("Server starts from the client's half", BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf))
Check("Client starts from the server's half", BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf))
Zero = #True
For i = 0 To #BakaShrot_X25519_SecretKeySize - 1
If ClientPair\SecretKey[i] Or ServerPair\SecretKey[i]
Zero = #False
EndIf
Next
Check("Both key pairs wiped once started", Zero)
Text = RoundTrip(@Client, @Server, "push over a session", @Ok)
Check("Session: client -> server", Bool(Ok\i And Text = "push over a session"), Text)
Text = RoundTrip(@Server, @Client, "answer over a session", @Ok)
Check("Session: server -> client", Bool(Ok\i And Text = "answer over a session"), Text)
Check("Session: a key per direction", Bool(Not CompareMemory(@Client\SendKey[0], @Client\ReceiveKey[0], #BakaShrot_Cipher_KeySize)))
Check("Session: the client's send key is the server's receive key", CompareMemory(@Client\SendKey[0], @Server\ReceiveKey[0], #BakaShrot_Cipher_KeySize))
*Plain = ToUtf8("back to me", @PlainSize)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
Check("Session: reflected to the client, refused", IsRefused(@Client, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
; Someone in the middle swapping the server's half for theirs: the client
; ends up with keys the real server doesn't have. (The server's signature
; of the halves catches it first, in the handshake.)
BakaShrot_Session_NewKeyPair(@ClientPair)
BakaShrot_Session_NewKeyPair(@ServerPair)
BakaShrot_Session_NewKeyPair(@MiddlePair)
CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32)
CopyMemory(@MiddlePair\PublicKey[0], @MiddleHalf, 32)
BakaShrot_Session_StartServer(@Server, @ServerPair, @ClientHalf)
BakaShrot_Session_StartClient(@Client, @ClientPair, @MiddleHalf)
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
Check("Session: halves swapped, the server can't decrypt", IsRefused(@Server, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
; Another connection of the same client gets other keys.
Define Server2.BakaShrot_Cipher
CopyMemory(@Server, @Other, SizeOf(BakaShrot_Cipher))
BakaShrot_Session_NewKeyPair(@ClientPair)
BakaShrot_Session_NewKeyPair(@ServerPair)
CopyMemory(@ClientPair\PublicKey[0], @ClientHalf, 32)
CopyMemory(@ServerPair\PublicKey[0], @ServerHalf, 32)
BakaShrot_Session_StartServer(@Server2, @ServerPair, @ClientHalf)
BakaShrot_Session_StartClient(@Client, @ClientPair, @ServerHalf)
Check("Session: another connection, other keys", Bool(Not CompareMemory(@Server2\ReceiveKey[0], @Other\ReceiveKey[0], #BakaShrot_Cipher_KeySize)))
*Sealed = BakaShrot_Cipher_Encrypt(@Client, *Plain, PlainSize\i, @SealedSize)
Check("Session: replayed into another connection, refused", IsRefused(@Other, *Sealed, SealedSize\i))
FreeMemory(*Sealed)
FreeMemory(*Plain)
BakaShrot_Session_NewKeyPair(@ServerPair)
Check("Session: an all-zero half refused", Bool(Not BakaShrot_Session_StartServer(@Server, @ServerPair, *ZeroKey)))
Check("Session: refused, the cipher isn't usable", Bool(Not Server\IsReady))
BakaShrot_Session_ClearHelloKeys(@HelloKeys)
BakaShrot_Session_ClearHelloKeys(@OtherHelloKeys)
sodium_memzero(*ServerPrivate, #BakaShrot_Ed25519_PrivateKeySize)
sodium_memzero(*OtherPrivate, #BakaShrot_Ed25519_PrivateKeySize)
BakaShrot_Cipher_Clear(@Client)
BakaShrot_Cipher_Clear(@Server)
BakaShrot_Cipher_Clear(@Server2)
BakaShrot_Cipher_Clear(@Other)
PrintN("")
If Fails
PrintN(Str(Fails) + " check(s) failed")
End 1
EndIf
PrintN("All checks passed")
End 0
+250
View File
@@ -0,0 +1,250 @@
# 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,
# 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,
# or compile Tests\Bench\BenchServer.pb into it). Uses port 12405.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\GetMessages-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Build = (Resolve-Path $Build).Path
$Dir = Join-Path $Build "_getmessagestest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Port = 12405
$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() }
}
# Runs a tool, its output as lines (Lines) and joined (Out).
function Tool([string]$Name, [string[]]$A) {
$O = @(& (Join-Path $Build $Name) @A 2>&1 | ForEach-Object { "$_" })
@{ Code = $LASTEXITCODE; Lines = $O; Out = ($O -join " | ") }
}
function Check([string]$What, [bool]$Ok, [string]$Detail) {
if (-not $Ok) { $script:Fails++ }
if ($Detail.Length -gt 300) { $Detail = $Detail.Substring(0, 300) + "... (" + $Detail.Length + " chars)" }
"{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)
}
# The ids GetMessages printed, in order.
function Ids($Result) {
@($Result.Lines | Where-Object { $_ -match "^\d+`t" } | ForEach-Object { [long]($_ -split "`t", 2)[0] })
}
# Whether Ids are exactly From..To.
function Is-Run($Ids, [long]$From, [long]$To) {
$Want = if ($To -ge $From) { @($From..$To) } else { @() }
($Ids -join ",") -eq ($Want -join ",")
}
function Push($Data, $Ini, [string]$Topic = "") {
$F = Join-Path $Dir "push.txt"
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
$A = @()
if ($Topic) { $A += @("-t", $Topic) }
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
}
$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]
logs = 1
secret = 2
[BakaShrot.Nodes]
server = 1
kitchen = 5
lounge = 6
empty = 7
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
DatabasePath = $(Join-Path $Dir "server.sqlite")
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
PushTopics = logs;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.lounge]
PublicKeys = $($L.Pub)
Identities = logs:lounge
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)"
$P
}
$Kitchen = Client-Ini "kitchen" $K
$Lounge = Client-Ini "lounge" $L
if (Test-Port $Port) { throw "Port $Port is already in use" }
$Stop = Join-Path $Dir "server.stop"
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "server.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "server.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
$Follower = $null
try {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($P.HasExited) { throw "The server exited: $(Get-Content (Join-Path $Dir "server.log") -Raw)" }
if ((Get-Date) -gt $D) { throw "The server isn't listening" }
Start-Sleep -Milliseconds 100
}
# --- Nothing yet ----------------------------------------------------------
$R = Tool "GetMessages.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)
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 -------------------------------------------------------
$Started = Get-Date
$Pushed = 0
for ($i = 1; $i -le 120; $i++) {
$R = Push ('{"i":' + $i + '}') $Kitchen
if ($R.Code -eq 0) { $Pushed++ }
}
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)
$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)
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)
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)
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)
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)
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)
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)
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)
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)
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
# --- 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)
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 " / ")
# --- Answers split at ~1 MB -----------------------------------------------
# 5 of 600 KB and one of 3 MB: one per answer, the big one alone.
$Sizes = @(600KB, 600KB, 600KB, 3MB, 600KB, 600KB)
$BigOk = 0
foreach ($Size in $Sizes) {
$Data = '{"pad":"' + ("x" * ($Size - 10)) + '"}'
if ((Push $Data $Kitchen).Code -eq 0) { $BigOk++ }
}
Check "6 big pushes (5 x 600 KB, 3 MB)" ($BigOk -eq 6) "$BigOk pushed"
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen)
$Ids = Ids $R
$Lengths = @($R.Lines | ForEach-Object { (($_ -split "`t", 2)[1]).Length })
$WantLengths = @($Sizes | ForEach-Object { $_ })
Check "All 6 read back whole, over several answers" (
$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)
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") `
-ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" `
-WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru
$null = $Follower.Handle
Start-Sleep -Milliseconds 1500
Check "--follow keeps running once caught up" (-not $Follower.HasExited) $(if ($Follower.HasExited) { "exited with $($Follower.ExitCode)" } else { "running" })
$null = Push '{"f":1}' $Kitchen
$null = Push '{"f":2}' $Kitchen
$null = Push '{"f":3}' $Kitchen
$D = (Get-Date).AddSeconds(10)
do {
Start-Sleep -Milliseconds 200
$Lines = @()
try {
$Fs = [IO.File]::Open($FollowOut, "Open", "Read", "ReadWrite")
$Text = (New-Object IO.StreamReader($Fs)).ReadToEnd(); $Fs.Close()
$Lines = @($Text -split "`r?`n" | Where-Object { $_ -ne "" })
} catch { }
} while ($Lines.Count -lt 3 -and (Get-Date) -lt $D)
Check "--follow --after latest: only the 3 new ones" (
$Lines.Count -eq 3 -and $Lines[0] -eq "129`t{`"f`":1}" -and $Lines[2] -eq "131`t{`"f`":3}"
) ($Lines -join " / ")
# The server going away ends it with a failure.
Set-Content $Stop "x"
if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force }
$Ended = $Follower.WaitForExit(15000)
Check "--follow fails once the server is gone" ($Ended -and $Follower.ExitCode -eq 1) $(if ($Ended) { "exit code $($Follower.ExitCode)" } else { "still running" })
$Log = Get-Content (Join-Path $Dir "server.log") -Raw
$Bad = @($Log -split "`r?`n" | Where-Object { $_ -match "invalid|unexpected|Failed" })
Check "Server log: no invalid or unexpected packets" ($Bad.Count -eq 0) $(if ($Bad.Count) { $Bad -join " / " } else { "clean" })
}
finally {
if ($Follower -and -not $Follower.HasExited) { Stop-Process -Id $Follower.Id -Force }
if (-not $P.HasExited) {
Set-Content $Stop "x"
if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force }
}
}
""
if ($Fails -eq 0) { "All checks passed" } else { "$Fails check(s) failed" }
exit $(if ($Fails -eq 0) { 0 } else { 1 })
+162
View File
@@ -0,0 +1,162 @@
; ============================================================================
; Simulates the Hello -> ChallengeRequest -> ChallengeResponse handshake
; between a client and a server, without sockets.
; Each "send" is an encoded buffer, each "receive" decodes that same buffer.
;
; Compile as a console program, exits with 0 if everything passed, 1 otherwise.
; The keys and signatures are placeholders, only the packets and the nonce
; check are tested: the cryptography is Tests/CipherTest.pb's.
; ============================================================================
EnableExplicit
XIncludeFile "../Commons/Networking/Packets/HelloPacket.pbi"
XIncludeFile "../Commons/Networking/Packets/ChallengeRequestPacket.pbi"
XIncludeFile "../Commons/Networking/Packets/ChallengeResponsePacket.pbi"
; Prints the result of a check, and stops the test on the first failure.
Procedure Check(Condition.b, Message.s)
If Condition
PrintN("[OK] " + Message)
ProcedureReturn
EndIf
PrintN("[FAIL] " + Message)
End 1
EndProcedure
Define *Wire, WireSize.Integer, *View.MsgPackData
; Client side
Define ClientHello.BakaShrot_AuthHello
Define *ClientChallenge.BakaShrot_ChallengeRequest
Define ClientResponse.BakaShrot_ChallengeResponse
; Server side
Define *ServerHello.BakaShrot_AuthHello
Define ServerChallenge.BakaShrot_ChallengeRequest
Define *ServerResponse.BakaShrot_ChallengeResponse
Define *ServerReplayed.BakaShrot_ChallengeResponse
Define *ServerWrongType.BakaShrot_ChallengeResponse
; Nonce the server keeps for this connection, until the response arrives.
Define *ServerConnectionNonce = AllocateMemory(#BakaShrot_NonceSize)
; Nonce a second connection got, to test a replayed response.
Define *OtherConnectionNonce = AllocateMemory(#BakaShrot_NonceSize)
OpenConsole()
Check(Bool(*ServerConnectionNonce And *OtherConnectionNonce), "Allocated the server's nonce buffers")
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")
*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize)
Check(Bool(*Wire), "Client encoded its hello")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the hello")
*ServerHello = BakaShrot_HelloPacket_Decode(*View)
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")
; --- 2. Server -> Client: ChallengeRequest ----------------------------------
Check(Bool(CryptRandomData(@ServerChallenge\Nonce[0], #BakaShrot_NonceSize)), "Server generated a nonce")
CopyMemory(@ServerChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize)
ServerChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl"
Check(Bool(CryptRandomData(@ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize)), "Server made a session key")
Check(Bool(CryptRandomData(@ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)), "Server made a placeholder signature")
*Wire = BakaShrot_ChallengeRequestPacket_Encode(@ServerChallenge, @WireSize)
Check(Bool(*Wire), "Server encoded the challenge request")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Client wrapped the challenge request")
*ClientChallenge = BakaShrot_ChallengeRequestPacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(*ClientChallenge), "Client decoded the challenge request")
Check(Bool(*ClientChallenge\ChallengeB64 = "U2VydmVyQ2hhbGxlbmdl"), "Challenge's ChallengeB64 survived")
Check(CompareMemory(@*ClientChallenge\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Challenge's nonce survived")
Check(CompareMemory(@*ClientChallenge\ServerSessionKey[0], @ServerChallenge\ServerSessionKey[0], #BakaShrot_SessionKeySize), "Challenge's ServerSessionKey survived")
Check(CompareMemory(@*ClientChallenge\ServerSignature[0], @ServerChallenge\ServerSignature[0], #BakaShrot_HandshakeSignatureSize), "Challenge's ServerSignature survived")
; --- 3. Client -> Server: ChallengeResponse ---------------------------------
; Placeholder for the real signature of ChallengeB64 + Nonce.
ClientResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg=="
CopyMemory(@*ClientChallenge\Nonce[0], @ClientResponse\Nonce[0], #BakaShrot_NonceSize)
*Wire = BakaShrot_ChallengeResponsePacket_Encode(@ClientResponse, @WireSize)
Check(Bool(*Wire), "Client encoded the challenge response")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the challenge response")
*ServerResponse = BakaShrot_ChallengeResponsePacket_Decode(*View)
MsgPackFree(*View, #False)
Check(Bool(*ServerResponse), "Server decoded the challenge response")
Check(Bool(*ServerResponse\ChallengeResponseB64 = "U2lnbmVkOiAiU2VydmVyQ2hhbGxlbmdlIg=="), "Response's ChallengeResponseB64 survived")
Check(CompareMemory(@*ServerResponse\Nonce[0], *ServerConnectionNonce, #BakaShrot_NonceSize), "Server accepted the nonce it issued")
; --- 4. Replay: the same response sent on another connection ----------------
; *Wire still holds the response captured in step 3.
Check(Bool(CryptRandomData(*OtherConnectionNonce, #BakaShrot_NonceSize)), "Server generated a nonce for another connection")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the replayed response")
*ServerReplayed = BakaShrot_ChallengeResponsePacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(*ServerReplayed), "Replayed response is still a well-formed packet")
Check(Bool(Not CompareMemory(@*ServerReplayed\Nonce[0], *OtherConnectionNonce, #BakaShrot_NonceSize)), "Server rejected the replayed response's nonce")
; --- 5. A hello sent where a challenge response is expected ------------------
*Wire = BakaShrot_HelloPacket_Encode(@ClientHello, @WireSize)
Check(Bool(*Wire), "Client encoded a second hello")
*View = MsgPackWrapMsgBuffer(*Wire, WireSize\i)
Check(Bool(*View), "Server wrapped the misplaced hello")
*ServerWrongType = BakaShrot_ChallengeResponsePacket_Decode(*View)
MsgPackFree(*View, #False)
FreeMemory(*Wire)
Check(Bool(Not *ServerWrongType), "Challenge response decoder rejected a hello")
; --- Cleanup -----------------------------------------------------------------
FreeStructure(*ServerHello)
FreeStructure(*ClientChallenge)
FreeStructure(*ServerResponse)
FreeStructure(*ServerReplayed)
FreeMemory(*ServerConnectionNonce)
FreeMemory(*OtherConnectionNonce)
CloseCryptRandom()
PrintN("")
PrintN("Handshake simulation passed.")
End 0
+283
View File
@@ -0,0 +1,283 @@
# End-to-end test of topic/node names, filters and replication by name:
# two servers with different ids for the same names, strict "named on both
# sides" replication, wildcards (taking undeclared names, filtering),
# old and new config keys, the list tool.
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it). Uses ports 12401-12402.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Names-Test.ps1
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"))
$ErrorActionPreference = "Stop"
$Dir = Join-Path $Build "_namestest"
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 Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
$Ok = ($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)
if (-not $Ok) { $script:Fails++ }
"{0} {1}`n -> [{2}] {3}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $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) {
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)
}
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = 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]
logs = 1
sensors = 2
secret = 3
sensors.temp = 4
[BakaShrot.Nodes]
serverA = 10
serverB = 11
kitchen = 2
garage = 5
kitchen-2 = 6
blocal = 20
bsecret = 21
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12401
ReplicatingTopics = logs;sensors*
DatabasePath = $(Join-Path $Dir "a.sqlite")
PeerSyncInterval = 1
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
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
PushTopics = logs;sensors*
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.kitchen2]
PublicKeys = $($K2.Pub)
Identities = logs:kitchen-2
PushTopics = logs;sensors.temp
[BakaShrot.Client.garage]
PublicKeys = $($G.Pub)
Identities = logs:garage
"@
# --- Server B: the old key names, logs = 200, sensors = 201 ----------------
# garage isn't named here (dropped from A), extra isn't named on A (dropped
# from B), node 9 isn't named anywhere (dropped both ways). sensors.temp and
# kitchen-2 aren't named here either, but taken by AcceptTopics/AcceptNodes
# patterns. bsecret is named on both, but held back by SendNodes.
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]
logs = 200
sensors = 201
extra = 202
[BakaShrot.Nodes]
serverA = 1
serverB = 2
kitchen = $Kitchen
blocal = 3
bsecret = 4
[BakaShrot.Server]
Host = 127.0.0.1
Port = 12402
ReplicatingTopicIds = *
DatabasePath = $(Join-Path $Dir "b.sqlite")
PeerSyncInterval = 1
PeerRetryDelay = 1
[BakaShrot.Peer.a]
Host = 127.0.0.1
Port = 12401
TopicId = logs
NodeId = serverA
PublicKey = $($A.Pub)
AcceptTopics = logs;sensors;sensors.*
AcceptNodes = kitchen;blocal;kitchen-*
SendNodes = blocal;9
[BakaShrot.Client.a]
PublicKeys = $($A.Pub)
Identities = logs:serverA
[BakaShrot.Client.local]
PublicKeys = $($BC.Pub)
Identities = sensors:blocal;logs:9;logs:bsecret
PushTopics = sensors;logs;extra
ReadTopics = *
AllowQuery = 1
"@
}
Write-B "7"
# New key names, except garage's (TopicId / NodeId, by ids).
$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])"
$P
}
$Kitchen = Client-Ini "kitchen" $K "logs" "kitchen" 12401
$Garage = Client-Ini "garage" $G "1" "5" 12401 -OldKeys
$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
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"}'
$M1 = "@" + (Join-Path $Dir "m1.json"); $M2 = "@" + (Join-Path $Dir "m2.json"); $M3 = "@" + (Join-Path $Dir "m3.json")
$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
"--- 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\)"
"--- 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[,}])'
"--- 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: 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"
Start-Sleep -Seconds 4
Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\) \| \{"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"\]\]'
} finally {
Stop-Srv $SA; Stop-Srv $SB
}
"--- No refusals: each side only sent what the other one knows"
$Refusals = @(Get-Content (Join-Path $Dir "a.log"), (Join-Path $Dir "b.log") | Select-String "replicated here|known here|refused:")
$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 " | " })
"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" | % { " $_" }
"--- Conflict: B's config now says kitchen = 8, but its messages are under 7"
Write-B "8"
$SB = Start-Srv "b"
$SB.P.WaitForExit(15000) | Out-Null
$Log = Get-Content (Join-Path $Dir "b.log") -Raw
$Ok = $SB.P.HasExited -and $SB.P.ExitCode -eq 1 -and $Log -match "give it id 7"
if (-not $Ok) { $Fails++ }
"{0} B refuses to start`n -> [{1}] {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $SB.P.ExitCode, (($Log -split "`n") | Select-String "names don't match")
if (-not $SB.P.HasExited) { Stop-Srv $SB }
"--- Conflict fixed: kitchen = 7 again"
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"
} finally { Stop-Srv $SB }
""
if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED" }
+116
View File
@@ -0,0 +1,116 @@
# End-to-end test of the Python interactor (Interactors/Python/bakashrot.py):
# starts a server with an empty database and runs
# Interactors/Python/check_bakashrot.py against it, through Build\'s DLL,
# then Tests/wire_check.py: what goes over the wire is encrypted.
# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe (Bench-Replication.ps1,
# or compile Tests\Bench\BenchServer.pb into it) and a 64-bit Python 3.8+.
# Uses ports 12406 and 12407.
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Python-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 "_pythontest"
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
New-Item -ItemType Directory $Dir | Out-Null
$Server = Join-Path $Build "Bench\BenchServer.exe"
$Port = 12406
$ProxyPort = 12407
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() }
}
$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]
logs = 1
secret = 2
[BakaShrot.Nodes]
server = 1
kitchen = 5
lounge = 6
[BakaShrot.Server]
Host = 127.0.0.1
Port = $Port
DatabasePath = $(Join-Path $Dir "server.sqlite")
[BakaShrot.Client.kitchen]
PublicKeys = $($K.Pub)
Identities = logs:kitchen
PushTopics = logs;secret
ReadTopics = *
AllowQuery = 1
[BakaShrot.Client.lounge]
PublicKeys = $($L.Pub)
Identities = logs:lounge
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)"
$P
}
$Kitchen = Client-Ini "kitchen" $K
$Lounge = Client-Ini "lounge" $L
if (Test-Port $Port) { throw "Port $Port is already in use" }
$Stop = Join-Path $Dir "server.stop"
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "server.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
-RedirectStandardOutput (Join-Path $Dir "server.log") -WindowStyle Hidden -PassThru
$null = $P.Handle
$Code = 1
try {
$D = (Get-Date).AddSeconds(15)
while (-not (Test-Port $Port)) {
if ($P.HasExited) { throw "The server exited: $(Get-Content (Join-Path $Dir "server.log") -Raw)" }
if ((Get-Date) -gt $D) { throw "The server isn't listening" }
Start-Sleep -Milliseconds 100
}
$env:PYTHONIOENCODING = "utf-8"
& $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" })
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
# key pair's public key plays the wrong server's.
""
& $Python -B (Join-Path $PSScriptRoot "wire_check.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $ProxyPort $L.Pub
if ($LASTEXITCODE) { $Code = 1 }
Start-Sleep -Milliseconds 300
$Log = Get-Content (Join-Path $Dir "server.log")
$Checks = [ordered]@{
"Server log: the tampered packet didn't decrypt" = "sent a packet that doesn't decrypt"
"Server log: the hello for another server wasn't opened" = "hello that isn't sealed for this server"
}
foreach ($Name in $Checks.Keys) {
if (@($Log | Where-Object { $_ -match [regex]::Escape($Checks[$Name]) }).Count) { "PASS $Name" } else { "FAIL $Name"; $Code = 1 }
}
}
finally {
if (-not $P.HasExited) {
Set-Content $Stop "x"
if (-not $P.WaitForExit(15000)) { Stop-Process -Id $P.Id -Force }
}
}
exit $Code
+144
View File
@@ -0,0 +1,144 @@
"""What goes over the wire, run by Tests/Python-Test.ps1.
Puts a TCP proxy between the client (BakaShrot_Client.dll, through
Interactors/Python/bakashrot.py) and the server, recording every byte, then
checks that:
- a pushed message, the client's identity and its topic never show up in
plain text, either way, handshake included;
- the message still makes it through and back;
- a byte flipped by the proxy after the handshake drops the connection;
- a client given another server's public key can't connect.
Usage: wire_check.py <BakaShrot_Client.dll> <client.ini> <proxy port> <other public key>
Exits with 0 if every check passed, 1 otherwise.
"""
import os
import socket
import sys
import threading
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, proxy_port, other_key = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
fails = 0
def check(what, ok, detail=""):
global fails
print(("PASS " if ok else "FAIL ") + what)
if detail:
print(" -> " + detail)
if not ok:
fails += 1
class Proxy:
"""Forwards one connection at a time to the server, keeping what passed.
tamper: flips a bit in the next chunk the client sends."""
def __init__(self, listen_port, server_host, server_port):
self.server = (server_host, server_port)
self.listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.listener.bind(("127.0.0.1", listen_port))
self.listener.listen(4)
self.to_server = bytearray()
self.to_client = bytearray()
self.tamper = False
threading.Thread(target=self._accept, daemon=True).start()
def _accept(self):
while True:
try:
client, _ = self.listener.accept()
except OSError:
return
upstream = socket.create_connection(self.server)
threading.Thread(target=self._pump, args=(client, upstream, True), daemon=True).start()
threading.Thread(target=self._pump, args=(upstream, client, False), daemon=True).start()
def _pump(self, source, target, from_client):
try:
while True:
data = source.recv(65536)
if not data:
break
data = bytearray(data)
if from_client and self.tamper:
self.tamper = False
data[-1] ^= 0x01
(self.to_server if from_client else self.to_client).extend(data)
target.sendall(data)
except OSError:
pass
for s in (source, target):
try:
s.shutdown(socket.SHUT_RDWR)
except OSError:
pass
s.close()
base = Client.from_ini(ini_path, dll_path)
proxy = Proxy(proxy_port, base.host, base.port)
marker = "wire-marker-7f3a91"
client = Client(base.private_key, base.public_key, base.server_public_key, base.topic, 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)
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)
check("Read as a run of messages too", any(marker in m.data for m in pages.messages))
client.close()
except BakaShrotError as error:
check("Pushed and read back through the proxy", False, str(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):
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)
# A bit flipped after the handshake: the server drops the connection.
try:
client.connect()
proxy.tamper = True
try:
client.push({"note": "tampered"})
check("A tampered request drops the connection", False, "the push went through")
except BakaShrotError as error:
check("A tampered request drops the connection", not client.connected, str(error))
client.close()
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,
base.host, base.port, dll_path)
try:
impostor.connect()
check("Another server's public key can't connect", False, "it connected")
impostor.close()
except BakaShrotError as error:
check("Another server's public key can't connect", True, str(error))
# And the right one still can, straight to the server.
try:
base.connect()
check("The right key still connects", base.connected)
base.close()
except BakaShrotError as error:
check("The right key still connects", False, str(error))
print()
print("All checks passed" if not fails else f"{fails} check(s) failed")
sys.exit(1 if fails else 0)