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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions .github/workflows/deploy-site.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ on:
- 'docs-site/**'
workflow_dispatch:

# Allow this job to clone the repo and create a page deployment
# Only the deploy job can publish.
permissions:
contents: read
pages: write
id-token: write

jobs:
build:
Expand All @@ -23,10 +21,15 @@ jobs:
uses: withastro/action@e84f40bd8d2caa9e768ec82ad30dd81f0b280853 # v6
with:
path: ./docs-site # The root location of your Astro project inside the repository.
# Also add copies of the search index for other Valkey sites to consume.
build-cmd: npm run build && ./scripts/index-copies.sh build

deploy:
needs: build
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
Expand Down
35 changes: 35 additions & 0 deletions .github/workflows/docs-site.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Docs site

on:
pull_request:
branches: [ main ]
paths:
- 'docs-site/**'
- '.github/workflows/docs-site.yml'

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: docs-site
steps:
- name: Checkout code
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '24'
cache: npm
cache-dependency-path: docs-site/package-lock.json
- name: Install dependencies
run: npm ci
- name: Build the docs site
run: npm run build
- name: Check the Pagefind index version served by other sites is compatible with this site
run: ./scripts/index-copies.sh check
1 change: 1 addition & 0 deletions docs-site/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export default defineConfig({
integrations: [
starlight({
title: 'Valkey Admin',
components: { Search: './src/components/Search.astro' },
head: [
{
tag: 'script',
Expand Down
129 changes: 129 additions & 0 deletions docs-site/scripts/index-copies.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
#!/usr/bin/env bash
# Builds copies of this site's search index at /pagefind/v<major.minor>/, one for every Pagefind minor version from the
# oldest a Valkey site runs up to the newest release. Pagefind only merges indexes built with its own minor version, so
# this site must provide any version other sites may need.
#
# scripts/index-copies.sh build produces the necessary indexes for other sites to consume
# scripts/index-copies.sh check checks current Pagefind is compatible with indexes hosted by other sites
#
# Both fail if a site that has set up cross-site search has no copy for this build's Pagefind minor version yet.
# Redeploying that site usually adds the copy.
#
# Each Valkey site with cross-site search has a copy of this script. Keep the copies in sync.

set -euo pipefail
case ${1:-} in build | check) ;; *) echo "usage: $0 build|check" >&2; exit 2 ;; esac

cd "$(dirname "$0")/.."
OTHER_SITES=$(jq -r '.otherSites[]' src/cross-site-search.json)
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT

minor_version() { cut -d. -f1-2 <<< "$1"; } # 1.5.2 -> 1.5

# Prints the Pagefind version of the index at $1, "none" if it has no usable index (a 404, or an entry file without a
# release number), or "down" for anything else, such as a 503 or no answer.
index_state() {
local status version
rm -f "$TMP/entry.json" # clean any prior state
status=$(curl -sS --retry 3 --retry-connrefused --max-time 20 -o "$TMP/entry.json" -w '%{http_code}' \
"${1}pagefind-entry.json" 2>/dev/null) || status=failed
case $status in
404) echo none; return ;;
200) ;;
*) echo down; return ;;
esac
version=$(jq -r .version "$TMP/entry.json" 2>/dev/null) || version=
if [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "$version"
else
echo none
fi
}

check_other_sites() {
local this_minor index version copy_version missing=()
this_minor=$(minor_version "$1")
for index in $OTHER_SITES; do
# Check whether the site has any Pagefind index at all.
version=$(index_state "$index")
case $version in
none) continue ;;
down) missing+=("$index"); continue ;;
esac
# Check whether the site publishes its own version-specific index version.
case $(index_state "${index}v$(minor_version "$version")/") in
none) continue ;; # hasn't set up cross-site search
down) missing+=("$index"); continue ;;
esac
# Check whether the needed version is available.
copy_version=$(index_state "${index}v${this_minor}/")
[ "$(minor_version "$copy_version")" = "$this_minor" ] || missing+=("$index")
done
[ "${#missing[@]}" -gt 0 ] || return 0

cat >&2 << EOF
::error::These sites have no copy of their search index for Pagefind ${this_minor} yet, or can't be reached: ${missing[*]}
Deployed now, this site's search would leave them out. Either:
- redeploy them first, which adds a ${this_minor} copy if ${this_minor} is within the versions they publish.
- keep this site on the Pagefind version it uses now.
EOF
return 1
}

