-
Notifications
You must be signed in to change notification settings - Fork 25
/
BuildHistoryCharts.fs
406 lines (344 loc) · 15.1 KB
/
BuildHistoryCharts.fs
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
module BuildStats.BuildHistoryCharts
open System
open System.Net
open System.Net.Http
open System.Net.Http.Headers
open Microsoft.Extensions.Caching.Memory
open Microsoft.FSharp.Core.Option
open FSharp.Control.Tasks.V2.ContextInsensitive
open Newtonsoft.Json.Linq
open Giraffe
open BuildStats.Common
open BuildStats.HttpClients
// -------------------------------------------
// Common Types and Functions
// -------------------------------------------
type BuildStatus =
| Success
| Failed
| Cancelled
| Pending
| Unknown
type Build =
{
Id : int
BuildNumber : int
TimeTaken : TimeSpan
Status : BuildStatus
Branch : string
FromPullRequest : bool
}
let pullRequestFilter (inclFromPullRequest : bool)
(build : Build) =
inclFromPullRequest || not build.FromPullRequest
let calculateTimeTaken (started : Nullable<DateTime>)
(finished : Nullable<DateTime>) =
match started.HasValue with
| true ->
match finished.HasValue with
| true -> finished.Value - started.Value
| false -> TimeSpan.Zero
| false -> TimeSpan.Zero
// -------------------------------------------
// Build Metrics
// -------------------------------------------
module BuildMetrics =
let longestBuildTime (builds : Build list) =
match builds.Length with
| 0 -> TimeSpan.Zero
| _ ->
builds
|> List.maxBy (fun x -> x.TimeTaken.TotalMilliseconds)
|> fun x -> x.TimeTaken
let shortestBuildTime (builds : Build list) =
match builds.Length with
| 0 -> TimeSpan.Zero
| _ ->
builds
|> List.minBy (fun x -> x.TimeTaken.TotalMilliseconds)
|> fun x -> x.TimeTaken
let averageBuildTime (builds : Build list) =
match builds.Length with
| 0 -> TimeSpan.Zero
| _ ->
builds
|> List.averageBy (fun x -> x.TimeTaken.TotalMilliseconds)
|> TimeSpan.FromMilliseconds
// -------------------------------------------
// AppVeyor
// -------------------------------------------
type AppVeyorHttpClient (httpClient : FallbackHttpClient) =
let parseToJArray (json : string) =
let obj = Json.deserialize json :?> JObject
obj.Value<JArray> "builds"
let parseStatus (status : string) =
match status with
| "success" -> Success
| "failed" -> Failed
| "cancelled" -> Cancelled
| "queued" | "running" -> Pending
| _ -> Unknown
let isPullRequest (pullRequestId : string) =
isNotNull pullRequestId
let convertToBuilds (items : JArray option) =
match items with
| None -> []
| Some items ->
items
|> Seq.map (fun x ->
let started = x.Value<Nullable<DateTime>> "started"
let finished = x.Value<Nullable<DateTime>> "finished"
{
Id = x.Value<int> "buildId"
BuildNumber = x.Value<int> "buildNumber"
Status = x.Value<string> "status" |> parseStatus
Branch = x.Value<string> "branch"
FromPullRequest = x.Value<string> "pullRequestId" |> isPullRequest
TimeTaken = calculateTimeTaken started finished
})
|> Seq.toList
member __.GetBuildsAsync (authToken : string option)
(slug : string * string)
(buildCount : int)
(branch : string option)
(inclFromPullRequest : bool) =
task {
let account, project = slug
let branchFilter =
match branch with
| Some b -> sprintf "&branch=%s" b
| None -> ""
let url =
sprintf "https://ci.appveyor.com/api/projects/%s/%s/history?recordsNumber=%d%s"
account project (5 * buildCount) branchFilter
let request = new HttpRequestMessage(HttpMethod.Get, url)
if authToken.IsSome then
let token = AES.decryptUrlEncodedString Config.cryptoKey authToken.Value
request.Headers.Authorization <- AuthenticationHeaderValue("Bearer", token)
let! json = httpClient.SendAsync request
return json
|> (Str.toOption
>> map parseToJArray
>> convertToBuilds)
|> List.filter (pullRequestFilter inclFromPullRequest)
|> List.truncate buildCount
}
// -------------------------------------------
// TravisCI
// -------------------------------------------
type TravisCIHttpClient (httpClient : FallbackHttpClient, cache : IMemoryCache) =
let tryGetTLD account project =
let key = sprintf "%s%s" account project
match cache.TryGetValue<string> key with
| true, tld -> Some tld
| false, _ -> None
let cacheTLD account project tld =
let key = sprintf "%s%s" account project
cache.Set(key, tld) |> ignore
let parseToJArray (json : string) =
let obj = Json.deserialize json :?> JObject
obj.Value<JArray> "builds"
let parseStatus (status : string) =
match status with
| "failed" | "broken"
| "failing" | "errored" -> Failed
| "passed" | "fixed" -> Success
| "canceled" -> Cancelled
| "pending" -> Pending
| _ -> Unknown
let isPullRequest eventType = eventType = "pull_request"
let convertToBuilds (items : JArray option) =
match items with
| None -> []
| Some items ->
items
|> Seq.map (fun x ->
let started = x.Value<Nullable<DateTime>> "started_at"
let finished = x.Value<Nullable<DateTime>> "finished_at"
let state = x.Value<string> "state"
{
Id = x.Value<int> "id"
BuildNumber = x.Value<int> "number"
Branch = (x.Value<JObject> "branch").Value<string> "name"
FromPullRequest = x.Value<string> "event_type" |> isPullRequest
TimeTaken = calculateTimeTaken started finished
Status = parseStatus state
})
|> Seq.toList
let rec getBuildsAsync (isFallback : bool)
(authToken : string option)
(slug : string * string)
(buildCount : int)
(branch : string option)
(inclFromPullRequest : bool) =
task {
let account, project = slug
let request = new HttpRequestMessage()
request.Method <- HttpMethod.Get
request.Headers.Add("Travis-API-Version", "3")
request.Headers.TryAddWithoutValidation("User-Agent", "BuildStats.info-API") |> ignore
let topLevelDomain =
match isFallback, authToken with
| true, _ -> "org"
| false, None -> defaultArg (tryGetTLD account project) "com"
| false, Some t ->
let token = AES.decryptUrlEncodedString Config.cryptoKey t
request.Headers.Authorization <- AuthenticationHeaderValue("token", token)
"com"
let branchFilter =
match branch with
| Some b -> sprintf "&branch.name=%s" b
| None -> ""
let eventFilter =
match inclFromPullRequest with
| true -> ""
| false -> "&build.event_type[]=push&build.event_type[]=cron&build.event_type[]=api"
let url =
sprintf "https://api.travis-ci.%s/repo/%s/builds?limit=%d%s%s"
topLevelDomain
(WebUtility.UrlEncode (sprintf "%s/%s" account project))
buildCount
branchFilter
eventFilter
request.RequestUri <- new Uri(url)
let! json = httpClient.SendAsync request
let builds =
json
|> (Str.toOption
>> map parseToJArray
>> convertToBuilds)
if isFallback || not builds.IsEmpty then
cacheTLD account project topLevelDomain
return builds
else
return!
getBuildsAsync
true
authToken
slug
buildCount
branch
inclFromPullRequest
}
member __.GetBuildsAsync (authToken : string option)
(slug : string * string)
(buildCount : int)
(branch : string option)
(inclFromPullRequest : bool) =
getBuildsAsync false authToken slug buildCount branch inclFromPullRequest
// -------------------------------------------
// CircleCI
// -------------------------------------------
type CircleCIHttpClient (httpClient : FallbackHttpClient) =
let parseToJArray (json : string) =
Json.deserialize json :?> JArray
let parseStatus (status : string) =
match status with
| "success" | "fixed" | "no_tests" -> Success
| "failed" | "infrastructure_fail" | "timedout" -> Failed
| "canceled" | "not_run" | "retried" | "not_running" -> Cancelled
| "scheduled" | "queued" | "running" -> Pending
| _ -> Unknown
let isPullRequest (subject : string) =
isNotNull subject && subject.ToLowerInvariant().Contains("pull request")
let convertToBuilds (items : JArray option) =
match items with
| None -> []
| Some items ->
items
|> Seq.map (fun x ->
let started = x.Value<Nullable<DateTime>> "start_time"
let finished = x.Value<Nullable<DateTime>> "stop_time"
{
Id = x.Value<int> "build_num"
BuildNumber = x.Value<int> "build_num"
Status = x.Value<string> "status" |> parseStatus
Branch = x.Value<string> "branch"
FromPullRequest = x.Value<string> "subject" |> isPullRequest
TimeTaken = calculateTimeTaken started finished
})
|> Seq.toList
member __.GetBuildsAsync (authToken : string option)
(slug : string * string)
(buildCount : int)
(branch : string option)
(inclFromPullRequest : bool) =
task {
let account, project = slug
let branchFilter =
match branch with
| Some b -> sprintf "/tree/%s" <| WebUtility.UrlEncode b
| None -> ""
// CircleCI has a max limit of 100 items per request
// ToDo: Refactor to pull more items when buildCount is higher
let limit = min 100 (5 * buildCount)
let url =
sprintf "https://circleci.com/api/v1/project/%s/%s%s?limit=%i"
account project branchFilter limit
let request = new HttpRequestMessage(HttpMethod.Get, url)
let! json = httpClient.SendAsync request
return json
|> (Str.toOption
>> map parseToJArray
>> convertToBuilds)
|> List.filter (pullRequestFilter inclFromPullRequest)
|> List.truncate buildCount
}
// -------------------------------------------
// Azure Pipelines
// -------------------------------------------
type AzurePipelinesHttpClient (httpClient : FallbackHttpClient) =
let parseToJArray (json : string) =
let obj = Json.deserialize json :?> JObject
obj.Value<JArray> "value"
let parseStatus (status : string) =
match status with
| "succeeded" -> Success
| "failed" | "partiallySucceeded" -> Failed
| "canceled" -> Cancelled
| "none" -> Pending
| _ -> Unknown
let isPullRequest (reason : string) =
isNotNull reason && reason.Equals("pullRequest")
let convertToBuilds (items : JArray option) =
match items with
| None -> []
| Some items ->
items
|> Seq.map (fun x ->
let started = x.Value<Nullable<DateTime>> "startTime"
let finished = x.Value<Nullable<DateTime>> "finishTime"
{
Id = x.Value<int> "id"
BuildNumber = x.Value<int> "id"
Status = x.Value<string> "result" |> parseStatus
Branch = (x.Value<string> "sourceBranch").Replace("refs/heads/", "")
FromPullRequest = x.Value<string> "reason" |> isPullRequest
TimeTaken = calculateTimeTaken started finished
})
|> Seq.toList
member __.GetBuildsAsync (authToken : string option)
(slug : string * string * int)
(buildCount : int)
(branch : string option)
(inclFromPullRequest : bool) =
task {
let account, project, definitionId = slug
let branchFilter =
match branch with
| Some b -> sprintf "&branchName=refs/heads/%s" <| WebUtility.UrlEncode b
| None -> ""
let limit = min 200 (4 * buildCount)
let apiVersion = "4.1"
let url =
sprintf "https://dev.azure.com/%s/%s/_apis/build/builds?api-version=%s&definitions=%i&$top=%i%s"
account project apiVersion definitionId limit branchFilter
let request = new HttpRequestMessage(HttpMethod.Get, url)
let! json = httpClient.SendAsync request
return json
|> (Str.toOption
>> map parseToJArray
>> convertToBuilds)
|> List.filter (pullRequestFilter inclFromPullRequest)
|> List.truncate buildCount
}