Upload a build with PowerShell

A ready Windows PowerShell script that uploads your build and waits for its stream test. Built into every Windows 10 and 11 - nothing to install. Part of Automated upload.

Before you start

The script

Built into every Windows 10 and 11. Save as e3ds-upload.ps1, then in PowerShell:

$env:E3DS_API_KEY = "your API key"
powershell -ExecutionPolicy Bypass -File .\e3ds-upload.ps1 MyGame.zip MyGame
<#
Upload an Unreal / Unity build (.zip) to Eagle 3D Streaming and wait for its stream test.

    powershell -ExecutionPolicy Bypass -File e3ds-upload.ps1 <build.zip> <app name> [-PartSize MB] [-Parallel N] [-Timeout MIN] [-NoWait]
    (Windows PowerShell 5.1 or 7)

  -PartSize MB   size of each part (default: our server picks; 5 MB .. 5 GB, at most 10,000 parts).
                 A part size as big as the file = a one-part upload.
  -Parallel N    how many parts are sent at the same time (default 4).
  -Timeout MIN   how long to wait for the stream-test result (default 45 - big builds take longer to test).
  -NoWait        upload only; the result comes by email and in the Control Panel.

Your API key is read from the environment variable E3DS_API_KEY (Control Panel -> Developer Section -> API key):
    $env:E3DS_API_KEY = "your key"
If the upload stops (network, closed window), run the same command again: it continues where it stopped.
Exit codes (the same in the Python and Node.js scripts):
  0 passed (also "passed, but a newer version is live") or uploaded with -NoWait;  1 the stream test failed;
  2 not tested - a newer upload of the same app is tested instead;  3 no result within -Timeout;
  4 the upload itself failed (API key, file, network) - run the same command again to continue it.
Same steps as the REST guide:
  1. POST /v1/uploads/app-builds   2. PUT each part   3. POST /v1/uploads/app-builds/<uploadId>/complete
  4. (optional) GET /v1/uploads/app-builds/<uploadId>
#>
param([Parameter(Mandatory = $true)][string]$Zip, [Parameter(Mandatory = $true)][string]$App,
      [double]$PartSize = 0, [ValidateRange(1, 64)][int]$Parallel = 4, [double]$Timeout = 45, [switch]$NoWait)
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Add-Type -AssemblyName System.Net.Http
$Api = if ($env:E3DS_API_BASE) { $env:E3DS_API_BASE.TrimEnd("/") } else { "https://agw.eagle3dstreaming.com" }
$WaitMinutes = if ($NoWait) { 0 } elseif ($env:E3DS_WAIT_MINUTES) { [double]$env:E3DS_WAIT_MINUTES } else { $Timeout }
$Key = $env:E3DS_API_KEY
if (-not $Key) { Write-Host "Set E3DS_API_KEY to your API key first."; exit 4 }
$Tries = 6; $Method = "powershell"

# One HTTP request with retries on network errors and 5xx. Returns @{ Status; Json; Headers; Text }.
function Send([string]$Verb, [string]$Url, $Body = $null, $Headers = @{}, [byte[]]$Bytes = $null) {
    $last = ""
    for ($i = 1; $i -le $Tries; $i++) {
        try {
            $a = @{ Method = $Verb; Uri = $Url; Headers = $Headers; UseBasicParsing = $true }
            if ($null -ne $Body) { $a.Body = [Text.Encoding]::UTF8.GetBytes(($Body | ConvertTo-Json -Depth 6 -Compress)); $a.ContentType = "application/json" }
            if ($null -ne $Bytes) { $a.Body = $Bytes; $a.ContentType = "application/octet-stream" }
            $r = Invoke-WebRequest @a
            $json = $null; if ($r.Content -is [string] -and $r.Content.Trim().StartsWith("{")) { $json = $r.Content | ConvertFrom-Json }
            return @{ Status = [int]$r.StatusCode; Json = $json; Headers = $r.Headers }
        } catch {
            $status = 0
            if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
            $text = "$($_.ErrorDetails.Message)"
            if ($status -ge 400 -and $status -lt 500) {   # an answer, not a network error: the caller decides
                $json = $null; if ($text.Trim().StartsWith("{")) { $json = $text | ConvertFrom-Json }
                return @{ Status = $status; Json = $json; Headers = @{}; Text = $text }
            }
            $last = $_.Exception.Message
            Write-Host "   try $i/$Tries failed ($last)$(if ($i -lt $Tries) { ' - trying again' })"
            if ($i -lt $Tries) { Start-Sleep -Seconds ([Math]::Min(30, [Math]::Pow(2, $i))) }   # no wait after the last try
        }
    }
    throw "Giving up after $Tries tries: $last"
}
function ErrorText($r) { if ($r.Json -and $r.Json.error) { return "HTTP $($r.Status): $($r.Json.error.message)" } return "HTTP $($r.Status): $($r.Text)" }
function Read-Part([int]$n, [int64]$partSize) {
    $len = [Math]::Min($partSize, $Size - ($n - 1) * $partSize)
    $buf = New-Object byte[] $len
    $stream.Position = ($n - 1) * $partSize
    [void]$stream.Read($buf, 0, $len)
    return , $buf
}
function Show-Sent { Write-Host ("2. sent {0:N1} / {1:N1} MB ({2}%)" -f ($script:sent / 1MB), ($Size / 1MB), [Math]::Floor(100 * $script:sent / $Size)) }

