gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchw63-force-push52576cb0force push: defer on a failed scan, one-to-one pairs, docs (#56)mrew63-force-push/lib/events.hl

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

Branches

Latest commits

  • 52576cb0force push: defer on a failed scan, one-to-one pairs, docs (#56)mre
  • 5a7b3e68|||PR a force push keeps the same pull request (#56)mre
  • cc1be2d6Merge branch 'w62-pr-close' into mainGitoria
  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • 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