Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 6 additions & 12 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,6 @@
from opendirector_api.localization import localized_error_for_language


class EditHandoffDecision(BaseModel):
requester: UUID
accept: bool


class FontCoverageResponse(BaseModel):
fingerprint: str = Field(pattern=r'^sha256:[0-9a-f]{64}$')
# One bit per Unicode scalar position: fixed 139,264 bytes / 185,688 base64 chars.
Expand Down Expand Up @@ -132,7 +127,10 @@ def snapshot(project_id: UUID):
return projects.snapshot(project_id)

@router.post('/projects/{project_id}/open', response_model=ProjectSnapshot)
def open_project(project_id: UUID, x_opendirector_session: UUID = Header()):
def open_project(project_id: UUID, x_opendirector_session: UUID = Header(),
x_opendirector_persistent: bool = Header(default=False)):
if x_opendirector_persistent:
return projects.open(project_id, str(x_opendirector_session), persistent=True)
return projects.open(project_id, str(x_opendirector_session))

@router.post('/projects/{project_id}/open-canvas')
Expand All @@ -157,12 +155,8 @@ def edit_session(project_id: UUID, x_opendirector_session: UUID = Header()):
return projects.editing_state(project_id, str(x_opendirector_session))

@router.post('/projects/{project_id}/edit-session')
def request_edit_session(project_id: UUID, x_opendirector_session: UUID = Header()):
return projects.request_edit(project_id, str(x_opendirector_session))

@router.put('/projects/{project_id}/edit-session')
def resolve_edit_session(project_id: UUID, value: EditHandoffDecision, x_opendirector_session: UUID = Header()):
return projects.resolve_edit(project_id, str(x_opendirector_session), str(value.requester), value.accept)
def take_edit_ownership(project_id: UUID, x_opendirector_session: UUID = Header()):
return projects.take_edit_ownership(project_id, str(x_opendirector_session))

