gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commiteb7aeeb9eb7aeeb9mission brief 016mreeb7aeeb9/lib/tickets.hl

27.7 KB

  1. // lib/tickets.hl — TICKETS AND THEIR RELATIONS: the central logic of tickets.worldapi.org. Statics only, the server realm.
  2. // A face / an API route (components/, lib/api.hl) checks the session or token and calls one function here; every
  3. // write answers the rows the push carries.
  4. //
  5. // CREATOR'S CONVENTIONS (2026-09-24, ticket #38): every primary key is the mpackdb UUID
  6. // (`@id`, a string like '0mufbkwhlpjq'), never a `*id` counter; the files live in
  7. // storage/mpackdb/. A NUMBER A PERSON SEES is a separate field: tickets are numbered PER
  8. // PROJECT from 1 (`number`); tickets migrated from the old global store keep their old
  9. // global number as `oldNumber` (docs and comments say "#38"). Order never comes from key
  10. // order: lists sort by the stored times, a history by (created, seq).
  11. //
  12. // ticketsTable pk @id index project state source !path *oldNumber
  13. // { project (project @id — NOT the name), number, path ('<project @id>/<number>', unique),
  14. // oldNumber?, subject, summary, state, source, created, updated, events,
  15. // createdBy (users @id, '' = opened before the login), assignee (users @id, '') }
  16. // linksTable pk @id index @ticket @other (ticket #4, mission 017) { kind, ticket, other, user, created }
  17. // kind 'parent': `ticket` is a child of `other` (at most one per ticket)
  18. // kind 'blockedBy': `ticket` is blocked by `other` (waits on it)
  19. // A removed relation is deleted here; the history keeps it ('link' events, lib/events.hl).
  20. // Every write appends its event to the history (events.hl putEvent) and stores the ticket with the new
  21. // `events` count / `updated`; then the event stream numbers it and tells the listening programs (stream.hl
  22. // recordEvent, ticket #26). Projects, members and roles: lib/projects.hl; state names and page shapes:
  23. // lib/tickets-helpers.hl.
  24. //
  25. // WHO MAY is the role in the ticket's project (projects.hl): a refusal for a missing right has
  26. // `forbidden = true` (the API answers 403). EVERY WRITE HAS A USER (ticket #7): the logged-in user of the
  27. // web session or of the API token (users.hl). `source` is the import key (the ticket file's name) — an
  28. // import with a known source is answered with the existing ticket, never a second one.
  29. //
  30. // reading ticketRowOf, ticketRecord / ticketAt / ticketByRef / ticketByKey, ticketRows, inboxRows,
  31. // eventRows, ticketWithEvents, stateChoices, ticketRights
  32. // writing createTicket, addComment, changeState, assignTicket, editTicket, removeMember
  33. // relations relationsOf, relatedViews, setParent, changeBlocker
  34. import { MPackDB } from 'hl:mpackdb'
  35. import { now } from 'hl:time'
  36. import { storageDir, countOf, first, merged, clean, isDigits, localStamp, newestFirst, oldestFirst, ticketHref, ticketApiHref, projectHrefOf } from './util.hl'
  37. import { nameOfUser } from './users.hl'
  38. import { projectRecord, projectByAnySlug, projectByRef, projectSlugOf, roleOf, rankOf, isMember, mayEditIn, memberRecord, memberRows, userByRef, assignChoices, userOk, authorMissing, removeMembership } from './projects.hl'
  39. import { states, inboxStates, stateOf, slugOf, refOf, keyOf, relationViewOf } from './tickets-helpers.hl'
  40. import { putEvent, eventsError, eventRowAt, historyOf, creatorNameOf } from './events.hl'
  41. import { recordEvent } from './stream.hl'
  42. static ticketsTable = new MPackDB(file = storageDir + '/tickets.db', primaryKey = '@id', indexes = ['project', 'state', 'source', '!path', '*oldNumber'])
  43. static linksTable = new MPackDB(file = storageDir + '/links.db', primaryKey = '@id', indexes = ['@ticket', '@other'])
  44. // ---- the shapes a page and the API show ---------------------------------------------
  45. // A ROW IS A PLAIN HYBRID: what the View reads is what the browser receives.
  46. // `id` is the UUID; `number` + `project` (the slug) are what a person uses; `oldNumber` / `oldRef`
  47. // only on tickets migrated from the global numbering.
  48. static ticketRowOf = (t) => {
  49. n = t.events != null ? t.events : 0
  50. p = projectRecord(t.project)
  51. slug = p != null ? p.slug : ''
  52. byId = t.createdBy != null ? t.createdBy : ''
  53. toId = t.assignee != null ? t.assignee : ''
  54. row = {
  55. id = t.id
  56. project = slug
  57. projectId = t.project
  58. projectTitle = p != null ? p.title : ''
  59. number = t.number
  60. ref = '#' + t.number
  61. subject = t.subject
  62. summary = t.summary
  63. state = t.state
  64. stateSlug = slugOf(t.state)
  65. source = t.source != null ? t.source : ''
  66. created = localStamp(t.created)
  67. createdMs = t.created
  68. updated = localStamp(t.updated)
  69. updatedMs = t.updated
  70. events = n
  71. href = ticketHref(slug, t.number)
  72. apiHref = ticketApiHref(slug, t.number)
  73. projectHref = projectHrefOf(slug)
  74. hasOld = t.oldNumber != null
  75. oldRef = t.oldNumber != null ? '#' + t.oldNumber : ''
  76. createdById = byId
  77. createdBy = byId != '' ? nameOfUser(byId) : creatorNameOf(t)
  78. assigneeId = toId
  79. assignee = toId != '' ? nameOfUser(toId) : ''
  80. hasAssignee = toId != ''
  81. }
  82. if (t.oldNumber != null) { row.oldNumber = t.oldNumber }
  83. // ticket #4 (mission 017): the relations, as refs with their states (relationsOf below)
  84. rel = relationsOf(t)
  85. row.parent = rel.parent
  86. row.children = rel.children
  87. row.allChildrenConfirmed = rel.allChildrenConfirmed
  88. row.blockedBy = rel.blockedBy
  89. row.blocks = rel.blocks
  90. return row
  91. }
  92. // ---- finding a ticket -------------------------------------------------------------------
  93. static ticketRecord = (uuid) => { return uuid == null || uuid == '' ? null : ticketsTable.fetch('' + uuid) }
  94. // `project` is a slug (a former one too)
  95. static ticketAt = (project, number) => {
  96. if (project == null || !isDigits(number)) { return null }
  97. p = projectByAnySlug(project)
  98. if (p == null) { return null }
  99. return first(ticketsTable.find('path', p.id + '/' + toNumber('' + number)))
  100. }
  101. static ticketByOld = (oldNumber) => {
  102. if (!isDigits(oldNumber)) { return null }
  103. return first(ticketsTable.find('oldNumber', toNumber('' + oldNumber)))
  104. }
  105. // what `/api/tickets/:ref` and `/tickets/:ref` accept: the OLD global number (digits)
  106. // or the ticket's UUID
  107. static ticketByRef = (ref) => {
  108. if (ref == null) { return null }
  109. if (isDigits(ref)) { return ticketByOld(ref) }
  110. return ticketRecord(ref)
  111. }
  112. // ---- reads -------------------------------------------------------------------------
  113. // newest update first; both filters optional (null = all); `project` is a slug
  114. static ticketRows = (project, state) => {
  115. rows = []
  116. let all = null
  117. if (project != null) {
  118. p = projectByAnySlug(project)
  119. if (p == null) { return rows }
  120. all = ticketsTable.find('project', p.id)
  121. } else {
  122. all = ticketsTable.find(null, null)
  123. }
  124. if (countOf(all) == 0) { return rows }
  125. for (t of all) {
  126. if (state == null || t.state == state) { rows.push(ticketRowOf(t)) }
  127. }
  128. return newestFirst(rows, 'updatedMs')
  129. }
  130. // THE INBOX of a user: the tickets ASSIGNED TO THEM in pending and in review, two lists
  131. static inboxRows = (user) => {
  132. out = { pending = [] review = [] }
  133. if (user == null || user.id == null) { return out }
  134. a = []
  135. b = []
  136. ps = ticketsTable.find('state', 'pending')
  137. if (countOf(ps) > 0) { for (t of ps) { if (t.assignee == user.id) { a.push(ticketRowOf(t)) } } }
  138. rs = ticketsTable.find('state', 'review')
  139. if (countOf(rs) > 0) { for (t of rs) { if (t.assignee == user.id) { b.push(ticketRowOf(t)) } } }
  140. out.pending = newestFirst(a, 'updatedMs')
  141. out.review = newestFirst(b, 'updatedMs')
  142. return out
  143. }
  144. static inboxCountOf = (user) => {
  145. x = inboxRows(user)
  146. return x.pending.length + x.review.length
  147. }
  148. // the page's row of `/<project>/<number>` (ticket #25), or null
  149. static ticketRowAt = (project, number) => {
  150. t = ticketAt(project, number)
  151. return t == null ? null : ticketRowOf(t)
  152. }
  153. // the event history of a ticket (UUID), oldest first (events.hl historyOf)
  154. static eventRows = (ticketId) => {
  155. t = ticketRecord(ticketId)
  156. if (t == null) { return [] }
  157. return historyOf(t)
  158. }
  159. // the options of a state select: [{ value, label }] — the states THIS user may move the ticket to
  160. // (a `use` member: only open ⇄ review; `edit` / `admin`: every other state)
  161. static stateChoices = (t, user) => {
  162. out = []
  163. if (t == null || user == null) { return out }
  164. role = roleOf(t.project, user)
  165. for (s of states) {
  166. if (s != t.state && mayMoveTo(role, t.state, s)) { out.push({ value = s label = s }) }
  167. }
  168. return out
  169. }
  170. static mayMoveTo = (role, current, target) => {
  171. if (rankOf(role) >= 2) { return true }
  172. if (rankOf(role) == 1) { return (current == 'open' && target == 'review') || (current == 'review' && target == 'open') }
  173. return false
  174. }
  175. // what a user may do on a ticket (a record): comment (a member), edit / assign (edit, admin), the states they
  176. // may move it to, and the members it can be assigned to — the ticket page asks after a login or a change
  177. static ticketRights = (t, user) => {
  178. return { comment = isMember(t.project, user) edit = mayEdit(t, user) options = stateChoices(t, user) members = assignChoices(t.project) }
  179. }
  180. // ---- writes: each answers what the push carries --------------------------------------
  181. // The author is the user — there is no free author field any more.
  182. // the next per-project number: the highest one in the project + 1 (first = 1)
  183. static nextNumber = (projectId) => {
  184. let top = 0
  185. all = ticketsTable.find('project', projectId)
  186. if (countOf(all) > 0) {
  187. for (t of all) { if (t.number != null && t.number > top) { top = t.number } }
  188. }
  189. return top + 1
  190. }
  191. // answers { error, field, forbidden? } or { ticket (row), event (row), existed }
  192. // `project` = the slug (or id) of an existing project; `assignee` optional (a member's name / id)
  193. static createTicket = (project, subject, summary, user, source, assignee) => {
  194. s = clean(subject)
  195. if (clean(project) == '') { return { error = 'project is required' field = 'project' } }
  196. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  197. if (!userOk(user)) { return authorMissing }
  198. p = projectByRef(clean(project))
  199. if (p == null) { return { error = 'no such project: ' + clean(project) field = 'project' } }
  200. if (!mayEditIn(p.id, user)) { return { error = 'you need the role edit or admin in ' + p.slug + ' to open a ticket' field = 'project' forbidden = true } }
  201. let who = ''
  202. if (assignee != null && clean(assignee) != '') {
  203. r = userByRef(assignee, p.id)
  204. if (r.error != null) { return { error = r.error field = 'assignee' } }
  205. who = r.user.id
  206. }
  207. src = clean(source)
  208. if (src != '') {
  209. known = ticketsTable.find('source', src)
  210. if (countOf(known) > 0) { return { ticket = ticketRowOf(known[0]) event = null existed = true } }
  211. }
  212. t0 = now()
  213. n = nextNumber(p.id)
  214. id = ticketsTable.put({ project = p.id number = n path = p.id + '/' + n subject = s summary = clean(summary) state = 'open' source = src created = t0 updated = t0 events = 1 createdBy = user.id assignee = who })
  215. if (id == null) { return { error = 'could not store the ticket: ' + ticketsTable.lastError() field = '' } }
  216. t = ticketsTable.fetch(id)
  217. eid = putEvent({ ticket = id seq = 1 kind = 'created' author = user.name user = user.id text = src != '' ? 'imported from ' + src : '' created = t0 })
  218. out = { ticket = ticketRowOf(t) event = eventRowAt(eid, t) existed = false }
  219. if (who != '') {
  220. let seq = 2
  221. aid = putEvent({ ticket = id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = '' created = t0 })
  222. ticketsTable.update(id, merged(t, { events = seq }))
  223. t2 = ticketsTable.fetch(id)
  224. out.ticket = ticketRowOf(t2)
  225. out.assignEvent = eventRowAt(aid, t2)
  226. recordEvent(eid, t2)
  227. recordEvent(aid, t2)
  228. } else {
  229. recordEvent(eid, t)
  230. }
  231. return out
  232. }
  233. // answers { error } or { ticket, event }; `ticketId` is the UUID. Any member may comment.
  234. static addComment = (ticketId, user, text) => {
  235. t = ticketRecord(ticketId)
  236. if (t == null) { return { error = 'no such ticket' } }
  237. body = clean(text)
  238. if (body == '') { return { error = 'a comment needs text' field = 'text' } }
  239. if (!userOk(user)) { return authorMissing }
  240. if (!isMember(t.project, user)) { return { error = 'only a member of the project can comment' field = '' forbidden = true } }
  241. t0 = now()
  242. let seq = (t.events != null ? t.events : 0) + 1
  243. eid = putEvent({ ticket = t.id seq = seq kind = 'comment' author = user.name user = user.id text = body created = t0 })
  244. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  245. t2 = ticketsTable.fetch(t.id)
  246. recordEvent(eid, t2)
  247. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  248. }
  249. // the admin who gets a ticket that lands in the inbox with nobody assigned: the oldest admin
  250. static defaultAssignee = (projectId) => {
  251. for (m of memberRows(projectId)) { if (m.role == 'admin') { return m.user } }
  252. return ''
  253. }
  254. // answers { error } or { ticket, event, assignEvent? }; an optional note rides on the state event.
  255. // `forbidden = true` on a refusal the user may not overcome (the role does not allow that move).
  256. // A ticket that goes to review / pending with nobody assigned is assigned to the project's first admin
  257. // (so it reaches an inbox) — a second, 'assign' event.
  258. static changeState = (ticketId, state, user, note) => {
  259. t = ticketRecord(ticketId)
  260. if (t == null) { return { error = 'no such ticket' } }
  261. s = stateOf(state)
  262. if (s == null) { return { error = 'unknown state — one of: ' + states.join(', ') field = 'state' } }
  263. if (s == t.state) { return { error = 'the ticket is already ' + s field = 'state' } }
  264. if (!userOk(user)) { return authorMissing }
  265. role = roleOf(t.project, user)
  266. if (role == null) { return { error = 'only a member of the project can change the state' field = 'state' forbidden = true } }
  267. if (!mayMoveTo(role, t.state, s)) { return { error = 'the role ' + role + ' can only move a ticket between open and review' field = 'state' forbidden = true } }
  268. t0 = now()
  269. let seq = (t.events != null ? t.events : 0) + 1
  270. eid = putEvent({ ticket = t.id seq = seq kind = 'state' author = user.name user = user.id text = clean(note) from = t.state to = s created = t0 })
  271. changes = { state = s updated = t0 events = seq }
  272. let aid = null
  273. let auto = ''
  274. if (inboxStates.includes(s) && (t.assignee == null || t.assignee == '')) { auto = defaultAssignee(t.project) }
  275. if (auto != '') {
  276. seq = seq + 1
  277. aid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = auto previous = '' created = t0 })
  278. changes.assignee = auto
  279. changes.events = seq
  280. }
  281. ticketsTable.update(t.id, merged(t, changes))
  282. t2 = ticketsTable.fetch(t.id)
  283. recordEvent(eid, t2)
  284. if (aid != null) { recordEvent(aid, t2) }
  285. out = { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  286. if (aid != null) { out.assignEvent = eventRowAt(aid, t2) }
  287. return out
  288. }
  289. // answers { error, forbidden? } or { ticket, event }; `assignee` = a member's users @id, '' = nobody
  290. static assignTicket = (ticketId, user, assignee) => {
  291. t = ticketRecord(ticketId)
  292. if (t == null) { return { error = 'no such ticket' } }
  293. if (!userOk(user)) { return authorMissing }
  294. if (!mayEditIn(t.project, user)) { return { error = 'you need the role edit or admin to assign a ticket' field = 'assignee' forbidden = true } }
  295. who = assignee == null ? '' : clean(assignee)
  296. if (who != '' && memberRecord(t.project, who) == null) { return { error = 'the assignee must be a member of the project' field = 'assignee' } }
  297. was = t.assignee != null ? t.assignee : ''
  298. if (who == was) { return { error = who == '' ? 'the ticket is not assigned' : 'the ticket is already assigned to that person' field = 'assignee' } }
  299. t0 = now()
  300. let seq = (t.events != null ? t.events : 0) + 1
  301. eid = putEvent({ ticket = t.id seq = seq kind = 'assign' author = user.name user = user.id text = '' assignee = who previous = was created = t0 })
  302. ticketsTable.update(t.id, merged(t, { assignee = who updated = t0 events = seq }))
  303. t2 = ticketsTable.fetch(t.id)
  304. recordEvent(eid, t2)
  305. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  306. }
  307. // ---- editing (ticket #8, mission 014; ticket #20: by the role) --------------------------------
  308. // THE AUTHOR of a ticket is `createdBy` (users @id), or null for a ticket opened before the login
  309. // existed. MAY THIS USER EDIT the ticket (a record)? Any member with the role edit or admin of
  310. // its project (`use` members only comment and move it between open and review).
  311. static mayEdit = (t, user) => {
  312. if (t == null || !userOk(user)) { return false }
  313. return mayEditIn(t.project, user)
  314. }
  315. static mayEditId = (ticketId, user) => { return mayEdit(ticketRecord(ticketId), user) }
  316. // answers { error, field?, forbidden? } or { ticket, event }. `subject` / `summary` null = keep
  317. // that one. The previous values stay in the 'edit' event (append-only history).
  318. static editTicket = (ticketId, user, subject, summary) => {
  319. t = ticketRecord(ticketId)
  320. if (t == null) { return { error = 'no such ticket' } }
  321. if (!userOk(user)) { return authorMissing }
  322. if (!mayEdit(t, user)) { return { error = 'you need the role edit or admin in the project to edit a ticket' field = '' forbidden = true } }
  323. if (subject == null && summary == null) { return { error = 'nothing to change: give subject and/or summary' field = '' } }
  324. let oldSummary = t.summary != null ? t.summary : ''
  325. s = subject != null ? clean(subject) : t.subject
  326. if (s == '') { return { error = 'subject is required' field = 'subject' } }
  327. sm = summary != null ? clean(summary) : oldSummary
  328. if (s == t.subject && sm == oldSummary) { return { error = 'nothing changed' field = subject != null ? 'subject' : 'summary' } }
  329. t0 = now()
  330. let seq = (t.events != null ? t.events : 0) + 1
  331. eid = putEvent({ ticket = t.id seq = seq kind = 'edit' author = user.name user = user.id text = '' oldSubject = t.subject oldSummary = oldSummary subject = s summary = sm created = t0 })
  332. if (eid == null) { return { error = 'could not store the edit: ' + eventsError() field = '' } }
  333. ticketsTable.update(t.id, merged(t, { subject = s summary = sm updated = t0 events = seq }))
  334. t2 = ticketsTable.fetch(t.id)
  335. recordEvent(eid, t2)
  336. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) }
  337. }
  338. // an admin removes a member (projects.hl removeMembership); the tickets assigned to the person are no longer
  339. // assigned to anybody. Answers { members } or { error, forbidden? }
  340. static removeMember = (projectId, actor, userId) => {
  341. r = removeMembership(projectId, actor, userId)
  342. if (r.error != null) { return r }
  343. all = ticketsTable.find('project', projectId)
  344. if (countOf(all) > 0) {
  345. for (t of all) {
  346. if (t.assignee == userId) { ticketsTable.update(t.id, merged(t, { assignee = '' })) }
  347. }
  348. }
  349. return r
  350. }
  351. // the API's view of one ticket (a record): the row and its whole history
  352. static ticketWithEvents = (t) => {
  353. if (t == null) { return null }
  354. return { ticket = ticketRowOf(t) events = eventRows(t.id) }
  355. }
  356. // ---- relations: parent / child and blocked-by (ticket #4, mission 017) ----------------------
  357. // A ticket has at most ONE PARENT (any project); a parent lists its CHILDREN with their states.
  358. // A ticket can be BLOCKED BY other tickets (any project) — it waits on them; the other side
  359. // shows what it BLOCKS. The scheduler reads them from the JSON rows (`parent`, `children`,
  360. // `blockedBy`, `blocks`, each a ref with the state) and the Markdown view.
  361. // PARENT STATE: `allChildrenConfirmed` (the key kept for the clients; it now means DONE) is true when
  362. // a ticket has children and every one of them is `done`. It is only SHOWN ("all children done") — the
  363. // parent's own state is never changed by it.
  364. // WHO MAY set / remove a relation (ticket #20): a member with the role edit or admin in the project of
  365. // EITHER of the two tickets. Replacing a parent needs the
  366. // right for the old pair AND the new pair. No loops: a ticket cannot be its own ancestor, and
  367. // cannot (transitively) wait on itself.
  368. // Tickets are named as `<project>#<number>` (spaces around `#` allowed) or by their UUID.
  369. // the link records of one side, oldest first (stored time): field 'ticket' = this ticket's own
  370. // relations (its parent, its blockers), field 'other' = the ones pointing at it (children, blocked)
  371. static linkRecords = (field, ticketId, kind) => {
  372. out = []
  373. if (ticketId == null || ticketId == '') { return out }
  374. all = linksTable.find(field, '' + ticketId)
  375. if (countOf(all) == 0) { return out }
  376. for (l of all) { if (l.kind == kind) { out.push(l) } }
  377. return oldestFirst(out, 'created')
  378. }
  379. static parentLinkOf = (ticketId) => { return first(linkRecords('ticket', ticketId, 'parent')) }
  380. static parentIdOf = (ticketId) => {
  381. l = parentLinkOf(ticketId)
  382. return l == null ? null : l.other
  383. }
  384. static idsOfLinks = (links, field) => {
  385. out = []
  386. for (l of links) { out.push(l[field]) }
  387. return out
  388. }
  389. static childIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'parent'), 'ticket') }
  390. static blockerIdsOf = (ticketId) => { return idsOfLinks(linkRecords('ticket', ticketId, 'blockedBy'), 'other') }
  391. static blockedIdsOf = (ticketId) => { return idsOfLinks(linkRecords('other', ticketId, 'blockedBy'), 'ticket') }
  392. static refsOfIds = (ids) => {
  393. out = []
  394. for (i of ids) {
  395. let t = ticketRecord(i)
  396. if (t != null) { out.push(refOf(t)) }
  397. }
  398. return out
  399. }
  400. // { parent (ref or null), children, blockedBy, blocks (lists of refs), allChildrenConfirmed }
  401. static relationsOf = (t) => {
  402. pid = parentIdOf(t.id)
  403. p = pid != null ? ticketRecord(pid) : null
  404. kids = refsOfIds(childIdsOf(t.id))
  405. let all = kids.length > 0
  406. for (c of kids) { if (c.state != 'done') { all = false } }
  407. return { parent = p != null ? refOf(p) : null children = kids allChildrenConfirmed = all blockedBy = refsOfIds(blockerIdsOf(t.id)) blocks = refsOfIds(blockedIdsOf(t.id)) }
  408. }
  409. // the relation views of a ticket AND every ticket related to it (+ `extra` ids: a parent or
  410. // blocker just removed) — what a write pushes, so every open page of them follows
  411. static relatedViews = (ticketId, extra) => {
  412. ids = ['' + ticketId]
  413. seen = {}
  414. seen['' + ticketId] = true
  415. more = []
  416. pid = parentIdOf(ticketId)
  417. if (pid != null) { more.push(pid) }
  418. for (i of childIdsOf(ticketId)) { more.push(i) }
  419. for (i of blockerIdsOf(ticketId)) { more.push(i) }
  420. for (i of blockedIdsOf(ticketId)) { more.push(i) }
  421. for (i of extra) { if (i != null) { more.push(i) } }
  422. for (i of more) {
  423. if (seen['' + i] != true) {
  424. seen['' + i] = true
  425. ids.push('' + i)
  426. }
  427. }
  428. out = []
  429. for (i of ids) {
  430. let t = ticketRecord(i)
  431. if (t != null) { out.push(relationViewOf(ticketRowOf(t))) }
  432. }
  433. return out
  434. }
  435. // `<project>#<number>` (spaces around '#' allowed) or a UUID → the ticket record, or null
  436. static ticketByKey = (key) => {
  437. k = clean(key)
  438. if (k == '') { return null }
  439. at = k.indexOf('#')
  440. if (at < 0) { return isDigits(k) ? null : ticketRecord(k) }
  441. p = k.slice(0, at).trim()
  442. n = k.slice(at + 1).trim()
  443. if (p == '') { return null }
  444. return ticketAt(p, n)
  445. }
  446. static mayLink = (a, b, user) => {
  447. if (!userOk(user)) { return false }
  448. if (a != null && mayEditIn(a.project, user)) { return true }
  449. if (b != null && mayEditIn(b.project, user)) { return true }
  450. return false
  451. }
  452. static linkForbidden = { error = 'you need the role edit or admin in the project of either ticket to change this relation' field = '' forbidden = true }
  453. // the history event of a relation change, on ticket `t`; answers { ticket, event, related }
  454. static linkEvent = (t, user, linkKind, action, other, previous, extra) => {
  455. t0 = now()
  456. let seq = (t.events != null ? t.events : 0) + 1
  457. // the values BEFORE the literal: an entry named `other` / `user` would shadow the variable
  458. // for the entries after it (mission 011 lesson)
  459. uname = user.name
  460. uid = user.id
  461. oid = other.id
  462. oproject = projectSlugOf(other)
  463. onumber = other.number
  464. rec = { ticket = t.id seq = seq kind = 'link' author = uname user = uid text = '' linkKind = linkKind action = action other = oid otherProject = oproject otherNumber = onumber created = t0 }
  465. if (previous != null) {
  466. rec.previous = previous.id
  467. rec.previousProject = projectSlugOf(previous)
  468. rec.previousNumber = previous.number
  469. }
  470. eid = putEvent(rec)
  471. if (eid == null) { return { error = 'could not store the event: ' + eventsError() field = '' } }
  472. ticketsTable.update(t.id, merged(t, { updated = t0 events = seq }))
  473. t2 = ticketsTable.fetch(t.id)
  474. recordEvent(eid, t2)
  475. return { ticket = ticketRowOf(t2) event = eventRowAt(eid, t2) related = relatedViews(t.id, extra) }
  476. }
  477. // SET (key = `<project>#<n>` / UUID) or REMOVE (key = '') the parent of a ticket (UUID).
  478. // Answers { error, field, forbidden? } or { ticket, event, related }.
  479. static setParent = (ticketId, user, key) => {
  480. t = ticketRecord(ticketId)
  481. if (t == null) { return { error = 'no such ticket' } }
  482. if (!userOk(user)) { return authorMissing }
  483. k = clean(key)
  484. cur = parentLinkOf(t.id)
  485. curT = cur != null ? ticketRecord(cur.other) : null
  486. if (k == '') {
  487. if (cur == null || curT == null) { return { error = 'the ticket has no parent' field = 'parent' } }
  488. if (!mayLink(t, curT, user)) { return linkForbidden }
  489. linksTable.delete(cur.id)
  490. return linkEvent(t, user, 'parent', 'removed', curT, null, [curT.id])
  491. }
  492. p = ticketByKey(k)
  493. if (p == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = 'parent' } }
  494. if (p.id == t.id) { return { error = 'a ticket cannot be its own parent' field = 'parent' } }
  495. if (curT != null && curT.id == p.id) { return { error = 'the parent is already ' + keyOf(p) field = 'parent' } }
  496. // no loop: the new parent must not be this ticket's child, grandchild, …
  497. let up = p.id
  498. let steps = 0
  499. while (up != null && steps < 1000) {
  500. if (up == t.id) { return { error = 'a loop: ' + keyOf(p) + ' is below this ticket' field = 'parent' } }
  501. up = parentIdOf(up)
  502. steps = steps + 1
  503. }
  504. if (!mayLink(t, p, user)) { return linkForbidden }
  505. if (curT != null && !mayLink(t, curT, user)) { return linkForbidden }
  506. lid = linksTable.put({ kind = 'parent' ticket = t.id other = p.id user = user.id created = now() })
  507. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  508. if (cur != null) { linksTable.delete(cur.id) }
  509. return linkEvent(t, user, 'parent', 'set', p, curT, [curT != null ? curT.id : null])
  510. }
  511. // does ticket `start` (transitively) wait on ticket `target`? (blocked-by links)
  512. static waitsOn = (start, target) => {
  513. stack = [start]
  514. seen = {}
  515. let steps = 0
  516. while (stack.length > 0 && steps < 10000) {
  517. let cur = stack.pop()
  518. steps = steps + 1
  519. if (cur == target) { return true }
  520. if (seen['' + cur] != true) {
  521. seen['' + cur] = true
  522. for (i of blockerIdsOf(cur)) { stack.push(i) }
  523. }
  524. }
  525. return false
  526. }
  527. // ADD (adding = true) or REMOVE a blocker of a ticket (UUID): ticket `key` blocks it.
  528. // `field` names the API field ('add' / 'remove'). Answers as setParent.
  529. static changeBlocker = (ticketId, user, key, adding, field) => {
  530. t = ticketRecord(ticketId)
  531. if (t == null) { return { error = 'no such ticket' } }
  532. if (!userOk(user)) { return authorMissing }
  533. k = clean(key)
  534. if (k == '') { return { error = 'name the blocking ticket as <project>#<number>' field = field } }
  535. o = ticketByKey(k)
  536. if (o == null) { return { error = 'no such ticket: ' + k + ' (name it as <project>#<number>)' field = field } }
  537. let existing = null
  538. for (l of linkRecords('ticket', t.id, 'blockedBy')) { if (l.other == o.id) { existing = l } }
  539. if (adding) {
  540. if (o.id == t.id) { return { error = 'a ticket cannot block itself' field = field } }
  541. if (existing != null) { return { error = 'already blocked by ' + keyOf(o) field = field } }
  542. if (waitsOn(o.id, t.id)) { return { error = 'a loop: ' + keyOf(o) + ' already waits on this ticket' field = field } }
  543. if (!mayLink(t, o, user)) { return linkForbidden }
  544. lid = linksTable.put({ kind = 'blockedBy' ticket = t.id other = o.id user = user.id created = now() })
  545. if (lid == null) { return { error = 'could not store the relation: ' + linksTable.lastError() field = '' } }
  546. return linkEvent(t, user, 'blockedBy', 'set', o, null, [])
  547. }
  548. if (existing == null) { return { error = 'not blocked by ' + keyOf(o) field = field } }
  549. if (!mayLink(t, o, user)) { return linkForbidden }
  550. linksTable.delete(existing.id)
  551. return linkEvent(t, user, 'blockedBy', 'removed', o, null, [o.id])
  552. }