# Index versions to publish from this site. Finds the oldest version a Valkey site uses, and gathers each minor version
# of Pagefind published since up to the newest release.
versions_to_copy() {
local in_use=("$1") index state oldest
for index in $OTHER_SITES; do
state=$(index_state "$index")
case $state in
none) echo "::warning::${index} has no index; its version isn't counted" >&2 ;;
# Without its version, this deploy could stop publishing the copy that site's search uses.
down) echo "::error::${index} can't be reached; re-run this deploy once it can" >&2; return 1 ;;
*) echo "${index} runs Pagefind ${state}" >&2; in_use+=("$state") ;;
esac
done
oldest=$(printf '%s\n' "${in_use[@]}" | sort -V | head -1)
curl -fsS --retry 3 --retry-connrefused --max-time 20 https://registry.npmjs.org/pagefind | jq -r --arg oldest "$(minor_version "$oldest")" '
def minor: split(".")[:2] | map(tonumber);
.versions | keys
| map(select(test("^[0-9]+\\.[0-9]+\\.[0-9]+$"))) # releases, not pre-releases
| map(select(minor >= ($oldest | minor))) # from the oldest minor version in use
| group_by(minor) | map(max_by(split(".") | map(tonumber))) | .[] # the newest patch of each
'
}

# Downloads Pagefind $1 to $TMP/$1/pagefind.
download_pagefind() {
local dir asset url
dir=$TMP/$1
case $(uname -s)-$(uname -m) in
Linux-x86_64 | Linux-aarch64) asset="pagefind-v$1-$(uname -m)-unknown-linux-musl.tar.gz" ;;
Darwin-arm64) asset="pagefind-v$1-aarch64-apple-darwin.tar.gz" ;;
Darwin-x86_64) asset="pagefind-v$1-x86_64-apple-darwin.tar.gz" ;;
*) echo "no Pagefind release for $(uname -s) $(uname -m)" >&2; return 1 ;;
esac
url="https://github.com/Pagefind/pagefind/releases/download/v$1/${asset}"
mkdir -p "$dir"
curl -fsSL --retry 3 --max-time 300 "$url" -o "$dir/$asset"
curl -fsSL --retry 3 --max-time 60 "$url.sha256" -o "$dir/$asset.sha256"
if command -v sha256sum > /dev/null; then
(cd "$dir" && sha256sum -c --quiet "$asset.sha256")
else
(cd "$dir" && shasum -a 256 -c --quiet "$asset.sha256") # macOS has shasum instead
fi
tar -xzf "$dir/$asset" -C "$dir"
}

this_version=$(jq -er .version dist/pagefind/pagefind-entry.json)
check_other_sites "$this_version"
[ "$1" = build ] || exit 0

# Through a file, since a failure inside $(...) wouldn't stop the script.
versions_to_copy "$this_version" > "$TMP/versions"
for version in $(< "$TMP/versions"); do
echo "Building a Pagefind ${version} copy at pagefind/v$(minor_version "$version")/"
download_pagefind "$version"
"$TMP/$version/pagefind" --site dist --output-path "dist/pagefind/v$(minor_version "$version")"
done
138 changes: 138 additions & 0 deletions docs-site/src/components/Search.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
---
// Adds the other Valkey sites' results to Starlight's search box. A stopgap until Pagefind PR #1361 and Starlight PR #4307
// are released, after which Starlight's `pagefind.mergeIndex` setting can replace the <script>. Until then, an index that
// fails to load after passing its check leaves the search box on "Searching…" until the page is reloaded.
import Default from "@astrojs/starlight/components/Search.astro"
import sites from "../cross-site-search.json"
---

<Default {...Astro.props}><slot /></Default>

<!-- Tags this site's pages with its name, which every Valkey site's search shows on results and uses in the site filter. -->
<span hidden data-pagefind-filter={`site:${sites.label}`} data-pagefind-meta={`site:${sites.label}`}></span>

<script>
// @ts-expect-error -- Starlight's internal module has no types
import { pagefindUserConfig } from "virtual:starlight/pagefind-config"
import sites from "../cross-site-search.json"

type PagefindEntry = { version: string; languages: Record<string, { hash: string }> }

const searchBox = "#starlight__search"
const ownBundle = import.meta.env.BASE_URL.replace(/\/$/, "") + "/pagefind/"
const pagefindModule = ownBundle + "pagefind.js"

// Limit for the background check of each other site. Searches don't wait for it, and a site slower than this is left out.
const loadTimeoutMs = 3000

// Merging a missing index would break every search (Pagefind issue #887), so each index is checked first.
async function probeIndexVersion(bundlePath: string) {
try {
const signal = AbortSignal.timeout(loadTimeoutMs)
// `?ts=` skips caches, as Pagefind does when it loads this file, so the check sees the same deploy Pagefind will.
const entry: PagefindEntry = await (await fetch(`${bundlePath}pagefind-entry.json?ts=${Date.now()}`, { signal })).json()
const language = Object.values(entry.languages)[0]
const meta = await fetch(`${bundlePath}pagefind.${language.hash}.pf_meta`, { signal })
return meta.ok ? entry.version.split(".").slice(0, 2).join(".") : null
} catch {
return null
}
}

