gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/lib/events.hl

13.7 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' && k != 'onlyApp') { 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. // `extra.onlyApp` (gitoria#45) = ONLY that app (a reply in its thread, "Review again"); neither key is sent in the body
  62. static raiseEvent = (repo, event, action, extra, senderId) => {
  63. except = extra != null ? extra.exceptApp : null
  64. only = extra != null ? extra.onlyApp : null
  65. ids = []
  66. for (app of appsOfRepo(repo.id)) {
  67. if (app.id != except && (only == null || app.id == only)) { ids.push(raiseTo(repo, app, event, action, extra, senderId)) }
  68. }
  69. return ids
  70. }
  71. static raisePing = (repo, app, senderId) => {
  72. return raiseTo(repo, app, 'ping', null, null, senderId)
  73. }
  74. // every change of syncPulls becomes a pull_request event. Nothing here waits for a receiver and nothing throws at the caller.
  75. static syncAndRaise = (slug, userId) => {
  76. changes = syncPulls(slug, userId)
  77. repo = repoBySlug(slug)
  78. if (repo == null || countOfList(appsOfRepo(repo.id)) == 0) { return changes }
  79. for (c of changes) {
  80. pull = pullObject(slug, c.number)
  81. if (pull != null) {
  82. extra = { pull = pull }
  83. if (c.action == 'synchronize') { extra.before = c.before extra.after = c.after extra.forced = c.forced }
  84. if (c.action == 'merged') { extra.mergeCommit = c.mergeCommit }
  85. raiseEvent(repo, 'pull_request', c.action, extra, c.sender != null ? c.sender.id : null)
  86. }
  87. }
  88. return changes
  89. }
  90. // ---- the owner's buttons and the delivery log ----------------------------------------------------------------------
  91. // Settings → Apps → "Send ping" (the owner is checked by lib/apps.hl) → the delivery's uuid
  92. static pingApp = (repo, app, userId) => {
  93. return raisePing(repo, app, userId)
  94. }
  95. // redeliver one delivery of an app: back to pending, due now, the SAME uuid. → true, or false when the app has no such delivery
  96. static redeliver = (appId, deliveryId) => {
  97. d = deliveryId == null || hlTypeName(deliveryId) != 'String' ? null : deliveriesTable.fetch(deliveryId)
  98. if (d == null || d.app != appId) { return false }
  99. deliveriesTable.update(d.id, rowWith(d, { status = 'pending' step = 0 nextAt = now() updated = now() }))
  100. return true
  101. }
  102. // an app's deliveries, newest first (created, then id), one page: GET {api}/deliveries?cursor=&limit= → { deliveries, next }.
  103. // 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).
  104. static deliveryPage = (appId, cursor, limit) => {
  105. all = deliveriesTable.find('app', appId)
  106. rows = []
  107. if (countOfList(all) > 0) { for (d of all) { rows.push(d) } }
  108. let i = 1
  109. while (i < rows.length) {
  110. cur = rows[i]
  111. let j = i - 1
  112. while (j >= 0 && (rows[j].created < cur.created || (rows[j].created == cur.created && rows[j].id < cur.id))) {
  113. rows[j + 1] = rows[j]
  114. j = j - 1
  115. }
  116. rows[j + 1] = cur
  117. i = i + 1
  118. }
  119. let cut = -1
  120. let cutId = ''
  121. if (cursor != null && hlTypeName(cursor) == 'String' && cursor.includes('_')) {
  122. u = cursor.indexOf('_')
  123. cut = toNumber(cursor.slice(0, u))
  124. cutId = cursor.slice(u + 1)
  125. if (cut == null) { cut = -1 }
  126. }
  127. n = limit == null || limit < 1 ? 50 : (limit > 100 ? 100 : limit)
  128. out = []
  129. let more = false
  130. for (d of rows) {
  131. older = cut < 0 || d.created < cut || (d.created == cut && d.id < cutId)
  132. if (older) {
  133. if (out.length < n) { out.push(d) } else { more = true }
  134. }
  135. }
  136. list = []
  137. 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 }) }
  138. last = out.length > 0 ? out[out.length - 1] : null
  139. return { deliveries = list next = more && last != null ? '' + last.created + '_' + last.id : null }
  140. }
  141. // ---- THE SENDER ----------------------------------------------------------------------------------------------------
  142. // mkdir is the one atomic step: true when THIS call made the folder
  143. static claim = (name) => {
  144. mkDir(claimsDir, 448)
  145. r = run(['mkdir', claimsDir + '/' + name])
  146. return r != null && r.exit == 0
  147. }
  148. // what Settings → Apps shows for an app: its NEWEST delivery (by `updated`) → { text, at } or null. Read from the deliveries table only:
  149. // the sender never writes the apps row (a stale process could bring back an old secret or a removed key).
  150. static lastDeliveryOf = (appId) => {
  151. rows = deliveriesTable.find('app', appId)
  152. if (countOfList(rows) == 0) { return null }
  153. let top = rows[0]
  154. for (d of rows) { if (d.updated > top.updated) { top = d } }
  155. shown = top.lastCode == 0 ? 'no answer' : '' + top.lastCode
  156. let text = top.event + ' is waiting'
  157. if (top.status == 'delivered') { text = top.event + ' delivered (' + top.lastCode + ')' }
  158. else if (top.status == 'failed') { text = top.event + ' failed (' + shown + ')' }
  159. else if (top.tries > 0) { text = top.event + ' will be tried again (' + shown + ')' }
  160. return { text = text at = top.updated }
  161. }
  162. // after an attempt: delivered, or a later try, or failed
  163. static finishAttempt = (d, app, code) => {
  164. t = now()
  165. if (code >= 200 && code < 300) {
  166. deliveriesTable.update(d.id, rowWith(d, { status = 'delivered' lastCode = code updated = t claimedUntil = 0 }))
  167. return null
  168. }
  169. steps = retryMs()
  170. shown = code == 0 ? 'no answer' : '' + code
  171. if (d.step >= steps.length) {
  172. deliveriesTable.update(d.id, rowWith(d, { status = 'failed' lastCode = code updated = t claimedUntil = 0 }))
  173. return null
  174. }
  175. deliveriesTable.update(d.id, rowWith(d, { lastCode = code step = d.step + 1 nextAt = t + steps[d.step] updated = t claimedUntil = 0 }))
  176. return null
  177. }
  178. // one row: claim attempt number tries + 1, then POST. The row is written BEFORE the POST (claimedBy / claimedUntil / tries) and after it (the outcome).
  179. static sendOne = (d0) => {
  180. if (!claim(d0.id + '.' + (d0.tries + 1))) { return null }
  181. app = appsTable.fetch(d0.app)
  182. if (app == null) { deliveriesTable.delete(d0.id) return null } // the app was removed: its events die with it
  183. deliveriesTable.update(d0.id, rowWith(d0, { tries = d0.tries + 1 claimedBy = me claimedUntil = now() + claimMs updated = now() }))
  184. d = deliveriesTable.fetch(d0.id)
  185. // the address is checked again at send time (the allow-list may have changed since connect); no redirects are followed
  186. if (!urlAllowed(app.hookUrl)) {
  187. deliveriesTable.update(d.id, rowWith(d, { status = 'failed' lastCode = 0 updated = now() claimedUntil = 0 }))
  188. return null
  189. }
  190. 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) }
  191. res = fetch(app.hookUrl, { method = 'POST' headers = headers body = d.body timeoutMs = 10000 maxRedirects = 0 })
  192. code = res == null || res.status == null ? 0 : res.status
  193. finishAttempt(deliveriesTable.fetch(d.id), app, code)
  194. return null
  195. }
  196. // a claimed attempt whose process died: nobody finished it long after claimedUntil → count it as failed (one winner: the `.dead` folder)
  197. static closeDead = (d) => {
  198. if (d.tries == 0 || d.claimedUntil == 0 || now() < d.claimedUntil + claimMs) { return false }
  199. if (!claim(d.id + '.' + d.tries + '.dead')) { return true }
  200. app = appsTable.fetch(d.app)
  201. if (app == null) { deliveriesTable.delete(d.id) return true }
  202. finishAttempt(d, app, 0)
  203. return true
  204. }
  205. // 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
  206. static sweep = () => {
  207. t = now()
  208. if (t - lastSweep < sweepEveryMs) { return null }
  209. lastSweep = t
  210. for (app of appsTable.find(null, null)) {
  211. rows = deliveriesTable.find('app', app.id)
  212. if (countOfList(rows) > 0) {
  213. keep = []
  214. for (d of rows) {
  215. if (t - d.created > maxAgeMs) { deliveriesTable.delete(d.id) } else { keep.push(d) }
  216. }
  217. // the oldest first (an insertion sort: no sort(), hybriel #1), then the surplus goes
  218. let i = 1
  219. while (i < keep.length) {
  220. cur = keep[i]
  221. let j = i - 1
  222. while (j >= 0 && keep[j].created > cur.created) {
  223. keep[j + 1] = keep[j]
  224. j = j - 1
  225. }
  226. keep[j + 1] = cur
  227. i = i + 1
  228. }
  229. let drop = 0
  230. while (drop < keep.length - maxPerApp) {
  231. deliveriesTable.delete(keep[drop].id)
  232. drop = drop + 1
  233. }
  234. }
  235. }
  236. if (exists(claimsDir)) {
  237. for (folder of listDir(claimsDir)) {
  238. if (deliveriesTable.fetch(folder.name.split('.')[0]) == null) { run(['rmdir', folder.path]) }
  239. }
  240. }
  241. return null
  242. }
  243. // ONE TICK of the timer (project.hl): the due rows, oldest first, at most 20; a row is only ever touched through claim()
  244. static sendDue = () => {
  245. t = now()
  246. due = deliveriesTable.find('status', 'pending')
  247. if (countOfList(due) == 0) { sweep() return null }
  248. let sent = 0
  249. for (d of due) {
  250. if (sent < perTick) {
  251. // 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
  252. if (!closeDead(d) && d.nextAt <= t && d.claimedUntil <= t) {
  253. sendOne(d)
  254. sent = sent + 1
  255. }
  256. }
  257. }
  258. sweep()
  259. return null
  260. }

Branches

Latest commits

  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre