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
10 changes: 5 additions & 5 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2037,8 +2037,8 @@ def _judged_elsewhere(home: str, paths: list, uids: set) -> set:
"""Which of the jobs *uids* of the run folders *paths*, deleted together,
keep their judgements: those with another folder of the same identity
outside them - a copy - under a root of any workspace or another run, read
afresh, never from a cache; all of them when one of those roots cannot be
read, since who owns them is then unknown."""
afresh, never from a cache; all of them when one of those roots, or a
workspace, cannot be read, since who owns them is then unknown."""
try:
return _copies(home, paths, uids)
except OSError:
Expand All @@ -2048,10 +2048,10 @@ def _judged_elsewhere(home: str, paths: list, uids: set) -> set:
def _copies(home: str, paths: list, uids: set) -> set:
outside = lambda d: all(os.path.commonpath([os.path.realpath(d), p]) != p for p in paths)
roots = []
for ws in workspace.list_all(home):
if not all(os.path.isdir(r) for r in ws.job_roots or ws.roots):
for ws in workspace.every(home):
if not all(os.path.isdir(r) for r in workspace.walked(ws)):
return set(uids)
roots += ws.job_roots or ws.roots
roots += workspace.walked(ws)
roots += [j for parent in {os.path.dirname(p) for p in paths} for e in os.scandir(parent)
if e.is_dir(follow_symlinks=False) and e.path not in paths and os.path.isdir(j := os.path.join(e.path, "jobs"))]
return {job_uid.strict(d) for d in parse.find_job_dirs(roots, strict=lambda name: True) if outside(d)} & uids
Expand Down
3 changes: 2 additions & 1 deletion app/nullius/judge/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,9 +498,10 @@ def owners(ws, into: Optional[str] = None, names=None) -> Optional[dict]:
of its roots, or a folder in one that may be a job, cannot be read: its jobs, and so the owners,
are unknown."""
from dataclasses import replace
from nullius import workspace
from nullius.runs import parse, uid as job_uid
into = into or home()
roots = ws.job_roots or ws.roots
roots = workspace.walked(ws)
spelt = None if names is None else {s for n in names for s in _names(n)}
mine = lambda name: spelt is None or not spelt.isdisjoint(_names(name))
if not all(os.path.isdir(r) for r in roots):
Expand Down
247 changes: 205 additions & 42 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

A workspace gives the app's roots, and what it made from them, a name and a
directory, so they survive a restart, so two sets of runs can be kept apart,
and so the expensive part — parsing a 375-trial job, converting a foreign
run tree — happens once per change rather than once per page.
and so the expensive part, parsing a 375-trial job, happens once per change
rather than once per page.

<home>/<name>/workspace.json name, label, roots, created, opened, closed
<home>/<name>/imported/ previously converted job directories
<home>/<name>/workspace.json version, uid, name, label, roots, created, job_roots
<home>/<name>/state.json opened, closed: an open rewrites this alone
<home>/<name>/imported/ job directories converted before: ``job_roots``
names those read still (``walked``)
<home>/<name>/jobs/<id>.json a parsed Job, keyed by the job dir's signature
<home>/<name>/jobs/counts.json its runs and checks, while its jobs had all ended

Expand Down Expand Up @@ -36,14 +38,16 @@
"""
from __future__ import annotations

import contextlib
import hashlib
import json
import os
import shutil
import random
import re
import threading
from dataclasses import asdict, dataclass, field, fields
import uuid
from dataclasses import dataclass, field, fields
from datetime import datetime, timezone
from typing import Callable

Expand Down Expand Up @@ -97,8 +101,10 @@ class Workspace:
created: str
opened: str
dir: str
job_roots: list = field(default_factory=list) # job directories the parser walks
job_roots: list = field(default_factory=list) # those of its imported/ it reads too (walked)
folder: tuple = () # its folder's device and inode when read; never stored
closed: bool = False # closed by the user: a restart leaves it closed
uid: str = "" # made with it, never changed; none in one saved before

@property
def imports_dir(self) -> str:
Expand All @@ -121,14 +127,110 @@ def _path(home_dir: str, name: str) -> str:
return os.path.join(home_dir, name, "workspace.json")


RECORD_VERSION = 1 # bump when what workspace.json holds changes
_RECORD = ("uid", "name", "label", "roots", "created", "job_roots")
_STATE = ("opened", "closed")


def save(ws: Workspace) -> None:
"""*ws* written whole as it is held here, its state before its record: a record is
never there without the state that goes with it."""
_write(ws, _STATE)
_write(ws, _RECORD)


def _write(ws: Workspace, keys) -> None:
os.makedirs(ws.dir, exist_ok=True)
data = {k: v for k, v in asdict(ws).items() if k != "dir"}
ondisk.write_whole(os.path.join(ws.dir, "workspace.json"), lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1))
data = {k: getattr(ws, k) for k in keys}
if keys is _RECORD:
data = {"version": RECORD_VERSION, **data}
path = os.path.join(ws.dir, "workspace.json" if keys is _RECORD else "state.json")
ondisk.write_whole(path, lambda fh: json.dump(data, fh, ensure_ascii=False, indent=1))


def _locked(ws: Workspace):
return ondisk.locked(os.path.join(ws.dir, "workspace.json.lock"))


def _folder(ws_dir: str) -> tuple:
"""A folder's device and inode: its own through a rename, no other folder's while it is there."""
try:
found = os.stat(ws_dir)
except OSError:
return ()
return found.st_dev, found.st_ino


def _still(ws: Workspace, now: Workspace | None) -> Workspace | None:
"""*now*, read under *ws*'s name, when it is the workspace *ws* was read from: not one
made under that name since *ws* was renamed or deleted. By its uid; when neither was
saved with one, by its folder and created time."""
if now is None:
return None
if ws.uid or now.uid:
return now if ws.uid == now.uid else None
return now if not ws.folder or (ws.folder, ws.created) == (now.folder, now.created) else None


@contextlib.contextmanager
def _current(ws: Workspace):
"""*ws* as it is on disk now, under its lock, to change and write: of two writers at
once, each reads what the other wrote. None once the workspace is gone, renamed or
deleted: nothing here makes its folder again, nor changes another made under its name."""
if not os.path.isdir(ws.dir):
yield None
return
with _locked(ws):
yield _still(ws, load(os.path.dirname(ws.dir), ws.name))


def _change(ws: Workspace, change: Callable) -> None:
"""``change`` made to *ws*'s record and saved, with its state: a record from before
``state.json`` leaves its opened and closed there. *ws* takes the roots and label saved."""
with _current(ws) as now:
if now is None:
return
change(now)
save(now)
ws.roots, ws.label = now.roots, now.label


def _set_state(ws: Workspace, **state) -> None:
"""*state* written over *ws*'s own, the rest of it as it is on disk; *ws* takes both."""
with _current(ws) as now:
if now is None:
return
for key, value in state.items():
setattr(now, key, value)
_write(now, _STATE)
ws.opened, ws.closed = now.opened, now.closed


def add_roots(ws: Workspace, roots) -> None:
"""*ws* with *roots* it does not hold yet."""
def add(now):
now.roots = list(now.roots) + [r for r in roots if r not in now.roots]
_change(ws, add)


def _state(ws_dir: str) -> dict | None:
"""``state.json``'s opened and closed; None when there is no file (a workspace saved
before it), ValueError when the file is not a state."""
try:
with open(os.path.join(ws_dir, "state.json"), encoding="utf-8") as fh:
data = json.load(fh)
except FileNotFoundError:
return None
except OSError as error:
raise ValueError(str(error)) from error
if not isinstance(data, dict) or not isinstance(data.get("opened"), str) or not isinstance(data.get("closed"), bool):
raise ValueError("invalid workspace state")
return {k: data[k] for k in _STATE}


