gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchw53-pulls-speed-pr80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymrew53-pulls-speed-pr/lib/pullsync.hl

15.8 KB

  1. // lib/pullsync.hl — PULL REQUEST RECORDS (gitoria#40, part of the push API #38; contract docs/apps-api.md §3, §4).
  2. // A pull request is still a commit whose subject starts `|||PR` (git-helpers.hl parsePull), but now it is also STORED, so it has
  3. // a number that never changes and is never reused. Two tables, both keyed by the repo's ID (never the slug: a repo can be renamed):
  4. // pullRecs pk @id index !key, !shaKey, repo { rid (the repo's @id), number, key "<repo>#<n>", shaKey "<repo> <sha>", sha (the |||PR commit), source,
  5. // target, implicit (the target is the repo's main branch), state open|closed|merged, head, authorId, authorName,
  6. // heads (every head the PR has had, oldest first: an app may review an earlier one), createdMs, updatedMs } storage/mpackdb/pullrecs.db
  7. // pullInit pk @id index !repo { rid } a repo whose PRs were numbered once (the numbers of the old ones, oldest first)
  8. // ensurePulls(slug) numbers the PRs a repo already has, once, without changes (before the first push / page view)
  9. // syncPulls(slug, userId) compares git with the records → the CHANGES (opened|reopened|synchronize|closed|merged), each with the
  10. // ref refs/pull/<n>/head already pointing at the new head; logChange writes them (until gitoria#43 sends events)
  11. // pullObject(slug, n) the contract's `pull` JSON; withNumbers(list, slug) puts "#N" on the rows of /pulls.
  12. // A record is found again by the sha of its |||PR commit (that is what identifies a PR to git); its source branch may be renamed.
  13. // Merged is final. Nothing here throws: a failed git call skips that PR until the next sync.
  14. import { MPackDB } from 'hl:mpackdb'
  15. import { now, timestamp } from 'hl:time'
  16. import { appendFile } from 'hl:fs'
  17. import { NL, storageDir, countOfList, firstOf, repoOrigin, px } from './util.hl'
  18. import { repoBySlug } from './repos.hl'
  19. import { nameOfUser } from './users.hl'
  20. import { gitRaw, pickDefault } from './git.hl'
  21. import { tabs, isHexId, safeName, parsePull } from './git-helpers.hl'
  22. import { bodyOfLines, ticketNames } from './pullsync-helpers.hl'
  23. import { approvalsJson, approvalsOf } from './approvals.hl'
  24. import { statusesOf, statusJson, requiredOf, approversOf } from './statuses.hl'
  25. static pullRecs = new MPackDB(file = storageDir + '/pullrecs.db', primaryKey = '@id', indexes = ['!key', '!shaKey', 'rid'])
  26. static pullInit = new MPackDB(file = storageDir + '/pullinit.db', primaryKey = '@id', indexes = ['!rid'])
  27. static changeLog = storageDir + '/pull-changes.log'
  28. static maxNew = 50
  29. static scan = 500
  30. static zeroId = '0000000000000000000000000000000000000000'
  31. // ---- small git answers -------------------------------------------------------------------------------------
  32. // the first line of a git call's output, or '' (failed, nothing, or not a plain id when `hexOnly`)
  33. static firstLine = (slug, args) => {
  34. r = gitRaw(slug, args)
  35. if (r == null || r.exit != 0 || r.lines.length == 0) { return '' }
  36. return r.lines[0]
  37. }
  38. static isAncestor = (slug, a, b) => {
  39. if (a == null || b == null || a == '' || b == '') { return false }
  40. r = gitRaw(slug, ['merge-base', '--is-ancestor', a, b])
  41. return r != null && r.exit == 0
  42. }
  43. // { name: tip sha } of every branch, and the names in order
  44. static branchTips = (slug) => {
  45. tips = {}
  46. names = []
  47. r = gitRaw(slug, ['for-each-ref', '--format=%(refname:short)%09%(objectname)', 'refs/heads'])
  48. if (r != null && r.exit == 0) {
  49. for (l of r.lines) {
  50. f = tabs(l)
  51. if (f.length == 2 && safeName(f[0]) && isHexId(f[1])) {
  52. tips[f[0]] = f[1]
  53. names.push(f[0])
  54. }
  55. }
  56. }
  57. return { tips = tips names = names }
  58. }
  59. // The recorded source wins while it contains the marker. Without one, prefer the known head's
  60. // branch before another branch that merely contains the marker (for example a later PR).
  61. static sourceOf = (String slug, String sha, String target, String preferred, String head) => {
  62. return sourceResult(slug, sha, target, preferred, head).source
  63. }
  64. // The list cache also needs to know whether EVERY git read succeeded. Keep sourceOf's string contract.
  65. static sourceResult = (String slug, String sha, String target, String preferred, String head) => {
  66. r = gitRaw(slug, ['for-each-ref', '--contains', sha, '--format=%(refname:short)%09%(objectname)', 'refs/heads'])
  67. if (r == null || r.exit != 0) { return { source = '' ok = false } }
  68. candidates = []
  69. for (l of r.lines) {
  70. f = tabs(l)
  71. if (f.length == 2 && safeName(f[0]) && f[0] != target && isHexId(f[1])) {
  72. if (f[0] == preferred) { return { source = f[0] ok = true } }
  73. candidates.push({ name = f[0] tip = f[1] })
  74. }
  75. }
  76. knownHead = head == null || head == '' ? sha : head
  77. for (c of candidates) { if (c.tip == knownHead) { return { source = c.name ok = true } } }
  78. let complete = true
  79. for (c of candidates) {
  80. ancestor = gitRaw(slug, ['merge-base', '--is-ancestor', knownHead, c.tip])
  81. if (ancestor == null || (ancestor.exit != 0 && ancestor.exit != 1)) { complete = false }
  82. if (ancestor != null && ancestor.exit == 0) { return { source = c.name ok = complete } }
  83. }
  84. return { source = candidates.length > 0 ? candidates[0].name : '' ok = complete }
  85. }
  86. // the commit that put the PR into the target: the first one on the target's first-parent line that has the PR commit as an ancestor
  87. // (the merge commit of the Merge button; a fast-forward's commit itself); the target's tip when git cannot say
  88. static mergeCommitOf = (slug, sha, targetTip) => {
  89. r = gitRaw(slug, ['rev-list', '--first-parent', '--ancestry-path', '--reverse', sha + '..' + targetTip])
  90. if (r != null && r.exit == 0 && r.lines.length > 0 && isHexId(r.lines[0])) { return r.lines[0] }
  91. return targetTip
  92. }
  93. // ---- the refs/pull/N/head ref (and refs/pull/N/heads/<sha> for every head it ever had) ----------------------------------------------------------------------------
  94. // point it at `head`, with the old value given (a ref that is not there must not be there). → true when it points there afterwards
  95. static setPullRef = (slug, n, head) => {
  96. ref = 'refs/pull/' + n + '/head'
  97. cur = firstLine(slug, ['rev-parse', '--verify', '-q', ref])
  98. if (cur == head) { return true }
  99. r = gitRaw(slug, ['update-ref', '-m', 'pull request ' + n, ref, head, cur == '' ? zeroId : cur])
  100. if (r == null || r.exit != 0) { return false }
  101. // every head stays referenced (refs/pull/N/heads/<sha>, hidden like the rest of refs/pull): an app may review an earlier head, git gc must not drop it
  102. gitRaw(slug, ['update-ref', '-m', 'pull request ' + n + ' head', 'refs/pull/' + n + '/heads/' + head, head])
  103. return true
  104. }
  105. // ---- the records -------------------------------------------------------------------------------------------
  106. static recordsOf = (repoId) => {
  107. all = pullRecs.find('rid', repoId)
  108. return countOfList(all) == 0 ? [] : all
  109. }
  110. static recordBySha = (repoId, sha) => { return firstOf(pullRecs.find('shaKey', repoId + ' ' + sha)) }
  111. static recordByNumber = (repoId, n) => { return firstOf(pullRecs.find('key', repoId + '#' + n)) }
  112. // the next number: one more than the highest (records are never removed, so a number is never used twice)
  113. static nextNumber = (repoId) => {
  114. let top = 0
  115. for (r of recordsOf(repoId)) { if (r.number > top) { top = r.number } }
  116. return top + 1
  117. }
  118. // every head the record has had (a list of shas); the current one is always in it
  119. static headsOf = (rec) => {
  120. out = []
  121. if (rec.heads != null && countOfList(rec.heads) > 0) { for (h of rec.heads) { out.push(h) } }
  122. if (rec.head != null && !out.includes(rec.head)) { out.push(rec.head) }
  123. return out
  124. }
  125. static withHead = (rec, head) => {
  126. out = headsOf(rec)
  127. if (!out.includes(head)) { out.push(head) }
  128. return out
  129. }
  130. // was this sha ever a head of pull request N of the repo? (gitoria#44: a review of an earlier head is fine, only a sha that never was one is stale)
  131. static wasHeadOf = (slug, n, sha) => {
  132. repo = repoBySlug(slug)
  133. if (repo == null || n == null || sha == null || hlTypeName(sha) != 'String') { return false }
  134. rec = recordByNumber(repo.id, n)
  135. return rec != null && headsOf(rec).includes(sha)
  136. }
  137. static isInitialized = (repoId) => { return firstOf(pullInit.find('rid', repoId)) != null }
  138. static changeOf = (rec, action, before, after, forced, mergeCommit, pusherId) => {
  139. let sender = null
  140. if (pusherId != null) { sender = { id = pusherId name = nameOfUser(pusherId) } }
  141. return { number = rec.number action = action before = before after = after forced = forced mergeCommit = mergeCommit sender = sender }
  142. }
  143. // the commits of the repo that start a pull request, oldest first, not yet stored: [{ sha, ct, author, parsed }]
  144. static newCandidates = (slug, repoId) => {
  145. out = []
  146. lg = gitRaw(slug, ['log', '-' + scan, '--branches', '--format=%H%x09%ct%x09%an%x09%s'])
  147. if (lg == null || lg.exit != 0) { return out }
  148. for (l of lg.lines) {
  149. f = tabs(l)
  150. if (f.length >= 4 && isHexId(f[0]) && f[0].length == 40) {
  151. pr = parsePull(f.slice(3).join(' '))
  152. if (pr != null && out.length < maxNew && recordBySha(repoId, f[0]) == null) {
  153. out.push({ sha = f[0] ct = toNumber(f[1]) * 1000 author = f[2] parsed = pr })
  154. }
  155. }
  156. }
  157. // commit time, oldest first (an insertion sort: no sort(), hybriel #1)
  158. let i = 1
  159. while (i < out.length) {
  160. cur = out[i]
  161. let j = i - 1
  162. while (j >= 0 && out[j].ct > cur.ct) {
  163. out[j + 1] = out[j]
  164. j = j - 1
  165. }
  166. out[j + 1] = cur
  167. i = i + 1
  168. }
  169. return out
  170. }
  171. // the whole comparison. quiet = number the existing PRs and return no changes (ensurePulls). → the changes (a list)
  172. static syncNow = (slug, pusherId, quiet) => {
  173. changes = []
  174. repo = repoBySlug(slug)
  175. if (repo == null) { return changes }
  176. bt = branchTips(slug)
  177. if (bt.names.length == 0) { return changes }
  178. dflt = pickDefault(bt.names, repo.branch)
  179. stamp = now()
  180. // 1. the PRs we know
  181. for (rec of recordsOf(repo.id)) {
  182. if (rec.state != 'merged') {
  183. target = rec.implicit == true ? dflt : rec.target
  184. targetTip = bt.tips[target]
  185. let source = rec.source
  186. let tip = source != '' ? bt.tips[source] : null
  187. let onBranch = tip != null && isAncestor(slug, rec.sha, tip)
  188. if (!onBranch) {
  189. // the commit may sit on another branch now (the branch was renamed)
  190. other = sourceOf(slug, rec.sha, target, rec.source, rec.head)
  191. if (other != '' && bt.tips[other] != null) {
  192. source = other
  193. tip = bt.tips[other]
  194. onBranch = true
  195. }
  196. }
  197. u = rec
  198. u.target = target
  199. u.source = source
  200. let action = ''
  201. let before = rec.head
  202. let after = rec.head
  203. let forced = false
  204. let mergeCommit = null
  205. if (targetTip != null && isAncestor(slug, rec.sha, targetTip)) {
  206. action = 'merged'
  207. u.state = 'merged'
  208. if (onBranch) { after = tip }
  209. mergeCommit = mergeCommitOf(slug, rec.sha, targetTip)
  210. } else if (onBranch && rec.state == 'closed') {
  211. action = 'reopened'
  212. u.state = 'open'
  213. after = tip
  214. } else if (onBranch && tip != rec.head) {
  215. action = 'synchronize'
  216. after = tip
  217. forced = !isAncestor(slug, rec.head, tip)
  218. } else if (!onBranch && rec.state == 'open') {
  219. action = 'closed'
  220. u.state = 'closed'
  221. }
  222. u.head = after
  223. u.heads = withHead(rec, after)
  224. if (action != '' || source != rec.source || target != rec.target) {
  225. // the ref first: an event is only sent for a head that can be fetched
  226. if (action == '' || setPullRef(slug, rec.number, after)) {
  227. u.updatedMs = stamp
  228. pullRecs.update(rec.id, u)
  229. if (action != '' && !quiet) { changes.push(changeOf(u, action, before, after, forced, mergeCommit, pusherId)) }
  230. }
  231. }
  232. }
  233. }
  234. // 2. the PRs we have not seen, oldest first (numbers follow the commit time)
  235. for (c of newCandidates(slug, repo.id)) {
  236. target = c.parsed.target == '' ? dflt : c.parsed.target
  237. targetTip = bt.tips[target]
  238. source = sourceOf(slug, c.sha, target)
  239. merged = targetTip != null && isAncestor(slug, c.sha, targetTip)
  240. if (merged || (source != '' && bt.tips[source] != null)) {
  241. head = !merged && source != '' ? bt.tips[source] : c.sha
  242. n = nextNumber(repo.id)
  243. author = quiet || pusherId == null ? null : pusherId
  244. rec = { rid = repo.id number = n key = repo.id + '#' + n shaKey = repo.id + ' ' + c.sha sha = c.sha source = source target = target implicit = c.parsed.target == '' state = merged ? 'merged' : 'open' head = head heads = [head] authorId = author authorName = author != null ? nameOfUser(author) : c.author createdMs = quiet ? c.ct : stamp updatedMs = quiet ? c.ct : stamp }
  245. if (setPullRef(slug, n, head)) {
  246. id = pullRecs.put(rec)
  247. if (id != null && !quiet) {
  248. saved = pullRecs.fetch(id)
  249. changes.push(changeOf(saved, merged ? 'merged' : 'opened', null, head, false, merged ? mergeCommitOf(slug, c.sha, targetTip) : null, pusherId))
  250. }
  251. }
  252. }
  253. }
  254. return changes
  255. }
  256. // number the PRs a repo already has, ONCE (quiet); call it before a push is taken and when /pulls is built
  257. static ensurePulls = (slug) => {
  258. repo = repoBySlug(slug)
  259. if (repo == null || isInitialized(repo.id)) { return null }
  260. syncNow(slug, null, true)
  261. // an empty repo (no branch yet) has nothing to number and is initialized too: its first PR is a live one
  262. pullInit.put({ rid = repo.id })
  263. return null
  264. }
  265. // THE ENTRY: compare git with the records. Never fails the caller: whatever goes wrong yields the changes found so far (none).
  266. // userId = the gitoria user who pushed or merged (null when unknown). Every change is logged (logChange) and returned.
  267. static syncPulls = (slug, userId) => {
  268. ensurePulls(slug)
  269. changes = syncNow(slug, userId, false)
  270. for (c of changes) { logChange(slug, c) }
  271. return changes
  272. }
  273. // the change log until gitoria#43 sends events: one JSON line in storage/pull-changes.log (and the console)
  274. static logChange = (slug, c) => {
  275. repo = repoBySlug(slug)
  276. line = JSON.stringify({ time = timestamp(now()) repoId = repo != null ? repo.id : null slug = slug number = c.number action = c.action before = c.before after = c.after forced = c.forced mergeCommit = c.mergeCommit sender = c.sender })
  277. appendFile(changeLog, line + NL, 384)
  278. console.log('pull-change ' + line)
  279. return null
  280. }
  281. // ---- the contract's `pull` object (§4) --------------------------------------------------------------------
  282. static pullObject = (String slug, Number n, Hybrid approvalRows = null) => {
  283. repo = repoBySlug(slug)
  284. if (repo == null || n == null) { return null }
  285. rec = recordByNumber(repo.id, n)
  286. if (rec == null) { return null }
  287. msg = gitRaw(slug, ['log', '-1', '--format=%B', rec.sha])
  288. lines = msg != null && msg.exit == 0 ? msg.lines : []
  289. pr = lines.length > 0 ? parsePull(lines[0]) : null
  290. title = pr != null && pr.title != '' ? pr.title : (rec.source != '' ? rec.source : rec.sha.slice(0, 8))
  291. body = bodyOfLines(lines)
  292. baseTip = firstLine(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + rec.target])
  293. mergeBase = baseTip != '' ? firstLine(slug, ['merge-base', baseTip, rec.head]) : ''
  294. project = repo.tktProject != null ? repo.tktProject : ''
  295. statuses = []
  296. for (r of statusesOf(repo.id, rec.head)) { statuses.push(statusJson(r)) }
  297. return {
  298. number = rec.number
  299. title = title
  300. body = body
  301. draft = false
  302. state = rec.state
  303. author = { id = rec.authorId name = rec.authorName }
  304. source = rec.source
  305. target = rec.target
  306. head = rec.head
  307. ref = 'refs/pull/' + rec.number + '/head'
  308. baseRef = 'refs/heads/' + rec.target
  309. base = baseTip != '' ? baseTip : null
  310. mergeBase = mergeBase != '' ? mergeBase : null
  311. tickets = ticketNames(title + NL + body, project)
  312. url = repoOrigin(slug) + '/pulls/' + rec.number
  313. created = timestamp(rec.createdMs)
  314. updated = timestamp(rec.updatedMs)
  315. statuses = statuses
  316. required = requiredOf(repo.id)
  317. approvers = approversOf(repo.id)
  318. approvals = approvalsJson(approvalRows == null ? approvalsOf(repo.id, rec.number) : approvalRows, rec.head)
  319. }
  320. }
  321. // the rows of /pulls with their number: `number` (0 = not stored) and `numberText` ("#3")
  322. static withNumbers = (list, slug) => {
  323. out = []
  324. repo = repoBySlug(slug)
  325. for (p of list) {
  326. q = p
  327. rec = repo != null ? recordBySha(repo.id, p.sha) : null
  328. q.number = rec != null ? rec.number : 0
  329. q.numberText = rec != null ? '#' + rec.number : ''
  330. q.pageHref = rec != null ? px(slug) + '/pulls/' + rec.number : p.href
  331. out.push(q)
  332. }
  333. return out
  334. }

Branches

Latest commits

  • 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
  • 2a89d8d0|||PR person approvals: Approve button for people; merge needs the required checks or a listed person's approval (#52)mre
  • 83f0c953Report person approval verificationmre
  • 3ae94b86Record browser failures and verify owned tab cleanupmre
  • 54eec687Gate person approvals and merge alternativesmre
  • 12b08829Add person approvals for pull request headsmre
  • 55c84779Merge branch 'gp-gate-ports' into mainGitoria
  • 57af42bbREADME: point to deploy.sh for the port listmre
  • d63375d2README: gate commands with explicit portsmre
  • feeaa701|||PR gates: explicit ports only, deploy.sh passes themmre
  • 6cc1f943Merge branch 'records-1112' into mainGitoria
  • 9448c438|||PR records: LOG, missions and reports since 11-09mre
  • 6dc08a8eMerge branch 'p51-public-pr-reads' into mainGitoria
  • 7b88cfe0Type publicReaderOfRequest parameters (L10)Gitoria
  • 2a4b3dc1|||PR Anonymous reads of public repos' pulls and statusesmre
  • 21b2c141Merge branch 's25-no-session-on-login-error' into mainGitoria