gitoria

gitoria

All repositories: gitoria

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

19.7 KB

  1. // lib/reviews.hl — REVIEWS, INLINE THREADS AND COMMENTS OF CONNECTED APPS (gitoria#44, part of the push API #38; contract docs/apps-api.md §5).
  2. // Three tables, all keyed by the repo's ID and the PR number (never the slug: a repo can be renamed), storage/mpackdb/*.db:
  3. // reviewsTable pk @id index key, app { rid, key "<rid>#<n>", number, app (apps @id), head, verdict approve|request_changes|comment, body, created (ms) }
  4. // threadsTable pk @id index key, app { rid, key, number, app, path, line, head (the sha it was written on), resolved, seq (the seq of its first comment, the list order), created }
  5. // commentsTable pk @id index key, rid, thread { rid, key, number, seq, thread (threads @id, null = the PR's conversation), author { type app|user, id, name }, body, created (ms) }
  6. // SEQ grows strictly within a repo over all comments of all PRs (a watermark for the app). One process counts in memory; two processes share storage
  7. // during a deploy swap and an mpackdb handle does not see the other's writes, so the number is CLAIMED on the filesystem: `mkdir storage/mpackdb/seq/<repo id>/<n>`
  8. // (POSIX mkdir fails when it exists, atomically, the way lib/events.hl claims a delivery); the loser takes the next number. Numbers stay unique and each process
  9. // hands out growing ones; across the two processes a lower number can land in the table a moment AFTER a higher one (claimed first, written second), so an app
  10. // that reads exactly in that window can pass it by. The folders stay (one empty folder per comment).
  11. // Entry points (lib/api.hl is a thin wrapper): listPulls, getPull, postReview, listReviews, listThreads, postReply, resolveThread, listComments, postComment,
  12. // and currentVerdict(repoId, number, appId) = the app's latest review of a PR (a `comment` review does not clear an earlier request_changes; #45/#46 use it).
  13. import { MPackDB } from 'hl:mpackdb'
  14. import { now } from 'hl:time'
  15. import { run } from 'hl:proc'
  16. import { mkDir } from 'hl:fs'
  17. import { storageDir, countOfList, firstOf } from './util.hl'
  18. import { gitRaw } from './git.hl'
  19. import { ensurePulls, pullObject, recordByNumber, recordsOf, headsOf, firstLine } from './pullsync.hl'
  20. import { answer, failure, notFound, invalid, isoMs, bodyError, wholeNumber, numberOf, limitOf, sortRows, pageOf, commentable, maxBody, maxComments } from './reviews-helpers.hl'
  21. static reviewsTable = new MPackDB(file = storageDir + '/reviews.db', primaryKey = '@id', indexes = ['key', 'app'])
  22. static threadsTable = new MPackDB(file = storageDir + '/threads.db', primaryKey = '@id', indexes = ['key', 'app'])
  23. static commentsTable = new MPackDB(file = storageDir + '/comments.db', primaryKey = '@id', indexes = ['key', 'rid', 'thread'])
  24. static seqDir = storageDir + '/seq'
  25. static seqSeen = {}
  26. static emptyTree = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'
  27. static verdicts = ['approve', 'request_changes', 'comment']
  28. static rowsOf = (list) => { return countOfList(list) == 0 ? [] : list }
  29. static keyOf = (rid, n) => { return rid + '#' + n }
  30. static authorOfApp = (app) => { return { type = 'app' id = app.id name = app.name } }
  31. // ---- seq -----------------------------------------------------------------------------------------------------
  32. static topSeq = (rid) => {
  33. let top = 0
  34. for (c of rowsOf(commentsTable.find('rid', rid))) { if (c.seq > top) { top = c.seq } }
  35. return top
  36. }
  37. // the next number of the repo, claimed with mkdir; null when it cannot be claimed
  38. static nextSeq = (rid) => {
  39. let n = seqSeen[rid] != null ? seqSeen[rid] : topSeq(rid)
  40. mkDir(seqDir, 448)
  41. mkDir(seqDir + '/' + rid, 448)
  42. let tries = 0
  43. while (tries < 1000) {
  44. n = n + 1
  45. tries = tries + 1
  46. r = run(['mkdir', seqDir + '/' + rid + '/' + n])
  47. if (r != null && r.exit == 0) {
  48. seqSeen[rid] = n
  49. return n
  50. }
  51. }
  52. return null
  53. }
  54. // ---- shapes ----------------------------------------------------------------------------------------------------
  55. static commentShape = (c) => { return { id = c.id seq = c.seq author = c.author body = c.body created = isoMs(c.created) } }
  56. static bySeq = (a, b) => { return a.seq < b.seq }
  57. static threadShape = (t, current) => {
  58. cs = []
  59. for (c of sortRows(rowsOf(commentsTable.find('thread', t.id)), bySeq)) { cs.push(commentShape(c)) }
  60. return { id = t.id path = t.path line = t.line head = t.head outdated = t.head != current resolved = t.resolved comments = cs }
  61. }
  62. static reviewShape = (r) => { return { id = r.id verdict = r.verdict head = r.head body = r.body created = isoMs(r.created) } }
  63. // a comment written into a thread (or the conversation when threadId is null) → the stored row, or null when no seq could be claimed
  64. static writeComment = (repo, rec, threadId, author, body) => {
  65. seq = nextSeq(repo.id)
  66. if (seq == null) { return null }
  67. row = { rid = repo.id key = keyOf(repo.id, rec.number) number = rec.number seq = seq thread = threadId author = author body = body created = now() }
  68. id = commentsTable.put(row)
  69. if (id == null) { return null }
  70. return commentsTable.fetch(id)
  71. }
  72. // ---- the PR of a route: the record, or null (unknown number)
  73. static recOf = (repo, nText) => {
  74. n = numberOf(nText)
  75. return n == null ? null : recordByNumber(repo.id, n)
  76. }
  77. // an own thread of this PR, or null (another app's, another PR's, another repo's, unknown: all the same 404)
  78. static threadOf = (app, repo, rec, id) => {
  79. if (id == null || hlTypeName(id) != 'String') { return null }
  80. t = threadsTable.fetch(id)
  81. return t != null && t.rid == repo.id && t.number == rec.number && t.app == app.id ? t : null
  82. }
  83. // ---- pulls ----------------------------------------------------------------------------------------------------------
  84. static listPulls = (repo, q) => {
  85. ensurePulls(repo.slug)
  86. state = q != null && q.state != null ? q.state : 'open'
  87. if (state != 'open' && state != 'all') { return invalid('state must be open or all', [{ field = 'state' }]) }
  88. cursor = q != null && q.cursor != null ? toNumber(q.cursor) : null
  89. if (q != null && q.cursor != null && (cursor == null || cursor < 1)) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }
  90. recs = []
  91. for (r of rowsOf(recordsOf(repo.id))) { if (state == 'all' || r.state == 'open') { recs.push(r) } }
  92. page = pageOf(sortRows(recs, (a, b) => { return a.number > b.number }), limitOf(q), (r) => { return cursor == null || r.number < cursor }, (r) => { return '' + r.number })
  93. pulls = []
  94. for (r of page.items) { pulls.push(pullObject(repo.slug, r.number)) }
  95. return answer(200, { pulls = pulls next = page.next })
  96. }
  97. static getPull = (repo, nText) => {
  98. ensurePulls(repo.slug)
  99. rec = recOf(repo, nText)
  100. if (rec == null) { return notFound('pull request') }
  101. return answer(200, pullObject(repo.slug, rec.number))
  102. }
  103. // ---- reviews --------------------------------------------------------------------------------------------------------
  104. // every complaint about the SHAPE of a review: [{ index, field, reason }] (index = null for the review itself)
  105. static shapeProblems = (input) => {
  106. out = []
  107. if (input.verdict == null || !verdicts.includes(input.verdict)) { out.push({ field = 'verdict' reason = 'must be approve, request_changes or comment' }) }
  108. e = bodyError(input.body, 'body', false)
  109. if (e != null) { out.push({ field = 'body' reason = e }) }
  110. cs = input.comments
  111. if (cs != null && hlTypeName(cs) != 'Hybrid') {
  112. out.push({ field = 'comments' reason = 'must be a list' })
  113. } else if (cs != null) {
  114. if (countOfList(cs) > maxComments) { out.push({ field = 'comments' reason = 'at most ' + maxComments + ' inline comments' }) } else {
  115. let i = 0
  116. while (i < countOfList(cs)) {
  117. c = cs[i]
  118. if (c == null || hlTypeName(c) != 'Hybrid') { out.push({ index = i field = 'comments' reason = 'must be { path, line, body }' }) } else {
  119. if (c.path == null || hlTypeName(c.path) != 'String' || c.path == '') { out.push({ index = i field = 'path' reason = 'path is required' }) }
  120. if (!wholeNumber(c.line)) { out.push({ index = i field = 'line' reason = 'line must be a whole number from 1' }) }
  121. ce = bodyError(c.body, 'body', true)
  122. if (ce != null) { out.push({ index = i field = 'body' reason = ce }) }
  123. }
  124. i = i + 1
  125. }
  126. }
  127. }
  128. return out
  129. }
  130. // the lines the review's comments may use: the diff from the merge-base of the CURRENT target tip and the review's head → { files } or { error }
  131. static diffLines = (slug, rec, head) => {
  132. tip = firstLine(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + rec.target])
  133. mb = tip != '' ? firstLine(slug, ['merge-base', tip, head]) : ''
  134. r = gitRaw(slug, ['diff', '-M', '-U3', mb != '' ? mb : emptyTree, head])
  135. if (r == null || r.exit != 0) { return { error = 'git could not make the diff' } }
  136. return { files = commentable(r.lines) }
  137. }
  138. static postReview = (app, repo, nText, input) => {
  139. ensurePulls(repo.slug)
  140. rec = recOf(repo, nText)
  141. if (rec == null) { return notFound('pull request') }
  142. if (input == null || hlTypeName(input) != 'Hybrid') { return invalid('the body must be a JSON object', null) }
  143. problems = shapeProblems(input)
  144. if (input.head == null || hlTypeName(input.head) != 'String') { problems.push({ field = 'head' reason = 'head is required (a commit sha)' }) }
  145. if (problems.length > 0) { return invalid('the review is malformed', problems) }
  146. if (!headsOf(rec).includes(input.head)) { return failure(409, 'stale_head', 'that sha was never a head of this pull request; the current head is ' + rec.head, null) }
  147. cs = input.comments == null ? [] : input.comments
  148. if (countOfList(cs) > 0) {
  149. d = diffLines(repo.slug, rec, input.head)
  150. if (d.error != null) { return failure(500, 'internal', d.error, null) }
  151. bad = []
  152. let i = 0
  153. while (i < countOfList(cs)) {
  154. lines = d.files[cs[i].path]
  155. if (lines == null) { bad.push({ index = i path = cs[i].path line = cs[i].line reason = 'no_such_file' }) } else if (lines['' + cs[i].line] != true) { bad.push({ index = i path = cs[i].path line = cs[i].line reason = 'line_not_in_diff' }) }
  156. i = i + 1
  157. }
  158. if (bad.length > 0) { return invalid('some inline comments are not on a line of the diff; nothing was stored', bad) }
  159. }
  160. author = authorOfApp(app)
  161. stamp = now()
  162. rid = reviewsTable.put({ rid = repo.id key = keyOf(repo.id, rec.number) number = rec.number app = app.id head = input.head verdict = input.verdict body = input.body == null ? '' : input.body created = stamp })
  163. if (rid == null) { return failure(500, 'internal', 'could not store the review', null) }
  164. made = []
  165. let i = 0
  166. while (i < countOfList(cs)) {
  167. seq = nextSeq(repo.id)
  168. if (seq == null) { return failure(500, 'internal', 'could not number the comment', null) }
  169. tid = threadsTable.put({ rid = repo.id key = keyOf(repo.id, rec.number) number = rec.number app = app.id path = cs[i].path line = cs[i].line head = input.head resolved = false seq = seq created = stamp })
  170. if (tid == null) { return failure(500, 'internal', 'could not store a thread', null) }
  171. commentsTable.put({ rid = repo.id key = keyOf(repo.id, rec.number) number = rec.number seq = seq thread = tid author = author body = cs[i].body created = stamp })
  172. made.push({ id = tid path = cs[i].path line = cs[i].line })
  173. i = i + 1
  174. }
  175. return answer(201, { review = { id = rid verdict = input.verdict head = input.head created = isoMs(stamp) } threads = made })
  176. }
  177. // A null app is a member reader: all reviews, with the same public shape; apps keep their own scope.
  178. static listReviews = (app, repo, nText, q) => {
  179. rec = recOf(repo, nText)
  180. if (rec == null) { return notFound('pull request') }
  181. own = []
  182. for (r of rowsOf(reviewsTable.find('key', keyOf(repo.id, rec.number)))) { if (app == null || r.app == app.id) { own.push(r) } }
  183. // newest first; the same millisecond: the later stored one first (the list is in storage order)
  184. let rows = []
  185. let i = own.length - 1
  186. while (i >= 0) {
  187. rows.push(own[i])
  188. i = i - 1
  189. }
  190. rows = sortRows(rows, (a, b) => { return a.created > b.created })
  191. let cutMs = -1
  192. let cutId = ''
  193. if (q != null && q.cursor != null) {
  194. u = hlTypeName(q.cursor) == 'String' ? q.cursor.indexOf('_') : -1
  195. cutMs = u > 0 ? toNumber(q.cursor.slice(0, u)) : null
  196. if (cutMs == null || u < 0) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }
  197. cutId = q.cursor.slice(u + 1)
  198. }
  199. // after the cursor = older, or the same millisecond and further down the list than the cursor's row
  200. let passed = cutMs < 0
  201. page = pageOf(rows, limitOf(q), (r) => {
  202. if (passed) { return true }
  203. if (r.id == cutId) { passed = true }
  204. return false
  205. }, (r) => { return '' + r.created + '_' + r.id })
  206. out = []
  207. for (r of page.items) { out.push(reviewShape(r)) }
  208. return answer(200, { reviews = out next = page.next })
  209. }
  210. // ---- threads ----------------------------------------------------------------------------------------------------------
  211. // A null app is a member reader: all threads, with the same public shape; apps keep their own scope.
  212. static listThreads = (app, repo, nText, q) => {
  213. rec = recOf(repo, nText)
  214. if (rec == null) { return notFound('pull request') }
  215. cursor = q != null && q.cursor != null ? toNumber(q.cursor) : null
  216. if (q != null && q.cursor != null && (cursor == null || cursor < 1)) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }
  217. own = []
  218. for (t of rowsOf(threadsTable.find('key', keyOf(repo.id, rec.number)))) { if (app == null || t.app == app.id) { own.push(t) } }
  219. page = pageOf(sortRows(own, bySeq), limitOf(q), (t) => { return cursor == null || t.seq > cursor }, (t) => { return '' + t.seq })
  220. out = []
  221. for (t of page.items) { out.push(threadShape(t, rec.head)) }
  222. return answer(200, { threads = out next = page.next })
  223. }
  224. static postReply = (app, repo, nText, threadId, input) => {
  225. rec = recOf(repo, nText)
  226. if (rec == null) { return notFound('pull request') }
  227. t = threadOf(app, repo, rec, threadId)
  228. if (t == null) { return notFound('thread') }
  229. if (input == null || hlTypeName(input) != 'Hybrid') { return invalid('the body must be a JSON object', null) }
  230. e = bodyError(input.body, 'body', true)
  231. if (e != null) { return invalid(e, [{ field = 'body' reason = e }]) }
  232. c = writeComment(repo, rec, t.id, authorOfApp(app), input.body)
  233. if (c == null) { return failure(500, 'internal', 'could not store the comment', null) }
  234. return answer(201, { comment = commentShape(c) })
  235. }
  236. static resolveThread = (app, repo, nText, threadId, input) => {
  237. rec = recOf(repo, nText)
  238. if (rec == null) { return notFound('pull request') }
  239. t = threadOf(app, repo, rec, threadId)
  240. if (t == null) { return notFound('thread') }
  241. if (input == null || hlTypeName(input) != 'Hybrid' || (input.resolved != true && input.resolved != false)) {
  242. return invalid('resolved must be true or false', [{ field = 'resolved' }])
  243. }
  244. u = { id = t.id rid = t.rid key = t.key number = t.number app = t.app path = t.path line = t.line head = t.head resolved = input.resolved seq = t.seq created = t.created }
  245. threadsTable.update(t.id, u)
  246. return answer(200, { thread = threadShape(threadsTable.fetch(t.id), rec.head) })
  247. }
  248. // ---- the conversation --------------------------------------------------------------------------------------------------
  249. static listComments = (repo, nText, q) => {
  250. rec = recOf(repo, nText)
  251. if (rec == null) { return notFound('pull request') }
  252. cursor = q != null && q.cursor != null ? toNumber(q.cursor) : null
  253. if (q != null && q.cursor != null && (cursor == null || cursor < 0)) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }
  254. talk = []
  255. for (c of rowsOf(commentsTable.find('key', keyOf(repo.id, rec.number)))) { if (c.thread == null) { talk.push(c) } }
  256. page = pageOf(sortRows(talk, bySeq), limitOf(q), (c) => { return cursor == null || c.seq > cursor }, (c) => { return '' + c.seq })
  257. out = []
  258. for (c of page.items) { out.push(commentShape(c)) }
  259. return answer(200, { comments = out next = page.next })
  260. }
  261. static postComment = (app, repo, nText, input) => {
  262. rec = recOf(repo, nText)
  263. if (rec == null) { return notFound('pull request') }
  264. if (input == null || hlTypeName(input) != 'Hybrid') { return invalid('the body must be a JSON object', null) }
  265. e = bodyError(input.body, 'body', true)
  266. if (e != null) { return invalid(e, [{ field = 'body' reason = e }]) }
  267. c = writeComment(repo, rec, null, authorOfApp(app), input.body)
  268. if (c == null) { return failure(500, 'internal', 'could not store the comment', null) }
  269. return answer(201, { comment = commentShape(c) })
  270. }
  271. // ---- the current verdict ----------------------------------------------------------------------------------------------------
  272. // the app's standing on a PR → { verdict, head, id, created } or null (no review). It is the app's LATEST approve or request_changes; a `comment` review does not
  273. // clear an earlier request_changes (contract §5), so it only counts when the app has given no approve / request_changes at all. #45 shows it, #46 uses it.
  274. static currentVerdict = (repoId, number, appId) => {
  275. let top = null
  276. let latest = null
  277. for (r of rowsOf(reviewsTable.find('key', keyOf(repoId, number)))) {
  278. if (r.app == appId) {
  279. if (latest == null || r.created >= latest.created) { latest = r }
  280. if (r.verdict != 'comment' && (top == null || r.created >= top.created)) { top = r }
  281. }
  282. }
  283. use = top != null ? top : latest
  284. return use == null ? null : { verdict = use.verdict head = use.head id = use.id created = use.created }
  285. }
  286. // ---- PEOPLE (gitoria#45): what the PR page writes. The caller (lib/prpage.hl) checked who may; these store and number like an app's comment does ----------
  287. static authorOfUser = (u) => { return { type = 'user' id = u.id name = u.name } }
  288. // a person's comment in the conversation → { comment } | { error }
  289. static personComment = (repo, rec, user, body) => {
  290. e = bodyError(body, 'the comment', true)
  291. if (e != null) { return { error = e } }
  292. c = writeComment(repo, rec, null, authorOfUser(user), body)
  293. return c == null ? { error = 'could not store the comment' } : { comment = commentShape(c) }
  294. }
  295. // any thread of this PR (the page shows every app's), or null
  296. static anyThreadOf = (repo, rec, id) => {
  297. if (id == null || hlTypeName(id) != 'String') { return null }
  298. t = threadsTable.fetch(id)
  299. return t != null && t.rid == repo.id && t.number == rec.number ? t : null
  300. }
  301. // a person's reply in a thread → { comment, thread (the stored row) } | { error }
  302. static personReply = (repo, rec, user, threadId, body) => {
  303. t = anyThreadOf(repo, rec, threadId)
  304. if (t == null) { return { error = 'no such thread' } }
  305. e = bodyError(body, 'the reply', true)
  306. if (e != null) { return { error = e } }
  307. c = writeComment(repo, rec, t.id, authorOfUser(user), body)
  308. return c == null ? { error = 'could not store the comment' } : { comment = commentShape(c) thread = t }
  309. }
  310. // resolve / reopen → { thread (row), shape, changed } | { error }
  311. static personResolve = (repo, rec, threadId, resolved) => {
  312. t = anyThreadOf(repo, rec, threadId)
  313. if (t == null) { return { error = 'no such thread' } }
  314. if (resolved != true && resolved != false) { return { error = 'resolved must be true or false' } }
  315. if (t.resolved == resolved) { return { thread = t shape = threadShape(t, rec.head) changed = false } }
  316. threadsTable.update(t.id, { id = t.id rid = t.rid key = t.key number = t.number app = t.app path = t.path line = t.line head = t.head resolved = resolved seq = t.seq created = t.created })
  317. n = threadsTable.fetch(t.id)
  318. return { thread = n shape = threadShape(n, rec.head) changed = true }
  319. }
  320. // everything of one PR for the page, oldest first where it reads as a talk: { reviews (newest first), threads (by seq), talk (conversation by seq) } as stored rows + shapes
  321. static pullTalk = (repo, rec) => {
  322. k = keyOf(repo.id, rec.number)
  323. revs = sortRows(rowsOf(reviewsTable.find('key', k)), (a, b) => { return a.created > b.created })
  324. ths = sortRows(rowsOf(threadsTable.find('key', k)), bySeq)
  325. talk = []
  326. for (c of sortRows(rowsOf(commentsTable.find('key', k)), bySeq)) { if (c.thread == null) { talk.push(commentShape(c)) } }
  327. shapes = []
  328. for (t of ths) { shapes.push({ row = t shape = threadShape(t, rec.head) }) }
  329. return { reviews = revs threads = shapes talk = talk }
  330. }

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