gitoria
All repositories: gitoria
15.0 KB
// lib/statuses.hl — THE STATUS OF A COMMIT SET BY AN APP (gitoria#46, part of the push API gitoria#38; contract docs/apps-api.md §5 "Status").// Two tables, both keyed by the repo's ID (never the slug), every write to them is here:// statusRows pk @id index !key, shaKey storage/mpackdb/statuses.db// { rid, key "<rid> <sha> <appId> <context>", shaKey "<rid> <sha>", sha, context, state pending|success|failure|error, title, summary (≤ 65,536),// url (https or null), appId (apps @id), appName, updatedMs } one row per (repo, head sha, APP, context) (v1.4); a newer PUT of the same app replaces only its own.// A row of the old shape (key without the app id, written before v1.4) is found by its shaKey + appId + context and re-keyed by that app's next PUT: no migration.// requiredRows pk @id index !key, rid storage/mpackdb/statusreq.db// { rid, key "<rid> <appId> <context>", appId, context } the app + context the owner requires before a pull request may be merged (v1.4);// an entry whose app is gone stays, shows as "(removed app)" and is never met// listStatuses(repo, sha) the GET route's work (v1.3) → { statuses } or { unknown: true }// putStatus(repo, app, body) the PUT route's work → { status } or { invalid: [details] } or { unknown: true }// badgesOf / requirementOf what /pulls shows for a pull request's CURRENT head, and what blocks its Merge button// missingText(slug, head, number) is the shared app-or-person merge check; app-only requirements keep their existing rule.import { missingWords, missingMessage } from './statuses-helpers.hl'import { MPackDB } from 'hl:mpackdb'import { now, timestamp } from 'hl:time'import { storageDir, countOfList, firstOf, plainError } from './util.hl'import { repoBySlug, ownsRepo, mayPush } from './repos.hl'import { nameOfUser, userRecord } from './users.hl'import { memberIds, refOfRepo, refOfOrg } from './members.hl'import { orgBySlug } from './orgs.hl'import { hasApproval, approvalsOf } from './approvals.hl'import { appsTable } from './apps-table.hl'import { gitRaw } from './git.hl'import { isHexId } from './git-helpers.hl'static statusRows = new MPackDB(file = storageDir + '/statuses.db', primaryKey = '@id', indexes = ['!key', 'shaKey', 'appId'])static requiredRows = new MPackDB(file = storageDir + '/statusreq.db', primaryKey = '@id', indexes = ['!key', 'rid'])static states = ['pending', 'success', 'failure', 'error']static maxSummary = 65536static maxRequired = 20// ---- the PUT --------------------------------------------------------------------------------------------------// is the sha a commit of this repo? (the object exists and is a commit)static isCommitOf = (slug, sha) => {if (sha == null || hlTypeName(sha) != 'String' || sha.length != 40 || !isHexId(sha)) { return false }r = gitRaw(slug, ['cat-file', '-e', sha + '^{commit}'])return r != null && r.exit == 0}static httpsUrl = (u) => {return hlTypeName(u) == 'String' && u.length <= 500 && u.startsWith('https://') && u.length > 10 && plainError(u, 500, 'the url') == null && !u.includes(' ')}// the body's complaints as contract `details` ([] = fine)static problems = (j) => {out = []if (hlTypeName(j.context) != 'String' || j.context.trim() == '') {out.push({ field = 'context' reason = 'required' })} else if (plainError(j.context, 100, 'the context') != null) {out.push({ field = 'context' reason = 'too_long_or_not_one_line' })}if (hlTypeName(j.state) != 'String' || !states.includes(j.state)) { out.push({ field = 'state' reason = 'one_of_pending_success_failure_error' }) }if (j.title != null && (hlTypeName(j.title) != 'String' || plainError(j.title, 200, 'the title') != null)) { out.push({ field = 'title' reason = 'one_line_at_most_200' }) }if (j.summary != null && (hlTypeName(j.summary) != 'String' || j.summary.length > maxSummary)) { out.push({ field = 'summary' reason = 'text_at_most_65536' }) }if (j.url != null && !httpsUrl(j.url)) { out.push({ field = 'url' reason = 'https_only' }) }return out}static statusJson = (row) => {return { head = row.sha sha = row.sha context = row.context state = row.state title = row.title summary = row.summary url = row.url app = { id = row.appId name = row.appName } updated = timestamp(row.updatedMs) }}// PUT {api}/statuses/<sha> for `app` on `repo` (both from appOfRequest). The sha is a path value: anything that is not a commit of the repo is `unknown` (422).// the row of THIS app for (sha, context): by the new key, else (old shape, key without the app id) by the sha's rowsstatic ownRow = (rid, sha, appId, ctx) => {f = firstOf(statusRows.find('key', rid + ' ' + sha + ' ' + appId + ' ' + ctx))if (f != null) { return f }for (r of statusesOf(rid, sha)) { if (r.appId == appId && r.context == ctx) { return r } }return null}static putStatus = (Hybrid repo, Hybrid app, String sha, Hybrid j) => {bad = problems(j)if (bad.length > 0) { return { invalid = bad } }if (!isCommitOf(repo.slug, sha)) { return { unknown = true } }ctx = j.context.trim()row = { rid = repo.id key = repo.id + ' ' + sha + ' ' + app.id + ' ' + ctx shaKey = repo.id + ' ' + sha sha = sha context = ctx state = j.state title = j.title == null ? '' : j.title.trim() summary = j.summary == null ? '' : j.summary url = j.url appId = app.id appName = app.name updatedMs = now() }old = ownRow(repo.id, sha, app.id, ctx)if (old != null) { statusRows.update(old.id, row) } else { statusRows.put(row) }saved = ownRow(repo.id, sha, app.id, ctx)if (saved == null) { return { invalid = [{ field = 'status' reason = 'could_not_store' }] } }emit client gitoriaStatusChanged(repo.slug, sha)return { status = statusJson(saved) }}// GET {api}/statuses/<sha> (v1.3): every context on the sha, from every app → { statuses } or { unknown: true } when the repo has no such commitstatic listStatuses = (repo, sha) => {if (!isCommitOf(repo.slug, sha)) { return { unknown = true } }out = []for (r of statusesOf(repo.id, sha)) { out.push(statusJson(r)) }return { statuses = out }}// ---- required before merge --------------------------------------------------------------------------------------static appNameOf = (appId) => {a = appId == null ? null : appsTable.fetch(appId)return a == null ? '(removed app)' : a.name}// The owner's entries: app + context, or userId (a required person).static requiredEntries = (repoId) => {all = requiredRows.find('rid', repoId)out = []if (countOfList(all) > 0) { for (r of all) { out.push({ appId = r.appId context = r.context userId = r.userId }) } }return out}// Legacy pull.required remains app + context only. People have their own additive field.static requiredOf = (repoId) => {out = []for (e of requiredEntries(repoId)) {if (e.userId == null) { out.push({ app = { id = e.appId name = appNameOf(e.appId) } context = e.context }) }}return out}static approversOf = (String repoId) => {out = []for (e of requiredEntries(repoId)) { if (e.userId != null) { out.push({ user = { id = e.userId name = nameOfUser(e.userId) } }) } }return out}// the owner's list for the Settings page: [{ id, name }] with name "App name · context"static requiredList = (repoId) => {all = requiredRows.find('rid', repoId)out = []if (countOfList(all) > 0) { for (r of all) { out.push({ id = r.id isPerson = r.userId != null name = r.userId != null ? 'Person · ' + nameOfUser(r.userId) : appNameOf(r.appId) + ' · ' + r.context }) } }return out}// The selected app's most recently updated status on any commit of this repo.static latestAppContext = (String repoId, String appId) => {app = appId == null || appId == '' ? null : appsTable.fetch(appId)if (app == null || app.repo != repoId) { return '' }let latest = null// An app belongs to exactly one repo; the index also covers existing rows.for (r of statusRows.cursor('appId', appId, ['rid', 'context', 'updatedMs'])) {if (r.rid == repoId && (latest == null || r.updatedMs > latest.updatedMs)) { latest = r }}return latest == null ? '' : latest.context}// Plain Settings copy derived from the current entries, also after live list changes.static requiredRule = (Hybrid rows) => {let apps = falselet people = falsefor (r of rows) { if (r.isPerson) { people = true } else { apps = true } }if (apps && people) { return 'Merge is allowed when every app check above is success, or one of these people approved the current head.' }if (people) { return 'Merge needs an approval from one of these people.' }if (apps) { return 'Merge needs every app check above to be success.' }return ''}// the owner requires app + context → { rows } or { error }. The app is picked by its id (an app of THIS repo).static requireContext = (userId, session, slug, appId, ctxName) => {repo = repoBySlug(slug)if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can change what a merge requires' } }app = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)if (app == null || app.repo != repo.id) { return { error = 'pick one of the apps connected to this repository' } }bad = plainError(ctxName, 100, 'the context')if (bad != null) { return { error = bad } }ctx = ('' + ctxName).trim()if (ctx == '') { return { error = 'give the context the app sets, for example kunibert' } }key = repo.id + ' ' + app.id + ' ' + ctxif (firstOf(requiredRows.find('key', key)) != null) { return { rows = requiredList(repo.id) } }if (requiredEntries(repo.id).length >= maxRequired) { return { error = 'at most ' + maxRequired + ' contexts can be required' } }id = requiredRows.put({ rid = repo.id key = key appId = app.id context = ctx })if (id == null) { return { error = 'could not store the setting: ' + requiredRows.lastError() } }return { rows = requiredList(repo.id) }}// Owners select known users with the same push rights used by Merge (including organization members).static peopleOfRepo = (String slug) => {repo = repoBySlug(slug)out = []if (repo == null) { return out }ids = [repo.owner]for (id of memberIds(refOfRepo(slug))) { if (!ids.includes(id)) { ids.push(id) } }org = orgBySlug(repo.org)if (org != null) {if (!ids.includes(org.owner)) { ids.push(org.owner) }for (id of memberIds(refOfOrg(org.slug))) { if (!ids.includes(id)) { ids.push(id) } }}for (id of ids) { if (userRecord(id) != null && mayPush(id, repo)) { out.push({ id = id name = nameOfUser(id) }) } }return out}static requirePerson = (String userId, Hybrid session, String slug, String personId) => {repo = repoBySlug(slug)if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can change what a merge requires' } }if (personId == null || !mayPush(personId, repo)) { return { error = 'pick an owner or member of this repository' } }key = repo.id + ' user ' + personIdif (firstOf(requiredRows.find('key', key)) != null) { return { rows = requiredList(repo.id) } }if (requiredEntries(repo.id).length >= maxRequired) { return { error = 'at most ' + maxRequired + ' entries can be required' } }id = requiredRows.put({ rid = repo.id key = key userId = personId })return id == null ? { error = 'could not store the setting' } : { rows = requiredList(repo.id) }}static dropRequired = (userId, session, slug, id) => {repo = repoBySlug(slug)if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can change what a merge requires' } }row = id == null || hlTypeName(id) != 'String' ? null : requiredRows.fetch(id)if (row == null || row.rid != repo.id) { return { error = 'no such requirement' } }requiredRows.delete(row.id)return { rows = requiredList(repo.id) }}// ---- what a pull request shows and what blocks it ---------------------------------------------------------------static statusesOf = (repoId, head) => {all = statusRows.find('shaKey', repoId + ' ' + head)return countOfList(all) == 0 ? [] : all}// the badge of one status row: its state (class too), "<app>: <context>" and the title as textstatic badgeOf = (row) => {return { id = row.id state = row.state cls = 'badge ' + row.state label = row.appName + ': ' + row.context title = row.title hasTitle = row.title != '' url = row.url == null ? '' : row.url hasUrl = row.url != null }}// Missing alternatives on this PR/head: all app contexts, or any listed person. App-only details keep their old shape.static missingOf = (String repoId, String head, Number number, Hybrid approvals = null) => {have = statusesOf(repoId, head)out = []people = []let appCount = 0let approved = falserepoRows = requiredEntries(repoId)rows = approvals == null ? approvalsOf(repoId, number) : approvalsfor (e of repoRows) {if (e.userId != null) {people.push({ id = e.userId name = nameOfUser(e.userId) })if (hasApproval(rows, e.userId, head)) { approved = true }continue}appCount = appCount + 1let state = 'missing'if (e.appId != null && appsTable.fetch(e.appId) != null) {for (s of have) { if (s.appId == e.appId && s.context == e.context && s.state == 'success') { state = 'success' } else if (s.appId == e.appId && s.context == e.context && state == 'missing') { state = s.state } }}if (state != 'success') { out.push({ app = { id = e.appId name = appNameOf(e.appId) } context = e.context state = state }) }}if (people.length > 0) {if (approved || (appCount > 0 && out.length == 0)) { return [] }out.push({ approval = { users = people } state = 'missing' })}return out}// Internal alternatives stay separate from the legacy API detail rows.static missingDetails = (Hybrid missing) => {out = []for (e of missing) { if (e.app != null) { out.push(e) } }return out}static missingApproval = (Hybrid missing) => {for (e of missing) { if (e.approval != null) { return { users = e.approval.users state = 'missing' } } }return null}static missingText = (String slug, String head, Number number, Hybrid approvals = null) => {repo = repoBySlug(slug)return repo == null ? '' : missingMessage(head, missingOf(repo.id, head, number, approvals))}// the branch's tip, '' when unknownstatic headOf = (slug, branch) => {if (branch == null || branch == '') { return '' }r = gitRaw(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + branch])return r != null && r.exit == 0 && r.lines.length > 0 && isHexId(r.lines[0]) ? r.lines[0] : ''}// the rows of /pulls with `statuses` (badges of the CURRENT head), and the Merge button off while a required context is not success therestatic withStatuses = (list, slug) => {out = []repo = repoBySlug(slug)for (p of list) {q = phead = repo != null ? headOf(slug, p.source) : ''badges = []let blocked = ''if (head != '') {for (s of statusesOf(repo.id, head)) { badges.push(badgeOf(s)) }m = missingOf(repo.id, head, p.number)if (m.length > 0) { blocked = 'Merge waits for: ' + missingWords(m) }}q.statuses = badgesq.hasStatuses = badges.length > 0q.blockText = blockedif (blocked != '') {q.canMerge = falseq.mergeClass = 'nomerge'}out.push(q)}return out}
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