gitoria
All repositories: gitoria
19.7 KB
// 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).// Three tables, all keyed by the repo's ID and the PR number (never the slug: a repo can be renamed), storage/mpackdb/*.db:// reviewsTable pk @id index key, app { rid, key "<rid>#<n>", number, app (apps @id), head, verdict approve|request_changes|comment, body, created (ms) }// 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 }// 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) }// 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// 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>`// (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// 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// that reads exactly in that window can pass it by. The folders stay (one empty folder per comment).// Entry points (lib/api.hl is a thin wrapper): listPulls, getPull, postReview, listReviews, listThreads, postReply, resolveThread, listComments, postComment,// 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).import { MPackDB } from 'hl:mpackdb'import { now } from 'hl:time'import { run } from 'hl:proc'import { mkDir } from 'hl:fs'import { storageDir, countOfList, firstOf } from './util.hl'import { gitRaw } from './git.hl'import { ensurePulls, pullObject, recordByNumber, recordsOf, headsOf, firstLine } from './pullsync.hl'import { answer, failure, notFound, invalid, isoMs, bodyError, wholeNumber, numberOf, limitOf, sortRows, pageOf, commentable, maxBody, maxComments } from './reviews-helpers.hl'static reviewsTable = new MPackDB(file = storageDir + '/reviews.db', primaryKey = '@id', indexes = ['key', 'app'])static threadsTable = new MPackDB(file = storageDir + '/threads.db', primaryKey = '@id', indexes = ['key', 'app'])static commentsTable = new MPackDB(file = storageDir + '/comments.db', primaryKey = '@id', indexes = ['key', 'rid', 'thread'])static seqDir = storageDir + '/seq'static seqSeen = {}static emptyTree = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'static verdicts = ['approve', 'request_changes', 'comment']static rowsOf = (list) => { return countOfList(list) == 0 ? [] : list }static keyOf = (rid, n) => { return rid + '#' + n }static authorOfApp = (app) => { return { type = 'app' id = app.id name = app.name } }// ---- seq -----------------------------------------------------------------------------------------------------static topSeq = (rid) => {let top = 0for (c of rowsOf(commentsTable.find('rid', rid))) { if (c.seq > top) { top = c.seq } }return top}// the next number of the repo, claimed with mkdir; null when it cannot be claimedstatic nextSeq = (rid) => {let n = seqSeen[rid] != null ? seqSeen[rid] : topSeq(rid)mkDir(seqDir, 448)mkDir(seqDir + '/' + rid, 448)let tries = 0while (tries < 1000) {n = n + 1tries = tries + 1r = run(['mkdir', seqDir + '/' + rid + '/' + n])if (r != null && r.exit == 0) {seqSeen[rid] = nreturn n}}return null}// ---- shapes ----------------------------------------------------------------------------------------------------static commentShape = (c) => { return { id = c.id seq = c.seq author = c.author body = c.body created = isoMs(c.created) } }static bySeq = (a, b) => { return a.seq < b.seq }static threadShape = (t, current) => {cs = []for (c of sortRows(rowsOf(commentsTable.find('thread', t.id)), bySeq)) { cs.push(commentShape(c)) }return { id = t.id path = t.path line = t.line head = t.head outdated = t.head != current resolved = t.resolved comments = cs }}static reviewShape = (r) => { return { id = r.id verdict = r.verdict head = r.head body = r.body created = isoMs(r.created) } }// a comment written into a thread (or the conversation when threadId is null) → the stored row, or null when no seq could be claimedstatic writeComment = (repo, rec, threadId, author, body) => {seq = nextSeq(repo.id)if (seq == null) { return null }row = { rid = repo.id key = keyOf(repo.id, rec.number) number = rec.number seq = seq thread = threadId author = author body = body created = now() }id = commentsTable.put(row)if (id == null) { return null }return commentsTable.fetch(id)}// ---- the PR of a route: the record, or null (unknown number)static recOf = (repo, nText) => {n = numberOf(nText)return n == null ? null : recordByNumber(repo.id, n)}// an own thread of this PR, or null (another app's, another PR's, another repo's, unknown: all the same 404)static threadOf = (app, repo, rec, id) => {if (id == null || hlTypeName(id) != 'String') { return null }t = threadsTable.fetch(id)return t != null && t.rid == repo.id && t.number == rec.number && t.app == app.id ? t : null}// ---- pulls ----------------------------------------------------------------------------------------------------------static listPulls = (repo, q) => {ensurePulls(repo.slug)state = q != null && q.state != null ? q.state : 'open'if (state != 'open' && state != 'all') { return invalid('state must be open or all', [{ field = 'state' }]) }cursor = q != null && q.cursor != null ? toNumber(q.cursor) : nullif (q != null && q.cursor != null && (cursor == null || cursor < 1)) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }recs = []for (r of rowsOf(recordsOf(repo.id))) { if (state == 'all' || r.state == 'open') { recs.push(r) } }page = pageOf(sortRows(recs, (a, b) => { return a.number > b.number }), limitOf(q), (r) => { return cursor == null || r.number < cursor }, (r) => { return '' + r.number })pulls = []for (r of page.items) { pulls.push(pullObject(repo.slug, r.number)) }return answer(200, { pulls = pulls next = page.next })}static getPull = (repo, nText) => {ensurePulls(repo.slug)rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }return answer(200, pullObject(repo.slug, rec.number))}// ---- reviews --------------------------------------------------------------------------------------------------------// every complaint about the SHAPE of a review: [{ index, field, reason }] (index = null for the review itself)static shapeProblems = (input) => {out = []if (input.verdict == null || !verdicts.includes(input.verdict)) { out.push({ field = 'verdict' reason = 'must be approve, request_changes or comment' }) }e = bodyError(input.body, 'body', false)if (e != null) { out.push({ field = 'body' reason = e }) }cs = input.commentsif (cs != null && hlTypeName(cs) != 'Hybrid') {out.push({ field = 'comments' reason = 'must be a list' })} else if (cs != null) {if (countOfList(cs) > maxComments) { out.push({ field = 'comments' reason = 'at most ' + maxComments + ' inline comments' }) } else {let i = 0while (i < countOfList(cs)) {c = cs[i]if (c == null || hlTypeName(c) != 'Hybrid') { out.push({ index = i field = 'comments' reason = 'must be { path, line, body }' }) } else {if (c.path == null || hlTypeName(c.path) != 'String' || c.path == '') { out.push({ index = i field = 'path' reason = 'path is required' }) }if (!wholeNumber(c.line)) { out.push({ index = i field = 'line' reason = 'line must be a whole number from 1' }) }ce = bodyError(c.body, 'body', true)if (ce != null) { out.push({ index = i field = 'body' reason = ce }) }}i = i + 1}}}return out}// 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 }static diffLines = (slug, rec, head) => {tip = firstLine(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + rec.target])mb = tip != '' ? firstLine(slug, ['merge-base', tip, head]) : ''r = gitRaw(slug, ['diff', '-M', '-U3', mb != '' ? mb : emptyTree, head])if (r == null || r.exit != 0) { return { error = 'git could not make the diff' } }return { files = commentable(r.lines) }}static postReview = (app, repo, nText, input) => {ensurePulls(repo.slug)rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }if (input == null || hlTypeName(input) != 'Hybrid') { return invalid('the body must be a JSON object', null) }problems = shapeProblems(input)if (input.head == null || hlTypeName(input.head) != 'String') { problems.push({ field = 'head' reason = 'head is required (a commit sha)' }) }if (problems.length > 0) { return invalid('the review is malformed', problems) }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) }cs = input.comments == null ? [] : input.commentsif (countOfList(cs) > 0) {d = diffLines(repo.slug, rec, input.head)if (d.error != null) { return failure(500, 'internal', d.error, null) }bad = []let i = 0while (i < countOfList(cs)) {lines = d.files[cs[i].path]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' }) }i = i + 1}if (bad.length > 0) { return invalid('some inline comments are not on a line of the diff; nothing was stored', bad) }}author = authorOfApp(app)stamp = now()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 })if (rid == null) { return failure(500, 'internal', 'could not store the review', null) }made = []let i = 0while (i < countOfList(cs)) {seq = nextSeq(repo.id)if (seq == null) { return failure(500, 'internal', 'could not number the comment', null) }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 })if (tid == null) { return failure(500, 'internal', 'could not store a thread', null) }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 })made.push({ id = tid path = cs[i].path line = cs[i].line })i = i + 1}return answer(201, { review = { id = rid verdict = input.verdict head = input.head created = isoMs(stamp) } threads = made })}// A null app is a member reader: all reviews, with the same public shape; apps keep their own scope.static listReviews = (app, repo, nText, q) => {rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }own = []for (r of rowsOf(reviewsTable.find('key', keyOf(repo.id, rec.number)))) { if (app == null || r.app == app.id) { own.push(r) } }// newest first; the same millisecond: the later stored one first (the list is in storage order)let rows = []let i = own.length - 1while (i >= 0) {rows.push(own[i])i = i - 1}rows = sortRows(rows, (a, b) => { return a.created > b.created })let cutMs = -1let cutId = ''if (q != null && q.cursor != null) {u = hlTypeName(q.cursor) == 'String' ? q.cursor.indexOf('_') : -1cutMs = u > 0 ? toNumber(q.cursor.slice(0, u)) : nullif (cutMs == null || u < 0) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }cutId = q.cursor.slice(u + 1)}// after the cursor = older, or the same millisecond and further down the list than the cursor's rowlet passed = cutMs < 0page = pageOf(rows, limitOf(q), (r) => {if (passed) { return true }if (r.id == cutId) { passed = true }return false}, (r) => { return '' + r.created + '_' + r.id })out = []for (r of page.items) { out.push(reviewShape(r)) }return answer(200, { reviews = out next = page.next })}// ---- threads ----------------------------------------------------------------------------------------------------------// A null app is a member reader: all threads, with the same public shape; apps keep their own scope.static listThreads = (app, repo, nText, q) => {rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }cursor = q != null && q.cursor != null ? toNumber(q.cursor) : nullif (q != null && q.cursor != null && (cursor == null || cursor < 1)) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }own = []for (t of rowsOf(threadsTable.find('key', keyOf(repo.id, rec.number)))) { if (app == null || t.app == app.id) { own.push(t) } }page = pageOf(sortRows(own, bySeq), limitOf(q), (t) => { return cursor == null || t.seq > cursor }, (t) => { return '' + t.seq })out = []for (t of page.items) { out.push(threadShape(t, rec.head)) }return answer(200, { threads = out next = page.next })}static postReply = (app, repo, nText, threadId, input) => {rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }t = threadOf(app, repo, rec, threadId)if (t == null) { return notFound('thread') }if (input == null || hlTypeName(input) != 'Hybrid') { return invalid('the body must be a JSON object', null) }e = bodyError(input.body, 'body', true)if (e != null) { return invalid(e, [{ field = 'body' reason = e }]) }c = writeComment(repo, rec, t.id, authorOfApp(app), input.body)if (c == null) { return failure(500, 'internal', 'could not store the comment', null) }return answer(201, { comment = commentShape(c) })}static resolveThread = (app, repo, nText, threadId, input) => {rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }t = threadOf(app, repo, rec, threadId)if (t == null) { return notFound('thread') }if (input == null || hlTypeName(input) != 'Hybrid' || (input.resolved != true && input.resolved != false)) {return invalid('resolved must be true or false', [{ field = 'resolved' }])}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 }threadsTable.update(t.id, u)return answer(200, { thread = threadShape(threadsTable.fetch(t.id), rec.head) })}// ---- the conversation --------------------------------------------------------------------------------------------------static listComments = (repo, nText, q) => {rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }cursor = q != null && q.cursor != null ? toNumber(q.cursor) : nullif (q != null && q.cursor != null && (cursor == null || cursor < 0)) { return invalid('cursor is not one we gave out', [{ field = 'cursor' }]) }talk = []for (c of rowsOf(commentsTable.find('key', keyOf(repo.id, rec.number)))) { if (c.thread == null) { talk.push(c) } }page = pageOf(sortRows(talk, bySeq), limitOf(q), (c) => { return cursor == null || c.seq > cursor }, (c) => { return '' + c.seq })out = []for (c of page.items) { out.push(commentShape(c)) }return answer(200, { comments = out next = page.next })}static postComment = (app, repo, nText, input) => {rec = recOf(repo, nText)if (rec == null) { return notFound('pull request') }if (input == null || hlTypeName(input) != 'Hybrid') { return invalid('the body must be a JSON object', null) }e = bodyError(input.body, 'body', true)if (e != null) { return invalid(e, [{ field = 'body' reason = e }]) }c = writeComment(repo, rec, null, authorOfApp(app), input.body)if (c == null) { return failure(500, 'internal', 'could not store the comment', null) }return answer(201, { comment = commentShape(c) })}// ---- the current verdict ----------------------------------------------------------------------------------------------------// 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// 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.static currentVerdict = (repoId, number, appId) => {let top = nulllet latest = nullfor (r of rowsOf(reviewsTable.find('key', keyOf(repoId, number)))) {if (r.app == appId) {if (latest == null || r.created >= latest.created) { latest = r }if (r.verdict != 'comment' && (top == null || r.created >= top.created)) { top = r }}}use = top != null ? top : latestreturn use == null ? null : { verdict = use.verdict head = use.head id = use.id created = use.created }}// ---- 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 ----------static authorOfUser = (u) => { return { type = 'user' id = u.id name = u.name } }// a person's comment in the conversation → { comment } | { error }static personComment = (repo, rec, user, body) => {e = bodyError(body, 'the comment', true)if (e != null) { return { error = e } }c = writeComment(repo, rec, null, authorOfUser(user), body)return c == null ? { error = 'could not store the comment' } : { comment = commentShape(c) }}// any thread of this PR (the page shows every app's), or nullstatic anyThreadOf = (repo, rec, id) => {if (id == null || hlTypeName(id) != 'String') { return null }t = threadsTable.fetch(id)return t != null && t.rid == repo.id && t.number == rec.number ? t : null}// a person's reply in a thread → { comment, thread (the stored row) } | { error }static personReply = (repo, rec, user, threadId, body) => {t = anyThreadOf(repo, rec, threadId)if (t == null) { return { error = 'no such thread' } }e = bodyError(body, 'the reply', true)if (e != null) { return { error = e } }c = writeComment(repo, rec, t.id, authorOfUser(user), body)return c == null ? { error = 'could not store the comment' } : { comment = commentShape(c) thread = t }}// resolve / reopen → { thread (row), shape, changed } | { error }static personResolve = (repo, rec, threadId, resolved) => {t = anyThreadOf(repo, rec, threadId)if (t == null) { return { error = 'no such thread' } }if (resolved != true && resolved != false) { return { error = 'resolved must be true or false' } }if (t.resolved == resolved) { return { thread = t shape = threadShape(t, rec.head) changed = false } }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 })n = threadsTable.fetch(t.id)return { thread = n shape = threadShape(n, rec.head) changed = true }}// 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 + shapesstatic pullTalk = (repo, rec) => {k = keyOf(repo.id, rec.number)revs = sortRows(rowsOf(reviewsTable.find('key', k)), (a, b) => { return a.created > b.created })ths = sortRows(rowsOf(threadsTable.find('key', k)), bySeq)talk = []for (c of sortRows(rowsOf(commentsTable.find('key', k)), bySeq)) { if (c.thread == null) { talk.push(commentShape(c)) } }shapes = []for (t of ths) { shapes.push({ row = t shape = threadShape(t, rec.head) }) }return { reviews = revs threads = shapes talk = talk }}
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