gitoria

gitoria

All repositories: gitoria

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

15.0 KB

  1. // 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").
  2. // Two tables, both keyed by the repo's ID (never the slug), every write to them is here:
  3. // statusRows pk @id index !key, shaKey storage/mpackdb/statuses.db
  4. // { rid, key "<rid> <sha> <appId> <context>", shaKey "<rid> <sha>", sha, context, state pending|success|failure|error, title, summary (≤ 65,536),
  5. // 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.
  6. // 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.
  7. // requiredRows pk @id index !key, rid storage/mpackdb/statusreq.db
  8. // { rid, key "<rid> <appId> <context>", appId, context } the app + context the owner requires before a pull request may be merged (v1.4);
  9. // an entry whose app is gone stays, shows as "(removed app)" and is never met
  10. // listStatuses(repo, sha) the GET route's work (v1.3) → { statuses } or { unknown: true }
  11. // putStatus(repo, app, body) the PUT route's work → { status } or { invalid: [details] } or { unknown: true }
  12. // badgesOf / requirementOf what /pulls shows for a pull request's CURRENT head, and what blocks its Merge button
  13. // missingText(slug, head, number) is the shared app-or-person merge check; app-only requirements keep their existing rule.
  14. import { missingWords, missingMessage } from './statuses-helpers.hl'
  15. import { MPackDB } from 'hl:mpackdb'
  16. import { now, timestamp } from 'hl:time'
  17. import { storageDir, countOfList, firstOf, plainError } from './util.hl'
  18. import { repoBySlug, ownsRepo, mayPush } from './repos.hl'
  19. import { nameOfUser, userRecord } from './users.hl'
  20. import { memberIds, refOfRepo, refOfOrg } from './members.hl'
  21. import { orgBySlug } from './orgs.hl'
  22. import { hasApproval, approvalsOf } from './approvals.hl'
  23. import { appsTable } from './apps-table.hl'
  24. import { gitRaw } from './git.hl'
  25. import { isHexId } from './git-helpers.hl'
  26. static statusRows = new MPackDB(file = storageDir + '/statuses.db', primaryKey = '@id', indexes = ['!key', 'shaKey', 'appId'])
  27. static requiredRows = new MPackDB(file = storageDir + '/statusreq.db', primaryKey = '@id', indexes = ['!key', 'rid'])
  28. static states = ['pending', 'success', 'failure', 'error']
  29. static maxSummary = 65536
  30. static maxRequired = 20
  31. // ---- the PUT --------------------------------------------------------------------------------------------------
  32. // is the sha a commit of this repo? (the object exists and is a commit)
  33. static isCommitOf = (slug, sha) => {
  34. if (sha == null || hlTypeName(sha) != 'String' || sha.length != 40 || !isHexId(sha)) { return false }
  35. r = gitRaw(slug, ['cat-file', '-e', sha + '^{commit}'])
  36. return r != null && r.exit == 0
  37. }
  38. static httpsUrl = (u) => {
  39. return hlTypeName(u) == 'String' && u.length <= 500 && u.startsWith('https://') && u.length > 10 && plainError(u, 500, 'the url') == null && !u.includes(' ')
  40. }
  41. // the body's complaints as contract `details` ([] = fine)
  42. static problems = (j) => {
  43. out = []
  44. if (hlTypeName(j.context) != 'String' || j.context.trim() == '') {
  45. out.push({ field = 'context' reason = 'required' })
  46. } else if (plainError(j.context, 100, 'the context') != null) {
  47. out.push({ field = 'context' reason = 'too_long_or_not_one_line' })
  48. }
  49. if (hlTypeName(j.state) != 'String' || !states.includes(j.state)) { out.push({ field = 'state' reason = 'one_of_pending_success_failure_error' }) }
  50. 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' }) }
  51. if (j.summary != null && (hlTypeName(j.summary) != 'String' || j.summary.length > maxSummary)) { out.push({ field = 'summary' reason = 'text_at_most_65536' }) }
  52. if (j.url != null && !httpsUrl(j.url)) { out.push({ field = 'url' reason = 'https_only' }) }
  53. return out
  54. }
  55. static statusJson = (row) => {
  56. 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) }
  57. }
  58. // 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).
  59. // the row of THIS app for (sha, context): by the new key, else (old shape, key without the app id) by the sha's rows
  60. static ownRow = (rid, sha, appId, ctx) => {
  61. f = firstOf(statusRows.find('key', rid + ' ' + sha + ' ' + appId + ' ' + ctx))
  62. if (f != null) { return f }
  63. for (r of statusesOf(rid, sha)) { if (r.appId == appId && r.context == ctx) { return r } }
  64. return null
  65. }
  66. static putStatus = (Hybrid repo, Hybrid app, String sha, Hybrid j) => {
  67. bad = problems(j)
  68. if (bad.length > 0) { return { invalid = bad } }
  69. if (!isCommitOf(repo.slug, sha)) { return { unknown = true } }
  70. ctx = j.context.trim()
  71. 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() }
  72. old = ownRow(repo.id, sha, app.id, ctx)
  73. if (old != null) { statusRows.update(old.id, row) } else { statusRows.put(row) }
  74. saved = ownRow(repo.id, sha, app.id, ctx)
  75. if (saved == null) { return { invalid = [{ field = 'status' reason = 'could_not_store' }] } }
  76. emit client gitoriaStatusChanged(repo.slug, sha)
  77. return { status = statusJson(saved) }
  78. }
  79. // GET {api}/statuses/<sha> (v1.3): every context on the sha, from every app → { statuses } or { unknown: true } when the repo has no such commit
  80. static listStatuses = (repo, sha) => {
  81. if (!isCommitOf(repo.slug, sha)) { return { unknown = true } }
  82. out = []
  83. for (r of statusesOf(repo.id, sha)) { out.push(statusJson(r)) }
  84. return { statuses = out }
  85. }
  86. // ---- required before merge --------------------------------------------------------------------------------------
  87. static appNameOf = (appId) => {
  88. a = appId == null ? null : appsTable.fetch(appId)
  89. return a == null ? '(removed app)' : a.name
  90. }
  91. // The owner's entries: app + context, or userId (a required person).
  92. static requiredEntries = (repoId) => {
  93. all = requiredRows.find('rid', repoId)
  94. out = []
  95. if (countOfList(all) > 0) { for (r of all) { out.push({ appId = r.appId context = r.context userId = r.userId }) } }
  96. return out
  97. }
  98. // Legacy pull.required remains app + context only. People have their own additive field.
  99. static requiredOf = (repoId) => {
  100. out = []
  101. for (e of requiredEntries(repoId)) {
  102. if (e.userId == null) { out.push({ app = { id = e.appId name = appNameOf(e.appId) } context = e.context }) }
  103. }
  104. return out
  105. }
  106. static approversOf = (String repoId) => {
  107. out = []
  108. for (e of requiredEntries(repoId)) { if (e.userId != null) { out.push({ user = { id = e.userId name = nameOfUser(e.userId) } }) } }
  109. return out
  110. }
  111. // the owner's list for the Settings page: [{ id, name }] with name "App name · context"
  112. static requiredList = (repoId) => {
  113. all = requiredRows.find('rid', repoId)
  114. out = []
  115. 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 }) } }
  116. return out
  117. }
  118. // The selected app's most recently updated status on any commit of this repo.
  119. static latestAppContext = (String repoId, String appId) => {
  120. app = appId == null || appId == '' ? null : appsTable.fetch(appId)
  121. if (app == null || app.repo != repoId) { return '' }
  122. let latest = null
  123. // An app belongs to exactly one repo; the index also covers existing rows.
  124. for (r of statusRows.cursor('appId', appId, ['rid', 'context', 'updatedMs'])) {
  125. if (r.rid == repoId && (latest == null || r.updatedMs > latest.updatedMs)) { latest = r }
  126. }
  127. return latest == null ? '' : latest.context
  128. }
  129. // Plain Settings copy derived from the current entries, also after live list changes.
  130. static requiredRule = (Hybrid rows) => {
  131. let apps = false
  132. let people = false
  133. for (r of rows) { if (r.isPerson) { people = true } else { apps = true } }
  134. if (apps && people) { return 'Merge is allowed when every app check above is success, or one of these people approved the current head.' }
  135. if (people) { return 'Merge needs an approval from one of these people.' }
  136. if (apps) { return 'Merge needs every app check above to be success.' }
  137. return ''
  138. }
  139. // the owner requires app + context → { rows } or { error }. The app is picked by its id (an app of THIS repo).
  140. static requireContext = (userId, session, slug, appId, ctxName) => {
  141. repo = repoBySlug(slug)
  142. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can change what a merge requires' } }
  143. app = appId == null || hlTypeName(appId) != 'String' ? null : appsTable.fetch(appId)
  144. if (app == null || app.repo != repo.id) { return { error = 'pick one of the apps connected to this repository' } }
  145. bad = plainError(ctxName, 100, 'the context')
  146. if (bad != null) { return { error = bad } }
  147. ctx = ('' + ctxName).trim()
  148. if (ctx == '') { return { error = 'give the context the app sets, for example kunibert' } }
  149. key = repo.id + ' ' + app.id + ' ' + ctx
  150. if (firstOf(requiredRows.find('key', key)) != null) { return { rows = requiredList(repo.id) } }
  151. if (requiredEntries(repo.id).length >= maxRequired) { return { error = 'at most ' + maxRequired + ' contexts can be required' } }
  152. id = requiredRows.put({ rid = repo.id key = key appId = app.id context = ctx })
  153. if (id == null) { return { error = 'could not store the setting: ' + requiredRows.lastError() } }
  154. return { rows = requiredList(repo.id) }
  155. }
  156. // Owners select known users with the same push rights used by Merge (including organization members).
  157. static peopleOfRepo = (String slug) => {
  158. repo = repoBySlug(slug)
  159. out = []
  160. if (repo == null) { return out }
  161. ids = [repo.owner]
  162. for (id of memberIds(refOfRepo(slug))) { if (!ids.includes(id)) { ids.push(id) } }
  163. org = orgBySlug(repo.org)
  164. if (org != null) {
  165. if (!ids.includes(org.owner)) { ids.push(org.owner) }
  166. for (id of memberIds(refOfOrg(org.slug))) { if (!ids.includes(id)) { ids.push(id) } }
  167. }
  168. for (id of ids) { if (userRecord(id) != null && mayPush(id, repo)) { out.push({ id = id name = nameOfUser(id) }) } }
  169. return out
  170. }
  171. static requirePerson = (String userId, Hybrid session, String slug, String personId) => {
  172. repo = repoBySlug(slug)
  173. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can change what a merge requires' } }
  174. if (personId == null || !mayPush(personId, repo)) { return { error = 'pick an owner or member of this repository' } }
  175. key = repo.id + ' user ' + personId
  176. if (firstOf(requiredRows.find('key', key)) != null) { return { rows = requiredList(repo.id) } }
  177. if (requiredEntries(repo.id).length >= maxRequired) { return { error = 'at most ' + maxRequired + ' entries can be required' } }
  178. id = requiredRows.put({ rid = repo.id key = key userId = personId })
  179. return id == null ? { error = 'could not store the setting' } : { rows = requiredList(repo.id) }
  180. }
  181. static dropRequired = (userId, session, slug, id) => {
  182. repo = repoBySlug(slug)
  183. if (repo == null || userId == null || !ownsRepo(slug, session)) { return { error = 'only the owner of this repository can change what a merge requires' } }
  184. row = id == null || hlTypeName(id) != 'String' ? null : requiredRows.fetch(id)
  185. if (row == null || row.rid != repo.id) { return { error = 'no such requirement' } }
  186. requiredRows.delete(row.id)
  187. return { rows = requiredList(repo.id) }
  188. }
  189. // ---- what a pull request shows and what blocks it ---------------------------------------------------------------
  190. static statusesOf = (repoId, head) => {
  191. all = statusRows.find('shaKey', repoId + ' ' + head)
  192. return countOfList(all) == 0 ? [] : all
  193. }
  194. // the badge of one status row: its state (class too), "<app>: <context>" and the title as text
  195. static badgeOf = (row) => {
  196. 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 }
  197. }
  198. // Missing alternatives on this PR/head: all app contexts, or any listed person. App-only details keep their old shape.
  199. static missingOf = (String repoId, String head, Number number, Hybrid approvals = null) => {
  200. have = statusesOf(repoId, head)
  201. out = []
  202. people = []
  203. let appCount = 0
  204. let approved = false
  205. repoRows = requiredEntries(repoId)
  206. rows = approvals == null ? approvalsOf(repoId, number) : approvals
  207. for (e of repoRows) {
  208. if (e.userId != null) {
  209. people.push({ id = e.userId name = nameOfUser(e.userId) })
  210. if (hasApproval(rows, e.userId, head)) { approved = true }
  211. continue
  212. }
  213. appCount = appCount + 1
  214. let state = 'missing'
  215. if (e.appId != null && appsTable.fetch(e.appId) != null) {
  216. 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 } }
  217. }
  218. if (state != 'success') { out.push({ app = { id = e.appId name = appNameOf(e.appId) } context = e.context state = state }) }
  219. }
  220. if (people.length > 0) {
  221. if (approved || (appCount > 0 && out.length == 0)) { return [] }
  222. out.push({ approval = { users = people } state = 'missing' })
  223. }
  224. return out
  225. }
  226. // Internal alternatives stay separate from the legacy API detail rows.
  227. static missingDetails = (Hybrid missing) => {
  228. out = []
  229. for (e of missing) { if (e.app != null) { out.push(e) } }
  230. return out
  231. }
  232. static missingApproval = (Hybrid missing) => {
  233. for (e of missing) { if (e.approval != null) { return { users = e.approval.users state = 'missing' } } }
  234. return null
  235. }
  236. static missingText = (String slug, String head, Number number, Hybrid approvals = null) => {
  237. repo = repoBySlug(slug)
  238. return repo == null ? '' : missingMessage(head, missingOf(repo.id, head, number, approvals))
  239. }
  240. // the branch's tip, '' when unknown
  241. static headOf = (slug, branch) => {
  242. if (branch == null || branch == '') { return '' }
  243. r = gitRaw(slug, ['rev-parse', '--verify', '-q', 'refs/heads/' + branch])
  244. return r != null && r.exit == 0 && r.lines.length > 0 && isHexId(r.lines[0]) ? r.lines[0] : ''
  245. }
  246. // the rows of /pulls with `statuses` (badges of the CURRENT head), and the Merge button off while a required context is not success there
  247. static withStatuses = (list, slug) => {
  248. out = []
  249. repo = repoBySlug(slug)
  250. for (p of list) {
  251. q = p
  252. head = repo != null ? headOf(slug, p.source) : ''
  253. badges = []
  254. let blocked = ''
  255. if (head != '') {
  256. for (s of statusesOf(repo.id, head)) { badges.push(badgeOf(s)) }
  257. m = missingOf(repo.id, head, p.number)
  258. if (m.length > 0) { blocked = 'Merge waits for: ' + missingWords(m) }
  259. }
  260. q.statuses = badges
  261. q.hasStatuses = badges.length > 0
  262. q.blockText = blocked
  263. if (blocked != '') {
  264. q.canMerge = false
  265. q.mergeClass = 'nomerge'
  266. }
  267. out.push(q)
  268. }
  269. return out
  270. }

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