-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.fs
More file actions
773 lines (645 loc) · 29.3 KB
/
Program.fs
File metadata and controls
773 lines (645 loc) · 29.3 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
namespace Akka.WebSocketBridge
open System
open System.Text
open System.Threading
open System.Threading.Tasks
open System.Diagnostics
open Newtonsoft.Json
open Newtonsoft.Json.Linq
open Akka.Actor
open Akka.Configuration
open Akka.Event
open Akka.Cluster
open Suave
open Suave.Filters
open Suave.Operators
open Suave.Successful
open Suave.Sockets
open Suave.Sockets.Control
open Suave.WebSocket
open Suave.ServerErrors
/// Handle returned when the server is started; dispose or call Stop to shut it down.
type ServerHandle internal (cts: CancellationTokenSource) =
member _.Stop() =
if not cts.IsCancellationRequested then
cts.Cancel()
interface IDisposable with
member this.Dispose() = this.Stop()
type ReplyActor<'T>(system: ActorSystem, tcs: TaskCompletionSource<'T>) as this =
inherit UntypedActor()
let selfRef = this.Self
override _.OnReceive message =
match message with
| :? 'T as payload ->
if tcs.TrySetResult payload then
system.Stop selfRef
| :? Akka.Actor.Status.Failure as failure ->
let cause : Exception = failure.Cause
if tcs.TrySetException(cause) then
system.Stop selfRef
| _ -> ()
override _.PostStop() =
if not tcs.Task.IsCompleted then
tcs.TrySetCanceled() |> ignore
type EchoActor(system: ActorSystem, nodeAddress: string) as this =
inherit UntypedActor()
let log = system.Log
override _.PreStart() =
log.Info("EchoActor starting on {0}", nodeAddress)
override _.PostStop() =
log.Info("EchoActor stopped.")
override _.OnReceive message =
match message with
| :? string as msg when String.Equals(msg, "healthcheck", StringComparison.OrdinalIgnoreCase) ->
printfn "checking healthness by actor"
this.Sender.Tell("ok", this.Self)
| :? string as msg ->
log.Info("EchoActor received payload: {0}", msg)
| _ -> ()
module WebSocketServer =
let log (actorSystem: ActorSystem) =
Logging.GetLogger(actorSystem, "Akka.WebSocketBridge")
type SocketPayload = byte[]
#if NET10_0_OR_GREATER
let emptyPayload : ByteSegment = Memory<byte>.Empty
#else
let emptyPayload : SocketPayload = Array.empty<byte>
#endif
#if NET10_0_OR_GREATER
// 假設你的定義是: type ByteSegment = Memory<byte>
let decodeUtf8 (data: ByteSegment) =
// 直接使用 .Span 屬性
// Encoding.GetString 有一個多載可以吃 ReadOnlySpan<byte>
Encoding.UTF8.GetString(data.Span)
#else
let decodeUtf8 (data: SocketPayload) =
Encoding.UTF8.GetString data
#endif
#if NET10_0_OR_GREATER
// 輔助函式:將 string 轉為 ByteSegment
let encodeUtf8 (text: string) : ByteSegment =
Encoding.UTF8.GetBytes(text).AsMemory()
#else
// 輔助函式:將 string 轉為 SocketPayload
let encodeUtf8 (text: string) : SocketPayload =
Encoding.UTF8.GetBytes(text)
#endif
#if NET10_0_OR_GREATER
// 假設 data 是 byte[] (原本的 SocketPayload)
let inline sendFrame (ws: WebSocket) opcode (bSegment: ByteSegment) =
ws.send opcode bSegment true
#else
let inline sendFrame (ws: WebSocket) opcode (data: SocketPayload): Async<Choice<unit, Error>> =
let segment = ArraySegment<byte>(data, 0, data.Length)
ws.send opcode segment true
#endif
let handleSent (logOpt:ILoggingAdapter option) rtn =
match rtn with
#if NET10_0_OR_GREATER
| Ok () -> ()
#else
| Choice1Of2 () -> ()
#endif
#if NET10_0_OR_GREATER
| Result.Error ex ->
#else
| Choice2Of2 ex ->
#endif
if logOpt.IsSome then
let log = logOpt.Value
match ex with
| SocketError se ->
log.Warning(sprintf "KillActor failure: SocketError: %A" se)
| InputDataError v ->
log.Warning(sprintf "KillActor failure: InputDataError: %A" v)
| ConnectionError ce ->
log.Warning($"KillActor failure: ConnectionError: {ce}")
/// <summary>
/// 這是一個短命的 Proxy Actor,生命週期等同於 WebSocket 連線。
/// 它代表「遠端的瀏覽器」,當其他 Actor 對它 Tell 時,它會寫入 WS。
/// </summary>
type WebSocketResponseActor(ws: WebSocket) as self =
inherit UntypedActor()
let ia = self :> IInternalActor
let log = ia.ActorContext.GetLogger()
override _.OnReceive (message: obj) =
match message with
| :? string as text ->
// 收到字串 -> 轉成 UTF8 -> 發送 Text Frame
let payload = encodeUtf8 text
// Fire-and-forget 發送 (不等待結果,避免阻塞 Actor Mailbox)
async {
#if NET10_0_OR_GREATER
// .NET 10 / Suave 3.x (ValueTask)
let task = sendFrame ws Text payload
let! rtn = task.AsTask() |> Async.AwaitTask
#else
// Old Suave (Async)
let! rtn = sendFrame ws Text payload
#endif
handleSent (Some log) rtn
} |> Async.Start
| _ ->
// 也可以擴充支援 byte[] 等其他格式
()
let sendWithReply<'TResponse>
(system: ActorSystem)
(target: IActorRef)
(messageFactory: IActorRef -> obj)
: Async<'TResponse> =
async {
let tcs = TaskCompletionSource<'TResponse>()
let adapter =
system.ActorOf(
Props.Create(typeof<ReplyActor<'TResponse>>, [| system :> obj; tcs :> obj |])
)
let message = messageFactory adapter
target.Tell(message, adapter)
try
return! tcs.Task |> Async.AwaitTask
finally
system.Stop(adapter)
}
let websocketLoop
(actorSystem: ActorSystem)
(handleActorGetter: ActorSystem -> WebSocket option -> IActorRef option)
(ws: WebSocket)
: SocketOp<unit> =
let logger = log actorSystem
match handleActorGetter actorSystem (Some ws) with
| None ->
socket {
logger.Error("No handler actor available for WebSocket connection; closing client.")
do! sendFrame ws Close emptyPayload
return ()
}
| Some handler ->
// 1. 【關鍵修改】建立代表這個 WebSocket Client 的代理 Actor
// 使用 Guid 避免名稱衝突
let proxyName = $"ws-client-{Guid.NewGuid()}"
let proxyProps = Props.Create(fun () -> WebSocketResponseActor(ws))
let proxyActor = actorSystem.ActorOf(proxyProps, proxyName)
// 2. 確保 loop 結束時銷毀這個 Actor (Dispose)
let cleanup () =
logger.Debug($"WebSocket closed, stopping proxy actor: {proxyName}")
actorSystem.Stop(proxyActor)
let rec loop () =
socket {
let! msg = ws.read()
match msg with
#if NET10_0_OR_GREATER
| (Text, (data: ByteSegment), true) ->
#else
| (Text, (data: SocketPayload), true) ->
#endif
let payload = decodeUtf8 data
logger.Debug("Forwarding WebSocket payload: {0}", payload)
let handledAsJson =
try
match JToken.Parse(payload) with
| :? JArray as arr ->
let elements = arr.Children()
if elements |> Seq.forall (fun element -> element.Type = JTokenType.String) then
let values =
elements
|> Seq.map (fun element -> element.ToObject<string>())
|> Seq.toArray
handler.Tell(values, proxyActor)
true
else
false
| :? JValue as value when value.Type = JTokenType.String ->
handler.Tell(value.ToObject<string>(), proxyActor)
true
| _ -> false
with
| :? JsonReaderException -> false
if not handledAsJson then
handler.Tell(payload, proxyActor)
return! loop ()
| (Text, d, false) ->
logger.Warning(sprintf "Received fragmented WebSocket message %A. Closing connection." d)
do! sendFrame ws Close emptyPayload
return ()
| (Close, _, _) ->
logger.Info("Client requested WebSocket close.")
do! sendFrame ws Close emptyPayload
return ()
#if NET10_0_OR_GREATER
| (Ping, (data: ByteSegment), _) ->
#else
| (Ping, (data: SocketPayload), _) ->
#endif
do! sendFrame ws Pong data
return! loop ()
| (Binary, _, _)
| (Pong, _, _)
| (Continuation, _, _)
| (Reserved, _, _) ->
// Not supporting binary or continuation frames; stay silent.
return! loop ()
}
// 使用 try...finally 確保 Actor 被銷毀
socket {
try
return! loop ()
with ex ->
logger.Error($"WebSocket loop error: {ex.Message}")
return ()
}
|> Suave.Sockets.SocketOp.map (fun x ->
cleanup() // Loop 結束時執行清理
)
/// Start a Suave WebSocket endpoint that forwards JSON text frames to the supplied actor.
let start
(actorSystem: ActorSystem)
(wsName: string)
(defaultWebpartOpt: (IActorRef option -> WebPart list) option)
configChoice
(handleActorGetter: ActorSystem -> WebSocket option -> IActorRef option)
: ServerHandle =
if isNull (box actorSystem) then
nullArg (nameof actorSystem)
if isNull (box handleActorGetter) then
nullArg (nameof handleActorGetter)
let wsEndpoint =
let socketLoop = websocketLoop actorSystem handleActorGetter
handShake (fun ws _ -> socketLoop ws)
let healthRoute : WebPart =
fun ctx ->
async {
match handleActorGetter actorSystem None with
| None ->
return! SERVICE_UNAVAILABLE "handler unavailable" ctx
| Some handler ->
try
let! reply =
sendWithReply<string> actorSystem handler (fun replyTo -> box "healthcheck")
return! OK reply ctx
with ex ->
return! INTERNAL_ERROR ex.Message ctx
}
let webApp =
match defaultWebpartOpt with
| None -> []
| Some lGen -> lGen (handleActorGetter actorSystem None)
|> List.append [
path $"/{wsName}" >=> wsEndpoint
path "/health" >=> healthRoute
]
|> choose
let config =
match configChoice with
| Choice1Of2 c -> c
| Choice2Of2 (host, port) ->
{ defaultConfig with
bindings = [ HttpBinding.createSimple HTTP host port ]
homeFolder = None }
let cts = new CancellationTokenSource()
#if NET10_0_OR_GREATER
let config = { config with cancellationToken = cts.Token }
let listening, (server:Task) = startWebServerAsync config webApp
server.ContinueWith(fun (t:Task) ->
if t.IsFaulted then printfn "Server crashed: %A" t.Exception) |> ignore
#else
let listening, (server:Async<unit>) = startWebServerAsync config webApp
Async.Start(server, cancellationToken = cts.Token)
#endif
listening
|> Async.Catch
|> Async.RunSynchronously
|> function
| Choice1Of2 _ -> ()
| Choice2Of2 ex ->
cts.Cancel()
raise ex
new ServerHandle(cts)
module SimpleKiller =
open WebSocketServer
open System
open System.Diagnostics
open System.Runtime.InteropServices
//[<StructLayout(LayoutKind.Sequential)>]
type STARTUPINFOEX() =
member val StartupInfo = new ProcessStartInfo() with get, set
[<Flags>]
type ProcessCreationFlags =
| EXTENDED_STARTUPINFO_PRESENT = 0x00080000
| CREATE_NO_WINDOW = 0x08000000
[<DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)>]
extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
ProcessCreationFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
IntPtr lpStartupInfo,
IntPtr lpProcessInformation
)
let startWithoutHandleInheritance (encodedScript: string) =
let cmd = sprintf "powershell.exe -NoLogo -NoProfile -EncodedCommand %s" encodedScript
let ok =
CreateProcess(
null,
cmd,
IntPtr.Zero,
IntPtr.Zero,
false, // ❗ 不繼承任何 handle
ProcessCreationFlags.CREATE_NO_WINDOW,
IntPtr.Zero,
null,
IntPtr.Zero,
IntPtr.Zero
)
if not ok then
let err = Marshal.GetLastWin32Error()
failwithf "CreateProcess failed: %d" err
else
printfn "PowerShell started without inherited handles."
type KillActor((f:unit -> unit), system: ActorSystem, nodeAddress: string, wsOpt:WebSocket option) as this =
inherit UntypedActor()
let log = system.Log
let escapeForSingleQuotedLiteral (value: string) =
if isNull value then
String.Empty
else
value.Replace("'", "''")
let startMonitoringProcess (filePath: string) (scriptText: string) =
let safeFilePath = if isNull filePath then String.Empty else filePath
let safeScriptText = if isNull scriptText then String.Empty else scriptText
if String.IsNullOrWhiteSpace safeFilePath then
log.Warning("KillActor received kill command without a target file; skipping PowerShell monitor.")
else
try
let fileLiteral = $"'{escapeForSingleQuotedLiteral safeFilePath}'"
let scriptBase64 =
if String.IsNullOrWhiteSpace safeScriptText then
String.Empty
else
Convert.ToBase64String(Encoding.Unicode.GetBytes safeScriptText)
let scriptLiteral = $"'{escapeForSingleQuotedLiteral scriptBase64}'"
let psBuilder = StringBuilder()
psBuilder.AppendLine("$ErrorActionPreference = 'Stop'") |> ignore
psBuilder.AppendLine($"$targetPath = {fileLiteral}") |> ignore
psBuilder.AppendLine($"$scriptTextBase64 = {scriptLiteral}") |> ignore
psBuilder.AppendLine("function Get-FileSignature {") |> ignore
psBuilder.AppendLine(" param([string]$Path)") |> ignore
psBuilder.AppendLine(" if (-not (Test-Path -LiteralPath $Path)) {") |> ignore
psBuilder.AppendLine(" return $null") |> ignore
psBuilder.AppendLine(" }") |> ignore
psBuilder.AppendLine(" $item = Get-Item -LiteralPath $Path") |> ignore
psBuilder.AppendLine(" $version = $null") |> ignore
psBuilder.AppendLine(" try {") |> ignore
psBuilder.AppendLine(" $version = $item.VersionInfo.FileVersion") |> ignore
psBuilder.AppendLine(" } catch {") |> ignore
psBuilder.AppendLine(" $version = $null") |> ignore
psBuilder.AppendLine(" }") |> ignore
psBuilder.AppendLine(" [pscustomobject]@{") |> ignore
psBuilder.AppendLine(" Version = $version") |> ignore
psBuilder.AppendLine(" Created = $item.LastWriteTime") |> ignore
psBuilder.AppendLine(" }") |> ignore
psBuilder.AppendLine("}") |> ignore
psBuilder.AppendLine("$initial = Get-FileSignature -Path $targetPath") |> ignore
psBuilder.AppendLine("while ($true) {") |> ignore
psBuilder.AppendLine(" Start-Sleep -Milliseconds 1000") |> ignore
psBuilder.AppendLine(" $current = Get-FileSignature -Path $targetPath") |> ignore
psBuilder.AppendLine(" if ($null -eq $initial) {") |> ignore
psBuilder.AppendLine(" if ($null -ne $current) { break }") |> ignore
psBuilder.AppendLine(" } elseif ($null -ne $current) {") |> ignore
psBuilder.AppendLine(" if (($current.Version -ne $initial.Version) -or ($current.Created -ne $initial.Created)) {") |> ignore
psBuilder.AppendLine(" break") |> ignore
psBuilder.AppendLine(" }") |> ignore
psBuilder.AppendLine(" }") |> ignore
psBuilder.AppendLine("}") |> ignore
psBuilder.AppendLine("if (-not [string]::IsNullOrWhiteSpace($scriptTextBase64)) {") |> ignore
psBuilder.AppendLine(" $scriptText = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($scriptTextBase64))") |> ignore
psBuilder.AppendLine(" if (-not [string]::IsNullOrWhiteSpace($scriptText)) {") |> ignore
psBuilder.AppendLine(" $scriptBlock = [scriptblock]::Create($scriptText)") |> ignore
psBuilder.AppendLine(" & $scriptBlock") |> ignore
psBuilder.AppendLine(" }") |> ignore
psBuilder.AppendLine("}") |> ignore
let script = psBuilder.ToString()
//IO.File.WriteAllText("C:\\killactor_monitor.ps1", script)
let encodedScript =
script
//"write-host 'hi'"
|> Encoding.Unicode.GetBytes
|> Convert.ToBase64String
let startInfo = ProcessStartInfo()
startInfo.FileName <- "powershell.exe"
//startInfo.Arguments <- "-NoExit -NoLogo -NoProfile -EncodedCommand " + encodedScript
startInfo.Arguments <- "-NoLogo -NoProfile -EncodedCommand " + encodedScript
startInfo.CreateNoWindow <- true
startInfo.WindowStyle <- ProcessWindowStyle.Hidden
startInfo.UseShellExecute <- true
//startInfo.RedirectStandardInput <- true
//startInfo.RedirectStandardOutput <- true
//startInfo.RedirectStandardError <- true
let proc = Process.Start(startInfo)
//startWithoutHandleInheritance encodedScript
//log.Info("KillActor started monitoring PowerShell process '{1}'.", safeFilePath)
match proc with
| null ->
log.Warning("KillActor could not start monitoring PowerShell process for '{0}'.", safeFilePath)
| proc ->
log.Info("KillActor started monitoring PowerShell process (PID {0}) for '{1}'.", proc.Id, safeFilePath)
with ex ->
log.Warning("KillActor failed to launch monitoring PowerShell process for '{0}'. Cause: {1}", safeFilePath, ex.Message)
static member val locker: obj = obj() with get
static member val iaref: IActorRef option = None with get, set
override _.PreStart() =
log.Info("KillActor starting on {0}", nodeAddress)
override _.PostStop() =
log.Info("KillActor stopped.")
override _.OnReceive message =
match message with
| :? (string[]) as payload ->
if payload.Length = 0 then
log.Warning("KillActor received empty string array payload.")
else
let command = payload.[0]
if String.Equals(command, "healthcheck", StringComparison.OrdinalIgnoreCase) then
printfn "checking healthness by actor"
this.Sender.Tell("ok", this.Self)
elif String.Equals(command, "kill", StringComparison.OrdinalIgnoreCase) then
let filePath = if payload.Length > 1 then payload.[1] else null
let scriptText = if payload.Length > 2 then payload.[2] else null
startMonitoringProcess filePath scriptText
log.Info("KillActor killing now.")
Environment.Exit(0)
else
log.Info("KillActor received string[] payload for command: {0}", command)
| :? string as msg when String.Equals(msg, "healthcheck", StringComparison.OrdinalIgnoreCase) ->
printfn $"checking healthness by actor, wsOpt.IsNone: {wsOpt.IsNone}"
if wsOpt.IsNone then
this.Sender.Tell("ok", this.Self)
else
async {
#if NET10_0_OR_GREATER
let payload = "ok" |> Encoding.UTF8.GetBytes |> Memory<byte>
// 1. 先呼叫 .AsTask() 轉成普通 Task
// 2. 再呼叫 Async.AwaitTask
let! rtn =
wsOpt.Value.send Text payload true
|> (fun vt -> vt.AsTask())
|> Async.AwaitTask
#else
let! rtn = wsOpt.Value.send Text (ArraySegment<byte>(Encoding.UTF8.GetBytes "ok")) true
#endif
handleSent (Some log) rtn
}
|> Async.Start
| :? string as msg when String.Equals(msg, "kill", StringComparison.OrdinalIgnoreCase) ->
log.Info("KillActor killing now (no automation payload).")
f ()
Environment.Exit(0)
| :? string as msg ->
log.Info("KillActor received payload: {0}", msg)
| msg ->
log.Info(sprintf "KillActor received payload: %A" msg)
let simpleKillerFun (f:unit -> unit) nodeAddress (actorSystem:ActorSystem) (wsOpt:WebSocket option) =
lock KillActor.locker (fun _ ->
if KillActor.iaref.IsSome then
KillActor.iaref
else
let killProps = Props.Create<KillActor>(f, actorSystem, nodeAddress, wsOpt)
let killActor = actorSystem.ActorOf(killProps, "ws-kill")
KillActor.iaref <- Some killActor
Some killActor
)
module Program =
open System
open System.IO
open System.Reflection
//let exeDir = AppDomain.CurrentDomain.BaseDirectory
//let dll = Directory.GetFiles(exeDir, "MergedSB.dll")[0]
//try
// Assembly.LoadFile(dll) |> ignore
// printfn "Loaded: %s" dll
//with ex ->
// printfn "Failed to load %s: %s" dll ex.Message
let parseInt (fallback: int) (value: string) =
let maxPort = int UInt16.MaxValue
match Int32.TryParse value with
| true, v when v > 0 && v <= maxPort -> v
| _ -> fallback
let pickArg (args: string[]) index fallback =
if args.Length > index then args.[index] else fallback
let demo args =
let httpHost = pickArg args 0 "0.0.0.0"
let httpPort = pickArg args 1 "8080" |> parseInt 8080
let clusterHost = pickArg args 2 "127.0.0.1"
let clusterPort = pickArg args 3 "4053" |> parseInt 4053
let seedNodes =
if args.Length > 4 then
args.[4]
.Split([|','|], StringSplitOptions.RemoveEmptyEntries)
|> Array.map (fun s -> s.Trim())
|> Array.filter (String.IsNullOrWhiteSpace >> not)
else
[| sprintf "akka.tcp://WebSocketCluster@%s:%d" clusterHost clusterPort |]
let seedNodesLiteral =
seedNodes
|> Array.map (fun node -> sprintf "\"%s\"" node)
|> String.concat ", "
let hocon =
$"""
akka {{
loglevel = "INFO"
stdout-loglevel = "INFO"
actor.provider = "cluster"
remote.dot-netty.tcp {{
hostname = "{clusterHost}"
public-hostname = "{clusterHost}"
port = {clusterPort}
}}
cluster {{
seed-nodes = [{seedNodesLiteral}]
}}
}}
"""
let config = ConfigurationFactory.ParseString hocon
let actorSystem = ActorSystem.Create("WebSocketCluster", config)
let log = actorSystem.Log
let cluster = Cluster.Get(actorSystem)
let nodeAddress = cluster.SelfAddress.ToString()
log.Info("Cluster seed node configured at {0}", nodeAddress)
let echoProps = Props.Create<EchoActor>(actorSystem, nodeAddress)
let echoActor = actorSystem.ActorOf(echoProps, "ws-echo")
log.Info("Echo actor spawned at {0}", echoActor.Path.ToStringWithUid())
let echoActorGetter (asys:ActorSystem) (_: WebSocket option) =
Some echoActor
let server = WebSocketServer.start actorSystem "ws" None (Choice2Of2 (httpHost, httpPort)) echoActorGetter
log.Info("Suave WebSocket bridge listening on ws://{0}:{1}/ws", httpHost, httpPort)
let server2 = WebSocketServer.start actorSystem "ws2" None (Choice2Of2 (httpHost, 60254)) (SimpleKiller.simpleKillerFun (fun () -> ()) httpHost)
let shutdownLock = obj ()
let mutable stopped = false
let shutdown () =
lock shutdownLock (fun () ->
if not stopped then
stopped <- true
log.Info("Shutting down WebSocket bridge and actor system...")
server.Stop()
actorSystem.Terminate()
|> Async.AwaitTask
|> Async.RunSynchronously
actorSystem.WhenTerminated.Wait()
log.Info("Termination complete.")
)
Console.CancelKeyPress.Add(fun args ->
args.Cancel <- true
shutdown ()
)
printfn "Seed nodes: %s" (seedNodes |> String.concat ", ")
printfn "Press ENTER to stop..."
Console.ReadLine() |> ignore
shutdown ()
[<EntryPoint>]
let main args =
demo args
0
(*
Test in console of a browser:
(function testWebSocket() {
// 1. 設定目標位址 (根據你的 F# 預設值: Port 8080, Path /ws)
const host = "localhost"; // 如果 Server 在別台機器,請改 IP
const port = 8080;
const path = "ws";
const url = `ws://${host}:${port}/${path}`;
console.log(`🚀 嘗試連線至: ${url}`);
try {
const ws = new WebSocket(url);
// 連線成功事件
ws.onopen = () => {
console.log("%c✅ 連線成功 (Connected)", "color: green; font-weight: bold;");
// 發送測試訊息
const payload = "Hello Akka.NET!";
console.log(`📤 發送訊息: "${payload}"`);
ws.send(payload);
};
// 接收訊息事件 (預期會收到 Echo)
ws.onmessage = (event) => {
console.log("%c📥 收到回覆 (Received):", "color: blue; font-weight: bold;", event.data);
// 收到回覆後,可選擇關閉連線
// ws.close();
};
// 錯誤處理
ws.onerror = (err) => {
console.error("❌ 發生錯誤 (Error):", err);
console.log("💡 提示: 請確認 F# 程式已啟動,且沒有被防火牆擋住 Port 8080。");
};
// 連線關閉
ws.onclose = (evt) => {
console.log(`⚠️ 連線已關閉 (Closed) - Code: ${evt.code}, Reason: ${evt.reason}`);
};
// 將 ws 物件掛到 window 上,方便你在 Console 手動玩 (例如 window.debugWS.send("test"))
window.debugWS = ws;
console.log("ℹ️ WebSocket 物件已儲存至 'window.debugWS',你可以手動輸入 debugWS.send('...')");
} catch (e) {
console.error("💥 初始化失敗:", e);
}
})();
*)