@router.put('/sessions/{session_id}')
def heartbeat(session_id: UUID, value: Session):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def view(self, project_id, client_id, value=None, *, session=None, missing_ok=Fa
return None if missing_ok else ViewState(projectId=project_id, clientId=client_id)

def open_canvas(
self, project_id: UUID | str, session: str, *, allow_preview: bool,
self, project_id: UUID | str, session: str, *, allow_preview: bool, persistent: bool = False,
) -> tuple[ProjectSnapshot, dict[str, str | None]]:
with self.local.transaction() as db:
self._recover()
Expand All @@ -131,12 +131,11 @@ def open_canvas(
if allow_preview:
editor = self.local.editor(db, str(project_id))
if editor and editor['id'] != session:
self.local.clear_other_edit_requests(db, str(project_id), session)
db.execute("DELETE FROM sessions WHERE id=?", (session,))
else:
self.local.acquire_edit_lease(db, project, session)
self.local.acquire_edit_lease(db, project, session, persistent=True)
else:
self.local.acquire_edit_lease(db, project, session)
self.local.acquire_edit_lease(db, project, session, persistent=persistent)
state = self.local.editing_state(db, str(project_id), session)
record, validated = self._current_record(db, project_id, path, manifest)
if not validated:
Expand All @@ -145,23 +144,18 @@ def open_canvas(
self._schedule_warm(path, manifest)
return record.snapshot.model_copy(deep=True), state

def open(self, project_id: UUID | str, session: str) -> ProjectSnapshot:
snapshot, _ = self.open_canvas(project_id, session, allow_preview=False)
def open(self, project_id: UUID | str, session: str, *, persistent=False) -> ProjectSnapshot:
snapshot, _ = self.open_canvas(project_id, session, allow_preview=False, persistent=persistent)
return snapshot

def editing_state(self, project_id, session):
with self.local.transaction() as db:
return self.local.editing_state(db, str(project_id), session)

def request_edit(self, project_id, session):
def take_edit_ownership(self, project_id, session):
with self.local.transaction() as db:
path, _ = self._find(db, project_id)
return self.local.request_edit(db, dict(id=str(project_id), path=str(path)), session)

def resolve_edit(self, project_id, session, requester, accept):
with self.local.transaction() as db:
path, _ = self._find(db, project_id)
return self.local.resolve_edit(db, dict(id=str(project_id), path=str(path)), session, requester, accept)
return self.local.take_edit_ownership(db, dict(id=str(project_id), path=str(path)), session)

def heartbeat(self, session, project_id):
self.open(project_id, session)
Expand Down
70 changes: 14 additions & 56 deletions packages/core/src/opendirector/infrastructure/local_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,6 @@ class LocalProjects:
# separate key lets browsers open or release their own editing session.
_AGENT_SESSION_PREFIX = "agent:"

HANDOFF_SECONDS = 120

def __init__(self, repository: Path):
self.repository = repository.resolve()
self.root = self.repository / "projects"
Expand All @@ -91,10 +89,6 @@ def __init__(self, repository: Path):
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, expires REAL NOT NULL,
path TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS edit_handoffs (
project_id TEXT PRIMARY KEY, owner TEXT NOT NULL,
requester TEXT NOT NULL, expires REAL NOT NULL
);
""")
db.execute("DELETE FROM sessions WHERE expires<=?", (time.time(),))

Expand Down Expand Up @@ -128,70 +122,35 @@ def _conflict(parent: Path, name: str, source: Path | None = None):
raise ProjectError("该位置已有同名文件或文件夹,请使用其他名称。", 409)


def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str) -> None:
def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str, *, persistent=False) -> None:
identifier(session)
project_id = project["id"]
self.clear_other_edit_requests(db, project_id, session)
if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND id NOT LIKE ? AND expires>?",
(project_id, session, self._AGENT_SESSION_PREFIX + "%", time.time())).fetchone():
raise ProjectError("该项目正在其他窗口中打开,请先关闭后再试。", 409, code="project_open_elsewhere")
lease = db.execute("SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone()
lease = db.execute("SELECT path, expires FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone()
if lease and lease["path"] != project["path"]:
raise ProjectError("项目目录已在应用外改名或移动,请复制未保存内容并刷新页面。", 409)
db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, time.time() + self.LEASE_SECONDS, project["path"]))

expires = float("inf") if persistent or (lease and lease["expires"] == float("inf")) else time.time() + self.LEASE_SECONDS
db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, expires, project["path"]))

def clear_other_edit_requests(self, db, project_id, session):
db.execute(
"DELETE FROM edit_handoffs WHERE project_id!=? AND (owner=? OR requester=?)",
(project_id, session, session),
)

def editor(self, db, project_id, *, now=None):
return db.execute(
"SELECT id FROM sessions WHERE project_id=? AND id NOT LIKE ? AND expires>?",
(project_id, self._AGENT_SESSION_PREFIX + "%", time.time() if now is None else now),
).fetchone()

def editing_state(self, db, project_id, session, *, now=None):
now = time.time() if now is None else now
editor = self.editor(db, project_id, now=now)
if editor is None:
return {'mode': 'preview', 'handoff': 'available'}
owner = editor['id']
pending = db.execute(
"SELECT requester FROM edit_handoffs WHERE project_id=? AND owner=? AND expires>?",
(project_id, owner, now),
).fetchone()
if owner == session:
return {'mode': 'edit', 'requester': pending['requester'] if pending else None}
return {'mode': 'preview', 'handoff': (
'requested' if pending and pending['requester'] == session
else 'busy' if pending else 'occupied'
)}

def request_edit(self, db, project, session):
project_id = project['id']
now = time.time()
state = self.editing_state(db, project_id, session, now=now)
if state == {'mode': 'preview', 'handoff': 'available'}:
self.acquire_edit_lease(db, project, session)
elif state == {'mode': 'preview', 'handoff': 'occupied'}:
db.execute("""
INSERT INTO edit_handoffs(project_id,owner,requester,expires) VALUES (?,?,?,?)
ON CONFLICT(project_id) DO UPDATE SET owner=excluded.owner,
requester=excluded.requester, expires=excluded.expires
""", (project_id, self.editor(db, project_id, now=now)['id'], session, now + self.HANDOFF_SECONDS))
return self.editing_state(db, project_id, session)

def resolve_edit(self, db, project, session, requester, accept):
project_id = project['id']
if self.editing_state(db, project_id, session) == {'mode': 'edit', 'requester': requester}:
db.execute("DELETE FROM edit_handoffs WHERE project_id=?", (project_id,))
if accept:
db.execute("DELETE FROM sessions WHERE id=?", (session,))
self.acquire_edit_lease(db, project, requester)
return self.editing_state(db, project_id, session)
def editing_state(self, db, project_id, session):
editor = self.editor(db, project_id)
return {'mode': 'edit' if editor and editor['id'] == session else 'preview'}

def take_edit_ownership(self, db, project, session):
editor = self.editor(db, project['id'])
if editor and editor['id'] != session:
db.execute("DELETE FROM sessions WHERE id=?", (editor['id'],))
self.acquire_edit_lease(db, project, session, persistent=True)
return self.editing_state(db, project['id'], session)

def agent_session_key(self, session: str) -> str:
return self._AGENT_SESSION_PREFIX + identifier(session)
Expand All @@ -215,5 +174,4 @@ def release_agent_session(self, session: str):

def release(self, session: str):
with self.transaction() as db:
db.execute("DELETE FROM edit_handoffs WHERE owner=? OR requester=?", (session, session))
db.execute("DELETE FROM sessions WHERE id=?", (session,))
95 changes: 36 additions & 59 deletions src/backend/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,7 @@ import { detectLocale } from "../i18n/locale.ts";
import type { Locale } from "../i18n/types.ts";
import { tNow } from "../i18n/messages.ts";

export const sessionId = crypto.randomUUID();
globalThis.window?.opendirectorDesktop?.registerSession(sessionId);

const SESSION_KEY = "opendirector.session.v1";
const lockName = (id: string) => `opendirector.session.${id}`;

interface SessionLocks {
request(name: string, callback: () => Promise<void>): Promise<void>;
query(): Promise<{ held?: { name?: string }[] }>;
}

/** Release this tab's previous page lease after a reload or crash.
*
* Each page load uses a new session. When the previous page could not send its
* release (crash, killed process, lost keepalive), its lease would otherwise
* block the reloaded tab as "another window" until it expires. The previous
* session is released only when no live page still holds its Web Lock, so a
* duplicated tab, which copies sessionStorage, never releases a live window.
* Without Web Locks nothing is released and the lease simply expires. */
export async function releaseStaleSession(
previous: string | null,
current: string,
locks: SessionLocks | undefined,
release: (id: string) => Promise<unknown>,
pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)),
) {
if (!locks) return false;
// Hold this page's lock for its lifetime; the browser drops it on unload.
void locks.request(lockName(current), () => new Promise<void>(() => {})).catch(() => {});
if (!previous || previous === current) return false;
for (let attempt = 0; attempt < 8; attempt++) {
// A reloading page may still be tearing down; look again briefly.
if (attempt) await pause(250);
const state = await locks.query().catch(() => null);
if (!state) return false;
if (!state.held?.some((lock) => lock.name === lockName(previous))) {
await release(previous).catch(() => {});
return true;
}
}
return false;
}

function tabStorage(): Storage | null {
try {
Expand All @@ -55,25 +14,40 @@ function tabStorage(): Storage | null {
}

const previousSession = tabStorage()?.getItem(SESSION_KEY) ?? null;
/** This page replaced an earlier page of the same tab (reload or reconnect). */
export const reloadedTab = previousSession !== null;
try {
tabStorage()?.setItem(SESSION_KEY, sessionId);
} catch {
// Private modes may refuse storage; the lease then just expires.
export let sessionId = previousSession ?? crypto.randomUUID();

async function claimSession(id: string): Promise<boolean> {
if (!globalThis.navigator?.locks) return true;
return new Promise((resolve, reject) => {
void navigator.locks.request(`opendirector.session.${id}`, { ifAvailable: true }, async (lock) => {
resolve(Boolean(lock));
if (lock) await new Promise<void>(() => {});
}).catch(reject);
});
}

/** Requests wait until a stale lease from this tab's previous page is gone. */
const sessionReady = releaseStaleSession(
previousSession,
sessionId,
(globalThis.navigator as { locks?: SessionLocks } | undefined)?.locks,
(id) =>
fetch(`/api/creation/sessions/${id}`, {
method: "DELETE",
headers: { "X-OpenDirector-Request": "1" },
}),
).catch(() => false);
function installSession(id: string) {
sessionId = id;
headers["X-OpenDirector-Session"] = id;
try {
tabStorage()?.setItem(SESSION_KEY, id);
} catch {
// Storage can be disabled in the browser.
}
globalThis.window?.opendirectorDesktop?.registerSession(id);
}

export async function rotateSession() {
const id = crypto.randomUUID();
await claimSession(id);
installSession(id);
}

const sessionReady = (async () => {
if (await claimSession(sessionId).catch(() => true)) installSession(sessionId);
else await rotateSession();
})();

export class ApiError extends Error {
status: number | null;
Expand Down Expand Up @@ -128,6 +102,7 @@ export async function request<T>(
leaseRenewed = false,
): Promise<T> {
await sessionReady;
const requestedSession = sessionId;
let response: Response;
try {
response = await fetch(`/api${path}`, {
Expand All @@ -145,12 +120,14 @@ export async function request<T>(
error.status === 409 &&
error.code === "session_expired" &&
!leaseRenewed &&
requestedSession === sessionId &&
projectId &&
leaseRecovery &&
!options.signal?.aborted &&
(await leaseRecovery(projectId).catch(() => false))
)
return request<T>(path, options, true);
) {
if (requestedSession === sessionId) return request<T>(path, options, true);
}
throw error;
}
if (response.status === 204) return undefined as T;
Expand Down
2 changes: 1 addition & 1 deletion src/backend/creationClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ export class CreationClient {
if ("editing" in opened)
installEditingState(this.id, parseEditingState(opened.editing));
else
installEditingState(this.id, { mode: "edit", requester: null });
installEditingState(this.id, { mode: "edit" });
canvas = "snapshot" in opened ? opened : undefined;
if (canvas)
this.referenceStates = new Map(
Expand Down
30 changes: 11 additions & 19 deletions src/backend/editSession.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,11 @@
import { json, request } from "./api.ts";
import { request, rotateSession } from "./api.ts";

export type EditingState =
| { mode: "edit"; requester: string | null }
| { mode: "preview"; handoff: "available" | "occupied" | "requested" | "busy" };
export type EditingState = { mode: "edit" | "preview" };

export function parseEditingState(value: unknown): EditingState {
if (typeof value === "object" && value !== null && "mode" in value) {
if (value.mode === "edit" && "requester" in value &&
(value.requester === null || typeof value.requester === "string"))
return { mode: value.mode, requester: value.requester };
if (value.mode === "preview" && "handoff" in value &&
(value.handoff === "available" || value.handoff === "occupied" ||
value.handoff === "requested" || value.handoff === "busy"))
return { mode: value.mode, handoff: value.handoff };
}
if (typeof value === "object" && value !== null && "mode" in value &&
(value.mode === "edit" || value.mode === "preview"))
return { mode: value.mode };
throw new TypeError("Invalid editing session response");
}

Expand All @@ -31,9 +23,7 @@ export function getEditingState(projectId: string) {

export function installEditingState(projectId: string, state: EditingState) {
const previous = getEditingState(projectId);
if (previous?.mode === "edit" && state.mode === "edit" && previous.requester === state.requester ||
previous?.mode === "preview" && state.mode === "preview" && previous.handoff === state.handoff)
return;
if (previous?.mode === state.mode) return;
current = { projectId, state };
for (const listener of listeners) listener();
}
Expand All @@ -42,6 +32,8 @@ export async function readEditingState(projectId: string, init?: RequestInit) {
return parseEditingState(await request<unknown>(`/creation/projects/${projectId}/edit-session`, init));
}

export const requestEditing = (projectId: string) => readEditingState(projectId, { method: "POST" });
export const resolveEditing = (projectId: string, requester: string, accept: boolean) =>
readEditingState(projectId, json("PUT", { requester, accept }));
export async function takeEditingOwnership(projectId: string) {
// Each takeover uses a fresh write identity, even when returning to the same tab.
await rotateSession();
return readEditingState(projectId, { method: "POST", signal: AbortSignal.timeout(10000) });
}
Loading
Loading