gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitc6162f00c6162f00gitoria#46: status badges on /pulls, Required before merge in Settingsmrec6162f00/lib/events.hl

13.5 KB

  1. // lib/events.hl — GITORIA SENDS SIGNED EVENTS TO CONNECTED APPS (gitoria#43, part of the push API gitoria#38; contract docs/apps-api.md §4).
  2. // raiseEvent(repo, event, action, extra, senderId) one delivery row per connected app of the repo (not to the app that caused it: extra.exceptApp),
  3. // the body built ONCE here and stored as the exact bytes that are signed and sent. Only writes rows:
  4. // a push or a page action never waits for a receiver.
  5. // syncAndRaise(slug, userId) pullsync.hl syncPulls + a pull_request event for every change (the three places a push or a merge lands)
  6. // raisePing(repo, app, senderId) the `ping` event for ONE app (at connect, and the Settings "Send ping" button)
  7. // sendDue() the sender, called by the hl:time timer in project.hl: takes due rows and POSTs them
  8. // redeliver(appId, deliveryId) puts a row back to pending now (POST {api}/deliveries/:id/redeliver, lib/api.hl appRedeliver)
  9. // deliveryPage(appId, cursor, limit) one page of the app's rows for GET {api}/deliveries (lib/api.hl appDeliveries)
  10. // deliveriesTable pk id (the uuid, also X-Push-Delivery) index app, status storage/mpackdb/deliveries.db
  11. // { id, app (apps @id), repo (repos @id), event, action, body (the signed bytes), tries (attempts made, never reset), step (index in the retry schedule),
  12. // nextAt, status pending|delivered|failed, lastCode (0 = no answer), created, updated, claimedBy, claimedUntil }
  13. // ONE PROCESS SENDS A ROW (two processes share storage during a deploy: the standby). The table has no compare-and-set and a handle does not see another
  14. // process's writes, so the claim is the filesystem's: `mkdir storage/claims/<delivery>.<tries>` (POSIX mkdir fails when the folder exists, atomically,
  15. // across processes). Whoever's mkdir succeeds owns attempt number <tries> of that delivery and is the only one that POSTs it; the loser skips it. The next
  16. // attempt has a new number (tries + 1), so the folder of an old attempt never blocks a later one. While an attempt is in flight the row says so (claimedUntil in the future) and the other process skips it. A claimed attempt whose process died (the row still
  17. // says the same tries long after claimedUntil) is closed by a second folder `<delivery>.<tries>.dead` (again one winner), which counts the attempt as failed.
  18. import { MPackDB } from 'hl:mpackdb'
  19. import { now, timestamp } from 'hl:time'
  20. import { fetch } from 'hl:fetch'
  21. import { run } from 'hl:proc'
  22. import { mkDir, listDir, exists } from 'hl:fs'
  23. import { randomBytes } from 'hl:crypto'
  24. import { storageDir, countOfList, firstOf, localStamp } from './util.hl'
  25. import { repoBySlug } from './repos.hl'
  26. import { nameOfUser } from './users.hl'
  27. import { appsTable, appsOfRepo } from './apps-table.hl'
  28. import { urlAllowed } from './apps-helpers.hl'
  29. import { syncPulls, pullObject } from './pullsync.hl'
  30. import { newUuid, signatureOf, retryMs, repoPart } from './events-helpers.hl'
  31. static deliveriesTable = new MPackDB(file = storageDir + '/deliveries.db', primaryKey = 'id', indexes = ['app', 'status'])
  32. static claimsDir = storageDir + '/claims'
  33. static me = randomBytes(6, 'hex') // this process, for claimedBy
  34. static maxAgeMs = 604800000 // retention: 7 days
  35. static maxPerApp = 200
  36. static perTick = 20
  37. static claimMs = 30000 // a claim is normally finished well inside this (the POST times out at 10 s)
  38. static sweepEveryMs = 60000
  39. static lastSweep = 0
  40. // a whole delivery row with some fields changed (update() replaces the record)
  41. static rowWith = (d, change) => {
  42. o = { id = d.id app = d.app repo = d.repo event = d.event action = d.action body = d.body tries = d.tries step = d.step nextAt = d.nextAt status = d.status lastCode = d.lastCode created = d.created updated = d.updated claimedBy = d.claimedBy claimedUntil = d.claimedUntil }
  43. for (k of change.keys()) { o[k] = change[k] }
  44. return o
  45. }
  46. // ---- RAISING: only writes rows -----------------------------------------------------------------------------------
  47. // one row for one app: the body is made now, once → the delivery's uuid
  48. static raiseTo = (repo, app, event, action, extra, senderId) => {
  49. id = newUuid()
  50. t = now()
  51. let sender = null
  52. if (senderId != null) { sender = { id = senderId name = nameOfUser(senderId) } }
  53. body = { event = event action = action delivery = id time = timestamp(t) repo = repoPart(repo) app = { id = app.id name = app.name } sender = sender }
  54. if (extra != null) {
  55. for (k of extra.keys()) { if (k != 'exceptApp') { body[k] = extra[k] } }
  56. }
  57. deliveriesTable.put({ id = id app = app.id repo = repo.id event = event action = action body = JSON.stringify(body) tries = 0 step = 0 nextAt = t status = 'pending' lastCode = 0 created = t updated = t claimedBy = '' claimedUntil = 0 })
  58. return id
  59. }
  60. // every connected app of the repo gets the event, except the one `extra.exceptApp` names (an app gets no events about its own actions)
  61. static raiseEvent = (repo, event, action, extra, senderId) => {
  62. except = extra != null ? extra.exceptApp : null
  63. ids = []
  64. for (app of appsOfRepo(repo.id)) {
  65. if (app.id != except) { ids.push(raiseTo(repo, app, event, action, extra, senderId)) }
  66. }
  67. return ids
  68. }
  69. static raisePing = (repo, app, senderId) => {
  70. return raiseTo(repo, app, 'ping', null, null, senderId)
  71. }
  72. // every change of syncPulls becomes a pull_request event. Nothing here waits for a receiver and nothing throws at the caller.
  73. static syncAndRaise = (slug, userId) => {
  74. changes = syncPulls(slug, userId)
  75. repo = repoBySlug(slug)
  76. if (repo == null || countOfList(appsOfRepo(repo.id)) == 0) { return changes }
  77. for (c of changes) {
  78. pull = pullObject(slug, c.number)
  79. if (pull != null) {
  80. extra = { pull = pull }
  81. if (c.action == 'synchronize') { extra.before = c.before extra.after = c.after extra.forced = c.forced }
  82. if (c.action == 'merged') { extra.mergeCommit = c.mergeCommit }
  83. raiseEvent(repo, 'pull_request', c.action, extra, c.sender != null ? c.sender.id : null)
  84. }
  85. }
  86. return changes
  87. }
  88. // ---- the owner's buttons and the delivery log ----------------------------------------------------------------------
  89. // Settings → Apps → "Send ping" (the owner is checked by lib/apps.hl) → the delivery's uuid
  90. static pingApp = (repo, app, userId) => {
  91. return raisePing(repo, app, userId)
  92. }
  93. // redeliver one delivery of an app: back to pending, due now, the SAME uuid. → true, or false when the app has no such delivery
  94. static redeliver = (appId, deliveryId) => {
  95. d = deliveryId == null || hlTypeName(deliveryId) != 'String' ? null : deliveriesTable.fetch(deliveryId)
  96. if (d == null || d.app != appId) { return false }
  97. deliveriesTable.update(d.id, rowWith(d, { status = 'pending' step = 0 nextAt = now() updated = now() }))
  98. return true
  99. }
  100. // an app's deliveries, newest first (created, then id), one page: GET {api}/deliveries?cursor=&limit= → { deliveries, next }.
  101. // The cursor is "<created>_<id>" of the last row of the page: the next page is every row older than that one (rows raised meanwhile do not shift it).
  102. static deliveryPage = (appId, cursor, limit) => {
  103. all = deliveriesTable.find('app', appId)
  104. rows = []
  105. if (countOfList(all) > 0) { for (d of all) { rows.push(d) } }
  106. let i = 1
  107. while (i < rows.length) {
  108. cur = rows[i]
  109. let j = i - 1
  110. while (j >= 0 && (rows[j].created < cur.created || (rows[j].created == cur.created && rows[j].id < cur.id))) {
  111. rows[j + 1] = rows[j]
  112. j = j - 1
  113. }
  114. rows[j + 1] = cur
  115. i = i + 1
  116. }
  117. let cut = -1
  118. let cutId = ''
  119. if (cursor != null && hlTypeName(cursor) == 'String' && cursor.includes('_')) {
  120. u = cursor.indexOf('_')
  121. cut = toNumber(cursor.slice(0, u))
  122. cutId = cursor.slice(u + 1)
  123. if (cut == null) { cut = -1 }
  124. }
  125. n = limit == null || limit < 1 ? 50 : (limit > 100 ? 100 : limit)
  126. out = []
  127. let more = false
  128. for (d of rows) {
  129. older = cut < 0 || d.created < cut || (d.created == cut && d.id < cutId)
  130. if (older) {
  131. if (out.length < n) { out.push(d) } else { more = true }
  132. }
  133. }
  134. list = []
  135. for (d of out) { list.push({ id = d.id event = d.event action = d.action time = timestamp(d.created) status = d.status tries = d.tries lastCode = d.lastCode }) }
  136. last = out.length > 0 ? out[out.length - 1] : null
  137. return { deliveries = list next = more && last != null ? '' + last.created + '_' + last.id : null }
  138. }
  139. // ---- THE SENDER ----------------------------------------------------------------------------------------------------
  140. // mkdir is the one atomic step: true when THIS call made the folder
  141. static claim = (name) => {
  142. mkDir(claimsDir, 448)
  143. r = run(['mkdir', claimsDir + '/' + name])
  144. return r != null && r.exit == 0
  145. }
  146. // what Settings → Apps shows for an app: its NEWEST delivery (by `updated`) → { text, at } or null. Read from the deliveries table only:
  147. // the sender never writes the apps row (a stale process could bring back an old secret or a removed key).
  148. static lastDeliveryOf = (appId) => {
  149. rows = deliveriesTable.find('app', appId)
  150. if (countOfList(rows) == 0) { return null }
  151. let top = rows[0]
  152. for (d of rows) { if (d.updated > top.updated) { top = d } }
  153. shown = top.lastCode == 0 ? 'no answer' : '' + top.lastCode
  154. let text = top.event + ' is waiting'
  155. if (top.status == 'delivered') { text = top.event + ' delivered (' + top.lastCode + ')' }
  156. else if (top.status == 'failed') { text = top.event + ' failed (' + shown + ')' }
  157. else if (top.tries > 0) { text = top.event + ' will be tried again (' + shown + ')' }
  158. return { text = text at = top.updated }
  159. }
  160. // after an attempt: delivered, or a later try, or failed
  161. static finishAttempt = (d, app, code) => {
  162. t = now()
  163. if (code >= 200 && code < 300) {
  164. deliveriesTable.update(d.id, rowWith(d, { status = 'delivered' lastCode = code updated = t claimedUntil = 0 }))
  165. return null
  166. }
  167. steps = retryMs()
  168. shown = code == 0 ? 'no answer' : '' + code
  169. if (d.step >= steps.length) {
  170. deliveriesTable.update(d.id, rowWith(d, { status = 'failed' lastCode = code updated = t claimedUntil = 0 }))
  171. return null
  172. }
  173. deliveriesTable.update(d.id, rowWith(d, { lastCode = code step = d.step + 1 nextAt = t + steps[d.step] updated = t claimedUntil = 0 }))
  174. return null
  175. }
  176. // one row: claim attempt number tries + 1, then POST. The row is written BEFORE the POST (claimedBy / claimedUntil / tries) and after it (the outcome).
  177. static sendOne = (d0) => {
  178. if (!claim(d0.id + '.' + (d0.tries + 1))) { return null }
  179. app = appsTable.fetch(d0.app)
  180. if (app == null) { deliveriesTable.delete(d0.id) return null } // the app was removed: its events die with it
  181. deliveriesTable.update(d0.id, rowWith(d0, { tries = d0.tries + 1 claimedBy = me claimedUntil = now() + claimMs updated = now() }))
  182. d = deliveriesTable.fetch(d0.id)
  183. // the address is checked again at send time (the allow-list may have changed since connect); no redirects are followed
  184. if (!urlAllowed(app.hookUrl)) {
  185. deliveriesTable.update(d.id, rowWith(d, { status = 'failed' lastCode = 0 updated = now() claimedUntil = 0 }))
  186. return null
  187. }
  188. headers = { 'Content-Type' = 'application/json' 'User-Agent' = 'gitoria' 'X-Push-Event' = d.event 'X-Push-Delivery' = d.id 'X-Push-Signature-256' = signatureOf(app.secret, d.body) }
  189. res = fetch(app.hookUrl, { method = 'POST' headers = headers body = d.body timeoutMs = 10000 maxRedirects = 0 })
  190. code = res == null || res.status == null ? 0 : res.status
  191. finishAttempt(deliveriesTable.fetch(d.id), app, code)
  192. return null
  193. }
  194. // a claimed attempt whose process died: nobody finished it long after claimedUntil → count it as failed (one winner: the `.dead` folder)
  195. static closeDead = (d) => {
  196. if (d.tries == 0 || d.claimedUntil == 0 || now() < d.claimedUntil + claimMs) { return false }
  197. if (!claim(d.id + '.' + d.tries + '.dead')) { return true }
  198. app = appsTable.fetch(d.app)
  199. if (app == null) { deliveriesTable.delete(d.id) return true }
  200. finishAttempt(d, app, 0)
  201. return true
  202. }
  203. // retention: rows older than 7 days go; of the rest at most 200 per app stay (the oldest go first); the claim folders of deleted rows go too
  204. static sweep = () => {
  205. t = now()
  206. if (t - lastSweep < sweepEveryMs) { return null }
  207. lastSweep = t
  208. for (app of appsTable.find(null, null)) {
  209. rows = deliveriesTable.find('app', app.id)
  210. if (countOfList(rows) > 0) {
  211. keep = []
  212. for (d of rows) {
  213. if (t - d.created > maxAgeMs) { deliveriesTable.delete(d.id) } else { keep.push(d) }
  214. }
  215. // the oldest first (an insertion sort: no sort(), hybriel #1), then the surplus goes
  216. let i = 1
  217. while (i < keep.length) {
  218. cur = keep[i]
  219. let j = i - 1
  220. while (j >= 0 && keep[j].created > cur.created) {
  221. keep[j + 1] = keep[j]
  222. j = j - 1
  223. }
  224. keep[j + 1] = cur
  225. i = i + 1
  226. }
  227. let drop = 0
  228. while (drop < keep.length - maxPerApp) {
  229. deliveriesTable.delete(keep[drop].id)
  230. drop = drop + 1
  231. }
  232. }
  233. }
  234. if (exists(claimsDir)) {
  235. for (folder of listDir(claimsDir)) {
  236. if (deliveriesTable.fetch(folder.name.split('.')[0]) == null) { run(['rmdir', folder.path]) }
  237. }
  238. }
  239. return null
  240. }
  241. // ONE TICK of the timer (project.hl): the due rows, oldest first, at most 20; a row is only ever touched through claim()
  242. static sendDue = () => {
  243. t = now()
  244. due = deliveriesTable.find('status', 'pending')
  245. if (countOfList(due) == 0) { sweep() return null }
  246. let sent = 0
  247. for (d of due) {
  248. if (sent < perTick) {
  249. // a row another process is sending right now (claimedUntil in the future) is left alone: its next attempt number must not be claimed under it
  250. if (!closeDead(d) && d.nextAt <= t && d.claimedUntil <= t) {
  251. sendOne(d)
  252. sent = sent + 1
  253. }
  254. }
  255. }
  256. sweep()
  257. return null
  258. }

