gitoria
All repositories: gitoria
13.7 KB
// 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).// raiseEvent(repo, event, action, extra, senderId) one delivery row per connected app of the repo (not to the app that caused it: extra.exceptApp),// the body built ONCE here and stored as the exact bytes that are signed and sent. Only writes rows:// a push or a page action never waits for a receiver.// syncAndRaise(slug, userId) pullsync.hl syncPulls + a pull_request event for every change (the three places a push or a merge lands)// raisePing(repo, app, senderId) the `ping` event for ONE app (at connect, and the Settings "Send ping" button)// sendDue() the sender, called by the hl:time timer in project.hl: takes due rows and POSTs them// redeliver(appId, deliveryId) puts a row back to pending now (POST {api}/deliveries/:id/redeliver, lib/api.hl appRedeliver)// deliveryPage(appId, cursor, limit) one page of the app's rows for GET {api}/deliveries (lib/api.hl appDeliveries)// deliveriesTable pk id (the uuid, also X-Push-Delivery) index app, status storage/mpackdb/deliveries.db// { id, app (apps @id), repo (repos @id), event, action, body (the signed bytes), tries (attempts made, never reset), step (index in the retry schedule),// nextAt, status pending|delivered|failed, lastCode (0 = no answer), created, updated, claimedBy, claimedUntil }// 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// process's writes, so the claim is the filesystem's: `mkdir storage/claims/<delivery>.<tries>` (POSIX mkdir fails when the folder exists, atomically,// 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// 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// 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.import { MPackDB } from 'hl:mpackdb'import { now, timestamp } from 'hl:time'import { fetch } from 'hl:fetch'import { run } from 'hl:proc'import { mkDir, listDir, exists } from 'hl:fs'import { randomBytes } from 'hl:crypto'import { storageDir, countOfList, firstOf, localStamp } from './util.hl'import { repoBySlug } from './repos.hl'import { nameOfUser } from './users.hl'import { appsTable, appsOfRepo } from './apps-table.hl'import { urlAllowed } from './apps-helpers.hl'import { syncPulls, pullObject } from './pullsync.hl'import { newUuid, signatureOf, retryMs, repoPart } from './events-helpers.hl'static deliveriesTable = new MPackDB(file = storageDir + '/deliveries.db', primaryKey = 'id', indexes = ['app', 'status'])static claimsDir = storageDir + '/claims'static me = randomBytes(6, 'hex') // this process, for claimedBystatic maxAgeMs = 604800000 // retention: 7 daysstatic maxPerApp = 200static perTick = 20static claimMs = 30000 // a claim is normally finished well inside this (the POST times out at 10 s)static sweepEveryMs = 60000static lastSweep = 0// a whole delivery row with some fields changed (update() replaces the record)static rowWith = (d, change) => {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 }for (k of change.keys()) { o[k] = change[k] }return o}// ---- RAISING: only writes rows -----------------------------------------------------------------------------------// one row for one app: the body is made now, once → the delivery's uuidstatic raiseTo = (repo, app, event, action, extra, senderId) => {id = newUuid()t = now()let sender = nullif (senderId != null) { sender = { id = senderId name = nameOfUser(senderId) } }body = { event = event action = action delivery = id time = timestamp(t) repo = repoPart(repo) app = { id = app.id name = app.name } sender = sender }if (extra != null) {for (k of extra.keys()) { if (k != 'exceptApp' && k != 'onlyApp') { body[k] = extra[k] } }}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 })return id}// every connected app of the repo gets the event, except the one `extra.exceptApp` names (an app gets no events about its own actions);// `extra.onlyApp` (gitoria#45) = ONLY that app (a reply in its thread, "Review again"); neither key is sent in the bodystatic raiseEvent = (repo, event, action, extra, senderId) => {except = extra != null ? extra.exceptApp : nullonly = extra != null ? extra.onlyApp : nullids = []for (app of appsOfRepo(repo.id)) {if (app.id != except && (only == null || app.id == only)) { ids.push(raiseTo(repo, app, event, action, extra, senderId)) }}return ids}static raisePing = (repo, app, senderId) => {return raiseTo(repo, app, 'ping', null, null, senderId)}// every change of syncPulls becomes a pull_request event. Nothing here waits for a receiver and nothing throws at the caller.static syncAndRaise = (slug, userId) => {changes = syncPulls(slug, userId)repo = repoBySlug(slug)if (repo == null || countOfList(appsOfRepo(repo.id)) == 0) { return changes }for (c of changes) {pull = pullObject(slug, c.number)if (pull != null) {extra = { pull = pull }if (c.action == 'synchronize') { extra.before = c.before extra.after = c.after extra.forced = c.forced }if (c.action == 'merged') { extra.mergeCommit = c.mergeCommit }raiseEvent(repo, 'pull_request', c.action, extra, c.sender != null ? c.sender.id : null)}}return changes}// ---- the owner's buttons and the delivery log ----------------------------------------------------------------------// Settings → Apps → "Send ping" (the owner is checked by lib/apps.hl) → the delivery's uuidstatic pingApp = (repo, app, userId) => {return raisePing(repo, app, userId)}// redeliver one delivery of an app: back to pending, due now, the SAME uuid. → true, or false when the app has no such deliverystatic redeliver = (appId, deliveryId) => {d = deliveryId == null || hlTypeName(deliveryId) != 'String' ? null : deliveriesTable.fetch(deliveryId)if (d == null || d.app != appId) { return false }deliveriesTable.update(d.id, rowWith(d, { status = 'pending' step = 0 nextAt = now() updated = now() }))return true}// an app's deliveries, newest first (created, then id), one page: GET {api}/deliveries?cursor=&limit= → { deliveries, next }.// 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).static deliveryPage = (appId, cursor, limit) => {all = deliveriesTable.find('app', appId)rows = []if (countOfList(all) > 0) { for (d of all) { rows.push(d) } }let i = 1while (i < rows.length) {cur = rows[i]let j = i - 1while (j >= 0 && (rows[j].created < cur.created || (rows[j].created == cur.created && rows[j].id < cur.id))) {rows[j + 1] = rows[j]j = j - 1}rows[j + 1] = curi = i + 1}let cut = -1let cutId = ''if (cursor != null && hlTypeName(cursor) == 'String' && cursor.includes('_')) {u = cursor.indexOf('_')cut = toNumber(cursor.slice(0, u))cutId = cursor.slice(u + 1)if (cut == null) { cut = -1 }}n = limit == null || limit < 1 ? 50 : (limit > 100 ? 100 : limit)out = []let more = falsefor (d of rows) {older = cut < 0 || d.created < cut || (d.created == cut && d.id < cutId)if (older) {if (out.length < n) { out.push(d) } else { more = true }}}list = []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 }) }last = out.length > 0 ? out[out.length - 1] : nullreturn { deliveries = list next = more && last != null ? '' + last.created + '_' + last.id : null }}// ---- THE SENDER ----------------------------------------------------------------------------------------------------// mkdir is the one atomic step: true when THIS call made the folderstatic claim = (name) => {mkDir(claimsDir, 448)r = run(['mkdir', claimsDir + '/' + name])return r != null && r.exit == 0}// what Settings → Apps shows for an app: its NEWEST delivery (by `updated`) → { text, at } or null. Read from the deliveries table only:// the sender never writes the apps row (a stale process could bring back an old secret or a removed key).static lastDeliveryOf = (appId) => {rows = deliveriesTable.find('app', appId)if (countOfList(rows) == 0) { return null }let top = rows[0]for (d of rows) { if (d.updated > top.updated) { top = d } }shown = top.lastCode == 0 ? 'no answer' : '' + top.lastCodelet text = top.event + ' is waiting'if (top.status == 'delivered') { text = top.event + ' delivered (' + top.lastCode + ')' }else if (top.status == 'failed') { text = top.event + ' failed (' + shown + ')' }else if (top.tries > 0) { text = top.event + ' will be tried again (' + shown + ')' }return { text = text at = top.updated }}// after an attempt: delivered, or a later try, or failedstatic finishAttempt = (d, app, code) => {t = now()if (code >= 200 && code < 300) {deliveriesTable.update(d.id, rowWith(d, { status = 'delivered' lastCode = code updated = t claimedUntil = 0 }))return null}steps = retryMs()shown = code == 0 ? 'no answer' : '' + codeif (d.step >= steps.length) {deliveriesTable.update(d.id, rowWith(d, { status = 'failed' lastCode = code updated = t claimedUntil = 0 }))return null}deliveriesTable.update(d.id, rowWith(d, { lastCode = code step = d.step + 1 nextAt = t + steps[d.step] updated = t claimedUntil = 0 }))return null}// one row: claim attempt number tries + 1, then POST. The row is written BEFORE the POST (claimedBy / claimedUntil / tries) and after it (the outcome).static sendOne = (d0) => {if (!claim(d0.id + '.' + (d0.tries + 1))) { return null }app = appsTable.fetch(d0.app)if (app == null) { deliveriesTable.delete(d0.id) return null } // the app was removed: its events die with itdeliveriesTable.update(d0.id, rowWith(d0, { tries = d0.tries + 1 claimedBy = me claimedUntil = now() + claimMs updated = now() }))d = deliveriesTable.fetch(d0.id)// the address is checked again at send time (the allow-list may have changed since connect); no redirects are followedif (!urlAllowed(app.hookUrl)) {deliveriesTable.update(d.id, rowWith(d, { status = 'failed' lastCode = 0 updated = now() claimedUntil = 0 }))return null}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) }res = fetch(app.hookUrl, { method = 'POST' headers = headers body = d.body timeoutMs = 10000 maxRedirects = 0 })code = res == null || res.status == null ? 0 : res.statusfinishAttempt(deliveriesTable.fetch(d.id), app, code)return null}// a claimed attempt whose process died: nobody finished it long after claimedUntil → count it as failed (one winner: the `.dead` folder)static closeDead = (d) => {if (d.tries == 0 || d.claimedUntil == 0 || now() < d.claimedUntil + claimMs) { return false }if (!claim(d.id + '.' + d.tries + '.dead')) { return true }app = appsTable.fetch(d.app)if (app == null) { deliveriesTable.delete(d.id) return true }finishAttempt(d, app, 0)return true}// 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 toostatic sweep = () => {t = now()if (t - lastSweep < sweepEveryMs) { return null }lastSweep = tfor (app of appsTable.find(null, null)) {rows = deliveriesTable.find('app', app.id)if (countOfList(rows) > 0) {keep = []for (d of rows) {if (t - d.created > maxAgeMs) { deliveriesTable.delete(d.id) } else { keep.push(d) }}// the oldest first (an insertion sort: no sort(), hybriel #1), then the surplus goeslet i = 1while (i < keep.length) {cur = keep[i]let j = i - 1while (j >= 0 && keep[j].created > cur.created) {keep[j + 1] = keep[j]j = j - 1}keep[j + 1] = curi = i + 1}let drop = 0while (drop < keep.length - maxPerApp) {deliveriesTable.delete(keep[drop].id)drop = drop + 1}}}if (exists(claimsDir)) {for (folder of listDir(claimsDir)) {if (deliveriesTable.fetch(folder.name.split('.')[0]) == null) { run(['rmdir', folder.path]) }}}return null}// ONE TICK of the timer (project.hl): the due rows, oldest first, at most 20; a row is only ever touched through claim()static sendDue = () => {t = now()due = deliveriesTable.find('status', 'pending')if (countOfList(due) == 0) { sweep() return null }let sent = 0for (d of due) {if (sent < perTick) {// a row another process is sending right now (claimedUntil in the future) is left alone: its next attempt number must not be claimed under itif (!closeDead(d) && d.nextAt <= t && d.claimedUntil <= t) {sendOne(d)sent = sent + 1}}}sweep()return null}
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