gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainbd3591c7conductor: gates run on the live day44 binarymremain/lib/gitoria-api.hl

5.9 KB

  1. $mode = 'static'
  2. import { run } from 'hl:proc'
  3. import { readFile } from 'hl:fs'
  4. import { tryFetch } 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 = tryFetch(client.api + route, options)
  48. if (r.status == 0) { return { status = 0, ok = false, body = null, code = 'network_error', message = 'request failed', details = null, headers = {} } }
  49. body = JSON.tryParse(r.text())
  50. let out = { status = r.status, ok = r.ok, =body, code = null, message = null, details = null, headers = r.headers }
  51. if (!r.ok && body == null) { out.code = 'not_json' }
  52. if (!r.ok && body != null && body.error != null) {
  53. \\ contract: { error: { code, message, details } }; a route gitoria has not built yet answers { error: "<text>" }
  54. if (hlTypeName(body.error) == 'String') { out.code = 'not_found' out.message = body.error }
  55. if (hlTypeName(body.error) != 'String') { out.code = body.error.code out.message = body.error.message out.details = body.error.details }
  56. }
  57. return out
  58. }
  59. // A valid token: cached in memory until `tokenMarginSeconds` before `expires` (ISO strings compare as text).
  60. getToken = (Boolean fresh = false) => {
  61. if (!fresh && client.token != null && client.expires > timestamp(now() + tokenMarginSeconds * 1000).slice(0, 19)) { return client.token }
  62. r = exchange('POST', tokenRoute, client.key, {})
  63. require(r.ok && r.body != null && hlTypeName(r.body.token) == 'String' && hlTypeName(r.body.expires) == 'String', 'token request failed: HTTP ' + r.status + ' ' + r.code)
  64. client.token = r.body.token
  65. client.expires = r.body.expires.slice(0, 19)
  66. return client.token
  67. }
  68. // One API call. 401 -> one new token and one retry; 429 -> wait Retry-After (capped), up to maxRateTries; anything else is returned
  69. // as the structured result (callers decide: 409 and 422 are normal answers). Use must() to turn a failure into an error.
  70. call = (String method, String route, Hybrid payload = null) => {
  71. let refreshed = false
  72. let tries = 0
  73. while (true) {
  74. r = exchange(method, route, getToken(), payload)
  75. if (r.status == 401 && !refreshed) {
  76. refreshed = true
  77. getToken(true)
  78. continue
  79. }
  80. if (r.status == 429 && tries < maxRateTries) {
  81. tries = tries + 1
  82. let wait = toNumber(r.headers['retry-after'])
  83. if (wait == null || wait < 0) { wait = 1 }
  84. sleep(wait > maxRetryAfter ? maxRetryAfter : wait)
  85. continue
  86. }
  87. return r
  88. }
  89. }
  90. must = (Hybrid r, String what) => {
  91. if (!r.ok) { hlError(scrub(what + ': HTTP ' + r.status + ' ' + r.code + ' ' + r.message)) }
  92. return r.body
  93. }
  94. // Every page of a list answer: key = 'threads' | 'comments' | 'pulls'.
  95. listAll = (String route, String key) => {
  96. let items = []
  97. let cursor = null
  98. let pages = 0
  99. while (true) {
  100. body = must(call('GET', route + '?limit=' + pageLimit + (cursor == null ? '' : '&cursor=' + encodeURIComponent(cursor))), 'GET ' + route)
  101. for (x of body[key]) { items.push(x) }
  102. cursor = body.next
  103. pages = pages + 1
  104. require(pages < 1000, 'too many pages')
  105. if (cursor == null) { break }
  106. }
  107. return items
  108. }
  109. getPull = (Number n) => { return must(call('GET', pullRoute(n)), 'GET ' + pullRoute(n)) }
  110. getThreads = (Number n) => { return listAll(threadsRoute(n), 'threads') }
  111. putStatus = (String sha, String state, String title, String summary) => {
  112. return call('PUT', statusRoute(sha), { context = statusContext, =state, =title, summary = scrub(summary), url = null })
  113. }

Branches

Latest commits

  • bd3591c7conductor: gates run on the live day44 binarymre
  • 47f747a7records: jukebox #9 fix livemre
  • 0a3169fdMerge branch 'vendored-size' into mainKunibert
  • e447bb09Vendored size fix: keep renames with an app side whole; type the filter parameter (L10)mre
  • 99ccc742Vendored size fix: no renames in the app diff, filter the resumed delta toomre
  • 1a52e100|||PR Diff size limit counts only app files when vendored paths are setmre
  • 50a1867estatus: jukebox #9mre
  • c57484e6log: jukebox #9 diff sizemre
  • 795a20carecords: guard fix live (PR 8)mre
  • 6981d96fMerge branch 'fresh-on-nocmd' into mainKunibert
  • 37c47840runner: one shared prompt for both fresh-session fallbacks (L16)mre
  • f945d2e1|||PR runner: a resumed run with no command on a new head gets one fresh session instead of a tool errormre
  • 10b2a49estatus: PR 314, guard fix proposedmre
  • e73995a3log: hycon PR 314 approved after fresh reviewmre
  • f60427falog: hycon PR 314 false tool errormre
  • 481974f7log: Hermes accepts PR 259 findingmre
  • bb0976acrecords: hycon PR 259 design findingmre
  • 5c637c24records: hycon PR 259 false tool errormre
  • a344c406log: routger 132 reviewedmre
  • 56e70dcbrecords: review time limit 1800 s (routger 132)mre