async function mergeOtherSites() {
const pagefind = await import(/* @vite-ignore */ pagefindModule)
const ownVersion = await probeIndexVersion(ownBundle)
if (!ownVersion) {
console.warn("Search: this site's index didn't load, so not merging the other sites")
return
}
await Promise.all(sites.otherSites.map(async (index) => {
// Pagefind only merges indexes built with the same minor version as this site's Pagefind. So each Valkey site
// publishes a copy of its index for every version in use, and this merges the one for this site's version.
const bundle = `${index}v${ownVersion}/`
if ((await probeIndexVersion(bundle)) !== ownVersion) {
console.warn(`Search: leaving out ${index}, which has no copy for Pagefind ${ownVersion} or didn't load in time`)
return
}
// Merged indexes don't inherit the search box's settings, so they're given its ranking. The weight lowers their
// scores, so this site's own pages usually come first.
await pagefind.mergeIndex(bundle, { ranking: pagefindUserConfig.ranking, indexWeight: sites.otherSitesIndexWeight })
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Without this the merged site is missing from the filter.
await pagefind.filters()
searchAgain()
}))
}

// Changing the search box's value during an IME composition breaks the composition. iOS Safari leaves the box stuck
// (WebKit bug 255857), and Chromium can duplicate the composed text. A search that comes due during one waits until
// it ends.
let isComposing = false
let isSearchAgainPending = false

// Pagefind doesn't redo a search that finished before a site merged, so its results would leave that site out until
// the query changes. Changing the query and putting it back makes the search box search again.
function searchAgain() {
if (isComposing) {
isSearchAgainPending = true
return
}
const input = document.querySelector<HTMLInputElement>(`${searchBox} .pagefind-ui__search-input`)
if (!input?.value) return
const { value: query, selectionStart, selectionEnd } = input
input.value = query + " "
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
input.dispatchEvent(new Event("input"))
input.value = query
input.dispatchEvent(new Event("input"))
input.setSelectionRange(selectionStart, selectionEnd)
}

// Merging downloads from the other sites, so it only starts when the visitor first opens the search box.
document.querySelector(searchBox)?.addEventListener("focusin", () => {
mergeOtherSites().catch((error) => console.warn("Search: merging the other sites failed", error))
}, { once: true })

document.querySelector(searchBox)?.addEventListener("compositionstart", () => {
isComposing = true
})
document.querySelector(searchBox)?.addEventListener("compositionend", () => {
isComposing = false
if (!isSearchAgainPending) return
isSearchAgainPending = false
// Waits a task in case a browser fires this before the composed text is in the box.
setTimeout(searchAgain)
})

// Pagefind shows only results matching every ticked site, so ticking two would show nothing. Ticking a site therefore
// unticks the others (Pagefind issue #594).
document.addEventListener("change", (event) => {
const ticked = event.target
const isSiteTicked = ticked instanceof HTMLInputElement && ticked.checked && ticked.matches(`${searchBox} input[name="site"]`)
if (!isSiteTicked) return
for (const other of document.querySelectorAll<HTMLInputElement>(`${searchBox} input[name="site"]:checked`)) {
// Click rather than set `checked`, so that Pagefind notices.
if (other !== ticked) other.click()
}
})
</script>

<style is:global>
/* The site filter as a row of pills above the results, rather than a column beside them. */
#starlight__search .pagefind-ui__drawer { flex-direction: column; gap: 0; }
#starlight__search .pagefind-ui__filter-panel { flex: none; width: 100%; max-width: none; margin-top: calc(16px * var(--pagefind-ui-scale)); }
#starlight__search .pagefind-ui__filter-panel-label { display: none; }

/* Only the site filter, so that another Pagefind filter a page might add keeps Pagefind's own look. */
#starlight__search .pagefind-ui__filter-block:has(input[name="site"]) {
/* With one site there's nothing to pick. */
&:not(:has(.pagefind-ui__filter-value ~ .pagefind-ui__filter-value)) { display: none; }
/* The heading is also the toggle that opens the filter, so it's only hidden once the filter is open. */
&[open] > .pagefind-ui__filter-name { display: none; }
.pagefind-ui__filter-value::before { display: none; }
/* Hidden but still focusable, so the pills work from the keyboard. */
.pagefind-ui__filter-checkbox { position: absolute; opacity: 0; }
.pagefind-ui__filter-group { flex-direction: row; flex-wrap: wrap; gap: calc(8px * var(--pagefind-ui-scale)); padding-top: 0; }
.pagefind-ui__filter-label { padding: calc(4px * var(--pagefind-ui-scale)) calc(14px * var(--pagefind-ui-scale)); border: 1px solid var(--pagefind-ui-border); border-radius: 999px; }
.pagefind-ui__filter-value--checked .pagefind-ui__filter-label { background: var(--pagefind-ui-primary); border-color: var(--pagefind-ui-primary); color: var(--pagefind-ui-background); }
.pagefind-ui__filter-checkbox:focus-visible + .pagefind-ui__filter-label { outline: 2px solid var(--pagefind-ui-primary); outline-offset: 2px; }
}
</style>
5 changes: 5 additions & 0 deletions docs-site/src/cross-site-search.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"label": "Valkey Admin",
"otherSites": ["https://valkey.io/pagefind/", "https://glide.valkey.io/pagefind/", "https://spring.valkey.io/pagefind/"],
"otherSitesIndexWeight": 0.1
}
Loading