def load(home_dir: str, name: str, *, strict: bool = False) -> Workspace | None:
"""Read a workspace. Strict launch reads refuse a damaged existing destination."""
"""Read a workspace. Strict launch reads refuse a damaged existing destination.
A record of another version is not read, so never written over: only a launch says so."""
if not name or not _NAME.fullmatch(name):
return None
try:
Expand All @@ -142,14 +244,31 @@ def load(home_dir: str, name: str, *, strict: bool = False) -> Workspace | None:
if strict:
raise ValueError("The launch workspace cannot be read. Repair it or choose another workspace.") from error
return None
known = {f.name for f in fields(Workspace)} - {"dir"}
legacy = not isinstance(data, dict) or "version" not in data # from before state.json: opened and closed are in the record
if not legacy and data["version"] != RECORD_VERSION:
if strict:
raise ValueError(f"The launch workspace was saved as version {data['version']!r} and this Nullius reads version "
f"{RECORD_VERSION}. Upgrade Nullius or choose another workspace.")
return None
known = {f.name for f in fields(Workspace)} - {"dir", "folder"}
if not legacy:
known -= set(_STATE)
ws_dir = os.path.join(home_dir, name)
try:
state, lacks = _state(ws_dir), "" if legacy else "no"
except ValueError:
state, lacks = None, "an invalid"
if state is None and lacks:
if strict:
raise ValueError(f"The launch workspace has {lacks} state.json. Repair it or choose another workspace.")
state = {"opened": "", "closed": True} # unknown: never taken for the one left open
try:
if not isinstance(data, dict) or not data.get("name"):
raise ValueError("missing workspace name")
ws = Workspace(dir=os.path.join(home_dir, name),
**{k: v for k, v in data.items() if k in known})
record = {"opened": "", **{k: v for k, v in data.items() if k in known}, **(state or {})}
ws = Workspace(dir=ws_dir, folder=_folder(ws_dir), **record)
if strict and (ws.name != name
or any(not isinstance(getattr(ws, k), str) for k in ("name", "label", "created", "opened"))
or any(not isinstance(getattr(ws, k), str) for k in ("uid", "name", "label", "created", "opened"))
or not isinstance(ws.closed, bool)
or any(not isinstance(roots, list) or any(not isinstance(r, str) for r in roots)
for roots in (ws.roots, ws.job_roots))):
Expand All @@ -173,6 +292,32 @@ def list_all(home_dir: str) -> list:
return sorted(found, key=lambda w: w.opened, reverse=True)


def every(home_dir: str) -> list:
"""Every workspace under *home_dir*, for a reader that must miss none: OSError while one
there cannot be read (another version, damaged), since what it holds is unknown."""
try:
names = sorted(os.listdir(home_dir))
except FileNotFoundError:
return []
found = []
for name in names:
try:
ws = load(home_dir, name)
except (TypeError, ValueError) as error:
raise OSError(f"workspace {name} cannot be read") from error
if ws is None and _NAME.fullmatch(name) and os.path.lexists(_path(home_dir, name)):
raise OSError(f"workspace {name} cannot be read")
found += [ws] if ws else []
return found


def walked(ws: Workspace) -> list:
"""The folders *ws*'s jobs are read from, open or closed: its roots, then the job roots
it kept in its own ``imported/``, converted before."""
kept = [r for r in ws.job_roots if os.path.commonpath([os.path.abspath(r), ws.imports_dir]) == ws.imports_dir]
return list(dict.fromkeys([*ws.roots, *kept]))


def last_open(home_dir: str) -> Workspace | None:
"""The workspace opened last, unless the user closed it."""
last = next(iter(list_all(home_dir)), None)
Expand Down Expand Up @@ -201,15 +346,24 @@ def _free(name: str, taken) -> str:


