1param([Parameter(Mandatory=$true)][string] $Helper, [Parameter(Mandatory=$true)][string] $Dump)
2$ErrorActionPreference = 'Stop'
3Add-Type -TypeDefinition @'
4using System;
5using System.IO;
6using System.Net;
7using System.Net.Sockets;
8using System.Threading;
9using System.Security.Cryptography;
10using System.Text;
11using System.Collections.Generic;
12public sealed class CrashUploadFixture : IDisposable {
13 TcpListener listener; Thread thread; volatile bool stop;
14 public int Port, Requests; public bool Valid; public string Error;
15 public CrashUploadFixture(int code, bool receipt, string extra) {
16 listener=new TcpListener(IPAddress.Loopback,0); listener.Start(); Port=((IPEndPoint)listener.LocalEndpoint).Port;
17 thread=new Thread(()=>Run(code,receipt,extra)); thread.IsBackground=true; thread.Start();
18 }
19 void Run(int code,bool receipt,string extra) {
20 try {
21 while(!stop) {
22 if(!listener.Pending()) { Thread.Sleep(10); continue; }
23 using(var client=listener.AcceptTcpClient()) {
24 client.ReceiveTimeout=10000; client.SendTimeout=10000; var stream=client.GetStream();
25 var header=new StringBuilder(); int b;
26 while((b=stream.ReadByte())!=-1) { header.Append((char)b); if(header.ToString().EndsWith("\r\n\r\n")) break; if(header.Length>16384) throw new Exception("headers too large"); }
27 var lines=header.ToString().Split(new[]{"\r\n"},StringSplitOptions.None);
28 var fields=new Dictionary<string,string>(StringComparer.OrdinalIgnoreCase);
29 for(int i=1;i<lines.Length;i++) { int colon=lines[i].IndexOf(':'); if(colon>0) fields[lines[i].Substring(0,colon)]=lines[i].Substring(colon+1).Trim(); }
30 if(fields.ContainsKey("Expect")) { byte[] interim=Encoding.ASCII.GetBytes("HTTP/1.1 100 Continue\r\n\r\n"); stream.Write(interim,0,interim.Length); }
31 long remaining=long.Parse(fields["Content-Length"]); byte[] buffer=new byte[65536]; string hash;
32 using(var sha=SHA256.Create()) {
33 while(remaining>0) { int n=stream.Read(buffer,0,(int)Math.Min(remaining,buffer.Length)); if(n==0) throw new Exception("truncated body"); sha.TransformBlock(buffer,0,n,null,0); remaining-=n; }
34 sha.TransformFinalBlock(buffer,0,0); hash=BitConverter.ToString(sha.Hash).Replace("-","").ToLowerInvariant();
35 }
36 Requests++; Valid=lines[0]=="POST /v1/client-crashes HTTP/1.1" && hash==fields["X-Rise-Dump-SHA256"] && fields["X-Rise-Trace"]=="trace_test.log" && fields["Content-Type"]=="application/octet-stream";
37 string reply="HTTP/1.1 "+code+" Test\r\nContent-Length: 0\r\nConnection: close\r\n"+extra;
38 if(receipt) reply+="X-Rise-Crash-Id: "+fields["X-Rise-Crash-Id"]+"\r\nX-Rise-Dump-SHA256: "+hash+"\r\n";
39 byte[] response=Encoding.ASCII.GetBytes(reply+"\r\n"); stream.Write(response,0,response.Length);
40 }
41 }
42 } catch(Exception e) { if(!stop) Error=e.ToString(); }
43 }
44 public void Dispose() { stop=true; listener.Stop(); thread.Join(15000); }
45}
46'@
47$helperPath = (Resolve-Path -LiteralPath $Helper).Path
48$dumpPath = (Resolve-Path -LiteralPath $Dump).Path
49$root = Join-Path $PSScriptRoot ('..\Output\CrashUploadTests-' + (Get-Date -Format 'yyyyMMdd-HHmmss'))
50[void][IO.Directory]::CreateDirectory($root)
51function Assert($Condition, [string]$Description) { if (-not $Condition) { throw "FAIL $Description" }; Write-Host "PASS $Description" }
52function Run-Helper([string]$Queue, [string]$Endpoint, [string]$Mode = '--upload') {
53 $process = Start-Process -FilePath $helperPath -ArgumentList @($Mode, ('"' + $Queue + '"'), ('"' + $Endpoint + '"')) -WindowStyle Hidden -PassThru
54 if (-not $process.WaitForExit(30000)) { $process.Kill(); throw 'Isolated uploader timed out' }
55 Assert ($process.ExitCode -eq 0) 'helper completed'
56}
57foreach ($scenario in @(
58 @{ Name='created'; Code=201; Receipt=$true; Extra=''; Delivered=$true },
59 @{ Name='duplicate'; Code=200; Receipt=$true; Extra=''; Delivered=$true },
60 @{ Name='missing-receipt'; Code=200; Receipt=$false; Extra=''; Delivered=$false },
61 @{ Name='wrong-receipt'; Code=200; Receipt=$false; Extra="X-Rise-Crash-Id: wrong`r`nX-Rise-Dump-SHA256: wrong`r`n"; Delivered=$false },
62 @{ Name='conflict'; Code=409; Receipt=$false; Extra=''; Delivered=$false },
63 @{ Name='rate-limit'; Code=429; Receipt=$false; Extra="Retry-After: 7200`r`n"; Delivered=$false },
64 @{ Name='outage'; Code=503; Receipt=$false; Extra=''; Delivered=$false },
65 @{ Name='redirect'; Code=307; Receipt=$false; Extra="Location: http://127.0.0.1:9/no-follow`r`n"; Delivered=$false }
66)) {
67 $queue = [IO.Path]::GetFullPath((Join-Path $root $scenario.Name)); [void][IO.Directory]::CreateDirectory($queue)
68 $id = [Guid]::NewGuid().ToString('D'); $base = Join-Path $queue $id
69 Copy-Item -LiteralPath $dumpPath -Destination ($base + '.dmp')
70 [IO.File]::WriteAllText($base + '.meta', "trace_test.log`n")
71 $server = New-Object CrashUploadFixture($scenario.Code, $scenario.Receipt, $scenario.Extra)
72 try {
73 $url = "http://127.0.0.1:$($server.Port)/v1/client-crashes"
74 Run-Helper $queue $url
75 Assert ($server.Valid -and $server.Requests -eq 1 -and -not $server.Error) ($scenario.Name + ': exact body/hash/headers')
76 Assert ((Test-Path -LiteralPath ($base + '.uploaded')) -eq $scenario.Delivered) ($scenario.Name + ': receipt required')
77 Assert (Test-Path -LiteralPath ($base + '.dmp')) ($scenario.Name + ': local dump retained')
78 Run-Helper $queue $url '--retry'
79 Assert ($server.Requests -eq 1) ($scenario.Name + ': no immediate retry or duplicate delivery')
80 if ($scenario.Name -eq 'rate-limit') {
81 $next = [long]((Get-Content -LiteralPath ($base + '.retry') -Raw).Split(' ')[0])
82 $now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
83 Assert ($next -ge $now + 7190) 'Retry-After honored'
84 }
85 } finally { $server.Dispose() }
86}
87Write-Host "Transport tests passed: $root"