@crombolo/server 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,17 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.19.0",
34
- "@crombolo/api-management": "0.19.0",
35
- "@crombolo/assistant": "0.19.0",
36
- "@crombolo/auth": "0.19.0",
37
- "@crombolo/backoffice-host": "0.19.0",
38
- "@crombolo/contracts": "0.19.0",
39
- "@crombolo/core": "0.19.0",
40
- "@crombolo/data": "0.19.0",
41
- "@crombolo/render": "0.19.0",
42
- "@crombolo/schema": "0.19.0",
43
- "@crombolo/transfer": "0.19.0",
33
+ "@crombolo/api-delivery": "0.20.0",
34
+ "@crombolo/api-management": "0.20.0",
35
+ "@crombolo/assistant": "0.20.0",
36
+ "@crombolo/auth": "0.20.0",
37
+ "@crombolo/backoffice-host": "0.20.0",
38
+ "@crombolo/contracts": "0.20.0",
39
+ "@crombolo/core": "0.20.0",
40
+ "@crombolo/data": "0.20.0",
41
+ "@crombolo/render": "0.20.0",
42
+ "@crombolo/schema": "0.20.0",
43
+ "@crombolo/transfer": "0.20.0",
44
44
  "@logtape/logtape": "^2.3.8"
45
45
  }
46
46
  }
@@ -11,7 +11,13 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
11
11
  import { join } from 'node:path'
12
12
  import type { Principal } from '@crombolo/api-management'
13
13
  import type { SchemaWorkflow } from '@crombolo/core'
14
- import { type Db, readWorkflows, syncWorkflows, UserGroupRepository } from '@crombolo/data'
14
+ import {
15
+ type ApprovalScheduleEntry,
16
+ type Db,
17
+ readWorkflows,
18
+ syncWorkflows,
19
+ UserGroupRepository,
20
+ } from '@crombolo/data'
15
21
  import {
16
22
  fileNameFor,
17
23
  loadSchemaDirectory,
@@ -51,12 +57,27 @@ async function changePreview(approvals: Approvals, principal: Principal, workflo
51
57
  )
52
58
  const version = workflowVersion(workflow)
53
59
  if (stored && stored.version === version) return []
60
+ // A scheduled request is decided already: a change leaves it alone.
54
61
  const waiting = (await approvals.inFlight(principal)).filter(
55
- (r) => (r.workflow.key ?? r.workflow.alias) === id,
62
+ (r) => r.state === 'waiting' && (r.workflow.key ?? r.workflow.alias) === id,
56
63
  )
57
64
  return waiting.map((r) => ({ key: r.key, page: r.nodeName, outcome: workflow.onChange }))
58
65
  }
59
66
 
67
+ /**
68
+ * `schedule`: `[{ culture, publishTime, unpublishTime }]`, times in ISO form.
69
+ * A time that does not parse stays an invalid date, which the engine refuses.
70
+ */
71
+ function readSchedule(value: unknown): ApprovalScheduleEntry[] | null {
72
+ if (!Array.isArray(value)) return null
73
+ const time = (t: unknown) => (typeof t === 'string' && t ? new Date(t) : null)
74
+ return value.map((e: Record<string, unknown>) => ({
75
+ culture: typeof e?.culture === 'string' && e.culture ? e.culture : null,
76
+ publishTime: time(e?.publishTime),
77
+ unpublishTime: time(e?.unpublishTime),
78
+ }))
79
+ }
80
+
60
81
  export async function handleApprovalsApi(
61
82
  request: Request,
62
83
  path: string,
@@ -81,6 +102,7 @@ export async function handleApprovalsApi(
81
102
  b.action === 'unpublish' ? 'unpublish' : 'publish',
82
103
  cultures && cultures.length > 0 ? cultures : null,
83
104
  text(b.comment),
105
+ readSchedule(b.schedule),
84
106
  ),
85
107
  )
86
108
  }
package/src/approvals.ts CHANGED
@@ -5,7 +5,8 @@
5
5
  *
