@crombolo/server 0.69.1 → 0.70.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 +15 -14
- package/src/adapters/blueprints.ts +51 -5
- package/src/adapters/change-recording.ts +140 -0
- package/src/adapters/content.ts +132 -21
- package/src/adapters/documents.ts +26 -5
- package/src/adapters/elements.ts +3 -0
- package/src/adapters/media.ts +7 -1
- package/src/adapters/schema-files.ts +89 -1
- package/src/adapters/workspace-dictionary.ts +287 -0
- package/src/adapters/workspace-file-port.ts +160 -0
- package/src/adapters/workspace-languages.ts +94 -0
- package/src/approvals-api.ts +16 -7
- package/src/bundle-api.ts +19 -16
- package/src/bundle-install.ts +4 -0
- package/src/change-transfer.ts +676 -0
- package/src/changes-api.ts +258 -0
- package/src/component-templates-api.ts +2 -2
- package/src/config.ts +161 -21
- package/src/content-events.ts +65 -1
- package/src/content-operations.ts +22 -3
- package/src/core.ts +2 -0
- package/src/environment-values-api.ts +161 -0
- package/src/node-operations.ts +150 -2
- package/src/ports.ts +174 -52
- package/src/remote-changes.ts +279 -0
- package/src/remote-schema.ts +126 -0
- package/src/remote-workspaces.ts +82 -0
- package/src/remote.ts +289 -192
- package/src/schema-transfer.ts +240 -41
- package/src/schema.ts +7 -2
- package/src/seed/compile.ts +13 -1
- package/src/seed/values.ts +3 -0
- package/src/server.ts +948 -364
- package/src/settings.ts +123 -5
- package/src/site-sections.ts +1 -1
- package/src/workspace-access.ts +152 -0
- package/src/workspace-checks.ts +299 -0
- package/src/workspace-losses.ts +95 -0
- package/src/workspace-processes.ts +306 -0
- package/src/workspace-render-child.ts +168 -0
- package/src/workspace-schema-dir.ts +100 -0
- package/src/workspace-schema.ts +598 -0
- package/src/workspace-sites.ts +179 -0
- package/src/workspace-views.ts +121 -0
- package/src/workspaces.ts +1031 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Story 392: what removing a language, a form's field or a workflow costs, which only
|
|
3
|
+
* the site's data says: a language with values, a field with entries and a workflow
|
|
4
|
+
* with open requests become a change that loses something, accepted by name first.
|
|
5
|
+
*/
|
|
6
|
+
import { CHANGE_CLASSES, type ChangeKind, needsAcceptance } from '@crombolo/core'
|
|
7
|
+
import type { Db } from '@crombolo/data'
|
|
8
|
+
|
|
9
|
+
interface Item {
|
|
10
|
+
id: string
|
|
11
|
+
kind: ChangeKind
|
|
12
|
+
class: string
|
|
13
|
+
subject: string
|
|
14
|
+
accept: boolean
|
|
15
|
+
says: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const OPEN_REQUESTS = ['waiting', 'scheduled']
|
|
19
|
+
|
|
20
|
+
const raised = <T extends Item>(found: T, kind: ChangeKind, says: string): T => ({
|
|
21
|
+
...found,
|
|
22
|
+
id: `${kind}:${found.subject}`,
|
|
23
|
+
kind,
|
|
24
|
+
class: CHANGE_CLASSES[kind],
|
|
25
|
+
accept: needsAcceptance(kind),
|
|
26
|
+
says,
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
const count = async (rows: Promise<Array<{ n: unknown }>>) => Number((await rows)[0]?.n ?? 0)
|
|
30
|
+
|
|
31
|
+
/** Each item as it costs on this site. */
|
|
32
|
+
export async function withLosses<T extends Item>(db: Db, items: readonly T[]): Promise<T[]> {
|
|
33
|
+
const out: T[] = []
|
|
34
|
+
for (const found of items) {
|
|
35
|
+
if (found.kind === 'language-removed') {
|
|
36
|
+
const n = await count(
|
|
37
|
+
db.q
|
|
38
|
+
.selectFrom('property_value as pv')
|
|
39
|
+
.innerJoin('language as l', 'l.id', 'pv.language_id')
|
|
40
|
+
.where('l.iso_code', '=', found.subject)
|
|
41
|
+
.select((eb) => eb.fn.countAll().as('n'))
|
|
42
|
+
.execute(),
|
|
43
|
+
)
|
|
44
|
+
out.push(
|
|
45
|
+
n > 0
|
|
46
|
+
? raised(found, 'language-values-dropped', `${found.says} Its ${n} values go with it.`)
|
|
47
|
+
: found,
|
|
48
|
+
)
|
|
49
|
+
} else if (found.kind === 'form-field-removed') {
|
|
50
|
+
const [form, field] = found.subject.split('.') as [string, string]
|
|
51
|
+
const n = await count(
|
|
52
|
+
db.q
|
|
53
|
+
.selectFrom('form_entry_value as v')
|
|
54
|
+
.innerJoin('form_entry as e', 'e.id', 'v.entry_id')
|
|
55
|
+
.where('e.form_alias', '=', form)
|
|
56
|
+
.where('v.field_alias', '=', field)
|
|
57
|
+
.select((eb) => eb.fn.countAll().as('n'))
|
|
58
|
+
.execute(),
|
|
59
|
+
)
|
|
60
|
+
out.push(
|
|
61
|
+
n > 0
|
|
62
|
+
? raised(
|
|
63
|
+
found,
|
|
64
|
+
'form-field-entries-orphaned',
|
|
65
|
+
`${found.says} ${n} entries hold it, and the form will no longer show it.`,
|
|
66
|
+
)
|
|
67
|
+
: found,
|
|
68
|
+
)
|
|
69
|
+
} else if (found.kind === 'workflow-removed') {
|
|
70
|
+
// Each request holds the workflow it was made under, whole.
|
|
71
|
+
const open = await db.q
|
|
72
|
+
.selectFrom('approval_request')
|
|
73
|
+
.where('state', 'in', OPEN_REQUESTS)
|
|
74
|
+
.select('workflow')
|
|
75
|
+
.execute()
|
|
76
|
+
const n = open.filter((r) => {
|
|
77
|
+
try {
|
|
78
|
+
return (JSON.parse(String(r.workflow)) as { alias?: string }).alias === found.subject
|
|
79
|
+
} catch {
|
|
80
|
+
return false
|
|
81
|
+
}
|
|
82
|
+
}).length
|
|
83
|
+
out.push(
|
|
84
|
+
n > 0
|
|
85
|
+
? raised(
|
|
86
|
+
found,
|
|
87
|
+
'workflow-requests-withdrawn',
|
|
88
|
+
`${found.says} ${n} requests waiting under it are withdrawn.`,
|
|
89
|
+
)
|
|
90
|
+
: found,
|
|
91
|
+
)
|
|
92
|
+
} else out.push(found)
|
|
93
|
+
}
|
|
94
|
+
return out
|
|
95
|
+
}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The processes a node runs a workspace's renders in (story 378): one for each
|
|
3
|
+
* workspace that changed its views, started at its first render and given it.
|
|
4
|
+
* A render that runs over its time is answered with an error naming the
|
|
5
|
+
* workspace, and its process stopped; a crash is the same, and the next render
|
|
6
|
+
* starts it again. A process is stopped when idle, over its memory, when its
|
|
7
|
+
* workspace is merged or discarded, and, past the node's limit, the least
|
|
8
|
+
* recently used. The rest of the site never waits on one.
|
|
9
|
+
*/
|
|
10
|
+
import { fileURLToPath } from 'node:url'
|
|
11
|
+
import { Outcome, type OutcomeStatus } from '@crombolo/core'
|
|
12
|
+
import type { DialectName, NodeSchemaState, WorkspaceScope } from '@crombolo/data'
|
|
13
|
+
import type {
|
|
14
|
+
PublishedCache,
|
|
15
|
+
PublishedContent,
|
|
16
|
+
Renderer,
|
|
17
|
+
RenderRequest,
|
|
18
|
+
RenderResult,
|
|
19
|
+
} from '@crombolo/render'
|
|
20
|
+
import type { ChildAnswer, ChildInit, ChildRender, PlainRequest } from './workspace-render-child.ts'
|
|
21
|
+
|
|
22
|
+
const CHILD = fileURLToPath(new URL('./workspace-render-child.ts', import.meta.url))
|
|
23
|
+
|
|
24
|
+
/** What a render in a workspace's process came to. */
|
|
25
|
+
export type ProcessRender = Extract<ChildAnswer, { type: 'rendered' }>
|
|
26
|
+
|
|
27
|
+
interface Running {
|
|
28
|
+
workspace: WorkspaceScope & { name: string }
|
|
29
|
+
proc: ReturnType<typeof Bun.spawn>
|
|
30
|
+
ready: Promise<void>
|
|
31
|
+
waiting: Map<number, (answer: ProcessRender) => void>
|
|
32
|
+
usedAt: number
|
|
33
|
+
rss: number
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface WorkspaceProcessOptions {
|
|
37
|
+
dialect: DialectName
|
|
38
|
+
sqliteFile: string
|
|
39
|
+
nodeState: NodeSchemaState
|
|
40
|
+
nodeId: string
|
|
41
|
+
/** The environment whose own values its pages show (story 387). */
|
|
42
|
+
environment?: string
|
|
43
|
+
componentsCacheDir: string
|
|
44
|
+
/** How many run at once on this node. */
|
|
45
|
+
limit: number
|
|
46
|
+
idleMs: number
|
|
47
|
+
memoryMb: number
|
|
48
|
+
renderMs: number
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function createWorkspaceProcesses(options: WorkspaceProcessOptions) {
|
|
52
|
+
const running = new Map<string, Running>()
|
|
53
|
+
let next = 1
|
|
54
|
+
|
|
55
|
+
const stop = (key: string, why: string) => {
|
|
56
|
+
const one = running.get(key)
|
|
57
|
+
if (!one) return
|
|
58
|
+
running.delete(key)
|
|
59
|
+
for (const answer of one.waiting.values())
|
|
60
|
+
answer({ type: 'rendered', id: 0, status: 'error', error: why })
|
|
61
|
+
one.waiting.clear()
|
|
62
|
+
one.proc.kill()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const sweep = () => {
|
|
66
|
+
const now = Date.now()
|
|
67
|
+
for (const [key, one] of running) {
|
|
68
|
+
if (one.waiting.size > 0) continue
|
|
69
|
+
if (now - one.usedAt > options.idleMs) stop(key, 'It was left idle.')
|
|
70
|
+
else if (one.rss > options.memoryMb * 1024 * 1024) stop(key, 'It grew past its memory.')
|
|
71
|
+
}
|
|
72
|
+
while (running.size > Math.max(1, options.limit)) {
|
|
73
|
+
const oldest = [...running.entries()].sort((a, b) => a[1].usedAt - b[1].usedAt)[0]
|
|
74
|
+
if (!oldest) break
|
|
75
|
+
stop(oldest[0], 'Another workspace needed its place.')
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
const timer = setInterval(sweep, 30_000)
|
|
79
|
+
timer.unref?.()
|
|
80
|
+
|
|
81
|
+
function start(workspace: WorkspaceScope & { name: string }): Running {
|
|
82
|
+
let ready!: () => void
|
|
83
|
+
const one: Running = {
|
|
84
|
+
workspace,
|
|
85
|
+
usedAt: Date.now(),
|
|
86
|
+
rss: 0,
|
|
87
|
+
waiting: new Map(),
|
|
88
|
+
ready: new Promise<void>((resolve) => {
|
|
89
|
+
ready = resolve
|
|
90
|
+
}),
|
|
91
|
+
proc: Bun.spawn(['bun', CHILD], {
|
|
92
|
+
stdin: 'ignore',
|
|
93
|
+
stdout: 'ignore',
|
|
94
|
+
stderr: 'ignore',
|
|
95
|
+
env: { ...process.env },
|
|
96
|
+
ipc(message: ChildAnswer) {
|
|
97
|
+
if (message.type === 'ready') ready()
|
|
98
|
+
else if (message.type === 'memory') one.rss = message.rss
|
|
99
|
+
else {
|
|
100
|
+
const answer = one.waiting.get(message.id)
|
|
101
|
+
one.waiting.delete(message.id)
|
|
102
|
+
answer?.(message)
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
onExit() {
|
|
106
|
+
if (running.get(workspace.key) === one)
|
|
107
|
+
stop(workspace.key, `The workspace "${workspace.name}" stopped while it was rendering.`)
|
|
108
|
+
},
|
|
109
|
+
}),
|
|
110
|
+
}
|
|
111
|
+
const init: ChildInit = {
|
|
112
|
+
type: 'init',
|
|
113
|
+
dialect: options.dialect,
|
|
114
|
+
sqliteFile: options.sqliteFile,
|
|
115
|
+
workspace: { id: workspace.id, key: workspace.key },
|
|
116
|
+
nodeState: options.nodeState,
|
|
117
|
+
nodeId: options.nodeId,
|
|
118
|
+
...(options.environment ? { environment: options.environment } : {}),
|
|
119
|
+
componentsCacheDir: options.componentsCacheDir,
|
|
120
|
+
renderTimeoutMs: options.renderMs,
|
|
121
|
+
}
|
|
122
|
+
one.proc.send(init)
|
|
123
|
+
running.set(workspace.key, one)
|
|
124
|
+
sweep()
|
|
125
|
+
return one
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** One page in the workspace's process, starting it if it is not running. */
|
|
129
|
+
async function render(
|
|
130
|
+
workspace: WorkspaceScope & { name: string },
|
|
131
|
+
page: Omit<ChildRender, 'type' | 'id'>,
|
|
132
|
+
): Promise<ProcessRender> {
|
|
133
|
+
const one = running.get(workspace.key) ?? start(workspace)
|
|
134
|
+
one.usedAt = Date.now()
|
|
135
|
+
const id = next++
|
|
136
|
+
const answered = new Promise<ProcessRender>((resolve) => one.waiting.set(id, resolve))
|
|
137
|
+
const limit = new Promise<ProcessRender>((resolve) => {
|
|
138
|
+
const t = setTimeout(() => {
|
|
139
|
+
if (!one.waiting.has(id)) return
|
|
140
|
+
// Over its time: this render is answered, and its process is stopped.
|
|
141
|
+
stop(
|
|
142
|
+
workspace.key,
|
|
143
|
+
`The workspace "${workspace.name}" took longer than ${Math.round(options.renderMs / 1000)} seconds to render this page.`,
|
|
144
|
+
)
|
|
145
|
+
resolve({
|
|
146
|
+
type: 'rendered',
|
|
147
|
+
id,
|
|
148
|
+
status: 'error',
|
|
149
|
+
error: `The workspace "${workspace.name}" took longer than ${Math.round(options.renderMs / 1000)} seconds to render this page.`,
|
|
150
|
+
})
|
|
151
|
+
}, options.renderMs)
|
|
152
|
+
t.unref?.()
|
|
153
|
+
})
|
|
154
|
+
await Promise.race([one.ready, limit])
|
|
155
|
+
const message: ChildRender = { type: 'render', id, ...page }
|
|
156
|
+
if (running.get(workspace.key) === one) one.proc.send(message)
|
|
157
|
+
return Promise.race([answered, limit])
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
render,
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* A renderer for the workspace's site that renders its pages in its process:
|
|
165
|
+
* the node resolves the page and settles who may see it, as `Renderer` does,
|
|
166
|
+
* and the process renders it. Everything else is Shared's renderer's.
|
|
167
|
+
*/
|
|
168
|
+
rendererFor(
|
|
169
|
+
workspace: WorkspaceScope & { name: string },
|
|
170
|
+
cache: PublishedCache,
|
|
171
|
+
shared: Renderer,
|
|
172
|
+
revision: () => string,
|
|
173
|
+
): Renderer {
|
|
174
|
+
const inProcess = async (
|
|
175
|
+
content: PublishedContent,
|
|
176
|
+
culture: string | null,
|
|
177
|
+
request: RenderRequest,
|
|
178
|
+
): Promise<RenderResult> => {
|
|
179
|
+
if (!content.componentAlias) return { status: 'noTemplate', content }
|
|
180
|
+
const answer = await render(workspace, {
|
|
181
|
+
key: content.key,
|
|
182
|
+
culture,
|
|
183
|
+
draft: request.preview === true,
|
|
184
|
+
request: plainOf(request),
|
|
185
|
+
revision: revision(),
|
|
186
|
+
})
|
|
187
|
+
return resultOf(answer, content)
|
|
188
|
+
}
|
|
189
|
+
return new Proxy(shared, {
|
|
190
|
+
get(target, property) {
|
|
191
|
+
if (property === 'render')
|
|
192
|
+
return async (route: string, host = '', request: RenderRequest = {}) => {
|
|
193
|
+
const resolved = await cache.resolve(host, route)
|
|
194
|
+
if (!resolved) return { status: 'notFound' }
|
|
195
|
+
if (resolved.redirect)
|
|
196
|
+
return {
|
|
197
|
+
status: 'redirect',
|
|
198
|
+
location: resolved.redirect,
|
|
199
|
+
content: resolved.content,
|
|
200
|
+
}
|
|
201
|
+
const content = await permitted(cache, resolved.content, resolved.culture, request)
|
|
202
|
+
if (!content) return { status: 'notFound' }
|
|
203
|
+
return inProcess(content, resolved.culture, request)
|
|
204
|
+
}
|
|
205
|
+
if (property === 'renderModel') return inProcess
|
|
206
|
+
const value = Reflect.get(target, property, target)
|
|
207
|
+
return typeof value === 'function' ? value.bind(target) : value
|
|
208
|
+
},
|
|
209
|
+
})
|
|
210
|
+
},
|
|
211
|
+
|
|
212
|
+
/** Stops a workspace's process: merged, discarded, or done with. */
|
|
213
|
+
stop: (key: string) => stop(key, 'It was closed.'),
|
|
214
|
+
|
|
215
|
+
/** The process id running a workspace's renders, if one is: for tests and the status page. */
|
|
216
|
+
pidOf: (key: string) => running.get(key)?.proc.pid,
|
|
217
|
+
|
|
218
|
+
get size(): number {
|
|
219
|
+
return running.size
|
|
220
|
+
},
|
|
221
|
+
|
|
222
|
+
/** Checks the limits now, as the timer does. */
|
|
223
|
+
sweep,
|
|
224
|
+
|
|
225
|
+
/** Stops them all, as the node stops. */
|
|
226
|
+
close(): void {
|
|
227
|
+
clearInterval(timer)
|
|
228
|
+
for (const key of [...running.keys()]) stop(key, 'The site is stopping.')
|
|
229
|
+
},
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export type WorkspaceProcesses = ReturnType<typeof createWorkspaceProcesses>
|
|
234
|
+
|
|
235
|
+
const MAX_ACCESS_SUBSTITUTIONS = 5
|
|
236
|
+
|
|
237
|
+
/** The page to show in place of this one, as `Renderer` settles it; undefined for none. */
|
|
238
|
+
async function permitted(
|
|
239
|
+
cache: PublishedCache,
|
|
240
|
+
content: PublishedContent,
|
|
241
|
+
culture: string | null,
|
|
242
|
+
request: RenderRequest,
|
|
243
|
+
): Promise<PublishedContent | undefined> {
|
|
244
|
+
if (!request.access) return content
|
|
245
|
+
let current = content
|
|
246
|
+
for (let step = 0; step < MAX_ACCESS_SUBSTITUTIONS; step++) {
|
|
247
|
+
const decision = await request.access(current)
|
|
248
|
+
if (decision.status === 'allowed') return current
|
|
249
|
+
if (decision.contentKey.toLowerCase() === current.key.toLowerCase()) return undefined
|
|
250
|
+
const next = await cache.byKey(decision.contentKey, culture)
|
|
251
|
+
if (!next) return undefined
|
|
252
|
+
current = next
|
|
253
|
+
}
|
|
254
|
+
return undefined
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function plainOf(request: RenderRequest): PlainRequest {
|
|
258
|
+
const plain: PlainRequest = {}
|
|
259
|
+
for (const key of [
|
|
260
|
+
'member',
|
|
261
|
+
'origin',
|
|
262
|
+
'url',
|
|
263
|
+
'seo',
|
|
264
|
+
'preview',
|
|
265
|
+
'antiforgery',
|
|
266
|
+
'submission',
|
|
267
|
+
'part',
|
|
268
|
+
] as const)
|
|
269
|
+
if (request[key] !== undefined) (plain as Record<string, unknown>)[key] = request[key]
|
|
270
|
+
if (request.headers) plain.headers = [...request.headers.entries()]
|
|
271
|
+
return plain
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function resultOf(answer: ProcessRender, content: PublishedContent): RenderResult {
|
|
275
|
+
const caching = {
|
|
276
|
+
personal: answer.personal ?? false,
|
|
277
|
+
...(answer.revalidate !== undefined ? { revalidate: answer.revalidate } : {}),
|
|
278
|
+
...(answer.memberFiles ? { memberFiles: answer.memberFiles } : {}),
|
|
279
|
+
}
|
|
280
|
+
switch (answer.status) {
|
|
281
|
+
case 'ok':
|
|
282
|
+
return { status: 'ok', html: answer.html ?? '', content, ...caching }
|
|
283
|
+
case 'outcome':
|
|
284
|
+
return {
|
|
285
|
+
status: 'outcome',
|
|
286
|
+
outcome: Outcome.of((answer.outcome?.status ?? 404) as OutcomeStatus, {
|
|
287
|
+
...(answer.outcome?.message ? { message: answer.outcome.message } : {}),
|
|
288
|
+
...(answer.outcome?.location ? { location: answer.outcome.location } : {}),
|
|
289
|
+
}),
|
|
290
|
+
content,
|
|
291
|
+
...caching,
|
|
292
|
+
}
|
|
293
|
+
case 'redirect':
|
|
294
|
+
return { status: 'redirect', location: answer.location ?? '/', content }
|
|
295
|
+
case 'noTemplate':
|
|
296
|
+
return { status: 'noTemplate', content }
|
|
297
|
+
case 'notFound':
|
|
298
|
+
return { status: 'notFound' }
|
|
299
|
+
default:
|
|
300
|
+
return {
|
|
301
|
+
status: 'error',
|
|
302
|
+
error: new Error(answer.error ?? 'It could not be rendered.'),
|
|
303
|
+
content,
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A workspace's renders, in a process of its own (story 378). Started by the
|
|
3
|
+
* server for a workspace that changed its views, it opens its own connection to
|
|
4
|
+
* the site's database, builds the workspace's published cache and views from
|
|
5
|
+
* what the workspace holds, and renders the pages it is asked for. A template
|
|
6
|
+
* that hangs, crashes or grows only takes this process with it.
|
|
7
|
+
*
|
|
8
|
+
* Messages, over Bun's IPC: `init` (the database, the workspace, where to write
|
|
9
|
+
* its views), then `render` with an id; it answers `ready`, `rendered` with the
|
|
10
|
+
* same id, and `memory` now and then.
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
connect,
|
|
14
|
+
type Db,
|
|
15
|
+
type DialectName,
|
|
16
|
+
type NodeSchemaState,
|
|
17
|
+
type WorkspaceScope,
|
|
18
|
+
} from '@crombolo/data'
|
|
19
|
+
import { contentForNode, PublishedCache, type RenderRequest } from '@crombolo/render'
|
|
20
|
+
import { createPublishedContentSource, loadDraftNode } from './adapters/documents.ts'
|
|
21
|
+
import type { CromboloConfig } from './config.ts'
|
|
22
|
+
import { siteSearchFor } from './site-search.ts'
|
|
23
|
+
import { createWorkspaceViews } from './workspace-views.ts'
|
|
24
|
+
|
|
25
|
+
export interface ChildInit {
|
|
26
|
+
type: 'init'
|
|
27
|
+
dialect: DialectName
|
|
28
|
+
sqliteFile: string
|
|
29
|
+
workspace: WorkspaceScope
|
|
30
|
+
nodeState: NodeSchemaState
|
|
31
|
+
nodeId: string
|
|
32
|
+
environment?: string
|
|
33
|
+
/** Where its views are written: `<componentsCacheDir>-workspaces`. */
|
|
34
|
+
componentsCacheDir: string
|
|
35
|
+
renderTimeoutMs: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What of a render's request can cross to the process: plain values only. */
|
|
39
|
+
export type PlainRequest = Pick<
|
|
40
|
+
RenderRequest,
|
|
41
|
+
'member' | 'origin' | 'url' | 'seo' | 'preview' | 'antiforgery' | 'submission' | 'part'
|
|
42
|
+
> & { headers?: Array<[string, string]> }
|
|
43
|
+
|
|
44
|
+
export interface ChildRender {
|
|
45
|
+
type: 'render'
|
|
46
|
+
id: number
|
|
47
|
+
/** The page, its access already settled by the node: published, or its draft for a preview. */
|
|
48
|
+
key: string
|
|
49
|
+
culture: string | null
|
|
50
|
+
draft: boolean
|
|
51
|
+
request: PlainRequest
|
|
52
|
+
/** The workspace's revision now: when it moved, the cache starts again. */
|
|
53
|
+
revision: string
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export type ChildAnswer =
|
|
57
|
+
| { type: 'ready' }
|
|
58
|
+
| { type: 'memory'; rss: number }
|
|
59
|
+
| {
|
|
60
|
+
type: 'rendered'
|
|
61
|
+
id: number
|
|
62
|
+
status: 'ok' | 'notFound' | 'noTemplate' | 'redirect' | 'outcome' | 'error'
|
|
63
|
+
html?: string
|
|
64
|
+
error?: string
|
|
65
|
+
location?: string
|
|
66
|
+
personal?: boolean
|
|
67
|
+
revalidate?: number | false
|
|
68
|
+
memberFiles?: string[]
|
|
69
|
+
outcome?: { status: number; message?: string; location?: string }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let db: Db | undefined
|
|
73
|
+
let cache: PublishedCache | undefined
|
|
74
|
+
let views: ReturnType<typeof createWorkspaceViews> | undefined
|
|
75
|
+
let workspace: WorkspaceScope | undefined
|
|
76
|
+
let revision = ''
|
|
77
|
+
let schema: { nodeState: NodeSchemaState; nodeId: string } | undefined
|
|
78
|
+
|
|
79
|
+
const send = (answer: ChildAnswer) => process.send?.(answer)
|
|
80
|
+
|
|
81
|
+
async function init(message: ChildInit) {
|
|
82
|
+
db = await connect({ dialect: message.dialect, file: message.sqliteFile, poolSize: 2 })
|
|
83
|
+
workspace = message.workspace
|
|
84
|
+
schema = {
|
|
85
|
+
nodeState: message.nodeState,
|
|
86
|
+
nodeId: message.nodeId,
|
|
87
|
+
...(message.environment ? { environment: message.environment } : {}),
|
|
88
|
+
}
|
|
89
|
+
cache = new PublishedCache(
|
|
90
|
+
createPublishedContentSource(db, {
|
|
91
|
+
nodeState: message.nodeState,
|
|
92
|
+
workspace: workspace.id,
|
|
93
|
+
...(message.environment ? { environment: message.environment } : {}),
|
|
94
|
+
}),
|
|
95
|
+
{},
|
|
96
|
+
)
|
|
97
|
+
views = createWorkspaceViews({
|
|
98
|
+
db,
|
|
99
|
+
config: {
|
|
100
|
+
componentsCacheDir: message.componentsCacheDir,
|
|
101
|
+
renderTimeoutMs: message.renderTimeoutMs,
|
|
102
|
+
} as CromboloConfig,
|
|
103
|
+
cache,
|
|
104
|
+
})
|
|
105
|
+
send({ type: 'ready' })
|
|
106
|
+
setInterval(() => send({ type: 'memory', rss: process.memoryUsage().rss }), 2000).unref()
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The page to render: the published one, or its draft as preview shows it. */
|
|
110
|
+
async function contentOf(message: ChildRender) {
|
|
111
|
+
if (!cache || !db || !schema || !workspace) return undefined
|
|
112
|
+
const published = await cache.byKey(message.key, message.culture)
|
|
113
|
+
if (!message.draft) return published
|
|
114
|
+
const draft = await loadDraftNode(db, message.key, { ...schema, workspace: workspace.id })
|
|
115
|
+
if (!draft) return undefined
|
|
116
|
+
const snapshot = await cache.snapshot()
|
|
117
|
+
return contentForNode(
|
|
118
|
+
draft,
|
|
119
|
+
published?.url ?? `/${draft.key}`,
|
|
120
|
+
message.culture,
|
|
121
|
+
snapshot.languages,
|
|
122
|
+
).withValueContext(await cache.valueContext(message.culture))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function render(message: ChildRender) {
|
|
126
|
+
if (!cache || !views || !workspace || !db) return
|
|
127
|
+
if (message.revision !== revision) {
|
|
128
|
+
cache.invalidate()
|
|
129
|
+
revision = message.revision
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const renderer = await views.rendererFor(workspace, cache)
|
|
133
|
+
const content = await contentOf(message)
|
|
134
|
+
if (!renderer || !content) {
|
|
135
|
+
send({ type: 'rendered', id: message.id, status: 'notFound' })
|
|
136
|
+
return
|
|
137
|
+
}
|
|
138
|
+
const { headers, ...plain } = message.request
|
|
139
|
+
const result = await renderer.renderModel(content, message.culture, {
|
|
140
|
+
...plain,
|
|
141
|
+
...(headers ? { headers: new Headers(headers) } : {}),
|
|
142
|
+
search: siteSearchFor(db, cache, plain.member),
|
|
143
|
+
})
|
|
144
|
+
const answer: ChildAnswer = { type: 'rendered', id: message.id, status: result.status }
|
|
145
|
+
if (result.status === 'ok' || result.status === 'outcome') {
|
|
146
|
+
answer.personal = result.personal
|
|
147
|
+
if (result.revalidate !== undefined) answer.revalidate = result.revalidate
|
|
148
|
+
if (result.memberFiles) answer.memberFiles = result.memberFiles
|
|
149
|
+
}
|
|
150
|
+
if (result.status === 'ok') answer.html = result.html
|
|
151
|
+
if (result.status === 'error') answer.error = result.error.message
|
|
152
|
+
if (result.status === 'redirect') answer.location = result.location
|
|
153
|
+
if (result.status === 'outcome')
|
|
154
|
+
answer.outcome = {
|
|
155
|
+
status: result.outcome.status,
|
|
156
|
+
...(result.outcome.message ? { message: result.outcome.message } : {}),
|
|
157
|
+
...(result.outcome.location ? { location: result.outcome.location } : {}),
|
|
158
|
+
}
|
|
159
|
+
send(answer)
|
|
160
|
+
} catch (error) {
|
|
161
|
+
send({ type: 'rendered', id: message.id, status: 'error', error: String(error) })
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
process.on('message', (message: ChildInit | ChildRender) => {
|
|
166
|
+
if (message.type === 'init') void init(message)
|
|
167
|
+
else if (message.type === 'render') void render(message)
|
|
168
|
+
})
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Story 392: the form and workflow designers in a workspace. Their routes read and
|
|
3
|
+
* write `schema/` as files, so in a workspace they are given a folder holding the
|
|
4
|
+
* workspace's copy; what a request changes there becomes the workspace's files, for
|
|
5
|
+
* its merge. In Shared, what it changes is recorded as the person's. docs/workspaces.md.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
existsSync,
|
|
9
|
+
mkdirSync,
|
|
10
|
+
mkdtempSync,
|
|
11
|
+
readdirSync,
|
|
12
|
+
readFileSync,
|
|
13
|
+
rmSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from 'node:fs'
|
|
16
|
+
import { tmpdir } from 'node:os'
|
|
17
|
+
import { dirname, join, relative, sep } from 'node:path'
|
|
18
|
+
import { type Db, WorkspaceFileRepository } from '@crombolo/data'
|
|
19
|
+
import { recordEdit } from './adapters/change-recording.ts'
|
|
20
|
+
import { WORKSPACE_SCHEMA_PREFIX } from './adapters/schema-files.ts'
|
|
21
|
+
import { currentWorkspace } from './workspaces.ts'
|
|
22
|
+
|
|
23
|
+
/** Where a route reads and writes `schema/`, and whether that is a workspace's. */
|
|
24
|
+
export interface SchemaPlace {
|
|
25
|
+
schemaDir: string
|
|
26
|
+
writable: boolean
|
|
27
|
+
/** The workspace's copy, not Shared's: nothing is synced or published from it. */
|
|
28
|
+
inWorkspace: boolean
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const filesUnder = (dir: string): Map<string, string> => {
|
|
32
|
+
const out = new Map<string, string>()
|
|
33
|
+
const walk = (at: string) => {
|
|
34
|
+
for (const entry of readdirSync(at, { withFileTypes: true })) {
|
|
35
|
+
const path = join(at, entry.name)
|
|
36
|
+
if (entry.isDirectory()) walk(path)
|
|
37
|
+
else out.set(relative(dir, path).split(sep).join('/'), readFileSync(path, 'utf8'))
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
walk(dir)
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Runs `run` against the workspace the request is held in (story 375's scope has
|
|
46
|
+
* already been entered), or against Shared's `schema/` where there is none.
|
|
47
|
+
*/
|
|
48
|
+
export async function inSchemaPlace(
|
|
49
|
+
db: Db,
|
|
50
|
+
shared: Omit<SchemaPlace, 'inWorkspace'>,
|
|
51
|
+
request: Request,
|
|
52
|
+
run: (place: SchemaPlace) => Promise<Response>,
|
|
53
|
+
/** Who asks: a change to Shared's files is recorded as theirs (story 392). */
|
|
54
|
+
by?: string,
|
|
55
|
+
): Promise<Response> {
|
|
56
|
+
const workspace = currentWorkspace()
|
|
57
|
+
if (!workspace) {
|
|
58
|
+
const place = { ...shared, inWorkspace: false }
|
|
59
|
+
if (request.method === 'GET' || !by || !existsSync(shared.schemaDir)) return run(place)
|
|
60
|
+
const before = filesUnder(shared.schemaDir)
|
|
61
|
+
const response = await run(place)
|
|
62
|
+
if (!response.ok) return response
|
|
63
|
+
const after = filesUnder(shared.schemaDir)
|
|
64
|
+
for (const path of new Set([...before.keys(), ...after.keys()]))
|
|
65
|
+
await recordEdit(
|
|
66
|
+
db,
|
|
67
|
+
by,
|
|
68
|
+
`${WORKSPACE_SCHEMA_PREFIX}${path}`,
|
|
69
|
+
before.get(path) ?? null,
|
|
70
|
+
after.get(path) ?? null,
|
|
71
|
+
)
|
|
72
|
+
return response
|
|
73
|
+
}
|
|
74
|
+
const store = new WorkspaceFileRepository(db)
|
|
75
|
+
const before = new Map(
|
|
76
|
+
[...(await store.files(workspace.id, WORKSPACE_SCHEMA_PREFIX))].map(([key, text]) => [
|
|
77
|
+
key.slice(WORKSPACE_SCHEMA_PREFIX.length),
|
|
78
|
+
text,
|
|
79
|
+
]),
|
|
80
|
+
)
|
|
81
|
+
const dir = mkdtempSync(join(tmpdir(), 'crombolo-workspace-designer-'))
|
|
82
|
+
try {
|
|
83
|
+
for (const [path, text] of before) {
|
|
84
|
+
mkdirSync(dirname(join(dir, path)), { recursive: true })
|
|
85
|
+
writeFileSync(join(dir, path), text)
|
|
86
|
+
}
|
|
87
|
+
const response = await run({ schemaDir: dir, writable: true, inWorkspace: true })
|
|
88
|
+
if (request.method === 'GET' || !response.ok) return response
|
|
89
|
+
const after = filesUnder(dir)
|
|
90
|
+
for (const [path, text] of after)
|
|
91
|
+
if (before.get(path) !== text)
|
|
92
|
+
await store.write(workspace.id, `${WORKSPACE_SCHEMA_PREFIX}${path}`, text, 'additive')
|
|
93
|
+
for (const path of before.keys())
|
|
94
|
+
if (!after.has(path))
|
|
95
|
+
await store.write(workspace.id, `${WORKSPACE_SCHEMA_PREFIX}${path}`, null, 'breaking')
|
|
96
|
+
return response
|
|
97
|
+
} finally {
|
|
98
|
+
rmSync(dir, { recursive: true, force: true })
|
|
99
|
+
}
|
|
100
|
+
}
|