aboutsummaryrefslogtreecommitdiffstats
path: root/run_tcp.ps1
blob: 175fc26ccff9510e0252f10b7c72bd7d7c5b5f3f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
param(
  [string]$ConfigPath = ".\config.sexp",
  [string]$ServerHost = "127.0.0.1",
  [int]$Port = 7777,
  [string[]]$Command,
  [string]$CommandsPath,
  [switch]$UseExistingServer,
  [switch]$UseLocalServer,
  [switch]$SkipBuild,
  [switch]$NoInteractive
)

$ErrorActionPreference = "Stop"

function Invoke-Build {
  Write-Host "Building Sakura..."
  dune build
  if (-not $?) {
    throw "Build failed."
  }
}

function Start-SakuraServer {
  param(
    [string]$Config,
    [string]$WorkingDirectory,
    [switch]$UseOpam
  )

  Write-Host "Starting Sakura server with config $Config ..."
  $filePath = "dune"
  $serverArgs = @("exec", "sakura-server", "--", $Config)
  if ($UseOpam) {
    $filePath = "opam"
    $serverArgs = @("exec", "--", "sakura-server", $Config)
  }

  $proc = Start-Process -FilePath $filePath `
    -ArgumentList $serverArgs `
    -WorkingDirectory $WorkingDirectory `
    -PassThru

  return $proc
}

function Wait-ForTcp {
  param(
    [string]$TargetHost,
    [int]$TargetPort,
    [int]$TimeoutSeconds = 20
  )

  $deadline = (Get-Date).AddSeconds($TimeoutSeconds)
  while ((Get-Date) -lt $deadline) {
    $client = $null
    try {
      $client = [System.Net.Sockets.TcpClient]::new()
      $async = $client.BeginConnect($TargetHost, $TargetPort, $null, $null)
      if ($async.AsyncWaitHandle.WaitOne(250)) {
        $client.EndConnect($async)
        $client.Close()
        return
      }
      $client.Close()
    } catch {
      if ($null -ne $client) {
        $client.Close()
      }
      Start-Sleep -Milliseconds 250
    }
  }

  throw "Timed out waiting for TCP server at $TargetHost`:$TargetPort"
}

function Connect-Tcp {
  param(
    [string]$TargetHost,
    [int]$TargetPort
  )

  $client = [System.Net.Sockets.TcpClient]::new($TargetHost, $TargetPort)
  $stream = $client.GetStream()
  $writer = [System.IO.StreamWriter]::new($stream)
  $writer.AutoFlush = $true
  $reader = [System.IO.StreamReader]::new($stream)

  return @{
    Client = $client
    Writer = $writer
    Reader = $reader
  }
}

function Send-Command {
  param(
    [System.IO.StreamWriter]$Writer,
    [System.IO.StreamReader]$Reader,
    [string]$Line
  )

  $Writer.WriteLine($Line)
  $response = $Reader.ReadLine()
  if ($null -eq $response) {
    throw "Connection closed by server."
  }

  Write-Host "< $response"
}

$repoRoot = $PSScriptRoot
$serverProcess = $null

try {
  if (-not $SkipBuild) {
    Invoke-Build
  }

  if (-not $UseExistingServer) {
    if ($UseLocalServer) {
      Write-Host "Server mode: local dune exec sakura-server"
    } else {
      Write-Host "Server mode: opam-installed sakura-server"
    }
    $serverProcess = Start-SakuraServer -Config $ConfigPath -WorkingDirectory $repoRoot -UseOpam:(-not $UseLocalServer)
    Wait-ForTcp -TargetHost $ServerHost -TargetPort $Port
    Write-Host "Server is ready on $ServerHost`:$Port"
  }

  $conn = Connect-Tcp -TargetHost $ServerHost -TargetPort $Port
  $writer = $conn.Writer
  $reader = $conn.Reader

  $commandsToSend = @()
  if ($null -ne $Command -and $Command.Count -gt 0) {
    $commandsToSend += $Command
  }
  if (-not [string]::IsNullOrWhiteSpace($CommandsPath)) {
    $fileCommands = Get-Content -Path $CommandsPath |
      Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
    $commandsToSend += $fileCommands
  }

  if ($commandsToSend.Count -gt 0) {
    foreach ($cmd in $commandsToSend) {
      Write-Host "> $cmd"
      Send-Command -Writer $writer -Reader $reader -Line $cmd
    }
  }

  if (-not $NoInteractive) {
    Write-Host "Interactive mode. Type :quit to exit."
    while ($true) {
      $line = Read-Host ">"
      if ($line -eq ":quit") {
        break
      }
      if ([string]::IsNullOrWhiteSpace($line)) {
        continue
      }

      Send-Command -Writer $writer -Reader $reader -Line $line
    }
  }

  $writer.Dispose()
  $reader.Dispose()
  $conn.Client.Close()
}
finally {
  if ($null -ne $serverProcess -and -not $serverProcess.HasExited) {
    Write-Host "Stopping Sakura server (PID $($serverProcess.Id))"
    Stop-Process -Id $serverProcess.Id -Force
  }
}