@lincyaw/workspace 1.0.0-rc.15 → 1.0.0-rc.150
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/README.md +6 -4
- package/package.json +12 -6
- package/src/domain/paths.ts +0 -15
- package/src/node/agent-activity.ts +46 -0
- package/src/node/archive.ts +33 -0
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +16 -6
- package/src/node/capture.ts +383 -0
- package/src/node/config.ts +135 -50
- package/src/node/document-assets.ts +2 -2
- package/src/node/document-audio.ts +66 -47
- package/src/node/document-authoring.ts +30 -15
- package/src/node/document-check.ts +36 -0
- package/src/node/document-history.ts +32 -5
- package/src/node/document-images.ts +24 -14
- package/src/node/document-import.ts +123 -0
- package/src/node/document-index.ts +654 -0
- package/src/node/document-materials.ts +80 -0
- package/src/node/document-operations.ts +4 -2
- package/src/node/document-transcription.ts +2 -1
- package/src/node/document-voice.ts +121 -13
- package/src/node/git-runner.mjs +19 -0
- package/src/node/git.ts +141 -22
- package/src/node/host-activity.ts +17 -0
- package/src/node/host-upgrade.ts +28 -0
- package/src/node/jobs.ts +40 -8
- package/src/node/local-history.ts +85 -0
- package/src/node/locks.ts +12 -0
- package/src/node/mcp-settings.ts +68 -0
- package/src/node/media-upload-messages.ts +4 -0
- package/src/node/media-upload-page.ts +57 -0
- package/src/node/media-upload.css +4 -0
- package/src/node/media-uploads.ts +116 -0
- package/src/node/page-delete.ts +0 -1
- package/src/node/project-files.ts +2 -2
- package/src/node/projects.ts +20 -5
- package/src/node/review/agent-session-reviews.ts +211 -68
- package/src/node/review/agent-workspace.ts +151 -0
- package/src/node/review/git-review.ts +72 -29
- package/src/node/review/record.ts +41 -9
- package/src/node/review/routes.ts +9 -1
- package/src/node/review/windows-dependencies.ts +163 -0
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +299 -74
- package/src/node/routes.ts +52 -59
- package/src/node/serve.ts +267 -52
- package/src/node/site.ts +5 -5
- package/src/node/source-editor.ts +66 -26
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/tree-operations.ts +425 -0
- package/src/node/tree-routes.ts +107 -0
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-migrate.ts +54 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +21 -8
- package/templates/document/default/{lecture.json → index.pmd} +5 -1
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Presmium's workspace: the site of several documents (`presmium build` at a workspace root) and the local workbench `presmium serve`, with the document templates.
|
|
4
4
|
|
|
5
|
-
Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical
|
|
5
|
+
Part of [Presmium](https://github.com/Lincyaw/presmium), which compiles canonical index.pmd teaching documents into web pages, slides, Jupyter notebooks and narrated playback.
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -10,11 +10,11 @@ It comes with `@lincyaw/cli`.
|
|
|
10
10
|
|
|
11
11
|
## Workspaces
|
|
12
12
|
|
|
13
|
-
A workspace has `presmium.workspace.yaml` at its root
|
|
13
|
+
A workspace has `presmium.workspace.yaml` at its root; every `index.pmd` below it is a document, placed in the document tree by its own `placement` (the file lists no documents):
|
|
14
14
|
|
|
15
15
|
```yaml
|
|
16
16
|
title: Introduction to machine learning
|
|
17
|
-
|
|
17
|
+
defaults: { lang: en } # settings every document inherits unless it sets its own
|
|
18
18
|
site:
|
|
19
19
|
nav:
|
|
20
20
|
- { text: Week 1, link: /week1/ }
|
|
@@ -22,13 +22,15 @@ site:
|
|
|
22
22
|
|
|
23
23
|
`presmium build` at the root builds the site into `dist/web/`, with the documents' translations under `/<document>/<lang>/`.
|
|
24
24
|
|
|
25
|
+
Node callers can import `isWorkspaceRoot` from `@lincyaw/workspace/config` to identify a workspace without loading its service.
|
|
26
|
+
|
|
25
27
|
## The workbench (preview)
|
|
26
28
|
|
|
27
29
|
`presmium serve` runs the workbench on your machine: the live site, editing the source in the browser, managing documents and the history of changes. The routes the workbench (`@lincyaw/workbench`) uses are experimental; the command, the workspace configuration file and the Node services stay.
|
|
28
30
|
|
|
29
31
|
## Documentation
|
|
30
32
|
|
|
31
|
-
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/
|
|
33
|
+
- [Author guide](https://github.com/Lincyaw/presmium/blob/main/site/guide/locales/en/index.pmd): workspaces
|
|
32
34
|
- [Security and the trust model](https://github.com/Lincyaw/presmium/blob/main/SECURITY.md)
|
|
33
35
|
|
|
34
36
|
## License
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workspace",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.150",
|
|
4
4
|
"description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -16,13 +16,14 @@
|
|
|
16
16
|
],
|
|
17
17
|
"type": "module",
|
|
18
18
|
"engines": {
|
|
19
|
-
"node": "
|
|
19
|
+
"node": "^24.22.3 || >=26.13.1"
|
|
20
20
|
},
|
|
21
21
|
"publishConfig": {
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
24
|
"exports": {
|
|
25
25
|
".": "./src/index.ts",
|
|
26
|
+
"./config": "./src/node/config.ts",
|
|
26
27
|
"./package.json": "./package.json"
|
|
27
28
|
},
|
|
28
29
|
"files": [
|
|
@@ -30,15 +31,20 @@
|
|
|
30
31
|
"templates"
|
|
31
32
|
],
|
|
32
33
|
"dependencies": {
|
|
34
|
+
"@yarnpkg/nm": "4.1.2",
|
|
35
|
+
"cmd-shim": "9.0.2",
|
|
33
36
|
"image-size": "2.0.4",
|
|
37
|
+
"jszip": "^3.10.2",
|
|
34
38
|
"mime-types": "3.0.2",
|
|
39
|
+
"playwright-chromium": "1.64.1",
|
|
35
40
|
"yaml": "^2.9.1",
|
|
36
|
-
"@lincyaw/compiler": "1.0.0-rc.
|
|
37
|
-
"@lincyaw/
|
|
38
|
-
"@lincyaw/
|
|
41
|
+
"@lincyaw/compiler": "1.0.0-rc.150",
|
|
42
|
+
"@lincyaw/design": "1.0.0-rc.150",
|
|
43
|
+
"@lincyaw/kernel": "1.0.0-rc.150",
|
|
44
|
+
"@lincyaw/server": "1.0.0-rc.150"
|
|
39
45
|
},
|
|
40
46
|
"devDependencies": {
|
|
41
47
|
"@types/mime-types": "^3.0.1",
|
|
42
|
-
"@lincyaw/mcp": "1.0.0-rc.
|
|
48
|
+
"@lincyaw/mcp": "1.0.0-rc.150"
|
|
43
49
|
}
|
|
44
50
|
}
|
package/src/domain/paths.ts
CHANGED
|
@@ -46,21 +46,6 @@ export function invalidDocumentDir(dir: string): string | undefined {
|
|
|
46
46
|
return undefined
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
function segmentPattern(segment: string): RegExp {
|
|
50
|
-
const escaped = segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*').replace(/\?/g, '[^/]')
|
|
51
|
-
return new RegExp(`^${escaped}$`)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export function matchesPattern(pattern: string, path: string): boolean {
|
|
55
|
-
const want = pattern.replace(/^\.\//, '').split('/')
|
|
56
|
-
const have = path.split('/')
|
|
57
|
-
return want.length === have.length && want.every((segment, i) => segmentPattern(segment).test(have[i]!))
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function patternSegments(pattern: string): (string | RegExp)[] {
|
|
61
|
-
return pattern.replace(/^\.\//, '').split('/').map(segment => (/[*?]/.test(segment) ? segmentPattern(segment) : segment))
|
|
62
|
-
}
|
|
63
|
-
|
|
64
49
|
const NOT_RELATIVE = /^(?:[a-z][a-z\d+.-]*:|\/|#|\?)/i
|
|
65
50
|
|
|
66
51
|
export function movedUrl(url: string, file: string, was: string, from: string, to: string): string | undefined {
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { pushStream, sseResponse, problemResponse, randomUUID } from '@lincyaw/kernel'
|
|
2
|
+
import type { AgentActivity, AgentActivityObserver, AgentActivitySnapshot, Route } from '@lincyaw/kernel'
|
|
3
|
+
|
|
4
|
+
/** One workspace lifetime, bounded observations, and member-scoped readers on the existing event transport. */
|
|
5
|
+
export function createAgentActivity() {
|
|
6
|
+
const entries = new Map<string, { member: string, value: AgentActivity, timer: ReturnType<typeof setTimeout> }>()
|
|
7
|
+
const readers = new Set<{ member: string, send(snapshot: AgentActivitySnapshot): void, end(): void }>()
|
|
8
|
+
let closed = false
|
|
9
|
+
const snapshot = (member: string): AgentActivitySnapshot => ({ activities: [...entries.values()].filter(entry => entry.member === member).map(entry => structuredClone(entry.value)) })
|
|
10
|
+
const publish = (member: string) => { for (const reader of readers) if (reader.member === member) reader.send(snapshot(member)) }
|
|
11
|
+
const remove = (id: string) => {
|
|
12
|
+
const entry = entries.get(id)
|
|
13
|
+
if (!entry) return
|
|
14
|
+
clearTimeout(entry.timer); entries.delete(id); publish(entry.member)
|
|
15
|
+
}
|
|
16
|
+
const service: AgentActivityObserver = {
|
|
17
|
+
begin(input, member) {
|
|
18
|
+
if (closed) return () => {}
|
|
19
|
+
if (entries.size >= 64) remove(entries.keys().next().value!)
|
|
20
|
+
const id = randomUUID(), value: AgentActivity = { ...structuredClone(input), id, state: 'running', startedAt: Date.now() }
|
|
21
|
+
const entry = { member: member.id, value, timer: setTimeout(() => remove(id), 600_000) }
|
|
22
|
+
entry.timer.unref(); entries.set(id, entry); publish(member.id)
|
|
23
|
+
return state => {
|
|
24
|
+
if (closed || entries.get(id) !== entry || entry.value.state !== 'running') return
|
|
25
|
+
clearTimeout(entry.timer)
|
|
26
|
+
entry.value = { ...entry.value, state, finishedAt: Date.now() }
|
|
27
|
+
entry.timer = setTimeout(() => remove(id), 6000); entry.timer.unref(); publish(member.id)
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
const route: Route = { role: 'owner', handle: async (request, ctx) => {
|
|
32
|
+
if (request.method !== 'GET') return problemResponse(405, 'GET')
|
|
33
|
+
if (closed) return problemResponse(503, 'agent-activity-closed')
|
|
34
|
+
const stream = pushStream<{ event: string, data: AgentActivitySnapshot }>(push => {
|
|
35
|
+
const reader = { member: ctx.member.id, send: (data: AgentActivitySnapshot) => push({ event: 'agent-activity', data }), end: () => stream.end() }
|
|
36
|
+
readers.add(reader); reader.send(snapshot(reader.member))
|
|
37
|
+
return () => { readers.delete(reader) }
|
|
38
|
+
}, { signal: request.signal, latestOnly: true })
|
|
39
|
+
return sseResponse(stream, request.signal)
|
|
40
|
+
} }
|
|
41
|
+
return { service, routes: { 'agent-activity/events': route }, close() {
|
|
42
|
+
closed = true
|
|
43
|
+
for (const entry of entries.values()) clearTimeout(entry.timer)
|
|
44
|
+
entries.clear(); for (const reader of readers) reader.end(); readers.clear()
|
|
45
|
+
} }
|
|
46
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
2
|
+
import { readdir } from 'node:fs/promises'
|
|
3
|
+
import { join, relative, sep } from 'node:path'
|
|
4
|
+
import { pipeline } from 'node:stream/promises'
|
|
5
|
+
import JSZip from 'jszip'
|
|
6
|
+
|
|
7
|
+
// Files already compressed are stored as they are: deflating them again costs time and saves nothing.
|
|
8
|
+
const STORED = /\.(?:png|jpe?g|gif|webp|avif|ico|mp4|webm|mov|mp3|m4a|aac|ogg|opus|flac|woff2?|zip|gz|br|pdf|pptx)$/i
|
|
9
|
+
|
|
10
|
+
async function filesBelow(dir: string): Promise<string[]> {
|
|
11
|
+
const found: string[] = []
|
|
12
|
+
for (const entry of (await readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
13
|
+
const path = join(dir, entry.name)
|
|
14
|
+
if (entry.isDirectory()) found.push(...await filesBelow(path))
|
|
15
|
+
else if (entry.isFile()) found.push(path)
|
|
16
|
+
}
|
|
17
|
+
return found
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Writes the files below `dir` into the ZIP archive `file`, their paths relative to `dir`. Each file is read as a
|
|
22
|
+
* stream and written as it is compressed (JSZip's `streamFiles`), in small steps, so a large site neither fills the
|
|
23
|
+
* memory nor holds up the service's other requests.
|
|
24
|
+
*/
|
|
25
|
+
export async function writeArchive(dir: string, file: string, signal?: AbortSignal): Promise<void> {
|
|
26
|
+
const zip = new JSZip()
|
|
27
|
+
for (const path of await filesBelow(dir)) {
|
|
28
|
+
const name = relative(dir, path).split(sep).join('/')
|
|
29
|
+
zip.file(name, createReadStream(path), { binary: true, compression: STORED.test(name) ? 'STORE' : 'DEFLATE', compressionOptions: { level: 6 } })
|
|
30
|
+
}
|
|
31
|
+
signal?.throwIfAborted()
|
|
32
|
+
await pipeline(zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true }), createWriteStream(file), signal ? { signal } : {})
|
|
33
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomBytes, randomUUID, createHash } from 'node:crypto'
|
|
2
|
-
import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
|
|
2
|
+
import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientActionChangesSource, authoringClientActionMutatesDraft, authoringClientActionUsesLocalDraft, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
|
|
3
3
|
import type { AuthoringClientAcknowledgement, AuthoringClientConnection, AuthoringClientDescriptor, AuthoringClientEvent, AuthoringClientLease, AuthoringClientOpen, AuthoringClientReport, AuthoringClientRequest, AuthoringClientRequestResult, AuthoringClients, CanonicalSource, Member, PushStream, Route } from '@lincyaw/kernel'
|
|
4
4
|
import { validateAuthoringClientAcknowledgement, validateAuthoringClientLease, validateAuthoringClientOpen, validateAuthoringClientQuery, validateAuthoringClientReport, validateAuthoringClientRequest, validateAuthoringClientRequestQuery } from '@lincyaw/kernel/node'
|
|
5
5
|
import { readAuthoringDocument } from './document-editor.ts'
|
|
@@ -7,7 +7,7 @@ import { catchRequestErrors, RequestError } from './errors.ts'
|
|
|
7
7
|
import type { SourceEditor } from './source-editor.ts'
|
|
8
8
|
|
|
9
9
|
type Client = { member: string, credential: string, value: AuthoringClientDescriptor, sequence: number, lastSignature?: string, send?(value: AuthoringClientEvent): void, close?(): void }
|
|
10
|
-
type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout
|
|
10
|
+
type Pending = { member: string, signature: string, request: AuthoringClientRequest, value: AuthoringClientRequestResult, timer?: ReturnType<typeof setTimeout>, done: Promise<void>, resolve(): void }
|
|
11
11
|
const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
|
|
12
12
|
const size = (value: unknown) => JSON.stringify(value, null, 2).length
|
|
13
13
|
const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { const text = JSON.stringify(value); if (text === undefined) throw new RequestError(400, 'client-request-invalid'); if (text.length > maximum) throw new RequestError(413, 'client-request-too-large') }
|
|
@@ -15,7 +15,8 @@ const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(va
|
|
|
15
15
|
const terminal = (pending: Pending) => !['sent', 'executing'].includes(pending.value.state)
|
|
16
16
|
|
|
17
17
|
/** Ephemeral live-client control. It owns no document writer, compilation or durable task ledger. */
|
|
18
|
-
export function createAuthoringClients(editor: SourceEditor) {
|
|
18
|
+
export function createAuthoringClients(editor: SourceEditor, options: { reviewRequired?: boolean } = {}) {
|
|
19
|
+
const requiresReview = (type: import('@lincyaw/kernel').AuthoringClientActionType) => options.reviewRequired && authoringClientActionChangesSource(type) && type !== 'source.flush'
|
|
19
20
|
const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
|
|
20
21
|
let closed = false
|
|
21
22
|
const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
|
|
@@ -41,6 +42,7 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
41
42
|
if (terminal(pending)) return
|
|
42
43
|
clearTimeout(pending.timer); pending.timer = undefined
|
|
43
44
|
pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
|
|
45
|
+
pending.resolve()
|
|
44
46
|
if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.expectedClientState.connectionId })
|
|
45
47
|
}
|
|
46
48
|
const disconnect = (client: Client, connectionId: string) => {
|
|
@@ -68,9 +70,15 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
68
70
|
if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'client-query-invalid')
|
|
69
71
|
const all = [...clients.values()].filter(client => client.member === member.id && client.value.document === document && (!query.clientId || client.value.clientId === query.clientId)
|
|
70
72
|
&& (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
|
|
71
|
-
const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['
|
|
73
|
+
const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['other-form-drafts', 'review', 'open-document', ...options.reviewRequired ? ['source-writes-require-review'] : []] }
|
|
72
74
|
for (const client of all) {
|
|
73
75
|
const row = structuredClone(client.value)
|
|
76
|
+
row.snapshot.actions = row.snapshot.actions.filter(type => !requiresReview(type))
|
|
77
|
+
const pending = [...requests.values()].find(pending => pending.member === member.id && pending.value.document === document && pending.value.clientId === row.clientId && pending.value.epoch === row.epoch && !terminal(pending))
|
|
78
|
+
if (pending) {
|
|
79
|
+
row.pendingRequest = { requestId: pending.value.requestId, action: pending.value.action, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }
|
|
80
|
+
row.snapshot.actions = []
|
|
81
|
+
}
|
|
74
82
|
if (size({ ...answer, clients: [...answer.clients, row], nextAfter: row.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
|
|
75
83
|
answer.clients.push(row)
|
|
76
84
|
}
|
|
@@ -78,14 +86,15 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
78
86
|
return { ...answer, ...answer.clients.length < all.length ? { nextAfter: answer.clients.at(-1)!.clientId } : {} }
|
|
79
87
|
},
|
|
80
88
|
async request(document, request, member) {
|
|
81
|
-
|
|
89
|
+
authorize(document, member); budget(request)
|
|
82
90
|
if (!validateAuthoringClientRequest(request)) throw new RequestError(400, 'client-request-invalid')
|
|
91
|
+
if (requiresReview(request.action.type)) throw new RequestError(409, 'authoring-review-required')
|
|
83
92
|
const key = requestKey(member.id, document, request), signature = digest(request), known = requests.get(key)
|
|
84
|
-
if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known,
|
|
93
|
+
if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known, authoringClientActionUsesLocalDraft(request.action.type) ? undefined : current(document, member)) }
|
|
85
94
|
const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
|
|
86
95
|
if (!client || !state?.connected || state.document !== document || state.epoch !== request.epoch) throw new RequestError(409, 'client-unavailable')
|
|
87
96
|
if (state.connectionId !== request.expectedClientState.connectionId || state.snapshot.revision !== request.expectedClientState.revision) throw new RequestError(409, 'client-state-changed')
|
|
88
|
-
if (!sameSource(
|
|
97
|
+
if (!authoringClientActionUsesLocalDraft(request.action.type) && !sameSource(current(document, member), request.source) || (request.action.type === 'body-drafts.retry' ? state.snapshot.source.documentId !== request.source.documentId : !sameSource(state.snapshot.source, request.source))) throw new RequestError(409, 'client-source-changed')
|
|
89
98
|
if (!state.snapshot.actions.includes(request.action.type)) throw new RequestError(409, 'client-action-unavailable')
|
|
90
99
|
if ([...requests.values()].some(value => !terminal(value) && value.member === member.id && value.request.clientId === request.clientId)) throw new RequestError(409, 'client-busy')
|
|
91
100
|
while (requests.size >= AUTHORING_CLIENT_MAX_REQUESTS) {
|
|
@@ -95,11 +104,13 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
95
104
|
}
|
|
96
105
|
const now = Date.now(), value: AuthoringClientRequestResult = { document, clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type, source: request.source,
|
|
97
106
|
state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), verification: 'not-acknowledged', current: false }
|
|
98
|
-
|
|
107
|
+
let resolve!: () => void
|
|
108
|
+
const done = new Promise<void>(finish => resolve = finish)
|
|
109
|
+
const pending: Pending = { member: member.id, signature, request: structuredClone(request), value, done, resolve }
|
|
99
110
|
pending.timer = setTimeout(() => finish(pending, 'expired', 'client-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
|
|
100
111
|
requests.set(key, pending)
|
|
101
112
|
client.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
|
|
102
|
-
return readResult(pending,
|
|
113
|
+
return readResult(pending, authoringClientActionUsesLocalDraft(request.action.type) ? undefined : current(document, member))
|
|
103
114
|
},
|
|
104
115
|
async get(document, query, member) {
|
|
105
116
|
authorize(document, member); budget(query)
|
|
@@ -110,6 +121,21 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
110
121
|
try { actual = current(document, member) } catch { /* An old receipt stays readable if the current source is invalid. */ }
|
|
111
122
|
return readResult(pending, actual)
|
|
112
123
|
},
|
|
124
|
+
async cancel(document, query, member) {
|
|
125
|
+
if (closed) throw new RequestError(503, 'client-owner-closed')
|
|
126
|
+
if (!hasRole(member, 'editor')) throw new RequestError(403, 'client-permission-denied')
|
|
127
|
+
budget(query)
|
|
128
|
+
if (!validateAuthoringClientRequestQuery(query)) throw new RequestError(400, 'client-request-query-invalid')
|
|
129
|
+
const pending = requests.get(requestKey(member.id, document, query))
|
|
130
|
+
if (!pending) throw new RequestError(404, 'client-request-not-found')
|
|
131
|
+
if (!terminal(pending) && !pending.value.cancellationRequested) {
|
|
132
|
+
pending.value.cancellationRequested = true
|
|
133
|
+
clients.get(clientKey(member.id, query.clientId))?.send?.({ type: 'cancel', requestId: query.requestId, connectionId: pending.value.connectionId })
|
|
134
|
+
}
|
|
135
|
+
let actual: CanonicalSource | undefined
|
|
136
|
+
try { actual = current(document, member) } catch { /* Cancelling the caller's original request does not require a valid new source. */ }
|
|
137
|
+
return readResult(pending, actual)
|
|
138
|
+
},
|
|
113
139
|
}
|
|
114
140
|
const register = (document: string, value: AuthoringClientOpen, member: Member): AuthoringClientLease => {
|
|
115
141
|
const source = current(document, member)
|
|
@@ -147,28 +173,39 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
147
173
|
if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'client-request-timeout')
|
|
148
174
|
if (!pending || terminal(pending) || pending.request.expectedClientState.connectionId !== lease.connectionId) throw new RequestError(409, 'client-request-expired')
|
|
149
175
|
if (ack.state === 'executing' && pending.value.state !== 'sent' || ack.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'client-ack-state-invalid')
|
|
150
|
-
if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === '
|
|
151
|
-
const
|
|
152
|
-
|
|
153
|
-
if (ack.state === '
|
|
176
|
+
if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'executing' && pending.request.action.type === 'body-drafts.retry' && ack.snapshot.source.documentId === pending.request.source.documentId) && !(ack.state === 'done' && (authoringClientActionChangesSource(pending.request.action.type) || authoringClientActionUsesLocalDraft(pending.request.action.type)) && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
|
|
177
|
+
const localDraft = authoringClientActionUsesLocalDraft(pending.request.action.type)
|
|
178
|
+
const actual = !localDraft && (ack.state === 'executing' || ack.state === 'done') ? current(document, member) : undefined
|
|
179
|
+
if (ack.state === 'executing' && (ack.snapshot.revision !== pending.request.expectedClientState.revision || !localDraft && (!actual || !sameSource(actual, pending.request.source)))) throw new RequestError(409, 'client-state-changed')
|
|
180
|
+
if (ack.state === 'done' && !localDraft && (!actual || !sameSource(actual, ack.snapshot.source))) throw new RequestError(409, 'client-source-changed')
|
|
154
181
|
const action = pending.request.action
|
|
155
|
-
const family = action.type.startsWith('comment-drafts.') ? 'comment' : action.type.startsWith('component-drafts.') ? 'component' : undefined
|
|
182
|
+
const family = action.type.startsWith('production-drafts.') ? 'production' : action.type.startsWith('body-drafts.') ? 'body' : action.type.startsWith('comment-drafts.') ? 'comment' : action.type.startsWith('component-drafts.') ? 'component' : undefined
|
|
156
183
|
if (ack.result && (!family || ack.state !== 'done' || ack.result.type !== action.type || ack.result.family !== family)) throw new RequestError(400, 'client-result-invalid')
|
|
157
184
|
if (family && ack.state === 'done') {
|
|
158
185
|
const result = ack.result
|
|
159
|
-
const mutation = action.type
|
|
186
|
+
const mutation = authoringClientActionMutatesDraft(action.type)
|
|
160
187
|
if (!result || (mutation ? ack.snapshot.revision <= pending.request.expectedClientState.revision : ack.snapshot.revision !== pending.request.expectedClientState.revision)) throw new RequestError(409, `client-${family}-drafts-changed`)
|
|
161
188
|
if (!authoringClientResultFits({ request: pending.request, connection: client.value, document, snapshot: ack.snapshot }, result)) throw new RequestError(413, `client-${family}-result-too-large`)
|
|
189
|
+
if ((action.type === 'body-drafts.read' || action.type === 'production-drafts.read') && (result.type !== action.type || result.draft !== action.draft
|
|
190
|
+
|| result.offset !== action.offset || result.endOffset !== result.offset + result.jsonText.length || result.endOffset > result.totalUtf16
|
|
191
|
+
|| result.jsonText.length > (action.maxChars ?? 2048))) throw new RequestError(400, 'client-result-invalid')
|
|
162
192
|
if ((action.type === 'comment-drafts.read' || action.type === 'component-drafts.read') && (result.type !== action.type || result.draft.id !== action.draft.id || result.draft.revision !== action.draft.revision || result.draft.token !== action.draft.token
|
|
163
193
|
|| action.type === 'component-drafts.read' && (result.type !== action.type || result.draft.blockId !== action.draft.blockId || result.draft.stepId !== action.draft.stepId)
|
|
164
194
|
|| result.offset !== action.offset || result.endOffset !== result.offset + result.jsonText.length || result.endOffset > result.totalUtf16
|
|
165
195
|
|| result.jsonText.length > (action.maxChars ?? 2048))) throw new RequestError(400, 'client-result-invalid')
|
|
166
|
-
if ((action.type === 'comment-drafts.inspect' || action.type === 'component-drafts.inspect') && (result.type !== action.type || result.drafts.length > (action.limit ?? 10)
|
|
196
|
+
if ((action.type === 'comment-drafts.inspect' || action.type === 'component-drafts.inspect' || action.type === 'body-drafts.inspect' || action.type === 'production-drafts.inspect') && (result.type !== action.type || result.drafts.length > (action.limit ?? 10)
|
|
167
197
|
|| action.cursor && action.cursor.token !== result.token || result.next && result.next.token !== result.token)) throw new RequestError(400, 'client-result-invalid')
|
|
198
|
+
if (action.type === 'body-drafts.restore' || action.type === 'body-drafts.discard' || action.type === 'body-drafts.retry') {
|
|
199
|
+
if (result.type !== action.type || !('outcome' in result) || result.draft !== action.draft
|
|
200
|
+
|| (action.type === 'body-drafts.restore' ? !['restored', 'already-saved'].includes(result.outcome)
|
|
201
|
+
: action.type === 'body-drafts.discard' ? !['source-restored', 'backup-discarded'].includes(result.outcome) : result.outcome !== 'saved')) throw new RequestError(400, 'client-result-invalid')
|
|
202
|
+
}
|
|
203
|
+
if (action.type === 'production-drafts.discard' && (result.type !== action.type || result.draft !== action.draft || !result.discarded)) throw new RequestError(400, 'client-result-invalid')
|
|
168
204
|
const sameComment = (a: import('@lincyaw/kernel').ClientCommentDraftReference | null, b: import('@lincyaw/kernel').ClientCommentDraftReference | null) => a === null || b === null ? a === b
|
|
169
205
|
: a.id === b.id && a.revision === b.revision && a.token === b.token
|
|
170
|
-
if (action.type === 'comment-drafts.restore' && (result.type !== action.type || !sameComment(result.draft, action.draft)
|
|
171
|
-
||
|
|
206
|
+
if (action.type === 'comment-drafts.restore' && (result.type !== action.type || !sameComment(result.draft, action.draft)
|
|
207
|
+
|| action.composerId !== undefined && (result.composerId !== action.composerId || !sameComment(result.preservedCurrent, action.expectedCurrent ?? null))
|
|
208
|
+
|| result.restored.revision !== 1 || result.restored.id === action.draft.id || result.restored.id === result.preservedCurrent?.id)) throw new RequestError(400, 'client-result-invalid')
|
|
172
209
|
if (action.type === 'comment-drafts.discard' && (result.type !== action.type || !sameComment(result.draft, action.draft) || !result.discarded)) throw new RequestError(400, 'client-result-invalid')
|
|
173
210
|
const sameDraft = (a: import('@lincyaw/kernel').ClientComponentDraftReference | null, b: import('@lincyaw/kernel').ClientComponentDraftReference | null) => a === null || b === null ? a === b
|
|
174
211
|
: a.id === b.id && a.revision === b.revision && a.token === b.token && a.blockId === b.blockId && a.stepId === b.stepId
|
|
@@ -194,7 +231,23 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
194
231
|
if (!validateAuthoringClientReport(value.report)) throw new RequestError(400, 'client-report-invalid')
|
|
195
232
|
report(connection(ctx.document, value.connection, ctx.member), value.report, digest(value.report)); return jsonResponse({ accepted: true })
|
|
196
233
|
}) })
|
|
197
|
-
return { service,
|
|
234
|
+
return { service,
|
|
235
|
+
async flush(documents: string[], member: Member): Promise<void> {
|
|
236
|
+
const active = [...clients.values()].filter(client => client.member === member.id && client.value.connected && documents.includes(client.value.document))
|
|
237
|
+
await Promise.all(active.map(async client => {
|
|
238
|
+
const state = client.value
|
|
239
|
+
if (!state.snapshot.actions.includes('source.flush')) {
|
|
240
|
+
if (state.snapshot.editing.dirty || state.snapshot.editing.saving || state.snapshot.editing.composing || state.snapshot.editing.conflicted) throw new RequestError(409, 'agent-author-editing', { next: 'The author has unconfirmed input. Read the current author files and retry after that input is saved. Nothing was published.' })
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
const request: AuthoringClientRequest = { clientId: state.clientId, epoch: state.epoch, requestId: randomUUID(), source: state.snapshot.source,
|
|
244
|
+
expectedClientState: { connectionId: state.connectionId, revision: state.snapshot.revision }, action: { type: 'source.flush' } }
|
|
245
|
+
await service.request(state.document, request, member)
|
|
246
|
+
const pending = requests.get(requestKey(member.id, state.document, request))!
|
|
247
|
+
await pending.done
|
|
248
|
+
if (pending.value.state !== 'done') throw new RequestError(409, 'agent-author-editing', { next: 'The author client could not confirm its saved input. Read the current author files and retry. Nothing was published.' })
|
|
249
|
+
}))
|
|
250
|
+
}, routes: {
|
|
198
251
|
'authoring-clients/register': post('register'), 'authoring-clients/report': post('report'), 'authoring-clients/ack': post('ack'),
|
|
199
252
|
'authoring-clients/events': { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
|
|
200
253
|
if (request.method !== 'GET') return problemResponse(405, 'GET')
|
|
@@ -202,5 +255,5 @@ export function createAuthoringClients(editor: SourceEditor) {
|
|
|
202
255
|
if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'client-connection-invalid')
|
|
203
256
|
return sseResponse(open(ctx.document, lease, ctx.member, request.signal), request.signal)
|
|
204
257
|
}) } satisfies Route,
|
|
205
|
-
}, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values())
|
|
258
|
+
}, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'client-owner-closed'); requests.clear(); clients.clear() } }
|
|
206
259
|
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { randomBytes, randomUUID, createHash } from 'node:crypto'
|
|
2
|
+
import { AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
|
|
3
|
+
import type { AuthoringWindowAcknowledgement, AuthoringWindowDescriptor, AuthoringWindowEvent, AuthoringWindowLease, AuthoringWindowOpen, AuthoringWindowReference, AuthoringWindowReport, AuthoringWindowRequest, AuthoringWindowRequestResult, AuthoringWindows, Member, Route } from '@lincyaw/kernel'
|
|
4
|
+
import { validateAuthoringClientLease, validateAuthoringClientQuery, validateAuthoringClientRequestQuery, validateAuthoringWindowAcknowledgement, validateAuthoringWindowHandle, validateAuthoringWindowOpen, validateAuthoringWindowReport, validateAuthoringWindowRequest } from '@lincyaw/kernel/node'
|
|
5
|
+
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
6
|
+
|
|
7
|
+
type Client = { member: string, credential: string, sequence: number, signature?: string, value: AuthoringWindowDescriptor, send?(event: AuthoringWindowEvent): void, close?(): void }
|
|
8
|
+
type Pending = { member: string, signature: string, request: AuthoringWindowRequest, value: AuthoringWindowRequestResult, timer?: ReturnType<typeof setTimeout> }
|
|
9
|
+
const terminal = (value: Pending) => !['sent', 'executing'].includes(value.value.state)
|
|
10
|
+
const size = (value: unknown) => JSON.stringify(value, null, 2).length
|
|
11
|
+
const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value, (_, item) => isRecord(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)).digest('hex')
|
|
12
|
+
const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { if (value === undefined || size(value) > maximum) throw new RequestError(413, 'window-request-too-large') }
|
|
13
|
+
|
|
14
|
+
/** Root window control has its own lifetime, not the currently attached document's authority. */
|
|
15
|
+
export function createAuthoringWindows(target: (document: string, member: Member) => string) {
|
|
16
|
+
const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
|
|
17
|
+
let closed = false
|
|
18
|
+
const authorize = (member: Member) => { if (closed) throw new RequestError(503, 'window-owner-closed'); if (!hasRole(member, 'owner')) throw new RequestError(403, 'window-permission-denied') }
|
|
19
|
+
const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
|
|
20
|
+
const requestKey = (member: string, value: AuthoringWindowReference) => JSON.stringify([member, value.clientId, value.epoch, value.requestId])
|
|
21
|
+
const finish = (pending: Pending, state: AuthoringWindowRequestResult['state'], code?: string) => {
|
|
22
|
+
if (terminal(pending)) return
|
|
23
|
+
clearTimeout(pending.timer); pending.timer = undefined
|
|
24
|
+
pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
|
|
25
|
+
if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.connectionId })
|
|
26
|
+
}
|
|
27
|
+
const disconnect = (client: Client, connectionId: string) => {
|
|
28
|
+
if (client.value.connectionId !== connectionId) return
|
|
29
|
+
client.value = { ...client.value, connected: false }; client.send = undefined; client.close = undefined
|
|
30
|
+
for (const pending of requests.values()) if (!terminal(pending) && pending.member === client.member && pending.request.clientId === client.value.clientId && pending.request.connectionId === connectionId) finish(pending, 'expired', 'window-disconnected')
|
|
31
|
+
}
|
|
32
|
+
const connection = (lease: AuthoringWindowLease, member: Member) => {
|
|
33
|
+
authorize(member)
|
|
34
|
+
const client = clients.get(clientKey(member.id, lease.clientId))
|
|
35
|
+
if (!client?.value.connected || client.value.epoch !== lease.epoch || client.value.connectionId !== lease.connectionId || client.credential !== lease.credential) throw new RequestError(409, 'window-connection-changed')
|
|
36
|
+
return client
|
|
37
|
+
}
|
|
38
|
+
const targetCurrent = (request: AuthoringWindowRequest, member: Member) => {
|
|
39
|
+
if (request.action.type === 'document.open') {
|
|
40
|
+
if (!request.target || request.target.document !== request.action.document || target(request.target.document, member) !== request.target.documentId) throw new RequestError(409, 'window-target-changed')
|
|
41
|
+
} else if (request.target) throw new RequestError(400, 'window-request-invalid')
|
|
42
|
+
}
|
|
43
|
+
const readResult = (pending: Pending, member: Member): AuthoringWindowRequestResult => {
|
|
44
|
+
const client = clients.get(clientKey(member.id, pending.request.clientId)), value = pending.value
|
|
45
|
+
let current = Boolean(client?.value.connected && client.value.epoch === value.epoch && client.value.connectionId === value.connectionId && value.snapshot && digest(client.value.snapshot) === digest(value.snapshot))
|
|
46
|
+
try { targetCurrent(pending.request, member) } catch { current = false }
|
|
47
|
+
return structuredClone({ ...value, current })
|
|
48
|
+
}
|
|
49
|
+
const report = (client: Client, value: AuthoringWindowReport) => {
|
|
50
|
+
const signature = digest(value)
|
|
51
|
+
if (value.sequence < client.sequence || value.sequence === client.sequence && signature !== client.signature || value.snapshot.revision < client.value.snapshot.revision) throw new RequestError(409, 'window-report-superseded')
|
|
52
|
+
if (value.sequence === client.sequence) return
|
|
53
|
+
client.sequence = value.sequence; client.signature = signature
|
|
54
|
+
client.value = { ...client.value, snapshot: structuredClone(value.snapshot), observedAt: new Date().toISOString() }
|
|
55
|
+
}
|
|
56
|
+
const retained = (reference: AuthoringWindowReference | string, member: Member) => {
|
|
57
|
+
authorize(member); budget(reference)
|
|
58
|
+
if (typeof reference === 'string') {
|
|
59
|
+
if (!validateAuthoringWindowHandle(reference)) throw new RequestError(400, 'window-query-invalid')
|
|
60
|
+
const matches = [...requests.values()].filter(value => value.member === member.id && value.request.requestId === reference)
|
|
61
|
+
if (matches.length > 1) throw new RequestError(409, 'window-query-ambiguous')
|
|
62
|
+
if (!matches[0]) throw new RequestError(404, 'window-request-not-found')
|
|
63
|
+
return matches[0]
|
|
64
|
+
}
|
|
65
|
+
if (!validateAuthoringClientRequestQuery(reference)) throw new RequestError(400, 'window-query-invalid')
|
|
66
|
+
const pending = requests.get(requestKey(member.id, reference))
|
|
67
|
+
if (!pending) throw new RequestError(404, 'window-request-not-found')
|
|
68
|
+
return pending
|
|
69
|
+
}
|
|
70
|
+
const service: AuthoringWindows = {
|
|
71
|
+
async list(query, member) {
|
|
72
|
+
authorize(member); budget(query)
|
|
73
|
+
if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'window-query-invalid')
|
|
74
|
+
const all = [...clients.values()].filter(client => client.member === member.id && (!query.clientId || client.value.clientId === query.clientId) && (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
|
|
75
|
+
const answer = { scope: 'workspace' as const, clients: [] as AuthoringWindowDescriptor[] }
|
|
76
|
+
for (const client of all) {
|
|
77
|
+
const value = structuredClone(client.value), pending = [...requests.values()].find(request => request.member === member.id && request.request.clientId === value.clientId && !terminal(request))
|
|
78
|
+
if (pending) { value.pendingRequest = { requestId: pending.request.requestId, action: pending.request.action.type, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }; value.snapshot.actions = [] }
|
|
79
|
+
if (size({ ...answer, clients: [...answer.clients, value], nextAfter: value.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
|
|
80
|
+
answer.clients.push(value)
|
|
81
|
+
}
|
|
82
|
+
if (all.length && !answer.clients.length) throw new RequestError(413, 'window-state-too-large')
|
|
83
|
+
return { ...answer, ...answer.clients.length < all.length ? { nextAfter: answer.clients.at(-1)!.clientId } : {} }
|
|
84
|
+
},
|
|
85
|
+
async request(request, member) {
|
|
86
|
+
authorize(member); budget(request)
|
|
87
|
+
if (!validateAuthoringWindowRequest(request)) throw new RequestError(400, 'window-request-invalid')
|
|
88
|
+
const key = requestKey(member.id, request), signature = digest(request), known = requests.get(key)
|
|
89
|
+
if (known) { if (signature !== known.signature) throw new RequestError(409, 'window-request-id-reused'); return readResult(known, member) }
|
|
90
|
+
const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
|
|
91
|
+
if (!state?.connected || state.epoch !== request.epoch || state.connectionId !== request.connectionId) throw new RequestError(409, 'window-unavailable')
|
|
92
|
+
if (state.snapshot.revision !== request.revision) throw new RequestError(409, 'window-state-changed')
|
|
93
|
+
if (!state.snapshot.actions.includes(request.action.type)) throw new RequestError(409, 'window-action-unavailable')
|
|
94
|
+
if ([...requests.values()].some(value => value.member === member.id && value.request.clientId === request.clientId && !terminal(value))) throw new RequestError(409, 'window-busy')
|
|
95
|
+
targetCurrent(request, member)
|
|
96
|
+
while (requests.size >= AUTHORING_CLIENT_MAX_REQUESTS) { const old = [...requests].find(([, value]) => terminal(value)); if (!old) throw new RequestError(429, 'window-request-capacity'); requests.delete(old[0]) }
|
|
97
|
+
const now = Date.now(), value: AuthoringWindowRequestResult = { clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type,
|
|
98
|
+
state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), acknowledged: false, current: false }
|
|
99
|
+
const pending: Pending = { member: member.id, signature, request: structuredClone(request), value }
|
|
100
|
+
pending.timer = setTimeout(() => finish(pending, 'expired', 'window-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
|
|
101
|
+
requests.set(key, pending); client!.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
|
|
102
|
+
return readResult(pending, member)
|
|
103
|
+
},
|
|
104
|
+
async get(reference, member) { return readResult(retained(reference, member), member) },
|
|
105
|
+
async cancel(reference, member) {
|
|
106
|
+
const pending = retained(reference, member)
|
|
107
|
+
if (!terminal(pending) && !pending.value.cancellationRequested) { pending.value.cancellationRequested = true; clients.get(clientKey(member.id, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.value.connectionId }) }
|
|
108
|
+
return readResult(pending, member)
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
const register = (value: AuthoringWindowOpen, member: Member): AuthoringWindowLease => {
|
|
112
|
+
authorize(member)
|
|
113
|
+
const key = clientKey(member.id, value.clientId), old = clients.get(key)
|
|
114
|
+
if (!old && clients.size >= AUTHORING_CLIENT_MAX_CLIENTS) { const disposable = [...clients].find(([, client]) => !client.value.connected); if (!disposable) throw new RequestError(429, 'window-capacity'); clients.delete(disposable[0]) }
|
|
115
|
+
old?.close?.()
|
|
116
|
+
const credential = randomBytes(32).toString('base64url'), connectionId = randomUUID()
|
|
117
|
+
clients.set(key, { member: member.id, credential, sequence: -1, value: { clientId: value.clientId, epoch: value.epoch, connectionId, connected: false, snapshot: structuredClone(value.snapshot), observedAt: new Date().toISOString() } })
|
|
118
|
+
return { clientId: value.clientId, epoch: value.epoch, connectionId, credential }
|
|
119
|
+
}
|
|
120
|
+
const acknowledge = (lease: AuthoringWindowLease, value: AuthoringWindowAcknowledgement, member: Member) => {
|
|
121
|
+
const client = connection(lease, member), pending = requests.get(requestKey(member.id, { ...lease, requestId: value.requestId }))
|
|
122
|
+
if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'window-request-timeout')
|
|
123
|
+
if (!pending || terminal(pending) || pending.request.connectionId !== lease.connectionId) throw new RequestError(409, 'window-request-expired')
|
|
124
|
+
if (value.state === 'executing' && pending.value.cancellationRequested) throw new RequestError(409, 'window-request-cancelled')
|
|
125
|
+
if (value.state === 'executing' && pending.value.state !== 'sent' || value.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'window-ack-state-invalid')
|
|
126
|
+
if (value.state !== 'done' && value.outcome !== undefined || (value.state === 'done' || value.state === 'executing') && value.error) throw new RequestError(400, 'window-ack-invalid')
|
|
127
|
+
if (value.state === 'executing' && (value.snapshot.revision !== pending.request.revision || digest(value.snapshot) !== digest(client.value.snapshot))) throw new RequestError(409, 'window-state-changed')
|
|
128
|
+
if (value.state === 'executing' || value.state === 'done') targetCurrent(pending.request, member)
|
|
129
|
+
if (value.state === 'done') {
|
|
130
|
+
const action = pending.request.action, location = value.snapshot.location
|
|
131
|
+
if (value.snapshot.revision < pending.request.revision || action.type === 'window.read' && (value.outcome !== 'observed' || value.snapshot.revision !== pending.request.revision)
|
|
132
|
+
|| action.type === 'document.open' && (!['opened', 'unchanged'].includes(value.outcome ?? '') || location.type !== 'document' || location.status !== 'ready' || location.document !== action.document || location.documentId !== pending.request.target?.documentId)
|
|
133
|
+
|| action.type === 'document.close' && (!['closed', 'unchanged'].includes(value.outcome ?? '') || location.type !== 'home')) throw new RequestError(409, 'window-action-not-verified')
|
|
134
|
+
}
|
|
135
|
+
report(client, value)
|
|
136
|
+
pending.value = { ...pending.value, snapshot: structuredClone(value.snapshot), ...value.outcome ? { outcome: value.outcome } : {}, ...value.error ? { error: value.error } : {}, acknowledged: true }
|
|
137
|
+
if (value.state === 'executing') pending.value.state = 'executing'; else finish(pending, value.state)
|
|
138
|
+
return { accepted: true }
|
|
139
|
+
}
|
|
140
|
+
const post = (kind: 'register' | 'report' | 'ack'): Route => ({ role: 'owner', maxBody: 16384, handle: (request, ctx) => catchRequestErrors(async () => {
|
|
141
|
+
if (request.method !== 'POST') return problemResponse(405, 'POST')
|
|
142
|
+
const value: unknown = await request.json().catch(() => undefined); budget(value, AUTHORING_CLIENT_MAX_RESPONSE_CHARS)
|
|
143
|
+
if (kind === 'register') { if (!validateAuthoringWindowOpen(value)) throw new RequestError(400, 'window-open-invalid'); return jsonResponse(register(value, ctx.member)) }
|
|
144
|
+
if (!isRecord(value) || Object.keys(value).some(key => !['connection', 'report'].includes(key)) || !validateAuthoringClientLease(value.connection)) throw new RequestError(400, 'window-connection-invalid')
|
|
145
|
+
if (kind === 'ack') { if (!validateAuthoringWindowAcknowledgement(value.report)) throw new RequestError(400, 'window-ack-invalid'); return jsonResponse(acknowledge(value.connection, value.report, ctx.member)) }
|
|
146
|
+
if (!validateAuthoringWindowReport(value.report)) throw new RequestError(400, 'window-report-invalid')
|
|
147
|
+
report(connection(value.connection, ctx.member), value.report); return jsonResponse({ accepted: true })
|
|
148
|
+
}) })
|
|
149
|
+
return { service, routes: {
|
|
150
|
+
'authoring-windows/register': post('register'), 'authoring-windows/report': post('report'), 'authoring-windows/ack': post('ack'),
|
|
151
|
+
'authoring-windows/events': { role: 'owner', handle: (request, ctx) => catchRequestErrors(async () => {
|
|
152
|
+
authorize(ctx.member)
|
|
153
|
+
if (request.method !== 'GET') return problemResponse(405, 'GET')
|
|
154
|
+
const query = new URL(request.url).searchParams, lease = { clientId: query.get('clientId'), epoch: query.get('epoch'), connectionId: query.get('connectionId'), credential: request.headers.get('X-Presmium-Authoring-Client') }
|
|
155
|
+
if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'window-connection-invalid')
|
|
156
|
+
const client = clients.get(clientKey(ctx.member.id, lease.clientId))
|
|
157
|
+
if (!client || client.value.epoch !== lease.epoch || client.credential !== lease.credential) throw new RequestError(409, 'window-connection-changed')
|
|
158
|
+
client.close?.(); const connectionId = randomUUID()
|
|
159
|
+
client.value = { ...client.value, connected: true, connectionId }
|
|
160
|
+
const stream = pushStream<{ event: string, data: AuthoringWindowEvent }>(push => { client.send = data => push({ event: 'authoring-client', data }); return () => disconnect(client, connectionId) }, { signal: request.signal })
|
|
161
|
+
client.close = () => stream.end(); client.send?.({ type: 'connected', connectionId })
|
|
162
|
+
return sseResponse(stream, request.signal)
|
|
163
|
+
}) } satisfies Route,
|
|
164
|
+
}, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'window-owner-closed'); clients.clear(); requests.clear() } }
|
|
165
|
+
}
|