# PUT several parts at the same time; each part is tried again up to $Tries times.
function Send-Parts([int[]]$nums, $urls, [int64]$partSize) {
    $http = New-Object System.Net.Http.HttpClient
    $http.Timeout = [TimeSpan]::FromMinutes(30)
    try {
        $left = @($nums)
        for ($i = 1; $i -le $Tries -and $left.Count; $i++) {
            $tasks = @{}
            foreach ($n in $left) {
                $content = New-Object System.Net.Http.ByteArrayContent(, (Read-Part $n $partSize))
                $content.Headers.ContentType = "application/octet-stream"
                $tasks[$n] = $http.PutAsync([string]$urls[$n], $content)
            }
            $failed = @()
            foreach ($n in $left) {
                try {
                    $resp = $tasks[$n].GetAwaiter().GetResult()
                    if (-not $resp.IsSuccessStatusCode) { throw "HTTP $([int]$resp.StatusCode)" }
                } catch {
                    Write-Host "   part $n try $i/$Tries failed ($($_.Exception.GetBaseException().Message))$(if ($i -lt $Tries) { ' - trying again' })"
                    $failed += $n
                }
            }
            $left = $failed
            if ($left.Count -and $i -lt $Tries) { Start-Sleep -Seconds ([Math]::Min(30, [Math]::Pow(2, $i))) }
        }
        if ($left.Count) { throw "Part(s) $($left -join ', ') were not accepted." }
    } finally { $http.Dispose() }
}

# start -> parts -> complete -> (wait). Our server starts the stream test by itself after complete.
function Upload-New {
    $auth = @{ Authorization = "Bearer $Key" }
    $base = "$Api/v1/uploads/app-builds"
    $start = @{ app = $App; fileName = $File.Name; fileSize = $Size; method = $Method }
    if ($PartSize -gt 0) { $start.partSize = [int64]($PartSize * 1MB) }
    $r = Send Post $base $start $auth
    if ($r.Status -ge 300) { throw "Could not start the upload ($(ErrorText $r))" }
    $up = $r.Json; $id = $up.uploadId; $partSize = [int64]$up.partSize; $total = [int]$up.totalParts
    $done = @{}; foreach ($p in @($up.doneParts)) { if ($null -ne $p) { $done[[int]$(if ($p.partNumber) { $p.partNumber } else { $p })] = $true } }
    $urls = @{}; foreach ($p in @($up.parts)) { if ($p) { $urls[[int]$p.partNumber] = $p.url } }
    $todo = @(1..$total | Where-Object { -not $done.ContainsKey($_) })
    Write-Host "1. upload started: app '$App', version $($up.version), $total part(s) of $([Math]::Round($partSize / 1MB, 2)) MB, $Parallel at a time$(if ($done.Count) { " - resuming, $($done.Count) part(s) already sent" })"

    $script:sent = [Math]::Min($Size, $done.Count * $partSize)
    for ($i = 0; $i -lt $todo.Count; $i += $Parallel) {
        $batch = @($todo[$i..([Math]::Min($i + $Parallel, $todo.Count) - 1)])
        $missing = @($batch | Where-Object { -not $urls.ContainsKey($_) })
        if ($missing.Count) {   # more part addresses
            $r = Send Post "$base/$id/parts" @{ partNumbers = $missing } $auth
            if ($r.Status -ge 300) { throw "Could not get part addresses ($(ErrorText $r))" }
            foreach ($p in $r.Json.parts) { $urls[[int]$p.partNumber] = $p.url }
        }
        Send-Parts $batch $urls $partSize
        $script:sent = [Math]::Min($Size, $script:sent + $batch.Count * $partSize); Show-Sent
    }

    $r = Send Post "$base/$id/complete" $null $auth
    if ($r.Status -ge 300) { throw "Could not complete the upload ($(ErrorText $r))" }
    Write-Host "3. upload complete ($($r.Json.state)) - our server starts the stream test by itself"
    if ($WaitMinutes -le 0) { Write-Host "   not waiting: the result comes by email and in the Control Panel"; return 0 }

    $deadline = (Get-Date).AddMinutes($WaitMinutes)
    while ((Get-Date) -lt $deadline) {
        Start-Sleep -Seconds 30
        $s = (Send Get "$base/$id" $null $auth).Json
        if ($s.state -eq "passed") { Write-Host "4. PASSED - app '$App', version $($up.version) $(if ($s.live -ne $false) { 'is live' } else { "passed, but a newer version is live ($($s.liveVersion))" })"; return 0 }
        if ($s.state -eq "failed") { Write-Host "4. FAILED: $($s.reason) $($s.report)"; return 1 }
        if ($s.state -eq "replaced") { Write-Host "4. REPLACED by a newer upload $($s.replacedBy) - version $($up.version) was not tested (live version: $($s.liveVersion))"; return 2 }
        Write-Host ("   {0} {1}..." -f (Get-Date -Format "HH:mm:ss"), $s.state)
    }
    Write-Host "4. NO RESULT after $WaitMinutes minutes - it will come by email and in the Control Panel"
    return 3
}