def create(home_dir: str, roots, label: str = "", *, opened: bool = True, exact: bool = False) -> Workspace:
name = label
if not exact:
taken = {ws.name for ws in list_all(home_dir)}
name = slug(label)
name = _free(name, taken) if name else random_name(taken)
name, taken = label, set() if exact else {ws.name for ws in list_all(home_dir)}
os.makedirs(home_dir, exist_ok=True)
while True:
if not exact:
name = slug(label)
name = _free(name, taken) if name else random_name(taken)
try:
os.mkdir(os.path.join(home_dir, name)) # the name is this workspace's from here: another create moves on
break
except FileExistsError:
if exact:
raise
taken.add(name)
now = _now()
ws = Workspace(name=name, label=label.strip() or name, roots=list(roots),
created=now, opened=now if opened else "", closed=not opened, dir=os.path.join(home_dir, name))
ws = Workspace(name=name, label=label.strip() or name, roots=list(roots), created=now, opened=now if opened else "",
closed=not opened, dir=os.path.join(home_dir, name), uid=uuid.uuid4().hex)
save(ws)
ws.folder = _folder(ws.dir) # as load reads it
return ws


Expand All @@ -221,27 +375,36 @@ def rename(home_dir: str, ws: Workspace, label: str) -> Workspace:
label with nothing to slug keeps the name it has. The roots it reads
stay where they are."""
label = (label or "").strip()
if not label:
if not label or not os.path.isdir(ws.dir):
return ws
name = slug(label)
if name and name != ws.name:
# a directory there that holds no workspace - left behind, half made - is taken too
taken = {w.name for w in list_all(home_dir)} | set(os.listdir(home_dir))
name = _free(name, taken - {ws.name})
new_dir = os.path.join(home_dir, name)
os.rename(ws.dir, new_dir)
from nullius.judge import store
store.unmark(ws.dir, to=new_dir)
ws.name, ws.dir = name, new_dir
ws.label = label
save(ws)
with _locked(ws): # the lock moves with the folder
now = _still(ws, load(home_dir, ws.name))
if now is None:
return ws
if name and name != ws.name:
# a directory there that holds no workspace - left behind, half made - is taken too
taken = {w.name for w in list_all(home_dir)} | set(os.listdir(home_dir))
name = _free(name, taken - {ws.name})
new_dir = os.path.join(home_dir, name)
os.rename(ws.dir, new_dir)
from nullius.judge import store
store.unmark(ws.dir, to=new_dir)
now.name, now.dir = name, new_dir
now.label = label
save(now)
ws.name, ws.dir, ws.label, ws.roots = now.name, now.dir, now.label, now.roots
return ws


def touch(ws: Workspace) -> None:
ws.opened = _now()
ws.closed = False
save(ws)
"""*ws* opened now: its state alone is written, its record is left as it is."""
_set_state(ws, opened=_now(), closed=False)


def close(ws: Workspace) -> None:
"""*ws* closed by the user: a restart leaves it closed."""
_set_state(ws, closed=True)


def delete(home_dir: str, name: str) -> bool:
Expand Down Expand Up @@ -346,9 +509,11 @@ def holding_all(home_dir: str, folders) -> dict:

def forget(ws: Workspace, roots, job_dirs) -> None:
"""*ws* without *roots*, and without its parsed jobs of *job_dirs*."""
ws.roots = [r for r in ws.roots if r not in roots]
def drop_roots(now):
now.roots = [r for r in now.roots if r not in roots]
now.job_roots = [r for r in now.job_roots if r not in roots]
_change(ws, drop_roots)
ws.job_roots = [r for r in ws.job_roots if r not in roots]
save(ws)

def drop(index):
# a root already gone from disk finds no job dirs: its entries go by where they were
Expand Down Expand Up @@ -577,17 +742,15 @@ def _merge_index(ws: Workspace, now: dict, before: dict, after: dict) -> None:


def _holds(ws: Workspace) -> Callable | None:
"""Whether *ws*, as its record is now, holds a job folder: one under a root, or under a
job root it kept in ``imported/``, as ``open_workspace`` reads them. None when the record
cannot be read."""
"""Whether *ws*, as its record is now, holds a job folder: one under a folder it reads
(``walked``). None when the record cannot be read."""
try:
now = load(os.path.dirname(ws.dir), ws.name)
except (TypeError, ValueError):
now = None
if now is None:
return None
kept = [*now.roots, *(r for r in now.job_roots
if os.path.commonpath([os.path.abspath(r), now.imports_dir]) == now.imports_dir)]
kept = walked(now)
return lambda job_dir: _under(job_dir, kept)


Expand Down
Loading
Loading