6
6
  * The graph rules are `@crombolo/core`'s; the record is `ApprovalRepository`'s.
7
7
  * This decides: who may act, what an edit does to a waiting request, when a
8
- * stage is done, and when the page is published.
8
+ * stage is done, and when the page is published — at once, or at the time the
9
+ * request asked for (story 029), the schedule job doing the publishing.
9
10
  */
10
11
 
11
12
  import type { Principal } from '@crombolo/api-management'
@@ -27,6 +28,7 @@ import {
27
28
  ApprovalRepository,
28
29
  type ApprovalRepository as ApprovalRepositoryType,
29
30
  type ApprovalRequest,
31
+ type ApprovalScheduleEntry,
30
32
  type ApprovalStep,
31
33
  AuditLog,
32
34
  type Db,
@@ -100,6 +102,12 @@ export interface RequestView {
100
102
  action: ApprovalAction
101
103
  cultures: string[] | null
102
104
  state: ApprovalRequest['state']
105
+ /** The times it asked for, in ISO form; null to publish on approval. */
106
+ schedule: Array<{
107
+ culture: string | null
108
+ publishTime: string | null
109
+ unpublishTime: string | null
110
+ }> | null
103
111
  requestedBy: string
104
112
  requestedAt: string
105
113
  workflow: SchemaWorkflow
@@ -141,12 +149,24 @@ export interface Approvals {
141
149
  beforeSave(principal: Principal, key: string): Promise<string | undefined>
142
150
  /** What the save does to a waiting request, once it has gone through. */
143
151
  afterSave(principal: Principal, key: string): Promise<void>
152
+ /** A direct publish, schedule or unpublish by someone allowed to: a scheduled request ends. */
153
+ afterDirectPublish(principal: Principal, key: string, what: string): Promise<void>
154
+ /** The schedule job fired one of a page's schedules: a scheduled request goes on or ends. */
155
+ scheduleFired(
156
+ key: string,
157
+ culture: string | null,
158
+ action: 'Release' | 'Expire',
159
+ result: { ok: true } | { ok: false; reason: string },
160
+ ): Promise<void>
161
+ /** Ends scheduled requests whose schedule is gone: the recycle bin, an import, the CLI. */
162
+ sweepScheduled(now?: number): Promise<void>
144
163
  send(
145
164
  principal: Principal,
146
165
  key: string,
147
166
  action: ApprovalAction,
148
167
  cultures: string[] | null,
149
168
  comment?: string,
169
+ schedule?: ApprovalScheduleEntry[] | null,
150
170
  ): Promise<RequestView>
151
171
  approve(
152
172
  principal: Principal,
@@ -172,12 +192,69 @@ export interface Approvals {
172
192
  ): Promise<{ total: number; items: RequestView[] }>
173
193
  }
174
194
 
195
+ const SWEEP_GRACE_MS = 5 * 60_000
196
+
197
+ /** A time as a person reads it in a history or an e-mail, in UTC. Pure. */
198
+ export const describeTime = (time: Date): string =>
199
+ `${time.toISOString().slice(0, 16).replace('T', ' ')} UTC`
200
+
201
+ /** "published at …" for each time a request asks for, culture by culture. Pure. */
202
+ export function describeSchedule(
203
+ action: ApprovalAction,
204
+ entries: readonly ApprovalScheduleEntry[],
205
+ ): string {
206
+ return entries
207
+ .flatMap((e) => {
208
+ const culture = e.culture ? ` (${e.culture})` : ''
209
+ return [
210
+ ...(action === 'publish' && e.publishTime
211
+ ? [`published at ${describeTime(e.publishTime)}${culture}`]
212
+ : []),
213
+ ...(e.unpublishTime ? [`taken down at ${describeTime(e.unpublishTime)}${culture}`] : []),
214
+ ]
215
+ })
216
+ .join(', ')
217
+ }
218
+
219
+ /** Why a request may not carry these times, or undefined when it may. Pure. */
220
+ export function scheduleRefusal(
221
+ workflow: SchemaWorkflow,
222
+ action: ApprovalAction,
223
+ cultures: readonly string[] | null,
224
+ entries: readonly ApprovalScheduleEntry[],
225
+ now = Date.now(),
226
+ ): string | undefined {
227
+ if (entries.length === 0) return undefined
228
+ if (!workflow.scheduling)
229
+ return `"${workflow.name}" does not let a request say when to publish. Send it without a time.`
230
+ const named = new Set((cultures ?? []).map((c) => c.toLowerCase()))
231
+ const seen = new Set<string>()
232
+ for (const e of entries) {
233
+ if (action === 'unpublish' && e.publishTime)
234
+ return 'A request to take the page down can only say when to take it down.'
235
+ for (const time of [e.publishTime, e.unpublishTime])
236
+ if (time && (Number.isNaN(time.getTime()) || time.getTime() <= now))
237
+ return 'Pick a time in the future.'
238
+ if (e.publishTime && e.unpublishTime && e.unpublishTime <= e.publishTime)
239
+ return 'The page has to be taken down after it is published.'
240
+ const culture = e.culture?.toLowerCase() ?? null
241
+ if (culture === null ? cultures !== null : !named.has(culture))
242
+ return culture === null
243
+ ? 'This request names its languages: give each one its own time.'
244
+ : `"${e.culture}" is not one of the languages this request sends.`
245
+ if (seen.has(culture ?? '')) return 'Give each language one time.'
246
+ seen.add(culture ?? '')
247
+ }
248
+ return undefined
249
+ }
250
+
175
251
  export function createApprovals(options: ApprovalsOptions): Approvals {
176
252
  const { db } = options
177
253
  const requests = (tx: Db = db): ApprovalRepositoryType => new ApprovalRepository(tx)
178
254
  const nodes = new NodeRepository(db)
179
255
  const groups = new UserGroupRepository(db)
180
256
  const audit = new AuditLog(db)
257
+ const documents = () => new DocumentRepository(db, { nodeState: options.nodeState })
181
258
 
182
259
  const page = async (key: string): Promise<PageFacts | undefined> => {
183
260
  const node = await nodes.byKey(key)
@@ -388,11 +465,66 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
388
465
  return false
389
466
  }
390
467
 
468
+ /** The time a request's entry asks it to act at: publish for a publish request, take down otherwise. */
469
+ const dueAt = (request: ApprovalRequest, entry: ApprovalScheduleEntry) =>
470
+ request.action === 'publish' ? entry.publishTime : entry.unpublishTime
471
+
472
+ /** Removes the schedule rows a request wrote, culture by culture. */
473
+ const clearSchedule = async (request: ApprovalRequest) => {
474
+ if (!request.schedule) return
475
+ await documents().setSchedule(
476
+ request.nodeKey,
477
+ request.schedule.map((e) => ({ culture: e.culture, publishTime: null, unpublishTime: null })),
478
+ )
479
+ }
480
+
481
+ /** An approved page that could not be published goes back to its editor with the reason. */
482
+ const unpublishable = async (
483
+ request: ApprovalRequest,
484
+ facts: PageFacts | undefined,
485
+ reason: string,
486
+ ) => {
487
+ const repo = requests()
488
+ await repo.setState(request.id, 'sent-back')
489
+ await repo.record(request.id, {
490
+ kind: 'sent-back',
491
+ comment: `approved, but it could not be ${request.action === 'publish' ? 'published' : 'taken down'}: ${reason}`,
492
+ })
493
+ await notify(
494
+ 'editor',
495
+ request,
496
+ [],
497
+ `Could not publish: ${facts?.name ?? 'a page'}`,
498
+ `"${facts?.name}" was approved but could not be published: ${reason}`,
499
+ )
500
+ }
501
+
502
+ /** The request is done: recorded as approved, and its editor told. */
503
+ const approved = async (request: ApprovalRequest, principal: Principal | undefined) => {
504
+ const facts = await page(request.nodeKey)
505
+ await requests().setState(request.id, 'approved')
506
+ await auditStep(
507
+ principal,
508
+ facts,
509
+ request.action === 'publish' ? 'Published on approval' : 'Unpublished on approval',
510
+ `through "${request.workflow.name}"`,
511
+ )
512
+ await notify(
513
+ 'editor',
514
+ request,
515
+ [],
516
+ `Approved: ${facts?.name ?? 'a page'}`,
517
+ `"${facts?.name}" was approved through "${request.workflow.name}" and is now ${request.action === 'publish' ? 'published' : 'taken down'}.`,
518
+ )
519
+ }
520
+
391
521
  /**
392
522
  * Publishes (or takes down) a fully approved page, outside any transaction:
393
523
  * publishing takes the content tree's lock, which must never be waited on
394
- * from inside one. A page that cannot be published goes back to its editor
395
- * with the reason, rather than sitting approved and unpublished.
524
+ * from inside one. What the request asked to happen later is scheduled
525
+ * instead, and the request stays open until it has. A page that cannot be
526
+ * published goes back to its editor with the reason, rather than sitting
527
+ * approved and unpublished.
396
528
  */
397
529
  const finish = async (
398
530
  request: ApprovalRequest,
@@ -400,48 +532,73 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
400
532
  ): Promise<void> => {
401
533
  const repo = requests()
402
534
  const facts = await page(request.nodeKey)
403
- const result =
404
- request.action === 'publish'
405
- ? await options.publisher.publish(request.nodeKey, request.cultures)
406
- : await options.publisher.unpublish(request.nodeKey, request.cultures)
407
- if (!result.ok) {
408
- await repo.setState(request.id, 'sent-back')
535
+ const now = Date.now()
536
+ const later: ApprovalScheduleEntry[] = []
537
+ const expires: ApprovalScheduleEntry[] = []
538
+ let cultures: string[] | null | undefined = request.cultures
539
+ let passed = false
540
+ if (request.schedule) {
541
+ const nowCultures: Array<string | null> = []
542
+ for (const entry of request.schedule) {
543
+ const due = dueAt(request, entry)
544
+ if (due && due.getTime() > now) {
545
+ later.push(request.action === 'publish' ? entry : { ...entry, publishTime: null })
546
+ continue
547
+ }
548
+ if (due) passed = true
549
+ nowCultures.push(entry.culture)
550
+ if (request.action === 'publish' && entry.unpublishTime)
551
+ expires.push({ ...entry, publishTime: null })
552
+ }
553
+ // Cultures the request names without a time publish on approval.
554
+ const timed = new Set(request.schedule.map((e) => e.culture?.toLowerCase()))
555
+ const untimed = (request.cultures ?? []).filter((c) => !timed.has(c.toLowerCase()))
556
+ cultures = nowCultures.includes(null)
557
+ ? request.cultures
558
+ : nowCultures.length + untimed.length > 0
559
+ ? [...(nowCultures as string[]), ...untimed]
560
+ : undefined
561
+ }
562
+ if (cultures !== undefined) {
563
+ const result =
564
+ request.action === 'publish'
565
+ ? await options.publisher.publish(request.nodeKey, cultures)
566
+ : await options.publisher.unpublish(request.nodeKey, cultures)
567
+ if (!result.ok) return unpublishable(request, facts, result.reason)
409
568
  await repo.record(request.id, {
410
- kind: 'sent-back',
411
- comment: `approved, but it could not be ${request.action === 'publish' ? 'published' : 'taken down'}: ${result.reason}`,
569
+ kind: request.action === 'publish' ? 'published' : 'unpublished',
570
+ userKey: principal?.id ?? null,
571
+ comment: passed ? 'the requested time had passed when it was approved' : null,
412
572
  })
413
- await notify(
414
- 'editor',
415
- request,
416
- [],
417
- `Could not publish: ${facts?.name ?? 'a page'}`,
418
- `"${facts?.name}" was approved but could not be published: ${result.reason}`,
419
- )
420
- return
573
+ if (request.action === 'publish')
574
+ await options.notifier?.raise(
575
+ { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
576
+ principal ? { key: principal.id, name: principal.name } : null,
577
+ `approved through "${request.workflow.name}"`,
578
+ )
421
579
  }
422
- await repo.setState(request.id, 'approved')
580
+ if (later.length + expires.length > 0)
581
+ await documents().setSchedule(request.nodeKey, [...later, ...expires])
582
+ if (later.length === 0) return approved(request, principal)
583
+ const when = describeSchedule(request.action, later)
584
+ await repo.setState(request.id, 'scheduled')
423
585
  await repo.record(request.id, {
424
- kind: request.action === 'publish' ? 'published' : 'unpublished',
586
+ kind: 'scheduled',
425
587
  userKey: principal?.id ?? null,
588
+ comment: when,
426
589
  })
427
590
  await auditStep(
428
591
  principal,
429
592
  facts,
430
- request.action === 'publish' ? 'Published on approval' : 'Unpublished on approval',
431
- `through "${request.workflow.name}"`,
593
+ 'Scheduled on approval',
594
+ `${when}, through "${request.workflow.name}"`,
432
595
  )
433
- if (request.action === 'publish')
434
- await options.notifier?.raise(
435
- { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
436
- principal ? { key: principal.id, name: principal.name } : null,
437
- `approved through "${request.workflow.name}"`,
438
- )
439
596
  await notify(
440
597
  'editor',
441
598
  request,
442
599
  [],
443
600
  `Approved: ${facts?.name ?? 'a page'}`,
444
- `"${facts?.name}" was approved through "${request.workflow.name}" and is now ${request.action === 'publish' ? 'published' : 'taken down'}.`,
601
+ `"${facts?.name}" was approved through "${request.workflow.name}" and will be ${when}.`,
445
602
  )
446
603
  }
447
604
 
@@ -501,6 +658,12 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
501
658
  action: request.action,
502
659
  cultures: request.cultures,
503
660
  state: request.state,
661
+ schedule:
662
+ request.schedule?.map((e) => ({
663
+ culture: e.culture,
664
+ publishTime: e.publishTime?.toISOString() ?? null,
665
+ unpublishTime: e.unpublishTime?.toISOString() ?? null,
666
+ })) ?? null,
504
667
  requestedBy: request.requestedBy,
505
668
  requestedAt: request.requestedAt.toISOString(),
506
669
  workflow: request.workflow,
@@ -518,7 +681,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
518
681
  ? []
519
682
  : actionable.filter((s) => !already(s.alias)).map((s) => s.alias),
520
683
  sendBack: actionable.map((s) => s.alias),
521
- withdraw: waiting && (ownChange || principal.isAdmin),
684
+ withdraw: (waiting || request.state === 'scheduled') && (ownChange || principal.isAdmin),
522
685
  },
523
686
  }
524
687
  }
@@ -593,9 +756,14 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
593
756
  },
594
757
 
595
758
  async beforeSave(principal, key) {
596
- const request = await requests().waitingFor(key)
759
+ const request = await requests().openFor(key)
597
760
  if (!request || principal.isAdmin) return undefined
598
761
  const edit = request.workflow.onEdit
762
+ if (request.state === 'scheduled') {
763
+ if (edit === 'lock' || edit === 'lock-after-first-approval')
764
+ return `This page is approved and will be ${describeSchedule(request.action, request.schedule ?? [])}. It cannot be changed until then; withdraw the request to change it.`
765
+ return undefined
766
+ }
599
767
  if (edit === 'lock')
600
768
  return 'This page is waiting for approval and cannot be changed until it is decided.'
601
769
  if (edit === 'lock-after-first-approval') {
@@ -608,7 +776,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
608
776
 
609
777
  async afterSave(principal, key) {
610
778
  const repo = requests()
611
- const request = await repo.waitingFor(key)
779
+ const request = await repo.openFor(key)
612
780
  if (!request) return
613
781
  const head =
614
782
  (await new DocumentRepository(db, { nodeState: options.nodeState }).eventMarkers(key))
@@ -622,13 +790,14 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
622
790
  userKey: principal.id,
623
791
  comment: 'the page was changed after it was sent',
624
792
  })
793
+ if (request.state === 'scheduled') await clearSchedule(request)
625
794
  return
626
795
  }
627
796
  await repo.setEvent(request.id, head)
628
797
  await repo.record(request.id, { kind: 'edited', userKey: principal.id })
629
798
  },
630
799
 
631
- async send(principal, key, action, cultures, comment) {
800
+ async send(principal, key, action, cultures, comment, schedule) {
632
801
  const facts = await page(key)
633
802
  if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
634
803
  const workflow = await covering(facts)
@@ -638,13 +807,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
638
807
  ? 'No workflow covers this page: it can be published directly.'
639
808
  : 'Taking this page down needs no approval.',
640
809
  )
810
+ const timed = (schedule ?? []).filter((e) => e.publishTime || e.unpublishTime)
811
+ const refusal = scheduleRefusal(workflow, action, cultures, timed)
812
+ if (refusal) throw new ApprovalRefused(refusal)
641
813
  const stored = (await readWorkflows(db)).find(
642
814
  (s) => (s.workflow.key ?? s.workflow.alias) === (workflow.key ?? workflow.alias),
643
815
  )
644
816
  const outcome = await db.transaction(async (tx) => {
645
817
  const repo = requests(tx)
646
- if (await repo.waitingFor(key))
647
- throw new ApprovalRefused('This page is already waiting for approval.', 409)
818
+ const open = await repo.openFor(key)
819
+ if (open)
820
+ throw new ApprovalRefused(
821
+ open.state === 'scheduled'
822
+ ? `This page is already approved and will be ${describeSchedule(open.action, open.schedule ?? [])}. Withdraw that request to send it with another time.`
823
+ : 'This page is already waiting for approval.',
824
+ 409,
825
+ )
648
826
  const head =
649
827
  (await new DocumentRepository(tx, { nodeState: options.nodeState }).eventMarkers(key))
650
828
  ?.head ?? null
@@ -656,11 +834,13 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
656
834
  workflow,
657
835
  workflowVersion: stored?.version ?? '',
658
836
  requestedBy: principal.id,
837
+ schedule: timed.length > 0 ? timed : null,
659
838
  })
839
+ const when = timed.length > 0 ? describeSchedule(action, timed) : ''
660
840
  await repo.record(request.id, {
661
841
  kind: 'sent',
662
842
  userKey: principal.id,
663
- comment: comment?.trim() || null,
843
+ comment: [comment?.trim(), when && `to be ${when}`].filter(Boolean).join('\n\n') || null,
664
844
  })
665
845
  const first = startStages(workflow)
666
846
  await reach(repo, request, first)
@@ -669,7 +849,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
669
849
  request,
670
850
  first,
671
851
  `Waiting for your approval: ${facts.name}`,
672
- `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${comment ? `\n\n${comment}` : ''}`,
852
+ `${principal.name} sent "${facts.name}" for approval through "${workflow.name}".${when ? ` It is to be ${when}.` : ''}${comment ? `\n\n${comment}` : ''}`,
673
853
  )
674
854
  const complete = await settle(repo, request)
675
855
  await auditStep(
@@ -784,7 +964,10 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
784
964
  },
785
965
 
786
966
  async withdraw(principal, requestKey) {
787
- const request = await waitingRequest(requestKey)
967
+ const request = await requests().byKey(requestKey)
968
+ if (!request) throw new ApprovalRefused('There is no such request.', 404)
969
+ if (request.state !== 'waiting' && request.state !== 'scheduled')
970
+ throw new ApprovalRefused('This request has already been decided.', 409)
788
971
  if (normaliseUuid(principal.id) !== request.requestedBy && !principal.isAdmin)
789
972
  throw new ApprovalRefused(
790
973
  'Only the person who sent it, or an administrator, can withdraw it.',
@@ -792,6 +975,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
792
975
  )
793
976
  await requests().setState(request.id, 'withdrawn')
794
977
  await requests().record(request.id, { kind: 'withdrawn', userKey: principal.id })
978
+ if (request.state === 'scheduled') await clearSchedule(request)
795
979
  await auditStep(
796
980
  principal,
797
981
  await page(request.nodeKey),
@@ -801,12 +985,88 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
801
985
  return view(principal, (await requests().byKey(request.key)) as ApprovalRequest)
802
986
  },
803
987
 
988
+ async afterDirectPublish(principal, key, what) {
989
+ const repo = requests()
990
+ const request = await repo.openFor(key)
991
+ if (request?.state !== 'scheduled') return
992
+ await repo.setState(request.id, 'superseded')
993
+ await repo.record(request.id, {
994
+ kind: 'superseded',
995
+ userKey: principal.id,
996
+ comment: `${principal.name} ${what} directly`,
997
+ })
998
+ await auditStep(
999
+ principal,
1000
+ await page(key),
1001
+ 'Superseded approval request',
1002
+ `scheduled under "${request.workflow.name}"`,
1003
+ )
1004
+ },
1005
+
1006
+ async scheduleFired(key, culture, action, result) {
1007
+ const repo = requests()
1008
+ const request = await repo.openFor(key)
1009
+ if (request?.state !== 'scheduled' || !request.schedule) return
1010
+ // An expiry on a page a request published is an ordinary schedule by then.
1011
+ if (action !== (request.action === 'publish' ? 'Release' : 'Expire')) return
1012
+ const same = (a: string | null, b: string | null) =>
1013
+ (a?.toLowerCase() ?? null) === (b?.toLowerCase() ?? null)
1014
+ if (!request.schedule.some((e) => same(e.culture, culture))) return
1015
+ const facts = await page(key)
1016
+ if (!result.ok) {
1017
+ await clearSchedule(request)
1018
+ return unpublishable(request, facts, result.reason)
1019
+ }
1020
+ await repo.record(request.id, {
1021
+ kind: request.action === 'publish' ? 'published' : 'unpublished',
1022
+ comment: `as scheduled${culture ? ` (${culture})` : ''}`,
1023
+ })
1024
+ const left = (await documents().schedules(key)).some(
1025
+ (row) =>
1026
+ row.action === action && request.schedule?.some((e) => same(e.culture, row.culture)),
1027
+ )
1028
+ if (!left) await approved(request, undefined)
1029
+ },
1030
+
1031
+ async sweepScheduled(now = Date.now()) {
1032
+ for (const request of await requests().scheduled()) {
1033
+ const node = await nodes.byKey(request.nodeKey)
1034
+ if (!node || node.trashed) {
1035
+ if (node) await clearSchedule(request)
1036
+ await requests().setState(request.id, 'withdrawn')
1037
+ await requests().record(request.id, {
1038
+ kind: 'withdrawn',
1039
+ comment: node ? 'the page was moved to the recycle bin' : 'the page was deleted',
1040
+ })
1041
+ continue
1042
+ }
1043
+ const action = request.action === 'publish' ? 'Release' : 'Expire'
1044
+ const rows = await documents().schedules(request.nodeKey)
1045
+ const left = rows.some(
1046
+ (row) =>
1047
+ row.action === action &&
1048
+ request.schedule?.some(
1049
+ (e) => (e.culture?.toLowerCase() ?? null) === (row.culture?.toLowerCase() ?? null),
1050
+ ),
1051
+ )
1052
+ if (left) continue
1053
+ // A row the job has claimed and is publishing is gone too: give it time to report.
1054
+ const due = (request.schedule ?? []).flatMap((e) => dueAt(request, e) ?? [])
1055
+ if (due.some((d) => d.getTime() <= now && d.getTime() > now - SWEEP_GRACE_MS)) continue
1056
+ await requests().setState(request.id, 'withdrawn')
1057
+ await requests().record(request.id, {
1058
+ kind: 'withdrawn',
1059
+ comment: 'the schedule was removed',
1060
+ })
1061
+ }
1062
+ },
1063
+
804
1064
  async forPage(principal, key) {
805
1065
  const facts = await page(key)
806
1066
  if (!facts) throw new ApprovalRefused('The page could not be found.', 404)
807
1067
  const workflow = await covering(facts)
808
1068
  const all = await requests().forNode(key)
809
- const waiting = all.find((r) => r.state === 'waiting')
1069
+ const waiting = all.find((r) => r.state === 'waiting' || r.state === 'scheduled')
810
1070
  return {
811
1071
  workflow,
812
1072
  request: waiting ? await view(principal, waiting) : undefined,
@@ -826,7 +1086,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
826
1086
 
827
1087
  async waitingFor(principal) {
828
1088
  const out: RequestView[] = []
829
- for (const request of await requests().waiting()) {
1089
+ for (const request of await requests().open()) {
830
1090
  const v = await view(principal, request)
831
1091
  if (v.can.approve.length > 0 || v.can.sendBack.length > 0) out.push(v)
832
1092
  }
@@ -834,7 +1094,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
834
1094
  },
835
1095
 
836
1096
  async inFlight(principal) {
837
- return Promise.all((await requests().waiting()).map((r) => view(principal, r)))
1097
+ return Promise.all((await requests().open()).map((r) => view(principal, r)))
838
1098
  },
839
1099
 
840
1100
  async finished(principal, skip, take) {
package/src/config.ts CHANGED
@@ -740,4 +740,4 @@ export function describeDatabase(
740
740
  }
741
741
  }
742
742
 
743
- export const VERSION = '0.19.0'
743
+ export const VERSION = '0.20.0'
package/src/jobs.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from '@crombolo/data'
19
19
  import type { PublishedCache } from '@crombolo/render'
20
20
  import { auditRetainedSince, recordAudit } from './adapters/audit.ts'
21
+ import type { Approvals } from './approvals.ts'
21
22
  import type {
22
23
  ContentNotificationRunner,
23
24
  ContentNotificationRunReport,
@@ -61,6 +62,8 @@ export interface JobsOptions {
61
62
  contentNotificationsMs?: number
62
63
  /** Queues the notifications scheduled publishing makes, as an editor's publish does. */
63
64
  notifier?: ContentNotifier
65
+ /** Told what scheduled publishing did, for the approval requests waiting on it (story 029). */
66
+ approvals?: Pick<Approvals, 'scheduleFired' | 'sweepScheduled'>
64
67
  }
65
68
 
66
69
  export interface ScheduledRun {
@@ -123,11 +126,17 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
123
126
  detail: `Scheduled${due.culture ? ` (${due.culture})` : ''}`,
124
127
  })
125
128
  options.onDocumentChanged?.(due.key)
129
+ await options.approvals?.scheduleFired(due.key, due.culture, due.action, { ok: true })
126
130
  } catch (error) {
127
131
  if (!(error instanceof PublishBlockedError)) throw error
128
132
  run.failed.push({ key: due.key, reason: error.message })
133
+ await options.approvals?.scheduleFired(due.key, due.culture, due.action, {
134
+ ok: false,
135
+ reason: error.message,
136
+ })
129
137
  }
130
138
  }
139
+ await options.approvals?.sweepScheduled(now.getTime())
131
140
  if (run.published.length + run.unpublished.length > 0) options.cache.invalidate()
132
141
  for (const key of run.published) {
133
142
  await options.webhooks?.raise({ alias: 'Umbraco.ContentPublish', key })
package/src/server.ts CHANGED
@@ -893,6 +893,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
893
893
  const jobs = createBackgroundJobs({
894
894
  db,
895
895
  cache,
896
+ approvals: managementDeps.approvals as Approvals | undefined,
896
897
  nodeState: schema.nodeState,
897
898
  nodeId: schema.nodeId,
898
899
  versionCleanup: config.versionCleanup,