@crombolo/server 0.72.0 → 0.73.2
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 +14 -14
- package/src/change-transfer.ts +46 -3
- package/src/config.ts +1 -1
- package/src/content-events.ts +75 -4
- package/src/served-api.ts +121 -0
- package/src/served-schema.ts +231 -0
- package/src/server.ts +108 -3
- package/src/webhooks.ts +35 -1
- package/src/workspace-processes.ts +82 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.73.2",
|
|
4
4
|
"description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -32,19 +32,19 @@
|
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@crombolo/api-delivery": "0.
|
|
36
|
-
"@crombolo/api-management": "0.
|
|
37
|
-
"@crombolo/auth": "0.
|
|
38
|
-
"@crombolo/backoffice-host": "0.
|
|
39
|
-
"@crombolo/common": "0.
|
|
40
|
-
"@crombolo/content": "0.
|
|
41
|
-
"@crombolo/contracts": "0.
|
|
42
|
-
"@crombolo/core": "0.
|
|
43
|
-
"@crombolo/data": "0.
|
|
44
|
-
"@crombolo/extension": "0.
|
|
45
|
-
"@crombolo/render": "0.
|
|
46
|
-
"@crombolo/schema": "0.
|
|
47
|
-
"@crombolo/transfer": "0.
|
|
35
|
+
"@crombolo/api-delivery": "0.73.2",
|
|
36
|
+
"@crombolo/api-management": "0.73.2",
|
|
37
|
+
"@crombolo/auth": "0.73.2",
|
|
38
|
+
"@crombolo/backoffice-host": "0.73.2",
|
|
39
|
+
"@crombolo/common": "0.73.2",
|
|
40
|
+
"@crombolo/content": "0.73.2",
|
|
41
|
+
"@crombolo/contracts": "0.73.2",
|
|
42
|
+
"@crombolo/core": "0.73.2",
|
|
43
|
+
"@crombolo/data": "0.73.2",
|
|
44
|
+
"@crombolo/extension": "0.73.2",
|
|
45
|
+
"@crombolo/render": "0.73.2",
|
|
46
|
+
"@crombolo/schema": "0.73.2",
|
|
47
|
+
"@crombolo/transfer": "0.73.2",
|
|
48
48
|
"@logtape/logtape": "^2.3.8",
|
|
49
49
|
"@opentelemetry/api": "1.10.0",
|
|
50
50
|
"@opentelemetry/context-async-hooks": "3.0.0",
|
package/src/change-transfer.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
DbDate,
|
|
21
21
|
DocumentRepository,
|
|
22
22
|
type DocumentRepositoryOptions,
|
|
23
|
+
SCHEDULE_PREFIX,
|
|
23
24
|
TransferRunRepository,
|
|
24
25
|
type Workspace,
|
|
25
26
|
WorkspaceFileRepository,
|
|
@@ -32,6 +33,7 @@ import type {
|
|
|
32
33
|
ChangeBundlePage,
|
|
33
34
|
ChangePageState,
|
|
34
35
|
ChangeValue,
|
|
36
|
+
PageSchedule,
|
|
35
37
|
} from '@crombolo/transfer'
|
|
36
38
|
import type { MediaFileStore } from './media-files.ts'
|
|
37
39
|
import type { WorkspaceMerging } from './node-operations.ts'
|
|
@@ -249,8 +251,18 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
|
|
|
249
251
|
JSON.parse(i.before as string),
|
|
250
252
|
]),
|
|
251
253
|
) as Map<string, DocumentAggregate>
|
|
254
|
+
// Story 395: a page's schedule, as the change set it.
|
|
255
|
+
const schedules = new Map(
|
|
256
|
+
items
|
|
257
|
+
.filter((i) => i.path.startsWith(SCHEDULE_PREFIX) && i.after !== null)
|
|
258
|
+
.map((i) => [
|
|
259
|
+
normaliseUuid(i.path.slice(SCHEDULE_PREFIX.length)),
|
|
260
|
+
JSON.parse(i.after as string) as PageSchedule,
|
|
261
|
+
]),
|
|
262
|
+
)
|
|
252
263
|
for (const item of items) {
|
|
253
|
-
if (item.path.startsWith(REMOVED_PAGE_PREFIX))
|
|
264
|
+
if (item.path.startsWith(REMOVED_PAGE_PREFIX) || item.path.startsWith(SCHEDULE_PREFIX))
|
|
265
|
+
continue
|
|
254
266
|
const versions = await changes.versions(item.path)
|
|
255
267
|
const at = versions.findIndex((v) => v.changeId === change.id)
|
|
256
268
|
const earlier = at > 0 ? versions[at - 1] : undefined
|
|
@@ -277,6 +289,7 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
|
|
|
277
289
|
if (!shape) continue
|
|
278
290
|
const action =
|
|
279
291
|
row.action === 'create' ? 'create' : row.action === 'recycle' ? 'delete' : 'update'
|
|
292
|
+
const schedule = schedules.get(normaliseUuid(row.nodeKey))
|
|
280
293
|
const page = pageOf(
|
|
281
294
|
row.nodeKey,
|
|
282
295
|
row.kind,
|
|
@@ -286,6 +299,7 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
|
|
|
286
299
|
after,
|
|
287
300
|
await lastChangeOfNode(row.nodeKey, row.beforeEventId, change.key),
|
|
288
301
|
)
|
|
302
|
+
if (page.after && schedule) page.after.schedule = schedule
|
|
289
303
|
pages.push(page)
|
|
290
304
|
depends.push(...(await madeBy([page.after], change.key)))
|
|
291
305
|
if (page.lastChange && page.action !== 'create') depends.push(page.lastChange)
|
|
@@ -463,9 +477,18 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
|
|
|
463
477
|
}
|
|
464
478
|
if (schemaTouched) await options.schema()?.build({ id: workspace.id, key: workspace.key })
|
|
465
479
|
const staged = [...(workspace.stagedChanges ?? [])]
|
|
466
|
-
for (const { change } of todo)
|
|
480
|
+
for (const { change } of todo) {
|
|
481
|
+
// Story 395: a schedule is set on Shared once the change is merged, as a merge drops a workspace's.
|
|
482
|
+
const schedules = change.pages.flatMap((p) =>
|
|
483
|
+
p.after?.schedule ? [{ key: p.key, kind: p.kind, entries: p.after.schedule }] : [],
|
|
484
|
+
)
|
|
467
485
|
if (!staged.some((s) => s.key === change.key))
|
|
468
|
-
staged.push({
|
|
486
|
+
staged.push({
|
|
487
|
+
key: change.key,
|
|
488
|
+
name: change.name,
|
|
489
|
+
...(schedules.length > 0 ? { schedules } : {}),
|
|
490
|
+
})
|
|
491
|
+
}
|
|
469
492
|
await workspaces.setStaged(workspace.id, staged)
|
|
470
493
|
return { workspace: (await workspaces.byKey(workspace.key)) ?? workspace, skipped, conflicts }
|
|
471
494
|
}
|
|
@@ -667,9 +690,29 @@ export function createChangeTransfer(options: ChangeTransferOptions) {
|
|
|
667
690
|
conflicts: outcome.blockers.map((says) => ({ change: workspace.key, item: '', says })),
|
|
668
691
|
workspace: workspace.key,
|
|
669
692
|
}
|
|
693
|
+
for (const change of applied)
|
|
694
|
+
for (const page of change.schedules ?? []) await scheduleHere(page)
|
|
670
695
|
return { ok: true, skipped, changeId: outcome.changeId ?? null }
|
|
671
696
|
}
|
|
672
697
|
|
|
698
|
+
/** A page's schedule as a change carries it, replacing what Shared had for the page. */
|
|
699
|
+
async function scheduleHere(page: { key: string; kind: string; entries: PageSchedule }) {
|
|
700
|
+
const here = repo(page.kind as PageKind)
|
|
701
|
+
if (!(await here.byKey(page.key))) return
|
|
702
|
+
const had = await here.schedules(page.key)
|
|
703
|
+
const cleared = [...new Set(had.map((s) => s.culture))]
|
|
704
|
+
.filter((culture) => !page.entries.some((e) => e.culture === culture))
|
|
705
|
+
.map((culture) => ({ culture, publishTime: null, unpublishTime: null }))
|
|
706
|
+
await here.setSchedule(page.key, [
|
|
707
|
+
...cleared,
|
|
708
|
+
...page.entries.map((e) => ({
|
|
709
|
+
culture: e.culture,
|
|
710
|
+
publishTime: e.publishTime ? new Date(e.publishTime) : null,
|
|
711
|
+
unpublishTime: e.unpublishTime ? new Date(e.unpublishTime) : null,
|
|
712
|
+
})),
|
|
713
|
+
])
|
|
714
|
+
}
|
|
715
|
+
|
|
673
716
|
return { exportChange, exportWorkspace, exportSince, stage, apply, mergeStaged }
|
|
674
717
|
}
|
|
675
718
|
|
package/src/config.ts
CHANGED
|
@@ -1492,7 +1492,7 @@ export function describeDatabase(
|
|
|
1492
1492
|
}
|
|
1493
1493
|
}
|
|
1494
1494
|
|
|
1495
|
-
export const VERSION = '0.
|
|
1495
|
+
export const VERSION = '0.73.2'
|
|
1496
1496
|
|
|
1497
1497
|
/** A whole number of seconds from the environment; undefined when unset or not one. */
|
|
1498
1498
|
/** A positive number from a setting, else the default. */
|
package/src/content-events.ts
CHANGED
|
@@ -26,8 +26,16 @@ import {
|
|
|
26
26
|
notificationFor,
|
|
27
27
|
webhookFor,
|
|
28
28
|
} from '@crombolo/content'
|
|
29
|
-
import {
|
|
29
|
+
import {
|
|
30
|
+
AuditLog,
|
|
31
|
+
ChangeRepository,
|
|
32
|
+
ContentEventRepository,
|
|
33
|
+
currentAuditContext,
|
|
34
|
+
type Db,
|
|
35
|
+
DocumentRepository,
|
|
36
|
+
} from '@crombolo/data'
|
|
30
37
|
import type { ContentNotifier } from './content-notifications.ts'
|
|
38
|
+
import { neededBy, servedView } from './served-schema.ts'
|
|
31
39
|
import type { WebhookService } from './webhooks.ts'
|
|
32
40
|
|
|
33
41
|
export interface ContentEventSinkOptions {
|
|
@@ -75,6 +83,43 @@ export const outboxActor = (actor: MediaActor) => {
|
|
|
75
83
|
}
|
|
76
84
|
}
|
|
77
85
|
|
|
86
|
+
/** A page's schedule as a change carries it: per language, when it goes live and comes down. */
|
|
87
|
+
export const scheduleEntries = (
|
|
88
|
+
rows: ReadonlyArray<{ culture: string | null; action: 'Release' | 'Expire'; date: Date }>,
|
|
89
|
+
) => {
|
|
90
|
+
const byCulture = new Map<
|
|
91
|
+
string | null,
|
|
92
|
+
{ culture: string | null; publishTime: string | null; unpublishTime: string | null }
|
|
93
|
+
>()
|
|
94
|
+
for (const row of rows) {
|
|
95
|
+
const entry = byCulture.get(row.culture) ?? {
|
|
96
|
+
culture: row.culture,
|
|
97
|
+
publishTime: null,
|
|
98
|
+
unpublishTime: null,
|
|
99
|
+
}
|
|
100
|
+
if (row.action === 'Release') entry.publishTime = row.date.toISOString()
|
|
101
|
+
else entry.unpublishTime = row.date.toISOString()
|
|
102
|
+
byCulture.set(row.culture, entry)
|
|
103
|
+
}
|
|
104
|
+
return [...byCulture.values()]
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Story 395: a person, or a tool acting for one (a sign-in exchanged with an actor, 364). */
|
|
108
|
+
async function madeBy(): Promise<{ by: 'person' | 'tool'; tool?: { id: string; name: string } }> {
|
|
109
|
+
const actor = currentAuditContext()?.exchange?.actor
|
|
110
|
+
return actor
|
|
111
|
+
? { by: 'tool', tool: { id: actor.id, name: actor.name ?? actor.id } }
|
|
112
|
+
: { by: 'person' }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Story 395: the unserved changes a page needs, once a host reports what is served. */
|
|
116
|
+
async function needsOf(tx: Db, key: string) {
|
|
117
|
+
const view = await servedView(tx)
|
|
118
|
+
if (!view) return {}
|
|
119
|
+
const page = await new DocumentRepository(tx).byKey(key)
|
|
120
|
+
return page ? { needs: neededBy(view, page) } : {}
|
|
121
|
+
}
|
|
122
|
+
|
|
78
123
|
export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
|
|
79
124
|
/** A person's own write in the back office or the API, not a merge's nor the site's code. */
|
|
80
125
|
const ownEdit = (actor: Actor) => actor.kind === 'user' && !actor.origin.via
|
|
@@ -86,9 +131,24 @@ export function createContentEventSink(options: ContentEventSinkOptions): EventS
|
|
|
86
131
|
if (!key || !userKey || !ownEdit(actor)) return
|
|
87
132
|
const changes = new ChangeRepository(tx)
|
|
88
133
|
if (SAVES.has(event.type)) await changes.pageSavedBy(userKey, { key, kind: 'document' })
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
if (!
|
|
134
|
+
// Story 395: setting or clearing a schedule is passed on as a publish is.
|
|
135
|
+
const scheduled = event.type === 'scheduled'
|
|
136
|
+
if (!PUBLISHES.has(event.type) && !scheduled) return
|
|
137
|
+
const schedule = await new DocumentRepository(tx).schedules(key)
|
|
138
|
+
if (scheduled || schedule.length > 0)
|
|
139
|
+
await changes.scheduleOf(userKey, { key, kind: 'document' }, scheduleEntries(schedule))
|
|
140
|
+
const closed = await changes.publishedBy(userKey, { key, kind: 'document' })
|
|
141
|
+
if (closed) await announceChange(tx, key, closed, actor)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** `Crombolo.ChangePublished` for a page's change, as an outbox event in its transaction. */
|
|
145
|
+
async function announceChange(
|
|
146
|
+
tx: Db,
|
|
147
|
+
key: string,
|
|
148
|
+
closed: { key: string; name: string | null; from?: 'own-workspace' },
|
|
149
|
+
actor: Actor,
|
|
150
|
+
) {
|
|
151
|
+
const change = { ...closed, ...(await madeBy()), ...(await needsOf(tx, key)) }
|
|
92
152
|
const hook = { alias: CHANGE_PUBLISHED, key }
|
|
93
153
|
await new ContentEventRepository(tx).record({
|
|
94
154
|
kind: 'change-published',
|
|
@@ -105,6 +165,17 @@ export function createContentEventSink(options: ContentEventSinkOptions): EventS
|
|
|
105
165
|
}
|
|
106
166
|
|
|
107
167
|
return {
|
|
168
|
+
async ownPublished(tx, published, actor) {
|
|
169
|
+
if (!options.changes) return
|
|
170
|
+
const change = await new ChangeRepository(tx).byId(published.changeId)
|
|
171
|
+
if (!change) return
|
|
172
|
+
await announceChange(
|
|
173
|
+
tx,
|
|
174
|
+
published.key,
|
|
175
|
+
{ key: change.key, name: change.name, from: 'own-workspace' },
|
|
176
|
+
actor,
|
|
177
|
+
)
|
|
178
|
+
},
|
|
108
179
|
async record(tx: Db, event, actor) {
|
|
109
180
|
if (options.changes) await recordInChange(tx, event, actor as Actor)
|
|
110
181
|
const entry = auditEntryFor(event, actor)
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Story 395's routes. A host reports each change it applied to the served copy
|
|
3
|
+
* (`PUT <plugin>/api/changes/served`) and reads back the newest (`GET`), and leaves
|
|
4
|
+
* a person a notice of how it went (`POST <plugin>/api/notices`): each needs Apply
|
|
5
|
+
* changes. The back office takes a person's own notices (`GET .../notices/mine`).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Principal } from '@crombolo/api-management/domain'
|
|
9
|
+
import { normaliseUuid } from '@crombolo/core'
|
|
10
|
+
import {
|
|
11
|
+
BackofficeNoticeRepository,
|
|
12
|
+
ChangeRepository,
|
|
13
|
+
type Db,
|
|
14
|
+
ServedChangeRepository,
|
|
15
|
+
} from '@crombolo/data'
|
|
16
|
+
import { servedView } from './served-schema.ts'
|
|
17
|
+
|
|
18
|
+
export interface ServedApiOptions {
|
|
19
|
+
/** Whether the caller may apply changes here, as the change routes decide it. */
|
|
20
|
+
mayApply(principal: Principal): Promise<boolean>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
24
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status })
|
|
25
|
+
const refused = (message: string, status: number) => json({ message }, status)
|
|
26
|
+
|
|
27
|
+
/** A link a notice may carry: a path in the back office, or a web address. Pure. */
|
|
28
|
+
export const noticeLink = (link: unknown): string | null | undefined => {
|
|
29
|
+
if (link === undefined || link === null || link === '') return null
|
|
30
|
+
if (typeof link !== 'string' || link.length > 1000) return undefined
|
|
31
|
+
if (link.startsWith('/') && !link.startsWith('//')) return link
|
|
32
|
+
try {
|
|
33
|
+
const url = new URL(link)
|
|
34
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : undefined
|
|
35
|
+
} catch {
|
|
36
|
+
return undefined
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function createServedApi(db: Db, options: ServedApiOptions) {
|
|
41
|
+
const served = new ServedChangeRepository(db)
|
|
42
|
+
const notices = new BackofficeNoticeRepository(db)
|
|
43
|
+
|
|
44
|
+
async function servedRoute(request: Request, principal: Principal): Promise<Response> {
|
|
45
|
+
if (!(await options.mayApply(principal)))
|
|
46
|
+
return refused('Reporting what the live site holds needs the Apply changes right.', 403)
|
|
47
|
+
if (request.method === 'PUT') {
|
|
48
|
+
const body = (await request.json().catch(() => undefined)) as { key?: unknown } | undefined
|
|
49
|
+
const key = typeof body?.key === 'string' ? body.key.trim() : ''
|
|
50
|
+
if (!UUID.test(key)) return refused('Name the change applied there by its key.', 400)
|
|
51
|
+
const held = await new ChangeRepository(db).held([key])
|
|
52
|
+
if (!held.has(normaliseUuid(key))) return refused('There is no such change here.', 404)
|
|
53
|
+
await served.report(key, principal.id)
|
|
54
|
+
} else if (request.method !== 'GET') return new Response(null, { status: 405 })
|
|
55
|
+
const newest = await served.newest()
|
|
56
|
+
const view = await servedView(db)
|
|
57
|
+
const waiting = new Set(
|
|
58
|
+
[...(view?.pending.values() ?? [])].flatMap((i) => i.changes.map((c) => c.key)),
|
|
59
|
+
)
|
|
60
|
+
return json({
|
|
61
|
+
newest: newest
|
|
62
|
+
? { key: newest.key, name: newest.name, reportedAt: newest.reportedAt.toISOString() }
|
|
63
|
+
: null,
|
|
64
|
+
waiting: waiting.size,
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function post(request: Request, principal: Principal): Promise<Response> {
|
|
69
|
+
if (!(await options.mayApply(principal)))
|
|
70
|
+
return refused('Leaving someone a notice needs the Apply changes right.', 403)
|
|
71
|
+
const body = (await request.json().catch(() => undefined)) as
|
|
72
|
+
| Record<string, unknown>
|
|
73
|
+
| undefined
|
|
74
|
+
const user = typeof body?.user === 'string' ? body.user.trim() : ''
|
|
75
|
+
if (!UUID.test(user)) return refused('Name the person by their key.', 400)
|
|
76
|
+
const message = typeof body?.message === 'string' ? body.message.trim() : ''
|
|
77
|
+
if (!message || message.length > 1000)
|
|
78
|
+
return refused('Say what happened, in at most 1000 characters.', 400)
|
|
79
|
+
const kind = body?.kind ?? 'success'
|
|
80
|
+
if (kind !== 'success' && kind !== 'failure')
|
|
81
|
+
return refused('A notice is a success or a failure.', 400)
|
|
82
|
+
const link = noticeLink(body?.link)
|
|
83
|
+
if (link === undefined) return refused('A link is a back office path or a web address.', 400)
|
|
84
|
+
const found = await db.q
|
|
85
|
+
.selectFrom('user_account')
|
|
86
|
+
.select('id')
|
|
87
|
+
.where('key', '=', normaliseUuid(user))
|
|
88
|
+
.execute()
|
|
89
|
+
if (found.length === 0) return refused('There is no such person here.', 404)
|
|
90
|
+
const id = await notices.add({ userKey: user, kind, message, link })
|
|
91
|
+
return json({ id }, 201)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return {
|
|
95
|
+
/** Answers the route at `rest` under the changes path, if it is this one. */
|
|
96
|
+
async changes(
|
|
97
|
+
request: Request,
|
|
98
|
+
principal: Principal,
|
|
99
|
+
rest: string,
|
|
100
|
+
): Promise<Response | undefined> {
|
|
101
|
+
return rest === '/served' ? servedRoute(request, principal) : undefined
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
/** Answers `<plugin>/api/notices` and `/notices/mine`. */
|
|
105
|
+
async notices(request: Request, principal: Principal, rest: string): Promise<Response> {
|
|
106
|
+
if (rest === '' && request.method === 'POST') return post(request, principal)
|
|
107
|
+
if (rest === '/mine' && request.method === 'GET') {
|
|
108
|
+
const taken = await notices.take(principal.id)
|
|
109
|
+
return json({
|
|
110
|
+
items: taken.map((n) => ({
|
|
111
|
+
kind: n.kind,
|
|
112
|
+
message: n.message,
|
|
113
|
+
link: n.link,
|
|
114
|
+
createdAt: n.createdAt.toISOString(),
|
|
115
|
+
})),
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
return new Response(null, { status: rest === '' || rest === '/mine' ? 405 : 404 })
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What of the site's schema the served copy holds (story 395), from the changes a
|
|
3
|
+
* host reported applying there. Schema is served when the change that last touched
|
|
4
|
+
* it was reported, or came before the oldest one reported. Only what the served
|
|
5
|
+
* copy does not have at all is held back from making content; a page using
|
|
6
|
+
* anything not yet served names the changes it needs.
|
|
7
|
+
*/
|
|
8
|
+
import { normaliseUuid, problemDetails, problemResponse } from '@crombolo/core'
|
|
9
|
+
import {
|
|
10
|
+
ComponentRepository,
|
|
11
|
+
ContentTypeRepository,
|
|
12
|
+
type Db,
|
|
13
|
+
type FileVersion,
|
|
14
|
+
ServedChangeRepository,
|
|
15
|
+
} from '@crombolo/data'
|
|
16
|
+
|
|
17
|
+
const TYPE_FILES = 'schema/content-types/'
|
|
18
|
+
const COMPONENT_FILES = 'components/'
|
|
19
|
+
|
|
20
|
+
/** What a page needs, by the kind a host is told. */
|
|
21
|
+
export type NeededKind = 'documentType' | 'elementType' | 'template'
|
|
22
|
+
|
|
23
|
+
/** One unserved change a page needs, and what for. */
|
|
24
|
+
export interface NeededChange {
|
|
25
|
+
key: string
|
|
26
|
+
name: string | null
|
|
27
|
+
items: Array<{ kind: NeededKind; alias: string }>
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface Item {
|
|
31
|
+
kind: NeededKind
|
|
32
|
+
key: string
|
|
33
|
+
alias: string
|
|
34
|
+
made: boolean
|
|
35
|
+
changes: Array<{ key: string; name: string | null }>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What the served copy lacks, when a host has reported anything. */
|
|
39
|
+
export interface ServedView {
|
|
40
|
+
/** Types and element types the served copy does not have. */
|
|
41
|
+
hiddenTypes: ReadonlySet<string>
|
|
42
|
+
/** Templates, by component key, the served copy does not have. */
|
|
43
|
+
hiddenTemplates: ReadonlySet<string>
|
|
44
|
+
/** Everything touched since, made or changed, by its key. */
|
|
45
|
+
pending: ReadonlyMap<string, Item>
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const firstLine = (text: string, name: string) =>
|
|
49
|
+
new RegExp(`^${name}\\s*=\\s*"([^"]*)"`, 'm').exec(text)?.[1]
|
|
50
|
+
|
|
51
|
+
const cache = new WeakMap<Db, { revision: string; view: ServedView | undefined }>()
|
|
52
|
+
|
|
53
|
+
/** The served copy's view of the schema, or undefined while nothing is reported. */
|
|
54
|
+
export async function servedView(db: Db): Promise<ServedView | undefined> {
|
|
55
|
+
const served = new ServedChangeRepository(db)
|
|
56
|
+
const revision = await served.revision()
|
|
57
|
+
const known = cache.get(db)
|
|
58
|
+
if (known?.revision === revision) return known.view
|
|
59
|
+
const view = await build(db, served)
|
|
60
|
+
cache.set(db, { revision, view })
|
|
61
|
+
return view
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function build(db: Db, served: ServedChangeRepository): Promise<ServedView | undefined> {
|
|
65
|
+
const reported = await served.keys()
|
|
66
|
+
if (reported.size === 0) return undefined
|
|
67
|
+
const since = (await served.since())?.getTime() ?? Number.POSITIVE_INFINITY
|
|
68
|
+
const isServed = (v: FileVersion) =>
|
|
69
|
+
reported.has(normaliseUuid(v.changeKey)) || v.startedAt.getTime() < since
|
|
70
|
+
const byPath = new Map<string, FileVersion[]>()
|
|
71
|
+
for (const v of await served.fileVersions([TYPE_FILES, COMPONENT_FILES]))
|
|
72
|
+
byPath.set(v.path, [...(byPath.get(v.path) ?? []), v])
|
|
73
|
+
const latest = [...byPath.values()].map((vs) => vs[vs.length - 1] as FileVersion)
|
|
74
|
+
const texts = await served.texts(
|
|
75
|
+
latest.flatMap((v) => (v.afterHash && v.path.startsWith(TYPE_FILES) ? [v.afterHash] : [])),
|
|
76
|
+
)
|
|
77
|
+
const typeKeys = new Map(
|
|
78
|
+
[...(await new ContentTypeRepository(db).aliasesByKey())].map(([key, alias]) => [alias, key]),
|
|
79
|
+
)
|
|
80
|
+
const componentKeys = new Map(
|
|
81
|
+
(await new ComponentRepository(db).all()).map((c) => [c.alias, c.key]),
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
const hiddenTypes = new Set<string>()
|
|
85
|
+
const hiddenTemplates = new Set<string>()
|
|
86
|
+
const pending = new Map<string, Item>()
|
|
87
|
+
for (const [path, versions] of byPath) {
|
|
88
|
+
const last = versions[versions.length - 1] as FileVersion
|
|
89
|
+
if (last.removed) continue
|
|
90
|
+
const identity = identityOf(path, last, texts, typeKeys, componentKeys)
|
|
91
|
+
if (!identity) continue
|
|
92
|
+
const unserved = versions.filter((v) => !isServed(v))
|
|
93
|
+
if (unserved.length === 0) continue
|
|
94
|
+
const madeAt = [...versions].reverse().find((v) => v.made)
|
|
95
|
+
const made = madeAt !== undefined && !isServed(madeAt)
|
|
96
|
+
const changes = [
|
|
97
|
+
...new Map(unserved.map((v) => [v.changeKey, { key: v.changeKey, name: v.changeName }])),
|
|
98
|
+
].map(([, c]) => c)
|
|
99
|
+
pending.set(identity.key, { ...identity, made, changes })
|
|
100
|
+
if (made) (identity.kind === 'template' ? hiddenTemplates : hiddenTypes).add(identity.key)
|
|
101
|
+
}
|
|
102
|
+
return { hiddenTypes, hiddenTemplates, pending }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function identityOf(
|
|
106
|
+
path: string,
|
|
107
|
+
last: FileVersion,
|
|
108
|
+
texts: ReadonlyMap<string, string>,
|
|
109
|
+
typeKeys: ReadonlyMap<string, string>,
|
|
110
|
+
componentKeys: ReadonlyMap<string, string>,
|
|
111
|
+
): { kind: NeededKind; key: string; alias: string } | undefined {
|
|
112
|
+
if (path.startsWith(TYPE_FILES)) {
|
|
113
|
+
const text = last.afterHash ? texts.get(last.afterHash) : undefined
|
|
114
|
+
const alias = text ? firstLine(text, 'alias') : undefined
|
|
115
|
+
if (!text || !alias) return undefined
|
|
116
|
+
const key = firstLine(text, 'key') ?? typeKeys.get(alias)
|
|
117
|
+
if (!key) return undefined
|
|
118
|
+
const element = /^is-element\s*=\s*true/m.test(text)
|
|
119
|
+
return { kind: element ? 'elementType' : 'documentType', key: normaliseUuid(key), alias }
|
|
120
|
+
}
|
|
121
|
+
const alias = path
|
|
122
|
+
.slice(COMPONENT_FILES.length)
|
|
123
|
+
.replace(/\.[a-z]+$/i, '')
|
|
124
|
+
.split('/')
|
|
125
|
+
.pop()
|
|
126
|
+
const key = alias ? componentKeys.get(alias) : undefined
|
|
127
|
+
return alias && key ? { kind: 'template', key: normaliseUuid(key), alias } : undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const ELEMENT_KEY = /"contentTypeKey"\s*:\s*"([0-9a-f-]{36})"/gi
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The unserved changes a page needs: those that made or last changed its type, its
|
|
134
|
+
* template, or the element types its blocks use. Empty when it needs none.
|
|
135
|
+
*/
|
|
136
|
+
export function neededBy(
|
|
137
|
+
view: ServedView,
|
|
138
|
+
page: { contentTypeKey: string; componentKey: string | null; values: unknown },
|
|
139
|
+
): NeededChange[] {
|
|
140
|
+
const keys = new Set([normaliseUuid(page.contentTypeKey)])
|
|
141
|
+
if (page.componentKey) keys.add(normaliseUuid(page.componentKey))
|
|
142
|
+
for (const m of JSON.stringify(page.values ?? []).matchAll(ELEMENT_KEY))
|
|
143
|
+
keys.add(normaliseUuid(m[1] as string))
|
|
144
|
+
const out = new Map<string, NeededChange>()
|
|
145
|
+
for (const key of keys) {
|
|
146
|
+
const item = view.pending.get(key)
|
|
147
|
+
if (!item) continue
|
|
148
|
+
for (const change of item.changes) {
|
|
149
|
+
const entry = out.get(change.key) ?? { ...change, items: [] }
|
|
150
|
+
if (!entry.items.some((i) => i.kind === item.kind && i.alias === item.alias))
|
|
151
|
+
entry.items.push({ kind: item.kind, alias: item.alias })
|
|
152
|
+
out.set(change.key, entry)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return [...out.values()]
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Operations that change schema or code, refused outside a named workspace once anything is reported. */
|
|
159
|
+
export function isSchemaWrite(operationId: string, method: string): boolean {
|
|
160
|
+
if (method === 'GET') return false
|
|
161
|
+
if (/Folder|AvailableCompositions|QueryExecute/.test(operationId)) return false
|
|
162
|
+
return /^(Post|Put|Delete|Patch)(DocumentType|MediaType|MemberType|DataType|PartialView|Script|Stylesheet|Template)/.test(
|
|
163
|
+
operationId,
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** The refusal of a schema change outside a named workspace. */
|
|
168
|
+
export const schemaInWorkspace = (): Response =>
|
|
169
|
+
problemResponse(
|
|
170
|
+
problemDetails({
|
|
171
|
+
title: 'Build this in a workspace',
|
|
172
|
+
status: 409,
|
|
173
|
+
detail:
|
|
174
|
+
'Types, data types, templates, components, stylesheets and scripts go to the live site with a release here: open a workspace to change them.',
|
|
175
|
+
}),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
/** Operations whose answer offers types for a new page or Library item. */
|
|
179
|
+
export const OFFERS_TYPES: ReadonlySet<string> = new Set([
|
|
180
|
+
'GetDocumentTypeAllowedAtRoot',
|
|
181
|
+
'GetDocumentTypeByIdAllowedChildren',
|
|
182
|
+
'GetDocumentTypeAllowedInLibrary',
|
|
183
|
+
])
|
|
184
|
+
|
|
185
|
+
/** The header the back office sends when someone is making content, rather than schema. */
|
|
186
|
+
export const PURPOSE_HEADER = 'crombolo-purpose'
|
|
187
|
+
|
|
188
|
+
type Json = Record<string, unknown>
|
|
189
|
+
|
|
190
|
+
/** An answer with what the served copy lacks taken out of what it offers. */
|
|
191
|
+
export async function withoutUnserved(
|
|
192
|
+
response: Response,
|
|
193
|
+
operationId: string,
|
|
194
|
+
view: ServedView,
|
|
195
|
+
makingContent: boolean,
|
|
196
|
+
): Promise<Response> {
|
|
197
|
+
const types = OFFERS_TYPES.has(operationId)
|
|
198
|
+
const typeDetail = makingContent && operationId === 'GetDocumentTypeById'
|
|
199
|
+
const dataType = makingContent && operationId === 'GetDataTypeById'
|
|
200
|
+
if (!response.ok || (!types && !typeDetail && !dataType)) return response
|
|
201
|
+
const body = (await response.json()) as Json
|
|
202
|
+
const hidden = (id: unknown) => typeof id === 'string' && view.hiddenTypes.has(normaliseUuid(id))
|
|
203
|
+
if (types && Array.isArray(body.items)) {
|
|
204
|
+
const items = (body.items as Json[]).filter((i) => !hidden(i.id))
|
|
205
|
+
body.total = Math.max(
|
|
206
|
+
0,
|
|
207
|
+
Number(body.total ?? items.length) - (body.items.length - items.length),
|
|
208
|
+
)
|
|
209
|
+
body.items = items
|
|
210
|
+
}
|
|
211
|
+
if (typeDetail) {
|
|
212
|
+
const template = (t: unknown) =>
|
|
213
|
+
typeof (t as Json | null)?.id === 'string' &&
|
|
214
|
+
view.hiddenTemplates.has(normaliseUuid((t as Json).id as string))
|
|
215
|
+
if (Array.isArray(body.allowedTemplates))
|
|
216
|
+
body.allowedTemplates = (body.allowedTemplates as unknown[]).filter((t) => !template(t))
|
|
217
|
+
if (template(body.defaultTemplate)) body.defaultTemplate = null
|
|
218
|
+
}
|
|
219
|
+
if (dataType && Array.isArray(body.values))
|
|
220
|
+
body.values = (body.values as Json[]).map((v) =>
|
|
221
|
+
v.alias === 'blocks' && Array.isArray(v.value)
|
|
222
|
+
? {
|
|
223
|
+
...v,
|
|
224
|
+
value: (v.value as Json[]).filter((b) => !hidden(b.contentElementTypeKey)),
|
|
225
|
+
}
|
|
226
|
+
: v,
|
|
227
|
+
)
|
|
228
|
+
const headers = new Headers(response.headers)
|
|
229
|
+
headers.delete('content-length')
|
|
230
|
+
return new Response(JSON.stringify(body), { status: response.status, headers })
|
|
231
|
+
}
|
package/src/server.ts
CHANGED
|
@@ -116,6 +116,7 @@ import {
|
|
|
116
116
|
UserRepository,
|
|
117
117
|
WorkspaceFileRepository,
|
|
118
118
|
WorkspaceLinkRepository,
|
|
119
|
+
WorkspaceProcessRepository,
|
|
119
120
|
WorkspaceRepository,
|
|
120
121
|
type WritesPaused,
|
|
121
122
|
withAuditContext,
|
|
@@ -274,6 +275,14 @@ import { createRemote, may, type RestartOutcome } from './remote.ts'
|
|
|
274
275
|
import { createChangeRoutes, mayApplyChanges, streamBody } from './remote-changes.ts'
|
|
275
276
|
import { createPeopleExchange } from './remote-people.ts'
|
|
276
277
|
import { createSchemaTransfer, UPLOAD_LIMITS } from './schema-transfer.ts'
|
|
278
|
+
import { createServedApi } from './served-api.ts'
|
|
279
|
+
import {
|
|
280
|
+
isSchemaWrite,
|
|
281
|
+
PURPOSE_HEADER,
|
|
282
|
+
schemaInWorkspace,
|
|
283
|
+
servedView,
|
|
284
|
+
withoutUnserved,
|
|
285
|
+
} from './served-schema.ts'
|
|
277
286
|
import { SiteAssets } from './site-assets.ts'
|
|
278
287
|
import { unknownHostProvided } from './site-file.ts'
|
|
279
288
|
import { PublicFiles } from './site-public.ts'
|
|
@@ -370,10 +379,21 @@ import {
|
|
|
370
379
|
workspaceHosts,
|
|
371
380
|
} from './workspace-access.ts'
|
|
372
381
|
import { createWorkspaceChecks } from './workspace-checks.ts'
|
|
373
|
-
import {
|
|
382
|
+
import {
|
|
383
|
+
createWorkspaceProcesses,
|
|
384
|
+
PROCESS_FAILURES_REPORTED,
|
|
385
|
+
type WorkspaceProcesses,
|
|
386
|
+
type WorkspaceProcessReports,
|
|
387
|
+
workspaceProcessList,
|
|
388
|
+
} from './workspace-processes.ts'
|
|
374
389
|
import { createWorkspaceSchema } from './workspace-schema.ts'
|
|
375
390
|
import { createWorkspaceSites } from './workspace-sites.ts'
|
|
376
|
-
import {
|
|
391
|
+
import {
|
|
392
|
+
createWorkspaceScope,
|
|
393
|
+
createWorkspacesApi,
|
|
394
|
+
OWN_WORKSPACE,
|
|
395
|
+
WORKSPACE_HEADER,
|
|
396
|
+
} from './workspaces.ts'
|
|
377
397
|
|
|
378
398
|
export interface ServerHandle {
|
|
379
399
|
config: CromboloConfig
|
|
@@ -1729,7 +1749,21 @@ export async function createServer(
|
|
|
1729
1749
|
},
|
|
1730
1750
|
onServerEvent: announce,
|
|
1731
1751
|
// Story 375: a request in a workspace, with the workspace held while it runs.
|
|
1732
|
-
|
|
1752
|
+
// Story 395: outside a named one, schema is refused and what is not served is not offered.
|
|
1753
|
+
scope: async (request, principal, operation) => {
|
|
1754
|
+
const named = request.headers.get(WORKSPACE_HEADER)?.trim()
|
|
1755
|
+
const view = named && named.toLowerCase() !== OWN_WORKSPACE ? undefined : await servedView(db)
|
|
1756
|
+
if (view && isSchemaWrite(operation.operationId, request.method)) return schemaInWorkspace()
|
|
1757
|
+
const scope = await workspaceScope(request, principal, operation)
|
|
1758
|
+
if (!view || scope instanceof Response) return scope
|
|
1759
|
+
const making = request.headers.get(PURPOSE_HEADER)?.trim().toLowerCase() === 'content'
|
|
1760
|
+
const filtered = async <T>(answer: T): Promise<T> =>
|
|
1761
|
+
answer instanceof Response
|
|
1762
|
+
? ((await withoutUnserved(answer, operation.operationId, view, making)) as T)
|
|
1763
|
+
: answer
|
|
1764
|
+
if (scope) return { run: async (fn) => filtered(await scope.run(fn)) }
|
|
1765
|
+
return request.method === 'GET' ? { run: async (fn) => filtered(await fn()) } : undefined
|
|
1766
|
+
},
|
|
1733
1767
|
})
|
|
1734
1768
|
|
|
1735
1769
|
// Fixed by the contract and the client's SDK, wherever the editor is mounted.
|
|
@@ -1752,6 +1786,36 @@ export async function createServer(
|
|
|
1752
1786
|
}
|
|
1753
1787
|
}
|
|
1754
1788
|
|
|
1789
|
+
// Story 396: how many workspaces' processes keep failing, across the nodes, for /health.
|
|
1790
|
+
const processLog = logger('workspaces')
|
|
1791
|
+
const processRows = new WorkspaceProcessRepository(db)
|
|
1792
|
+
let failingWorkspaces = 0
|
|
1793
|
+
let failingCheckedAt = 0
|
|
1794
|
+
const refreshFailing = async () => {
|
|
1795
|
+
if (Date.now() - failingCheckedAt < 5000) return
|
|
1796
|
+
failingCheckedAt = Date.now()
|
|
1797
|
+
failingWorkspaces = await processRows
|
|
1798
|
+
.failing(PROCESS_FAILURES_REPORTED)
|
|
1799
|
+
.catch(() => failingWorkspaces)
|
|
1800
|
+
}
|
|
1801
|
+
const processReports: WorkspaceProcessReports = {
|
|
1802
|
+
started: (workspace) => {
|
|
1803
|
+
void processRows.started(schema.nodeId, workspace.key).catch(() => {})
|
|
1804
|
+
},
|
|
1805
|
+
stopped: (workspace) => {
|
|
1806
|
+
void processRows.stopped(schema.nodeId, workspace.key).catch(() => {})
|
|
1807
|
+
},
|
|
1808
|
+
failed: (workspace, reason) => {
|
|
1809
|
+
processLog.warning('workspace.process.failed {workspace} on node {nodeId}: {reason}', {
|
|
1810
|
+
workspace: workspace.key,
|
|
1811
|
+
nodeId: schema.nodeId,
|
|
1812
|
+
reason,
|
|
1813
|
+
})
|
|
1814
|
+
failingCheckedAt = 0
|
|
1815
|
+
void processRows.failed(schema.nodeId, workspace.key, reason).catch(() => {})
|
|
1816
|
+
},
|
|
1817
|
+
}
|
|
1818
|
+
|
|
1755
1819
|
const health = () => {
|
|
1756
1820
|
const paused = poller.paused
|
|
1757
1821
|
const readOnly = schema.compatibilityMode || poller.behind || paused !== undefined
|
|
@@ -1780,6 +1844,8 @@ export async function createServer(
|
|
|
1780
1844
|
// Where jobs run, and on a node that leaves them to a worker whether one
|
|
1781
1845
|
// is running them; reported, never drained on (story 223).
|
|
1782
1846
|
...(config.role === 'web' ? {} : { jobs: core.workerWatch.status() }),
|
|
1847
|
+
// Reported, never drained on: one workspace failing is its owner's to fix.
|
|
1848
|
+
workspaces: { failing: failingWorkspaces },
|
|
1783
1849
|
}
|
|
1784
1850
|
}
|
|
1785
1851
|
|
|
@@ -1839,8 +1905,10 @@ export async function createServer(
|
|
|
1839
1905
|
idleMs: config.workspaceProcessIdleMinutes * 60_000,
|
|
1840
1906
|
memoryMb: config.workspaceProcessMemoryMb,
|
|
1841
1907
|
renderMs: config.workspaceRenderSeconds * 1000,
|
|
1908
|
+
reports: processReports,
|
|
1842
1909
|
})
|
|
1843
1910
|
: undefined
|
|
1911
|
+
if (workspaceProcesses) await processRows.nodeStarted(schema.nodeId).catch(() => {})
|
|
1844
1912
|
const workspacesApi = createWorkspacesApi(db, {
|
|
1845
1913
|
enabled: () => workspacesOn(config),
|
|
1846
1914
|
locked: () => contentLocked(config),
|
|
@@ -1931,6 +1999,11 @@ export async function createServer(
|
|
|
1931
1999
|
return `workspaces/${open[1]}/change`
|
|
1932
2000
|
return undefined
|
|
1933
2001
|
}
|
|
2002
|
+
// Story 395: the served copy's changes, reported by a host, and its notices for people.
|
|
2003
|
+
const noticesPath = `${paths.pluginPath}/api/notices`
|
|
2004
|
+
const servedApi = createServedApi(db, {
|
|
2005
|
+
mayApply: async (principal) => mayApplyChanges(principal, config.applyChangesBy, may),
|
|
2006
|
+
})
|
|
1934
2007
|
/** A token the caller set in `Authorization`, never the back office's cookie. */
|
|
1935
2008
|
const carriesBearer = (request: Request) => {
|
|
1936
2009
|
const header = request.headers.get('authorization')
|
|
@@ -2081,6 +2154,7 @@ export async function createServer(
|
|
|
2081
2154
|
|
|
2082
2155
|
// Non-contract, unauthenticated: a load balancer drains a node that has fallen behind.
|
|
2083
2156
|
if (pathname === '/health') {
|
|
2157
|
+
await refreshFailing()
|
|
2084
2158
|
const status = health()
|
|
2085
2159
|
return Response.json(status, { status: status.ok ? 200 : 503 })
|
|
2086
2160
|
}
|
|
@@ -3411,6 +3485,25 @@ export async function createServer(
|
|
|
3411
3485
|
)
|
|
3412
3486
|
}
|
|
3413
3487
|
|
|
3488
|
+
// Story 395: what the served copy holds, and notices a host leaves for a person.
|
|
3489
|
+
if (pathname === `${changesPath}/served` || pathname === noticesPath) {
|
|
3490
|
+
if (!carriesBearer(request))
|
|
3491
|
+
return Response.json(
|
|
3492
|
+
{ message: 'A host calls this with a sign-in token in Authorization, not a cookie.' },
|
|
3493
|
+
{ status: 401 },
|
|
3494
|
+
)
|
|
3495
|
+
const principal = await authenticate(request)
|
|
3496
|
+
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
3497
|
+
return pathname === noticesPath
|
|
3498
|
+
? servedApi.notices(request, principal, '')
|
|
3499
|
+
: ((await servedApi.changes(request, principal, '/served')) as Response)
|
|
3500
|
+
}
|
|
3501
|
+
if (pathname === `${noticesPath}/mine`) {
|
|
3502
|
+
const principal = await authenticate(request)
|
|
3503
|
+
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
3504
|
+
return servedApi.notices(request, principal, '/mine')
|
|
3505
|
+
}
|
|
3506
|
+
|
|
3414
3507
|
// Story 394: a change exported or taken, for a token in Authorization alone.
|
|
3415
3508
|
const moving = managementChange(pathname, request.method)
|
|
3416
3509
|
if (moving) {
|
|
@@ -3427,6 +3520,18 @@ export async function createServer(
|
|
|
3427
3520
|
)
|
|
3428
3521
|
}
|
|
3429
3522
|
|
|
3523
|
+
// Story 396: the workspaces whose processes run, or keep failing, across the nodes.
|
|
3524
|
+
if (pathname === `${workspacesPath}/processes` && request.method === 'GET') {
|
|
3525
|
+
const principal = await authenticate(request)
|
|
3526
|
+
if (!principal) return new Response('Unauthorized', { status: 401 })
|
|
3527
|
+
if (!hasSection(principal, 'settings'))
|
|
3528
|
+
return Response.json(
|
|
3529
|
+
{ message: 'Workspace processes are for people who look after the site.' },
|
|
3530
|
+
{ status: 403 },
|
|
3531
|
+
)
|
|
3532
|
+
return Response.json({ items: await workspaceProcessList(db) })
|
|
3533
|
+
}
|
|
3534
|
+
|
|
3430
3535
|
// Story 375: workspaces, opened, listed, shared and discarded.
|
|
3431
3536
|
if (pathname === workspacesPath || pathname.startsWith(`${workspacesPath}/`)) {
|
|
3432
3537
|
const principal = await authenticate(request)
|
package/src/webhooks.ts
CHANGED
|
@@ -240,8 +240,40 @@ export interface WebhookFacts extends RaisedWebhookEvent {
|
|
|
240
240
|
via?: string
|
|
241
241
|
/** Its ancestors' keys, nearest first, for Crombolo's payload (story 208). */
|
|
242
242
|
ancestors?: string[]
|
|
243
|
+
/** The change a publish finished (story 388), who made it, and what it needs (story 395). */
|
|
244
|
+
change?: {
|
|
245
|
+
key: string
|
|
246
|
+
name: string | null
|
|
247
|
+
by?: 'person' | 'tool'
|
|
248
|
+
tool?: { id: string; name: string }
|
|
249
|
+
needs?: Array<{
|
|
250
|
+
key: string
|
|
251
|
+
name: string | null
|
|
252
|
+
items: Array<{ kind: string; alias: string }>
|
|
253
|
+
}>
|
|
254
|
+
/** Story 397: published in the person's own workspace, merging that page alone. */
|
|
255
|
+
from?: 'own-workspace'
|
|
256
|
+
}
|
|
243
257
|
}
|
|
244
258
|
|
|
259
|
+
/** The change as a payload names it (story 395). Pure. */
|
|
260
|
+
const changeOf = (change: NonNullable<WebhookFacts['change']>) => ({
|
|
261
|
+
Key: change.key,
|
|
262
|
+
Name: change.name,
|
|
263
|
+
By: change.by ?? 'person',
|
|
264
|
+
...(change.tool ? { Tool: { Id: change.tool.id, Name: change.tool.name } } : {}),
|
|
265
|
+
...(change.needs
|
|
266
|
+
? {
|
|
267
|
+
Needs: change.needs.map((n) => ({
|
|
268
|
+
Key: n.key,
|
|
269
|
+
Name: n.name,
|
|
270
|
+
Items: n.items.map((i) => ({ Kind: i.kind, Alias: i.alias })),
|
|
271
|
+
})),
|
|
272
|
+
}
|
|
273
|
+
: {}),
|
|
274
|
+
...(change.from ? { From: change.from } : {}),
|
|
275
|
+
})
|
|
276
|
+
|
|
245
277
|
/** An event as the site's own handler receives it (story 298). Pure. */
|
|
246
278
|
export function siteEventOf(facts: WebhookFacts): SiteContentEvent {
|
|
247
279
|
return {
|
|
@@ -258,11 +290,13 @@ export function webhookPayload(
|
|
|
258
290
|
facts: WebhookFacts,
|
|
259
291
|
payload: WebhookDefinition['payload'],
|
|
260
292
|
): Record<string, unknown> {
|
|
261
|
-
|
|
293
|
+
const change = facts.change ? { Change: changeOf(facts.change) } : {}
|
|
294
|
+
if (payload !== 'crombolo') return { Id: facts.key, ...change }
|
|
262
295
|
return {
|
|
263
296
|
Id: facts.key,
|
|
264
297
|
ContentType: facts.contentTypeAlias ?? null,
|
|
265
298
|
Ancestors: facts.ancestors ?? [],
|
|
299
|
+
...change,
|
|
266
300
|
}
|
|
267
301
|
}
|
|
268
302
|
|
|
@@ -9,7 +9,14 @@
|
|
|
9
9
|
*/
|
|
10
10
|
import { fileURLToPath } from 'node:url'
|
|
11
11
|
import { Outcome, type OutcomeStatus } from '@crombolo/core'
|
|
12
|
-
import
|
|
12
|
+
import {
|
|
13
|
+
type Db,
|
|
14
|
+
type DialectName,
|
|
15
|
+
type NodeSchemaState,
|
|
16
|
+
WorkspaceProcessRepository,
|
|
17
|
+
WorkspaceRepository,
|
|
18
|
+
type WorkspaceScope,
|
|
19
|
+
} from '@crombolo/data'
|
|
13
20
|
import type {
|
|
14
21
|
PublishedCache,
|
|
15
22
|
PublishedContent,
|
|
@@ -31,6 +38,8 @@ interface Running {
|
|
|
31
38
|
waiting: Map<number, (answer: ProcessRender) => void>
|
|
32
39
|
usedAt: number
|
|
33
40
|
rss: number
|
|
41
|
+
/** Whether it said it was ready. */
|
|
42
|
+
started: boolean
|
|
34
43
|
}
|
|
35
44
|
|
|
36
45
|
export interface WorkspaceProcessOptions {
|
|
@@ -46,16 +55,28 @@ export interface WorkspaceProcessOptions {
|
|
|
46
55
|
idleMs: number
|
|
47
56
|
memoryMb: number
|
|
48
57
|
renderMs: number
|
|
58
|
+
/** Story 396: told of each process started and stopped, and of each that failed. */
|
|
59
|
+
reports?: WorkspaceProcessReports
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Where a node tells the site of its workspaces' processes (story 396). */
|
|
63
|
+
export interface WorkspaceProcessReports {
|
|
64
|
+
started(workspace: { key: string }): void
|
|
65
|
+
stopped(workspace: { key: string }): void
|
|
66
|
+
failed(workspace: { key: string; name: string }, reason: string): void
|
|
49
67
|
}
|
|
50
68
|
|
|
51
69
|
export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
52
70
|
const running = new Map<string, Running>()
|
|
53
71
|
let next = 1
|
|
54
72
|
|
|
55
|
-
|
|
73
|
+
/** Stops a workspace's process; `failed` when it crashed, hung or never came up. */
|
|
74
|
+
const stop = (key: string, why: string, failed = false) => {
|
|
56
75
|
const one = running.get(key)
|
|
57
76
|
if (!one) return
|
|
58
77
|
running.delete(key)
|
|
78
|
+
options.reports?.stopped(one.workspace)
|
|
79
|
+
if (failed) options.reports?.failed(one.workspace, why)
|
|
59
80
|
for (const answer of one.waiting.values())
|
|
60
81
|
answer({ type: 'rendered', id: 0, status: 'error', error: why })
|
|
61
82
|
one.waiting.clear()
|
|
@@ -84,6 +105,7 @@ export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
|
84
105
|
workspace,
|
|
85
106
|
usedAt: Date.now(),
|
|
86
107
|
rss: 0,
|
|
108
|
+
started: false,
|
|
87
109
|
waiting: new Map(),
|
|
88
110
|
ready: new Promise<void>((resolve) => {
|
|
89
111
|
ready = resolve
|
|
@@ -94,17 +116,23 @@ export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
|
94
116
|
stderr: 'ignore',
|
|
95
117
|
env: { ...process.env },
|
|
96
118
|
ipc(message: ChildAnswer) {
|
|
97
|
-
if (message.type === 'ready')
|
|
98
|
-
|
|
119
|
+
if (message.type === 'ready') {
|
|
120
|
+
one.started = true
|
|
121
|
+
ready()
|
|
122
|
+
} else if (message.type === 'memory') one.rss = message.rss
|
|
99
123
|
else {
|
|
100
124
|
const answer = one.waiting.get(message.id)
|
|
101
125
|
one.waiting.delete(message.id)
|
|
102
126
|
answer?.(message)
|
|
103
127
|
}
|
|
104
128
|
},
|
|
105
|
-
onExit() {
|
|
129
|
+
onExit(_proc, exitCode, signal) {
|
|
106
130
|
if (running.get(workspace.key) === one)
|
|
107
|
-
stop(
|
|
131
|
+
stop(
|
|
132
|
+
workspace.key,
|
|
133
|
+
`The workspace "${workspace.name}" stopped on its own (${signal ?? `exit code ${exitCode}`}).`,
|
|
134
|
+
true,
|
|
135
|
+
)
|
|
108
136
|
},
|
|
109
137
|
}),
|
|
110
138
|
}
|
|
@@ -121,6 +149,7 @@ export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
|
121
149
|
}
|
|
122
150
|
one.proc.send(init)
|
|
123
151
|
running.set(workspace.key, one)
|
|
152
|
+
options.reports?.started(workspace)
|
|
124
153
|
sweep()
|
|
125
154
|
return one
|
|
126
155
|
}
|
|
@@ -137,10 +166,13 @@ export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
|
137
166
|
const limit = new Promise<ProcessRender>((resolve) => {
|
|
138
167
|
const t = setTimeout(() => {
|
|
139
168
|
if (!one.waiting.has(id)) return
|
|
140
|
-
// Over its time: this render is answered, and its process is stopped.
|
|
169
|
+
// Over its time: this render is answered, and its process is stopped, as failed.
|
|
141
170
|
stop(
|
|
142
171
|
workspace.key,
|
|
143
|
-
|
|
172
|
+
one.started
|
|
173
|
+
? `The workspace "${workspace.name}" took longer than ${Math.round(options.renderMs / 1000)} seconds to render this page.`
|
|
174
|
+
: `The workspace "${workspace.name}" did not start within ${Math.round(options.renderMs / 1000)} seconds.`,
|
|
175
|
+
true,
|
|
144
176
|
)
|
|
145
177
|
resolve({
|
|
146
178
|
type: 'rendered',
|
|
@@ -232,6 +264,48 @@ export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
|
232
264
|
|
|
233
265
|
export type WorkspaceProcesses = ReturnType<typeof createWorkspaceProcesses>
|
|
234
266
|
|
|
267
|
+
/** How many failures in the hour put a workspace on the list (story 396). */
|
|
268
|
+
export const PROCESS_FAILURES_REPORTED = 3
|
|
269
|
+
|
|
270
|
+
/** A node not seen within this long runs nothing, as far as the list goes. */
|
|
271
|
+
const NODE_SEEN_WITHIN_MS = 60_000
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* The workspaces with a process running on a live node, and those that failed three
|
|
275
|
+
* or more times in the last hour, with who to tell (story 396).
|
|
276
|
+
*/
|
|
277
|
+
export async function workspaceProcessList(db: Db) {
|
|
278
|
+
const reports = await new WorkspaceProcessRepository(db).report({
|
|
279
|
+
seenWithinMs: NODE_SEEN_WITHIN_MS,
|
|
280
|
+
})
|
|
281
|
+
const workspaces = new WorkspaceRepository(db)
|
|
282
|
+
const out = []
|
|
283
|
+
for (const report of reports) {
|
|
284
|
+
const failing = report.failures >= PROCESS_FAILURES_REPORTED
|
|
285
|
+
if (!failing && report.nodes.length === 0) continue
|
|
286
|
+
const workspace = await workspaces.byKey(report.key)
|
|
287
|
+
const owner = workspace
|
|
288
|
+
? await db.q
|
|
289
|
+
.selectFrom('user_account')
|
|
290
|
+
.select('user_name')
|
|
291
|
+
.where('key', '=', workspace.ownerKey)
|
|
292
|
+
.executeTakeFirst()
|
|
293
|
+
: undefined
|
|
294
|
+
out.push({
|
|
295
|
+
key: report.key,
|
|
296
|
+
name: workspace?.name ?? null,
|
|
297
|
+
owner: workspace ? { key: workspace.ownerKey, name: owner?.user_name ?? null } : null,
|
|
298
|
+
nodes: report.nodes,
|
|
299
|
+
running: report.nodes.length > 0,
|
|
300
|
+
failing,
|
|
301
|
+
failures: report.failures,
|
|
302
|
+
lastError: report.lastError,
|
|
303
|
+
since: report.since.toISOString(),
|
|
304
|
+
})
|
|
305
|
+
}
|
|
306
|
+
return out
|
|
307
|
+
}
|
|
308
|
+
|
|
235
309
|
const MAX_ACCESS_SUBSTITUTIONS = 5
|
|
236
310
|
|
|
237
311
|
/** The page to show in place of this one, as `Renderer` settles it; undefined for none. */
|