gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc9b48bfec9b48bfeVendor Hybriel plugins; deploy ships bin/ from zig-outKunibertc9b48bfe/lib/gitoria-api.hl

5.5 KB

  1. $mode = 'static'
  2. import { run } from 'hl:proc'
  3. import { readFile } from 'hl:fs'
  4. import { fetch } from 'hl:fetch'
  5. import { sleep, timestamp, now } from 'hl:time'
  6. import { require } from './review-output.hl'
  7. // ONE place for every [OPEN] name of the gitoria apps contract (apps-api.md v1) and the limits.
  8. tokenRoute = '/apps/token'
  9. pullRoute = (Number n) => { return '/pulls/' + n }
  10. threadsRoute = (Number n) => { return '/pulls/' + n + '/threads' }
  11. reviewsRoute = (Number n) => { return '/pulls/' + n + '/reviews' }
  12. repliesRoute = (Number n, String id) => { return '/pulls/' + n + '/threads/' + id + '/replies' }
  13. resolveRoute = (Number n, String id) => { return '/pulls/' + n + '/threads/' + id + '/resolve' }
  14. statusRoute = (String sha) => { return '/statuses/' + sha }
  15. statusContext = 'kunibert' // [OPEN] field name `context`
  16. pageLimit = 100
  17. maxRetryAfter = 60 // seconds a 429 may make us wait, per try
  18. maxRateTries = 3
  19. tokenMarginSeconds = 120 // fetch a new token this long before `expires`
  20. requestTimeoutMs = 30000
  21. // The client state of this process. The key and the token live ONLY here (and the key file); nothing writes them anywhere.
  22. client = { api = null, key = null, token = null, expires = null }
  23. // Key file: first line, must not be readable by group or others.
  24. connect = (String api, String keyFile) => {
  25. require(api.startsWith('http://') || api.startsWith('https://'), 'api base must be an http(s) URL')
  26. mode = run(['stat', '-c', '%a', keyFile], { timeout = 10 })
  27. require(mode.exit == 0, 'key file not readable')
  28. require(mode.lines.join('').trim().endsWith('00'), 'key file must have mode 600 (no group/other access)')
  29. key = readFile(keyFile).split('\n')[0].trim()
  30. require(key != '', 'key file is empty')
  31. client.api = api.endsWith('/') ? api.slice(0, api.length - 1) : api
  32. client.key = key
  33. client.token = null
  34. client.expires = null
  35. }
  36. // Never let a secret into a message, a log or a status summary.
  37. scrub = (String text) => {
  38. let t = text
  39. if (client.key != null && client.key != '') { t = t.replaceAll(client.key, '[key]') }
  40. if (client.token != null && client.token != '') { t = t.replaceAll(client.token, '[token]') }
  41. return t
  42. }
  43. // Structured result of one HTTP exchange: { status, ok, body (parsed or null), code, message, details, headers }.
  44. exchange = (String method, String route, String bearer, Hybrid payload) => {
  45. let options = { method = method, headers = { authorization = 'Bearer ' + bearer, accept = 'application/json' }, timeoutMs = requestTimeoutMs, maxRedirects = 0 }
  46. if (payload != null) { options.json = payload }
  47. r = fetch(client.api + route, options)
  48. let body = null
  49. text = r.text()
  50. if (text != '') { body = JSON.parse(text) }
  51. let out = { status = r.status, ok = r.ok, =body, code = null, message = null, details = null, headers = r.headers }
  52. if (!r.ok && body != null && body.error != null) { out.code = body.error.code out.message = body.error.message out.details = body.error.details }
  53. return out
  54. }
  55. // A valid token: cached in memory until `tokenMarginSeconds` before `expires` (ISO strings compare as text).
  56. getToken = (Boolean fresh = false) => {
  57. if (!fresh && client.token != null && client.expires > timestamp(now() + tokenMarginSeconds * 1000).slice(0, 19)) { return client.token }
  58. r = exchange('POST', tokenRoute, client.key, {})
  59. require(r.ok && r.body != null && hlTypeName(r.body.token) == 'String' && hlTypeName(r.body.expires) == 'String', 'token request failed: HTTP ' + r.status + ' ' + r.code)
  60. client.token = r.body.token
  61. client.expires = r.body.expires.slice(0, 19)
  62. return client.token
  63. }
  64. // One API call. 401 -> one new token and one retry; 429 -> wait Retry-After (capped), up to maxRateTries; anything else is returned
  65. // as the structured result (callers decide: 409 and 422 are normal answers). Use must() to turn a failure into an error.
  66. call = (String method, String route, Hybrid payload = null) => {
  67. let refreshed = false
  68. let tries = 0
  69. while (true) {
  70. r = exchange(method, route, getToken(), payload)
  71. if (r.status == 401 && !refreshed) {
  72. refreshed = true
  73. getToken(true)
  74. continue
  75. }
  76. if (r.status == 429 && tries < maxRateTries) {
  77. tries = tries + 1
  78. let wait = toNumber(r.headers['retry-after'])
  79. if (wait == null || wait < 0) { wait = 1 }
  80. sleep(wait > maxRetryAfter ? maxRetryAfter : wait)
  81. continue
  82. }
  83. return r
  84. }
  85. }
  86. must = (Hybrid r, String what) => {
  87. if (!r.ok) { hlError(scrub(what + ': HTTP ' + r.status + ' ' + r.code + ' ' + r.message)) }
  88. return r.body
  89. }
  90. // Every page of a list answer: key = 'threads' | 'comments' | 'pulls'.
  91. listAll = (String route, String key) => {
  92. let items = []
  93. let cursor = null
  94. let pages = 0
  95. while (true) {
  96. body = must(call('GET', route + '?limit=' + pageLimit + (cursor == null ? '' : '&cursor=' + encodeURIComponent(cursor))), 'GET ' + route)
  97. for (x of body[key]) { items.push(x) }
  98. cursor = body.next
  99. pages = pages + 1
  100. require(pages < 1000, 'too many pages')
  101. if (cursor == null) { break }
  102. }
  103. return items
  104. }
  105. getPull = (Number n) => { return must(call('GET', pullRoute(n)), 'GET ' + pullRoute(n)) }
  106. getThreads = (Number n) => { return listAll(threadsRoute(n), 'threads') }
  107. putStatus = (String sha, String state, String title, String summary) => {
  108. return call('PUT', statusRoute(sha), { context = statusContext, =state, =title, summary = scrub(summary), url = null })
  109. }

Branches

Latest commits

  • c9b48bfeVendor Hybriel plugins; deploy ships bin/ from zig-outKunibert
  • a41ba15fKunibert: event intake, git cache, review runner, posting, linked tickets, deploy filesKunibert