forked from microsoft/PowerShellForGitHub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GitHubGraphQl.ps1
365 lines (289 loc) · 12.9 KB
/
GitHubGraphQl.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
function Invoke-GHGraphQl
{
<#
.SYNOPSIS
A wrapper around Invoke-WebRequest that understands the GitHub GraphQL API.
.DESCRIPTION
A very heavy wrapper around Invoke-WebRequest that understands the GitHub QraphQL API.
It also understands how to parse and handle errors from the GraphQL calls.
The Git repo for this module can be found here: http://aka.ms/PowerShellForGitHub
.PARAMETER Description
A friendly description of the operation being performed for logging.
.PARAMETER Body
This parameter forms the body of the request. It will be automatically
encoded to UTF8 and sent as Content Type: "application/json; charset=UTF-8"
.PARAMETER AccessToken
If provided, this will be used as the AccessToken for authentication with the
GraphQL Api as opposed to requesting a new one.
.PARAMETER TelemetryEventName
If provided, the successful execution of this GraphQL command will be logged to telemetry
using this event name.
.PARAMETER TelemetryProperties
If provided, the successful execution of this GraphQL command will be logged to telemetry
with these additional properties. This will be silently ignored if TelemetryEventName
is not provided as well.
.PARAMETER TelemetryExceptionBucket
If provided, any exception that occurs will be logged to telemetry using this bucket.
It's possible that users will wish to log exceptions but not success (by providing
TelemetryEventName) if this is being executed as part of a larger scenario. If this
isn't provided, but TelemetryEventName *is* provided, then TelemetryEventName will be
used as the exception bucket value in the event of an exception. If neither is specified,
no bucket value will be used.
.OUTPUTS
PSCustomObject
.EXAMPLE
Invoke-GHGraphQl
.NOTES
This wraps Invoke-WebRequest as opposed to Invoke-RestMethod because we want access
to the headers that are returned in the response, and Invoke-RestMethod drops those headers.
#>
[CmdletBinding()]
[OutputType([System.Management.Automation.ErrorRecord])]
param(
[string] $Description,
[Parameter(Mandatory)]
[string] $Body,
[string] $AccessToken,
[string] $TelemetryEventName = $null,
[hashtable] $TelemetryProperties = @{},
[string] $TelemetryExceptionBucket = $null
)
Invoke-UpdateCheck
# Telemetry-related
$stopwatch = New-Object -TypeName System.Diagnostics.Stopwatch
$localTelemetryProperties = @{}
$TelemetryProperties.Keys | ForEach-Object { $localTelemetryProperties[$_] = $TelemetryProperties[$_] }
$errorBucket = $TelemetryExceptionBucket
if ([String]::IsNullOrEmpty($errorBucket))
{
$errorBucket = $TelemetryEventName
}
$stopwatch.Start()
$hostName = $(Get-GitHubConfiguration -Name 'ApiHostName')
if ($hostName -eq 'github.com')
{
$url = "https://api.$hostName/graphql"
}
else
{
$url = "https://$hostName/api/v3/graphql"
}
$headers = @{
'User-Agent' = 'PowerShellForGitHub'
}
$AccessToken = Get-AccessToken -AccessToken $AccessToken
if (-not [String]::IsNullOrEmpty($AccessToken))
{
$headers['Authorization'] = "token $AccessToken"
}
$timeOut = Get-GitHubConfiguration -Name WebRequestTimeoutSec
$method = 'Post'
Write-Log -Message $Description -Level Debug
Write-Log -Message "Accessing [$method] $url [Timeout = $timeOut]" -Level Debug
if (Get-GitHubConfiguration -Name LogRequestBody)
{
Write-Log -Message $Body -Level Debug
}
$bodyAsBytes = [System.Text.Encoding]::UTF8.GetBytes($Body)
# Disable Progress Bar in function scope during Invoke-WebRequest
$ProgressPreference = 'SilentlyContinue'
# Save Current Security Protocol
$originalSecurityProtocol = [Net.ServicePointManager]::SecurityProtocol
# Enforce TLS v1.2 Security Protocol
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$invokeWebRequestParms = @{
Uri = $url
Method = $method
Headers = $headers
Body = $bodyAsBytes
UseDefaultCredentials = $true
UseBasicParsing = $true
TimeoutSec = $timeOut
Verbose = $false
}
try
{
$result = Invoke-WebRequest @invokeWebRequestParms
}
catch
{
$ex = $_.Exception
<#
PowerShell 5 Invoke-WebRequest returns a 'System.Net.WebException' object on error.
PowerShell 6+ Invoke-WebRequest returns a 'Microsoft.PowerShell.Commands.HttpResponseException' or
a 'System.Net.Http.HttpRequestException' object on error.
#>
if ($ex.PSTypeNames[0] -eq 'System.Net.Http.HttpRequestException')
{
Write-Debug -Message "Processing PowerShell Core 'System.Net.Http.HttpRequestException'"
$newErrorRecordParms = @{
ErrorMessage = $ex.Message
ErrorId = $_.FullyQualifiedErrorId
ErrorCategory = $_.CategoryInfo.Category
TargetObject = $_.TargetObject
}
$errorRecord = New-ErrorRecord @newErrorRecordParms
Write-Log -Exception $errorRecord -Level Error
Set-TelemetryException -Exception $ex -ErrorBucket $errorBucket -Properties $localTelemetryProperties
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
elseif ($ex.PSTypeNames[0] -eq 'Microsoft.PowerShell.Commands.HttpResponseException' -or
$ex.PSTypeNames[0] -eq 'System.Net.WebException')
{
Write-Debug -Message "Processing '$($ex.PSTypeNames[0])'"
$errorMessage = @()
$errorMessage += $ex.Message
$errorDetailsMessage = $_.ErrorDetails.Message
if (-not [string]::IsNullOrEmpty($errorDetailsMessage))
{
Write-Debug -Message "Processing Error Details message '$errorDetailsMessage'"
try
{
Write-Debug -Message 'Checking Error Details message for JSON content'
$errorDetailsMessageJson = $errorDetailsMessage | ConvertFrom-Json
}
catch [System.ArgumentException]
{
# Will be thrown if $errorDetailsMessage isn't JSON content
Write-Debug -Message 'No Error Details Message JSON content Found'
$errorDetailsMessageJson = $false
}
if ($errorDetailsMessageJson)
{
Write-Debug -Message 'Adding Error Details Message JSON content to output'
Write-Debug -Message "Error Details Message: $($errorDetailsMessageJson.message)"
Write-Debug -Message "Error Details Documentation URL: $($errorDetailsMessageJson.documentation_url)"
$errorMessage += ($errorDetailsMessageJson.message.Trim() +
' | ' + $errorDetailsMessageJson.documentation_url.Trim())
if ($errorDetailsMessageJson.details)
{
$errorMessage += $errorDetailsMessageJson.details | Format-Table | Out-String
}
}
else
{
# In this case, it's probably not a normal message from the API
Write-Debug -Message 'Adding Error Details Message String to output'
$errorMessage += $_.ErrorDetails.Message | Out-String
}
}
if (-not [System.String]::IsNullOrEmpty($ex.Response))
{
Write-Debug -Message "Processing '$($ex.Response.PSTypeNames[0])' Object"
<#
PowerShell 5.x returns a 'System.Net.HttpWebResponse' exception response object and
PowerShell 6+ returns a 'System.Net.Http.HttpResponseMessage' exception response object.
#>
$requestId = ''
if ($ex.Response.PSTypeNames[0] -eq 'System.Net.HttpWebResponse')
{
if (($ex.Response.Headers.Count -gt 0) -and
(-not [System.String]::IsNullOrEmpty($ex.Response.Headers['X-GitHub-Request-Id'])))
{
$requestId = $ex.Response.Headers['X-GitHub-Request-Id']
}
}
elseif ($ex.Response.PSTypeNames[0] -eq 'System.Net.Http.HttpResponseMessage')
{
$requestId = ($ex.Response.Headers | Where-Object -Property Key -eq 'X-GitHub-Request-Id').Value
}
if (-not [System.String]::IsNullOrEmpty($requestId))
{
Write-Debug -Message "GitHub RequestID '$requestId' in response header"
$localTelemetryProperties['RequestId'] = $requestId
$requestIdMessage += "RequestId: $requestId"
$errorMessage += $requestIdMessage
Write-Log -Message $requestIdMessage -Level Debug
}
}
$newErrorRecordParms = @{
ErrorMessage = $errorMessage -join [Environment]::NewLine
ErrorId = $_.FullyQualifiedErrorId
ErrorCategory = $_.CategoryInfo.Category
TargetObject = $Body
}
$errorRecord = New-ErrorRecord @newErrorRecordParms
Write-Log -Exception $errorRecord -Level Error
Set-TelemetryException -Exception $ex -ErrorBucket $errorBucket -Properties $localTelemetryProperties
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
else
{
Write-Debug -Message "Processing Other Exception '$($ex.PSTypeNames[0])'"
$newErrorRecordParms = @{
ErrorMessage = $ex.Message
ErrorId = $_.FullyQualifiedErrorId
ErrorCategory = $_.CategoryInfo.Category
TargetObject = $body
}
$errorRecord = New-ErrorRecord @newErrorRecordParms
Write-Log -Exception $errorRecord -Level Error
Set-TelemetryException -Exception $ex -ErrorBucket $errorBucket -Properties $localTelemetryProperties
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
}
finally
{
# Restore original security protocol
[Net.ServicePointManager]::SecurityProtocol = $originalSecurityProtocol
}
# Record the telemetry for this event.
$stopwatch.Stop()
if (-not [String]::IsNullOrEmpty($TelemetryEventName))
{
$telemetryMetrics = @{ 'Duration' = $stopwatch.Elapsed.TotalSeconds }
Set-TelemetryEvent -EventName $TelemetryEventName -Properties $localTelemetryProperties -Metrics $telemetryMetrics -Verbose:$false
}
Write-Debug -Message "GraphQl result: '$($result.Content)'"
$graphQlResult = $result.Content | ConvertFrom-Json
if ($graphQlResult.errors)
{
Write-Debug -Message "GraphQl Error: $($graphQLResult.errors | Out-String)"
if (-not [System.String]::IsNullOrEmpty($graphQlResult.errors[0].type))
{
$errorId = $graphQlResult.errors[0].type
switch ($errorId)
{
'NOT_FOUND'
{
Write-Debug -Message "GraphQl Error Type: $errorId"
$errorCategory = [System.Management.Automation.ErrorCategory]::ObjectNotFound
}
Default
{
Write-Debug -Message "GraphQL Unknown Error Type: $errorId"
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation
}
}
}
else
{
Write-Debug -Message "GraphQl Unspecified Error"
$errorId = 'UnspecifiedError'
$errorCategory = [System.Management.Automation.ErrorCategory]::NotSpecified
}
$errorMessage = @()
$errorMessage += "GraphQl Error: $($graphQlResult.errors[0].message)"
if ($result.Headers.Count -gt 0 -and
-not [System.String]::IsNullOrEmpty($result.Headers['X-GitHub-Request-Id']))
{
$requestId = $result.Headers['X-GitHub-Request-Id']
$requestIdMessage += "RequestId: $requestId"
$errorMessage += $requestIdMessage
Write-Log -Message $requestIdMessage -Level Debug
}
$newErrorRecordParms = @{
ErrorMessage = $errorMessage -join [Environment]::NewLine
ErrorId = $errorId
ErrorCategory = $errorCategory
TargetObject = $Body
}
$errorRecord = New-ErrorRecord @newErrorRecordParms
Write-Log -Exception $errrorRecord -Level Error
$PSCmdlet.ThrowTerminatingError($errorRecord)
}
else
{
return $graphQlResult
}
}