mikser-io 6.4.1 → 6.9.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/index.js +2 -1
- package/package.json +1 -1
- package/src/api.js +165 -0
- package/src/plugins/rest.js +83 -51
package/index.js
CHANGED
package/package.json
CHANGED
package/src/api.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// Public, transport-agnostic primitives that the REST plugin's HTTP
|
|
2
|
+
// endpoints are thin wrappers over. Library users embedding mikser
|
|
3
|
+
// programmatically can import these directly.
|
|
4
|
+
|
|
5
|
+
import { randomUUID } from 'node:crypto'
|
|
6
|
+
import { writeFile, unlink, mkdir } from 'node:fs/promises'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { updateEntity as defaultUpdateEntity } from './lifecycle.js'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Bind to the runtime and return an on-demand renderer that pipelines
|
|
12
|
+
* concurrent calls into the minimum number of `runtime.process()` cycles.
|
|
13
|
+
* The returned binding is stateful — each call to useRenderer() owns its
|
|
14
|
+
* own pending queue and `completed`-hook lifecycle. Mount once per
|
|
15
|
+
* consumer (the REST plugin mounts one; a library service mounts its own).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const { render } = useRenderer(runtime)
|
|
19
|
+
* const { output, entity } = await render(entityShape)
|
|
20
|
+
*
|
|
21
|
+
* @param {object} runtime - the mikser runtime singleton
|
|
22
|
+
* @param {object} [opts]
|
|
23
|
+
* @param {Function} [opts.updateEntity] - override lifecycle.updateEntity (mostly for testing)
|
|
24
|
+
* @param {number} [opts.defaultTimeout] - per-render timeout in ms (default 30_000)
|
|
25
|
+
* @returns {{ render: (entity, { timeout? }?) => Promise<{ output, entity }> }}
|
|
26
|
+
*/
|
|
27
|
+
export function useRenderer(runtime, {
|
|
28
|
+
updateEntity = defaultUpdateEntity,
|
|
29
|
+
defaultTimeout = 30_000,
|
|
30
|
+
} = {}) {
|
|
31
|
+
let pending = []
|
|
32
|
+
let cycleRunning = false
|
|
33
|
+
|
|
34
|
+
async function runBatch() {
|
|
35
|
+
if (cycleRunning || pending.length === 0) return
|
|
36
|
+
cycleRunning = true
|
|
37
|
+
|
|
38
|
+
const batch = pending
|
|
39
|
+
pending = []
|
|
40
|
+
|
|
41
|
+
const remaining = new Map(batch.map(b => [b.correlationId, b]))
|
|
42
|
+
const completedHooks = runtime.hooks.completed
|
|
43
|
+
const hook = async (entry) => {
|
|
44
|
+
const cid = entry.entity?._correlationId
|
|
45
|
+
if (!cid) return
|
|
46
|
+
const item = remaining.get(cid)
|
|
47
|
+
if (!item) return
|
|
48
|
+
remaining.delete(cid)
|
|
49
|
+
clearTimeout(item.timer)
|
|
50
|
+
item.resolve({ output: entry.output, entity: entry.entity })
|
|
51
|
+
}
|
|
52
|
+
completedHooks.push(hook)
|
|
53
|
+
|
|
54
|
+
for (const item of batch) {
|
|
55
|
+
item.timer = setTimeout(() => {
|
|
56
|
+
if (remaining.delete(item.correlationId)) {
|
|
57
|
+
item.reject(new Error(`Render timeout for ${item.entity.id}`))
|
|
58
|
+
}
|
|
59
|
+
}, item.timeout)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
for (const item of batch) {
|
|
64
|
+
await updateEntity(item.entity).catch(item.reject)
|
|
65
|
+
}
|
|
66
|
+
await runtime.process()
|
|
67
|
+
} catch (err) {
|
|
68
|
+
for (const item of remaining.values()) {
|
|
69
|
+
clearTimeout(item.timer)
|
|
70
|
+
item.reject(err)
|
|
71
|
+
}
|
|
72
|
+
remaining.clear()
|
|
73
|
+
} finally {
|
|
74
|
+
for (const item of remaining.values()) {
|
|
75
|
+
clearTimeout(item.timer)
|
|
76
|
+
item.reject(new Error(`Render did not complete for ${item.entity.id}`))
|
|
77
|
+
}
|
|
78
|
+
const idx = completedHooks.indexOf(hook)
|
|
79
|
+
if (idx >= 0) completedHooks.splice(idx, 1)
|
|
80
|
+
cycleRunning = false
|
|
81
|
+
if (pending.length) setImmediate(runBatch)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Submit an entity for rendering. Resolves with `{ output, entity }`
|
|
87
|
+
* where `output.result` is whatever the renderer/postprocessor returned
|
|
88
|
+
* (a string for HTML/text outputs, a Buffer for PDFs, etc.).
|
|
89
|
+
*
|
|
90
|
+
* Requests arriving concurrently are coalesced into the next available
|
|
91
|
+
* `runtime.process()` cycle — within that cycle, mikser's worker pool
|
|
92
|
+
* renders the batch in parallel.
|
|
93
|
+
*
|
|
94
|
+
* @param {object} entity - any entity-shaped object
|
|
95
|
+
* @param {object} [opts]
|
|
96
|
+
* @param {number} [opts.timeout] - override the default timeout
|
|
97
|
+
* @returns {Promise<{output, entity}>}
|
|
98
|
+
*/
|
|
99
|
+
function render(entity, { timeout = defaultTimeout } = {}) {
|
|
100
|
+
return new Promise((resolve, reject) => {
|
|
101
|
+
const correlationId = randomUUID()
|
|
102
|
+
pending.push({
|
|
103
|
+
entity: { ...entity, _correlationId: correlationId },
|
|
104
|
+
correlationId,
|
|
105
|
+
timeout,
|
|
106
|
+
resolve,
|
|
107
|
+
reject,
|
|
108
|
+
timer: null,
|
|
109
|
+
})
|
|
110
|
+
if (!cycleRunning) setImmediate(runBatch)
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return { render }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Bind to a single collection's source folder and return file-level
|
|
119
|
+
* `write` / `remove` operations against it. Each collection plugin sets
|
|
120
|
+
* `runtime.options.<name>Folder` during its onLoaded hook; this looks
|
|
121
|
+
* that up lazily, so it's safe to call useCollection() anywhere after
|
|
122
|
+
* `runtime.start()`.
|
|
123
|
+
*
|
|
124
|
+
* Distinct from `lifecycle.updateEntity` / `lifecycle.deleteEntity` —
|
|
125
|
+
* those write journal entries. These write actual files; in watch mode
|
|
126
|
+
* the resulting fs change is what kicks the next sync→process cycle.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* const documents = useCollection(runtime, 'documents')
|
|
130
|
+
* await documents.write('en/draft.md', '# Hi')
|
|
131
|
+
* await documents.remove('en/old.md')
|
|
132
|
+
*
|
|
133
|
+
* @param {object} runtime - the mikser runtime singleton
|
|
134
|
+
* @param {string} name - collection name (e.g. 'documents')
|
|
135
|
+
* @returns {{
|
|
136
|
+
* name: string,
|
|
137
|
+
* folder: string,
|
|
138
|
+
* write(relativePath: string, content?: string): Promise<string>,
|
|
139
|
+
* remove(relativePath: string): Promise<void>,
|
|
140
|
+
* }}
|
|
141
|
+
*/
|
|
142
|
+
export function useCollection(runtime, name) {
|
|
143
|
+
function resolveFolder() {
|
|
144
|
+
const folder = runtime?.options?.[`${name}Folder`]
|
|
145
|
+
if (!folder) throw new Error(`Unknown collection: ${name}`)
|
|
146
|
+
return folder
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
name,
|
|
151
|
+
get folder() { return resolveFolder() },
|
|
152
|
+
|
|
153
|
+
async write(relativePath, content = '') {
|
|
154
|
+
const uri = path.join(resolveFolder(), relativePath)
|
|
155
|
+
await mkdir(path.dirname(uri), { recursive: true })
|
|
156
|
+
await writeFile(uri, content, 'utf8')
|
|
157
|
+
return uri
|
|
158
|
+
},
|
|
159
|
+
|
|
160
|
+
async remove(relativePath) {
|
|
161
|
+
const uri = path.join(resolveFolder(), relativePath)
|
|
162
|
+
await unlink(uri)
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
}
|
package/src/plugins/rest.js
CHANGED
|
@@ -1,12 +1,75 @@
|
|
|
1
1
|
import path from 'node:path'
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
2
|
+
import { access } from 'node:fs/promises'
|
|
3
|
+
import { useRenderer, useCollection } from '../api.js'
|
|
4
|
+
|
|
5
|
+
// MIME type lookup used when streaming a postprocessor's output back over
|
|
6
|
+
// HTTP. The renderer's output extension lives on entity.destination
|
|
7
|
+
// (assigned by the layouts plugin), so we use it as the source of truth.
|
|
8
|
+
const MIME_BY_EXT = {
|
|
9
|
+
pdf: 'application/pdf',
|
|
10
|
+
html: 'text/html; charset=utf-8',
|
|
11
|
+
xml: 'application/xml; charset=utf-8',
|
|
12
|
+
xhtml: 'application/xhtml+xml; charset=utf-8',
|
|
13
|
+
rss: 'application/rss+xml; charset=utf-8',
|
|
14
|
+
atom: 'application/atom+xml; charset=utf-8',
|
|
15
|
+
json: 'application/json; charset=utf-8',
|
|
16
|
+
css: 'text/css; charset=utf-8',
|
|
17
|
+
js: 'application/javascript; charset=utf-8',
|
|
18
|
+
svg: 'image/svg+xml',
|
|
19
|
+
png: 'image/png',
|
|
20
|
+
jpg: 'image/jpeg',
|
|
21
|
+
jpeg: 'image/jpeg',
|
|
22
|
+
webp: 'image/webp',
|
|
23
|
+
gif: 'image/gif',
|
|
24
|
+
mp4: 'video/mp4',
|
|
25
|
+
webm: 'video/webm',
|
|
26
|
+
txt: 'text/plain; charset=utf-8',
|
|
27
|
+
md: 'text/markdown; charset=utf-8',
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function mimeForEntity(entity) {
|
|
31
|
+
if (!entity?.destination) return null
|
|
32
|
+
const ext = path.extname(entity.destination).toLowerCase().replace(/^\./, '')
|
|
33
|
+
return MIME_BY_EXT[ext] ?? null
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Decide how to send the render output over HTTP. Exported (and pure-ish)
|
|
37
|
+
// so tests can exercise the branching without spinning up a real server.
|
|
38
|
+
export async function sendRenderOutput(res, output, entity) {
|
|
39
|
+
if (output == null || output.result == null) {
|
|
40
|
+
return res.status(204).send()
|
|
41
|
+
}
|
|
42
|
+
const result = output.result
|
|
43
|
+
const mime = mimeForEntity(entity)
|
|
44
|
+
|
|
45
|
+
if (Buffer.isBuffer(result)) {
|
|
46
|
+
if (mime) res.type(mime)
|
|
47
|
+
return res.send(result)
|
|
48
|
+
}
|
|
49
|
+
if (typeof result === 'string') {
|
|
50
|
+
// A few postprocessors might return an absolute path to a generated
|
|
51
|
+
// file rather than its contents. Only attempt this when the string
|
|
52
|
+
// looks plausibly path-shaped — short, starts with a slash, and the
|
|
53
|
+
// file actually exists. Otherwise treat it as content.
|
|
54
|
+
if (result.length < 4096 && (result.startsWith('/') || /^[A-Za-z]:[\\/]/.test(result))) {
|
|
55
|
+
try {
|
|
56
|
+
await access(result)
|
|
57
|
+
return res.sendFile(result)
|
|
58
|
+
} catch { /* not a path, fall through */ }
|
|
59
|
+
}
|
|
60
|
+
if (mime) res.type(mime)
|
|
61
|
+
return res.send(result)
|
|
62
|
+
}
|
|
63
|
+
// Anything else (plain object, etc.) is sent as JSON.
|
|
64
|
+
return res.json(result)
|
|
65
|
+
}
|
|
5
66
|
|
|
6
67
|
export default ({
|
|
7
68
|
runtime,
|
|
8
69
|
onLoaded,
|
|
9
70
|
useLogger,
|
|
71
|
+
updateEntity,
|
|
72
|
+
findEntities,
|
|
10
73
|
}) => {
|
|
11
74
|
onLoaded(async () => {
|
|
12
75
|
const logger = useLogger()
|
|
@@ -28,9 +91,13 @@ export default ({
|
|
|
28
91
|
res.status(401).json({ error: 'Unauthorized' })
|
|
29
92
|
}
|
|
30
93
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
94
|
+
// Reuse the transport-agnostic primitives from src/api.js so the
|
|
95
|
+
// library entry point and the REST endpoints share the exact same
|
|
96
|
+
// batching/timeouts/error semantics.
|
|
97
|
+
const { render } = useRenderer(runtime, {
|
|
98
|
+
updateEntity,
|
|
99
|
+
defaultTimeout: runtime.config.rest?.renderTimeout ?? 30_000,
|
|
100
|
+
})
|
|
34
101
|
|
|
35
102
|
router.get('/entities', async (req, res) => {
|
|
36
103
|
try {
|
|
@@ -62,69 +129,34 @@ export default ({
|
|
|
62
129
|
router.put('/entities', auth, async (req, res) => {
|
|
63
130
|
try {
|
|
64
131
|
const { collection, relativePath, content = '' } = req.body
|
|
65
|
-
|
|
66
|
-
if (!folder) return res.status(400).json({ error: `Unknown collection: ${collection}` })
|
|
67
|
-
const uri = path.join(folder, relativePath)
|
|
68
|
-
await mkdir(path.dirname(uri), { recursive: true })
|
|
69
|
-
await writeFile(uri, content, 'utf8')
|
|
132
|
+
await useCollection(runtime, collection).write(relativePath, content)
|
|
70
133
|
res.status(202).json({ ok: true })
|
|
71
134
|
} catch (err) {
|
|
72
135
|
logger.error('REST update error: %s', err.message)
|
|
73
|
-
res.status(500).json({ error: err.message })
|
|
136
|
+
res.status(/Unknown collection/.test(err.message) ? 400 : 500).json({ error: err.message })
|
|
74
137
|
}
|
|
75
138
|
})
|
|
76
139
|
|
|
77
140
|
router.delete('/entities', auth, async (req, res) => {
|
|
78
141
|
try {
|
|
79
142
|
const { collection, relativePath } = req.body
|
|
80
|
-
|
|
81
|
-
if (!folder) return res.status(400).json({ error: `Unknown collection: ${collection}` })
|
|
82
|
-
const uri = path.join(folder, relativePath)
|
|
83
|
-
await unlink(uri)
|
|
143
|
+
await useCollection(runtime, collection).remove(relativePath)
|
|
84
144
|
res.status(202).json({ ok: true })
|
|
85
145
|
} catch (err) {
|
|
86
146
|
logger.error('REST delete error: %s', err.message)
|
|
87
|
-
res.status(500).json({ error: err.message })
|
|
147
|
+
res.status(/Unknown collection/.test(err.message) ? 400 : 500).json({ error: err.message })
|
|
88
148
|
}
|
|
89
149
|
})
|
|
90
150
|
|
|
91
|
-
router.post('/render', async (req, res) => {
|
|
151
|
+
router.post('/render', auth, async (req, res) => {
|
|
92
152
|
try {
|
|
93
|
-
const entity =
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const output = await new Promise((resolve, reject) => {
|
|
97
|
-
const timer = setTimeout(() => {
|
|
98
|
-
runtime.removeHook('completed', hook)
|
|
99
|
-
reject(new Error(`Render timeout for ${entity.id}`))
|
|
100
|
-
}, timeout)
|
|
101
|
-
|
|
102
|
-
const hook = async (entry) => {
|
|
103
|
-
if (entry.entity._correlationId !== entity._correlationId) return
|
|
104
|
-
clearTimeout(timer)
|
|
105
|
-
runtime.removeHook('completed', hook)
|
|
106
|
-
resolve(entry.output)
|
|
107
|
-
}
|
|
108
|
-
runtime.addHook('completed', hook)
|
|
109
|
-
|
|
110
|
-
updateEntity(entity)
|
|
111
|
-
.then(() => runtime.process())
|
|
112
|
-
.catch(reject)
|
|
113
|
-
})
|
|
114
|
-
|
|
115
|
-
if (output?.result != null) {
|
|
116
|
-
const isFile = await access(output.result).then(() => true).catch(() => false)
|
|
117
|
-
if (isFile) {
|
|
118
|
-
res.sendFile(output.result)
|
|
119
|
-
} else {
|
|
120
|
-
res.send(output.result)
|
|
121
|
-
}
|
|
122
|
-
} else {
|
|
123
|
-
res.status(204).send()
|
|
124
|
-
}
|
|
153
|
+
const { output, entity } = await render(req.body)
|
|
154
|
+
await sendRenderOutput(res, output, entity)
|
|
125
155
|
} catch (err) {
|
|
126
156
|
logger.error('REST render error: %s', err.message)
|
|
127
|
-
res.
|
|
157
|
+
if (!res.headersSent) {
|
|
158
|
+
res.status(500).json({ error: err.message })
|
|
159
|
+
}
|
|
128
160
|
}
|
|
129
161
|
})
|
|
130
162
|
|