-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi_controller.cr
More file actions
662 lines (582 loc) · 23.9 KB
/
Copy pathapi_controller.cr
File metadata and controls
662 lines (582 loc) · 23.9 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
require "kemal"
require "json"
require "../services/tokei_service"
require "../services/analysis_service"
require "../services/language_stats_service"
require "../services/badge_service"
require "../services/log_service"
require "../models/analysis"
module Tokei::Api::Controllers
# Controller for API
module ApiController
GITHUB_PATH_SAFE = /^[A-Za-z0-9._-]+$/
private def self.valid_github_param?(value : String) : Bool
value.matches?(GITHUB_PATH_SAFE)
end
private def self.invalid_owner_repo_response(env : HTTP::Server::Context) : String
env.response.status_code = 400
env.response.content_type = "application/json"
{error: {code: "invalid_request", message: "Invalid owner or repo", status: 400}}.to_json
end
private def self.status_for_exception(ex : Exception) : Int32
case ex
when Tokei::Api::Services::TokeiService::CloneTimeoutError,
Tokei::Api::Services::TokeiService::AnalysisTimeoutError
504
when Tokei::Api::Services::TokeiService::CloneFailedError,
Tokei::Api::Services::TokeiService::AnalysisFailedError
502
else
500
end
end
private def self.log_route_error(event : String, ex : Exception, fields = {} of String => String) : Nil
Tokei::Api::Services::LogService.error_exception(event, ex, fields)
end
private def self.mask_repo_url(repo_url : String) : String
Tokei::Api::Services::LogService.mask_url(repo_url)
end
private def self.request_id : String
Tokei::Api::Services::LogService.request_id
end
private def self.request_id(env : HTTP::Server::Context) : String
Tokei::Api::Services::LogService.request_id(env)
end
# Badge data generation (via shared service)
private def self.generate_badge_data(badge_type : String, analysis)
Tokei::Api::Services::BadgeService.generate(badge_type, analysis)
end
# Get the most recent analysis for a repository URL
private def self.get_analysis_for_repo(repo_url : String, req_id : String = request_id)
Tokei::Api::Services::AnalysisService.get_for_repo(repo_url, req_id)
end
# Get analysis with full result payload when language breakdown is needed.
private def self.get_full_analysis_for_repo(repo_url : String, req_id : String = request_id)
analysis = get_analysis_for_repo(repo_url, req_id)
# Summary-only records carry an empty result payload; reload full row by id.
unless analysis.result.as_h.empty?
return analysis
end
id = analysis.id
if id && (full_analysis = Tokei::Api::Models::Analysis.find(id.to_s))
return full_analysis
end
# Fallback: perform analysis again via the shared lock if the row disappeared between queries.
get_analysis_for_repo(repo_url, req_id)
end
# Setup API endpoints
# ameba:disable Metrics/CyclomaticComplexity
def self.setup
# GET /api/badge/:type endpoint (for dynamic shields.io badges)
get "/api/badge/:type" do |env|
req_id = request_id(env)
begin
# Get badge type and repository URL
badge_type = env.params.url["type"]
# NOTE: query param may be missing
repo_url = env.params.query["url"]? || ""
env.response.content_type = "application/json"
# URL validation
unless Tokei::Api::Services::TokeiService.valid_repo_url?(repo_url)
env.response.status_code = 400
next {
schemaVersion: 1,
label: "error",
message: "Invalid repository URL",
color: "red",
}.to_json
end
# Search for existing analysis results (badge endpoint does not trigger analysis)
analysis = Tokei::Api::Models::Analysis.find_latest_by_repo_url(repo_url)
# Check if we have any analysis result
if analysis.nil?
env.response.status_code = 404
next {
schemaVersion: 1,
label: "error",
message: "No analysis found",
color: "red",
}.to_json
end
# Allow intermediaries to cache badge payload briefly
env.response.headers["Cache-Control"] = "public, max-age=300"
# Generate badge data
begin
badge_data = generate_badge_data(badge_type, analysis)
badge_data.to_json
rescue
env.response.status_code = 400
{
schemaVersion: 1,
label: "error",
message: "Invalid badge type",
color: "red",
}.to_json
end
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.badge.failed", ex, {
"req_id" => req_id,
"route" => "/api/badge/:type",
"badge_type" => badge_type,
"repo_url" => mask_repo_url(repo_url.to_s),
"status" => env.response.status_code.to_s,
})
{
schemaVersion: 1,
label: "error",
message: "Server error",
color: "red",
}.to_json
end
end
# Core API endpoints
# POST /api/analyses endpoint (analyze a repository)
post "/api/analyses" do |env|
req_id = request_id(env)
begin
# Get repository URL from request body
request_body = env.request.body.try(&.gets_to_end) || ""
if request_body.empty?
raise KeyError.new("Missing required field: url")
end
request_json = JSON.parse(request_body)
repo_url = request_json["url"]?.try(&.as_s) || ""
if repo_url.empty?
raise KeyError.new("Missing required field: url")
end
unless Tokei::Api::Services::TokeiService.valid_repo_url?(repo_url)
env.response.status_code = 400
next {error: {code: "invalid_request", message: "Invalid repository URL", status: 400}}.to_json
end
# Get analysis
analysis = get_analysis_for_repo(repo_url, req_id)
# Prepare response data
response_data = {
data: {
id: analysis.id.to_s,
url: analysis.repo_url,
analyzed_at: analysis.analyzed_at,
status: "completed",
summary: {
total_lines: analysis.total_lines,
total_code: analysis.total_code,
total_comments: analysis.total_comments,
total_blanks: analysis.total_blanks,
languages_count: analysis.language_count,
top_language: analysis.top_language,
code_comment_ratio: analysis.code_comment_ratio,
},
links: {
self: "/api/analyses/#{analysis.id}",
languages: "/api/analyses/#{analysis.id}/languages",
web: "/analyses/#{analysis.id}",
},
},
}
# Return results
env.response.status_code = 201 # Created
env.response.content_type = "application/json"
response_data.to_json
rescue JSON::ParseException
env.response.status_code = 400
{error: {code: "invalid_request", message: "Invalid JSON format", status: 400}}.to_json
rescue KeyError
env.response.status_code = 400
{error: {code: "invalid_request", message: "Missing required field: url", status: 400}}.to_json
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.analysis.create.failed", ex, {
"req_id" => req_id,
"route" => "POST /api/analyses",
"repo_url" => mask_repo_url(repo_url.to_s),
"status" => env.response.status_code.to_s,
})
{error: {code: "server_error", message: "Internal server error", status: env.response.status_code}}.to_json
end
end
# GET /api/analyses endpoint (retrieve analysis result by repository URL)
get "/api/analyses" do |env|
req_id = request_id(env)
begin
# Get repository URL from query parameter
repo_url = env.params.query["url"]?
# Return error if URL is not provided
if repo_url.nil? || repo_url.empty?
env.response.status_code = 400
next {error: {code: "invalid_request", message: "Missing required query parameter: url", status: 400}}.to_json
end
# Validate repository URL
unless Tokei::Api::Services::TokeiService.valid_repo_url?(repo_url)
env.response.status_code = 400
next {error: {code: "invalid_request", message: "Invalid repository URL", status: 400}}.to_json
end
# Find latest analysis result for the repository
analysis = Tokei::Api::Models::Analysis.find_latest_by_repo_url(repo_url)
# Return 404 if no analysis is found
if analysis.nil?
env.response.status_code = 404
next {error: {code: "not_found", message: "No analysis found for the given URL", status: 404}}.to_json
end
# Prepare response data
response_data = {
data: {
id: analysis.id.to_s,
url: analysis.repo_url,
analyzed_at: analysis.analyzed_at,
status: "completed",
summary: {
total_lines: analysis.total_lines,
total_code: analysis.total_code,
total_comments: analysis.total_comments,
total_blanks: analysis.total_blanks,
languages_count: analysis.language_count,
top_language: analysis.top_language,
code_comment_ratio: analysis.code_comment_ratio,
},
links: {
self: "/api/analyses/#{analysis.id}",
languages: "/api/analyses/#{analysis.id}/languages",
web: "/analyses/#{analysis.id}",
},
},
}
env.response.content_type = "application/json"
response_data.to_json
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.analysis.lookup.failed", ex, {
"req_id" => req_id,
"route" => "GET /api/analyses",
"repo_url" => mask_repo_url(repo_url.to_s),
"status" => env.response.status_code.to_s,
})
{error: {code: "server_error", message: "Internal server error", status: env.response.status_code}}.to_json
end
end
# GET /api/analyses/:id endpoint (retrieve specific analysis results)
get "/api/analyses/:id" do |env|
req_id = request_id(env)
begin
id = env.params.url["id"]
analysis = Tokei::Api::Models::Analysis.find(id)
if analysis.nil?
env.response.status_code = 404
next {error: {code: "not_found", message: "Analysis not found", status: 404}}.to_json
end
languages_data = Tokei::Api::Services::LanguageStatsService.extract_basic(analysis.result)
# Prepare response data
response_data = {
data: {
id: analysis.id.to_s,
url: analysis.repo_url,
analyzed_at: analysis.analyzed_at,
status: "completed",
summary: {
total_lines: analysis.total_lines,
total_code: analysis.total_code,
total_comments: analysis.total_comments,
total_blanks: analysis.total_blanks,
languages_count: analysis.language_count,
top_language: analysis.top_language,
code_comment_ratio: analysis.code_comment_ratio,
},
languages: languages_data,
links: {
self: "/api/analyses/#{analysis.id}",
languages: "/api/analyses/#{analysis.id}/languages",
web: "/analyses/#{analysis.id}",
},
},
}
env.response.content_type = "application/json"
response_data.to_json
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.analysis.show.failed", ex, {
"req_id" => req_id,
"route" => "GET /api/analyses/:id",
"id" => id,
"status" => env.response.status_code.to_s,
})
{error: {code: "server_error", message: "Internal server error", status: env.response.status_code}}.to_json
end
end
# GET /api/analyses/:id/languages endpoint (retrieve language statistics)
get "/api/analyses/:id/languages" do |env|
req_id = request_id(env)
begin
id = env.params.url["id"]
analysis = Tokei::Api::Models::Analysis.find(id)
if analysis.nil?
env.response.status_code = 404
next {error: {code: "not_found", message: "Analysis not found", status: 404}}.to_json
end
languages_data = Tokei::Api::Services::LanguageStatsService.extract_with_percentage(analysis.result)
# Prepare response data
response_data = {
data: {
repository_id: analysis.id.to_s,
languages: languages_data,
},
}
env.response.content_type = "application/json"
response_data.to_json
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.analysis.languages.failed", ex, {
"req_id" => req_id,
"route" => "GET /api/analyses/:id/languages",
"id" => id,
"status" => env.response.status_code.to_s,
})
{error: {code: "server_error", message: "Internal server error", status: env.response.status_code}}.to_json
end
end
# GET /api/analyses/:id/badges/:type endpoint (retrieve badge data)
get "/api/analyses/:id/badges/:type" do |env|
req_id = request_id(env)
begin
id = env.params.url["id"]
badge_type = env.params.url["type"]
env.response.content_type = "application/json"
analysis = Tokei::Api::Models::Analysis.find_summary_by_id(id)
if analysis.nil?
env.response.status_code = 404
next {
schemaVersion: 1,
label: "error",
message: "Analysis not found",
color: "red",
}.to_json
end
env.response.headers["Cache-Control"] = "public, max-age=300"
# Generate badge data
begin
badge_data = generate_badge_data(badge_type, analysis)
badge_data.to_json
rescue
env.response.status_code = 400
{
schemaVersion: 1,
label: "error",
message: "Invalid badge type",
color: "red",
}.to_json
end
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.analysis.badge.failed", ex, {
"req_id" => req_id,
"route" => "/api/analyses/:id/badges/:type",
"id" => id,
"badge_type" => badge_type,
"status" => env.response.status_code.to_s,
})
{
schemaVersion: 1,
label: "error",
message: "Server error",
color: "red",
}.to_json
end
end
# GitHub-specific API endpoints
# GET /api/github/:owner/:repo endpoint (analyze GitHub repository)
get "/api/github/:owner/:repo" do |env|
req_id = request_id(env)
begin
owner = env.params.url["owner"]
repo = env.params.url["repo"]
unless valid_github_param?(owner) && valid_github_param?(repo)
next invalid_owner_repo_response(env)
end
# Construct GitHub repository URL
repo_url = "https://github.com/#{owner}/#{repo}"
# Get analysis
analysis = get_full_analysis_for_repo(repo_url, req_id)
languages_data = Tokei::Api::Services::LanguageStatsService.extract_basic(analysis.result)
# Prepare response data
response_data = {
data: {
id: analysis.id.to_s,
url: analysis.repo_url,
owner: owner,
repo: repo,
analyzed_at: analysis.analyzed_at,
status: "completed",
summary: {
total_lines: analysis.total_lines,
total_code: analysis.total_code,
total_comments: analysis.total_comments,
total_blanks: analysis.total_blanks,
languages_count: analysis.language_count,
top_language: analysis.top_language,
code_comment_ratio: analysis.code_comment_ratio,
},
languages: languages_data,
links: {
self: "/api/github/#{owner}/#{repo}",
languages: "/api/github/#{owner}/#{repo}/languages",
web: "/github/#{owner}/#{repo}",
badges: {
lines: "/api/github/#{owner}/#{repo}/badges/lines",
language: "/api/github/#{owner}/#{repo}/badges/language",
languages: "/api/github/#{owner}/#{repo}/badges/languages",
ratio: "/api/github/#{owner}/#{repo}/badges/ratio",
},
},
},
}
env.response.content_type = "application/json"
response_data.to_json
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.github.show.failed", ex, {
"req_id" => req_id,
"route" => "GET /api/github/:owner/:repo",
"owner" => owner,
"repo" => repo,
"repo_url" => mask_repo_url("https://github.com/#{owner}/#{repo}"),
"status" => env.response.status_code.to_s,
})
{error: {code: "server_error", message: "Internal server error", status: env.response.status_code}}.to_json
end
end
# GET /api/github/:owner/:repo/languages endpoint (retrieve language statistics)
get "/api/github/:owner/:repo/languages" do |env|
req_id = request_id(env)
begin
owner = env.params.url["owner"]
repo = env.params.url["repo"]
unless valid_github_param?(owner) && valid_github_param?(repo)
next invalid_owner_repo_response(env)
end
# Construct GitHub repository URL
repo_url = "https://github.com/#{owner}/#{repo}"
# Get analysis
analysis = get_full_analysis_for_repo(repo_url, req_id)
languages_data = Tokei::Api::Services::LanguageStatsService.extract_with_percentage(analysis.result)
# Prepare response data
response_data = {
data: {
owner: owner,
repo: repo,
repository_id: analysis.id.to_s,
languages: languages_data,
},
}
env.response.content_type = "application/json"
response_data.to_json
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.github.languages.failed", ex, {
"req_id" => req_id,
"route" => "GET /api/github/:owner/:repo/languages",
"owner" => owner,
"repo" => repo,
"repo_url" => mask_repo_url("https://github.com/#{owner}/#{repo}"),
"status" => env.response.status_code.to_s,
})
{error: {code: "server_error", message: "Internal server error", status: env.response.status_code}}.to_json
end
end
# GET /api/github/:owner/:repo/badges/:type endpoint (retrieve badge data)
get "/api/github/:owner/:repo/badges/:type" do |env|
req_id = request_id(env)
begin
owner = env.params.url["owner"]
repo = env.params.url["repo"]
badge_type = env.params.url["type"]
unless valid_github_param?(owner) && valid_github_param?(repo)
next invalid_owner_repo_response(env)
end
# Construct GitHub repository URL
repo_url = "https://github.com/#{owner}/#{repo}"
# Get analysis
analysis = get_analysis_for_repo(repo_url, req_id)
# Generate badge data
begin
env.response.content_type = "application/json"
badge_data = generate_badge_data(badge_type, analysis)
badge_data.to_json
rescue
env.response.status_code = 400
{
schemaVersion: 1,
label: "error",
message: "Invalid badge type",
color: "red",
}.to_json
end
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("api.github.badge.failed", ex, {
"req_id" => req_id,
"route" => "/api/github/:owner/:repo/badges/:type",
"owner" => owner,
"repo" => repo,
"repo_url" => mask_repo_url("https://github.com/#{owner}/#{repo}"),
"badge_type" => badge_type,
"status" => env.response.status_code.to_s,
})
{
schemaVersion: 1,
label: "error",
message: "Server error",
color: "red",
}.to_json
end
end
# Badge direct access endpoint
# GET /badge/github/:owner/:repo/:type endpoint (simplified badge URLs)
get "/badge/github/:owner/:repo/:type" do |env|
req_id = request_id(env)
begin
owner = env.params.url["owner"]
repo = env.params.url["repo"]
badge_type = env.params.url["type"]
unless valid_github_param?(owner) && valid_github_param?(repo)
next invalid_owner_repo_response(env)
end
# Construct GitHub repository URL
repo_url = "https://github.com/#{owner}/#{repo}"
# Get analysis
analysis = get_analysis_for_repo(repo_url, req_id)
# Generate badge data
begin
env.response.content_type = "application/json"
badge_data = generate_badge_data(badge_type, analysis)
badge_data.to_json
rescue
env.response.status_code = 400
{
schemaVersion: 1,
label: "error",
message: "Invalid badge type",
color: "red",
}.to_json
end
rescue ex
env.response.status_code = status_for_exception(ex)
log_route_error("badge.github.failed", ex, {
"req_id" => req_id,
"route" => "/badge/github/:owner/:repo/:type",
"owner" => owner,
"repo" => repo,
"repo_url" => mask_repo_url("https://github.com/#{owner}/#{repo}"),
"badge_type" => badge_type,
"status" => env.response.status_code.to_s,
})
{
schemaVersion: 1,
label: "error",
message: "Server error",
color: "red",
}.to_json
end
end
# ameba:enable Metrics/CyclomaticComplexity
end
end
end