Branches

Latest commits

  • c6162f00gitoria#46: status badges on /pulls, Required before merge in Settingsmre
  • e5a0b64egitoria#46: PUT statuses/<sha>, required contexts block the merge on the servermre
  • 49533a50gitoria#43: signed events to connected apps (merge w43-events)mre
  • 1a1e87d5gitoria#43: the sender never writes the apps row; Settings shows the newest deliverymre
  • cd442066gitoria#43: app-auth unit test reads the apps table from its new filemre
  • 5dccbe38gitoria#43: in-flight rows are left alone by the other process; gate in deploy.sh; READMEmre
  • 8c8805f3merge main (gitoria#42), delivery log and redelivery routes, sweep fixmre
  • 5a996ea8gitoria#42: short-lived app tokens, read-only git fetch with them (merge w42-app-token)mre
  • afdb0cbfgitoria#43: rename the moved helper (name clash in the browser build)mre
  • 15e01e94gitoria#43: tests/events.mjs and its probemre
  • 77829b73gitoria#43: signed events to connected apps (deliveries table, sender timer, pull_request events, ping)mre
  • b5d696fegitoria#42: app tokens (gat_, one hour), appOfRequest, app token as the git read passwordmre
  • 1997e77dgitoria#40: stable PR numbers, refs/pull/N/head, ssh pushes reach the app (merge w40-pr-number)mre
  • 9364fb16gitoria#40: ssh pushes call /__git/pushed before and after (ensurePulls, notifyPush, syncPulls); gate over the sshd imagemre
  • fdb9ed28gitoria#41: repo owners can connect an app (merge w41-apps-connect)mre
  • 2ef23df0gitoria#40: the browser gate reads the title without the #Nmre
  • 9af07ecegitoria#41: connect an app to a repo (apps table, connect flow, manual add, allow-list, settings)mre
  • b9137ff0gitoria#40: pull requests are stored with a number, refs/pull/N/head, syncPulls and pullObject; /pulls shows #Nmre
  • 06d622daown image tag gitoria-runtime:debian12 for gitoria and standby (shared tag lost git)mre
  • 20caa33agitoria#37: media queries in the language's @media block (minWidth = '60rem') in list, codebrowser and repomre