mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-28 20:29:19 +01:00
Compare commits
3 Commits
9d897c13f4
...
02659e0abf
| Author | SHA1 | Date | |
|---|---|---|---|
| 02659e0abf | |||
| 085d08b5c9 | |||
| 200432a2b4 |
107
aur-publish/lib/aur_publish_one.sh
Normal file
107
aur-publish/lib/aur_publish_one.sh
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Building, verifying and pushing one package to the AUR.
|
||||||
|
#
|
||||||
|
# Sourced by publish.sh, never executed: these functions read the readonly
|
||||||
|
# config (AUR_HOST, AUR_ROOT, DRY_RUN, PUBLISHED, FAILED) that the entry script declares, and
|
||||||
|
# a `readonly` re-run inside a twice-sourced lib would abort under `set -e`.
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
publish_one() {
|
||||||
|
local pkg="$1" repo="$2" wrapper="$3" binary="$4" expected="$5"
|
||||||
|
local dir="$AUR_ROOT/$pkg"
|
||||||
|
local version
|
||||||
|
|
||||||
|
log "$pkg"
|
||||||
|
|
||||||
|
[[ -d "$repo" ]] || { warn "$pkg: no repo at $repo"; return 1; }
|
||||||
|
[[ -f "$dir/PKGBUILD" ]] || { warn "$pkg: no PKGBUILD at $dir"; return 1; }
|
||||||
|
|
||||||
|
version="$(newest_tag "$repo")"
|
||||||
|
[[ -n "$version" ]] || { warn "$pkg: no vX.Y.Z tag on the remote"; return 1; }
|
||||||
|
info "newest release tag: v$version"
|
||||||
|
|
||||||
|
cd "$dir"
|
||||||
|
sed -i -E "s/^pkgver=.*/pkgver=$version/" PKGBUILD
|
||||||
|
# The tarball for a tag contains the PKGBUILD, so the checksum can only be
|
||||||
|
# computed after the tag exists — never committed ahead of time.
|
||||||
|
updpkgsums >/dev/null 2>&1 || { warn "$pkg: updpkgsums failed (tag missing?)"; return 1; }
|
||||||
|
|
||||||
|
info "building"
|
||||||
|
if ! env PATH=/usr/bin:/bin:/usr/local/bin makepkg -Cf --noconfirm >/dev/null 2>&1; then
|
||||||
|
warn "$pkg: makepkg failed"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
local built
|
||||||
|
built="$(find . -maxdepth 1 -name "$pkg-$version-*.pkg.tar.zst" | head -1)"
|
||||||
|
[[ -n "$built" ]] || { warn "$pkg: no package produced"; return 1; }
|
||||||
|
|
||||||
|
# namcap's "ELF files outside of a valid path ('opt/')" is a false positive
|
||||||
|
# for /opt-installed apps, so only genuinely new errors are worth failing on.
|
||||||
|
local findings
|
||||||
|
findings="$(namcap "$built" 2>&1 | grep -E ' E: ' | grep -v "outside of a valid path" || true)"
|
||||||
|
if [[ -n "$findings" ]]; then
|
||||||
|
warn "$pkg: namcap errors:"
|
||||||
|
printf ' %s\n' "$findings"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
info "installing and launching"
|
||||||
|
sudo pacman -U --noconfirm "$built" >/dev/null 2>&1 \
|
||||||
|
|| { warn "$pkg: pacman -U failed"; return 1; }
|
||||||
|
verify_installed "$binary" "$expected" "$wrapper" || { warn "$pkg: launch check failed"; return 1; }
|
||||||
|
|
||||||
|
# Generated before the rule check, which verifies it matches the PKGBUILD.
|
||||||
|
makepkg --printsrcinfo > .SRCINFO
|
||||||
|
check_aur_rules "$pkg" || return 1
|
||||||
|
|
||||||
|
# The AUR repo is a separate remote living alongside the build dir; adding
|
||||||
|
# it here (rather than cloning into a fresh path) keeps the verified
|
||||||
|
# PKGBUILD and the thing being pushed byte-identical.
|
||||||
|
if [[ ! -d .git ]]; then
|
||||||
|
git init -q -b master .
|
||||||
|
git remote add origin "ssh://aur@$AUR_HOST/$pkg.git"
|
||||||
|
fi
|
||||||
|
git remote get-url origin >/dev/null 2>&1 \
|
||||||
|
|| git remote add origin "ssh://aur@$AUR_HOST/$pkg.git"
|
||||||
|
|
||||||
|
# Fetch first: an existing AUR package must be built on, not overwritten.
|
||||||
|
if git fetch -q origin master 2>/dev/null; then
|
||||||
|
git reset -q --soft FETCH_HEAD 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat > .gitignore <<'EOF'
|
||||||
|
# Build products; the AUR tracks only the recipe.
|
||||||
|
*.pkg.tar.zst
|
||||||
|
*.tar.gz
|
||||||
|
src/
|
||||||
|
pkg/
|
||||||
|
EOF
|
||||||
|
|
||||||
|
git add PKGBUILD .SRCINFO .gitignore
|
||||||
|
if git diff --cached --quiet; then
|
||||||
|
info "already up to date on the AUR; nothing to push"
|
||||||
|
PUBLISHED+=("$pkg v$version (unchanged)")
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
git -c user.name='Krzysztof Rudnicki' \
|
||||||
|
-c user.email='krzysztofrudnicki0@gmail.com' \
|
||||||
|
commit -q -m "$pkg $version-1"
|
||||||
|
|
||||||
|
if ((DRY_RUN)); then
|
||||||
|
info "DRY RUN — not pushing"
|
||||||
|
PUBLISHED+=("$pkg v$version (dry run)")
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
info "pushing to the AUR"
|
||||||
|
git push -q origin master 2>&1 | tail -3 || { warn "$pkg: push failed"; return 1; }
|
||||||
|
PUBLISHED+=("$pkg v$version")
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
107
aur-publish/lib/aur_registration.sh
Normal file
107
aur-publish/lib/aur_registration.sh
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Waiting for AUR registration and SSH access to come up.
|
||||||
|
#
|
||||||
|
# Sourced by publish.sh, never executed: these functions read the readonly
|
||||||
|
# config (AUR_HOST, SSH_KEY, GATE, POLL_SECONDS) that the entry script declares, and
|
||||||
|
# a `readonly` re-run inside a twice-sourced lib would abort under `set -e`.
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
register_status() {
|
||||||
|
python3 "$GATE" /register 2>/dev/null | head -1
|
||||||
|
}
|
||||||
|
|
||||||
|
open_browser() {
|
||||||
|
local url="$1"
|
||||||
|
local browser
|
||||||
|
for browser in xdg-open thorium-browser chromium google-chrome-stable firefox librewolf; do
|
||||||
|
if command -v "$browser" >/dev/null 2>&1; then
|
||||||
|
"$browser" "$url" >/dev/null 2>&1 &
|
||||||
|
info "Opened $url in $browser"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
warn "No browser found; open this yourself: $url"
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_key() {
|
||||||
|
if [[ ! -f "$SSH_KEY" ]]; then
|
||||||
|
log "Generating an AUR SSH key (none at $SSH_KEY)"
|
||||||
|
ssh-keygen -t ed25519 -f "$SSH_KEY" -N '' -C 'kuhy@aur'
|
||||||
|
fi
|
||||||
|
if ! grep -q "Host $AUR_HOST" "$HOME/.ssh/config" 2>/dev/null; then
|
||||||
|
log "Adding $AUR_HOST to ~/.ssh/config"
|
||||||
|
mkdir -p "$HOME/.ssh"
|
||||||
|
cat >> "$HOME/.ssh/config" <<EOF
|
||||||
|
|
||||||
|
# AUR uses a dedicated key so it stays separate from the GitHub identity.
|
||||||
|
Host $AUR_HOST
|
||||||
|
User aur
|
||||||
|
IdentityFile $SSH_KEY
|
||||||
|
IdentitiesOnly yes
|
||||||
|
EOF
|
||||||
|
chmod 600 "$HOME/.ssh/config"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
ssh_works() {
|
||||||
|
# The AUR refuses interactive shells; "Interactive shell is disabled" on a
|
||||||
|
# successful key auth is the success signal, not an error.
|
||||||
|
ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new \
|
||||||
|
-o ConnectTimeout=15 "aur@$AUR_HOST" help 2>&1 |
|
||||||
|
grep -qiE 'interactive shell is disabled|Welcome to AUR'
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_registration() {
|
||||||
|
local status
|
||||||
|
status="$(register_status)"
|
||||||
|
if [[ "$status" == "200" ]]; then
|
||||||
|
log "AUR registration is OPEN"
|
||||||
|
else
|
||||||
|
log "AUR registration is closed (HTTP $status). Polling every ${POLL_SECONDS}s."
|
||||||
|
info "Ctrl-C to stop; re-run any time, nothing is lost."
|
||||||
|
while :; do
|
||||||
|
sleep "$POLL_SECONDS"
|
||||||
|
status="$(register_status)"
|
||||||
|
if [[ "$status" == "200" ]]; then
|
||||||
|
log "Registration is BACK (HTTP 200)"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
printf ' %s still HTTP %s\n' "$(date +%H:%M)" "$status"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
open_browser "https://$AUR_HOST/register"
|
||||||
|
cat <<EOF
|
||||||
|
|
||||||
|
------------------------------------------------------------------
|
||||||
|
Sign up, and paste this into the "SSH Public Key" field:
|
||||||
|
|
||||||
|
$(sed 's/^/ /' "$SSH_KEY.pub")
|
||||||
|
|
||||||
|
You will need to confirm the address from your email before the
|
||||||
|
account works. This script waits for that automatically.
|
||||||
|
------------------------------------------------------------------
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
wait_for_ssh() {
|
||||||
|
log "Waiting for the SSH key to authenticate against the AUR"
|
||||||
|
local waited=0
|
||||||
|
until ssh_works; do
|
||||||
|
sleep 30
|
||||||
|
waited=$((waited + 30))
|
||||||
|
if ((waited % 300 == 0)); then
|
||||||
|
info "still waiting ($((waited / 60)) min) — key not accepted yet"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
log "SSH authentication OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Phase 2: build, verify and publish one package
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
122
aur-publish/lib/aur_verify.sh
Normal file
122
aur-publish/lib/aur_verify.sh
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# ============================================================================
|
||||||
|
# Gates a package must pass before it is allowed near the AUR.
|
||||||
|
#
|
||||||
|
# Sourced by publish.sh, never executed: these functions read the readonly
|
||||||
|
# config (AUR_ROOT, DRY_RUN) that the entry script declares, and
|
||||||
|
# a `readonly` re-run inside a twice-sourced lib would abort under `set -e`.
|
||||||
|
# ============================================================================
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
newest_tag() {
|
||||||
|
# Newest clean vX.Y.Z on the remote. Build tags (vX.Y.Z-build.N) and the
|
||||||
|
# grafted upstream Flutter SDK tags in diet-guard are excluded on purpose.
|
||||||
|
git -C "$1" ls-remote --tags origin 2>/dev/null |
|
||||||
|
awk '{print $2}' |
|
||||||
|
sed 's|refs/tags/||' |
|
||||||
|
grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' |
|
||||||
|
sed 's/^v//' |
|
||||||
|
sort -V |
|
||||||
|
tail -1
|
||||||
|
}
|
||||||
|
|
||||||
|
verify_installed() {
|
||||||
|
local binary="$1" expected="$2" wrapper="$3" output
|
||||||
|
|
||||||
|
# An instance left over from a previous run would make the wrapper print
|
||||||
|
# "already running" and hand off, which passes trivially and turns the
|
||||||
|
# strongest gate in this script into the weakest. Clear it first so the
|
||||||
|
# check always exercises a real cold start.
|
||||||
|
#
|
||||||
|
# Resolved through /proc/<pid>/exe rather than any form of name or
|
||||||
|
# command-line matching. Every argv-based approach selects the wrong
|
||||||
|
# processes here:
|
||||||
|
# * `pkill -x` compares against the kernel's 15-character comm field, and
|
||||||
|
# two of these wrappers are longer (habit_stack_desktop is 19), so a
|
||||||
|
# name match would silently never fire.
|
||||||
|
# * `pkill -f`, and equally `ps -eo args` piped through a pattern, match
|
||||||
|
# any process whose command line merely *mentions* the path — this
|
||||||
|
# script, the shell running it, and the matching tool itself all
|
||||||
|
# qualify, so the run kills its own shell instead of the app. A
|
||||||
|
# $$/$PPID guard does not cover it, because the offending shell is
|
||||||
|
# often a more distant ancestor.
|
||||||
|
# /proc/<pid>/exe is a kernel-maintained symlink to the binary actually
|
||||||
|
# being executed, so it cannot collide with an incidental mention.
|
||||||
|
# The wrapper name is unique per app, so the /opt/<pkg>/ segment is left as
|
||||||
|
# a glob instead of threading the package name through another parameter.
|
||||||
|
#
|
||||||
|
# The link is read without `-f`: it is already fully resolved, and by the
|
||||||
|
# time this runs `pacman -U` has replaced the binary, so a leftover process
|
||||||
|
# points at an unlinked inode that the kernel reports with a " (deleted)"
|
||||||
|
# suffix. That suffix has to be stripped or the match silently misses the
|
||||||
|
# one process this exists to kill.
|
||||||
|
local pid exe killed=()
|
||||||
|
for pid in /proc/[0-9]*; do
|
||||||
|
pid="${pid#/proc/}"
|
||||||
|
exe="$(readlink "/proc/$pid/exe" 2>/dev/null)" || continue
|
||||||
|
exe="${exe% (deleted)}"
|
||||||
|
[[ "$exe" == /opt/*/bin/"$wrapper" ]] || continue
|
||||||
|
kill -TERM "$pid" 2>/dev/null && killed+=("$pid")
|
||||||
|
done
|
||||||
|
if ((${#killed[@]})); then
|
||||||
|
info "stopped a running instance so the launch check is meaningful"
|
||||||
|
# `kill` only reports that the signal was sent. Waiting for the process
|
||||||
|
# to actually go keeps a slow exit from failing the cold start below on
|
||||||
|
# a port that is still bound.
|
||||||
|
local waited=0
|
||||||
|
while ((waited < 100)) && kill -0 "${killed[@]}" 2>/dev/null; do
|
||||||
|
sleep 0.1
|
||||||
|
((waited++))
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
output="$(timeout 15 "/usr/bin/$binary" 2>&1 | head -3 || true)"
|
||||||
|
if grep -qF "$expected" <<<"$output"; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
warn "unexpected startup output: $output"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# The AUR does not review uploads, but "packages that violate the rules may be
|
||||||
|
# deleted without warning" (AUR submission guidelines). These are the rules that
|
||||||
|
# are mechanically checkable, enforced here so a violation blocks the push
|
||||||
|
# rather than surfacing later as a deletion request.
|
||||||
|
check_aur_rules() {
|
||||||
|
local pkg="$1" problems=()
|
||||||
|
|
||||||
|
grep -q '^# Maintainer:' PKGBUILD \
|
||||||
|
|| problems+=("missing '# Maintainer:' comment on line 1")
|
||||||
|
|
||||||
|
grep -qE "^arch=\(.*x86_64" PKGBUILD \
|
||||||
|
|| problems+=("x86_64 not in arch=() — packages without it are not allowed")
|
||||||
|
|
||||||
|
# `replaces` makes pacman rip out the named package on the next -Sy, which
|
||||||
|
# is only correct for a genuine rename. `conflicts` is the right tool.
|
||||||
|
grep -q '^replaces=' PKGBUILD \
|
||||||
|
&& problems+=("uses replaces=; AUR rules reserve it for renames — use conflicts=")
|
||||||
|
|
||||||
|
# A package already in an official repo must never be duplicated.
|
||||||
|
if pacman -Si "$pkg" >/dev/null 2>&1; then
|
||||||
|
problems+=("$pkg exists in an official repo — must not be submitted")
|
||||||
|
fi
|
||||||
|
|
||||||
|
grep -qE '^(pkgdesc|url|license)=' PKGBUILD \
|
||||||
|
|| problems+=("missing pkgdesc/url/license")
|
||||||
|
|
||||||
|
# A stale .SRCINFO is the single most common upload rejection.
|
||||||
|
if ! diff -q <(makepkg --printsrcinfo) .SRCINFO >/dev/null 2>&1; then
|
||||||
|
problems+=(".SRCINFO does not match PKGBUILD")
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ((${#problems[@]})); then
|
||||||
|
warn "$pkg: AUR rule violations:"
|
||||||
|
printf ' - %s\n' "${problems[@]}"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
info "AUR rule checks passed"
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
@ -86,305 +86,14 @@ require_tools() {
|
|||||||
# Phase 1: wait for registration, then for the key to work
|
# Phase 1: wait for registration, then for the key to work
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
register_status() {
|
# The rest lives in lib/, sourced (not executed) so every function sees the
|
||||||
python3 "$GATE" /register 2>/dev/null | head -1
|
# readonly config above and the mutable FAILED/PUBLISHED arrays main() reads.
|
||||||
}
|
# shellcheck source=lib/aur_registration.sh
|
||||||
|
source "$SCRIPT_DIR/lib/aur_registration.sh"
|
||||||
open_browser() {
|
# shellcheck source=lib/aur_verify.sh
|
||||||
local url="$1"
|
source "$SCRIPT_DIR/lib/aur_verify.sh"
|
||||||
local browser
|
# shellcheck source=lib/aur_publish_one.sh
|
||||||
for browser in xdg-open thorium-browser chromium google-chrome-stable firefox librewolf; do
|
source "$SCRIPT_DIR/lib/aur_publish_one.sh"
|
||||||
if command -v "$browser" >/dev/null 2>&1; then
|
|
||||||
"$browser" "$url" >/dev/null 2>&1 &
|
|
||||||
info "Opened $url in $browser"
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
warn "No browser found; open this yourself: $url"
|
|
||||||
}
|
|
||||||
|
|
||||||
ensure_key() {
|
|
||||||
if [[ ! -f "$SSH_KEY" ]]; then
|
|
||||||
log "Generating an AUR SSH key (none at $SSH_KEY)"
|
|
||||||
ssh-keygen -t ed25519 -f "$SSH_KEY" -N '' -C 'kuhy@aur'
|
|
||||||
fi
|
|
||||||
if ! grep -q "Host $AUR_HOST" "$HOME/.ssh/config" 2>/dev/null; then
|
|
||||||
log "Adding $AUR_HOST to ~/.ssh/config"
|
|
||||||
mkdir -p "$HOME/.ssh"
|
|
||||||
cat >> "$HOME/.ssh/config" <<EOF
|
|
||||||
|
|
||||||
# AUR uses a dedicated key so it stays separate from the GitHub identity.
|
|
||||||
Host $AUR_HOST
|
|
||||||
User aur
|
|
||||||
IdentityFile $SSH_KEY
|
|
||||||
IdentitiesOnly yes
|
|
||||||
EOF
|
|
||||||
chmod 600 "$HOME/.ssh/config"
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
ssh_works() {
|
|
||||||
# The AUR refuses interactive shells; "Interactive shell is disabled" on a
|
|
||||||
# successful key auth is the success signal, not an error.
|
|
||||||
ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new \
|
|
||||||
-o ConnectTimeout=15 "aur@$AUR_HOST" help 2>&1 |
|
|
||||||
grep -qiE 'interactive shell is disabled|Welcome to AUR'
|
|
||||||
}
|
|
||||||
|
|
||||||
wait_for_registration() {
|
|
||||||
local status
|
|
||||||
status="$(register_status)"
|
|
||||||
if [[ "$status" == "200" ]]; then
|
|
||||||
log "AUR registration is OPEN"
|
|
||||||
else
|
|
||||||
log "AUR registration is closed (HTTP $status). Polling every ${POLL_SECONDS}s."
|
|
||||||
info "Ctrl-C to stop; re-run any time, nothing is lost."
|
|
||||||
while :; do
|
|
||||||
sleep "$POLL_SECONDS"
|
|
||||||
status="$(register_status)"
|
|
||||||
if [[ "$status" == "200" ]]; then
|
|
||||||
log "Registration is BACK (HTTP 200)"
|
|
||||||
break
|
|
||||||
fi
|
|
||||||
printf ' %s still HTTP %s\n' "$(date +%H:%M)" "$status"
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
open_browser "https://$AUR_HOST/register"
|
|
||||||
cat <<EOF
|
|
||||||
|
|
||||||
------------------------------------------------------------------
|
|
||||||
Sign up, and paste this into the "SSH Public Key" field:
|
|
||||||
|
|
||||||
$(sed 's/^/ /' "$SSH_KEY.pub")
|
|
||||||
|
|
||||||
You will need to confirm the address from your email before the
|
|
||||||
account works. This script waits for that automatically.
|
|
||||||
------------------------------------------------------------------
|
|
||||||
EOF
|
|
||||||
}
|
|
||||||
|
|
||||||
wait_for_ssh() {
|
|
||||||
log "Waiting for the SSH key to authenticate against the AUR"
|
|
||||||
local waited=0
|
|
||||||
until ssh_works; do
|
|
||||||
sleep 30
|
|
||||||
waited=$((waited + 30))
|
|
||||||
if ((waited % 300 == 0)); then
|
|
||||||
info "still waiting ($((waited / 60)) min) — key not accepted yet"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
log "SSH authentication OK"
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Phase 2: build, verify and publish one package
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
newest_tag() {
|
|
||||||
# Newest clean vX.Y.Z on the remote. Build tags (vX.Y.Z-build.N) and the
|
|
||||||
# grafted upstream Flutter SDK tags in diet-guard are excluded on purpose.
|
|
||||||
git -C "$1" ls-remote --tags origin 2>/dev/null |
|
|
||||||
awk '{print $2}' |
|
|
||||||
sed 's|refs/tags/||' |
|
|
||||||
grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' |
|
|
||||||
sed 's/^v//' |
|
|
||||||
sort -V |
|
|
||||||
tail -1
|
|
||||||
}
|
|
||||||
|
|
||||||
verify_installed() {
|
|
||||||
local binary="$1" expected="$2" wrapper="$3" output
|
|
||||||
|
|
||||||
# An instance left over from a previous run would make the wrapper print
|
|
||||||
# "already running" and hand off, which passes trivially and turns the
|
|
||||||
# strongest gate in this script into the weakest. Clear it first so the
|
|
||||||
# check always exercises a real cold start.
|
|
||||||
#
|
|
||||||
# Resolved through /proc/<pid>/exe rather than any form of name or
|
|
||||||
# command-line matching. Every argv-based approach selects the wrong
|
|
||||||
# processes here:
|
|
||||||
# * `pkill -x` compares against the kernel's 15-character comm field, and
|
|
||||||
# two of these wrappers are longer (habit_stack_desktop is 19), so a
|
|
||||||
# name match would silently never fire.
|
|
||||||
# * `pkill -f`, and equally `ps -eo args` piped through a pattern, match
|
|
||||||
# any process whose command line merely *mentions* the path — this
|
|
||||||
# script, the shell running it, and the matching tool itself all
|
|
||||||
# qualify, so the run kills its own shell instead of the app. A
|
|
||||||
# $$/$PPID guard does not cover it, because the offending shell is
|
|
||||||
# often a more distant ancestor.
|
|
||||||
# /proc/<pid>/exe is a kernel-maintained symlink to the binary actually
|
|
||||||
# being executed, so it cannot collide with an incidental mention.
|
|
||||||
# The wrapper name is unique per app, so the /opt/<pkg>/ segment is left as
|
|
||||||
# a glob instead of threading the package name through another parameter.
|
|
||||||
#
|
|
||||||
# The link is read without `-f`: it is already fully resolved, and by the
|
|
||||||
# time this runs `pacman -U` has replaced the binary, so a leftover process
|
|
||||||
# points at an unlinked inode that the kernel reports with a " (deleted)"
|
|
||||||
# suffix. That suffix has to be stripped or the match silently misses the
|
|
||||||
# one process this exists to kill.
|
|
||||||
local pid exe killed=()
|
|
||||||
for pid in /proc/[0-9]*; do
|
|
||||||
pid="${pid#/proc/}"
|
|
||||||
exe="$(readlink "/proc/$pid/exe" 2>/dev/null)" || continue
|
|
||||||
exe="${exe% (deleted)}"
|
|
||||||
[[ "$exe" == /opt/*/bin/"$wrapper" ]] || continue
|
|
||||||
kill -TERM "$pid" 2>/dev/null && killed+=("$pid")
|
|
||||||
done
|
|
||||||
if ((${#killed[@]})); then
|
|
||||||
info "stopped a running instance so the launch check is meaningful"
|
|
||||||
# `kill` only reports that the signal was sent. Waiting for the process
|
|
||||||
# to actually go keeps a slow exit from failing the cold start below on
|
|
||||||
# a port that is still bound.
|
|
||||||
local waited=0
|
|
||||||
while ((waited < 100)) && kill -0 "${killed[@]}" 2>/dev/null; do
|
|
||||||
sleep 0.1
|
|
||||||
((waited++))
|
|
||||||
done
|
|
||||||
fi
|
|
||||||
|
|
||||||
output="$(timeout 15 "/usr/bin/$binary" 2>&1 | head -3 || true)"
|
|
||||||
if grep -qF "$expected" <<<"$output"; then
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
warn "unexpected startup output: $output"
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# The AUR does not review uploads, but "packages that violate the rules may be
|
|
||||||
# deleted without warning" (AUR submission guidelines). These are the rules that
|
|
||||||
# are mechanically checkable, enforced here so a violation blocks the push
|
|
||||||
# rather than surfacing later as a deletion request.
|
|
||||||
check_aur_rules() {
|
|
||||||
local pkg="$1" problems=()
|
|
||||||
|
|
||||||
grep -q '^# Maintainer:' PKGBUILD \
|
|
||||||
|| problems+=("missing '# Maintainer:' comment on line 1")
|
|
||||||
|
|
||||||
grep -qE "^arch=\(.*x86_64" PKGBUILD \
|
|
||||||
|| problems+=("x86_64 not in arch=() — packages without it are not allowed")
|
|
||||||
|
|
||||||
# `replaces` makes pacman rip out the named package on the next -Sy, which
|
|
||||||
# is only correct for a genuine rename. `conflicts` is the right tool.
|
|
||||||
grep -q '^replaces=' PKGBUILD \
|
|
||||||
&& problems+=("uses replaces=; AUR rules reserve it for renames — use conflicts=")
|
|
||||||
|
|
||||||
# A package already in an official repo must never be duplicated.
|
|
||||||
if pacman -Si "$pkg" >/dev/null 2>&1; then
|
|
||||||
problems+=("$pkg exists in an official repo — must not be submitted")
|
|
||||||
fi
|
|
||||||
|
|
||||||
grep -qE '^(pkgdesc|url|license)=' PKGBUILD \
|
|
||||||
|| problems+=("missing pkgdesc/url/license")
|
|
||||||
|
|
||||||
# A stale .SRCINFO is the single most common upload rejection.
|
|
||||||
if ! diff -q <(makepkg --printsrcinfo) .SRCINFO >/dev/null 2>&1; then
|
|
||||||
problems+=(".SRCINFO does not match PKGBUILD")
|
|
||||||
fi
|
|
||||||
|
|
||||||
if ((${#problems[@]})); then
|
|
||||||
warn "$pkg: AUR rule violations:"
|
|
||||||
printf ' - %s\n' "${problems[@]}"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
info "AUR rule checks passed"
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
publish_one() {
|
|
||||||
local pkg="$1" repo="$2" wrapper="$3" binary="$4" expected="$5"
|
|
||||||
local dir="$AUR_ROOT/$pkg"
|
|
||||||
local version
|
|
||||||
|
|
||||||
log "$pkg"
|
|
||||||
|
|
||||||
[[ -d "$repo" ]] || { warn "$pkg: no repo at $repo"; return 1; }
|
|
||||||
[[ -f "$dir/PKGBUILD" ]] || { warn "$pkg: no PKGBUILD at $dir"; return 1; }
|
|
||||||
|
|
||||||
version="$(newest_tag "$repo")"
|
|
||||||
[[ -n "$version" ]] || { warn "$pkg: no vX.Y.Z tag on the remote"; return 1; }
|
|
||||||
info "newest release tag: v$version"
|
|
||||||
|
|
||||||
cd "$dir"
|
|
||||||
sed -i -E "s/^pkgver=.*/pkgver=$version/" PKGBUILD
|
|
||||||
# The tarball for a tag contains the PKGBUILD, so the checksum can only be
|
|
||||||
# computed after the tag exists — never committed ahead of time.
|
|
||||||
updpkgsums >/dev/null 2>&1 || { warn "$pkg: updpkgsums failed (tag missing?)"; return 1; }
|
|
||||||
|
|
||||||
info "building"
|
|
||||||
if ! env PATH=/usr/bin:/bin:/usr/local/bin makepkg -Cf --noconfirm >/dev/null 2>&1; then
|
|
||||||
warn "$pkg: makepkg failed"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
local built
|
|
||||||
built="$(find . -maxdepth 1 -name "$pkg-$version-*.pkg.tar.zst" | head -1)"
|
|
||||||
[[ -n "$built" ]] || { warn "$pkg: no package produced"; return 1; }
|
|
||||||
|
|
||||||
# namcap's "ELF files outside of a valid path ('opt/')" is a false positive
|
|
||||||
# for /opt-installed apps, so only genuinely new errors are worth failing on.
|
|
||||||
local findings
|
|
||||||
findings="$(namcap "$built" 2>&1 | grep -E ' E: ' | grep -v "outside of a valid path" || true)"
|
|
||||||
if [[ -n "$findings" ]]; then
|
|
||||||
warn "$pkg: namcap errors:"
|
|
||||||
printf ' %s\n' "$findings"
|
|
||||||
return 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
info "installing and launching"
|
|
||||||
sudo pacman -U --noconfirm "$built" >/dev/null 2>&1 \
|
|
||||||
|| { warn "$pkg: pacman -U failed"; return 1; }
|
|
||||||
verify_installed "$binary" "$expected" "$wrapper" || { warn "$pkg: launch check failed"; return 1; }
|
|
||||||
|
|
||||||
# Generated before the rule check, which verifies it matches the PKGBUILD.
|
|
||||||
makepkg --printsrcinfo > .SRCINFO
|
|
||||||
check_aur_rules "$pkg" || return 1
|
|
||||||
|
|
||||||
# The AUR repo is a separate remote living alongside the build dir; adding
|
|
||||||
# it here (rather than cloning into a fresh path) keeps the verified
|
|
||||||
# PKGBUILD and the thing being pushed byte-identical.
|
|
||||||
if [[ ! -d .git ]]; then
|
|
||||||
git init -q -b master .
|
|
||||||
git remote add origin "ssh://aur@$AUR_HOST/$pkg.git"
|
|
||||||
fi
|
|
||||||
git remote get-url origin >/dev/null 2>&1 \
|
|
||||||
|| git remote add origin "ssh://aur@$AUR_HOST/$pkg.git"
|
|
||||||
|
|
||||||
# Fetch first: an existing AUR package must be built on, not overwritten.
|
|
||||||
if git fetch -q origin master 2>/dev/null; then
|
|
||||||
git reset -q --soft FETCH_HEAD 2>/dev/null || true
|
|
||||||
fi
|
|
||||||
|
|
||||||
cat > .gitignore <<'EOF'
|
|
||||||
# Build products; the AUR tracks only the recipe.
|
|
||||||
*.pkg.tar.zst
|
|
||||||
*.tar.gz
|
|
||||||
src/
|
|
||||||
pkg/
|
|
||||||
EOF
|
|
||||||
|
|
||||||
git add PKGBUILD .SRCINFO .gitignore
|
|
||||||
if git diff --cached --quiet; then
|
|
||||||
info "already up to date on the AUR; nothing to push"
|
|
||||||
PUBLISHED+=("$pkg v$version (unchanged)")
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
git -c user.name='Krzysztof Rudnicki' \
|
|
||||||
-c user.email='krzysztofrudnicki0@gmail.com' \
|
|
||||||
commit -q -m "$pkg $version-1"
|
|
||||||
|
|
||||||
if ((DRY_RUN)); then
|
|
||||||
info "DRY RUN — not pushing"
|
|
||||||
PUBLISHED+=("$pkg v$version (dry run)")
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
|
|
||||||
info "pushing to the AUR"
|
|
||||||
git push -q origin master 2>&1 | tail -3 || { warn "$pkg: push failed"; return 1; }
|
|
||||||
PUBLISHED+=("$pkg v$version")
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
require_tools
|
require_tools
|
||||||
|
|||||||
152
crdt_sync_dart/test/firebase_auth_rest_google_test.dart
Normal file
152
crdt_sync_dart/test/firebase_auth_rest_google_test.dart
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
/// A fixed "now" so token expiry is deterministic rather than wall-clock.
|
||||||
|
final _now = DateTime.utc(2026, 8, 3, 12);
|
||||||
|
|
||||||
|
http.Response _json(int statusCode, Object body) =>
|
||||||
|
http.Response(jsonEncode(body), statusCode);
|
||||||
|
|
||||||
|
/// Builds a provider whose POSTs return [responses] in call order (each
|
||||||
|
/// either an [http.Response] or a thrown [http.ClientException]).
|
||||||
|
FirebaseTokenProvider _provider(
|
||||||
|
List<Object> responses, {
|
||||||
|
FirebaseCredentialStore? store,
|
||||||
|
DateTime? now,
|
||||||
|
}) {
|
||||||
|
var index = 0;
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
final response = responses[index];
|
||||||
|
index++;
|
||||||
|
if (response is http.ClientException) throw response;
|
||||||
|
return response as http.Response;
|
||||||
|
});
|
||||||
|
return FirebaseTokenProvider(
|
||||||
|
apiKey: 'fake-api-key',
|
||||||
|
store: store ?? InMemoryCredentialStore(),
|
||||||
|
httpClient: mock,
|
||||||
|
clock: () => now ?? _now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('signInWithGoogle', () {
|
||||||
|
test('stores the session returned by identitytoolkit', () async {
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await provider.signInWithGoogle(idToken: 'google-token');
|
||||||
|
|
||||||
|
final saved = await store.load();
|
||||||
|
expect(saved!.idToken, 'id-g');
|
||||||
|
expect(saved.refreshToken, 'refresh-g');
|
||||||
|
expect(saved.expiresAt, _now.add(const Duration(hours: 1)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('posts the IdP credential form-encoded to signInWithIdp', () async {
|
||||||
|
// The identitytoolkit quirk worth pinning: the Google token travels in a
|
||||||
|
// form-encoded `postBody` string, not as a JSON field. Getting this
|
||||||
|
// wrong returns INVALID_IDP_RESPONSE, which reads like a bad token.
|
||||||
|
late http.Request captured;
|
||||||
|
final provider = FirebaseTokenProvider(
|
||||||
|
apiKey: 'fake-api-key',
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
httpClient: http_testing.MockClient((request) async {
|
||||||
|
captured = request;
|
||||||
|
return _json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
clock: () => _now,
|
||||||
|
);
|
||||||
|
|
||||||
|
await provider.signInWithGoogle(idToken: 'google-token');
|
||||||
|
|
||||||
|
expect(captured.url.path, contains('accounts:signInWithIdp'));
|
||||||
|
final body = jsonDecode(captured.body) as Map<String, dynamic>;
|
||||||
|
expect(body['postBody'], 'id_token=google-token&providerId=google.com');
|
||||||
|
expect(body['returnSecureToken'], isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reports Google\'s reason on a rejected token', () async {
|
||||||
|
final provider = _provider([
|
||||||
|
_json(400, {
|
||||||
|
'error': {'message': 'INVALID_IDP_RESPONSE'},
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
() => provider.signInWithGoogle(idToken: 'stale-token'),
|
||||||
|
throwsA(
|
||||||
|
isA<FirebaseAuthError>().having(
|
||||||
|
(e) => e.message,
|
||||||
|
'message',
|
||||||
|
contains('INVALID_IDP_RESPONSE'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('leaves no session stored when the token is rejected', () async {
|
||||||
|
// A failed Google sign-in must not look like a signed-in device: the
|
||||||
|
// next idToken() has to fail loudly rather than serve a stale token.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(400, {
|
||||||
|
'error': {'message': 'INVALID_IDP_RESPONSE'},
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await expectLater(
|
||||||
|
() => provider.signInWithGoogle(idToken: 'bad'),
|
||||||
|
throwsA(isA<FirebaseAuthError>()),
|
||||||
|
);
|
||||||
|
expect(await store.load(), isNull);
|
||||||
|
expect(await provider.hasSession(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns the email Firebase reports', () async {
|
||||||
|
// A fresh install knows no email until Firebase answers with one, so
|
||||||
|
// this return value is what lets the device store its account. Reading
|
||||||
|
// the email from anywhere on-device instead would store an empty one.
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'email': 'signed-in@example.com',
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(
|
||||||
|
await provider.signInWithGoogle(idToken: 'token'),
|
||||||
|
'signed-in@example.com',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns null when the response carries no email', () async {
|
||||||
|
// Not fatal: the session is still valid, so sign-in succeeds and the
|
||||||
|
// caller simply has no address to display.
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(await provider.signInWithGoogle(idToken: 'token'), isNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -150,376 +150,4 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('signInWithGoogle', () {
|
|
||||||
test('stores the session returned by identitytoolkit', () async {
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await provider.signInWithGoogle(idToken: 'google-token');
|
|
||||||
|
|
||||||
final saved = await store.load();
|
|
||||||
expect(saved!.idToken, 'id-g');
|
|
||||||
expect(saved.refreshToken, 'refresh-g');
|
|
||||||
expect(saved.expiresAt, _now.add(const Duration(hours: 1)));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('posts the IdP credential form-encoded to signInWithIdp', () async {
|
|
||||||
// The identitytoolkit quirk worth pinning: the Google token travels in a
|
|
||||||
// form-encoded `postBody` string, not as a JSON field. Getting this
|
|
||||||
// wrong returns INVALID_IDP_RESPONSE, which reads like a bad token.
|
|
||||||
late http.Request captured;
|
|
||||||
final provider = FirebaseTokenProvider(
|
|
||||||
apiKey: 'fake-api-key',
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
httpClient: http_testing.MockClient((request) async {
|
|
||||||
captured = request;
|
|
||||||
return _json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
});
|
|
||||||
}),
|
|
||||||
clock: () => _now,
|
|
||||||
);
|
|
||||||
|
|
||||||
await provider.signInWithGoogle(idToken: 'google-token');
|
|
||||||
|
|
||||||
expect(captured.url.path, contains('accounts:signInWithIdp'));
|
|
||||||
final body = jsonDecode(captured.body) as Map<String, dynamic>;
|
|
||||||
expect(body['postBody'], 'id_token=google-token&providerId=google.com');
|
|
||||||
expect(body['returnSecureToken'], isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('reports Google\'s reason on a rejected token', () async {
|
|
||||||
final provider = _provider([
|
|
||||||
_json(400, {
|
|
||||||
'error': {'message': 'INVALID_IDP_RESPONSE'},
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
expect(
|
|
||||||
() => provider.signInWithGoogle(idToken: 'stale-token'),
|
|
||||||
throwsA(
|
|
||||||
isA<FirebaseAuthError>().having(
|
|
||||||
(e) => e.message,
|
|
||||||
'message',
|
|
||||||
contains('INVALID_IDP_RESPONSE'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('leaves no session stored when the token is rejected', () async {
|
|
||||||
// A failed Google sign-in must not look like a signed-in device: the
|
|
||||||
// next idToken() has to fail loudly rather than serve a stale token.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(400, {
|
|
||||||
'error': {'message': 'INVALID_IDP_RESPONSE'},
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await expectLater(
|
|
||||||
() => provider.signInWithGoogle(idToken: 'bad'),
|
|
||||||
throwsA(isA<FirebaseAuthError>()),
|
|
||||||
);
|
|
||||||
expect(await store.load(), isNull);
|
|
||||||
expect(await provider.hasSession(), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('returns the email Firebase reports', () async {
|
|
||||||
// A fresh install knows no email until Firebase answers with one, so
|
|
||||||
// this return value is what lets the device store its account. Reading
|
|
||||||
// the email from anywhere on-device instead would store an empty one.
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'email': 'signed-in@example.com',
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
await provider.signInWithGoogle(idToken: 'token'),
|
|
||||||
'signed-in@example.com',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('returns null when the response carries no email', () async {
|
|
||||||
// Not fatal: the session is still valid, so sign-in succeeds and the
|
|
||||||
// caller simply has no address to display.
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
expect(await provider.signInWithGoogle(idToken: 'token'), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('rejects a session for a uid other than the expected one', () async {
|
|
||||||
// The mis-tapped-account-picker case. signInWithIdp signs in OR SIGNS
|
|
||||||
// UP, so an unlinked Google identity is accepted as a brand-new user
|
|
||||||
// rather than refused. Without this check the device would store that
|
|
||||||
// session and then be denied every read and write, permanently.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'localId': 'some-other-uid',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await expectLater(
|
|
||||||
() => provider.signInWithGoogle(
|
|
||||||
idToken: 'token-for-the-wrong-account',
|
|
||||||
expectedUid: 'the-right-uid',
|
|
||||||
),
|
|
||||||
throwsA(
|
|
||||||
isA<FirebaseAuthError>().having(
|
|
||||||
(e) => e.message,
|
|
||||||
'message',
|
|
||||||
allOf(contains('some-other-uid'), contains('the-right-uid')),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
await store.load(),
|
|
||||||
isNull,
|
|
||||||
reason: 'a wrong-account session must not persist',
|
|
||||||
);
|
|
||||||
expect(await provider.hasSession(), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('accepts a session whose uid matches the expected one', () async {
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'localId': 'the-right-uid',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await provider.signInWithGoogle(
|
|
||||||
idToken: 'token',
|
|
||||||
expectedUid: 'the-right-uid',
|
|
||||||
);
|
|
||||||
|
|
||||||
expect((await store.load())!.idToken, 'id-g');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('skips the uid check when no uid is expected', () async {
|
|
||||||
// FirebaseProject.configFor leaves uid empty on the app path; comparing
|
|
||||||
// against '' would otherwise fail every sign-in.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'localId': 'whatever-uid',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await provider.signInWithGoogle(idToken: 'token', expectedUid: '');
|
|
||||||
|
|
||||||
expect((await store.load())!.idToken, 'id-g');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('its session refreshes like a password session', () async {
|
|
||||||
// signInWithIdp returns the same refresh-token shape as
|
|
||||||
// signInWithPassword, which is why the refresh path needed no changes.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-g',
|
|
||||||
'refreshToken': 'refresh-g',
|
|
||||||
// Already inside the refresh skew, so the next read must refresh.
|
|
||||||
'expiresIn': '60',
|
|
||||||
}),
|
|
||||||
_json(200, {
|
|
||||||
'id_token': 'id-g2',
|
|
||||||
'refresh_token': 'refresh-g2',
|
|
||||||
'expires_in': '3600',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await provider.signInWithGoogle(idToken: 'google-token');
|
|
||||||
expect(await provider.idToken(), 'id-g2');
|
|
||||||
expect((await store.load())!.refreshToken, 'refresh-g2');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('idToken', () {
|
|
||||||
test('fails loudly when no session is stored', () {
|
|
||||||
// Never returns null or a stale token: a sync that quietly stops
|
|
||||||
// syncing is exactly the failure mode being designed out.
|
|
||||||
expect(
|
|
||||||
_provider([]).idToken,
|
|
||||||
throwsA(
|
|
||||||
isA<FirebaseAuthError>().having(
|
|
||||||
(e) => e.message,
|
|
||||||
'message',
|
|
||||||
contains('not signed in'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('returns the stored token without a network call', () async {
|
|
||||||
// An empty response list means any HTTP call would throw a range error.
|
|
||||||
final provider = _provider(
|
|
||||||
[],
|
|
||||||
store: InMemoryCredentialStore(_credentials()),
|
|
||||||
);
|
|
||||||
expect(await provider.idToken(), 'id-1');
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'refreshes an expired token and persists the rotated refresh token',
|
|
||||||
() async {
|
|
||||||
final store = InMemoryCredentialStore(
|
|
||||||
_credentials(validFor: const Duration(minutes: -5)),
|
|
||||||
);
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'id_token': 'id-2',
|
|
||||||
'refresh_token': 'refresh-2',
|
|
||||||
'expires_in': '3600',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
expect(await provider.idToken(), 'id-2');
|
|
||||||
final saved = await store.load();
|
|
||||||
expect(saved!.refreshToken, 'refresh-2');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('fails loudly when the refresh token has been revoked', () async {
|
|
||||||
final provider = _provider(
|
|
||||||
[
|
|
||||||
_json(400, {
|
|
||||||
'error': {'message': 'TOKEN_EXPIRED'},
|
|
||||||
}),
|
|
||||||
],
|
|
||||||
store: InMemoryCredentialStore(
|
|
||||||
_credentials(validFor: const Duration(minutes: -5)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
provider.idToken,
|
|
||||||
throwsA(
|
|
||||||
isA<FirebaseAuthError>().having(
|
|
||||||
(e) => e.message,
|
|
||||||
'message',
|
|
||||||
contains('TOKEN_EXPIRED'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('session lifecycle', () {
|
|
||||||
test('hasSession is false before sign-in and true after', () async {
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final provider = _provider([
|
|
||||||
_json(200, {
|
|
||||||
'idToken': 'id-1',
|
|
||||||
'refreshToken': 'refresh-1',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
expect(await provider.hasSession(), isFalse);
|
|
||||||
await provider.signIn(email: 'a@b.c', password: 'x');
|
|
||||||
expect(await provider.hasSession(), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('signOut clears the store so the next idToken fails', () async {
|
|
||||||
final provider = _provider(
|
|
||||||
[],
|
|
||||||
store: InMemoryCredentialStore(_credentials()),
|
|
||||||
);
|
|
||||||
expect(await provider.idToken(), 'id-1');
|
|
||||||
await provider.signOut();
|
|
||||||
expect(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('close releases the HTTP client', () {
|
|
||||||
expect(_provider([]).close, returnsNormally);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('a refresh token the server rejects', () {
|
|
||||||
// Regression: hasSession() was a presence check, so a revoked token still
|
|
||||||
// read as "Connected" while every sync died with TOKEN_EXPIRED. Observed
|
|
||||||
// on the desktop todo build on 2026-08-11.
|
|
||||||
test(
|
|
||||||
'is cleared, so hasSession stops claiming the device is connected',
|
|
||||||
() async {
|
|
||||||
final store = InMemoryCredentialStore(
|
|
||||||
_credentials(validFor: const Duration(seconds: -1)),
|
|
||||||
);
|
|
||||||
final provider = _provider([
|
|
||||||
_json(400, {
|
|
||||||
'error': {'message': 'TOKEN_EXPIRED'},
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await expectLater(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
|
||||||
expect(
|
|
||||||
await provider.hasSession(),
|
|
||||||
isFalse,
|
|
||||||
reason: 'a revoked session must not keep reporting as connected',
|
|
||||||
);
|
|
||||||
expect(await store.load(), isNull);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('survives a network error, which is transient', () async {
|
|
||||||
// The opposite failure: signing out whenever the wifi drops would need a
|
|
||||||
// manual sign-in on every device to recover.
|
|
||||||
final store = InMemoryCredentialStore(
|
|
||||||
_credentials(validFor: const Duration(seconds: -1)),
|
|
||||||
);
|
|
||||||
final provider = _provider([
|
|
||||||
http.ClientException('connection reset'),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await expectLater(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
|
||||||
expect(
|
|
||||||
await provider.hasSession(),
|
|
||||||
isTrue,
|
|
||||||
reason: 'a transient failure must not discard a good refresh token',
|
|
||||||
);
|
|
||||||
expect(await store.load(), isNotNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('survives a 5xx, which is also transient', () async {
|
|
||||||
final store = InMemoryCredentialStore(
|
|
||||||
_credentials(validFor: const Duration(seconds: -1)),
|
|
||||||
);
|
|
||||||
final provider = _provider([
|
|
||||||
_json(503, {
|
|
||||||
'error': {'message': 'SERVICE_UNAVAILABLE'},
|
|
||||||
}),
|
|
||||||
], store: store);
|
|
||||||
|
|
||||||
await expectLater(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
|
||||||
expect(await provider.hasSession(), isTrue);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
206
crdt_sync_dart/test/firebase_auth_rest_tokens_test.dart
Normal file
206
crdt_sync_dart/test/firebase_auth_rest_tokens_test.dart
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
/// A fixed "now" so token expiry is deterministic rather than wall-clock.
|
||||||
|
final _now = DateTime.utc(2026, 8, 3, 12);
|
||||||
|
|
||||||
|
http.Response _json(int statusCode, Object body) =>
|
||||||
|
http.Response(jsonEncode(body), statusCode);
|
||||||
|
|
||||||
|
/// Builds a provider whose POSTs return [responses] in call order (each
|
||||||
|
/// either an [http.Response] or a thrown [http.ClientException]).
|
||||||
|
FirebaseTokenProvider _provider(
|
||||||
|
List<Object> responses, {
|
||||||
|
FirebaseCredentialStore? store,
|
||||||
|
DateTime? now,
|
||||||
|
}) {
|
||||||
|
var index = 0;
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
final response = responses[index];
|
||||||
|
index++;
|
||||||
|
if (response is http.ClientException) throw response;
|
||||||
|
return response as http.Response;
|
||||||
|
});
|
||||||
|
return FirebaseTokenProvider(
|
||||||
|
apiKey: 'fake-api-key',
|
||||||
|
store: store ?? InMemoryCredentialStore(),
|
||||||
|
httpClient: mock,
|
||||||
|
clock: () => now ?? _now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
FirebaseCredentials _credentials({
|
||||||
|
String idToken = 'id-1',
|
||||||
|
String refreshToken = 'refresh-1',
|
||||||
|
Duration validFor = const Duration(hours: 1),
|
||||||
|
}) => FirebaseCredentials(
|
||||||
|
idToken: idToken,
|
||||||
|
refreshToken: refreshToken,
|
||||||
|
expiresAt: _now.add(validFor),
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('idToken', () {
|
||||||
|
test('fails loudly when no session is stored', () {
|
||||||
|
// Never returns null or a stale token: a sync that quietly stops
|
||||||
|
// syncing is exactly the failure mode being designed out.
|
||||||
|
expect(
|
||||||
|
_provider([]).idToken,
|
||||||
|
throwsA(
|
||||||
|
isA<FirebaseAuthError>().having(
|
||||||
|
(e) => e.message,
|
||||||
|
'message',
|
||||||
|
contains('not signed in'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns the stored token without a network call', () async {
|
||||||
|
// An empty response list means any HTTP call would throw a range error.
|
||||||
|
final provider = _provider(
|
||||||
|
[],
|
||||||
|
store: InMemoryCredentialStore(_credentials()),
|
||||||
|
);
|
||||||
|
expect(await provider.idToken(), 'id-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'refreshes an expired token and persists the rotated refresh token',
|
||||||
|
() async {
|
||||||
|
final store = InMemoryCredentialStore(
|
||||||
|
_credentials(validFor: const Duration(minutes: -5)),
|
||||||
|
);
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'id_token': 'id-2',
|
||||||
|
'refresh_token': 'refresh-2',
|
||||||
|
'expires_in': '3600',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
expect(await provider.idToken(), 'id-2');
|
||||||
|
final saved = await store.load();
|
||||||
|
expect(saved!.refreshToken, 'refresh-2');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('fails loudly when the refresh token has been revoked', () async {
|
||||||
|
final provider = _provider(
|
||||||
|
[
|
||||||
|
_json(400, {
|
||||||
|
'error': {'message': 'TOKEN_EXPIRED'},
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
store: InMemoryCredentialStore(
|
||||||
|
_credentials(validFor: const Duration(minutes: -5)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
provider.idToken,
|
||||||
|
throwsA(
|
||||||
|
isA<FirebaseAuthError>().having(
|
||||||
|
(e) => e.message,
|
||||||
|
'message',
|
||||||
|
contains('TOKEN_EXPIRED'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('session lifecycle', () {
|
||||||
|
test('hasSession is false before sign-in and true after', () async {
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-1',
|
||||||
|
'refreshToken': 'refresh-1',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
expect(await provider.hasSession(), isFalse);
|
||||||
|
await provider.signIn(email: 'a@b.c', password: 'x');
|
||||||
|
expect(await provider.hasSession(), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('signOut clears the store so the next idToken fails', () async {
|
||||||
|
final provider = _provider(
|
||||||
|
[],
|
||||||
|
store: InMemoryCredentialStore(_credentials()),
|
||||||
|
);
|
||||||
|
expect(await provider.idToken(), 'id-1');
|
||||||
|
await provider.signOut();
|
||||||
|
expect(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('close releases the HTTP client', () {
|
||||||
|
expect(_provider([]).close, returnsNormally);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('a refresh token the server rejects', () {
|
||||||
|
// Regression: hasSession() was a presence check, so a revoked token still
|
||||||
|
// read as "Connected" while every sync died with TOKEN_EXPIRED. Observed
|
||||||
|
// on the desktop todo build on 2026-08-11.
|
||||||
|
test(
|
||||||
|
'is cleared, so hasSession stops claiming the device is connected',
|
||||||
|
() async {
|
||||||
|
final store = InMemoryCredentialStore(
|
||||||
|
_credentials(validFor: const Duration(seconds: -1)),
|
||||||
|
);
|
||||||
|
final provider = _provider([
|
||||||
|
_json(400, {
|
||||||
|
'error': {'message': 'TOKEN_EXPIRED'},
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await expectLater(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
||||||
|
expect(
|
||||||
|
await provider.hasSession(),
|
||||||
|
isFalse,
|
||||||
|
reason: 'a revoked session must not keep reporting as connected',
|
||||||
|
);
|
||||||
|
expect(await store.load(), isNull);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('survives a network error, which is transient', () async {
|
||||||
|
// The opposite failure: signing out whenever the wifi drops would need a
|
||||||
|
// manual sign-in on every device to recover.
|
||||||
|
final store = InMemoryCredentialStore(
|
||||||
|
_credentials(validFor: const Duration(seconds: -1)),
|
||||||
|
);
|
||||||
|
final provider = _provider([
|
||||||
|
http.ClientException('connection reset'),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await expectLater(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
||||||
|
expect(
|
||||||
|
await provider.hasSession(),
|
||||||
|
isTrue,
|
||||||
|
reason: 'a transient failure must not discard a good refresh token',
|
||||||
|
);
|
||||||
|
expect(await store.load(), isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('survives a 5xx, which is also transient', () async {
|
||||||
|
final store = InMemoryCredentialStore(
|
||||||
|
_credentials(validFor: const Duration(seconds: -1)),
|
||||||
|
);
|
||||||
|
final provider = _provider([
|
||||||
|
_json(503, {
|
||||||
|
'error': {'message': 'SERVICE_UNAVAILABLE'},
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await expectLater(provider.idToken, throwsA(isA<FirebaseAuthError>()));
|
||||||
|
expect(await provider.hasSession(), isTrue);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
134
crdt_sync_dart/test/firebase_auth_rest_uid_test.dart
Normal file
134
crdt_sync_dart/test/firebase_auth_rest_uid_test.dart
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
/// A fixed "now" so token expiry is deterministic rather than wall-clock.
|
||||||
|
final _now = DateTime.utc(2026, 8, 3, 12);
|
||||||
|
|
||||||
|
http.Response _json(int statusCode, Object body) =>
|
||||||
|
http.Response(jsonEncode(body), statusCode);
|
||||||
|
|
||||||
|
/// Builds a provider whose POSTs return [responses] in call order (each
|
||||||
|
/// either an [http.Response] or a thrown [http.ClientException]).
|
||||||
|
FirebaseTokenProvider _provider(
|
||||||
|
List<Object> responses, {
|
||||||
|
FirebaseCredentialStore? store,
|
||||||
|
DateTime? now,
|
||||||
|
}) {
|
||||||
|
var index = 0;
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
final response = responses[index];
|
||||||
|
index++;
|
||||||
|
if (response is http.ClientException) throw response;
|
||||||
|
return response as http.Response;
|
||||||
|
});
|
||||||
|
return FirebaseTokenProvider(
|
||||||
|
apiKey: 'fake-api-key',
|
||||||
|
store: store ?? InMemoryCredentialStore(),
|
||||||
|
httpClient: mock,
|
||||||
|
clock: () => now ?? _now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('signInWithGoogle uid verification', () {
|
||||||
|
test('rejects a session for a uid other than the expected one', () async {
|
||||||
|
// The mis-tapped-account-picker case. signInWithIdp signs in OR SIGNS
|
||||||
|
// UP, so an unlinked Google identity is accepted as a brand-new user
|
||||||
|
// rather than refused. Without this check the device would store that
|
||||||
|
// session and then be denied every read and write, permanently.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'localId': 'some-other-uid',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await expectLater(
|
||||||
|
() => provider.signInWithGoogle(
|
||||||
|
idToken: 'token-for-the-wrong-account',
|
||||||
|
expectedUid: 'the-right-uid',
|
||||||
|
),
|
||||||
|
throwsA(
|
||||||
|
isA<FirebaseAuthError>().having(
|
||||||
|
(e) => e.message,
|
||||||
|
'message',
|
||||||
|
allOf(contains('some-other-uid'), contains('the-right-uid')),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
await store.load(),
|
||||||
|
isNull,
|
||||||
|
reason: 'a wrong-account session must not persist',
|
||||||
|
);
|
||||||
|
expect(await provider.hasSession(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepts a session whose uid matches the expected one', () async {
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'localId': 'the-right-uid',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await provider.signInWithGoogle(
|
||||||
|
idToken: 'token',
|
||||||
|
expectedUid: 'the-right-uid',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect((await store.load())!.idToken, 'id-g');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('skips the uid check when no uid is expected', () async {
|
||||||
|
// FirebaseProject.configFor leaves uid empty on the app path; comparing
|
||||||
|
// against '' would otherwise fail every sign-in.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'localId': 'whatever-uid',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await provider.signInWithGoogle(idToken: 'token', expectedUid: '');
|
||||||
|
|
||||||
|
expect((await store.load())!.idToken, 'id-g');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('its session refreshes like a password session', () async {
|
||||||
|
// signInWithIdp returns the same refresh-token shape as
|
||||||
|
// signInWithPassword, which is why the refresh path needed no changes.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final provider = _provider([
|
||||||
|
_json(200, {
|
||||||
|
'idToken': 'id-g',
|
||||||
|
'refreshToken': 'refresh-g',
|
||||||
|
// Already inside the refresh skew, so the next read must refresh.
|
||||||
|
'expiresIn': '60',
|
||||||
|
}),
|
||||||
|
_json(200, {
|
||||||
|
'id_token': 'id-g2',
|
||||||
|
'refresh_token': 'refresh-g2',
|
||||||
|
'expires_in': '3600',
|
||||||
|
}),
|
||||||
|
], store: store);
|
||||||
|
|
||||||
|
await provider.signInWithGoogle(idToken: 'google-token');
|
||||||
|
expect(await provider.idToken(), 'id-g2');
|
||||||
|
expect((await store.load())!.refreshToken, 'refresh-g2');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -5,7 +5,8 @@ import 'package:http/http.dart' as http;
|
|||||||
import 'package:http/testing.dart' as http_testing;
|
import 'package:http/testing.dart' as http_testing;
|
||||||
import 'package:test/test.dart';
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
const _databaseUrl = 'https://example-default-rtdb.europe-west1.firebasedatabase.app';
|
const _databaseUrl =
|
||||||
|
'https://example-default-rtdb.europe-west1.firebasedatabase.app';
|
||||||
|
|
||||||
http.Response _json(int statusCode, Object? body) =>
|
http.Response _json(int statusCode, Object? body) =>
|
||||||
http.Response(jsonEncode(body), statusCode);
|
http.Response(jsonEncode(body), statusCode);
|
||||||
@ -31,10 +32,7 @@ FirebaseTokenProvider _auth() => FirebaseTokenProvider(
|
|||||||
/// decoded result.
|
/// decoded result.
|
||||||
late List<http.Request> requests;
|
late List<http.Request> requests;
|
||||||
|
|
||||||
FirebaseRestClient _client(
|
FirebaseRestClient _client(Object response, {FirebaseTokenProvider? auth}) {
|
||||||
Object response, {
|
|
||||||
FirebaseTokenProvider? auth,
|
|
||||||
}) {
|
|
||||||
requests = [];
|
requests = [];
|
||||||
final mock = http_testing.MockClient((request) async {
|
final mock = http_testing.MockClient((request) async {
|
||||||
requests.add(request);
|
requests.add(request);
|
||||||
@ -58,8 +56,10 @@ void main() {
|
|||||||
|
|
||||||
test('leaves dot-free device ids untouched', () {
|
test('leaves dot-free device ids untouched', () {
|
||||||
expect(encodeKey('pc'), 'pc');
|
expect(encodeKey('pc'), 'pc');
|
||||||
expect(encodeKey('32c28cf3-c0eb-423f-8bac-9bda9f158054'),
|
expect(
|
||||||
'32c28cf3-c0eb-423f-8bac-9bda9f158054');
|
encodeKey('32c28cf3-c0eb-423f-8bac-9bda9f158054'),
|
||||||
|
'32c28cf3-c0eb-423f-8bac-9bda9f158054',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('escapes every character RTDB forbids, plus the escape char', () {
|
test('escapes every character RTDB forbids, plus the escape char', () {
|
||||||
@ -103,10 +103,7 @@ void main() {
|
|||||||
test('requests the escaped path with the auth token', () async {
|
test('requests the escaped path with the auth token', () async {
|
||||||
final client = _client(_json(200, '{}'));
|
final client = _client(_json(200, '{}'));
|
||||||
await client.getFileText('ns/devices/pc/log.json');
|
await client.getFileText('ns/devices/pc/log.json');
|
||||||
expect(
|
expect(requests.single.url.path, '/ns/devices/pc/log~2Ejson.json');
|
||||||
requests.single.url.path,
|
|
||||||
'/ns/devices/pc/log~2Ejson.json',
|
|
||||||
);
|
|
||||||
expect(requests.single.url.queryParameters['auth'], 'id-token');
|
expect(requests.single.url.queryParameters['auth'], 'id-token');
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -125,13 +122,16 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('raises DatabaseNotFoundError when the rules reject the uid', () async {
|
test(
|
||||||
final client = _client(_json(401, {'error': 'Permission denied'}));
|
'raises DatabaseNotFoundError when the rules reject the uid',
|
||||||
expect(
|
() async {
|
||||||
() => client.getFileText('ns/devices/pc/log.json'),
|
final client = _client(_json(401, {'error': 'Permission denied'}));
|
||||||
throwsA(isA<DatabaseNotFoundError>()),
|
expect(
|
||||||
);
|
() => client.getFileText('ns/devices/pc/log.json'),
|
||||||
});
|
throwsA(isA<DatabaseNotFoundError>()),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('raises DatabaseNotFoundError on 403 too', () async {
|
test('raises DatabaseNotFoundError on 403 too', () async {
|
||||||
final client = _client(_json(403, {'error': 'Permission denied'}));
|
final client = _client(_json(403, {'error': 'Permission denied'}));
|
||||||
@ -195,180 +195,4 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('putFileText', () {
|
|
||||||
test('writes the text as a JSON string leaf', () async {
|
|
||||||
final client = _client(_json(200, '{"a":1}'));
|
|
||||||
await client.putFileText(
|
|
||||||
'ns/devices/pc/log.json',
|
|
||||||
'{"a":1}',
|
|
||||||
message: 'ignored by rtdb',
|
|
||||||
);
|
|
||||||
expect(requests.single.method, 'PUT');
|
|
||||||
expect(requests.single.body, jsonEncode('{"a":1}'));
|
|
||||||
expect(requests.single.url.path, '/ns/devices/pc/log~2Ejson.json');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('raises on a non-2xx response', () async {
|
|
||||||
final client = _client(_json(400, {'error': 'bad'}));
|
|
||||||
expect(
|
|
||||||
() => client.putFileText('ns/devices/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('turns a network failure into FirebaseSyncError', () async {
|
|
||||||
final client = _client(http.ClientException('offline'));
|
|
||||||
expect(
|
|
||||||
() => client.putFileText('ns/devices/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('patchValues', () {
|
|
||||||
test('PATCHes rather than PUTs, so sibling keys survive', () async {
|
|
||||||
// A PUT on the shared revs map would wipe every other device's entry,
|
|
||||||
// after which those devices would look permanently unchanged and never
|
|
||||||
// be fetched again.
|
|
||||||
final client = _client(_json(200, {'pc': 'abc'}));
|
|
||||||
await client.patchValues('ns/revs', {'pc': 'abc'});
|
|
||||||
expect(requests.single.method, 'PATCH');
|
|
||||||
expect(requests.single.body, jsonEncode({'pc': 'abc'}));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('raises on a non-2xx response', () async {
|
|
||||||
final client = _client(_json(500, {'error': 'boom'}));
|
|
||||||
expect(
|
|
||||||
() => client.patchValues('ns/revs', {'pc': 'abc'}),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('turns a network failure into FirebaseSyncError', () async {
|
|
||||||
final client = _client(http.ClientException('offline'));
|
|
||||||
expect(
|
|
||||||
() => client.patchValues('ns/revs', {'pc': 'abc'}),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('getStringMap', () {
|
|
||||||
test('returns the map with keys decoded', () async {
|
|
||||||
final client = _client(_json(200, {'pc': 'sha-1', 'phone': 'sha-2'}));
|
|
||||||
expect(await client.getStringMap('ns/revs'), {
|
|
||||||
'pc': 'sha-1',
|
|
||||||
'phone': 'sha-2',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('degrades to empty when absent', () async {
|
|
||||||
final client = _client(_json(200, null));
|
|
||||||
expect(await client.getStringMap('ns/revs'), isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('skips non-string entries rather than failing the sync', () async {
|
|
||||||
// The revs node is an optimisation; a corrupt one must degrade into
|
|
||||||
// "fetch everything", never into a failed tick.
|
|
||||||
final client = _client(_json(200, {'pc': 'sha-1', 'phone': 42}));
|
|
||||||
expect(await client.getStringMap('ns/revs'), {'pc': 'sha-1'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('raises on a non-2xx response', () async {
|
|
||||||
final client = _client(_json(500, {'error': 'boom'}));
|
|
||||||
expect(
|
|
||||||
() => client.getStringMap('ns/revs'),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('deleteFile', () {
|
|
||||||
test('sends a DELETE to the escaped path', () async {
|
|
||||||
final client = _client(_json(200, null));
|
|
||||||
await client.deleteFile('ns/devices/pc/log.json');
|
|
||||||
expect(requests.single.method, 'DELETE');
|
|
||||||
expect(requests.single.url.path, '/ns/devices/pc/log~2Ejson.json');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('raises on a non-2xx response', () async {
|
|
||||||
final client = _client(_json(500, {'error': 'boom'}));
|
|
||||||
expect(
|
|
||||||
() => client.deleteFile('ns/devices/pc/log.json'),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('turns a network failure into FirebaseSyncError', () async {
|
|
||||||
final client = _client(http.ClientException('offline'));
|
|
||||||
expect(
|
|
||||||
() => client.deleteFile('ns/devices/pc/log.json'),
|
|
||||||
throwsA(isA<FirebaseSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('canAccessRemote', () {
|
|
||||||
test('is true when the database root reads', () async {
|
|
||||||
expect(await _client(_json(200, {'ns': true})).canAccessRemote(), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false when the rules reject the token', () async {
|
|
||||||
expect(await _client(_json(401, {'error': 'denied'})).canAccessRemote(),
|
|
||||||
isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false on a network error', () async {
|
|
||||||
expect(
|
|
||||||
await _client(http.ClientException('offline')).canAccessRemote(),
|
|
||||||
isFalse,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false when no session is stored, rather than throwing', () async {
|
|
||||||
// "cannot get a token" is exactly "cannot access the remote", and a
|
|
||||||
// settings screen's Test-connection button must not blow up.
|
|
||||||
final client = _client(
|
|
||||||
_json(200, {}),
|
|
||||||
auth: FirebaseTokenProvider(
|
|
||||||
apiKey: 'k',
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
httpClient: http_testing.MockClient((_) async => _json(200, {})),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
expect(await client.canAccessRemote(), isFalse);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('RemoteStore contract', () {
|
|
||||||
test('FirebaseRestClient is a RemoteStore', () {
|
|
||||||
expect(_client(_json(200, null)), isA<RemoteStore>());
|
|
||||||
});
|
|
||||||
|
|
||||||
test('DatabaseNotFoundError is catchable as either error type', () {
|
|
||||||
final error = DatabaseNotFoundError('gone');
|
|
||||||
expect(error, isA<FirebaseSyncError>());
|
|
||||||
expect(error, isA<RemoteNotFoundError>());
|
|
||||||
expect(error, isA<RemoteSyncError>());
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a trailing slash on the database URL is tolerated', () async {
|
|
||||||
final client = FirebaseRestClient(
|
|
||||||
databaseUrl: '$_databaseUrl/',
|
|
||||||
auth: _auth(),
|
|
||||||
httpClient: http_testing.MockClient((request) async {
|
|
||||||
requests.add(request);
|
|
||||||
return _json(200, 'ok');
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
requests = [];
|
|
||||||
await client.getFileText('ns/x.json');
|
|
||||||
expect(requests.single.url.toString(), startsWith('$_databaseUrl/ns/'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('close releases the HTTP client', () {
|
|
||||||
expect(_client(_json(200, null)).close, returnsNormally);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
227
crdt_sync_dart/test/firebase_client_writes_test.dart
Normal file
227
crdt_sync_dart/test/firebase_client_writes_test.dart
Normal file
@ -0,0 +1,227 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
const _databaseUrl =
|
||||||
|
'https://example-default-rtdb.europe-west1.firebasedatabase.app';
|
||||||
|
|
||||||
|
http.Response _json(int statusCode, Object? body) =>
|
||||||
|
http.Response(jsonEncode(body), statusCode);
|
||||||
|
|
||||||
|
/// A provider holding a long-lived token, so client tests never hit the auth
|
||||||
|
/// endpoints -- an HTTP call from the token provider would fail loudly here.
|
||||||
|
FirebaseTokenProvider _auth() => FirebaseTokenProvider(
|
||||||
|
apiKey: 'fake-api-key',
|
||||||
|
store: InMemoryCredentialStore(
|
||||||
|
FirebaseCredentials(
|
||||||
|
idToken: 'id-token',
|
||||||
|
refreshToken: 'refresh-token',
|
||||||
|
expiresAt: DateTime.utc(2099),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
httpClient: http_testing.MockClient(
|
||||||
|
(_) async => throw StateError('auth must not be contacted'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// Records every request the client makes, so tests can assert on the URL
|
||||||
|
/// (which carries the key escaping and the shallow flag) as well as the
|
||||||
|
/// decoded result.
|
||||||
|
late List<http.Request> requests;
|
||||||
|
|
||||||
|
FirebaseRestClient _client(Object response, {FirebaseTokenProvider? auth}) {
|
||||||
|
requests = [];
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
requests.add(request);
|
||||||
|
if (response is http.ClientException) throw response;
|
||||||
|
return response as http.Response;
|
||||||
|
});
|
||||||
|
return FirebaseRestClient(
|
||||||
|
databaseUrl: _databaseUrl,
|
||||||
|
auth: auth ?? _auth(),
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('putFileText', () {
|
||||||
|
test('writes the text as a JSON string leaf', () async {
|
||||||
|
final client = _client(_json(200, '{"a":1}'));
|
||||||
|
await client.putFileText(
|
||||||
|
'ns/devices/pc/log.json',
|
||||||
|
'{"a":1}',
|
||||||
|
message: 'ignored by rtdb',
|
||||||
|
);
|
||||||
|
expect(requests.single.method, 'PUT');
|
||||||
|
expect(requests.single.body, jsonEncode('{"a":1}'));
|
||||||
|
expect(requests.single.url.path, '/ns/devices/pc/log~2Ejson.json');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raises on a non-2xx response', () async {
|
||||||
|
final client = _client(_json(400, {'error': 'bad'}));
|
||||||
|
expect(
|
||||||
|
() => client.putFileText('ns/devices/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('turns a network failure into FirebaseSyncError', () async {
|
||||||
|
final client = _client(http.ClientException('offline'));
|
||||||
|
expect(
|
||||||
|
() => client.putFileText('ns/devices/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('patchValues', () {
|
||||||
|
test('PATCHes rather than PUTs, so sibling keys survive', () async {
|
||||||
|
// A PUT on the shared revs map would wipe every other device's entry,
|
||||||
|
// after which those devices would look permanently unchanged and never
|
||||||
|
// be fetched again.
|
||||||
|
final client = _client(_json(200, {'pc': 'abc'}));
|
||||||
|
await client.patchValues('ns/revs', {'pc': 'abc'});
|
||||||
|
expect(requests.single.method, 'PATCH');
|
||||||
|
expect(requests.single.body, jsonEncode({'pc': 'abc'}));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raises on a non-2xx response', () async {
|
||||||
|
final client = _client(_json(500, {'error': 'boom'}));
|
||||||
|
expect(
|
||||||
|
() => client.patchValues('ns/revs', {'pc': 'abc'}),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('turns a network failure into FirebaseSyncError', () async {
|
||||||
|
final client = _client(http.ClientException('offline'));
|
||||||
|
expect(
|
||||||
|
() => client.patchValues('ns/revs', {'pc': 'abc'}),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('getStringMap', () {
|
||||||
|
test('returns the map with keys decoded', () async {
|
||||||
|
final client = _client(_json(200, {'pc': 'sha-1', 'phone': 'sha-2'}));
|
||||||
|
expect(await client.getStringMap('ns/revs'), {
|
||||||
|
'pc': 'sha-1',
|
||||||
|
'phone': 'sha-2',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('degrades to empty when absent', () async {
|
||||||
|
final client = _client(_json(200, null));
|
||||||
|
expect(await client.getStringMap('ns/revs'), isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('skips non-string entries rather than failing the sync', () async {
|
||||||
|
// The revs node is an optimisation; a corrupt one must degrade into
|
||||||
|
// "fetch everything", never into a failed tick.
|
||||||
|
final client = _client(_json(200, {'pc': 'sha-1', 'phone': 42}));
|
||||||
|
expect(await client.getStringMap('ns/revs'), {'pc': 'sha-1'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raises on a non-2xx response', () async {
|
||||||
|
final client = _client(_json(500, {'error': 'boom'}));
|
||||||
|
expect(
|
||||||
|
() => client.getStringMap('ns/revs'),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('deleteFile', () {
|
||||||
|
test('sends a DELETE to the escaped path', () async {
|
||||||
|
final client = _client(_json(200, null));
|
||||||
|
await client.deleteFile('ns/devices/pc/log.json');
|
||||||
|
expect(requests.single.method, 'DELETE');
|
||||||
|
expect(requests.single.url.path, '/ns/devices/pc/log~2Ejson.json');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('raises on a non-2xx response', () async {
|
||||||
|
final client = _client(_json(500, {'error': 'boom'}));
|
||||||
|
expect(
|
||||||
|
() => client.deleteFile('ns/devices/pc/log.json'),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('turns a network failure into FirebaseSyncError', () async {
|
||||||
|
final client = _client(http.ClientException('offline'));
|
||||||
|
expect(
|
||||||
|
() => client.deleteFile('ns/devices/pc/log.json'),
|
||||||
|
throwsA(isA<FirebaseSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('canAccessRemote', () {
|
||||||
|
test('is true when the database root reads', () async {
|
||||||
|
expect(await _client(_json(200, {'ns': true})).canAccessRemote(), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false when the rules reject the token', () async {
|
||||||
|
expect(
|
||||||
|
await _client(_json(401, {'error': 'denied'})).canAccessRemote(),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false on a network error', () async {
|
||||||
|
expect(
|
||||||
|
await _client(http.ClientException('offline')).canAccessRemote(),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false when no session is stored, rather than throwing', () async {
|
||||||
|
// "cannot get a token" is exactly "cannot access the remote", and a
|
||||||
|
// settings screen's Test-connection button must not blow up.
|
||||||
|
final client = _client(
|
||||||
|
_json(200, {}),
|
||||||
|
auth: FirebaseTokenProvider(
|
||||||
|
apiKey: 'k',
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
httpClient: http_testing.MockClient((_) async => _json(200, {})),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
expect(await client.canAccessRemote(), isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('RemoteStore contract', () {
|
||||||
|
test('FirebaseRestClient is a RemoteStore', () {
|
||||||
|
expect(_client(_json(200, null)), isA<RemoteStore>());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('DatabaseNotFoundError is catchable as either error type', () {
|
||||||
|
final error = DatabaseNotFoundError('gone');
|
||||||
|
expect(error, isA<FirebaseSyncError>());
|
||||||
|
expect(error, isA<RemoteNotFoundError>());
|
||||||
|
expect(error, isA<RemoteSyncError>());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a trailing slash on the database URL is tolerated', () async {
|
||||||
|
final client = FirebaseRestClient(
|
||||||
|
databaseUrl: '$_databaseUrl/',
|
||||||
|
auth: _auth(),
|
||||||
|
httpClient: http_testing.MockClient((request) async {
|
||||||
|
requests.add(request);
|
||||||
|
return _json(200, 'ok');
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
requests = [];
|
||||||
|
await client.getFileText('ns/x.json');
|
||||||
|
expect(requests.single.url.toString(), startsWith('$_databaseUrl/ns/'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('close releases the HTTP client', () {
|
||||||
|
expect(_client(_json(200, null)).close, returnsNormally);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
164
crdt_sync_dart/test/firebase_config_client_google_test.dart
Normal file
164
crdt_sync_dart/test/firebase_config_client_google_test.dart
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
/// Tests for the shared Firebase configuration on the Dart side.
|
||||||
|
///
|
||||||
|
/// The failure modes asserted here are the ones that would otherwise surface
|
||||||
|
/// as an authentication error long after the real mistake, so each is checked
|
||||||
|
/// to name the field at fault rather than merely to throw.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
const _valid = {
|
||||||
|
'apiKey': 'AIzaSyExample',
|
||||||
|
'databaseUrl':
|
||||||
|
'https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app',
|
||||||
|
'projectId': 'kuhy-syncs',
|
||||||
|
'uid': 'OvA2REQyLIhAHOEjzwS1o877rgG3',
|
||||||
|
'email': 'sync@example.com',
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A [RemoteStore] that does nothing, standing in for the GitHub client.
|
||||||
|
class _StubRemote implements RemoteStore {
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async => [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async => null;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async {}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('client construction with Google', () {
|
||||||
|
test('refuses a Google account that is not the configured uid', () async {
|
||||||
|
// End of the chain the phone actually walks: a mis-tapped account in the
|
||||||
|
// picker must fail here rather than storing a session that the security
|
||||||
|
// rules then deny on every read and write.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final mock = http_testing.MockClient(
|
||||||
|
(request) async => http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'idToken': 'id',
|
||||||
|
'refreshToken': 'refresh',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'localId': 'a-different-persons-uid',
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await expectLater(
|
||||||
|
firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: store,
|
||||||
|
googleIdToken: () async => 'token-for-the-wrong-account',
|
||||||
|
httpClient: mock,
|
||||||
|
),
|
||||||
|
throwsA(isA<FirebaseAuthError>()),
|
||||||
|
);
|
||||||
|
expect(await store.load(), isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to the password when Google returns null', () async {
|
||||||
|
// Desktop and headless: the provider is wired but nobody is signed in
|
||||||
|
// with Google, so the machine credential has to still work.
|
||||||
|
final sentTo = <String>[];
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
sentTo.add(request.url.path);
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'idToken': 'id',
|
||||||
|
'refreshToken': 'refresh',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
final client = await firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
password: 'hunter2',
|
||||||
|
googleIdToken: () async => null,
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sentTo.single, contains('signInWithPassword'));
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refuses to build when Google returns null and no password', () async {
|
||||||
|
await expectLater(
|
||||||
|
firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
googleIdToken: () async => null,
|
||||||
|
),
|
||||||
|
throwsA(isA<ConfigException>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reuses a stored session without a password', () async {
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
await store.save(
|
||||||
|
FirebaseCredentials(
|
||||||
|
idToken: 'id',
|
||||||
|
refreshToken: 'refresh',
|
||||||
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
final client = await firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: store,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(client, isA<FirebaseRestClient>());
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'mirrorStoreFor makes Firebase primary and GitHub the mirror',
|
||||||
|
() async {
|
||||||
|
// Which backend is authoritative is the one thing a rollback depends on.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
await store.save(
|
||||||
|
FirebaseCredentials(
|
||||||
|
idToken: 'id',
|
||||||
|
refreshToken: 'refresh',
|
||||||
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
final github = _StubRemote();
|
||||||
|
|
||||||
|
final mirror = await mirrorStoreFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: store,
|
||||||
|
githubClient: github,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(mirror.primary, isA<FirebaseRestClient>());
|
||||||
|
expect(mirror.mirror, same(github));
|
||||||
|
mirror.close();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
127
crdt_sync_dart/test/firebase_config_client_test.dart
Normal file
127
crdt_sync_dart/test/firebase_config_client_test.dart
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
/// Tests for the shared Firebase configuration on the Dart side.
|
||||||
|
///
|
||||||
|
/// The failure modes asserted here are the ones that would otherwise surface
|
||||||
|
/// as an authentication error long after the real mistake, so each is checked
|
||||||
|
/// to name the field at fault rather than merely to throw.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
const _valid = {
|
||||||
|
'apiKey': 'AIzaSyExample',
|
||||||
|
'databaseUrl':
|
||||||
|
'https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app',
|
||||||
|
'projectId': 'kuhy-syncs',
|
||||||
|
'uid': 'OvA2REQyLIhAHOEjzwS1o877rgG3',
|
||||||
|
'email': 'sync@example.com',
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('client construction', () {
|
||||||
|
test('refuses to build without a session or a password', () async {
|
||||||
|
// Better than signing in with an empty password and failing remotely.
|
||||||
|
await expectLater(
|
||||||
|
firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
),
|
||||||
|
throwsA(isA<ConfigException>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('signs in with the password when there is no session', () async {
|
||||||
|
// The first-run path: no cached refresh token, so it must exchange the
|
||||||
|
// password for one rather than failing.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final sentTo = <String>[];
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
sentTo.add(request.url.path);
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'idToken': 'id',
|
||||||
|
'refreshToken': 'refresh',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'localId': _valid['uid'],
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
final client = await firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: store,
|
||||||
|
password: 'hunter2',
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sentTo.single, contains('signInWithPassword'));
|
||||||
|
expect(await store.load(), isNotNull, reason: 'session must persist');
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('signs in with Google when a token is available', () async {
|
||||||
|
// The one-tap path: a fresh install with no password typed anywhere.
|
||||||
|
final store = InMemoryCredentialStore();
|
||||||
|
final sentTo = <String>[];
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
sentTo.add(request.url.path);
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'idToken': 'id',
|
||||||
|
'refreshToken': 'refresh',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
'localId': _valid['uid'],
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
final client = await firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: store,
|
||||||
|
googleIdToken: () async => 'google-token',
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sentTo.single, contains('signInWithIdp'));
|
||||||
|
expect(await store.load(), isNotNull, reason: 'session must persist');
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('prefers Google over the password when both are available', () async {
|
||||||
|
// Google is the credential the user did not have to type, so on a device
|
||||||
|
// offering both it should win.
|
||||||
|
final sentTo = <String>[];
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
sentTo.add(request.url.path);
|
||||||
|
return http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'idToken': 'id',
|
||||||
|
'refreshToken': 'refresh',
|
||||||
|
'expiresIn': '3600',
|
||||||
|
// Firebase always returns localId; the config carries a uid, so
|
||||||
|
// omitting it here would trip the wrong-account guard.
|
||||||
|
'localId': _valid['uid'],
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
final client = await firebaseClientFor(
|
||||||
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
password: 'hunter2',
|
||||||
|
googleIdToken: () async => 'google-token',
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(sentTo.single, contains('signInWithIdp'));
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -8,8 +8,6 @@ library;
|
|||||||
import 'dart:convert';
|
import 'dart:convert';
|
||||||
|
|
||||||
import 'package:crdt_sync/crdt_sync.dart';
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
import 'package:http/http.dart' as http;
|
|
||||||
import 'package:http/testing.dart' as http_testing;
|
|
||||||
import 'package:test/test.dart';
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
const _valid = {
|
const _valid = {
|
||||||
@ -21,31 +19,6 @@ const _valid = {
|
|||||||
'email': 'sync@example.com',
|
'email': 'sync@example.com',
|
||||||
};
|
};
|
||||||
|
|
||||||
/// A [RemoteStore] that does nothing, standing in for the GitHub client.
|
|
||||||
class _StubRemote implements RemoteStore {
|
|
||||||
@override
|
|
||||||
Future<List<String>> listDirectory(String path) async => [];
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> getFileText(String path) async => null;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> putFileText(
|
|
||||||
String path,
|
|
||||||
String text, {
|
|
||||||
required String message,
|
|
||||||
}) async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> deleteFile(String path, {String message = ''}) async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> canAccessRemote() async => true;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void close() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
group('FirebaseConfig', () {
|
group('FirebaseConfig', () {
|
||||||
test('parses a valid config', () {
|
test('parses a valid config', () {
|
||||||
@ -141,220 +114,4 @@ void main() {
|
|||||||
expect(ConfigException('boom').toString(), contains('boom'));
|
expect(ConfigException('boom').toString(), contains('boom'));
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('client construction', () {
|
|
||||||
test('refuses to build without a session or a password', () async {
|
|
||||||
// Better than signing in with an empty password and failing remotely.
|
|
||||||
await expectLater(
|
|
||||||
firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
),
|
|
||||||
throwsA(isA<ConfigException>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('signs in with the password when there is no session', () async {
|
|
||||||
// The first-run path: no cached refresh token, so it must exchange the
|
|
||||||
// password for one rather than failing.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final sentTo = <String>[];
|
|
||||||
final mock = http_testing.MockClient((request) async {
|
|
||||||
sentTo.add(request.url.path);
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'idToken': 'id',
|
|
||||||
'refreshToken': 'refresh',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'localId': _valid['uid'],
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
final client = await firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: store,
|
|
||||||
password: 'hunter2',
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(sentTo.single, contains('signInWithPassword'));
|
|
||||||
expect(await store.load(), isNotNull, reason: 'session must persist');
|
|
||||||
client.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('signs in with Google when a token is available', () async {
|
|
||||||
// The one-tap path: a fresh install with no password typed anywhere.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final sentTo = <String>[];
|
|
||||||
final mock = http_testing.MockClient((request) async {
|
|
||||||
sentTo.add(request.url.path);
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'idToken': 'id',
|
|
||||||
'refreshToken': 'refresh',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'localId': _valid['uid'],
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
final client = await firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: store,
|
|
||||||
googleIdToken: () async => 'google-token',
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(sentTo.single, contains('signInWithIdp'));
|
|
||||||
expect(await store.load(), isNotNull, reason: 'session must persist');
|
|
||||||
client.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('prefers Google over the password when both are available', () async {
|
|
||||||
// Google is the credential the user did not have to type, so on a device
|
|
||||||
// offering both it should win.
|
|
||||||
final sentTo = <String>[];
|
|
||||||
final mock = http_testing.MockClient((request) async {
|
|
||||||
sentTo.add(request.url.path);
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'idToken': 'id',
|
|
||||||
'refreshToken': 'refresh',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
// Firebase always returns localId; the config carries a uid, so
|
|
||||||
// omitting it here would trip the wrong-account guard.
|
|
||||||
'localId': _valid['uid'],
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
final client = await firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
password: 'hunter2',
|
|
||||||
googleIdToken: () async => 'google-token',
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(sentTo.single, contains('signInWithIdp'));
|
|
||||||
client.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('refuses a Google account that is not the configured uid', () async {
|
|
||||||
// End of the chain the phone actually walks: a mis-tapped account in the
|
|
||||||
// picker must fail here rather than storing a session that the security
|
|
||||||
// rules then deny on every read and write.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
final mock = http_testing.MockClient(
|
|
||||||
(request) async => http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'idToken': 'id',
|
|
||||||
'refreshToken': 'refresh',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
'localId': 'a-different-persons-uid',
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
await expectLater(
|
|
||||||
firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: store,
|
|
||||||
googleIdToken: () async => 'token-for-the-wrong-account',
|
|
||||||
httpClient: mock,
|
|
||||||
),
|
|
||||||
throwsA(isA<FirebaseAuthError>()),
|
|
||||||
);
|
|
||||||
expect(await store.load(), isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('falls back to the password when Google returns null', () async {
|
|
||||||
// Desktop and headless: the provider is wired but nobody is signed in
|
|
||||||
// with Google, so the machine credential has to still work.
|
|
||||||
final sentTo = <String>[];
|
|
||||||
final mock = http_testing.MockClient((request) async {
|
|
||||||
sentTo.add(request.url.path);
|
|
||||||
return http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'idToken': 'id',
|
|
||||||
'refreshToken': 'refresh',
|
|
||||||
'expiresIn': '3600',
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
final client = await firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
password: 'hunter2',
|
|
||||||
googleIdToken: () async => null,
|
|
||||||
httpClient: mock,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(sentTo.single, contains('signInWithPassword'));
|
|
||||||
client.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('refuses to build when Google returns null and no password', () async {
|
|
||||||
await expectLater(
|
|
||||||
firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: InMemoryCredentialStore(),
|
|
||||||
googleIdToken: () async => null,
|
|
||||||
),
|
|
||||||
throwsA(isA<ConfigException>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('reuses a stored session without a password', () async {
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
await store.save(
|
|
||||||
FirebaseCredentials(
|
|
||||||
idToken: 'id',
|
|
||||||
refreshToken: 'refresh',
|
|
||||||
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
final client = await firebaseClientFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: store,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(client, isA<FirebaseRestClient>());
|
|
||||||
client.close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'mirrorStoreFor makes Firebase primary and GitHub the mirror',
|
|
||||||
() async {
|
|
||||||
// Which backend is authoritative is the one thing a rollback depends on.
|
|
||||||
final store = InMemoryCredentialStore();
|
|
||||||
await store.save(
|
|
||||||
FirebaseCredentials(
|
|
||||||
idToken: 'id',
|
|
||||||
refreshToken: 'refresh',
|
|
||||||
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
final github = _StubRemote();
|
|
||||||
|
|
||||||
final mirror = await mirrorStoreFor(
|
|
||||||
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
||||||
store: store,
|
|
||||||
githubClient: github,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(mirror.primary, isA<FirebaseRestClient>());
|
|
||||||
expect(mirror.mirror, same(github));
|
|
||||||
mirror.close();
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -140,152 +140,4 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('putFileText', () {
|
|
||||||
test('creates a new file with no sha when none existed', () async {
|
|
||||||
final client = _client([
|
|
||||||
_response(404),
|
|
||||||
_response(200),
|
|
||||||
], putResponse: _response(201));
|
|
||||||
await client.putFileText('devices/pc/log.json', '{}', message: 'm');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('updates an existing file by including its sha', () async {
|
|
||||||
final client = _client([
|
|
||||||
_response(200, {'sha': 'abc123'}),
|
|
||||||
], putResponse: _response(200));
|
|
||||||
await client.putFileText('devices/pc/log.json', '{}', message: 'm');
|
|
||||||
});
|
|
||||||
|
|
||||||
test(
|
|
||||||
'throws RepoNotFoundError when checking sha on a missing repo',
|
|
||||||
() async {
|
|
||||||
final client = _client([_response(404), _response(404)]);
|
|
||||||
expect(
|
|
||||||
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<RepoNotFoundError>()),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test('throws GitHubSyncError when the sha check itself fails', () async {
|
|
||||||
final client = _client([_response(500)]);
|
|
||||||
expect(
|
|
||||||
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<GitHubSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('throws GitHubSyncError on a put network exception', () async {
|
|
||||||
final client = _client([
|
|
||||||
_response(404),
|
|
||||||
_response(200),
|
|
||||||
], putError: http.ClientException('offline'));
|
|
||||||
expect(
|
|
||||||
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<GitHubSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('throws GitHubSyncError on a put non-2xx response', () async {
|
|
||||||
final client = _client([
|
|
||||||
_response(404),
|
|
||||||
_response(200),
|
|
||||||
], putResponse: _response(422));
|
|
||||||
expect(
|
|
||||||
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<GitHubSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('canAccessRepo', () {
|
|
||||||
test('is true when the repo endpoint returns 2xx', () async {
|
|
||||||
expect(await _client([_response(200)]).canAccessRepo(), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false when the repo is missing (404)', () async {
|
|
||||||
expect(await _client([_response(404)]).canAccessRepo(), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false on a network error', () async {
|
|
||||||
expect(await _client([_networkError]).canAccessRepo(), isFalse);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('canAccessRemote', () {
|
|
||||||
// The RemoteStore spelling must behave exactly like the legacy name.
|
|
||||||
test('is true when the repo endpoint returns 2xx', () async {
|
|
||||||
expect(await _client([_response(200)]).canAccessRemote(), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false when the repo is missing (404)', () async {
|
|
||||||
expect(await _client([_response(404)]).canAccessRemote(), isFalse);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is false on a network error', () async {
|
|
||||||
expect(await _client([_networkError]).canAccessRemote(), isFalse);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('RemoteStore contract', () {
|
|
||||||
test('GitHubClient is a RemoteStore', () {
|
|
||||||
expect(_client([]), isA<RemoteStore>());
|
|
||||||
});
|
|
||||||
|
|
||||||
test('RepoNotFoundError is catchable as either error type', () {
|
|
||||||
// Backend-neutral callers catch RemoteNotFoundError; existing GitHub
|
|
||||||
// callers catch GitHubSyncError. One exception must satisfy both.
|
|
||||||
final error = RepoNotFoundError('gone');
|
|
||||||
expect(error, isA<GitHubSyncError>());
|
|
||||||
expect(error, isA<RemoteNotFoundError>());
|
|
||||||
expect(error, isA<RemoteSyncError>());
|
|
||||||
});
|
|
||||||
|
|
||||||
test('errors stringify as their own type', () {
|
|
||||||
expect(GitHubSyncError('boom').toString(), 'GitHubSyncError: boom');
|
|
||||||
expect(RepoNotFoundError('gone').toString(), 'RepoNotFoundError: gone');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('deleteFile', () {
|
|
||||||
test('deletes an existing file (resolves its own sha)', () async {
|
|
||||||
final client = _client(
|
|
||||||
[_response(200, {'sha': 'abc123'})],
|
|
||||||
deleteResponse: _response(200),
|
|
||||||
);
|
|
||||||
await expectLater(client.deleteFile('devices/pc/log.json'), completes);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is a no-op when the file does not exist', () async {
|
|
||||||
// sha lookup 404s, repo-exists check 200s -> null sha -> no DELETE sent.
|
|
||||||
final client = _client([
|
|
||||||
_response(404),
|
|
||||||
_response(200),
|
|
||||||
], deleteError: StateError('DELETE must not be called'));
|
|
||||||
await expectLater(client.deleteFile('devices/pc/gone.json'), completes);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('throws GitHubSyncError on a delete non-2xx response', () async {
|
|
||||||
final client = _client(
|
|
||||||
[_response(200, {'sha': 'abc123'})],
|
|
||||||
deleteResponse: _response(500),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
() => client.deleteFile('devices/pc/log.json'),
|
|
||||||
throwsA(isA<GitHubSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('throws GitHubSyncError on a delete network exception', () async {
|
|
||||||
final client = _client(
|
|
||||||
[_response(200, {'sha': 'abc123'})],
|
|
||||||
deleteError: http.ClientException('offline'),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
() => client.deleteFile('devices/pc/log.json'),
|
|
||||||
throwsA(isA<GitHubSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
198
crdt_sync_dart/test/github_client_writes_test.dart
Normal file
198
crdt_sync_dart/test/github_client_writes_test.dart
Normal file
@ -0,0 +1,198 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
http.Response _response(int statusCode, [Object? jsonBody]) =>
|
||||||
|
http.Response(jsonEncode(jsonBody ?? {}), statusCode);
|
||||||
|
|
||||||
|
/// Sentinel meaning "this GET throws a network exception", since a real
|
||||||
|
/// [http.Response] can't carry an invalid status code.
|
||||||
|
final _networkError = Object();
|
||||||
|
|
||||||
|
/// Builds a client whose GETs return [getResponses] in call order (each
|
||||||
|
/// either an [http.Response] or [_networkError]), and whose PUT returns
|
||||||
|
/// [putResponse] (or throws [putError] if network fails).
|
||||||
|
GitHubClient _client(
|
||||||
|
List<Object> getResponses, {
|
||||||
|
http.Response? putResponse,
|
||||||
|
Object? putError,
|
||||||
|
http.Response? deleteResponse,
|
||||||
|
Object? deleteError,
|
||||||
|
}) {
|
||||||
|
var getIndex = 0;
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
if (request.method == 'GET') {
|
||||||
|
final response = getResponses[getIndex];
|
||||||
|
getIndex++;
|
||||||
|
if (identical(response, _networkError)) {
|
||||||
|
throw http.ClientException('offline');
|
||||||
|
}
|
||||||
|
return response as http.Response;
|
||||||
|
}
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
if (putError != null) throw putError;
|
||||||
|
return putResponse!;
|
||||||
|
}
|
||||||
|
if (request.method == 'DELETE') {
|
||||||
|
if (deleteError != null) throw deleteError;
|
||||||
|
return deleteResponse!;
|
||||||
|
}
|
||||||
|
throw UnsupportedError('unexpected method ${request.method}');
|
||||||
|
});
|
||||||
|
return GitHubClient(
|
||||||
|
owner: 'kuhyx',
|
||||||
|
repo: 'crdt-sync-demo',
|
||||||
|
token: 'fake-token',
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('putFileText', () {
|
||||||
|
test('creates a new file with no sha when none existed', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(404),
|
||||||
|
_response(200),
|
||||||
|
], putResponse: _response(201));
|
||||||
|
await client.putFileText('devices/pc/log.json', '{}', message: 'm');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('updates an existing file by including its sha', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(200, {'sha': 'abc123'}),
|
||||||
|
], putResponse: _response(200));
|
||||||
|
await client.putFileText('devices/pc/log.json', '{}', message: 'm');
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'throws RepoNotFoundError when checking sha on a missing repo',
|
||||||
|
() async {
|
||||||
|
final client = _client([_response(404), _response(404)]);
|
||||||
|
expect(
|
||||||
|
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<RepoNotFoundError>()),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test('throws GitHubSyncError when the sha check itself fails', () async {
|
||||||
|
final client = _client([_response(500)]);
|
||||||
|
expect(
|
||||||
|
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws GitHubSyncError on a put network exception', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(404),
|
||||||
|
_response(200),
|
||||||
|
], putError: http.ClientException('offline'));
|
||||||
|
expect(
|
||||||
|
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws GitHubSyncError on a put non-2xx response', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(404),
|
||||||
|
_response(200),
|
||||||
|
], putResponse: _response(422));
|
||||||
|
expect(
|
||||||
|
() => client.putFileText('devices/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('canAccessRepo', () {
|
||||||
|
test('is true when the repo endpoint returns 2xx', () async {
|
||||||
|
expect(await _client([_response(200)]).canAccessRepo(), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false when the repo is missing (404)', () async {
|
||||||
|
expect(await _client([_response(404)]).canAccessRepo(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false on a network error', () async {
|
||||||
|
expect(await _client([_networkError]).canAccessRepo(), isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('canAccessRemote', () {
|
||||||
|
// The RemoteStore spelling must behave exactly like the legacy name.
|
||||||
|
test('is true when the repo endpoint returns 2xx', () async {
|
||||||
|
expect(await _client([_response(200)]).canAccessRemote(), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false when the repo is missing (404)', () async {
|
||||||
|
expect(await _client([_response(404)]).canAccessRemote(), isFalse);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is false on a network error', () async {
|
||||||
|
expect(await _client([_networkError]).canAccessRemote(), isFalse);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('RemoteStore contract', () {
|
||||||
|
test('GitHubClient is a RemoteStore', () {
|
||||||
|
expect(_client([]), isA<RemoteStore>());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('RepoNotFoundError is catchable as either error type', () {
|
||||||
|
// Backend-neutral callers catch RemoteNotFoundError; existing GitHub
|
||||||
|
// callers catch GitHubSyncError. One exception must satisfy both.
|
||||||
|
final error = RepoNotFoundError('gone');
|
||||||
|
expect(error, isA<GitHubSyncError>());
|
||||||
|
expect(error, isA<RemoteNotFoundError>());
|
||||||
|
expect(error, isA<RemoteSyncError>());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('errors stringify as their own type', () {
|
||||||
|
expect(GitHubSyncError('boom').toString(), 'GitHubSyncError: boom');
|
||||||
|
expect(RepoNotFoundError('gone').toString(), 'RepoNotFoundError: gone');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('deleteFile', () {
|
||||||
|
test('deletes an existing file (resolves its own sha)', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(200, {'sha': 'abc123'}),
|
||||||
|
], deleteResponse: _response(200));
|
||||||
|
await expectLater(client.deleteFile('devices/pc/log.json'), completes);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is a no-op when the file does not exist', () async {
|
||||||
|
// sha lookup 404s, repo-exists check 200s -> null sha -> no DELETE sent.
|
||||||
|
final client = _client([
|
||||||
|
_response(404),
|
||||||
|
_response(200),
|
||||||
|
], deleteError: StateError('DELETE must not be called'));
|
||||||
|
await expectLater(client.deleteFile('devices/pc/gone.json'), completes);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws GitHubSyncError on a delete non-2xx response', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(200, {'sha': 'abc123'}),
|
||||||
|
], deleteResponse: _response(500));
|
||||||
|
expect(
|
||||||
|
() => client.deleteFile('devices/pc/log.json'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws GitHubSyncError on a delete network exception', () async {
|
||||||
|
final client = _client([
|
||||||
|
_response(200, {'sha': 'abc123'}),
|
||||||
|
], deleteError: http.ClientException('offline'));
|
||||||
|
expect(
|
||||||
|
() => client.deleteFile('devices/pc/log.json'),
|
||||||
|
throwsA(isA<GitHubSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
196
crdt_sync_dart/test/mirror_store_fallback_test.dart
Normal file
196
crdt_sync_dart/test/mirror_store_fallback_test.dart
Normal file
@ -0,0 +1,196 @@
|
|||||||
|
/// Tests for the dual-write decorator used during the GitHub -> Firebase
|
||||||
|
/// cutover.
|
||||||
|
///
|
||||||
|
/// The asymmetry is the whole point and is what these assert: a primary
|
||||||
|
/// failure must fail the tick, a mirror failure must not, and reads must
|
||||||
|
/// consult both so that a half-migrated app (one device moved, one not) still
|
||||||
|
/// converges in both directions.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
/// A scriptable in-memory [RemoteStore] that can be told to fail.
|
||||||
|
class _FakeStore implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeStore({Map<String, String>? files, this.failing = false})
|
||||||
|
: files = files ?? {};
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
bool failing;
|
||||||
|
final List<String> writes = [];
|
||||||
|
bool closed = false;
|
||||||
|
|
||||||
|
void _guard(String what) {
|
||||||
|
if (failing) throw RemoteSyncError('$what failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async {
|
||||||
|
_guard('list');
|
||||||
|
return files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
_guard('read');
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
_guard('write');
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
_guard('map read');
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async {
|
||||||
|
_guard('delete');
|
||||||
|
files.remove(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => !failing;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store with no bulk-map capability, standing in for [GitHubClient].
|
||||||
|
class _FakeStoreWithoutBulkRead implements RemoteStore {
|
||||||
|
_FakeStoreWithoutBulkRead([Map<String, String>? files])
|
||||||
|
: _inner = _FakeStore(files: files);
|
||||||
|
|
||||||
|
final _FakeStore _inner;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(String p, String t, {required String message}) =>
|
||||||
|
_inner.putFileText(p, t, message: message);
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) =>
|
||||||
|
_inner.deleteFile(path, message: message);
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
||||||
|
@override
|
||||||
|
void close() => _inner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
({
|
||||||
|
MirrorStore store,
|
||||||
|
_FakeStore primary,
|
||||||
|
_FakeStore mirror,
|
||||||
|
List<String> failures,
|
||||||
|
})
|
||||||
|
_mirror({
|
||||||
|
Map<String, String>? primaryFiles,
|
||||||
|
Map<String, String>? mirrorFiles,
|
||||||
|
bool primaryFailing = false,
|
||||||
|
bool mirrorFailing = false,
|
||||||
|
}) {
|
||||||
|
final primary = _FakeStore(files: primaryFiles, failing: primaryFailing);
|
||||||
|
final mirror = _FakeStore(files: mirrorFiles, failing: mirrorFailing);
|
||||||
|
final failures = <String>[];
|
||||||
|
return (
|
||||||
|
store: MirrorStore(
|
||||||
|
primary: primary,
|
||||||
|
mirror: mirror,
|
||||||
|
onMirrorFailure: (operation, _) => failures.add(operation),
|
||||||
|
),
|
||||||
|
primary: primary,
|
||||||
|
mirror: mirror,
|
||||||
|
failures: failures,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('primary read fallback', () {
|
||||||
|
test('getFileText falls back to the mirror', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFailing: true,
|
||||||
|
mirrorFiles: {'ns/phone/log.json': '{}'},
|
||||||
|
);
|
||||||
|
expect(await m.store.getFileText('ns/phone/log.json'), '{}');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getFileText throws when both fail', () async {
|
||||||
|
final m = _mirror(primaryFailing: true, mirrorFailing: true);
|
||||||
|
await expectLater(
|
||||||
|
() => m.store.getFileText('ns/phone/log.json'),
|
||||||
|
throwsA(isA<RemoteSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getFileText throws when primary fails and mirror lacks it', () async {
|
||||||
|
// A reachable mirror that simply does not hold the file is not an
|
||||||
|
// answer either, since the primary's copy was never read.
|
||||||
|
final m = _mirror(primaryFailing: true);
|
||||||
|
await expectLater(
|
||||||
|
() => m.store.getFileText('ns/phone/log.json'),
|
||||||
|
throwsA(isA<RemoteSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getStringMap falls back to the mirror', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFailing: true,
|
||||||
|
mirrorFiles: {'ns/revs/phone': 'r1'},
|
||||||
|
);
|
||||||
|
expect(await m.store.getStringMap('ns/revs'), {'phone': 'r1'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getStringMap throws when both fail', () async {
|
||||||
|
final m = _mirror(primaryFailing: true, mirrorFailing: true);
|
||||||
|
await expectLater(
|
||||||
|
() => m.store.getStringMap('ns/revs'),
|
||||||
|
throwsA(isA<RemoteSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getStringMap tolerates a mirror that cannot bulk-read', () async {
|
||||||
|
// A mirror with no bulk-read capability (GitHub) contributes nothing,
|
||||||
|
// but that is not a failure -- it simply has no revisions to add, so a
|
||||||
|
// working primary's map must still come back.
|
||||||
|
final store = MirrorStore(
|
||||||
|
primary: _FakeStore(files: {'ns/revs/pc': 'r1'}),
|
||||||
|
mirror: _FakeStoreWithoutBulkRead(),
|
||||||
|
);
|
||||||
|
expect(await store.getStringMap('ns/revs'), {'pc': 'r1'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('writes stay fail-closed on a primary failure', () async {
|
||||||
|
// The read fix must NOT loosen writes: an unaccepted write has not
|
||||||
|
// happened, so it must still fail the tick.
|
||||||
|
final m = _mirror(primaryFailing: true);
|
||||||
|
await expectLater(
|
||||||
|
() => m.store.putFileText('ns/pc/log.json', '{}', message: 'm'),
|
||||||
|
throwsA(isA<RemoteSyncError>()),
|
||||||
|
);
|
||||||
|
await expectLater(
|
||||||
|
() => m.store.deleteFile('ns/pc/log.json'),
|
||||||
|
throwsA(isA<RemoteSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
153
crdt_sync_dart/test/mirror_store_reads_test.dart
Normal file
153
crdt_sync_dart/test/mirror_store_reads_test.dart
Normal file
@ -0,0 +1,153 @@
|
|||||||
|
/// Tests for the dual-write decorator used during the GitHub -> Firebase
|
||||||
|
/// cutover.
|
||||||
|
///
|
||||||
|
/// The asymmetry is the whole point and is what these assert: a primary
|
||||||
|
/// failure must fail the tick, a mirror failure must not, and reads must
|
||||||
|
/// consult both so that a half-migrated app (one device moved, one not) still
|
||||||
|
/// converges in both directions.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
/// A scriptable in-memory [RemoteStore] that can be told to fail.
|
||||||
|
class _FakeStore implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeStore({Map<String, String>? files, this.failing = false})
|
||||||
|
: files = files ?? {};
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
bool failing;
|
||||||
|
final List<String> writes = [];
|
||||||
|
bool closed = false;
|
||||||
|
|
||||||
|
void _guard(String what) {
|
||||||
|
if (failing) throw RemoteSyncError('$what failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async {
|
||||||
|
_guard('list');
|
||||||
|
return files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
_guard('read');
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
_guard('write');
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
_guard('map read');
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async {
|
||||||
|
_guard('delete');
|
||||||
|
files.remove(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => !failing;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
({
|
||||||
|
MirrorStore store,
|
||||||
|
_FakeStore primary,
|
||||||
|
_FakeStore mirror,
|
||||||
|
List<String> failures,
|
||||||
|
})
|
||||||
|
_mirror({
|
||||||
|
Map<String, String>? primaryFiles,
|
||||||
|
Map<String, String>? mirrorFiles,
|
||||||
|
bool primaryFailing = false,
|
||||||
|
bool mirrorFailing = false,
|
||||||
|
}) {
|
||||||
|
final primary = _FakeStore(files: primaryFiles, failing: primaryFailing);
|
||||||
|
final mirror = _FakeStore(files: mirrorFiles, failing: mirrorFailing);
|
||||||
|
final failures = <String>[];
|
||||||
|
return (
|
||||||
|
store: MirrorStore(
|
||||||
|
primary: primary,
|
||||||
|
mirror: mirror,
|
||||||
|
onMirrorFailure: (operation, _) => failures.add(operation),
|
||||||
|
),
|
||||||
|
primary: primary,
|
||||||
|
mirror: mirror,
|
||||||
|
failures: failures,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('listDirectory', () {
|
||||||
|
test('unions devices from both backends', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFiles: {'ns/pc/log.json': '{}'},
|
||||||
|
mirrorFiles: {'ns/phone/log.json': '{}'},
|
||||||
|
);
|
||||||
|
expect(await m.store.listDirectory('ns'), containsAll(['pc', 'phone']));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('does not duplicate a device present in both', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFiles: {'ns/pc/log.json': '{}'},
|
||||||
|
mirrorFiles: {'ns/pc/log.json': '{}'},
|
||||||
|
);
|
||||||
|
expect(await m.store.listDirectory('ns'), ['pc']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a mirror failure degrades to the primary list', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFiles: {'ns/pc/log.json': '{}'},
|
||||||
|
mirrorFailing: true,
|
||||||
|
);
|
||||||
|
expect(await m.store.listDirectory('ns'), ['pc']);
|
||||||
|
expect(m.failures, ['listDirectory ns']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a primary failure degrades to the mirror list', () async {
|
||||||
|
// READS are resilient on both sides: a Firebase outage must not hide
|
||||||
|
// the mirror's devices. This used to throw, which made a primary outage
|
||||||
|
// look like "no devices exist" -- the union read silently degrading to
|
||||||
|
// nothing, precisely when the fallback was needed.
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFailing: true,
|
||||||
|
mirrorFiles: {'ns/phone/log.json': '{}'},
|
||||||
|
);
|
||||||
|
expect(await m.store.listDirectory('ns'), ['phone']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('both backends failing throws', () async {
|
||||||
|
// With no answer from either side, fail closed: an empty list is
|
||||||
|
// indistinguishable from "no devices", and callers act on that.
|
||||||
|
final m = _mirror(primaryFailing: true, mirrorFailing: true);
|
||||||
|
await expectLater(
|
||||||
|
() => m.store.listDirectory('ns'),
|
||||||
|
throwsA(isA<RemoteSyncError>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
248
crdt_sync_dart/test/mirror_store_revisions_test.dart
Normal file
248
crdt_sync_dart/test/mirror_store_revisions_test.dart
Normal file
@ -0,0 +1,248 @@
|
|||||||
|
/// Tests for the dual-write decorator used during the GitHub -> Firebase
|
||||||
|
/// cutover.
|
||||||
|
///
|
||||||
|
/// The asymmetry is the whole point and is what these assert: a primary
|
||||||
|
/// failure must fail the tick, a mirror failure must not, and reads must
|
||||||
|
/// consult both so that a half-migrated app (one device moved, one not) still
|
||||||
|
/// converges in both directions.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
/// A scriptable in-memory [RemoteStore] that can be told to fail.
|
||||||
|
class _FakeStore implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeStore({Map<String, String>? files, this.failing = false})
|
||||||
|
: files = files ?? {};
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
bool failing;
|
||||||
|
final List<String> writes = [];
|
||||||
|
bool closed = false;
|
||||||
|
|
||||||
|
void _guard(String what) {
|
||||||
|
if (failing) throw RemoteSyncError('$what failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async {
|
||||||
|
_guard('list');
|
||||||
|
return files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
_guard('read');
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
_guard('write');
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
_guard('map read');
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async {
|
||||||
|
_guard('delete');
|
||||||
|
files.remove(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => !failing;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A store with no bulk-map capability, standing in for [GitHubClient].
|
||||||
|
class _FakeStoreWithoutBulkRead implements RemoteStore {
|
||||||
|
_FakeStoreWithoutBulkRead([Map<String, String>? files])
|
||||||
|
: _inner = _FakeStore(files: files);
|
||||||
|
|
||||||
|
final _FakeStore _inner;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(String p, String t, {required String message}) =>
|
||||||
|
_inner.putFileText(p, t, message: message);
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) =>
|
||||||
|
_inner.deleteFile(path, message: message);
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
||||||
|
@override
|
||||||
|
void close() => _inner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
({
|
||||||
|
MirrorStore store,
|
||||||
|
_FakeStore primary,
|
||||||
|
_FakeStore mirror,
|
||||||
|
List<String> failures,
|
||||||
|
})
|
||||||
|
_mirror({
|
||||||
|
Map<String, String>? primaryFiles,
|
||||||
|
Map<String, String>? mirrorFiles,
|
||||||
|
bool primaryFailing = false,
|
||||||
|
bool mirrorFailing = false,
|
||||||
|
}) {
|
||||||
|
final primary = _FakeStore(files: primaryFiles, failing: primaryFailing);
|
||||||
|
final mirror = _FakeStore(files: mirrorFiles, failing: mirrorFailing);
|
||||||
|
final failures = <String>[];
|
||||||
|
return (
|
||||||
|
store: MirrorStore(
|
||||||
|
primary: primary,
|
||||||
|
mirror: mirror,
|
||||||
|
onMirrorFailure: (operation, _) => failures.add(operation),
|
||||||
|
),
|
||||||
|
primary: primary,
|
||||||
|
mirror: mirror,
|
||||||
|
failures: failures,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('revision maps', () {
|
||||||
|
test('merge both backends, primary winning on conflict', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFiles: {'ns/revs/pc': 'primary-rev'},
|
||||||
|
mirrorFiles: {'ns/revs/pc': 'mirror-rev', 'ns/revs/phone': 'old-rev'},
|
||||||
|
);
|
||||||
|
expect(await m.store.getStringMap('ns/revs'), {
|
||||||
|
'pc': 'primary-rev',
|
||||||
|
// An un-migrated device publishes revisions only to the mirror;
|
||||||
|
// without this it would look revision-less and be re-downloaded
|
||||||
|
// every tick for the whole trial.
|
||||||
|
'phone': 'old-rev',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a mirror failure degrades to primary revisions only', () async {
|
||||||
|
final m = _mirror(
|
||||||
|
primaryFiles: {'ns/revs/pc': 'primary-rev'},
|
||||||
|
mirrorFailing: true,
|
||||||
|
);
|
||||||
|
expect(await m.store.getStringMap('ns/revs'), {'pc': 'primary-rev'});
|
||||||
|
expect(m.failures, ['getStringMap ns/revs']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a backend without bulk reads simply contributes nothing', () async {
|
||||||
|
final store = MirrorStore(
|
||||||
|
primary: _FakeStore(files: {'ns/revs/pc': 'primary-rev'}),
|
||||||
|
mirror: _FakeStoreWithoutBulkRead({'ns/revs/phone': 'ignored'}),
|
||||||
|
);
|
||||||
|
expect(await store.getStringMap('ns/revs'), {'pc': 'primary-rev'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is empty when the primary has no bulk reads either', () async {
|
||||||
|
final store = MirrorStore(
|
||||||
|
primary: _FakeStoreWithoutBulkRead(),
|
||||||
|
mirror: _FakeStoreWithoutBulkRead(),
|
||||||
|
);
|
||||||
|
expect(await store.getStringMap('ns/revs'), isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('lifecycle', () {
|
||||||
|
test('canAccessRemote reports only the primary', () async {
|
||||||
|
// A Test-connection button must not report success because the backend
|
||||||
|
// being retired happens to answer.
|
||||||
|
final m = _mirror(primaryFailing: true);
|
||||||
|
expect(await m.store.canAccessRemote(), isFalse);
|
||||||
|
final healthy = _mirror(mirrorFailing: true);
|
||||||
|
expect(await healthy.store.canAccessRemote(), isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('close releases both backends', () {
|
||||||
|
final m = _mirror();
|
||||||
|
m.store.close();
|
||||||
|
expect(m.primary.closed, isTrue);
|
||||||
|
expect(m.mirror.closed, isTrue);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a mirror failure with no handler is still swallowed', () async {
|
||||||
|
final store = MirrorStore(
|
||||||
|
primary: _FakeStore(),
|
||||||
|
mirror: _FakeStore(failing: true),
|
||||||
|
);
|
||||||
|
await expectLater(
|
||||||
|
store.putFileText('ns/pc/log.json', '{}', message: 'm'),
|
||||||
|
completes,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('is itself a RemoteStore, so syncLog accepts it', () {
|
||||||
|
expect(_mirror().store, isA<RemoteStore>());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('end to end through syncLog', () {
|
||||||
|
test('a half-migrated pair still converges both ways', () async {
|
||||||
|
// desktop is on Firebase+mirror; phone has not migrated and still
|
||||||
|
// writes only to GitHub. Both must end up with both records.
|
||||||
|
final github = _FakeStore();
|
||||||
|
final firebase = _FakeStore();
|
||||||
|
|
||||||
|
Log log(String id, String nodeId) => {
|
||||||
|
id: Record(
|
||||||
|
id: id,
|
||||||
|
fields: {
|
||||||
|
'v': (id, Hlc(wallTimeMs: 1000, counter: 0, nodeId: nodeId)),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
};
|
||||||
|
// The library's own serialization, so this exercises the same
|
||||||
|
// encoding the apps use rather than a test-only one.
|
||||||
|
const encode = logToJson;
|
||||||
|
const decode = logFromJson;
|
||||||
|
|
||||||
|
// Un-migrated phone: GitHub only.
|
||||||
|
await syncLog(
|
||||||
|
client: github,
|
||||||
|
deviceId: 'phone',
|
||||||
|
pathPrefix: 'ns/devices',
|
||||||
|
localLog: log('from-phone', 'node-phone'),
|
||||||
|
encode: encode,
|
||||||
|
decode: decode,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Migrated desktop: Firebase primary, GitHub mirror.
|
||||||
|
final merged = await syncLog(
|
||||||
|
client: MirrorStore(primary: firebase, mirror: github),
|
||||||
|
deviceId: 'desktop',
|
||||||
|
pathPrefix: 'ns/devices',
|
||||||
|
localLog: log('from-desktop', 'node-desktop'),
|
||||||
|
encode: encode,
|
||||||
|
decode: decode,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(merged.keys, containsAll(['from-phone', 'from-desktop']));
|
||||||
|
// The desktop's merged result is mirrored back to GitHub, so the
|
||||||
|
// un-migrated phone sees it on its next tick.
|
||||||
|
expect(github.files['ns/devices/desktop/log.json'], isNotNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -74,29 +74,6 @@ class _FakeStore implements RemoteStore, BulkMapReader {
|
|||||||
void close() => closed = true;
|
void close() => closed = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A store with no bulk-map capability, standing in for [GitHubClient].
|
|
||||||
class _FakeStoreWithoutBulkRead implements RemoteStore {
|
|
||||||
_FakeStoreWithoutBulkRead([Map<String, String>? files])
|
|
||||||
: _inner = _FakeStore(files: files);
|
|
||||||
|
|
||||||
final _FakeStore _inner;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
|
||||||
@override
|
|
||||||
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
|
||||||
@override
|
|
||||||
Future<void> putFileText(String p, String t, {required String message}) =>
|
|
||||||
_inner.putFileText(p, t, message: message);
|
|
||||||
@override
|
|
||||||
Future<void> deleteFile(String path, {String message = ''}) =>
|
|
||||||
_inner.deleteFile(path, message: message);
|
|
||||||
@override
|
|
||||||
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
|
||||||
@override
|
|
||||||
void close() => _inner.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
({
|
({
|
||||||
MirrorStore store,
|
MirrorStore store,
|
||||||
_FakeStore primary,
|
_FakeStore primary,
|
||||||
@ -210,243 +187,4 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('listDirectory', () {
|
|
||||||
test('unions devices from both backends', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFiles: {'ns/pc/log.json': '{}'},
|
|
||||||
mirrorFiles: {'ns/phone/log.json': '{}'},
|
|
||||||
);
|
|
||||||
expect(await m.store.listDirectory('ns'), containsAll(['pc', 'phone']));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('does not duplicate a device present in both', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFiles: {'ns/pc/log.json': '{}'},
|
|
||||||
mirrorFiles: {'ns/pc/log.json': '{}'},
|
|
||||||
);
|
|
||||||
expect(await m.store.listDirectory('ns'), ['pc']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a mirror failure degrades to the primary list', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFiles: {'ns/pc/log.json': '{}'},
|
|
||||||
mirrorFailing: true,
|
|
||||||
);
|
|
||||||
expect(await m.store.listDirectory('ns'), ['pc']);
|
|
||||||
expect(m.failures, ['listDirectory ns']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a primary failure degrades to the mirror list', () async {
|
|
||||||
// READS are resilient on both sides: a Firebase outage must not hide
|
|
||||||
// the mirror's devices. This used to throw, which made a primary outage
|
|
||||||
// look like "no devices exist" -- the union read silently degrading to
|
|
||||||
// nothing, precisely when the fallback was needed.
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFailing: true,
|
|
||||||
mirrorFiles: {'ns/phone/log.json': '{}'},
|
|
||||||
);
|
|
||||||
expect(await m.store.listDirectory('ns'), ['phone']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('both backends failing throws', () async {
|
|
||||||
// With no answer from either side, fail closed: an empty list is
|
|
||||||
// indistinguishable from "no devices", and callers act on that.
|
|
||||||
final m = _mirror(primaryFailing: true, mirrorFailing: true);
|
|
||||||
await expectLater(
|
|
||||||
() => m.store.listDirectory('ns'),
|
|
||||||
throwsA(isA<RemoteSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('primary read fallback', () {
|
|
||||||
test('getFileText falls back to the mirror', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFailing: true,
|
|
||||||
mirrorFiles: {'ns/phone/log.json': '{}'},
|
|
||||||
);
|
|
||||||
expect(await m.store.getFileText('ns/phone/log.json'), '{}');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('getFileText throws when both fail', () async {
|
|
||||||
final m = _mirror(primaryFailing: true, mirrorFailing: true);
|
|
||||||
await expectLater(
|
|
||||||
() => m.store.getFileText('ns/phone/log.json'),
|
|
||||||
throwsA(isA<RemoteSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('getFileText throws when primary fails and mirror lacks it', () async {
|
|
||||||
// A reachable mirror that simply does not hold the file is not an
|
|
||||||
// answer either, since the primary's copy was never read.
|
|
||||||
final m = _mirror(primaryFailing: true);
|
|
||||||
await expectLater(
|
|
||||||
() => m.store.getFileText('ns/phone/log.json'),
|
|
||||||
throwsA(isA<RemoteSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('getStringMap falls back to the mirror', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFailing: true,
|
|
||||||
mirrorFiles: {'ns/revs/phone': 'r1'},
|
|
||||||
);
|
|
||||||
expect(await m.store.getStringMap('ns/revs'), {'phone': 'r1'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('getStringMap throws when both fail', () async {
|
|
||||||
final m = _mirror(primaryFailing: true, mirrorFailing: true);
|
|
||||||
await expectLater(
|
|
||||||
() => m.store.getStringMap('ns/revs'),
|
|
||||||
throwsA(isA<RemoteSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('getStringMap tolerates a mirror that cannot bulk-read', () async {
|
|
||||||
// A mirror with no bulk-read capability (GitHub) contributes nothing,
|
|
||||||
// but that is not a failure -- it simply has no revisions to add, so a
|
|
||||||
// working primary's map must still come back.
|
|
||||||
final store = MirrorStore(
|
|
||||||
primary: _FakeStore(files: {'ns/revs/pc': 'r1'}),
|
|
||||||
mirror: _FakeStoreWithoutBulkRead(),
|
|
||||||
);
|
|
||||||
expect(await store.getStringMap('ns/revs'), {'pc': 'r1'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('writes stay fail-closed on a primary failure', () async {
|
|
||||||
// The read fix must NOT loosen writes: an unaccepted write has not
|
|
||||||
// happened, so it must still fail the tick.
|
|
||||||
final m = _mirror(primaryFailing: true);
|
|
||||||
await expectLater(
|
|
||||||
() => m.store.putFileText('ns/pc/log.json', '{}', message: 'm'),
|
|
||||||
throwsA(isA<RemoteSyncError>()),
|
|
||||||
);
|
|
||||||
await expectLater(
|
|
||||||
() => m.store.deleteFile('ns/pc/log.json'),
|
|
||||||
throwsA(isA<RemoteSyncError>()),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('revision maps', () {
|
|
||||||
test('merge both backends, primary winning on conflict', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFiles: {'ns/revs/pc': 'primary-rev'},
|
|
||||||
mirrorFiles: {'ns/revs/pc': 'mirror-rev', 'ns/revs/phone': 'old-rev'},
|
|
||||||
);
|
|
||||||
expect(await m.store.getStringMap('ns/revs'), {
|
|
||||||
'pc': 'primary-rev',
|
|
||||||
// An un-migrated device publishes revisions only to the mirror;
|
|
||||||
// without this it would look revision-less and be re-downloaded
|
|
||||||
// every tick for the whole trial.
|
|
||||||
'phone': 'old-rev',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a mirror failure degrades to primary revisions only', () async {
|
|
||||||
final m = _mirror(
|
|
||||||
primaryFiles: {'ns/revs/pc': 'primary-rev'},
|
|
||||||
mirrorFailing: true,
|
|
||||||
);
|
|
||||||
expect(await m.store.getStringMap('ns/revs'), {'pc': 'primary-rev'});
|
|
||||||
expect(m.failures, ['getStringMap ns/revs']);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a backend without bulk reads simply contributes nothing', () async {
|
|
||||||
final store = MirrorStore(
|
|
||||||
primary: _FakeStore(files: {'ns/revs/pc': 'primary-rev'}),
|
|
||||||
mirror: _FakeStoreWithoutBulkRead({'ns/revs/phone': 'ignored'}),
|
|
||||||
);
|
|
||||||
expect(await store.getStringMap('ns/revs'), {'pc': 'primary-rev'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is empty when the primary has no bulk reads either', () async {
|
|
||||||
final store = MirrorStore(
|
|
||||||
primary: _FakeStoreWithoutBulkRead(),
|
|
||||||
mirror: _FakeStoreWithoutBulkRead(),
|
|
||||||
);
|
|
||||||
expect(await store.getStringMap('ns/revs'), isEmpty);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('lifecycle', () {
|
|
||||||
test('canAccessRemote reports only the primary', () async {
|
|
||||||
// A Test-connection button must not report success because the backend
|
|
||||||
// being retired happens to answer.
|
|
||||||
final m = _mirror(primaryFailing: true);
|
|
||||||
expect(await m.store.canAccessRemote(), isFalse);
|
|
||||||
final healthy = _mirror(mirrorFailing: true);
|
|
||||||
expect(await healthy.store.canAccessRemote(), isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('close releases both backends', () {
|
|
||||||
final m = _mirror();
|
|
||||||
m.store.close();
|
|
||||||
expect(m.primary.closed, isTrue);
|
|
||||||
expect(m.mirror.closed, isTrue);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('a mirror failure with no handler is still swallowed', () async {
|
|
||||||
final store = MirrorStore(
|
|
||||||
primary: _FakeStore(),
|
|
||||||
mirror: _FakeStore(failing: true),
|
|
||||||
);
|
|
||||||
await expectLater(
|
|
||||||
store.putFileText('ns/pc/log.json', '{}', message: 'm'),
|
|
||||||
completes,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('is itself a RemoteStore, so syncLog accepts it', () {
|
|
||||||
expect(_mirror().store, isA<RemoteStore>());
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('end to end through syncLog', () {
|
|
||||||
test('a half-migrated pair still converges both ways', () async {
|
|
||||||
// desktop is on Firebase+mirror; phone has not migrated and still
|
|
||||||
// writes only to GitHub. Both must end up with both records.
|
|
||||||
final github = _FakeStore();
|
|
||||||
final firebase = _FakeStore();
|
|
||||||
|
|
||||||
Log log(String id, String nodeId) => {
|
|
||||||
id: Record(
|
|
||||||
id: id,
|
|
||||||
fields: {
|
|
||||||
'v': (id, Hlc(wallTimeMs: 1000, counter: 0, nodeId: nodeId)),
|
|
||||||
},
|
|
||||||
),
|
|
||||||
};
|
|
||||||
// The library's own serialization, so this exercises the same
|
|
||||||
// encoding the apps use rather than a test-only one.
|
|
||||||
const encode = logToJson;
|
|
||||||
const decode = logFromJson;
|
|
||||||
|
|
||||||
// Un-migrated phone: GitHub only.
|
|
||||||
await syncLog(
|
|
||||||
client: github,
|
|
||||||
deviceId: 'phone',
|
|
||||||
pathPrefix: 'ns/devices',
|
|
||||||
localLog: log('from-phone', 'node-phone'),
|
|
||||||
encode: encode,
|
|
||||||
decode: decode,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Migrated desktop: Firebase primary, GitHub mirror.
|
|
||||||
final merged = await syncLog(
|
|
||||||
client: MirrorStore(primary: firebase, mirror: github),
|
|
||||||
deviceId: 'desktop',
|
|
||||||
pathPrefix: 'ns/devices',
|
|
||||||
localLog: log('from-desktop', 'node-desktop'),
|
|
||||||
encode: encode,
|
|
||||||
decode: decode,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(merged.keys, containsAll(['from-phone', 'from-desktop']));
|
|
||||||
// The desktop's merged result is mirrored back to GitHub, so the
|
|
||||||
// un-migrated phone sees it on its next tick.
|
|
||||||
expect(github.files['ns/devices/desktop/log.json'], isNotNull);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
158
crdt_sync_dart/test/sync_revisions_backends_test.dart
Normal file
158
crdt_sync_dart/test/sync_revisions_backends_test.dart
Normal file
@ -0,0 +1,158 @@
|
|||||||
|
/// Tests for the revision tracking that keeps sync inside the free tier.
|
||||||
|
///
|
||||||
|
/// Two savings, both measured against the GitHub-backed history this
|
||||||
|
/// replaces: 88.3% of pushes there were byte-identical no-ops, and every tick
|
||||||
|
/// re-downloaded every peer's whole log regardless of whether it had changed.
|
||||||
|
/// These tests assert the *request counts*, since that -- not the merge
|
||||||
|
/// result -- is what the free-tier headroom depends on.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
Log _log(String id, String value, {String nodeId = 'node-a'}) => {
|
||||||
|
id: Record(
|
||||||
|
id: id,
|
||||||
|
fields: {
|
||||||
|
'value': (value, Hlc(wallTimeMs: 1000, counter: 0, nodeId: nodeId)),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
String _encode(Log log) =>
|
||||||
|
jsonEncode(log.map((id, record) => MapEntry(id, record.toJson())));
|
||||||
|
|
||||||
|
Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
|
||||||
|
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// An in-memory [RemoteStore] that also serves revision maps in one read,
|
||||||
|
/// standing in for [FirebaseRestClient]. Counts every call so tests can
|
||||||
|
/// assert on traffic rather than on results.
|
||||||
|
class _FakeRemote implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeRemote(this.files);
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
final List<String> reads = [];
|
||||||
|
final List<String> writes = [];
|
||||||
|
final List<String> mapReads = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async => files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
reads.add(path);
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
mapReads.add(path);
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async =>
|
||||||
|
files.remove(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [RemoteStore] with no bulk-map capability, standing in for
|
||||||
|
/// [GitHubClient]: revision tracking must degrade, not break.
|
||||||
|
///
|
||||||
|
/// Delegates rather than extends, because a subclass of [_FakeRemote] would
|
||||||
|
/// inherit `BulkMapReader` -- the very capability this fake exists to lack.
|
||||||
|
class _FakeRemoteWithoutBulkRead implements RemoteStore {
|
||||||
|
_FakeRemoteWithoutBulkRead(Map<String, String> files)
|
||||||
|
: _inner = _FakeRemote(files);
|
||||||
|
|
||||||
|
final _FakeRemote _inner;
|
||||||
|
|
||||||
|
Map<String, String> get files => _inner.files;
|
||||||
|
List<String> get reads => _inner.reads;
|
||||||
|
List<String> get writes => _inner.writes;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) => _inner.putFileText(path, text, message: message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) =>
|
||||||
|
_inner.deleteFile(path, message: message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() => _inner.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Log> _tick(
|
||||||
|
RemoteStore remote,
|
||||||
|
SyncStateStore? store, {
|
||||||
|
Log local = const {},
|
||||||
|
String deviceId = 'pc',
|
||||||
|
}) => syncLog(
|
||||||
|
client: remote,
|
||||||
|
deviceId: deviceId,
|
||||||
|
pathPrefix: 'ns/devices',
|
||||||
|
localLog: local,
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
stateStore: store,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('backends without bulk-map reads', () {
|
||||||
|
test('still sync correctly, just without the saving', () async {
|
||||||
|
// GitHubClient has no BulkMapReader, so revision lookup degrades to
|
||||||
|
// "fetch everything" -- correctness must not depend on the optimisation.
|
||||||
|
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
||||||
|
final remote = _FakeRemoteWithoutBulkRead({
|
||||||
|
'ns/devices/phone/log.json': peer,
|
||||||
|
});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
final first = await _tick(remote, store);
|
||||||
|
expect(first.keys, contains('b'));
|
||||||
|
|
||||||
|
remote.reads.clear();
|
||||||
|
await _tick(remote, store, local: first);
|
||||||
|
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
125
crdt_sync_dart/test/sync_revisions_order_test.dart
Normal file
125
crdt_sync_dart/test/sync_revisions_order_test.dart
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
/// Tests for the revision tracking that keeps sync inside the free tier.
|
||||||
|
///
|
||||||
|
/// Two savings, both measured against the GitHub-backed history this
|
||||||
|
/// replaces: 88.3% of pushes there were byte-identical no-ops, and every tick
|
||||||
|
/// re-downloaded every peer's whole log regardless of whether it had changed.
|
||||||
|
/// These tests assert the *request counts*, since that -- not the merge
|
||||||
|
/// result -- is what the free-tier headroom depends on.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
Log _log(String id, String value, {String nodeId = 'node-a'}) => {
|
||||||
|
id: Record(
|
||||||
|
id: id,
|
||||||
|
fields: {
|
||||||
|
'value': (value, Hlc(wallTimeMs: 1000, counter: 0, nodeId: nodeId)),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
String _encode(Log log) =>
|
||||||
|
jsonEncode(log.map((id, record) => MapEntry(id, record.toJson())));
|
||||||
|
|
||||||
|
Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
|
||||||
|
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// An in-memory [RemoteStore] that also serves revision maps in one read,
|
||||||
|
/// standing in for [FirebaseRestClient]. Counts every call so tests can
|
||||||
|
/// assert on traffic rather than on results.
|
||||||
|
class _FakeRemote implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeRemote(this.files);
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
final List<String> reads = [];
|
||||||
|
final List<String> writes = [];
|
||||||
|
final List<String> mapReads = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async => files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
reads.add(path);
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
mapReads.add(path);
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async =>
|
||||||
|
files.remove(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Log> _tick(
|
||||||
|
RemoteStore remote,
|
||||||
|
SyncStateStore? store, {
|
||||||
|
Log local = const {},
|
||||||
|
String deviceId = 'pc',
|
||||||
|
}) => syncLog(
|
||||||
|
client: remote,
|
||||||
|
deviceId: deviceId,
|
||||||
|
pathPrefix: 'ns/devices',
|
||||||
|
localLog: local,
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
stateStore: store,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('revision publishing order', () {
|
||||||
|
test('publishes the log before its revision', () async {
|
||||||
|
// Reversed, a peer would cache "seen rev X" against a log it never
|
||||||
|
// received, and skip it forever.
|
||||||
|
final remote = _FakeRemote({});
|
||||||
|
await _tick(remote, InMemorySyncStateStore(), local: _log('a', '1'));
|
||||||
|
expect(
|
||||||
|
remote.writes.indexOf('ns/devices/pc/log.json'),
|
||||||
|
lessThan(remote.writes.indexOf('ns/revs/pc')),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each device writes only its own revision key', () async {
|
||||||
|
// Per-device keys rather than one shared map: a whole-map write would
|
||||||
|
// erase every other device's entry, after which those peers would look
|
||||||
|
// permanently unchanged and never be fetched again.
|
||||||
|
final remote = _FakeRemote({'ns/revs/phone': 'peer-rev'});
|
||||||
|
await _tick(remote, InMemorySyncStateStore(), local: _log('a', '1'));
|
||||||
|
expect(remote.files['ns/revs/phone'], 'peer-rev');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('PersistedSyncStateStore', () {});
|
||||||
|
}
|
||||||
193
crdt_sync_dart/test/sync_revisions_peers_test.dart
Normal file
193
crdt_sync_dart/test/sync_revisions_peers_test.dart
Normal file
@ -0,0 +1,193 @@
|
|||||||
|
/// Tests for the revision tracking that keeps sync inside the free tier.
|
||||||
|
///
|
||||||
|
/// Two savings, both measured against the GitHub-backed history this
|
||||||
|
/// replaces: 88.3% of pushes there were byte-identical no-ops, and every tick
|
||||||
|
/// re-downloaded every peer's whole log regardless of whether it had changed.
|
||||||
|
/// These tests assert the *request counts*, since that -- not the merge
|
||||||
|
/// result -- is what the free-tier headroom depends on.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
Log _log(String id, String value, {String nodeId = 'node-a'}) => {
|
||||||
|
id: Record(
|
||||||
|
id: id,
|
||||||
|
fields: {
|
||||||
|
'value': (value, Hlc(wallTimeMs: 1000, counter: 0, nodeId: nodeId)),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
String _encode(Log log) =>
|
||||||
|
jsonEncode(log.map((id, record) => MapEntry(id, record.toJson())));
|
||||||
|
|
||||||
|
Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
|
||||||
|
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// An in-memory [RemoteStore] that also serves revision maps in one read,
|
||||||
|
/// standing in for [FirebaseRestClient]. Counts every call so tests can
|
||||||
|
/// assert on traffic rather than on results.
|
||||||
|
class _FakeRemote implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeRemote(this.files);
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
final List<String> reads = [];
|
||||||
|
final List<String> writes = [];
|
||||||
|
final List<String> mapReads = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async => files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
reads.add(path);
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
mapReads.add(path);
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async =>
|
||||||
|
files.remove(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Log> _tick(
|
||||||
|
RemoteStore remote,
|
||||||
|
SyncStateStore? store, {
|
||||||
|
Log local = const {},
|
||||||
|
String deviceId = 'pc',
|
||||||
|
}) => syncLog(
|
||||||
|
client: remote,
|
||||||
|
deviceId: deviceId,
|
||||||
|
pathPrefix: 'ns/devices',
|
||||||
|
localLog: local,
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
stateStore: store,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('peer download suppression', () {
|
||||||
|
test('downloads a peer whose revision it has never seen', () async {
|
||||||
|
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
||||||
|
final remote = _FakeRemote({
|
||||||
|
'ns/devices/phone/log.json': peer,
|
||||||
|
'ns/revs/phone': revisionOf(peer),
|
||||||
|
});
|
||||||
|
final merged = await _tick(remote, InMemorySyncStateStore());
|
||||||
|
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
||||||
|
expect(merged.keys, contains('b'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('skips the download when the peer revision is unchanged', () async {
|
||||||
|
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
||||||
|
final remote = _FakeRemote({
|
||||||
|
'ns/devices/phone/log.json': peer,
|
||||||
|
'ns/revs/phone': revisionOf(peer),
|
||||||
|
});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
final first = await _tick(remote, store);
|
||||||
|
remote.reads.clear();
|
||||||
|
|
||||||
|
// The peer's records are already in the local log from tick one, so
|
||||||
|
// re-downloading them is pure waste -- this is the ~700 MB/month that
|
||||||
|
// the revision check removes.
|
||||||
|
await _tick(remote, store, local: first);
|
||||||
|
expect(remote.reads, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('downloads again once the peer publishes a new revision', () async {
|
||||||
|
final peerV1 = _encode(_log('b', 'v1', nodeId: 'node-b'));
|
||||||
|
final remote = _FakeRemote({
|
||||||
|
'ns/devices/phone/log.json': peerV1,
|
||||||
|
'ns/revs/phone': revisionOf(peerV1),
|
||||||
|
});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
final first = await _tick(remote, store);
|
||||||
|
remote.reads.clear();
|
||||||
|
|
||||||
|
final peerV2 = _encode({
|
||||||
|
..._decode(peerV1),
|
||||||
|
..._log('c', 'v2', nodeId: 'node-b'),
|
||||||
|
});
|
||||||
|
remote.files['ns/devices/phone/log.json'] = peerV2;
|
||||||
|
remote.files['ns/revs/phone'] = revisionOf(peerV2);
|
||||||
|
|
||||||
|
final second = await _tick(remote, store, local: first);
|
||||||
|
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
||||||
|
expect(second.keys, containsAll(['b', 'c']));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('re-downloads a peer whose push was corrupt', () async {
|
||||||
|
// A failed decode must not be remembered as seen, or the corruption
|
||||||
|
// would be permanent.
|
||||||
|
final remote = _FakeRemote({
|
||||||
|
'ns/devices/phone/log.json': 'not json at all',
|
||||||
|
'ns/revs/phone': revisionOf('not json at all'),
|
||||||
|
});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
await _tick(remote, store);
|
||||||
|
remote.reads.clear();
|
||||||
|
|
||||||
|
await _tick(remote, store);
|
||||||
|
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('downloads when the peer has published no revision yet', () async {
|
||||||
|
// A device still running the pre-migration code publishes a log but no
|
||||||
|
// revision; it must not be silently ignored.
|
||||||
|
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
||||||
|
final remote = _FakeRemote({'ns/devices/phone/log.json': peer});
|
||||||
|
final store = InMemorySyncStateStore();
|
||||||
|
final merged = await _tick(remote, store);
|
||||||
|
expect(merged.keys, contains('b'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('skips a peer that has nothing pushed yet', () async {
|
||||||
|
final remote = _FakeRemote({'ns/devices/phone/other.txt': 'x'});
|
||||||
|
final merged = await _tick(remote, InMemorySyncStateStore());
|
||||||
|
expect(merged, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never reads its own device back', () async {
|
||||||
|
final remote = _FakeRemote({
|
||||||
|
'ns/devices/pc/log.json': _encode(_log('a', '1')),
|
||||||
|
'ns/revs/pc': 'whatever',
|
||||||
|
});
|
||||||
|
await _tick(remote, InMemorySyncStateStore());
|
||||||
|
expect(remote.reads, isEmpty);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
193
crdt_sync_dart/test/sync_revisions_persistence_test.dart
Normal file
193
crdt_sync_dart/test/sync_revisions_persistence_test.dart
Normal file
@ -0,0 +1,193 @@
|
|||||||
|
/// Tests for the revision tracking that keeps sync inside the free tier.
|
||||||
|
///
|
||||||
|
/// Two savings, both measured against the GitHub-backed history this
|
||||||
|
/// replaces: 88.3% of pushes there were byte-identical no-ops, and every tick
|
||||||
|
/// re-downloaded every peer's whole log regardless of whether it had changed.
|
||||||
|
/// These tests assert the *request counts*, since that -- not the merge
|
||||||
|
/// result -- is what the free-tier headroom depends on.
|
||||||
|
library;
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
Log _log(String id, String value, {String nodeId = 'node-a'}) => {
|
||||||
|
id: Record(
|
||||||
|
id: id,
|
||||||
|
fields: {
|
||||||
|
'value': (value, Hlc(wallTimeMs: 1000, counter: 0, nodeId: nodeId)),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
};
|
||||||
|
|
||||||
|
String _encode(Log log) =>
|
||||||
|
jsonEncode(log.map((id, record) => MapEntry(id, record.toJson())));
|
||||||
|
|
||||||
|
Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
|
||||||
|
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||||
|
);
|
||||||
|
|
||||||
|
/// An in-memory [RemoteStore] that also serves revision maps in one read,
|
||||||
|
/// standing in for [FirebaseRestClient]. Counts every call so tests can
|
||||||
|
/// assert on traffic rather than on results.
|
||||||
|
class _FakeRemote implements RemoteStore, BulkMapReader {
|
||||||
|
_FakeRemote(this.files);
|
||||||
|
|
||||||
|
final Map<String, String> files;
|
||||||
|
final List<String> reads = [];
|
||||||
|
final List<String> writes = [];
|
||||||
|
final List<String> mapReads = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<String>> listDirectory(String path) async => files.keys
|
||||||
|
.where((key) => key.startsWith('$path/'))
|
||||||
|
.map((key) => key.substring(path.length + 1).split('/').first)
|
||||||
|
.toSet()
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> getFileText(String path) async {
|
||||||
|
reads.add(path);
|
||||||
|
return files[path];
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> putFileText(
|
||||||
|
String path,
|
||||||
|
String text, {
|
||||||
|
required String message,
|
||||||
|
}) async {
|
||||||
|
writes.add(path);
|
||||||
|
files[path] = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<Map<String, String>> getStringMap(String path) async {
|
||||||
|
mapReads.add(path);
|
||||||
|
return {
|
||||||
|
for (final entry in files.entries)
|
||||||
|
if (entry.key.startsWith('$path/'))
|
||||||
|
entry.key.substring(path.length + 1): entry.value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> deleteFile(String path, {String message = ''}) async =>
|
||||||
|
files.remove(path);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<bool> canAccessRemote() async => true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<Log> _tick(
|
||||||
|
RemoteStore remote,
|
||||||
|
SyncStateStore? store, {
|
||||||
|
Log local = const {},
|
||||||
|
String deviceId = 'pc',
|
||||||
|
}) => syncLog(
|
||||||
|
client: remote,
|
||||||
|
deviceId: deviceId,
|
||||||
|
pathPrefix: 'ns/devices',
|
||||||
|
localLog: local,
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
stateStore: store,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('PersistedSyncStateStore', () {
|
||||||
|
test('round-trips state through persistence', () async {
|
||||||
|
final persistence = _FakePersistence();
|
||||||
|
const state = SyncState(
|
||||||
|
pushedRev: 'rev-local',
|
||||||
|
peerRevs: {'phone': 'rev-phone'},
|
||||||
|
);
|
||||||
|
|
||||||
|
await PersistedSyncStateStore(persistence).save(state);
|
||||||
|
final loaded = await PersistedSyncStateStore(persistence).load();
|
||||||
|
|
||||||
|
// A *separate* store instance reads it back: that is the whole point --
|
||||||
|
// surviving the cold start that an in-memory store does not.
|
||||||
|
expect(loaded.pushedRev, 'rev-local');
|
||||||
|
expect(loaded.peerRevs, {'phone': 'rev-phone'});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('survives a cold start, so peers are not re-downloaded', () async {
|
||||||
|
// The free-tier claim on mobile rests on this: a fresh process must
|
||||||
|
// still skip an unchanged peer.
|
||||||
|
final persistence = _FakePersistence();
|
||||||
|
final remote = _FakeRemote({
|
||||||
|
'ns/devices/phone/log.json': _encode(_log('a', '1')),
|
||||||
|
'ns/revs/phone': revisionOf(_encode(_log('a', '1'))),
|
||||||
|
});
|
||||||
|
|
||||||
|
await _tick(remote, PersistedSyncStateStore(persistence));
|
||||||
|
remote.reads.clear();
|
||||||
|
await _tick(remote, PersistedSyncStateStore(persistence));
|
||||||
|
|
||||||
|
expect(remote.reads, isNot(contains('ns/devices/phone/log.json')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reports nothing remembered when absent', () async {
|
||||||
|
final loaded = await PersistedSyncStateStore(_FakePersistence()).load();
|
||||||
|
|
||||||
|
expect(loaded.pushedRev, isNull);
|
||||||
|
expect(loaded.peerRevs, isEmpty);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('degrades to remembering nothing when empty', () async {
|
||||||
|
final loaded = await PersistedSyncStateStore(
|
||||||
|
_FakePersistence(text: ''),
|
||||||
|
).load();
|
||||||
|
|
||||||
|
expect(loaded.pushedRev, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('degrades to remembering nothing when corrupt', () async {
|
||||||
|
// Costs one tick of extra traffic rather than failing the sync.
|
||||||
|
final loaded = await PersistedSyncStateStore(
|
||||||
|
_FakePersistence(text: 'not json{'),
|
||||||
|
).load();
|
||||||
|
|
||||||
|
expect(loaded.pushedRev, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('degrades to remembering nothing when not an object', () async {
|
||||||
|
final loaded = await PersistedSyncStateStore(
|
||||||
|
_FakePersistence(text: '["a list"]'),
|
||||||
|
).load();
|
||||||
|
|
||||||
|
expect(loaded.pushedRev, isNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('degrades to remembering nothing when the read throws', () async {
|
||||||
|
// An unreadable file must not fail the tick.
|
||||||
|
final loaded = await PersistedSyncStateStore(
|
||||||
|
_FakePersistence(readThrows: true),
|
||||||
|
).load();
|
||||||
|
|
||||||
|
expect(loaded.pushedRev, isNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [LogPersistence] fake with injectable failure modes.
|
||||||
|
class _FakePersistence implements LogPersistence {
|
||||||
|
_FakePersistence({this.text, this.readThrows = false});
|
||||||
|
|
||||||
|
String? text;
|
||||||
|
final bool readThrows;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<String?> read() async {
|
||||||
|
if (readThrows) throw const FormatException('unreadable');
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> write(String value) async => text = value;
|
||||||
|
}
|
||||||
@ -83,45 +83,6 @@ class _FakeRemote implements RemoteStore, BulkMapReader {
|
|||||||
void close() {}
|
void close() {}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A [RemoteStore] with no bulk-map capability, standing in for
|
|
||||||
/// [GitHubClient]: revision tracking must degrade, not break.
|
|
||||||
///
|
|
||||||
/// Delegates rather than extends, because a subclass of [_FakeRemote] would
|
|
||||||
/// inherit `BulkMapReader` -- the very capability this fake exists to lack.
|
|
||||||
class _FakeRemoteWithoutBulkRead implements RemoteStore {
|
|
||||||
_FakeRemoteWithoutBulkRead(Map<String, String> files)
|
|
||||||
: _inner = _FakeRemote(files);
|
|
||||||
|
|
||||||
final _FakeRemote _inner;
|
|
||||||
|
|
||||||
Map<String, String> get files => _inner.files;
|
|
||||||
List<String> get reads => _inner.reads;
|
|
||||||
List<String> get writes => _inner.writes;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<List<String>> listDirectory(String path) => _inner.listDirectory(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> getFileText(String path) => _inner.getFileText(path);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> putFileText(
|
|
||||||
String path,
|
|
||||||
String text, {
|
|
||||||
required String message,
|
|
||||||
}) => _inner.putFileText(path, text, message: message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> deleteFile(String path, {String message = ''}) =>
|
|
||||||
_inner.deleteFile(path, message: message);
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<bool> canAccessRemote() => _inner.canAccessRemote();
|
|
||||||
|
|
||||||
@override
|
|
||||||
void close() => _inner.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<Log> _tick(
|
Future<Log> _tick(
|
||||||
RemoteStore remote,
|
RemoteStore remote,
|
||||||
SyncStateStore? store, {
|
SyncStateStore? store, {
|
||||||
@ -224,228 +185,4 @@ void main() {
|
|||||||
expect(remote.writes.where((w) => w.startsWith('ns/revs')), isEmpty);
|
expect(remote.writes.where((w) => w.startsWith('ns/revs')), isEmpty);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('peer download suppression', () {
|
|
||||||
test('downloads a peer whose revision it has never seen', () async {
|
|
||||||
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'ns/devices/phone/log.json': peer,
|
|
||||||
'ns/revs/phone': revisionOf(peer),
|
|
||||||
});
|
|
||||||
final merged = await _tick(remote, InMemorySyncStateStore());
|
|
||||||
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
|
||||||
expect(merged.keys, contains('b'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('skips the download when the peer revision is unchanged', () async {
|
|
||||||
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'ns/devices/phone/log.json': peer,
|
|
||||||
'ns/revs/phone': revisionOf(peer),
|
|
||||||
});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
final first = await _tick(remote, store);
|
|
||||||
remote.reads.clear();
|
|
||||||
|
|
||||||
// The peer's records are already in the local log from tick one, so
|
|
||||||
// re-downloading them is pure waste -- this is the ~700 MB/month that
|
|
||||||
// the revision check removes.
|
|
||||||
await _tick(remote, store, local: first);
|
|
||||||
expect(remote.reads, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('downloads again once the peer publishes a new revision', () async {
|
|
||||||
final peerV1 = _encode(_log('b', 'v1', nodeId: 'node-b'));
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'ns/devices/phone/log.json': peerV1,
|
|
||||||
'ns/revs/phone': revisionOf(peerV1),
|
|
||||||
});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
final first = await _tick(remote, store);
|
|
||||||
remote.reads.clear();
|
|
||||||
|
|
||||||
final peerV2 = _encode({
|
|
||||||
..._decode(peerV1),
|
|
||||||
..._log('c', 'v2', nodeId: 'node-b'),
|
|
||||||
});
|
|
||||||
remote.files['ns/devices/phone/log.json'] = peerV2;
|
|
||||||
remote.files['ns/revs/phone'] = revisionOf(peerV2);
|
|
||||||
|
|
||||||
final second = await _tick(remote, store, local: first);
|
|
||||||
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
|
||||||
expect(second.keys, containsAll(['b', 'c']));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('re-downloads a peer whose push was corrupt', () async {
|
|
||||||
// A failed decode must not be remembered as seen, or the corruption
|
|
||||||
// would be permanent.
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'ns/devices/phone/log.json': 'not json at all',
|
|
||||||
'ns/revs/phone': revisionOf('not json at all'),
|
|
||||||
});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
await _tick(remote, store);
|
|
||||||
remote.reads.clear();
|
|
||||||
|
|
||||||
await _tick(remote, store);
|
|
||||||
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('downloads when the peer has published no revision yet', () async {
|
|
||||||
// A device still running the pre-migration code publishes a log but no
|
|
||||||
// revision; it must not be silently ignored.
|
|
||||||
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
|
||||||
final remote = _FakeRemote({'ns/devices/phone/log.json': peer});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
final merged = await _tick(remote, store);
|
|
||||||
expect(merged.keys, contains('b'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('skips a peer that has nothing pushed yet', () async {
|
|
||||||
final remote = _FakeRemote({'ns/devices/phone/other.txt': 'x'});
|
|
||||||
final merged = await _tick(remote, InMemorySyncStateStore());
|
|
||||||
expect(merged, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('never reads its own device back', () async {
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'ns/devices/pc/log.json': _encode(_log('a', '1')),
|
|
||||||
'ns/revs/pc': 'whatever',
|
|
||||||
});
|
|
||||||
await _tick(remote, InMemorySyncStateStore());
|
|
||||||
expect(remote.reads, isEmpty);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('backends without bulk-map reads', () {
|
|
||||||
test('still sync correctly, just without the saving', () async {
|
|
||||||
// GitHubClient has no BulkMapReader, so revision lookup degrades to
|
|
||||||
// "fetch everything" -- correctness must not depend on the optimisation.
|
|
||||||
final peer = _encode(_log('b', 'from-phone', nodeId: 'node-b'));
|
|
||||||
final remote = _FakeRemoteWithoutBulkRead({
|
|
||||||
'ns/devices/phone/log.json': peer,
|
|
||||||
});
|
|
||||||
final store = InMemorySyncStateStore();
|
|
||||||
final first = await _tick(remote, store);
|
|
||||||
expect(first.keys, contains('b'));
|
|
||||||
|
|
||||||
remote.reads.clear();
|
|
||||||
await _tick(remote, store, local: first);
|
|
||||||
expect(remote.reads, contains('ns/devices/phone/log.json'));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('revision publishing order', () {
|
|
||||||
test('publishes the log before its revision', () async {
|
|
||||||
// Reversed, a peer would cache "seen rev X" against a log it never
|
|
||||||
// received, and skip it forever.
|
|
||||||
final remote = _FakeRemote({});
|
|
||||||
await _tick(remote, InMemorySyncStateStore(), local: _log('a', '1'));
|
|
||||||
expect(
|
|
||||||
remote.writes.indexOf('ns/devices/pc/log.json'),
|
|
||||||
lessThan(remote.writes.indexOf('ns/revs/pc')),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('each device writes only its own revision key', () async {
|
|
||||||
// Per-device keys rather than one shared map: a whole-map write would
|
|
||||||
// erase every other device's entry, after which those peers would look
|
|
||||||
// permanently unchanged and never be fetched again.
|
|
||||||
final remote = _FakeRemote({'ns/revs/phone': 'peer-rev'});
|
|
||||||
await _tick(remote, InMemorySyncStateStore(), local: _log('a', '1'));
|
|
||||||
expect(remote.files['ns/revs/phone'], 'peer-rev');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
group('PersistedSyncStateStore', () {
|
|
||||||
test('round-trips state through persistence', () async {
|
|
||||||
final persistence = _FakePersistence();
|
|
||||||
const state = SyncState(
|
|
||||||
pushedRev: 'rev-local',
|
|
||||||
peerRevs: {'phone': 'rev-phone'},
|
|
||||||
);
|
|
||||||
|
|
||||||
await PersistedSyncStateStore(persistence).save(state);
|
|
||||||
final loaded = await PersistedSyncStateStore(persistence).load();
|
|
||||||
|
|
||||||
// A *separate* store instance reads it back: that is the whole point --
|
|
||||||
// surviving the cold start that an in-memory store does not.
|
|
||||||
expect(loaded.pushedRev, 'rev-local');
|
|
||||||
expect(loaded.peerRevs, {'phone': 'rev-phone'});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('survives a cold start, so peers are not re-downloaded', () async {
|
|
||||||
// The free-tier claim on mobile rests on this: a fresh process must
|
|
||||||
// still skip an unchanged peer.
|
|
||||||
final persistence = _FakePersistence();
|
|
||||||
final remote = _FakeRemote({
|
|
||||||
'ns/devices/phone/log.json': _encode(_log('a', '1')),
|
|
||||||
'ns/revs/phone': revisionOf(_encode(_log('a', '1'))),
|
|
||||||
});
|
|
||||||
|
|
||||||
await _tick(remote, PersistedSyncStateStore(persistence));
|
|
||||||
remote.reads.clear();
|
|
||||||
await _tick(remote, PersistedSyncStateStore(persistence));
|
|
||||||
|
|
||||||
expect(remote.reads, isNot(contains('ns/devices/phone/log.json')));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('reports nothing remembered when absent', () async {
|
|
||||||
final loaded = await PersistedSyncStateStore(_FakePersistence()).load();
|
|
||||||
|
|
||||||
expect(loaded.pushedRev, isNull);
|
|
||||||
expect(loaded.peerRevs, isEmpty);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('degrades to remembering nothing when empty', () async {
|
|
||||||
final loaded = await PersistedSyncStateStore(
|
|
||||||
_FakePersistence(text: ''),
|
|
||||||
).load();
|
|
||||||
|
|
||||||
expect(loaded.pushedRev, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('degrades to remembering nothing when corrupt', () async {
|
|
||||||
// Costs one tick of extra traffic rather than failing the sync.
|
|
||||||
final loaded = await PersistedSyncStateStore(
|
|
||||||
_FakePersistence(text: 'not json{'),
|
|
||||||
).load();
|
|
||||||
|
|
||||||
expect(loaded.pushedRev, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('degrades to remembering nothing when not an object', () async {
|
|
||||||
final loaded = await PersistedSyncStateStore(
|
|
||||||
_FakePersistence(text: '["a list"]'),
|
|
||||||
).load();
|
|
||||||
|
|
||||||
expect(loaded.pushedRev, isNull);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('degrades to remembering nothing when the read throws', () async {
|
|
||||||
// An unreadable file must not fail the tick.
|
|
||||||
final loaded = await PersistedSyncStateStore(
|
|
||||||
_FakePersistence(readThrows: true),
|
|
||||||
).load();
|
|
||||||
|
|
||||||
expect(loaded.pushedRev, isNull);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A [LogPersistence] fake with injectable failure modes.
|
|
||||||
class _FakePersistence implements LogPersistence {
|
|
||||||
_FakePersistence({this.text, this.readThrows = false});
|
|
||||||
|
|
||||||
String? text;
|
|
||||||
final bool readThrows;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<String?> read() async {
|
|
||||||
if (readThrows) throw const FormatException('unreadable');
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future<void> write(String value) async => text = value;
|
|
||||||
}
|
}
|
||||||
|
|||||||
175
crdt_sync_dart/test/sync_skips_test.dart
Normal file
175
crdt_sync_dart/test/sync_skips_test.dart
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart' as http_testing;
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
Hlc _make(int wallTimeMs, {int counter = 0, String nodeId = 'node-a'}) =>
|
||||||
|
Hlc(wallTimeMs: wallTimeMs, counter: counter, nodeId: nodeId);
|
||||||
|
|
||||||
|
String _encode(Log log) =>
|
||||||
|
jsonEncode(log.map((id, record) => MapEntry(id, record.toJson())));
|
||||||
|
|
||||||
|
Log _decode(String text) => (jsonDecode(text) as Map<String, dynamic>).map(
|
||||||
|
(id, data) => MapEntry(id, Record.fromJson(data as Map<String, dynamic>)),
|
||||||
|
);
|
||||||
|
|
||||||
|
http.Response _response(int statusCode, [Object? jsonBody]) =>
|
||||||
|
http.Response(jsonEncode(jsonBody ?? {}), statusCode);
|
||||||
|
|
||||||
|
class _PutCall {
|
||||||
|
_PutCall(this.path, this.body);
|
||||||
|
final String path;
|
||||||
|
final Map<String, dynamic> body;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a [GitHubClient] backed by an in-memory router: GET
|
||||||
|
/// `.../contents/<key>` returns `contentResponses[key]` (404 if absent), the
|
||||||
|
/// bare repo-existence GET always succeeds, and every PUT is recorded into
|
||||||
|
/// [putCalls] and answered with 200.
|
||||||
|
({GitHubClient client, List<_PutCall> putCalls}) _client({
|
||||||
|
Map<String, http.Response> contentResponses = const {},
|
||||||
|
}) {
|
||||||
|
final putCalls = <_PutCall>[];
|
||||||
|
final mock = http_testing.MockClient((request) async {
|
||||||
|
final path = request.url.path;
|
||||||
|
if (!path.contains('/contents/')) {
|
||||||
|
return _response(200);
|
||||||
|
}
|
||||||
|
final key = path.split('/contents/').last;
|
||||||
|
if (request.method == 'PUT') {
|
||||||
|
putCalls.add(
|
||||||
|
_PutCall(key, jsonDecode(request.body) as Map<String, dynamic>),
|
||||||
|
);
|
||||||
|
return _response(200);
|
||||||
|
}
|
||||||
|
return contentResponses[key] ?? _response(404);
|
||||||
|
});
|
||||||
|
final client = GitHubClient(
|
||||||
|
owner: 'kuhyx',
|
||||||
|
repo: 'crdt-sync-demo',
|
||||||
|
token: 'fake-token',
|
||||||
|
httpClient: mock,
|
||||||
|
);
|
||||||
|
return (client: client, putCalls: putCalls);
|
||||||
|
}
|
||||||
|
|
||||||
|
http.Response _directoryOf(List<String> deviceIds) =>
|
||||||
|
_response(200, deviceIds.map((id) => {'name': id, 'type': 'dir'}).toList());
|
||||||
|
|
||||||
|
http.Response _fileContaining(String text) =>
|
||||||
|
_response(200, {'content': base64.encode(utf8.encode(text))});
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('syncLog skips unusable peer files', () {
|
||||||
|
test('skips a device with no pushed file yet', () async {
|
||||||
|
final (:client, :putCalls) = _client(
|
||||||
|
contentResponses: {
|
||||||
|
'devices': _directoryOf(['phone']),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final merged = await syncLog(
|
||||||
|
client: client,
|
||||||
|
deviceId: 'pc',
|
||||||
|
pathPrefix: 'devices',
|
||||||
|
localLog: {},
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(merged, isEmpty);
|
||||||
|
expect(putCalls.single.body['content'], base64.encode(utf8.encode('{}')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('skips a device whose pushed file is corrupt', () async {
|
||||||
|
final (:client, :putCalls) = _client(
|
||||||
|
contentResponses: {
|
||||||
|
'devices': _directoryOf(['phone']),
|
||||||
|
'devices/phone/log.json': _fileContaining('{not valid json'),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final merged = await syncLog(
|
||||||
|
client: client,
|
||||||
|
deviceId: 'pc',
|
||||||
|
pathPrefix: 'devices',
|
||||||
|
localLog: {},
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(merged, isEmpty);
|
||||||
|
expect(putCalls, hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('skips a device whose pushed JSON has the wrong shape', () async {
|
||||||
|
// Valid JSON that isn't a record map (e.g. from an incompatible
|
||||||
|
// writer) must be skipped like corrupt JSON, not crash the whole
|
||||||
|
// sync -- this is what the `on TypeError` catch in `syncLog` is
|
||||||
|
// for, not just JSON syntax errors caught by `FormatException`.
|
||||||
|
final (:client, :putCalls) = _client(
|
||||||
|
contentResponses: {
|
||||||
|
'devices': _directoryOf(['phone']),
|
||||||
|
'devices/phone/log.json': _fileContaining('{"a": 5}'),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final merged = await syncLog(
|
||||||
|
client: client,
|
||||||
|
deviceId: 'pc',
|
||||||
|
pathPrefix: 'devices',
|
||||||
|
localLog: {},
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(merged, isEmpty);
|
||||||
|
expect(putCalls, hasLength(1));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('merges in a remote device\'s entries', () async {
|
||||||
|
final remoteLog = <String, Record>{
|
||||||
|
'b': Record(id: 'b', fields: {'text': ('from phone', _make(100))}),
|
||||||
|
};
|
||||||
|
final (:client, :putCalls) = _client(
|
||||||
|
contentResponses: {
|
||||||
|
'devices': _directoryOf(['phone']),
|
||||||
|
'devices/phone/log.json': _fileContaining(_encode(remoteLog)),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
final merged = await syncLog(
|
||||||
|
client: client,
|
||||||
|
deviceId: 'pc',
|
||||||
|
pathPrefix: 'devices',
|
||||||
|
localLog: {},
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(merged, equals(remoteLog));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('uses a custom filename and commit message', () async {
|
||||||
|
final (:client, :putCalls) = _client(
|
||||||
|
contentResponses: {'devices': _directoryOf([])},
|
||||||
|
);
|
||||||
|
|
||||||
|
await syncLog(
|
||||||
|
client: client,
|
||||||
|
deviceId: 'pc',
|
||||||
|
pathPrefix: 'devices',
|
||||||
|
localLog: {},
|
||||||
|
encode: _encode,
|
||||||
|
decode: _decode,
|
||||||
|
filename: 'notes.json',
|
||||||
|
commitMessage: 'custom message',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(putCalls.single.path, 'devices/pc/notes.json');
|
||||||
|
expect(putCalls.single.body['message'], 'custom message');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -156,114 +156,5 @@ void main() {
|
|||||||
|
|
||||||
expect(merged.keys, contains('stale'));
|
expect(merged.keys, contains('stale'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('skips a device with no pushed file yet', () async {
|
|
||||||
final (:client, :putCalls) = _client(
|
|
||||||
contentResponses: {
|
|
||||||
'devices': _directoryOf(['phone']),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
final merged = await syncLog(
|
|
||||||
client: client,
|
|
||||||
deviceId: 'pc',
|
|
||||||
pathPrefix: 'devices',
|
|
||||||
localLog: {},
|
|
||||||
encode: _encode,
|
|
||||||
decode: _decode,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(merged, isEmpty);
|
|
||||||
expect(putCalls.single.body['content'], base64.encode(utf8.encode('{}')));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('skips a device whose pushed file is corrupt', () async {
|
|
||||||
final (:client, :putCalls) = _client(
|
|
||||||
contentResponses: {
|
|
||||||
'devices': _directoryOf(['phone']),
|
|
||||||
'devices/phone/log.json': _fileContaining('{not valid json'),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
final merged = await syncLog(
|
|
||||||
client: client,
|
|
||||||
deviceId: 'pc',
|
|
||||||
pathPrefix: 'devices',
|
|
||||||
localLog: {},
|
|
||||||
encode: _encode,
|
|
||||||
decode: _decode,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(merged, isEmpty);
|
|
||||||
expect(putCalls, hasLength(1));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('skips a device whose pushed JSON has the wrong shape', () async {
|
|
||||||
// Valid JSON that isn't a record map (e.g. from an incompatible
|
|
||||||
// writer) must be skipped like corrupt JSON, not crash the whole
|
|
||||||
// sync -- this is what the `on TypeError` catch in `syncLog` is
|
|
||||||
// for, not just JSON syntax errors caught by `FormatException`.
|
|
||||||
final (:client, :putCalls) = _client(
|
|
||||||
contentResponses: {
|
|
||||||
'devices': _directoryOf(['phone']),
|
|
||||||
'devices/phone/log.json': _fileContaining('{"a": 5}'),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
final merged = await syncLog(
|
|
||||||
client: client,
|
|
||||||
deviceId: 'pc',
|
|
||||||
pathPrefix: 'devices',
|
|
||||||
localLog: {},
|
|
||||||
encode: _encode,
|
|
||||||
decode: _decode,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(merged, isEmpty);
|
|
||||||
expect(putCalls, hasLength(1));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('merges in a remote device\'s entries', () async {
|
|
||||||
final remoteLog = <String, Record>{
|
|
||||||
'b': Record(id: 'b', fields: {'text': ('from phone', _make(100))}),
|
|
||||||
};
|
|
||||||
final (:client, :putCalls) = _client(
|
|
||||||
contentResponses: {
|
|
||||||
'devices': _directoryOf(['phone']),
|
|
||||||
'devices/phone/log.json': _fileContaining(_encode(remoteLog)),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
final merged = await syncLog(
|
|
||||||
client: client,
|
|
||||||
deviceId: 'pc',
|
|
||||||
pathPrefix: 'devices',
|
|
||||||
localLog: {},
|
|
||||||
encode: _encode,
|
|
||||||
decode: _decode,
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(merged, equals(remoteLog));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('uses a custom filename and commit message', () async {
|
|
||||||
final (:client, :putCalls) = _client(
|
|
||||||
contentResponses: {'devices': _directoryOf([])},
|
|
||||||
);
|
|
||||||
|
|
||||||
await syncLog(
|
|
||||||
client: client,
|
|
||||||
deviceId: 'pc',
|
|
||||||
pathPrefix: 'devices',
|
|
||||||
localLog: {},
|
|
||||||
encode: _encode,
|
|
||||||
decode: _decode,
|
|
||||||
filename: 'notes.json',
|
|
||||||
commitMessage: 'custom message',
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(putCalls.single.path, 'devices/pc/notes.json');
|
|
||||||
expect(putCalls.single.body['message'], 'custom message');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,208 +0,0 @@
|
|||||||
==============================================================================
|
|
||||||
TOTALS: 4045 readable files (code 2700, prose 580, data 765)
|
|
||||||
code lines total: 471,749
|
|
||||||
==============================================================================
|
|
||||||
|
|
||||||
### LONGEST FILES OVERALL (any readable kind), top 30
|
|
||||||
|
|
||||||
lines kind lang path
|
|
||||||
------ ----- ---------- ---------------------------------------------------------------------------------------------------------
|
|
||||||
174800 prose Text testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/pacman/words.txt
|
|
||||||
2053 prose Markdown testsAndMisc/docs/superpowers/plans/2026-05-01-phone-focus-recovery.md
|
|
||||||
1838 prose Markdown todo/BACKLOG.md
|
|
||||||
1734 code Shell testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/setup_midnight_shutdown.sh
|
|
||||||
1570 data JSON testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/leechblock_defaults.json
|
|
||||||
1475 data JSON macro-cam/assets/testdata/meals.json
|
|
||||||
1437 code TypeScript konbini-67/src/core/shift.test.ts
|
|
||||||
1417 code Dart epopeja_karta/lib/l10n/generated/app_localizations.dart
|
|
||||||
1383 code Shell testsAndMisc/linux_configuration/scripts/single_use/features/setup_nextcloud_raspberry.sh
|
|
||||||
1337 code Shell testsAndMisc/linux_configuration/scripts/periodic_background/check_and_enable_services.sh
|
|
||||||
1325 code Dart home_inventory/test/data/item_repository_test.dart
|
|
||||||
1276 code Shell testsAndMisc/linux_configuration/scripts/single_use/features/raspberry_pi_nextcloud.sh
|
|
||||||
1274 data JSON macro-cam/assets/testdata/model_areas.json
|
|
||||||
1120 code Dart home_inventory/lib/data/item_repository.dart
|
|
||||||
1116 code Shell testsAndMisc/linux_configuration/scripts/single_use/utils/root_bl9000.sh
|
|
||||||
1101 prose Markdown diet-guard/CLAUDE.md
|
|
||||||
1097 code TypeScript konbini-67/src/core/shift.ts
|
|
||||||
1091 data JSON macro-cam/assets/testdata/claude_meal_estimates.json
|
|
||||||
1091 code Shell testsAndMisc/phone_focus_mode/focus_ctl.sh
|
|
||||||
1089 code Dart dufs-cloud/app/test/browser_screen_test.dart
|
|
||||||
1076 code Python steam-backlog-enforcer/steam_backlog_enforcer/main.py
|
|
||||||
1072 code Python steam-backlog-enforcer/steam_backlog_enforcer/tests/test_stats.py
|
|
||||||
1052 code Dart diet-guard/app/lib/screens/history_screen.dart
|
|
||||||
1047 code TypeScript dufs-cloud/web/src/components/gallery.test.tsx
|
|
||||||
1042 code Python steam-backlog-enforcer/steam_backlog_enforcer/tests/test_total_block.py
|
|
||||||
1017 code Dart diet-guard/app/test/screens/history_screen_test.dart
|
|
||||||
1017 code Shell testsAndMisc/linux_configuration/scripts/single_use/utils/generate_study_materials.sh
|
|
||||||
942 code Shell testsAndMisc/linux_configuration/scripts/single_use/utils/lookup_docs.sh
|
|
||||||
929 code Shell testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/pacman/pacman_wrapper.sh
|
|
||||||
925 prose Markdown todo/CLAUDE.md
|
|
||||||
|
|
||||||
### LONGEST CODE FILES, top 30
|
|
||||||
|
|
||||||
lines lang commits/yr path
|
|
||||||
----- ---------- ---------- ---------------------------------------------------------------------------------------------------------
|
|
||||||
1734 Shell 9 testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/setup_midnight_shutdown.sh
|
|
||||||
1437 TypeScript 12 konbini-67/src/core/shift.test.ts
|
|
||||||
1417 Dart 2 epopeja_karta/lib/l10n/generated/app_localizations.dart
|
|
||||||
1383 Shell 1 testsAndMisc/linux_configuration/scripts/single_use/features/setup_nextcloud_raspberry.sh
|
|
||||||
1337 Shell 8 testsAndMisc/linux_configuration/scripts/periodic_background/check_and_enable_services.sh
|
|
||||||
1325 Dart 6 home_inventory/test/data/item_repository_test.dart
|
|
||||||
1276 Shell 1 testsAndMisc/linux_configuration/scripts/single_use/features/raspberry_pi_nextcloud.sh
|
|
||||||
1120 Dart 7 home_inventory/lib/data/item_repository.dart
|
|
||||||
1116 Shell 1 testsAndMisc/linux_configuration/scripts/single_use/utils/root_bl9000.sh
|
|
||||||
1097 TypeScript 13 konbini-67/src/core/shift.ts
|
|
||||||
1091 Shell 9 testsAndMisc/phone_focus_mode/focus_ctl.sh
|
|
||||||
1089 Dart 12 dufs-cloud/app/test/browser_screen_test.dart
|
|
||||||
1076 Python 26 steam-backlog-enforcer/steam_backlog_enforcer/main.py
|
|
||||||
1072 Python 4 steam-backlog-enforcer/steam_backlog_enforcer/tests/test_stats.py
|
|
||||||
1052 Dart 6 diet-guard/app/lib/screens/history_screen.dart
|
|
||||||
1047 TypeScript 9 dufs-cloud/web/src/components/gallery.test.tsx
|
|
||||||
1042 Python 2 steam-backlog-enforcer/steam_backlog_enforcer/tests/test_total_block.py
|
|
||||||
1017 Dart 6 diet-guard/app/test/screens/history_screen_test.dart
|
|
||||||
1017 Shell 2 testsAndMisc/linux_configuration/scripts/single_use/utils/generate_study_materials.sh
|
|
||||||
942 Shell 2 testsAndMisc/linux_configuration/scripts/single_use/utils/lookup_docs.sh
|
|
||||||
929 Shell 6 testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/pacman/pacman_wrapper.sh
|
|
||||||
918 Shell 5 testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/setup_night_lockdown.sh
|
|
||||||
912 Shell 5 testsAndMisc/linux_configuration/scripts/periodic_background/hosts/install.sh
|
|
||||||
912 Shell 3 testsAndMisc/linux_configuration/scripts/single_use/features/setup_searxng.sh
|
|
||||||
909 Dart 15 dufs-cloud/app/lib/screens/browser_screen.dart
|
|
||||||
897 Dart 8 screen-locker/stronglift_replacement/workout_app/lib/screens/history_screen.dart
|
|
||||||
896 Dart 2 epopeja_karta/test/widget_test.dart
|
|
||||||
870 Shell 2 testsAndMisc/linux_configuration/scripts/single_use/utils/update_android_hosts.sh
|
|
||||||
869 Shell 3 testsAndMisc/linux_configuration/scripts/single_use/utils/analyze_repo.sh
|
|
||||||
850 Python 3 europe-county-map/scripts/extract_ck3_counties.py
|
|
||||||
|
|
||||||
### LONGEST PROSE (md/txt/rst/tex), top 30
|
|
||||||
|
|
||||||
lines lang path
|
|
||||||
------ -------- -----------------------------------------------------------------------------------------------
|
|
||||||
174800 Text testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/pacman/words.txt
|
|
||||||
2053 Markdown testsAndMisc/docs/superpowers/plans/2026-05-01-phone-focus-recovery.md
|
|
||||||
1838 Markdown todo/BACKLOG.md
|
|
||||||
1101 Markdown diet-guard/CLAUDE.md
|
|
||||||
925 Markdown todo/CLAUDE.md
|
|
||||||
761 Markdown testsAndMisc/linux_configuration/docs/SECURITY_HARDENING_ANALYSIS.md
|
|
||||||
709 Markdown testsAndMisc/docs/superpowers/specs/2026-05-01-phone-focus-recovery-design.md
|
|
||||||
648 Markdown .claude/plans/i-dont-want-to-resilient-teapot.md
|
|
||||||
621 Markdown konbini-67/SPEC-physicality.md
|
|
||||||
592 Markdown .claude/plans/i-added-google-anonymous-elegant-stallman.md
|
|
||||||
578 Markdown .claude/plans/i-am-trying-to-starry-emerson.md
|
|
||||||
564 Markdown .claude/plans/inventory-app-improvements-1-cheeky-mountain.md
|
|
||||||
548 LaTeX CV/magisterskie/cv.tex
|
|
||||||
528 Markdown diet-guard/app/.agents/skills/dart-migrate-to-checks-package/SKILL.md
|
|
||||||
528 Markdown todo/.agents/skills/dart-migrate-to-checks-package/SKILL.md
|
|
||||||
521 Markdown .claude/plans/build-prompt-melodic-mango.md
|
|
||||||
478 Markdown .claude/plans/abundant-cooking-hippo.md
|
|
||||||
461 Markdown .claude/plans/where-the-guard-lives-fluffy-shell.md
|
|
||||||
459 Markdown .claude/plans/changes-to-diet-guard-splendid-spindle.md
|
|
||||||
440 Markdown .claude/plans/japanese-convenience-store-clerk-witty-cocoa.md
|
|
||||||
421 Markdown .claude/plans/all-repos-that-build-cozy-pike.md
|
|
||||||
419 Markdown diet-guard/app/.agents/skills/dart-setup-ffi-assets/SKILL.md
|
|
||||||
419 Markdown todo/.agents/skills/dart-setup-ffi-assets/SKILL.md
|
|
||||||
406 Markdown .claude/plans/grind-leetcode-guard-velvet-engelbart.md
|
|
||||||
402 Markdown .claude/skills/wiki-to-mcp-kb/references/pitfalls.md
|
|
||||||
402 Markdown .claude/plans/inventory-management-for-spicy-cray.md
|
|
||||||
390 Markdown .claude/plans/read-and-fix-incident-2026-08-05-no-way-wiggly-karp.md
|
|
||||||
386 Markdown .claude/plans/take-https-github-com-punkpeye-awesome-m-gentle-swing.md
|
|
||||||
384 Markdown testsAndMisc/.claude/skills/test-driven-development/SKILL.md
|
|
||||||
384 Markdown testsAndMisc/.github/skills/test-driven-development/SKILL.md
|
|
||||||
|
|
||||||
### TOP REFACTOR ROI (lines x commits-last-year), top 30
|
|
||||||
|
|
||||||
roi lines commits/yr lang path
|
|
||||||
----- ----- ---------- ---------- ---------------------------------------------------------------------------------------------------------
|
|
||||||
27976 1076 26 Python steam-backlog-enforcer/steam_backlog_enforcer/main.py
|
|
||||||
22796 556 41 Shell testsAndMisc/phone_focus_mode/config.sh
|
|
||||||
18720 390 48 Python screen-locker/screen_locker/screen_lock.py
|
|
||||||
17244 1437 12 TypeScript konbini-67/src/core/shift.test.ts
|
|
||||||
15606 1734 9 Shell testsAndMisc/linux_configuration/scripts/periodic_background/digital_wellbeing/setup_midnight_shutdown.sh
|
|
||||||
14261 1097 13 TypeScript konbini-67/src/core/shift.ts
|
|
||||||
14041 739 19 Dart todo/lib/ui/capture_screen.dart
|
|
||||||
13635 909 15 Dart dufs-cloud/app/lib/screens/browser_screen.dart
|
|
||||||
13068 1089 12 Dart dufs-cloud/app/test/browser_screen_test.dart
|
|
||||||
12495 833 15 Shell testsAndMisc/phone_focus_mode/deploy.sh
|
|
||||||
11220 660 17 Dart todo/test/capture_screen_test.dart
|
|
||||||
10696 1337 8 Shell testsAndMisc/linux_configuration/scripts/periodic_background/check_and_enable_services.sh
|
|
||||||
9954 553 18 Python steam-backlog-enforcer/steam_backlog_enforcer/game_install.py
|
|
||||||
9819 1091 9 Shell testsAndMisc/phone_focus_mode/focus_ctl.sh
|
|
||||||
9423 1047 9 TypeScript dufs-cloud/web/src/components/gallery.test.tsx
|
|
||||||
9252 771 12 Dart screen-locker/stronglift_replacement/workout_app/lib/screens/settings_screen.dart
|
|
||||||
7950 1325 6 Dart home_inventory/test/data/item_repository_test.dart
|
|
||||||
7840 1120 7 Dart home_inventory/lib/data/item_repository.dart
|
|
||||||
7215 555 13 Python steam-backlog-enforcer/steam_backlog_enforcer/library_hider.py
|
|
||||||
7176 897 8 Dart screen-locker/stronglift_replacement/workout_app/lib/screens/history_screen.dart
|
|
||||||
7170 478 15 Python wake-alarm/wake_alarm/_alarm.py
|
|
||||||
7020 702 10 Dart todo/lib/ui/note_editor.dart
|
|
||||||
6994 538 13 TypeScript konbini-67/src/app.test.tsx
|
|
||||||
6773 521 13 Python steam-backlog-enforcer/steam_backlog_enforcer/scanning.py
|
|
||||||
6768 752 9 Dart screen-locker/stronglift_replacement/workout_app/lib/services/storage_service.dart
|
|
||||||
6699 319 21 Python screen-locker/screen_locker/tests/conftest.py
|
|
||||||
6612 551 12 CSS europe-county-map/src/App.css
|
|
||||||
6600 440 15 Dart diet-guard/app/lib/screens/log_meal_screen.dart
|
|
||||||
6516 543 12 Shell testsAndMisc/phone_focus_mode/focus_daemon.sh
|
|
||||||
6312 1052 6 Dart diet-guard/app/lib/screens/history_screen.dart
|
|
||||||
|
|
||||||
### DISTRIBUTION BY LANGUAGE (code only)
|
|
||||||
|
|
||||||
lang n median mean p75 p90 p95 p99 max
|
|
||||||
---------- --- ------ ----- --- --- --- ---- ----
|
|
||||||
Python 895 179 206.6 294 399 466 652 1076
|
|
||||||
Dart 758 105 160.5 203 351 480 897 1417
|
|
||||||
TypeScript 459 85 125.4 162 266 361 698 1437
|
|
||||||
Shell 363 120 201.1 243 457 663 1276 1734
|
|
||||||
Kotlin 68 26 71.0 69 223 277 564 564
|
|
||||||
HTML 60 402 333.8 548 716 738 843 843
|
|
||||||
C 22 21 70.5 88 229 249 478 478
|
|
||||||
CSS 19 169 261.1 535 768 774 774 774
|
|
||||||
Swift 17 12 12 15 16 16 16 16
|
|
||||||
C++ 16 70 97.8 151 288 288 288 288
|
|
||||||
JavaScript 15 47 65.7 97 134 179 179 179
|
|
||||||
Java 8 40 69.2 101 247 247 247 247
|
|
||||||
|
|
||||||
### DISTRIBUTION BY PROJECT (code only, >=10 files)
|
|
||||||
|
|
||||||
project n median MEAN p90 max total
|
|
||||||
---------------------- --- ------ ----- --- ---- -------
|
|
||||||
steam-backlog-enforcer 114 269 301.3 588 1076 34,352
|
|
||||||
epopeja_karta 37 192 289.4 759 1417 10,708
|
|
||||||
kuhytrack 12 215 240 392 652 2,880
|
|
||||||
screen-locker 211 169 209.8 390 897 44,261
|
|
||||||
steam-game-installer 18 144 198.2 473 765 3,567
|
|
||||||
utils 127 167 193.3 412 525 24,552
|
|
||||||
mcp-servers 27 136 189.1 467 487 5,106
|
|
||||||
testsAndMisc 745 127 187.7 421 1734 139,813
|
|
||||||
europe-county-map 75 138 181.8 374 850 13,637
|
|
||||||
manga_translate 40 144 181.2 417 720 7,250
|
|
||||||
leetcode-guard 117 181 180.4 296 400 21,111
|
|
||||||
wake-alarm 68 150 178.2 405 764 12,118
|
|
||||||
diet-guard 217 128 175.6 379 1052 38,101
|
|
||||||
yay-mcp 16 109 168.3 478 554 2,693
|
|
||||||
todo 99 109 165.9 405 739 16,421
|
|
||||||
i3wm-mcp 12 130 165.8 275 615 1,989
|
|
||||||
home_inventory 113 96 152.6 328 1325 17,249
|
|
||||||
konbini-67 73 96 149.6 209 1437 10,919
|
|
||||||
dufs-cloud 126 99 146.8 257 1089 18,497
|
|
||||||
hotline3d 38 82 136.4 353 736 5,184
|
|
||||||
macro-cam 55 103 133.5 279 574 7,341
|
|
||||||
wiki-kb 31 95 121.3 215 463 3,760
|
|
||||||
atomichabits 15 88 109.8 188 251 1,647
|
|
||||||
octoforge 76 80 104.3 209 510 7,929
|
|
||||||
kuhylog 92 89 94.9 166 301 8,727
|
|
||||||
.claude 17 64 74.5 177 311 1,267
|
|
||||||
iron-and-anvil 40 55 71.7 159 220 2,869
|
|
||||||
habit_stack 54 42 71.7 169 288 3,870
|
|
||||||
personal-website 25 48 65.3 165 303 1,633
|
|
||||||
|
|
||||||
### COUNT OVER CANDIDATE THRESHOLDS (code only)
|
|
||||||
|
|
||||||
threshold files over % of code of those, edited last yr
|
|
||||||
--------- ---------- --------- ------------------------
|
|
||||||
300 474 17.6% 452
|
|
||||||
400 243 9.0% 229
|
|
||||||
500 118 4.4% 114
|
|
||||||
600 82 3.0% 80
|
|
||||||
800 33 1.2% 33
|
|
||||||
1000 19 0.7% 19
|
|
||||||
1500 1 0.0% 1
|
|
||||||
2000 0 0.0% 0
|
|
||||||
201
file_length/_tables.py
Normal file
201
file_length/_tables.py
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
"""Exemption tables for the 250-line file-length cap.
|
||||||
|
|
||||||
|
The data half: which extensions are capped, and which paths are generated,
|
||||||
|
vendored, third-party or session artifacts. :mod:`file_length.exemptions`
|
||||||
|
holds the rules that read these, and :mod:`file_length.config` re-exports
|
||||||
|
both as the public surface.
|
||||||
|
|
||||||
|
Duplicating these lists in shell is what lets a gate and a survey silently
|
||||||
|
disagree, so they live here once.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
#: Hard cap. Files above this fail the gate. Code and prose alike.
|
||||||
|
MAX_LINES = 250
|
||||||
|
|
||||||
|
#: Extensions the cap applies to: real programming languages plus prose.
|
||||||
|
#: Markup (.html/.css/.scss) is deliberately absent -- templates split into
|
||||||
|
#: partials, not functions, so a line cap does not express anything useful.
|
||||||
|
CAPPED_EXTENSIONS = {
|
||||||
|
# code
|
||||||
|
".py",
|
||||||
|
".dart",
|
||||||
|
".ts",
|
||||||
|
".tsx",
|
||||||
|
".js",
|
||||||
|
".jsx",
|
||||||
|
".sh",
|
||||||
|
".bash",
|
||||||
|
".zsh",
|
||||||
|
".c",
|
||||||
|
".h",
|
||||||
|
".cpp",
|
||||||
|
".cc",
|
||||||
|
".hpp",
|
||||||
|
".go",
|
||||||
|
".rs",
|
||||||
|
".java",
|
||||||
|
".kt",
|
||||||
|
".kts",
|
||||||
|
".swift",
|
||||||
|
".rb",
|
||||||
|
".lua",
|
||||||
|
".sql",
|
||||||
|
".vue",
|
||||||
|
".cs",
|
||||||
|
".php",
|
||||||
|
# prose
|
||||||
|
".md",
|
||||||
|
".markdown",
|
||||||
|
".txt",
|
||||||
|
".rst",
|
||||||
|
".tex",
|
||||||
|
".org",
|
||||||
|
}
|
||||||
|
|
||||||
|
#: Generated files: regenerated by a tool, so splitting them is meaningless
|
||||||
|
#: (the tool would just rewrite the original next run).
|
||||||
|
GENERATED_PATTERN = re.compile(
|
||||||
|
r"\.g\.dart$"
|
||||||
|
r"|\.freezed\.dart$"
|
||||||
|
r"|\.gr\.dart$"
|
||||||
|
r"|\.config\.dart$"
|
||||||
|
r"|\.mocks\.dart$"
|
||||||
|
r"|\.min\.(js|css)$"
|
||||||
|
r"|\.pb\.(go|py)$"
|
||||||
|
r"|_pb2(_grpc)?\.py$"
|
||||||
|
r"|\.generated\.ts$"
|
||||||
|
r"|\.d\.ts$"
|
||||||
|
r"|/l10n/generated/"
|
||||||
|
r"|/generated/"
|
||||||
|
)
|
||||||
|
|
||||||
|
#: A marker in the first few lines also marks a file generated. Covers tools
|
||||||
|
#: that do not use a distinguishing extension.
|
||||||
|
GENERATED_MARKERS = (
|
||||||
|
"GENERATED CODE - DO NOT MODIFY",
|
||||||
|
"@generated",
|
||||||
|
"DO NOT EDIT",
|
||||||
|
"Autogenerated",
|
||||||
|
"AUTOGENERATED",
|
||||||
|
"generated by",
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Directory names never descended into: dependencies, build output, caches.
|
||||||
|
EXCLUDED_DIRS = frozenset(
|
||||||
|
{
|
||||||
|
".git",
|
||||||
|
"node_modules",
|
||||||
|
".dart_tool",
|
||||||
|
"build",
|
||||||
|
".venv",
|
||||||
|
"venv",
|
||||||
|
"env",
|
||||||
|
"site-packages",
|
||||||
|
"target",
|
||||||
|
"ephemeral",
|
||||||
|
"__pycache__",
|
||||||
|
".mypy_cache",
|
||||||
|
".pytest_cache",
|
||||||
|
".ruff_cache",
|
||||||
|
"dist",
|
||||||
|
".next",
|
||||||
|
"vendor",
|
||||||
|
"third_party",
|
||||||
|
"Pods",
|
||||||
|
".gradle",
|
||||||
|
".idea",
|
||||||
|
".cxx",
|
||||||
|
"coverage",
|
||||||
|
"htmlcov",
|
||||||
|
".tox",
|
||||||
|
"Library",
|
||||||
|
"Temp",
|
||||||
|
"obj",
|
||||||
|
".terraform",
|
||||||
|
".fvm",
|
||||||
|
".angular",
|
||||||
|
".cache",
|
||||||
|
".svelte-kit",
|
||||||
|
"migrations",
|
||||||
|
".ci-mirror-venv",
|
||||||
|
".hippo",
|
||||||
|
".build-deps",
|
||||||
|
# Where CI checks out the shared gate itself (kuhyx/utils). Without
|
||||||
|
# this, a repo's lint job fails on utils' own long files -- a gate
|
||||||
|
# that fails for reasons the repo being gated cannot fix.
|
||||||
|
".utils",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Third-party content living *inside* a repo you own, keyed by repo dir name.
|
||||||
|
#: Verified by git remote / vendor manifest, not guessed.
|
||||||
|
VENDORED_SUBPATHS = {
|
||||||
|
"mcp-servers": ("servers",),
|
||||||
|
"dufs-cloud": ("app/assets/pdfjs", "web/assets/pdfjs"),
|
||||||
|
".claude": (
|
||||||
|
"projects",
|
||||||
|
"shell-snapshots",
|
||||||
|
"cache",
|
||||||
|
"backups",
|
||||||
|
"todos",
|
||||||
|
"statsig",
|
||||||
|
"history",
|
||||||
|
"chrome",
|
||||||
|
"downloads",
|
||||||
|
"plugins",
|
||||||
|
"ide",
|
||||||
|
),
|
||||||
|
# Agent skill bundles vendored from Anthropic (todo: commit f91311f).
|
||||||
|
# A SKILL.md is a fixed-name file with frontmatter; detail belongs in a
|
||||||
|
# sibling references/ dir, so splitting one into SKILL.part2.md would
|
||||||
|
# break the format rather than improve readability.
|
||||||
|
"todo": (".agents/skills",),
|
||||||
|
}
|
||||||
|
|
||||||
|
#: Directory names that mark a vendored agent-skill tree wherever they appear.
|
||||||
|
#: Keyed by name rather than repo because these bundles get dropped into any
|
||||||
|
#: repo that wants them, not just the one they were first seen in.
|
||||||
|
VENDORED_ANYWHERE = ("/.agents/skills/", "/.claude/skills/")
|
||||||
|
|
||||||
|
#: Frozen records of past agent sessions: an implementation plan or an
|
||||||
|
#: append-only session log describes what was done at one moment. Splitting one
|
||||||
|
#: rewrites a historical record for no reading benefit -- nobody navigates them,
|
||||||
|
#: they are read whole or not at all. Same category as generated files.
|
||||||
|
#:
|
||||||
|
#: Deliberately NOT the whole of docs/superpowers/: `specs/` and `contracts/`
|
||||||
|
#: stay capped, because those are living documents that get re-read and edited.
|
||||||
|
SESSION_ARTIFACTS_ANYWHERE = (
|
||||||
|
"/docs/superpowers/plans/",
|
||||||
|
"/docs/superpowers/sessions/",
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Whole repos under ~ that are third-party clones, not kuhy's work.
|
||||||
|
#: Verified 2026-08-14 by `git remote get-url origin` + commit authors.
|
||||||
|
THIRD_PARTY_REPOS = frozenset(
|
||||||
|
{
|
||||||
|
"StringTheory", # github.com/AnthonySf/TheStringTheory
|
||||||
|
"reaper-mcp", # github.com/TwelveTake-Studios/reaper-mcp
|
||||||
|
"freesound-mcp", # github.com/timjrobinson/FreesoundMCPServer
|
||||||
|
"llama_cpp_dart_local", # generated FFI bindings
|
||||||
|
"aseprite-mcp",
|
||||||
|
"Mapperatorinator", # github.com/OliBomby/Mapperatorinator
|
||||||
|
"aur",
|
||||||
|
"build-your-own-x",
|
||||||
|
"build_your_x",
|
||||||
|
"byox-ladder",
|
||||||
|
"warriorjs",
|
||||||
|
"untools",
|
||||||
|
"awesome-mcp-explorer",
|
||||||
|
"runnerup",
|
||||||
|
"depotdownloader",
|
||||||
|
"actions-runner",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
#: A `.txt` whose mean line is shorter than this is data (a wordlist, a
|
||||||
|
#: coordinate dump), not prose, so the cap does not apply.
|
||||||
|
DATA_TXT_MAX_MEAN_LINE = 25
|
||||||
File diff suppressed because it is too large
Load Diff
@ -1,252 +1,45 @@
|
|||||||
"""Shared configuration for the 250-line file-length cap.
|
"""Shared configuration for the 250-line file-length cap.
|
||||||
|
|
||||||
Single source of truth for the cap and its exemptions, imported by both the
|
Single source of truth for the cap and its exemptions, imported by both the
|
||||||
pre-commit gate (`check.py`) and the survey. Duplicating these lists in shell
|
pre-commit gate (`check.py`) and the survey. This module is the public
|
||||||
is what lets a gate and a survey silently disagree.
|
surface: :mod:`file_length._tables` holds the data, and
|
||||||
|
:mod:`file_length.exemptions` the rules that read it.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from file_length._tables import (
|
||||||
import re
|
CAPPED_EXTENSIONS,
|
||||||
|
DATA_TXT_MAX_MEAN_LINE,
|
||||||
#: Hard cap. Files above this fail the gate. Code and prose alike.
|
EXCLUDED_DIRS,
|
||||||
MAX_LINES = 250
|
GENERATED_MARKERS,
|
||||||
|
GENERATED_PATTERN,
|
||||||
#: Extensions the cap applies to: real programming languages plus prose.
|
MAX_LINES,
|
||||||
#: Markup (.html/.css/.scss) is deliberately absent -- templates split into
|
SESSION_ARTIFACTS_ANYWHERE,
|
||||||
#: partials, not functions, so a line cap does not express anything useful.
|
THIRD_PARTY_REPOS,
|
||||||
CAPPED_EXTENSIONS = {
|
VENDORED_ANYWHERE,
|
||||||
# code
|
VENDORED_SUBPATHS,
|
||||||
".py",
|
)
|
||||||
".dart",
|
from file_length.exemptions import (
|
||||||
".ts",
|
is_data_text,
|
||||||
".tsx",
|
is_generated,
|
||||||
".js",
|
is_session_artifact,
|
||||||
".jsx",
|
is_vendored,
|
||||||
".sh",
|
|
||||||
".bash",
|
|
||||||
".zsh",
|
|
||||||
".c",
|
|
||||||
".h",
|
|
||||||
".cpp",
|
|
||||||
".cc",
|
|
||||||
".hpp",
|
|
||||||
".go",
|
|
||||||
".rs",
|
|
||||||
".java",
|
|
||||||
".kt",
|
|
||||||
".kts",
|
|
||||||
".swift",
|
|
||||||
".rb",
|
|
||||||
".lua",
|
|
||||||
".sql",
|
|
||||||
".vue",
|
|
||||||
".cs",
|
|
||||||
".php",
|
|
||||||
# prose
|
|
||||||
".md",
|
|
||||||
".markdown",
|
|
||||||
".txt",
|
|
||||||
".rst",
|
|
||||||
".tex",
|
|
||||||
".org",
|
|
||||||
}
|
|
||||||
|
|
||||||
#: Generated files: regenerated by a tool, so splitting them is meaningless
|
|
||||||
#: (the tool would just rewrite the original next run).
|
|
||||||
GENERATED_PATTERN = re.compile(
|
|
||||||
r"\.g\.dart$"
|
|
||||||
r"|\.freezed\.dart$"
|
|
||||||
r"|\.gr\.dart$"
|
|
||||||
r"|\.config\.dart$"
|
|
||||||
r"|\.mocks\.dart$"
|
|
||||||
r"|\.min\.(js|css)$"
|
|
||||||
r"|\.pb\.(go|py)$"
|
|
||||||
r"|_pb2(_grpc)?\.py$"
|
|
||||||
r"|\.generated\.ts$"
|
|
||||||
r"|\.d\.ts$"
|
|
||||||
r"|/l10n/generated/"
|
|
||||||
r"|/generated/"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
#: A marker in the first few lines also marks a file generated. Covers tools
|
__all__ = [
|
||||||
#: that do not use a distinguishing extension.
|
"CAPPED_EXTENSIONS",
|
||||||
GENERATED_MARKERS = (
|
"DATA_TXT_MAX_MEAN_LINE",
|
||||||
"GENERATED CODE - DO NOT MODIFY",
|
"EXCLUDED_DIRS",
|
||||||
"@generated",
|
"GENERATED_MARKERS",
|
||||||
"DO NOT EDIT",
|
"GENERATED_PATTERN",
|
||||||
"Autogenerated",
|
"MAX_LINES",
|
||||||
"AUTOGENERATED",
|
"SESSION_ARTIFACTS_ANYWHERE",
|
||||||
"generated by",
|
"THIRD_PARTY_REPOS",
|
||||||
)
|
"VENDORED_ANYWHERE",
|
||||||
|
"VENDORED_SUBPATHS",
|
||||||
#: Directory names never descended into: dependencies, build output, caches.
|
"is_data_text",
|
||||||
EXCLUDED_DIRS = frozenset(
|
"is_generated",
|
||||||
{
|
"is_session_artifact",
|
||||||
".git",
|
"is_vendored",
|
||||||
"node_modules",
|
]
|
||||||
".dart_tool",
|
|
||||||
"build",
|
|
||||||
".venv",
|
|
||||||
"venv",
|
|
||||||
"env",
|
|
||||||
"site-packages",
|
|
||||||
"target",
|
|
||||||
"ephemeral",
|
|
||||||
"__pycache__",
|
|
||||||
".mypy_cache",
|
|
||||||
".pytest_cache",
|
|
||||||
".ruff_cache",
|
|
||||||
"dist",
|
|
||||||
".next",
|
|
||||||
"vendor",
|
|
||||||
"third_party",
|
|
||||||
"Pods",
|
|
||||||
".gradle",
|
|
||||||
".idea",
|
|
||||||
".cxx",
|
|
||||||
"coverage",
|
|
||||||
"htmlcov",
|
|
||||||
".tox",
|
|
||||||
"Library",
|
|
||||||
"Temp",
|
|
||||||
"obj",
|
|
||||||
".terraform",
|
|
||||||
".fvm",
|
|
||||||
".angular",
|
|
||||||
".cache",
|
|
||||||
".svelte-kit",
|
|
||||||
"migrations",
|
|
||||||
".ci-mirror-venv",
|
|
||||||
".hippo",
|
|
||||||
".build-deps",
|
|
||||||
# Where CI checks out the shared gate itself (kuhyx/utils). Without
|
|
||||||
# this, a repo's lint job fails on utils' own long files -- a gate
|
|
||||||
# that fails for reasons the repo being gated cannot fix.
|
|
||||||
".utils",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
#: Third-party content living *inside* a repo you own, keyed by repo dir name.
|
|
||||||
#: Verified by git remote / vendor manifest, not guessed.
|
|
||||||
VENDORED_SUBPATHS = {
|
|
||||||
"mcp-servers": ("servers",),
|
|
||||||
"dufs-cloud": ("app/assets/pdfjs", "web/assets/pdfjs"),
|
|
||||||
".claude": (
|
|
||||||
"projects",
|
|
||||||
"shell-snapshots",
|
|
||||||
"cache",
|
|
||||||
"backups",
|
|
||||||
"todos",
|
|
||||||
"statsig",
|
|
||||||
"history",
|
|
||||||
"chrome",
|
|
||||||
"downloads",
|
|
||||||
"plugins",
|
|
||||||
"ide",
|
|
||||||
),
|
|
||||||
# Agent skill bundles vendored from Anthropic (todo: commit f91311f).
|
|
||||||
# A SKILL.md is a fixed-name file with frontmatter; detail belongs in a
|
|
||||||
# sibling references/ dir, so splitting one into SKILL.part2.md would
|
|
||||||
# break the format rather than improve readability.
|
|
||||||
"todo": (".agents/skills",),
|
|
||||||
}
|
|
||||||
|
|
||||||
#: Directory names that mark a vendored agent-skill tree wherever they appear.
|
|
||||||
#: Keyed by name rather than repo because these bundles get dropped into any
|
|
||||||
#: repo that wants them, not just the one they were first seen in.
|
|
||||||
VENDORED_ANYWHERE = ("/.agents/skills/", "/.claude/skills/")
|
|
||||||
|
|
||||||
#: Frozen records of past agent sessions: an implementation plan or an
|
|
||||||
#: append-only session log describes what was done at one moment. Splitting one
|
|
||||||
#: rewrites a historical record for no reading benefit -- nobody navigates them,
|
|
||||||
#: they are read whole or not at all. Same category as generated files.
|
|
||||||
#:
|
|
||||||
#: Deliberately NOT the whole of docs/superpowers/: `specs/` and `contracts/`
|
|
||||||
#: stay capped, because those are living documents that get re-read and edited.
|
|
||||||
SESSION_ARTIFACTS_ANYWHERE = (
|
|
||||||
"/docs/superpowers/plans/",
|
|
||||||
"/docs/superpowers/sessions/",
|
|
||||||
)
|
|
||||||
|
|
||||||
#: Whole repos under ~ that are third-party clones, not kuhy's work.
|
|
||||||
#: Verified 2026-08-14 by `git remote get-url origin` + commit authors.
|
|
||||||
THIRD_PARTY_REPOS = frozenset(
|
|
||||||
{
|
|
||||||
"StringTheory", # github.com/AnthonySf/TheStringTheory
|
|
||||||
"reaper-mcp", # github.com/TwelveTake-Studios/reaper-mcp
|
|
||||||
"freesound-mcp", # github.com/timjrobinson/FreesoundMCPServer
|
|
||||||
"llama_cpp_dart_local", # generated FFI bindings
|
|
||||||
"aseprite-mcp",
|
|
||||||
"Mapperatorinator", # github.com/OliBomby/Mapperatorinator
|
|
||||||
"aur",
|
|
||||||
"build-your-own-x",
|
|
||||||
"build_your_x",
|
|
||||||
"byox-ladder",
|
|
||||||
"warriorjs",
|
|
||||||
"untools",
|
|
||||||
"awesome-mcp-explorer",
|
|
||||||
"runnerup",
|
|
||||||
"depotdownloader",
|
|
||||||
"actions-runner",
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
#: A `.txt` whose mean line is shorter than this is data (a wordlist, a
|
|
||||||
#: coordinate dump), not prose, so the cap does not apply.
|
|
||||||
DATA_TXT_MAX_MEAN_LINE = 25
|
|
||||||
|
|
||||||
|
|
||||||
def is_generated(path: Path) -> bool:
|
|
||||||
"""True if the file is tool-generated and must not be split by hand."""
|
|
||||||
if GENERATED_PATTERN.search(path.as_posix()):
|
|
||||||
return True
|
|
||||||
try:
|
|
||||||
with path.open("r", encoding="utf-8", errors="replace") as handle:
|
|
||||||
head = "".join(next(handle, "") for _ in range(5))
|
|
||||||
except OSError:
|
|
||||||
return False
|
|
||||||
return any(marker in head for marker in GENERATED_MARKERS)
|
|
||||||
|
|
||||||
|
|
||||||
def is_data_text(path: Path, lines: int, size: int) -> bool:
|
|
||||||
"""True for wordlist-style .txt: many lines, very short ones."""
|
|
||||||
if path.suffix.lower() != ".txt" or lines <= 0:
|
|
||||||
return False
|
|
||||||
return (size / lines) < DATA_TXT_MAX_MEAN_LINE
|
|
||||||
|
|
||||||
|
|
||||||
def is_vendored(path: Path) -> bool:
|
|
||||||
"""True if the path sits under a known vendored subtree or excluded dir.
|
|
||||||
|
|
||||||
Callers must pass an absolute path (see `check.absolutize`). Every rule
|
|
||||||
below needs the repo-name context that a repo-relative path has already
|
|
||||||
thrown away: '/.claude/skills/' cannot match 'skills/x.md', so a relative
|
|
||||||
path would quietly skip the exemption instead of applying it.
|
|
||||||
"""
|
|
||||||
parts = path.parts
|
|
||||||
if any(part in EXCLUDED_DIRS for part in parts):
|
|
||||||
return True
|
|
||||||
posix = path.as_posix()
|
|
||||||
if any(marker in posix for marker in VENDORED_ANYWHERE):
|
|
||||||
return True
|
|
||||||
for repo, subs in VENDORED_SUBPATHS.items():
|
|
||||||
for sub in subs:
|
|
||||||
if f"/{repo}/{sub}/" in posix:
|
|
||||||
return True
|
|
||||||
return any(f"/{repo}/" in posix for repo in THIRD_PARTY_REPOS)
|
|
||||||
|
|
||||||
|
|
||||||
def is_session_artifact(path: Path) -> bool:
|
|
||||||
"""True for a frozen agent-session record (a plan or a session log).
|
|
||||||
|
|
||||||
Kept separate from `is_vendored` so the gate reports why a file is exempt:
|
|
||||||
these are kuhy's own files, not third-party code.
|
|
||||||
|
|
||||||
Callers must pass an absolute path (see `check.absolutize`), for the same
|
|
||||||
reason `is_vendored` does -- a repo-relative path has already dropped the
|
|
||||||
leading directory these markers match on.
|
|
||||||
"""
|
|
||||||
posix = path.as_posix()
|
|
||||||
return any(marker in posix for marker in SESSION_ARTIFACTS_ANYWHERE)
|
|
||||||
|
|||||||
82
file_length/exemptions.py
Normal file
82
file_length/exemptions.py
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
"""Predicates deciding whether a file is exempt from the 250-line cap.
|
||||||
|
|
||||||
|
Split from :mod:`file_length.config`, which holds the tables these read.
|
||||||
|
Keeping the rules separate from the data they consult means a new exemption
|
||||||
|
is a table entry, not a new branch, and the gate and the survey keep sharing
|
||||||
|
one definition of "exempt".
|
||||||
|
|
||||||
|
Re-exported from :mod:`file_length.config`, so existing
|
||||||
|
``from file_length.config import is_generated`` imports keep working.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from file_length._tables import (
|
||||||
|
DATA_TXT_MAX_MEAN_LINE,
|
||||||
|
EXCLUDED_DIRS,
|
||||||
|
GENERATED_MARKERS,
|
||||||
|
GENERATED_PATTERN,
|
||||||
|
SESSION_ARTIFACTS_ANYWHERE,
|
||||||
|
THIRD_PARTY_REPOS,
|
||||||
|
VENDORED_ANYWHERE,
|
||||||
|
VENDORED_SUBPATHS,
|
||||||
|
)
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def is_generated(path: Path) -> bool:
|
||||||
|
"""True if the file is tool-generated and must not be split by hand."""
|
||||||
|
if GENERATED_PATTERN.search(path.as_posix()):
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
with path.open("r", encoding="utf-8", errors="replace") as handle:
|
||||||
|
head = "".join(next(handle, "") for _ in range(5))
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
return any(marker in head for marker in GENERATED_MARKERS)
|
||||||
|
|
||||||
|
|
||||||
|
def is_data_text(path: Path, lines: int, size: int) -> bool:
|
||||||
|
"""True for wordlist-style .txt: many lines, very short ones."""
|
||||||
|
if path.suffix.lower() != ".txt" or lines <= 0:
|
||||||
|
return False
|
||||||
|
return (size / lines) < DATA_TXT_MAX_MEAN_LINE
|
||||||
|
|
||||||
|
|
||||||
|
def is_vendored(path: Path) -> bool:
|
||||||
|
"""True if the path sits under a known vendored subtree or excluded dir.
|
||||||
|
|
||||||
|
Callers must pass an absolute path (see `check.absolutize`). Every rule
|
||||||
|
below needs the repo-name context that a repo-relative path has already
|
||||||
|
thrown away: '/.claude/skills/' cannot match 'skills/x.md', so a relative
|
||||||
|
path would quietly skip the exemption instead of applying it.
|
||||||
|
"""
|
||||||
|
parts = path.parts
|
||||||
|
if any(part in EXCLUDED_DIRS for part in parts):
|
||||||
|
return True
|
||||||
|
posix = path.as_posix()
|
||||||
|
if any(marker in posix for marker in VENDORED_ANYWHERE):
|
||||||
|
return True
|
||||||
|
for repo, subs in VENDORED_SUBPATHS.items():
|
||||||
|
for sub in subs:
|
||||||
|
if f"/{repo}/{sub}/" in posix:
|
||||||
|
return True
|
||||||
|
return any(f"/{repo}/" in posix for repo in THIRD_PARTY_REPOS)
|
||||||
|
|
||||||
|
|
||||||
|
def is_session_artifact(path: Path) -> bool:
|
||||||
|
"""True for a frozen agent-session record (a plan or a session log).
|
||||||
|
|
||||||
|
Kept separate from `is_vendored` so the gate reports why a file is exempt:
|
||||||
|
these are kuhy's own files, not third-party code.
|
||||||
|
|
||||||
|
Callers must pass an absolute path (see `check.absolutize`), for the same
|
||||||
|
reason `is_vendored` does -- a repo-relative path has already dropped the
|
||||||
|
leading directory these markers match on.
|
||||||
|
"""
|
||||||
|
posix = path.as_posix()
|
||||||
|
return any(marker in posix for marker in SESSION_ARTIFACTS_ANYWHERE)
|
||||||
84
gatelock/gatelock/_grabwatch.py
Normal file
84
gatelock/gatelock/_grabwatch.py
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
"""Deciding whether this application still holds the input grab.
|
||||||
|
|
||||||
|
Split from :mod:`gatelock._recovery`, which re-asserts the grab when this
|
||||||
|
says it is gone. The question is subtle enough -- and its history costly
|
||||||
|
enough -- to be worth reading on its own, and the log-throttling state it
|
||||||
|
needs is the reason it is a small object rather than a function.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class GrabWatch:
|
||||||
|
"""Answers "is the grab still ours?", warning once per distinct cause."""
|
||||||
|
|
||||||
|
def __init__(self, root: tk.Misc) -> None:
|
||||||
|
"""Watch the grab on `root`'s display.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
root: The Tk widget whose display the grab is read from.
|
||||||
|
"""
|
||||||
|
self._root = root
|
||||||
|
self._last_warning: str | None = None
|
||||||
|
|
||||||
|
def holds_grab(self) -> bool:
|
||||||
|
"""Whether the grab is held by a window this application owns.
|
||||||
|
|
||||||
|
Deliberately *not* ``grab_current() is self._root``. Our own transient
|
||||||
|
children take the grab for themselves: a posted Tk menu grabs the menu
|
||||||
|
window, and the old identity test read that as "the grab was lost" and
|
||||||
|
called ``grab_set_global()`` a second later, stealing it back off our
|
||||||
|
own widget mid-interaction. That is what made the screen-locker sport
|
||||||
|
selector unusable while locked on 2026-07-26. Any window we own still
|
||||||
|
means the lock has the pointer and keyboard.
|
||||||
|
|
||||||
|
``grab_current`` resolves the name Tcl gives it against our own widget
|
||||||
|
map, so anything that does not resolve -- a Tcl-created popdown such as
|
||||||
|
a ``ttk.Combobox``'s, or a stale name -- raises ``KeyError`` and is NOT
|
||||||
|
provably ours. That counts as lost and the grab is re-taken: fail
|
||||||
|
closed, because this module exists to keep the lock, and losing a
|
||||||
|
popdown beats believing we hold a grab we do not.
|
||||||
|
|
||||||
|
Known limitation: a second ``tk.Tk()`` in the same process reports its
|
||||||
|
root as ``"."`` too, which is indistinguishable from ours. The old
|
||||||
|
identity test had exactly the same blind spot. ``_heat_skip``'s
|
||||||
|
throwaway root is the only other one in screen-locker, and it is
|
||||||
|
destroyed before the lock window exists.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True while a window we own holds the grab.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
held = self._root.grab_current() is not None
|
||||||
|
except KeyError as exc:
|
||||||
|
self.warn_once(
|
||||||
|
f"the grab is held by {exc.args[0]!r}, not one of our windows"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
except tk.TclError:
|
||||||
|
self.warn_once("could not read the current grab")
|
||||||
|
return False
|
||||||
|
if held:
|
||||||
|
self._last_warning = None
|
||||||
|
return held
|
||||||
|
|
||||||
|
def warn_once(self, reason: str) -> None:
|
||||||
|
"""Warn about a lost grab, but only when the reason changes.
|
||||||
|
|
||||||
|
These states can persist for the whole lock (a dark display, a popdown
|
||||||
|
that keeps re-grabbing), and this runs once a second -- warning every
|
||||||
|
tick would push a line per second into the journal for as long as it
|
||||||
|
lasts. Silence is not the alternative: the first occurrence and every
|
||||||
|
change of cause are still logged at WARNING.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
reason: Why the grab is not provably ours.
|
||||||
|
"""
|
||||||
|
if reason != self._last_warning:
|
||||||
|
_logger.warning("%s; treating it as lost and re-taking it", reason)
|
||||||
|
self._last_warning = reason
|
||||||
136
gatelock/gatelock/_placement.py
Normal file
136
gatelock/gatelock/_placement.py
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
"""Where a lock surface sits, and putting it back when it drifts.
|
||||||
|
|
||||||
|
Split from :mod:`gatelock._surfaces`, which owns creating and destroying the
|
||||||
|
windows. This half owns the geometry questions -- is the window mapped, is it
|
||||||
|
still exactly on its output -- and the re-assertion pass that answers "no" by
|
||||||
|
correcting it.
|
||||||
|
|
||||||
|
Everything here only ever *adds* visibility. Nothing in this module can hide
|
||||||
|
or unmap a surface; that asymmetry is what makes the recovery loop monotonic.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
import tkinter as tk
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
from gatelock._config import LockConfig
|
||||||
|
|
||||||
|
from gatelock._outputs import OutputRect
|
||||||
|
from gatelock._surfaces import SurfaceInfo
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _Surface:
|
||||||
|
"""One Toplevel and the output it is pinned to."""
|
||||||
|
|
||||||
|
info: SurfaceInfo
|
||||||
|
window: tk.Toplevel
|
||||||
|
built: bool = field(default=False)
|
||||||
|
|
||||||
|
|
||||||
|
def set_geometry(window: tk.Toplevel, rect: OutputRect) -> None:
|
||||||
|
"""Pin a window to an output's rectangle."""
|
||||||
|
window.geometry(rect.geometry())
|
||||||
|
|
||||||
|
|
||||||
|
def is_mapped(surface: _Surface) -> bool:
|
||||||
|
"""Whether a surface's window is currently mapped."""
|
||||||
|
return bool(surface.window.winfo_ismapped())
|
||||||
|
|
||||||
|
|
||||||
|
def geometry_matches(surface: _Surface) -> bool:
|
||||||
|
"""Whether a surface still sits exactly on its output."""
|
||||||
|
rect = surface.info.rect
|
||||||
|
window = surface.window
|
||||||
|
return (
|
||||||
|
window.winfo_rootx() == rect.x
|
||||||
|
and window.winfo_rooty() == rect.y
|
||||||
|
and window.winfo_width() == rect.width
|
||||||
|
and window.winfo_height() == rect.height
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def enforce_one(surface: _Surface, *, overrideredirect: bool) -> bool:
|
||||||
|
"""Re-assert one surface's placement and stacking.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
surface: The surface to correct.
|
||||||
|
overrideredirect: Whether the lock runs WM-unmanaged, in which case
|
||||||
|
the flag is re-set -- it can be dropped across an unmap/map cycle,
|
||||||
|
and a managed lock window would be moved by the WM.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if anything needed correcting.
|
||||||
|
"""
|
||||||
|
window = surface.window
|
||||||
|
changed = False
|
||||||
|
if not is_mapped(surface):
|
||||||
|
window.deiconify()
|
||||||
|
changed = True
|
||||||
|
if not geometry_matches(surface):
|
||||||
|
set_geometry(window, surface.info.rect)
|
||||||
|
changed = True
|
||||||
|
if overrideredirect:
|
||||||
|
window.overrideredirect(boolean=True)
|
||||||
|
window.lift()
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def blind_outputs(
|
||||||
|
surfaces: Mapping[str, _Surface], names: frozenset[str]
|
||||||
|
) -> tuple[str, ...]:
|
||||||
|
"""Live outputs that are NOT currently showing a lock.
|
||||||
|
|
||||||
|
This is the alarm for the original defect: an output the user can see,
|
||||||
|
with no lock on it, means the escape UI is somewhere they cannot reach.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
surfaces: The live surfaces, keyed by output name.
|
||||||
|
names: The outputs that should be covered.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The uncovered output names, sorted.
|
||||||
|
"""
|
||||||
|
blind: list[str] = []
|
||||||
|
for name in sorted(names):
|
||||||
|
surface = surfaces.get(name)
|
||||||
|
if surface is None or not is_mapped(surface):
|
||||||
|
blind.append(name)
|
||||||
|
return tuple(blind)
|
||||||
|
|
||||||
|
|
||||||
|
def enforce_all(
|
||||||
|
surfaces: Mapping[str, _Surface], *, overrideredirect: bool
|
||||||
|
) -> tuple[str, ...]:
|
||||||
|
"""Re-assert every surface's placement and stacking.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
surfaces: The live surfaces, keyed by output name.
|
||||||
|
overrideredirect: Whether the lock runs WM-unmanaged.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The names of the outputs whose surfaces needed correcting, sorted.
|
||||||
|
"""
|
||||||
|
corrected = [
|
||||||
|
surface.info.output_name
|
||||||
|
for surface in surfaces.values()
|
||||||
|
if enforce_one(surface, overrideredirect=overrideredirect)
|
||||||
|
]
|
||||||
|
return tuple(sorted(corrected))
|
||||||
|
|
||||||
|
|
||||||
|
def needs_backdrop_root(config: LockConfig) -> bool:
|
||||||
|
"""Whether the root must stay mapped as a backdrop and grab holder.
|
||||||
|
|
||||||
|
Deliberately *not* simplified to "iff override-redirect".
|
||||||
|
``LockConfig(mode="soft", grab="global")`` is a reachable combination, and
|
||||||
|
a global grab requires a viewable window -- X refuses to grab for a
|
||||||
|
withdrawn one. Collapsing this predicate would make that config fail at
|
||||||
|
runtime only.
|
||||||
|
"""
|
||||||
|
return config.resolved_overrideredirect() or config.resolved_grab() != "none"
|
||||||
@ -36,54 +36,19 @@ keeps the grab. Pulling a cable is therefore not an escape.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import contextlib
|
import contextlib
|
||||||
from dataclasses import dataclass
|
|
||||||
import logging
|
import logging
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING
|
|
||||||
|
|
||||||
|
from gatelock._grabwatch import GrabWatch
|
||||||
|
from gatelock._recovery_types import RecoveryCollaborators, RecoveryReport
|
||||||
from gatelock._vt import disable_vt_switching
|
from gatelock._vt import disable_vt_switching
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
|
||||||
from gatelock._detect import OutputChangeDetector
|
|
||||||
from gatelock._outputs import OutputEnumerator
|
|
||||||
from gatelock._surfaces import SurfaceDelta, SurfaceSet
|
|
||||||
from gatelock._window import LockConfig, LockWindowHooks
|
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
_VT_REASSERT_EVERY = 30
|
_VT_REASSERT_EVERY = 30
|
||||||
"""Re-disable VT switching every N verify ticks, in case something reset it."""
|
"""Re-disable VT switching every N verify ticks, in case something reset it."""
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RecoveryReport:
|
|
||||||
"""What one tick observed and corrected."""
|
|
||||||
|
|
||||||
scan_ok: bool
|
|
||||||
source: str
|
|
||||||
live_outputs: tuple[str, ...] = ()
|
|
||||||
delta: SurfaceDelta | None = None
|
|
||||||
corrected: tuple[str, ...] = ()
|
|
||||||
grab_reasserted: bool = False
|
|
||||||
vt_reasserted: bool = False
|
|
||||||
blind: tuple[str, ...] = ()
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class RecoveryCollaborators:
|
|
||||||
"""The pieces one tick re-asserts over.
|
|
||||||
|
|
||||||
Bundled to keep the loop's constructor at one object instead of a
|
|
||||||
growing, unbounded arg list.
|
|
||||||
"""
|
|
||||||
|
|
||||||
config: LockConfig
|
|
||||||
surfaces: SurfaceSet
|
|
||||||
enumerator: OutputEnumerator
|
|
||||||
detector: OutputChangeDetector
|
|
||||||
hooks: LockWindowHooks
|
|
||||||
|
|
||||||
|
|
||||||
class RecoveryLoop:
|
class RecoveryLoop:
|
||||||
"""Re-asserts the lock's coverage on a timer and on change events."""
|
"""Re-asserts the lock's coverage on a timer and on change events."""
|
||||||
|
|
||||||
@ -99,7 +64,7 @@ class RecoveryLoop:
|
|||||||
self._ticks = 0
|
self._ticks = 0
|
||||||
self._drain_job: str | None = None
|
self._drain_job: str | None = None
|
||||||
self._verify_job: str | None = None
|
self._verify_job: str | None = None
|
||||||
self._last_grab_warning: str | None = None
|
self._grab = GrabWatch(root)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def ticks(self) -> int:
|
def ticks(self) -> int:
|
||||||
@ -238,43 +203,12 @@ class RecoveryLoop:
|
|||||||
def holds_grab(self) -> bool:
|
def holds_grab(self) -> bool:
|
||||||
"""Whether the grab is held by a window this application owns.
|
"""Whether the grab is held by a window this application owns.
|
||||||
|
|
||||||
Deliberately *not* ``grab_current() is self._root``. Our own transient
|
|
||||||
children take the grab for themselves: a posted Tk menu grabs the menu
|
|
||||||
window, and the old identity test read that as "the grab was lost" and
|
|
||||||
called ``grab_set_global()`` a second later, stealing it back off our
|
|
||||||
own widget mid-interaction. That is what made the screen-locker sport
|
|
||||||
selector unusable while locked on 2026-07-26. Any window we own still
|
|
||||||
means the lock has the pointer and keyboard.
|
|
||||||
|
|
||||||
``grab_current`` resolves the name Tcl gives it against our own widget
|
|
||||||
map, so anything that does not resolve -- a Tcl-created popdown such as
|
|
||||||
a ``ttk.Combobox``'s, or a stale name -- raises ``KeyError`` and is NOT
|
|
||||||
provably ours. That counts as lost and the grab is re-taken: fail
|
|
||||||
closed, because this module exists to keep the lock, and losing a
|
|
||||||
popdown beats believing we hold a grab we do not.
|
|
||||||
|
|
||||||
Known limitation: a second ``tk.Tk()`` in the same process reports its
|
|
||||||
root as ``"."`` too, which is indistinguishable from ours. The old
|
|
||||||
identity test had exactly the same blind spot. ``_heat_skip``'s
|
|
||||||
throwaway root is the only other one in screen-locker, and it is
|
|
||||||
destroyed before the lock window exists.
|
|
||||||
|
|
||||||
Public so an embedder (or a verification harness) can ask the same
|
Public so an embedder (or a verification harness) can ask the same
|
||||||
question the loop asks, rather than re-implementing it and drifting.
|
question the loop asks, rather than re-implementing it and drifting.
|
||||||
|
See :class:`gatelock._grabwatch.GrabWatch` for why the test is not a
|
||||||
|
simple identity check.
|
||||||
"""
|
"""
|
||||||
try:
|
return self._grab.holds_grab()
|
||||||
held = self._root.grab_current() is not None
|
|
||||||
except KeyError as exc:
|
|
||||||
self._warn_once(
|
|
||||||
f"the grab is held by {exc.args[0]!r}, not one of our windows"
|
|
||||||
)
|
|
||||||
return False
|
|
||||||
except tk.TclError:
|
|
||||||
self._warn_once("could not read the current grab")
|
|
||||||
return False
|
|
||||||
if held:
|
|
||||||
self._last_grab_warning = None
|
|
||||||
return held
|
|
||||||
|
|
||||||
def _reassert_focus(self) -> None:
|
def _reassert_focus(self) -> None:
|
||||||
"""Re-focus the preferred surface after any output came back live.
|
"""Re-focus the preferred surface after any output came back live.
|
||||||
@ -294,19 +228,6 @@ class RecoveryLoop:
|
|||||||
index = self._surfaces.preferred_focus_index()
|
index = self._surfaces.preferred_focus_index()
|
||||||
self._hooks.on_focus_ready(self._surfaces.focus_surface(index))
|
self._hooks.on_focus_ready(self._surfaces.focus_surface(index))
|
||||||
|
|
||||||
def _warn_once(self, reason: str) -> None:
|
|
||||||
"""Warn about a lost grab, but only when the reason changes.
|
|
||||||
|
|
||||||
These states can persist for the whole lock (a dark display, a popdown
|
|
||||||
that keeps re-grabbing), and this runs once a second -- warning every
|
|
||||||
tick would push a line per second into the journal for as long as it
|
|
||||||
lasts. Silence is not the alternative: the first occurrence and every
|
|
||||||
change of cause are still logged at WARNING.
|
|
||||||
"""
|
|
||||||
if reason != self._last_grab_warning:
|
|
||||||
_logger.warning("%s; treating it as lost and re-taking it", reason)
|
|
||||||
self._last_grab_warning = reason
|
|
||||||
|
|
||||||
def _reassert_vt(self) -> bool:
|
def _reassert_vt(self) -> bool:
|
||||||
"""Periodically re-disable VT switching. Never re-enables it.
|
"""Periodically re-disable VT switching. Never re-enables it.
|
||||||
|
|
||||||
|
|||||||
47
gatelock/gatelock/_recovery_types.py
Normal file
47
gatelock/gatelock/_recovery_types.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
"""The value types one recovery tick produces and consumes.
|
||||||
|
|
||||||
|
Split from :mod:`gatelock._recovery` for the 250-line cap. Data only -- no
|
||||||
|
behaviour, and deliberately no import of the loop, so a caller can type
|
||||||
|
against a report without pulling in the machinery that builds one.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from gatelock._config import LockConfig
|
||||||
|
from gatelock._detect import OutputChangeDetector
|
||||||
|
from gatelock._hooks import LockWindowHooks
|
||||||
|
from gatelock._outputs import OutputEnumerator
|
||||||
|
from gatelock._surfaces import SurfaceDelta, SurfaceSet
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RecoveryReport:
|
||||||
|
"""What one tick observed and corrected."""
|
||||||
|
|
||||||
|
scan_ok: bool
|
||||||
|
source: str
|
||||||
|
live_outputs: tuple[str, ...] = ()
|
||||||
|
delta: SurfaceDelta | None = None
|
||||||
|
corrected: tuple[str, ...] = ()
|
||||||
|
grab_reasserted: bool = False
|
||||||
|
vt_reasserted: bool = False
|
||||||
|
blind: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RecoveryCollaborators:
|
||||||
|
"""The pieces one tick re-asserts over.
|
||||||
|
|
||||||
|
Bundled to keep the loop's constructor at one object instead of a
|
||||||
|
growing, unbounded arg list.
|
||||||
|
"""
|
||||||
|
|
||||||
|
config: LockConfig
|
||||||
|
surfaces: SurfaceSet
|
||||||
|
enumerator: OutputEnumerator
|
||||||
|
detector: OutputChangeDetector
|
||||||
|
hooks: LockWindowHooks
|
||||||
54
gatelock/gatelock/_surface_types.py
Normal file
54
gatelock/gatelock/_surface_types.py
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
"""The value types describing a lock surface and a change to the set of them.
|
||||||
|
|
||||||
|
Split from :mod:`gatelock._surfaces` for the 250-line cap. Data and one
|
||||||
|
Protocol, no behaviour, so an app can type against a surface without
|
||||||
|
importing the machinery that builds one.
|
||||||
|
|
||||||
|
Re-exported from :mod:`gatelock._surfaces`, so existing imports of these
|
||||||
|
names keep working.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import TYPE_CHECKING, Protocol
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
import tkinter as tk
|
||||||
|
|
||||||
|
from gatelock._outputs import OutputRect
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SurfaceInfo:
|
||||||
|
"""Identifies one lock surface and the output it covers."""
|
||||||
|
|
||||||
|
output_name: str
|
||||||
|
rect: OutputRect
|
||||||
|
index: int
|
||||||
|
is_primary: bool
|
||||||
|
|
||||||
|
|
||||||
|
class SurfaceBuilder(Protocol):
|
||||||
|
"""What a consuming app must implement to paint its UI on each output."""
|
||||||
|
|
||||||
|
def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None:
|
||||||
|
"""Build this app's widgets inside ``parent`` for one output."""
|
||||||
|
|
||||||
|
def teardown_surface(self, surface: SurfaceInfo) -> None:
|
||||||
|
"""Forget any per-surface state; the window is about to be destroyed."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class SurfaceDelta:
|
||||||
|
"""What one :meth:`SurfaceSet.apply` changed."""
|
||||||
|
|
||||||
|
created: tuple[str, ...] = ()
|
||||||
|
moved: tuple[str, ...] = ()
|
||||||
|
removed: tuple[str, ...] = ()
|
||||||
|
unverified: tuple[str, ...] = ()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def changed(self) -> bool:
|
||||||
|
"""Whether anything structural happened."""
|
||||||
|
return bool(self.created or self.moved or self.removed)
|
||||||
@ -34,15 +34,39 @@ recording, because each rules out an approach that looks reasonable:
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
import logging
|
import logging
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
from typing import TYPE_CHECKING, Protocol
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from gatelock._placement import (
|
||||||
|
_Surface,
|
||||||
|
blind_outputs,
|
||||||
|
needs_backdrop_root,
|
||||||
|
enforce_all,
|
||||||
|
set_geometry,
|
||||||
|
)
|
||||||
|
from gatelock._surface_types import (
|
||||||
|
SurfaceBuilder,
|
||||||
|
SurfaceDelta,
|
||||||
|
SurfaceInfo,
|
||||||
|
)
|
||||||
|
from gatelock._textmirror import TextMirror, mirror_text_widgets
|
||||||
|
|
||||||
|
# Names this module re-exports after the 250-line split. Listed explicitly so
|
||||||
|
# the autofixer cannot prune an import that exists *for* its re-export -- it
|
||||||
|
# stripped mirror_text_widgets once, and `gatelock` itself stopped importing.
|
||||||
|
__all__ = [
|
||||||
|
"SurfaceBuilder",
|
||||||
|
"SurfaceDelta",
|
||||||
|
"SurfaceInfo",
|
||||||
|
"SurfaceSet",
|
||||||
|
"TextMirror",
|
||||||
|
"mirror_text_widgets",
|
||||||
|
"needs_backdrop_root",
|
||||||
|
]
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Sequence
|
from gatelock._outputs import OutputScan
|
||||||
|
|
||||||
from gatelock._outputs import OutputRect, OutputScan
|
|
||||||
from gatelock._window import LockConfig
|
from gatelock._window import LockConfig
|
||||||
|
|
||||||
_logger = logging.getLogger(__name__)
|
_logger = logging.getLogger(__name__)
|
||||||
@ -52,117 +76,6 @@ _logger = logging.getLogger(__name__)
|
|||||||
# and the type stubs, which have no keyword overload.
|
# and the type stubs, which have no keyword overload.
|
||||||
_TOPMOST_ON = True
|
_TOPMOST_ON = True
|
||||||
|
|
||||||
_TEXT_START = "1.0"
|
|
||||||
_TEXT_END = "end-1c"
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class SurfaceInfo:
|
|
||||||
"""Identifies one lock surface and the output it covers."""
|
|
||||||
|
|
||||||
output_name: str
|
|
||||||
rect: OutputRect
|
|
||||||
index: int
|
|
||||||
is_primary: bool
|
|
||||||
|
|
||||||
|
|
||||||
class SurfaceBuilder(Protocol):
|
|
||||||
"""What a consuming app must implement to paint its UI on each output."""
|
|
||||||
|
|
||||||
def build_surface(self, parent: tk.Misc, surface: SurfaceInfo) -> None:
|
|
||||||
"""Build this app's widgets inside ``parent`` for one output."""
|
|
||||||
|
|
||||||
def teardown_surface(self, surface: SurfaceInfo) -> None:
|
|
||||||
"""Forget any per-surface state; the window is about to be destroyed."""
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class SurfaceDelta:
|
|
||||||
"""What one :meth:`SurfaceSet.apply` changed."""
|
|
||||||
|
|
||||||
created: tuple[str, ...] = ()
|
|
||||||
moved: tuple[str, ...] = ()
|
|
||||||
removed: tuple[str, ...] = ()
|
|
||||||
unverified: tuple[str, ...] = ()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def changed(self) -> bool:
|
|
||||||
"""Whether anything structural happened."""
|
|
||||||
return bool(self.created or self.moved or self.removed)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class _Surface:
|
|
||||||
"""One Toplevel and the output it is pinned to."""
|
|
||||||
|
|
||||||
info: SurfaceInfo
|
|
||||||
window: tk.Toplevel
|
|
||||||
built: bool = field(default=False)
|
|
||||||
|
|
||||||
|
|
||||||
def needs_backdrop_root(config: LockConfig) -> bool:
|
|
||||||
"""Whether the root must stay mapped as a backdrop and grab holder.
|
|
||||||
|
|
||||||
Deliberately *not* simplified to "iff override-redirect".
|
|
||||||
``LockConfig(mode="soft", grab="global")`` is a reachable combination, and
|
|
||||||
a global grab requires a viewable window -- X refuses to grab for a
|
|
||||||
withdrawn one. Collapsing this predicate would make that config fail at
|
|
||||||
runtime only.
|
|
||||||
"""
|
|
||||||
return config.resolved_overrideredirect() or config.resolved_grab() != "none"
|
|
||||||
|
|
||||||
|
|
||||||
class TextMirror:
|
|
||||||
"""Keeps N ``tk.Text`` widgets showing the same value.
|
|
||||||
|
|
||||||
``tk.Text`` has no ``textvariable``, so it is the one widget that cannot
|
|
||||||
ride the shared-``StringVar`` mechanism the rest of the mirroring uses.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, widgets: Sequence[tk.Text], var: tk.StringVar) -> None:
|
|
||||||
"""Bind ``widgets`` to each other through ``var``."""
|
|
||||||
self._widgets = list(widgets)
|
|
||||||
self._var = var
|
|
||||||
self._syncing = False
|
|
||||||
for widget in self._widgets:
|
|
||||||
widget.bind("<KeyRelease>", self._on_key_release, add="+")
|
|
||||||
self._var.trace_add("write", self._on_var_write)
|
|
||||||
|
|
||||||
def _on_key_release(self, event: tk.Event[tk.Text]) -> None:
|
|
||||||
"""Push the edited widget's content into the shared variable."""
|
|
||||||
if self._syncing:
|
|
||||||
return
|
|
||||||
self._syncing = True
|
|
||||||
try:
|
|
||||||
self._var.set(event.widget.get(_TEXT_START, _TEXT_END))
|
|
||||||
finally:
|
|
||||||
self._syncing = False
|
|
||||||
self._fan_out(source=event.widget)
|
|
||||||
|
|
||||||
def _on_var_write(self, *_args: str) -> None:
|
|
||||||
"""Push the shared variable's value into every widget."""
|
|
||||||
if self._syncing:
|
|
||||||
return
|
|
||||||
self._fan_out(source=None)
|
|
||||||
|
|
||||||
def _fan_out(self, *, source: tk.Text | None) -> None:
|
|
||||||
"""Write the variable's value into every widget but ``source``."""
|
|
||||||
value = self._var.get()
|
|
||||||
self._syncing = True
|
|
||||||
try:
|
|
||||||
for widget in self._widgets:
|
|
||||||
if widget is source or widget.get(_TEXT_START, _TEXT_END) == value:
|
|
||||||
continue
|
|
||||||
widget.delete(_TEXT_START, "end")
|
|
||||||
widget.insert(_TEXT_START, value)
|
|
||||||
finally:
|
|
||||||
self._syncing = False
|
|
||||||
|
|
||||||
|
|
||||||
def mirror_text_widgets(widgets: Sequence[tk.Text], var: tk.StringVar) -> TextMirror:
|
|
||||||
"""Keep several ``tk.Text`` mirrors in sync through one variable."""
|
|
||||||
return TextMirror(widgets, var)
|
|
||||||
|
|
||||||
|
|
||||||
class SurfaceSet:
|
class SurfaceSet:
|
||||||
"""The full set of lock windows, kept in step with the live outputs."""
|
"""The full set of lock windows, kept in step with the live outputs."""
|
||||||
@ -252,12 +165,7 @@ class SurfaceSet:
|
|||||||
with no lock on it, means the escape UI is somewhere they cannot reach.
|
with no lock on it, means the escape UI is somewhere they cannot reach.
|
||||||
"""
|
"""
|
||||||
names = live_names if live_names is not None else self.names()
|
names = live_names if live_names is not None else self.names()
|
||||||
blind: list[str] = []
|
return blind_outputs(self._surfaces, names)
|
||||||
for name in sorted(names):
|
|
||||||
surface = self._surfaces.get(name)
|
|
||||||
if surface is None or not self._is_mapped(surface):
|
|
||||||
blind.append(name)
|
|
||||||
return tuple(blind)
|
|
||||||
|
|
||||||
def enforce(self) -> tuple[str, ...]:
|
def enforce(self) -> tuple[str, ...]:
|
||||||
"""Re-assert every surface's placement and stacking.
|
"""Re-assert every surface's placement and stacking.
|
||||||
@ -265,29 +173,10 @@ class SurfaceSet:
|
|||||||
Only ever *adds* visibility: remaps what became unmapped, corrects
|
Only ever *adds* visibility: remaps what became unmapped, corrects
|
||||||
drifted geometry, and raises. Nothing here can hide a surface.
|
drifted geometry, and raises. Nothing here can hide a surface.
|
||||||
"""
|
"""
|
||||||
corrected = [
|
return enforce_all(
|
||||||
surface.info.output_name
|
self._surfaces,
|
||||||
for surface in self._surfaces.values()
|
overrideredirect=self._config.resolved_overrideredirect(),
|
||||||
if self._enforce_one(surface)
|
)
|
||||||
]
|
|
||||||
return tuple(sorted(corrected))
|
|
||||||
|
|
||||||
def _enforce_one(self, surface: _Surface) -> bool:
|
|
||||||
"""Re-assert one surface. True if anything needed correcting."""
|
|
||||||
window = surface.window
|
|
||||||
changed = False
|
|
||||||
if not self._is_mapped(surface):
|
|
||||||
window.deiconify()
|
|
||||||
changed = True
|
|
||||||
if not self._geometry_matches(surface):
|
|
||||||
self._set_geometry(window, surface.info.rect)
|
|
||||||
changed = True
|
|
||||||
# Re-assert override-redirect: it can be dropped across an unmap/map
|
|
||||||
# cycle, and a managed lock window would be moved by the WM.
|
|
||||||
if self._config.resolved_overrideredirect():
|
|
||||||
window.overrideredirect(boolean=True)
|
|
||||||
window.lift()
|
|
||||||
return changed
|
|
||||||
|
|
||||||
def raise_all(self) -> None:
|
def raise_all(self) -> None:
|
||||||
"""Lift every surface above whatever else is on screen."""
|
"""Lift every surface above whatever else is on screen."""
|
||||||
@ -321,7 +210,7 @@ class SurfaceSet:
|
|||||||
if self._config.resolved_overrideredirect():
|
if self._config.resolved_overrideredirect():
|
||||||
window.overrideredirect(boolean=True)
|
window.overrideredirect(boolean=True)
|
||||||
window.configure(bg=self._config.bg, cursor="arrow")
|
window.configure(bg=self._config.bg, cursor="arrow")
|
||||||
self._set_geometry(window, info.rect)
|
set_geometry(window, info.rect)
|
||||||
if not self._config.resolved_overrideredirect():
|
if not self._config.resolved_overrideredirect():
|
||||||
window.attributes("-topmost", _TOPMOST_ON)
|
window.attributes("-topmost", _TOPMOST_ON)
|
||||||
window.deiconify()
|
window.deiconify()
|
||||||
@ -342,7 +231,7 @@ class SurfaceSet:
|
|||||||
not discard half-typed input.
|
not discard half-typed input.
|
||||||
"""
|
"""
|
||||||
surface.info = info
|
surface.info = info
|
||||||
self._set_geometry(surface.window, info.rect)
|
set_geometry(surface.window, info.rect)
|
||||||
surface.window.lift()
|
surface.window.lift()
|
||||||
_logger.info(
|
_logger.info(
|
||||||
"lock surface on %s moved to %s", info.output_name, info.rect.geometry()
|
"lock surface on %s moved to %s", info.output_name, info.rect.geometry()
|
||||||
@ -359,22 +248,3 @@ class SurfaceSet:
|
|||||||
"""Tear down every surface. Used only when the whole lock is closing."""
|
"""Tear down every surface. Used only when the whole lock is closing."""
|
||||||
for name in list(self._surfaces):
|
for name in list(self._surfaces):
|
||||||
self._destroy(name)
|
self._destroy(name)
|
||||||
|
|
||||||
def _set_geometry(self, window: tk.Toplevel, rect: OutputRect) -> None:
|
|
||||||
"""Pin a window to an output's rectangle."""
|
|
||||||
window.geometry(rect.geometry())
|
|
||||||
|
|
||||||
def _is_mapped(self, surface: _Surface) -> bool:
|
|
||||||
"""Whether a surface's window is currently mapped."""
|
|
||||||
return bool(surface.window.winfo_ismapped())
|
|
||||||
|
|
||||||
def _geometry_matches(self, surface: _Surface) -> bool:
|
|
||||||
"""Whether a surface still sits exactly on its output."""
|
|
||||||
rect = surface.info.rect
|
|
||||||
window = surface.window
|
|
||||||
return (
|
|
||||||
window.winfo_rootx() == rect.x
|
|
||||||
and window.winfo_rooty() == rect.y
|
|
||||||
and window.winfo_width() == rect.width
|
|
||||||
and window.winfo_height() == rect.height
|
|
||||||
)
|
|
||||||
|
|||||||
75
gatelock/gatelock/_textmirror.py
Normal file
75
gatelock/gatelock/_textmirror.py
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
"""Keeping several Text widgets showing the same string.
|
||||||
|
|
||||||
|
Split from :mod:`gatelock._surfaces` for the 250-line cap. A lock renders one
|
||||||
|
surface per output, so a multi-line field exists once per monitor and all the
|
||||||
|
copies have to agree; ``tk.StringVar`` does this for Entry and Spinbox but not
|
||||||
|
for ``tk.Text``, which has no textvariable.
|
||||||
|
|
||||||
|
Re-exported from :mod:`gatelock._surfaces` and from :mod:`gatelock`, so
|
||||||
|
existing imports of either name keep working.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import tkinter as tk
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
# Tk text indices: the first character, and the last one before the newline
|
||||||
|
# Text always appends.
|
||||||
|
_TEXT_START = "1.0"
|
||||||
|
_TEXT_END = "end-1c"
|
||||||
|
|
||||||
|
|
||||||
|
class TextMirror:
|
||||||
|
"""Keeps N ``tk.Text`` widgets showing the same value.
|
||||||
|
|
||||||
|
``tk.Text`` has no ``textvariable``, so it is the one widget that cannot
|
||||||
|
ride the shared-``StringVar`` mechanism the rest of the mirroring uses.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, widgets: Sequence[tk.Text], var: tk.StringVar) -> None:
|
||||||
|
"""Bind ``widgets`` to each other through ``var``."""
|
||||||
|
self._widgets = list(widgets)
|
||||||
|
self._var = var
|
||||||
|
self._syncing = False
|
||||||
|
for widget in self._widgets:
|
||||||
|
widget.bind("<KeyRelease>", self._on_key_release, add="+")
|
||||||
|
self._var.trace_add("write", self._on_var_write)
|
||||||
|
|
||||||
|
def _on_key_release(self, event: tk.Event[tk.Text]) -> None:
|
||||||
|
"""Push the edited widget's content into the shared variable."""
|
||||||
|
if self._syncing:
|
||||||
|
return
|
||||||
|
self._syncing = True
|
||||||
|
try:
|
||||||
|
self._var.set(event.widget.get(_TEXT_START, _TEXT_END))
|
||||||
|
finally:
|
||||||
|
self._syncing = False
|
||||||
|
self._fan_out(source=event.widget)
|
||||||
|
|
||||||
|
def _on_var_write(self, *_args: str) -> None:
|
||||||
|
"""Push the shared variable's value into every widget."""
|
||||||
|
if self._syncing:
|
||||||
|
return
|
||||||
|
self._fan_out(source=None)
|
||||||
|
|
||||||
|
def _fan_out(self, *, source: tk.Text | None) -> None:
|
||||||
|
"""Write the variable's value into every widget but ``source``."""
|
||||||
|
value = self._var.get()
|
||||||
|
self._syncing = True
|
||||||
|
try:
|
||||||
|
for widget in self._widgets:
|
||||||
|
if widget is source or widget.get(_TEXT_START, _TEXT_END) == value:
|
||||||
|
continue
|
||||||
|
widget.delete(_TEXT_START, "end")
|
||||||
|
widget.insert(_TEXT_START, value)
|
||||||
|
finally:
|
||||||
|
self._syncing = False
|
||||||
|
|
||||||
|
|
||||||
|
def mirror_text_widgets(widgets: Sequence[tk.Text], var: tk.StringVar) -> TextMirror:
|
||||||
|
"""Keep several ``tk.Text`` mirrors in sync through one variable."""
|
||||||
|
return TextMirror(widgets, var)
|
||||||
@ -4,7 +4,6 @@ Split from ``test_escape.py`` (250-line cap), which keeps policy defaults,
|
|||||||
timestamp parsing, loading, and the integrity guarantee.
|
timestamp parsing, loading, and the integrity guarantee.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
|||||||
@ -5,8 +5,6 @@ keeps the python-xlib backend itself; this covers the enumerator that drives
|
|||||||
it and the OutputScan it produces.
|
it and the OutputScan it produces.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|||||||
@ -4,7 +4,6 @@ Split from ``test_outputs.py`` (250-line cap), which keeps rect geometry,
|
|||||||
the live predicate, and xrandr-query parsing.
|
the live predicate, and xrandr-query parsing.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|||||||
@ -18,11 +18,24 @@ SOURCE_ROOT = Path(__file__).resolve().parent.parent
|
|||||||
|
|
||||||
|
|
||||||
def symbols(module: str) -> set[str]:
|
def symbols(module: str) -> set[str]:
|
||||||
"""Every attribute and name referenced in a module's source."""
|
"""Every attribute and name referenced across the `module` family.
|
||||||
tree = ast.parse((SOURCE_ROOT / module).read_text(encoding="utf-8"))
|
|
||||||
return {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)} | {
|
Globbed rather than read as one exact filename, so that splitting a module
|
||||||
n.id for n in ast.walk(tree) if isinstance(n, ast.Name)
|
for the 250-line cap cannot narrow the invariant to whichever half kept the
|
||||||
}
|
original name. A new `_recovery_*.py` sibling is covered the moment it
|
||||||
|
exists; nobody has to remember to extend a list here.
|
||||||
|
"""
|
||||||
|
stem = module.removesuffix(".py")
|
||||||
|
paths = sorted(SOURCE_ROOT.glob(f"{stem}*.py"))
|
||||||
|
if not paths:
|
||||||
|
msg = f"no module matching {stem}*.py -- renamed? the guard is off"
|
||||||
|
raise AssertionError(msg)
|
||||||
|
found: set[str] = set()
|
||||||
|
for path in paths:
|
||||||
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||||
|
found |= {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
|
||||||
|
found |= {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)}
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
class TestStaticInvariant:
|
class TestStaticInvariant:
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
Split from ``test_surfaces.py`` to hold the shared 250-line cap.
|
Split from ``test_surfaces.py`` to hold the shared 250-line cap.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
Split from ``test_window.py`` to hold the shared 250-line cap.
|
Split from ``test_window.py`` to hold the shared 250-line cap.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import tkinter as tk
|
import tkinter as tk
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
Split from ``test_window_surfaces.py`` to hold the shared 250-line cap.
|
Split from ``test_window_surfaces.py`` to hold the shared 250-line cap.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import queue
|
import queue
|
||||||
|
|||||||
@ -4,7 +4,6 @@ Split from ``test_window_surfaces.py`` to hold the shared 250-line cap;
|
|||||||
that file keeps arming without a display and the grab-blocked logging.
|
that file keeps arming without a display and the grab-blocked logging.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import signal
|
import signal
|
||||||
|
|||||||
204
github_device_auth/test/device_auth_poll_test.dart
Normal file
204
github_device_auth/test/device_auth_poll_test.dart
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:github_device_auth/github_device_auth.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
import 'package:http/testing.dart';
|
||||||
|
|
||||||
|
/// Never actually waits: the poll loop's pacing is injected so a test that
|
||||||
|
/// exercises `slow_down` does not take 15 real seconds.
|
||||||
|
Future<void> noDelay(Duration _) async {}
|
||||||
|
|
||||||
|
GitHubDeviceAuth authWith(
|
||||||
|
MockClient client, {
|
||||||
|
String scope = 'repo',
|
||||||
|
}) => GitHubDeviceAuth(
|
||||||
|
clientId: 'cid',
|
||||||
|
scope: scope,
|
||||||
|
httpClient: client,
|
||||||
|
delay: noDelay,
|
||||||
|
);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('pollForToken', () {
|
||||||
|
const device = DeviceCodeResponse(
|
||||||
|
deviceCode: 'dc',
|
||||||
|
userCode: 'UC',
|
||||||
|
verificationUri: 'u',
|
||||||
|
interval: 1,
|
||||||
|
expiresIn: 60,
|
||||||
|
);
|
||||||
|
|
||||||
|
test('returns the token once the user authorizes', () async {
|
||||||
|
var calls = 0;
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient((_) async {
|
||||||
|
calls += 1;
|
||||||
|
// First poll pending, second succeeds -- the normal path.
|
||||||
|
return http.Response(
|
||||||
|
calls == 1
|
||||||
|
? jsonEncode({'error': 'authorization_pending'})
|
||||||
|
: jsonEncode({'access_token': 'tok'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(await auth.pollForToken(device), 'tok');
|
||||||
|
expect(calls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('obeys slow_down by taking GitHub s new interval', () async {
|
||||||
|
var calls = 0;
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient((_) async {
|
||||||
|
calls += 1;
|
||||||
|
return http.Response(
|
||||||
|
calls == 1
|
||||||
|
? jsonEncode({'error': 'slow_down', 'interval': 30})
|
||||||
|
: jsonEncode({'access_token': 'tok'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(await auth.pollForToken(device), 'tok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('slow_down without an interval still backs off', () async {
|
||||||
|
var calls = 0;
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient((_) async {
|
||||||
|
calls += 1;
|
||||||
|
return http.Response(
|
||||||
|
calls == 1
|
||||||
|
? jsonEncode({'error': 'slow_down'})
|
||||||
|
: jsonEncode({'access_token': 'tok'}),
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(await auth.pollForToken(device), 'tok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws on a terminal error', () async {
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient(
|
||||||
|
(_) async => http.Response(
|
||||||
|
jsonEncode({
|
||||||
|
'error': 'access_denied',
|
||||||
|
'error_description': 'user said no',
|
||||||
|
}),
|
||||||
|
200,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await expectLater(
|
||||||
|
auth.pollForToken(device),
|
||||||
|
throwsA(
|
||||||
|
isA<DeviceAuthException>()
|
||||||
|
.having((e) => e.code, 'code', 'access_denied')
|
||||||
|
.having((e) => e.message, 'message', 'user said no'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('falls back to the code when no description is given', () async {
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient(
|
||||||
|
(_) async => http.Response(jsonEncode({'error': 'expired'}), 200),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await expectLater(
|
||||||
|
auth.pollForToken(device),
|
||||||
|
throwsA(
|
||||||
|
isA<DeviceAuthException>().having((e) => e.message, 'msg', 'expired'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('throws on a response with neither a token nor an error', () async {
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient((_) async => http.Response(jsonEncode({'x': 1}), 200)),
|
||||||
|
);
|
||||||
|
await expectLater(
|
||||||
|
auth.pollForToken(device),
|
||||||
|
throwsA(
|
||||||
|
isA<DeviceAuthException>().having((e) => e.code, 'code', 'unknown'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('retries a transient network failure instead of giving up', () async {
|
||||||
|
// GitHub can close the connection at the moment the user authorizes,
|
||||||
|
// and a phone can drop its network mid-poll. Losing an approved grant
|
||||||
|
// to a socket blip is the bug this retry exists to prevent.
|
||||||
|
var calls = 0;
|
||||||
|
final auth = authWith(
|
||||||
|
MockClient((_) async {
|
||||||
|
calls += 1;
|
||||||
|
if (calls == 1) {
|
||||||
|
throw http.ClientException('Connection closed before full header');
|
||||||
|
}
|
||||||
|
return http.Response(jsonEncode({'access_token': 'tok'}), 200);
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(await auth.pollForToken(device), 'tok');
|
||||||
|
expect(calls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('gives up once the device code has expired', () async {
|
||||||
|
const expired = DeviceCodeResponse(
|
||||||
|
deviceCode: 'dc',
|
||||||
|
userCode: 'UC',
|
||||||
|
verificationUri: 'u',
|
||||||
|
interval: 1,
|
||||||
|
// Already in the past, so the loop body never runs.
|
||||||
|
expiresIn: -1,
|
||||||
|
);
|
||||||
|
final auth = authWith(MockClient((_) async => http.Response('{}', 200)));
|
||||||
|
await expectLater(
|
||||||
|
auth.pollForToken(expired),
|
||||||
|
throwsA(
|
||||||
|
isA<DeviceAuthException>().having(
|
||||||
|
(e) => e.code,
|
||||||
|
'code',
|
||||||
|
'expired_token',
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('close() is safe to call', () {
|
||||||
|
authWith(MockClient((_) async => http.Response('{}', 200))).close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('constructs with a real http client and default scope', () {
|
||||||
|
final auth = GitHubDeviceAuth(clientId: 'cid')..close();
|
||||||
|
expect(auth.scope, 'repo');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('polls the overridden token endpoint', () async {
|
||||||
|
late Uri seen;
|
||||||
|
final auth = GitHubDeviceAuth(
|
||||||
|
clientId: 'cid',
|
||||||
|
tokenUrl: 'http://127.0.0.1:9/gh/auth/device/poll',
|
||||||
|
httpClient: MockClient((req) async {
|
||||||
|
seen = req.url;
|
||||||
|
return http.Response(jsonEncode({'access_token': 'tok'}), 200);
|
||||||
|
}),
|
||||||
|
delay: noDelay,
|
||||||
|
);
|
||||||
|
|
||||||
|
await auth.pollForToken(
|
||||||
|
const DeviceCodeResponse(
|
||||||
|
deviceCode: 'dc',
|
||||||
|
userCode: 'UC',
|
||||||
|
verificationUri: 'u',
|
||||||
|
interval: 1,
|
||||||
|
expiresIn: 60,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(seen.toString(), 'http://127.0.0.1:9/gh/auth/device/poll');
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -125,183 +125,4 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
group('pollForToken', () {
|
|
||||||
const device = DeviceCodeResponse(
|
|
||||||
deviceCode: 'dc',
|
|
||||||
userCode: 'UC',
|
|
||||||
verificationUri: 'u',
|
|
||||||
interval: 1,
|
|
||||||
expiresIn: 60,
|
|
||||||
);
|
|
||||||
|
|
||||||
test('returns the token once the user authorizes', () async {
|
|
||||||
var calls = 0;
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient((_) async {
|
|
||||||
calls += 1;
|
|
||||||
// First poll pending, second succeeds -- the normal path.
|
|
||||||
return http.Response(
|
|
||||||
calls == 1
|
|
||||||
? jsonEncode({'error': 'authorization_pending'})
|
|
||||||
: jsonEncode({'access_token': 'tok'}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(await auth.pollForToken(device), 'tok');
|
|
||||||
expect(calls, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('obeys slow_down by taking GitHub s new interval', () async {
|
|
||||||
var calls = 0;
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient((_) async {
|
|
||||||
calls += 1;
|
|
||||||
return http.Response(
|
|
||||||
calls == 1
|
|
||||||
? jsonEncode({'error': 'slow_down', 'interval': 30})
|
|
||||||
: jsonEncode({'access_token': 'tok'}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(await auth.pollForToken(device), 'tok');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('slow_down without an interval still backs off', () async {
|
|
||||||
var calls = 0;
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient((_) async {
|
|
||||||
calls += 1;
|
|
||||||
return http.Response(
|
|
||||||
calls == 1
|
|
||||||
? jsonEncode({'error': 'slow_down'})
|
|
||||||
: jsonEncode({'access_token': 'tok'}),
|
|
||||||
200,
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(await auth.pollForToken(device), 'tok');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('throws on a terminal error', () async {
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient(
|
|
||||||
(_) async => http.Response(
|
|
||||||
jsonEncode({
|
|
||||||
'error': 'access_denied',
|
|
||||||
'error_description': 'user said no',
|
|
||||||
}),
|
|
||||||
200,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await expectLater(
|
|
||||||
auth.pollForToken(device),
|
|
||||||
throwsA(
|
|
||||||
isA<DeviceAuthException>()
|
|
||||||
.having((e) => e.code, 'code', 'access_denied')
|
|
||||||
.having((e) => e.message, 'message', 'user said no'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('falls back to the code when no description is given', () async {
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient(
|
|
||||||
(_) async => http.Response(jsonEncode({'error': 'expired'}), 200),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await expectLater(
|
|
||||||
auth.pollForToken(device),
|
|
||||||
throwsA(
|
|
||||||
isA<DeviceAuthException>().having((e) => e.message, 'msg', 'expired'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('throws on a response with neither a token nor an error', () async {
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient((_) async => http.Response(jsonEncode({'x': 1}), 200)),
|
|
||||||
);
|
|
||||||
await expectLater(
|
|
||||||
auth.pollForToken(device),
|
|
||||||
throwsA(
|
|
||||||
isA<DeviceAuthException>().having((e) => e.code, 'code', 'unknown'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('retries a transient network failure instead of giving up', () async {
|
|
||||||
// GitHub can close the connection at the moment the user authorizes,
|
|
||||||
// and a phone can drop its network mid-poll. Losing an approved grant
|
|
||||||
// to a socket blip is the bug this retry exists to prevent.
|
|
||||||
var calls = 0;
|
|
||||||
final auth = authWith(
|
|
||||||
MockClient((_) async {
|
|
||||||
calls += 1;
|
|
||||||
if (calls == 1) {
|
|
||||||
throw http.ClientException('Connection closed before full header');
|
|
||||||
}
|
|
||||||
return http.Response(jsonEncode({'access_token': 'tok'}), 200);
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
expect(await auth.pollForToken(device), 'tok');
|
|
||||||
expect(calls, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('gives up once the device code has expired', () async {
|
|
||||||
const expired = DeviceCodeResponse(
|
|
||||||
deviceCode: 'dc',
|
|
||||||
userCode: 'UC',
|
|
||||||
verificationUri: 'u',
|
|
||||||
interval: 1,
|
|
||||||
// Already in the past, so the loop body never runs.
|
|
||||||
expiresIn: -1,
|
|
||||||
);
|
|
||||||
final auth = authWith(MockClient((_) async => http.Response('{}', 200)));
|
|
||||||
await expectLater(
|
|
||||||
auth.pollForToken(expired),
|
|
||||||
throwsA(
|
|
||||||
isA<DeviceAuthException>()
|
|
||||||
.having((e) => e.code, 'code', 'expired_token'),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test('close() is safe to call', () {
|
|
||||||
authWith(MockClient((_) async => http.Response('{}', 200))).close();
|
|
||||||
});
|
|
||||||
|
|
||||||
test('constructs with a real http client and default scope', () {
|
|
||||||
final auth = GitHubDeviceAuth(clientId: 'cid')..close();
|
|
||||||
expect(auth.scope, 'repo');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('polls the overridden token endpoint', () async {
|
|
||||||
late Uri seen;
|
|
||||||
final auth = GitHubDeviceAuth(
|
|
||||||
clientId: 'cid',
|
|
||||||
tokenUrl: 'http://127.0.0.1:9/gh/auth/device/poll',
|
|
||||||
httpClient: MockClient((req) async {
|
|
||||||
seen = req.url;
|
|
||||||
return http.Response(jsonEncode({'access_token': 'tok'}), 200);
|
|
||||||
}),
|
|
||||||
delay: noDelay,
|
|
||||||
);
|
|
||||||
|
|
||||||
await auth.pollForToken(
|
|
||||||
const DeviceCodeResponse(
|
|
||||||
deviceCode: 'dc',
|
|
||||||
userCode: 'UC',
|
|
||||||
verificationUri: 'u',
|
|
||||||
interval: 1,
|
|
||||||
expiresIn: 60,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
expect(seen.toString(), 'http://127.0.0.1:9/gh/auth/device/poll');
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,6 +18,8 @@ fi
|
|||||||
source "$LIB_DIR/common.sh"
|
source "$LIB_DIR/common.sh"
|
||||||
# shellcheck source=lib/file_guard.sh
|
# shellcheck source=lib/file_guard.sh
|
||||||
source "$LIB_DIR/file_guard.sh"
|
source "$LIB_DIR/file_guard.sh"
|
||||||
|
# shellcheck source=lib/file_guard_unlock.sh
|
||||||
|
source "$LIB_DIR/file_guard_unlock.sh"
|
||||||
# shellcheck source=lib/package_block.sh
|
# shellcheck source=lib/package_block.sh
|
||||||
source "$LIB_DIR/package_block.sh"
|
source "$LIB_DIR/package_block.sh"
|
||||||
|
|
||||||
|
|||||||
@ -138,213 +138,3 @@ fg_enforce() {
|
|||||||
[[ "$BIND_MOUNT" == "yes" ]] && _reapply_bind_mount "$name"
|
[[ "$BIND_MOUNT" == "yes" ]] && _reapply_bind_mount "$name"
|
||||||
log_hook "file-guard $name: enforce ok"
|
log_hook "file-guard $name: enforce ok"
|
||||||
}
|
}
|
||||||
|
|
||||||
fg_unlock() {
|
|
||||||
local name="$1"
|
|
||||||
require_root
|
|
||||||
load_target_conf "$name"
|
|
||||||
# shellcheck disable=SC2153 # PLUGIN set by load_target_conf, not a typo
|
|
||||||
load_plugin "$PLUGIN"
|
|
||||||
echo "About to unlock file-guard '$name' ($TARGET) for editing."
|
|
||||||
read -rp "Reason for unlocking: " reason
|
|
||||||
[[ -n "$reason" ]] || die "a reason is required"
|
|
||||||
log_hook "file-guard $name: UNLOCK requested by ${SUDO_USER:-$(whoami)}: $reason"
|
|
||||||
echo "Unlocking in 45s (Ctrl-C to abort)..."
|
|
||||||
sleep 45
|
|
||||||
# Stop the watcher before unlocking: chattr alone (no content write)
|
|
||||||
# fires PathModified, and the resulting enforce pass unconditionally
|
|
||||||
# re-locks the target even with no drift - which would silently
|
|
||||||
# re-lock this file out from under the editor. Confirmed live during
|
|
||||||
# the shutdown-schedule migration (see guard-lib project notes).
|
|
||||||
systemctl stop "guard-file@${name}.path" 2>/dev/null || true
|
|
||||||
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
|
||||||
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
|
||||||
unlock_file "$TARGET"
|
|
||||||
log_hook "file-guard $name: unlocked for editing"
|
|
||||||
|
|
||||||
local before after
|
|
||||||
before="$(sha256sum "$TARGET" 2>/dev/null | awk '{print $1}')"
|
|
||||||
# Deliberately unquoted: $EDITOR commonly carries arguments (e.g.
|
|
||||||
# "code --wait", "emacsclient -t") that must be word-split.
|
|
||||||
${EDITOR:-vi} "$TARGET"
|
|
||||||
after="$(sha256sum "$TARGET" 2>/dev/null | awk '{print $1}')"
|
|
||||||
|
|
||||||
if [[ "$before" != "$after" ]]; then
|
|
||||||
if declare -f validate >/dev/null 2>&1 && ! validate "$TARGET"; then
|
|
||||||
echo "New content fails this instance's validate() check - reverting your edit; canonical unchanged." >&2
|
|
||||||
log_hook "file-guard $name: edit REJECTED (failed validate), reverting to canonical"
|
|
||||||
[[ -e "$CANONICAL" ]] && cp --preserve=mode,ownership,timestamps "$CANONICAL" "$TARGET"
|
|
||||||
else
|
|
||||||
# Update canonical to match: without this, re-locking below
|
|
||||||
# fires the watcher, which would see the new content as
|
|
||||||
# "drift" against the stale canonical and silently revert
|
|
||||||
# this legitimate edit.
|
|
||||||
log_hook "file-guard $name: content changed, updating canonical"
|
|
||||||
unlock_file "$CANONICAL"
|
|
||||||
cp --preserve=mode,ownership,timestamps "$TARGET" "$CANONICAL"
|
|
||||||
lock_file "$CANONICAL"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
log_hook "file-guard $name: no content change"
|
|
||||||
fi
|
|
||||||
|
|
||||||
lock_file "$TARGET"
|
|
||||||
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
|
||||||
[[ "$BIND_MOUNT" == "yes" ]] && _reapply_bind_mount "$name"
|
|
||||||
systemctl start "guard-file@${name}.path" 2>/dev/null || true
|
|
||||||
log_hook "file-guard $name: re-locked after edit"
|
|
||||||
echo "Re-locked '$name'."
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_uninstall() {
|
|
||||||
local name="$1"
|
|
||||||
shift
|
|
||||||
local keep_canonical=0
|
|
||||||
while [[ $# -gt 0 ]]; do
|
|
||||||
case "$1" in
|
|
||||||
--keep-canonical) keep_canonical=1; shift ;;
|
|
||||||
*) die "file-guard uninstall: unknown argument '$1'" ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
require_root
|
|
||||||
load_target_conf "$name"
|
|
||||||
systemctl disable --now "guard-file@$name.path" 2>/dev/null || true
|
|
||||||
systemctl disable --now "guard-bind-mount@$name.service" 2>/dev/null || true
|
|
||||||
rm -rf "${GUARD_LIB_SYSTEMD_DIR:?}/guard-file@$name.path.d"
|
|
||||||
systemctl daemon-reload
|
|
||||||
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
|
||||||
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
|
||||||
unlock_file "$TARGET"
|
|
||||||
if [[ "$keep_canonical" -eq 0 ]]; then
|
|
||||||
unlock_file "$CANONICAL"
|
|
||||||
rm -f "$CANONICAL"
|
|
||||||
fi
|
|
||||||
rm -f "$(target_conf_path "$name")"
|
|
||||||
log_hook "file-guard $name: uninstalled (keep_canonical=$keep_canonical)"
|
|
||||||
echo "uninstalled file-guard '$name'"
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_status() {
|
|
||||||
local name="$1"
|
|
||||||
load_target_conf "$name"
|
|
||||||
echo "name: $name"
|
|
||||||
echo "target: $TARGET"
|
|
||||||
echo "canonical: $CANONICAL"
|
|
||||||
# shellcheck disable=SC2153 # BIND_MOUNT/PLUGIN/ALSO_WATCH set by load_target_conf, not typos
|
|
||||||
echo "bind_mount: $BIND_MOUNT"
|
|
||||||
echo "plugin: ${PLUGIN:-<none>}"
|
|
||||||
echo "also_watch: ${ALSO_WATCH:-<none>}"
|
|
||||||
if [[ -e "$TARGET" ]]; then
|
|
||||||
local attrs
|
|
||||||
attrs="$(lsattr "$TARGET" 2>/dev/null | awk '{print $1}')"
|
|
||||||
echo "target attrs: ${attrs:-unknown}"
|
|
||||||
else
|
|
||||||
echo "target: MISSING"
|
|
||||||
fi
|
|
||||||
local unit_state
|
|
||||||
unit_state="$(systemctl is-active "guard-file@$name.path" 2>/dev/null || true)"
|
|
||||||
echo "path unit: ${unit_state:-unknown}"
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_canonical_path() {
|
|
||||||
# Machine-readable single-value output: the canonical path for an
|
|
||||||
# instance, so consumers with bespoke unlock flows (that can't go
|
|
||||||
# through `unlock`/`enforce` directly) don't have to hardcode or
|
|
||||||
# duplicate guard-lib's canonical-path convention.
|
|
||||||
local name="$1"
|
|
||||||
load_target_conf "$name"
|
|
||||||
echo "$CANONICAL"
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_pacman_unlock() {
|
|
||||||
# Quiet, non-interactive unlock used only by the generic pacman
|
|
||||||
# PreTransaction hook - no typed reason, no editor. The pacman
|
|
||||||
# transaction itself is the sanctioned reason.
|
|
||||||
#
|
|
||||||
# Stops the path unit, not just chattr -i's the target: chattr alone
|
|
||||||
# fires PathModified, and if the watcher's enforce pass wins the race
|
|
||||||
# against pacman's own write, it silently re-locks the file before
|
|
||||||
# pacman gets to it, breaking the very transaction this hook exists
|
|
||||||
# to allow. Matches the pre-existing hosts-guard pacman hooks, which
|
|
||||||
# stop hosts-guard.path/nsswitch-guard.path/resolved-guard.path for
|
|
||||||
# the same reason.
|
|
||||||
local name="$1"
|
|
||||||
load_target_conf "$name"
|
|
||||||
systemctl stop "guard-file@${name}.path" 2>/dev/null || true
|
|
||||||
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
|
||||||
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
|
||||||
unlock_file "$TARGET"
|
|
||||||
log_hook "file-guard $name: pacman-unlock (pre-transaction)"
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_pacman_relock() {
|
|
||||||
# Counterpart to fg_pacman_unlock, used only by the generic pacman
|
|
||||||
# PostTransaction hook: re-enforce (drift-restore + chattr +i, and -
|
|
||||||
# if this instance is bind-mounted - re-establish the read-only
|
|
||||||
# bind mount, since fg_enforce does that itself now) then restart
|
|
||||||
# the path unit that pacman-unlock stopped.
|
|
||||||
local name="$1"
|
|
||||||
fg_enforce "$name"
|
|
||||||
systemctl start "guard-file@${name}.path" 2>/dev/null || true
|
|
||||||
log_hook "file-guard $name: pacman-relock (post-transaction)"
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_sync_canonical() {
|
|
||||||
# Counterpart to fg_pacman_unlock for callers that legitimately EDITED
|
|
||||||
# the target (not pacman's own hook flow, which wants drift reverted).
|
|
||||||
# Adopts the target's current content as the new canonical, instead of
|
|
||||||
# fg_enforce's drift-check-and-revert - which would otherwise silently
|
|
||||||
# undo the very edit the caller just made. Assumes the watcher was
|
|
||||||
# already stopped by a prior fg_pacman_unlock; does not stop it itself.
|
|
||||||
local name="$1"
|
|
||||||
load_target_conf "$name"
|
|
||||||
snapshot_canonical "$name"
|
|
||||||
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
|
||||||
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
|
||||||
unlock_file "$TARGET"
|
|
||||||
lock_file "$TARGET"
|
|
||||||
[[ "$BIND_MOUNT" == "yes" ]] && _reapply_bind_mount "$name"
|
|
||||||
systemctl start "guard-file@${name}.path" 2>/dev/null || true
|
|
||||||
log_hook "file-guard $name: synced canonical to current content"
|
|
||||||
}
|
|
||||||
|
|
||||||
# Self-bind-mounts TARGET over itself, then remounts that layer
|
|
||||||
# read-only. This is a mount-level lock independent of chattr: even a
|
|
||||||
# successful `chattr -i` bypass still can't write through a read-only
|
|
||||||
# mount. Deliberately does NOT bind CANONICAL over TARGET - that would
|
|
||||||
# merge them onto the same inode, so chattr/writes to either would hit
|
|
||||||
# both and "restore from canonical" would become meaningless.
|
|
||||||
_reapply_bind_mount() {
|
|
||||||
local name="$1"
|
|
||||||
if mountpoint -q "$TARGET" 2>/dev/null; then
|
|
||||||
return 0
|
|
||||||
fi
|
|
||||||
mount --bind "$TARGET" "$TARGET"
|
|
||||||
mount -o remount,ro,bind "$TARGET"
|
|
||||||
log_hook "file-guard $name: bind-mounted $TARGET read-only"
|
|
||||||
}
|
|
||||||
|
|
||||||
fg_bind_mount() {
|
|
||||||
local name="$1"
|
|
||||||
require_root
|
|
||||||
load_target_conf "$name"
|
|
||||||
_reapply_bind_mount "$name"
|
|
||||||
}
|
|
||||||
|
|
||||||
file_guard_main() {
|
|
||||||
local sub="$1"
|
|
||||||
shift || true
|
|
||||||
case "$sub" in
|
|
||||||
install) fg_install "$@" ;;
|
|
||||||
enforce) fg_enforce "$@" ;;
|
|
||||||
unlock) fg_unlock "$@" ;;
|
|
||||||
pacman-unlock) fg_pacman_unlock "$@" ;;
|
|
||||||
uninstall) fg_uninstall "$@" ;;
|
|
||||||
status) fg_status "$@" ;;
|
|
||||||
canonical-path) fg_canonical_path "$@" ;;
|
|
||||||
bind-mount) fg_bind_mount "$@" ;;
|
|
||||||
pacman-relock) fg_pacman_relock "$@" ;;
|
|
||||||
sync) fg_sync_canonical "$@" ;;
|
|
||||||
*) die "file-guard: unknown subcommand '$sub' (expected install|enforce|unlock|pacman-unlock|pacman-relock|sync|uninstall|status|canonical-path|bind-mount)" ;;
|
|
||||||
esac
|
|
||||||
}
|
|
||||||
|
|||||||
214
guard-lib/lib/file_guard_unlock.sh
Normal file
214
guard-lib/lib/file_guard_unlock.sh
Normal file
@ -0,0 +1,214 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# guardctl file-guard unlocking, pacman coordination and dispatch.
|
||||||
|
# Split from file_guard.sh for the shared 250-line cap; sourced by
|
||||||
|
# guardctl right after it, never executed directly.
|
||||||
|
|
||||||
|
fg_unlock() {
|
||||||
|
local name="$1"
|
||||||
|
require_root
|
||||||
|
load_target_conf "$name"
|
||||||
|
# shellcheck disable=SC2153 # PLUGIN set by load_target_conf, not a typo
|
||||||
|
load_plugin "$PLUGIN"
|
||||||
|
echo "About to unlock file-guard '$name' ($TARGET) for editing."
|
||||||
|
read -rp "Reason for unlocking: " reason
|
||||||
|
[[ -n "$reason" ]] || die "a reason is required"
|
||||||
|
log_hook "file-guard $name: UNLOCK requested by ${SUDO_USER:-$(whoami)}: $reason"
|
||||||
|
echo "Unlocking in 45s (Ctrl-C to abort)..."
|
||||||
|
sleep 45
|
||||||
|
# Stop the watcher before unlocking: chattr alone (no content write)
|
||||||
|
# fires PathModified, and the resulting enforce pass unconditionally
|
||||||
|
# re-locks the target even with no drift - which would silently
|
||||||
|
# re-lock this file out from under the editor. Confirmed live during
|
||||||
|
# the shutdown-schedule migration (see guard-lib project notes).
|
||||||
|
systemctl stop "guard-file@${name}.path" 2>/dev/null || true
|
||||||
|
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
||||||
|
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
||||||
|
unlock_file "$TARGET"
|
||||||
|
log_hook "file-guard $name: unlocked for editing"
|
||||||
|
|
||||||
|
local before after
|
||||||
|
before="$(sha256sum "$TARGET" 2>/dev/null | awk '{print $1}')"
|
||||||
|
# Deliberately unquoted: $EDITOR commonly carries arguments (e.g.
|
||||||
|
# "code --wait", "emacsclient -t") that must be word-split.
|
||||||
|
${EDITOR:-vi} "$TARGET"
|
||||||
|
after="$(sha256sum "$TARGET" 2>/dev/null | awk '{print $1}')"
|
||||||
|
|
||||||
|
if [[ "$before" != "$after" ]]; then
|
||||||
|
if declare -f validate >/dev/null 2>&1 && ! validate "$TARGET"; then
|
||||||
|
echo "New content fails this instance's validate() check - reverting your edit; canonical unchanged." >&2
|
||||||
|
log_hook "file-guard $name: edit REJECTED (failed validate), reverting to canonical"
|
||||||
|
[[ -e "$CANONICAL" ]] && cp --preserve=mode,ownership,timestamps "$CANONICAL" "$TARGET"
|
||||||
|
else
|
||||||
|
# Update canonical to match: without this, re-locking below
|
||||||
|
# fires the watcher, which would see the new content as
|
||||||
|
# "drift" against the stale canonical and silently revert
|
||||||
|
# this legitimate edit.
|
||||||
|
log_hook "file-guard $name: content changed, updating canonical"
|
||||||
|
unlock_file "$CANONICAL"
|
||||||
|
cp --preserve=mode,ownership,timestamps "$TARGET" "$CANONICAL"
|
||||||
|
lock_file "$CANONICAL"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
log_hook "file-guard $name: no content change"
|
||||||
|
fi
|
||||||
|
|
||||||
|
lock_file "$TARGET"
|
||||||
|
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
||||||
|
[[ "$BIND_MOUNT" == "yes" ]] && _reapply_bind_mount "$name"
|
||||||
|
systemctl start "guard-file@${name}.path" 2>/dev/null || true
|
||||||
|
log_hook "file-guard $name: re-locked after edit"
|
||||||
|
echo "Re-locked '$name'."
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_uninstall() {
|
||||||
|
local name="$1"
|
||||||
|
shift
|
||||||
|
local keep_canonical=0
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--keep-canonical) keep_canonical=1; shift ;;
|
||||||
|
*) die "file-guard uninstall: unknown argument '$1'" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
require_root
|
||||||
|
load_target_conf "$name"
|
||||||
|
systemctl disable --now "guard-file@$name.path" 2>/dev/null || true
|
||||||
|
systemctl disable --now "guard-bind-mount@$name.service" 2>/dev/null || true
|
||||||
|
rm -rf "${GUARD_LIB_SYSTEMD_DIR:?}/guard-file@$name.path.d"
|
||||||
|
systemctl daemon-reload
|
||||||
|
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
||||||
|
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
||||||
|
unlock_file "$TARGET"
|
||||||
|
if [[ "$keep_canonical" -eq 0 ]]; then
|
||||||
|
unlock_file "$CANONICAL"
|
||||||
|
rm -f "$CANONICAL"
|
||||||
|
fi
|
||||||
|
rm -f "$(target_conf_path "$name")"
|
||||||
|
log_hook "file-guard $name: uninstalled (keep_canonical=$keep_canonical)"
|
||||||
|
echo "uninstalled file-guard '$name'"
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_status() {
|
||||||
|
local name="$1"
|
||||||
|
load_target_conf "$name"
|
||||||
|
echo "name: $name"
|
||||||
|
echo "target: $TARGET"
|
||||||
|
echo "canonical: $CANONICAL"
|
||||||
|
# shellcheck disable=SC2153 # BIND_MOUNT/PLUGIN/ALSO_WATCH set by load_target_conf, not typos
|
||||||
|
echo "bind_mount: $BIND_MOUNT"
|
||||||
|
echo "plugin: ${PLUGIN:-<none>}"
|
||||||
|
echo "also_watch: ${ALSO_WATCH:-<none>}"
|
||||||
|
if [[ -e "$TARGET" ]]; then
|
||||||
|
local attrs
|
||||||
|
attrs="$(lsattr "$TARGET" 2>/dev/null | awk '{print $1}')"
|
||||||
|
echo "target attrs: ${attrs:-unknown}"
|
||||||
|
else
|
||||||
|
echo "target: MISSING"
|
||||||
|
fi
|
||||||
|
local unit_state
|
||||||
|
unit_state="$(systemctl is-active "guard-file@$name.path" 2>/dev/null || true)"
|
||||||
|
echo "path unit: ${unit_state:-unknown}"
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_canonical_path() {
|
||||||
|
# Machine-readable single-value output: the canonical path for an
|
||||||
|
# instance, so consumers with bespoke unlock flows (that can't go
|
||||||
|
# through `unlock`/`enforce` directly) don't have to hardcode or
|
||||||
|
# duplicate guard-lib's canonical-path convention.
|
||||||
|
local name="$1"
|
||||||
|
load_target_conf "$name"
|
||||||
|
echo "$CANONICAL"
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_pacman_unlock() {
|
||||||
|
# Quiet, non-interactive unlock used only by the generic pacman
|
||||||
|
# PreTransaction hook - no typed reason, no editor. The pacman
|
||||||
|
# transaction itself is the sanctioned reason.
|
||||||
|
#
|
||||||
|
# Stops the path unit, not just chattr -i's the target: chattr alone
|
||||||
|
# fires PathModified, and if the watcher's enforce pass wins the race
|
||||||
|
# against pacman's own write, it silently re-locks the file before
|
||||||
|
# pacman gets to it, breaking the very transaction this hook exists
|
||||||
|
# to allow. Matches the pre-existing hosts-guard pacman hooks, which
|
||||||
|
# stop hosts-guard.path/nsswitch-guard.path/resolved-guard.path for
|
||||||
|
# the same reason.
|
||||||
|
local name="$1"
|
||||||
|
load_target_conf "$name"
|
||||||
|
systemctl stop "guard-file@${name}.path" 2>/dev/null || true
|
||||||
|
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
||||||
|
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
||||||
|
unlock_file "$TARGET"
|
||||||
|
log_hook "file-guard $name: pacman-unlock (pre-transaction)"
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_pacman_relock() {
|
||||||
|
# Counterpart to fg_pacman_unlock, used only by the generic pacman
|
||||||
|
# PostTransaction hook: re-enforce (drift-restore + chattr +i, and -
|
||||||
|
# if this instance is bind-mounted - re-establish the read-only
|
||||||
|
# bind mount, since fg_enforce does that itself now) then restart
|
||||||
|
# the path unit that pacman-unlock stopped.
|
||||||
|
local name="$1"
|
||||||
|
fg_enforce "$name"
|
||||||
|
systemctl start "guard-file@${name}.path" 2>/dev/null || true
|
||||||
|
log_hook "file-guard $name: pacman-relock (post-transaction)"
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_sync_canonical() {
|
||||||
|
# Counterpart to fg_pacman_unlock for callers that legitimately EDITED
|
||||||
|
# the target (not pacman's own hook flow, which wants drift reverted).
|
||||||
|
# Adopts the target's current content as the new canonical, instead of
|
||||||
|
# fg_enforce's drift-check-and-revert - which would otherwise silently
|
||||||
|
# undo the very edit the caller just made. Assumes the watcher was
|
||||||
|
# already stopped by a prior fg_pacman_unlock; does not stop it itself.
|
||||||
|
local name="$1"
|
||||||
|
load_target_conf "$name"
|
||||||
|
snapshot_canonical "$name"
|
||||||
|
# shellcheck disable=SC2153 # BIND_MOUNT set by load_target_conf, not a typo
|
||||||
|
[[ "$BIND_MOUNT" == "yes" ]] && collapse_bind_mount "$TARGET"
|
||||||
|
unlock_file "$TARGET"
|
||||||
|
lock_file "$TARGET"
|
||||||
|
[[ "$BIND_MOUNT" == "yes" ]] && _reapply_bind_mount "$name"
|
||||||
|
systemctl start "guard-file@${name}.path" 2>/dev/null || true
|
||||||
|
log_hook "file-guard $name: synced canonical to current content"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Self-bind-mounts TARGET over itself, then remounts that layer
|
||||||
|
# read-only. This is a mount-level lock independent of chattr: even a
|
||||||
|
# successful `chattr -i` bypass still can't write through a read-only
|
||||||
|
# mount. Deliberately does NOT bind CANONICAL over TARGET - that would
|
||||||
|
# merge them onto the same inode, so chattr/writes to either would hit
|
||||||
|
# both and "restore from canonical" would become meaningless.
|
||||||
|
_reapply_bind_mount() {
|
||||||
|
local name="$1"
|
||||||
|
if mountpoint -q "$TARGET" 2>/dev/null; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
mount --bind "$TARGET" "$TARGET"
|
||||||
|
mount -o remount,ro,bind "$TARGET"
|
||||||
|
log_hook "file-guard $name: bind-mounted $TARGET read-only"
|
||||||
|
}
|
||||||
|
|
||||||
|
fg_bind_mount() {
|
||||||
|
local name="$1"
|
||||||
|
require_root
|
||||||
|
load_target_conf "$name"
|
||||||
|
_reapply_bind_mount "$name"
|
||||||
|
}
|
||||||
|
|
||||||
|
file_guard_main() {
|
||||||
|
local sub="$1"
|
||||||
|
shift || true
|
||||||
|
case "$sub" in
|
||||||
|
install) fg_install "$@" ;;
|
||||||
|
enforce) fg_enforce "$@" ;;
|
||||||
|
unlock) fg_unlock "$@" ;;
|
||||||
|
pacman-unlock) fg_pacman_unlock "$@" ;;
|
||||||
|
uninstall) fg_uninstall "$@" ;;
|
||||||
|
status) fg_status "$@" ;;
|
||||||
|
canonical-path) fg_canonical_path "$@" ;;
|
||||||
|
bind-mount) fg_bind_mount "$@" ;;
|
||||||
|
pacman-relock) fg_pacman_relock "$@" ;;
|
||||||
|
sync) fg_sync_canonical "$@" ;;
|
||||||
|
*) die "file-guard: unknown subcommand '$sub' (expected install|enforce|unlock|pacman-unlock|pacman-relock|sync|uninstall|status|canonical-path|bind-mount)" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
143
sync_settings_ui/test/sync_settings_screen_backup_test.dart
Normal file
143
sync_settings_ui/test/sync_settings_screen_backup_test.dart
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
|
||||||
|
FirebaseRestClient _fakeClient() => FirebaseRestClient(
|
||||||
|
databaseUrl: 'https://example.firebasedatabase.app',
|
||||||
|
auth: FirebaseTokenProvider(
|
||||||
|
apiKey: 'test-key',
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _wrap(Widget child) => MaterialApp(home: child);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('Backup section', () {
|
||||||
|
testWidgets('omitted entirely when backup is null', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Backup'), findsNothing);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('export and import call the injected callbacks', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
var exported = false;
|
||||||
|
var imported = false;
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
backup: BackupSlot(
|
||||||
|
label: 'notes',
|
||||||
|
export: () async => exported = true,
|
||||||
|
import: () async => imported = true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Backup'), findsOneWidget);
|
||||||
|
await tester.tap(find.text('Export notes'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(exported, isTrue);
|
||||||
|
expect(find.text('Exported notes.'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(imported, isTrue);
|
||||||
|
expect(find.text('Imported notes.'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('export failure reports the error', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
backup: BackupSlot(
|
||||||
|
label: 'notes',
|
||||||
|
export: () async => throw Exception('disk full'),
|
||||||
|
import: () async {},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Export notes'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('Export failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('import failure reports the error', (tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
backup: BackupSlot(
|
||||||
|
label: 'notes',
|
||||||
|
export: () async {},
|
||||||
|
import: () async => throw Exception('corrupt file'),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Import notes'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.textContaining('Import failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('shows a loading indicator until initial load completes', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final completer = Completer<FirebaseAccount?>();
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () => completer.future,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
||||||
|
|
||||||
|
completer.complete(null);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||||
|
});
|
||||||
|
}
|
||||||
145
sync_settings_ui/test/sync_settings_screen_google_test.dart
Normal file
145
sync_settings_ui/test/sync_settings_screen_google_test.dart
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:crdt_sync/crdt_sync.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:sync_settings_ui/sync_settings_ui.dart';
|
||||||
|
|
||||||
|
FirebaseRestClient _fakeClient() => FirebaseRestClient(
|
||||||
|
databaseUrl: 'https://example.firebasedatabase.app',
|
||||||
|
auth: FirebaseTokenProvider(
|
||||||
|
apiKey: 'test-key',
|
||||||
|
store: InMemoryCredentialStore(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
Widget _wrap(Widget child) => MaterialApp(home: child);
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('Firebase section Google sign-in', () {
|
||||||
|
testWidgets('Google sign-in cancelled shows the cancellation message', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
googleFirebaseFactory: () async => null,
|
||||||
|
googleAvailable: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sign in with Google'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Google sign-in was cancelled.'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'Google sign-in that does not persist a session reports the retry '
|
||||||
|
'message',
|
||||||
|
(tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
googleFirebaseFactory: () async => _fakeClient(),
|
||||||
|
googleAvailable: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sign in with Google'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
find.textContaining('did not save the session'),
|
||||||
|
findsOneWidget,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
testWidgets('Google sign-in wrong-account error surfaces the message', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
googleFirebaseFactory: () async =>
|
||||||
|
throw FirebaseAuthError('wrong uid'),
|
||||||
|
googleAvailable: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sign in with Google'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('wrong uid'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('Google sign-in generic failure surfaces the error text', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
googleFirebaseFactory: () async => throw StateError('boom'),
|
||||||
|
googleAvailable: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
await tester.tap(find.text('Sign in with Google'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.textContaining('Google sign-in failed'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets(
|
||||||
|
'hides the Google button when googleAvailable is true but no '
|
||||||
|
'googleFirebaseFactory is wired -- a visible button that can never '
|
||||||
|
'succeed must not render',
|
||||||
|
(tester) async {
|
||||||
|
await tester.pumpWidget(
|
||||||
|
_wrap(
|
||||||
|
SyncSettingsScreen(
|
||||||
|
accountLoader: () async => null,
|
||||||
|
accountSaver: (_) async {},
|
||||||
|
accountClearer: () async {},
|
||||||
|
sessionProbe: () async => false,
|
||||||
|
firebaseFactory: () async => null,
|
||||||
|
googleAvailable: true,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Sign in with Google'), findsNothing);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -203,255 +203,5 @@ void main() {
|
|||||||
expect(find.text('Connected to Firebase.'), findsOneWidget);
|
expect(find.text('Connected to Firebase.'), findsOneWidget);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
testWidgets('Google sign-in cancelled shows the cancellation message', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
googleFirebaseFactory: () async => null,
|
|
||||||
googleAvailable: true,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('Google sign-in was cancelled.'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'Google sign-in that does not persist a session reports the retry '
|
|
||||||
'message',
|
|
||||||
(tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
googleFirebaseFactory: () async => _fakeClient(),
|
|
||||||
googleAvailable: true,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(
|
|
||||||
find.textContaining('did not save the session'),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
testWidgets('Google sign-in wrong-account error surfaces the message', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
googleFirebaseFactory: () async =>
|
|
||||||
throw FirebaseAuthError('wrong uid'),
|
|
||||||
googleAvailable: true,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('wrong uid'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('Google sign-in generic failure surfaces the error text', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
googleFirebaseFactory: () async => throw StateError('boom'),
|
|
||||||
googleAvailable: true,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Sign in with Google'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.textContaining('Google sign-in failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets(
|
|
||||||
'hides the Google button when googleAvailable is true but no '
|
|
||||||
'googleFirebaseFactory is wired -- a visible button that can never '
|
|
||||||
'succeed must not render',
|
|
||||||
(tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
googleAvailable: true,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('Sign in with Google'), findsNothing);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
group('Backup section', () {
|
|
||||||
testWidgets('omitted entirely when backup is null', (tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('Backup'), findsNothing);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('export and import call the injected callbacks', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
var exported = false;
|
|
||||||
var imported = false;
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
backup: BackupSlot(
|
|
||||||
label: 'notes',
|
|
||||||
export: () async => exported = true,
|
|
||||||
import: () async => imported = true,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
expect(find.text('Backup'), findsOneWidget);
|
|
||||||
await tester.tap(find.text('Export notes'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(exported, isTrue);
|
|
||||||
expect(find.text('Exported notes.'), findsOneWidget);
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(imported, isTrue);
|
|
||||||
expect(find.text('Imported notes.'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('export failure reports the error', (tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
backup: BackupSlot(
|
|
||||||
label: 'notes',
|
|
||||||
export: () async => throw Exception('disk full'),
|
|
||||||
import: () async {},
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Export notes'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.textContaining('Export failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('import failure reports the error', (tester) async {
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () async => null,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
backup: BackupSlot(
|
|
||||||
label: 'notes',
|
|
||||||
export: () async {},
|
|
||||||
import: () async => throw Exception('corrupt file'),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
|
|
||||||
await tester.tap(find.text('Import notes'));
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.textContaining('Import failed'), findsOneWidget);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
testWidgets('shows a loading indicator until initial load completes', (
|
|
||||||
tester,
|
|
||||||
) async {
|
|
||||||
final completer = Completer<FirebaseAccount?>();
|
|
||||||
await tester.pumpWidget(
|
|
||||||
_wrap(
|
|
||||||
SyncSettingsScreen(
|
|
||||||
accountLoader: () => completer.future,
|
|
||||||
accountSaver: (_) async {},
|
|
||||||
accountClearer: () async {},
|
|
||||||
sessionProbe: () async => false,
|
|
||||||
firebaseFactory: () async => null,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
await tester.pump();
|
|
||||||
expect(find.byType(CircularProgressIndicator), findsOneWidget);
|
|
||||||
|
|
||||||
completer.complete(null);
|
|
||||||
await tester.pumpAndSettle();
|
|
||||||
expect(find.byType(CircularProgressIndicator), findsNothing);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -37,7 +37,9 @@ ROOT = Path(__file__).resolve().parents[2]
|
|||||||
TOKENS_MD = ROOT / "unified-design-system" / "tokens.md"
|
TOKENS_MD = ROOT / "unified-design-system" / "tokens.md"
|
||||||
TOKENS_CSS = ROOT / "web_ui" / "src" / "tokens.css"
|
TOKENS_CSS = ROOT / "web_ui" / "src" / "tokens.css"
|
||||||
TOKENS_DART = ROOT / "design_system" / "lib" / "src" / "tokens.dart"
|
TOKENS_DART = ROOT / "design_system" / "lib" / "src" / "tokens.dart"
|
||||||
LOCKCONFIG_PY = ROOT / "gatelock" / "gatelock" / "_window.py"
|
# LockConfig moved out of _window.py when that file was split for the
|
||||||
|
# 250-line cap; the palette lives with the dataclass, not the window.
|
||||||
|
LOCKCONFIG_PY = ROOT / "gatelock" / "gatelock" / "_config.py"
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@ -121,7 +123,16 @@ def parse_tk(text: str) -> dict[str, str]:
|
|||||||
found: dict[str, str] = {}
|
found: dict[str, str] = {}
|
||||||
start = text.find("class LockConfig")
|
start = text.find("class LockConfig")
|
||||||
if start == -1:
|
if start == -1:
|
||||||
return found
|
# Fail closed. Returning {} here made every tk comparison vacuously
|
||||||
|
# pass when LockConfig moved to _config.py during the 250-line split:
|
||||||
|
# "0 parsed token(s)" read as success, and the drift guard was off
|
||||||
|
# for the whole gatelock stack without anything going red.
|
||||||
|
msg = (
|
||||||
|
"LockConfig not found in the file palette_check reads. It has "
|
||||||
|
"moved; update LOCKCONFIG_PY rather than letting the tk stack go "
|
||||||
|
"unchecked."
|
||||||
|
)
|
||||||
|
raise SystemExit(msg)
|
||||||
body = text[start:]
|
body = text[start:]
|
||||||
decl = re.compile(r'^\s{4}(\w+):\s*str\s*=\s*"(#[0-9A-Fa-f]{6})"', re.MULTILINE)
|
decl = re.compile(r'^\s{4}(\w+):\s*str\s*=\s*"(#[0-9A-Fa-f]{6})"', re.MULTILINE)
|
||||||
for name, value in decl.findall(body):
|
for name, value in decl.findall(body):
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user