diff --git a/lanes-index b/lanes-index index e9002201..49f28572 100755 --- a/lanes-index +++ b/lanes-index @@ -8,6 +8,15 @@ Amendment 14, ratified by Brett Heap 2026-10-05, verbatim "ratify 48"). lanes-index status per source: store, lag, errors lanes-index export --out [--source | --worktrees] the read flags' reader + lanes-index mode index or primary, from + the configuration alone + + and the SQL register's (feature 007, opensoft/openRepoTools#165), in the + forms contracts/register-cli.md fixes, each landing with its own task: + + lanes-index register snapshot | commit | classify | read + lanes-index journal | render | import | cutover | rollback | outage + lanes-index bootstrap | login | ready | set-mode | serve THE REGISTER'S TRUTH STAYS WHERE IT IS (clause (a)). The workspace repository's `lanes/LANES.md`, `lanes/log/*.md`, `lanes/aliases.tsv` and `lanes/archive/` @@ -69,11 +78,21 @@ refused when it is group- or world-readable, inside a git work tree or under connect to Postgres only as `reader_url=` and are refused without it - never with the writer's credential. +THE MODE (feature 007, D3): `mode=index`, the default, or `mode=primary`, +where the SQL register is the register's store. `lanes-index mode` answers it +from the configuration alone, and `lanes-edit.sh` asks it only where a +configuration exists (FR-002). While `RENDER_GIT_HALF` is False, +`mode=primary` is refused where the configuration is read (Q6(c), FR-003): +`mode` and `register read` exit 78, `EX_CONFIG`, and every other subcommand +exits 2, each with `MODE_PRIMARY_REFUSED_TEXT`. + Exit codes: 0 done · 1 a read or a write failed (nothing half-written) · 2 a refusal (the configuration, a `--source` that is not this workstation's, an inventory on a workstation with no name) · 3 `export` only: the index cannot answer (missing, unreachable, wiped, unknown -schema - the reason is in `/why`) · 64 usage. +schema - the reason is in `/why`) · 64 usage. The SQL register's +subcommands add 69, 75 and 78, and 3 for a write in doubt, each named by an +`EXIT_` constant once a subcommand exits with it (contracts/exit-codes.md). """ from __future__ import annotations @@ -100,6 +119,32 @@ VERSION = "1" #: way for the index to be wrong. SCHEMA_VERSION = 1 +#: Q6(c)'S REFUSAL, BUILT IN (FR-003; D3, design Y:4848 and Y:4872): False +#: until the renderer's git half is installed, so no write can reach a +#: register this build could not mirror. While it is False, `load_config` +#: refuses `mode=primary`: `mode` and `register read` exit `EXIT_CONFIG` with +#: `MODE_PRIMARY_REFUSED_TEXT`, and every other subcommand refuses it with 2 +#: and the same text. Lane 3's T328, phase 3's last pull request, is the only +#: change that sets it True. A test that needs `primary` runs a copy of this +#: file with it flipped, in its own temporary directory (FR-017). Never an +#: environment variable, which any lane could set. +RENDER_GIT_HALF = False + +#: Q6(c)'s fixed text (agreement test 14; design Y:4872). +MODE_PRIMARY_REFUSED_TEXT = ( + "mode=primary is not available in this build: the renderer's git half is not " + "installed, so a write could not be mirrored; nothing was written") + +#: THE EXIT CODES, NAMED (contracts/exit-codes.md section 1): the tests read +#: the constant, never a literal. The task that first exits with a code names +#: it here; `mode`'s are 0, 2, 64 and 78. #160's own exits keep their literals. +EXIT_OK = 0 +EXIT_REFUSED = 2 +EXIT_USAGE = 64 +#: `EX_CONFIG`: Q6(c)'s refusal of `mode=primary`, from `mode` and +#: `register read` only (D3, Y:368-382; F8, lane 4's pick). +EXIT_CONFIG = 78 + US = "\x1f" LANES_DIR = "lanes/" REGISTER_PATH = "lanes/LANES.md" @@ -120,6 +165,18 @@ class Refusal(Exception): """A refusal: exit 2, nothing read and nothing written.""" +class PrimaryNotBuilt(Refusal): + """Q6(c)'s refusal of `mode=primary` while `RENDER_GIT_HALF` is False + (FR-003), raised by `load_config` with `MODE_PRIMARY_REFUSED_TEXT`. + + It is a `Refusal`, so every subcommand that answers a refused + configuration with 2 answers this one with 2 too, `journal --write-id` + included, whose other refused configurations are 3 (contract §3.4, CO-3). + Only `mode` and `register read`, in all four of its forms, catch it first + and exit `EXIT_CONFIG` (contract §2.7): under `--for guard` it stays 78, + though a refused configuration is 1 there (O14).""" + + class StoreUnusable(Exception): """The store cannot answer: missing, unreachable, wiped or another schema. @@ -231,25 +288,353 @@ def _url_has_password(url: str) -> bool: return bool(re.search(r"(^|\s)password\s*=", low, re.IGNORECASE)) -def _check_private_file(path: str, what: str) -> None: +def _check_private_file(path: str, what: str, *, shown: bool = True) -> None: + """`path` refused unless it is a regular file with no group or other + permission bit. Where `shown` is False, `path` is a key's value, which may + be a misplaced URL or password, so no refusal prints it: `what` names the + key (contracts/config.md section 4: a refusal prints no URL and no + password).""" + named, target = (f"{what} {path}", path) if shown else (what, "the file it names") try: st = os.stat(path) except OSError as exc: - raise Refusal(f"{what} {path} cannot be read: {exc.strerror or exc}") + why = exc.strerror or (exc if shown else type(exc).__name__) + raise Refusal(f"{named} cannot be read: {why}") if not stat.S_ISREG(st.st_mode): - raise Refusal(f"{what} {path} is not a regular file") + raise Refusal(f"{named} is not a regular file") if st.st_mode & 0o077: raise Refusal( - f"{what} {path} is mode {oct(st.st_mode & 0o777)[2:]}, so another account " + f"{named} is mode {oct(st.st_mode & 0o777)[2:]}, so another account " f"on this workstation can read it (Amendment 14(c): mode 0600). " - f"Fix it: chmod 600 {path}") + f"Fix it: chmod 600 {target}") + + +#: SVC-2'S FIXED MAPPING (Question 11; design Y:3798-3819): the six query +#: parameters a connection URL may carry, each to the libpq variable `psql` +#: reads it from. The URL's own parts map the same way: its hosts to `PGHOST`, +#: their ports to `PGPORT`, its database to `PGDATABASE` and its user to +#: `PGUSER`. Anything else is refused, so a direct read and the service (U5) +#: connect with the same parameters. +PG_URL_PARAMS = { + "sslmode": "PGSSLMODE", + "sslrootcert": "PGSSLROOTCERT", + "sslcert": "PGSSLCERT", + "sslkey": "PGSSLKEY", + "target_session_attrs": "PGTARGETSESSIONATTRS", + "connect_timeout": "PGCONNECT_TIMEOUT", +} + +#: NEVER HANDED ON FROM THE CALLER'S ENVIRONMENT (Y:4970; lane 5's 6579523948, +#: accepted by lane 3 in 6579562840): a password, and each variable that points +#: libpq at a file the configuration did not name. `PGPASSFILE` is then set to +#: the configured file or `_no_password_file()`. `PGSERVICE` goes too, and is +#: set only on the admin path (T109, T110): libpq reads a service's entries +#: BEFORE the `PG*` variables (`conninfo_add_defaults`), so an inherited +#: service would outrank the URL's own parts once they travel as variables, +#: where `-d ` used to outrank it. +PG_ENV_DROPPED = ("PGPASSWORD", "PGPASSFILE", "PGSERVICEFILE", "PGSYSCONFDIR", "PGSERVICE") + +#: `connect_timeout` is the workstation's `c` (D9). A value under 2 is refused, +#: since libpq reads 1 as 2 and 0 as no limit (Y:3810-3811); with none, `c` is +#: 2 on a register path. #160's index paths keep their 5 s (`PostgresStore`). +CONNECT_TIMEOUT_MIN = 2 +CONNECT_TIMEOUT_DEFAULT = 2 + + +def _pg_url_decode(text: str, what: str, part: str) -> str: + """One URL part percent-decoded as libpq decodes it (`conninfo_uri_decode`): + `%XX` only, so a `+` stays a `+`. A broken escape, a `%00` and bytes that + are not UTF-8 are refused.""" + out = bytearray() + i = 0 + while i < len(text): + if text[i] != "%": + out += text[i].encode("utf-8") + i += 1 + continue + pair = text[i + 1:i + 3] + if len(pair) != 2 or not all(c in "0123456789abcdefABCDEF" for c in pair): + raise Refusal(f"{what}: its {part} carries a `%` that is not a `%XX` escape") + if pair == "00": + raise Refusal(f"{what}: its {part} carries `%00`, which libpq refuses") + out.append(int(pair, 16)) + i += 3 + try: + return out.decode("utf-8") + except UnicodeDecodeError: + raise Refusal(f"{what}: its {part} does not decode as UTF-8") + + +def pg_url_env(url: str, what: str = "the URL") -> dict: + """THE ONE MAPPING from a configured URL to the `PG*` variables of the + `psql` child that connects with it (Question 11; SVC-2, design + Y:3798-3819). No `lanes-index` path puts a connection string in an + argument list, where `/proc` shows it for the process's life (Y:3491): + each hands its child the variables this returns, and the service (U5) + reuses it. + + The URL is libpq's own, read as `conninfo_uri_parse_options` reads it: + `postgresql://` or `postgres://`, then `[user@]`, then hosts as + `host[:port]` separated by commas (an IPv6 address in brackets), then + `[/database]` and `[?name=value&...]`, each part percent-decoded. The hosts + go to `PGHOST` and their ports to `PGPORT`, each a comma list as libpq + keeps it, the database to `PGDATABASE`, the user to `PGUSER`, and each of + `PG_URL_PARAMS` to its twin. Only what the URL names is returned. + + REFUSED, as `Refusal` (2), naming `what` and never printing the URL: a + connection string of any other form; a password, in the user part or as + `password=`; a query parameter outside the six, or one named twice; and a + `connect_timeout` that is not a whole number of at least 2 seconds.""" + text = url.strip() + prefix = next((p for p in ("postgresql://", "postgres://") if text.startswith(p)), "") + if not prefix: + raise Refusal( + f"{what} is not a `postgresql://` URL. Every `psql` takes its connection " + f"from `PG*` variables mapped from a URL's parts (SVC-2), never from a " + f"connection string in its arguments") + password = (f"{what} carries a password. The secret lives only in the 0600 libpq " + f"password file, never in a URL a command line or a log can show") + rest = text[len(prefix):] + env: dict = {} + # THE USER: the first `@` before any `/`, where libpq looks for it. + at, slash = rest.find("@"), rest.find("/") + if at != -1 and (slash == -1 or at < slash): + userinfo, rest = rest[:at], rest[at + 1:] + if ":" in userinfo: + raise Refusal(password) + user = _pg_url_decode(userinfo, what, "user") + if user: + env["PGUSER"] = user + # THE HOSTS AND THEIR PORTS, each list joined by commas as libpq joins it. + hosts, ports, i = [], [], 0 + while True: + if rest[i:i + 1] == "[": + end = rest.find("]", i + 1) + if end in (-1, i + 1): + raise Refusal(f"{what}: an IPv6 host's brackets are empty or never closed") + host, i = rest[i + 1:end], end + 1 + if rest[i:i + 1] not in ("", ":", "/", "?", ","): + raise Refusal(f"{what}: an IPv6 host's `]` is followed by an unexpected " + f"character") + else: + j = i + while j < len(rest) and rest[j] not in ":/?,": + j += 1 + host, i = rest[i:j], j + port = "" + if rest[i:i + 1] == ":": + j = i + 1 + while j < len(rest) and rest[j] not in "/?,": + j += 1 + port, i = rest[i + 1:j], j + hosts.append(host) + ports.append(port) + if rest[i:i + 1] != ",": + break + i += 1 + if ",".join(hosts): + env["PGHOST"] = _pg_url_decode(",".join(hosts), what, "host") + if ",".join(ports): + env["PGPORT"] = _pg_url_decode(",".join(ports), what, "port") + # THE DATABASE, from the hosts' `/` to the query. An empty one is left + # unset, as libpq leaves it. + tail, query = rest[i:], "" + if tail.startswith("/"): + database, _mark, query = tail[1:].partition("?") + if database: + env["PGDATABASE"] = _pg_url_decode(database, what, "database") + elif tail.startswith("?"): + query = tail[1:] + pieces = query.split("&") if query else [] + if pieces and pieces[-1] == "": + pieces.pop() # a trailing `&`, which libpq passes over + seen = set() + for piece in pieces: + if piece.count("=") != 1: + raise Refusal(f"{what}: a query parameter is not one `name=value`") + raw_name, raw_value = piece.split("=") + name = _pg_url_decode(raw_name, what, "query") + if name == "password": + raise Refusal(password) + if name not in PG_URL_PARAMS: + named = (f"`{name}=`" if re.fullmatch(r"[a-z_]{1,40}", name) + else "a name that is not a libpq keyword") + raise Refusal( + f"{what} carries the query parameter {named}, which no connection " + f"carries: only {', '.join(PG_URL_PARAMS)} map to `PG*` variables (SVC-2)") + if name in seen: + raise Refusal(f"{what} names `{name}=` twice") + seen.add(name) + env[PG_URL_PARAMS[name]] = _pg_url_decode(raw_value, what, f"`{name}=`") + if "PGCONNECT_TIMEOUT" in env: + raw = env["PGCONNECT_TIMEOUT"] + if not re.fullmatch(r"\s*[+-]?[0-9]+\s*", raw): + raise Refusal(f"{what} carries a `connect_timeout=` that is not a whole number " + f"of seconds") + if int(raw) < CONNECT_TIMEOUT_MIN: + # THE KEY AND THE MINIMUM, NEVER THE VALUE (lane 3's ruling, + # opensoft/openRepoTools#165 6938005990; contracts/config.md section 4, + # :119 and R14; exit-codes.md:57): a whole number under 2 may be a + # misplaced password, so the refusal names `connect_timeout=` alone. + raise Refusal( + f"{what} carries a `connect_timeout=` under {CONNECT_TIMEOUT_MIN}: it is " + f"the workstation's `c` (D9), and libpq reads 1 as 2 and 0 as no limit") + env["PGCONNECT_TIMEOUT"] = str(int(raw)) + return env + + +def _pg_host_stays_local(host: str) -> bool: + """Whether libpq reaches one of `PGHOST`'s hosts without leaving this + machine (R09; contract §2.5): a Unix socket - an empty host, which is + libpq's default socket directory, or a host that decodes to an absolute + path - or a loopback host, `localhost`, an address in 127.0.0.0/8, or + ::1. Anything else is a TCP host that is not loopback, a name included, + whatever it resolves to.""" + import ipaddress # only the TLS check at load reads addresses + + if host == "" or host.startswith("/") or host.lower() == "localhost": + return True + try: + address = ipaddress.ip_address(host) + except ValueError: + return False + if address.version == 4: + return address in ipaddress.ip_network("127.0.0.0/8") + return address == ipaddress.IPv6Address("::1") + + +def pg_url_refuse_unverified_tls(env: dict, what: str) -> None: + """THE TLS REFUSAL AT LOAD (FR-011; lane 3's R09 left it to lane 1, and + lane 1's T104 takes it; contract §2.5). `env` is `pg_url_env`'s mapping of + one URL. Where any of its hosts is a TCP host that is not loopback, the URL + must carry `sslmode=verify-full` and an `sslrootcert=` that names an + existing regular file, the root of the issuer that signs the server's + certificate: libpq's default, `prefer`, verifies nothing (design Y:2324), + and `system` is never that root, since no system store holds a private + one (C7, Y:2324). A socket and a loopback host connect without it, so a + local cluster and its 127.0.0.1 stand-ins keep working. + + REFUSED, as `Refusal` (2), naming `what` and everything missing, and + printing no URL, no host and no root file's path.""" + hosts = env.get("PGHOST", "").split(",") + if all(_pg_host_stays_local(host) for host in hosts): + return + missing = [] + if "PGSSLMODE" not in env: + missing.append("its query carries no `sslmode=`, and libpq's default, `prefer`, " + "verifies nothing") + elif env["PGSSLMODE"] != "verify-full": + missing.append("its `sslmode=` is not `verify-full`, so the server is not verified " + "against its name") + root = env.get("PGSSLROOTCERT", "") + if not root: + missing.append("its query carries no `sslrootcert=` naming the root file") + elif root == "system": + missing.append("its `sslrootcert=` is `system`, the system's store, which holds no " + "private root (C7)") + else: + try: + regular = stat.S_ISREG(os.stat(root).st_mode) + why = "" if regular else "it is not a regular file" + except OSError as exc: + regular, why = False, exc.strerror or "it cannot be read" + if not regular: + missing.append(f"its `sslrootcert=` names no existing regular file ({why})") + if missing: + raise Refusal( + f"{what} names a TCP host that is not loopback, where a connection must " + f"verify the server (FR-011): it needs `sslmode=verify-full` and an " + f"`sslrootcert=` that names the root file of the issuer that signs the " + f"server's certificate, never `system` (design Y:2324), but " + f"{'; and '.join(missing)}. Only a Unix socket and a loopback host " + f"(`localhost`, 127.0.0.0/8 or ::1) connect without them") + + +def _check_register_keys(cfg: dict, path: str) -> None: + """007'S KEYS, EACH ON ITS OWN (FR-001; contracts/config.md section 4, R7, + R11, R12 and R16), refused as `Refusal` (2). `register_addresses` and + `register_rtt_ms` are made whole numbers in `cfg`. Each refusal names the + key and the file, and never the value, which may be a misplaced URL or + password (contracts/config.md section 4: no URL and no password).""" + # THE MODE (FR-001; Y:4849): `index` or `primary`, and absent is `index`. + if cfg["mode"] not in ("index", "primary"): + raise Refusal(f"`mode=` in {path}: the mode is `index` or `primary`") + if not SCHEMA_NAME_RE.fullmatch(cfg["register_schema"]): + raise Refusal(f"`register_schema=` in {path} is not a plain lower-case SQL identifier") + # `N_a` AND THE ROUND TRIP (D9, Y:5877; SVC-6, Y:4005): each a whole number, + # measured when the workstation joins. + for key, least, what in (("register_addresses", 1, "`N_a`, the number of addresses " + "the register's endpoint resolves to (D9)"), + ("register_rtt_ms", 0, "the p90 of the workstation's round " + "trips to the register, in whole milliseconds (SVC-6)")): + if not re.fullmatch(r"[0-9]+", cfg[key]) or int(cfg[key]) < least: + raise Refusal(f"`{key}=` in {path} is not a whole number of at least " + f"{least}: it is {what}") + cfg[key] = int(cfg[key]) + for key, what in (("register_passfile", "the libpq password file"), + ("render_key", "the renderer's deploy-key file")): + if cfg[key]: + _check_private_file(cfg[key], f"{what} (`{key}=`)", shown=False) + + +def _check_register_connections(cfg: dict, path: str, named_store: str, mapped: dict) -> None: + """007'S RULES ACROSS KEYS (FR-001, FR-011; contracts/config.md section 4, + R8, R9, R10 and R15), refused as `Refusal` (2). `named_store` is `store=` + as the file wrote it, before its default; `mapped` holds `pg_url_env`'s + mapping of each URL the file names.""" + # PRIMARY NEEDS THE REGISTER'S OWN DATABASE (FR-001): the register is shared + # by every workstation, and SQLite is one disk. + if cfg["mode"] == "primary": + wrong = [] + if named_store == "sqlite": + wrong.append("it names `store=sqlite`, and the register, which every " + "workstation shares, is never on one disk") + if not cfg["register_url"]: + wrong.append("it names no `register_url=`, the REGISTER-WRITER login the " + "register's writes connect as") + if wrong: + raise Refusal(f"`mode=primary` in {path} is refused: {'; and '.join(wrong)}") + if not cfg["register_url"]: + # #160'S FILE (US1): its `reader_url=` may name a TCP host with no TLS, + # and it loads as it always has. + return + # THE REGISTER-WRITER PAIR, by the rule `PostgresStore` applies to `url=`: + # a read never connects with the writer's credential. + if not cfg["reader_url"]: + raise Refusal( + f"`register_url=` in {path} has no `reader_url=` beside it: the register's " + f"reads connect only as this engineer's READER login, never with the " + f"writer's credential (Amendment 14(c))") + # THE TLS REFUSAL AT LOAD (R09; FR-011), of both URLs. + pg_url_refuse_unverified_tls(mapped["register_url"], f"`register_url=` in {path}") + pg_url_refuse_unverified_tls(mapped["reader_url"], + f"`reader_url=` in {path}, beside its `register_url=`,") def load_config() -> dict: - """The per-workstation configuration, refused on any of clause (c)'s grounds.""" + """The per-workstation configuration, refused on any of clause (c)'s grounds, + and on 007's (FR-001, FR-011; contracts/config.md section 4): `mode=` that + is not `index` or `primary`; `mode=primary` naming `store=sqlite`, or with + no `register_url=`; `register_url=` with no `reader_url=`; a + `register_schema=` that is not a plain lower-case SQL identifier; a + `register_addresses=` or `register_rtt_ms=` that is not a whole number; a + `register_passfile=` or `render_key=` that is not a private regular file; + and, where `register_url=` is set, R09's TLS refusal of it and of + `reader_url=`. A file with no `register_url=` is #160's, and loads as it + always has. + + While `RENDER_GIT_HALF` is False, `mode=primary` is refused as + `PrimaryNotBuilt` (Q6(c), FR-003), after the file's own checks and each + key's, and before the rules across keys, so `mode=primary` with + `store=sqlite`, with no `register_url=` or with a URL R09 would refuse is + Q6(c)'s refusal until the constant is set.""" path, named = config_path() cfg = {"path": path, "present": False, "store": "", "url": "", "passfile": "", - "reader_url": "", "reader_passfile": "", "sqlite": "", "schema": "lanes_index"} + "reader_url": "", "reader_passfile": "", "sqlite": "", "schema": "lanes_index", + # 007's keys (FR-001; Y:4849): absent `mode=` is `index`, today's behaviour. + "mode": "index", "register_url": "", "register_passfile": "", "register_label": "", + "register_schema": "lanes_register", "render_key": "", "register_addresses": "1", + "register_rtt_ms": "0"} if not os.path.lexists(path): if named: raise Refusal(f"LANES_INDEX_CONFIG names {path}, which does not exist") @@ -277,52 +662,115 @@ def load_config() -> dict: lines = handle.read().splitlines() except (OSError, UnicodeDecodeError) as exc: raise Refusal(f"the configuration {path} cannot be read: {exc}") - known = ("store", "url", "passfile", "reader_url", "reader_passfile", "sqlite", "schema") + known = ("store", "url", "passfile", "reader_url", "reader_passfile", "sqlite", "schema", + "mode", "register_url", "register_passfile", "register_label", + "register_schema", "render_key", "register_addresses", "register_rtt_ms") for number, raw in enumerate(lines, 1): line = raw.strip() if not line or line.startswith("#"): continue if "=" not in line: - raise Refusal(f"{path}:{number} is not `key=value`: {line!r}") + raise Refusal(f"{path}:{number} is not `key=value`") key, value = (part.strip() for part in line.split("=", 1)) if key not in known: - raise Refusal(f"{path}:{number} names `{key}=`, which this indexer does not " + named = (f"`{key}=`" if re.fullmatch(r"[a-z_]{1,40}", key) + else "a key that is not a plain lower-case word") + raise Refusal(f"{path}:{number} names {named}, which this indexer does not " f"know (it reads {', '.join(k + '=' for k in known)})") if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": value = value[1:-1] if value.startswith("~/"): value = os.path.join(_home(), value[2:]) cfg[key] = value - for key in ("url", "reader_url"): + mapped = {} + for key in ("url", "reader_url", "register_url"): if cfg[key] and _url_has_password(cfg[key]): raise Refusal( f"`{key}=` in {path} carries a password. The secret lives only in the " - f"0600 libpq password file `passfile=` names (Amendment 14(c)), never in " - f"a URL a command line or a log can show") + f"0600 libpq password file " + f"`{'register_passfile' if key == 'register_url' else 'passfile'}=` names " + f"(Amendment 14(c)), never in a URL a command line or a log can show") + # MAPPED AT LOAD (Question 11; Y:4970, "`load_config` refuses any other + # query parameter"): a URL SVC-2's mapping refuses is refused here, before + # any command runs a `psql`, and never at a first connect. + if cfg[key]: + mapped[key] = pg_url_env(cfg[key], f"`{key}=` in {path}") + named_store = cfg["store"] store = cfg["store"] or ("postgres" if cfg["url"] else "sqlite") if store not in ("sqlite", "postgres"): - raise Refusal(f"`store={cfg['store']}` in {path}: the store is `sqlite` or `postgres`") + raise Refusal(f"`store=` in {path}: the store is `sqlite` or `postgres`") if store == "postgres" and not cfg["url"]: raise Refusal(f"`store=postgres` in {path} names no `url=`") cfg["store"] = store if not SCHEMA_NAME_RE.match(cfg["schema"]): - raise Refusal(f"`schema={cfg['schema']}` in {path} is not a plain lower-case SQL identifier") + raise Refusal(f"`schema=` in {path} is not a plain lower-case SQL identifier") for key in ("passfile", "reader_passfile"): if cfg[key]: - _check_private_file(cfg[key], f"the libpq password file (`{key}=`)") + _check_private_file(cfg[key], f"the libpq password file (`{key}=`)", shown=False) + _check_register_keys(cfg, path) + # Q6(c)'S REFUSAL (FR-003; Y:4849, Y:4872), once the file and every key in + # it has passed on its own, and BEFORE the rules across keys: a `primary` + # this build cannot serve is refused for that, whatever else the file + # says. So test 14's refusing state, with `register_url=` on `db.invalid` + # and no TLS, is 78 from `mode` and `register read`, never R15's 2. + if cfg["mode"] == "primary" and not RENDER_GIT_HALF: + raise PrimaryNotBuilt(MODE_PRIMARY_REFUSED_TEXT) + _check_register_connections(cfg, path, named_store, mapped) if store == "sqlite": sqlite_path = cfg["sqlite"] or os.path.join(state_dir(), "lanes-index.sqlite") sqlite_path = os.path.abspath(sqlite_path) tree = git_work_tree_of(os.path.dirname(os.path.realpath(sqlite_path))) if tree: + # THE FILE, OR THE KEY ALONE (lane 3's rulings, opensoft/openRepoTools#165 + # 6933409373 and 6934430226; contracts/config.md section 4, :119): the + # store's path is named only where `sqlite=`'s value holds no `://`, no + # `@` and no `=`, so it can be no URL and no `password=`; otherwise the + # key alone, as R11's refusal names it. + named = (f"the SQLite store {sqlite_path}" + if "://" not in cfg["sqlite"] and "@" not in cfg["sqlite"] + and "=" not in cfg["sqlite"] + else "the SQLite store `sqlite=` names") raise Refusal( - f"the SQLite store {sqlite_path} would be inside the git work tree {tree}; " + f"{named} would be inside the git work tree {tree}; " f"the index lives on local disk and never inside a work tree " f"(Amendment 14(c)). Name another path with `sqlite=`") cfg["sqlite"] = sqlite_path return cfg +def cmd_mode(args: list[str]) -> int: + """`lanes-index mode` (contract §3.1; D3, Y:2441-2453; F8): this + workstation's mode, `index` or `primary`, as ONE line on stdout and nothing + else, exit 0. It reads only the configuration, through `load_config`, and + opens no database and runs no `psql` (Y:3521). + + With no file at the default path, and `LANES_INDEX_CONFIG` unset or empty, + it answers `index`, as does a file with no `mode=`. A configuration + `load_config` refuses exits 2. `mode=primary` while `RENDER_GIT_HALF` is + False exits `EXIT_CONFIG`, 78, with `MODE_PRIMARY_REFUSED_TEXT` on stderr + and nothing on stdout. An argument is usage, 64, before anything is + read, and its usage line never shows the argument, which may be a + misplaced URL or password (contract §2.6: nothing secret reaches + stderr). Its caller, `lanes-edit.sh` (lane 4's T409), reads 78 as "exit 69, + writing nothing", and every other end as files mode with a warning.""" + for arg in args: + if arg in ("-h", "--help"): + say(USAGE) + return EXIT_OK + note(f"mode takes no argument - see {PROG} --help") + return EXIT_USAGE + try: + cfg = load_config() + except PrimaryNotBuilt as exc: + note(str(exc)) + return EXIT_CONFIG + except Refusal as exc: + note(f"REFUSED: {exc}") + return EXIT_REFUSED + say(cfg["mode"]) + return EXIT_OK + + # =============================================================== the source def lanes_edit_path() -> str: @@ -358,9 +806,14 @@ def workspace_root() -> str: check=False, env=helper_env(), stdin=subprocess.DEVNULL) root = proc.stdout.strip() if proc.returncode != 0 or not root: - why = (proc.stderr.strip().splitlines() or ["no answer"])[0] + # NOT ITS WORDS (lane 1, under B1 of opensoft/openRepoTools-code#89 comment + # 6947619546): they name `workspace.yaml`'s `repository:` and the checkout's + # `origin` as they stand, either of which may hold a credential, before any key is + # made of them; `lanes-edit.sh workspace-root` says them to whoever runs it raise StoreUnusable("unread", f"`lanes-edit.sh workspace-root` exited " - f"{proc.returncode}: {why}") + f"{proc.returncode}: the workspace repository could not be found " + f"(its own words are not shown, since they can name a credential; " + f"run it to see them)") return root @@ -397,6 +850,164 @@ def source_of(root: str) -> str: return f"register:{repo}" +def _source_key(source: str) -> str: + """THE INDEX'S KEY FOR `source`, WITH NO CREDENTIAL (lane 3's ruling, + opensoft/openRepoTools-code#89 comment 6940341452): `source_of`'s value with + the userinfo of its URL taken out where that userinfo can be a credential: + all of it in an http(s) URL, where a token can stand as the user, and in any + URL whose userinfo holds a password (a `:`). Every other value - GitHub's + `owner/repo`, a path, an scp-like or ssh login such as `git@`, `inventory:` + and `register:?` - is returned as it is, so a source with no credential + keeps today's key and no stored row of it moves. Two keys are equal only + where the URLs differ by their credential alone: the same repository. The + userinfo is what stands before an `@` in the URL's authority, which ends at + its first `/`, `?` or `#` (RFC 3986 3.2).""" + m = re.match(r"(register:([A-Za-z][A-Za-z0-9+.-]*)://)([^/?#]*)@", source) + if m and (m.group(2).lower() in ("http", "https") or ":" in m.group(3)): + return m.group(1) + source[m.end():] + return source + + +#: WHAT `status` SAYS IN PLACE OF A LEGACY ENTRY'S LAST ERROR (lane 3's ruling, +#: opensoft/openRepoTools-code#89 comment 6941833120). v1.1.0 and v1.2.0 keyed a +#: source as `source_of` read it, a credential included, and SQLite's `CasLost` put +#: that key in the text `_record_error` saved. An entry whose name `_source_key` +#: changes is such an entry, so its error is never printed; the next `sync` or +#: `reconcile` removes it (`_drop_legacy`). +LEGACY_LAST_ERROR = ("not shown: an earlier build filed this entry under a key that held a " + "credential, and the next sync or reconcile removes it") + +#: THE FORMS THIS BUILD FILES A SOURCE UNDER, AS PREFIXES (lane 3's ruling, +#: opensoft/openRepoTools-code#89 comment 6944673181): `register:` and the repository +#: `source_of` reads (`register:?` where `_record_error` cannot resolve it), `inventory:` +#: and this workstation's name (`inventory:?`), and T058's `ledger:` in the +#: ledger half's tables. The prefix is the whole exact list: what follows it is a +#: repository or a workstation's name as given, and neither has a closed form. +FILED_PREFIXES = ("register:", INVENTORY_PREFIX, "ledger:") + +#: WHAT `status` PRINTS IN PLACE OF A WHOLE ENTRY WHOSE KEY IS NOT A FORM THIS BUILD +#: FILES (lane 3's ruling, comment 6944416906): its key, provenance and error unshown. +LEGACY_SOURCE_LINE = ("source not shown: an earlier build filed an entry under a key this " + "build does not file, which may hold a credential; the next sync or " + "reconcile removes it") + + +#: THE KEY RULE'S `password` TERM (lane 3's ruling, question 2 of +#: opensoft/openRepoTools-code#89 comment 6955397261): `password` in ASCII letters, in any +#: case by explicit classes, then any run of separators, then `=` or `%3D`. A separator is a +#: character `str.isspace()` holds, as the ruling's explicit list of 29 (U+0009-000D, +#: U+001C-0020, U+0085, U+00A0, U+1680, U+2000-200A, U+2028, U+2029, U+202F, U+205F and +#: U+3000), each written as backslash-u and four hex digits, which both engines read; `+`; +#: or a percent-escape, `%` and two hex digits. ONE ASCII raw-string text, used verbatim by +#: Python (`re.search`, no flags; SQLite takes Python's list) and PostgreSQL (`~`, never +#: `~*`, under `standard_conforming_strings`). Never backslash-x, which PostgreSQL reads with +#: any number of hex digits. The word is literal: `p%61ssword=`, and `pa` U+017F `sword=`, +#: stay clean, as the rule is structural. +PASSWORD_RULE = (r"[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]([" + r"\u0009\u000a\u000b\u000c\u000d\u001c\u001d\u001e\u001f\u0020" + r"\u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006" + r"\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000" + r"+]|%[0-9A-Fa-f]{2})*(=|%3[Dd])") + + +def _is_legacy(name: str) -> bool: + """A KEY AN EARLIER BUILD FILED AND THIS ONE WOULD NOT (lane 3's rulings, + opensoft/openRepoTools-code#89 comments 6944416906 and 6944673181), judged by its + STRUCTURE, never by a guess at a token in its text: a key under none of + `FILED_PREFIXES` (v1.1.0 and v1.2.0 `_record_error` filed the raw `--source` value: + a URL, a `password=` value, a bare token); a key `_source_key` changes (a register + URL's userinfo that can hold a credential); a key holding `password=`, in any case + (`inventory:password=` among them); and an `inventory:` or `ledger:` key holding a + URL with userinfo, which no workstation's name holds. A key of every other form is + one this build files, and stays as it is. ITS EDGES (lane 3's ruling, + opensoft/openRepoTools-code#89 comment 6947619546): a key holding a control + character (C0, DEL or C1), or `password` and then `=` or `%3D` across any run of + separators (`PASSWORD_RULE`, lane 3's ruling on comment 6955397261), is legacy too; + and no source this build makes is (`resolve_source`, `inventory_source`).""" + if not name.startswith(FILED_PREFIXES): + return True + if _source_key(name) != name or re.search(r"[\x00-\x1f\x7f-\x9f]", name): + return True + if re.search(PASSWORD_RULE, name): + return True + return (not name.startswith("register:") and + re.search(r"[A-Za-z][A-Za-z0-9+.-]*://[^/?#]*@", name) is not None) + + +#: `_is_legacy` AS THE SERVER READS IT (lane 1's coordinator, on commit 14's design): the +#: PostgreSQL removal chooses a legacy source's rows by the same structural rule, so neither +#: a legacy key nor any value made from one, a digest included, is in the script. Term by +#: term: no filed prefix; `PASSWORD_RULE` itself; `_source_key`'s userinfo in an http(s) +#: URL, or holding a `:` in any URL; an `inventory:` or `ledger:` key holding URL userinfo. +#: No term is case-blind (`~*`): each case is an explicit class, as Python reads it (lane 3's +#: ruling on comment 6955397261). +PG_LEGACY_SQL = ("(NOT (source LIKE 'register:%' OR source LIKE 'inventory:%' OR source LIKE " + "'ledger:%') OR source ~ '[\\x01-\\x1f\\x7f-\\x9f]' OR source ~ '" + PASSWORD_RULE + "' " + "OR source ~ '^register:[Hh][Tt][Tt][Pp][Ss]?://[^/?#]*@' " + "OR source ~ '^register:[A-Za-z][A-Za-z0-9+.-]*://[^/?#]*:[^/?#]*@' OR (source " + "!~ '^register:' AND source ~ '[A-Za-z][A-Za-z0-9+.-]*://[^/?#]*@'))") + + +#: THE REFUSAL OF A SOURCE THIS BUILD WOULD CALL LEGACY (lane 3's ruling, B1 of +#: opensoft/openRepoTools-code#89 comment 6947619546): exit 2 before anything is printed, +#: filed or sent, in words that do not echo the value. +REGISTER_KEY_REFUSED = ("this workstation's register, as `workspace.yaml` or the checkout's " + "`origin` names it, is not a form this build files: it may hold a " + "credential, a `password=` or a control character. Nothing was printed, " + "filed or sent; name the repository without one") +INVENTORY_KEY_REFUSED = ("this workstation's name, as `LANES_WORKSTATION` or the host gives it, " + "is not a form this build files: it may hold a credential, a " + "`password=` or a control character. Nothing was printed, filed or " + "sent; give the workstation a plain name") + +#: THE FIXED WORDS OF A CLEANUP OR AN INDEX psql CALL THAT FAILED (lane 3's ruling, +#: opensoft/openRepoTools-code#89 comment 6944416906): none of them carries a value read +#: from a file, a key or psql's text. +STATUS_UNREADABLE = ("the status file cannot be read, so the entries an earlier build " + "filed in it cannot be removed") +STATUS_UNREPLACEABLE = ("the status file cannot be replaced, so the entries an earlier " + "build filed in it are not removed") +STATUS_UNPARSEABLE_WARNING = ("WARNING: the status file is not one this build can parse; none " + "of its bytes are shown, and a run that writes replaces it with " + "an empty one") +SCRUB_UNMARKED = ("the mark that the store's scrub is due cannot be made, so no source an " + "earlier build filed was removed") +SCRUB_UNFINISHED = ("a scrub is pending: a source an earlier build filed was removed, and " + "the store's free space, WAL or journal was not clean after every try; the " + "next write finishes the scrub first") +#: A scrub's tries in one run, and the pause before each retry, times its number. +SCRUB_ATTEMPTS = 3 +SCRUB_PAUSE_S = 0.5 +#: The scrub mark's whole text: it holds no key. +SCRUB_MARK_TEXT = ("lanes-index: a source was removed from this store; its free space, WAL " + "and journal are scrubbed before the next write\n") +PSQL_NO_CONNECTION = ("psql could not connect to the index's database, or lost its " + "connection (exit 2); psql's own words are not shown") +PSQL_CAS_LOST = ("the provenance of this workstation's source moved under this sync; " + "nothing was written") +#: The SQLSTATEs of a table or schema that does not exist: an index `open_read` calls +#: `wiped`, and `open_write` fills. +PSQL_UNDEFINED = ("42P01", "3F000") +#: psql's ERROR LINE (lane 3's ruling, question 1 of opensoft/openRepoTools-code#89 comment +#: 6955397261): the index's psql runs under `VERBOSITY=sqlstate`, so libpq prints a message +#: as its severity and its SQLSTATE alone, with no text, DETAIL, HINT, QUERY or CONTEXT, and +#: under `-f -` psql puts its `psql::: ` locus before it: one line a message, and +#: no quoted value reaches stderr. The LAST line that carries the locus decides: a NOTICE's +#: located line (42P07 of `IF NOT EXISTS`) comes before a later error, and ON_ERROR_STOP +#: prints nothing after the error. Where that line ends in a colon, two blanks and a +#: five-character code, that is the code; otherwise (a psql-side error, located with no code) +#: there is no SQLSTATE. Not the last MATCH: an earlier NOTICE's code would win. +PSQL_LOCATED_RE = re.compile(r"^psql:[^\n]*:[0-9]+: [^\n]*$", re.M) +PSQL_SQLSTATE_RE = re.compile(r"^psql:[^\n]*:[0-9]+: [^\n]+: ([0-9A-Z]{5})$", re.M) +#: THE INDEX'S psql ARGUMENTS: the script on stdin as the file `-`, which psql 16 names +#: `` (command.c, `process_file`), so its logger puts `psql::: ` before +#: each message (logging.c); and `VERBOSITY=sqlstate` (lane 3's ruling on comment +#: 6955397261, in place of `verbose`; psql 12 or later has it, and spec.md puts psql 15 or +#: later on every workstation). The register path keeps `verbose` (`REGISTER_PSQL_ARGS`). +INDEX_PSQL_ARGS = ("--no-psqlrc", "-X", "-q", "-v", "ON_ERROR_STOP=1", + "-v", "VERBOSITY=sqlstate", "-v", "SHOW_CONTEXT=never", "-f", "-") + + def branch() -> str: return os.environ.get("LANES_BRANCH") or "main" @@ -677,15 +1288,60 @@ def cell_state(row: str) -> str: return rest -REGISTER_KIND_RE = re.compile(r"^(HOLD RELEASED|HOLD|LANDING|LANDED)[ \t]+(—|-)[ \t]") +#: THE ONE CLASSIFIER'S KINDS (feature 007, FR-030; design S6 and D18). A +#: register line's kind is its own opening words, then blanks, an em dash or a +#: hyphen, and a blank. Rule 6's `LANDING` and `LANDED` and Amendment 10's +#: `HOLD` and `HOLD RELEASED` are today's four; Q17(B) adds `HOLD (refresh)`, +#: `HOLD (run id)`, `HOLD WITHDRAWN`, `HOLD EXPIRED`, `QUEUED-HOLD` and +#: `LANDING WITHDRAWN`, and F13 adds `LANDING EXPIRED`. The dash after the kind +#: keeps `HOLD (refresh) — ` from reading as `HOLD` and `LANDING EXPIRED — ` +#: from reading as `LANDING`, and leaves `LANDING EXPIREDX — `, +#: `HOLD REQUESTED — ` and `QUEUED-HOLD (refresh) — ` lines of no kind. +REGISTER_KIND_RE = re.compile( + r"^(HOLD RELEASED|HOLD WITHDRAWN|HOLD EXPIRED|HOLD \(refresh\)|HOLD \(run id\)|HOLD" + r"|QUEUED-HOLD|LANDING EXPIRED|LANDING WITHDRAWN|LANDING|LANDED)[ \t]+(—|-)[ \t]") + +#: Q17(B), kind by kind: the `slot_role` and `slot_kind` that migration 1's +#: `register_lines` holds for a line of each kind (design S6's table, and its +#: note on `register_lines.slot_kind`). A take holds its repository's `main`. +#: A close ends an open take of its own slot kind: `HOLD RELEASED`, +#: `HOLD WITHDRAWN` and `HOLD EXPIRED` the writer's `HOLD`, `LANDED` the +#: writer's `LANDING`, and `LANDING EXPIRED` the `LANDING` of the lane its +#: `for_lane` names. `HOLD (refresh)` and `HOLD (run id)` continue an open +#: `HOLD` and take nothing new; they, `QUEUED-HOLD` and `LANDING WITHDRAWN` +#: take and close nothing. `register_lines`' CHECKs still bind each row: a +#: slot needs a `repo_key`, and a landing slot a PR. +REGISTER_SLOTS: dict[str, tuple[str | None, str | None]] = { + "HOLD": ("take", "hold"), + "HOLD (refresh)": (None, None), + "HOLD (run id)": (None, None), + "HOLD RELEASED": ("close", "hold"), + "HOLD WITHDRAWN": ("close", "hold"), + "HOLD EXPIRED": ("close", "hold"), + "QUEUED-HOLD": (None, None), + "LANDING": ("take", "landing"), + "LANDED": ("close", "landing"), + "LANDING EXPIRED": ("close", "landing"), + "LANDING WITHDRAWN": (None, None), +} def parse_register_line(line: str) -> dict | None: - """Rule 6's `LANDING`/`LANDED` and Amendment 10's `HOLD`/`HOLD RELEASED`. - - The kind is the line's own first word(s); every other field is read the way - `RULE6_AWK` reads it, best effort, because a `HOLD` is free text by - Amendment 10(e) and the raw line is kept beside whatever was found.""" + """The one classifier (FR-030): a register line's kind and fields, or None + for a line of no kind. + + The kind is the line's own first word(s), by `REGISTER_KIND_RE`; every + other field is read the way `RULE6_AWK` reads it, best effort, because a + `HOLD` is free text by Amendment 10(e) and the raw line is kept beside + whatever was found. Each field is its first match, so a + `LANDING EXPIRED`'s `lane` is its writer, whose `lane ` comes first. + + A `LANDING EXPIRED` alone has one field more (F13), `for_lane`: the holder + whose `LANDING` it closes, from its first `for lane `, cut as a + `lane ` is cut. Its row needs the holder, the PR and the repository + (`register_lines`' CHECKs), so a line in its shape that lacks any of the + three is a line of no kind, None: it takes and releases nothing. Every + other kind keeps the seven fields it had.""" m = REGISTER_KIND_RE.match(line) if not m: return None @@ -710,9 +1366,107 @@ def parse_register_line(line: str) -> dict | None: tm = re.search(r"→ ([0-9a-f]{7,40})\b", line) or re.search(r" main ([0-9a-f]{7,40})\b", line) if tm: fields["tip"] = tm.group(1) + if fields["kind"] == "LANDING EXPIRED": + hm = re.search(r"for lane ([A-Za-z0-9._-]+)", line) + if not hm or fields["pr"] is None or fields["repo"] is None: + return None + fields["for_lane"] = hm.group(1) return fields +def register_utc_epoch(utc: str | None) -> int | None: + """A register line's UTC as `utc_ts` takes it (feature 007; contract + draft 4.10, section 3.5): the stamp `parse_register_line` found, + `YYYY-MM-DDTHH:MM[:SS]Z`, as whole seconds since the epoch, or None where + there is no stamp or it cannot be a time - a month 13, a day 45 or a + February 30th, an hour 24 or more, a minute or a second 60 or more, a year + 0. A take sends this, NULL for None, and never a value filled in (design + Y:5116): a stamp that does not parse is a take with no UTC, never a guess + at the nearest time.""" + if not utc: + return None + fmt = "%Y-%m-%dT%H:%M:%SZ" if utc.count(":") == 2 else "%Y-%m-%dT%H:%MZ" + try: + stamp = _dt.datetime.strptime(utc, fmt) + except ValueError: + return None + return int(stamp.replace(tzinfo=_dt.timezone.utc).timestamp()) + + +def classify_register_line(line: str) -> tuple[str, str, str, str, str]: + """`register classify`'s five fields for one register line (contract + draft 4.10, section 3.5; lane 3's R04), each `-` where absent: + + - ``, the kind `REGISTER_KIND_RE` reads: the line's SHAPE, even + where F13's fields are missing, so a hand-typed `LANDING EXPIRED` that + `parse_register_line` reads as no kind is still `LANDING EXPIRED`; + - ``, that kind's role in `REGISTER_SLOTS`, `take` or `close`, + whatever fields the line lacks, and `-` for a kind that takes and + closes nothing; + - ``, `` and ``: `parse_register_line`'s + repository as the line writes it (no `repos.tsv`: alias resolution + stays the commit's), its UTC as `register_utc_epoch` reads it, and its + lane. Where `parse_register_line` reads no kind - a `LANDING EXPIRED` + lacking F13's holder, PR or repository - it reads none of the three. + + Every field is ASCII with no tab: the kinds are fixed, and the + repository and the lane are cut by `[A-Za-z0-9/._-]` and + `[A-Za-z0-9._-]`.""" + m = REGISTER_KIND_RE.match(line) + if not m: + return ("-", "-", "-", "-", "-") + kind = m.group(1) + fields = parse_register_line(line) or {} + epoch = register_utc_epoch(fields.get("utc")) + return (kind, REGISTER_SLOTS[kind][0] or "-", fields.get("repo") or "-", + "-" if epoch is None else str(epoch), fields.get("lane") or "-") + + +def cmd_register_classify(args: list[str]) -> int: + """`lanes-index register classify` (contract draft 4.10, section 3.5; FR-030, + serving FR-032; lane 3's R04): THE ONE CLASSIFIER, for `append-line`'s + refusals on primary. `lanes-edit.sh` (lane 4's T424) pipes register lines + in, one per LF-ended line, and reads back one line each, in order: + `` TAB `` TAB `` TAB `` TAB ``, + as `classify_register_line` gives them. A bash copy of the classifier + would be the second classifier design Y:6247-6249 warns of. + + So the caller refuses, with 2 and before the lock, a line whose `` + is `LANDING EXPIRED`; a `take` whose `` or `` is `-`; + and a `LANDING` whose `` is `-`. + + stdin is read as bytes and cut at LF alone, so a CR stays inside its line + and the output has exactly one line per input line; a last line with no + LF is a line, and empty input prints nothing. An argument is usage, 64, + before anything is read, and its usage line never shows the argument, + which may be a misplaced URL or password (contract §2.6: nothing secret + reaches stderr). The configuration is loaded only so that a + refused one is refused, 2 (Q6(c)'s refusal of `mode=primary` included, + as a `Refusal`); nothing in it is used, since the contract lets this read + no key but `register_schema=`, and with no database call it needs none. + It opens no store and runs no `psql`.""" + for arg in args: + if arg in ("-h", "--help"): + say(USAGE) + return 0 + note(f"register classify takes no argument: it reads register lines on stdin - see " + f"{PROG} --help") + return 64 + try: + load_config() + except Refusal as exc: + note(f"REFUSED: {exc}") + return 2 + stdin = getattr(sys.stdin, "buffer", None) + lines = (stdin.read() if stdin is not None else b"").split(b"\n") + if lines[-1] == b"": + lines.pop() + sys.stdout.write("".join("\t".join(classify_register_line(_decode(raw))) + "\n" + for raw in lines)) + sys.stdout.flush() + return 0 + + # ======================================================== the records built TABLE_COLUMNS = { @@ -1045,6 +1799,13 @@ def ddl(dialect: str, schema: str) -> list[str]: return stmts +#: EVERY TABLE THAT KEYS ON A SOURCE, in both stores: the provenance and each of +#: `TABLE_COLUMNS`'. A legacy source leaves all of them in one transaction. +SOURCE_TABLES = ("provenance",) + tuple(TABLE_COLUMNS) +#: Every source any of them keys on, as one SELECT that both stores answer. +SOURCES_QUERY = " UNION ".join(f"SELECT source FROM {table}" for table in SOURCE_TABLES) + + class SqliteStore: dialect = "sqlite" @@ -1090,6 +1851,79 @@ class SqliteStore: raise StoreUnusable("unreachable", f"{self.path}: {exc}") self._check_schema(writing=True) + def _scrub_mark(self) -> str: + return self.path + "-scrub" + + def _mark_scrub(self) -> None: + """The scrub mark, written and synced, 0600 (a mark left before is made 0600 + again), its text `SCRUB_MARK_TEXT`; AND ITS FOLDER SYNCED (B3 of + opensoft/openRepoTools-code#89 comment 6947619546), so the mark's entry outlives a + crash with the removal. Either failing is `SCRUB_UNMARKED`, and no removal begins.""" + try: + # NEVER THROUGH A LINK, AND A REGULAR FILE ONLY (W116's pre-review of commit 15), + # as the status file is read + fd = os.open(self._scrub_mark(), os.O_WRONLY | os.O_CREAT | os.O_TRUNC | + getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), 0o600) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise OSError("the scrub mark is not a regular file") + os.fchmod(fd, 0o600) + os.write(fd, SCRUB_MARK_TEXT.encode("utf-8")) + os.fsync(fd) + finally: + os.close(fd) + dfd = os.open(os.path.dirname(self.path) or ".", os.O_RDONLY) + try: + os.fsync(dfd) + finally: + os.close(dfd) + except OSError: + raise StoreUnusable("unreachable", SCRUB_UNMARKED) from None + + def scrub(self) -> None: + """THE SCRUB A REMOVAL LEFT DUE, where its mark stands (BLOCKING 4 of + opensoft/openRepoTools-code#89 comment 6944416906). With `secure_delete` on, a + VACUUM rewrites the file, so its free space holds nothing that went. A WAL store + is checkpointed with TRUNCATE, which copies every frame back into the file and + leaves the WAL empty; any other store is set to the DELETE journal, whose journal + goes at each commit, so no WAL or journal keeps an old page. Only then does the + mark go. A step that fails leaves the mark and is a `StoreUnusable` with fixed + words, and the next writer's cleanup (`_drop_legacy`), which ends with this + whether it removed anything or not, runs the scrub again. A failed step is + first tried again, `SCRUB_ATTEMPTS` times in all (lane 3's ruling, B2 of + comment 6947619546); only then does the run end, saying a scrub is pending.""" + import sqlite3 + mark = self._scrub_mark() + if not os.path.exists(mark): + return + for attempt in range(1, SCRUB_ATTEMPTS + 1): + try: + if self._scrub_once(mark): + return + except (sqlite3.Error, OSError): + pass + if attempt < SCRUB_ATTEMPTS: + time.sleep(SCRUB_PAUSE_S * attempt) + raise StoreUnusable("unreachable", SCRUB_UNFINISHED) + + def _scrub_once(self, mark: str) -> bool: + """One pass of `scrub`: True once the mark is gone, False where a check finds the + WAL or the journal not yet clean; a failed step raises.""" + self.conn.execute("PRAGMA secure_delete = ON") + mode = str(self.conn.execute("PRAGMA journal_mode").fetchone()[0]).lower() + if mode != "wal": + mode = str(self.conn.execute("PRAGMA journal_mode = DELETE").fetchone()[0]).lower() + self.conn.execute("VACUUM") + if mode == "wal": + busy = self.conn.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()[0] + wal = self.path + "-wal" + if busy or (os.path.exists(wal) and os.path.getsize(wal) != 0): + return False + elif mode != "delete" or os.path.exists(self.path + "-journal"): + return False + os.unlink(mark) + return True + def _check_schema(self, writing: bool): import sqlite3 try: @@ -1131,6 +1965,44 @@ class SqliteStore: except sqlite3.Error as exc: raise StoreUnusable("wiped", f"{self.path}: {exc}") + def provenance_and_sources(self, source: str) -> tuple: + """`provenance(source)`, and every source any table of the store keys on, + sorted: a sync's one read before it removes a legacy source.""" + import sqlite3 + old = self.provenance(source) + try: + return old, sorted(r[0] for r in self.conn.execute(SOURCES_QUERY)) + except sqlite3.Error as exc: + raise StoreUnusable("wiped", f"{self.path}: {exc}") + + def drop_sources(self, sources: list) -> None: + """Every row of each of `sources`, from every table that keys on a source, + in ONE transaction (lane 3's ruling, opensoft/openRepoTools-code#89 comment + 6941833120), with `secure_delete` on, so that what goes is zeroed. A SCRUB + MARK THAT HOLDS NO KEY is made durable BEFORE the transaction begins (lane 1's + choice for BLOCKING 4 of comment 6944416906), and only `scrub` takes it off, once + the file's free space, its WAL and its journal hold no copy of what went: a run + that fails after the COMMIT leaves the mark, and the next writer's cleanup + (`_drop_legacy`) finishes the scrub before that run writes anything of its own.""" + import sqlite3 + if not sources: + return + self._mark_scrub() + marks = ", ".join("?" for _ in sources) + try: + self.conn.execute("PRAGMA secure_delete = ON") + self.conn.execute("BEGIN IMMEDIATE") + for table in SOURCE_TABLES: + self.conn.execute(f"DELETE FROM {table} WHERE source IN ({marks})", + list(sources)) + self.conn.execute("COMMIT") + except sqlite3.Error as exc: + try: + self.conn.execute("ROLLBACK") + except sqlite3.Error: + pass + raise StoreUnusable("unreachable", f"{self.path}: {exc}") + def rows(self, table: str, source: str, columns: list[str]) -> list: # A TABLE THAT CANNOT BE READ IS A STORE THAT CANNOT ANSWER, said as the # provenance's reads say it (opensoft/openRepoTools#173, Copilot's @@ -1186,7 +2058,13 @@ class SqliteStore: want = old["commit_sha"] if old else None if (cur[0] if cur else None) != want or (cur is None) != (old is None): self.conn.execute("ROLLBACK") - raise CasLost(f"the provenance of {source} moved under this sync " + # NO URL IN ANY FORM ON STDERR (exit-codes.md:57; lane 3's ruling, + # opensoft/openRepoTools-code#89 comment 6940341452): a key that is not + # a plain `register:` or `inventory:` name is not named. + shown = (source if re.fullmatch(r"(register|inventory):[A-Za-z0-9_.-]+" + r"(/[A-Za-z0-9_.-]+)?", source) + else "this workstation's register") + raise CasLost(f"the provenance of {shown} moved under this sync " f"(it read {str(want)[:12]}, the store now holds " f"{str(cur[0] if cur else None)[:12]}); nothing was written") if cur is None: @@ -1232,6 +2110,27 @@ def _pg_quote(value) -> str: return "'" + str(value).replace("'", "''") + "'" +def _pg_digest(source: str) -> str: + """The hex SHA-256 of `source`'s UTF-8 bytes, as the server computes it.""" + return hashlib.sha256(source.encode("utf-8")).hexdigest() + + +def _pg_source_is(source: str, column: str = "source") -> str: + """NO SOURCE KEY IN ANY SQL TEXT (lane 3's ruling, opensoft/openRepoTools-code#89 + comment 6944673181): the server chooses a source's rows by the SHA-256 of the key, + which it computes from the row itself, so the key is in no statement, no psql + echo of one and no server log of one.""" + return f"encode(sha256(convert_to({column}, 'UTF8')), 'hex') = '{_pg_digest(source)}'" + + +def _copy_text(value) -> str: + """One field of `COPY ... FROM STDIN` in TEXT format: the inverse of `_pg_unescape`.""" + if value is None: + return "\\N" + return (str(value).replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n") + .replace("\r", "\\r")) + + def _pg_unescape(field: str): """One field of `COPY ... TO STDOUT` in TEXT format: `\\N` is NULL and a backslash escapes the rest, exactly as the server wrote it.""" @@ -1269,17 +2168,180 @@ def _pg_unescape(field: str): return "".join(out) +#: THE SQL REGISTER'S TWO ROLES (FR-012; L1-A5; design Y:3455-3461, "Roles and +#: credentials"), which `PostgresStore(cfg, role)` takes beside #160's `writer` +#: and `reader`. REGISTER-WRITER connects with `register_url=` and +#: `register_passfile=`; READER with `reader_url=` and `reader_passfile=`, never +#: with a writer's file. Each reads `register_schema=`, and every call either +#: makes is a register path. +REGISTER_ROLES = ("register_writer", "register_reader") + +#: THE ARGV OF EVERY REGISTER CALL, exactly (contract §2.2): #160's +#: `--no-psqlrc -X -q -v ON_ERROR_STOP=1`; `-A -t`, so a SELECT's value prints +#: bare while COPY's rows are unchanged; and `VERBOSITY=verbose` with +#: `SHOW_CONTEXT=never`, so `psql`'s first line on stderr is +#: `ERROR: : ` (Y:2590). No connection string and no `-d` +#: (Y:3491): the connection is the environment's alone. +REGISTER_PSQL_ARGS = ("--no-psqlrc", "-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", + "-v", "VERBOSITY=verbose", "-v", "SHOW_CONTEXT=never") + +#: D9'S ROWS (design Y:3501-3537; contract §2.4), one per kind of register call: +#: `lock_timeout` and `statement_timeout` in ms, which ride the startup +#: packet's `options=` as `PGOPTIONS`, `-c lock_timeout= -c +#: statement_timeout=` (Y:1573, Y:3503); the least client timer the row +#: gives, in s; and the role that runs it, or None where both do. A row's +#: client timer is `N_a`·`c` + its statement bound + 1 s, never below that +#: least figure (Y:3509-3511). The guard's has none: its caller cuts it at the +#: parse's start line, `T0 + 3.75 s` (Y:3518). The bounds need a direct +#: connection to the primary, never through a pooler, which drops `options` +#: (C13, Y:1575). `import --single` and `render --revert` take the commit's +#: row for their commit call and the writer's rows for the rest (Y:3536-3537). +#: The mode query runs no `psql` (Y:3521); the service's child (Y:3519) and a +#: migration (Y:3531) are not a role's calls. +REGISTER_BOUNDS = { + # row: (lock_timeout ms, statement_timeout ms, least timer s, role) + "snapshot": (2000, 5000, 8, "register_writer"), # `register snapshot`, `act-begin`'s: S (Y:3522) + "commit": (2000, 5000, 8, "register_writer"), # `register commit`: C (Y:3523) + "lookup": (2000, 6000, 9, "register_writer"), # `journal --write-id`, each try: T_L (Y:3524) + "read": (1000, 3000, 6, "register_reader"), # `register read` forms 1, 3; `journal --last`: T_r (Y:3526) + "guard": (1000, 1500, None, "register_reader"), # `register read --for guard`, forms 2, 4 (Y:3518) + "render": (1000, 10000, 15, None), # `journal --since`, `render`; `reconcile` (Y:3527) + "status": (1000, 5000, 8, "register_reader"), # `status` (Y:3528) + "rollback": (5000, 10000, 15, "register_writer"), # `rollback`, each call (Y:3529) + "import": (2000, 300000, 330, "register_writer"), # `import` (Y:3530) + "cutover": (5000, 10000, 15, "register_writer"), # `cutover`, `switch_to_files`, `record_marker` (Y:3532-3534) + "outage": (2000, 5000, 8, "register_writer"), # `outage declare`'s database probe (Y:3535) +} + +#: #160's `\echo` marker, as ONE request carries it (contract §2.3; Y:1417): a +#: `COPY` whose one row is the marker line `\echo` printed, byte for byte, so +#: `_query_many`'s parse reads both alike. COPY's text format escapes only +#: backslash, newline, carriage return, tab and the other C escapes, never +#: `\x1e`. +REGISTER_MARKER_COPY = r"COPY (SELECT E'\x1eLANES-INDEX-NEXT') TO STDOUT" + +#: `psql` 15 OR LATER (FR-012; block :152; Y:5876, Y:5914): a register call +#: sends its statements as one request joined by `\;`, and a `psql` before 15 +#: prints only that request's last result. `ready` asks for 16 (Y-ops:445). +PSQL_MIN_MAJOR = 15 + +#: Each `psql`'s version, read ONCE PER PROCESS by `psql --version`, keyed by +#: the path run: (its major number, or None where none could be read; the +#: version as it named it). +_PSQL_VERSIONS: dict = {} + + +def _psql_version_of(text: str) -> tuple: + """`psql --version`'s answer as (major or None, the version as named): + `psql (PostgreSQL) 16.15 (Ubuntu ...)` is (16, "16.15"). Anything else + is (None, its first line, printable and at most 60 characters).""" + first = (text.strip().splitlines() or [""])[0] + match = re.search(r"\(PostgreSQL\) ([0-9]+)([0-9A-Za-z.]*)", first) + if match: + return int(match.group(1)), match.group(1) + match.group(2) + return None, re.sub(r"[^\x20-\x7e]", "?", first)[:60] + + +class PsqlFailed(StoreUnusable): + """A register call's `psql` that did not answer (FR-012): a + `StoreUnusable` of kind `unreachable`, as #160 reads one, with what a + register command maps to its own code KEPT APART for it (contract §2.2's + exits, §2.6, §2.7). It maps nothing itself. + + `psql_exit` is `psql`'s exit - 0 only for an answer that is not UTF-8, + negative where a signal ended it - or None where it never ended on its + own. `stderr` is its whole stderr, and `first_line` that stderr's first + line, where §2.6 reads the code. `timer_expired` is True where the call's + client timer (D9) cut it. `ran` is False where no `psql` was handed the + request: none could be started, the timer was spent before it, or the + version check refused it - so the call cannot be in doubt.""" + + def __init__(self, kind: str, detail: str, *, psql_exit: int | None = None, + stderr: str = "", first_line: str = "", timer_expired: bool = False, + ran: bool = True): + super().__init__(kind, detail) + self.psql_exit = psql_exit + self.stderr = stderr + self.first_line = first_line + self.timer_expired = timer_expired + self.ran = ran + + +class PsqlTooOld(PsqlFailed): + """`psql` older than 15, or one whose `--version` names no version this + build can read (FR-012; block :152): 69, naming the version, raised + before anything is sent, so `ran` is False (contract §2.7's 69 row: "a + `psql` that cannot be started or is too old"). `version` is the version + as `psql --version` named it.""" + + def __init__(self, version: str, readable: bool): + if readable: + why = (f"psql {version} is older than {PSQL_MIN_MAJOR}: a register call sends " + f"its statements as ONE request joined by `\\;`, and a psql before " + f"{PSQL_MIN_MAJOR} prints only its last result (FR-012)") + else: + why = (f"psql --version names no version this build can read " + f"({version or 'nothing'!r}), and a register call needs psql " + f"{PSQL_MIN_MAJOR} or later (FR-012)") + super().__init__("psql-too-old", f"{why}; nothing was sent", ran=False) + self.version = version + + class PostgresStore: """QA Postgres, reached ONLY through `psql` and ONLY where `url=` is configured. Nothing here imports a driver: `psql` is libpq's own client, and the password it needs is in the 0600 file `PGPASSFILE` names - never - in this process's arguments and never in an environment it hands on.""" + in this process's arguments and never in an environment it hands on. The + connection itself reaches `psql` as `PG*` variables (Question 11), never + as `-d `. + + THE SQL REGISTER'S ROLES (FR-012): `register_writer` and `register_reader` + connect with `register_url=` and `reader_url=`, read `register_schema=`, + and make register calls only: one request each (`request`, and + `_query_many` with a D9 `row`), with D9's bounds, the URL as the whole + connection and `psql` 15 or later. #160's index methods refuse on them, + since a register path names its own client timer.""" dialect = "postgres" + #: #160'S INDEX PATHS KEEP THEIR BOUNDS (Y:4970, "the index paths keep 5 s + #: and 300 s"): `PGCONNECT_TIMEOUT` defaults to 5, and an inherited value + #: or the URL's `connect_timeout=` wins; the client timer is 300 s. + INDEX_CONNECT_TIMEOUT = "5" + INDEX_TIMER_S = 300 def __init__(self, cfg: dict, role: str): - self.schema = cfg["schema"] - if role == "reader": + #: A REGISTER ROLE (FR-012): every call it makes is a register path, + #: and its `search_path` is `register_schema=`. + self.role = role + self.register = role in REGISTER_ROLES + self.schema = ((cfg.get("register_schema") or "lanes_register") if self.register + else cfg["schema"]) + if role == "register_writer": + # THE REGISTER'S WRITES: this engineer's REGISTER-WRITER login, never + # the indexer's `url=` (Y:3459; contract §2.5). + if not cfg.get("register_url"): + raise Refusal( + "the configuration names no `register_url=`: the register's writes " + "connect only as this engineer's REGISTER-WRITER login (FR-012), never " + "as the indexer's `url=`") + self.url, self.passfile = cfg["register_url"], cfg.get("register_passfile") or "" + key = "register_url" + elif role == "register_reader": + # THE REGISTER'S READS: this engineer's READER login, with its own + # file and never a writer's - not `register_passfile=`, and not #160's + # `passfile=` either (Y:3460; contract §2.5). Only beside a + # `register_url=`: without one, `reader_url=` is #160's, and + # `load_config` never held it to R09's TLS check. + if not cfg.get("register_url") or not cfg.get("reader_url"): + raise Refusal( + "the register's reads connect only as this engineer's READER login, " + "`reader_url=`, beside the `register_url=` it pairs with (FR-012), and " + "never with the writer's credential: the configuration names " + + ("no `register_url=`" if not cfg.get("register_url") else + "no `reader_url=`")) + self.url, self.passfile = cfg["reader_url"], cfg.get("reader_passfile") or "" + key = "reader_url" + elif role == "reader": # NEVER THE WRITER'S CREDENTIAL FOR A READ (Copilot round 1 on #164). # The writer is the indexer's and no session's (14(c)), and `export` # is run by a session typing `--index`: with no `reader_url=` the @@ -1290,49 +2352,259 @@ class PostgresStore: "reads (`status`, `--index`) connect only as the SELECT-only reader, " "never with the writer's credential (Amendment 14(c))") self.url, self.passfile = cfg["reader_url"], cfg.get("reader_passfile") or cfg["passfile"] - else: + key = "reader_url" + elif role == "writer": self.url, self.passfile = cfg["url"], cfg["passfile"] + key = "url" + else: + raise ValueError(f"PostgresStore has no role {role!r}: it takes " + f"{', '.join(('writer', 'reader') + REGISTER_ROLES)}") + #: The configuration key whose URL this store connects with. + self.key = key + # THE CONNECTION, MAPPED ONCE (Question 11; SVC-2): the variables every + # `psql` this store runs connects with, refused here, before any `psql`, + # where the URL cannot be mapped. + self.pg_env = pg_url_env(self.url, f"`{key}=` in {cfg.get('path') or 'the configuration'}") + #: `c` (D9): the URL's `connect_timeout=`, else 2. A register path's + #: `PGCONNECT_TIMEOUT`, and the connect bound in its client timer. + self.connect_timeout = int(self.pg_env.get("PGCONNECT_TIMEOUT", CONNECT_TIMEOUT_DEFAULT)) + #: `N_a` (D9): `register_addresses=`, the addresses the register's + #: endpoint resolves to, default 1; libpq tries `c` on each in turn. + self.addresses = int(cfg.get("register_addresses") or 1) if self.register else 1 self.label = "postgres" self.where = re.sub(r"^[A-Za-z][A-Za-z0-9+.-]*://", "", self.url).split("?", 1)[0] self.psql = shutil.which("psql") or "" - def _env(self) -> dict: + def _env(self, *, register: bool = False, options: str | None = None) -> dict: # THE CONFIGURED PASSWORD FILE OR NONE AT ALL (14(c); Copilot on #164): # an inherited `PGPASSWORD` or `PGPASSFILE` is dropped, and with no # `passfile=` libpq is handed an EMPTY 0600 file of this command's own - # never left to find `~/.pgpass` or a file some other environment named. - env = {k: v for k, v in os.environ.items() if k not in ("PGPASSWORD", "PGPASSFILE")} + # So are `PGSERVICEFILE`, `PGSYSCONFDIR` and `PGSERVICE` + # (`PG_ENV_DROPPED`), and the URL's own parts are set over whatever was + # inherited, as `-d ` set them over it. + if register or self.register: + # THE URL IS THE WHOLE CONNECTION ON A REGISTER PATH (lane 3's ruling, + # #165 6747611042; contract §2.2): EVERY inherited variable whose name + # begins `PG` is dropped first - `PGHOSTADDR`, `PGSSLMODE`, `PGOPTIONS`, + # `PGTARGETSESSIONATTRS` and the rest - so `psql` gets only the URL's + # mapping, the configured password file, `PGCONNECT_TIMEOUT` at `c` + # (set, not defaulted, so an inherited value can never lengthen the + # connect bound its client timer counts: Y:4970), the call's own + # bounds as `PGOPTIONS`, and `PGAPPNAME`. + env = {k: v for k, v in os.environ.items() if not k.startswith("PG")} + env.update(self.pg_env) + env["PGPASSFILE"] = self.passfile or _no_password_file() + env["PGCONNECT_TIMEOUT"] = str(self.connect_timeout) + if options: + env["PGOPTIONS"] = options + env["PGAPPNAME"] = PROG + return env + env = {k: v for k, v in os.environ.items() if k not in PG_ENV_DROPPED} + env.update(self.pg_env) env["PGPASSFILE"] = self.passfile or _no_password_file() - env.setdefault("PGCONNECT_TIMEOUT", "5") + env.setdefault("PGCONNECT_TIMEOUT", self.INDEX_CONNECT_TIMEOUT) env["PGAPPNAME"] = PROG return env - def _run(self, script: str) -> str: + def _run(self, script: str, *, timer: float | None = None, + register: bool = False, options: str | None = None, cas: bool = False) -> str: + """`script` on `psql`'s stdin, its connection in the environment alone. + + `timer` is the call's client timer (D9), `subprocess.run`'s `timeout` on + the whole `psql`, the connect inside it. #160's index paths keep + `INDEX_TIMER_S`. A `register` path - every call of a register role - + names its own timer and its D9 bounds as `options`, and runs as + `_run_register` runs it.""" + register = register or self.register + if timer is None: + if register: + raise ValueError("a register path's psql call names its own client timer (D9)") + timer = self.INDEX_TIMER_S + if register and not options: + raise ValueError("a register path's psql call carries its D9 bounds as PGOPTIONS") if not self.psql: + if register: + raise PsqlFailed("unreachable", f"`{self.key}=` is configured and there is no " + f"`psql` on PATH", ran=False) raise StoreUnusable("unreachable", "`url=` is configured and there is no `psql` on PATH") + if register: + return self._run_register(script, timer, options) try: + # `VERBOSITY=sqlstate` AND `SHOW_CONTEXT=never` (`INDEX_PSQL_ARGS`, lane 3's + # ruling on comment 6955397261): each message is its severity and SQLSTATE + # alone. The script is the file `-`, so each message carries psql's locus. proc = subprocess.run( - [self.psql, "--no-psqlrc", "-X", "-q", "-v", "ON_ERROR_STOP=1", "-d", self.url], - input=script, capture_output=True, text=True, check=False, env=self._env(), - timeout=300) + [self.psql, *INDEX_PSQL_ARGS], + input=script, capture_output=True, text=True, check=False, + env=self._env(register=register), timeout=timer) except subprocess.TimeoutExpired: - raise StoreUnusable("unreachable", "psql did not answer within 300 s") + raise StoreUnusable("unreachable", f"psql did not answer within {timer:g} s") except OSError as exc: raise StoreUnusable("unreachable", f"psql could not be run: {exc}") if proc.returncode != 0: - err = (proc.stderr.strip().splitlines() or [f"psql exited {proc.returncode}"]) - if "lanes-index: provenance moved" in proc.stderr: - raise CasLost(err[-1]) - if proc.returncode == 2: - raise StoreUnusable("unreachable", err[0]) - raise StoreUnusable("unreachable", err[-1]) + raise self._failure(proc.returncode, proc.stderr, cas) return proc.stdout - def _query_many(self, queries: list[str], snapshot: bool = False) -> list[list[list]]: + @staticmethod + def _failure(code: int, stderr: str, cas: bool) -> Exception: + """A FAILED INDEX CALL IN FIXED WORDS, NEVER A LINE OF psql'S TEXT (lane 3's + ruling, BLOCKING 5 of opensoft/openRepoTools-code#89 comment 6944416906): psql + can quote the script in a `LINE`, `QUERY` or `CONTEXT` line or a COPY row, so + nothing of what it says is said or filed. Its stderr is read for the SQLSTATE + alone: under `VERBOSITY=sqlstate` it holds no text, and the LAST line with psql's + locus decides (`PSQL_SQLSTATE_RE`; lane 3's ruling on comment 6955397261), so no + message text and no severity word decides: + - exit 2: psql could not connect, or lost the connection; + - 42P01 or 3F000: a table or schema the index needs does not exist, which + `open_read` calls `wiped` (commit 13's caret mend, now by the code); + - P0001 or 23505 in a write (`cas`): the compare-and-swap's RAISE, or a row a + writer filed first: the provenance moved; + - any other SQLSTATE, by its five characters; none, by psql's exit.""" + if code == 2: + return StoreUnusable("unreachable", PSQL_NO_CONNECTION) + located = PSQL_LOCATED_RE.findall(stderr) + last = PSQL_SQLSTATE_RE.match(located[-1]) if located else None + sqlstate = last.group(1) if last else "" + if cas and sqlstate in ("P0001", "23505"): + return CasLost(PSQL_CAS_LOST) + if sqlstate in PSQL_UNDEFINED: + exc = StoreUnusable("unreachable", f"psql: a table or schema the index needs " + f"does not exist (SQLSTATE {sqlstate})") + elif sqlstate: + exc = StoreUnusable("unreachable", f"psql stopped the index's script with " + f"SQLSTATE {sqlstate} (exit {code}); psql's own words are " + f"not shown, since they can quote the script") + else: + exc = StoreUnusable("unreachable", f"psql exited {code} with no SQLSTATE; " + f"psql's own words are not shown, since they can quote the " + f"script") + exc.sqlstate = sqlstate + return exc + + def _run_register(self, script: str, timer: float, options: str) -> str: + """`_run` on a register path (FR-012): `REGISTER_PSQL_ARGS`, the + register environment with `options` as `PGOPTIONS`, and `psql` 15 or + later, checked once per process inside this call's timer, so the + whole call stays inside its D9 client timer. + + A `psql` that does not answer raises `PsqlFailed`, every kind as + `unreachable`, with its exit, its stderr's first line and the timer's + expiry kept apart; the code each means is the register command's to + give (contract §2.2, §2.6, §2.7).""" + deadline = time.monotonic() + timer + env = self._env(register=True, options=options) + self._check_psql_version(env, deadline) + left = deadline - time.monotonic() + expired = f"psql did not answer within {timer:g} s" + if left <= 0: + raise PsqlFailed("unreachable", expired, timer_expired=True, ran=False) + try: + proc = subprocess.run([self.psql, *REGISTER_PSQL_ARGS], input=script.encode("utf-8"), + capture_output=True, check=False, env=env, timeout=left) + except subprocess.TimeoutExpired as exc: + stderr = (exc.stderr or b"").decode("utf-8", "replace") + raise PsqlFailed("unreachable", expired, stderr=stderr, + first_line=(stderr.strip().splitlines() or [""])[0], + timer_expired=True) + except OSError as exc: + raise PsqlFailed("unreachable", f"psql could not be run: {exc}", ran=False) + stderr = proc.stderr.decode("utf-8", "replace") + first = (stderr.strip().splitlines() or [""])[0] + if proc.returncode != 0: + raise PsqlFailed("unreachable", first or f"psql exited {proc.returncode}", + psql_exit=proc.returncode, stderr=stderr, first_line=first) + try: + return proc.stdout.decode("utf-8") + except UnicodeDecodeError: + raise PsqlFailed("unreachable", "psql exited 0 with an answer that is not UTF-8", + psql_exit=0, stderr=stderr, first_line=first) + + def _check_psql_version(self, env: dict, deadline: float) -> None: + """`psql` 15 OR LATER, checked ONCE PER PROCESS (FR-012; block :152; + Y:5914) by `psql --version`, in the register environment and inside + the call's timer. An older one, or one that names no version this + build can read, is `PsqlTooOld`: 69, naming the version, with nothing + sent. A `--version` that cannot be run or does not answer is a + `PsqlFailed` with nothing sent, and is asked again by the next call.""" + known = _PSQL_VERSIONS.get(self.psql) + if known is None: + left = deadline - time.monotonic() + if left <= 0: + raise PsqlFailed("unreachable", "psql --version did not answer within its " + "call's client timer", timer_expired=True, ran=False) + try: + proc = subprocess.run([self.psql, "--version"], stdin=subprocess.DEVNULL, + capture_output=True, check=False, env=env, timeout=left) + except subprocess.TimeoutExpired: + raise PsqlFailed("unreachable", "psql --version did not answer within its " + "call's client timer", timer_expired=True, ran=False) + except OSError as exc: + raise PsqlFailed("unreachable", f"psql could not be run: {exc}", ran=False) + known = _psql_version_of(proc.stdout.decode("utf-8", "replace") + if proc.returncode == 0 else "") + _PSQL_VERSIONS[self.psql] = known + major, version = known + if major is None or major < PSQL_MIN_MAJOR: + raise PsqlTooOld(version, major is not None) + + def bounds(self, row: str, timer: float | None = None) -> tuple[str, float]: + """D9's `row` for one call of this register role: its `PGOPTIONS`, + `-c lock_timeout= -c statement_timeout=`, and its client timer + in s, `N_a`·`c` + the statement bound + 1 s and never below the row's + figure (`REGISTER_BOUNDS`). Only the guard's caller passes `timer`, its + cut at `T0 + 3.75 s`; every other row sets its own. A row of the other + role is refused: a read never connects with the writer's credential.""" + if not self.register: + raise ValueError("only the register's roles carry D9's bounds; #160's index " + "paths keep theirs") + if row not in REGISTER_BOUNDS: + raise ValueError(f"D9 has no register row {row!r}") + lock_ms, statement_ms, least_s, role = REGISTER_BOUNDS[row] + if role and role != self.role: + raise ValueError(f"D9's {row} row is run as {role}, and this store is {self.role}") + options = f"-c lock_timeout={lock_ms} -c statement_timeout={statement_ms}" + if least_s is None: + if timer is None: + raise ValueError(f"D9's {row} row is cut by its caller, at T0 + 3.75 s (Y:3518)") + return options, timer + if timer is not None: + raise ValueError(f"D9's {row} row sets its own client timer; only the guard's " + f"caller cuts one") + return options, max(least_s, self.addresses * self.connect_timeout + statement_ms / 1000 + 1) + + def request(self, statements: list[str], row: str, *, timer: float | None = None) -> str: + """ONE REQUEST PER CALL (FR-012; contract §2.3; Y:5876): `statements` + joined by `psql`'s `\\;` into one simple-protocol Query on stdin, + `A \\; B \\; C;`, so the call costs the connect and one round trip, + with D9's bounds for `row` and its client timer (`bounds`). Since + PostgreSQL 13 `statement_timeout` bounds each statement of it. + + Each statement is one SQL statement with no `;` of its own outside a + literal, no `--` comment and no `psql` meta-command; a trailing `;` is + dropped. Returns `psql`'s stdout; a failure is `PsqlFailed`.""" + if not self.register: + raise ValueError("only the register's roles send a register request") + parts = [statement.strip().rstrip(";").rstrip() for statement in statements] + if not parts or not all(parts): + raise ValueError("a register request is one or more statements, none of them empty") + options, timer = self.bounds(row, timer) + return self._run(" \\; ".join(parts) + ";\n", timer=timer, register=True, + options=options) + + def _query_many(self, queries: list[str], snapshot: bool = False, *, + row: str | None = None, timer: float | None = None) -> list[list[list]]: """Several SELECTs in ONE connection, each answered as TEXT-format COPY rows; a marker line no COPY row can be (one field, a control character) separates them. With `snapshot`, in ONE read-only - REPEATABLE READ transaction: every SELECT reads the same snapshot.""" + REPEATABLE READ transaction: every SELECT reads the same snapshot. + + With `row`, a register role's read (FR-012; contract §2.3; Y:1417): + the same statements as ONE request (`request`), joined by `\\;`, with + the marker sent as `REGISTER_MARKER_COPY`, whose row is the line + `\\echo` prints, so the output is byte-identical and the parse below is + #160's, unchanged. `row` names D9's bounds; `timer` is the guard's + cut.""" marker = "\x1eLANES-INDEX-NEXT" parts = [f"SET search_path TO \"{self.schema}\";"] if snapshot: @@ -1342,7 +2614,11 @@ class PostgresStore: parts.append("\\echo '\\036LANES-INDEX-NEXT'") if snapshot: parts.append("COMMIT;") - out = self._run("\n".join(parts) + "\n") + if row is None: + out = self._run("\n".join(parts) + "\n") + else: + out = self.request([REGISTER_MARKER_COPY if part.startswith("\\echo") else part + for part in parts], row, timer=timer) results, current = [], [] for line in out.split("\n"): if line == marker: @@ -1359,7 +2635,7 @@ class PostgresStore: res = self._query_many([ f"SELECT version FROM \"{self.schema}\".schema_version"]) except StoreUnusable as exc: - if "does not exist" in exc.detail: + if getattr(exc, "sqlstate", "") in PSQL_UNDEFINED: raise StoreUnusable("wiped", exc.detail) raise versions = {int(r[0]) for r in res[0]} if res else set() @@ -1397,6 +2673,33 @@ class PostgresStore: return [{"source": r[0], "commit_sha": r[1], "generation": r[2], "indexed_utc": r[3], "schema_version": r[4]} for r in (res[0] if res else [])] + def provenance_and_sources(self, source: str) -> tuple: + """`SqliteStore.provenance_and_sources` in ONE psql call: a sync reads the + provenance in any case, so a sync with no legacy source to remove sends no + psql call that commit 12's sync did not.""" + res = self._query_many([self._provenance_query(source), SOURCES_QUERY]) + if len(res) != 2: + raise StoreUnusable("unreachable", f"psql answered {len(res)} of the 2 reads of " + f"the provenance and the sources") + return self._provenance_of(res[0]), sorted(r[0] for r in res[1]) + + def drop_sources(self, sources: list) -> None: + """`SqliteStore.drop_sources`: every legacy source's rows, from every table that + keys on a source, in ONE transaction. The server chooses them by `PG_LEGACY_SQL`, + the rule `_is_legacy` states, so neither a legacy key nor any value made from one is + in the script; `sources`, `_is_legacy`'s answer, says whether one is to go.""" + if not sources: + return + lines = ["SET standard_conforming_strings = on;", "BEGIN;", + f"SET LOCAL search_path TO \"{self.schema}\";"] + lines += [f"DELETE FROM {table} WHERE {PG_LEGACY_SQL};" for table in SOURCE_TABLES] + lines.append("COMMIT;") + self._run("\n".join(lines) + "\n") + + def scrub(self) -> None: + """Nothing is due: PostgreSQL's own VACUUM reclaims what a DELETE leaves, and no + file of this workstation holds the store.""" + def rows(self, table: str, source: str, columns: list[str]) -> list: res = self._query_many([self._rows_query(table, source, columns)]) return self._rows_of(res[0] if res else [], columns) @@ -1404,7 +2707,7 @@ class PostgresStore: @staticmethod def _provenance_query(source: str) -> str: return (f"SELECT commit_sha, generation, indexed_utc, schema_version FROM provenance " - f"WHERE source = {_pg_quote(source)}") + f"WHERE {_pg_source_is(source)}") @staticmethod def _provenance_of(answer: list) -> dict | None: @@ -1417,7 +2720,7 @@ class PostgresStore: @staticmethod def _rows_query(table: str, source: str, columns: list[str]) -> str: return (f"SELECT {', '.join(['record_id'] + columns)} FROM {table} " - f"WHERE source = {_pg_quote(source)}") + f"WHERE {_pg_source_is(source)}") @staticmethod def _rows_of(answer: list, columns: list[str]) -> list: @@ -1447,27 +2750,38 @@ class PostgresStore: deletes: dict, generation: int | None = None) -> None: now = utc_now() want = old["commit_sha"] if old else None + # NO SOURCE KEY IN ANY SQL TEXT (lane 3's ruling, opensoft/openRepoTools-code#89 + # comment 6944673181): a new source's provenance row goes in as COPY data, and + # every statement after it finds the row by the key's SHA-256 (`_pg_source_is`) + # and takes the key from it (`mine`). + mine = f"(SELECT p.source FROM provenance p WHERE {_pg_source_is(source, 'p.source')})" lines = ["SET standard_conforming_strings = on;", "BEGIN;", - f"SET LOCAL search_path TO \"{self.schema}\";", - # THE COMPARE-AND-SWAP, FIRST AND IN THE SAME TRANSACTION AS THE - # ROWS: the UPDATE takes the provenance row's lock, so a second - # writer reading the same old commit blocks here and then finds - # it moved, and its whole transaction goes (Amendment 14(d)). - "DO $lanes_index_cas$ DECLARE n integer; BEGIN", - f" INSERT INTO provenance (source, commit_sha, generation, indexed_utc, " - f"schema_version) VALUES ({_pg_quote(source)}, NULL, NULL, {_pg_quote(now)}, " - f"{SCHEMA_VERSION}) ON CONFLICT (source) DO NOTHING;", - f" UPDATE provenance SET commit_sha = {_pg_quote(new_sha)}, generation = " - f"{_pg_quote(generation)}, indexed_utc = " - f"{_pg_quote(now)}, schema_version = {SCHEMA_VERSION} WHERE source = " - f"{_pg_quote(source)} AND commit_sha IS NOT DISTINCT FROM {_pg_quote(want)};", - " GET DIAGNOSTICS n = ROW_COUNT;", - " IF n <> 1 THEN RAISE EXCEPTION 'lanes-index: provenance moved under this " - "sync; nothing was written'; END IF;", - "END $lanes_index_cas$;"] + f"SET LOCAL search_path TO \"{self.schema}\";"] + if old is None: + # A writer that filed this source's row since it was read makes the COPY a + # unique violation (23505), which is the compare-and-swap's answer: it moved. + lines += ["COPY provenance (source, commit_sha, generation, indexed_utc, " + "schema_version) FROM STDIN;", + "\t".join([_copy_text(source), _copy_text(None), _copy_text(None), + _copy_text(now), str(SCHEMA_VERSION)]), + "\\."] + lines += [ + # THE COMPARE-AND-SWAP, FIRST AND IN THE SAME TRANSACTION AS THE + # ROWS: the UPDATE takes the provenance row's lock, so a second + # writer reading the same old commit blocks here and then finds + # it moved, and its whole transaction goes (Amendment 14(d)). + "DO $lanes_index_cas$ DECLARE n integer; BEGIN", + f" UPDATE provenance SET commit_sha = {_pg_quote(new_sha)}, generation = " + f"{_pg_quote(generation)}, indexed_utc = " + f"{_pg_quote(now)}, schema_version = {SCHEMA_VERSION} WHERE " + f"{_pg_source_is(source)} AND commit_sha IS NOT DISTINCT FROM {_pg_quote(want)};", + " GET DIAGNOSTICS n = ROW_COUNT;", + " IF n <> 1 THEN RAISE EXCEPTION 'lanes-index: provenance moved under this " + "sync; nothing was written'; END IF;", + "END $lanes_index_cas$;"] for table, ids in deletes.items(): for rec_id in ids: - lines.append(f"DELETE FROM {table} WHERE source = {_pg_quote(source)} AND " + lines.append(f"DELETE FROM {table} WHERE source = {mine} AND " f"record_id = {_pg_quote(rec_id)};") for table, recs in upserts.items(): cols = TABLE_COLUMNS[table] @@ -1475,13 +2789,13 @@ class PostgresStore: "schema_version"] sets = ", ".join(f"{c} = EXCLUDED.{c}" for c in allc[2:]) for rec_id, rec in recs.items(): - values = [source, rec_id] + [rec.get(c) for c in cols] + \ + values = [rec_id] + [rec.get(c) for c in cols] + \ [rec["digest"], rec.get("_provenance", new_sha), now, SCHEMA_VERSION] lines.append(f"INSERT INTO {table} ({', '.join(allc)}) VALUES " - f"({', '.join(_pg_quote(v) for v in values)}) ON CONFLICT " + f"({mine}, {', '.join(_pg_quote(v) for v in values)}) ON CONFLICT " f"(source, record_id) DO UPDATE SET {sets};") lines.append("COMMIT;") - self._run("\n".join(lines) + "\n") + self._run("\n".join(lines) + "\n", cas=True) def _no_password_file() -> str: @@ -1503,6 +2817,2957 @@ def open_store(cfg: dict, role: str): return SqliteStore(cfg) if cfg["store"] == "sqlite" else PostgresStore(cfg, role) +# ===== the SQL register: schema, roles, bootstrap and logins (007) +# +# THE SQL REGISTER'S SCHEMA, WHICH THE BOOTSTRAP ALONE APPLIES (feature 007, +# opensoft/openRepoTools#165; design.md §1.2, §1.3.1 and §1.5). Nothing here is +# a subcommand. `lanes-index bootstrap` calls `apply_register_migrations` +# through Brett's admin connection, after §1.4's CREATE ROLEs and the admin's +# GRANT and before §1.4's other statements. No client role owns anything in +# `lanes_register`, so no writer can apply a migration (§1.5: "Only the +# bootstrap applies them"). +# +# FORWARD ONLY (§1.5). Migrations are numbered scripts, each one transaction, +# applied in order from the schema's `version` up to `REGISTER_SCHEMA_VERSION`. +# There is no down-migration: a bad one is followed by a forward fix. Each +# `migrations` row records `script_sha256`, the digest of its script as shipped. +# +# Migration 1 creates the schema. Its `CREATE SCHEMA` fails on a schema that +# already exists, so it never runs twice. Every later script follows §1.5's +# step 3, in one transaction: +# - `SET LOCAL lock_timeout = '2000ms'`; +# - `UPDATE register_head SET seq = seq WHERE id = 1`, so every older +# writer snapshot gets 40001; +# - a check that `version` is one below its own, else LR003; +# - its DDL and GRANTs, then the new `version` and floors; +# - its `migrations` row. +# A 55P03 is retried, never queued. + +#: THE REGISTER'S SCHEMA THIS BUILD KNOWS (§1.5), apart from #160's +#: `SCHEMA_VERSION` above. Every copy in a release is one number (lane 2's +#: hygiene test, L2-N6), so it is assigned here and nowhere else. +REGISTER_SCHEMA_VERSION = 1 + +#: The floors the newest migration sets (§1.5, "The floors"): the oldest client +#: version that may write, and the oldest that may read. By default a migration +#: sets both to its own number, R3a's exact match. One that leaves older +#: clients correct may keep them, and says so in its header. +REGISTER_WRITERS_FROM = 1 +REGISTER_READERS_FROM = 1 + +#: Migration 1, part one: design.md §1.2's SQL block with lane 1's changes +#: (T107, opensoft/openRepoTools#165), which design.md has yet to fold: +#: erratum (c)'s backstop, `row_line_id`'s UNIQUE made DEFERRABLE INITIALLY +#: IMMEDIATE (ERR-48), and idx1's index `object_holds_by_line`, for step 6 +#: (lane 3's NIT). Case 6a changes nothing here. It holds the +#: tables, views and indexes in `lanes_register`, and `render_file`, +#: `line_scopes`, `doc_line_scopes`, `entry_new_keys`, `scope_fault` and +#: `scope_checked`. It opens the one transaction (BEGIN), and part two ends it. +_REGISTER_M1_TABLES = r"""BEGIN; -- one transaction (§1.5): SET LOCAL needs one +CREATE SCHEMA lanes_register AUTHORIZATION lanes_register_owner; +SET LOCAL ROLE lanes_register_owner; -- so the owner owns every table and function +SET LOCAL search_path TO lanes_register, pg_catalog; + +CREATE TABLE schema_version ( -- §1.5: every client checks it first + id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), + version integer NOT NULL CHECK (version >= 1), + writers_from integer NOT NULL, -- oldest client version that may write + readers_from integer NOT NULL, -- oldest client version that may read + applied_utc timestamptz NOT NULL, + CHECK (1 <= readers_from AND readers_from <= writers_from AND writers_from <= version)); + +CREATE TABLE migrations ( -- forward only: one row per script applied + version integer PRIMARY KEY CHECK (version >= 1), + script_sha256 text NOT NULL CHECK (script_sha256 ~ '^[0-9a-f]{64}$'), + applied_utc timestamptz NOT NULL DEFAULT date_trunc('second', clock_timestamp()), + by_lane text NOT NULL, + by_ws text NOT NULL CHECK (by_ws <> '')); + +CREATE TABLE register_switch ( -- S1: the database half; lanes/STORE mirrors it (D24) + id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), + mode text NOT NULL CHECK (mode IN ('files', 'primary')), + marker_state text NOT NULL CHECK (marker_state IN ('absent', 'adding', 'present', 'removing')), + -- F1, F2, F12: the marker as SQL knows it; adding and + -- removing wait for S4's read-back (record_marker) + marker_seq bigint, -- the operator entry that last changed the marker + marker_commit text CHECK (marker_commit ~ '^[0-9a-f]{40}$'), -- the commit the read-back confirmed + generation uuid NOT NULL, -- F10, F18: the bootstrap's, or an after-loss cutover's + repository text NOT NULL, -- owner/name + database_label text NOT NULL CHECK (strpos(database_label, '@') = 0), -- never a credential + import_commit text CHECK (import_commit ~ '^[0-9a-f]{40}$'), + import_tree text CHECK (import_tree ~ '^[0-9a-f]{40}$'), -- C's lanes tree id + import_seq bigint, + set_utc timestamptz NOT NULL, + set_seq bigint NOT NULL CHECK (set_seq >= -1), -- the seq of the last change: an operator + -- entry's own (a cutover's 1, m+1 or b+1, a rollback's k+1), or an abort's base + set_by_lane text NOT NULL, + set_by_ws text NOT NULL CHECK (set_by_ws <> ''), + restore_prior jsonb, -- the restore form's cutover: the switch row and + -- lanes/STORE's rows it replaced, for its abort + CHECK (mode = 'files' OR (import_commit IS NOT NULL AND import_tree IS NOT NULL + AND import_seq IS NOT NULL)), + CHECK ((mode = 'primary') = (marker_state IN ('adding', 'present'))), + CHECK (marker_state = 'absent' OR marker_seq IS NOT NULL), + CHECK (marker_state <> 'present' OR marker_commit IS NOT NULL), + CHECK (restore_prior IS NULL OR marker_state = 'adding')); -- cleared once confirmed + +CREATE TABLE register_head ( -- S1, S2, S6: its row lock orders every write. + id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), -- Never a SEQUENCE or IDENTITY: + seq bigint NOT NULL CHECK (seq >= -1)); -- gaps, and not commit order. -1: empty + +CREATE TABLE mirror_state ( -- D16: what the renderer reports; it never gates alone + id smallint PRIMARY KEY DEFAULT 1 CHECK (id = 1), + diverged_sha text CHECK (diverged_sha ~ '^[0-9a-f]{40}$'), -- a stray commit stopped the renderer, + -- or a last Register-Seq above the head (N6); a rollback + -- entry is refused while it is set (S5, LR012) + found_utc timestamptz, + found_by_ws text CHECK (found_by_ws <> ''), + last_error text, -- the last failed pass, for status + last_error_utc timestamptz, + CHECK ((diverged_sha IS NULL) = (found_utc IS NULL)), + CHECK ((last_error IS NULL) = (last_error_utc IS NULL))); + +CREATE TABLE journal ( -- S2: one entry per write, gapless, commit order + seq bigint PRIMARY KEY CHECK (seq >= 0), -- = Register-Seq + base_seq bigint UNIQUE REFERENCES journal (seq), -- one chain, no gap + write_id uuid NOT NULL CONSTRAINT journal_write_id_key UNIQUE, -- ADV-C3 + utc timestamptz NOT NULL DEFAULT date_trunc('second', clock_timestamp()), -- S6 + kind text NOT NULL CHECK (kind IN ('import', 'cutover', 'write', + 'stray-import', 'stray-revert', 'rollback')), + operator boolean GENERATED ALWAYS AS (kind IN ('cutover', 'rollback')) STORED, + -- D24, F2: touches lanes/STORE alone; never rendered; + -- the command that writes it pushes it + verb text NOT NULL, + lane text NOT NULL, -- 'unknown' where today's subject says it + workstation text NOT NULL CHECK (workstation <> ''), -- Rule 10 + author text NOT NULL CHECK (author ~ '^[^<>]+ <[^<>]*>$' + AND strpos(author, E'\n') = 0), + message text NOT NULL CHECK (message <> '' AND strpos(message, E'\r') = 0), + git_commit text CHECK (git_commit ~ '^[0-9a-f]{40}$'), + git_tree text CHECK (git_tree ~ '^[0-9a-f]{40}$'), + repos_blob text CHECK (repos_blob ~ '^[0-9a-f]{40}$'), + args_sha256 text CHECK (args_sha256 ~ '^[0-9a-f]{64}$'), -- F10: the lane, verb and arguments, + -- as the pending record's digest + act_id text CHECK (act_id ~ '^[^@[:space:]]+$'), -- D5, F5: the id of the act that made + -- a write (LANES_ACT); NULL: no act + CHECK (kind <> 'write' OR args_sha256 IS NOT NULL), + CONSTRAINT journal_act_id_write CHECK (kind = 'write' OR act_id IS NULL), -- none on another kind + CHECK (base_seq IS NULL OR base_seq = seq - 1), -- the one root (journal_one_root) may sit at any seq + CHECK (utc = date_trunc('second', utc)), -- whole seconds, as utc_now writes them + CHECK (kind <> 'import' OR (git_commit IS NOT NULL AND git_tree IS NOT NULL)), + CHECK (kind NOT IN ('stray-import', 'stray-revert') OR git_commit IS NOT NULL)); +CREATE UNIQUE INDEX journal_one_root ON journal ((base_seq IS NULL)) WHERE base_seq IS NULL; -- one chain, one root + +CREATE TABLE journal_edits ( -- Rule 9(d): a known, finite set of line edits + seq bigint NOT NULL REFERENCES journal (seq), + ord integer NOT NULL CHECK (ord >= 1), -- applied in this order + op text NOT NULL CHECK (op IN ('create', 'append', 'replace', 'delete', + 'rename', 'remove')), + path text COLLATE "C" NOT NULL, + line_no integer CHECK (line_no >= 1), -- in the image the earlier edits left + old_sha256 text CHECK (old_sha256 ~ '^[0-9a-f]{64}$'), + new_text text CHECK (strpos(new_text, E'\n') = 0 AND strpos(new_text, E'\r') = 0), + to_path text COLLATE "C" CHECK (to_path ~ '^lanes/(archive|log)/[^/]+\.md$' + AND to_path <> 'lanes/log/README.md'), + PRIMARY KEY (seq, ord), + CHECK (path ~ '^lanes/(LANES\.md|STORE|aliases\.tsv|archive/[^/]+\.md|log/[^/]+\.md)$' + AND path <> 'lanes/log/README.md'), -- Q18 (A): the rendered paths, and lanes/STORE for the operator entries + CHECK ((op IN ('replace', 'delete')) = (line_no IS NOT NULL AND old_sha256 IS NOT NULL)), + CHECK ((op IN ('append', 'replace')) = (new_text IS NOT NULL)), + CHECK ((op = 'rename') = (to_path IS NOT NULL))); + +CREATE TABLE journal_files ( -- S2: each touched file's bytes after the write + seq bigint NOT NULL REFERENCES journal (seq), + path text COLLATE "C" NOT NULL CHECK (path ~ '^lanes/(LANES\.md|STORE|aliases\.tsv|archive/[^/]+\.md|log/[^/]+\.md)$' AND path <> 'lanes/log/README.md'), -- Q18 (A), as journal_edits.path: the render set and lanes/STORE (data-model.md:48–50; spec#17's re-review r4) + present boolean NOT NULL, -- false: removed or renamed away + sha256 text CHECK (sha256 ~ '^[0-9a-f]{64}$'), + final_newline boolean, -- files.final_newline after the write + PRIMARY KEY (seq, path), + CHECK (present = (sha256 IS NOT NULL) AND present = (final_newline IS NOT NULL))); + +CREATE TABLE journal_scopes ( -- D5, F5: each entry's touched keys (lane 4's scopes), + seq bigint NOT NULL REFERENCES journal (seq) ON DELETE CASCADE, -- derived by steps 5a and 8a, + scope text COLLATE "C" NOT NULL -- never sent by a client + CHECK (scope = lower(scope) AND (scope = '*' -- '*': every scope + OR scope ~ '^(row|bind|objects|alias|archive):[^[:space:]]+$' + OR scope ~ '^sid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')), + PRIMARY KEY (scope, seq)); -- step 3b: one index range per listed scope + +CREATE TABLE files ( -- the rendered files as they stand + path text COLLATE "C" PRIMARY KEY + CHECK (path ~ '^lanes/(LANES\.md|STORE|aliases\.tsv|archive/[^/]+\.md|log/[^/]+\.md)$' + AND path <> 'lanes/log/README.md'), + final_newline boolean NOT NULL, + sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'), + last_seq bigint NOT NULL REFERENCES journal (seq)); + +CREATE TABLE doc_lines ( -- the truth: a file is its lines in line_no order + line_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- stable; writes are serial under + -- the head lock: ascending = append order + path text COLLATE "C" NOT NULL REFERENCES files (path) ON UPDATE CASCADE, + line_no integer NOT NULL CHECK (line_no >= 1), + text text NOT NULL CHECK (strpos(text, E'\n') = 0 AND strpos(text, E'\r') = 0), + written_seq bigint NOT NULL REFERENCES journal (seq), + written_mode text NOT NULL CHECK (written_mode IN ('files', 'primary')), -- S1: mode last written + written_ws text, + CONSTRAINT doc_lines_pos UNIQUE (path, line_no) DEFERRABLE INITIALLY IMMEDIATE, -- a delete shifts lines + CHECK (written_mode = 'files' OR coalesce(written_ws, '') <> '')); -- Rule 10, new writes + +-- The structured layer: today's parsers' rows, filled in the same transaction. A constraint +-- that history breaks binds only mode = 'primary' (r3a/REPORT.md:348). +CREATE TABLE lanes ( -- one row per lane, LANES.md and archive/ together + lane_key text COLLATE "C" PRIMARY KEY, + lane text COLLATE "C" NOT NULL CHECK (lower(lane) = lane_key), -- Amendment 15 + row_line_id bigint UNIQUE DEFERRABLE INITIALLY IMMEDIATE -- ERR-48: checked at the statement's + REFERENCES doc_lines (line_id) DEFERRABLE INITIALLY DEFERRED, -- end, as + -- doc_lines_pos is, so never an ON CONFLICT arbiter + aliases jsonb, home text, workstation text, started_utc text, handoff_path text, + state_phrase text, objects_cell text, session_ids jsonb, last_session text, + archived boolean NOT NULL, + owner text, -- a copy; S4 answers from the row's own text + last_seq bigint NOT NULL REFERENCES journal (seq), + last_mode text NOT NULL CHECK (last_mode IN ('files', 'primary'))); +CREATE INDEX lanes_by_last_session ON lanes (last_session); -- binding; the guard's triple + +CREATE TABLE log_lines ( -- every log line; unreadable ones kept (7(b)) + line_id bigint PRIMARY KEY REFERENCES doc_lines (line_id) ON DELETE CASCADE + DEFERRABLE INITIALLY DEFERRED, + file text COLLATE "C" NOT NULL, + ordinal integer NOT NULL, + lane text NOT NULL, + verb text, session text, workstation text, utc text, utc_ts timestamptz, object text, + ref text, payload text, payload_fields jsonb, free_text text, written_lane text, + unreadable boolean NOT NULL, + unreadable_why text, + raw text NOT NULL, + seq bigint NOT NULL REFERENCES journal (seq), + mode text NOT NULL CHECK (mode IN ('files', 'primary')), + CONSTRAINT log_lines_pos UNIQUE (file, ordinal) DEFERRABLE INITIALLY IMMEDIATE, -- shifts too + CHECK (unreadable = (unreadable_why IS NOT NULL)), + CHECK (mode = 'files' OR (NOT unreadable AND coalesce(workstation, '') <> '' -- no CHECK on + AND utc ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$' -- verb: WORD + AND utc_ts IS NOT NULL))); -- (S6, 7(b)) +CREATE INDEX log_lines_by_object ON log_lines (object) WHERE NOT unreadable; + +CREATE TABLE object_holds ( -- each lane's LAST line per object, file order + object text NOT NULL, + lane_key text COLLATE "C" NOT NULL, + lane text NOT NULL, + verb text NOT NULL, + utc_ts timestamptz, + file text COLLATE "C" NOT NULL, + ordinal integer NOT NULL, + superseded_by text, -- another lane whose last line on it is TAKEOVER + spellings text[], -- D19, a live claim's: as typed, canonical key, the writer's aliases + exempt boolean NOT NULL DEFAULT false, -- set only by an import, on a pair already at C + seq bigint NOT NULL REFERENCES journal (seq), + mode text NOT NULL CHECK (mode IN ('files', 'primary')), + PRIMARY KEY (object, lane_key), + CHECK (NOT exempt OR mode = 'files')); +CREATE UNIQUE INDEX one_live_claim ON object_holds (object) -- Rule 1's net under claim's own check + WHERE NOT exempt AND superseded_by IS NULL AND verb IN ('CLAIMED', 'TAKEOVER'); +CREATE INDEX object_holds_by_line ON object_holds (file, ordinal); -- step 6 finds a line's holds (ERR-48) + +CREATE VIEW holds AS -- holders_of (code/lanes-index:1013-1036) + SELECT object, lane_key, lane, verb, utc_ts, file, ordinal, seq, mode FROM object_holds + WHERE superseded_by IS NULL AND object NOT LIKE 'lane:%' -- lane-kind objects hold nothing + AND verb IN ('CLAIMED', 'TAKEOVER', 'OPENED', 'LANDING', 'WITHDRAWN'); + +CREATE VIEW stale_claims AS -- claim_is_stale (code/lanes-edit.sh:4318) on the DB clock + SELECT h.* FROM object_holds h + WHERE h.verb = 'CLAIMED' AND h.superseded_by IS NULL + AND clock_timestamp() - h.utc_ts > interval '4 hours' + AND NOT EXISTS (SELECT 1 FROM log_lines o WHERE o.object = h.object AND o.verb = 'OPENED') + AND NOT EXISTS (SELECT 1 FROM log_lines o WHERE lower(o.lane) = h.lane_key + AND o.file = h.file AND o.ordinal > h.ordinal AND o.verb = 'OPENED' + AND h.object = ANY (string_to_array(o.payload, ' '))); + +CREATE TABLE register_lines ( -- every non-row LANES.md line of a kind, parsed best effort + line_id bigint PRIMARY KEY REFERENCES doc_lines (line_id) ON DELETE CASCADE + DEFERRABLE INITIALLY DEFERRED, + kind text, + slot_role text CHECK (slot_role IN ('take', 'close')), -- NULL decides nothing + slot_kind text CHECK (slot_kind IN ('hold', 'landing')), + lane text, repo text, repo_key text, pr integer, tip text, utc text, utc_ts timestamptz, + session text, + for_lane text, -- F13: the lane whose LANDING a LANDING EXPIRED closes + raw text NOT NULL, + seq bigint NOT NULL REFERENCES journal (seq), + mode text NOT NULL CHECK (mode IN ('files', 'primary')), + workstation text, + repo_spellings text[], -- D18, a slot line's: as typed, canonical key, the writer's aliases + CHECK ((slot_role IS NULL) = (slot_kind IS NULL)), + CHECK (slot_role IS NULL OR repo_key IS NOT NULL), + CHECK (slot_kind IS DISTINCT FROM 'landing' OR pr IS NOT NULL), -- RULE6_AWK pairs by PR + CHECK ((for_lane IS NOT NULL) = (kind IS NOT DISTINCT FROM 'LANDING EXPIRED')), + CHECK (for_lane IS NULL OR (slot_role = 'close' AND slot_kind = 'landing')), + CHECK (mode = 'files' OR coalesce(workstation, '') <> '')); +CREATE INDEX register_lines_slots ON register_lines (repo_key, line_id) WHERE slot_role IS NOT NULL; +CREATE INDEX files_last_seq ON files (last_seq); -- the seven columns that reference +CREATE INDEX doc_lines_written_seq ON doc_lines (written_seq); -- journal (seq) and lead no index, +CREATE INDEX lanes_last_seq ON lanes (last_seq); -- so an import's deletes do not +CREATE INDEX log_lines_seq ON log_lines (seq); -- scan a table per journal row +CREATE INDEX object_holds_seq ON object_holds (seq); +CREATE INDEX register_lines_seq ON register_lines (seq); +CREATE INDEX journal_scopes_seq ON journal_scopes (seq); + +CREATE VIEW main_slots AS -- A10, Rule 6: the earliest open take wins + SELECT t.repo_key, t.line_id, t.kind, t.slot_kind, t.lane, t.pr, t.tip, t.utc_ts, t.raw, + CASE WHEN t.slot_kind = 'landing' + THEN clock_timestamp() - t.utc_ts > interval '30 minutes' END AS stale, + rank() OVER (PARTITION BY t.repo_key ORDER BY t.line_id) AS place, + t.repo_spellings -- D18: one repository, however spelled + FROM register_lines t + WHERE t.slot_role = 'take' + AND NOT EXISTS (SELECT 1 FROM register_lines c + WHERE c.slot_role = 'close' AND c.slot_kind = t.slot_kind + AND (c.repo_key = t.repo_key OR c.repo_spellings && t.repo_spellings) + AND lower(coalesce(c.for_lane, c.lane)) = lower(t.lane) + AND c.line_id > t.line_id AND (t.slot_kind = 'hold' OR c.pr = t.pr)); + +CREATE FUNCTION render_file(p_path text) RETURNS bytea LANGUAGE sql STABLE + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ + SELECT convert_to(coalesce(string_agg(d.text, E'\n' ORDER BY d.line_no), '') + || CASE WHEN f.final_newline AND count(d.line_id) > 0 THEN E'\n' ELSE '' END, 'UTF8') + FROM files f LEFT JOIN doc_lines d ON d.path = f.path + WHERE f.path = p_path GROUP BY f.final_newline $f$; + +CREATE FUNCTION line_scopes(p_path text, p_text text) RETURNS SETOF text LANGUAGE sql IMMUTABLE + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ + -- D5, F5: the scopes a line names by its text, by build_records' rules (code/lanes-index:765): + -- a row by ROW_AWK's (row_name, :648-660), in LANES.md (:831-837) or the archive (:843-847); a + -- lane-kind line by its verb (parse_log_line, :538-546) in the log that file_lane names + -- (:530-532); an alias line by its first two tab fields (:849-865); a uuid by UUID_RE (:110). + -- S3: an archived row also names its normalized key, where that differs from its own, by + -- RETIRED_ROWS_AWK's key() (code/lanes-edit.sh:3743-3760): the name before its last '-', + -- lower-cased, '-', and the digits after it, less one trailing letter, without leading zeros. + WITH l AS (SELECT substring(p_text FROM '^\|[^`]*`([^`]*)`') AS rown, + p_path ~ '^lanes/log/' AND p_text ~ + '^[ \t]*(STARTED|RESUMED|PAUSED|ENDED|RETIRED|RENAMED)[ \t]* — ' AS lane_kind, + lower(regexp_replace(regexp_replace(p_path, '^.*/', ''), '\.[Mm][Dd]$', '')) AS flane), + a AS (SELECT lower(m[1]) || '-' || coalesce(nullif(ltrim(m[2], '0'), ''), '0') AS akey + FROM l, regexp_match(rown, '^(.*)-([0-9]+)[A-Za-z]?$') AS m) -- NULL: no key + SELECT 'row:' || lower(rown) FROM l WHERE p_path = 'lanes/LANES.md' AND rown <> '' + UNION SELECT 'archive:' || lower(rown) FROM l WHERE p_path ~ '^lanes/archive/' AND rown <> '' + UNION SELECT 'archive:' || akey FROM l, a WHERE p_path ~ '^lanes/archive/' AND akey <> lower(rown) + UNION SELECT 'bind:' || flane FROM l WHERE lane_kind + UNION SELECT 'sid:' || u.m[1] FROM l, regexp_matches(lower(p_text), + '([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})', 'g') AS u(m) + WHERE lane_kind OR (rown <> '' AND p_path ~ '^lanes/(LANES\.md|archive/)') + UNION SELECT 'alias:' || lower(a) FROM l, unnest(ARRAY[btrim(split_part(p_text, E'\t', 1), E' \t'), + btrim(split_part(p_text, E'\t', 2), E' \t')]) AS a + WHERE p_path = 'lanes/aliases.tsv' AND p_text !~ '^[ \t]*#' AND a <> '' $f$; + +CREATE FUNCTION doc_line_scopes(p_line_id bigint, p_path text) RETURNS SETOF text LANGUAGE sql STABLE + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ + -- A stored line's scopes, read at p_path: its text's, and objects: from its structured row: a + -- readable log line on an object that is not lane-kind (parse_log, :618-645), and a slot + -- line's lane and a LANDING EXPIRED's for_lane (parse_register_line, :683-713; D18, F13). + SELECT line_scopes(p_path, d.text) FROM doc_lines d WHERE d.line_id = p_line_id + UNION SELECT 'objects:' || lower(g.lane) FROM log_lines g + WHERE g.line_id = p_line_id AND NOT g.unreadable AND g.object NOT LIKE 'lane:%' + UNION SELECT 'objects:' || lower(x) FROM register_lines r, unnest(ARRAY[r.lane, r.for_lane]) AS x + WHERE r.line_id = p_line_id AND r.slot_role IS NOT NULL AND x IS NOT NULL $f$; + +CREATE FUNCTION entry_new_keys(p_seq bigint) RETURNS TABLE (path text, line_no integer, scope text) + LANGUAGE sql STABLE SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ + -- Step 8a's new side, each key with the line it came from (N2): every line entry p_seq appended + -- or replaced, every line a rename moved, read at its new path, and objects: for every lane + -- holding an object it wrote a hold for, at that lane's last line on the object. + SELECT d.path, d.line_no, k.scope FROM doc_lines d, doc_line_scopes(d.line_id, d.path) AS k(scope) + WHERE d.written_seq = p_seq + UNION SELECT d.path, d.line_no, k.scope FROM journal_edits j JOIN doc_lines d ON d.path = j.to_path, + doc_line_scopes(d.line_id, d.path) AS k(scope) + WHERE j.seq = p_seq AND j.op = 'rename' + UNION SELECT h.file, h.ordinal, 'objects:' || lower(h.lane_key) -- N1: lower(), as doc_line_scopes; + FROM object_holds n JOIN object_holds h ON h.object = n.object -- lane_key is lower case by construction + WHERE n.seq = p_seq AND n.object NOT LIKE 'lane:%' $f$; + +CREATE FUNCTION scope_fault(p_scope text) RETURNS text LANGUAGE sql IMMUTABLE + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ + -- N2: NULL where a derived key has a scope's form, journal_scopes' CHECK read with Unicode's + -- White_Space (the no-break space included; the CHECK's [:space:] under "C" is ASCII's alone); + -- else the key, each white-space character shown as [U+hhhh]. + SELECT CASE WHEN p_scope ~ '^sid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR (p_scope ~ '^(row|bind|objects|alias|archive):.' AND p_scope !~ w.re + AND p_scope = lower(p_scope COLLATE "C")) THEN NULL + ELSE (SELECT string_agg(CASE WHEN c ~ w.re THEN '[U+' || lpad(upper(to_hex(ascii(c))), 4, '0') + || ']' ELSE c END, '' ORDER BY n) + FROM regexp_split_to_table(p_scope, '') WITH ORDINALITY AS t(c, n)) END + FROM (VALUES ('[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]')) AS w(re) $f$; + +CREATE FUNCTION scope_checked(p_path text, p_line integer, p_scope text) RETURNS text + LANGUAGE plpgsql IMMUTABLE SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ +-- N2: a derived key, returned as it is, or LR010 naming the line it came from. +DECLARE + v_shown text := scope_fault(p_scope); +BEGIN + IF v_shown IS NOT NULL THEN + RAISE EXCEPTION 'key: % line % derives %, which is not a scope (a scope''s name is lower case, not empty, and holds no white space)', + p_path, p_line, v_shown USING ERRCODE = 'LR010'; END IF; + RETURN p_scope; +END $f$; +-- commit_write, switch_to_files, record_marker, find_write and record_mirror_state follow in §1.3.1, in this transaction; +-- its block ends migration 1: schema_version (1, 1, 1), register_head (-1), an empty +-- mirror_state row, the switch at 'files' (set_seq -1), the migrations row, then COMMIT. +""" + +#: Migration 1, part two: design.md §1.3.1's SQL block with lane 1's changes +#: to `commit_write` (T107, opensoft/openRepoTools#165), which design.md has +#: yet to fold: erratum (c)'s step 6, which deletes the structured rows its +#: edits leave stale, with the entry's `object_holds` comment (ERR-48); and +#: case 6a, where step 6 keeps the objects whose holds it deletes, step 7 +#: re-marks their stored rows and stamps no `seq` or `mode` on them, and step +#: 5a adds `objects:` for every lane holding an object whose hold sits on a +#: line the entry changes (lane 3's ruling, #165 6771318480). It holds +#: `commit_write` in full, then `switch_to_files`, `record_marker`, +#: `find_write` and `record_mirror_state`, then migration 1's rows: the version +#: (1, 1, 1), the head at -1, an empty `mirror_state`, the switch at `files` +#: with the marker `absent` and `set_seq` -1, and the `migrations` row. Then +#: COMMIT. Its psql variables are the bootstrap's inputs: `repo`, `label`, +#: `lane`, `ws` and `script_sha256`. +_REGISTER_M1_FUNCTIONS = r"""CREATE FUNCTION commit_write(p_base bigint, p_write_id uuid, p_client integer, p_generation uuid, + p_entry jsonb) + RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ +-- The entry is one jsonb object; an absent key is an empty list. +-- journal {kind, verb, lane, workstation, author, message, git_commit, git_tree, +-- repos_blob, args_sha256}: step 5's columns; args_sha256 (F10) is the +-- pending record's digest of the lane, verb and arguments +-- root_seq an import's root on an empty journal (--after-loss's m); else absent +-- switch {after_loss, database_label}: a cutover's after-loss form (F18) +-- not_after required: the call's bound (F3), the snapshot's database clock plus the +-- call's client timer plus 2 s; an attempt that ends past it is LR008 +-- act a write's, made inside one of lane 4's acts (D5, F5); else absent: +-- {id, base, generation, expect}: LANES_ACT's id (journal.act_id) and base +-- seq, the generation its base was read in, and LANES_EXPECT's scopes, a +-- list that may be empty (step 3b). Files mode ignores both variables. +-- edits [{ord, op, path, line_no, old_sha256, new_text, to_path}], journal_edits' +-- columns; old_sha256 is the sha256 of the line's UTF-8 text, without its LF +-- files [{path, present, sha256, final_newline}]: every path an edit touches, as +-- it stands after the write (a rename's old path is present = false); for a write or a stray-import, also a present path other than lanes/STORE, already in files, whose only change is its final_newline (lane 3's ruling 3, step 8; spec#17's re-review r9) +-- lanes [{path, line_no, raw, lane_key, lane, aliases, home, workstation, +-- started_utc, handoff_path, state_phrase, objects_cell, session_ids, +-- last_session, archived, owner}] +-- log_lines [{path, line_no, raw, lane, verb, session, workstation, utc, utc_ts, +-- object, ref, payload, payload_fields, free_text, written_lane, +-- unreadable, unreadable_why}] +-- register_lines [{path, line_no, raw, kind, slot_role, slot_kind, lane, repo, repo_key, +-- repo_spellings, pr, tip, utc, utc_ts, session, for_lane, workstation}] +-- object_holds [{object, lane_key, lane, verb, utc_ts, file, ordinal, spellings, exempt}]: +-- each lane's last line per object, as the lines stand after the write, for +-- every lane and object that a line the entry writes, replaces or deletes +-- names, and every one the lines of a renamed log give: step 6 deletes the +-- holds on each line it changes, and every hold of a path it renames or +-- removes (ERR-48); superseded_by is computed here +-- A structured row names its line by path and line_no, and its raw is that line's text. +-- Step 7 applies lanes, log_lines, register_lines, then object_holds, in that order. +DECLARE + v_head bigint; + v_ver schema_version; + v_sw register_switch; + v_old journal; -- F10: a write id already in the journal + v_needs text; + v_after_loss boolean := coalesce((p_entry -> 'switch' ->> 'after_loss')::boolean, false); + v_seq bigint; + v_kind text := p_entry -> 'journal' ->> 'kind'; + v_ws text := p_entry -> 'journal' ->> 'workstation'; + v_wmode text; -- written_mode and mode of the rows written + v_holds jsonb := coalesce(p_entry -> 'object_holds', '[]'); + v_gone text[] := '{}'; -- case 6a: the objects whose holds step 6 deleted + v_imp journal; + v_prior jsonb; -- the restore form's: what its cutover replaces + v_line doc_lines; + ed journal_edits; + r record; + v_n integer; + v_sha text; + v_con text; + v_det text; + v_not_after timestamptz; -- F3: the call's bound (step 9) + v_act jsonb := p_entry -> 'act'; -- D5, F5: the act, or NULL (step 3b) + v_expect text[]; -- its scopes, lower case, as listed + v_hit record; -- the entry that changed one (LR009) + v_mir mirror_state; -- S5: a rollback's divergence gate (LR012) + v_take register_lines; -- U3's take, or F13's newest take + v_close record; -- F13: the close that already closed it +BEGIN + IF jsonb_typeof(p_entry -> 'journal') IS DISTINCT FROM 'object' THEN -- the entry's shape + RAISE EXCEPTION 'the entry has no journal object' USING ERRCODE = 'LR004'; END IF; + IF EXISTS (SELECT 1 FROM jsonb_each(p_entry -> 'journal') k + WHERE jsonb_typeof(k.value) NOT IN ('string', 'null')) + OR EXISTS (SELECT 1 FROM unnest(ARRAY['edits', 'files', 'lanes', 'log_lines', + 'register_lines', 'object_holds']) k + WHERE p_entry ? k AND jsonb_typeof(p_entry -> k) <> 'array') + OR jsonb_typeof(p_entry -> 'not_after') IS DISTINCT FROM 'string' THEN + RAISE EXCEPTION 'the entry is not well formed' USING ERRCODE = 'LR004'; END IF; + v_not_after := (p_entry ->> 'not_after')::timestamptz; + v_needs := CASE v_kind WHEN 'write' THEN 'primary' WHEN 'stray-import' THEN 'primary' + WHEN 'stray-revert' THEN 'primary' WHEN 'rollback' THEN 'primary' + WHEN 'import' THEN 'files' WHEN 'cutover' THEN 'files' END; + IF v_needs IS NULL THEN + RAISE EXCEPTION 'unknown kind %', v_kind USING ERRCODE = 'LR004'; END IF; + v_wmode := CASE WHEN v_kind IN ('write', 'cutover') THEN 'primary' ELSE 'files' END; + IF v_kind IN ('cutover', 'rollback') AND ( -- ruling 1: an operator entry writes lanes/STORE + EXISTS (SELECT 1 FROM jsonb_array_elements(coalesce(p_entry -> 'files', '[]')) f -- alone: + WHERE f ->> 'path' IS DISTINCT FROM 'lanes/STORE') -- no other files row and + OR EXISTS (SELECT 1 FROM unnest(ARRAY['lanes', 'log_lines', 'register_lines', -- no row + 'object_holds']) k + WHERE jsonb_array_length(coalesce(p_entry -> k, '[]')) > 0)) THEN + RAISE EXCEPTION 'a % entry writes outside lanes/STORE (ruling 1)', v_kind + USING ERRCODE = 'LR004'; END IF; + IF v_act IS NOT NULL THEN -- the act's shape (D5, F5): a write's alone + IF v_kind <> 'write' OR jsonb_typeof(v_act) <> 'object' + OR jsonb_typeof(v_act -> 'id') IS DISTINCT FROM 'string' + OR jsonb_typeof(v_act -> 'base') IS DISTINCT FROM 'number' + OR jsonb_typeof(v_act -> 'generation') IS DISTINCT FROM 'string' + OR jsonb_typeof(coalesce(v_act -> 'expect', '[]')) <> 'array' THEN + RAISE EXCEPTION 'the entry''s act is not well formed' USING ERRCODE = 'LR004'; END IF; + IF v_act ->> 'id' !~ '^[^@[:space:]]+$' OR v_act ->> 'base' !~ '^[0-9]+$' + OR lower(v_act ->> 'generation') + !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR EXISTS (SELECT 1 FROM jsonb_array_elements(coalesce(v_act -> 'expect', '[]')) x + WHERE jsonb_typeof(x) <> 'string' + OR lower(x #>> '{}') !~ ('^((row|bind|objects|alias|archive):[^[:space:]]+' + || '|sid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$')) THEN + RAISE EXCEPTION 'the entry''s act is not well formed' USING ERRCODE = 'LR004'; END IF; + v_expect := ARRAY(SELECT lower(t.x) FROM jsonb_array_elements_text(coalesce(v_act -> 'expect', + '[]')) WITH ORDINALITY AS t(x, n) ORDER BY t.n); + END IF; + +SELECT seq INTO v_head FROM register_head WHERE id = 1 FOR UPDATE; -- 1. the lock +SELECT * INTO v_sw FROM register_switch WHERE id = 1; -- the generation first, +IF p_generation IS DISTINCT FROM v_sw.generation THEN -- F10, F18: an id from another database, + RAISE EXCEPTION 'write % belongs to register generation %, not %', p_write_id, p_generation, + v_sw.generation USING ERRCODE = 'LR007', DETAIL = 'generation'; END IF; -- whatever the switch reads (S-3) +SELECT * INTO v_old FROM journal WHERE write_id = p_write_id; -- a write in doubt +IF FOUND THEN -- that committed + IF v_old.lane IS DISTINCT FROM p_entry -> 'journal' ->> 'lane' + OR v_old.verb IS DISTINCT FROM p_entry -> 'journal' ->> 'verb' + OR v_old.args_sha256 IS DISTINCT FROM p_entry -> 'journal' ->> 'args_sha256' THEN + RAISE EXCEPTION 'write % is seq %, another write''s (F10)', p_write_id, v_old.seq + USING ERRCODE = 'LR007', DETAIL = 'another-write'; END IF; + RAISE EXCEPTION 'write % is in the journal at seq %', p_write_id, v_old.seq USING ERRCODE = 'LR006'; END IF; +IF v_head IS DISTINCT FROM p_base THEN + RAISE EXCEPTION 'register head is %, not %', v_head, p_base USING ERRCODE = 'LR001'; END IF; +SELECT * INTO v_ver FROM schema_version WHERE id = 1; -- 2. the version +IF p_client > v_ver.version OR p_client < v_ver.writers_from THEN + RAISE EXCEPTION 'register schema % (writers from %); this client is %', v_ver.version, + v_ver.writers_from, p_client USING ERRCODE = 'LR003'; END IF; +IF NOT (CASE WHEN v_kind = 'cutover' AND v_after_loss AND v_sw.mode = 'primary' -- 3. the switch + THEN v_sw.marker_state = 'present' -- a restore's after-loss cutover + ELSE v_sw.mode = v_needs AND v_sw.marker_state = + CASE v_needs WHEN 'primary' THEN 'present' ELSE 'absent' END + END) THEN + RAISE EXCEPTION 'register switch is % with the marker %', v_sw.mode, v_sw.marker_state + USING ERRCODE = 'LR002'; END IF; + + -- 3a. The kinds table's rules that come before the seq is taken. + IF v_kind = 'import' THEN -- no 'write' entry: start the journal again (head -1) + DELETE FROM register_lines; DELETE FROM log_lines; DELETE FROM lanes; + DELETE FROM object_holds; DELETE FROM doc_lines; DELETE FROM files; + IF NOT EXISTS (SELECT 1 FROM journal WHERE base_seq IS NOT NULL) THEN -- only its root; after a rollback, continue + DELETE FROM journal_files; DELETE FROM journal_edits; DELETE FROM journal; + UPDATE register_head SET seq = -1 WHERE id = 1; + v_head := -1; + END IF; + END IF; + IF p_entry ? 'root_seq' AND (v_kind <> 'import' OR v_head <> -1) THEN + RAISE EXCEPTION 'root_seq % on a journal that is not empty', p_entry ->> 'root_seq' + USING ERRCODE = 'LR004'; END IF; + IF v_kind = 'cutover' AND v_after_loss -- N4: an after-loss form names its database + AND p_entry -> 'switch' ->> 'database_label' IS NULL THEN + RAISE EXCEPTION 'an after-loss cutover with no database_label (N4)' USING ERRCODE = 'LR004'; END IF; + IF v_kind = 'rollback' THEN -- S5: never over a recorded divergence (F1); FOR SHARE, so + SELECT * INTO v_mir FROM mirror_state WHERE id = 1 FOR SHARE; -- record_mirror_state's UPDATE + IF v_mir.diverged_sha IS NOT NULL THEN -- waits, or this read waits for it + RAISE EXCEPTION 'rollback refused: diverged at %, found % by %; resolve it first with import --single or render --revert (F1, S5)', + v_mir.diverged_sha, v_mir.found_utc, v_mir.found_by_ws USING ERRCODE = 'LR012'; END IF; + END IF; + IF v_kind = 'cutover' AND NOT (v_after_loss AND v_sw.mode = 'primary') THEN + SELECT * INTO v_imp FROM journal WHERE kind = 'import' ORDER BY seq DESC LIMIT 1; + IF v_imp.seq IS DISTINCT FROM p_base THEN + RAISE EXCEPTION 'cutover base %, but the latest import is %', p_base, v_imp.seq + USING ERRCODE = 'LR004'; END IF; + ELSIF v_kind = 'cutover' THEN -- the restore form: what it replaces, for its abort + IF NOT (p_entry -> 'switch' ->> 'database_label' IS DISTINCT FROM v_sw.database_label) THEN + RAISE EXCEPTION 'after-loss cutover: database % is the switch''s own label, not a replacement''s (N4)', + v_sw.database_label USING ERRCODE = 'LR004'; END IF; -- N4: the live database, by mistake + v_prior := jsonb_build_object('switch', to_jsonb(v_sw), + 'file', (SELECT to_jsonb(f) FROM files f WHERE f.path = 'lanes/STORE'), + 'lines', (SELECT jsonb_agg(to_jsonb(d) ORDER BY d.line_no) FROM doc_lines d + WHERE d.path = 'lanes/STORE')); + END IF; + + -- 3b. The act's expectations (S1's step 3.2; D5, F5), under the head's lock and + -- before the seq is taken: refused when an entry after the act's base, made outside this act, + -- touched a listed scope. Each entry's scopes are its steps 5a and 8a's, stored at its commit. + IF cardinality(v_expect) > 0 THEN -- no expectations: no check + IF lower(v_act ->> 'generation')::uuid IS DISTINCT FROM v_sw.generation THEN + RAISE EXCEPTION 'act % has its base in register generation %, not %', v_act ->> 'id', + v_act ->> 'generation', v_sw.generation USING ERRCODE = 'LR007', DETAIL = 'act-generation'; END IF; + IF (v_act ->> 'base')::bigint > v_head THEN + RAISE EXCEPTION 'act % has its base at %, past the head %', v_act ->> 'id', + v_act ->> 'base', v_head USING ERRCODE = 'LR004'; END IF; + SELECT s.scope, s.seq, j.lane, j.verb INTO v_hit -- one indexed query, on (scope, seq) + FROM journal_scopes s JOIN journal j ON j.seq = s.seq + WHERE s.scope = ANY (v_expect || '*'::text) AND s.seq > (v_act ->> 'base')::bigint + AND j.act_id IS DISTINCT FROM v_act ->> 'id' -- the act's own entries never refuse it + ORDER BY s.seq, s.scope LIMIT 1; + IF FOUND THEN + RAISE EXCEPTION 'expectation: % changed at seq % by %/%', + CASE v_hit.scope WHEN '*' THEN v_expect[1] ELSE v_hit.scope END, v_hit.seq, v_hit.lane, + v_hit.verb USING ERRCODE = 'LR009'; END IF; + END IF; + +UPDATE register_head SET seq = CASE WHEN v_head = -1 -- 4. advance; the empty journal's + THEN coalesce((p_entry ->> 'root_seq')::bigint, 0) ELSE seq + 1 END -- one entry is the root, at 0 or `m` + WHERE id = 1 RETURNING seq INTO v_seq; +INSERT INTO journal (seq, base_seq, write_id, kind, verb, lane, workstation, author, message, + git_commit, git_tree, repos_blob, args_sha256, act_id) -- 5. the entry +SELECT v_seq, nullif(v_head, -1), p_write_id, e.*, p_entry -> 'act' ->> 'id' -- D5's act, or NULL + FROM jsonb_to_record(p_entry -> 'journal') + AS e(kind text, verb text, lane text, workstation text, author text, message text, + git_commit text, git_tree text, repos_blob text, args_sha256 text); + + -- 5a. The touched keys' old side (D5, F5): what each line this entry replaces or deletes + -- (found by path and old_sha256), and every line of a path it removes or renames, said + -- before step 6 changes it; and objects: for every lane holding an object whose hold sits + -- on such a line, since step 6 deletes that hold and step 7 re-marks the object's stored + -- rows, so the flip is reported (case 6a; lane 3's ruling, #165 6771318480). + IF v_kind IN ('write', 'stray-import') THEN + INSERT INTO journal_scopes (seq, scope) + SELECT DISTINCT v_seq, scope_checked(d.path, d.line_no, k.scope) -- N2: LR010, not 23514 + FROM jsonb_to_recordset(coalesce(p_entry -> 'edits', '[]')) AS x(op text, path text, + old_sha256 text) + JOIN doc_lines d ON d.path = x.path AND (x.op IN ('remove', 'rename') + OR (x.op IN ('replace', 'delete') + AND encode(sha256(convert_to(d.text, 'UTF8')), 'hex') = x.old_sha256)) + CROSS JOIN LATERAL (SELECT doc_line_scopes(d.line_id, d.path) + UNION SELECT 'objects:' || lower(o.lane_key) -- N1: lower(), as entry_new_keys + FROM object_holds h JOIN object_holds o ON o.object = h.object + WHERE h.file = d.path AND h.ordinal = d.line_no AND h.object NOT LIKE 'lane:%') AS k(scope); + END IF; + + -- 6. The edits: journal_edits as sent, then applied in ord order. The structured rows an edit + -- leaves stale go with it (ERR-48; lane 3's ruling (c), #165 6755386771): as a replace or a + -- delete changes a line, its lanes row by row_line_id, its log_lines and register_lines rows + -- by line_id, and its object_holds by (file, ordinal); a remove, those of every line of its + -- path; a rename, the old path's object_holds, while its log_lines move to the new file's + -- lane. Step 7 then inserts what the entry sends: an entry carries no deletes. The objects + -- whose holds go are kept in v_gone, and step 7 re-marks them (case 6a, #165 6771318480). + INSERT INTO journal_edits (seq, ord, op, path, line_no, old_sha256, new_text, to_path) + SELECT v_seq, x.ord, x.op, x.path, x.line_no, x.old_sha256, x.new_text, x.to_path + FROM jsonb_to_recordset(coalesce(p_entry -> 'edits', '[]')) AS x(ord integer, op text, + path text, line_no integer, old_sha256 text, new_text text, to_path text); + IF v_kind IN ('cutover', 'rollback') -- D24, F2: an operator entry has edits + AND NOT EXISTS (SELECT 1 FROM journal_edits WHERE seq = v_seq) THEN + RAISE EXCEPTION 'a % entry with no edit', v_kind USING ERRCODE = 'LR004'; END IF; + FOR ed IN SELECT * FROM journal_edits WHERE seq = v_seq ORDER BY ord LOOP + IF (ed.path = 'lanes/STORE') <> (v_kind IN ('cutover', 'rollback')) THEN -- and edits + RAISE EXCEPTION 'edit %: a % edits lanes/STORE alone, or never', ed.ord, v_kind -- STORE alone + USING ERRCODE = 'LR004'; END IF; + IF (v_kind = 'import' AND ed.op NOT IN ('create', 'append')) OR v_kind = 'stray-revert' THEN + RAISE EXCEPTION 'edit %: a % may not %', ed.ord, v_kind, ed.op USING ERRCODE = 'LR004'; + END IF; + IF (ed.op = 'create') = EXISTS (SELECT 1 FROM files WHERE path = ed.path) THEN + RAISE EXCEPTION 'edit %: % % %', ed.ord, ed.op, ed.path, + CASE WHEN ed.op = 'create' THEN 'exists' ELSE 'does not exist' END + USING ERRCODE = 'LR004'; END IF; + CASE ed.op + WHEN 'create' THEN + INSERT INTO files (path, final_newline, sha256, last_seq) -- step 8 sets the last two + VALUES (ed.path, true, encode(sha256(''::bytea), 'hex'), v_seq); + WHEN 'append' THEN + SELECT coalesce(max(line_no), 0) + 1 INTO v_n FROM doc_lines WHERE path = ed.path; + IF ed.line_no IS DISTINCT FROM NULL AND ed.line_no <> v_n THEN + RAISE EXCEPTION 'edit %: append at %, but % has % lines', ed.ord, ed.line_no, ed.path, + v_n - 1 USING ERRCODE = 'LR004'; END IF; + INSERT INTO doc_lines (path, line_no, text, written_seq, written_mode, written_ws) + VALUES (ed.path, v_n, ed.new_text, v_seq, v_wmode, v_ws); + WHEN 'replace', 'delete' THEN + SELECT * INTO v_line FROM doc_lines WHERE path = ed.path AND line_no = ed.line_no; + IF NOT FOUND OR encode(sha256(convert_to(v_line.text, 'UTF8')), 'hex') <> ed.old_sha256 THEN + RAISE EXCEPTION 'edit %: % line % is not %', ed.ord, ed.path, ed.line_no, ed.old_sha256 + USING ERRCODE = 'LR004'; END IF; + -- The line's structured rows go before it changes, and step 7 inserts what the entry + -- sends. Its holds go too, so a delete's shift below leaves none of them on the line + -- that moves into its place. + DELETE FROM lanes WHERE row_line_id = v_line.line_id; + DELETE FROM log_lines WHERE line_id = v_line.line_id; + DELETE FROM register_lines WHERE line_id = v_line.line_id; + WITH g AS (DELETE FROM object_holds WHERE file = ed.path AND ordinal = ed.line_no + RETURNING object) + SELECT v_gone || ARRAY(SELECT object FROM g) INTO v_gone; + IF ed.op = 'replace' THEN + UPDATE doc_lines SET text = ed.new_text, written_seq = v_seq, written_mode = v_wmode, + written_ws = v_ws + WHERE line_id = v_line.line_id; + ELSE -- doc_lines_pos checks at the statement's end + DELETE FROM doc_lines WHERE line_id = v_line.line_id; + UPDATE doc_lines SET line_no = line_no - 1 WHERE path = ed.path AND line_no > ed.line_no; + UPDATE log_lines SET ordinal = ordinal - 1 WHERE file = ed.path AND ordinal > ed.line_no; + UPDATE object_holds SET ordinal = ordinal - 1 WHERE file = ed.path AND ordinal > ed.line_no; + END IF; + WHEN 'rename' THEN + IF EXISTS (SELECT 1 FROM files WHERE path = ed.to_path) THEN + RAISE EXCEPTION 'edit %: % exists', ed.ord, ed.to_path USING ERRCODE = 'LR004'; END IF; + UPDATE files SET path = ed.to_path WHERE path = ed.path; -- cascades to doc_lines + WITH g AS (DELETE FROM object_holds WHERE file = ed.path -- the entry sends the new path's + RETURNING object) + SELECT v_gone || ARRAY(SELECT object FROM g) INTO v_gone; + -- The log's lines move to the new file's lane, by file_lane (code/lanes-index:530-532), + -- and a lane-kind object names that lane, as parse_log's does (:618-645). + UPDATE log_lines SET file = ed.to_path, + lane = regexp_replace(regexp_replace(ed.to_path, '^.*/', ''), '\.[Mm][Dd]$', '') + WHERE file = ed.path; + UPDATE log_lines SET object = 'lane:' || lane + WHERE file = ed.to_path AND object LIKE 'lane:%'; + WHEN 'remove' THEN -- every line's structured rows, then the lines + DELETE FROM lanes WHERE row_line_id IN (SELECT line_id FROM doc_lines WHERE path = ed.path); + DELETE FROM log_lines WHERE line_id IN (SELECT line_id FROM doc_lines WHERE path = ed.path); + DELETE FROM register_lines WHERE line_id IN (SELECT line_id FROM doc_lines + WHERE path = ed.path); + WITH g AS (DELETE FROM object_holds WHERE file = ed.path RETURNING object) + SELECT v_gone || ARRAY(SELECT object FROM g) INTO v_gone; + DELETE FROM doc_lines WHERE path = ed.path; + DELETE FROM files WHERE path = ed.path; + END CASE; + END LOOP; + + -- 7. The structured rows, upserted by key, each given its line's line_id. + FOR r IN + SELECT x.t, x.path, x.line_no, x.raw, d.line_id, d.text FROM ( + SELECT 'lanes' AS t, path, line_no, raw FROM jsonb_to_recordset(coalesce(p_entry -> 'lanes', + '[]')) AS y(path text, line_no integer, raw text) + UNION ALL SELECT 'log_lines', path, line_no, raw FROM jsonb_to_recordset(coalesce( + p_entry -> 'log_lines', '[]')) AS y(path text, line_no integer, raw text) + UNION ALL SELECT 'register_lines', path, line_no, raw FROM jsonb_to_recordset(coalesce( + p_entry -> 'register_lines', '[]')) AS y(path text, line_no integer, raw text)) x + LEFT JOIN doc_lines d ON d.path = x.path AND d.line_no = x.line_no + LOOP + IF r.line_id IS NULL OR r.text IS DISTINCT FROM r.raw THEN + RAISE EXCEPTION '% row at % line %: no such line, or raw is not its text', r.t, r.path, + r.line_no + USING ERRCODE = 'LR004'; END IF; + END LOOP; + INSERT INTO lanes AS o (lane_key, lane, row_line_id, aliases, home, workstation, started_utc, + handoff_path, state_phrase, objects_cell, session_ids, last_session, + archived, owner, last_seq, last_mode) + SELECT x.lane_key, x.lane, d.line_id, x.aliases, x.home, x.workstation, x.started_utc, + x.handoff_path, x.state_phrase, x.objects_cell, x.session_ids, x.last_session, + x.archived, x.owner, v_seq, v_wmode + FROM jsonb_to_recordset(coalesce(p_entry -> 'lanes', '[]')) AS x(path text, line_no integer, + lane_key text, lane text, aliases jsonb, home text, workstation text, started_utc text, + handoff_path text, state_phrase text, objects_cell text, session_ids jsonb, + last_session text, archived boolean, owner text) + JOIN doc_lines d ON d.path = x.path AND d.line_no = x.line_no + ON CONFLICT (lane_key) DO UPDATE SET lane = EXCLUDED.lane, row_line_id = EXCLUDED.row_line_id, + aliases = EXCLUDED.aliases, home = EXCLUDED.home, workstation = EXCLUDED.workstation, + started_utc = EXCLUDED.started_utc, handoff_path = EXCLUDED.handoff_path, + state_phrase = EXCLUDED.state_phrase, objects_cell = EXCLUDED.objects_cell, + session_ids = EXCLUDED.session_ids, last_session = EXCLUDED.last_session, + archived = EXCLUDED.archived, owner = EXCLUDED.owner, last_seq = EXCLUDED.last_seq, + last_mode = EXCLUDED.last_mode; + INSERT INTO log_lines (line_id, file, ordinal, lane, verb, session, workstation, utc, utc_ts, + object, ref, payload, payload_fields, free_text, written_lane, + unreadable, unreadable_why, raw, seq, mode) + SELECT d.line_id, x.path, x.line_no, x.lane, x.verb, x.session, x.workstation, x.utc, + x.utc_ts, x.object, x.ref, x.payload, x.payload_fields, x.free_text, x.written_lane, + x.unreadable, x.unreadable_why, x.raw, v_seq, v_wmode + FROM jsonb_to_recordset(coalesce(p_entry -> 'log_lines', '[]')) AS x(path text, + line_no integer, raw text, lane text, verb text, session text, workstation text, + utc text, utc_ts timestamptz, object text, ref text, payload text, payload_fields jsonb, + free_text text, written_lane text, unreadable boolean, unreadable_why text) + JOIN doc_lines d ON d.path = x.path AND d.line_no = x.line_no + ON CONFLICT (line_id) DO UPDATE SET file = EXCLUDED.file, ordinal = EXCLUDED.ordinal, + lane = EXCLUDED.lane, verb = EXCLUDED.verb, session = EXCLUDED.session, + workstation = EXCLUDED.workstation, utc = EXCLUDED.utc, utc_ts = EXCLUDED.utc_ts, + object = EXCLUDED.object, ref = EXCLUDED.ref, payload = EXCLUDED.payload, + payload_fields = EXCLUDED.payload_fields, free_text = EXCLUDED.free_text, + written_lane = EXCLUDED.written_lane, unreadable = EXCLUDED.unreadable, + unreadable_why = EXCLUDED.unreadable_why, raw = EXCLUDED.raw, seq = EXCLUDED.seq, + mode = EXCLUDED.mode; + INSERT INTO register_lines (line_id, kind, slot_role, slot_kind, lane, repo, repo_key, pr, tip, + utc, utc_ts, session, for_lane, raw, seq, mode, workstation, + repo_spellings) + SELECT d.line_id, x.kind, x.slot_role, x.slot_kind, x.lane, x.repo, x.repo_key, x.pr, x.tip, + x.utc, x.utc_ts, x.session, x.for_lane, x.raw, v_seq, v_wmode, x.workstation, + x.repo_spellings + FROM jsonb_to_recordset(coalesce(p_entry -> 'register_lines', '[]')) AS x(path text, + line_no integer, raw text, kind text, slot_role text, slot_kind text, lane text, + repo text, repo_key text, pr integer, tip text, utc text, utc_ts timestamptz, + session text, for_lane text, workstation text, repo_spellings text[]) + JOIN doc_lines d ON d.path = x.path AND d.line_no = x.line_no + ON CONFLICT (line_id) DO UPDATE SET kind = EXCLUDED.kind, slot_role = EXCLUDED.slot_role, + slot_kind = EXCLUDED.slot_kind, lane = EXCLUDED.lane, repo = EXCLUDED.repo, + repo_key = EXCLUDED.repo_key, pr = EXCLUDED.pr, tip = EXCLUDED.tip, utc = EXCLUDED.utc, + utc_ts = EXCLUDED.utc_ts, session = EXCLUDED.session, for_lane = EXCLUDED.for_lane, + raw = EXCLUDED.raw, seq = EXCLUDED.seq, mode = EXCLUDED.mode, + workstation = EXCLUDED.workstation, repo_spellings = EXCLUDED.repo_spellings; + -- superseded_by, #160's rule (code/lanes-index:1013-1036): a lane's state on an object is + -- its own last line on it, and another lane whose own last line on it is a TAKEOVER + -- supersedes it. The stored rows of each touched object are re-marked first, against the + -- incoming rows, so no transient pair of live claims trips one_live_claim. An object whose + -- hold step 6 deleted is touched though the entry sends no hold on it (case 6a; lane 3's + -- ruling, #165 6771318480). A re-mark stamps no seq or mode, so D19 never takes such a row + -- for this entry's own claim, and an exempt row keeps its files mode. + BEGIN -- a 23505 on one_live_claim is LR005 + UPDATE object_holds h SET superseded_by = ( + SELECT min(e.lane_key) FROM ( + SELECT i.object, i.lane_key, i.verb + FROM jsonb_to_recordset(v_holds) AS i(object text, lane_key text, verb text) + UNION ALL + SELECT s.object, s.lane_key, s.verb FROM object_holds s + WHERE NOT v_holds @> jsonb_build_array(jsonb_build_object('object', s.object, + 'lane_key', s.lane_key))) e + WHERE e.object = h.object AND e.lane_key <> h.lane_key AND e.verb = 'TAKEOVER') + WHERE v_holds @> jsonb_build_array(jsonb_build_object('object', h.object)) + OR h.object = ANY (v_gone); + INSERT INTO object_holds (object, lane_key, lane, verb, utc_ts, file, ordinal, superseded_by, + spellings, exempt, seq, mode) + SELECT x.object, x.lane_key, x.lane, x.verb, x.utc_ts, x.file, x.ordinal, + (SELECT min(e.lane_key) FROM ( + SELECT i.object, i.lane_key, i.verb + FROM jsonb_to_recordset(v_holds) AS i(object text, lane_key text, verb text) + UNION ALL + SELECT s.object, s.lane_key, s.verb FROM object_holds s + WHERE NOT v_holds @> jsonb_build_array(jsonb_build_object('object', s.object, + 'lane_key', s.lane_key))) e + WHERE e.object = x.object AND e.lane_key <> x.lane_key AND e.verb = 'TAKEOVER'), + x.spellings, v_kind = 'import' AND coalesce(x.exempt, false), v_seq, v_wmode + FROM jsonb_to_recordset(v_holds) AS x(object text, lane_key text, lane text, verb text, + utc_ts timestamptz, file text, ordinal integer, spellings text[], exempt boolean) + ON CONFLICT (object, lane_key) DO UPDATE SET lane = EXCLUDED.lane, verb = EXCLUDED.verb, + utc_ts = EXCLUDED.utc_ts, file = EXCLUDED.file, ordinal = EXCLUDED.ordinal, + superseded_by = EXCLUDED.superseded_by, spellings = EXCLUDED.spellings, + exempt = EXCLUDED.exempt, seq = EXCLUDED.seq, mode = EXCLUDED.mode; + EXCEPTION WHEN unique_violation THEN + GET STACKED DIAGNOSTICS v_con = CONSTRAINT_NAME, v_det = PG_EXCEPTION_DETAIL; + IF v_con = 'one_live_claim' THEN + RAISE EXCEPTION 'the object is held (one_live_claim): %', v_det + USING ERRCODE = 'LR005', DETAIL = 'one-live-claim'; + END IF; + RAISE; + END; + IF v_wmode = 'primary' THEN -- the register's own rules bind new writes + SELECT * INTO v_take FROM register_lines n -- U3: Rule 6's 30 minutes are measured from a + WHERE n.seq = v_seq AND n.slot_role = 'take' AND n.utc_ts IS NULL LIMIT 1; -- take's UTC + IF FOUND THEN + RAISE EXCEPTION 'a % take with no readable UTC (U3): %', v_take.kind, left(v_take.raw, 160) + USING ERRCODE = 'LR005', DETAIL = 'take-no-utc'; END IF; + IF EXISTS (SELECT 1 FROM object_holds n JOIN object_holds o ON o.lane_key <> n.lane_key + WHERE n.seq = v_seq AND n.verb IN ('CLAIMED', 'TAKEOVER') + AND n.superseded_by IS NULL AND NOT n.exempt + AND o.verb IN ('CLAIMED', 'TAKEOVER') AND o.superseded_by IS NULL + AND n.spellings && o.spellings) THEN + RAISE EXCEPTION 'a claim''s spellings overlap another lane''s live claim (D19)' + USING ERRCODE = 'LR005', DETAIL = 'claim-spellings'; END IF; + IF EXISTS (SELECT 1 FROM register_lines n JOIN main_slots m -- one repository, however + ON m.repo_key = n.repo_key OR m.repo_spellings && n.repo_spellings -- spelled + WHERE n.seq = v_seq AND n.slot_role = 'take' AND m.line_id < n.line_id + AND lower(m.lane) <> lower(n.lane)) THEN + RAISE EXCEPTION 'another lane holds main for this repository first (D18)' + USING ERRCODE = 'LR005', DETAIL = 'main-held'; END IF; + FOR r IN SELECT * FROM register_lines n -- F13: a LANDING EXPIRED closes the + WHERE n.seq = v_seq AND n.kind = 'LANDING EXPIRED' LOOP -- holder's stale LANDING + SELECT * INTO v_take FROM register_lines t -- C1: the holder's newest take that it closes, + WHERE t.slot_role = 'take' AND t.slot_kind = 'landing' -- matched as main_slots + AND (t.repo_key = r.repo_key OR t.repo_spellings && r.repo_spellings) -- matches + AND t.pr = r.pr AND lower(t.lane) = lower(r.for_lane) AND t.line_id < r.line_id + ORDER BY t.line_id DESC LIMIT 1; + IF NOT FOUND OR v_take.repo_key IS DISTINCT FROM r.repo_key THEN -- point 5: repo_key alone + RAISE EXCEPTION 'no open LANDING by % for PR #% under repo_key % (F13): there is none, or its newest is keyed %', + r.for_lane, r.pr, r.repo_key, coalesce(v_take.repo_key, '-') + USING ERRCODE = 'LR005', DETAIL = 'expired-none'; END IF; + SELECT c.kind, c.lane INTO v_close FROM register_lines c -- C2: a close, matched as + WHERE c.slot_role = 'close' AND c.slot_kind = 'landing' -- main_slots matches one + AND (c.repo_key = v_take.repo_key OR c.repo_spellings && v_take.repo_spellings) + AND c.pr = v_take.pr AND c.line_id > v_take.line_id AND c.line_id <> r.line_id + AND lower(coalesce(c.for_lane, c.lane)) = lower(v_take.lane) + ORDER BY c.line_id LIMIT 1; + IF FOUND THEN + RAISE EXCEPTION '%''s LANDING for PR #% under repo_key % is already closed, by a % of % (F13)', + v_take.lane, v_take.pr, v_take.repo_key, v_close.kind, v_close.lane + USING ERRCODE = 'LR005', DETAIL = 'expired-closed'; END IF; + IF NOT coalesce(clock_timestamp() - v_take.utc_ts > interval '30 minutes', false) THEN + RAISE EXCEPTION '%''s newest LANDING for PR #% under repo_key % is too young (F13): its age by the database''s clock is %, not more than Rule 6''s 30 minutes', + v_take.lane, v_take.pr, v_take.repo_key, + coalesce(date_trunc('second', clock_timestamp() - v_take.utc_ts)::text, 'unknown, since its UTC cannot be read') + USING ERRCODE = 'LR005', DETAIL = 'expired-young'; END IF; + END LOOP; + END IF; + + -- 8. The proof: every files row names the render set or lanes/STORE (LR004 before journal_files' CHECK); every touched path is in the entry's files; for a write, an import or a stray import, every files row is a touched path or a present one other than `lanes/STORE` whose final_newline differs from its files.final_newline, since a change of only a final newline is an edit (lane 3's ruling on lane 1's #165 6882354358), and a `lanes/STORE` row with no edit is LR004 here, since only cutover and rollback, the operator entries, may name `lanes/STORE` (spec#17's re-review r9 and its delta review 7i, each its first BLOCKING finding); while a stray revert, free of journal_edits, names untouched ones, but never `lanes/STORE`, which is not rendered, with its own diagnostic (spec#17's re-review r4 and r5), and its rows prove the register's current truth and never change it: a present row must equal its path's stored final_newline and sha256, a row with present null is refused, and a row with present false must name a path not in files, since that is how a revert removes a file the stray added, and a check before the loop refuses one for a path in files, with the loop's own "proof: % is present" as a second line of defence (spec#17's re-review r10; lane 3's ruling, commit 28; and its re-review r11, commit 29); and each renders to its digest. + IF EXISTS (SELECT 1 FROM journal_edits j, LATERAL (VALUES (j.path), (j.to_path)) t(p) + WHERE j.seq = v_seq AND t.p IS NOT NULL + AND NOT coalesce(p_entry -> 'files', '[]') @> jsonb_build_array( + jsonb_build_object('path', t.p))) THEN + RAISE EXCEPTION 'an edited path has no files row in the entry' USING ERRCODE = 'LR004'; + END IF; + IF EXISTS (SELECT 1 FROM jsonb_to_recordset(coalesce(p_entry -> 'files', '[]')) AS x(path text) WHERE x.path IS NULL OR x.path !~ '^lanes/(LANES\.md|STORE|aliases\.tsv|archive/[^/]+\.md|log/[^/]+\.md)$' OR x.path = 'lanes/log/README.md') THEN RAISE EXCEPTION 'a files row names a path outside the render set and lanes/STORE' USING ERRCODE = 'LR004'; END IF; IF v_kind IN ('write', 'import', 'stray-import') AND EXISTS (SELECT 1 FROM jsonb_to_recordset(coalesce(p_entry -> 'files', '[]')) AS x(path text, present boolean, final_newline boolean) WHERE NOT EXISTS (SELECT 1 FROM journal_edits j WHERE j.seq = v_seq AND x.path IN (j.path, j.to_path)) AND NOT (coalesce(x.present, false) AND x.path <> 'lanes/STORE' AND EXISTS (SELECT 1 FROM files f WHERE f.path = x.path AND f.final_newline IS DISTINCT FROM coalesce(x.final_newline, f.final_newline)))) THEN RAISE EXCEPTION 'a files row names a path the entry does not edit' USING ERRCODE = 'LR004'; END IF; IF v_kind = 'stray-revert' AND EXISTS (SELECT 1 FROM jsonb_to_recordset(coalesce(p_entry -> 'files', '[]')) AS x(path text) WHERE x.path = 'lanes/STORE') THEN RAISE EXCEPTION 'a stray-revert files row names lanes/STORE, which is not rendered' USING ERRCODE = 'LR004'; END IF; IF v_kind = 'stray-revert' AND EXISTS (SELECT 1 FROM jsonb_to_recordset(coalesce(p_entry -> 'files', '[]')) AS x(path text, present boolean, sha256 text, final_newline boolean) WHERE x.present IS NULL OR (x.present AND NOT EXISTS (SELECT 1 FROM files f WHERE f.path = x.path AND f.final_newline = x.final_newline AND f.sha256 = x.sha256)) OR (x.present IS FALSE AND EXISTS (SELECT 1 FROM files f WHERE f.path = x.path))) THEN RAISE EXCEPTION 'a stray-revert files row would change the register: a present row must equal the stored final_newline and sha256 of its path, a row with present false must name a path not in files, and present may not be null' USING ERRCODE = 'LR004'; END IF; FOR r IN SELECT * FROM jsonb_to_recordset(coalesce(p_entry -> 'files', '[]')) + AS x(path text, present boolean, sha256 text, final_newline boolean) LOOP + INSERT INTO journal_files (seq, path, present, sha256, final_newline) + VALUES (v_seq, r.path, r.present, r.sha256, r.final_newline); + IF r.present THEN + UPDATE files SET final_newline = coalesce(r.final_newline, final_newline) + WHERE path = r.path; + v_sha := encode(sha256(render_file(r.path)), 'hex'); + IF v_sha IS DISTINCT FROM r.sha256 THEN + RAISE EXCEPTION 'proof: % renders %, the entry says %', r.path, v_sha, r.sha256 + USING ERRCODE = 'LR004'; END IF; + UPDATE files SET sha256 = r.sha256, last_seq = v_seq WHERE path = r.path; + ELSIF EXISTS (SELECT 1 FROM files WHERE path = r.path) THEN + RAISE EXCEPTION 'proof: % is present', r.path USING ERRCODE = 'LR004'; + END IF; + END LOOP; + + -- 8a. The touched keys' new side (D5, F5), from what the entry wrote, never from a list it + -- sends: each line it appended or replaced, each line a rename moved, read at its new path, + -- and objects: for every lane holding an object it wrote a hold for, since a TAKEOVER + -- supersedes the others and the taker's next line may restore them (entry_new_keys). An + -- import, a cutover and a rollback move what every read rests on: their one key is '*', which + -- every scope meets. N2: each key is checked before it is stored, in path and line order, and + -- an import checks every key its lines and holds derive, though it stores only '*'. + IF v_kind IN ('import', 'cutover', 'rollback') THEN + INSERT INTO journal_scopes (seq, scope) VALUES (v_seq, '*'); + END IF; + IF v_kind = 'import' THEN + PERFORM count(scope_checked(k.path, k.line_no, k.scope)) + FROM (SELECT * FROM entry_new_keys(v_seq) ORDER BY 1, 2, 3) AS k; + ELSIF v_kind NOT IN ('cutover', 'rollback') THEN + INSERT INTO journal_scopes (seq, scope) + SELECT v_seq, scope_checked(k.path, k.line_no, k.scope) + FROM (SELECT * FROM entry_new_keys(v_seq) ORDER BY 1, 2, 3) AS k + ON CONFLICT DO NOTHING; + END IF; + + -- The kinds table's rules that come after: D24's two operator entries move the switch. + IF v_kind = 'cutover' THEN -- set_seq: its own seq, 1, m+1 after a re-import, or b+1 after a restore + UPDATE register_switch SET mode = 'primary', marker_state = 'adding', marker_seq = v_seq, + import_seq = coalesce(v_imp.seq, import_seq), -- a restore's has no import entry + import_commit = coalesce(v_imp.git_commit, import_commit), + import_tree = coalesce(v_imp.git_tree, import_tree), set_seq = v_seq, + database_label = CASE WHEN v_after_loss THEN p_entry -> 'switch' ->> 'database_label' + ELSE database_label END, + generation = CASE WHEN v_after_loss THEN gen_random_uuid() ELSE generation END, + set_utc = date_trunc('second', clock_timestamp()), + set_by_lane = p_entry -> 'journal' ->> 'lane', set_by_ws = v_ws, + restore_prior = v_prior -- NULL but in the restore form + WHERE id = 1; + ELSIF v_kind = 'rollback' THEN -- set_seq: its own entry, the last seq, k+1 + UPDATE register_switch SET mode = 'files', marker_state = 'removing', marker_seq = v_seq, + set_seq = v_seq, set_utc = date_trunc('second', clock_timestamp()), + set_by_lane = p_entry -> 'journal' ->> 'lane', set_by_ws = v_ws + WHERE id = 1; + ELSIF v_kind IN ('stray-import', 'stray-revert') THEN + UPDATE mirror_state SET diverged_sha = NULL, found_utc = NULL, found_by_ws = NULL + WHERE id = 1; + END IF; + IF NOT (clock_timestamp() < v_not_after) THEN -- 9. the bound (F3): past it, nothing commits + RAISE EXCEPTION 'write % reached its end at %, past its not_after %', p_write_id, + clock_timestamp(), v_not_after USING ERRCODE = 'LR008'; END IF; + RETURN v_seq; -- the deferred foreign keys check at COMMIT +END $f$; + +CREATE FUNCTION switch_to_files(p_client integer, p_cutover_seq bigint, p_lane text, p_ws text) + RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ +-- The cutover's abort (F2): run only after a read-back proves the entry's commit absent from +-- origin. In the restore form it puts back what restore_prior holds and sets nothing to files. +DECLARE + v_head bigint; + v_ver schema_version; + v_sw register_switch; +BEGIN + SELECT seq INTO v_head FROM register_head WHERE id = 1 FOR UPDATE; -- the same lock + SELECT * INTO v_ver FROM schema_version WHERE id = 1; + IF p_client > v_ver.version OR p_client < v_ver.writers_from THEN + RAISE EXCEPTION 'register schema % (writers from %); this client is %', v_ver.version, + v_ver.writers_from, p_client USING ERRCODE = 'LR003'; END IF; + SELECT * INTO v_sw FROM register_switch WHERE id = 1; -- an unconfirmed cutover only + IF v_sw.mode <> 'primary' OR v_sw.marker_state <> 'adding' + OR v_sw.marker_seq IS DISTINCT FROM p_cutover_seq OR v_head <> p_cutover_seq THEN + RAISE EXCEPTION 'no unconfirmed cutover at seq %', p_cutover_seq USING ERRCODE = 'LR002'; END IF; + DELETE FROM doc_lines WHERE path = 'lanes/STORE'; -- its rows, children first + DELETE FROM files WHERE path = 'lanes/STORE'; + IF v_sw.restore_prior IS NOT NULL THEN -- the restore form: lanes/STORE + INSERT INTO files -- as it was at b, line ids too + SELECT * FROM jsonb_populate_record(NULL::files, v_sw.restore_prior -> 'file'); + INSERT INTO doc_lines OVERRIDING SYSTEM VALUE + SELECT * FROM jsonb_populate_recordset(NULL::doc_lines, v_sw.restore_prior -> 'lines'); + END IF; + DELETE FROM journal_files WHERE seq = p_cutover_seq; + DELETE FROM journal_edits WHERE seq = p_cutover_seq; + DELETE FROM journal WHERE seq = p_cutover_seq; + UPDATE register_head SET seq = p_cutover_seq - 1 WHERE id = 1; -- a new row version: every + -- older writer snapshot gets 40001 + IF v_sw.restore_prior IS NOT NULL THEN -- and the switch row as it was: + DELETE FROM register_switch WHERE id = 1; -- primary, present, its label and + INSERT INTO register_switch -- generation; no seq after b + SELECT * FROM jsonb_populate_record(NULL::register_switch, v_sw.restore_prior -> 'switch'); + RETURN p_cutover_seq - 1; + END IF; + UPDATE register_switch SET mode = 'files', marker_state = 'absent', marker_seq = NULL, + set_seq = p_cutover_seq - 1, + set_utc = date_trunc('second', clock_timestamp()), set_by_lane = p_lane, set_by_ws = p_ws + WHERE id = 1; + RETURN p_cutover_seq - 1; +END $f$; + +CREATE FUNCTION record_marker(p_client integer, p_seq bigint, p_commit text, p_ws text) + RETURNS text LANGUAGE plpgsql SECURITY DEFINER + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ +-- S4's read-back of an operator entry's push, recorded (F12). +DECLARE + v_ver schema_version; + v_sw register_switch; + v_new text; +BEGIN + PERFORM 1 FROM register_head WHERE id = 1 FOR UPDATE; -- serialises with the abort + SELECT * INTO v_ver FROM schema_version WHERE id = 1; + IF p_client > v_ver.version OR p_client < v_ver.writers_from THEN + RAISE EXCEPTION 'register schema % (writers from %); this client is %', v_ver.version, + v_ver.writers_from, p_client USING ERRCODE = 'LR003'; END IF; + SELECT * INTO v_sw FROM register_switch WHERE id = 1; + IF v_sw.marker_state NOT IN ('adding', 'removing') OR v_sw.marker_seq IS DISTINCT FROM p_seq THEN + RAISE EXCEPTION 'no unconfirmed operator entry at seq %', p_seq USING ERRCODE = 'LR002'; END IF; + v_new := CASE v_sw.marker_state WHEN 'adding' THEN 'present' ELSE 'absent' END; + UPDATE register_switch SET marker_state = v_new, marker_commit = p_commit, + set_utc = date_trunc('second', clock_timestamp()), set_by_ws = p_ws, + restore_prior = NULL -- confirmed: nothing left to put back + WHERE id = 1; + RETURN v_new; +END $f$; + +CREATE FUNCTION find_write(p_write_id uuid, p_not_after timestamptz, p_generation uuid, + p_lane text, p_verb text, p_args_sha256 text) + RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ +-- F3's one lookup (S2; D8, S1), at READ COMMITTED in a transaction the caller rolls back. +-- p_not_after is the largest not_after the write's commit calls carried, and p_generation, +-- p_lane, p_verb and p_args_sha256 are what those calls sent (NIT 1). It waits, holding no +-- lock, until the server's clock has passed p_not_after, at most 3 s (the call's statement_timeout +-- less its lock_timeout and 1 s); then it takes the head row's lock under the caller's +-- lock_timeout (55P03 while a transaction of the write may still be open), checks the clock again +-- under it, the exact complement of commit_write's step 9, then checks as commit_write does, in +-- its order (S-3): another generation is LR007, and so is an entry of this id for another lane, +-- verb or arguments. It returns the write's seq, or NULL if it is absent. The writer has no +-- UPDATE, so it cannot take that lock itself. +DECLARE + v_wait interval := p_not_after - clock_timestamp(); + v_gen uuid; -- the switch's generation, under the lock + v_old journal; -- the entry of this id, if any +BEGIN + IF p_not_after IS NULL THEN + RAISE EXCEPTION 'lookup of write %: no not_after', p_write_id USING ERRCODE = 'LR011'; END IF; + IF v_wait > interval '3 seconds' THEN -- LR011: further ahead than the wait's bound + RAISE EXCEPTION 'lookup of write %: not_after % is % ahead of the database clock, past the 3 s wait', + p_write_id, p_not_after, v_wait USING ERRCODE = 'LR011'; END IF; + IF v_wait > interval '0' THEN -- the wait, on the server's clock, before the lock + PERFORM pg_sleep(extract(epoch FROM v_wait) + 0.001); END IF; + PERFORM 1 FROM register_head WHERE id = 1 FOR UPDATE; + IF clock_timestamp() < p_not_after THEN -- step 9 commits only while this holds + RAISE EXCEPTION 'lookup of write %: the database clock % has not passed not_after % under the head row''s lock', + p_write_id, clock_timestamp(), p_not_after USING ERRCODE = 'LR011'; END IF; + SELECT generation INTO v_gen FROM register_switch WHERE id = 1; + IF p_generation IS DISTINCT FROM v_gen THEN -- commit_write's order: the generation first + RAISE EXCEPTION 'write % belongs to register generation %, not %', p_write_id, p_generation, + v_gen USING ERRCODE = 'LR007', DETAIL = 'generation'; END IF; + SELECT * INTO v_old FROM journal WHERE write_id = p_write_id; + IF NOT FOUND THEN RETURN NULL; END IF; -- absent + IF v_old.lane IS DISTINCT FROM p_lane OR v_old.verb IS DISTINCT FROM p_verb + OR v_old.args_sha256 IS DISTINCT FROM p_args_sha256 THEN -- then another write's entry + RAISE EXCEPTION 'write % is seq %, another write''s (F10)', p_write_id, v_old.seq + USING ERRCODE = 'LR007', DETAIL = 'another-write'; END IF; + RETURN v_old.seq; -- found: this write's own entry +END $f$; + +CREATE FUNCTION record_mirror_state(p_ws text, p_diverged_sha text, p_error text) + RETURNS void LANGUAGE plpgsql SECURITY DEFINER + SET search_path = lanes_register, pg_catalog, pg_temp AS $f$ +-- S5: its UPDATE takes the row's FOR NO KEY UPDATE lock, which conflicts with a rollback's FOR +-- SHARE, so it waits for that rollback to end, and a rollback that reaches the row after it waits +-- for it. It reads nothing before it writes and takes no other lock, so no explicit lock is needed. +BEGIN + UPDATE mirror_state SET -- each right-hand side reads the old row + found_utc = CASE WHEN diverged_sha IS NOT NULL OR p_diverged_sha IS NULL THEN found_utc + ELSE date_trunc('second', clock_timestamp()) END, + found_by_ws = CASE WHEN diverged_sha IS NOT NULL OR p_diverged_sha IS NULL THEN found_by_ws + ELSE p_ws END, + diverged_sha = coalesce(diverged_sha, p_diverged_sha), -- D16: the first finder's; only a + -- stray entry clears it + last_error = p_error, + last_error_utc = CASE WHEN p_error IS NULL THEN NULL + ELSE date_trunc('second', clock_timestamp()) END + WHERE id = 1; +END $f$; + +-- Migration 1's rows, from operations.md §2.4's bootstrap inputs (psql -v repo=… label=… lane=… ws=… script_sha256=…). +INSERT INTO schema_version (version, writers_from, readers_from, applied_utc) + VALUES (1, 1, 1, date_trunc('second', clock_timestamp())); +INSERT INTO register_head (seq) VALUES (-1); +INSERT INTO mirror_state DEFAULT VALUES; +INSERT INTO register_switch (mode, marker_state, generation, repository, database_label, set_utc, + set_seq, set_by_lane, set_by_ws) + VALUES ('files', 'absent', gen_random_uuid(), :'repo', :'label', + date_trunc('second', clock_timestamp()), -1, :'lane', :'ws'); +INSERT INTO migrations (version, script_sha256, by_lane, by_ws) + VALUES (1, :'script_sha256', :'lane', :'ws'); +COMMIT; -- then 1.4's statements after its CREATE ROLEs +""" + +#: Every migration this build ships, by number. Each script is one transaction, +#: sent whole as one `psql` call. +REGISTER_MIGRATIONS = { + 1: _REGISTER_M1_TABLES + "\n" + _REGISTER_M1_FUNCTIONS, +} + +#: The `schema_version` row a script leaves: migration 1's INSERT, or a later +#: script's UPDATE. +_REGISTER_VERSION_ROW_RE = re.compile( + r"INSERT INTO schema_version \(version, writers_from, readers_from, applied_utc\)\s+" + r"VALUES \((\d+), (\d+), (\d+)," + r"|UPDATE schema_version SET version = (\d+), writers_from = (\d+), readers_from = (\d+)") + + +def _register_migrations_consistent() -> None: + """THE ONE-NUMBER RULE INSIDE THIS FILE, checked before anything is sent. + The scripts are numbered 1 to `REGISTER_SCHEMA_VERSION` with no gap. The + floors keep `schema_version`'s CHECK. The newest script leaves the version + and floors the constants name. A build that breaks this is a defect, so + the error is not a refusal.""" + if sorted(REGISTER_MIGRATIONS) != list(range(1, REGISTER_SCHEMA_VERSION + 1)): + raise RuntimeError(f"register migrations {sorted(REGISTER_MIGRATIONS)} are not 1 to " + f"REGISTER_SCHEMA_VERSION {REGISTER_SCHEMA_VERSION}") + if not 1 <= REGISTER_READERS_FROM <= REGISTER_WRITERS_FROM <= REGISTER_SCHEMA_VERSION: + raise RuntimeError(f"register floors: readers from {REGISTER_READERS_FROM}, writers from " + f"{REGISTER_WRITERS_FROM}, version {REGISTER_SCHEMA_VERSION}") + rows = [tuple(int(n) for n in m.groups() if n is not None) + for m in _REGISTER_VERSION_ROW_RE.finditer(REGISTER_MIGRATIONS[REGISTER_SCHEMA_VERSION])] + want = (REGISTER_SCHEMA_VERSION, REGISTER_WRITERS_FROM, REGISTER_READERS_FROM) + if rows != [want]: + raise RuntimeError(f"register migration {REGISTER_SCHEMA_VERSION} leaves schema_version " + f"{rows}, not {want}") + + +def register_migration_sha256(version: int) -> str: + """The `script_sha256` that migration `version`'s `migrations` row records: + the sha256 of the script's UTF-8 bytes as shipped, with its psql variables + unexpanded. Every build that ships the same script records the same digest.""" + return hashlib.sha256(REGISTER_MIGRATIONS[version].encode("utf-8")).hexdigest() + + +def register_migration_plan(current: int | None) -> list[int]: + """The migrations that take a schema at `current` to + `REGISTER_SCHEMA_VERSION`, in order. `current` is the `schema_version` + row's `version`, or None where the schema `lanes_register` does not exist. + An empty list means `unchanged`. A schema newer than this build is refused + (operations.md §2.4: 2), and is never migrated down.""" + _register_migrations_consistent() + if current is None: + return list(range(1, REGISTER_SCHEMA_VERSION + 1)) + if not isinstance(current, int) or isinstance(current, bool) or current < 1: + raise ValueError(f"a register schema version is a number of at least 1, not {current!r}") + if current > REGISTER_SCHEMA_VERSION: + raise Refusal(f"the register's schema is at version {current}, newer than this " + f"{PROG}'s {REGISTER_SCHEMA_VERSION}: upgrade the tools. A schema is " + f"migrated forward, never down") + return list(range(current + 1, REGISTER_SCHEMA_VERSION + 1)) + + +def _register_migration_variables(repository: str, label: str, lane: str, + workstation: str) -> dict[str, str]: + """The bootstrap's inputs, as the scripts' psql variables. Each is checked + here against the CHECKs of design.md §1.2 that it meets, so that a bad + input is refused with 2 before anything is sent, rather than failing as a + 23514 inside the transaction.""" + values = {"repository": ("repo", repository), "label": ("label", label), + "lane": ("lane", lane), "workstation": ("ws", workstation)} + for what, (_name, value) in values.items(): + if not isinstance(value, str) or not value.strip(): + raise Refusal(f"bootstrap: the {what} is empty") + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in value): + raise Refusal(f"bootstrap: the {what} holds a control character") + if "@" in label: + raise Refusal("bootstrap: a database label holds no '@', so it is never a credential " + "(design.md §1.2, register_switch.database_label)") + return {name: value for name, value in values.values()} + + +def apply_register_migrations(run, current: int | None, *, repository: str, label: str, + lane: str, workstation: str) -> list[tuple[int, str]]: + """MIGRATE THE REGISTER FORWARD TO `REGISTER_SCHEMA_VERSION` (§1.5). This + is the bootstrap's step and nobody else's: `lanes-index bootstrap` calls + it, and no subcommand does. + + `current` is as `register_migration_plan` takes it. The other inputs are + the bootstrap's own (operations.md §2.4): `--repository`, `--label` and + `--lane`, and the host's workstation name. They fill the switch's `repository`, + `database_label`, `set_by_lane` and `set_by_ws`, and the `migrations` row's + `by_lane` and `by_ws`. + + `run(script, variables)` sends one script through Brett's admin + connection as ONE `psql` call: + - the script on stdin, with `-X` and `-v ON_ERROR_STOP=1`; + - one `-v =` per variable; + - `PGCLIENTENCODING=UTF8`, since `line_scopes`' pattern holds an em dash; + - no `--single-transaction`, since each script has its own BEGIN and + COMMIT. + It raises on any end but 0. The script's transaction has then rolled back, + so the schema stands at the version before it. + + Returns `(version, script_sha256)` for each migration applied, in order. + An empty list means `unchanged`. Bad inputs, and a schema newer than this + build, are refused before anything is sent.""" + plan = register_migration_plan(current) + variables = _register_migration_variables(repository, label, lane, workstation) + applied = [] + for version in plan: + digest = register_migration_sha256(version) + run(REGISTER_MIGRATIONS[version], dict(variables, script_sha256=digest)) + applied.append((version, digest)) + return applied + + +def register_version_refusal(version: int, writers_from: int, readers_from: int, *, + write: bool) -> str | None: + """§1.5'S WINDOW, as a client checks it before it reads or writes. A + writer goes on only where `writers_from` <= `REGISTER_SCHEMA_VERSION` <= + `version`. A reader goes on only where `readers_from` <= + `REGISTER_SCHEMA_VERSION` <= `version`. + + Returns None inside the window. Outside it, the returned refusal names + both numbers and the remedy, in the shape of `commit_write`'s LR003. The + exit code is the caller's own: 69 for writers, S3's readers and the + register commands; 2 for the guard; 1 for `managed-projection`.""" + floor, who = (writers_from, "writers") if write else (readers_from, "readers") + head = f"register schema {version} ({who} from {floor}); this client is {REGISTER_SCHEMA_VERSION}" + if REGISTER_SCHEMA_VERSION > version: + return f"{head}: the database is behind: run the bootstrap" + if REGISTER_SCHEMA_VERSION < floor: + return f"{head}: upgrade the tools" + return None + + +# §1.4'S ROLES AND GRANTS (design.md §1.4). Brett's admin connection sends +# §1.4's block in two parts, with migration 1 between them, as the block's own +# comment line says. `lanes-index bootstrap` calls, in this order: +# 1. `register_roles_query()`, read through that connection, for the names +# of §1.4's roles that exist already; +# 2. `apply_register_roles(run, found)`: the CREATE ROLE of each role the +# query did not find, then the admin's GRANT; +# 3. `apply_register_migrations` (above); +# 4. `apply_register_grants(run, database=)`: the rest of the block. +# Every statement goes as the design prints it, comments and all. The GRANT +# and the rest can run again. Nothing here is a subcommand, and nothing here +# sets a floor on a role: each login carries its own (`lanes-index login`). + +#: Design.md §1.4's SQL block, verbatim: the register's roles and GRANTs. +#: Above its comment line "-- Migration 1 (...) runs here, and commits. Then:" +#: are the CREATE ROLEs of the owner and the two groups, none of which can log +#: in, and of the indexer's login, then the admin's GRANT of the owner and the +#: indexer to itself, WITH INHERIT TRUE, SET TRUE. Below it are CONNECT and +#: USAGE, SELECT on the tables and, for `pg_dump`, on the sequences, the +#: default privileges, EXECUTE on the five writer functions and on +#: `render_file`, and `lanes_index`'s schema. Its one psql variable is `db`. +_REGISTER_ROLE_BLOCK = r"""CREATE ROLE lanes_register_owner NOLOGIN; -- owns lanes_register and its functions +CREATE ROLE lanes_register_writer NOLOGIN; -- REGISTER-WRITER: a group; each engineer's login joins it +CREATE ROLE lanes_register_reader NOLOGIN; -- READER: a group, as the writer's +CREATE ROLE lanes_indexer LOGIN; -- Amendment 14's indexer +GRANT lanes_register_owner, lanes_indexer TO CURRENT_USER -- PG16 gives a CREATEROLE admin + WITH INHERIT TRUE, SET TRUE; -- ADMIN only: SET for 1.2's AUTHORIZATION and + -- SET ROLE, INHERIT for the GRANTs below +-- Migration 1 (§1.2, §1.3.1) runs here, and commits. Then: +REVOKE ALL ON DATABASE :"db" FROM PUBLIC; -- the database Q22 names (psql -v db=…) +GRANT CONNECT ON DATABASE :"db" TO lanes_register_writer, lanes_register_reader, lanes_indexer; + +REVOKE ALL ON SCHEMA lanes_register FROM PUBLIC; +GRANT USAGE ON SCHEMA lanes_register TO lanes_register_writer, lanes_register_reader; +REVOKE ALL ON ALL TABLES IN SCHEMA lanes_register FROM PUBLIC; +GRANT SELECT ON ALL TABLES IN SCHEMA lanes_register TO lanes_register_writer, lanes_register_reader; +ALTER DEFAULT PRIVILEGES FOR ROLE lanes_register_owner IN SCHEMA lanes_register -- and a later + GRANT SELECT ON TABLES TO lanes_register_writer, lanes_register_reader; -- migration's +GRANT SELECT ON ALL SEQUENCES IN SCHEMA lanes_register TO lanes_register_reader; -- pg_dump reads +ALTER DEFAULT PRIVILEGES FOR ROLE lanes_register_owner IN SCHEMA lanes_register -- doc_lines' + GRANT SELECT ON SEQUENCES TO lanes_register_reader; -- identity +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA lanes_register FROM PUBLIC; +ALTER DEFAULT PRIVILEGES FOR ROLE lanes_register_owner -- global form: a per-schema REVOKE + REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC; -- cannot undo PUBLIC's default +GRANT EXECUTE ON FUNCTION lanes_register.commit_write(bigint, uuid, integer, uuid, jsonb), + lanes_register.switch_to_files(integer, bigint, text, text), + lanes_register.record_marker(integer, bigint, text, text), + lanes_register.find_write(uuid, timestamptz, uuid, text, text, text), + lanes_register.record_mirror_state(text, text, text) + TO lanes_register_writer; -- no INSERT, UPDATE, DELETE or DDL anywhere +GRANT EXECUTE ON FUNCTION lanes_register.render_file(text) + TO lanes_register_writer, lanes_register_reader; + +-- #160's schema: the indexer owns it and its open_write fills it; the reader reads it. +-- The register writer gets nothing in lanes_index, and the indexer nothing in lanes_register. +CREATE SCHEMA IF NOT EXISTS lanes_index AUTHORIZATION lanes_indexer; +REVOKE ALL ON SCHEMA lanes_index FROM PUBLIC; +GRANT USAGE ON SCHEMA lanes_index TO lanes_register_reader; +GRANT SELECT ON ALL TABLES IN SCHEMA lanes_index TO lanes_register_reader; -- any already there +ALTER DEFAULT PRIVILEGES FOR ROLE lanes_indexer IN SCHEMA lanes_index + GRANT SELECT ON TABLES TO lanes_register_reader; +ALTER DEFAULT PRIVILEGES FOR ROLE lanes_indexer IN SCHEMA lanes_index -- #160 has no sequence; + GRANT SELECT ON SEQUENCES TO lanes_register_reader; -- a later one, for pg_dump + +-- The floors are each login's own (the login step): a role's settings reach no member. +""" + +#: The block's comment line where migration 1 runs and commits: its split. +_REGISTER_ROLE_BLOCK_SPLIT = "-- Migration 1 (§1.2, §1.3.1) runs here, and commits. Then:\n" + +#: One of the block's CREATE ROLE statements: one line, its comment included. +_REGISTER_CREATE_ROLE_RE = re.compile( + r"CREATE ROLE ([a-z_][a-z0-9_]*) (?:NO)?LOGIN;[ \t]*(?:--[^\n]*)?\n") + + +def _register_sql_units(text: str) -> list[str]: + """`text` cut into units, byte for byte, by the layout of the design's SQL + blocks: a line that starts in column 0 starts a unit, the indented lines + after it belong to it, and a blank line is a unit of its own. So a + statement's unit holds its trailing comments, and its units sent + unchanged send the design's text unchanged. Text that does not cut so is + a defect of this build.""" + units = re.findall(r"[^ \t\n][^\n]*\n(?:[ \t][^\n]*\n)*|\n", text) + if "".join(units) != text: + raise RuntimeError("register SQL text does not cut into units: each unit starts in " + "column 0, and every line ends in a newline") + return units + + +def _register_role_block_parts() -> tuple[list[tuple[str, str]], str, str]: + """§1.4'S BLOCK, CUT WHERE MIGRATION 1 RUNS. Returns `(creates, grant, + rest)`, each the block's own text: + - `creates`: `(role, statement)` for each CREATE ROLE above the split, + in the block's order; + - `grant`: the admin's GRANT, the last statement above the split, with + its comment lines; + - `rest`: everything below the split. + A block that does not cut so is a defect of this build, so the error is + not a refusal.""" + head, split, rest = _REGISTER_ROLE_BLOCK.partition(_REGISTER_ROLE_BLOCK_SPLIT) + if (not split or not head.endswith("\n") + or _REGISTER_ROLE_BLOCK.count(_REGISTER_ROLE_BLOCK_SPLIT) != 1): + raise RuntimeError("the register's role block has no one line where migration 1 runs") + *units, grant = _register_sql_units(head) + creates = [] + for unit in units: + match = _REGISTER_CREATE_ROLE_RE.fullmatch(unit) + if not match: + raise RuntimeError(f"the register's role block holds {unit!r} before its GRANT, " + f"not a CREATE ROLE") + creates.append((match.group(1), unit)) + roles = [role for role, _statement in creates] + if (not roles or len(set(roles)) != len(roles) or not grant.startswith("GRANT ") + or " TO CURRENT_USER" not in grant): + raise RuntimeError(f"the register's role block creates {roles}, then {grant!r}: not " + f"distinct roles, then the admin's GRANT") + return creates, grant, rest + + +def register_role_names() -> list[str]: + """The roles §1.4 creates, in its order: the owner, the writer and reader + groups, and the indexer's login.""" + return [role for role, _statement in _register_role_block_parts()[0]] + + +def register_roles_query() -> str: + """THE `pg_roles` CHECK that guards §1.4's CREATE ROLEs: one query, read + through the admin connection just before `apply_register_roles`. Its rows + are the names of those of §1.4's roles that exist already, one per row. + The names are the block's own, plain identifiers by + `_REGISTER_CREATE_ROLE_RE`, so each is a literal as it stands.""" + names = ", ".join(f"'{role}'" for role in register_role_names()) + return f"SELECT rolname FROM pg_catalog.pg_roles WHERE rolname IN ({names}) ORDER BY rolname;\n" + + +def _register_role_selection(existing) -> tuple[list[str], list[str]]: + """The roles to create, and the statements to send, given `existing`.""" + if isinstance(existing, (str, bytes)): + raise TypeError("the roles found are a collection of names, not one string") + found = frozenset(existing) + if not all(isinstance(role, str) for role in found): + raise TypeError(f"the roles found are names, each a str: {sorted(map(repr, found))}") + creates, grant, _rest = _register_role_block_parts() + absent = [(role, statement) for role, statement in creates if role not in found] + statements = [statement for _role, statement in absent] + [grant] + return [role for role, _statement in absent], statements + + +def register_role_statements(existing) -> list[str]: + """§1.4'S FIRST PART, GUARDED: the statements the bootstrap sends before + migration 1. `existing` holds the role names `register_roles_query` found. + Returns the CREATE ROLE of each of §1.4's roles that `existing` lacks, in + the block's order, then the admin's GRANT, which goes every time since it + can run again. Each is the block's own text, byte for byte, comments and + all: none is wrapped, rewritten or put in a DO block. Where no role + exists, they are the block's first part whole. Nothing is sent here.""" + return _register_role_selection(existing)[1] + + +def apply_register_roles(run, existing) -> list[str]: + """SEND §1.4'S FIRST PART: the bootstrap's step before migration 1, which + `--roles-only` sends too. + + `existing` is as `register_role_statements` takes it, read just before. + `run(script, variables)` is the runner `apply_register_migrations` takes. + The statements go as one script, with no psql variable and, as in §1.4, + no BEGIN. The bootstrap's runner sends it with psql's + `--single-transaction` (lane 1's ruling for T109), so it commits whole, + and the owner role and the admin's SET on it then stand before migration + 1's `CREATE SCHEMA ... AUTHORIZATION lanes_register_owner` and its `SET + LOCAL ROLE` need them; a run that fails leaves nothing. + + Returns the roles it created, in the block's order; the others were + there already, `unchanged`. The GRANT is sent either way.""" + created, statements = _register_role_selection(existing) + run("".join(statements), {}) + return created + + +def apply_register_grants(run, *, database: str) -> None: + """SEND §1.4'S SECOND PART: the bootstrap's step after migration 1 has + committed. It is the rest of the block below its split line, whole: the + database's CONNECT, the schemas' USAGE, SELECT and default privileges, + EXECUTE on the writer functions and on `render_file`, and `lanes_index`'s + schema. + + `database` is the register's database, the one the admin connection + reaches and owns (operations.md §2.4). It goes as the psql variable `db`, + which the block reads as `:"db"`, an identifier psql quotes. It is + refused before anything is sent where it is empty or holds a control + character. Like the first part, the script carries no BEGIN, and the + bootstrap's runner sends it as one transaction. Each statement can run + again, so a run that fails is finished by the next.""" + if not isinstance(database, str) or not database.strip(): + raise Refusal("bootstrap: the database name is empty") + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in database): + raise Refusal("bootstrap: the database name holds a control character") + run(_register_role_block_parts()[2], {"db": database}) + + +# `LANES-INDEX BOOTSTRAP` (operations.md §2.4; FR-053, FR-054; T109). Brett's +# command for the register's roles and schema, run from his own shell and never +# from a lane session, through the admin service he names. In this order: +# 1. the refusals that need no connection: usage (64); an argument that +# carries a connection string or a password, `store=sqlite`, a +# `register_schema=` that is not a plain identifier or that a script does +# not render for, a stdout that is not a terminal without +# `--no-passwords`, and a workstation with no name (2); +# 2. ONE READ through the admin service: who the admin is and what it may +# do, which of §1.4's roles exist, the schema, the states §1.4's +# statements leave, and each privilege of §1.4's roles outside its scope. +# An admin that may not create roles or schemas, or does not own the +# database, a schema newer than this build, and a privilege outside a +# role's scope are refused (2) before anything is written; +# 3. §1.4's first part (T108), with the indexer's password where it creates +# that login, as one transaction; then that login's password-file line, +# printed once; +# 4. migration 1 (T107), rendered for `register_schema=` (lane 3's ruling +# (a), #165 6746655077), or `unchanged`; +# 5. §1.4's second part, rendered the same way, as one transaction; +# 6. one read that confirms the result: the indexer cannot write the +# register's tables, no role holds a privilege outside its scope, and +# the database-level states stand. +# With the switch at `primary`, as on a restored backup, it verifies, applies a +# pending migration, writes no label and "changes nothing else" (ops:434). +# `--roles-only` sends steps 3 and §1.4's three database-level statements, as +# one transaction (option (a), lane 3's ruling, #165 6727022920). +# +# ONE TRANSACTION A STEP, AND Y'S BYTES UNCHANGED (lane 1's ruling for T109). +# A part whose text carries no transaction control goes through psql's +# `--single-transaction`, with `-v ON_ERROR_STOP=1`, so a failed step leaves +# nothing. A migration carries its own BEGIN and COMMIT, and goes as T107's +# runner sends it. Every statement each step sends can run inside a +# transaction block: CREATE ROLE, GRANT, REVOKE, ALTER ROLE, ALTER DEFAULT +# PRIVILEGES and CREATE SCHEMA. +# +# THE ADMIN CONNECTION (ops:404; lane 3's ruling, #165 6747611042). `psql` +# reaches the database only through `PGSERVICE=` in its environment. +# Every inherited variable whose name begins `PG` is dropped first, and only +# `lanes-index`'s own fixed settings are set beside it. So only Brett's own +# `~/.pg_service.conf` defines the connection, his own `~/.pgpass` holds its +# password, and `lanes-index` never picks a database. + +#: The codes this subcommand exits with, by contracts/exit-codes.md §1's names. +#: `bootstrap` is the first new subcommand on this line to exit with them; #160's +#: own exits keep their literals. +EXIT_UNAVAILABLE = 69 + + +class RegisterUnavailable(Exception): + """The admin connection failed, or the database refused what was sent: + exit 69 (operations.md §2.4's exits). The step that was running rolled + back as a whole; a step before it stands, and a rerun goes on from it.""" + + +class _RegisterUsage(Exception): + """A bootstrap command line that is not its usage: exit 64, before any + connection is opened.""" + + +#: The schema Y's scripts name. A run on it renders each script to its own +#: bytes, so the rendered digest equals `script_sha256`. +REGISTER_TEMPLATE_SCHEMA = "lanes_register" + +#: §1.4's three roles whose names begin with the template's schema name. The +#: rendering never touches them, and they are the only such names a rendered +#: script may hold (lane 3's ruling (a)). +_REGISTER_SCHEMA_NAMED_ROLES = frozenset( + ("lanes_register_owner", "lanes_register_writer", "lanes_register_reader")) + +#: The indexer's login: §1.4's one login, and so the one password the +#: bootstrap ever generates. +_REGISTER_INDEXER = "lanes_indexer" + +#: The client timer of each admin `psql` call, as #160's own bound. D9 gives a +#: migration no timer (Y:3530); this one only ends a call that hangs. +_REGISTER_ADMIN_TIMEOUT_S = 300 + +#: The SCRAM-SHA-256 iteration count psql's `\password` uses by default (the +#: server's `scram_iterations`, 4096 in PostgreSQL 16). +_REGISTER_SCRAM_ITERATIONS = 4096 + +_REGISTER_TOKEN = r"(? --label --repository + --lane [--no-passwords] +{PROG} bootstrap --admin-service --roles-only [--no-passwords] + +Makes the SQL register's roles and schema, or migrates the schema forward, through +the libpq service in your own ~/.pg_service.conf, with its password in +your own ~/.pgpass (operations.md §2.4). The service names the register's +database; {PROG} never picks one. Run it from your shell: it prints the +indexer's password-file line once, only to a terminal. + + --label the database's label, written into the switch it creates + --repository the workspace repository the register serves + --lane the lane or person running it + --roles-only only the roles and the three database-level statements a + database dump does not carry, before a restore + --no-passwords for roles that log in by peer, trust or certificate + +Exit: 0 done · 2 refused, nothing written · 64 usage · 69 the admin connection +failed, or the database refused a step.""" + + +def render_register_script(text: str, schema: str, what: str = "the script") -> str: + """ONE OF Y'S SCRIPTS, RENDERED FOR `register_schema=` (lane 3's ruling + (a), #165 6746655077). Y's bytes stay the template. + + Whole identifier tokens `lanes_register` are replaced by `schema` where + they name the schema, and nowhere else: + - after `CREATE SCHEMA`, and after `ON SCHEMA` and `IN SCHEMA`, which + §1.4's second part uses; + - in every `search_path` list; + - as a qualifier, before a `.`. + So `lanes_register_owner`, `lanes_register_writer` and + `lanes_register_reader`, which are other tokens, stay as they are. After + rendering, a script that still names `lanes_register`, in any case, as + anything but those three roles is refused (2), and so is a schema that is + not a plain lower-case identifier. On `lanes_register` the result is the + template's own bytes.""" + if not isinstance(schema, str) or not SCHEMA_NAME_RE.match(schema): + raise Refusal("register_schema= is not a plain lower-case SQL identifier " + "([a-z_][a-z0-9_]{0,62})") + out = _REGISTER_SCHEMA_WORD_RE.sub(lambda m: m.group(1) + schema, text) + out = _REGISTER_SEARCH_PATH_RE.sub( + lambda m: m.group(1) + _REGISTER_TOKEN_RE.sub(lambda _t: schema, m.group(2)), out) + out = _REGISTER_QUALIFIER_RE.sub(lambda _m: schema, out) + left = sorted({m.group(0) for m in _REGISTER_NAME_RE.finditer(out) + if m.group(0).lower() != schema + and m.group(0).lower() not in _REGISTER_SCHEMA_NAMED_ROLES}) + if left: + raise Refusal(f"bootstrap: {what}, rendered for the schema {schema}, still names " + f"{', '.join(left)}, which is neither that schema nor one of the roles " + f"{', '.join(sorted(_REGISTER_SCHEMA_NAMED_ROLES))} (lane 3's ruling (a), " + f"#165 6746655077); this build cannot bootstrap that schema") + return out + + +def _register_rendered(schema: str) -> tuple[dict[str, str], str]: + """Every script the bootstrap may send that names the schema, rendered + before anything is sent: each migration, keyed by its template, and + §1.4's second part.""" + migrations = {REGISTER_MIGRATIONS[version]: render_register_script( + REGISTER_MIGRATIONS[version], schema, f"migration {version}") + for version in sorted(REGISTER_MIGRATIONS)} + rest = render_register_script(_register_role_block_parts()[2], schema, + "§1.4's second part") + return migrations, rest + + +def _register_execute_grants() -> dict[str, list[str]]: + """§1.4's EXECUTE grants, read from its own text: for each group, the + signatures it may execute, as `name(types)` without the schema.""" + grants: dict[str, list[str]] = {} + for unit in _register_sql_units(_register_role_block_parts()[2]): + if not unit.startswith("GRANT EXECUTE ON FUNCTION "): + continue + signatures = re.findall(r"lanes_register\.([a-z_][a-z0-9_]*\([^()]*\))", unit) + to = re.search(r"\n[ \t]+TO ([a-z_][a-z0-9_]*(?:, [a-z_][a-z0-9_]*)*);", unit) + if not signatures or not to: + raise RuntimeError(f"the register's role block's EXECUTE grant {unit!r} does not " + f"read as functions, then TO its roles") + for role in to.group(1).split(", "): + grants.setdefault(role, []).extend(signatures) + if set(grants) != {"lanes_register_writer", "lanes_register_reader"}: + raise RuntimeError(f"the register's role block grants EXECUTE to {sorted(grants)}") + return grants + + +def _register_roles_only_parts() -> list[str]: + """`--roles-only`'S THREE DATABASE-LEVEL STATEMENTS, each §1.4's own unit, + unchanged and in its order: Y:2243's `REVOKE ALL ON DATABASE ... FROM + PUBLIC`, Y:2244's `GRANT CONNECT`, and Y:2256-2257's global `ALTER + DEFAULT PRIVILEGES FOR ROLE lanes_register_owner REVOKE EXECUTE ON + FUNCTIONS FROM PUBLIC`. No database dump carries them (lane 3's ruling + (a), #165 6727022920).""" + units = _register_sql_units(_register_role_block_parts()[2]) + picks = [ + [u for u in units if u.startswith("REVOKE ALL ON DATABASE ")], + [u for u in units if u.startswith("GRANT CONNECT ON DATABASE ")], + [u for u in units if u.startswith("ALTER DEFAULT PRIVILEGES FOR ROLE lanes_register_owner ") + and " IN SCHEMA " not in u and "REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC" in u], + ] + if any(len(pick) != 1 for pick in picks): + raise RuntimeError("the register's role block does not hold exactly one of each of " + "the three database-level statements") + return [pick[0] for pick in picks] + + +def register_scram_verifier(password: str, salt: bytes | None = None, + iterations: int = _REGISTER_SCRAM_ITERATIONS) -> str: + """A SCRAM-SHA-256 verifier for `password`, computed here, on the client, + as psql's `\\password` computes it (RFC 5802, RFC 7677; PostgreSQL's + `scram_build_secret`): a random 16-byte salt, PBKDF2-HMAC-SHA-256, then + `SCRAM-SHA-256$:$:`, each part in + base64. The server stores it as given, so neither its log nor a failed + statement ever holds the password itself. The bootstrap's passwords are + ASCII letters, digits, `-` and `_`, which SASLprep leaves as they are.""" + import base64 + import hmac + import secrets + if salt is None: + salt = secrets.token_bytes(16) + salted = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) + client_key = hmac.new(salted, b"Client Key", hashlib.sha256).digest() + stored_key = hashlib.sha256(client_key).digest() + server_key = hmac.new(salted, b"Server Key", hashlib.sha256).digest() + + def b64(raw: bytes) -> str: + return base64.b64encode(raw).decode("ascii") + + return f"SCRAM-SHA-256${iterations}:{b64(salt)}${b64(stored_key)}:{b64(server_key)}" + + +def _register_pgpass_line(database: str, login: str, password: str) -> str: + """A libpq password-file line for `login` on `database`, at any host and + port: the file holds this one line, and the URL beside it names the host. + `:` and `\\` in a field are escaped, as libpq reads them.""" + def field(value: str) -> str: + return value.replace("\\", "\\\\").replace(":", "\\:") + return f"*:*:{field(database)}:{field(login)}:{field(password)}" + + +def _register_admin_env(service: str) -> dict: + """THE ADMIN `psql`'S ENVIRONMENT (ops:404; lane 3's ruling, #165 + 6747611042): every inherited variable whose name begins `PG` dropped, then + `PGSERVICE=` and `lanes-index`'s own fixed settings, nothing else + that begins `PG`. A `connect_timeout=` in the service file wins over + `PGCONNECT_TIMEOUT` (libpq reads the service first), so 2, D9's `c` where + none is measured, holds only where the service names none.""" + env = {key: value for key, value in os.environ.items() if not key.startswith("PG")} + env["PGSERVICE"] = service + env["PGAPPNAME"] = PROG + env["PGCLIENTENCODING"] = "UTF8" + env["PGCONNECT_TIMEOUT"] = "2" + return env + + +def _register_psql_error(proc: subprocess.CompletedProcess) -> str: + lines = [_REGISTER_VERIFIER_RE.sub("SCRAM-SHA-256$", line.strip()) + for line in (proc.stderr or "").splitlines() if line.strip()] + for line in lines: + if re.search(r"\b(ERROR|FATAL|PANIC):|psql: error:", line): + return line + return lines[-1] if lines else f"psql exited {proc.returncode}" + + +def _register_admin_psql(service: str, script: str, variables: dict, *, + single_transaction: bool) -> str: + """ONE `psql` CALL THROUGH THE ADMIN SERVICE: the script on stdin (`-f -`), + `-X`, `-q`, `-w` (never a password prompt), `-v ON_ERROR_STOP=1`, one + `-v =` per variable, and, for a script with no transaction + control of its own, `--single-transaction`, so the call commits whole or + leaves nothing. No connection string and no service name is in its + argument list. + + Returns its stdout. Any end but 0, a timer that runs out, or no `psql` is + `RegisterUnavailable` (69), with psql's error, every verifier in it + masked. On success, a WARNING psql printed is passed on; a NOTICE is not.""" + psql = shutil.which("psql") + if not psql: + raise RegisterUnavailable("there is no psql on PATH") + argv = [psql, "-X", "-q", "-w", "-v", "ON_ERROR_STOP=1"] + if single_transaction: + argv.append("--single-transaction") + for name, value in variables.items(): + argv += ["-v", f"{name}={value}"] + argv += ["-f", "-"] + try: + proc = subprocess.run(argv, input=script, capture_output=True, encoding="utf-8", + errors="replace", check=False, env=_register_admin_env(service), + timeout=_REGISTER_ADMIN_TIMEOUT_S) + except subprocess.TimeoutExpired: + raise RegisterUnavailable(f"psql did not answer within {_REGISTER_ADMIN_TIMEOUT_S} s") + except OSError as exc: + raise RegisterUnavailable(f"psql could not be run: {exc}") + if proc.returncode != 0: + raise RegisterUnavailable(_register_psql_error(proc)) + for line in (proc.stderr or "").splitlines(): + if re.search(r"\bWARNING:", line): + note(_REGISTER_VERIFIER_RE.sub("SCRAM-SHA-256$", line.strip())) + return proc.stdout + + +def _register_reads(service: str, tag: str, queries: list[str], *, + command: str = "bootstrap") -> list[list[list]]: + """Several SELECTs through the admin service in ONE `psql` call and one + transaction, each answered as TEXT-format COPY rows, as `_query_many` + reads them. Nothing is written. `command` names the subcommand reading, + `bootstrap` or `login`, in the script's first line.""" + lines = [f"-- lanes-index {command}: {tag}"] + for query in queries: + lines.append(f"COPY ({query}) TO STDOUT;") + lines.append("\\echo '\\036LANES-INDEX-NEXT'") + out = _register_admin_psql(service, "\n".join(lines) + "\n", {}, single_transaction=True) + results: list[list[list]] = [] + current: list[list] = [] + for line in out.split("\n"): + if line == _REGISTER_NEXT: + results.append(current) + current = [] + continue + if line: + current.append([_pg_unescape(field) for field in line.split("\t")]) + if len(results) != len(queries): + raise RegisterUnavailable(f"psql answered {len(results)} of the {len(queries)} reads " + f"of the {command}'s {tag}") + return results + + +def _register_names_sql(names) -> str: + return ", ".join(_pg_quote(name) for name in names) + + +def _register_admin_query() -> str: + """Who the admin is, and what it may do (operations.md §2.4's refusals).""" + return ("SELECT current_user::text, current_database()::text, " + "a.rolsuper OR a.rolcreaterole, " + "pg_catalog.has_database_privilege(current_database(), 'CREATE'), " + "pg_catalog.pg_has_role(current_user, d.datdba, 'USAGE'), " + "current_setting('server_version_num') " + "FROM pg_catalog.pg_roles a, pg_catalog.pg_database d " + "WHERE a.rolname = current_user AND d.datname = current_database()") + + +def _register_schema_query(schema: str) -> str: + """The schema, if it exists, and whether it holds a register's three + first tables.""" + return (f"SELECT n.nspname::text, " + f"to_regclass({_pg_quote(schema + '.schema_version')}) IS NOT NULL, " + f"to_regclass({_pg_quote(schema + '.register_switch')}) IS NOT NULL, " + f"to_regclass({_pg_quote(schema + '.register_head')}) IS NOT NULL " + f"FROM pg_catalog.pg_namespace n WHERE n.nspname = {_pg_quote(schema)}") + + +def _register_indexer_login_query() -> str: + """Whether `lanes_indexer`, where it exists, can log in: one row, + `rolcanlogin`, or none where the role is absent. `url=` logs in as it + (design.md §1.4), so an existing indexer that cannot log in is refused + before any write (lane 3's ruling, opensoft/openRepoTools#165 + 6894116246).""" + return ("SELECT rolcanlogin FROM pg_catalog.pg_roles " + f"WHERE rolname = {_pg_quote(_REGISTER_INDEXER)}") + + +def _register_states_query() -> str: + """THE STATES §1.4'S STATEMENTS LEAVE, each true where it already stands: + PUBLIC holds no privilege on the database; the two groups and the indexer + each hold CONNECT; the owner's global default privileges give PUBLIC no + EXECUTE; and the admin holds the owner and the indexer WITH INHERIT TRUE, + SET TRUE. So each line prints `created` or `unchanged`.""" + roles = register_role_names() + owner, indexer = roles[0], _REGISTER_INDEXER + groups = _register_names_sql(roles[1:3] + [indexer]) + database_acl = ("FROM pg_catalog.pg_database d CROSS JOIN LATERAL pg_catalog.aclexplode(" + "coalesce(d.datacl, pg_catalog.acldefault('d', d.datdba))) AS e " + "WHERE d.datname = current_database()") + return (f"SELECT NOT EXISTS (SELECT 1 {database_acl} AND e.grantee = 0), " + f"(SELECT count(DISTINCT e.grantee) {database_acl} AND e.privilege_type = 'CONNECT' " + f"AND e.grantee IN (SELECT a.oid FROM pg_catalog.pg_roles a " + f"WHERE a.rolname IN ({groups}))) = 3, " + f"EXISTS (SELECT 1 FROM pg_catalog.pg_default_acl x " + f"JOIN pg_catalog.pg_roles a ON a.oid = x.defaclrole " + f"WHERE a.rolname = {_pg_quote(owner)} AND x.defaclnamespace = 0 " + f"AND x.defaclobjtype = 'f' AND NOT EXISTS (SELECT 1 FROM " + f"pg_catalog.aclexplode(x.defaclacl) AS e WHERE e.grantee = 0 " + f"AND e.privilege_type = 'EXECUTE')), " + f"(SELECT count(DISTINCT b.rolname) FROM pg_catalog.pg_auth_members m " + f"JOIN pg_catalog.pg_roles b ON b.oid = m.roleid " + f"JOIN pg_catalog.pg_roles a ON a.oid = m.member " + f"WHERE a.rolname = current_user " + f"AND b.rolname IN ({_register_names_sql([owner, indexer])}) " + f"AND coalesce((to_jsonb(m) ->> 'inherit_option')::boolean, false) " + f"AND coalesce((to_jsonb(m) ->> 'set_option')::boolean, false)) = 2") + + +def _register_fingerprint_query(schema: str) -> str: + """One digest of every privilege in the register's schema and in + `lanes_index`: the schemas', the relations', the functions' and the + default privileges. Equal before and after §1.4's second part means it + changed nothing.""" + names = _register_names_sql([schema, "lanes_index"]) + return ("SELECT md5(coalesce(string_agg(x.line, chr(10) ORDER BY x.line), '')) FROM (" + f"SELECT 'schema ' || n.nspname || ' ' || coalesce(n.nspacl::text, '-') AS line " + f"FROM pg_catalog.pg_namespace n WHERE n.nspname IN ({names}) " + f"UNION ALL SELECT 'relation ' || n.nspname || '.' || c.relname || ' ' " + f"|| coalesce(c.relacl::text, '-') FROM pg_catalog.pg_class c " + f"JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + f"WHERE n.nspname IN ({names}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S') " + f"UNION ALL SELECT 'function ' || n.nspname || '.' || p.proname || '(' " + f"|| pg_catalog.oidvectortypes(p.proargtypes) || ') ' || coalesce(p.proacl::text, '-') " + f"FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " + f"WHERE n.nspname IN ({names}) " + f"UNION ALL SELECT 'default ' || da.defaclrole::regrole::text || ' ' || n.nspname " + f"|| ' ' || da.defaclobjtype::text || ' ' || da.defaclacl::text " + f"FROM pg_catalog.pg_default_acl da " + f"JOIN pg_catalog.pg_namespace n ON n.oid = da.defaclnamespace " + f"WHERE n.nspname IN ({names})) AS x(line)") + + +def _register_scope_queries(schema: str) -> list[str]: + """EACH PRIVILEGE OF §1.4'S ROLES OUTSIDE ITS SCOPE (operations.md §2.4: + "a role holds a privilege outside its scope ... named and never revoked + silently"). Four reads, each a row `(role, what it holds, class)`: + - an attribute: SUPERUSER, CREATEROLE, CREATEDB, REPLICATION or + BYPASSRLS on any of the four, or LOGIN on the owner or a group; + - a membership of any of the four in any role; + - a grant, by the object's ACL with PostgreSQL's defaults filled in, to + a group, the indexer or PUBLIC, beyond §1.4's matrix: + - REGISTER-WRITER: USAGE on the schema, SELECT on its tables but + not its sequences, which §1.4 grants READER alone, EXECUTE on + the five writer functions and `render_file`, CONNECT; nothing in + `lanes_index`; + - READER: USAGE and SELECT in both schemas, EXECUTE on + `render_file`, CONNECT; + - the indexer: anything in `lanes_index`, CONNECT; nothing in the + register's schema; + - PUBLIC: nothing; + and a group's privilege in that matrix, or the indexer's CONNECT, + held WITH GRANT OPTION, which §1.4 never gives, is beyond it too, + named as `holds WITH GRANT OPTION on `; the + indexer's own privileges in `lanes_index`, its owner's, carry it; + - a table of the register's schema that a group or the indexer can + write by any route, and a table of `lanes_index` the writer can: + operations.md §2.4's "the indexer cannot write the register's + tables". + The class marks PUBLIC's PostgreSQL defaults, CONNECT and TEMPORARY on the + database and EXECUTE on a function, which §1.4's REVOKEs remove.""" + roles = register_role_names() + four = _register_names_sql(roles) + three = _register_names_sql(roles[1:]) + s = _pg_quote(schema) + fns = [] + for role, signatures in sorted(_register_execute_grants().items()): + who = "writer" if role == roles[1] else "reader" + for signature in signatures: + fns.append(f"(to_regprocedure({_pg_quote(schema + '.' + signature)})::oid, " + f"{_pg_quote(who)})") + attributes = ( + "SELECT a.rolname::text, 'has the attribute ' || x.attr, '' " + "FROM pg_catalog.pg_roles a CROSS JOIN LATERAL (VALUES " + "('SUPERUSER', a.rolsuper), ('CREATEROLE', a.rolcreaterole), " + "('CREATEDB', a.rolcreatedb), ('REPLICATION', a.rolreplication), " + "('BYPASSRLS', a.rolbypassrls), " + f"('LOGIN', a.rolcanlogin AND a.rolname <> {_pg_quote(_REGISTER_INDEXER)})) AS x(attr, held) " + f"WHERE a.rolname IN ({four}) AND x.held") + memberships = ( + "SELECT a.rolname::text, 'is a member of the role ' || quote_ident(b.rolname), '' " + "FROM pg_catalog.pg_auth_members m " + "JOIN pg_catalog.pg_roles a ON a.oid = m.member " + "JOIN pg_catalog.pg_roles b ON b.oid = m.roleid " + f"WHERE a.rolname IN ({four})") + grants = ( + "WITH g(oid, name, who) AS (" + "SELECT a.oid, a.rolname::text, v.who FROM (VALUES " + f"({_pg_quote(roles[1])}, 'writer'), ({_pg_quote(roles[2])}, 'reader'), " + f"({_pg_quote(_REGISTER_INDEXER)}, 'indexer')) AS v(rolname, who) " + "JOIN pg_catalog.pg_roles a ON a.rolname = v.rolname " + "UNION ALL SELECT 0::oid, 'PUBLIC', 'public'), " + "ns(oid, nspname, half, acl) AS (" + f"SELECT n.oid, n.nspname::text, CASE WHEN n.nspname = {s} THEN 'register' " + "ELSE 'index' END, coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner)) " + f"FROM pg_catalog.pg_namespace n WHERE n.nspname IN ({s}, 'lanes_index')), " + "obj(kind, half, oid, label, acl) AS (" + "SELECT 'schema'::text, ns.half, ns.oid, 'schema ' || quote_ident(ns.nspname), ns.acl " + "FROM ns " + "UNION ALL SELECT CASE WHEN c.relkind = 'S' THEN 'sequence' ELSE 'table' END, " + "ns.half, c.oid, CASE WHEN c.relkind = 'S' THEN 'sequence ' ELSE 'table ' END " + "|| quote_ident(ns.nspname) || '.' || quote_ident(c.relname), " + "coalesce(c.relacl, pg_catalog.acldefault(" + "CASE WHEN c.relkind = 'S' THEN 's' ELSE 'r' END::\"char\", c.relowner)) " + "FROM ns JOIN pg_catalog.pg_class c ON c.relnamespace = ns.oid " + "WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S') " + "UNION ALL SELECT 'function', ns.half, p.oid, 'function ' || quote_ident(ns.nspname) " + "|| '.' || quote_ident(p.proname) || '(' || pg_catalog.oidvectortypes(p.proargtypes) " + "|| ')', coalesce(p.proacl, pg_catalog.acldefault('f', p.proowner)) " + "FROM ns JOIN pg_catalog.pg_proc p ON p.pronamespace = ns.oid " + "UNION ALL SELECT 'database', 'database', d.oid, 'database ' || quote_ident(d.datname), " + "coalesce(d.datacl, pg_catalog.acldefault('d', d.datdba)) " + "FROM pg_catalog.pg_database d WHERE d.datname = current_database()), " + f"fn(oid, who) AS (VALUES {', '.join(fns)}) " + "SELECT g.name, 'holds ' || e.privilege_type || CASE WHEN e.is_grantable " + "THEN ' WITH GRANT OPTION' ELSE '' END || ' on ' || o.label, " + "CASE WHEN g.who = 'public' AND o.kind = 'database' " + "AND e.privilege_type IN ('CONNECT', 'TEMPORARY') THEN 'public-default-database' " + "WHEN g.who = 'public' AND o.kind = 'function' AND o.half = 'register' " + "AND e.privilege_type = 'EXECUTE' THEN 'public-default-function' ELSE '' END " + "FROM obj o CROSS JOIN LATERAL pg_catalog.aclexplode(o.acl) AS e " + "JOIN g ON g.oid = e.grantee " + "WHERE NOT (" + "(g.who = 'writer' AND NOT e.is_grantable AND (" + "(o.half = 'register' AND o.kind = 'schema' AND e.privilege_type = 'USAGE') " + "OR (o.half = 'register' AND o.kind = 'table' " + "AND e.privilege_type = 'SELECT') " + "OR (o.half = 'register' AND o.kind = 'function' AND e.privilege_type = 'EXECUTE' " + "AND o.oid IN (SELECT fn.oid FROM fn WHERE fn.who = 'writer' AND fn.oid IS NOT NULL)) " + "OR (o.kind = 'database' AND e.privilege_type = 'CONNECT'))) " + "OR (g.who = 'reader' AND NOT e.is_grantable AND (" + "(o.kind = 'schema' AND e.privilege_type = 'USAGE') " + "OR (o.kind IN ('table', 'sequence') AND e.privilege_type = 'SELECT') " + "OR (o.half = 'register' AND o.kind = 'function' AND e.privilege_type = 'EXECUTE' " + "AND o.oid IN (SELECT fn.oid FROM fn WHERE fn.who = 'reader' AND fn.oid IS NOT NULL)) " + "OR (o.kind = 'database' AND e.privilege_type = 'CONNECT'))) " + "OR (g.who = 'indexer' AND (o.half = 'index' " + "OR (o.kind = 'database' AND e.privilege_type = 'CONNECT' " + "AND NOT e.is_grantable))))") + writes = ( + "SELECT a.rolname::text, 'can write the table ' || quote_ident(n.nspname) || '.' " + "|| quote_ident(c.relname) || ' (INSERT, UPDATE, DELETE or TRUNCATE)', '' " + "FROM pg_catalog.pg_roles a CROSS JOIN pg_catalog.pg_class c " + "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + f"WHERE a.rolname IN ({three}) AND c.relkind IN ('r', 'p') " + f"AND (n.nspname = {s} OR (n.nspname = 'lanes_index' " + f"AND a.rolname = {_pg_quote(roles[1])})) " + "AND pg_catalog.has_table_privilege(a.oid, c.oid, 'INSERT, UPDATE, DELETE, TRUNCATE')") + return [attributes, memberships, grants, writes] + + +def _register_scope_faults(rows: list[list], phase: str) -> list[str]: + """The faults among the scope reads' rows, for `phase`: + - `before`, ahead of any statement: PUBLIC's PostgreSQL defaults, which + §1.4's own REVOKEs remove, are not faults yet; + - `roles-only`, after `--roles-only`: PUBLIC's default EXECUTE on the + schema's functions is the full bootstrap's to remove; + - `all`, after the full bootstrap, and with the switch at `primary`, + where nothing is sent again: every row is a fault.""" + ignore = {"before": {"public-default-database", "public-default-function"}, + "roles-only": {"public-default-function"}, + "all": set()}[phase] + return [f"{row[0]} {row[1]}" for row in rows if len(row) >= 3 and row[2] not in ignore] + + +def _register_refuse_scope(faults: list[str]) -> None: + if faults: + raise Refusal("bootstrap: a role holds a privilege outside its scope, which the " + "bootstrap names and never revokes (operations.md §2.4); revoke it by " + "hand, then run it again:\n - " + "\n - ".join(faults)) + + +def _register_flag(value: str) -> bool: + if value not in ("t", "f"): + raise RegisterUnavailable(f"psql answered {value!r} where a boolean was asked") + return value == "t" + + +def _register_one_row(rows: list[list], width: int, what: str) -> list: + if len(rows) != 1 or len(rows[0]) != width: + raise RegisterUnavailable(f"psql answered {len(rows)} rows for {what}, not one row of " + f"{width} fields") + return rows[0] + + +def _register_states(rows: list[list]) -> dict: + row = _register_one_row(rows, 4, "the role block's states") + return dict(zip(("public", "connect", "defaults", "grant"), map(_register_flag, row))) + + +def _register_probe(service: str, schema: str) -> dict: + """THE BOOTSTRAP'S FIRST READ, through the admin service, before anything + is written.""" + queries = [_register_admin_query(), + register_roles_query().rstrip().rstrip(";"), + _register_schema_query(schema), + _register_states_query(), + _register_fingerprint_query(schema), + _register_indexer_login_query()] + _register_scope_queries(schema) + res = _register_reads(service, "probe", queries) + admin = _register_one_row(res[0], 6, "the admin") + schema_rows = res[2] + if len(schema_rows) > 1 or (schema_rows and len(schema_rows[0]) != 4): + raise RegisterUnavailable("psql answered more than one schema row") + return { + "user": admin[0], "database": admin[1], + "create_roles": _register_flag(admin[2]), "create_schemas": _register_flag(admin[3]), + "owns": _register_flag(admin[4]), "server": admin[5], + "roles": {row[0] for row in res[1] if row}, + "schema": None if not schema_rows else [_register_flag(v) for v in schema_rows[0][1:]], + "states": _register_states(res[3]), + "fingerprint": _register_one_row(res[4], 1, "the privileges' digest")[0], + "indexer_login": None if not res[5] else _register_flag( + _register_one_row(res[5], 1, "the indexer's LOGIN")[0]), + "scope": [row for rows in res[6:] for row in rows], + } + + +def _register_state(service: str, schema: str) -> dict: + """The register's own rows, where its schema exists: its version and + floors, the switch and the head.""" + res = _register_reads(service, "state", [ + f"SELECT version, writers_from, readers_from FROM {schema}.schema_version", + f"SELECT mode, marker_state, database_label, set_seq FROM {schema}.register_switch", + f"SELECT seq FROM {schema}.register_head"]) + for rows, what in zip(res, ("schema_version", "register_switch", "register_head")): + if len(rows) != 1: + raise Refusal(f"bootstrap: {schema}.{what} holds {len(rows)} rows, not one: this " + f"schema is not a register this tool made") + version = _register_one_row(res[0], 3, "schema_version") + switch = _register_one_row(res[1], 4, "register_switch") + head = _register_one_row(res[2], 1, "register_head") + try: + current = int(version[0]) + except (TypeError, ValueError): + raise RegisterUnavailable(f"psql answered the version {version[0]!r}") + return {"version": current, "mode": switch[0], "marker": switch[1], "label": switch[2], + "set_seq": switch[3], "head": head[0]} + + +def _register_confirm(service: str, schema: str) -> dict: + """THE BOOTSTRAP'S LAST READ: the states, the privileges' digest and the + scope reads again, after its statements.""" + res = _register_reads(service, "check", [_register_states_query(), + _register_fingerprint_query(schema)] + + _register_scope_queries(schema)) + return {"states": _register_states(res[0]), + "fingerprint": _register_one_row(res[1], 1, "the privileges' digest")[0], + "scope": [row for rows in res[2:] for row in rows]} + + +def _register_store_named_sqlite(cfg: dict) -> bool: + """Whether the configuration's own `store=` line says `sqlite`. A file + that names no `store=`, or no file, does not: `load_config` defaults the + store from `url=`, the index half's, and an engineer's file names no + `url=` (contracts/config.md §3.2).""" + if not cfg.get("present"): + return False + try: + with open(cfg["path"], encoding="utf-8") as handle: + lines = handle.read().splitlines() + except (OSError, UnicodeDecodeError) as exc: + raise Refusal(f"the configuration {cfg['path']} cannot be read: {exc}") + named = "" + for raw in lines: + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, value = (part.strip() for part in line.split("=", 1)) + if key == "store": + if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": + value = value[1:-1] + named = value + return named == "sqlite" + + +def _register_refuse_argument(flag: str, value: str, *, command: str = "bootstrap") -> None: + """An argument that carries a connection string or a password, such as a + `key=value` pair or a URI, is refused (2), and never echoed. `command` + names the subcommand refusing, `bootstrap` or `login`.""" + if "=" in value or "://" in value or _url_has_password(value): + raise Refusal(f"{command}: {flag} carries a connection string or a password (a " + f"`key=value` pair or a URI). The admin connection is a service name " + f"in your own ~/.pg_service.conf, and no argument carries a connection") + if flag == "--admin-service" and not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,62}", value): + raise Refusal(f"{command}: --admin-service is not a plain service name: letters, " + "digits, '_', '.' and '-', as a section of ~/.pg_service.conf") + + +def _register_workstation() -> str: + """This workstation's name, for the switch's `set_by_ws` and the + `migrations` row's `by_ws`. `$LANES_WORKSTATION`, where it is set, is + the name: it is the seam `lanes-edit.sh workstation` answers with first, + as it stands. Otherwise that command is asked, and it needs the + workspace repository. A container with no name is refused, as every + writer of the workstation column refuses it (R-A11-14).""" + seam = os.environ.get("LANES_WORKSTATION", "") + if seam: + return seam + try: + name, how = this_workstation() + except StoreUnusable as exc: + raise Refusal(f"bootstrap: this workstation's name cannot be read ({exc.detail})") + if how == "container-unset": + raise Refusal("bootstrap: this is a container and LANES_WORKSTATION is not set, so " + "the switch and the migrations row would be stamped with the " + "container's own id (Amendment 11, R-A11-14). Run it from the host's " + "shell, or export LANES_WORKSTATION") + return name + + +def _bootstrap_args(args: list[str]) -> dict | None: + """The bootstrap's flags; None for `--help`. First, as `login`'s, no + argument may carry a connection string or a password, wherever it + stands, a positional one or an unknown option's value among them (2, + never echoed); then its usage (64). `_bootstrap` refuses its values. + An unknown argument, positional or not, is named in `ready`'s form (lane + 3's ruling, opensoft/openRepoTools#165 6894208108): quoted only where all + of it matches `--?[A-Za-z][A-Za-z-]{0,30}`, and otherwise "unknown + argument that is not one of its flags", so no value is echoed.""" + for arg in args: + value = arg.partition("=")[2] if arg.startswith("--") and "=" in arg else arg + _register_refuse_argument("an argument", value) + opts: dict = {"--admin-service": None, "--label": None, "--repository": None, + "--lane": None, "--roles-only": False, "--no-passwords": False} + i = 0 + while i < len(args): + arg = args[i] + if arg in ("-h", "--help"): + return None + name, eq, value = arg.partition("=") + if name in ("--admin-service", "--label", "--repository", "--lane"): + if not eq: + value = args[i + 1] if i + 1 < len(args) else "" + i += 1 + if not value: + raise _RegisterUsage(f"bootstrap: {name} needs a value") + if opts[name] is not None: + raise _RegisterUsage(f"bootstrap: {name} is given twice") + opts[name] = value + elif arg in ("--roles-only", "--no-passwords"): + opts[arg] = True + else: + shown = (f"'{arg}'" if re.fullmatch(r"--?[A-Za-z][A-Za-z-]{0,30}", arg) + else "that is not one of its flags") + raise _RegisterUsage(f"bootstrap: unknown argument {shown}") + i += 1 + if opts["--admin-service"] is None: + raise _RegisterUsage("bootstrap needs --admin-service ") + if not opts["--roles-only"]: + missing = [flag for flag in ("--label", "--repository", "--lane") if opts[flag] is None] + if missing: + raise _RegisterUsage(f"bootstrap needs {', '.join(missing)} (or --roles-only)") + return opts + + +def _bootstrap_say(what: str, created: bool, detail: str = "") -> None: + say(f"{what}: {'created' if created else 'unchanged'}" + (f" ({detail})" if detail else "")) + + +def cmd_bootstrap(args: list[str]) -> int: + """`lanes-index bootstrap` (operations.md §2.4): its exits, by the + contract's constants.""" + try: + opts = _bootstrap_args(args) + except _RegisterUsage as exc: + note(f"{exc} - see {PROG} bootstrap --help") + return EXIT_USAGE + except Refusal as exc: + note(f"REFUSED: {exc}") + return EXIT_REFUSED + if opts is None: + say(_BOOTSTRAP_USAGE) + return EXIT_OK + try: + return _bootstrap(opts) + except Refusal as exc: + note(f"REFUSED: {exc}") + return EXIT_REFUSED + except RegisterUnavailable as exc: + note(f"bootstrap: the admin connection failed, or the database refused a step: {exc}") + return EXIT_UNAVAILABLE + + +def _bootstrap(opts: dict) -> int: + service = opts["--admin-service"] + roles_only = opts["--roles-only"] + for flag in ("--admin-service", "--label", "--repository", "--lane"): + if opts[flag] is not None: + _register_refuse_argument(flag, opts[flag]) + if not opts["--no-passwords"] and not sys.stdout.isatty(): + raise Refusal("bootstrap: stdout is not a terminal. It prints a password only to a " + "terminal, so that no transcript, log or pipe holds one: run it from your " + "shell, or pass --no-passwords for roles that need none") + cfg = load_config() + if _register_store_named_sqlite(cfg): + raise Refusal(f"bootstrap: {cfg['path']} names store=sqlite: the register is shared " + f"by workstations, and SQLite is one disk") + schema = cfg.get("register_schema") or REGISTER_TEMPLATE_SCHEMA + if not SCHEMA_NAME_RE.match(schema): + raise Refusal("register_schema= is not a plain lower-case SQL identifier " + "([a-z_][a-z0-9_]{0,62})") + if schema.startswith("pg_") or schema in ("lanes_index", cfg.get("schema") or "lanes_index"): + raise Refusal("bootstrap: register_schema= is the index half's schema or a name " + "PostgreSQL reserves; the register takes a schema of its own") + migrations, rest = _register_rendered(schema) + workstation = "" + if not roles_only: + workstation = _register_workstation() + _register_migration_variables(opts["--repository"], opts["--label"], opts["--lane"], + workstation) + + probe = _register_probe(service, schema) + who, database = probe["user"], probe["database"] + if not probe["create_roles"]: + raise Refusal(f"bootstrap: the admin {who} may not create roles: it has neither " + f"CREATEROLE nor SUPERUSER") + if not probe["create_schemas"]: + raise Refusal(f"bootstrap: the admin {who} may not create schemas in the database " + f"{database}") + if not probe["owns"]: + raise Refusal(f"bootstrap: the admin {who} does not own the database {database} " + f"(pg_has_role(current_user, datdba, 'USAGE') is false), where the " + f"database-level REVOKE and GRANT would only warn (design.md §1.4). Run " + f"it through a service that names a database its admin owns") + _register_refuse_scope(_register_scope_faults(probe["scope"], "before")) + if probe["indexer_login"] is False: + raise Refusal(f"bootstrap: the role {_REGISTER_INDEXER} exists and cannot log in " + f"(NOLOGIN), and url= logs in as it (design.md section 1.4). The " + f"bootstrap changes no existing role's attributes: give it LOGIN by " + f"hand, then run it again") + if not isinstance(database, str) or not database.strip() or any( + ord(ch) < 0x20 or ord(ch) == 0x7F for ch in database): + raise Refusal("bootstrap: the database's name is empty or holds a control character") + + state = None + if probe["schema"] is not None and not roles_only: + if not all(probe["schema"]): + raise Refusal(f"bootstrap: the schema {schema} exists and is not a register this " + f"tool made: it lacks schema_version, register_switch or " + f"register_head. Name another register_schema=, or drop it") + state = _register_state(service, schema) + plan = [] if roles_only else register_migration_plan( + None if state is None else state["version"]) + primary = state is not None and state["mode"] == "primary" + + names = register_role_names() + grant = _register_role_block_parts()[1] + granted = re.match(r"GRANT ([a-z_][a-z0-9_]*(?:, [a-z_][a-z0-9_]*)*) TO CURRENT_USER", grant) + if not granted or _REGISTER_INDEXER not in names: + raise RuntimeError("the register's role block's GRANT, or its indexer, is not as built") + grant_line = (f"the admin {who}'s membership of {granted.group(1).replace(', ', ' and ')}, " + f"WITH INHERIT TRUE, SET TRUE") + db_lines = [f"database {database}, REVOKE ALL FROM PUBLIC", + f"database {database}, GRANT CONNECT to {names[1]}, {names[2]} and " + f"{_REGISTER_INDEXER}", + f"default privileges of {names[0]}, REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC"] + db_states = [probe["states"][key] for key in ("public", "connect", "defaults")] + + if primary: + missing = [f"role {role}" for role in names if role not in probe["roles"]] + if not probe["states"]["grant"]: + missing.append(grant_line) + missing += [line for line, done in zip(db_lines, db_states) if not done] + if missing: + raise Refusal("bootstrap: the switch is at primary, so it changes nothing but a " + "pending migration (operations.md:434), and these are not in place: " + + "; ".join(missing) + ". Run bootstrap --roles-only first") + _register_refuse_scope(_register_scope_faults(probe["scope"], "all")) + for role in names: + _bootstrap_say(f"role {role}", False) + _bootstrap_say(grant_line, False) + else: + creating = [role for role in names if role not in probe["roles"]] + password = "" + extra = "" + if _REGISTER_INDEXER in creating and not opts["--no-passwords"]: + import secrets + password = secrets.token_urlsafe(32) + extra = (f"ALTER ROLE {_REGISTER_INDEXER} PASSWORD " + f"{_pg_quote(register_scram_verifier(password))};\n") + + def run_roles(script: str, variables: dict) -> None: + _register_admin_psql(service, script + extra, variables, single_transaction=True) + + created = apply_register_roles(run_roles, probe["roles"]) + for role in names: + _bootstrap_say(f"role {role}", role in created) + _bootstrap_say(grant_line, not probe["states"]["grant"]) + if password: + say(f"# {_REGISTER_INDEXER}'s password-file line, printed once: put it alone in a " + f"0600 file, and name that file in passfile=") + say(_register_pgpass_line(database, _REGISTER_INDEXER, password)) + sys.stdout.flush() + + if roles_only: + _register_admin_psql(service, "".join(_register_roles_only_parts()), {"db": database}, + single_transaction=True) + after = _register_confirm(service, schema) + unmet = [line for line, done in zip(db_lines, (after["states"][key] for key in + ("public", "connect", "defaults"))) + if not done] + if unmet or not after["states"]["grant"]: + raise Refusal("bootstrap --roles-only: after its statements these are still not in " + "place: " + "; ".join(unmet + ([] if after["states"]["grant"] + else [grant_line]))) + _register_refuse_scope(_register_scope_faults(after["scope"], "roles-only")) + for line, done in zip(db_lines, db_states): + _bootstrap_say(line, not done) + return EXIT_OK + + rendered_digests: dict[int, str] = {} + + def run_migration(script: str, variables: dict) -> None: + text = migrations.get(script) + if text is None: + raise RuntimeError("a migration this build does not ship was to be sent") + version = next(v for v, t in REGISTER_MIGRATIONS.items() if t == script) + rendered_digests[version] = hashlib.sha256(text.encode("utf-8")).hexdigest() + _register_admin_psql(service, text, variables, single_transaction=False) + + applied = apply_register_migrations( + run_migration, None if state is None else state["version"], + repository=opts["--repository"], label=opts["--label"], lane=opts["--lane"], + workstation=workstation) if plan else [] + if applied and applied[0][0] == 1: + _bootstrap_say(f"schema {schema}", True, f"version {REGISTER_SCHEMA_VERSION}") + elif applied: + say(f"schema {schema}: migrated (version {state['version']} to " + f"{REGISTER_SCHEMA_VERSION})") + else: + _bootstrap_say(f"schema {schema}", False, f"version {state['version']}") + for version, digest in applied: + _bootstrap_say(f"migration {version}", True, + f"script_sha256 {digest}, rendered sha256 {rendered_digests[version]}") + if state is None: + _bootstrap_say("switch", True, f"mode files, marker absent, label {opts['--label']}, " + f"set_seq -1, a new generation") + _bootstrap_say("head", True, "seq -1") + else: + _bootstrap_say("switch", False, f"mode {state['mode']}, marker {state['marker']}, " + f"label {state['label']}, set_seq {state['set_seq']}") + _bootstrap_say("head", False, f"seq {state['head']}") + + if not primary: + def run_grants(script: str, variables: dict) -> None: + if script != _register_role_block_parts()[2]: + raise RuntimeError("the role block's second part was not the one rendered") + _register_admin_psql(service, rest, variables, single_transaction=True) + + apply_register_grants(run_grants, database=database) + after = _register_confirm(service, schema) + unmet = [line for line, done in zip(db_lines, (after["states"][key] for key in + ("public", "connect", "defaults"))) + if not done] + if unmet or not after["states"]["grant"]: + raise Refusal("bootstrap: after its statements these are still not in place: " + + "; ".join(unmet + ([] if after["states"]["grant"] else [grant_line]))) + _register_refuse_scope(_register_scope_faults(after["scope"], "all")) + for line, done in zip(db_lines, db_states): + _bootstrap_say(line, not done) + _bootstrap_say(f"privileges in the schemas {schema} and lanes_index", + after["fingerprint"] != probe["fingerprint"]) + + say("# lanes-index.conf lines for this database, with no secret:") + if primary: + label = opts["--label"] + if label != state["label"]: + note(f"the switch is at primary and names {state['label']}; bootstrap writes no " + f"label. register_label={label} is for a restored backup's replacement, whose " + f"cutover --after-loss sets it; for the live database, keep {state['label']}") + else: + note(f"the switch is at primary and names {label}: if this is a restored backup, " + f"its replacement needs a label of its own (N4)") + else: + say("mode=index") + label = state["label"] if state is not None else opts["--label"] + if state is not None and opts["--label"] != state["label"]: + note(f"the switch already names {state['label']}, so --label {opts['--label']} is " + f"not written; register_label= is the switch's label") + say(f"register_label={label}") + if schema != REGISTER_TEMPLATE_SCHEMA: + say(f"register_schema={schema}") + return EXIT_OK + + +# `LANES-INDEX LOGIN` (operations.md §2.4, "lanes-index login"; FR-009, FR-054; +# T110). Brett's command for each engineer's two logins and the dump job's one +# (design.md §1.4, "One engineer's logins"; Brett's "Two logins each +# (Recommended)", #165 6723413756), run from his own shell after the bootstrap, +# through the admin service as the bootstrap connects, under §2.4's four rules: +# - `add ` makes `lanes_w_`, a member of REGISTER-WRITER, +# and `lanes_r_`, a member of READER, each with its group's +# floors and a password it generates. It prints, once, their two +# password-file lines, then the `register_url=` and `reader_url=` lines for +# that engineer's file. Run again, it changes nothing but a lost +# membership, which it puts back; +# - `add --dump-job` makes `lanes_register_dump` alone, §1.4's second half +# with `r=lanes_register_dump`, whose password Brett stores as the Key +# Vault secret the dump CronJob reads; +# - `rotate ` sets new passwords for both logins, and `rotate +# --dump-job` for `lanes_register_dump` alone (lane 3's ruling, +# #165 6726725691), and prints the new password-file lines; +# - `revoke `, for each of the two logins in turn, the writer's +# first, runs §1.4's revoke and prints each step's result. +# +# ONE TRANSACTION A STEP, AND Y'S BYTES UNCHANGED (as T108 and T109). The login +# step is one `--single-transaction` call: Y:2288-2300, or its second half alone +# for the dump job, less the CREATE ROLE of each login that exists already (the +# `pg_roles` guard, which is outside Y's bytes), then one `ALTER ROLE ... +# PASSWORD ''` for each login it creates, so each password is set in +# the transaction that makes its login. The revoke's three numbered steps are +# three such calls per login, each committed before the next, so their effects +# come in Y's order: no new session (28000), then an open session's next +# statement refused (42501), then its sessions ended (57P01), with step 3's +# grant to the admin never outliving that step. Joined, one login's three +# scripts are Y:2302-2309 byte for byte. A rotation is `ALTER ROLE ... PASSWORD` +# with a new verifier (Y:2312), both of an engineer's logins in one call. +# +# THE SECRET (operations.md:481; P20). `add` and `rotate` make passwords, so +# they refuse when stdout is not a terminal, before any connection; `revoke` +# prints none and does not. Each password is generated here, sent only as a +# SCRAM-SHA-256 verifier in the script on psql's stdin, and printed once, as a +# password-file line, after its step has committed. +# +# THE URL LINES (Y:2326; contracts/config.md §3.1). The bootstrap gives `login` +# no endpoint, and `login` guesses none: the host and port are those psql +# connected to, its own `:HOST` and `:PORT`, and the database is the one the +# admin connection reached, which on the install name ``, as the +# admin's own service does (Y:2324). Each line carries `sslmode=verify-full` and +# an `sslrootcert=` that `--sslrootcert ` fills, or that reads `` for the engineer to fill. No URL carries a password. + +#: Design.md §1.4's login step and revoke, verbatim (Y:2288-2309). The login +#: step's psql variables are `w` and `r`, the revoke's `login` and `grp`. +_REGISTER_LOGIN_BLOCK = r"""-- lanes-index login add : psql -v w=lanes_w_ -v r=lanes_r_. +-- The dump job's login is the second half alone, with r=lanes_register_dump. Each CREATE ROLE +-- is guarded by a pg_roles check, as the bootstrap's are. +CREATE ROLE :"w" LOGIN; -- its password: a SCRAM verifier, set as it is made +GRANT lanes_register_writer TO :"w"; -- again on a rerun: puts back a lost membership +ALTER ROLE :"w" SET lock_timeout = '2000ms'; -- the writer's floors, the login's own (§1.3) +ALTER ROLE :"w" SET statement_timeout = '5s'; +ALTER ROLE :"w" SET idle_in_transaction_session_timeout = '5s'; +CREATE ROLE :"r" LOGIN; +GRANT lanes_register_reader TO :"r"; +ALTER ROLE :"r" SET default_transaction_read_only = on; -- the reader's floors +ALTER ROLE :"r" SET lock_timeout = '1000ms'; +ALTER ROLE :"r" SET statement_timeout = '1500ms'; + +-- lanes-index login revoke : for each of its logins, psql -v login=… -v grp=… +ALTER ROLE :"login" NOLOGIN; -- 1. no new session (28000) +REVOKE :"grp" FROM :"login"; -- 2. an open session's next statement + -- is refused (42501) +GRANT :"login" TO CURRENT_USER WITH INHERIT TRUE, SET FALSE; -- 3. its privileges, so the admin may +SELECT pg_terminate_backend(pid) FROM pg_stat_activity -- end its sessions (57P01) with no + WHERE usename = :'login'; -- pg_signal_backend +REVOKE :"login" FROM CURRENT_USER; +""" + +#: The dump job's login, a READER login alone (design.md §1.4's roles table; +#: operations.md act 3's step 1). +_REGISTER_DUMP_LOGIN = "lanes_register_dump" + +#: An engineer's name (operations.md:487), matched whole. +_REGISTER_ENGINEER_RE = re.compile(r"[a-z][a-z0-9_]{0,40}") + +#: An `--sslrootcert` path: absolute, and of characters a URL's query carries +#: as they are, so the line needs no escaping. +_REGISTER_ROOT_FILE_RE = re.compile(r"/[A-Za-z0-9._/-]*") + +#: The login step's units: a login's CREATE ROLE, its group's GRANT and each of +#: its floors, each one line with its comment. +_REGISTER_LOGIN_CREATE_RE = re.compile(r'CREATE ROLE :"([wr])" LOGIN;[ \t]*(?:--[^\n]*)?\n') +_REGISTER_LOGIN_GRANT_RE = re.compile( + r'GRANT ([a-z_][a-z0-9_]*) TO :"([wr])";[ \t]*(?:--[^\n]*)?\n') +_REGISTER_LOGIN_FLOOR_RE = re.compile( + r"ALTER ROLE :\"([wr])\" SET ([a-z_]+) = '?([A-Za-z0-9]+)'?;[ \t]*(?:--[^\n]*)?\n") + +_LOGIN_USAGE = f"""\ +{PROG} login add --admin-service [--sslrootcert ] +{PROG} login add --dump-job --admin-service +{PROG} login rotate --admin-service +{PROG} login rotate --dump-job --admin-service +{PROG} login revoke --admin-service + +Makes, re-keys or revokes an engineer's two logins on the SQL register, +lanes_w_ (REGISTER-WRITER) and lanes_r_ (READER), each with +its group's floors, or the dump job's lanes_register_dump (READER), through the +libpq service in your own ~/.pg_service.conf, as bootstrap connects +(operations.md §2.4). Run it from your shell, after bootstrap: add and rotate +print each new password once, as a password-file line, only to a terminal, and +send it to the database only as a SCRAM verifier computed here. + + add makes the logins; run again, it puts back a lost membership and + changes nothing else. With an engineer, it also prints the + register_url= and reader_url= lines for that engineer's file, at + the host, port and database the admin connection reached + rotate a new password for each login; a session already open goes on + revoke for each login, the writer's first: NOLOGIN, its membership + revoked, then its sessions ended, each step's result printed + [a-z][a-z0-9_]{{0,40}} + --dump-job lanes_register_dump alone; store its password as the Key Vault + secret the dump CronJob reads + --sslrootcert + the root file on the engineer's host, for add's URL lines; + without it they read sslrootcert= + +Exit: 0 done · 2 refused, nothing written · 64 usage · 69 the admin connection +failed, or the database refused a step.""" + + +def _register_login_parts() -> dict: + """§1.4'S LOGIN BLOCK, CUT. Returns, each the block's own text: + - `head`: the login step's comment lines; + - `halves`: for `w` and `r`, that half's units in the block's order, its + CREATE ROLE first; + - `groups`: the group each half's GRANT names; + - `floors`: each half's `ALTER ROLE ... SET`s, as `name=value`, the form + `pg_roles.rolconfig` holds; + - `revoke`: the revoke's three steps, the first with the revoke's comment + line, so that joined they are the revoke whole. + A block that does not cut so is a defect of this build, so the error is + not a refusal.""" + step, blank, revoke = _REGISTER_LOGIN_BLOCK.partition("\n\n") + if not blank or "\n\n" in revoke or not revoke.endswith("\n"): + raise RuntimeError("the register's login block is not the login step, one blank " + "line, then the revoke") + units = _register_sql_units(step + "\n") + head = [] + while units and units[0].startswith("--"): + head.append(units.pop(0)) + halves: dict[str, list[str]] = {"w": [], "r": []} + groups: dict[str, str] = {} + floors: dict[str, list[str]] = {"w": [], "r": []} + order: list[str] = [] + for unit in units: + create = _REGISTER_LOGIN_CREATE_RE.fullmatch(unit) + grant = _REGISTER_LOGIN_GRANT_RE.fullmatch(unit) + floor = _REGISTER_LOGIN_FLOOR_RE.fullmatch(unit) + if create: + half = create.group(1) + if halves[half]: + raise RuntimeError(f"the login block's half {half} does not open with its " + f"CREATE ROLE") + elif grant: + half = grant.group(2) + if half in groups: + raise RuntimeError(f"the login block's half {half} grants two groups") + groups[half] = grant.group(1) + elif floor: + half = floor.group(1) + floors[half].append(f"{floor.group(2)}={floor.group(3)}") + else: + raise RuntimeError(f"the login block holds {unit!r}, which is not a CREATE ROLE, " + f"a GRANT or a floor") + if not halves[half] and not create: + raise RuntimeError(f"the login block's half {half} does not open with its " + f"CREATE ROLE") + if not order or order[-1] != half: + order.append(half) + halves[half].append(unit) + roles = register_role_names() + if (len(head) != 3 or order != ["w", "r"] or not floors["w"] or not floors["r"] + or groups != {"w": roles[1], "r": roles[2]}): + raise RuntimeError(f"the login block is not three comment lines, the writer's half, " + f"then the reader's, each granting its group: {order}, {groups}") + steps = _register_sql_units(revoke) + if (len(steps) != 6 or not steps[0].startswith("--") + or not steps[1].startswith('ALTER ROLE :"login" NOLOGIN;') + or not steps[2].startswith('REVOKE :"grp" FROM :"login";') + or not steps[3].startswith('GRANT :"login" TO CURRENT_USER WITH INHERIT TRUE, SET FALSE;') + or "pg_terminate_backend(pid)" not in steps[4] + or not steps[5].startswith('REVOKE :"login" FROM CURRENT_USER;')): + raise RuntimeError("the login block's revoke is not its comment, NOLOGIN, the " + "membership revoked, then the grant, the end of its sessions and " + "the grant revoked") + revoke_steps = ["".join(steps[:2]), steps[2], "".join(steps[3:])] + if "".join(revoke_steps) != revoke: + raise RuntimeError("the login block's revoke does not cut into three steps") + return {"head": "".join(head), "halves": halves, "groups": groups, "floors": floors, + "revoke": revoke_steps} + + +def register_login_script(halves: list[str], existing, verifiers: dict) -> str: + """THE LOGIN STEP AS SENT, one script for one `--single-transaction` call. + + `halves` is `["w", "r"]` for an engineer, or `["r"]` for the dump job, §1.4's + "second half alone". `existing` holds the halves whose login exists + already: their CREATE ROLE is left out, the `pg_roles` guard. `verifiers` + maps each half whose login this step creates to the SCRAM verifier of its + new password; each goes as one `ALTER ROLE :"" PASSWORD + '';` after the block's text. Every other line is the block's own + text, byte for byte, comments and all; for an engineer whose logins are + both new, the script opens with Y:2288-2300 whole.""" + parts = _register_login_parts() + if halves not in (["w", "r"], ["r"]): + raise ValueError(f"the login step's halves are ['w', 'r'] or ['r'], not {halves!r}") + if set(verifiers) - (set(halves) - set(existing)): + raise ValueError("a verifier was given for a login this step does not create") + text = parts["head"] if halves == ["w", "r"] else "" + for half in halves: + units = parts["halves"][half] + text += "".join(units[1:] if half in existing else units) + for half in halves: + if half in verifiers: + text += f'ALTER ROLE :"{half}" PASSWORD {_pg_quote(verifiers[half])};\n' + return text + + +def _register_login_query(login: str, group: str) -> str: + """One login's state, as one row or none: its name, whether it may log in, + whether it is a member of `group`, and its own settings, one per line.""" + return ("SELECT a.rolname::text, a.rolcanlogin, EXISTS (SELECT 1 FROM " + "pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles g ON g.oid = m.roleid " + f"WHERE m.member = a.oid AND g.rolname = {_pg_quote(group)}), " + "coalesce(pg_catalog.array_to_string(a.rolconfig, chr(10)), '') " + f"FROM pg_catalog.pg_roles a WHERE a.rolname = {_pg_quote(login)}") + + +def _register_login_probe(service: str, logins: list[tuple[str, str]], *, url: bool) -> dict: + """THE LOGIN'S FIRST READ, through the admin service, before anything is + written: who the admin is and what it may do, which of the two groups + exist, and each login's state. With `url`, also the host and port psql + connected to, psql's own `:HOST` and `:PORT`, which psql fills in.""" + groups = _register_login_parts()["groups"] + queries = [_register_admin_query(), + f"SELECT rolname::text FROM pg_catalog.pg_roles WHERE rolname IN " + f"({_register_names_sql([groups['w'], groups['r']])})"] + queries += [_register_login_query(login, groups[half]) for login, half in logins] + if url: + queries.append("SELECT :'HOST', :'PORT'") + res = _register_reads(service, "probe", queries, command="login") + admin = _register_one_row(res[0], 6, "the admin") + states: dict[str, dict] = {} + for (login, _half), rows in zip(logins, res[2:2 + len(logins)]): + if len(rows) > 1 or (rows and len(rows[0]) != 4): + raise RegisterUnavailable(f"psql answered {len(rows)} rows for the login {login}") + if rows: + states[login] = {"can_login": _register_flag(rows[0][1]), + "member": _register_flag(rows[0][2]), + "settings": set((rows[0][3] or "").split("\n")) - {""}} + probe = {"user": admin[0], "database": admin[1], "create_roles": _register_flag(admin[2]), + "owns": _register_flag(admin[4]), "groups": {row[0] for row in res[1] if row}, + "logins": states} + if url: + probe["host"], probe["port"] = _register_one_row( + res[-1], 2, "the admin connection's host and port") + return probe + + +def register_login_url(login: str, host: str, port: str, database: str, + root_file: str | None) -> str: + """ONE OF AN ENGINEER'S URL LINES' VALUES, in Y's form (Y:2326): + `postgresql://@:/?sslmode=verify-full&sslrootcert=`, + at the host, port and database the admin connection reached. A socket + directory is percent-encoded whole, an IPv6 address bracketed. No + password: the login's line goes in its own 0600 file.""" + from urllib.parse import quote + if not isinstance(port, str) or not re.fullmatch(r"[0-9]{1,5}", port): + raise RegisterUnavailable(f"psql answered the port {port!r}") + host = host or "" + if ":" in host and not host.startswith("/"): + where = "[" + quote(host, safe=":") + "]" + else: + where = quote(host, safe="") + return (f"postgresql://{login}@{where}:{port}/{quote(database, safe='')}" + f"?sslmode=verify-full&sslrootcert={root_file or ''}") + + +def _register_login_args(args: list[str]) -> dict | None: + """`login`'s command line; None for `--help`. First, no argument may carry + a connection string or a password, wherever it stands (2, never echoed); + then its usage (64); then its values (2). An unknown argument is named in + `ready`'s form (opensoft/openRepoTools#165 6894208108): quoted only where + all of it matches `--?[A-Za-z][A-Za-z-]{0,30}`. A word that does not + start with '-' is the action or the engineer, never unknown.""" + for arg in args: + value = arg.partition("=")[2] if arg.startswith("--") and "=" in arg else arg + _register_refuse_argument("an argument", value, command="login") + opts: dict = {"--admin-service": None, "--sslrootcert": None, "--dump-job": False} + words: list[str] = [] + i = 0 + while i < len(args): + arg = args[i] + if arg in ("-h", "--help"): + return None + name, eq, value = arg.partition("=") + if name in ("--admin-service", "--sslrootcert"): + if not eq: + value = args[i + 1] if i + 1 < len(args) else "" + i += 1 + if not value: + raise _RegisterUsage(f"login: {name} needs a value") + if opts[name] is not None: + raise _RegisterUsage(f"login: {name} is given twice") + opts[name] = value + elif arg == "--dump-job": + if opts["--dump-job"]: + raise _RegisterUsage("login: --dump-job is given twice") + opts["--dump-job"] = True + elif arg.startswith("-"): + shown = (f"'{arg}'" if re.fullmatch(r"--?[A-Za-z][A-Za-z-]{0,30}", arg) + else "that is not one of its flags") + raise _RegisterUsage(f"login: unknown argument {shown}") + else: + words.append(arg) + i += 1 + if not words or words[0] not in ("add", "rotate", "revoke"): + raise _RegisterUsage("login needs add, rotate or revoke") + action, rest = words[0], words[1:] + if len(rest) > 1: + raise _RegisterUsage(f"login {action} takes one engineer") + engineer = rest[0] if rest else None + dump = opts["--dump-job"] + if action == "revoke" and dump: + raise _RegisterUsage("login revoke takes an engineer; the dump job's login is " + "rotated, never revoked, by this command") + if action == "revoke" and engineer is None: + raise _RegisterUsage("login revoke needs an engineer") + if (engineer is None) == (not dump): + raise _RegisterUsage(f"login {action} needs an engineer or --dump-job, and not both") + if opts["--sslrootcert"] is not None and (action != "add" or dump): + raise _RegisterUsage("login: --sslrootcert is for the URL lines of login add " + "") + if opts["--admin-service"] is None: + raise _RegisterUsage("login needs --admin-service ") + if engineer is not None and not _REGISTER_ENGINEER_RE.fullmatch(engineer): + raise Refusal("login: the engineer's name is not ^[a-z][a-z0-9_]{0,40}$: a lower-case " + "letter, then up to 40 lower-case letters, digits or '_'") + _register_refuse_argument("--admin-service", opts["--admin-service"], command="login") + root = opts["--sslrootcert"] + if root is not None and (root == "system" or not _REGISTER_ROOT_FILE_RE.fullmatch(root)): + raise Refusal("login: --sslrootcert is not an absolute path of letters, digits, '.', " + "'_', '-' and '/'. It names the root file on the engineer's host, never " + "`system`, which holds no private root (design.md §1.4, Y:2324)") + return {"action": action, "engineer": engineer, "dump": dump, + "service": opts["--admin-service"], "root": root} + + +def cmd_login(args: list[str]) -> int: + """`lanes-index login` (operations.md §2.4): its exits, by the contract's + constants.""" + try: + opts = _register_login_args(args) + except _RegisterUsage as exc: + note(f"{exc} - see {PROG} login --help") + return EXIT_USAGE + except Refusal as exc: + note(f"REFUSED: {exc}") + return EXIT_REFUSED + if opts is None: + say(_LOGIN_USAGE) + return EXIT_OK + try: + return _login(opts) + except Refusal as exc: + note(f"REFUSED: {exc}") + return EXIT_REFUSED + except RegisterUnavailable as exc: + hint = {"add": " A step cut at its commit may have made a login: `login add` again " + "names what it finds, and `login rotate` gives such a login a password " + "you hold.", + "rotate": " A step cut at its commit may have changed the passwords: run " + "`login rotate` again.", + "revoke": " Each step printed above stands; run `login revoke` again to " + "finish."}[opts["action"]] if opts.get("sent") else " Nothing was sent." + note(f"login {opts['action']}: the admin connection failed, or the database refused " + f"a step: {exc}.{hint}") + return EXIT_UNAVAILABLE + + +def _login(opts: dict) -> int: + action, engineer, dump, service = (opts["action"], opts["engineer"], opts["dump"], + opts["service"]) + if action in ("add", "rotate") and not sys.stdout.isatty(): + raise Refusal(f"login {action}: stdout is not a terminal. It prints a password only " + f"to a terminal, so that no transcript, log or pipe holds one: run it " + f"from your shell") + load_config() + parts = _register_login_parts() + groups = parts["groups"] + if dump: + logins = [(_REGISTER_DUMP_LOGIN, "r")] + else: + logins = [(f"lanes_w_{engineer}", "w"), (f"lanes_r_{engineer}", "r")] + probe = _register_login_probe(service, logins, url=(action == "add" and not dump)) + who, database = probe["user"], probe["database"] + if not probe["create_roles"]: + raise Refusal(f"login {action}: the admin {who} may not create or alter roles: it has " + f"neither CREATEROLE nor SUPERUSER") + if not isinstance(database, str) or not database.strip() or any( + ord(ch) < 0x20 or ord(ch) == 0x7F for ch in database): + raise Refusal(f"login {action}: the database's name is empty or holds a control " + f"character") + states = probe["logins"] + if action == "revoke": + return _login_revoke(service, parts, logins, probe, opts) + for login, _half in logins: + state = states.get(login) + if action == "rotate" and state is None: + raise Refusal(f"login rotate: {login} does not exist; `login add` makes it") + if state is not None and not state["can_login"]: + raise Refusal(f"login {action}: {login} exists and cannot log in: it was revoked, " + f"and a revoked login's name is not reused while the server's logs " + f"still name it (design.md §1.4). " + + ("Give the engineer another name, or drop the role first" + if action == "add" else "A revoked login takes no new password")) + if action == "add": + missing = [groups[half] for _login_name, half in logins + if groups[half] not in probe["groups"]] + if missing: + raise Refusal(f"login add: {' and '.join(missing)} " + f"{'do' if len(missing) > 1 else 'does'} not exist: run bootstrap, " + f"or bootstrap --roles-only, first") + if not probe["owns"]: + note(f"login {action}: the admin {who} does not own the database {database}, which " + f"the lines below name. If it is not the register's database, run it again " + f"through the service that names that one") + import secrets + creating = [(login, half) for login, half in logins + if action == "rotate" or states.get(login) is None] + passwords = {login: secrets.token_urlsafe(32) for login, _half in creating} + verifiers = {half: register_scram_verifier(passwords[login]) for login, half in creating} + variables = {half: login for login, half in logins} + if action == "add": + script = register_login_script([half for _login_name, half in logins], + {half for login, half in logins if login in states}, + verifiers) + else: + script = "".join(f'ALTER ROLE :"{half}" PASSWORD {_pg_quote(verifiers[half])};\n' + for _login_name, half in logins) + opts["sent"] = True + _register_admin_psql(service, script, variables, single_transaction=True) + + if action == "add": + for login, half in logins: + state = states.get(login) + _bootstrap_say(f"login {login}", state is None, + "LOGIN, its password a SCRAM verifier set as it was made" + if state is None else "") + _bootstrap_say(f"login {login}'s membership of {groups[half]}", + state is None or not state["member"], + "put back" if state is not None and not state["member"] else "") + lacking = [f for f in parts["floors"][half] + if state is None or f not in state["settings"]] + _bootstrap_say(f"login {login}'s floors", bool(lacking), + ("put back: " if state is not None and lacking else "") + + ", ".join(lacking or parts["floors"][half])) + else: + for login, _half in logins: + say(f"login {login}'s password: changed (a new SCRAM verifier; a session already " + f"open goes on until it ends)") + for login, half in creating: + if dump: + say(f"# {login}'s password-file line, printed once: store it as the Key Vault " + f"secret the dump CronJob reads (its password is the line's last field)") + else: + key = "register_passfile=" if half == "w" else "reader_passfile=" + say(f"# {login}'s password-file line, printed once: put it alone in a 0600 file " + f"of {engineer}'s account, and name that file in {key}") + say(_register_pgpass_line(database, login, passwords[login])) + sys.stdout.flush() + if action == "add" and not creating: + say(f"# no password line: {' and '.join(login for login, _half in logins)} existed " + f"already. `{PROG} login rotate {'--dump-job' if dump else engineer}` gives " + f"{'it a new one' if dump else 'them new ones'}") + if action == "rotate" and not dump: + say(f"# until {engineer}'s two password files hold these lines, that workstation's " + f"new connections fail at login (69): write them before its lanes resume") + if action == "add" and not dump: + say(f"# lanes-index.conf lines for {engineer}'s file, with no secret; sslrootcert= " + f"names the root file on {engineer}'s host:") + for login, key in ((logins[0][0], "register_url="), (logins[1][0], "reader_url=")): + say(key + register_login_url(login, probe["host"], probe["port"], database, + opts["root"])) + return EXIT_OK + + +def _login_revoke(service: str, parts: dict, logins: list[tuple[str, str]], + probe: dict, opts: dict) -> int: + """§1.4'S REVOKE (Y:2302-2309; operations.md §2.4's `revoke`), for each of + the engineer's logins in turn, the writer's first: its three steps, each + one `--single-transaction` call that commits before the next, each step's + result printed as it ends. A login that does not exist is said so; where + neither does, nothing is revoked (2).""" + states, groups = probe["logins"], parts["groups"] + present = [(login, half) for login, half in logins if login in states] + if not present: + raise Refusal(f"login revoke: neither {logins[0][0]} nor {logins[1][0]} exists, so " + f"there is nothing to revoke; check the engineer's name") + missing = [groups[half] for _login, half in present if groups[half] not in probe["groups"]] + if missing: + raise Refusal(f"login revoke: {' and '.join(missing)} " + f"{'do' if len(missing) > 1 else 'does'} not exist, so no membership of " + f"{'them' if len(missing) > 1 else 'it'} can be revoked; nothing was " + f"revoked") + nologin, revoke_group, end_sessions = parts["revoke"] + for login, half in logins: + state = states.get(login) + if state is None: + say(f"login {login}: absent, nothing to revoke") + continue + variables = {"login": login, "grp": groups[half]} + opts["sent"] = True + _register_admin_psql(service, nologin, variables, single_transaction=True) + say(f"login {login}, step 1, NOLOGIN: " + + ("done (a new session is refused: 28000)" if state["can_login"] + else "unchanged (it could not log in)")) + sys.stdout.flush() + _register_admin_psql(service, revoke_group, variables, single_transaction=True) + say(f"login {login}, step 2, its membership of {groups[half]} revoked: " + + ("done (an open session's next statement is refused: 42501)" if state["member"] + else "unchanged (it held none)")) + sys.stdout.flush() + out = _register_admin_psql(service, end_sessions, variables, single_transaction=True) + answers = [line.strip() for line in out.splitlines() if line.strip() in ("t", "f")] + ended, gone = answers.count("t"), answers.count("f") + say(f"login {login}, step 3, its sessions ended: {ended} ended (57P01)" + + (f", {gone} gone before the signal" if gone else "") + + f"; the admin held {login}'s privileges for this step alone") + sys.stdout.flush() + return EXIT_OK + + # ============================================================ local status def _status_path() -> str: @@ -1518,24 +5783,126 @@ def read_status() -> dict: return {} +def _replace_status(data: dict) -> None: + """The status file as `data`, in one atomic replace, 0600.""" + os.makedirs(state_dir(), mode=0o700, exist_ok=True) + tmp = _status_path() + f".{os.getpid()}" + try: + with open(tmp, "w", encoding="utf-8") as handle: + json.dump(data, handle, indent=1, sort_keys=True) + os.chmod(tmp, 0o600) + os.replace(tmp, _status_path()) + except OSError: + # NO COPY LEFT BEHIND (W116's pre-review of commit 15): the file this call made, which + # may hold what the replace was to remove, goes with the failure + try: + os.unlink(tmp) + except OSError: + pass + raise + + +#: SET ONCE THE ONE WARNING IS SAID (W116's pre-review of commit 15): a run that meets a +#: malformed status file more than once says it once. +_WARNED = {"any": False} + + +def _warn_unparseable() -> None: + if not _WARNED["any"]: + _WARNED["any"] = True + note(STATUS_UNPARSEABLE_WARNING) + + def write_status(source: str, **fields) -> None: """This workstation's own record of its last attempt, which the store - cannot hold for an attempt that could not reach it.""" + cannot hold for an attempt that could not reach it. READ AS THE CLEANUP READS IT (B4 + of opensoft/openRepoTools-code#89 comment 6947619546): a status file that cannot be + read is left as it is, and one that cannot be parsed is replaced only with the one + fixed WARNING line said.""" try: - os.makedirs(state_dir(), mode=0o700, exist_ok=True) - data = read_status() + try: + data, parsed = _read_status_strictly() + except StoreUnusable: + return + if not parsed: + _warn_unparseable() entry = data.get(source, {}) entry.update(fields) data[source] = entry - tmp = _status_path() + f".{os.getpid()}" - with open(tmp, "w", encoding="utf-8") as handle: - json.dump(data, handle, indent=1, sort_keys=True) - os.chmod(tmp, 0o600) - os.replace(tmp, _status_path()) + _replace_status(data) except OSError: pass +def drop_legacy_status() -> int: + """Every status-file entry under a legacy key (`_is_legacy`) goes, its + `last_error` with it and never copied, in one atomic replace (lane 3's rulings, + opensoft/openRepoTools-code#89 comments 6941833120 and 6944416906), read and + replaced STRICTLY: a file that cannot be read or replaced fails the run with fixed + words, never a run that ends 0 with the entry kept, and one that cannot be parsed is + replaced with an empty one. An entry under a key this build files stays as it is. + Returns how many went.""" + data, parsed = _read_status_strictly() + gone = [name for name in data if _is_legacy(name)] + if parsed and not gone: + return 0 + try: + _replace_status({name: entry for name, entry in data.items() if name not in gone}) + except OSError: + raise StoreUnusable("unreachable", STATUS_UNREPLACEABLE) from None + return len(gone) + + +def _read_status_strictly() -> tuple: + """THE STATUS FILE AS THE CLEANUP READS IT (lane 3's rulings, + opensoft/openRepoTools-code#89 comments 6944416906 and 6944673181): `(entries, + parsed)`. A missing file holds no entry. A file that cannot be read is a + `StoreUnusable` with fixed words; one that can be read and not parsed - not UTF-8 + JSON, or not an object of objects - is `({}, False)`, and none of its bytes go + anywhere. NOTHING BUT A REGULAR FILE (B4 of opensoft/openRepoTools-code#89 comment + 6947619546): the path is read with `lstat`, and a symlink, dangling or not, a FIFO or + a folder is the same `StoreUnusable`; only a path with nothing at it is absent.""" + path = _status_path() + try: + mode = os.lstat(path).st_mode + except FileNotFoundError: + return {}, True + except OSError: + raise StoreUnusable("unreachable", STATUS_UNREADABLE) from None + if not stat.S_ISREG(mode): + raise StoreUnusable("unreachable", STATUS_UNREADABLE) + try: + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + with os.fdopen(fd, "rb") as handle: + if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): + raise StoreUnusable("unreachable", STATUS_UNREADABLE) + raw = handle.read() + except OSError: + raise StoreUnusable("unreachable", STATUS_UNREADABLE) from None + try: + data = json.loads(raw.decode("utf-8")) + except ValueError: + return {}, False + if not isinstance(data, dict) or not all(isinstance(e, dict) for e in data.values()): + return {}, False + return data, True + + +def check_status_file(dry_run: bool) -> None: + """THE STATUS FILE BEFORE A `sync` OR `reconcile` WRITES ANYTHING (lane 3's ruling + on item 3, opensoft/openRepoTools-code#89 comment 6944673181). One that cannot be + read fails the run. One that can be read and not parsed is replaced with an empty + one, atomically, as the run's first write, with one fixed WARNING line, and every + entry it held goes with it; the run goes on. A dry run writes nothing: it says the + same line and goes on as if the file held no entry. No byte of the file is said.""" + _data, parsed = _read_status_strictly() + if parsed: + return + _warn_unparseable() + if not dry_run: + drop_legacy_status() + + class SyncLock: """ONE SYNC AT A TIME PER WORKSTATION (14(d)). A second sync that finds the lock held leaves a RERUN mark and returns at once - the holder syncs again @@ -1609,17 +5976,32 @@ class SyncLock: # ================================================================ the acts def resolve_source(requested: str | None, root: str) -> str: - source = source_of(root) + # THE KEY WITH NO CREDENTIAL (lane 3's ruling, opensoft/openRepoTools-code#89 + # comment 6940341452): the store's key and the status file's, and every + # label, `why` and line that names this workstation's register, are this one. + source = _source_key(source_of(root)) + # A SOURCE THIS BUILD WOULD CALL LEGACY IS REFUSED, BEFORE ANYTHING USES IT (B1 of + # opensoft/openRepoTools-code#89 comment 6947619546) + if _is_legacy(source): + raise Refusal(REGISTER_KEY_REFUSED) if requested and requested != source: + # THE FLAG OR THE SOURCE'S KIND, NEVER THE VALUE (lane 3's ruling, + # opensoft/openRepoTools#165 6938005990; exit-codes.md:57, register-cli.md + # section 2.6): `--source` may hold a misplaced URL or `password=` value. if is_inventory(requested): - raise Refusal(f"{requested} is this workstation's worktree inventory, which " - f"`sync`/`reconcile --source inventory` write and `export " - f"--worktrees` reads; this is the register's path") + raise Refusal("`--source` names a worktree inventory, which " + "`sync`/`reconcile --source inventory` write and `export " + "--worktrees` reads; this is the register's path") if requested.startswith("ledger:"): - raise Refusal(f"{requested} is the managed ledger's half, which T058 of the 001 " - f"feature writes (Amendment 14(g) act 4); this indexer writes the " - f"register half only") - raise Refusal(f"this workstation's register is {source}, not {requested}") + raise Refusal("`--source` names the managed ledger's half, which T058 of the 001 " + "feature writes (Amendment 14(g) act 4); this indexer writes the " + "register half only") + # ITS OWN REGISTER BY THE REMOTE'S NAME, NO URL IN ANY FORM (lane 3's rulings, + # opensoft/openRepoTools-code#89 comments 6939379549 and 6939850492; + # exit-codes.md:57, register-cli.md:327): `source` is read from `workspace.yaml` + # or the checkout's `origin`, whose URL may carry a user, a password or a token. + raise Refusal("this workstation's register is the one `workspace.yaml` or the " + "checkout's `origin` names, not the source `--source` names") return source @@ -1660,11 +6042,64 @@ def stored_lanes_of(store, source: str) -> dict: ["lane", "owner", "row_text"])} +#: SET ONCE A RUN HAS REMOVED AN ENTRY AN EARLIER BUILD FILED (lane 1's addition A3 to +#: opensoft/openRepoTools-code#89 comment 6944416906): from then on, no line of the run +#: says that nothing was written. +_REMOVED = {"any": False} + + +def _nothing_written() -> str: + return ("nothing more written; the removal said above stands" if _REMOVED["any"] + else "nothing written") + + +def _drop_legacy(store, mode: str, sources: list) -> None: + """THE SOURCES AN EARLIER BUILD FILED UNDER A KEY THIS ONE WOULD NOT GO (lane 3's + rulings, opensoft/openRepoTools-code#89 comments 6941833120, 6944416906 and + 6944673181). v1.1.0 and v1.2.0 keyed a source as `source_of` read it, a credential + included, and their `_record_error` filed the raw `--source` value. Every writer + that is not a dry run - `sync` and `reconcile`, of the register or the inventory - + removes every legacy source (`_is_legacy`) from every table of the store in one + transaction, then from the status file, read strictly, its `last_error` discarded; + says so in a line that names no source; and only then finishes the store's scrub - + this run's, or one an earlier run left due, whether this run removed anything or + not - so the status file's cleanup does not wait on the scrub's last step. A key this + build files stays, and this run keeps or rebuilds its rows. `sources` is every + source the store keys on, read with the provenance (`provenance_and_sources`).""" + legacy = [source for source in sources if _is_legacy(source)] + store.drop_sources(legacy) + if legacy: + _REMOVED["any"] = True + try: + filed = drop_legacy_status() + except StoreUnusable: + # THE SCRUB STILL RUNS, OR ITS MARK STAYS FOR THE NEXT WRITER (B2 of + # opensoft/openRepoTools-code#89 comment 6947619546): a status file that cannot + # be replaced does not keep the store's bytes + if legacy: + say(f"{PROG} {mode}: removed {len(legacy)} source(s) from the index that an " + f"earlier build filed under a key that may hold a credential") + try: + store.scrub() + except StoreUnusable as exc: + # ITS OWN CONSTANT LINE, THAT A SCRUB IS PENDING, BESIDE THE REPLACE'S ERROR + note(f"{exc.kind}: {exc.detail}") + raise + if filed: + _REMOVED["any"] = True + if legacy or filed: + say(f"{PROG} {mode}: removed {len(legacy)} source(s) from the index and {filed} " + f"entry(s) from the status file that an earlier build filed under a key that " + f"may hold a credential") + store.scrub() + + def run_index(mode: str, requested: str | None, dry_run: bool) -> int: cfg = load_config() root = workspace_root() source = resolve_source(requested, root) tip = tip_of(root) + check_status_file(dry_run) store = open_store(cfg, "writer") if dry_run: try: @@ -1673,16 +6108,20 @@ def run_index(mode: str, requested: str | None, dry_run: bool) -> int: if exc.kind not in ("missing", "wiped"): raise store = None + old = store.provenance(source) if store is not None else None else: store.open_write() - old = store.provenance(source) if store is not None else None + old, sources = store.provenance_and_sources(source) + _drop_legacy(store, mode, sources) label = f"{source} at register@{tip[:12]} ({cfg['store']})" if old and old.get("commit_sha"): prev = old["commit_sha"] if not has_commit(root, prev): say(f"{PROG} {mode}: the index holds register@{prev[:12]}, which this checkout has " - f"not fetched - another workstation is ahead of it; nothing written") - write_status(source, last_attempt_utc=utc_now(), last_result="behind (unknown commit)") + f"not fetched - another workstation is ahead of it; {_nothing_written()}") + if not dry_run: + write_status(source, last_attempt_utc=utc_now(), + last_result="behind (unknown commit)") return 0 # NOT WHILE AN OWNER IS `unknown` (Codex on #164): an `unknown` may be a # read that failed, and asking again is how it clears - so a sync at @@ -1700,9 +6139,10 @@ def run_index(mode: str, requested: str | None, dry_run: bool) -> int: "rebuilt by wiping the index and reconciling") say(f"{PROG} {mode}: register@{tip[:12]} does not descend from the indexed " f"register@{prev[:12]}: {why}. The provenance only moves forward " - f"(Amendment 14(d)); nothing written") - write_status(source, last_attempt_utc=utc_now(), - last_result="not a descendant; nothing written") + f"(Amendment 14(d)); {_nothing_written()}") + if not dry_run: + write_status(source, last_attempt_utc=utc_now(), + last_result=f"not a descendant; {_nothing_written()}") return 0 if behind else 1 snap = read_snapshot(root, tip) records = build_records(snap) @@ -1740,7 +6180,7 @@ def run_index(mode: str, requested: str | None, dry_run: bool) -> int: if mode == "sync": say(f"{PROG} sync: {label} - the index is at the tip; nothing to write") else: - say(" total: nothing differs; nothing written") + say(f" total: nothing differs; {_nothing_written()}") write_status(source, last_attempt_utc=utc_now(), last_sync_utc=utc_now(), last_result="current", last_error="") return 0 @@ -1811,9 +6251,15 @@ def inventory_source(requested: str | None) -> str: "any workstation finds again (Amendment 11, R-A11-14). Export " "LANES_WORKSTATION, as the launcher does") source = f"{INVENTORY_PREFIX}{name}" + # A SOURCE THIS BUILD WOULD CALL LEGACY IS REFUSED, BEFORE ANYTHING USES IT (B1 of + # opensoft/openRepoTools-code#89 comment 6947619546) + if _is_legacy(source): + raise Refusal(INVENTORY_KEY_REFUSED) if requested and requested not in ("inventory", source): - raise Refusal(f"this workstation's inventory is {source}, not {requested}: an " - f"inventory is synced by the workstation whose disk holds it") + # THE SOURCE'S KIND, NEVER THE VALUE, as `resolve_source` says (lane 3's ruling) + raise Refusal(f"this workstation's inventory is {source}, not the inventory " + f"`--source` names: an inventory is synced by the workstation whose " + f"disk holds it") return source @@ -2059,6 +6505,7 @@ def fill_prs(trees: dict, stored: dict, mode: str, held: dict | None = None) -> def run_inventory(mode: str, requested: str | None, dry_run: bool) -> int: cfg = load_config() source = inventory_source(requested) + check_status_file(dry_run) store = open_store(cfg, "writer") if dry_run: try: @@ -2067,9 +6514,14 @@ def run_inventory(mode: str, requested: str | None, dry_run: bool) -> int: if exc.kind not in ("missing", "wiped"): raise store = None + old = store.provenance(source) if store is not None else None else: + # THE REGISTER'S CLEANUP, HERE TOO (BLOCKING 2 of opensoft/openRepoTools-code#89 + # comment 6944416906): an inventory-only workstation removes what an earlier + # build filed as the register's sync does, before anything else is written. store.open_write() - old = store.provenance(source) if store is not None else None + old, sources = store.provenance_and_sources(source) + _drop_legacy(store, mode, sources) trees, unread = collect_inventory() label = f"{source} ({cfg['store']})" cols = TABLE_COLUMNS["worktrees"] @@ -2189,7 +6641,7 @@ def run_inventory(mode: str, requested: str | None, dry_run: bool) -> int: if mode == "sync": say(f"{PROG} sync: {label} - the index is current; nothing to write") else: - say(" total: nothing differs; nothing written") + say(f" total: nothing differs; {_nothing_written()}") write_status(source, last_attempt_utc=utc_now(), last_sync_utc=utc_now(), last_result="current", last_error="") return 0 @@ -2214,15 +6666,18 @@ def is_inventory(requested: str | None) -> bool: def _sync_once(kind: str, requested: str | None) -> int: - if kind == "inventory": - # A REFUSAL HERE IS ANSWERED HERE: a register sync that took the - # inventory's mark must not lose the marks behind it to an exception. - try: - return _guarded(lambda: run_inventory("sync", requested, False), requested, kind) - except Refusal as exc: - note(f"REFUSED: {exc}") - return 2 - return _guarded(lambda: run_index("sync", requested, False), requested, kind) + # A REFUSAL HERE IS ANSWERED HERE, FOR EITHER KIND: a sync that took marks off the + # disk must not lose the ones behind it to an exception. The register's too (W116's + # re-check of commit 15): a plain `sync` whose workspace could not be read before the + # lock leaves a register mark, and a holder's later round can take it first; the + # holder says the refusal, as `main` would, files nothing, syncs the marks behind it, + # and exits 2. + act = run_inventory if kind == "inventory" else run_index + try: + return _guarded(lambda: act("sync", requested, False), requested, kind) + except Refusal as exc: + note(f"REFUSED: {exc}") + return 2 def cmd_sync(requested: str | None) -> int: @@ -2241,7 +6696,10 @@ def cmd_sync(requested: str | None) -> int: try: if kind == "inventory": inventory_source(requested) - elif requested: + else: + # THE REGISTER'S OWN KEY, WITH NO `--source` TOO (W116's pre-review of commit + # 15): one this build would call legacy is refused here, with 2, before a held + # lock answers 0 and before a mark is taken off the disk resolve_source(requested, workspace_root()) except StoreUnusable: pass @@ -2281,7 +6739,7 @@ def cmd_sync(requested: str | None) -> int: due.pop(0) if result == MOVED: say(f"{PROG} sync: origin/{branch()} kept moving through {rounds} reads; " - f"nothing written - the next write's nudge syncs it") + f"{_nothing_written()} - the next write's nudge syncs it") result = 0 # A FAILED SOURCE DOES NOT DROP THE OTHERS (Copilot round 1 on #171): # their marks were taken off the disk with this one's, so the loop @@ -2312,12 +6770,13 @@ def cmd_reconcile(requested: str | None, dry_run: bool) -> int: try: if kind == "inventory": return _guarded(lambda: run_inventory("reconcile", requested, dry_run), requested, - kind) + kind, dry_run) for _attempt in range(3): - rc = _guarded(lambda: run_index("reconcile", requested, dry_run), requested) + rc = _guarded(lambda: run_index("reconcile", requested, dry_run), requested, + dry_run=dry_run) if rc != MOVED: return rc - note(f"origin/{branch()} kept moving through three reads; nothing written") + note(f"origin/{branch()} kept moving through three reads; {_nothing_written()}") return 1 finally: lock.release() @@ -2328,34 +6787,43 @@ def cmd_reconcile(requested: str | None, dry_run: bool) -> int: MOVED = -1 -def _guarded(act, requested, kind: str = "register") -> int: +def _guarded(act, requested, kind: str = "register", dry_run: bool = False) -> int: + # A DRY RUN FILES NOTHING, ITS ERRORS INCLUDED (B4 of opensoft/openRepoTools-code#89 + # comment 6947619546) try: return act() except SourceMoved as exc: note(str(exc)) return MOVED except CasLost as exc: - note(str(exc)) - _record_error(requested, str(exc), kind) + text = str(exc).replace("nothing was written", _nothing_written()) + note(text) + if not dry_run: + _record_error(requested, text, kind) return 1 except StoreUnusable as exc: - note(f"{exc.kind}: {exc.detail} - nothing written") - _record_error(requested, f"{exc.kind}: {exc.detail}", kind) + note(f"{exc.kind}: {exc.detail} - {_nothing_written()}") + if not dry_run: + _record_error(requested, f"{exc.kind}: {exc.detail}", kind) return 1 def _record_error(requested, message: str, kind: str = "register") -> None: + # A SOURCE THAT COULD NOT BE RESOLVED IS FILED AS `register:?` OR `inventory:?`, + # NEVER AS THE VALUE GIVEN (lane 3's ruling, opensoft/openRepoTools-code#89 + # comment 6939379549): `--source` may hold a misplaced URL or `password=` value, + # and `status` prints every source this file names. if kind == "inventory": try: source = inventory_source(requested) except (StoreUnusable, Refusal): - source = requested if requested and requested != "inventory" else "inventory:?" + source = "inventory:?" write_status(source, last_attempt_utc=utc_now(), last_error=f"{utc_now()} {message}") return try: - source = requested or source_of(workspace_root()) - except StoreUnusable: - source = requested or "register:?" + source = resolve_source(requested, workspace_root()) + except (StoreUnusable, Refusal): + source = "register:?" write_status(source, last_attempt_utc=utc_now(), last_error=f"{utc_now()} {message}") @@ -2384,6 +6852,14 @@ def cmd_status() -> int: say(f"index: {exc.kind} - {exc.detail}") rc = 1 local = read_status() + # THIS WORKSTATION'S KEY AS `resolve_source` FILES IT, WITH NO CREDENTIAL + # (lane 3's ruling, opensoft/openRepoTools-code#89 comment 6940341452) + source = _source_key(source) + if source and _is_legacy(source): + # NOT PRINTED (B1 of comment 6947619546): the refusal's words in its place, exit 2 + say(f"workspace: {REGISTER_KEY_REFUSED}") + source = "" + rc = 2 sources = [p["source"] for p in provs] if source and source not in sources: sources.append(source) @@ -2392,13 +6868,25 @@ def cmd_status() -> int: inv_source = "" try: inv_source = inventory_source(None) - except (StoreUnusable, Refusal): + except Refusal as exc: + if str(exc) == INVENTORY_KEY_REFUSED: + # NOT PRINTED, AS THE REGISTER'S (B1 of comment 6947619546): exit 2 + say(f"inventory: {INVENTORY_KEY_REFUSED}") + rc = 2 + except StoreUnusable: inv_source = "" if inv_source and inv_source not in sources: sources.append(inv_source) for name in sorted(set(sources) | set(local)): + if _is_legacy(_source_key(name)): + # A KEY THIS BUILD DOES NOT FILE, EVEN LESS ITS CREDENTIAL (BLOCKING 1 of + # opensoft/openRepoTools-code#89 comment 6944416906): one fixed line in place + # of the whole entry, its key and its error unshown + say(LEGACY_SOURCE_LINE) + continue prov = next((p for p in provs if p["source"] == name), None) - say(f"source {name}") + # a name a build before this one filed with a credential is shown without it + say(f"source {_source_key(name)}") if name.startswith(INVENTORY_PREFIX): if prov is None: say(" provenance: none - this inventory is not indexed (a wiped or " @@ -2434,6 +6922,10 @@ def cmd_status() -> int: lag = commits_between(root, prov["commit_sha"], tip) say(f" lag: {'unknown (the indexed commit is not in this checkout)' if lag is None else f'{lag} commit(s)'}") entry = local.get(name, {}) + if _source_key(name) != name: + # A LEGACY ENTRY'S ERROR IS NEVER PRINTED (lane 3's ruling, + # opensoft/openRepoTools-code#89 comment 6941833120): it may hold the key. + entry = dict(entry, last_error=LEGACY_LAST_ERROR) say(f" last sync: {entry.get('last_sync_utc') or 'never, from this workstation'}" f"{' (' + entry['last_result'] + ')' if entry.get('last_result') else ''}") say(f" last error: {entry.get('last_error') or 'none'}") @@ -2450,7 +6942,9 @@ def cmd_export(out_dir: str, requested: str | None, worktrees: bool = False) -> success `meta`; on any reason the index cannot answer, `why` - one line, which `lanes-edit.sh` prints as `read: sources (index )`.""" if not os.path.isdir(out_dir): - note(f"--out {out_dir} is not a directory") + # THE FLAG, NEVER ITS VALUE (lane 3's ruling, opensoft/openRepoTools#165 + # 6938005990; exit-codes.md:57): `--out` may hold a misplaced URL or password. + note("--out is not a directory") return 64 def unusable(kind: str, detail: str) -> int: @@ -2539,8 +7033,10 @@ def _export_worktrees(out_dir: str, cfg: dict, unusable) -> int: try: store = open_store(cfg, "reader") store.open_read() + # NO LEGACY INVENTORY SOURCE IS READ (lane 1's coordinator, on commit 14's design): + # its rows are chosen by no value made from its key, and the next sync removes it provs = [p for p in store.all_provenance() - if str(p["source"]).startswith(INVENTORY_PREFIX)] + if str(p["source"]).startswith(INVENTORY_PREFIX) and not _is_legacy(p["source"])] if not provs: return unusable("wiped", f"no {INVENTORY_PREFIX} source in the " f"{cfg['store']} store") @@ -2568,8 +7064,10 @@ def _export_worktrees(out_dir: str, cfg: dict, unusable) -> int: # review of #289): a sync that wrote nothing - a lane listing that was not # whole, among others - leaves the table and its `synced` time as they # were, and only `status` said why. It is `status`'s `last error`, so a - # refused `reconcile` is in it too, a `--dry-run` included (NIT-1 of review - # r2 of #289). A fifth field, which a reader from before it ignores. + # refused `reconcile` is in it too, but not a `--dry-run`'s, which files nothing + # (lane 3's ruling, B4 of opensoft/openRepoTools-code#89 comment 6947619546, in + # place of NIT-1 of review r2 of #289). A fifth field, which a reader from before + # it ignores. # Another workstation's error is in its own record and not here, so a # shared store's other sources never carry one. recorded = read_status() @@ -2590,6 +7088,41 @@ USAGE = f"""\ {PROG} status per source: store, provenance, lag, errors {PROG} export --out [--source | --worktrees] the `--index` read flags' reader +{PROG} mode this workstation's mode: index or primary + +THE SQL REGISTER (feature 007, opensoft/openRepoTools#165): its subcommands, in +the forms contracts/register-cli.md fixes; is a write's identity, +`--write-id --generation --lane --verb +--args-sha256 `, and under `--at ` `--generation ` alone will do: +{PROG} register snapshot [ | --write-id new --lane --verb + --args-sha256 ] [--tree --checkout ] [--at ] +{PROG} register snapshot (--files | --all) --out +{PROG} register commit --workstation +{PROG} register classify register lines on stdin +{PROG} register read --prefetch --cache (--files | --all) +{PROG} register read --since --cache [--files ] [--log-key=] + (one of the two, or both) +{PROG} register read --for guard --prefetch --cache --pid --repo + [--lane=] +{PROG} register read --for guard --at --pid --cache --lane= +{PROG} journal --not-after [--clock --clock-age ] +{PROG} journal --since +{PROG} journal --last --path --grep [--at --generation ] +{PROG} render --images --at --out +{PROG} render --checkout +{PROG} import --at [--dry-run | --after-loss] +{PROG} cutover [--import ] [--after-loss | --marker-first] +{PROG} rollback [--hold-marker] +{PROG} outage declare --until --why [--mirror-seq ] +{PROG} outage declare --rollback --mirror-seq [--why ] +{PROG} outage clear +{PROG} bootstrap --admin-service --label --repository + --lane [--roles-only] [--no-passwords] +{PROG} login (add | rotate) ( | --dump-job) --admin-service +{PROG} login revoke --admin-service +{PROG} ready --expect index|primary --release --env +{PROG} set-mode index|primary [--config ] +{PROG} serve The DERIVED INDEX of the lane register (lane-collision-protocol Amendment 14). It is written behind the sources by this command alone, read only by tooling @@ -2620,6 +7153,32 @@ that decides nothing, and never a gate: no lane act reads it or waits on it. nudges `sync --source inventory`. The managed ledger's `ledger:` is T058's to write. +THE SQL REGISTER is the register's own store once a workstation is +`mode=primary`, written by `lanes-edit.sh` through `register snapshot` and +`register commit`, and read through `register read`. Its subcommands land one +pull request at a time: one this build does not have yet exits 64, as any +unknown subcommand does, and does nothing. + + mode Prints ONE line, `index` or `primary`, from the configuration + alone: it opens no database. No configuration file, or no + `mode=`, is `index`. A configuration it refuses is 2. + register The writers' snapshot and commit, `register classify`'s one + classifier, and the readers' and the guard's `register read`. + journal The in-doubt lookup by write id; `--since` and `--last` read. + render `--images`, the render set at a seq; `--checkout`, the renderer + fork, which answers "git half not installed" until phase 3, + when `--until` and `--revert ` join it. + import, cutover, rollback, outage + The operator's acts (operations.md sections 2.2 to 2.5), each + from the operator lane's own checkout. + bootstrap, login, ready, set-mode + The operator tools (operations.md section 2.4). + serve The register service (SVC-3), on `mode=primary` only. + + While this build refuses `mode=primary` (Q6(c): the renderer's git half is + not installed), `mode` and `register read` exit 78 with that text, and every + other subcommand refuses it with 2. + THE STORE: SQLite at ${{XDG_STATE_HOME:-~/.local/state}}/openRepoTools/lanes-index.sqlite, or QA Postgres through `psql` where the configuration names a `url=`. THE CONFIGURATION: ${{XDG_CONFIG_HOME:-~/.config}}/openRepoTools/lanes-index.conf, or the @@ -2635,8 +7194,39 @@ outside ~/.agents/, with no password in any URL: reader_passfile= its password file, where it is not the same one schema= the Postgres schema (default lanes_index) + The SQL register's keys (contracts/config.md): + mode=index|primary default index + register_url= this engineer's REGISTER-WRITER login; beside it, + reader_url= and reader_passfile= name this + engineer's READER login. At a TCP host that is not + loopback, each carries sslmode=verify-full and an + sslrootcert= naming the root file, never system + register_passfile= its 0600 password file + register_label=