Branches

Latest commits

  • eb7aeeb9mission brief 016mre
  • e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 26efb23freport w6-events (events test)mre
  • c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre
  • b7ec5981mission brief 015mre
  • 5dc68731docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
  • 6309ca81mission brief 014mre
  • c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
  • a30b5d12mission brief (w13)mre
  • b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
  • 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
  • 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
  • bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
  • 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre
  • 0369106emission 010 (code order) 4/4: README file map + import order + 'Same output' test, STATUS (entry, lessons, how to verify), LOG, report; tests/realdata-baseline.mjs + realdata-compare*.py (a cleanup answers the same on live data), tests/letcount.pymre
  • a75e0279mission 010 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (456 lets → plain declarations; Hybriel refuses a plain declaration inside a loop on its 2nd pass). gate 249/0, connect 60/0, real-data reads identical, a 50-step write sequence (API + faces) identical to the old codemre
  • e9d5c618mission 010 (code order) 2/4: one lib/ file per topic — store.hl split into projects / tickets (+ relations) / events / tickets-helpers, util.hl shared helpers (env, storage dir, URLs, sorts, Vienna time), the function routes out of project.hl into lib/api.hl (thin; auth/filters/Accept in api-helpers.hl), invite + member-removal logic out of the faces/routes into invites.hl / tickets.hl; project.hl is the map. /login/callback gets req + the session store by reference. gate 249/0, connect 60/0, real-data reads identicalmre
  • 97e269b5mission 010 (code order) 1/4: .hl files out of the root — lib/ (store, users, connections, invites, migrate, markdown, mdview, import = ticketfile, util = localtime, jsoncheck, api-helpers = api), tools/import.hl, components/styles.hl; import paths only. gate 249/0, connect 60/0, real-data reads identicalmre
  • 38f9d10ftickets: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gate 249/0, connect 60/0mre