if (-not (Test-Path -LiteralPath $Zip -PathType Leaf)) { Write-Host "UPLOAD FAILED: the file '$Zip' was not found."; exit 4 }
$File = Get-Item -LiteralPath $Zip
$Size = $File.Length
Write-Host ("Uploading {0} ({1:N1} MB) as app '{2}' to {3}" -f $File.Name, ($Size / 1MB), $App, $Api)
$stream = [IO.File]::OpenRead($File.FullName)
try {
    $code = Upload-New
} catch {
    Write-Host "UPLOAD FAILED: $($_.Exception.Message)"
    $code = 4
} finally { $stream.Close() }
exit $code

Running it, step by step

  1. Save the script above as e3ds-upload.ps1 next to your zip. Nothing to install.
  2. In a PowerShell window in that folder, set your API key: $env:E3DS_API_KEY = "your API key". It lasts until the window is closed.
  3. Run powershell -ExecutionPolicy Bypass -File .\e3ds-upload.ps1 MyGame.zip MyGame. -ExecutionPolicy Bypass lets Windows run this one script without changing any setting.

What it prints, from a real upload of a 218 MB build with -PartSize 50:

Uploading MyGame.zip (217.8 MB) as app 'MyGame' to https://agw.eagle3dstreaming.com
1. upload started: app 'MyGame', version v1795149047748, 5 part(s) of 50 MB, 4 at a time
2. sent 200.0 / 217.8 MB (91%)
2. sent 217.8 / 217.8 MB (100%)
3. upload complete (queued) - our server starts the stream test by itself
   22:31:24 queued...
   22:31:54 queued...
   22:32:25 testing...
...
   22:45:34 testing...
4. PASSED - app 'MyGame', version v1795149047748 is live

$LASTEXITCODE is 0 when the build passed and 1 when it failed (2: not tested because a newer upload of the same app is tested instead; 3: no result within -Timeout; 4: the upload itself failed - run the same command again and it continues where it stopped), so Azure DevOps, Jenkins or a Windows Task Scheduler job can act on it.

Watch it in 1:50

Upload with PowerShellVideo · 1:50

If the upload stops: run the same command again

Nothing extra is needed to resume. If the upload stops - the network drops, the computer sleeps, the window is closed, Ctrl+C - just run the same command again, with the same zip and the same app name, within 24 hours:

powershell -ExecutionPolicy Bypass -File .\e3ds-upload.ps1 MyGame.zip MyGame

The script finds the unfinished upload by itself and sends only the parts that are still missing. Its first line then says resuming, N part(s) already sent, and the version number stays the same. A part that fails on its own is sent again automatically (up to six tries), so a short network hiccup needs nothing from you at all. Video of a real run: youtu.be/c0x8wsBRiCs. How it works: Resumable uploads.

When it fails, and keeping the key safe

Every message the script can print, and what it means: when it fails. How to store the key in a pipeline: keep your API key safe. The other ways to upload automatically: Automated upload.

Related

Last updated