/
Core.ps1
1428 lines (1118 loc) · 36.8 KB
/
Core.ps1
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Starts a Pode Server with the supplied ScriptBlock.
.DESCRIPTION
Starts a Pode Server with the supplied ScriptBlock.
.PARAMETER ScriptBlock
The main logic for the Server.
.PARAMETER FilePath
A literal, or relative, path to a file containing a ScriptBlock for the Server's logic.
The directory of this file will be used as the Server's root path - unless a specific -RootPath is supplied.
.PARAMETER Interval
For 'Service' type Servers, will invoke the ScriptBlock every X seconds.
.PARAMETER Name
An optional name for the Server (intended for future ideas).
.PARAMETER Threads
The numbers of threads to use for Web and TCP servers.
.PARAMETER RootPath
An override for the Server's root path.
.PARAMETER Request
Intended for Serverless environments, this is Requests details that Pode can parse and use.
.PARAMETER Type
The server type, to define how Pode should run and deal with incoming Requests.
.PARAMETER DisableTermination
Disables the ability to terminate the Server.
.PARAMETER Browse
Open the web Server's default endpoint in your defualt browser.
.PARAMETER CurrentPath
Sets the Server's root path to be the current working path - for -FilePath only.
.EXAMPLE
Start-PodeServer { /* logic */ }
.EXAMPLE
Start-PodeServer -Interval 10 { /* logic */ }
.EXAMPLE
Start-PodeServer -Request $LambdaInput -Type 'AwsLambda' { /* logic */ }
#>
function Start-PodeServer
{
[CmdletBinding(DefaultParameterSetName='Script')]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0, ParameterSetName='Script')]
[scriptblock]
$ScriptBlock,
[Parameter(Mandatory=$true, ParameterSetName='File')]
[string]
$FilePath,
[Parameter()]
[int]
$Interval = 0,
[Parameter()]
[string]
$Name,
[Parameter()]
[int]
$Threads = 1,
[Parameter()]
[string]
$RootPath,
[Parameter()]
$Request,
[Parameter()]
[ValidateSet('', 'AzureFunctions', 'AwsLambda', 'Pode')]
[string]
$Type = [string]::Empty,
[switch]
$DisableTermination,
[switch]
$Browse,
[Parameter(ParameterSetName='File')]
[switch]
$CurrentPath
)
# ensure the session is clean
$PodeContext = $null
$ShowDoneMessage = $true
try {
# if we have a filepath, resolve it - and extract a root path from it
if ($PSCmdlet.ParameterSetName -ieq 'file') {
$FilePath = Get-PodeRelativePath -Path $FilePath -Resolve -TestPath
# if not already supplied, set root path
if ([string]::IsNullOrWhiteSpace($RootPath)) {
if ($CurrentPath) {
$RootPath = $PWD.Path
}
else {
$RootPath = Split-Path -Parent -Path $FilePath
}
}
}
# configure the server's root path
if (!(Test-IsEmpty $RootPath)) {
$RootPath = Get-PodeRelativePath -Path $RootPath -RootPath $MyInvocation.PSScriptRoot -JoinRoot -Resolve -TestPath
}
# create main context object
$PodeContext = New-PodeContext `
-ScriptBlock $ScriptBlock `
-FilePath $FilePath `
-Threads $Threads `
-Interval $Interval `
-ServerRoot (Protect-PodeValue -Value $RootPath -Default $MyInvocation.PSScriptRoot) `
-ServerType $Type
# set it so ctrl-c can terminate, unless serverless
if (!$PodeContext.Server.IsServerless) {
[Console]::TreatControlCAsInput = $true
}
# start the file monitor for interally restarting
Start-PodeFileMonitor
# start the server
Start-PodeInternalServer -Request $Request -Browse:$Browse
# at this point, if it's just a one-one off script, return
if ([string]::IsNullOrWhiteSpace($PodeContext.Server.Type) -or $PodeContext.Server.IsServerless) {
return
}
# sit here waiting for termination/cancellation, or to restart the server
while (!(Test-PodeTerminationPressed -Key $key) -and !($PodeContext.Tokens.Cancellation.IsCancellationRequested)) {
Start-Sleep -Seconds 1
# get the next key presses
$key = Get-PodeConsoleKey
# check for internal restart
if (($PodeContext.Tokens.Restart.IsCancellationRequested) -or (Test-PodeRestartPressed -Key $key)) {
Restart-PodeInternalServer
}
}
Write-Host 'Terminating...' -NoNewline -ForegroundColor Yellow
$PodeContext.Tokens.Cancellation.Cancel()
}
catch {
$ShowDoneMessage = $false
throw
}
finally {
# clean the runspaces and tokens
Close-PodeServer -ShowDoneMessage:$ShowDoneMessage
# clean the session
$PodeContext = $null
}
}
<#
.SYNOPSIS
The CLI for Pode, to initialise, build and start your Server.
.DESCRIPTION
The CLI for Pode, to initialise, build and start your Server.
.PARAMETER Action
The action to invoke on your Server.
.PARAMETER Dev
Supply when running "pode install", this will install any dev packages defined in your package.json.
.EXAMPLE
pode install -dev
.EXAMPLE
pode build
.EXAMPLE
pode start
#>
function Pode
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[ValidateSet('init', 'test', 'start', 'install', 'build')]
[Alias('a')]
[string]
$Action,
[switch]
[Alias('d')]
$Dev
)
# default config file name and content
$file = './package.json'
$name = Split-Path -Leaf -Path $pwd
$data = $null
# default config data that's used to populate on init
$map = @{
'name' = $name;
'version' = '1.0.0';
'description' = '';
'main' = './server.ps1';
'scripts' = @{
'start' = './server.ps1';
'install' = 'yarn install --force --ignore-scripts --modules-folder pode_modules';
"build" = 'psake';
'test' = 'invoke-pester ./tests/*.ps1'
};
'author' = '';
'license' = 'MIT';
}
# check and load config if already exists
if (Test-Path $file) {
$data = (Get-Content $file | ConvertFrom-Json)
}
# quick check to see if the data is required
if ($Action -ine 'init') {
if ($null -eq $data) {
Write-Host 'package.json file not found' -ForegroundColor Red
return
}
else {
$actionScript = $data.scripts.$Action
if ([string]::IsNullOrWhiteSpace($actionScript) -and $Action -ieq 'start') {
$actionScript = $data.main
}
if ([string]::IsNullOrWhiteSpace($actionScript) -and $Action -ine 'install') {
Write-Host "package.json does not contain a script for the $($Action) action" -ForegroundColor Yellow
return
}
}
}
else {
if ($null -ne $data) {
Write-Host 'package.json already exists' -ForegroundColor Yellow
return
}
}
switch ($Action.ToLowerInvariant())
{
'init' {
$v = Read-Host -Prompt "name ($($map.name))"
if (![string]::IsNullOrWhiteSpace($v)) { $map.name = $v }
$v = Read-Host -Prompt "version ($($map.version))"
if (![string]::IsNullOrWhiteSpace($v)) { $map.version = $v }
$map.description = Read-Host -Prompt "description"
$v = Read-Host -Prompt "entry point ($($map.main))"
if (![string]::IsNullOrWhiteSpace($v)) { $map.main = $v; $map.scripts.start = $v }
$map.author = Read-Host -Prompt "author"
$v = Read-Host -Prompt "license ($($map.license))"
if (![string]::IsNullOrWhiteSpace($v)) { $map.license = $v }
$map | ConvertTo-Json -Depth 10 | Out-File -FilePath $file -Encoding utf8 -Force
Write-Host 'Success, saved package.json' -ForegroundColor Green
}
'test' {
Invoke-PodePackageScript -ActionScript $actionScript
}
'start' {
Invoke-PodePackageScript -ActionScript $actionScript
}
'install' {
if ($Dev) {
Install-PodeLocalModules -Modules $data.devModules
}
Install-PodeLocalModules -Modules $data.modules
Invoke-PodePackageScript -ActionScript $actionScript
}
'build' {
Invoke-PodePackageScript -ActionScript $actionScript
}
}
}
<#
.SYNOPSIS
Opens a Web Server up as a Desktop Application.
.DESCRIPTION
Opens a Web Server up as a Desktop Application.
.PARAMETER Title
The title of the Application's window.
.PARAMETER Icon
A path to an icon image for the Application.
.PARAMETER WindowState
The state the Application's window starts, such as Minimized.
.PARAMETER WindowStyle
The border style of the Application's window.
.PARAMETER ResizeMode
Specifies if the Application's window is resizable.
.PARAMETER Height
The height of the window.
.PARAMETER Width
The width of the window.
.PARAMETER EndpointName
The specific endpoint name to use, if you are listening on multiple endpoints.
.PARAMETER HideFromTaskbar
Stops the Application from appearing on the taskbar.
.EXAMPLE
Show-PodeGui -Title 'MyApplication' -WindowState 'Maximized'
#>
function Show-PodeGui
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
$Title,
[Parameter()]
[string]
$Icon,
[Parameter()]
[ValidateSet('Normal', 'Maximized', 'Minimized')]
[string]
$WindowState = 'Normal',
[Parameter()]
[ValidateSet('None', 'SingleBorderWindow', 'ThreeDBorderWindow', 'ToolWindow')]
[string]
$WindowStyle = 'SingleBorderWindow',
[Parameter()]
[ValidateSet('CanResize', 'CanMinimize', 'NoResize')]
[string]
$ResizeMode = 'CanResize',
[Parameter()]
[int]
$Height = 0,
[Parameter()]
[int]
$Width = 0,
[Parameter()]
[string]
$EndpointName,
[switch]
$HideFromTaskbar
)
# error if serverless
Test-PodeIsServerless -FunctionName 'Show-PodeGui' -ThrowError
# only valid for Windows PowerShell
if ((Test-IsPSCore) -and ($PSVersionTable.PSVersion.Major -eq 6)) {
throw 'Show-PodeGui is currently only available for Windows PowerShell, and PowerShell 7 on Windows'
}
# enable the gui and set general settings
$PodeContext.Server.Gui.Enabled = $true
$PodeContext.Server.Gui.Title = $Title
$PodeContext.Server.Gui.ShowInTaskbar = !$HideFromTaskbar
$PodeContext.Server.Gui.WindowState = $WindowState
$PodeContext.Server.Gui.WindowStyle = $WindowStyle
$PodeContext.Server.Gui.ResizeMode = $ResizeMode
# set the window's icon path
if (![string]::IsNullOrWhiteSpace($Icon)) {
$PodeContext.Server.Gui.Icon = (Resolve-Path $Icon).Path
if (!(Test-Path $PodeContext.Server.Gui.Icon)) {
throw "Path to icon for GUI does not exist: $($PodeContext.Server.Gui.Icon)"
}
}
# set the height of the window
$PodeContext.Server.Gui.Height = $Height
if ($PodeContext.Server.Gui.Height -le 0) {
$PodeContext.Server.Gui.Height = 'auto'
}
# set the width of the window
$PodeContext.Server.Gui.Width = $Width
if ($PodeContext.Server.Gui.Width -le 0) {
$PodeContext.Server.Gui.Width = 'auto'
}
# set the gui to use a specific listener
$PodeContext.Server.Gui.EndpointName = $EndpointName
if (![string]::IsNullOrWhiteSpace($PodeContext.Server.Gui.EndpointName)) {
$found = ($PodeContext.Server.Endpoints | Where-Object {
$_.Name -eq $PodeContext.Server.Gui.EndpointName
} | Select-Object -First 1)
if ($null -eq $found) {
throw "Endpoint with name '$($EndpointName)' does not exist"
}
$PodeContext.Server.Gui.Endpoint = $found
}
}
<#
.SYNOPSIS
Bind an endpoint to listen for incoming Requests.
.DESCRIPTION
Bind an endpoint to listen for incoming Requests. The endpoints can be HTTP, HTTPS, TCP or SMTP, with the option to bind certificates.
.PARAMETER Address
The IP/Hostname of the endpoint.
.PARAMETER Port
The Port number of the endpoint.
.PARAMETER Protocol
The protocol of the supplied endpoint.
.PARAMETER Certificate
A certificate name to find and bind onto HTTPS endpoints (Windows only).
.PARAMETER CertificateThumbprint
A certificate thumbprint to bind onto HTTPS endpoints (Windows only).
.PARAMETER CertificateFile
The path to a certificate that can be use to enable HTTPS (Cross-platform)
.PARAMETER CertificatePassword
The password for the certificate referenced in CertificateFile (Cross-platform)
.PARAMETER RawCertificate
The raw X509 certificate that can be use to enable HTTPS (Cross-platform)
.PARAMETER Name
An optional name for the endpoint, that can be used with other functions.
.PARAMETER RedirectTo
The Name of another Endpoint to automatically generate a redirect route for all traffic.
.PARAMETER Force
Ignore Adminstrator checks for non-localhost endpoints.
.PARAMETER SelfSigned
Create and bind a self-signed certifcate onto HTTPS endpoints (Windows only).
.EXAMPLE
Add-PodeEndpoint -Address localhost -Port 8090 -Protocol Http
.EXAMPLE
Add-PodeEndpoint -Address localhost -Protocol Smtp
.EXAMPLE
Add-PodeEndpoint -Address dev.pode.com -Port 8443 -Protocol Https -SelfSigned
.EXAMPLE
Add-PodeEndpoint -Address live.pode.com -Protocol Https -CertificateThumbprint '2A9467F7D3940243D6C07DE61E7FCCE292'
#>
function Add-PodeEndpoint
{
[CmdletBinding()]
param (
[Parameter()]
[string]
$Address = 'localhost',
[Parameter()]
[int]
$Port = 0,
[Parameter()]
[ValidateSet('Http', 'Https', 'Smtp', 'Tcp', 'Ws', 'Wss')]
[string]
$Protocol,
[Parameter(Mandatory=$true, ParameterSetName='CertName')]
[string]
$Certificate = $null,
[Parameter(Mandatory=$true, ParameterSetName='CertThumb')]
[string]
$CertificateThumbprint = $null,
[Parameter(Mandatory=$true, ParameterSetName='CertFile')]
[string]
$CertificateFile = $null,
[Parameter(ParameterSetName='CertFile')]
[string]
$CertificatePassword = $null,
[Parameter(Mandatory=$true, ParameterSetName='CertRaw')]
[Parameter()]
[X509Certificate]
$RawCertificate = $null,
[Parameter()]
[string]
$Name = $null,
[Parameter()]
[string]
$RedirectTo = $null,
[switch]
$Force,
[Parameter(ParameterSetName='CertSelf')]
[switch]
$SelfSigned
)
# error if serverless
Test-PodeIsServerless -FunctionName 'Add-PodeEndpoint' -ThrowError
# parse the endpoint for host/port info
$FullAddress = "$($Address):$($Port)"
$_endpoint = Get-PodeEndpointInfo -Endpoint $FullAddress
# if a name was supplied, check it is unique
if (!(Test-IsEmpty $Name) -and
(Get-PodeCount ($PodeContext.Server.Endpoints | Where-Object { $_.Name -eq $Name })) -ne 0)
{
throw "An endpoint with the name '$($Name)' has already been defined"
}
# new endpoint object
$obj = @{
Name = $Name
Address = $null
RawAddress = $FullAddress
Port = $null
IsIPAddress = $true
HostName = 'localhost'
Ssl = (@('https', 'wss') -icontains $Protocol)
Protocol = $Protocol
Certificate = @{
Name = $Certificate
Thumbprint = $CertificateThumbprint
Raw = $RawCertificate
SelfSigned = $SelfSigned
}
}
# set the ip for the context
$obj.Address = (Get-PodeIPAddress $_endpoint.Host)
if (!(Test-PodeIPAddressLocalOrAny -IP $obj.Address)) {
$obj.HostName = "$($obj.Address)"
}
$obj.IsIPAddress = (Test-PodeIPAddress -IP $obj.Address -IPOnly)
# set the port for the context
$obj.Port = $_endpoint.Port
# if the address is non-local, then check admin privileges
if (!$Force -and !(Test-PodeIPAddressLocal -IP $obj.Address) -and !(Test-IsAdminUser)) {
throw 'Must be running with administrator priviledges to listen on non-localhost addresses'
}
# has this endpoint been added before? (for http/https we can just not add it again)
$exists = ($PodeContext.Server.Endpoints | Where-Object {
($_.Address -eq $obj.Address) -and ($_.Port -eq $obj.Port) -and ($_.Ssl -eq $obj.Ssl)
} | Measure-Object).Count
# if we're dealing with a certificate file, attempt to import it
if ($PSCmdlet.ParameterSetName -ieq 'certfile') {
# fail if protocol is not https
if (@('https', 'wss') -inotcontains $Protocol) {
throw "Certificate supplied for non-HTTPS/WSS endpoint"
}
$_path = Get-PodeRelativePath -Path $CertificateFile -JoinRoot -Resolve
if ([string]::IsNullOrWhiteSpace($CertificatePassword)) {
$obj.Certificate.Raw = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($_path)
}
else {
$obj.Certificate.Raw = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($_path, $CertificatePassword)
}
# fail if the cert is expired
if ($obj.Certificate.Raw.NotAfter -lt [datetime]::Now) {
throw "The certificate '$($CertificateFile)' has expired: $($obj.Certificate.Raw.NotAfter)"
}
}
if (!$exists) {
# has an endpoint already been defined for smtp/tcp?
if ((@('smtp', 'tcp') -icontains $Protocol) -and ($Protocol -ieq $PodeContext.Server.Type)) {
throw "An endpoint for $($Protocol.ToUpperInvariant()) has already been defined"
}
# set server type, ensure we aren't trying to change the server's type
if (@('ws', 'wss') -icontains $Protocol) {
$PodeContext.Server.WebSockets.Enabled = $true
}
else {
$_type = (Resolve-PodeValue -Check ($Protocol -ieq 'https') -TrueValue 'http' -FalseValue $Protocol)
if (($_type -ieq 'http') -and ($PodeContext.Server.Type -ieq 'pode')) {
$_type = 'pode'
}
if ([string]::IsNullOrWhiteSpace($PodeContext.Server.Type)) {
$PodeContext.Server.Type = $_type
}
elseif ($PodeContext.Server.Type -ine $_type) {
throw "Cannot add $($Protocol.ToUpperInvariant()) endpoint when already listening to $($PodeContext.Server.Type.ToUpperInvariant()) endpoints"
}
}
# add the new endpoint
$PodeContext.Server.Endpoints += $obj
}
# if RedirectTo is set, attempt to build a redirecting route
if (![string]::IsNullOrWhiteSpace($RedirectTo)) {
$redir_endpoint = ($PodeContext.Server.Endpoints | Where-Object { $_.Name -eq $RedirectTo } | Select-Object -First 1)
# ensure the name exists
if (Test-IsEmpty $redir_endpoint) {
throw "An endpoint with the name '$($RedirectTo)' has not been defined for redirecting"
}
# build the redirect route
Add-PodeRoute -Method * -Path * -Endpoint $obj.RawAddress -Protocol $obj.Protocol -ArgumentList $redir_endpoint -ScriptBlock {
param($e, $endpoint)
$addr = Resolve-PodeValue -Check (Test-PodeIPAddressAny -IP $endpoint.Address) -TrueValue 'localhost' -FalseValue $endpoint.Address
Move-PodeResponseUrl -Address $addr -Port $endpoint.Port -Protocol $endpoint.Protocol
}
}
}
<#
.SYNOPSIS
Adds a new Timer with logic to periodically invoke.
.DESCRIPTION
Adds a new Timer with logic to periodically invoke, with options to only run a specific number of times.
.PARAMETER Name
The Name of the Timer.
.PARAMETER Interval
The number of seconds to periodically invoke the Timer's ScriptBlock.
.PARAMETER ScriptBlock
The script for the Timer.
.PARAMETER Limit
The number of times the Timer should be invoked before being removed. (If 0, it will run indefinitely)
.PARAMETER Skip
The number of "invokes" to skip before the Timer actually runs.
.PARAMETER ArgumentList
An array of arguments to supply to the Timer's ScriptBlock.
.PARAMETER FilePath
A literal, or relative, path to a file containing a ScriptBlock for the Timer's logic.
.PARAMETER OnStart
If supplied, the timer will trigger when the server starts.
.EXAMPLE
Add-PodeTimer -Name 'Hello' -Interval 10 -ScriptBlock { 'Hello, world!' | Out-Default }
.EXAMPLE
Add-PodeTimer -Name 'RunOnce' -Interval 1 -Limit 1 -ScriptBlock { /* logic */ }
.EXAMPLE
Add-PodeTimer -Name 'RunAfter60secs' -Interval 10 -Skip 6 -ScriptBlock { /* logic */ }
.EXAMPLE
Add-PodeTimer -Name 'Args' -Interval 2 -ScriptBlock { /* logic */ } -ArgumentList 'arg1', 'arg2'
#>
function Add-PodeTimer
{
[CmdletBinding(DefaultParameterSetName='Script')]
param (
[Parameter(Mandatory=$true)]
[string]
$Name,
[Parameter(Mandatory=$true)]
[int]
$Interval,
[Parameter(Mandatory=$true, ParameterSetName='Script')]
[scriptblock]
$ScriptBlock,
[Parameter()]
[int]
$Limit = 0,
[Parameter()]
[int]
$Skip = 0,
[Parameter(Mandatory=$true, ParameterSetName='File')]
[string]
$FilePath,
[Parameter()]
[object[]]
$ArgumentList,
[switch]
$OnStart
)
# error if serverless
Test-PodeIsServerless -FunctionName 'Add-PodeTimer' -ThrowError
# ensure the timer doesn't already exist
if ($PodeContext.Timers.ContainsKey($Name)) {
throw "[Timer] $($Name): Timer already defined"
}
# is the interval valid?
if ($Interval -le 0) {
throw "[Timer] $($Name): Interval must be greater than 0"
}
# is the limit valid?
if ($Limit -lt 0) {
throw "[Timer] $($Name): Cannot have a negative limit"
}
# is the skip valid?
if ($Skip -lt 0) {
throw "[Timer] $($Name): Cannot have a negative skip value"
}
# if we have a file path supplied, load that path as a scriptblock
if ($PSCmdlet.ParameterSetName -ieq 'file') {
$ScriptBlock = Convert-PodeFileToScriptBlock -FilePath $FilePath
}
# calculate the next tick time (based on Skip)
$NextTick = [DateTime]::Now.AddSeconds($Interval)
if ($Skip -gt 1) {
$NextTick = $NextTick.AddSeconds($Interval * $Skip)
}
# add the timer
$PodeContext.Timers[$Name] = @{
Name = $Name
Interval = $Interval
Limit = $Limit
Count = 0
Skip = $Skip
Countable = ($Limit -gt 0)
NextTick = $NextTick
Script = $ScriptBlock
Arguments = $ArgumentList
OnStart = $OnStart
Completed = $false
}
}
<#
.SYNOPSIS
Adhoc invoke a Timer's logic.
.DESCRIPTION
Adhoc invoke a Timer's logic outside of its defined interval. This invocation doesn't count towards the Timer's limit.
.PARAMETER Name
The Name of the Timer.
.EXAMPLE
Invoke-PodeTimer -Name 'timer-name'
#>
function Invoke-PodeTimer
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
$Name
)
# ensure the timer exists
if (!$PodeContext.Timers.ContainsKey($Name)) {
throw "Timer '$($Name)' does not exist"
}
# run timer logic
Invoke-PodeInternalTimer -Timer ($PodeContext.Timers[$Name])
}
<#
.SYNOPSIS
Removes a specific Timer.
.DESCRIPTION
Removes a specific Timer.
.PARAMETER Name
The Name of Timer to be removed.
.EXAMPLE
Remove-PodeTimer -Name 'SaveState'
#>
function Remove-PodeTimer
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
$Name
)
$PodeContext.Timers.Remove($Name) | Out-Null
}
<#
.SYNOPSIS
Removes all Timers.
.DESCRIPTION
Removes all Timers.
.EXAMPLE
Clear-PodeTimers
#>
function Clear-PodeTimers
{
[CmdletBinding()]
param()
$PodeContext.Timers.Clear()
}
<#
.SYNOPSIS
Edits an existing Timer.
.DESCRIPTION
Edits an existing Timer's properties, such as interval or scriptblock.
.PARAMETER Name
The Name of the Timer.
.PARAMETER Interval
The new Interval for the Timer in seconds.
.PARAMETER ScriptBlock
The new ScriptBlock for the Timer.
.PARAMETER ArgumentList
Any new Arguments for the Timer.
.EXAMPLE
Edit-PodeTimer -Name 'Hello' -Interval 10
#>
function Edit-PodeTimer
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]
$Name,
[Parameter()]
[int]
$Interval = 0,
[Parameter()]
[scriptblock]
$ScriptBlock,
[Parameter()]
[object[]]
$ArgumentList
)
# ensure the timer exists
if (!$PodeContext.Timers.ContainsKey($Name)) {
throw "Timer '$($Name)' does not exist"
}
# edit interval if supplied
if ($Interval -gt 0) {
$PodeContext.Timers[$Name].Interval = $Interval
}
# edit scriptblock if supplied
if (!(Test-IsEmpty $ScriptBlock)) {
$PodeContext.Timers[$Name].Script = $ScriptBlock
}
# edit arguments if supplied
if (!(Test-IsEmpty $ArgumentList)) {
$PodeContext.Timers[$Name].Arguments = $ArgumentList
}
}
<#
.SYNOPSIS
Adds a new Schedule with logic to periodically invoke, defined using Cron Expressions.
.DESCRIPTION
Adds a new Schedule with logic to periodically invoke, defined using Cron Expressions.
.PARAMETER Name
The Name of the Schedule.
.PARAMETER Cron
One, or an Array, of Cron Expressions to define when the Schedule should trigger.
.PARAMETER ScriptBlock
The script defining the Schedule's logic.
.PARAMETER Limit
The number of times the Schedule should trigger before being removed.
.PARAMETER StartTime
A DateTime for when the Schedule should start triggering.
.PARAMETER EndTime
A DateTime for when the Schedule should stop triggering, and be removed.
.PARAMETER ArgumentList
A hashtable of arguments to supply to the Schedule's ScriptBlock.
.PARAMETER FilePath
A literal, or relative, path to a file containing a ScriptBlock for the Schedule's logic.
.PARAMETER OnStart
If supplied, the schedule will trigger when the server starts, regardless if the cron-expression matches the current time.
.EXAMPLE
Add-PodeSchedule -Name 'RunEveryMinute' -Cron '@minutely' -ScriptBlock { /* logic */ }
.EXAMPLE
Add-PodeSchedule -Name 'RunEveryTuesday' -Cron '0 0 * * TUE' -ScriptBlock { /* logic */ }
.EXAMPLE
Add-PodeSchedule -Name 'StartAfter2days' -Cron '@hourly' -StartTime [DateTime]::Now.AddDays(2) -ScriptBlock { /* logic */ }
.EXAMPLE
Add-PodeSchedule -Name 'Args' -Cron '@minutely' -ScriptBlock { /* logic */ } -ArgumentList @{ Arg1 = 'value' }
#>
function Add-PodeSchedule
{
[CmdletBinding(DefaultParameterSetName='Script')]
param (
[Parameter(Mandatory=$true)]
[string]
$Name,
[Parameter(Mandatory=$true)]
[string[]]
$Cron,
[Parameter(Mandatory=$true, ParameterSetName='Script')]