Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a36934e72c | ||
|
|
0f686aa2fb | ||
|
|
d5d21b7841 |
No files matched your search
@@ -2,6 +2,8 @@ data/*
|
||||
!data/pageswiki-cli
|
||||
!data/test_cli_assets.py
|
||||
!data/pageswiki_cli_test.py
|
||||
!data/test_cli_dr.py
|
||||
!data/pageswiki-remote
|
||||
/data2/
|
||||
/.codex/
|
||||
/.agents/
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import '../../static/js/editor-core.js';
|
||||
const {merge,validDraft}=globalThis.PagesEditorCore;
|
||||
test('three-way merge keeps disjoint changes',()=>{
|
||||
assert.equal(merge('one two three','ONE two three','one two THREE'),'ONE two THREE');
|
||||
assert.equal(merge('abc','abc','Abc'),'Abc');
|
||||
assert.equal(merge('abc','ABC','ABC'),'ABC');
|
||||
assert.equal(merge('abc','Abc','aBc'),null); // adjacent ranges
|
||||
assert.equal(merge('abc','axbc','aybc'),null); // competing insertions
|
||||
assert.equal(merge('abc','axbc','abc!'),'axbc!');
|
||||
assert.equal(merge('one two three','one LOCAL three','one REMOTE three'),null);
|
||||
});
|
||||
test('draft format, date, expiry and content validated',()=>{
|
||||
const now=Date.now(),draft={version:1,text:'source',baseBody:'base',baseRevision:'uuid',format:'markdown',savedAt:now};
|
||||
assert.ok(validDraft(draft,now));
|
||||
assert.ok(validDraft({...draft,format:'plain',text:'<script>literal</script>'},now));
|
||||
for(const fields of [{version:2},{text:null},{baseRevision:1},{format:'projection'},{savedAt:now-8*86400000},{savedAt:now+120000}]) assert.ok(!validDraft({...draft,...fields},now));
|
||||
});
|
||||
Generated
+1
@@ -27,6 +27,7 @@
|
||||
"@codemirror/legacy-modes": "^6.5.3",
|
||||
"@codemirror/state": "^6.6.0",
|
||||
"@codemirror/view": "^6.43.0",
|
||||
"@lezer/highlight": "^1.2.3",
|
||||
"@replit/codemirror-vim": "^6.3.0",
|
||||
"esbuild": "^0.28.0"
|
||||
}
|
||||
|
||||
@@ -4,12 +4,14 @@
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
"test": "node --test editor-core.test.mjs",
|
||||
"build": "node build.mjs"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@lezer/highlight": "^1.2.3",
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/commands": "^6.10.3",
|
||||
"@codemirror/lang-cpp": "^6.0.3",
|
||||
|
||||
+86
-162
@@ -1,9 +1,9 @@
|
||||
import { EditorView, keymap, lineNumbers } from "@codemirror/view";
|
||||
import { EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter } from "@codemirror/view";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
|
||||
import {
|
||||
bracketMatching,
|
||||
defaultHighlightStyle,
|
||||
HighlightStyle,
|
||||
StreamLanguage,
|
||||
syntaxHighlighting,
|
||||
} from "@codemirror/language";
|
||||
@@ -28,32 +28,59 @@ import { java } from "@codemirror/lang-java";
|
||||
import { cpp } from "@codemirror/lang-cpp";
|
||||
import { shell } from "@codemirror/legacy-modes/mode/shell";
|
||||
import { toml } from "@codemirror/legacy-modes/mode/toml";
|
||||
import { vim, Vim } from "@replit/codemirror-vim";
|
||||
import { vim, Vim, getCM } from "@replit/codemirror-vim";
|
||||
import { tags, highlightTree } from "@lezer/highlight";
|
||||
|
||||
// Stable semantic styles instead of selectors for generated Lezer class names.
|
||||
// CSS variables follow the selected Wiki theme without rebuilding the document.
|
||||
const pagesWikiHighlightStyle = HighlightStyle.define([
|
||||
{tag: tags.heading, class: "pw-syntax-heading"},
|
||||
{tag: [tags.link, tags.url], class: "pw-syntax-link"},
|
||||
{tag: tags.emphasis, class: "pw-syntax-emphasis"},
|
||||
{tag: tags.strong, class: "pw-syntax-strong"},
|
||||
{tag: [tags.keyword, tags.operatorKeyword], class: "pw-syntax-keyword"},
|
||||
{tag: [tags.tagName, tags.typeName, tags.monospace], class: "pw-syntax-type"},
|
||||
{tag: [tags.string, tags.special(tags.string)], class: "pw-syntax-string"},
|
||||
{tag: [tags.number, tags.bool, tags.null, tags.attributeName], class: "pw-syntax-number"},
|
||||
{tag: tags.comment, class: "pw-syntax-comment"},
|
||||
{tag: [tags.variableName, tags.propertyName], class: "pw-syntax-variable"},
|
||||
{tag: tags.function(tags.variableName), class: "pw-syntax-function"},
|
||||
{tag: tags.operator, class: "pw-syntax-operator"},
|
||||
{tag: tags.invalid, class: "pw-syntax-invalid"},
|
||||
]);
|
||||
|
||||
const pagesWikiTheme = EditorView.theme({
|
||||
".cm-selectionBackground": {
|
||||
backgroundColor: "rgba(255, 216, 102, 0.48) !important",
|
||||
backgroundColor: "var(--editor-selection) !important",
|
||||
},
|
||||
"&.cm-focused .cm-selectionBackground": {
|
||||
backgroundColor: "rgba(255, 216, 102, 0.58) !important",
|
||||
backgroundColor: "var(--editor-selection) !important",
|
||||
},
|
||||
".cm-selectionLayer .cm-selectionBackground": {
|
||||
backgroundColor: "rgba(255, 216, 102, 0.58) !important",
|
||||
backgroundColor: "var(--editor-selection) !important",
|
||||
},
|
||||
".cm-content ::selection": {
|
||||
backgroundColor: "rgba(255, 216, 102, 0.48) !important",
|
||||
color: "#ffffff !important",
|
||||
backgroundColor: "var(--editor-selection) !important",
|
||||
color: "var(--fg) !important",
|
||||
},
|
||||
});
|
||||
|
||||
let vimMode = "INSERT";
|
||||
|
||||
const languageAliases = {js:'javascript', ts:'typescript', py:'python', sh:'shell', bash:'shell', zsh:'shell', yml:'yaml', md:'markdown', c:'cpp', 'c++':'cpp', xml:'html', htm:'html'};
|
||||
|
||||
function languageExtension(mode) {
|
||||
switch (String(mode || "").toLowerCase()) {
|
||||
mode = String(mode || "").toLowerCase();
|
||||
switch (languageAliases[mode] || mode) {
|
||||
case "html":
|
||||
return html();
|
||||
case "markdown":
|
||||
return markdown();
|
||||
return markdown({codeLanguages: info => {
|
||||
const mode = info.trim().split(/\s+/)[0].toLowerCase();
|
||||
if (['md','markdown'].includes(mode)) return null;
|
||||
const support = languageExtension(mode);
|
||||
return support?.language || support;
|
||||
}});
|
||||
case "javascript":
|
||||
return javascript({ jsx: true });
|
||||
case "typescript":
|
||||
@@ -129,6 +156,7 @@ function attachMinimap(view, minimap, text) {
|
||||
|
||||
function setEditorMode(mode) {
|
||||
vimMode = mode;
|
||||
document.body.dataset.editorMode = mode.toLowerCase();
|
||||
|
||||
const el =
|
||||
document.getElementById("editor-vim-mode");
|
||||
@@ -152,6 +180,8 @@ function markdownCompletions(context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!context.explicit && !word.text.startsWith("{{")) return null;
|
||||
|
||||
return {
|
||||
from: word.from,
|
||||
options: [
|
||||
@@ -163,10 +193,14 @@ function markdownCompletions(context) {
|
||||
{ label: "```go", type: "snippet", apply: "```go\n\n```" },
|
||||
{ label: "```bash", type: "snippet", apply: "```bash\n\n```" },
|
||||
{ label: "[link](url)", type: "snippet", apply: "[text](url)" },
|
||||
{ label: "{{children}}", type: "function", apply: "{{children}}" },
|
||||
{ label: "{{children}}", type: "function", apply: "{{children}}", boost: 5 },
|
||||
{ label: "{{children:/}}", type: "function", apply: "{{children:/}}" },
|
||||
{ label: "{{children:/ exclude=/draft}}", type: "function", apply: "{{children:/ exclude=/draft}}" },
|
||||
],
|
||||
].map(option => option.label.startsWith("{{") ? {...option, apply(view, completion, from, to) {
|
||||
// Existing close-bracket text is part of this macro replacement.
|
||||
const tail = view.state.sliceDoc(to, to + 2).match(/^\}{1,2}/)?.[0] || "";
|
||||
view.dispatch({changes:{from,to:to+tail.length,insert:option.label},selection:{anchor:from+option.label.length}});
|
||||
}} : option),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -190,11 +224,9 @@ function installVimCommands() {
|
||||
window.PagesWikiCurrentPath || "/";
|
||||
};
|
||||
|
||||
const saveQuit =
|
||||
() => {
|
||||
save();
|
||||
setTimeout(quit, 120);
|
||||
};
|
||||
const saveQuit = async () => {
|
||||
if (await window.PagesEditor?.saveNow()) quit();
|
||||
};
|
||||
|
||||
// Register both canonical and short names.
|
||||
Vim.defineEx("write", "w", save);
|
||||
@@ -208,46 +240,13 @@ function installVimCommands() {
|
||||
}
|
||||
|
||||
function attachVimModeTracking(view) {
|
||||
view.dom.addEventListener(
|
||||
"keydown",
|
||||
(ev) => {
|
||||
if (ev.key === "Escape" || (ev.ctrlKey && ev.key === "[")) {
|
||||
setEditorMode("NORMAL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (vimMode === "NORMAL") {
|
||||
if (ev.key === "i" || ev.key === "a" || ev.key === "o" || ev.key === "O") {
|
||||
setEditorMode("INSERT");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.key === "R") {
|
||||
setEditorMode("REPLACE");
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.key === "v" || ev.key === "V") {
|
||||
setEditorMode("VISUAL");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (vimMode === "VISUAL" && ev.key === "Escape") {
|
||||
setEditorMode("NORMAL");
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
view.dom.addEventListener(
|
||||
"focusin",
|
||||
() => {
|
||||
if (!vimMode) {
|
||||
setEditorMode("INSERT");
|
||||
}
|
||||
}
|
||||
);
|
||||
// Observe actual Vim transitions, including A/I/c/operator motions and
|
||||
// command-line searches, rather than guessing the mode from individual keys.
|
||||
getCM(view)?.on("vim-mode-change", event => {
|
||||
const mode = String(event.mode || "normal").toUpperCase();
|
||||
setEditorMode(mode);
|
||||
view.dom.classList.toggle("pageswiki-vim-visual", mode === "VISUAL");
|
||||
});
|
||||
}
|
||||
|
||||
function attachStatusBar(view) {
|
||||
@@ -281,10 +280,29 @@ function attachStatusBar(view) {
|
||||
}
|
||||
|
||||
window.PagesWikiEditor = {
|
||||
highlightCodeBlock(code, mode) {
|
||||
mode = String(mode || '').toLowerCase();
|
||||
const language = languageExtension(mode);
|
||||
const text = code.textContent;
|
||||
// Projection only: never change canonical HTML, unlabelled/plain text,
|
||||
// or large samples. Large code files retain the windowed viewer.
|
||||
if (!language || text.length > 32768) return false;
|
||||
const parser = (language.language || language).parser;
|
||||
const fragment = document.createDocumentFragment();
|
||||
let offset = 0;
|
||||
highlightTree(parser.parse(text), pagesWikiHighlightStyle, (from, to, classes) => {
|
||||
if (from > offset) fragment.append(document.createTextNode(text.slice(offset, from)));
|
||||
const span = document.createElement('span'); span.className = classes;
|
||||
span.textContent = text.slice(from, to); fragment.append(span); offset = to;
|
||||
});
|
||||
fragment.append(document.createTextNode(text.slice(offset)));
|
||||
code.replaceChildren(fragment);
|
||||
return true;
|
||||
},
|
||||
createViewer(target, text, mode, minimap) {
|
||||
const extensions = [
|
||||
lineNumbers(),
|
||||
syntaxHighlighting(defaultHighlightStyle),
|
||||
syntaxHighlighting(pagesWikiHighlightStyle),
|
||||
pagesWikiTheme,
|
||||
EditorState.readOnly.of(true),
|
||||
EditorView.editable.of(false),
|
||||
@@ -305,11 +323,13 @@ window.PagesWikiEditor = {
|
||||
},
|
||||
|
||||
create(target, initialText, mode, options = {}) {
|
||||
const keymapName =
|
||||
String(options.keymap || "default").toLowerCase();
|
||||
const mobile = window.matchMedia("(pointer: coarse) and (hover: none)").matches;
|
||||
const keymapName = mobile ? "default" : String(options.keymap || "default").toLowerCase();
|
||||
|
||||
const extensions = [
|
||||
lineNumbers(),
|
||||
highlightActiveLine(),
|
||||
highlightActiveLineGutter(),
|
||||
history(),
|
||||
bracketMatching(),
|
||||
closeBrackets(),
|
||||
@@ -340,7 +360,7 @@ window.PagesWikiEditor = {
|
||||
);
|
||||
|
||||
if (options.syntax !== false) {
|
||||
extensions.push(syntaxHighlighting(defaultHighlightStyle));
|
||||
extensions.push(syntaxHighlighting(pagesWikiHighlightStyle));
|
||||
}
|
||||
|
||||
if (options.autocomplete !== false) {
|
||||
@@ -358,6 +378,9 @@ window.PagesWikiEditor = {
|
||||
if (language) {
|
||||
extensions.push(language);
|
||||
}
|
||||
if (mode === "html" || mode === "markdown") {
|
||||
extensions.push(EditorState.languageData.of(() => [{closeBrackets:{brackets:["(", "[", "'", '"', "`"]}}]));
|
||||
}
|
||||
|
||||
const view =
|
||||
new EditorView({
|
||||
@@ -372,116 +395,17 @@ window.PagesWikiEditor = {
|
||||
|
||||
if (keymapName === "vim") {
|
||||
attachVimModeTracking(view);
|
||||
attachPagesWikiExFallback(view);
|
||||
}
|
||||
|
||||
return view;
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
function attachPagesWikiExFallback(view) {
|
||||
let active = false;
|
||||
let buffer = "";
|
||||
|
||||
function save() {
|
||||
if (window.PagesEditor && window.PagesEditor.saveNow) {
|
||||
window.PagesEditor.saveNow();
|
||||
}
|
||||
}
|
||||
|
||||
function quit() {
|
||||
location.href =
|
||||
window.PagesWikiCurrentPath || "/";
|
||||
}
|
||||
|
||||
view.dom.addEventListener(
|
||||
"keydown",
|
||||
(ev) => {
|
||||
if (!active && vimMode === "NORMAL" && ev.key === ":") {
|
||||
active = true;
|
||||
buffer = "";
|
||||
return;
|
||||
}
|
||||
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.key === "Escape" || (ev.ctrlKey && ev.key === "[")) {
|
||||
active = false;
|
||||
buffer = "";
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.key === "Enter") {
|
||||
const cmd =
|
||||
buffer.trim();
|
||||
|
||||
active = false;
|
||||
buffer = "";
|
||||
|
||||
if (cmd === "w") {
|
||||
ev.preventDefault();
|
||||
save();
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd === "q") {
|
||||
ev.preventDefault();
|
||||
quit();
|
||||
return;
|
||||
}
|
||||
|
||||
if (cmd === "wq" || cmd === "x") {
|
||||
ev.preventDefault();
|
||||
save();
|
||||
setTimeout(quit, 120);
|
||||
return;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (ev.key.length === 1) {
|
||||
buffer += ev.key;
|
||||
}
|
||||
|
||||
if (ev.key === "Backspace") {
|
||||
buffer =
|
||||
buffer.slice(0, -1);
|
||||
}
|
||||
},
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
let pagesWikiPreviewTimer = null;
|
||||
|
||||
function schedulePagesWikiPreview(view) {
|
||||
const textarea =
|
||||
document.getElementById("editor");
|
||||
|
||||
const textarea = document.getElementById("editor");
|
||||
if (textarea) {
|
||||
textarea.value =
|
||||
view.state.doc.toString();
|
||||
textarea.dispatchEvent(new Event("input", {bubbles:true}));
|
||||
}
|
||||
|
||||
if (pagesWikiPreviewTimer) {
|
||||
clearTimeout(pagesWikiPreviewTimer);
|
||||
}
|
||||
|
||||
pagesWikiPreviewTimer =
|
||||
setTimeout(
|
||||
() => {
|
||||
if (
|
||||
window.PagesEditor &&
|
||||
window.PagesEditor.renderPreview
|
||||
) {
|
||||
window.PagesEditor.renderPreview();
|
||||
}
|
||||
},
|
||||
350
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/dr"
|
||||
)
|
||||
|
||||
// All role changes are operator-only and offline. Never expose this as a
|
||||
// domain-admin API: a data directory contains multiple campuses and domains.
|
||||
func runDR(args []string, out io.Writer) error {
|
||||
const usage = "pageswiki dr {init|status|snapshot|verify|restore|promote|resume-workers} [flags]\nUse COMMAND --help. Snapshot requires all writers stopped; promotion requires external fencing."
|
||||
if len(args) == 0 || args[0] == "--help" {
|
||||
_, err := fmt.Fprintln(out, usage)
|
||||
return err
|
||||
}
|
||||
cmd := args[0]
|
||||
switch cmd {
|
||||
case "init", "status", "snapshot", "verify", "restore", "promote", "resume-workers":
|
||||
default:
|
||||
return errors.New(usage)
|
||||
}
|
||||
f := flag.NewFlagSet("dr "+cmd, flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
defaultDir := os.Getenv("PAGESWIKI_DATA_DIR")
|
||||
if defaultDir == "" {
|
||||
defaultDir = "./data"
|
||||
}
|
||||
dir := f.String("data-dir", defaultDir, "instance data directory")
|
||||
var output, snapshot, hash, target, fenced, reference *string
|
||||
var stopped, loss, reviewed *bool
|
||||
switch cmd {
|
||||
case "resume-workers":
|
||||
reviewed = f.Bool("reviewed-restored-jobs", false, "attest restored queues and federation state have been reviewed for replay/duplicate effects")
|
||||
case "snapshot":
|
||||
output = f.String("output", "", "new snapshot directory outside data directory")
|
||||
stopped = f.Bool("writers-stopped", false, "attest ALL servers, CLIs and external writers are stopped")
|
||||
case "verify", "restore":
|
||||
snapshot = f.String("snapshot", "", "snapshot directory")
|
||||
hash = f.String("manifest-sha256", "", "manifest SHA-256 received over an authenticated channel")
|
||||
if cmd == "restore" {
|
||||
target = f.String("target", "", "new, nonexistent data directory (always standby)")
|
||||
}
|
||||
case "promote":
|
||||
fenced = f.String("fenced-node", "", "exact former primary node UUID")
|
||||
reference = f.String("fence-reference", "", "operator evidence/ticket for verified power/storage/network fencing")
|
||||
loss = f.Bool("accept-data-loss", false, "accept loss of writes since the snapshot cutoff")
|
||||
}
|
||||
if err := f.Parse(args[1:]); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if f.NArg() != 0 {
|
||||
return errors.New("unexpected positional arguments")
|
||||
}
|
||||
encode := func(v any) error { e := json.NewEncoder(out); e.SetIndent("", " "); return e.Encode(v) }
|
||||
ctx := context.Background()
|
||||
switch cmd {
|
||||
case "resume-workers":
|
||||
c, err := dr.ResumeWorkers(*dir, *reviewed)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(c)
|
||||
case "init":
|
||||
c, err := dr.Init(*dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(c)
|
||||
case "status":
|
||||
c, err := dr.Load(*dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(struct {
|
||||
Node *dr.Config `json:"node"`
|
||||
StandbyReadable bool `json:"standby_readable"`
|
||||
}{c, c != nil && c.Readable(time.Now())})
|
||||
case "snapshot":
|
||||
if *output == "" || !*stopped {
|
||||
return errors.New("snapshot requires --output and --writers-stopped; stop every writer first")
|
||||
}
|
||||
m, sum, err := dr.Snapshot(ctx, *dir, *output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(struct {
|
||||
Manifest *dr.Manifest `json:"manifest"`
|
||||
SHA256 string `json:"manifest_sha256"`
|
||||
}{m, sum})
|
||||
case "verify":
|
||||
if *snapshot == "" {
|
||||
return errors.New("--snapshot is required")
|
||||
}
|
||||
m, err := dr.Verify(ctx, *snapshot, *hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(m)
|
||||
case "restore":
|
||||
if *snapshot == "" || *target == "" {
|
||||
return errors.New("--snapshot and --target are required")
|
||||
}
|
||||
c, err := dr.Restore(ctx, *snapshot, *hash, *target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(c)
|
||||
case "promote":
|
||||
c, err := dr.Promote(*dir, *fenced, *reference, *loss)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return encode(c)
|
||||
}
|
||||
return errors.New("unknown DR command")
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDRCLIRequiresExplicitOfflineAttestation(t *testing.T) {
|
||||
var out bytes.Buffer
|
||||
err := runDR([]string{"snapshot", "--data-dir", t.TempDir(), "--output", "/not-used"}, &out)
|
||||
if err == nil || !strings.Contains(err.Error(), "writers-stopped") {
|
||||
t.Fatalf("unsafe invocation: %v", err)
|
||||
}
|
||||
if err = runDR([]string{"restore"}, &out); err == nil {
|
||||
t.Fatal("missing restore target accepted")
|
||||
}
|
||||
if err = runDR([]string{"snapshot", "--help"}, &out); err != nil || !strings.Contains(out.String(), "writers-stopped") {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
+55
-1
@@ -1,16 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/dr"
|
||||
"pageswiki/internal/server"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "schema" {
|
||||
if err := runSchema(os.Args[2:], os.Stdout); err != nil {
|
||||
log.Print(err)
|
||||
if errors.Is(err, errSchemaPending) {
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "dr" {
|
||||
if err := runDR(os.Args[2:], os.Stdout); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
enrollment, err := parseExternalCampusEnrollment(os.Args[1:])
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -34,6 +52,39 @@ func main() {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
instanceLock, err := dr.Lock(dataDir, false)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer instanceLock.Close()
|
||||
node, err := dr.Load(dataDir)
|
||||
if err != nil {
|
||||
log.Fatalf("invalid DR configuration (startup refused): %v", err)
|
||||
}
|
||||
if err = dr.RequireRole(node, os.Getenv("PAGESWIKI_DR_EXPECT_ROLE")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if node != nil && node.Role == "standby" {
|
||||
if len(os.Args) > 1 {
|
||||
log.Fatal("standby does not accept enrollment/startup mutation flags")
|
||||
}
|
||||
database, err := db.OpenReadOnly(filepath.Join(dataDir, "pages.db"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
st, err := store.NewReadOnlyWithDocumentRoot(database, filepath.Join(dataDir, "documents"))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
st.StandbyReadUntil = node.ReadUntil()
|
||||
log.Printf("DR standby: migrations, federation reconciliation and background workers disabled; snapshot=%s", node.SnapshotID)
|
||||
if err := server.New(st).Run(":3000"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
dbPath :=
|
||||
filepath.Join(
|
||||
dataDir,
|
||||
@@ -87,7 +138,10 @@ func main() {
|
||||
if err := enrollExternalCampus(dataDir, st, enrollment); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
startManagedCampusReconciler(dataDir, st)
|
||||
st.BackgroundJobsDisabled = node != nil && !node.WorkersEnabled
|
||||
if !st.BackgroundJobsDisabled {
|
||||
startManagedCampusReconciler(dataDir, st)
|
||||
}
|
||||
|
||||
srv := server.New(st)
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
var errSchemaPending = errors.New("schema migrations are pending; no changes were applied")
|
||||
var errSchemaBlocked = errors.New("schema history or contract is incompatible; no changes were applied")
|
||||
|
||||
func runSchema(args []string, out io.Writer) error {
|
||||
const usage = "pageswiki schema {status|check} [--db FILE | --data-dir DIR] [--json] [--timeout 30s]\nRead-only inspection of managed components; legacy migrations and pending DDL are not rehearsed.\ncheck exits 2 for pending migrations, 1 for incompatible state, 0 when managed components are current."
|
||||
if len(args) == 0 || args[0] == "--help" {
|
||||
_, err := fmt.Fprintln(out, usage)
|
||||
return err
|
||||
}
|
||||
if args[0] != "status" && args[0] != "check" {
|
||||
return errors.New(usage)
|
||||
}
|
||||
f := flag.NewFlagSet("schema "+args[0], flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
defaultDir := os.Getenv("PAGESWIKI_DATA_DIR")
|
||||
if defaultDir == "" {
|
||||
defaultDir = "./data"
|
||||
}
|
||||
dir := f.String("data-dir", defaultDir, "instance data directory (not created)")
|
||||
path := f.String("db", "", "explicit existing SQLite database path")
|
||||
jsonOutput := f.Bool("json", false, "JSON report")
|
||||
timeout := f.Duration("timeout", 30*time.Second, "inspection timeout")
|
||||
if err := f.Parse(args[1:]); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if f.NArg() != 0 || *timeout <= 0 {
|
||||
return errors.New("unexpected arguments or invalid timeout")
|
||||
}
|
||||
explicitDir := false
|
||||
f.Visit(func(flag *flag.Flag) {
|
||||
if flag.Name == "data-dir" {
|
||||
explicitDir = true
|
||||
}
|
||||
})
|
||||
if *path != "" && explicitDir {
|
||||
return errors.New("choose --db or --data-dir, not both")
|
||||
}
|
||||
if *path == "" {
|
||||
*path = filepath.Join(*dir, "pages.db")
|
||||
}
|
||||
database, err := db.OpenReadOnly(*path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer database.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
report, err := store.InspectSchema(ctx, database)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *jsonOutput {
|
||||
encoder := json.NewEncoder(out)
|
||||
encoder.SetIndent("", " ")
|
||||
err = encoder.Encode(report)
|
||||
} else {
|
||||
_, err = fmt.Fprintf(out, "Coverage: %s (not a full startup or data migration rehearsal)\n", report.Coverage)
|
||||
for _, component := range report.Components {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
_, err = fmt.Fprintf(out, "%-24s %-8s %d -> %d\n", component.Component, component.State, component.AppliedVersion, component.LatestVersion)
|
||||
for _, step := range component.Pending {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
_, err = fmt.Fprintf(out, " pending v%d %s (%d SQL statements, %d conditional columns)\n", step.Version, step.Name, step.Statements, len(step.AddColumns))
|
||||
}
|
||||
for _, issue := range component.Issues {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
_, err = fmt.Fprintf(out, " %s\n", issue)
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
_, err = fmt.Fprintf(out, "Legacy areas not covered: %v\n", report.LegacyAreas)
|
||||
}
|
||||
}
|
||||
if err != nil || args[0] == "status" {
|
||||
return err
|
||||
}
|
||||
pending := false
|
||||
for _, component := range report.Components {
|
||||
if component.State == "blocked" || component.State == "unknown" {
|
||||
return errSchemaBlocked
|
||||
}
|
||||
pending = pending || component.State == "pending"
|
||||
}
|
||||
if pending {
|
||||
return errSchemaPending
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestSchemaCommandMissingDatabaseDoesNotInitialize(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "missing")
|
||||
var out bytes.Buffer
|
||||
if err := runSchema([]string{"status", "--data-dir", dir}, &out); err == nil {
|
||||
t.Fatal("missing DB accepted")
|
||||
}
|
||||
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("directory created: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaCommandPendingAndBlocked(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := runSchema([]string{"status", "--data-dir", dir, "--json"}, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var report store.SchemaInspection
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if report.Coverage != "managed-components-only" || len(report.Components) == 0 || len(report.LegacyAreas) == 0 {
|
||||
t.Fatalf("report=%+v", report)
|
||||
}
|
||||
out.Reset()
|
||||
if err := runSchema([]string{"check", "--db", filepath.Join(dir, "pages.db")}, &out); !errors.Is(err, errSchemaPending) {
|
||||
t.Fatalf("pending: %v", err)
|
||||
}
|
||||
if _, err := database.Exec(`CREATE TABLE schema_migration_steps(component TEXT,version INTEGER,name TEXT,checksum TEXT,applied_at_ms INTEGER); INSERT INTO schema_migration_steps VALUES('future-component',1,'future','unknown',0)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out.Reset()
|
||||
if err := runSchema([]string{"check", "--data-dir", dir}, &out); !errors.Is(err, errSchemaBlocked) {
|
||||
t.Fatalf("unknown component: %v", err)
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type='table'`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("command initialized DB: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaCommandArguments(t *testing.T) {
|
||||
for _, args := range [][]string{{"apply"}, {"check", "--timeout", "0s"}, {"check", "extra"}, {"check", "--db", "a", "--data-dir", "b"}} {
|
||||
if err := runSchema(args, &bytes.Buffer{}); err == nil {
|
||||
t.Fatalf("accepted %v", args)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]string{nil, {"--help"}, {"check", "--help"}} {
|
||||
if err := runSchema(args, &bytes.Buffer{}); err != nil {
|
||||
t.Fatalf("help %v: %v", args, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaCommandCurrentApplicationDatabase(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := db.Init(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Initialize only this synthetic fixture. runSchema must not run the
|
||||
// constructor itself, even for an already initialized application DB.
|
||||
store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||
var out bytes.Buffer
|
||||
if err := runSchema([]string{"check", "--data-dir", dir, "--json"}, &out); err != nil {
|
||||
t.Fatalf("current database: %v\n%s", err, out.String())
|
||||
}
|
||||
var report store.SchemaInspection
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, component := range report.Components {
|
||||
if component.State != "current" {
|
||||
t.Fatalf("component=%+v", component)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ Uses only the Python standard library.
|
||||
from __future__ import annotations
|
||||
|
||||
import difflib
|
||||
import fcntl
|
||||
import fnmatch
|
||||
import glob
|
||||
import hashlib
|
||||
@@ -336,6 +337,26 @@ class PagesWikiCLI:
|
||||
if not self.database_path.is_file():
|
||||
raise CLIError(f"SQLite database not found: {self.database_path}")
|
||||
|
||||
# Coordinate with offline DR snapshots/promotions. Do this before any
|
||||
# schema repair or content write. A standby never permits this CLI.
|
||||
self._instance_lock = None
|
||||
try:
|
||||
lock_path = self.database_path.parent / ".pageswiki-instance.lock"
|
||||
self._instance_lock = lock_path.open("rb") if lock_path.exists() else lock_path.open("a+b")
|
||||
fcntl.flock(self._instance_lock.fileno(), fcntl.LOCK_SH | fcntl.LOCK_NB)
|
||||
for root in {self.data_dir, self.database_path.parent, self.documents.parent}:
|
||||
config_path = root / "dr-node.json"
|
||||
if config_path.exists():
|
||||
config = json.loads(config_path.read_text())
|
||||
if not isinstance(config, dict) or config.get("version") != 1 or config.get("role") != "primary":
|
||||
raise CLIError("DR standby or invalid configuration: data CLI is disabled")
|
||||
if root != self.database_path.parent or self.documents != root / "documents":
|
||||
raise CLIError("DR requires DB and documents in the same instance data directory")
|
||||
except (OSError, ValueError, CLIError) as exc:
|
||||
if self._instance_lock is not None:
|
||||
self._instance_lock.close()
|
||||
raise CLIError(f"DR maintenance guard: {exc}") from exc
|
||||
|
||||
self.db = sqlite3.connect(
|
||||
self.database_path,
|
||||
timeout=30,
|
||||
@@ -351,6 +372,8 @@ class PagesWikiCLI:
|
||||
|
||||
def close(self) -> None:
|
||||
self.db.close()
|
||||
if self._instance_lock is not None:
|
||||
self._instance_lock.close()
|
||||
|
||||
def _check_schema(self) -> None:
|
||||
required = {"objects", "paths", "revisions"}
|
||||
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility launcher for the unreleased prototype. Prefer pages-cli/pages."""
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import sys
|
||||
|
||||
print('Renamed to pages (pages-cli). Use pages configure, then pages login. See pages-cli/README.md.', file=sys.stderr)
|
||||
runpy.run_path(str(Path(__file__).resolve().parent.parent / 'pages-cli' / 'pages'), run_name='__main__')
|
||||
@@ -0,0 +1,34 @@
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from pageswiki_cli_test import pageswiki_cli
|
||||
|
||||
|
||||
class DRGuardTest(unittest.TestCase):
|
||||
def test_standby_rejected_before_database_open(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "pages.db").write_bytes(b"not a database; must not be opened")
|
||||
(root / "dr-node.json").write_text(json.dumps({"version": 1, "role": "standby"}))
|
||||
with patch.dict(os.environ, {"PAGESWIKI_DATA_DIR": directory, "PAGESWIKI_DB": str(root / "pages.db"), "PAGESWIKI_DOCUMENTS_DIR": str(root / "documents")}):
|
||||
with self.assertRaisesRegex(pageswiki_cli.CLIError, "standby"):
|
||||
pageswiki_cli.PagesWikiCLI()
|
||||
|
||||
def test_offline_maintenance_lock_blocks_cli(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "pages.db").write_bytes(b"not a database")
|
||||
with (root / ".pageswiki-instance.lock").open("wb") as lock:
|
||||
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
with patch.dict(os.environ, {"PAGESWIKI_DATA_DIR": directory, "PAGESWIKI_DB": str(root / "pages.db")}):
|
||||
with self.assertRaisesRegex(pageswiki_cli.CLIError, "maintenance guard"):
|
||||
pageswiki_cli.PagesWikiCLI()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -14,9 +14,39 @@ and future aligned translations, not as automatically current English editions.
|
||||
- Operations, i18n, ordered work, decisions and sources: chapters 18–22.
|
||||
- [Source-to-chapter inventory](ja/sources.md).
|
||||
- [Decision and inconsistency register](ja/decisions.md).
|
||||
- [Component names and responsibilities](ja/component-names.md): adopted subsystem names,
|
||||
all eight initial extractions, compatibility boundaries and the remaining component work.
|
||||
- [Dregarnuhr scheduler contract](ja/dregarnuhr.md): application registration, queue persistence,
|
||||
concurrency/retry tests and the remaining lease/HA/shutdown work.
|
||||
- [Geduldh document storage contract](ja/geduldh.md): immutable local payloads, bounded scratch copies,
|
||||
compatibility facades, Range/backfill/DR verification and remaining backend work.
|
||||
- [Mestionora search and index contract](ja/mestionora.md): SQLite/City lookup, explicit read policies,
|
||||
bounded enrichment, query-plan compatibility and remaining indexing/policy work.
|
||||
- [Ordoschnellic notification delivery contract](ja/ordoschnellic.md): bounded Web Push dispatch,
|
||||
transactional Inbox enqueue, privacy, retry/lease compatibility and remaining fencing/observability work.
|
||||
- [Schutzaria authorization and publication contract](ja/schutzaria.md): pure policy evaluation,
|
||||
immutable request snapshots, retained application checks and remaining consistency/reviewer work.
|
||||
- [Kunstzeal projection and renderer contract](ja/kunstzeal.md): stable adapter selection, bounded
|
||||
Kroki execution, source authorization, atomic derived cache and remaining provider/runtime work.
|
||||
- [Seheweit observation contract](ja/seheweit.md): bounded local collection, compatible snapshots,
|
||||
history windows/retention, cancellation and remaining availability/rollup/provider metrics work.
|
||||
- [Editor resilience subproject](ja/editor-resilience.md): drafts, conditional saves,
|
||||
conflict resolution, mobile authoring, language/history, round-trip preservation and collaboration gates.
|
||||
- [Storage portability and operations](storage-portability-and-operations.md): backend contracts,
|
||||
migration/backfill, backup/export/import and setup phases;
|
||||
[read-only schema preflight and rollout](../operations/storage-schema-rollout.md).
|
||||
|
||||
## Document roles
|
||||
|
||||
DRの詳細設計・初版CLI・復旧手順は [単一writerのDR](ja/disaster-recovery.md) を参照。
|
||||
インスタンス単位の停止snapshotと手動昇格を先行し、自動切替・オンライン同期は未実装。
|
||||
|
||||
次段階のDR-D1は**詳細設計完了・実装未着手**:
|
||||
[役割分離と再参加](ja/dr-authority-and-rejoin.md)、
|
||||
[protocol・同期・切替](ja/dr-protocol-and-sync.md)、
|
||||
[実施計画と受入試験](ja/dr-delivery-plan.md)。DB別件と独立して文書化し、
|
||||
保存側の能力契約が未提供の場合は自動切替を有効化しない。
|
||||
|
||||
`arch.md`, `address-model.md`, `access-model.md`, `auth.md` and `i18n-delivery.md`
|
||||
include original conceptual drafts. Detailed topic documents describe contracts
|
||||
and implementation slices. `implementation-status.md` contains dated progress;
|
||||
|
||||
@@ -12,6 +12,25 @@ Pages Wiki is designed as **semantic locality driven knowledge system** rather t
|
||||
- Capability-centric authorization
|
||||
- Delegated access via macaroons xxx
|
||||
|
||||
## Implementation component names
|
||||
|
||||
The adopted subsystem names and boundaries are defined in
|
||||
[Component names and responsibilities](ja/component-names.md).
|
||||
Grammaratur owns document-format conversion and authoring fidelity, Dregarnuhr
|
||||
owns in-process scheduling, and Geduldh owns immutable payload storage and bounded
|
||||
materialization. Mestionora owns SQLite search/index projections with caller-supplied
|
||||
read policies. Ordoschnellic owns bounded Web Push delivery and transport policy,
|
||||
with recipient checks and transactional Inbox enqueue retained in the application.
|
||||
Schutzaria evaluates trusted Path/locality/group/publication policy facts without I/O;
|
||||
authentication, fact loading and transactional authority remain application-owned.
|
||||
Kunstzeal owns built-in projection selection and bounded diagram-provider execution;
|
||||
source authorization and sandbox delivery remain in the application.
|
||||
Seheweit owns local resource collection and history-window/retention policy;
|
||||
authorization, queue control and SQL persistence remain in the application.
|
||||
All eight initial extractions preserve compatibility; their remaining capabilities
|
||||
are tracked separately. These names do not rename Knowledge
|
||||
City Model entities, public URIs, stored identifiers or deployment services.
|
||||
|
||||
## Knowledge City Model
|
||||
|
||||
Pages Wiki don’t only comprises Machine friendly but also Human-Facing friendly with Knowledge City Model.
|
||||
@@ -362,6 +381,12 @@ PAGE --> REV2
|
||||
PAGE --> REV3
|
||||
```
|
||||
|
||||
The staged evolution to PostgreSQL/MySQL, Redis caches, S3 and network file
|
||||
stores, together with backup/export/import and first-run setup, is defined in
|
||||
[Storage Portability and Operations](storage-portability-and-operations.md).
|
||||
The current supported runtime remains SQLite and local storage; the design
|
||||
does not imply that remote backends are already selectable.
|
||||
|
||||
Metadata is stored in the database. Immutable Document payloads use a global
|
||||
content-addressed filesystem:
|
||||
|
||||
|
||||
@@ -67,6 +67,13 @@ to `enforcing` once the bootstrap flow is complete.
|
||||
|
||||
## HTTP flows
|
||||
|
||||
Implementation clarification (2026-11-01): clients requesting JSON from
|
||||
`POST /_/auth/login` (or `/totp`) receive an opaque Bearer session rather than
|
||||
extracting a browser cookie. The remote CLI follows this existing flow and the
|
||||
same Domain membership/capability checks; see [remote CLI](ja/remote-cli.md).
|
||||
It does not implement an OIDC device handoff yet. The cookie descriptions below
|
||||
apply to browser sessions, not a requirement for all HTTP clients.
|
||||
|
||||
- `/_/auth/login`, `/_/auth/logout`, `/_/auth/callback/oidc/{provider}`
|
||||
- `/u/{username}` is the Domain-scoped profile and user-Wiki root.
|
||||
`/u/{username}/_/edit` is its owner-only profile editor and
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Data CLI
|
||||
|
||||
Remote HTTP access is a separate subproject, `pages-cli`, with the `pages`
|
||||
command (`pages-cli/pages`); see the
|
||||
[remote CLI contract and usage](ja/remote-cli.md). This local tool retains its
|
||||
trusted administrative database access and does not acquire Web credentials.
|
||||
|
||||
`data/pageswiki-cli` is a local administrative data surface. It provides
|
||||
rsync-like one-shot transfers and an interactive Semantic Path shell.
|
||||
|
||||
|
||||
@@ -25,6 +25,14 @@ notification delivery remains future work.
|
||||
External preview tools run through bounded
|
||||
commands with timeouts.
|
||||
|
||||
The in-process clock, loop, admission control and retry policy now live in
|
||||
`internal/dregarnuhr`. Application handlers are registered in
|
||||
`internal/server/event_handlers.go`; SQL ownership remains in `store` through
|
||||
the server queue adapter. The existing API, JSON, IDs and schema are unchanged.
|
||||
Admission is serialized within one runner, not across processes. Atomic claims
|
||||
are not expiring leases, and startup recovery must not run alongside another
|
||||
active writer. See [Dregarnuhr contracts and pending HA work](ja/dregarnuhr.md).
|
||||
|
||||
## Event log retention and trends
|
||||
|
||||
`event_logs` remains the recent, drill-down log. Each record is associated with
|
||||
|
||||
@@ -1,7 +1,81 @@
|
||||
# Architecture Implementation Roadmap
|
||||
|
||||
## Current highest priority (2026-10-31)
|
||||
|
||||
The user-prioritized [daily UX / browser / editor / CLI backlog](ja/priority-ux-20261031.md)
|
||||
takes precedence over the feature backlog below. It covers type-to-search, virtual
|
||||
Path navigation and browser commands, editor/plain-text and code styling, theme
|
||||
switching, session timeouts, contacts, City labels and a session-aware terminal client.
|
||||
Preserve authorization and storage safeguards. Track implementation, tests and
|
||||
deployment separately; a source checkpoint includes the pre-existing dirty worktree.
|
||||
|
||||
## Principles
|
||||
|
||||
### Named architecture components (2026-11-01)
|
||||
|
||||
- [x] Adopt stable responsibility-based names for eight components; preserve UI terminology,
|
||||
public APIs, persisted IDs, event consumer checkpoints and deployment boundaries.
|
||||
- [x] Extract Grammaratur: ordinary and protected authoring conversions, compatibility
|
||||
facades and application connections. Verification is recorded separately from deployment.
|
||||
- [x] Extract Dregarnuhr clock/loop/admission/retry contracts and the queue adapter;
|
||||
register the 14 existing business handlers outside the core. Preserve IDs/schema and atomic claims.
|
||||
- [ ] Add Dregarnuhr expiring leases, fencing, multi-process scheduling and application shutdown integration;
|
||||
these are not provided by the initial extraction. See [contract and remaining work](ja/dregarnuhr.md).
|
||||
- [x] Extract Geduldh local payload storage and bounded materialization; preserve the Document Store
|
||||
contract through aliases, connect application consumers, and test layout/Range/backfill/DR compatibility.
|
||||
External backends and placement changes remain separate work; see [contract and remaining work](ja/geduldh.md).
|
||||
- [x] Extract Mestionora SQLite search/index/City lookup with explicit read-policy callbacks,
|
||||
legacy aliases, candidate/snippet budgets, plan and authorization tests; see [search contract](ja/mestionora.md).
|
||||
- [ ] Preload lazy user-space read policies before Page search; retain snapshot consistency while
|
||||
removing nested connection requirements. Keep current-only/Domain-partitioned and language-aware indexing as later migrations.
|
||||
- [x] Extract Ordoschnellic bounded Web Push dispatch, retry policy and encrypted transport;
|
||||
preserve transactional Inbox enqueue, authorization, event IDs and subscription checkpoints.
|
||||
See [delivery contract and remaining work](ja/ordoschnellic.md).
|
||||
- [ ] Add distinct Push claim generations and subscription-version fencing, Retry-After and
|
||||
delivery metrics. Initial extraction retains existing retry/lease limitations, not exactly-once delivery.
|
||||
- [x] Extract Schutzaria pure Path/locality/group/publication/user-space evaluation and approval state transitions;
|
||||
retain authenticated fact loading, alias checks and transaction ownership in the application.
|
||||
See [policy contract and remaining work](ja/schutzaria.md).
|
||||
- [ ] Complete consistent authorization snapshots, lazy user-space preloading, reviewer inheritance/quorum,
|
||||
and publication revalidation. State-machine extraction alone does not enable the reviewer workflow.
|
||||
- [x] Extract Kunstzeal built-in adapter selection, bounded Kroki rendering and diagram hash/cache;
|
||||
retain source authorization/CSP and add redirect refusal plus atomic cache replacement.
|
||||
See [rendering contract and remaining work](ja/kunstzeal.md).
|
||||
- [ ] Add provider-versioned cache keys, render concurrency/coalescing, unified disable/metrics and
|
||||
additional diagram/slide providers. Initial extraction does not implement nwdiag or slides.
|
||||
- [x] Extract Seheweit resource collection, typed snapshots and history window/retention policy;
|
||||
retain APIs/schema/event IDs, connect foreground and background paths, bound proc reads,
|
||||
guard storage arithmetic, propagate write cancellation and reject read-only sample writes.
|
||||
See [observation contract and remaining work](ja/seheweit.md).
|
||||
- [ ] Add source availability, bounded/coalesced collection, rollups/retention budgets,
|
||||
component/provider metrics and instance-scoped HA/SNMP collectors. These are not part of the initial extraction.
|
||||
|
||||
See [component names, boundaries and acceptance criteria](ja/component-names.md).
|
||||
All eight initial component extractions are implemented; unchecked items describe remaining capabilities.
|
||||
Released and deployed as [v0.2.0](../operations/deployments/2026-11-01-v0.2.0.md) on 2026-11-01.
|
||||
|
||||
- [ ] Priority follow-up: eliminate AddEventLog deferred read-to-write transaction contention;
|
||||
preserve atomic raw-log/bucket writes and test independent concurrent writers. Production
|
||||
start-log failures are now observable; job execution succeeded, but log completeness is not guaranteed.
|
||||
|
||||
### Storage portability and operations (2026-09-27)
|
||||
|
||||
Implemented and fixture-tested; included in the [v0.2.0 production release](../operations/deployments/2026-11-01-v0.2.0.md).
|
||||
This does not mark the unchecked backend/HA capabilities below as implemented.
|
||||
|
||||
- [x] Immutable local Document Store contract, bounded materialization and streaming archive access.
|
||||
- [x] Resumable document backfill with store identity, UUID cursor and batch checkpoints.
|
||||
- [x] SQLite migration ledger with version/checksum, atomic adoption and current-schema assertions.
|
||||
- [x] Managed projection, resource, broadcast, navigation, adapter-session, import and event-queue schemas.
|
||||
- [x] Read-only `pageswiki schema status|check` with JSON output, pending steps and explicit legacy exclusions.
|
||||
- [ ] Remaining legacy schema/repository contracts and context propagation; configurable materialization limits/metrics.
|
||||
- [ ] PostgreSQL/MySQL, S3/SFTP and mounted-store contracts, optional Redis cache.
|
||||
- [ ] Coordinated backup/restore, portable export/import, Web operations and initial setup wizard.
|
||||
|
||||
See the [Japanese design and acceptance criteria](storage-portability-and-operations.md) and
|
||||
[preflight / deployment procedure](../operations/storage-schema-rollout.md).
|
||||
Passing managed-schema checks does not replace an isolated full-startup rehearsal.
|
||||
|
||||
### Task management first slice (2026-09-24)
|
||||
|
||||
2026-09-25 task CalDAV (`0.8.0`, implemented and fixture-tested, **deployed to app/app2 on 2026-09-26 at 00:24 JST**; [deployment record](../operations/deployments/2026-09-26-task-caldav.md)):
|
||||
@@ -443,6 +517,12 @@ without changing user-visible Page identity.
|
||||
|
||||
## Phase 6 — Activity, notification, and collaboration
|
||||
|
||||
- [x] Editor resilience E1–E5 initial delivery: local drafts, conditional language-head saves,
|
||||
conservative merge/conflict review, revision restore, language forks, mobile input, macro completion,
|
||||
and protected HTML authoring blocks. See [Japanese implementation contract](ja/editor-resilience.md).
|
||||
- [ ] Editor E6: authorized cross-instance editing presence and feature-gated CRDT collaboration.
|
||||
Follow-up: block-level HTML protection, hosted-editor/CLI migration, and extensible insertion palette.
|
||||
|
||||
- [ ] Formalize a Domain-sequenced event outbox for Page, Revision, Path,
|
||||
topology, policy, share, comment, reaction, quality, and federation events.
|
||||
- [ ] Add Page/Spot/Street/Quartier subscription and change-notification rules.
|
||||
@@ -479,6 +559,43 @@ without changing user-visible Page identity.
|
||||
|
||||
## Phase 8 — Controller disaster recovery and high availability
|
||||
|
||||
First slice: [Japanese DR design and operator runbook](ja/disaster-recovery.md).
|
||||
This is **instance-scoped offline recovery**, not automatic controller HA.
|
||||
|
||||
DR-D1 follow-up is **design complete, implementation pending** (2026-09-27):
|
||||
[authority/rejoin](ja/dr-authority-and-rejoin.md),
|
||||
[protocol/synchronization](ja/dr-protocol-and-sync.md),
|
||||
[delivery plan and acceptance matrix](ja/dr-delivery-plan.md).
|
||||
No DB/schema/code changes were made for this design-only follow-up.
|
||||
|
||||
- [x] Specify separate controller/data authority, shared-writer coupling,
|
||||
authenticated rejoin/probe, Learning state, checkpoint verification,
|
||||
fenced handover/preempt, API contracts, rollout gates and acceptance tests.
|
||||
- [ ] DR01–DR03: implement validated models, pure state machine and
|
||||
observation-only authenticated probe; discovery must not grant write access.
|
||||
- [ ] DR04–DR05: connect restart write gates and authority providers only after
|
||||
the separately managed storage interfaces and all writer paths are agreed.
|
||||
- [ ] DR06–DR10: connect consistent checkpoints, bounded resumable transfer,
|
||||
epoch-aware control manifests, verified fencing and manual group transitions.
|
||||
- [ ] DR11–DR13: certify preempt policy, scoped operator UI and failure drills;
|
||||
automatic lossless failover requires an independently verified durability boundary.
|
||||
|
||||
- [x] Node-local primary/standby configuration; read-only SQLite startup without
|
||||
migrations, key generation, scheduler, GC or managed-campus reconciliation.
|
||||
- [x] Offline snapshot/verify/restore CLI: committed WAL via SQLite Backup API,
|
||||
canonical files and keys, payload/reference verification, atomic new generations.
|
||||
- [x] Offline operator-attested promotion, old-primary identity/data-loss checks,
|
||||
promotion audit and explicit restored-job resumption. External fencing itself
|
||||
is not implemented or independently verified by these commands.
|
||||
- [x] Reject standby writes and stale reads; separate read/write readiness;
|
||||
coordinate server and data CLI with an instance maintenance lock.
|
||||
- [ ] Rebuild-free read-only organizer/CalDAV paths, standby UI/role indicators,
|
||||
DR settings panel and instance-operator authorization.
|
||||
- [ ] Online cross-store snapshot barrier, GC pins, resumable bounded delta
|
||||
transfer, encrypted/signed generations, retention and measured restore drills.
|
||||
- [ ] Restore controller sequence safely across accepted newer manifests; local
|
||||
audit epoch alone does not solve managed-instance replay protection.
|
||||
|
||||
- [ ] Add controller manifest journal replication to a designated DR instance,
|
||||
including signing-key rotation/escrow, encrypted backup, sequence verification,
|
||||
last-known-good snapshots, RPO/RTO reporting, and restore drills.
|
||||
@@ -519,6 +636,8 @@ without changing user-visible Page identity.
|
||||
freezing and configured hosted-editor actions.
|
||||
- [ ] Add Kroki and PlantUML diagram adapters with bounded input, pinned renderer
|
||||
version, cached immutable output, timeout, and network policy.
|
||||
Existing bounded Kroki execution is now in Kunstzeal; renderer-version keys and complete
|
||||
provider network/resource policy remain pending rather than marking this whole item complete.
|
||||
- [ ] Add nwdiag as a bounded network-diagram projection and editor adapter;
|
||||
support static SVG fallback, pinned renderer versions, and explicit source
|
||||
import/save without executing authored code.
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
更新:2026-09-25。実装・隔離fixture検証済み。同日05:59 JSTに本番2インスタンスへ反映済み。[反映記録](../../operations/deployments/2026-09-25-active-notifications-calendar-mobile.md)。実機Push受信確認は未実施。
|
||||
|
||||
2026-11-01追記:配送処理を [Ordoschnellic](ordoschnellic.md) へ初期分離。
|
||||
以下のUI・API・DB・購読を維持するソース変更であり、この分離自体は未デプロイ。
|
||||
claim世代と購読更新競合を含む配送保証・残件は同契約に記録する。
|
||||
|
||||
## UIと設定
|
||||
|
||||
通知ベルを開いたInboxの「⚙ 通知設定」に集約する。アカウント・ドメイン・ブラウザごとにlocalStorageへ保存し、他ユーザの設定を継承しない。通知本文はlocalStorageに保存しない。
|
||||
@@ -29,7 +33,7 @@
|
||||
- POST: PushSubscription、focused、seen(最大30通知ID)。購読更新/閲覧中のack。
|
||||
- DELETE: 現在の利用者が所有する購読を削除。
|
||||
|
||||
購読はDomain・Principal・**元の認証セッションのハッシュ**に束縛する。Bearer tokenは保存しない。配信時にセッション期限/失効、Principal、membership、Domain配置を再確認する。ログアウト後や無効化後は送信しない。最大8購読/利用者・Domain、30日lease(閲覧時に更新)。
|
||||
購読はDomain・Principal・**元の認証セッションのハッシュ**に束縛する。Bearer tokenは保存しない。claim時にセッション期限/失効、Principal、membership、Domain配置を再確認する。この時点でログアウト済み・無効化済みなら送信しない。claim後の失効と送信の競合は残る。最大8購読/利用者・Domain、30日lease(閲覧時に更新)。
|
||||
|
||||
VAPID秘密鍵は`notification_push_keys`に保存するため、DBバックアップを秘密情報として扱う。鍵を失った復旧では再購読が必要。端末の購読URL・鍵・通知本文をログへ出さない。
|
||||
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
状態:パスワード・TOTP・セッション、OIDC、LDAP、SMTPリンク、グループと主要な認可経路は実装済み。全経路の監査完了を意味しません。
|
||||
|
||||
2026-11-01、純粋な権限・公開範囲の評価を [Schutzaria](schutzaria.md) へ初期分離。
|
||||
認証・権限情報の読込・更新transactionは既存側に残し、API・ACL設定・公開範囲は変更しません。
|
||||
承認の継承・reviewer定足数を実装済みとするものではありません。
|
||||
|
||||
## 認証から認可へ
|
||||
|
||||
認証器はPrincipal identityを証明します。その後、Domain membership、グループ・Role、対象操作のcapability、上位Localityの制限を評価します。OIDCのclaimやメールアドレスだけで管理権限を付与しません。
|
||||
|
||||
@@ -33,6 +33,12 @@ Domain間PSKによるidentity・group継承は設計段階です。署名付き
|
||||
|
||||
## TODOと合格条件
|
||||
|
||||
DRの次段階は [管理主系とデータ主系の分離](dr-authority-and-rejoin.md) と
|
||||
[管理manifestの世代・受理契約](dr-protocol-and-sync.md) を参照する(詳細設計のみ)。
|
||||
Campusを管理するprimaryと、Domainデータに書き込むprimaryは別authority。
|
||||
ただし同じDBを正本として共有する役割は物理的なwriter切替を連動させる。
|
||||
保存済みroleやprobe応答だけで復帰ノードをprimaryにしない。
|
||||
|
||||
- 反映ACK、設定管理の解除、削除ドメインの保持・GC。
|
||||
- 同名・異originのグループ衝突、PSK失効、sequence欠落、鍵交換の試験。
|
||||
- 秘密の外部管理と明示的なローテーション手順。
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
# PagesWiki のコンポーネント命名と責務
|
||||
|
||||
2026-11-01 採用。神名を実装アーキテクチャの部品名として使用する。
|
||||
Grammaratur、Dregarnuhr、Geduldh、Mestionora、Ordoschnellic、Schutzaria、Kunstzeal、Seheweit の
|
||||
8部品の初期分離を実装した。初期分離と各部品の後続機能・本番展開の完了は区別する。
|
||||
|
||||
## 由来と適用範囲
|
||||
|
||||
プロジェクト名 pages は、作者の意図として Little Glee Monster の楽曲 pages に由来する。
|
||||
Knowledge City Model は『とある科学の超電磁砲』の学舎の園に着想を得た知識の配置モデル。
|
||||
このモデルの Campus、Domain、Quartier、Street、Spot、Page は変更しない。
|
||||
|
||||
内部の機能分担には『本好きの下剋上』の神々の名前を用いる。
|
||||
作品の役割とソフトウェアの役割を重ねる命名の参考は
|
||||
[TOMOYO Linux 作者の説明](https://i-love.sakura.ne.jp/tomoyo/)。
|
||||
名前の参照表は [プロジェクト作者の Gist](https://gist.github.com/anya-tokugawa/d3939b16298937f8b7e39a6ec3595464)。
|
||||
以下の英字表記は PagesWiki 内の採用表記であり、作品の公式翻訳表記を定義するものではない。
|
||||
|
||||
## 採用した部品名
|
||||
|
||||
| 部品名 | 内部識別名 | 担当範囲 | 担当しないもの |
|
||||
| --- | --- | --- | --- |
|
||||
| Mestionora メスティオノーラ | `mestionora` | 索引、検索、知識間の関連性の解決 | 正本保存、認可の独自判断、編集UI |
|
||||
| Grammaratur グラマラトゥーア | `grammaratur` | 文書形式変換、変換時の情報保全、変換診断 | 認可、画面用sanitizer、macro展開、Revision保存 |
|
||||
| Geduldh ゲドゥルリーヒ | `geduldh` | 内容アドレス付きDocumentの保存・取得・完全性検証 | 認証やタスク等の全DB、参照なしを独断判定するGC |
|
||||
| Dregarnuhr ドレッファングーア | `dregarnuhr` | 実行時刻、ジョブ投入・実行制御、リース、再試行 | カレンダーやタスクの業務ルール、通知本文・宛先 |
|
||||
| Ordoschnellic オルドシュネーリ | `ordoschnellic` | イベントに応じた通知、宛先別配送、配送状態 | 業務変更の生成、正本トランザクションの所有 |
|
||||
| Schutzaria シュツェーリア | `schutzaria` | 権限評価、公開範囲、共有・承認ポリシーの評価 | 個々のOIDC/LDAPプロバイダー実装、表示用HTML変換 |
|
||||
| Kunstzeal キュントズィール | `kunstzeal` | 図・スライド等の描画プロバイダー実行基盤 | 独自描画エンジンの強制、文書正本の変更 |
|
||||
| Seheweit ゼーエヴァイト | `seheweit` | リソース・稼働状態の収集、集約、観測 | ジョブ制御や観測対象の業務処理 |
|
||||
|
||||
名前はリリースごとに変えず、責務と共に維持する。バージョンは従来の SemVer 2.0.0 を継続する。
|
||||
機能を増やすためだけに神名を追加せず、境界と受入条件が成立してから部品を作る。
|
||||
神々の系譜や関係を依存グラフ、権限の上下関係、配置単位へ強制的に写さない。
|
||||
|
||||
## 実装と運用の命名規則
|
||||
|
||||
- パッケージ名は小文字の内部識別名、設計上の部品名は先頭大文字の表記とする。
|
||||
`DocumentStore` 等の契約・インターフェースと `PutIfAbsent` 等の操作名は技術用語を使う。
|
||||
- 1部品は1コンテナを意味しない。プロセス内のパッケージとして分離でき、独立配置は別判断。
|
||||
- UIは検索、通知、権限設定などの通常名を維持する。神名の理解を利用条件にしない。
|
||||
管理者向けの診断や設計文書には、神名と一般的な役割名を併記できる。
|
||||
- URI、既存のprovider/extension ID、設定キー、DB名、保存形式、イベント型、consumer ID、
|
||||
レジストリ上のイメージ名を命名のためだけに変更しない。特にconsumer IDの改名で
|
||||
既存checkpointを失い、通知や処理を再実行することを防ぐ。
|
||||
- 新たなログ・トレースで識別が必要なら固定の `component=grammaratur` 等を用いる。
|
||||
文書本文や認証情報は記録しない。無条件に変換ごとのログを追加しない。
|
||||
- 既存の `server` / `store` 一式を神名へ置換しない。呼び出し契約・テストを確立してから
|
||||
部品を抽出し、移行中は一方向の互換ラッパーを残す。実装を二重に保守しない。
|
||||
|
||||
## Grammaratur の実装契約
|
||||
|
||||
初期実装は `internal/grammaratur`。HTTP、DB、ファイル、ネットワークへ直接アクセスせず、
|
||||
文字列の変換だけを行う。認可と入力サイズ上限は呼び出し元が検証する。
|
||||
|
||||
| 関数 | 契約 |
|
||||
| --- | --- |
|
||||
| `HTMLToMarkdown` | 従来の通常変換。保護フェンスを理解しない外部エディタ等にも渡せる。変換損失の可能性は従来どおり |
|
||||
| `MarkdownToHTML` | 従来のMarkdown方言とオプションを維持した通常変換 |
|
||||
| `HTMLToMarkdownAuthoring` | 往復変換で構造・属性・文字が変わる場合は元HTMLを保護ブロックに保持 |
|
||||
| `MarkdownAuthoringHTML` | 明示的にauthoringを選んだ呼び出しだけで `{=html}` ブロックをHTMLへ戻す |
|
||||
|
||||
出力は表示を許可されたHTMLではない。ブラウザー表示時は従来どおり認可・macro展開・
|
||||
sanitizer・CSPを適用する。原文の保全とスクリプトの実行許可を混同しない。
|
||||
通常変換を保護ブロック対応へ暗黙に切り替えず、hosted editor の保存形式も変更しない。
|
||||
|
||||
`internal/compiler` のHTML/Markdown変換関数と `render.Markdown` は Grammaratur へ委譲する。
|
||||
組み込みエディタ、authoring API、Markdown出力、hosted editor のHTML入力変換は
|
||||
Grammaratur を直接呼び出す。既存の通常Markdown呼び出しは `render.Markdown` 経由でも
|
||||
同じ実装を使う。図のhash等、文書形式変換以外の `compiler` の処理は今回移さない。
|
||||
|
||||
依存方向は呼び出し元 → Grammaratur → 変換ライブラリ。
|
||||
Grammaratur から server/store/db/render/compiler へ戻る依存は作らない。
|
||||
新たな形式や詳細診断を追加する場合も、この境界を維持する。
|
||||
|
||||
## 移行順序と受入条件
|
||||
|
||||
1. **Grammaratur 初期分離**:通常変換と保護変換を集約。既存の関数・API・返却形式を維持。
|
||||
通常変換の旧ライブラリ出力との一致、互換ラッパー、保護ブロック、エディタ、
|
||||
hosted editor、表示安全性、ドキュメントexportを検証する。
|
||||
2. **Dregarnuhr 初期分離**:現行schedulerから汎用の時刻・retry・dispatch契約を抽出。
|
||||
preview、City、calendar、taskの実行ハンドラーは登録型の利用者として残す。
|
||||
fake clockとworker競合試験で優先度・実行上限・既存claimを検証する。
|
||||
期限付きlease・fencingは既存実装にもなく、初期分離には含めない。
|
||||
[実装契約と後続TODO](dregarnuhr.md) を参照。
|
||||
3. **Geduldh 初期分離**:既存 `documentstore.Store` 契約をaliasで維持し、
|
||||
ローカル保存と検証付き一時展開の実装を `internal/geduldh` に分離。
|
||||
filesystem layout、hash、Range、streaming、移行・DR手順を変えない。
|
||||
大きな `store` パッケージ全体の改名はしない。[文書保存契約と残件](geduldh.md) を参照。
|
||||
4. **Mestionora 初期分離**:SQLite検索・索引・City検索を分離し、
|
||||
呼出し元の権限判定と既存の候補・抜粋予算を維持。[検索と索引契約](mestionora.md) を参照。
|
||||
5. **Ordoschnellic 初期分離**:Web Pushの有界配送・再試行・暗号化を抽出し、
|
||||
Inboxの原子的登録と購読checkpointを維持。再送が起こり得る既存の保証範囲を変更しない。
|
||||
[通知配送契約と残件](ordoschnellic.md) を参照。
|
||||
6. **Schutzaria 初期分離**:DB非依存の読み取り・Locality・グループ・公開範囲・承認状態評価を分離。
|
||||
認証・DB読込・公開確定transactionは既存側に残す。[権限評価契約と残件](schutzaria.md) を参照。
|
||||
7. **Kunstzeal 初期分離**:ビルトイン表示方式の選択、Krokiの有界描画、図hash/cacheを分離。
|
||||
認可・ソース由来・CSPを維持し、redirect拒否とcache原子的置換を追加。[描画契約と残件](kunstzeal.md) を参照。
|
||||
8. **Seheweit 初期分離**:リソース収集と履歴保持・bucket規則を分離。現在値APIと背景監視を接続し、
|
||||
収集読込上限・容量計算・取消/read-only保存を補強。認可とSQLは既存側に残す。[観測契約と残件](seheweit.md) を参照。
|
||||
|
||||
この移行は配置変更、DB migration、機能追加を必須にしない。各段階でソース変更、
|
||||
テスト、commit、CI、デプロイを別々に記録する。本番反映は検証後の別操作とする。
|
||||
|
||||
## 今回の変更範囲
|
||||
|
||||
- 採用済み:8部品の名称と責務、互換性と依存方向の規則。
|
||||
- 実装済み:8部品の初期分離、旧入口の委譲、利用側の接続、境界・互換性テスト。
|
||||
- 後続:Dregarnuhr のリース・fencing・終了処理、
|
||||
Grammaratur の形式追加・詳細診断・ブロック単位の保護、Geduldh の外部backend・配置分離、
|
||||
Mestionora のポリシー事前読込・現行専用索引・言語別検索、Ordoschnellic のclaim世代・購読更新競合・配送観測、
|
||||
Schutzaria の権限読込の一貫性・承認継承・権限総覧、Kunstzeal のprovider版・実行予算・描画形式の拡充、
|
||||
Seheweit の情報源別availability・収集予算・rollup・component別観測・HA/SNMP。
|
||||
- 対象外:既存DBと本番データの変更、UIの改名、画像やロゴの利用、コンテナ分割、本番展開。
|
||||
|
||||
## 検証記録
|
||||
|
||||
2026-11-01、合成データと一時DBで以下を確認した。本番データへの操作は行っていない。
|
||||
|
||||
- `go test ./...` 成功。保存層・サーバー・CLI・設計書exportを含む。
|
||||
- `go test -race ./internal/grammaratur -count=1` 成功。
|
||||
- `go vet ./internal/grammaratur ./internal/compiler ./internal/render` 成功。
|
||||
- `PAGESWIKI_BROWSER_TEST=1` の `TestEditorResilienceChromium` と
|
||||
`TestHTMLProjectionChromium` 成功。編集・保存・競合・言語分岐・HTML保全と、
|
||||
9つの表示/編集経路の安全性を確認。
|
||||
- `git diff --check` 成功。
|
||||
|
||||
同日、Dregarnuhr の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。store・serverを含め全Goパッケージの回帰テストを実行。
|
||||
- `go test -race ./internal/dregarnuhr -count=1` 成功。
|
||||
- store/serverの `TestDregarnuhr*`、`TestClaimDueEvent*` とコアの境界・実行制御試験を
|
||||
race detector付きで実行し成功。外部カレンダーは実行せず、登録の確認だけを行った。
|
||||
- `go vet ./internal/dregarnuhr ./internal/store ./internal/server` 成功。
|
||||
- `git diff --check` 成功。今回ブラウザ試験の再実行はしていない。
|
||||
|
||||
同日、Geduldh の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。保存・サーバー・CLI・DR・設計書exportを含む。
|
||||
- `go test -race ./internal/geduldh ./internal/documentstore -count=5` 成功。
|
||||
新旧入口の型・エラー・保存キー互換、並行保存、一時コピーの共有と回収を確認。
|
||||
- store/server/DRの文書保存、バックフィル、Range配信、認可付き不変オブジェクト配信、
|
||||
ZIPの部分取得、Materialize、snapshot/restore試験をrace detector付きで実行し成功。
|
||||
- 保存失敗時のRevision非確定、DB競合時のpayload保全、Geduldhから保存したバイト列のDR復元を確認。
|
||||
- `go vet ./internal/geduldh ./internal/documentstore ./internal/store ./internal/dr` 成功。
|
||||
- `git diff --check` 成功。今回ブラウザ試験は再実行していない。
|
||||
|
||||
同日、Mestionora の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。既存DBを読む任意診断は無効にし、一時DB・合成データのみで実行。
|
||||
- Mestionoraの境界・認可・FTS実行計画をrace detector付きで3回反復し成功。
|
||||
- store/serverを含む検索、City、型・エラー互換、Domain/alias分離のテストを
|
||||
race detector付きで実行し成功。
|
||||
- `go vet ./internal/mestionora ./internal/store ./internal/server` 成功。
|
||||
- `TestSearchResultsChromium` 成功。1440pxと390pxでCity先頭表示、3表示モード、
|
||||
フィルター、リンク、危険なHTMLの文字列表示と横方向のはみ出し防止を検証。画像も目視確認。
|
||||
- 索引初期化・更新SQLはpackage/receiver/DBフィールドの移動以外が同一であることを確認。
|
||||
- `git diff --check` 成功。ポリシーの遅延DB参照に伴う接続制約は後続TODOとして記録。
|
||||
|
||||
同日、Ordoschnellic の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。既存DBを読む任意診断は無効にし、一時DB・合成データのみで実行。
|
||||
- `go test -race ./internal/ordoschnellic -count=5` 成功。
|
||||
バッチ上限、キャンセル後の終了保存、暗号化payload、HTTP分類、未設定clientでの送信禁止、依存境界を確認。
|
||||
- store/serverの通知・Activity Subscription・Task Activity・失効済みfocus通知と新規配送試験を
|
||||
race detector付きで3回反復し成功。並行claim、lease境界、旧attempt完了の拒否、
|
||||
認証/Domain/受取人の不一致、focused延期、backoff、Inbox保全、checkpoint継続を確認。
|
||||
- 追加した有界清掃・read-only拒否試験もrace detector付きで3回反復し成功。
|
||||
- `go vet ./internal/ordoschnellic ./internal/store ./internal/server` と `git diff --check` 成功。
|
||||
- 外部通知サービスへの送信・実端末Push受信・ブラウザ試験は今回実施していない。
|
||||
UIとService Workerは変更せず、配送の障害競合は後続TODOとして記録。
|
||||
|
||||
同日、Schutzaria の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。本番DBを読む任意診断を無効化し、一時DB・合成データで実行。
|
||||
- `go test -race ./internal/schutzaria -count=5` 成功。親子制限の交差、肯定grantの範囲、
|
||||
snapshotのコピー・並行参照、グループプロファイル、公開上限、予約Path、ユーザー領域、承認状態を検証。
|
||||
- store/serverのPath・Locality・匿名公開・公開ナビゲーション失効・グループ継承失効・
|
||||
governance・承認・endpoint判定をrace detector付きで2回反復し成功。
|
||||
- 新規のstore型/JSON/エラー互換、4,096件上限、DB失敗時の不完全policy拒否試験を
|
||||
race detector付きで3回反復し成功。
|
||||
- `TestCityGovernanceChromium` 成功。隔離fixtureで所有者委譲・公開上限・アクセス設定を操作し、保存結果を確認。
|
||||
- 抽出対象8ファイルのSQLリテラル(スキーマ・triggerを含む)が変更前と同一であることを確認。
|
||||
- `go vet ./internal/schutzaria ./internal/store ./internal/server` と `git diff --check` 成功。
|
||||
|
||||
同日、Kunstzeal の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。実Krokiではなくlocalhostの偽provider、一時DB・合成ソースを使用。
|
||||
- `go test -race ./internal/kunstzeal -count=5` 成功。表示順・catalogコピー・kind/hash互換、
|
||||
入出力上限、取消、エラー非開示、cacheの並行読取と原子的置換を検証。
|
||||
- serverのKunstzeal・既存diagram認可分離・表示形式・hosted adapter設定・HTML projection等を
|
||||
race detector付きで3回反復し成功。301/302/307/308の転送拒否、cache保存失敗時の表示継続も確認。
|
||||
- 追加の由来情報なし/期限切れのディスクcache拒否試験もrace detector付きで3回反復し成功。
|
||||
- `TestHTMLProjectionChromium` 成功。既存の9表示/編集経路で正本と表示の信頼境界を確認。
|
||||
- registry定義は型名の公開化以外が同一であることを確認。nwdiagは実装済みcatalogに存在しないため、設計書の状態を訂正。
|
||||
- `go vet ./internal/kunstzeal ./internal/compiler ./internal/server` と `git diff --check` 成功。
|
||||
- 実Kroki・本番ネットワーク・取り込み済み外部カレンダーへのアクセスは行っていない。
|
||||
|
||||
同日、Seheweit の初期分離後にも以下を確認した。
|
||||
|
||||
- `go test ./...` 成功。本番DBの任意診断は無効化し、一時DB・合成データで実行。
|
||||
- `go test -race ./internal/seheweit -count=5` 成功。JSON互換、情報源の失敗、proc読込上限、
|
||||
容量のoverflow/underflow防止、I/Oの取得可否とprocess identity、並行収集、履歴windowを検証。
|
||||
- store/serverのSeheweit・既存リソース監視・履歴・実行状態API試験をrace detector付きで3回反復し成功。
|
||||
同一jobの重複防止、保持境界、bucket代表の互換、取消、read-only保存拒否、清掃失敗時rollback、
|
||||
APIの期間fallbackと空配列、GETが履歴保存しないこと、認可・設定保持も確認。
|
||||
- `TestExecutionMonitorChromium` 成功。隔離fixtureで実行状態・リソース画面と設定ダイアログを操作し、
|
||||
監視間隔120秒の保存まで確認。2画面のスクリーンショットも確認。
|
||||
- `go vet ./internal/seheweit ./internal/store ./internal/server` と `git diff --check` 成功。
|
||||
- 本番DB・本番ネットワーク・取り込み済み外部カレンダーへのアクセスは行っていない。
|
||||
|
||||
8部品の初期分離はソース変更と検証まで完了。commit・push・本番展開は本作業に含めていない。
|
||||
|
||||
その後の明示的なリリース依頼により、同日 `v0.2.0` としてcommit・push・CI・本番反映を完了した。
|
||||
[配布digest・移行・復旧点・開始ログ競合の継続課題](../../operations/deployments/2026-11-01-v0.2.0.md)
|
||||
は初期分離の検証記録と分けて管理する。
|
||||
@@ -0,0 +1,194 @@
|
||||
# DR:単一書き込みノードと検証済み復旧世代
|
||||
|
||||
状態:2026-09-27、設計と第1段階の実装。自動フェイルオーバー、オンライン同期、設定画面は未実装。本番への適用・実データでの復旧訓練は別の承認を得て行う。
|
||||
|
||||
**次段階の詳細設計DR-D1が完了(文書のみ)**:
|
||||
[管理主系・データ主系と再参加](dr-authority-and-rejoin.md)、
|
||||
[通信・同期・切替protocol](dr-protocol-and-sync.md)、
|
||||
[実施計画・受入試験](dr-delivery-plan.md)。
|
||||
本書は既存offline実装の記録として保持する。次段階の判断・実装順はDR-D1を優先する。
|
||||
DBは別件の変更対象のため、本詳細設計作業ではDB・schema・実装コードを変更していない。
|
||||
|
||||
## 1. 基本方針
|
||||
|
||||
Campus / Domain の意味、UUID、FQDN、所属関係を変えず、**そのデータを動かすインスタンスの復旧構成**を追加する。通常時は primary だけが書き込み、standby は検証済みの過去世代を読み取り専用で扱う。ネットワーク疎通失敗だけでは昇格しない。
|
||||
|
||||
「相手が落ちた」と「こちらから相手へ接続できない」は区別できない。2台だけで相互監視して両方が書き込みを開始すると、SQLite のトランザクションが各ノードで正常でも、全体では異なる正本が生まれる。旧 primary の電源・ストレージ・通信経路を外部で確実に隔離する **fencing** を昇格の前提とする。初版のコマンドは運用者の確認記録を残すもので、fencing 自体を実行・保証しない。
|
||||
|
||||
### 復旧の単位
|
||||
|
||||
現状の `pages.db` は複数 Campus / Domain の情報を共有する。したがって第1段階は **データディレクトリ全体=1インスタンス**を複製・昇格する。Campus の設定欄だけで1 Campusを昇格させ、同じDB内の別Campusを読み取り専用に残す操作は提供しない。
|
||||
|
||||
コントローラと配下の管理インスタンスはそれぞれ別の復旧単位。コントローラのスナップショットにはリモート配置 Domain の設定は含まれるが、別インスタンスにある記事の実体までは含まれない。それぞれ保全する。
|
||||
|
||||
## 2. 論理モデル
|
||||
|
||||
| 項目 | 意味・保全先 |
|
||||
| --- | --- |
|
||||
| Campus / Domain UUID・FQDN | 既存の論理 identity。復旧でも変更しない |
|
||||
| `cluster_id` | 同じ復旧単位の primary / standby をまとめるUUID |
|
||||
| `node_id` | DRノード固有のUUID。復元時に新規採番する |
|
||||
| `primary_node_id` | スナップショットの作成元、または昇格後の自ノード |
|
||||
| `role` | `primary` / `standby`。プロセス起動時に読み、稼働中には変更しない |
|
||||
| `epoch` | 手動昇格の監査世代。**分散ロック・署名manifestのfencing tokenではない** |
|
||||
| `snapshot_id`, `captured_at` | 復元世代と保全開始時刻。再起動で鮮度をリセットしない |
|
||||
| `max_read_age_seconds` | 待機系の閲覧期限。初期値3,600秒、設定範囲1〜86,400秒 |
|
||||
| `workers_enabled` | キュー、GC、管理Campus reconcilerの再開許可。復元・昇格直後はfalse |
|
||||
| `promotion_history` | 時刻、旧primary UUID、隔離の証跡、復元世代、epoch |
|
||||
|
||||
設定は `data/dr-node.json`。これは**ノード固有**なのでprimaryのファイルをstandbyへ丸ごとコピーしない。`dr restore` がstandby用に生成する。`dr-node.json` を削除して昇格してはいけない。設定のない既存インスタンスは後方互換のため従来の書き込み可能起動となる。
|
||||
|
||||
DRホストの起動環境には `PAGESWIKI_DR_EXPECT_ROLE=standby` を指定する。設定が欠けた空volumeや、異なるroleのvolumeを誤mountした場合はDBを作らず起動を拒否する。昇格後に再起動するときだけ、配置設定も `primary` へ変更する。これは役割を変更する設定ではなく、期待した役割と実際が一致することを確認する安全装置。
|
||||
|
||||
既存の `instance-ed25519.key` と認証鍵は復旧する論理サービスの鍵であり、DRの物理 `node_id` とは別。鍵の複製を持つ旧ノードは確実に隔離する。
|
||||
|
||||
## 3. 初版の状態遷移とAPI
|
||||
|
||||
1. 既存 primary を停止し、`dr init` でノード設定を作成する。
|
||||
2. 全writer停止中に `dr snapshot` で世代を作成する。primaryは完了後に再開できる。
|
||||
3. 別ホストへ転送し、`dr verify` → `dr restore`。復元結果は常にstandby。
|
||||
4. standby を別のローカルデータディレクトリから起動する。データvolumeは **read-only mount** とする。primaryとSQLiteファイルを共有しない。
|
||||
5. 障害時は旧primaryを永続的に隔離し、standbyも停止して `dr promote`。
|
||||
6. 復元後の権限・鍵・設定・キューを確認し、必要な修正をした上で、書き込み可能mountで再起動する。LB/DNSの切替は外部運用。
|
||||
7. キューの重複実行・外部送信を検討して、停止中に `dr resume-workers`。再起動でジョブとreconcilerが動く。
|
||||
|
||||
`dr promote` と `dr resume-workers` はホスト運用者向けCLIに限定する。`campus_admin` や `domain_admin` が他Campusを巻き込んでインスタンス全体の役割を変えるHTTP APIは設けない。
|
||||
|
||||
### 待機系の動作
|
||||
|
||||
- SQLiteを `mode=ro` + `query_only` で開く。マイグレーション、Ensure系の初期化、認証鍵生成を行わない。
|
||||
- 書き込みHTTPメソッドを503で拒否する。認証発行、エディタ起動、外部エディタ起動、外部図表レンダリング、設定・連携・インポートも拒否する。POSTを成功扱いで捨てない。
|
||||
- GC、イベントスケジューラ、preview生成、外部カレンダー同期、Campus reconcilerを起動しない。
|
||||
- 普通のWiki文書・RAWの読み取りは従来の認可を通す。既存sessionもスナップショット時点のものに限る。新規ログインは不可。
|
||||
- **初版のorganizer/CalDAVと拡張機能APIはstandbyでは503**。既存の読み取り経路にDB索引の修復・資格情報の更新があるため。昇格後は通常の機能を使える。全機能のread replicaを実装済みとはしない。
|
||||
- レスポンスは `X-PagesWiki-DR-Role: standby`、`Cache-Control: private, no-store`。RAWの長期cache指定よりも優先する。
|
||||
- 古くなった復元世代からの閲覧は503で閉じる。`/health` は生存確認だけで、書き込み可能の判定に使用しない。
|
||||
- `GET /health/read` はDB接続と閲覧期限を検査する。`GET /health/write` はstandbyで常に503。primary側の200も**他ノードが停止している証明ではない**。
|
||||
|
||||
公開範囲縮小、アカウント失効、セッション失効は保全時点より後の変更が反映されない。閲覧期限はその時間を制限するだけで即時失効を保証しない。第1段階ではstandbyは運用者の隔離された検証環境とし、通常の読み取りLBには組み込まない。実際に外部公開へ切り替える前に、復旧時点以降の権限縮小・失効を再適用する。
|
||||
|
||||
## 4. バックアップの内容と整合性
|
||||
|
||||
| 対象 | 取扱い |
|
||||
| --- | --- |
|
||||
| `pages.db` | SQLite Backup APIで複製。コミット済みWALを含め、rowidを保存する |
|
||||
| `documents/**` | 記事・asset・taskのCASと、カレンダーの月別ICS・metadataを含む |
|
||||
| `themes/**` | ローカルテーマ |
|
||||
| `auth.key`, `instance-ed25519.key` | 存在する場合に保全。極めて機密性が高い |
|
||||
| `federation/**` | 管理Campus参加token・endpointなどの復旧情報 |
|
||||
| `dr-node.json` | **除外**。復元先でstandby用に新規生成 |
|
||||
| preview・一時import・編集中adapter workspace | 除外。未保存編集は復旧対象外 |
|
||||
| Docker image、Compose、環境変数、TLS鍵、外部volume | このCLIの対象外。別の保全対象台帳で管理 |
|
||||
|
||||
`PAGESWIKI_AUTH_KEY` を環境変数で与えている場合、それも別の暗号化されたsecret保全が必要。復旧先に**同じ値**を供給しないと既存認証・暗号化情報を復旧できない。CLIは環境変数の秘密値をmanifestに書かない。復旧に使用するアプリのimage digestと設定・secretの世代を運用記録に残し、まず同じバージョンで復元する。
|
||||
|
||||
### なぜ初版は停止バックアップか
|
||||
|
||||
SQLite Backup APIはDB内の整合性を確保するが、同時に更新中の `calendar.json` や別ファイルまで同じ論理時点へ固定しない。DBとファイル正本の境界にglobal snapshot barrierがない現状では、稼働中の `cp` / `rsync data/` を整合バックアップとはみなさない。
|
||||
|
||||
全てのWebサーバ、CLI、旧バイナリ、SQLite直接編集、外部writerを止める。新しいサーバ・データCLIは `.pageswiki-instance.lock` の共有ロックを保持し、保全・昇格は排他ロックで稼働中を拒否する。ただしこれは協調ロックであり、旧版や外部ツールを強制停止する機能ではない。`--writers-stopped` は実際の停止を運用者が確認したことの明示。
|
||||
|
||||
### 世代の作成・転送・復元
|
||||
|
||||
- 同じfilesystem内の一時ディレクトリへ作成し、ファイルfsync、manifest検証後にno-replaceのatomic renameで公開する。既存の保存先へ上書きしない。Linuxの `renameat2(RENAME_NOREPLACE)` を必要とする。
|
||||
- manifestはsnapshot/cluster/source-node/epoch、保全開始・完了時刻、相対path・size・SHA-256の一覧を持つ。初版は最大100,000ファイル、manifest最大64MiB。
|
||||
- 全payloadのSHA-256、CASファイル名、DBの `quick_check`、Revision/asset/task正本参照の存在、カレンダーmetadataから参照する月別世代のhashを確認する。カレンダーイベント本文の意味的再パースや外部同期はしない。
|
||||
- symlink、絶対path、`..`、重複path、未知の保全root、manifestにないpayloadを拒否する。
|
||||
- 転送はSSH等の認証された経路で行う。検証に渡す**期待manifest SHA-256を同じ未認証転送から自己申告させない**。現在のmanifestは署名付きではなく、期待hashの真正性は運用者が保証する。
|
||||
- バックアップは暗号化済み保管先、暗号化transport、復旧担当者だけのアクセス権で扱う。CLI自身の暗号化・KMS連携は未実装。ファイル0600、ディレクトリ0700で生成する。
|
||||
- 復元は新規ディレクトリへコピーし、コピー後もhash検証する。稼働中のデータへoverlayしない。失敗世代は公開せず、旧世代を勝手に削除しない。
|
||||
- 世代更新は新規復元→standby停止→mount切替→再起動。初版の復元では物理node UUIDが毎回変わるため、その都度配置台帳を更新する。
|
||||
|
||||
世代保持の初期案は「直近3世代+日次7世代+週次4世代」。容量・法的保持・鍵ローテーションの要件を確認して決定する。自動削除はまだ実装しない。破損・誤削除が複製されても戻せるよう、同期先とは独立した世代バックアップを最低1系統持つ。
|
||||
|
||||
## 5. CLIの運用例
|
||||
|
||||
以下はLinux上のバイナリ例。実環境の絶対pathへ置換する。全コマンドは対象ディレクトリを明示し、保全先はデータディレクトリ外にする。コンテナでは一時CLI用コンテナへ同じdataとbackup保存先をmountし、entrypointに `/pageswiki` を指定する(image内の実際の配置を確認する)。
|
||||
|
||||
```sh
|
||||
# 先にprimaryのサーバ・全writerを停止する。
|
||||
pageswiki dr init --data-dir /srv/pageswiki/data
|
||||
pageswiki dr status --data-dir /srv/pageswiki/data
|
||||
pageswiki dr snapshot --data-dir /srv/pageswiki/data \
|
||||
--output /srv/backup/pageswiki/generation-001 --writers-stopped
|
||||
|
||||
# 出力された manifest_sha256 を保管し、snapshotとともにDR側へ安全に転送する。
|
||||
# この時点でprimaryは再開できる。
|
||||
|
||||
# DR側。期待hashは安全に受け取った値。<EXPECTED_SHA256> は置換する。
|
||||
pageswiki dr verify --snapshot /srv/backup/pageswiki/generation-001 \
|
||||
--manifest-sha256 '<EXPECTED_SHA256>'
|
||||
pageswiki dr restore --snapshot /srv/backup/pageswiki/generation-001 \
|
||||
--manifest-sha256 '<EXPECTED_SHA256>' --target /srv/pageswiki/standby-001
|
||||
pageswiki dr status --data-dir /srv/pageswiki/standby-001
|
||||
# standby-001を /data:ro として起動。元の論理FQDN/Hostと環境secretを維持する。
|
||||
# PAGESWIKI_DR_EXPECT_ROLE=standby も起動環境に設定する。
|
||||
```
|
||||
|
||||
昇格例:
|
||||
|
||||
```sh
|
||||
# 旧primaryを停止・隔離し、再起動しても復帰しない外部fenceを確認する。
|
||||
# standbyも停止し、失われる範囲(captured_at以降)を確認する。
|
||||
pageswiki dr promote --data-dir /srv/pageswiki/standby-001 \
|
||||
--fenced-node '<FORMER_PRIMARY_NODE_UUID>' \
|
||||
--fence-reference 'incident-123: power fencing independently verified' \
|
||||
--accept-data-loss
|
||||
|
||||
# 隔離環境でrw mount、PAGESWIKI_DR_EXPECT_ROLE=primaryへ切替。
|
||||
# 権限失効を再適用し、起動・読み書き確認後に経路切替。
|
||||
# ジョブはまだ停止。内容を確認・調整し、再びプロセスを停止してから実行する。
|
||||
pageswiki dr resume-workers --data-dir /srv/pageswiki/standby-001 \
|
||||
--reviewed-restored-jobs
|
||||
# 再起動でスケジューラ/GC/Campus reconcilerが再開する。
|
||||
```
|
||||
|
||||
旧primaryはそのまま再参加させない。旧データは隔離して差分調査・必要な手動救出用に保全し、新primaryの最新スナップショットから新しいstandbyを作る。古いDBで新primaryを上書きする「切り戻し」は禁止。自動の双方向マージは提供しない。
|
||||
|
||||
## 6. Campusコントローラに固有の注意
|
||||
|
||||
Campus manifestの署名、発行sequence、管理ノードの受理sequenceと参加tokenを一体で保全する。記事バックアップとmanifest配信は同義ではない。
|
||||
|
||||
初版では既存Campus FQDNをDR側へ向け直す方式を採り、管理ノードへ勝手に別Campusを登録しない。ホスト名・証明書・reverse proxyの扱いは復旧手順に含める。`PAGESWIKI_INSTANCE_FQDN` も復旧する論理サービスに合わせる。
|
||||
|
||||
**重大な未解決事項:** 保全後にprimaryが新しいmanifestを発行し、管理ノードが既に受理していた場合、復元したcontrollerのsequenceが後退して再送を拒否され得る。DRのローカル `epoch` を増やすだけでは既存署名プロトコルのsequence後退を解消しない。reconcilerを既定停止する理由の一つである。強引なDB sequence書換えで回避せず、次段階で「外部fenceで承認されたcontroller epoch+epoch内sequence」のプロトコルと管理側の受理規則を実装する。それまではcontroller配信の完全自動復旧を保証しない。
|
||||
|
||||
## 7. 次段階:オンライン同期と自動昇格の詳細設計
|
||||
|
||||
以下は初版時点の構想。詳細化後の実施順は [DR01〜DR13](dr-delivery-plan.md) を正とし、
|
||||
probe/再参加gateと役割・writer境界の分離を先行する。実装済み項目ではない。
|
||||
|
||||
1. **オンライン整合checkpoint**:全正本writer(Web、CLI、calendar metadata、GC)で共有する短時間barrierを設ける。DB backup cutoffとcalendar metadata世代一覧を固定し、その世代が参照するCAS/monthly blobのGC pinを持つ。大きいblob転送はbarrier解除後に低優先度で行う。SQLite単独online backupをこの代替としない。
|
||||
2. **転送と受理**:instance-boundの別用途資格情報、mTLSまたは短命署名、cluster/node/epoch/sequence固定。Campus参加tokenを丸用しない。CAS差分転送→hash確認→DBとmetadata世代の受理→active pointer切替の順。途中世代はservableにしない。retryは同じsnapshot IDで冪等、帯域・IO・CPU上限、foreground優先、同時転送数を設定可能にする。
|
||||
3. **監視とUI**:設定画面の「運用 / DR」にノード、role、最終検証世代、保全時刻、受信時刻、遅延、容量、最終訓練結果を表示。Campus画面から復旧単位への関連リンクを出す。緑は「HTTP疎通」ではなく「検証済み世代・鮮度・役割整合」、黄は遅延、赤は破損/期限切れ。Domain設定へDRのhostnameを重複入力させない。
|
||||
4. **operator権限分離**:インスタンス運用者がreplica/転送鍵/役割を管理し、campus_adminは所属Campusの復旧状態を参照する。共有DBを跨ぐ昇格・secret操作はcampus_adminだけでは許可しない。初版のCLIに後からAPIを接続する際も同じ境界とする。
|
||||
5. **キュー・認証の復旧**:session/policy revocation watermarkを同期し、古いACLからのreadをfail closedにする。jobにepoch leaseとidempotency keyを導入し、外部副作用は送信先も含む重複制御または確認フローを設ける。lease期限だけで旧executorを安全とはみなさない。
|
||||
6. **controller epoch**:署名対象にleader identityとepochを含め、管理インスタンスは承認された単調増加epochとsequenceを永続化する。epoch移行はout-of-bandで信頼したfencing承認だけが行えるようにする。古い鍵/epochの再送と復元後のrollbackを試験する。
|
||||
7. **自動昇格**:第三のwitnessまたはconsensus storeと外部fencing backendを選択。lease失効時は旧primaryがcommitを拒否し、すべてのDB/ファイルwriterとジョブがepochを照合する。fence失敗・quorumなしでは書き込み停止を選び、二重writerを選ばない。これができるまで自動昇格ボタンや「疎通断だけでwrite ok」は実装しない。
|
||||
8. **LB参照構成**:write readiness、read freshness、drain、長時間upload、WebSocket、Host検証、接続中断時の冪等再試行を統合する。read/write振り分けはHTTPメソッドだけで決めない。RO nodeをwrite routeへ入れない。
|
||||
|
||||
API案は `/_/api/v1/instance/dr/...` を予約候補とするが現時点で未登録。転送はユーザーのPath URIと分離し、`POST snapshots`、snapshot ID配下のmanifest/payload、`POST acknowledge` をinstance-to-instance限定で設ける。公開 `/_/api/v1/federation/enroll` にbackupの読み出し能力を追加しない。
|
||||
|
||||
## 8. RPO / RTOと受入基準
|
||||
|
||||
初版のRPOは「障害発生時刻 − 最後に**DR側で検証完了した**snapshotのcaptured_at」。保全予定間隔や転送開始時刻ではない。RTOには障害判断、外部fence、復元/検証、権限失効の再適用、サービス検査、経路切替を含む。目標値は実データ量と許容停止時間から別途決定する。RPO=0・無停止とは表明しない。
|
||||
|
||||
自動試験は合成データを使い、次を確認する。
|
||||
|
||||
- 未checkpointのコミット済みWALを取り込み、rowidを維持する。
|
||||
- DB参照先の欠落・payload改変・manifest改変・path traversal・symlinkを拒否する。
|
||||
- 同じsnapshotを繰り返しverifyしても書き換えない。復元先既存ディレクトリを上書きしない。
|
||||
- サーバ/CLIの共有ロック中は保全・昇格を拒否する。
|
||||
- 復元後はノードUUIDが別になり、role=standby、worker停止となる。
|
||||
- standbyの起動とWiki読取でDBを変更せず、書込API/Store、外部起動、期限切れ閲覧を拒否する。認可をバイパスしない。
|
||||
- 旧primary identity・隔離の証跡・データ損失受容のいずれかがない昇格を拒否する。
|
||||
- 昇格後もjobを勝手に再送せず、明示的再開が必要。
|
||||
|
||||
実機の電源断、ネットワーク分断、鍵失効、容量不足、転送中断、DNS切替、controller sequence後退、復旧元と受信先のバージョン差異は別の復旧訓練が必要。訓練未完了を成功と扱わない。
|
||||
|
||||
## 9. 根拠資料と関連設計
|
||||
|
||||
- [SQLite Online Backup API](https://www.sqlite.org/backup.html):DB単位の整合したコピー。
|
||||
- [SQLite WAL](https://www.sqlite.org/wal.html):WALとDBファイルの扱い、共有filesystemの制約。
|
||||
- [SQLite VACUUM](https://www.sqlite.org/lang_vacuum.html):rowidが変わり得るため初版のコピー方式には採用しない。
|
||||
- [Campus / Domain](../campus-domain-model.md)、[署名manifest](../federation-manifest-integrity.md)、[運用と保全](operations.md)、[Phase 8](../implementation-roadmap.md#phase-8--controller-disaster-recovery-and-high-availability)。
|
||||
@@ -0,0 +1,285 @@
|
||||
# DR詳細設計:管理主系・データ主系・再参加
|
||||
|
||||
設計版:DR-D1、2026-09-27。**設計のみ。記載したAPI・状態機械・設定は未実装。**
|
||||
今回の作業は文書のみを変更し、DB、schema、migration、実行コード、配置設定、本番データを変更しない。
|
||||
既存の停止snapshot/手動昇格は [初版の実装・運用記録](disaster-recovery.md) に残す。
|
||||
|
||||
## 1. 文書体系・決定の適用範囲
|
||||
|
||||
- 本書:責務、identity、再参加状態、書き込み条件、障害時判断、設定・UI。
|
||||
- [通信・同期・主導権移譲契約](dr-protocol-and-sync.md):メッセージ、URI、検証、切替と保全。
|
||||
- [実施計画・受入試験](dr-delivery-plan.md):作業単位、変更予定箇所、依存、導入・撤退手順。
|
||||
|
||||
DR-D1は初版文書の「次段階」の設計を具体化・更新する。初版の `role` や `epoch` の意味を
|
||||
黙って変更せず、旧形式の移行は別の明示的操作とする。以下のMUST相当の条件は、
|
||||
「できれば実装する」事項でなく、機能有効化の前提とする。
|
||||
|
||||
DB別件の完了を待たず、wire型・純粋な状態機械・認証probe・表示の実装準備はできる。
|
||||
一方、writerを開く接続、online snapshot、manifest受理checkpointの永続化、
|
||||
独立した主系切替は、保存層の契約確認と別途の実装承認まで無効とする。
|
||||
|
||||
## 2. 決定一覧
|
||||
|
||||
| ID | 決定 |
|
||||
| --- | --- |
|
||||
| D01 | Campusの管理primaryとData replica groupの書き込みprimaryを分離する |
|
||||
| D02 | Instanceに全体共通のprimaryフラグを持たせず、役割はgroupごとに表現する |
|
||||
| D03 | 同じ物理writer境界を共有する役割は連動切替する。論理分離だけで独立writerにしない |
|
||||
| D04 | DR対象プロセスは再起動時に必ずrecoveringから入る。保存済みroleではwriterを開かない |
|
||||
| D05 | discovery/probeは情報収集。参加許可、昇格承認、正本の決定とは別 |
|
||||
| D06 | 発見したpeerの数や、最大の自己申告epochだけでは主系を選ばない |
|
||||
| D07 | 主系選定の既定はmanual、preempt既定はoff。自動モードは別の能力認定が必要 |
|
||||
| D08 | 自動裁定の最初の実装先は外部etcd v3 APIとする。PagesWiki独自Raftは作らない |
|
||||
| D09 | lease切れ・HTTP不通だけでは旧writer停止の証拠にならない。新grant前にfencingを要する |
|
||||
| D10 | 元primaryの未同期更新は隔離保存し、現primaryへ自動マージしない |
|
||||
| D11 | 共有DB環境での最初の同期単位はデータディレクトリ全体。Domain単位のSQL差分複製はしない |
|
||||
| D12 | バックアップ世代、データ書込世代、管理manifest世代を混同しない |
|
||||
| D13 | 状態収集/authority監視は通常のイベントキューに依存させない。大容量転送は低優先度 |
|
||||
| D14 | 主系復帰は同期→drain→最終checkpoint→権限移譲の協調的切替とする |
|
||||
|
||||
etcd採用は自動モードの設計上のprovider選択であり、この変更でサービスを導入しない。
|
||||
運用でetcdを用意しない場合もmanualの保全・復元を使える。実際のprovider配置、電源/保存先の
|
||||
fence手段、容量と目標RPO/RTOは導入時の入力であり、推測して本番設定に書かない。
|
||||
|
||||
## 3. 三つの境界
|
||||
|
||||
### 3.1 論理サービス
|
||||
|
||||
| 対象 | 不変のidentity | 主系の責務 | 待機系に複製するもの |
|
||||
| --- | --- | --- | --- |
|
||||
| Controller group(CG) | group UUID、Campus UUID | Campus設定、Domain配置、管理側継承情報、設定manifest発行 | 管理正本、発行履歴、承認済み構成、復旧用鍵参照 |
|
||||
| Data replica group(DG) | group UUID、dataset UUID | Domainのページ/asset/カレンダー/タスク/ローカル権限等の更新 | metadata、CAS、可変正本、失効情報、outbox/checkpoint |
|
||||
| Instance | node UUID、ノード固有鍵 | 上記役割を実行する場所 | Instance自体を業務正本のownerとしない |
|
||||
|
||||
1 Campusにつき管理authorityは1 CG。1 DGは複数Domainを持てる。1 Domainは同一時点では
|
||||
1 DGへ配置する。複数Campusのデータが1 DGに共存することも、既存DB構成の間は許容する。
|
||||
CGのprimaryはDGのprimaryである必要はない。ただし次節の物理境界制約に従う。
|
||||
|
||||
Campus/DomainのUUID、FQDN、Path、ユーザー領域のURIは維持する。
|
||||
Domain配置の将来形式は `replica_group_id` を正本にし、現在primaryのFQDNは解決結果とする。
|
||||
物理ノード移動をDomainの改名として記録しない。旧 `placement_instance_fqdn` は移行中の
|
||||
互換表示に限り、二つの値を別々のauthorityが更新する方式は採らない。
|
||||
|
||||
### 3.2 保存領域のwriter境界
|
||||
|
||||
`WriterResource` はDB、可変正本ストア等の実際の排他単位を表す。ローカルpath文字列だけで
|
||||
なく保存層が提供する安定したresource identityで識別する。複製コピー同士も同じ論理正本の
|
||||
writer resourceに属する。NFS上のSQLiteを別resourceと見せるような登録を拒否する。
|
||||
|
||||
各役割は更新するresourceの集合を宣言し、共有resourceを持つ役割の推移的なまとまりを
|
||||
`coupling_bundle` とする。同じbundleのwriter許可は一括で一つのnodeにだけ与える。
|
||||
例:CG1とDG1がpages.dbを共有、CG2も同じDBを更新するなら三役割すべてを連動させる。
|
||||
テーブル名が異なっていても、DB全体を物理snapshotで複製する間は分離しない。
|
||||
|
||||
独立切替を許可する条件は、保存担当が次の能力を明示すること。
|
||||
|
||||
- 対象の正本、派生projection、署名発行状態に独立した所有者とwriter境界がある。
|
||||
- 役割間の更新はversion付きのprotocolとして受理でき、別役割のDBへ直接書かない。
|
||||
- 対象resourceへの旧writerのアクセスを実際に停止できる。
|
||||
- role/resource対応の構成世代が全参加者で一致する。
|
||||
|
||||
能力が未申告なら `shared-instance` とし、独立切替要求は `WRITER_BOUNDARY_COUPLED` で拒否する。
|
||||
不足能力を理由にDB分割・DDLを自動実行しない。
|
||||
|
||||
### 3.3 障害・隔離の影響範囲
|
||||
|
||||
role単位で保存領域が分かれても、fenceがホスト電源断なら同居する全groupへ影響する。
|
||||
切替planは「writer連動範囲」と「fenceの影響範囲」を別々に計算する。
|
||||
他groupのprimaryまで停止するplanは、自動preemptしない。運用者の明示承認と、影響groupの
|
||||
サービス継続計画を必要とする。group単位のfence能力があると偽装して回避しない。
|
||||
|
||||
## 4. identity、保存位置、世代
|
||||
|
||||
以下は論理レコードの契約であり、RDBのテーブル定義ではない。
|
||||
|
||||
| レコード/値 | 保存主体 | 更新ルール |
|
||||
| --- | --- | --- |
|
||||
| Membership | AuthorityStore | group種別、member/learner、鍵、resource対応。expected revisionでCAS |
|
||||
| NodeIdentity | ノードローカル保護領域 | node UUIDと専用鍵。業務snapshotから他ノードへ複製しない |
|
||||
| `boot_id` | 各プロセス | 起動ごとに乱数UUID。過去のgrant/probe応答を再利用しない |
|
||||
| `trust_generation` | AuthorityStore+運用保全 | authority自身の災害復旧時に明示更新するtrust世代 |
|
||||
| `control_epoch` | CG authority | CGの主導権交代ごとに単調増加 |
|
||||
| `data_epoch` | DG authority | DGの書込権交代ごとに単調増加 |
|
||||
| `resource_epoch` | writer resource authority | 共有保存境界の許可更新。bundle全体で矛盾なく確定 |
|
||||
| `manifest_sequence` | CGの管理正本 | control_epoch内の管理配信順序。data_epochとは比較しない |
|
||||
| Checkpoint | 保存層+受信側 | dataset、epoch、cut ID、親checkpoint、内容hash、検証ACK |
|
||||
| Operation | AuthorityStore | 永続したintent、phase、expected世代、証跡、結果。timeoutで削除しない |
|
||||
| Node runtime state | メモリ+ノードローカル記録 | 観測状態。書込権の正本にはしない |
|
||||
|
||||
初版 `dr-node.json` の `epoch` は監査値なので、control/data epochへコピーしてauthorityと
|
||||
みなさない。旧 `cluster_id` は移行mapで既存の復旧単位へ対応させる。
|
||||
DR-D1では物理ノードを維持した世代更新でnode UUIDを変えず、`dataset_generation`を更新する。
|
||||
新しい物理ノードは新規identityを登録する。初版のrestoreによる採番との差は移行計画に明記する。
|
||||
|
||||
単に最大のepochを採用しない。有効なのは、信頼済みauthorityが登録したtrust世代・group・
|
||||
membershipに結び付いた証明だけ。timestampは監視用で、履歴の新旧や正本選定に使わない。
|
||||
|
||||
## 5. 設定契約
|
||||
|
||||
設定案の中心は次のGroupPolicy。ノード一覧に秘密値を埋め込まず `secret_ref` を用いる。
|
||||
|
||||
| 設定 | 既定/検証 | 意味 |
|
||||
| --- | --- | --- |
|
||||
| `kind` | 必須:control/data | 二つの役割を混同しない |
|
||||
| `coordination_mode` | manual | manual / coordinated。Campusの既存authority_modeとは別項目。自動モードは必要能力の全検査を要求 |
|
||||
| `members` / `learners` | 明示登録、重複不可 | 発見しただけのpeerをmemberへ追加しない |
|
||||
| `preferred_node_id` | 未指定 | 期待する主系。実際のprimaryを上書きする値ではない |
|
||||
| `preempt` | off | off / manual / automatic。controlとdataで別設定 |
|
||||
| `stable_for_seconds` | 300、範囲60〜86400 | preferred nodeが継続して正常・同期済みである必要時間 |
|
||||
| `switch_cooldown_seconds` | 1800、stable以上 | 交代直後の再切替を抑制。障害対応は別の明示操作 |
|
||||
| `preempt_window` | 空=時間制限なし | 任意の許可時間帯。タイムゾーン必須、DSTは計画時にUTCへ解決 |
|
||||
| `probe_interval_seconds` | 5、範囲2〜60 | ±20% jitter。leaseの更新周期とは別 |
|
||||
| `probe_timeout_seconds` | 2、範囲1〜10 | 接続・応答の合計deadline |
|
||||
| `suspect_after_failures` | 3、範囲2〜10 | 表示をsuspectにするだけ。これで昇格しない |
|
||||
| `read_policy` | disabled | disabled / fresh-authorized。失効watermark未対応なら後者は選べない |
|
||||
| `max_read_staleness_seconds` | 300、範囲1〜3600 | read replica能力実装後に適用。初版3600秒設定とは別version |
|
||||
| `rpo_target_seconds` | 必須・導入時入力 | 目標。同期の成功や無損失を保証するフラグではない |
|
||||
| `rto_target_seconds` | 必須・導入時入力 | fence・起動・routingを含む実測比較の目標 |
|
||||
| `data_loss_policy` | require-approval | 自動failoverで不明/未複製の損失を黙認しない |
|
||||
| `fence_provider_ref` | coordinatedでは必須 | 対象identity・resource・影響範囲を検証できるprovider |
|
||||
|
||||
上記は試験開始用の既定値。実環境のRTTやI/Oに応じて変更できるが、同期完了、現主系の隔離、
|
||||
相互排他、未知世代拒否といった安全条件は設定で無効化できない。
|
||||
preempt=automaticはcoordinated、全target能力、writer境界、適合fence、失効同期を必須とする。
|
||||
manualでは自動選挙も自動preemptも行わず、復帰しただけではwriterを再開しない。
|
||||
|
||||
## 6. 再参加の状態機械
|
||||
|
||||
設定上の優先順位、現在の役割、実行状態を別フィールドにする。
|
||||
状態遷移の入力は検証済みイベントのみ。単なるHTTP 200やpeerの文字列申告では遷移しない。
|
||||
|
||||
| 状態 | 入る条件 | 許可するもの | 次状態の条件 |
|
||||
| --- | --- | --- | --- |
|
||||
| `recovering` | 全DR対象プロセスの起動、許可失効、重大な構成変更 | ローカル検証、認証済みprobe | identity/構成が有効ならlearning |
|
||||
| `learning` | 書込gateを閉じてauthority/peerを照合中 | probe、checkpoint一覧、同期plan | authoritative state一致→syncing。矛盾→conflict |
|
||||
| `syncing` | 正しいsourceとbase世代が確定 | 不変世代の受信・検証 | 内容・schema・ACL等が一致→standby |
|
||||
| `standby` | 検証済み世代、最新membership | 同期追従、能力認定済みreadのみ | 書込grant取得→activating |
|
||||
| `activating` | 新grantとfence証跡が確定 | root切替、互換性検証、gate接続 | 二重確認+readiness成立→primary |
|
||||
| `primary` | group/resource/bootすべて一致した有効grant | 許可範囲のread/write | 計画移譲→draining。許可失効→recovering |
|
||||
| `draining` | operationが停止cutを要求 | 既存処理の完了待ち、checkpoint | writer停止証明後standby/停止。失敗ならoperation停止 |
|
||||
| `conflict` | 履歴分岐、同一世代で異hash、trust不一致 | 証拠保全、管理状態参照 | 運用者のreseed/解決planのみ |
|
||||
| `blocked` | 同期先不在、容量不足、fence不明、互換性不足 | 状態・監視 | 原因解消後、learningから再検査 |
|
||||
|
||||
learning/syncing中は一般のreadも公開しない。復元されたprivate文書と古いACLをうっかり公開しない。
|
||||
standbyでreadを許す場合も、内容の鮮度とは別に必要な失効watermarkを確認する。
|
||||
複数groupを持つInstanceは各groupの状態を表示する。単一の緑ランプで全役割をprimaryと見せない。
|
||||
|
||||
### 起動順序
|
||||
|
||||
1. ノードの専用identity、deployment期待値、承認済みmembershipを読む。
|
||||
2. 通常HTTP handler、migrations、worker、CLI接続より先にすべてのwriter gateを閉じる。
|
||||
3. read-only互換性検査と管理用control listenerだけを起動する。
|
||||
4. 新boot_idで認証probeし、authorityの現在値と照合する。誰にも到達できなければblocked。
|
||||
5. 必要なら旧ローカルデータを隔離保全し、正しいsourceから新generationへ同期する。
|
||||
6. 同期済みでもまずstandby。新bootに対するgrant取得を別処理で行う。
|
||||
|
||||
正常終了時にprimaryだった場合もこの順序を省略しない。単一ノードの非DR運用は従来起動を
|
||||
維持するが、DR設定の欠落を非DRへ自動フォールバックする経路はdeployment guardで拒否する。
|
||||
|
||||
## 7. 書き込み許可の条件
|
||||
|
||||
次の論理式をすべて満たす場合だけwriterを開く。
|
||||
|
||||
```text
|
||||
CanWrite(role, resource, boot) =
|
||||
approved_membership AND validated_trust_generation
|
||||
AND active_group_grant(holder=node, boot=boot, epoch=current)
|
||||
AND active_resource_grant(holder=node, bundle=current)
|
||||
AND verified_dataset AND schema_compatible AND revocations_applied
|
||||
AND local_gate_open AND NOT draining AND NOT expired
|
||||
```
|
||||
|
||||
Web/APIだけでなくCalDAV、CLI、managed設定受理、migrations、GC、asset処理、calendar保存、
|
||||
外部同期、outbox配信もwriter一覧に含める。HTTP GETでも修復/発行をする経路はwriteである。
|
||||
RO standbyへのmanifest適用は、そのreplicaのauthoritative DBへ直接行わず、現DG primaryへ
|
||||
適用するか同期対象のprojectionとして受け取る。ローカル状態報告の保存先と業務正本を混ぜない。
|
||||
|
||||
許可喪失時は新規処理を拒否し、実行中処理をキャンセル・停止する。しかしプロセス停止や
|
||||
ネットワーク遅延によりキャンセルが間に合わない可能性があるため、新primaryのgrant発行は
|
||||
外部fence確認または認定済み保存側fencingの完了まで待つ。local mutex/lease確認だけでは代替不可。
|
||||
|
||||
## 8. 裁定・信頼モデル
|
||||
|
||||
発見peer、複製peer、authority参加者は別。既存Campus参加トークンにbackup読出しや昇格権を
|
||||
追加しない。ノード間通信は専用identityとgroup限定の許可を使う。
|
||||
|
||||
coordinatedの初段providerは外部etcdの通常整合性readと比較更新transactionを使う。
|
||||
watchは再確認のきっかけで、watch結果だけから新grantを発行しない。epoch、membership、
|
||||
operation intentは期限切れで消さず、leaseは生存・短期許可にのみ用いる。
|
||||
etcdのKV transactionとwatchの保証は異なるためである。[etcd API guarantees](https://etcd.io/docs/v3.5/learning/api_guarantees/)
|
||||
|
||||
authorityは業務snapshotと別の保全・失効境界に置く。旧authority backupを戻してepochを
|
||||
巻き戻すことは禁止。authority全損時は全writerをfenceし、新trust_generationを
|
||||
out-of-bandで承認・再配布するbreak-glass手順を要求する。単にepochを大きくする操作ではない。
|
||||
authority quorumが失われた場合は新grantを発行しない。既存writerも許可更新不能なら閉じる。
|
||||
|
||||
2台のPagesWikiを相互監視するだけではcoordinated modeを認定しない。
|
||||
etcdは別途適切な障害領域に配置する。配置数やfence backendの接続情報は導入計画で確定する。
|
||||
manual modeの運用者証跡は自動検証済みfenceと区別し、UIと監査に表示する。
|
||||
|
||||
## 9. コントローラとデータ側の障害マトリクス
|
||||
|
||||
| 事象 | 管理側 | データ側 | 判定 |
|
||||
| --- | --- | --- | --- |
|
||||
| CG停止、DG正常 | 配置変更・新manifestを停止 | 有効なdata grantと許可済み設定で継続 | CGへの疎通だけをDGの書込条件にしない |
|
||||
| DG停止、CG正常 | 管理操作は継続可 | 対象DGのfailover判定 | CGが配置文字列を書き換えるだけでは昇格不可 |
|
||||
| 旧CG復帰 | learning→管理checkpoint同期 | DGの切替は不要 | CG preempt設定のみ評価 |
|
||||
| 旧DG復帰 | 配置group identityを維持 | learning→現DG primaryから同期 | 古いデータを優先しない |
|
||||
| 同じDBでCG/DGが別nodeを要求 | 連動planが必要 | 連動planが必要 | 独立要求を拒否 |
|
||||
| primaryとreplicaが分断 | authoritative grantとfenceを照合 | 同左 | 応答者だけの多数決はしない |
|
||||
| authorityのみ停止 | 更新許可の有効期間内だけ処理 | 同左 | 新grantなし、期限到達でwriter停止 |
|
||||
| 最新受理manifestより復元内容が古い | 自動配信しない | 古い権限を再適用しない | 管理復旧の明示承認が必要 |
|
||||
| role fenceが同居別groupも停止する | impact planを提示 | 対象groupも判定 | 自動preemptを拒否 |
|
||||
|
||||
## 10. UI・権限・監視
|
||||
|
||||
設定の「運用 / DR」を親にし、「概要」「グループ」「同期・保全」「切替履歴」を子パネルにする。
|
||||
概要は1group 1行、kind / Campus・Domain範囲 / 実primary / preferred / state / 同期点 /
|
||||
遅延 / 書込許可 / 原因を表示。ノード追加・ポリシー編集はアイコンからダイアログに収める。
|
||||
フォルダ名やpathではなくnode・groupを選択させ、秘密は参照名だけ表示する。
|
||||
|
||||
キャンパス設定にはCGの役割・状態とDR画面へのリンクを追加する。Domain設定では配置先を
|
||||
DG単位で選び、現在のnodeを補助表示する。旧配置方式は移行前であることを示す。
|
||||
|
||||
| 権限 | 許可 |
|
||||
| --- | --- |
|
||||
| instance operator(新しいホスト運用者権限) | node登録、trust/fence、backup秘密、bundle全体の切替・復元 |
|
||||
| campus_admin | 自Campusの管理状態参照、ポリシー変更/切替の申請 |
|
||||
| domain_admin | 自Domainの配置・同期状態参照。ホスト/鍵/他Domain情報は非表示 |
|
||||
| replica service identity | 明示groupのprobe、許可された世代の同期。operator API不可 |
|
||||
|
||||
instance operatorはcampus_adminへの暗黙追加ではない。初段はホストCLIだけでこの権限を
|
||||
実現し、既存認証DBに新roleを勝手に加えない。Webでのapplyは認可契約が完成するまで非表示。
|
||||
切替UIはplan→影響範囲・損失・fence表示→承認→進行状態。操作中も平常画面をoverlayしない。
|
||||
通知Inboxへ失敗/blocked/完了を集約し、probe失敗を毎回broadcastしない。
|
||||
|
||||
メトリクス:role state、grant残時間、最後のprobe成功、同期cut時刻、検証ACK時刻、
|
||||
pending bytes、転送速度/制限、hash失敗数、fence結果、operation phase、未複製の更新有無。
|
||||
UUID別の無制限時系列は避け、ノード/group別集計と履歴画面を分ける。秘密・文書本文をログに出さない。
|
||||
緑=primary許可あり/検証済みstandby、黄=learning/syncing/suspect、赤=conflict/blocked。
|
||||
色だけで判断させずラベルと原因コードを併記し、日本語・英語キーを用意する。
|
||||
|
||||
## 11. 保存担当との接続条件
|
||||
|
||||
DB変更の担当へ渡す成果物は、テーブル要求ではなく以下の能力・整合性契約。
|
||||
|
||||
- `DescribeResources`:各正本とwriter排他境界、共有するrole、schema対応範囲。
|
||||
- `InspectCheckpoint`:正本を変更せず、適用世代・内容digest・schema fingerprintを取得。
|
||||
- `FreezeWriters/ReleaseBarrier`:全writerの停止、未完了処理、最終cutの確定。
|
||||
- `CaptureCheckpoint/Pin/Unpin`:DBと可変正本を同じcutへ固定し、必要blobをGCから保護。
|
||||
- `StageGeneration/Verify/ActivateGeneration`:非稼働rootへ復元し、検証後に切替。
|
||||
- `ApplyControlManifest`:管理内容と受理checkpointを同じ永続化境界で確定。
|
||||
- `CheckWritePermit`:対応できる場合のみ保存側fencingとして能力宣言。
|
||||
|
||||
詳細な入出力と失敗時条件は [protocol](dr-protocol-and-sync.md) に定義する。
|
||||
契約を満たす実装がなければoffline capture/shared-instance/manualのままとし、DB別件を
|
||||
妨げるDDL、直接SQL、独自の並行正本ファイルを追加しない。
|
||||
|
||||
## 12. 参考と非目標
|
||||
|
||||
Learnerという考え方は、同期前のノードを選挙・サービス提供から外すための参考である。
|
||||
PagesWikiの状態名をetcdの状態と同一視しない。[etcd learner design](https://etcd.io/docs/v3.5/learning/design-learner/)
|
||||
|
||||
非目標:active-active更新、複製DBのSQL行単位マージ、任意LAN参加、gossipによる独自投票、
|
||||
DNSだけによるfencing、DB製品選択の変更、既存Campus/FQDNの改名、未同期更新の黙った破棄。
|
||||
同期とバックアップは別であり、replicaの存在を履歴世代の保全の代替としない。
|
||||
@@ -0,0 +1,231 @@
|
||||
# DR詳細設計:実施計画・受入試験・導入判定
|
||||
|
||||
設計版:DR-D1、2026-09-27。**詳細設計完了、実装作業は未着手。**
|
||||
ここでいう実装作業はDR-D1の再参加・役割分離protocol。既存のoffline DR CLIは別の初版。
|
||||
今回の成果物は文書のみであり、DB・migration・本番配置を変更する作業指示ではない。
|
||||
|
||||
## 1. 設計成果物と完了条件
|
||||
|
||||
| 成果物 | 本版で定義した範囲 |
|
||||
| --- | --- |
|
||||
| [役割・再参加](dr-authority-and-rejoin.md) | CG/DG/Instance、writer連動境界、identity、状態機械、設定・UI・権限 |
|
||||
| [protocol・同期](dr-protocol-and-sync.md) | 認証probe、API、authority契約、checkpoint、manifest v3案、切替・失敗時動作 |
|
||||
| 本書 | 実施順、予定変更箇所、DB別件への接続条件、試験、導入/撤退手順 |
|
||||
| [初版記録](disaster-recovery.md) | 既存機能と制約を保持し、DR-D1と区別 |
|
||||
|
||||
- [x] primaryを管理/データに分け、物理保存境界による連動条件を記述。
|
||||
- [x] 起動・probe・Learning・同期・昇格・preempt・失敗からの再参加を定義。
|
||||
- [x] 身元、世代、許可、同期内容、承認、未知損失の扱いを定義。
|
||||
- [x] API入出力、サイズ上限、再試行、冪等性、切替phase、認可主体を定義。
|
||||
- [x] DBを変更せずに準備できる範囲と、保存担当との合意待ち範囲を分離。
|
||||
- [x] 実装タスク、依存、合格条件、障害注入試験、導入/撤退条件を定義。
|
||||
- [ ] 実装・実機でのfencing認定・復旧訓練・本番反映。
|
||||
|
||||
「詳細設計完了」は実装方針と判断規則を定義した状態であり、未知の本番設備の能力を保証した
|
||||
意味ではない。RPO/RTO値、ノード数/FQDN、fence機器、容量、鍵保管先は導入時の必須入力として残す。
|
||||
これらを未設定のまま自動運転へ移行することはできない。
|
||||
|
||||
## 2. DB別件との作業境界
|
||||
|
||||
本タスクでは以下を行わない。
|
||||
|
||||
- アプリDBへのSELECTを含むアクセス、DBのコピー・バックアップ・復元、schema inspectの実行。
|
||||
- SQL/DDL/migration/repositoryの編集、コード生成、サーバ起動、CLIによるデータ操作。
|
||||
- compose、認証鍵、federation token、node設定、稼働コンテナ、外部カレンダーへのアクセス。
|
||||
- 文書を本番Wikiへアップロードする操作(アップロードもDBへの書き込みになるため)。
|
||||
|
||||
読み取る対象は設計書と必要最小限のソースコードだけ。ドキュメントの静的整合性確認を実施する。
|
||||
別件の変更を前提にDBの物理分割方法やテーブル名を確定させない。
|
||||
|
||||
保存担当へ渡すinterface要求は次の通り。応答はSQLの実装ではなく、能力の宣言とテスト結果で受け取る。
|
||||
|
||||
| 契約 | 保存担当に確認する事項 | 未提供時の挙動 |
|
||||
| --- | --- | --- |
|
||||
| Resource map | metadata/可変正本/署名発行状態が共有するwriter境界 | shared-instance連動のみ |
|
||||
| Schema inspection | 非破壊・read-onlyでの互換性/世代取得 | 復旧世代をservableにしない |
|
||||
| Consistent cut | DBとcalendar等を同じ論理時点で固定できる範囲 | 全writer停止snapshotのみ |
|
||||
| Durable pin | snapshot/GC/転送/再起動を跨ぐ参照保持 | online同期不可 |
|
||||
| Restore activation | 新generationの検証、root切替、途中停止からの復旧 | 自動復元不可、既存手動手順のみ |
|
||||
| Manifest apply | 管理内容と受理位置のatomic commit | manifest v3配信不可 |
|
||||
| Write fencing | 旧許可を実際の書込み先で拒否できるか | 外部fence必須 |
|
||||
| Durability receipt | client成功応答済み更新がreplica上で永続化された境界 | 自動無損失failover不可 |
|
||||
| Identity/secret inventory | logical service keyとphysical node keyの区別 | nodeを自動参加させない |
|
||||
|
||||
合意前に作業できるのは仕様型、pure state machine、mock provider、観測専用probe、
|
||||
静的UI/認可契約の設計まで。runtimeへのwrite gate接続も、別件の保存経路を網羅できることを
|
||||
確認してから行う。この順序は「DBが共有のままでもroleのflagだけ先に動かす」ことを禁止する。
|
||||
|
||||
## 3. 実装タスクと依存順
|
||||
|
||||
以下は将来の予定。行が存在しても対象ソースを今回変更しない。
|
||||
|
||||
| ID | 実施内容 | 主な変更予定箇所 | 依存 | 完了判定 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| DR01 | version付き型、ID/epoch/構成検証、resource coupling planner | `internal/dr`の新model/config/planner | 設計D1 | 不正構成・独立不可・未知版を拒否。DB依存なし |
|
||||
| DR02 | pure state machineとoperation phase reducer、fake clock | `internal/dr`のstate/operation | DR01 | 不変条件N1〜N10の遷移試験。失敗時はwriterを開かない |
|
||||
| DR03 | 専用node identity、mTLS/署名/nonce、観測専用probe | `internal/dr`のtransport、server管理route | DR01 | 未認証/別group/replayを拒否。probeでroleが変わらない |
|
||||
| DR04 | runtime startup gateの接続、非DR互換、旧CLI禁止 | `cmd/pageswiki/main.go`、server middleware、store/CLI全writer入口 | DR02/03+保存経路合意 | 再起動で必ずrecovering。起動修復/workerも許可前にwriteしない |
|
||||
| DR05 | AuthorityStore interface、manual provider、etcd providerと限定service | `internal/dr`のauthority、専用運用cmd | DR01/02 | CAS競合/timeout/再起動でgrantが二重にならない |
|
||||
| DR06 | checkpoint adapter、世代/pin台帳、schema/read-only検証 | 既存`internal/dr/snapshot.go`と保存担当adapter | DR01+保存契約合意 | offline fixtureから再開可能。online未対応を明示拒否 |
|
||||
| DR07 | 認証済みmanifest/Range転送、recipient ACK、負荷制御 | DR transport、documentstore adapter、scheduler表示 | DR03/06 | 中断再開/破損/別groupアクセス/容量不足を検出 |
|
||||
| DR08 | v1/v2 anchor移行、管理manifest v3発行/受理/ACK | federation manifest、enroll/reconcile、受理repository | DR03/05/06+受理永続化合意 | 同内容再送・旧epoch・欠落履歴・rollbackを正しく処理 |
|
||||
| DR09 | fence provider契約、impact planner、証跡照合 | DR fence/operation、運用connector | DR05 | 隔離未確認/誤node/別boot/別group影響で昇格拒否 |
|
||||
| DR10 | 手動switchover/failover/reseedをoperationへ統合 | DR CLI/API、root activation、routing adapter | DR04〜09 | 完全fixtureでroleごとの切替と共有DB連動が成立 |
|
||||
| DR11 | preempt planner、自動coordinated gate、cooldown | DR policy executor | DR10+設備認定 | flapping抑制、0損失の計画復帰、不可条件時の提案のみ |
|
||||
| DR12 | DR管理UI、i18n、health、Inbox、監査集約 | config panels、status APIs、metrics | DR03/10+operator認可 | group別表示、権限境界、秘密非表示、plan/applyが一致 |
|
||||
| DR13 | v0移行/本番runbook、復旧訓練、負荷/障害試験 | docs/operations、隔離検証環境 | DR10/12 | 受入matrix全通過、RPO/RTO実測、明示承認後のみ有効化 |
|
||||
|
||||
DR04以降のコード接続は、DB別件の差分が落ち着き接続点が合意された後。
|
||||
DR08のschema実装は保存担当の変更計画に載せ、DRタスクが独自migrationを追加しない。
|
||||
DR09の機器connectorは任意shell入力ではなく、許可された設備・resource IDへのtyped操作とする。
|
||||
|
||||
### 段階リリース
|
||||
|
||||
| 段階 | 提供するもの | 明示的に提供しないもの |
|
||||
| --- | --- | --- |
|
||||
| L0:現行初版 | offline snapshot、検証、手動復元・昇格 | 再参加判定、オンライン同期、自動fencing |
|
||||
| L1:観測 | DR01〜03、状態の参照UI | 自動昇格、既存writerのruntime変更 |
|
||||
| L2:再参加gate | DR04/05、operator承認下の起動、shared bundle判定 | 未接続の保存経路があるprofileの有効化 |
|
||||
| L3:同期・手動切替 | DR06〜10、認証転送、group別の計画操作 | 未認定providerの自動切替 |
|
||||
| L4:自動主系復帰 | 認定済みDR11/12、coordinated preempt | snapshotのみを根拠にした無人・無損失failover |
|
||||
| L5:自動障害復旧 | replica durability receipt等が揃うprofileのみ | 未複製更新や未知損失の黙認 |
|
||||
|
||||
各段階で有効化フラグは既定off。capabilityの揃わない段階へUI操作で飛び越せない。
|
||||
L1の観測機能が動作しても「Learningから自動で昇格できる」と表示しない。
|
||||
|
||||
## 4. CLI・API・UIの実施内容
|
||||
|
||||
将来CLI案(すべて未実装、DB直接更新用コマンドではない):
|
||||
|
||||
```text
|
||||
pageswiki dr config validate --file <operator-config>
|
||||
pageswiki dr groups status --group <id>
|
||||
pageswiki dr rejoin plan --group <id> --node <id>
|
||||
pageswiki dr switchover plan --group <id> --to <id>
|
||||
pageswiki dr failover plan --group <id> --to <id>
|
||||
pageswiki dr operations apply --plan <id> --plan-sha256 <hash>
|
||||
pageswiki dr operations show --id <id>
|
||||
pageswiki dr operations cancel --id <id>
|
||||
pageswiki dr reseed plan --group <id> --node <id> --checkpoint <id>
|
||||
```
|
||||
|
||||
現行の `dr promote` はL0専用とする。D1管理されたdatasetでは旧epochの手動書換えに
|
||||
ならないよう拒否し、operationへ案内する。旧binary/旧CLIもwriterとして動けない配置制約を
|
||||
設ける。新設定ファイルの存在を古いbinaryが無視する可能性は、file markerだけでは解決しない。
|
||||
|
||||
online CLI、Web、policy executorは同じplan/operation serviceを使う。
|
||||
dry-run/planはfence・permission・同期実体を変更しない。operatorがCLIから秘密付きbackupを
|
||||
扱えることと、campus_adminがWebから全DBをダウンロードできることを同一にしない。
|
||||
|
||||
UIは最初に観測だけを実装し、operationが完成した段階で切替ボタンを追加する。
|
||||
コンパクトなgroup一覧、control/dataの別ラベル、preempt状態、同期点、ブロック理由を優先する。
|
||||
確認dialogには「どのCampus/Domain/同居groupが止まるか」「失う可能性のある期間」
|
||||
「隔離手段」「未達条件」を列挙する。UNIX時刻入力や、色だけの安全判定は使わない。
|
||||
|
||||
## 5. 受入試験マトリクス
|
||||
|
||||
テストはfake clock/fake authority/fake fence/一時保存領域から開始し、
|
||||
実カレンダー・個人文書・本番ノードには接続しない。各テストは最終状態だけでなく、
|
||||
途中のwriter許可集合を記録し、同一resourceで2 holderになっていないことを検査する。
|
||||
|
||||
| ID | 入力・障害注入 | 期待結果 |
|
||||
| --- | --- | --- |
|
||||
| T01 | primary記録を持つnodeが再起動、peer応答なし | recovering→blocked、migration/worker含めwrite 0 |
|
||||
| T02 | 非DR instance起動 | 従来の起動を維持。DR期待環境で設定欠落なら起動拒否 |
|
||||
| T03 | 別group、未知鍵、同FQDNで別fingerprint、失効nodeからprobe | 認証/認可拒否、WARNING。membership変化なし |
|
||||
| T04 | 古いboot/nonce、応答遅延、重複JSON key、未知protocol、大きすぎるbody | 状態遷移なし。入力種別に応じたerror |
|
||||
| T05 | peerが大きいepoch/primaryを自己申告、authorityは異なる | 再確認・conflict、安全側停止。自己申告で昇格なし |
|
||||
| T06 | 発見peerの半数以上が同じ内容、登録authorityに到達不能 | 観測の多数決でgrantを出さない |
|
||||
| T07 | 同一DBのCG/DGが別holderを要求、alias resourceも混在 | WRITER_BOUNDARY_COUPLED、連動planを提示 |
|
||||
| T08 | 独立storeのCG停止、DGは有効grantと設定を保持 | CGだけ停止。DGは権限鮮度条件の範囲で継続 |
|
||||
| T09 | CGのpreempt on、DGのpreempt off | 独立profileならCGのみ戻る。sharedなら連動影響を承認前に提示 |
|
||||
| T10 | primaryの停止・再開、時計逆行、VM pause、permit応答喪失 | stale permitでwrite再開なし。新grantにはfenceを要求 |
|
||||
| T11 | 2 executor/2 candidateが同時に同group操作、response消失、manual agent二重起動 | 一つのoperation/grantだけ確定。同じIDで結果照合、manual agent排他 |
|
||||
| T12 | fence要求送信済みだが確認不明、別node/古いbootの証跡 | FENCE_UNCONFIRMED、grantなし |
|
||||
| T13 | ホストfenceが別DG primaryにも影響 | 自動preempt禁止、impactに全groupを列挙 |
|
||||
| T14 | capture中にDB更新・calendar世代更新・GC・schema変更 | barrier/capabilityに従い排他。保証不能ならcapture中止 |
|
||||
| T15 | 転送中断/Range再開、chunk改変、symlink/path traversal、未登録file ID | 検証失敗、他データを読ませずactive root不変 |
|
||||
| T16 | blobの一部欠落、calendar参照世代欠落、schema不適合、secret欠落 | verified/applicable ACKなし、standby公開なし |
|
||||
| T17 | pin後にsource再起動、transfer期限切れ、GC/保持処理 | 必要世代を消さない。残存pinを照合して回収 |
|
||||
| T18 | 同期中に新しいwrite、表示上lag=0だが最終cut未確定 | switchover不可。final checkpointの一致を必須とする |
|
||||
| T19 | metadataのみ最新、ACL/session失効は古い | read/write readinessとも不成立 |
|
||||
| T20 | 旧primaryに現系列にない更新 | 隔離保全、conflict。自動マージ/削除なし |
|
||||
| T21 | manifest旧epoch、同sequence異hash、欠落親、receiptなし | 適用拒否。v3導入後のv1/v2 downgradeも拒否 |
|
||||
| T22 | 内容適用と受理checkpointの間で失敗、publication receipt応答喪失 | 一体rollback/同内容照合。別payloadで再発行しない |
|
||||
| T23 | controller復元点が管理ノード受理位置より古い | blocked、epochを増やして古い権限を再配信しない |
|
||||
| T24 | 各operation phaseの前後でprocess kill | 文書化したphaseから再開。REVOKING以降は旧epoch復活なし |
|
||||
| T25 | GRANTED後root切替失敗、RO filesystem、disk full、fsync失敗 | 新primaryを公開せず、次の復旧operationへ |
|
||||
| T26 | routing更新失敗、DNS cacheに旧宛先、既存keep-alive | 新primaryは一つ。旧宛先はwrite拒否、routing修復 |
|
||||
| T27 | 同期済みpreferred nodeが繰り返しflap、時間帯/DST境界 | 安定時間リセット、cooldown遵守、不要な再切替なし |
|
||||
| T28 | snapshotの鮮度はRPO内だがclient成功応答の反映が不明 | 自動障害昇格不可。損失確認をoperatorへ要求 |
|
||||
| T29 | grant lease失効/authority quorum喪失/watch欠落 | 新grantなし。local gate期限で停止、外部fence前は他holder不可 |
|
||||
| T30 | AuthorityStoreを古いbackupへ復元、manual台帳の破損/消失 | 全writerを隔離、新trust世代の手動復旧。epochの黙認・自動初期化なし |
|
||||
| T31 | high IO/CPU/foreground要求増、巨大snapshot | stream/帯域/hash上限を維持。制御通信が転送に埋もれない |
|
||||
| T32 | campus_admin/domain_adminが他scope切替/backup秘密を要求 | 拒否。read UIも他Campus・secretを漏らさない |
|
||||
| T33 | restart後workerが過去jobを拾う、外部通知結果が曖昧 | 許可と再送条件を確認。曖昧な副作用は自動で成功/再送しない |
|
||||
| T34 | operatorがcancel/disable/旧binaryへのrollbackを要求 | 安全点だけ取消。active grantを消して旧系を復活させない |
|
||||
|
||||
T24はPLANNED〜COMPLETEDの全境界で行う。ネットワークを切るタイミングも
|
||||
「要求送信前」「相手がcommit後、応答前」「応答後、ローカル永続化前」に分ける。
|
||||
fixtureの全writer経路を一度ずつ実行し、HTTP guardだけで満たしたと判定しない。
|
||||
|
||||
## 6. 性能・運用の合格条件
|
||||
|
||||
固定のRTO保証値を現時点で作らず、次の測定結果を導入記録に残す。
|
||||
|
||||
- 通常foreground p50/p95/p99と、同時同期時の差。目安の許容悪化率は10%以内、超過なら転送予算を縮小。
|
||||
- DB/可変正本のbarrier時間、checkpoint作成時間、初回/増分転送時間、検証時間、必要空き容量。
|
||||
- suspect検知、fence確認、grant、起動、routing完了の各所要時間と合計RTO。
|
||||
- 障害時点と最後のDR側検証cutの差、client成功応答境界の確認可否、未複製損失の有無。
|
||||
- スナップショット10万/100万file相当のmanifest paging、RSS/heap、descriptor数の上限。
|
||||
初版v1の10万file上限を、v2の性能試験なしに解除しない。
|
||||
- 一日継続のprobe/転送/再起動試験で、timer・goroutine・scratch・pin・operationが無制限に増えない。
|
||||
|
||||
10%は候補性能予算であり、実機測定前に達成と表明しない。別件の保存層の性能評価と同じ
|
||||
fixture条件を使用する。外部サービス/実データにアクセスする実機試験は別途承認を得る。
|
||||
|
||||
## 7. 導入時に入力・承認する事項
|
||||
|
||||
設計として未決のアルゴリズムではなく、設備・運用に依存する導入パラメータを列挙する。
|
||||
|
||||
| 入力 | 決定する主体 | 未入力時 |
|
||||
| --- | --- | --- |
|
||||
| node FQDN/管理origin、node identity、対象Campus/DG、resource対応 | 運用者+保存担当 | 登録・同期を開始しない |
|
||||
| RPO/RTO、retention、容量/帯域予算 | 運用者 | 本番enable不可 |
|
||||
| authority配置、CA、専用service key保管/更新、quorum障害領域 | 運用者 | manualのみ |
|
||||
| fence機器/credential参照、再起動抑止、影響group | 運用者 | coordinated enable不可 |
|
||||
| backup/secret暗号化と復号担当、別障害領域の保全先 | 運用者 | 秘密付き転送不可 |
|
||||
| CG/DGごとのpreferred、preemptと許可時間帯 | 運用者+管理者 | preempt off |
|
||||
| 保存profile能力と対応app/image/schema | 保存担当 | offline/shared-instanceのみ |
|
||||
|
||||
## 8. 本番導入手順
|
||||
|
||||
1. 運用者が対象と入力を確定し、保存担当がresource map・能力契約を承認する。
|
||||
2. 本番とは通信しない隔離fixtureで対応段階のT01〜T34と負荷試験を実施する。
|
||||
3. 既存環境の保全・image digest・schema互換性・復旧手順をレビューする。実データ保全は別途承認。
|
||||
4. L1観測のみを配置し、比較表示を確認する。旧roleに基づくサービス挙動はこの段階では変えない。
|
||||
5. 全writerと旧CLIを停止する保守枠を取り、L2への移行planを確認する。
|
||||
6. 旧cluster/node/roleを新group/resourceに対応させ、fresh authorityをbootstrapする。
|
||||
旧primaryの確認記録を付け、元のepochを新authorityの根拠にしない。
|
||||
7. 新startup gate下で起動し、他nodeはlearnerとして参加。sourceと同期内容を検証する。
|
||||
8. L3の手動switchoverと復帰を1往復実施し、RPO/RTO・監査・権限失効・queueを検証する。
|
||||
9. 保存分離済みprofileならCG/DGの独立切替、共有profileなら連動拒否/連動切替を確認する。
|
||||
10. 能力が揃ったgroupに限り、明示承認を得てL4を有効化する。L5は別の認定を要求する。
|
||||
|
||||
ローリング移行中、旧ノードをwriter候補に残さない。mixed protocolで書込み可能nodeを
|
||||
増やす移行はしない。旧nodeからのprobeは対応版を表示し、新grant候補から除外する。
|
||||
管理manifest v3は全対象が移行anchorをACKした後に切替える。
|
||||
|
||||
## 9. 撤退・失敗時
|
||||
|
||||
DRの「無効化」は設定ファイル削除ではない。新operation受付を止め、active operationを照合し、
|
||||
一つのwriterを運用者が確定・隔離確認してから非DR運用への移行planを実行する。
|
||||
authorityを停止しただけで旧nodeに書き込みを許可しない。
|
||||
|
||||
L1だけなら観測プロセスを停止して戻せる。L2以降はrole/許可/DB互換性の記録を保持する。
|
||||
新epochでwriteが発生した後は、旧snapshotを起動することでrollbackしない。
|
||||
旧binaryに戻す場合は、最新データとschema互換性を検証し、DRのtrust/gateを無視するbinaryが
|
||||
同時に動かないことを外部で保証する。保証できなければ停止を継続する。
|
||||
|
||||
実施結果には、適用していない段階、満たしていない能力、最後に検証した世代、
|
||||
次に必要な承認を必ず残す。設計完了・実装完了・復旧訓練完了・本番稼働を同じチェックにしない。
|
||||
@@ -0,0 +1,397 @@
|
||||
# DR詳細設計:通信・同期・主導権移譲契約
|
||||
|
||||
設計版:DR-D1、2026-09-27。**すべて次段階の設計。新endpoint・設定・永続化は未実装。**
|
||||
責務と用語は [管理主系・データ主系](dr-authority-and-rejoin.md)、実装の順序は
|
||||
[実施計画](dr-delivery-plan.md) を正とする。DB変更は本作業に含めない。
|
||||
|
||||
## 1. 構成と永続化の契約
|
||||
|
||||
### 1.1 Authority Service
|
||||
|
||||
manual providerは単一のoperator管理agentと専用のdurable操作台帳を使用する。
|
||||
台帳は業務DB/snapshot外のローカル保護領域に置き、プロセス排他、revision比較、
|
||||
operationの追記・fsync後の応答を必須にする。grant発行・holder変更にはoperator承認が必要。
|
||||
同じ許可の短期renewは自動でもよいが、別boot/holderへの変更にはならない。
|
||||
台帳破損/消失/別agent起動で自動再初期化せずblockedにする。manual provider自体のHAは
|
||||
提供せず、復旧時は旧agentと全writerを隔離してtrust再承認する。これは独自分散合意ではない。
|
||||
この運用台帳をアプリmetadataや管理manifest受理checkpointの代わりには使わない。
|
||||
|
||||
独立した運用サービスとしてgroup membership、grant、operation、fence証跡の参照を扱う。
|
||||
coordinated providerはetcd v3の線形化readと比較更新transaction。業務nodeにはetcdの
|
||||
任意Put権を与えず、認証されたAuthority Serviceの限定操作を通す。APIプロセスは複数起動できるが、
|
||||
決定の正本は一つのetcd keyspaceであり、プロセスのメモリや通常event queueではない。
|
||||
|
||||
論理keyは `groups/{kind}/{uuid}/membership`、`.../active`、`resources/{uuid}/active`、
|
||||
`operations/{operation_uuid}`、`trust/generation`。これはetcdの論理配置案で、アプリDBのDDLではない。
|
||||
group/resource activeとoperation phaseの変更は同じCAS transactionで確定する。
|
||||
共有bundleは関連全group/resourceを同じtransactionに含める。provider上限を超えるbundleは
|
||||
登録時に拒否し、一部だけ切替えない。初期上限は1 bundleあたりgroup+resource合計32。
|
||||
|
||||
`active` は `{membership_revision, trust_generation, epoch, holder_node_id, holder_boot_id,
|
||||
state, operation_id, resource_epochs, checkpoint_id, revision}` を持つ。
|
||||
`state` は ACTIVE / REVOKING / FENCED / PREPARED / NONE。epochは10進文字列uint64、
|
||||
上限でエラー。membership revisionとprovider revisionもJSON数値精度に依存しない文字列にする。
|
||||
epochと操作intentはleaseに付けず保存し続ける。短期permitだけが期限付き。
|
||||
|
||||
### 1.2 契約インターフェース
|
||||
|
||||
| 契約 | 入力→結果 | 必須の性質 |
|
||||
| --- | --- | --- |
|
||||
| `ObserveAuthority` | group/bundle→membership、active、revision | 線形化read。watch/probeのcacheで代替不可 |
|
||||
| `PlanTransition` | expected revision、target、reason→immutable plan/hash | 不足能力・影響・損失・必要承認を全列挙。副作用なし |
|
||||
| `BeginTransition` | plan hash、承認、idempotency key→operation | CASで一つだけ開始、競合は409 |
|
||||
| `RecordFence` | operation、provider evidence→FENCED | exact node/boot/resource/operationへの新鮮な証跡を検証 |
|
||||
| `CommitGrant` | 検証ACK、fence、expected各revision→PREPARED | group/resourceを原子的に新holderへ。旧grantは復活不可 |
|
||||
| `RenewPermit` | active grant、boot、nonce→短期permit | ACTIVE holder、またはPREPARED holderの限定初期化scopeだけ。期限更新は権限移譲ではない |
|
||||
| `CompleteActivation` | writer gate/root検証ACK→ACTIVE | checkpoint/root、schema、grantの一致。未完なら配信不可 |
|
||||
| `DescribeResources` | role→resource集合・能力 | aliasを含む共通正本を検出。未申告は独立と見なさない |
|
||||
| `FreezeWriters` | bundle、operation、deadline→cut候補 | 新規受付停止、実行中writerをdrain。未知writerがいれば失敗 |
|
||||
| `CaptureCheckpoint` | freeze token→checkpoint、pins | metadata/可変正本の同一cut、checksum、復旧に必要な参照集合 |
|
||||
| `Stage/VerifyGeneration` | checkpoint、payload→verified ACK | 非稼働rootのみ。権限/互換性も検証し、writerを開かない |
|
||||
| `ActivateGeneration` | verified ACK、grant→root ACK | root pointerをdurableに切替。曖昧な状態はrecovering |
|
||||
| `ApplyControlManifest` | envelope、expected受理checkpoint→ACK | 内容・受理checkpointを同じ永続化境界でcommit |
|
||||
|
||||
PREPAREDではmigration/正本修復に必要な限定writerを新holderだけに許可できる。
|
||||
通常リクエストとworkerはACTIVEになるまで閉じる。移行が長引けばpermitを更新する必要がある。
|
||||
初段は同じschema/imageで復元し、DR切替にschema migrationを混ぜない。
|
||||
|
||||
`FreezeWriters` の成立はアプリDBの外から書くCLI等も止められる場合に限る。
|
||||
未知writerが存在する保存profileは、サーバ/CLI全停止と外部保守lockによるoffline modeだけを許可する。
|
||||
保存層で実現できない契約を、別ファイルへの二重書きで「同じtransaction」と称しない。
|
||||
|
||||
## 2. 信頼・ネットワーク
|
||||
|
||||
接続はHTTPS、TLS 1.2以上、mTLSによる専用node identityとgroup許可を必須にする。
|
||||
検証無効化、HTTPフォールバック、通常Campus参加tokenの転用はしない。
|
||||
既存の開発用 `--add-external-campus-http` はこのprotocolを許可しない。
|
||||
初回信頼はoperatorがCA/鍵fingerprintとnode UUIDを別経路で承認する。probeによるTOFUはしない。
|
||||
|
||||
TLS終端proxyを用いる場合、外部からのidentity headerを除去し、信頼済みproxy接続だけで
|
||||
検証済みidentityを伝える。加えて下記のnode署名で要求を束縛する。任意の
|
||||
`X-Client-Cert` やFQDNだけで認証しない。FQDNの再利用・鍵変更はWARNING+quarantine。
|
||||
|
||||
peer endpointはoperatorが登録したHTTPS originと固定prefixのみ。ユーザーのURL入力や
|
||||
probe応答の未知URLへ自動接続しない。redirectは禁止。私設networkの許可はgroupごとの
|
||||
allowlistで定義し、DNS解決後の宛先IPも検証する。TLSのserver nameと登録originは維持する。
|
||||
|
||||
### 署名envelope
|
||||
|
||||
共通JSON envelopeは `protocol_version="dr/1"`, `key_id`, `payload_b64`, `payload_sha256`,
|
||||
`signature_b64`。payloadはUTF-8 JSONの**送信した正確なbyte列**を署名し、再serializeしない。
|
||||
署名対象は用途別固定prefix(例 `pageswiki.dr.probe.request.v1\n`)+payload bytes。
|
||||
Ed25519を用い、種類の異なるenvelope間で署名を使い回さない。JSON重複key、未知version、
|
||||
不正UTF-8、深さ過大、型違い、未知の必須capabilityを拒否する。canonical JSONの独自実装は不要。
|
||||
|
||||
通信payloadは `request_id`, `sender_node_id`, `sender_boot_id`, `group_id`, `group_kind`,
|
||||
`membership_revision`, `trust_generation`, `nonce`, `issued_at`, `expires_at` を共通に持つ。
|
||||
nonceは32 random bytesのbase64url、request_idはUUID。応答は要求ID/nonce/宛先node/bootと
|
||||
要求payload hashをechoし、観測したauthority revisionを含める。nonce未要求・別boot・期限切れ
|
||||
応答は状態遷移に使わない。UTC時刻の許容ずれは5秒、response有効時間は10秒以内を初期値とする。
|
||||
時刻だけに依存せず、boot/nonce/authority revisionも検証する。
|
||||
|
||||
node用秘密鍵はnode-local。Campus manifest署名鍵とは別。信頼世代・鍵ローテーションは
|
||||
旧新keyの承認期間と撤回revisionを記録し、同一nodeを二つのbootが同時に有効化しない。
|
||||
|
||||
要求payloadには `http_method`, `request_target`, `audience_id` も含め、実際のmethod/管理URI/
|
||||
受信nodeまたはserviceに一致させる。署名検証前に別URIへrewriteしない。未知query、dot-segment、
|
||||
encoded slashなどの曖昧なpathを拒否する。path groupとpayload groupの不一致も拒否する。
|
||||
管理manifestの署名鍵をbackupから持ち出せても、Authority Serviceが確定したpublication receipt
|
||||
なしに新manifestを受理させない。署名鍵を保持することと、現在の発行権限を持つことを分離する。
|
||||
|
||||
POSTの通信envelopeはJSON body、GETは8KiB以内の `PagesWiki-DR-Request` headerへ格納し、
|
||||
GET bodyを要求しない。Range要求はその値も署名payloadへ含める。通常JSONの復号payload上限は
|
||||
256KiB/深さ16、manifest pageだけは1MiBまで。binary転送の応答検証は署名済みmanifestの
|
||||
chunk/全体hashで行い、全ファイルをbase64 JSONに包まない。
|
||||
保管するcheckpoint/manifest署名は通信envelopeと用途prefixを分け、request nonceや10秒の
|
||||
応答期限を付けない。不変artifactの由来/完全性検証と、今このnodeがアクセス・書込みできるかの
|
||||
短期許可検証を分離する。古いartifact署名が有効でも現行のwrite grantにはならない。
|
||||
|
||||
## 3. probeと再参加
|
||||
|
||||
`POST /_/api/v1/instance/dr/probes` を認証済みgroup member/learnerだけに提供する。
|
||||
無認証でpeer一覧、group一覧、snapshot一覧を返さない。
|
||||
|
||||
要求の追加項目:
|
||||
|
||||
```json
|
||||
{
|
||||
"group_kind": "data",
|
||||
"group_id": "<group-uuid>",
|
||||
"sender_node_id": "<node-uuid>",
|
||||
"sender_boot_id": "<new-boot-uuid>",
|
||||
"known_authority_revision": "123",
|
||||
"known_epoch": "7",
|
||||
"applied_checkpoint_id": "<checkpoint-uuid-or-null>",
|
||||
"supported_protocols": ["dr/1"],
|
||||
"capabilities": ["probe-v1", "offline-checkpoint-v1"],
|
||||
"nonce": "<random-base64url>"
|
||||
}
|
||||
```
|
||||
|
||||
例は共通項目の一部を省略した型説明で、稼働設定として投入しない。
|
||||
応答はprimary観測値、membership revision、state、checkpoint id/hash/親、
|
||||
内容cut時刻、verified/applicableの区別、schema互換性、roleに応じたcontrol受理位置を返す。
|
||||
資格情報・文書本文・ユーザー一覧・内部path・任意SQLは返さない。
|
||||
|
||||
probe結果は `observed`、AuthorityStore read結果は `authoritative` と区別する。
|
||||
処理順:node identity→group所属→nonce等→protocol→authority照合→履歴照合→同期plan。
|
||||
新しいepochを発見したら必ずauthorityへ再確認し、peerだけを根拠に旧許可を新primaryへ移さない。
|
||||
矛盾の疑いがあれば自ノードのwriterは安全側へ閉じるが、他ノードの昇格は承認しない。
|
||||
|
||||
既知peerへ並列fan-outする。初期同時数4、groupごと最大32 endpoint、1応答256KiB、
|
||||
要求/応答rateは1 nodeあたり10req/sまで。初回は即時、その後5秒±20%jitter。
|
||||
失敗時は最大60秒までbackoff、安定した成功で戻す。タイマー終了はsuspect表示だけを変える。
|
||||
membership変更はoperatorによるexpected revision付き操作。join要求はlearner候補に留め、
|
||||
既存memberやauthority quorumを自動的に増減させない。
|
||||
|
||||
## 4. API境界とエラー
|
||||
|
||||
全URIは予定。通常ユーザーのPath/公開Domainからは独立した管理経路に置く。
|
||||
|
||||
| method / prefix以下のURI | 呼出主体 | 契約 |
|
||||
| --- | --- | --- |
|
||||
| `GET capabilities` | 登録node/operator | protocol、schema/profile能力。対応申告であり同期完了証明ではない |
|
||||
| `POST probes` | group member/learner | 情報収集のみ。grantを発行しない |
|
||||
| `GET groups/{kind}/{id}/status` | node/operator、範囲制限した管理者 | observed/authoritative/as_ofを明示 |
|
||||
| `POST groups/{kind}/{id}/plans` | operator | rejoin / switchover / failover / reseedの副作用なしplan |
|
||||
| `POST operations` | operator/認定済みpolicy executor | plan hashと承認を照合して開始 |
|
||||
| `GET operations/{id}` | 許可された操作主体 | phase、未達条件、証跡、結果 |
|
||||
| `POST operations/{id}/cancel` | operator | cancel可能点だけ。grant移譲後を勝手に巻き戻さない |
|
||||
| `GET groups/{kind}/{id}/checkpoints/{id}` | 承認replica/operator | 署名metadata、transfer manifest参照 |
|
||||
| `POST transfers` | 承認replica/operator | group/checkpoint/recipientを固定した転送session |
|
||||
| `GET transfers/{id}/manifest` | session recipient | paged immutable manifest、snapshot ETag |
|
||||
| `GET transfers/{id}/files/{file_id}` | session recipient | 許可されたopaque file IDのRange取得 |
|
||||
| `POST transfers/{id}/acks` | session recipient | bytes受信/検証/適用ACKを別stageで記録 |
|
||||
| `POST groups/{kind}/{id}/permits/renew` | active holderのみ | node/boot/epoch/resourceを束縛した期限更新 |
|
||||
|
||||
prefixは `/_/api/v1/instance/dr/`。node-local probe/transferはnode agentが処理し、
|
||||
plans/operations/grantはAuthority Serviceが処理する。配置proxyは経路を区別し、
|
||||
node agentがauthority不通時に代わりのgrantを作らない。
|
||||
|
||||
state変更要求は `Idempotency-Key: UUID` とplan/expected revision必須。同じkey・同じbodyは
|
||||
同じoperationを返し、同じkeyで異bodyは409。応答喪失後は元operationをGETして照合する。
|
||||
planの有効期間は60秒。membership、epoch、checkpoint、fence影響範囲が変われば期限内でも失効。
|
||||
grant commit前にはもう一度最新条件を再検査する。
|
||||
|
||||
Web操作はoperator認可gatewayを介し、human actor・scope・承認内容・plan hashを短命の
|
||||
delegationに束縛してAuthority Serviceへ渡す。nodeの秘密鍵やetcd資格情報をブラウザへ渡さない。
|
||||
gatewayが認可しただけでimpact planの承認を省略しない。instance operatorの認可信頼源が
|
||||
接続されるまではWeb applyを無効にし、ホスト運用者のCLIだけを提供する。
|
||||
|
||||
| HTTP | code例 | 呼出側の動作 |
|
||||
| --- | --- | --- |
|
||||
| 400 | INVALID_ENVELOPE / UNSUPPORTED_VERSION | 修正までretryしない |
|
||||
| 401/403 | IDENTITY_REQUIRED / GROUP_FORBIDDEN | 権限修正。未知groupの内容は隠す |
|
||||
| 404 | UNKNOWN_RESOURCE | 他groupの存在を推測できる詳細を返さない |
|
||||
| 409 | STALE_EPOCH / OPERATION_CONFLICT / HISTORY_DIVERGED / WRITER_BOUNDARY_COUPLED | 再probeまたは新plan。自動上書きしない |
|
||||
| 412 | MANIFEST_CHANGED / STALE_PLAN | 同一転送・旧planを継続しない |
|
||||
| 413/429 | LIMIT_EXCEEDED / RATE_LIMITED | 上限内へ縮小、Retry-Afterを遵守 |
|
||||
| 501 | CAPABILITY_UNAVAILABLE | offline/manualへ明示的に再計画。暗黙downgradeしない |
|
||||
| 503 | AUTHORITY_UNAVAILABLE / NOT_READY / FENCE_UNCONFIRMED | 書き込みを閉じて待機 |
|
||||
|
||||
JSON errorは `code, message_key, request_id, retryable, operation_id`。本文・秘密・SQLは含めない。
|
||||
管理レスポンスはno-store。状態取得はETag可、ただしcached statusを昇格承認には使わない。
|
||||
|
||||
### 配信とreadiness
|
||||
|
||||
管理listenerは一般DomainのHost選択/ログインsessionから独立して認証し、learning中もprobeを
|
||||
受けられるようにする。復旧した業務DBの認証設定だけに、再参加の身元検証を依存させない。
|
||||
通常routeはHost→Domain→DG→resource/grantの順に解決し、各要求で対象groupを判定する。
|
||||
コントローラ用routeはCampus→CGを判定する。HTTP methodだけでどちらのprimaryか決めない。
|
||||
|
||||
node全体の `/health` は生存確認。複数groupで混在する場合、従来の `/health/write` は
|
||||
対象listenerの全write groupがreadyなときだけ200とする保守的な集約値で、個別routingには使わない。
|
||||
認証済みgroup statusの `read_ready`, `write_ready`, `state`, `reason`, `as_of` を
|
||||
routing adapterへ渡し、切替時はfresh authorityと実際のgate状態も照合する。
|
||||
PREPARED/ACTIVATINGは通常write readyにしない。既存接続も切替後の各要求で再検査し、
|
||||
古い接続が旧primaryへの書込権を保持することはない。URIやHostをDRノードFQDNへ書き換えない。
|
||||
|
||||
## 5. Checkpointとバックアップ契約
|
||||
|
||||
### 5.1 内容
|
||||
|
||||
checkpoint v2(初版snapshot v1とは別format)は次を持つ。
|
||||
|
||||
- format/protocol version、group kind/id、dataset ID、checkpoint UUID、親checkpoint hash。
|
||||
- source node/boot、trust generation、control/data/resource epoch、membership revision。
|
||||
- snapshot cut ID、cut時刻、capture完了時刻、内容集合digest。
|
||||
- app SemVer、image digest、保存profile、schema component/version/checksumの集合。
|
||||
- DB snapshot descriptor、可変正本manifest一覧、CAS参照集合、総byte数、file数。
|
||||
- 管理manifest受理位置、ACL/session失効watermark、outbox/job再送判定位置。
|
||||
- 暗号化方式・key参照・別保全のsecret一覧。secret値は一覧に含めない。
|
||||
- 操作状態 `capturing/sealed/transferring/verified/activated`。sealed前はservableにしない。
|
||||
|
||||
「送信完了」「受信した」「hash検証済み」「配信可能」「昇格可能」は別。
|
||||
checkpoint sequenceはその系列の順序であり、clientへ成功応答した全変更の境界とは限らない。
|
||||
初段のsnapshot同期は物理snapshot+CAS不足分転送。SQL差分適用やWALファイルの独自転送はしない。
|
||||
オンラインのtransaction log方式は保存層が将来別profileとして保証するまで使わない。
|
||||
|
||||
### 5.2 一貫したcapture
|
||||
|
||||
1. capture対象のbundle/resourceを確定し、schema変更と同時に走らないことを確認する。
|
||||
2. 新規writer受付を閉じ、DB・可変正本の処理中更新をdrainする。GCも対象世代を消せない状態にする。
|
||||
3. 保存層に同一cutのDB snapshotと可変正本manifestを固定させ、参照集合を確定する。
|
||||
4. 参照CAS/月別世代へのdurable pinを確立する。pinの永続化とcut固定を確認する。
|
||||
5. sealedしたDB像・metadataから後続コピーできることを確認してbarrierを解除する。
|
||||
6. 大きな不変payloadのhash確認/転送はforegroundより低優先度で継続する。
|
||||
|
||||
SQLite Backup APIはDB単位の整合コピーであり、別ファイルの同一cutまで自動保証しない。
|
||||
DB像の固定にコピー完了まで必要なprofileでは、その間barrierを維持する。
|
||||
「短時間online」と無条件に表明せず、barrier予算超過ならpublish前にcaptureを中止し、
|
||||
primaryを再検査して通常処理へ戻す。最初はoffline profileだけでもよい。
|
||||
[SQLite Backup API](https://www.sqlite.org/backup.html)
|
||||
|
||||
pinの保持はtransferの期限と独立。transfer sessionが切れても、保全世代/進行中operationから
|
||||
参照されるblobを消さない。完了/中止後もretentionに従って解放する。ノード再起動でpinが
|
||||
失われるprofileはオンラインcapture不可。保持台帳の実装は保存担当の契約に従う。
|
||||
|
||||
### 5.3 受信・再開・切替
|
||||
|
||||
受信は非稼働generationに対して行う。file IDはmanifest内でscope付きに割り当て、
|
||||
任意pathや他groupのhashを直接読めるAPIにしない。manifestは1page最大1,000件/1MiB、
|
||||
sealed manifestのroot digestとpage hashで全体を検証する。各payloadは全体hash/sizeと
|
||||
16MiB単位のchunk hashを持ち、Range再開時にもchunkと全体の両方を検証する。
|
||||
|
||||
転送sessionはrecipient node/boot、group、checkpoint、期限に結び付く。初期期限15分、
|
||||
再認証後に同じsealed checkpointへ再開可能。期限はreaderの権限であり正本の寿命ではない。
|
||||
宛先の空き容量は必要byte+20%と運用予約分を確認し、既存稼働世代を自動削除して空きを作らない。
|
||||
|
||||
受信後:全payload→DB/正本参照整合→schema互換→失効/鍵の可用性→内容digestの順に検証する。
|
||||
DB inspectionはread-onlyで行い、初期化/migrationによって検証対象を変化させない。
|
||||
検証ACKを受けても一般routingは開かず、standbyのread条件または新grantを別途確認する。
|
||||
root切替は新generationをfsyncした後、atomic pointer更新で行う。旧世代を保持し、
|
||||
再起動時にpointerとoperation recordが食い違えばrecoveringで照合する。
|
||||
|
||||
転送負荷の初期値:nodeごとpayload stream最大2、合計10MiB/s、hash worker 1、
|
||||
foreground高負荷時は新chunk受付を停止。制御用probe/permitは別connection・別予算。
|
||||
リソース監視値が取れない場合は固定上限を維持し、無制限へ拡張しない。
|
||||
pause/backoff/cancelの最大応答遅延は1 chunkのI/O期限内。候補値30秒、実測して認定する。
|
||||
通常event schedulerにはcapture/verify/転送等を表示するが、grant更新は専用loopとする。
|
||||
|
||||
### 5.4 保全・秘密・分岐
|
||||
|
||||
複製は保全世代の代替ではない。retention初期案は直近3+日次7+週次4、導入時に容量確認する。
|
||||
世代依存とpinsを検査してから削除し、root trust/復号鍵の保全はsnapshotとは別の障害領域に置く。
|
||||
業務復旧に必要な暗号化鍵は許可済みgroup nodeへ保護して配布するが、物理nodeの専用秘密鍵は
|
||||
他ノードへ配布しない。初版が保全するlegacy instance keyとは移行時に区別する。
|
||||
|
||||
復帰ノードに現primaryの系列にない変更があれば、旧DB/正本を隔離したgenerationとして保全する。
|
||||
件数・由来・時点を示し、手動export/importや内容比較へ渡す。データの新旧をmtimeだけで比較せず、
|
||||
自動マージ、自動削除、旧DBの現primaryへの逆コピーを禁止する。
|
||||
|
||||
## 6. 管理manifestの世代設計
|
||||
|
||||
既存schema_version 1/2、署名と受理checkpointを維持し、新契約は **schema_version 3案** とする。
|
||||
未対応受信先が一つでも対象に含まれる間はv3配信/CG自動移譲を有効化しない。
|
||||
capability応答だけでなく、移行済み受理状態のACKを必要とする。
|
||||
|
||||
v3 payloadは既存管理情報に `control_group_id`, `trust_generation`, `control_epoch`,
|
||||
`manifest_sequence`, `configuration_checkpoint_id`, `previous_manifest_hash`, `payload_hash`,
|
||||
`authority_commit_receipt` を追加する。署名は確定した管理内容を一度だけserializeしたbyte列に行う。
|
||||
|
||||
発行手順:同じ管理snapshotから内容を取得→候補payloadを永続化→有効control grant下で
|
||||
authorityへ `expected previous hash/sequence` によるpublication commitを要求→返却receiptと
|
||||
署名を保存→配信。応答喪失なら同じpayload hashでcommit結果を照合する。新規内容に同じsequenceを
|
||||
割り当てない。receiptのない「大きなepochのmanifest」は配信・受理しない。
|
||||
snapshot内容の取得とcheckpoint固定は保存担当の契約が必要で、既存の連番SQLだけで代替しない。
|
||||
|
||||
受信手順:
|
||||
|
||||
1. Campus/CG/署名鍵/trust世代/対象Domain ownershipを検証する。
|
||||
2. authority receiptと、現在許可されたcontrol epochを確認する。epoch切替時はfresh authority確認必須。
|
||||
3. 同epochの小さいsequence、同sequenceで異hash、親hash不一致は拒否する。
|
||||
4. 同epoch・同sequence・同hashは冪等ACKとする。
|
||||
5. 新epochは署名済み移譲recordとbase管理checkpointを検証する。単なる数値の大小では許可しない。
|
||||
6. 管理内容と受理位置を一つのtransaction境界で保存し、そのcommit後に適用ACKを返す。
|
||||
|
||||
管理ノードprobeから回収した最大受理位置は「これより前へ戻してはいけない」下限の証拠。
|
||||
完全な管理正本の代わりではない。checkpointが不足すればCGはblockedとし、新epochを使って
|
||||
古い権限を再発行しない。復旧snapshotがauthorityの最後のpublicationより古い場合は、
|
||||
正しい履歴の取得または運用者による明示的な再構成・失効再適用を要求する。
|
||||
|
||||
v1/v2からの移行は最後のrevision/hashをmigration anchorとして固定し、最初のv3がそれを参照する。
|
||||
trust pinを削除してやり直す方法は採らない。v3受理後のv1/v2自動fallbackも拒否する。
|
||||
この永続化の追加は将来のDB担当との合意対象であり、本設計作業では実装しない。
|
||||
|
||||
## 7. 計画切替とpreempt
|
||||
|
||||
preemptはpreferred nodeへ向けたswitchover operationをpolicy executorが作るだけであり、
|
||||
特別な高速昇格経路を持たない。offなら現primaryを維持、manualなら提案のみ通知する。
|
||||
automaticでも安定時間/時間帯/cooldown/能力/影響範囲を満たさない限りplanをapplyしない。
|
||||
|
||||
| operation phase | 確定させること | crash/timeout時 |
|
||||
| --- | --- | --- |
|
||||
| PLANNED | target、expected構成、影響、必要能力、見込時間 | 期限切れで再plan。副作用なし |
|
||||
| VALIDATING | authority最新値、target同期/鍵/schema/ACL、fence能力 | 旧primaryの権利は変更せず停止 |
|
||||
| DRAINING | 旧primaryの新規write/job停止、実行中処理の結果 | 旧grantがまだ有効とauthorityで確認できる場合だけdrain解除可能 |
|
||||
| SEALED | final cutと内容集合、targetの最終検証ACK | 不足があれば旧権利の扱いを照合。勝手に切替えない |
|
||||
| REVOKING | 旧permit再発行禁止を永続化 | ここから旧epochの自動復活は禁止 |
|
||||
| FENCING | 旧writerへの外部隔離と、その確認証跡 | 不明ならblocked。新grantなし |
|
||||
| GRANTED | 新epochのgroup/resource許可をPREPAREDで確定 | holderをGETで照合し再開。別targetへretryしない |
|
||||
| ACTIVATING | target root/gate/schema/readinessを検証 | targetを隔離、次のoperationを計画。旧系に単純rollback不可 |
|
||||
| ROUTING | TLS/Host/接続先を更新しread/write確認 | 新primaryは一つのままrouting修復 |
|
||||
| COMPLETED | sourceの降格、監査、Inbox、保持世代を記録 | 重複完了は冪等 |
|
||||
|
||||
planned switchoverの損失許容は常に0。最終cutのDBだけでなくCAS・可変正本・失効・outboxも
|
||||
targetに適用済みでなければSEALEDを超えない。「遅延がほぼ0」「同期率100%表示」だけでは不可。
|
||||
grantを移す瞬間はwriterが一時的に0になってよいが、2になってはいけない。
|
||||
|
||||
fence証拠はkind、provider、対象node/boot、対象resource、操作ID、確認時刻、結果、
|
||||
再起動/再接続を阻止する方法を含める。接続不能やSIGTERM送信済みだけではconfirmedにならない。
|
||||
初段の自動認定は全旧writerを確実に隔離できる外部providerだけ。保存側fencing契約が後で
|
||||
認定されれば、影響範囲を小さくするprofileとして追加できる。
|
||||
|
||||
**fenceで認定する範囲:** HTTP/LB経路を閉じただけではローカルjob/CLIの書込を止められない。
|
||||
プロセス停止なら全writerと再起動経路、電源断なら同居group、保存資格情報の失効なら対象となる
|
||||
すべての正本backendを対象にする。remote backendへ既に送った可変正本更新が遅れて完了する
|
||||
可能性も評価する。認定された保存側世代拒否、drain確認、または明確な処理終了証明がなく、
|
||||
旧更新が後から確定し得るprofileでは新grantを出さない。単にtimeoutを待ったことは終了証明ではない。
|
||||
メール等の既送信副作用はfenceで取り消せないため、outboxの曖昧結果は別途照合・承認対象にする。
|
||||
|
||||
## 8. 障害時昇格と許可喪失
|
||||
|
||||
障害時はprobe失敗でsuspect表示→authority照合→fence確認→最後の検証済み世代と損失評価→
|
||||
新grant、という順。旧primaryと最終cutを交渉できないため、計画切替と同じ0損失を仮定しない。
|
||||
RPO内というだけでは、成功応答済みの更新が失われない証拠にならない。
|
||||
|
||||
DR-D1の既定は未知損失/未複製変更があればoperator承認必須。自動failoverは保存profileが
|
||||
`acknowledged_writes_durable_on_replica` を提供し、authorityがその確定境界を照合できる場合に限る。
|
||||
現在の非同期snapshot profileはこの能力を持たないので、自動preemptは将来可能でも、
|
||||
無人・無損失failoverまで実装済みとはしない。許容損失による自動昇格profileは本版では提供しない。
|
||||
|
||||
短期permitの初期候補はTTL30秒、更新5秒、local safety margin10秒、更新RPC期限2秒。
|
||||
有効期限を受信時刻だけから延長せず、要求開始のmonotonic時刻と署名された有効期間から
|
||||
保守的なlocal deadlineを計算する。遅れた応答、clock異常、別boot、別epochは破棄する。
|
||||
許可喪失でwriter gateを閉じるが、プロセス停止/遅延commitの安全性はそれだけに依存せず、
|
||||
次holderにgrantする前の外部fenceで保証する。TTLが経過しただけの自動grantは禁止。
|
||||
|
||||
旧nodeが復帰しても、既存許可をdiskから復活させない。nonce付きprobeと新bootに束縛した
|
||||
fresh permitが必要。authority自身が復元され旧recordしかない場合は全体をblockedにする。
|
||||
|
||||
## 9. cancellation、監査、rollback
|
||||
|
||||
operationは長時間処理なので202を返し、通常event/queue画面には参照を出す。
|
||||
authorityのphase更新は通常キューの「再試行」ボタンで巻き戻さない。
|
||||
同じ操作を複数executorが拾ってもCAS phase+idempotency key+fence providerの操作IDで重複を抑える。
|
||||
外部副作用のexactly-onceを無条件に約束せず、曖昧な送信結果は照合またはoperator確認にする。
|
||||
|
||||
REVOKINGより前は、現grantが旧holderに有効と確認できる場合にだけcancelして復帰できる。
|
||||
REVOKING以降の失敗は新しい復旧operationと新epochで処理する。以前の設定ファイルに戻すだけの
|
||||
rollback、epoch減少、旧writerの再起動、受理checkpoint削除は禁止。
|
||||
|
||||
監査はactor、group/bundle、plan hash、old/new node/boot、各epoch、checkpoint、損失承認、
|
||||
fence証跡参照、phase、結果、request IDを残す。書き換え可能な業務snapshot内だけを監査の
|
||||
保全先にしない。probe全件は短期集約し、状態変化と操作の証跡は長期保存する。
|
||||
|
||||
## 10. 不変条件
|
||||
|
||||
- N1:同じwriter resourceに二つの有効holderを同時に作らない。
|
||||
- N2:probe、priority、preempt設定、watch通知は単独でwriterを開けない。
|
||||
- N3:新epochで古い管理内容/権限を無条件に正当化しない。
|
||||
- N4:未検証・不完全なgenerationへactive pointerを向けない。
|
||||
- N5:旧primaryの未同期変更を保全せずに削除・上書きしない。
|
||||
- N6:通常DBのrestorationでnode trust/authorityの単調性を巻き戻さない。
|
||||
- N7:すべてのwrite経路と背景処理がgate/隔離の範囲内にある。
|
||||
- N8:control切替とdata切替を区別し、共有resourceの場合だけ明示的に連動する。
|
||||
- N9:grant移譲後の失敗を旧epoch復活で回避しない。
|
||||
- N10:不足能力・到達不能・曖昧な副作用はfail closedにし、成功と表示しない。
|
||||
@@ -0,0 +1,147 @@
|
||||
# Dregarnuhr:イベント実行基盤
|
||||
|
||||
2026-11-01。初期分離を実装。公開API・永続データ形式は変更しない。
|
||||
名称と全体の移行順序は [コンポーネント命名と責務](component-names.md)、
|
||||
イベント仕様は [Event Scheduler](../event-scheduler.md) を参照。
|
||||
|
||||
## 目的と今回の境界
|
||||
|
||||
Dregarnuhr は「いつ、何件を実行し、失敗後にいつ再試行するか」を担当する。
|
||||
カレンダー同期、通知配送、City再構成、プレビュー生成の内容は担当しない。
|
||||
神名の導入に合わせ、従来の `server` にあった実行ループと制御を
|
||||
`internal/dregarnuhr` に分離した。別サービスや別コンテナにはしない。
|
||||
|
||||
| 層 | 責務 | 主な実装 |
|
||||
| --- | --- | --- |
|
||||
| 汎用実行基盤 | 時刻、定期フック、実行枠、ハンドラー呼出し、完了判定、再試行計算 | `internal/dregarnuhr` |
|
||||
| アプリケーション | 14種類の既存イベント登録、業務payload、監視・設定との接続 | `internal/server/event_handlers.go`、`dregarnuhr_queue.go` |
|
||||
| 永続化 | 優先順位付きatomic claim、実行状態、イベント定義、ログ・保持設定 | `internal/store/event_jobs.go` |
|
||||
|
||||
依存方向は server/store → dregarnuhr。Dregarnuhr は server、store、DB、
|
||||
ネットワーク、ファイルI/Oを直接参照しない。パッケージ境界をテストで固定する。
|
||||
SQLのスケジュール定義評価や投入時の重複排除は、今回の分離ではstoreに残す。
|
||||
|
||||
## 契約
|
||||
|
||||
- `Clock` / `Timer`:現在時刻とタイマーを注入する。テストは仮想時間を進め、実時間の待機に依存しない。
|
||||
- `Loop`:定期dispatch、初回のみの処理、繰り返し処理、外部wakeをまとめる。
|
||||
遅延したtickはまとめて処理し、取り戻すために何千回も連続実行しない。
|
||||
- `Registry`:イベント型から `Handler(context.Context, *Job)` を引く。
|
||||
空名、nilハンドラー、重複登録は拒否。未登録型は既存同様エラーになる。
|
||||
- `Queue`:設定読込、atomic claim、キャンセル状態確認、開始ログ、完了保存のアダプター契約。
|
||||
`ErrNoJob` は正常な空キューを表す。既存storeの `sql.ErrNoRows` はアダプターで変換する。
|
||||
- `Runner`:実行枠の確認からclaimまでを同一runner内で直列化し、ハンドラーをgoroutineで実行する。
|
||||
1回のdispatchは最大32件。完了で枠を解放し、次のdispatchをwakeする。
|
||||
- `Complete` / `RetryDelay`:DBを触らず完了状態と再試行時刻を算出する。
|
||||
`store.EventJob` / `QueueSettings` / `ErrEventSkipped` は互換aliasを維持する。
|
||||
|
||||
既存のHTTPエンドポイント、JSONフィールド、イベント型・ID・キー、consumerのcheckpoint、
|
||||
DBスキーマ、UI表示名は変更しない。実行ログには `component=dregarnuhr` を付ける。
|
||||
payloadを新たにログへ出力しない。業務エラー本文の安全性は引き続き各ハンドラーで担保する。
|
||||
|
||||
## 維持する実行規則
|
||||
|
||||
優先順位は `priority DESC, run_at_ms, created_at_ms, uuid`。
|
||||
SQLiteの単一 `UPDATE ... RETURNING` で選択とclaimを行い、同じジョブの二重claimを防ぐ。
|
||||
同一プロセスの実行上限はキュー設定に従う。foregroundリクエストがある間は、
|
||||
既存ジョブを強制終了せず、実行中が0件の場合に限り1件を開始できる。
|
||||
これにより長時間の編集接続があってもバックグラウンドを完全停止させない。
|
||||
|
||||
| フック | 間隔 |
|
||||
| --- | --- |
|
||||
| 定義評価・dispatch | 1秒、またはwake時 |
|
||||
| 初回プレビュー走査 | 起動後5秒 |
|
||||
| 定期プレビュー走査 | 15分 |
|
||||
| 履歴整理 | 1時間 |
|
||||
| 承認期限・City変更の走査 | 10秒、またはwake時 |
|
||||
|
||||
遅延後の定期フックは実行時刻から次の間隔を数える。厳密な壁時計への位相固定や
|
||||
取り逃した回数分のcatch-upは行わない。業務イベント定義のスケジュール方式は変更しない。
|
||||
|
||||
成功は `succeeded`、適用対象外は `skipped`、キャンセル要求を伴う失敗は `cancelled`。
|
||||
その他の失敗は上限前なら `queued`、上限到達なら `failed`。
|
||||
再試行は基準秒数 × 2^(試行回数−1)、上限24時間。
|
||||
例えば基準30秒なら最初の失敗後30秒、次は60秒となる。
|
||||
|
||||
## 同時に是正した点
|
||||
|
||||
1. 複数呼出しが同時に空き枠を確認して上限を超える競合を、runnerのadmissionロックで防ぐ。
|
||||
2. 再試行秒数・試行回数が極端に大きくても、durationのオーバーフロー前に24時間へ飽和させる。
|
||||
従来の通常設定での待ち時間は同じだが、初回から24時間を超える基準値も上限対象となる。
|
||||
3. 業務ハンドラーのpanicを失敗として記録・再試行対象にする。panicの内容自体は記録しない。
|
||||
4. キャンセル状態のDB読込失敗を「キャンセルなし」と扱わない。業務処理を止め、失敗経路へ送る。
|
||||
5. worker contextが取り消されても、独立した5秒contextで完了保存を試みる。
|
||||
保存失敗はログへ出す。旧式の設定用DB呼出しにはcontext未対応部分が残るため、
|
||||
保存処理全体の厳密な5秒上限を保証するものではない。
|
||||
|
||||
## v0.2.0後の優先修正:ログ保存競合
|
||||
|
||||
2026-11-01、ソース実装・合成データ検証。本番未反映。基点は `0f686aa`。
|
||||
v0.2.0本番観察で開始ログ保存のSQLITE_BUSY_SNAPSHOT(517)が発生したため、
|
||||
読取transactionをwriterへ昇格させる `AddEventLog` を修正した。
|
||||
|
||||
- `AddEventLogContext` は専用接続の `BEGIN IMMEDIATE` で書込権を先に取得し、
|
||||
イベント型/保持policyの読取、rawログ、集約bucketを同じtransaction内で扱う。
|
||||
DBスキーマ・公開API・ジョブの実行規則は変更しない。
|
||||
- 予算は最大2秒、呼出し元に短い期限があればそちらを優先する。
|
||||
接続取得後のSQLite busy待機を50msに限定し、BEGINのBUSYだけを10〜80ms間隔で再試行する。
|
||||
書込開始後やCOMMIT応答不明時の再送はしない。これにより内部retryの二重集計を避ける。
|
||||
OS/接続初期化/ドライバの停止までを含む厳密な実時間保証ではない。
|
||||
- 取消時も独立した最大1秒のcleanupでROLLBACKと接続のbusy_timeout復元を試みる。
|
||||
transaction状態や待機設定を確定できない接続はpoolへ戻さない。
|
||||
- 通常のイベント型取得はJob UUIDの主キー検索。履歴全走査やOR条件のsortを
|
||||
writer lock内で行わない。Job不在かつEvent UUID指定時のみ従来のfallbackを使う。
|
||||
空のEvent UUIDで無関係なジョブを拾わない。DB読取エラーを既定policyで隠さない。
|
||||
- rawログとbucketの途中失敗は両方rollback。ログ保存が成功した場合のみ両方を確定する。
|
||||
これはログ呼出し間のexactly-once保証ではなく、単一呼出し内の原子性である。
|
||||
- 完了状態を保存後にログだけ失敗した場合は `ErrEventCompletionLog` を返す。
|
||||
server adapterは `finish-log failed` として報告し、完了状態を失敗へ変えたり
|
||||
成功した業務処理を再実行したりしない。開始/進捗の失敗も別stageで報告する。
|
||||
- ログ保存失敗の診断はcomponent、Job UUID、イベント型、エラー分類/SQLite codeだけ。
|
||||
ドライバの生メッセージ、SQL、進捗本文、payload、認証情報はcomposeログへ転載しない。
|
||||
|
||||
受入試験は独立8接続の320件ログと別writer、原子rollback、取消後の再利用・待機設定復元、
|
||||
readonly、空ID誤分類、policy読取失敗、主キー利用、完了/retry状態の維持、
|
||||
開始・進捗・完了の失敗診断と秘密の非露出を対象とする。
|
||||
|
||||
全Goテスト(`go test ./... -count=1`)、全Go vet、関連store/server試験のrace検査
|
||||
(3回)が成功。通常の関連store試験は20回反復して確認した。
|
||||
テストは一時DBと合成ジョブのみ。本番DB・外部カレンダー・実通知先は使用しない。
|
||||
|
||||
長時間ロックで保存できなかったログの自動回収、完了状態とログ自体の一体commit、
|
||||
event-only fallback検索や保持処理の最適化は後続。v0.2.0タグは変更せず、
|
||||
本番反映時は新しいPATCH版として別途検証・公開する。
|
||||
|
||||
## 未実装:リース・HA・終了処理
|
||||
|
||||
**atomic claimは期限付きリースではない。現時点は単一writerプロセスの運用を前提とする。**
|
||||
別プロセス同士の同時実行数は共有されず、定期定義の投入もHA対応ではない。
|
||||
完了UPDATEはUUIDで対象を指定しており、旧workerの遅延完了を防ぐfencingはない。
|
||||
既存の起動時復旧は `running` を再投入するため、他のwriterが生きている状態では実行してはならない。
|
||||
exactly-onceの配送・実行は保証しない。外部副作用の冪等性は業務ハンドラー側の責務となる。
|
||||
|
||||
- [ ] owner、attempt/claim token、lease expiry、heartbeatを永続化する。
|
||||
- [ ] 完了・キャンセル更新で所有権とattemptを比較するfencingを導入する。
|
||||
- [ ] 期限切れ回収と定期投入を複数プロセスから安全に実行し、全体の実行上限を定義する。
|
||||
- [ ] 成功後・完了保存前の障害、lease更新停止、旧workerの遅延完了を障害注入試験する。
|
||||
- [ ] アプリケーションの停止contextをschedulerに接続し、受付停止・実行中処理のdrain・期限付き終了を実装する。
|
||||
- [ ] 各業務ハンドラーへcontextを伝播する。現状は独自のBackground/timeoutを使う処理も残る。
|
||||
- [x] 開始/進捗/完了ログのcontext伝播、有界writer取得、ログ保存失敗の診断(ソース実装。本番未反映)。
|
||||
- [ ] 古い設定DB呼出しをcontext対応にする。完了保存失敗・欠落ログの回収方針も定義する。
|
||||
|
||||
コアのLoop/Runnerはキャンセルを受け付けるが、現行アプリケーションは従来どおり
|
||||
Background contextで起動する。これをgraceful shutdown対応済みとは扱わない。
|
||||
これらはDB migrationとDR/authority設計を伴う後続作業であり、命名・初期分離に混在させない。
|
||||
|
||||
## 検証方針
|
||||
|
||||
本番DB、外部カレンダーの内容、実際の通知配送先には触れず、一時DB・合成ハンドラーで検証する。
|
||||
|
||||
- fake clock:初回・定期・wake、長時間遅延、閉じたwake channel、キャンセルとtimer解放。
|
||||
- race detector:並行dispatch、foreground制限、registryの排他、実行カウンター。
|
||||
- 一時DB:優先順・独立DB接続でのclaim、時刻境界、試行回数、30秒/60秒retry、各終了状態。
|
||||
- server接続:14ハンドラーの登録、実行間隔、永続状態と監視counter、read-only/ジョブ無効化の抑止。
|
||||
- 全Go回帰テスト・静的検査。既存API・業務イベントのテストも併用する。
|
||||
|
||||
実行結果は [命名文書の検証記録](component-names.md#検証記録) に追記する。
|
||||
ソース変更・テスト・commit・CI・本番展開は別段階として記録する。
|
||||
@@ -0,0 +1,117 @@
|
||||
# エディタ改善サブプロジェクト
|
||||
|
||||
状態:E1–E5 の初期実装と回帰検証完了。E6 は未実装・後続ゲート。
|
||||
既存 HTML 正本・不変 Revision・Page UUID・言語別 head を維持する。
|
||||
本書は `html-editor.md` の挿入パーツ設計を含むエディタ横断の実行計画。
|
||||
|
||||
2026-11-01:文書変換と情報保全の実装を `internal/grammaratur` へ分離。
|
||||
通常変換・保護変換の契約と既存APIは維持する。
|
||||
[コンポーネント命名と責務](component-names.md) に移行境界を定義する。
|
||||
|
||||
## 優先順位と完了条件
|
||||
|
||||
1. **E1 編集内容の保全**:端末内下書き、認証切れ/通信断/権限失効の区別、
|
||||
再認証後の明示的な保存再開、保存完了を待つ `:wq`、二重保存防止。
|
||||
2. **E2 保存競合**:言語別 head を DB トランザクション内で比較する CAS。
|
||||
同一箇所を変更していないと確定できる範囲だけ自動マージし、その他は
|
||||
基点/自分/最新の内容を表示して手動調整。相手の編集を無条件に上書きしない。
|
||||
3. **E3 操作改善**:モバイルで Vim を使わない、macro 補完時の終端重複を防ぐ、
|
||||
HTML/Markdown の切替で未保存データを捨てない、少数の挿入コンポーネント。
|
||||
4. **E4 履歴・言語**:旧 Revision を作業バッファに読み込み、確認保存で新 Revision。
|
||||
BCP 47 の明示言語は暗黙に `und` へフォールバックして上書きしない。
|
||||
翻訳は同じ Page UUID の別言語として分岐し、URL Path を別 Page にしない。
|
||||
5. **E5 変換保全**:HTML→Markdown→HTML の構造比較。不一致なら HTML を
|
||||
`{=html}` 保護フェンス内に保持する。projection 展開結果を正本や下書きへ保存しない。
|
||||
6. **E6 共同編集(後続)**:サーバーをまたぐ presence、選択範囲、CRDT/OT、
|
||||
編集セッションと永続化境界。単なる同時保存やポーリングを共同編集と呼ばない。
|
||||
|
||||
## 保存と下書きの契約
|
||||
|
||||
- 正本の保存単位は Page UUID × canonical language。開始 head(空も有効)を
|
||||
`base_revision_uuid` で渡す。比較と Revision 追加は同一 write transaction。
|
||||
- 旧クライアントの base 未指定は移行互換として残す。UI は必ず base を指定する。
|
||||
全入口の必須化・hosted editor/CLI 追従は後続ゲート。
|
||||
- 401 は再ログイン、403 は権限の再確認。変換 API の失敗時には Markdown を
|
||||
HTML として保存しない。リダイレクト/非 JSON のログイン応答も成功にしない。
|
||||
- 保存要求中の編集は別の dirty 状態として保持する。保存成功したスナップショット
|
||||
と現在内容が一致するときだけ下書きを削除する。応答喪失時は head 比較で回復する。
|
||||
- 下書きは origin・Domain・Principal・Page・language 単位。別ユーザーの下書きを
|
||||
自動表示しない。サーバー同期はしない。端末を共有する場合の平文保存リスクを明記。
|
||||
- 端末ストレージは容量制限・拒否・プライベートモード・ブラウザー終了で失われ得る。
|
||||
保存失敗を明示し、テキストのダウンロード導線を用意する。下書きには保存時刻、
|
||||
形式、基点 Revision と基点内容を保持し、期限とサイズの上限を設ける。
|
||||
- 復旧候補がある場合は無条件に server autosave しない。復元/破棄をユーザーが選ぶ。
|
||||
再接続だけで公開 Revision を自動更新しない。
|
||||
|
||||
## 初期実装の API・UI と制限
|
||||
|
||||
- `POST /_/api/v1/revisions/save`:任意の `base_revision_uuid` を追加。
|
||||
このエディタは常に指定し、409 を競合として処理する。`editor_principal_uuid` も照合し、
|
||||
編集中に別アカウントへ切り替わった状態で保存しない。旧クライアントの無条件保存は残る。
|
||||
- `GET /_/api/v1/editor/state?uuid=…&lang=…`:対象 Domain・Page の読取権限を検証。
|
||||
`metadata=1` は本文ファイルを読み込まず head を取得。`revision=…` は対象 Page の
|
||||
過去本文を取得する。非表示タブでのポーリングは停止し、表示時は30秒間隔。
|
||||
**これは保存済みの別更新検出であり、未保存の同時編集者 presence ではない。**
|
||||
- `POST /_/api/v1/editor/convert`:作業中 HTML を安全な authoring Markdown に変換。
|
||||
`POST /_/api/v1/render/markdown` の `authoring:true` で保護フェンスを元の HTML に戻す。
|
||||
`projection:true` と併用したプレビューでは従来の sanitizer・macro 展開を適用する。
|
||||
- 変換できない HTML は文書全体を保護する保守的な実装。フェンスは
|
||||
`` ```{=html} `` 形式(本文にバッククォートがある場合はそれより長い区切り)。
|
||||
任意の属性、コメント、未知要素、表の結合、画像キャプション、コード内空白を保持。
|
||||
フェンス内を編集でき、外側に Markdown を追記できる。通常のコードフェンス内にある
|
||||
`{=html}` サンプルは HTML として実行しない。保全は実行許可を与えるものではない。
|
||||
- 自動マージは各版を1つの変更範囲として比較する保守的方式。重複・隣接・同一挿入点は
|
||||
手動確認へ回す。自動再保存は3回まで再照合し、それ以上は確認画面へ移行。
|
||||
ファイル形式が変わった場合は自動マージせず退避と再読込を案内する。
|
||||
- 下書きは `localStorage`。UTF-8 JSON 全体で2 MiBまで、復元対象は7日以内。
|
||||
起動時に期限切れを削除するため、ブラウザーを開かない期間の物理削除は保証しない。
|
||||
Domain/Principal/Page/language/tab ごとに分離し、他タブの下書きを一括削除しない。
|
||||
IndexedDB・サーバー同期・暗号化は未実装。保存失敗時はダウンロードを案内する。
|
||||
- `+` は挿入・下書き、`文` は言語の編集・分岐、`↶` は旧リビジョンを作業バッファへ
|
||||
読み込む。復元は明示保存で新 Revision を追加し、旧 Revision を書き換えない。
|
||||
履歴は50件ずつ追加取得し、現在言語で絞り込む。分岐は翻訳生成ではなく本文のコピー。
|
||||
- 挿入は子ページ・表・画像キャプション・補足・コード・引用の6種の初期パレット。
|
||||
画像 URL 等のプレースホルダーは編集が必要。ファイルピッカー、図形・外部 widget の
|
||||
パラメータ編集、プラグインによる挿入パーツ登録は既存の HTML editor 設計に残る。
|
||||
- touch/coarse pointer + hover 不可の端末ではデスクトップの Vim 設定を上書きせず、
|
||||
当該編集セッションだけ通常入力にする。実機 iOS/Android の IME は別途受入試験。
|
||||
|
||||
## 次段階の実装順序
|
||||
|
||||
1. **E6a presence**:編集中リースの共有ストアと認可付き API、別端末を含む表示。
|
||||
管理者にだけ見える監視ではなく、同じ Page/language を編集できる参加者に限定する。
|
||||
2. **E6b realtime**:下記 CRDT 詳細設計・採用ライブラリ・同時変換ルールを確定した後に
|
||||
feature flag 付きで実装。現時点の CAS を最終コミット時の保護として残す。
|
||||
3. **E5b / E3b**:HTML ブロック単位の保護、hosted editor/CLI への保護フェンス対応、
|
||||
アセットピッカーと拡張挿入パーツ。通常の Markdown だけを扱う外部エディタへ
|
||||
このフェンスを無断で渡さない。既存の外部エディタ変換経路は本変更の対象外。
|
||||
4. 保存 API の旧クライアント移行と base 必須化、下書き大容量化・明示破棄 UX、
|
||||
共有端末ポリシー、モバイル実機テスト。
|
||||
|
||||
## 共同編集の詳細設計 TODO
|
||||
|
||||
- presence キーは Domain × Page UUID × language × Principal × tab session。
|
||||
TTL 付きリース、退出、バックグラウンド抑制、権限失効時の購読停止を定義。
|
||||
- API は `/_/api/v1/editor/` 配下に置く。WebSocket/SSE は origin・認証・対象 Page の
|
||||
read/write を接続時と継続時に検証。本文や利用者名を未認可者へ漏らさない。
|
||||
- 本文 CRDT は authoring source(HTML/Markdown の混在規則と基点を含む)を同期し、
|
||||
projection HTML を同期しない。言語・形式の不一致を同一 room に混在させない。
|
||||
- SQLite に毎キー入力を記録しない。スナップショット間隔・増分上限・圧縮・GC・
|
||||
HA 配信基盤と Revision commit 境界を定義。offline 分岐復帰・undo と IME を検証。
|
||||
- Yjs/Automerge 等は権限、再接続、肥大化、ライセンス、bundle サイズを比較する。
|
||||
この選択とサーバー共有状態を未設計のまま本番へ有効化しない。
|
||||
|
||||
## 検証・展開ゲート
|
||||
|
||||
テスト用 DB と合成文書だけを用いる。実データ・外部カレンダーにはアクセスしない。
|
||||
保存 CAS、空 head、言語分離、旧 Revision 復元、認証失効、別 Principal、通信断、
|
||||
変換失敗、保存中の追記、再試行、複数タブ、モバイル、IME、macro 終端、未知 HTML の
|
||||
round-trip を検証する。CRDT と複数インスタンス presence は別途負荷・安全性試験。
|
||||
本番反映・リリース採番は実装検証の後に行い、既存リリースタグは変更しない。
|
||||
|
||||
初期回帰試験:`TestEditorRevisionCAS`、`TestEditorResilienceAPI`、
|
||||
`TestAuthoringRoundTrip` / `TestAuthoringProtectedHTML`、`assets/editor/editor-core.test.mjs`。
|
||||
実ブラウザーは `PAGESWIKI_BROWSER_TEST=1` で `TestEditorResilienceChromium` と
|
||||
`TestHTMLProjectionChromium`。通信断、401、応答喪失、競合 UI、自動マージ、保存中の追記、
|
||||
変換失敗、下書き復元、旧版復元、言語分岐、マクロ補完、モバイル判定、テーマ、
|
||||
authoring/projection の分離を合成データで検証する。
|
||||
@@ -0,0 +1,96 @@
|
||||
# Geduldh の文書保存契約
|
||||
|
||||
2026-11-01、ローカルDocument Storeと一時展開の初期分離を実装。
|
||||
GeduldhはSHA-256で識別する不変の文書バイト列を保存・取得・検証する。
|
||||
従来の `internal/documentstore` の実装を移し、保存形式、DBスキーマ、公開URLは変えない。
|
||||
名称の位置付けは [コンポーネント命名と責務](component-names.md)、
|
||||
外部ストレージと運用の計画は [保存基盤の多様化](../storage-portability-and-operations.md) を参照。
|
||||
|
||||
## 実装と責務
|
||||
|
||||
| 層 | 所有するもの | 所有しないもの |
|
||||
| --- | --- | --- |
|
||||
| `internal/geduldh` | Store契約、ローカルpayload、保存キー、サイズ・hash検証、容量制限付き一時展開 | SQL、認証・認可、Page/Revision、GCの削除判断 |
|
||||
| `internal/documentstore` | 旧公開型のalias、旧コンストラクター・Keyの委譲 | 独自の保存実装・検証ロジック |
|
||||
| `internal/store` | Revisionと参照のtransaction、DB-only互換、バックフィルのidentity・checkpoint、read-only運用 | 別実装のローカルpayload writer |
|
||||
| server / DR / CLI | 認可後の配信、外部ツール、保全・復元の手順 | hashを知っていることによる認可の省略 |
|
||||
|
||||
アプリケーションと旧入口からGeduldhへの一方向依存とする。Geduldhからstore、DB、
|
||||
server、旧documentstoreへ戻る参照は作らない。HTTPレスポンスや権限判定も持たせない。
|
||||
`Component = "geduldh"` は内部の固定識別名であり、保存ディレクトリやサービス名ではない。
|
||||
|
||||
## 保存と取得の契約
|
||||
|
||||
`geduldh.Store` は既存の `documentstore.Store` と同じ型として扱える。
|
||||
|
||||
| 操作 | 契約 |
|
||||
| --- | --- |
|
||||
| `Stat(ctx, hash)` | 正規化したhashとバイト数を返す。内容全体の検証ではない |
|
||||
| `Open(ctx, hash)` | `Read`、`ReadAt`、`Seek`、`Close` に対応するReaderを返す。全体を先読みしない |
|
||||
| `PutIfAbsent(ctx, hash, size, reader)` | サイズとSHA-256を検証し、完全なpayloadだけを上書きせず公開する |
|
||||
| `Verify(ctx, hash)` | ストリーム全体を読み、SHA-256の一致を検証する |
|
||||
|
||||
通常の `Open` / `Stat` は全体をhash検証しない。Range配信やZIPの部分読み取りで
|
||||
ファイル全体の走査を強制しないためである。検証が必要な経路は `Verify` または検証付き
|
||||
Materializerを選ぶ。既存のRevision本文取得時のhash検査はstore側に残る。
|
||||
|
||||
保存キーは `sha256/<hashの先頭2文字>/<64桁hash>`、ルートは既存の `documents`。
|
||||
hashの前後空白の除去・小文字化、既存エラーの同一性を維持する。Path、ファイル名、
|
||||
Domain、言語、Revision UUIDは保存キーに混ぜない。配置の変更で公開URLやETagを変えない。
|
||||
|
||||
ローカル保存はルート内アクセス、64 KiB単位の検証コピー、一時ファイル、ファイルfsync、
|
||||
hardlinkによるno-replace公開、ディレクトリfsyncを維持する。
|
||||
既存payloadは再検証し、破損していても入力で上書き修復しない。
|
||||
`NewLocal` は保存先を作成しない。ルートの準備とバックフィルは起動・運用側の責務とする。
|
||||
|
||||
書込みではpayloadの永続化を先に完了し、その参照を持つRevisionのDB transactionを
|
||||
後で確定する。DB側の競合・rollbackで未参照payloadが残ることは許容する。
|
||||
Geduldhは参照数を判断せず、`Store` にDeleteを設けない。GCは保持・参照・backup pinを
|
||||
判断する別の経路とし、今回の分離では変更しない。
|
||||
|
||||
## 外部ツール用の一時コピー
|
||||
|
||||
`Materializer.Acquire` は同じhashの取得を共有し、検証済みのノードローカルコピーを
|
||||
`Lease` で返す。ここでのleaseは一時ファイルの利用権であり、分散ジョブの期限付きリースではない。
|
||||
最後の利用者がCloseするとコピーを削除する。正本のhardlinkを外部ツールへ渡さない。
|
||||
一人の待機中断で他の利用者を巻き込まず、全員が中断した場合は取得を取り消す。
|
||||
|
||||
既存アプリケーションの上限を維持する:同時取得2件、待機・利用中を含め64件、
|
||||
予約容量合計2 GiB、共有取得期限2分。呼出し側のファイル単位上限とcontextも適用する。
|
||||
一時ディレクトリは0700、コピーは0400。削除失敗時には予約容量を解放済みと扱わない。
|
||||
これらはアクセス元アプリケーションの設定であり、外部ストレージ対応の宣言ではない。
|
||||
|
||||
## 互換性と今回の変更範囲
|
||||
|
||||
- 旧documentstoreの型・エラーはalias、関数はGeduldhへの委譲とし、実装を二重に持たない。
|
||||
- storeの保存、読み取り、サイズ・部分取得、一時展開はGeduldhへ接続する。
|
||||
- `.document-store-id`、バックフィルのUUID cursor、DB-only互換、起動時移行は変更しない。
|
||||
- DR manifest、スナップショットの構造、復元手順、保存済みデータは変更しない。
|
||||
- UI、URI、設定キー、イメージ名、イベント型、consumer checkpointは変更しない。
|
||||
|
||||
これは既存の保存実装の分離であり、新たなファイル移行・DB migrationを必要としない。
|
||||
任意のmount先での永続性、外部backend、マルチノードHAを追加するものではない。
|
||||
|
||||
## 残件
|
||||
|
||||
- [ ] S3 / SFTPなどのbackendを、条件付き作成・部分取得・破損・切断の共通契約試験を経て追加する。
|
||||
- [ ] NFS / SMB / SSHFSはno-replace公開・fsync・mount喪失の実環境試験を行う。ローカルパスであるだけで対応済みとしない。
|
||||
- [ ] 旧Revision保存・本文取得を含む全経路へcontextを伝播する。
|
||||
- [ ] payload、可変正本、秘密情報、scratchの配置設定を分離する。
|
||||
- [ ] 一時展開の上限を設定化し、削除失敗・クラッシュ残骸の安全な回収とメトリクスを追加する。
|
||||
- [ ] Documentのサイズをメタデータ化し、外部backend導入時の一覧のStat/HEAD多発を防ぐ。
|
||||
- [ ] GCの参照snapshot・保持・backup pinと、外部ストレージの削除契約を整備する。
|
||||
|
||||
## 検証
|
||||
|
||||
合成payloadと一時DB・ディレクトリで、次を検証する。
|
||||
|
||||
- 移動前レイアウトの読み取り、新旧入口の型・エラー・キー互換、既存inodeの保持。
|
||||
- 並行書込み、不完全入力・既存破損の拒否、キャンセル、ルート外へのsymlink逸脱防止。
|
||||
- Range / ReaderAtと逐次読み取りの独立性、ZIP配信、認可を伴う不変オブジェクト配信。
|
||||
- 一時コピーの共有、容量・件数・時間制限、最終Closeでの削除、正本からの分離。
|
||||
- 永続化失敗時のRevision非確定、metadata競合時の正本保全、バックフィルの再開。
|
||||
- Geduldhで保存 → 既存DR snapshot → verify → restore → Geduldhで検証・読取り。
|
||||
|
||||
実行結果は [コンポーネントの検証記録](component-names.md#検証記録) に記載する。
|
||||
本番データの操作、commit・push・本番展開はこの初期分離には含めない。
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
状態:設計案。全面WYSIWYG採用は未決定。既存エディタを置換しない段階的改善を第一案とします。
|
||||
|
||||
2026-09-27 追記:[エディタ改善サブプロジェクト](editor-resilience.md) で
|
||||
端末下書き・CAS 保存・競合確認・言語分岐・旧版復元・HTML 保護ブロックと
|
||||
6種の初期挿入パレットを実装。以下の型付きパーツ schema、画像ピッカー、
|
||||
限定 block 視覚編集、リアルタイム共同編集は引き続き後続段階です。
|
||||
|
||||
## 解決したい問題
|
||||
|
||||
表、画像とcaption、引用、注意書き、コード、リンク、macro、埋め込みを毎回手書きする負荷を減らします。単にHTMLを隠すことより、既存文書を壊さず効率よく編集できることを重視します。
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# Kunstzeal の表示方式と描画プロバイダー契約
|
||||
|
||||
2026-11-01、既存の表示方式の選択とKroki図描画を `internal/kunstzeal` に初期分離した。
|
||||
Kunstzealは描画エンジンを自作する部品ではなく、表示方式と外部描画の呼出し契約をまとめる。
|
||||
Page/Revisionの正本、認可、HTMLの信頼境界は引き続きアプリケーションが所有する。
|
||||
スライド、nwdiag、新しい描画サービスの追加は今回含めない。
|
||||
[コンポーネント命名](component-names.md) と [表示アダプタ設計](../projection-adapters.md) を併読する。
|
||||
|
||||
## 責務と依存方向
|
||||
|
||||
| 部品 | 責務 |
|
||||
| --- | --- |
|
||||
| `kunstzeal.SelectAdapter` | 有効MIME・ファイル名から、既存の優先順で表示方式を選択 |
|
||||
| `kunstzeal.Catalog` | ビルトイン14種類の定義のコピーを返す。呼出し元から共有registryを変更させない |
|
||||
| `DiagramProvider` / `Kroki` | 型・入出力サイズ・時間を制限したSVG描画要求。エラーを一般化 |
|
||||
| 図のhash・cache | 既存hashの計算、有界読込、一時ファイルからの原子的なcache置換 |
|
||||
| server | 対象解決・認可・Domain/Path由来情報・HTTP応答・CSP・Kroki接続設定・hosted plugin管理 |
|
||||
| Grammaratur | HTML/Markdown等の文書形式変換。描画された図を正本へ書き込まない |
|
||||
| Dregarnuhr / 既存preview処理 | PDF・動画等の背景サムネイル生成。今回は移動しない |
|
||||
|
||||
server/compiler → kunstzeal の一方向依存とする。
|
||||
Kunstzealはstore/server/DBへ依存せず、認証CookieやBearer tokenを受け取らない。
|
||||
図cacheのファイルI/Oと設定済みKrokiへのHTTP以外に、新たな実行環境を持たない。
|
||||
任意の実行ファイルやshellを起動する機構ではない。
|
||||
|
||||
## 表示方式の選択と互換性
|
||||
|
||||
順序は `html`、`excalidraw`、`csv`、`archive`、`debian-package`、`eml`、`pe`、
|
||||
`json`、`text`、`image`、`audio`、`video`、`pdf`、`download` を維持する。
|
||||
特殊形式を一般JSON/textより先に選択し、未知の形式はdownloadへ落とす。
|
||||
MIME検出、文字コード変換、各形式のparserとViewer実装自体は今回移動しない。
|
||||
MIMEと拡張子の優先関係も変更しない。
|
||||
|
||||
`Descriptor`・`Adapter`・`Delivery` はserverの旧型をaliasで接続する。
|
||||
ID、Kind、Delivery、NeedsText、WindowableText、2MiBのテキストwindow閾値は同一。
|
||||
`/_/api/v1/adapter` のビルトイン一覧も同じcatalogを参照する。
|
||||
Catalogは複製したsliceを返すため、一覧編集が別要求の選択結果を変えない。
|
||||
|
||||
hosted viewer/editorの設定キー・有効無効・URL検証・起動ticket・保存経路は変更しない。
|
||||
ビルトイン選択registryを任意コードをロードするプラグイン機構へ変更するものではない。
|
||||
Excalidrawの別コンテナ/ブラウザ内描画、PDF、media、archive等の実行環境は従来のまま。
|
||||
|
||||
## Krokiの実行契約
|
||||
|
||||
`DiagramProvider.Render(ctx, kind, source)` はSVGバイト列またはエラーを返す。
|
||||
既存Kroki呼出しはmermaid・plantuml・graphviz・dot・d2のみ許可し、dotはgraphvizへ正規化する。
|
||||
任意のURL・出力形式・エンジン名は文書から指定できない。
|
||||
|
||||
| 項目 | 契約 |
|
||||
| --- | --- |
|
||||
| 図ソースPOST | 最大1MiB。超過時は送信せず413 |
|
||||
| HTML内の図ブロック | 32KiBまで。超過時は元のコードブロックを残す |
|
||||
| 描画要求 | POST、`text/plain; charset=utf-8`、最大15秒。親contextの取消も反映 |
|
||||
| 結果 | 2xxのみ成功、最大4MiB。非2xxの応答本文は利用者へ返さない |
|
||||
| endpoint | 管理者の `KROKI_URL`、空なら既存の `http://kroki:8000`。API入力から選択しない |
|
||||
| client | 呼出し元のHTTP clientが必須。未設定時に既定clientで送信しない |
|
||||
| redirect | serverのclientで全redirectを拒否。301/302/307/308も描画失敗として扱う |
|
||||
| エラー | 設定不備500、描画失敗502。接続先URL・provider本文・元ソースをエラー文へ含めない |
|
||||
|
||||
今回の是正として、endpointにuserinfo・query・fragmentを含む設定は拒否する。
|
||||
内部ComposeサービスへのHTTP接続は既存仕様なので許可する。公開IP限定の一般URL取得とは異なる。
|
||||
既存のHTTP clientによるproxy環境設定の扱いは変えない。接続先は信頼された運用設定として扱う。
|
||||
DNS/IP固定、providerのTLS認証・egress制限、描画サービス自体のファイル/ネットワークアクセス制限は
|
||||
この抽出だけでは提供しない。配置先・ネットワーク隔離と合わせた後続契約とする。
|
||||
|
||||
clientはcontextを尊重する必要がある。コアの時間制限は任意の悪意ある実装を強制停止するsandboxではない。
|
||||
HTTP clientとcoreの両方に時間予算を設けるが、描画サービス側のCPU/RAM使用量は別管理である。
|
||||
|
||||
## Cacheと認可
|
||||
|
||||
hashは従来の `SHA256(kind + NUL + format + NUL + source)` を維持し、
|
||||
`compiler.DiagramHash` とserverの旧入口は共通実装へ委譲する。
|
||||
HTML由来ではsourceの前に既存のHTML projection version・Domain・Pathを組み込み、
|
||||
同じ図でも異なるPathの権限参照を共有しない。POSTの入力そのものをhash化する方式も維持する。
|
||||
|
||||
保存先は既存の `<diagramRoot>/<kind>/<hash>.svg`。DB migrationやcache移行は不要。
|
||||
読込は最大4MiB。書込は同じディレクトリの一時ファイルを完成させてからrenameする。
|
||||
並行読込に途中までのSVGを渡さず、失敗時は一時ファイルを削除する。
|
||||
cacheの保存に失敗しても、正常に描画できた応答は返す。これは再生成可能なcacheであり、
|
||||
fsyncを伴う正本文書の耐障害commitや、同一キーの二重生成抑止ではない。
|
||||
|
||||
GETの認可はcache読込より先に行う。既存のソース由来情報はメモリ上で128件、30分以内。
|
||||
kind・Domain・Pathの現在の読み取り権限を検査し、期限切れ・由来不明・別Domain・権限なしは404。
|
||||
ディスクにSVGが残っていること自体はアクセス権にならない。
|
||||
POSTは既存のdomain read endpoint policyを通り、利用者が送ったソースを描画する別経路である。
|
||||
これを新たな匿名描画APIへ変更しない。
|
||||
|
||||
## SVGの信頼境界
|
||||
|
||||
providerが返すSVGをアプリケーションのHTMLへ直接挿入しない。
|
||||
cache hit、新規描画、直接アクセスでも、従来どおり次を付与する。
|
||||
|
||||
```text
|
||||
Content-Type: image/svg+xml; charset=utf-8
|
||||
Content-Security-Policy: sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:
|
||||
X-Content-Type-Options: nosniff
|
||||
Cache-Control: private, no-store
|
||||
```
|
||||
|
||||
バイト数を制限することとSVGの内容を安全と認定することは異なる。
|
||||
今回SVG sanitizerや完全な構文検証は追加しない。Kunstzealの出力は信頼済みHTMLではなく、
|
||||
上記のsandbox応答で扱う必要がある。HTML本文のsanitizer・macro展開・CSPはserverが引き続き適用する。
|
||||
図の正本ソース、Page/Revision、既存の表示URIは変更しない。
|
||||
|
||||
## 後続TODO
|
||||
|
||||
- [ ] provider ID/version・テーマ・オプションを含む新しいcache keyと、旧cacheからの移行/失効を設計する。
|
||||
- [ ] 同時描画上限、同一キーの実行集約、優先度、キャンセル、Dregarnuhrへの背景生成、過負荷時の安全な再試行表示を整備する。
|
||||
- [ ] provider単位の停止・切戻し・health・CPU/RAM/時間/件数/失敗の観測を統一する。今回hosted pluginの既存設定は維持したが、この統一機構は追加していない。
|
||||
- [ ] ソース由来cacheをプロセスglobalからinstance単位へ整理し、再起動・複数nodeでも認可と失効を保てる取得方式にする。
|
||||
- [ ] ディスクcacheの容量・TTL・清掃、renderer更新時の不整合、障害後の一時ファイル残留を管理する。
|
||||
- [ ] provider宛通信と描画サービス内の外部参照を分け、送信許可・接続先・ネットワーク隔離・バージョン固定を契約化する。
|
||||
- [ ] nwdiagの有界parser・安全なSVG出力・編集preview、Draw.io等のproviderを追加する。現在のregistryにnwdiagは実装されていない。
|
||||
- [ ] Reveal互換・HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
||||
- [ ] Excalidrawのhosted/browser実行とPDF/動画サムネイル・metadata subprocessを、各々の安全境界を維持したまま段階的に接続する。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
合成ソース・一時ディレクトリ・偽HTTP client・localhostの偽Krokiだけで検証する。
|
||||
入力/出力上限、取消、全redirect拒否、エラー情報の非開示、cacheの並行読込/置換、
|
||||
kind/hashとcatalog互換、Domain/Pathの認可、由来情報の期限、CSPを確認する。
|
||||
実Krokiの版ごとの描画品質や本番通信は今回の検証対象ではない。
|
||||
|
||||
実行記録は [コンポーネント検証記録](component-names.md#検証記録) に記載する。
|
||||
本番DB・取り込み済み外部カレンダーへアクセスせず、commit・push・デプロイは別段階とする。
|
||||
@@ -0,0 +1,110 @@
|
||||
# Mestionora の検索と索引契約
|
||||
|
||||
2026-11-01、既存のSQLite検索・検索索引・City検索を `internal/mestionora` へ初期分離した。
|
||||
検索の意味、順位、予算、HTTPレスポンス、索引の形式は維持する。
|
||||
権限ポリシーそのものはアプリケーションが所有し、Mestionoraは渡された読み取り判定を適用する。
|
||||
[コンポーネント命名](component-names.md) と [検索結果の仕様](../search-results.md) を併読する。
|
||||
|
||||
## 所有する処理
|
||||
|
||||
| 部品 | 責務 |
|
||||
| --- | --- |
|
||||
| `mestionora.SQLite` | Pageとファイルの候補抽出、絞り込み、順位付け、認可後の抜粋、H1サジェスト |
|
||||
| City検索 | Domain内のQuartier・Street・Spotのメタデータ照合、祖先を含む認可、表示名・ポータルPathの射影 |
|
||||
| 検索索引の初期化 | FTS5、現行Revisionの投影、既存のINSERT/DELETE trigger、従来のbackfill |
|
||||
| store互換入口 | 従来の関数を委譲し、結果型・検索条件・エラーをaliasで維持 |
|
||||
| server | Domainとscopeの解決、リクエストの権限ポリシー、日付のタイムゾーン変換、HTMLの安全な表示、URL生成 |
|
||||
|
||||
依存方向は server/store → mestionora → database/sql とHTML tokenizer。
|
||||
現段階はSQLite実装であり、ストレージから独立した検索サービスではない。
|
||||
DB接続の作成・所有、認証、認可ルール、Documentの正本保存、外部検索への送信は担当しない。
|
||||
`Component = "mestionora"` は内部識別名であり、公開URLやDB名を変更しない。
|
||||
|
||||
## 呼出し契約と互換性
|
||||
|
||||
`NewSQLite(db)` は接続プールを借用するだけで、I/O・DDL・索引再構成を行わない。
|
||||
`EnsureSearchIndexSchema` は従来の起動経路から明示的に呼ぶ。
|
||||
検索リクエストから初期化・migrationを起動しないため、読み取り専用接続でも検索できる。
|
||||
|
||||
- `SearchPathsInDomainFiltered`:追加のファイル・日付条件を使わない、認可付きキーワード検索。
|
||||
- `SearchPathsInDomainWithOptions`:ファイル種別、拡張子、更新日/作成日を組み合わせたPage検索。
|
||||
- `SearchPathSuggestionsInDomain`:本文抜粋を生成しない候補検索。許可されたHTML結果だけにH1を補う。
|
||||
- `SearchCityInDomain`:Cityのメタデータ検索。全CityMapや配下Pageの展開はしない。
|
||||
|
||||
新入口はすべて `allowed func(path string) bool` を要求する。nilなら結果を返さない。
|
||||
旧 `Store.SearchPathsInDomain` の全許可入口は信頼された既存呼出しとの互換のためにだけ残し、
|
||||
Mestionoraには移さない。HTTPの検索・サジェストはMestionoraへ直接、要求ごとの判定を渡す。
|
||||
|
||||
旧 `SearchResult`、`PathSuggestion`、`SearchOptions`、`CitySearchResult` の型とメソッド、
|
||||
`ErrInvalidSearchOptions` の同一性を保持する。H1とCity表示名の共通投影は一つの実装へ委譲する。
|
||||
UI・URI・GETパラメーター・JSON、表示順位、Domain/Path/Revisionの識別子は変更しない。
|
||||
|
||||
## 認可と読み取りの境界
|
||||
|
||||
Page検索は現在のDomain・scope・フィルターに合う候補をSQLで絞り、Path単位の認可を行う。
|
||||
同じ文書に公開と非公開のaliasがあっても、非公開Pathを別名として返さない。
|
||||
本文抜粋・要約・H1は許可された表示対象にだけ補う。FTS自体は非公開データも含む索引を
|
||||
走査するので、「非公開文書の索引を一切読まない」という保証ではない。
|
||||
未許可候補の件数、Path、ファイル名、タイトル、抜粋は返さず、全件拒否は通常の空結果とする。
|
||||
|
||||
City結果は境界PathとQuartier・Street祖先のすべてを確認する。
|
||||
未分類Spotのポータルを親Streetへ向ける既存の投影と、親側の判定を維持する。
|
||||
Mestionoraはユーザー間・Domain間で結果や許可判定を共有キャッシュしない。
|
||||
|
||||
Pageの候補と抜粋は同じ読み取りtransactionで扱う。認可callbackもその中で呼ぶため、
|
||||
事前読込済みの判定が望ましい。現行アプリケーションでは `/u/` のユーザー領域ポリシーに
|
||||
遅延DB参照が残る。このcallbackを使う場合は別接続の余力が必要であり、プールを1本へ制限すると
|
||||
待ち合わせ・timeoutの原因になる。Cityは候補transactionを終了してから認可する。
|
||||
認可とPage検索を別snapshotへ分割する変更は、Path/Revisionの再検証と合わせた後続設計とする。
|
||||
|
||||
検索データはHTMLとして信頼しない。抜粋の文字列化・script/style除去・強調表示と
|
||||
リンクのエンコードは既存のserver/template経路で行う。H1抽出はsanitizerではない。
|
||||
|
||||
## 保持する検索予算と意味
|
||||
|
||||
| 項目 | 上限・動作 |
|
||||
| --- | --- |
|
||||
| Page/Cityの入力 | 512 bytes・16語まで |
|
||||
| Page候補 | Path/filename部分一致、本文FTS、filename FTSの各streamで1,000件まで |
|
||||
| Page結果 | 既定100件、最大200件。認可後に順位付け・表示上限を適用 |
|
||||
| City候補・結果 | 種類ごとに1,000候補、許可された結果は最大30件 |
|
||||
| 検索時間 | 各検索2秒。HTTPはCityとPageで2秒を共有 |
|
||||
| 本文snippet | 1文書64 KiB、重複Revisionを除いた合計1 MiB、追加処理の時間予算400 ms |
|
||||
| サジェストHTTP | 700 ms、Page最大8件・City最大4件。Cityは任意の補足 |
|
||||
|
||||
Domain・scope・ファイル/日付条件を候補LIMITより先に適用する。
|
||||
FTS-firstのCROSS JOIN、現行RevisionとPathへの索引参照、rowidで限定したsnippet取得を維持する。
|
||||
通常検索でDocumentファイルをstatしたり、全件数を数えたりしない。
|
||||
大きい本文やsnippet予算超過は抜粋だけ省略し、許可されたヒットは残す。
|
||||
|
||||
FTSは各語を引用したprefix条件をANDで結合する。入力中の演算子や引用符をSQL/FTSの命令として
|
||||
扱わない。Path scopeは既存の正規化と区間比較を使い、`%`・`_` をワイルドカードにしない。
|
||||
MIMEと拡張子の優先順位、日付の半開区間、Cityにファイル種別を適用しない規則も変更しない。
|
||||
|
||||
今回の是正点として、Pageの認可中にcontextが取り消された場合は返却直前にも検査し、
|
||||
候補が残っていても部分的な成功として返さない。DBエラーのHTTP出力は従来どおり一般化する。
|
||||
|
||||
## 索引と残件
|
||||
|
||||
`revision_search`、`revision_search_state`、`latest_revision_index`、`search_schema_state`、
|
||||
既存triggerとbackfill SQLは名称・内容を維持した。分離による新しいmigrationや索引再作成は不要。
|
||||
起動時の従来の整備処理がなくなったわけではない。
|
||||
|
||||
- [ ] ユーザー領域を含む読み取りポリシーの事前読込と予算を整理し、接続1本でも認可中に待ち合わない構造にする。
|
||||
- [ ] 現行Revisionのみ・Domain別の索引、更新watermark、継続取得を設計する。現候補上限は網羅的な検索を保証しない。
|
||||
- [ ] 日本語の中間一致、HTMLの可視テキスト化、言語別順位と対象Revisionの選択をmigration付きで整備する。
|
||||
- [ ] 現状の最新RevisionはObject単位であり、言語別検索ではない。履歴検索・言語別検索の意味を別途決める。
|
||||
- [ ] 既存FTS backfillとtrigger再作成の起動コスト、再開可能性、readinessを整理する。
|
||||
- [ ] H1取得を索引メタデータへ移す。現在は認可後にDB本文の先頭65,536文字を取得する互換処理。
|
||||
- [ ] 外部検索・関連性検索は別provider契約とし、認可済みの範囲・送信先・送信内容を明示する。
|
||||
- [ ] 結果cacheを追加する場合はDomain、principal、policy version、索引versionを含め、失効を先に実装する。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
合成データと一時DBで新旧入口の一致、nil/拒否ポリシー、alias・Domain・リクエスト分離、
|
||||
認可後の抜粋とH1、キャンセル、読み取り専用動作、FTS/Cityの実行計画を検証する。
|
||||
既存の600 Page / 1,200 Revision試験、City祖先認可、MIME・日付条件、XSS回帰試験を維持する。
|
||||
Chromiumではデスクトップ・モバイルの3表示モード、City先頭表示、絞り込み、リンクを確認する。
|
||||
|
||||
実行結果は [コンポーネント検証記録](component-names.md#検証記録) に記載する。
|
||||
本番DBの診断や外部カレンダー内容へのアクセスは行わない。commit・push・本番反映は別操作とする。
|
||||
@@ -35,6 +35,13 @@ MWDB/Karton等の接続はpending/clean/suspicious/malicious/error/expiredの状
|
||||
|
||||
## DRとHAの順序
|
||||
|
||||
次段階の詳細設計DR-D1は [役割・再参加](dr-authority-and-rejoin.md)、
|
||||
[通信・同期・切替](dr-protocol-and-sync.md)、[実施計画](dr-delivery-plan.md) に分離した。
|
||||
設計のみの完了であり、DB別件に介入していない。管理primaryとデータprimaryを独立させるが、
|
||||
保存resourceを共有する場合は連動切替とし、probeを昇格の証明としない。
|
||||
|
||||
2026-09-27追記:[DR詳細設計と運用手順](disaster-recovery.md)に、インスタンス単位の停止snapshot、検証付き復元、読み取り専用起動、外部fenceを前提にした手動昇格の初版を定義した。オンライン同期・自動昇格・管理GUIは次段階。初版では待機系のorganizer/CalDAVは閉じ、昇格後に再開する。
|
||||
|
||||
コントローラDRは署名manifest journal、鍵の保全、sequence、昇格epoch、旧leaderのfencingから設計します。記事DBとDocumentの複製は別の責務です。Campus manifestは記事バックアップではありません。
|
||||
|
||||
LB/HAにはsession失効共有、job lease、cache invalidation、uploadのnode非依存、WebSocket drain、proxy origin検証を要します。SQLiteをネットワーク共有して複数writerで動かす構成は採りません。fenced single-writer+replicaか、適切なmetadata backendを先に選びます。
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
# Ordoschnellic の通知配送契約
|
||||
|
||||
2026-11-01、既存のWeb Push配送を `internal/ordoschnellic` に初期分離した。
|
||||
通知の作成・Inboxへの登録と、登録済み通知の配送を区別する。
|
||||
今回の対象は配送ループ、再試行方針、購読データ検証、暗号化したWeb Pushの送信。
|
||||
メール等の新チャネル追加、通知UI変更、独立サービス化は含めない。
|
||||
[コンポーネント命名](component-names.md) と [アクティブ通知](active-notifications.md) を併読する。
|
||||
|
||||
## 責務と依存方向
|
||||
|
||||
| 部品 | 所有する処理 |
|
||||
| --- | --- |
|
||||
| `ordoschnellic.Dispatcher` | 有界バッチ、閲覧中の延期、配送結果の集計、終了処理、キャンセルの伝播 |
|
||||
| `ordoschnellic.WebPush` | 保存済み購読の検証、通知識別子の暗号化、HTTP結果の分類 |
|
||||
| `ordoschnellic.Queue` | 清掃・取得・延期・完了を要求する契約。永続化の実装は所有しない |
|
||||
| store | Inboxとキューの原子的登録、購読とセッションの束縛、claim時の適格性確認、lease、結果保存 |
|
||||
| server | 認証済み購読API、VAPID鍵の取得、接続先制限付きHTTP client、キューadapter、イベント登録・集計ログ |
|
||||
| Dregarnuhr | 既存の `notification.push.deliver` を定期実行。通知本文や受取人は決めない |
|
||||
|
||||
依存方向は server/store → ordoschnellic → Web Pushライブラリ。
|
||||
Ordoschnellicからserver/store/DB/ファイルへ戻る依存を持たない。
|
||||
接続先の公開IP検証・DNS固定・TLS・redirect禁止はserverが提供するHTTP clientで行う。
|
||||
鍵providerやHTTP clientがない場合、既定clientで送信せず再試行扱いにする。
|
||||
|
||||
`Notification` と `PushDelivery` は共通型として分離し、既存store型はaliasで維持する。
|
||||
通知APIのJSON、エラー同一性、UUID、DBテーブルとtrigger、購読ID・session hash、イベント型、
|
||||
`builtin.notification.push` の定義IDは変えない。新規migrationや再購読は不要。
|
||||
|
||||
## 通知の生成と購読位置
|
||||
|
||||
業務処理が `CreateNotificationTx` を呼び、Inbox INSERT triggerが該当購読のキューを作る。
|
||||
業務側のrollbackはInboxと配送キューの両方を取り消す。ネットワーク送信をこのtransactionへ入れない。
|
||||
Inboxの重複キー `(domain_uuid, recipient_uuid, event_uuid, kind)` と、
|
||||
キューの `(subscription_id, notification_uuid)` を維持し、同じ通知を新UUIDで作り直さない。
|
||||
|
||||
Activity Subscriptionのconsumer ID・watermark、Task Activityのjournal→outbox橋渡しは
|
||||
別契約としてそのまま残す。Ordoschnellicという名前への置換やcheckpointの初期化は行わない。
|
||||
新規Push購読への過去Inboxの一斉再送もしない。
|
||||
|
||||
## 認可と送信情報
|
||||
|
||||
claimのDB transactionで、Domain・受取人・Inbox・購読・元セッションの対応を確認する。
|
||||
セッション期限/失効、Principalのactive/readonly、membershipのactive、Domainの有効性と
|
||||
local配置、未読状態、24時間以内の通知であることを検査する。
|
||||
条件を満たさないclaimは購読本文を渡さず、送信せずにキューを終了する。
|
||||
これはclaim時点の検証であり、検証直後からHTTP送信までの失効との競合を完全には排除しない。
|
||||
|
||||
送信先は従来のFCM・Mozilla・Appleの許可ホストのみ。
|
||||
HTTPS、userinfo/fragment/明示portの禁止、P-256鍵とauth鍵の形式検証を維持する。
|
||||
任意URLへの通知チャネルではない。HTTP clientは公開IPへのDNS固定とredirect禁止を維持し、
|
||||
サーバーの既存接続防御を迂回しない。
|
||||
|
||||
暗号化前のwake payloadは `uuid`・`owner`・`domain` の3項目のみ。
|
||||
件名・本文・Bearer tokenをPushへ入れない。OS側は一般的な新着表示、詳細は認可済みInboxで読む。
|
||||
VAPID秘密鍵は既存DB内にあり、今回の分離で格納場所・rotation方針は変えない。
|
||||
ログは `component=ordoschnellic` とsent/failedの件数のみ。購読URL・鍵・本文は記録しない。
|
||||
sentはPushサービスの2xx受付であり、端末への到達や利用者の閲覧を意味しない。
|
||||
|
||||
## 配送予算と終了規則
|
||||
|
||||
| 項目 | 維持する動作 |
|
||||
| --- | --- |
|
||||
| 実行間隔 | 既定30秒、priority -3。既存管理者設定を上書きしない |
|
||||
| バッチ | 最大20 claim・25秒。focusedや失効済みも件数予算に含む |
|
||||
| HTTP | 1要求5秒、redirectを追わない |
|
||||
| claim lease | 60秒。ネットワーク処理はclaim transactionの外で実行 |
|
||||
| 前面表示 | foreground lease 90秒。延期は1分、配送試行数を消費しない |
|
||||
| 成功 | 2xxで現在のキュー項目を完了 |
|
||||
| 再試行 | 通信/鍵取得失敗・429・5xx。試行1~4の後に2/4/8/16分、5試行目で終了 |
|
||||
| 購読失効 | 404・410、または不正な保存購読データで購読を削除 |
|
||||
| その他HTTP結果 | 現行仕様どおり当該通知の配送を終了。401/403も自動再試行しない |
|
||||
| 保持 | キュー24時間、Push TTL 300秒。清掃は購読100件・キュー500件/run、Inboxは消さない |
|
||||
| 終了保存 | 送信側contextが取り消されても独立した最大3秒で結果保存を試す |
|
||||
|
||||
`Queue`操作には時刻を渡し、テストでlease境界とbackoffを待ち時間なしで検証できる。
|
||||
旧store入口は現在時刻を渡して委譲する。タイムアウトには実時間contextを使う。
|
||||
新たにDregarnuhrから配送へcontextを伝播し、開始前キャンセルではDBにも接続しない。
|
||||
不正な試行数でshiftを行わず、終端扱いにする防御も追加した。
|
||||
|
||||
DB失敗は呼出し元へ返し、後続claimへ進まない。バッチ時間を使い切った残件は次回実行へ回す。
|
||||
親contextのキャンセルはエラーとして返す。Dregarnuhrの汎用ジョブに期限付きleaseが未実装でも、
|
||||
Pushキューには既存の60秒leaseがある。この二つを混同しない。
|
||||
|
||||
## 配送保証と残件
|
||||
|
||||
初期分離はexactly-onceを導入しない。HTTP成功直後にプロセスが停止したり結果保存に失敗すると、
|
||||
lease後に再送され得る。ブラウザ側のtagによる集約は端末表示の対策であり、配送の一回性ではない。
|
||||
通常の完了更新はattempt一致を検査するが、これを完全なfencingと呼ばない。
|
||||
|
||||
- [ ] claim世代をattemptと分離する。focused延期によるattempt減算では世代が再利用されるため、古いworkerの結果との競合が残る。
|
||||
- [ ] 404/410による購読削除を購読version/claim世代で条件付けする。現在はIDだけで削除するため、送信中に更新された同一購読を削除し得る。
|
||||
- [ ] claim後の失効と送信の競合を整理する。送信直前の再検証も完全な原子性を保証しないことを明記する。
|
||||
- [ ] Retry-After、失敗理由別のメトリクス、キュー深さ・最古待機時間、枯渇/失効/廃棄件数を追加する。本文・endpointは観測属性にしない。
|
||||
- [ ] lease超過や多重workerの障害試験、HTTP成功後のDB失敗を含む復旧手順を整備する。
|
||||
- [ ] quiet hours、digest、チャネル別設定、メール等の配送はrecipient/channel/versionの冪等キーと受入条件を決めてから追加する。
|
||||
- [ ] 実機のPush受信・再訪・ログアウト、VAPID rotation、端末一覧UIは既存の残件として継続する。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
合成データ・一時DB・偽HTTP clientのみで検証する。実通知サービスへの送信、
|
||||
本番DBや外部から取り込んだカレンダー内容へのアクセスは行わない。
|
||||
境界・型/JSON/イベントID互換、バッチ上限、キャンセル後の終了保存、HTTP分類、暗号化、
|
||||
認可失効、並行claim、lease回収、旧attempt完了の拒否、focus延期、Inbox保全を対象とする。
|
||||
既存のtransaction rollback・重複抑止・Activity Subscriptionのcheckpoint試験も維持する。
|
||||
|
||||
検証結果は [コンポーネント検証記録](component-names.md#検証記録) に記載する。
|
||||
ソース変更とテスト、本番反映は別段階。commit・push・デプロイは今回含めない。
|
||||
@@ -0,0 +1,134 @@
|
||||
# 最優先:日常操作・ブラウザ・エディタ・CLI(2026-10-31)
|
||||
|
||||
ユーザ指定の次期開発最優先。従来の機能追加より先に進める。ただし認可、正本の保全、競合検出を省略しない。本番反映とローカル検証済みは区別する。
|
||||
|
||||
## 実装順と受け入れ条件
|
||||
|
||||
### 1. ホームとファイルブラウザ
|
||||
|
||||
- [x] ホームで他の入力欄にフォーカスしていないとき、文字入力でグローバル検索へ移る。最初の文字を失わず、IME開始・修飾キー・モーダル・選択中テキストを妨げない。中央検索、検索+ブックマーク、従来トップバーを対象とする。実機IMEでの入力確定は下記受け入れ残件。
|
||||
- [x] ブラウザに `/` 始まりのアドレス欄を設け、絶対/相対Path、`cd`、`vi`、`view` を扱う。URLのquery/hashや外部URLと混同せず、同一Domain内のPathとして解決する。シェル実行はしない。
|
||||
- [x] ブラウザから名前を指定して新規文書エディタへ進む。既存Pathでは既存文書を編集する。
|
||||
- [ ] 後続:エディタの新規作成をGET時ではなく明示的な保存時へ遅延する。既存エディタはGET時にPage/Pathを作成するため、今回のナビゲーション追加ではその契約を維持する。UUIDを必要とする下書き/競合/言語/保存APIを合わせて変更する。
|
||||
- [x] 未作成Pathに仮想フォルダとして潜れる。空フォルダの実体は作らず、そこから作成/アップロードへ進む。現在Pathを貼り付け先など既存操作と共有する。
|
||||
- [x] キーボード移動、空フォルダ、特殊文字、日本語、ルート境界、読み取り専用アカウントからの作成拒否、既存の複数選択/ドラッグ操作をfixture検証する。
|
||||
|
||||
### 2. エディタと表示
|
||||
|
||||
- [x] カーソル/選択範囲/現在行をテーマに合わせる。Vimの実際のmode-changeで通常/挿入/置換/選択の状態とカーソル色を更新。`A` 等の移行もfixture確認済み。
|
||||
- [x] ライトモードで背景・文字・構文色・ガター・補完UIをテーマ化。生成されたLezerクラス名への依存を除去し、意味タグによる構文色へ移行。既存のエディタ復旧試験も通過。
|
||||
- [x] PlainTextの初期実装:ブラウザの新規文書ダイアログで指定、または `/e/-/{path}?edittype=plain`。既存の `text/plain` は自動選択。保存・プレビューは文字列のまま、HTML/マクロとして実行しない。下書き・競合処理にplainを追加し、異なる形式の下書きを自動復元しない。
|
||||
- [ ] PlainText後続:既存Wiki HTMLとの形式変換は損失確認・保存MIME・過去版復元の意味を確定してから。現在は409で拒否し、既存HTMLの原本と履歴を変更しない。Domain既定形式と外部アダプタのPlainText設定も後続。
|
||||
- [x] codeブロックのテーマ対応装飾、ブロック内の横スクロール、インラインcodeの区別、印刷時の折り返しCSS。300px幅での局所overflowをChromium検証。実機モバイルと印刷の目視確認は残件。
|
||||
|
||||
### 3. テーマ・アカウント・連絡先
|
||||
|
||||
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
||||
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
||||
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||
- [x] 電話連絡先の初期実装(2026-11-01ローカル検証済み、本番未反映):本人編集、独立した公開範囲、表示用文字列と正規化した `tel:` リンク。公開は明示確認とプロフィール/ドメイン上限に従う。クリックなしで発信しない。
|
||||
|
||||
### 4. Cityの表示名
|
||||
|
||||
- [x] 検索結果/ホーム・ビューア検索サジェストのCityリンクは設定詳細ではなく閲覧導線にする(2026-11-01本番反映済み)。対応するPathにPageがあればそのページ、なければそのPathのディレクトリ一覧へ。仮想未整理Spotは実在しない `/_undefined` ではなく親Streetを入口とする。タイトルリンクとPathリンクを統一し、認可、Domain分離、特殊文字のエンコードを維持する。管理詳細への明示的なリンクは残す。
|
||||
- [x] 初期対応:生成済みSpotの既定プレースホルダー名 `Undefined` を閲覧時の表示から外し、親Streetのタイトル(未設定なら名前)を使用する。独自タイトルは保持し、UUID/識別名/Path境界は書き換えない(2026-11-01本番反映済み)。
|
||||
- [ ] 「子Spotがあるならカルチエ名」という案の階層対応は別途確定する。現行はQuartier > Street > SpotでSpotを入れ子にできないため、今回の表示変更では昇格/再配置/権限境界の変更をしない。
|
||||
|
||||
### 5. セッション付きCLI/TUI
|
||||
|
||||
- [x] HTTPクライアント初期版 `pages-cli`/コマンド `pages`(2026-11-01ホストのユーザーPATHへ配置済み。実ユーザログインは未実施):configureによる接続先・既定プロファイル・言語管理、パスワード/TOTP、Bearer保持・失効、ls/cd/cat/view/get、既存Page edit/put、Path補完、メモリ内履歴、検索候補、ブラウザ引き継ぎ。詳細と原設計整合は [遠隔CLI](remote-cli.md)。既存DB直アクセスCLIは変更しない。
|
||||
- [ ] 既存 `data/pageswiki-cli` を拡張する専用起動コマンドとセッション保持。履歴や資格情報に0600相当の保護と失効/ログアウトを設ける。
|
||||
- [ ] `Ctrl+P` のfuzzy検索と、ローカル `$EDITOR` 編集。現在版/ETagを保持してアップロード時の競合を検出し、上書き・差分・キャンセルを選べるようにする。
|
||||
- [ ] パスワード認証に加え、ターミナルにURLを表示するブラウザ認証(OIDC)。既存Web認証と同じ本人性/MFA制約を適用し、短命・単回の認可コード+PKCEやdevice-flow相当の仕様を検討する。URLや履歴に長期トークンを含めない。
|
||||
- [ ] ターミナル表示が難しい内容はブラウザに引き継ぐ。short linkは認証を迂回しない内部リンクとし、公開share link発行とは分離する。自動公開しない。
|
||||
|
||||
## チェックポイントと進捗
|
||||
|
||||
### 2026-11-01:コマンドバーと共通シンタックス色(本番反映済み)
|
||||
|
||||
- ブラウザのPathアドレス欄をtopbarへ移設。1100px以下では非表示。左下に独立した `cd` / `vi` / `view` バーを常設し、入力欄などにフォーカスがない状態の文字入力を最初の1文字から引き継ぐ。
|
||||
- 共通ナビのあるホーム以外の画面では `g` でバーを表示、Escで閉じる。ホームのtype-to-searchは維持。フォーム、モーダル、テキスト選択、修飾キー、編集中のCodeMirror/Vimの `g` は奪わない。ブラウザのEscはバーを消さず入力をクリア。
|
||||
- Tab/Shift+TabでPathを補完・候補巡回。候補が1件のフォルダは再度Tabで配下を補完。相対Path、日本語、空白、`#` / `?` / `%` をそのまま扱い、Enter時にsegment単位でURLエンコード。シェル実行はしない。入力欄末尾以外/コマンド未入力時のTabは通常のフォーカス移動。
|
||||
- `path-picker?mode=children&path=...&prefix=...` を追加。親Path自身にPageが存在しても親へ戻らず配下を取得。名前専用SQLでRevision本文やプレビューを読み込まない。Domainと既存Path認可を維持。DB処理2秒、候補走査1000件、認可後最大250件、UI最大100件。上限時は絞り込みを促し、入力変更・Esc時はfetchを中止して古い結果を捨てる。prefixはASCII英字を大小区別せず照合し、それ以外はSQLiteの文字比較に従う。
|
||||
- モバイルのブラウザは中央一覧を優先。サイドバー/プレビューはボタンでオーバーレイ表示し、デスクトップの表示設定は変更しない。
|
||||
- CodeMirrorエディタ、コードファイルの読み取りビューア、文書中のコードブロックで `pw-syntax-*` とテーマの `--editor-*` 色を共有。Markdown内の対応言語のfenceも構文解析。全プリセットの切替、読み取りビューアとの色一致を確認。
|
||||
- Wiki本文・編集Preview・ブラウザPreview・公開ページ/公開ブログの言語指定付きコードブロックは、見えてきたものから1ブロックずつ遅延処理。32,768文字超と未対応言語は原文のまま表示し、正本・HTML保存データは変更しない。大きいコードファイルは既存のwindowed viewerを維持。新規CDN・外部ライブラリは追加しない。
|
||||
- Chromium 1440px/375pxでコマンド入力/補完/キャンセル/ナビゲーション/レスポンシブ/Vim保護/コード原文保持/動的Preview追加を確認。ホーム3種・エディタ復旧の既存回帰も通過。実機IMEの確定とiPhone Safariのソフトウェアキーボードは未確認。
|
||||
- 開始時ソース:`.deployment-backups/dev-command-20261101/source-before.tar.gz`。2026-11-01 07:14 JST頃、fix2をベースに対象ファイルだけを差し替えた `pageswiki-app:command-20261101` をapp/app2へ反映。電話連絡先/SQLite初期接続の後続変更は含めない。[反映記録](../../operations/deployments/2026-11-01-command-ux.md)を参照。
|
||||
|
||||
2026-10-31:上記チェック済み項目はローカル実装・fixture検証済み。本番未反映。新たなDBテーブル/migrationはない。セッション期限は既存Domain configに保存する。
|
||||
|
||||
2026-11-01:上記UXを本番app/app2へ反映済み。既存の保存基盤変更も含むため、隔離コピーでmigration/backfillを確認し、旧イベント索引の採用不具合を修正して反映した。Docker実行基盤の版ずれによる一時停止と復旧、切替直前の整合バックアップ、イメージ識別子・検証結果は [本番反映記録](../../operations/deployments/2026-11-01-priority-ux.md) を参照。
|
||||
|
||||
- 開始時のHEAD:`9dd425f7658b2eecb1152ec8d457d6224142f9fc`。既存の未コミット変更を含むソースを退避済み。
|
||||
- バックアップ:`.deployment-backups/dev-priority-20261031/source-before.tar.gz`。
|
||||
- 検証済みの区切り:同ディレクトリの `source-after-ux.tar.gz`。ハッシュと復元時の注意は同ディレクトリの `README.md` に記録する。
|
||||
- SHA-256:`8fa6864eeeaa89b3019c06f9c1975a13f380731efa033df810870fb04c4f94e2`。
|
||||
- 対象はGit管理対象と非ignoredの新規ソース。`.git`、秘密設定、本番DB・Document実体、コンテナイメージは対象外。本番の復元用バックアップではない。
|
||||
- 復旧時は別ディレクトリに展開して対象ファイルを比較・復元する。新規追加ファイルは個別に退避する。既存のユーザ変更を失う `git reset --hard` は使わない。
|
||||
- 本番へのデプロイ、DB変更、外部サービスへの接続はこの段階では行わない。
|
||||
|
||||
### 検証
|
||||
|
||||
- `go test ./...`:通過(opt-in browserを除く全パッケージ)。
|
||||
- Chromium:ホーム3レイアウトの入力検索、他入力/モーダル/修飾キー、IME開始イベント、仮想Path移動、新規Wiki/PlainText作成、既存ドラッグ選択、テーマ変更、Vimモード、PlainText保存とリテラルプレビュー、既存の下書き復旧・競合処理。
|
||||
- Node:パス正規化/URLエンコード/外部URL拒否、編集coreのmerge/draft検証。
|
||||
- 編集bundle再ビルド、`git diff --check`。Index Whiteのエディタをスクリーンショットでも確認。
|
||||
- 本番・実機Safari/iPhone・日本語IMEの確定動作・印刷・カスタムテーマ全種類は未確認。
|
||||
|
||||
## 後続実装の境界と状態
|
||||
|
||||
### 連絡先
|
||||
|
||||
まず `/u/{username}/_/edit` の本人連絡先を対象とし、オーガナイザーの汎用連絡先帳/CardDAVとは区別する。電話番号はDomain+Principalで保存し、既定private。プロフィール全体をpublicにしただけで電話番号を公開しない。独立した公開確認と上位公開制限を適用する。
|
||||
|
||||
表示文字列と正規化済みの電話番号を分離する。`tel:` の値はサーバが組み立て、入力された任意URIをそのまま採用しない。サービスコード/制御文字/改行/スキーム混入は初期版では受理しない。スマホでタップしたときだけOSへ委譲し、自動発信や外部の番号検証サービスへの送信はしない。
|
||||
|
||||
保存先はmanaged schema moduleとして追加し、本人更新と状態確認をtransaction内で行う。公開profile投影、API、検索、exportで非公開値を漏らさないfixtureを先に用意する。
|
||||
|
||||
2026-11-01実装:`profile-contacts` component v1、Domain+Principalを主キーとする。Principalや認証API/継承データには電話番号を追加しない。プロフィール画面のみ専用の認可済み取得を使い、非公開の番号はdomain_adminにも出さない。管理者の閲覧権限を本人の同意と扱わない。
|
||||
|
||||
- `/u/{username}/_/edit#contact` の独立フォームで本人のみ更新。CAS versionで古いフォームは409。activeの本人とactiveのDomain membershipをtransaction内で検査し、readonly/suspended/他Domainからの更新を拒否。
|
||||
- 既定private、domain/publicはプロフィール公開範囲でさらに制限。publicの新規設定・番号の差し替えは確認チェックが必要。ドメイン公開の撤回/プロフィール非公開への変更を次の読み取りから反映する。
|
||||
- 電話番号は3〜15桁、先頭の+、表示用の空白・ハイフン・括弧に限定。内線、URIパラメータ、サービスコード、制御文字、任意スキームを拒否。空欄保存は番号を消去してprivateに戻す。
|
||||
- JA/ENの説明・フォーム・保存後アンカーを追加。デスクトップ1440px/375pxで実ブラウザの入力・保存・telリンク・フォーム幅を検証。iPhoneの電話アプリ起動そのものは未検証。
|
||||
- store/HTTPで本人・匿名・他メンバー・管理者・越境・公開確認・公開撤回・競合・不正番号を検証。個人情報の本文を監査ログへ追加しない。CardDAV、住所録、複数番号、内線は後続。
|
||||
- **本番反映済みfix2にはこの機能を含めない。** 次回リリースでは追加componentの適用と、旧版への切り戻し条件を別途検証する。
|
||||
|
||||
### 新規DBの初期接続競合(後続修正、本番未反映)
|
||||
|
||||
全体回帰で `TestSQLMigrationLedgerConcurrencyAndChecksum` がまれにSQLITE_BUSYとなることを確認。診断メッセージをmigration connection取得/BEGINに分け、2,000回の反復で接続取得段階の失敗を再現した。`sql.Open` がlazyのため、最初の並行接続でWALへの切替が競合していた。
|
||||
|
||||
`db.Open` 内で5秒上限のPingを完了してからプールを公開し、初期接続失敗時はCloseして返す。migrationのBEGIN IMMEDIATE/checksum/transaction境界は変更しない。修正後の同テスト2,000回が成功。既にWALで稼働している本番DBのジョブ競合修正とは別件として扱う。
|
||||
|
||||
### Cityの名称規則
|
||||
|
||||
現行の未整理Spotは `name` の `-undefined` や `/_undefined` によって識別され、Street直下Pageの収容にも使われる。`city-estates.js` のラベルだけを書き換えても、API・パンくず・詳細・検索に別名が残る。
|
||||
|
||||
2026-11-01実装・本番反映済み:内部ID/境界と `display_title` を分離。生成Spotで既定名(空、識別名自身、Undefined等)の場合のみ親Street表示名へ射影し、独自タイトルは維持する。生成由来かどうかの永続フラグはないため、既存と同じ識別名suffix/仮想Path規則を使用する。通常Spotに意図的に付けた `Undefined` は変更しない。[反映記録・切り戻し](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||
|
||||
- 地図ラベル、パンくず、ディレクトリ、整理モーダル、詳細見出し、検索・サジェスト、ページ上の所属リンク、Cityマクロで同じ規則を使用。管理用識別名/Pathはそのまま残す。
|
||||
- 匿名地図は公開用に縮退させた名前から再計算し、認証済み投影のカスタムタイトルを再利用しない。所属リンクはSpotに加えて親Street/Quartierの閲覧権限も確認する。共有ナビゲーションキャッシュを表示名処理で変更しない。
|
||||
- 検索導線は `NavigationPath` と `HasPage` により本文/ブラウザ一覧へ分岐。検索結果のタイトルとPath、サジェストのURLを統一。`/_undefined` は親Streetへ案内し、無関係な先頭Pageをポータルにしない。
|
||||
- 遷移先の `/v/browser/{path}` はDomain全体のreadではなく対象Pathのreadで認可し、各子要素も個別に検査する。対象Pathを読めない利用者は403。匿名公開の一覧は従来の公開ナビゲーション処理を維持する。検索から本文/一覧を実際に開くHTTP試験を追加。
|
||||
- Pageの存在判定は既存Path索引のDomain+完全一致で検索SQL内に含める。本文、Revision、City全体の展開、結果ごとの追加HTTP/DB呼び出しは不要。候補上限/タイムアウト/親階層の認可を維持。EXPLAIN QUERY PLANでPath全走査がないことをfixture検査。
|
||||
- 検索画面は700px以下で検索欄をナビアイコンの下段に置き、プロフィールアイコンによる横はみ出しを解消。390pxと1440pxのブラウザ試験・モバイルスクリーンショットで確認。
|
||||
- 全Goテスト、Cityラベル(通常/popup)・整理操作・名前付き詳細遷移・検索表示(desktop/mobile)のChromium試験が成功。公開キャッシュ撤回、別Domain、親ACL、特殊文字、生成名と手動タイトル保持を検査。本番データ/外部カレンダーは使わない。
|
||||
- 復旧点:`.deployment-backups/dev-city-20261101/source-before.tar.gz`(SHA-256 `2675aff20450d24eb0fe1707ea5f3a38ee26c9bdf20dec1a29926d52ef5af4bf`)。DB/設定変更なし。別ディレクトリへ展開して差分復元する。前からある未コミット実装をまとめて取り消さない。
|
||||
- 検索CSSの変更前は同ディレクトリの `search-css-before.tar.gz` に別途保全(このファイルは着手時にHEADと同一)。変更後は `source-after.tar.gz`。範囲とハッシュは同ディレクトリのREADMEを参照。
|
||||
|
||||
ユーザの「子Spotがあるならカルチエ名」という案は、現行のSpotをネストしない制約と区別する必要がある。今回の対応では昇格/再配置はせず、空の仮想要素を生成し直さない。
|
||||
|
||||
### リモートCLI
|
||||
|
||||
現行 `data/pageswiki-cli` はSQLite/Document Storeへ直接アクセスする運用CLI。shell、補完、履歴、`$PAGER`/`$EDITOR` は既にあるが、Web認証を受けるリモートクライアントではない。Webユーザの認可をSQLite直アクセスへ継ぎ足さず、HTTP transportを持つ別コマンド(仮称 `pageswiki remote`)として段階導入する。
|
||||
|
||||
2026-11-01:試作名 `data/pageswiki-remote` から、ユーザ指定によりサブプロジェクト `pages-cli`/実行名 `pages` へ整理。`pages configure` と既定値により通常操作のprofile/lang引数を不要とした。以下は全体計画であり、Ctrl+P、OIDCハンドオフ、新規作成、強制上書きの対話選択、short linkは未実装。[初期版の範囲・制限・検証](remote-cli.md)を参照。
|
||||
|
||||
1. パスワード+TOTPの既存JSONログイン、失効/logout、接続先・Principal・Domain別セッション保存。秘密情報はコマンド引数/履歴/ログへ出さず、保存先0700・資格情報0600相当、TLS検証必須。
|
||||
2. `ls/cd/view/get/edit` と現在Pathの保持。検索は認可付き・件数制限・キャンセル可能なAPIを使用し、`Ctrl+P` のfuzzy選択へ接続。端末の制御シーケンスは本文/タイトルから除去する。
|
||||
3. `$EDITOR` は引数を分離して起動し、shellへ未検証Pathを連結しない。取得時のRevisionを保存し、CAS書込・409時の差分確認・一時ファイルの保持/削除を実装する。Wiki HTMLと編集Markdownは既存authoring変換APIを使い分ける。
|
||||
4. OIDCはブラウザ側で既存ログイン/MFAを完了し、短命・単回・認証先/クライアント紐付きのハンドオフでCLIへ交換する。長期BearerをURLへ載せない。確認画面、CSRF/PKCE相当、リプレイ拒否、発行上限、poll backoffを含めてから実装する。
|
||||
5. 表示できないオブジェクトは認証を維持した短い内部URLでブラウザへ引き継ぐ。公開share linkは自動発行しない。別originへのredirectにBearerを転送しない。
|
||||
|
||||
初期の遠隔アクセス試験は偽サーバと一時データのみ。本番資格情報や外部取り込み済みカレンダーの内容をテストに使わない。
|
||||
@@ -0,0 +1,95 @@
|
||||
# pages-cli:`pages` HTTPクライアント
|
||||
|
||||
2026-11-01。合成データで検証済み。同日、本番サーバのCity更新と合わせてクライアントをホストの `/home/anya/.local/bin/pages` に配置した。実ユーザの資格情報取得・ログイン・本番Page編集は未実施。接続設定とログインは利用者が行う。[反映記録](../../operations/deployments/2026-11-01-city-pages-cli.md)。
|
||||
|
||||
## 原設計との整合
|
||||
|
||||
原設計の [Address Model](../address-model.md)、[URI](../uri.md)、[認証バックエンド](../auth-backend.md)、[エディタの保存契約](editor-resilience.md)を使用する。
|
||||
|
||||
- Pathは到達経路、UUIDはPageの識別子、Revisionは履歴。取得は `/v/raw/path:/...`、`uuid:`、`rev:` で行い、`/raw/...` を増設しない。
|
||||
- 編集開始時にObject UUIDを確定し、指定言語のheadを取得。保存はUUID+言語+`base_revision_uuid`+`editor_principal_uuid`。Path変更に追従するため保存先を再解決して別Pageに書き込まない。
|
||||
- Wiki正本はHTML。編集用Markdownはauthoring射影であり、children等の表示展開結果を保存しない。保護HTMLフェンスを既存authoring APIで往復する。
|
||||
- Domainは接続originで決まり、HTTPで既存の認証・権限制御を受ける。Campus連携用トークン/PSKをユーザー認証に流用しない。
|
||||
- 旧認証設計にはCookie中心の記載が残るが、実装済みのJSONログインはBearerセッションを発行する。CLIはこのフローを使用し、Web Cookieを抽出しない。
|
||||
- `data/pageswiki-cli` は信頼されたローカル運用ツールとして維持。遠隔版はサブプロジェクト `pages-cli`、実行名 `pages`(`pages-cli/pages`)とし、DB・Document Storeを直接開かない。
|
||||
|
||||
サーバAPI/DBスキーマの追加・変更はない。初期実装はPython 3.9以降の標準ライブラリで動作するUnix系クライアント(fcntl、readline使用)。Windowsネイティブ版は未対応。
|
||||
|
||||
## 利用方法
|
||||
|
||||
```sh
|
||||
# 初回設定。パスワードはlogin時の非表示プロンプト、必要ならTOTPを続けて入力。
|
||||
pages configure --origin https://pages.example.test --username anya
|
||||
pages login
|
||||
pages status
|
||||
pages
|
||||
|
||||
# ワンショット。--lang はコマンドより前に指定する。
|
||||
pages ls /manual
|
||||
pages edit /manual/start
|
||||
pages get /manual/start ./start.html
|
||||
pages put ./start.html /manual/start --base REVISION_UUID
|
||||
pages logout
|
||||
```
|
||||
|
||||
配置方法と詳しい設定例は [pages-cli README](../../../pages-cli/README.md)。既定プロファイル名は `default`、編集言語は `und`。`pages configure --lang ja` で変更し、`configure set --profile work --origin ... --username ... --lang en` で接続先を追加する。`configure use work` で既定を切り替え、通常操作ではprofile/langの引数を省略する。一時的な `--profile`/`--lang` 上書きも残す。
|
||||
|
||||
設定は `config.json` の version/default_profile/profiles と、各接続のorigin/username/langに限定。パスワード・Bearerは設定表示へ含めない。configureはネットワーク通信をせず、ログイン中のorigin/username変更を拒否する。mainは設定ロック→セッションロックの順で取得し、起動時の接続先すり替えを防ぐ。手編集時も保存したセッションの接続先・アカウントとの一致を確認してから使用する。logoutは設定を手編集した場合でも、保存済みの元接続先に対して失効する。
|
||||
|
||||
対話シェルは `ls`、`cd`、`pwd`、`status`、`cat`、`view`、`get`、`put`、`edit`、`search`、`open`、`logout`、`exit` を扱う。`--help` で一覧、`edit --help` 等で引数を確認する。`cd` は仮想Pathにも移動でき、存在や閲覧可能な子の存在を保証しない。
|
||||
|
||||
TabはPath候補を取得し、上下キーは当該プロセス内の履歴をたどる。Pathに空白等があればシェルと同様に引用する。履歴はディスクへ保存しない。現在Pathは接続プロファイルへ保存する。同じプロファイルの同時実行はロックで拒否し、別プロファイルは独立して使える。
|
||||
|
||||
`search QUERY` は権限付きサジェストを表示する初期コマンド。Ctrl+Pのインクリメンタルfuzzy選択は未実装であり、通常のreadlineキー割当のまま。
|
||||
|
||||
### 閲覧・編集
|
||||
|
||||
- `get ADDRESS LOCAL` は最大64 MiBの正本を取得し、SHA-256を照合する。ローカル出力は0600で新規作成し、既存ファイルを上書きしない。Revision UUIDを表示する。
|
||||
- `cat` はpipe時に正本バイト列を出力。TTY時には制御文字を除去する。`view` はテキストを `$PAGER`(既定less)に渡し、HTMLを端末上で実行しない。
|
||||
- `edit` は `$EDITOR`(既定vi)をshellを介さず起動。HTMLはauthoring Markdownが既定、その他の対応テキストは原文。`--format raw` でHTMLを直接編集できる。`--format markdown` はHTML文書専用。
|
||||
- ローカル作業ファイルは0700の一時ディレクトリ内に0600で保存。成功・無変更時は削除、失敗/409/通信断時は原稿とrecovery.jsonを保持して場所を表示する。recovery.jsonにはorigin、UUID、基点Revision、言語、形式を記録し、Bearerは含めない。
|
||||
- 409では最新内容とローカル原稿の差分を表示し、保存は停止する。自動マージ、強制上書き、自動再送はしない。応答喪失時は取得してサーバの状態を確認してから再試行する。
|
||||
- `put` は既存Pageの既存言語のみ。`--base` が必須で、現在headと不一致なら送信しない。サーバ保存も同じbaseでCASを行う。編集を保持したい場合は最新を取得して差分を確認し、調整済み原稿とその最新Revisionを明示して保存する。
|
||||
- `put --format markdown` はauthoring変換を使用。rawは正本形式を保持する。ローカル拡張子で保存MIMEを勝手に変更しない。テキスト編集は1 MiB、JSON送信は2 MiBまで。
|
||||
- `rev:` は取得専用。新規Page、未作成の言語head、バイナリ編集、Asset更新は拒否する。新規作成のためにエディタGETの副作用を利用しない。
|
||||
- `open` は同一originのPath/UUID/Revisionビューアをブラウザで開く。BearerはURLに含めず、ブラウザ側のログインが必要。共有リンクは自動発行しない。
|
||||
|
||||
## HTTP契約
|
||||
|
||||
| 操作 | 既存エンドポイント |
|
||||
| --- | --- |
|
||||
| ログイン/MFA | POST `/_/auth/login`、`/_/auth/totp`、フォーム本文+Accept application/json |
|
||||
| 失効 | POST `/_/auth/logout`、Bearer |
|
||||
| 一覧・補完 | GET `/_/api/v1/path-picker?mode=children&path=...&prefix=...` |
|
||||
| 検索候補 | GET `/_/api/v1/search/suggest?q=...` |
|
||||
| 正本・識別子 | GET/HEAD `/v/raw/{explicit-address}?lang=...` |
|
||||
| 言語別編集状態 | GET `/_/api/v1/editor/state?uuid=...&lang=...` |
|
||||
| HTMLへの復帰 | POST `/_/api/v1/render/markdown`、authoring=true、projection=false |
|
||||
| CAS保存 | POST `/_/api/v1/revisions/save` |
|
||||
|
||||
一覧は既存の件数制限を維持し、truncatedを表示する。巨大な全階層を再帰取得しない。読み取りのRaw言語選択は既存サーバの候補選択に従うが、編集は指定言語のheadを必須とし、存在しない場合は拒否する。
|
||||
|
||||
## セキュリティと運用上の制限
|
||||
|
||||
- 遠隔はHTTPS必須、証明書検証を無効化するオプションなし。HTTPはlocalhost/127.0.0.1/::1の開発専用。
|
||||
- 接続先はoriginのみ。userinfo、Path、query、fragmentを含むURLは拒否。リダイレクトは同一originも含め追従しない。認証画面HTMLや302/303を成功と扱わない。
|
||||
- 設定は `$XDG_CONFIG_HOME/pages-cli/config.json`、セッションは同じルートの `sessions/PROFILE.json`(既定 `~/.config/pages-cli/`)。ディレクトリ0700/ファイル0600、所有者を検査し、シンボリックリンクは拒否。atomic replaceとプロファイルロックを使用。旧試作の `~/.config/pageswiki-remote/` は自動読込・移行・削除しない。再configure/loginし、不要な旧セッションはサーバ側で失効する。
|
||||
- 資格情報は平文のため、同一OSユーザーやrootからは保護できない。OS keyring/暗号化保存は後続。共有端末ではlogoutし、残した作業原稿は利用者が整理する。
|
||||
- パスワード/TOTP/Bearerを引数や履歴へ入力させない。保存したexpiryを超えたセッションでは操作を開始せず、実際の失効・権限はサーバで毎回判定する。logout失敗時は失効済みと報告せず資格情報を残す。
|
||||
- ネットワーク要求には20秒のsocket timeoutと応答サイズ上限。総転送時間の厳密deadline/ストリーミング巨大ファイル対応は後続。
|
||||
|
||||
## 検証と次段階
|
||||
|
||||
Python unittest:origin制限、端末制御文字、別origin redirect遮断、非JSON/403/サイズ上限、TOTP、資格情報権限・symlink・並行実行拒否、authoring/CAS payload、ダウンロード上書き拒否、409時の原稿保全。
|
||||
|
||||
設定追加後は12件:既定値/複数接続切替/言語保存、一時上書き、設定表示からのトークン除外、セッション保持中の再接続先変更拒否、手編集での接続先不一致拒否も検査。HTTP統合試験では公開エントリーポイントのconfigure→login→引数省略のls/status/edit→logoutを通す。
|
||||
|
||||
Goの `TestRemoteCLIHTTPIntegration`:一時DBと本物のHTTPハンドラでログイン、一覧、編集状態、authoring変換、保存、古いRevision拒否、Rawハッシュ、immutable拒否、存在しない言語拒否、put、ログアウト後の拒否を検査。Pythonがないビルド環境ではこの統合試験をskipする。外部カレンダーや本番資格情報は使わない。
|
||||
|
||||
次段階の順序:
|
||||
|
||||
1. Ctrl+Pによる検索選択、補完の引用文字/途中カーソル対応、永続履歴の明示opt-in。
|
||||
2. 新規Page+Path+初回Revisionの原子的な作成API、create/upload-only権限、並行作成の衝突、言語分岐。
|
||||
3. 競合の対話選択・復旧コマンド、巨大転送のstreamingとキャンセル、mget/mput(globのlocal/remoteを明示)。
|
||||
4. OIDCブラウザ認証の短命・単回・PKCE相当ハンドオフ。既存device approvalをそのまま転用せず、本人確認・Domain・CLIリクエストを束縛する。
|
||||
5. OS keyring、Windows対応、非公開の短縮リンク引き継ぎ。自動的な公開shareは行わない。
|
||||
@@ -4,6 +4,8 @@
|
||||
|
||||
## 優先順
|
||||
|
||||
2026-10-31:ユーザ指定により[日常操作・ブラウザ・エディタ・CLI](priority-ux-20261031.md)を次期開発の最優先とする。下記の従来機能追加より優先するが、認可・データ保全の安全条件は省略しない。TODO、受け入れ条件、復元用チェックポイントを同文書に集約する。
|
||||
|
||||
2026-09-27追記:`organizer.tasks 0.11.1`で[既定タスクリスト名の変更](task-dav-default-list-name.md)を実装し、12:51 JSTに[本番両インスタンスへ反映](../../operations/deployments/2026-09-27-default-task-list-name.md)。PROPPATCH 405を解消し、利用者・domain別の表示名を保存、全探索結果へ反映する。実機再試行は確認待ち。色・アイコン・通常プロジェクトのPROPPATCHは別件。
|
||||
|
||||
2026-09-27追記:`organizer.tasks 0.11.0`の[タスク所属統一と上書き同期](task-dav-project-unification.md)を実装し、12:18 JSTに[本番両インスタンスへ反映](../../operations/deployments/2026-09-27-task-unification.md)。全Webプロジェクトを個別CalDAVリストとして公開し、既定リストはプロジェクトなしに限定。無条件PUT/DELETEはトークン別設定なしで受理し、版履歴を保持する。実機再同期は確認待ち。次の優先タスクは競合候補の保存、Inbox通知、上書き前/受信版の比較・採否選択(同文書のTODO)。反映時に観測したスケジューラclaimの一時的DBロックとディスク容量整理も運用記録へ残した。
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# Schutzaria の権限と公開範囲の評価契約
|
||||
|
||||
2026-11-01、既存の権限・公開範囲の純粋な評価処理を `internal/schutzaria` に初期分離した。
|
||||
認証済みPrincipalと対象Domainに対して読み込んだ事実を評価する部品であり、
|
||||
認証器、DBアクセス、権限変更、匿名公開の確定を一括で置き換えるものではない。
|
||||
既存の許可・拒否、公開の明示的な承認、URI・JSON・DB・監査記録の形式を維持する。
|
||||
[コンポーネント命名](component-names.md)、[認証と権限](auth-permissions.md)、
|
||||
[Localityの権限・公開](../locality-access-publication.md) を併読する。
|
||||
|
||||
## 責務と境界
|
||||
|
||||
| 所有者 | 担当する処理 |
|
||||
| --- | --- |
|
||||
| Schutzaria | Path読み取りgrant、Locality制限の交差、グループ権限プロファイル、公開上限と意図、公開対象Pathの適格性、ユーザー領域のaudience、既存承認要求の状態遷移 |
|
||||
| store | Principal/membership/role/groupの有効性を含むDB読込、Objectの全alias検査、所有者権限、epoch/topology、更新transaction、trigger、監査、承認対象とmanifest |
|
||||
| server | セッション・HTTP認証、endpointと対象の解決、legacy/enforcingの選択、ユーザー領域の追加制限、匿名と認証済み経路の分離、表示・エラー応答 |
|
||||
| Mestionora等 | 呼出し元が渡す読み取り判定の適用。検索自体で権限を作らない |
|
||||
|
||||
依存は server/store → schutzaria → 標準ライブラリの文字列等の処理のみ。
|
||||
SchutzariaからDB、HTTP、ファイル、時計、server/storeへ依存しない。
|
||||
認証情報やネットワーク接続を受け取らず、ログに対象本文・ユーザー情報を追加しない。
|
||||
OIDC/LDAP、Cookie/Bearer、共有用credentialの検証方式は変更しない。
|
||||
|
||||
`store.ReadPathPolicy`、`LocalityPolicy`、`UserSpacePolicy`、`UserSpacePathPolicy` は型aliasで維持。
|
||||
従来の公開評価・ユーザー領域評価関数は新実装へ委譲し、承認遷移エラーの同一性も保つ。
|
||||
新しいmigration、既存ACLの再登録、ポリシー設定の初期化は不要。
|
||||
|
||||
## PathとLocalityの評価
|
||||
|
||||
`ReadPathPolicy` は読み取り専用・要求単位のスナップショット。
|
||||
構築時に入力sliceを内部mapへコピーし、外部の変更で既存要求の権限が広がらないようにする。
|
||||
nilとゼロ値は拒否する。新たなglobal cacheやユーザー間の共有cacheは作らない。
|
||||
|
||||
- RoleのPath grantは完全一致、Domain grantまたは既存Path wildcardはDomain内の全Path。
|
||||
- グループscopeはそのPathと配下。`/a` と `/ab` を区別し、`%`・`_` はワイルドカードにしない。
|
||||
- Object grantはこのスナップショットへ含めない。Objectが読めても全aliasの存在を公開しない。
|
||||
- Locality内の該当ユーザー/グループは和集合、祖先と同一Pathの複数Locality制限は積集合。
|
||||
- 一つでもread/writeが拒否なら、下位の肯定grantで回避できない。
|
||||
- Localityの肯定grantで追加できるのはread/write/create/uploadのみ。rename/link/delete/manageは増やさない。
|
||||
- 管理者の回復用制限回避は基礎grantを維持するだけで、新しい権限は作らない。
|
||||
|
||||
`LocalityAccess.Decide` は制限と基礎grantを合成する低水準操作である。
|
||||
nilのLocality制限は「制限なし」としてbasisを返すが、nilのReadPathPolicyは常に拒否する。
|
||||
読込失敗と「制限なし」を混同しない。storeは全読込が成功してからスナップショットを返す。
|
||||
今回、Locality読込エラー時に部分的なReadPathPolicyを返さずnilを返すよう明確化した。
|
||||
|
||||
Path正規化・Domain/Principalの選択・アカウント状態の評価は呼出し元の責務。
|
||||
Schutzariaのコンストラクターに利用者入力のadmin/allフラグを直接渡さない。
|
||||
既存のscope文字列の意味を保つため、この分離では追加のURL decodeやPath正規化を行わない。
|
||||
|
||||
Object取得は引き続きstoreで全ローカルaliasの制限を交差させる。
|
||||
外国Domain側の制限検査はローカル管理者のshortcutより先に行い、独立したObject grantで
|
||||
元Domainの制限を迂回させない。正本やPathの更新triggerも既存のまま残す。
|
||||
|
||||
## 権限プロファイル
|
||||
|
||||
| プロファイル | 許可するcapability |
|
||||
| --- | --- |
|
||||
| read | read |
|
||||
| read_write_once | read、create、upload |
|
||||
| read_write | read、create、write、upload、rename、link |
|
||||
| upload_only | upload |
|
||||
|
||||
どのプロファイルもdeleteや管理権限を暗黙に追加しない。
|
||||
read_write_onceの「未存在対象のみ」は、更新するtransactionでの存在確認と組み合わせて成立する。
|
||||
プロファイル判定単独で、既存文書を上書きできないことを保証するわけではない。
|
||||
Principalのreadonly・停止やmembership/groupの失効は、従来のDB読込で先に適用する。
|
||||
|
||||
## 公開設定と実際の匿名公開
|
||||
|
||||
`EvaluateLocalityPublication` はDomainから下位への、検証済みの順序付きchainを受け取る。
|
||||
Domainのpublicは公開を許す上限であり、それだけではPageを公開しない。
|
||||
祖先のauthenticated_aclを下位のpublicで解除できず、不明なpolicyは拒否する。
|
||||
既存互換として空chainは `(allows=true, published=false)` の中立値を返す。
|
||||
呼出し側は実在するDomainと階層を解決し、allowsだけを匿名アクセス許可に使わない。
|
||||
|
||||
`PublicSemanticPath` は予約名前空間・不正なPathの除外だけを担当する。
|
||||
これがtrueでも、内容の読取権限、alias、現行Revision、hash、公開manifest、
|
||||
governance/topology versionの検証は省略できない。
|
||||
匿名要求は既存の公開経路を通し、無効な認証情報を匿名へ降格させない。
|
||||
|
||||
既存の[自動公開](../automatic-publication.md)は明示的なStreet/Spot設定に限る。
|
||||
上位required、設定時のpublisherの現在の権限、固定したPath境界、公開範囲の確認は
|
||||
storeのtransactionに残す。今回の分離で自動公開の既定値を変えたり、旧記事を新たに公開しない。
|
||||
|
||||
ユーザー領域はrootと配下の設定が独立しており、rootのprivateを全配下のprivateへ読み替えない。
|
||||
配下overrideはさらに狭くするだけで、親のprivateを子のpublicで再公開できない。
|
||||
プロフィール・avatar・管理Path、所有者とDomain管理者の扱いは既存の呼出し元で維持する。
|
||||
不明なvisibilityの入力検証とDomainの公開上限は保存側で行う。
|
||||
|
||||
## 承認と共有の範囲
|
||||
|
||||
`ApprovalNextState` は現在のpending状態、generation一致、既知のdecisionだけを評価する。
|
||||
changes_requestedは従来どおりrejectedへ遷移する。ここでapprovedを返しても、
|
||||
公開manifestを作成したり、reviewer権限を付与したりしない。
|
||||
要求UUID・Domainの限定、認可、更新transactionとCAS、監査・Inboxは既存側の責務とする。
|
||||
|
||||
[承認ワークフロー](../publication-approval-inbox.md)の上位requiredの継承、reviewerの委譲制約、
|
||||
定足数、自己承認の禁止、期限と現行sourceの再検証、承認と公開確定の接続には未完了部分がある。
|
||||
状態遷移の抽出を、それらの実装完了や本番利用の許可とは扱わない。
|
||||
共有リンクのpurpose・期限・失効・対象の検証も今回新たに有効化・省略しない。
|
||||
|
||||
## 予算と一貫性の残件
|
||||
|
||||
既存の読み取りgrant最大4,096件、Locality制限最大4,096件、Object alias最大10,000件、
|
||||
ユーザー領域override最大256件を維持する。上限超過やDBエラーは拒否し、途中までの許可一覧を使わない。
|
||||
評価コアはDBの件数を増やさず、Path評価も保存されたancestor境界に対して行う。
|
||||
|
||||
不変の要求内スナップショットは、DB上の全権限情報を単一時点で読み込んだ保証ではない。
|
||||
`LoadReadPathPolicy`の通常DB経路はgrantとLocalityを別queryで読む。
|
||||
更新処理や匿名公開側にあるtransactionを、この分離で取り除かない。
|
||||
|
||||
- [ ] 権限・アカウント状態・対象更新を同一transaction/versionで固定する経路を拡充する。
|
||||
- [ ] ユーザー領域の遅延DB読込を有界の事前読込へ整理する。Mestionoraの認可callbackで別接続を必要とする制約は残る。
|
||||
- [ ] ReadPathPolicy全体の一貫した読込snapshotとcontext予算、group権限列挙の上限を設計する。
|
||||
- [ ] 自動公開の上位requiredを含む評価、所有者の委譲範囲、承認要求の期限・定足数・現行sourceの再検証を次の分離単位として整理する。
|
||||
- [ ] 説明可能な権限総覧を追加する。付与元・拒否元は閲覧者の権限内でのみ開示する。
|
||||
- [ ] 保護されたPathの粗い更新禁止triggerを、権限影響確認付きの原子的移動・mergeへ置き換える。
|
||||
- [ ] 共有リンクとCampus間ポリシー継承を、purpose・version・失効・対象束縛を持つ別契約として完成させる。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
コアでは親子のread/write・基礎grant・肯定grantの組み合わせ、同一Pathの複数制限、
|
||||
文字列境界、snapshotのコピーと並行参照、公開上限、予約Path、ユーザー領域の絞り込み、
|
||||
承認状態・generationを検証する。型alias・JSON・エラー同一性と読込失敗の拒否も確認する。
|
||||
既存の匿名ナビゲーション、公開失効、グループ継承失効、governance、Object/Path認可の試験を維持する。
|
||||
|
||||
結果は [コンポーネント検証記録](component-names.md#検証記録) に記録する。
|
||||
一時DBと合成データで検証し、本番ACLの変更や外部カレンダーへのアクセスは行わない。
|
||||
ソース変更・テストと、commit・push・本番反映は別段階とする。
|
||||
@@ -0,0 +1,104 @@
|
||||
# Seheweit のリソース収集と履歴契約
|
||||
|
||||
2026-11-01、リソース収集と履歴の期間・保持ルールを `internal/seheweit` に初期分離した。
|
||||
現在値APIとバックグラウンド監視は同じ収集実装を使う。Seheweitは観測を担当し、
|
||||
ジョブの実行制御・認可・DBトランザクション・表示は呼出し元に残す。
|
||||
これで採用した8部品の初期分離が揃うが、各部品の後続機能が完了したことは意味しない。
|
||||
[コンポーネント命名](component-names.md) と [システム拡張](../system-extensions.md) を併読する。
|
||||
|
||||
## 責務と接続
|
||||
|
||||
| 部品 | 責務 |
|
||||
| --- | --- |
|
||||
| `seheweit.Collect` | Go runtime、load average、プロセスI/O、Document Rootの容量を型付きSnapshotへ収集 |
|
||||
| `seheweit.ParseProcessIO` | 実ストレージ読み書きの累積値と、プロセス単位の識別子・取得可否 |
|
||||
| `seheweit.Window` / `RetentionCutoff` | 期間・bucket幅・保持境界。SQLやDB接続は持たない |
|
||||
| server | 管理権限の検査、キュー状態の読込、実行中worker数、HTTP応答、監視handlerの登録 |
|
||||
| store | 既存SQLiteへの保存・期限切れ削除・履歴query。schemaの所有は移さない |
|
||||
| Dregarnuhr | 監視イベントの実行時刻・claim・worker制御。観測結果から仕事を勝手に停止しない |
|
||||
| 設定画面 | ライブ値・履歴グラフ・実行中ジョブの表示、I/O差分速度の計算 |
|
||||
|
||||
server/store → seheweit の一方向依存とする。Seheweitからserver/store/DBは参照しない。
|
||||
文書内容・認証情報・ジョブpayload・外部カレンダーを読まない。
|
||||
ネットワーク接続、shell、ディレクトリ再帰走査、独自の定期loopは追加しない。
|
||||
Queueは呼出し元から渡す観測値だけであり、停止・再開・再試行のコールバックではない。
|
||||
|
||||
## 収集値と互換性
|
||||
|
||||
`Snapshot` のJSONは既存の `timestamp_ms`、`io`、`cpu`、`memory`、`storage`、`queue` を維持する。
|
||||
従来のmapを型付きstructへ置換し、背景保存時のtimestamp型assertionをなくす。
|
||||
旧 `processIOCounters` はalias、parserは委譲とし、取得ロジックを二重に持たない。
|
||||
|
||||
| 観測値 | 意味と制限 |
|
||||
| --- | --- |
|
||||
| CPU | Go runtimeの論理CPU数と `/proc/loadavg` の先頭3値。CPU使用率やcgroup上限ではない |
|
||||
| メモリ | Go heap、Go system bytes、GC回数、goroutine数。RSSやホスト全体の使用量ではない |
|
||||
| 容量 | Document Rootに対するStatfs。使用量は従来のtotal−Bavailで、予約領域も含む |
|
||||
| I/O | `/proc/self/io` のread_bytes/write_bytes。rchar/wcharやデバイスIOPSとは別 |
|
||||
| キュー | queued/running件数、プロセス内active worker数、paused。履歴ジョブ全件は取得しない |
|
||||
|
||||
procファイルの読込は各16KiBまで。超過・読込失敗時は部分データを採用しない。
|
||||
Statfsの失敗、非正のblock size、BavailがBlocksを上回る値、乗算overflowは容量0へ落とす。
|
||||
符号なし減算で巨大な使用量を作らない。絶対Pathへの解決失敗時も空Pathへ上書きしない。
|
||||
|
||||
I/O取得失敗は `available=false`。プロセスIDはプロセス起動ごとのランダムUUIDを共有し、
|
||||
collectorの呼出しごとには変えない。PID 1の再利用と、同一プロセス内の複数呼出しを区別する。
|
||||
既存のブラウザ計算は、再起動・カウンタ減少・時刻逆転・欠測・JS安全整数超過を速度0にせず欠測にする。
|
||||
並行収集では可変の共有Snapshotを使わない。
|
||||
|
||||
容量失敗時の0、load取得失敗時の空文字、キュー読込失敗時のゼロ値は既存互換のfallbackである。
|
||||
I/O以外の取得失敗を正常値と区別するavailability契約は後続とする。
|
||||
各情報源は順番に採取し、DB・runtime・OSを跨ぐ同一瞬間のsnapshotではない。
|
||||
|
||||
## 背景保存と履歴
|
||||
|
||||
イベントID `builtin.resource.sample`、型 `resource.sample`、既定60秒、許可範囲30〜86400秒、
|
||||
priority 100とmax attempts 1を維持する。設定済みのenabledとintervalは起動時に上書きしない。
|
||||
画面のライブ更新既定1秒と、背景の永続化既定60秒は別の周期である。
|
||||
|
||||
保存は `resource_samples` の既存schemaを使う。job_uuidの一意性で同一jobの重複登録を防ぎ、
|
||||
挿入と7日より古い行の削除を同一transactionに置く。既存行のpayloadをretryで上書きしない。
|
||||
保持境界は今回の採取timestampから7日前。境界と同じtimestampは残す。
|
||||
retryで挿入を無視しても、その採取時刻で清掃する既存動作は維持する。
|
||||
|
||||
`SaveResourceSampleContext` は取消contextをBeginTx・各SQLへ渡す。
|
||||
監視handlerは取消済みなら収集を始めず、保存時もcontextを引き継ぐ。
|
||||
read-only Storeでは保存を拒否する。旧 `SaveResourceSample` はBackground contextで委譲する。
|
||||
清掃失敗時には挿入もrollbackし、半端な成功を返さない。
|
||||
contextはDB待機を中断できるが、実行中のStatfs等を強制停止する仕組みではない。
|
||||
|
||||
履歴APIは `GET /_/api/v1/queue/resources/history?hours=1|24|168` のまま。
|
||||
UIの期間既定1時間と選択の記憶、APIの未指定・不正値時の24時間fallbackは変えない。
|
||||
内部Windowは1〜168時間へ制限し、幅は期間/360か最低1分、epoch基準でbucketを切る。
|
||||
期間両端を含み、最大361点を返す。空履歴は `[]`、retention_daysは7を維持する。
|
||||
|
||||
bucket代表は既存SQLの `MAX(id)`、つまり最後に挿入された行である。
|
||||
時刻の順序が逆転した入力では最大timestampの行とは限らず、平均・最大値・ピークでもない。
|
||||
期間はtimestamp索引で絞るが、361という上限は返却点数であり走査行数の固定上限ではない。
|
||||
現在値GETは収集だけ、履歴GETは読込だけで、どちらも保存や補間を行わない。
|
||||
ブラウザを閉じても背景イベントは止まらず、監視無効化・キュー停止では新規採取を止める。
|
||||
|
||||
## 権限と配置
|
||||
|
||||
既存queue APIの管理権限を維持し、新しい公開endpointやDomain間共有を追加しない。
|
||||
応答は引き続き `Cache-Control: no-store`。リソースはインスタンス全体の情報なので、
|
||||
個々の文書の公開権限とは分けて扱う。URI・設定キー・schema・保存済みJSONの移行は不要。
|
||||
追加コンテナや監視サービス、外部送信先の導入も行わない。
|
||||
|
||||
## 後続TODO
|
||||
|
||||
- [ ] 各情報源のavailability・診断コード・取得時刻を追加し、旧履歴とUIを互換移行する。DB失敗を空キューに見せない。
|
||||
- [ ] foreground多重要求の短時間共有と収集予算を設ける。runtime読込や遅いマウントのStatfsを計測し、画面要求を待たせない。
|
||||
- [ ] キュー状態読込へのcontext伝播と一貫性、観測API専用のinstance_operator権限を整理する。
|
||||
- [ ] 大量履歴の保持清掃を分割し、粒度別rollup・平均/最大/欠測数・容量予算を設計する。返却点数の制限だけで走査負荷は保証しない。
|
||||
- [ ] component/provider別の件数・失敗・待機時間・実行時間を低cardinalityで追加する。共有GoプロセスのCPU/RAMを根拠なく按分しない。
|
||||
- [ ] cgroup、デバイスI/O、外部adapterプロセスを独立scopeで観測する。現在のprocess I/Oと混合しない。
|
||||
- [ ] HAのinstance UUID・boot ID・node別収集・集約を定義する。現行process_idは永続instance identityではない。
|
||||
- [ ] SNMPv3 collectorを任意機能として追加する。接続先・OID許可、秘密管理、timeout、再試行、counter resetを別途検証する。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
合成counter・注入clock・一時DB・localhostのブラウザfixtureで、wire互換、収集失敗、容量の異常値、
|
||||
I/O識別、並行収集、保持境界、idempotence、rollback、取消、read-only拒否、認可、設定保持を検証する。
|
||||
実行記録は [コンポーネント検証記録](component-names.md#検証記録) に記載する。
|
||||
本番DBや取り込み済み外部カレンダーにアクセスせず、commit・push・本番展開は別段階とする。
|
||||
@@ -7,6 +7,11 @@ collaboration, federation, high-availability, content, security, and storage
|
||||
features. It defines extension boundaries, not permission to bypass existing
|
||||
identity or authorization rules.
|
||||
|
||||
Responsibility-based subsystem names are adopted in
|
||||
[Component names and responsibilities](ja/component-names.md). Grammaratur,
|
||||
Dregarnuhr, Geduldh, Mestionora, Ordoschnellic, Schutzaria, Kunstzeal and Seheweit have initial extractions. Naming does not change the contracts below,
|
||||
persisted extension IDs, authorization boundaries or deployment topology.
|
||||
|
||||
## Non-negotiable identity boundaries
|
||||
|
||||
Future features attach to stable identities:
|
||||
@@ -74,17 +79,20 @@ origin allowlist, timeout, and privacy policy.
|
||||
|
||||
### Document Store contract
|
||||
|
||||
The canonical interface is content-addressed and supports:
|
||||
The implemented canonical interface is `geduldh.Store`, with a compatible
|
||||
`documentstore.Store` alias. It is content-addressed and supports:
|
||||
|
||||
```text
|
||||
Stat(sha256)
|
||||
Open(sha256) / ReadAt(sha256, offset, length)
|
||||
PutIfAbsent(expected_sha256, stream)
|
||||
Verify(sha256)
|
||||
DeleteUnreferenced(sha256, retention proof)
|
||||
Stat(ctx, sha256)
|
||||
Open(ctx, sha256) -> Reader / ReaderAt / Seeker / Closer
|
||||
PutIfAbsent(ctx, expected_sha256, size, stream)
|
||||
Verify(ctx, sha256)
|
||||
```
|
||||
|
||||
Filesystem and S3 implementations obey the same contract. Bucket/key URLs are
|
||||
The local implementation and future S3 implementations must obey this contract.
|
||||
`DeleteUnreferenced(sha256, retention proof)` is a separate future GC contract,
|
||||
not a method available to ordinary payload consumers. See [Geduldh](ja/geduldh.md).
|
||||
Bucket/key URLs are
|
||||
placement data and never appear in Revision identity. Metadata databases,
|
||||
credentials, signing keys, sessions, and comments do not belong in this store.
|
||||
|
||||
|
||||
@@ -20,7 +20,8 @@ Revision UUID, and raw payload delivery.
|
||||
|
||||
## Current Adapter Contract
|
||||
|
||||
The server registry in `internal/server/content_adapter.go` describes:
|
||||
The registry in `internal/kunstzeal/adapters.go`, accessed through compatible
|
||||
server types and selection wrappers, describes:
|
||||
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
@@ -42,7 +43,7 @@ The initial registry reserves these stable IDs:
|
||||
| `text` | CodeMirror text | windowed text |
|
||||
| `csv` | bounded table with sticky header | paginated virtualized table |
|
||||
| `excalidraw` | validated interactive canvas + source fallback | canvas + editor action |
|
||||
| `nwdiag` | bounded network diagram projection | static SVG preview + hosted/editor action |
|
||||
| `json` | bounded JSON structure/text projection | indexed structural retrieval |
|
||||
| `archive` | ZIP/RAR/7z/TAR entry table + comic mode | archive directory |
|
||||
| `eml` | decoded headers and body | multipart mail viewer |
|
||||
| `debian-package` | ar/control metadata | package metadata |
|
||||
@@ -57,6 +58,12 @@ These adapters are built in and versioned with Pages Wiki. They are always
|
||||
listed by `GET /_/api/v1/adapter`; they are not configuration records and
|
||||
cannot be deleted by an administrator.
|
||||
|
||||
2026-11-01: adapter selection and existing Kroki execution were initially
|
||||
extracted into [Kunstzeal](ja/kunstzeal.md). Stable IDs/order and source authorization
|
||||
remain unchanged. nwdiag and slide providers are still TODO, not entries in the
|
||||
implemented registry. Kroki redirects are now refused; derived SVG cache writes
|
||||
use atomic replacement. Provider versioning and unified resource controls remain pending.
|
||||
|
||||
## Integration Adapter Plugins
|
||||
|
||||
Additional hosted viewers and editors are Domain-scoped integration adapter
|
||||
@@ -401,6 +408,8 @@ CSV detection uses MIME type or `.csv`. The derived adapter must:
|
||||
|
||||
## nwdiag network diagrams
|
||||
|
||||
Status: design/TODO. No nwdiag parser or built-in adapter is currently registered.
|
||||
|
||||
`nwdiag` is a source/document format, not an instruction to execute arbitrary
|
||||
code. The adapter parses a bounded, version-pinned grammar and produces a
|
||||
static SVG (or PNG) projection. It must reject oversized graphs, recursive
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
Implemented: 2026-09-14.
|
||||
|
||||
2026-11-01: SQLite search/index maintenance and City metadata lookup are extracted
|
||||
into `internal/mestionora`. Store APIs/types remain compatibility facades; HTTP
|
||||
search and suggestions call Mestionora with the existing request read policy.
|
||||
No new index schema or migration is introduced. See [Mestionora's contract](ja/mestionora.md).
|
||||
|
||||
## City-first results and search options
|
||||
|
||||
Search now places matching Quartiers, Streets and Spots above Page/file hits.
|
||||
@@ -114,7 +119,7 @@ Global counts, denied Paths, denied filenames, and denied excerpts are never
|
||||
included in the rendered data. An all-denied candidate set uses the same empty
|
||||
state as an ordinary no-match query.
|
||||
|
||||
All search statements use one read-only SQLite transaction, preserving a
|
||||
Page candidate and excerpt statements use one read-only SQLite transaction, preserving a
|
||||
consistent current Path / latest Revision snapshot. The three candidate streams
|
||||
are:
|
||||
|
||||
@@ -142,7 +147,10 @@ snapshot. `octet_length(body)` counts bytes, not Unicode characters; see
|
||||
Eligible body excerpts are fetched together with one FTS snippet query restricted
|
||||
by those rowids, not the unindexed UUID payload column. Name-only textual
|
||||
summaries use one additional bounded Revision-prefix query. There are no
|
||||
per-result authorization queries or Document-file stat calls. Existing preview
|
||||
Document-file stat calls. The normal Path policy is preloaded; lazy `/u/` policy
|
||||
lookups can still borrow another DB connection during authorization. Do not
|
||||
combine that callback with a single-connection pool until the policy preloading
|
||||
follow-up is implemented. Existing preview
|
||||
cache checks run only for displayed authorized results, without scheduling
|
||||
foreground generation.
|
||||
|
||||
@@ -240,7 +248,7 @@ are local observations, not latency guarantees or authenticated HTTP timings.
|
||||
This feature adds no schema migration or index rebuild.
|
||||
|
||||
```sh
|
||||
go test -race ./internal/server ./internal/store -run '^TestSearch' -count=1
|
||||
go test -race ./internal/mestionora ./internal/server ./internal/store -run '^TestSearch' -count=1
|
||||
PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestSearchResultsChromium$' -count=1
|
||||
# Optional: opens an existing DB with mode=ro and query_only, with no migrations.
|
||||
PAGESWIKI_SEARCH_DIAGNOSTIC_DB=/absolute/path/pages.db go test ./internal/store -run '^TestSearchReadOnlyDatabase$' -count=1 -v
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
# 保存基盤の多様化と運用機能の統合
|
||||
|
||||
状態:詳細設計・段階導入。2026-09-27。
|
||||
本書は [基本設計](arch.md) と [拡張契約](platform-extension-architecture.md) を補完する。
|
||||
各 TODO は実装済みを意味しない。本番 DB・保存先の移行は別途承認する。
|
||||
|
||||
## 1. 優先順位と対象
|
||||
|
||||
先に SQLite / PostgreSQL / MySQL、Redis 等の KV、ローカル / S3 / SSH / NFS / SMB の
|
||||
役割・契約を整える。その上にバックアップ、リリース、CLI、export/import、Web バックアップ、
|
||||
初回「ようこそ」画面を載せる。Web と CLI で別の保存実装を作らない。
|
||||
|
||||
実装順は **保存契約 → 正本の分離 → DB 移植 → 外部 Document → 運用ジョブ → UI**。
|
||||
Redis を RDB の代わりに選ぶ UI や、S3 URL をローカルディレクトリ欄へ指定する方式は採用しない。
|
||||
初期設定が SQLite + ローカルだけでも、単一ノード運用が追加サービスなしで成立すること。
|
||||
|
||||
## 2. 現行実装の監査
|
||||
|
||||
| 箇所 | 現状 | 移植前に必要な変更 |
|
||||
| --- | --- | --- |
|
||||
| `internal/db/db.go` | SQLite 固定、WAL、busy_timeout、NORMAL | 接続プロファイル、durability 設定、driver ごとの検証 |
|
||||
| `internal/db/migrate.go` / `Ensure*Schema` | DDL とデータ移行が分散。core bootstrap の ALTER エラー無視は是正、他の Ensure は継続監査 | 新 migration runner への段階集約と driver 別 DDL |
|
||||
| `internal/store` | `*sql.DB` への直接 SQL。SQLite 固有式が多い | repository ごとの SQL 分離・契約テスト |
|
||||
| `internal/store/document_store.go` | SHA-256 正本と DB body の移行互換 | payload backend の分離、復旧時以外の暗黙再作成の縮小 |
|
||||
| `internal/calendar/repository.go` | 月別 ICS + calendar.json、flock、rename、DB はキャッシュ | mutable canonical repository と条件付き世代更新 |
|
||||
| `DocumentRoot` の利用箇所 | calendar、auth.key の親、preview、import、payload を兼用 | payload / canonical state / secrets / scratch の分離 |
|
||||
| `DocumentPath` の利用箇所 | 外部コマンドへ直接ローカルパス | 期限付き Materialize、容量制限・後処理 |
|
||||
| `data/pageswiki-cli` | Python sqlite3 とローカル Document を直接操作 | online API モードを主経路に、offline repair を明示分離 |
|
||||
|
||||
調査時点で SQLite 固有語(PRAGMA、sqlite_master、rowid、INSERT OR、strftime 等)が
|
||||
テストを除く約 50 ファイルに存在する。接続ドライバだけ追加しても動作しない。
|
||||
「接続できた」と「PagesWiki の全機能を利用できる」をサポート状態として区別する。
|
||||
|
||||
## 3. 正本・派生物・機密情報を分離する
|
||||
|
||||
| 層 | 主なデータ | 保存先 | 消失時の扱い |
|
||||
| --- | --- | --- | --- |
|
||||
| MetadataRepository | UUID、Path、Revision、ACL、ユーザー/グループ、タスク、設定、outbox、確定ジョブ | SQLite / PostgreSQL / MySQL | バックアップから復元が必要 |
|
||||
| DocumentStore | SHA-256 で識別する不変バイト列 | local / S3 / 検証済み mounted filesystem / SFTP | バックアップから復元が必要 |
|
||||
| CanonicalStateRepository | カレンダーのメタ情報、月ごとの ICS 世代、ユーザー設定 | 世代付きファイル正本(local から段階拡張) | バックアップから復元が必要 |
|
||||
| CacheStore | 検索・表示・サジェスト・リソース集計の再生成可能データ | memory / SQL cache / Redis | 正本から再生成 |
|
||||
| SecretStore | auth.key、署名鍵、暗号化鍵、接続資格情報 | secret file / 環境 / 外部 Secret manager | 別権限・暗号化して保全 |
|
||||
| Scratch/Materialization | import 展開、外部ビューア用一時ファイル、生成中 preview | ノードローカルの専用領域 | 破棄して再実行 |
|
||||
|
||||
セッション失効、承認、ジョブ完了、タスクの変更を Redis のみの情報にしない。
|
||||
「Redis の AOF を有効にしたから正本のバックアップを省略できる」とはしない。
|
||||
|
||||
## 4. 共通インターフェース
|
||||
|
||||
### 4.1 不変 Document
|
||||
|
||||
Go 契約は `internal/geduldh.Store`。2026-11-01に既存ローカル実装を
|
||||
[Geduldh](ja/geduldh.md) へ分離し、`internal/documentstore.Store` は同じ型の互換aliasとした。
|
||||
|
||||
```text
|
||||
Stat(ctx, sha256) -> { hash, size }
|
||||
Open(ctx, sha256) -> Reader + ReaderAt + Seeker + Closer
|
||||
PutIfAbsent(ctx, sha256, size, stream)
|
||||
Verify(ctx, sha256)
|
||||
```
|
||||
|
||||
- 保存キーは既存互換の `sha256/<先頭2文字>/<64桁hash>`。Path やファイル名ではない。
|
||||
- サイズとハッシュの検証前に、完全な Document として読める状態にしない。
|
||||
- 不変 payload を先に永続化し、その後に参照する DB transaction を commit する。
|
||||
- DB rollback で未参照 blob が残るのは許容するが、存在しない blob の参照確定はしない。
|
||||
- 読み取りの Open/Seek/ReadAt は大容量全体の先読みをしない。remote range は上限・期限付き。
|
||||
- ETag は HTTP の条件付き取得に使い、SHA-256 とは別フィールドとする。
|
||||
- timeout、not found、破損、認証失敗、容量不足を区別する。エラー時に local へ勝手に書かない。
|
||||
- 通常の Put/Read インターフェースに Delete を含めない。GC は参照 snapshot、保持、backup pin、
|
||||
進行中 upload の保護を持つ専用経路から実施する。
|
||||
- local path を返すことを全 backend の必須機能にしない。
|
||||
|
||||
接続済みの範囲はローカルの保存・通常読み取り・サイズ取得・部分読み取りと、
|
||||
外部ツール用 Materialize。HTTP の主要な本文配信・部分取得には Request.Context を接続した。
|
||||
remote backend、従来の Revision 本文取得/保存 API 全体への context 伝搬は未接続。
|
||||
既存の DB body fallback は互換のため維持する。起動時 backfill は保存先ごとの進捗を記録し、
|
||||
完了済みの保存先では revisions の走査を省略する(後述)。
|
||||
|
||||
### 4.2 可変正本
|
||||
|
||||
カレンダーはファイル正本を維持し、月ごとの不変 ICS 世代を作成してから
|
||||
calendar manifest を `CompareAndSwap(expectedVersion, nextManifest)` で更新する。
|
||||
DB のカレンダー cache は manifest version に従って再生成する。
|
||||
S3 で POSIX rename/flock を模倣せず、条件付き manifest 更新を使う。
|
||||
カレンダーの競合は明示的に返し、古いキャッシュで正本を上書きしない。
|
||||
世代の削除はバックアップ pin と参照中 version を考慮する。
|
||||
|
||||
### 4.3 外部ツールへの受け渡し
|
||||
|
||||
`Materialize(ctx, hash, quota) -> localPath, cleanup` を別サービスにする。
|
||||
archive/PDF/動画/PE/DEB 等のローカルパス必須ツールはこれを利用する。
|
||||
SHA-256 検証、容量上限、同一 blob の取得集約、参照中の退避禁止、期限、キャンセルを持つ。
|
||||
remote Object URL や presigned URL を無条件にツールへ渡さない。
|
||||
ZIP の範囲参照で足りる処理は Materialize せず ReaderAt を使う。
|
||||
|
||||
実装は `internal/geduldh.Materializer`(旧 `internal/documentstore.Materializer` は互換alias)と
|
||||
`Store.MaterializeDocument(ctx, hash, maxBytes)`。同じ Store 内で同じ hash の取得をまとめ、
|
||||
利用者ごとの lease で参照中のコピーを保持する。待機者の一人がキャンセルしても他の待機者の
|
||||
取得は中断しない。全員がキャンセルしたら共有取得を中断し、最後の lease の Close で削除する。
|
||||
取得・検証に成功するまで外部コマンドへパスを渡さない。コピーは 0700 の専用一時ディレクトリに
|
||||
0400 で作り、正本への hardlink は渡さない(外部ツールが誤って正本を変更するのを防ぐ)。
|
||||
|
||||
現時点の固定上限(将来 deployment profile に移す):
|
||||
|
||||
- Store ごとに同時取得 2 件、取得待ち/利用中を含め 64 件、予約容量合計 2 GiB。
|
||||
- 共有取得の期限は 2 分。呼び出し元の request/preview/metadata の期限でも待機を中断する。
|
||||
- metadata / PDF は 512 MiB、動画 / 非 ZIP 展開は 1 GiB、Excalidraw は 16 MiB。
|
||||
- 保存先は `TMPDIR`(未設定時は OS の一時領域)。DocumentRoot やネットワークマウントを使わず、
|
||||
ノードローカルの十分な空き容量を持つ領域を指定する。tmpfs の場合はメモリ消費になる。
|
||||
- 削除失敗時には予約容量を解放済みと見なさない。プロセス強制終了で残った一時ファイルの
|
||||
安全な回収とリソース監視へのメトリクス接続は残件。
|
||||
|
||||
画像・ZIP サムネイル、ZIP 内の個別ファイル配信は Reader/ReaderAt を直接利用する。
|
||||
ZIP の個別配信は互換 DB body の全体 hydration をしない。非 ZIP / PDF / 動画などは、
|
||||
ローカル正本でも検証付き一時コピーを作るため追加 I/O が発生する。永続キャッシュや
|
||||
reflink 最適化は容量/失効/破損検出の契約を保った上で別途導入する。
|
||||
|
||||
## 5. RDB の対応設計
|
||||
|
||||
### 接続と migration
|
||||
|
||||
- 接続プロファイルはインスタンス管理で指定。Domain 管理者に DSN を公開しない。
|
||||
- driver ごとに host/port/database/TLS/secret reference/pool/timeout を持つ。
|
||||
- 未対応 driver は起動前に明示エラー。SQLite にフォールバックしない。
|
||||
- SQLite を既存互換で維持し、まず PostgreSQL、次いで MySQL 8.4 LTS / InnoDB を対象にする。
|
||||
PostgreSQL の最低対応版は CI matrix の確定時に明示する。MariaDB を MySQL と同一扱いしない。
|
||||
- 起動時 Ping、schema version、driver と schema の一致を検証する。
|
||||
- migration は driver/version/checksum/applied_at の履歴と排他的ロックを持つ。
|
||||
起動ごとの分散 Ensure* を段階的に集約し、未知の DDL エラーを無視しない。
|
||||
- MySQL の DDL は暗黙 commit を前提に、再開可能な移行段階を記録する。
|
||||
migration rollback を DB transaction だけで保証しない。
|
||||
|
||||
#### 初段の migration runner(実装済み範囲)
|
||||
|
||||
`internal/db.ApplySQLiteMigrations` は component ごとに連続した version、name、SQL の
|
||||
SHA-256 checksum、適用時刻を `schema_migration_steps` に記録する。
|
||||
専用 DB connection の `BEGIN IMMEDIATE` で他プロセスとの適用を直列化し、
|
||||
DDL と履歴を一つの transaction で commit する。失敗時は rollback し、transaction の
|
||||
状態が確定できなかった connection を pool へ戻さない。
|
||||
適用済み SQL の変更、version の欠落、バイナリより新しい移行履歴は起動時にエラーにする。
|
||||
適用済みの手順は編集せず、新しい version を追加する。
|
||||
|
||||
移行済みの利用先は Document backfill の進捗テーブルと、下表の 6 領域。
|
||||
既存の `schema_migrations` / `revision_metadata_v1` は変更せず維持する。
|
||||
core bootstrap の列追加は PRAGMA で存在確認し、未知の ALTER エラーを無視しない。
|
||||
古い revision の hash 計算は 128 件ずつ UUID を選択し、本文は一度に一件だけ読み込む。
|
||||
既存のすべての Ensure*Schema が新 runner へ移行したわけではなく、
|
||||
PostgreSQL/MySQL 対応や schema drift の完全な検査を意味しない。
|
||||
|
||||
| component | 対象 | 旧版から不足時に追加する列 |
|
||||
| --- | --- | --- |
|
||||
| `projection-metadata` | `projection_metadata` | なし |
|
||||
| `resource-history` | `resource_samples` | なし |
|
||||
| `broadcasts` | `broadcasts` | なし |
|
||||
| `browser-navigation` | `browser_navigation_links` | `is_directory` |
|
||||
| `adapter-sessions` | `adapter_sessions` | `root_path`, `principal_uuid` |
|
||||
| `imports` | import session/item/journal/City 対応の 5 テーブル | `import_journal.completed` |
|
||||
| `event-jobs` | jobs/definitions/logs/log policies/log buckets/queue settings | `event_uuid`, `priority`, `max_attempts`, `started_at_ms`, `finished_at_ms`, `cancel_requested` |
|
||||
| `document-store` | 本文移行の進捗 `document_backfills` | なし(v2 で契約を検証) |
|
||||
|
||||
定義は `internal/store/schema_modules.go` / `schema_jobs.go` と
|
||||
`document_backfill.go` に置き、診断時には同じ定義を参照する。既存 `Ensure*Schema` メソッドは
|
||||
互換ラッパーとして残し、テーブルの再作成・行の削除はしない。
|
||||
条件付き列追加は存在確認と ALTER を同じ migration transaction 内で実施する。
|
||||
追加列の宣言と schema assertion も checksum 対象とする。旧式定義の checksum は、
|
||||
新しい空フィールドを JSON へ出さないことで維持する。
|
||||
|
||||
component の最新 version に、現在のスキーマ全体に必要な assertions を記載する。
|
||||
適用済みでも毎回検査する。必要な列、一意性の対象列、インデックスの所属と列順、
|
||||
追加列の型/NOT NULL/default、adapter session の部分 UNIQUE 条件を確認する。
|
||||
すべての列の型・CHECK・照合順序・外部キーまでを網羅する汎用 diff ではない。
|
||||
後続 version が意図的に列を削除する場合に備え、過去 version の assertions は最新の契約で
|
||||
置き換える(過去の定義と checksum は改変しない)。
|
||||
|
||||
初回採用時は既存の行を保持したまま不足する既知の列・索引を作成する。
|
||||
採用後に schema が欠落/変更した場合は自動再作成せず、起動を止めて調査対象とする。
|
||||
event_jobs 用の検索索引は projection の初期化から Event Jobs の初期化へ移し、
|
||||
派生キャッシュからジョブ正本のスキーマへ向かう不要な依存を取り除いた。
|
||||
イベントキューは、既知の不足列を追加する v1 と、列を使う索引・周辺テーブルを採用する v2 に分ける。
|
||||
実行中ジョブの再キューイングは通常起動の状態復旧処理として分離し、migration runner や診断から呼ばない。
|
||||
|
||||
`pageswiki schema status|check` は `mode=ro` / `query_only` 接続で、管理対象の履歴/checksum と
|
||||
最新 schema assertions を検査する。読み取り transaction の snapshot から判断し、
|
||||
未作成 DB の初期化・鍵生成・本文移行・ジョブ復旧を実行しない。
|
||||
`check` の終了コードは current=0 / pending=2 / blocked・unknown・実行エラー=1。
|
||||
未適用 DDL は実行せず計画だけ表示するため、pending の成功を保証する dry-run ではない。
|
||||
未移行の従来 schema 処理は診断範囲外として出力し、起動リハーサルを別途要求する。
|
||||
反映前の確認項目は [保存基盤のスキーマ変更・反映手順](../operations/storage-schema-rollout.md) を参照。
|
||||
|
||||
#### 再開可能な Document backfill(実装済み範囲)
|
||||
|
||||
- `Store.BackfillDocuments(ctx, batchSize)` が一回最大 128 件の UUID/hash を取得する。
|
||||
本文は不足 blob の一件分だけ読む。単一の巨大な legacy 本文のメモリ上限は別の課題である。
|
||||
- 保存先の `.document-store-id` と DB の `document_backfills` を対応させ、
|
||||
UUID cursor・処理数・完了状態・更新時刻を記録する。UUID cursor は VACUUM で変わらない。
|
||||
- payload の検証・永続化後にバッチの checkpoint を更新する。失敗時は未完了バッチを再実行する。
|
||||
保存先単位のファイルロックで二重実行を防ぎ、ロック待ちも context のキャンセルを受け付ける。
|
||||
- 正本が既にある場合はその SHA-256 を検証し、古い/空の DB body は使わない。
|
||||
破損した正本は互換キャッシュで上書きせず、明示エラーにする。
|
||||
- 保存先を空のディレクトリへ差し替えると identity が変わり、以前の完了状態を流用しない。
|
||||
既存正本が一部欠落した場合の検出は verify/repair の役割であり、通常起動で全件監査しない。
|
||||
- DB-only の旧 writer/importer を止めた保守状態で実施する。通常の Page 保存は
|
||||
Document 永続化が先行するため、移行 cursor より前の UUID が増えても不足しない。
|
||||
- 初回移行は引き続き起動前に完了させる。完了済みの通常起動では revisions を問い合わせない。
|
||||
非同期化する際は未移行 payload の配信・readiness・保守モードの契約を先に整備する。
|
||||
- backup/restore は `.document-store-id` も含めて保存先を保全する。これは資格情報ではない。
|
||||
identity が欠落した旧バックアップは新しい保存先と扱い、再検証・移行する。
|
||||
|
||||
### SQL 差異と対策
|
||||
|
||||
| 差異 | 対策 |
|
||||
| --- | --- |
|
||||
| `?` / `$1` | repository の dialect/query builder で生成。文字列の単純置換はしない |
|
||||
| PRAGMA / sqlite_master | schema inspector を backend ごとに分離 |
|
||||
| `rowid` による順序 | 明示 sequence または `(created_at_ms, uuid)` 等の仕様化した順序へ移行 |
|
||||
| INSERT OR IGNORE/REPLACE / UPSERT | conflict target と更新列を明示。REPLACE の delete+insert を模倣しない |
|
||||
| 時刻関数 | 保存時刻はアプリ生成 UTC epoch ms / BIGINT、必要な DB 時刻用途は別途定義 |
|
||||
| LIKE / 照合順序 | Path/UUID/ハッシュの大小文字・正規化規則を共有。DB の既定照合に依存しない |
|
||||
| TEXT を含む複合 UNIQUE | MySQL の索引長を検討。長い Path は正規化 UTF-8 の digest を索引候補にし、原文比較で衝突検出 |
|
||||
| FTS / 日本語 / ranking | SearchIndex 契約へ分離。DB ごとの全文検索結果が完全一致すると仮定しない |
|
||||
| エラーコード | unique / FK / deadlock / serialization / busy を共通分類 |
|
||||
| job claim / pagination | SQLite single writer、PostgreSQL/MySQL row lock + claim token、安定した keyset cursor |
|
||||
|
||||
SQL を全機能一度に書き換えず、スキーマ → Object/Path/Revision/Asset → 認証/ACL →
|
||||
タスク/CalDAV → event/outbox/通知 → City/検索/管理の順に契約テストを追加する。
|
||||
全 repository の通過前は PostgreSQL/MySQL を本番選択可能と表示しない。
|
||||
外部 RDB を導入しただけでは HA ではない。job lease/fencing、可変正本、鍵共有が別の条件。
|
||||
|
||||
### DB 移行
|
||||
|
||||
既存データを上書きするのではなく、新規 target DB へ schema 作成 → snapshot import →
|
||||
UUID/件数/参照整合性/ACL検証 → 停止時間内の差分反映 → 接続先切替を行う。
|
||||
最初は書き込み停止で一貫性を確保し、オンライン dual-write は採用しない。
|
||||
移行元は保持。新 DB に書き込み開始後の単純な DSN 戻しはデータ喪失となるため禁止する。
|
||||
|
||||
## 6. Redis / KV
|
||||
|
||||
初期用途は TTL 付き共有キャッシュ、短時間の同一処理集約、通知配信の補助。
|
||||
永続ジョブ・通知 Inbox・失効情報・監査 outbox は RDB 側を正本とする。
|
||||
|
||||
- key は instance / domain / provider / schema / policy epoch を含める。
|
||||
- 認可を含む表示 cache は principal と権限 version を分離し、古い ACL で許可しない。
|
||||
- 接続 pool、TLS、ACL、タイムアウト、value 上限、TTL jitter、hit/miss/eviction を持つ。
|
||||
- cache 障害は安全な DB 参照へ限定的に縮退し、全リクエストの stampede を防止する。
|
||||
- Redis Pub/Sub は配送保証に使わない。通知の取りこぼしは DB Inbox から再取得する。
|
||||
- 分散ロックだけで正本の排他を保証しない。多ノード更新は DB の fencing token を検証する。
|
||||
- 永続化方式 RDB/AOF の運用と、再生成可能 cache のバックアップ不要性を区別する。
|
||||
|
||||
## 7. ファイルストア別の対応
|
||||
|
||||
| backend | 導入方法 | 必須条件・制限 |
|
||||
| --- | --- | --- |
|
||||
| local | 現在の data/documents と互換 | fsync、原子的な no-replace publish、ルート内アクセス |
|
||||
| S3 compatible | SDK adapter、bucket/prefix/region/endpoint | 条件付き作成、range、checksum、multipart 中断回収、TLS |
|
||||
| over SSH | 原則 SFTP adapter。SSHFS mount は別の検証対象 | known_hosts 固定、専用 user/root、host-key 変更を拒否、shell コマンド文字列禁止 |
|
||||
| NFS | OS/Compose で管理者が mount、アプリはパスを利用 | protocol/mount/lock/durability を環境別認証、切断時に失敗させる |
|
||||
| SMB | 同上、CIFS mount または後続 adapter | case-sensitive key 契約、rename/link/flush の実環境試験 |
|
||||
|
||||
### S3
|
||||
|
||||
SDK の標準 credential chain と secret reference を使い、本文や manifest に資格情報を埋め込まない。
|
||||
bucket は private を既定とし、公開 URL と物理キーを分離する。
|
||||
`If-None-Match: *` による作成、既存時の checksum 検証、`412` と通信障害の区別が必要。
|
||||
S3 ETag は Document SHA-256 と見なさない。互換製品ごとに conditional/multipart/checksum を検証する。
|
||||
upload は bounded spool または検証付き streaming とし、未検証データを final key へ公開しない。
|
||||
LIST をバックアップの整合性境界にせず、DB snapshot の参照 manifest で必要な hash を列挙する。
|
||||
障害中は書き込みを失敗させ、プロセスごとのローカル正本へ分岐させない。
|
||||
|
||||
### ネットワーク filesystem / SSH
|
||||
|
||||
SQLite の DB/WAL/SHM を NFS・SMB・SSHFS に置くことは禁止する。
|
||||
共有可能にするのは、契約テストで検証した Document/正本 backend に限る。
|
||||
アプリに mount 権限や任意 SSH コマンド実行権限を与えない。
|
||||
mount が消えた際に空のローカル mountpoint へ書くことを防ぐ sentinel / device / mount-id 検証が必要。
|
||||
context のキャンセルだけで、停止した NFS syscall を必ず中断できるとは扱わない。
|
||||
独立 worker、I/O 上限、circuit breaker、管理者向け degraded 状態を設計する。
|
||||
hard-link/no-replace や directory fsync のない共有領域を local backend として認定しない。
|
||||
|
||||
## 8. バックアップと export の区別
|
||||
|
||||
| 操作 | 目的 | 含めるもの |
|
||||
| --- | --- | --- |
|
||||
| backup/restore | 同一インスタンスの災害復旧 | DB snapshot、Document、カレンダー正本、設定、必要な鍵の暗号化保全 |
|
||||
| export/import | Domain/Path/プロジェクトの移動・交換 | 許可範囲の内容・revision・asset依存・選択したメタ情報。秘密は既定で除外 |
|
||||
| release/deploy | 実行コードの更新 | SemVer、Git commit、イメージ digest、schema互換条件。ユーザーデータとは別 |
|
||||
|
||||
バックアップ manifest は format_version、instance ID、アプリ SemVer、schema version、
|
||||
各 DB snapshot、正本 generation、Document の hash/size、暗号化情報、完了状態を持つ。
|
||||
全生成物を検証してから complete marker を発行する。部分生成を復旧可能と表示しない。
|
||||
|
||||
最初は全書き込み元(Web/API/CalDAV/CLI/同期 worker)を止める maintenance barrier を使い、
|
||||
GC を pin して DB と可変正本を snapshot する。不変 blob のコピーはその参照集合で行う。
|
||||
「DB はコピーしたが calendar.json は後から別の時点でコピーした」を許さない。
|
||||
オンライン化は revision/outbox watermarks と snapshot pin 実装後の段階とする。
|
||||
|
||||
- SQLite:online backup API / 検証済み snapshot。稼働中の pages.db 単独 rsync はしない。
|
||||
- PostgreSQL:論理 dump と必要に応じた physical backup/PITR を別モードにする。
|
||||
- MySQL:InnoDB の consistent snapshot と migration/DDL 排他を確認する。
|
||||
- Redis:再生成可能 cache は除外。独自永続用途を追加したら manifest へ明示する。
|
||||
- 鍵・接続資格情報:別保護領域へ暗号化。復元に必要な鍵を同じ暗号化アーカイブ内だけに入れない。
|
||||
- restore:新規領域へ展開・検証・dry-run、互換性確認、切替。通常 Web から稼働 DB を上書きしない。
|
||||
|
||||
保持期間、容量、転送帯域、暗号化、定期実行、リモート複製、リストア訓練を独立設定にする。
|
||||
バックアップ削除は全世代を単純削除せず、増分依存と稼働リリースの復旧条件を確認する。
|
||||
|
||||
## 9. 手動スクリプト・CLI・Web の共通化
|
||||
|
||||
将来の `pageswiki-admin` / `pageswiki` 運用サブコマンドに処理を集約し、
|
||||
編集可能な shell script は環境変数・設定ファイル・コマンドの薄い組み合わせにする。
|
||||
スクリプトから直接各 DB のテーブルへ別々に書く方式は増やさない。
|
||||
|
||||
候補コマンド(**まだ未実装**):
|
||||
|
||||
```text
|
||||
storage status / verify / migrate --plan / migrate --apply
|
||||
backup create / list / verify / restore --plan / restore --apply
|
||||
export --domain … --path … --format pageswiki-bundle
|
||||
import --file … --plan / import --file … --apply
|
||||
release verify / deploy --version vX.Y.Z --plan / deploy --apply
|
||||
```
|
||||
|
||||
online CLI は共通 API と権限・監査・event queue を通す。offline は保守モード専用で、
|
||||
直接 DB を開く現行 Python CLI は当面の互換/repair 経路として残す。
|
||||
import はサイズ・件数・展開率上限、zip-slip、symlink/hardlink を検証し、試行計画を先に表示する。
|
||||
UUID保持/新規採番、Path衝突、ACL継承、Cityサジェスト、部分失敗の再試行を明示選択にする。
|
||||
|
||||
Web バックアップは instance/campus 管理者向け。Domain export 権限と混同しない。
|
||||
設定パネルには履歴・状態・検証結果をコンパクトに表示し、作成条件はダイアログに収める。
|
||||
作成は既存 scheduler の `backup.create` / `backup.verify` event としてキューへ入れる。
|
||||
API は `/_/api/v1/backup/`、ジョブ状態は既存 `/_/api/v1/event/` / `queue` を利用する案とする。
|
||||
ダウンロードにも現在の認可、有効期限、監査、no-store を適用する。秘密付き archive を公開しない。
|
||||
Web から任意の保存先パス・任意コマンド・任意外部 URL を指定できるようにしない。
|
||||
|
||||
release script は v0.1.0 で整備した digest 昇格を再利用する。
|
||||
deploy は backup 検証 → image pull → maintenance/migration → health check → 切替。
|
||||
DB migration 後の旧イメージへの自動 rollback は互換性が明示された場合だけ許可する。
|
||||
|
||||
## 10. 初回ようこそ画面
|
||||
|
||||
状態は `uninitialized → claimed → configuring → validating → ready`。
|
||||
既存データのあるインスタンスには表示せず、DB 到達不能を未初期化と判定しない。
|
||||
初期 DB 未作成でも使える bootstrap 設定は local protected file / secret mount に置く。
|
||||
|
||||
1. ホスト側で生成した短寿命・一回限りの setup token で管理者が claim(競合時は一人だけ成功)。
|
||||
2. 単独 / controller / 外部 Campus 管理モードを選択。外部管理の名前等は従来どおり継承する。
|
||||
3. Metadata DB、Document backend、canonical state、任意 Redis を設定。
|
||||
4. TLS・資格情報・必要な保存操作を管理者指定 backend 内の専用 probe 領域で検証。
|
||||
5. 最初の管理者、言語・タイムゾーン、FQDN、バックアップ先/保持方針を確認。
|
||||
6. 設定を原子的に保存し migration/初期化を実行。成功後 setup token を失効し ready にする。
|
||||
|
||||
公開ネットワークで最初にアクセスした人を無条件に管理者にしない。
|
||||
setup 完了後は token 再利用不可。機密欄の再表示・ログ出力をしない。
|
||||
外部 Campus 自動参加など既存の非対話起動を維持する。
|
||||
|
||||
## 11. 段階別 TODO と受入条件
|
||||
|
||||
### S0:契約とローカル保存の是正
|
||||
|
||||
- [x] 不変 Document Store interface と既存キー規則を実装。
|
||||
- [x] local の streaming 検証、no-replace publish、directory fsync、root 内アクセスを実装。
|
||||
- [x] 現行 Store の保存・読み取り・サイズ・部分読み取りを接続。
|
||||
- [x] 並行書き込み、既存破損、サイズ/hash不一致、キャンセル、パス逸脱をテスト。
|
||||
- [ ] backup inventory / canonical state / secret / scratch の設定と寿命をコード上で分離。
|
||||
|
||||
### S1:移植準備
|
||||
|
||||
- [x] Open/Size/Window の context 付き API と主要 HTTP 配信への伝搬。
|
||||
- [x] archive/preview/一覧サイズの直ファイルアクセスを置換し Materialize を導入。
|
||||
- [x] ZIP 個別配信・画像/ZIP サムネイルを Reader/ReaderAt ベースへ変更。
|
||||
- [x] 共有取得、キャンセル、容量/件数制限、破損、最終利用後の削除をテスト。
|
||||
- [ ] 従来の Revision hydration/保存、一覧 DB クエリを含む全 payload API へ context を伝搬。
|
||||
- [ ] Document の byte size を DB のメタデータとして確定し、外部 backend で一覧ごとの
|
||||
Stat/HEAD が N+1 呼び出しにならないようにする(現状は既存のサイズ補完動作を維持)。
|
||||
- [ ] Materialize の固定上限を設定化し、クラッシュ残骸の安全な回収・メトリクスを接続。
|
||||
- [x] Document backfill の保存先 identity、UUID cursor、バッチ checkpoint、完了後の起動時走査省略。
|
||||
- [x] SQLite migration runner の version/checksum/排他/rollback と旧 hash 移行のメモリ使用改善。
|
||||
- [x] projection/resource/broadcast/browser-navigation/adapter-session/import の schema 定義集約、
|
||||
既存データを保持した採用、条件付き列追加、schema assertion の契約テスト。
|
||||
- [x] event queue/log schema の管理、起動時ジョブ復旧と schema 処理の分離。
|
||||
- [x] 読み取り専用 `schema status|check` CLI(JSON/終了コード/履歴・契約検査/対象外範囲の明示)。
|
||||
- [ ] backfill を保守 CLI / event queue / 進捗 UI へ接続し、非同期実行時の配信契約を整備。
|
||||
- [ ] 既存 Ensure*Schema を migration runner へ段階移行し repository 別 SQL 契約テストを整備。
|
||||
- [ ] deployment profile で SQL / Document / canonical / cache / secret の設定を分離。
|
||||
|
||||
### S2:外部 backend
|
||||
|
||||
- [ ] PostgreSQL の全 repository 移植と SQLite との共通機能テスト。
|
||||
- [ ] MySQL の DDL/索引/照合順序/同時書き込み試験。
|
||||
- [ ] S3 adapter と互換サービスで range/条件付き作成/破損/切断/容量制限を検証。
|
||||
- [ ] SFTP adapter と host-key 検証、NFS/SMB/SSHFS の契約検査と mount 喪失検知。
|
||||
- [ ] Redis cache adapter と停止時の制限付き縮退、policy epoch による失効。
|
||||
- [ ] mutable canonical CAS と metadata 参照の回復プロトコル、HA の fencing。
|
||||
|
||||
### S3:運用と移行
|
||||
|
||||
- [ ] 編集可能な設定例と薄い backup / release / deploy script。
|
||||
- [ ] DB/Document/calendar/keys を束ねる backup manifest、pin、verify、restore rehearsal。
|
||||
- [ ] 共通 online CLI、portable bundle export/import、plan/apply/retry。
|
||||
- [ ] Web バックアップ管理、初回ようこそ画面、ジョブ状態とリソース監視の接続。
|
||||
|
||||
完了条件は接続成功だけではなく、機能契約・故障注入・再起動・データ移行・
|
||||
バックアップからの復旧試験まで通ること。未実装 backend を「対応済み」と表示しない。
|
||||
|
||||
## 12. 根拠資料
|
||||
|
||||
- [SQLite WAL:network filesystem の制約](https://sqlite.org/wal.html)
|
||||
- [S3 の conditional writes](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html)
|
||||
- [Redis persistence](https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/)
|
||||
- [PostgreSQL backup / restore](https://www.postgresql.org/docs/current/backup.html)
|
||||
- [MySQL 8.4 backup / recovery](https://dev.mysql.com/doc/refman/8.4/en/backup-and-recovery.html)
|
||||
@@ -51,6 +51,9 @@ installed → configured → enabled → disabled/failed の状態遷移を監
|
||||
|
||||
## ビルトインのリソース監視
|
||||
|
||||
収集と履歴の期間・保持ルールは [Seheweit](ja/seheweit.md) に初期分離済み。
|
||||
serverが認可とキュー状態を扱い、storeが保存する。URI・schema・監視周期は変更しない。
|
||||
|
||||
- 定義ID `builtin.resource.sample`、イベント型 `resource.sample`。
|
||||
- 起動時に未登録の場合のみ追加。既定60秒、変更可能範囲30〜86400秒。
|
||||
- 既存キューのpriority=100、通常のclaim/履歴/ログ/キャンセルを利用する。
|
||||
@@ -59,7 +62,8 @@ installed → configured → enabled → disabled/failed の状態遷移を監
|
||||
同一jobの再実行は重複登録しない。書き込みと期限切れ削除は同一トランザクション。
|
||||
- 7日保持。期限切れ削除は収集時に実行する。停止中に過去データを捏造して補間しない。
|
||||
- `GET /_/api/v1/queue/resources/history?hours=1|24|168` は最大361点。
|
||||
timestamp索引で期間を絞り、バケット内の最終サンプルを返す。平均/最大値ではない。
|
||||
timestamp索引で期間を絞り、バケット内の最後に挿入されたサンプル(MAX(id))を返す。
|
||||
時刻が逆転した入力では最大timestampとは限らず、平均/最大値ではない。
|
||||
- 現在値APIと履歴を区別する。グラフの更新停止やブラウザを閉じる操作は収集を止めない。
|
||||
収集停止は監視イベントのenabledまたはキューのpausedによる。
|
||||
- ビルトイン定義は削除不可。無効化と間隔変更は再起動後も維持する。
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# 2026-11-01:City閲覧導線とpages-cliの反映
|
||||
|
||||
## 反映対象
|
||||
|
||||
2026-11-01 12:39 JST頃、Compose `app` / `app2` を切り替えた。連携アダプタは再作成していない。
|
||||
|
||||
- City検索結果とサジェストから、設定画面ではなく対応Pageまたは配下のブラウザ一覧へ遷移。
|
||||
- 生成された未整理Spotの既定名を親Streetの表示名へ射影。内部名・UUID・Path境界と独自タイトルは維持。
|
||||
- 親階層を含む閲覧権限の確認、匿名表示名の再計算、検索画面のモバイル幅調整。
|
||||
- `pages-cli` ソースをイメージの `/src/pages-cli/` に収録。CLIはホストの `/home/anya/.local/bin/pages` に配置。
|
||||
|
||||
直前のcommand版をベースに選択した31ファイルのみをCOPYしてビルドした。作業ツリー全体は含めない。電話連絡先、SQLite初期接続の後続変更は引き続き未反映。DBスキーマ・正本形式・認証設定の変更はない。
|
||||
|
||||
## イメージ・復旧点
|
||||
|
||||
- 反映版:`pageswiki-app:city-pages-cli-20261101`
|
||||
- ID:`sha256:bed6b2d3e497e72c26feba4edf225fd9c57d49546fec43db2f88f297fcd989ee`
|
||||
- 直前版:`pageswiki-app:rollback-before-city-pages-cli-20261101`
|
||||
- 直前版ID:`sha256:d6c059486c238a1af0c9ebb2b2f3ed51c005a9670a703c55c077ef5a56ca1ec2`
|
||||
- 限定ビルドレシピと配布ソース:`.deployment-backups/prod-city-pages-cli-20261101/{Dockerfile,overlay/}`
|
||||
- 同ディレクトリの `reference/` は直前イメージのソース、`verify/` は反映対象を合成したテスト用ソース。どちらも本番データではない。
|
||||
- 既存の停止時整合バックアップは保持。今回はデータ契約が不変のため、新たな全データコピーは取得していない。
|
||||
|
||||
`pageswiki-app:latest` を反映版へ変更。Git commit/push、レジストリpush、バージョンタグ追加は行っていない。
|
||||
|
||||
## 検証
|
||||
|
||||
- 限定ソースと候補イメージそれぞれで `go test ./... -count=1` 成功。イメージの試験はネットワーク無効、CPU 2、メモリ2GiB。
|
||||
- Python単体テスト12件成功。ホストの限定ソースで `TestRemoteCLIHTTPIntegration` の実行・成功を個別に確認。ログイン/既定設定/一覧/編集/競合拒否/ログアウトを合成データで検証。イメージ内にPythonは追加しておらず、イメージ内の同テストはskipする。
|
||||
- 限定ソースのCity系・検索結果・コマンドバー/ハイライトのChromium試験成功。検索結果は1440px/390pxを検査。
|
||||
- 既存バックアップのリハーサル専用コピー2系統を、ネットワーク無効・workers無効で起動。healthおよび管理対象8コンポーネントのschema check成功。リハーサルコンテナは切替前に削除。
|
||||
- 本番2台のイメージID一致、両方running/再起動回数0、app healthy。
|
||||
- localhost3000/3001と公開HTTPSのhealth、公開ログインが200。
|
||||
- 公開HTTPSのCity関連JS3ファイルと検索CSSのSHA-256が配布元と一致。
|
||||
- 本番2台の管理対象schema check成功。切替直後のログでpanic/fatal/job failed/database locked/scheduler claim failedの該当0件。
|
||||
|
||||
外部取り込みカレンダーの内容にはアクセスしていない。上記は長期負荷試験や本番の全データ完全性検査を意味しない。
|
||||
|
||||
## CLIの利用
|
||||
|
||||
配置前に既存 `pages` コマンドがないことを確認。ユーザーPATHに含まれる `/home/anya/.local/bin/pages` に0755で配置し、helpとソースとのSHA-256一致を確認した。
|
||||
|
||||
SHA-256:`1a6feb7349a5b1b5b25fbb46cab1c7ac7dd7a46cbaab5aea803151305ac9da77`
|
||||
|
||||
```sh
|
||||
pages configure --origin https://pages.anya.jp --username anya
|
||||
pages login
|
||||
pages
|
||||
```
|
||||
|
||||
利用者のプロファイルや資格情報は作成していない。本番資格情報による編集試験も行っていない。クライアントはPython 3.9以降のUnix系環境向け。別端末へのインストールは [pages-cli README](../../../pages-cli/README.md) を参照。OIDC引き継ぎ・Ctrl+P fuzzy UI・新規Page作成は後続。
|
||||
|
||||
## 今回の切り戻し
|
||||
|
||||
今回の変更にDB/正本の移行はない。データを戻さず、直前のcommand版イメージへ切り替える。
|
||||
|
||||
```sh
|
||||
docker image tag pageswiki-app:rollback-before-city-pages-cli-20261101 pageswiki-app:latest
|
||||
docker compose up -d --no-deps --no-build app app2
|
||||
```
|
||||
|
||||
両イメージID、health、ログイン、再起動回数を確認する。これは今回の変更専用の手順で、保存基盤変更前の古い版には適用しない。
|
||||
|
||||
CLIはサーバから独立しているため、サーバ切り戻しで削除する必要はない。利用停止時も保存済みセッションや設定を無断で削除しない。
|
||||
@@ -0,0 +1,45 @@
|
||||
# 2026-11-01:コマンドバーと共通シンタックス色の本番反映
|
||||
|
||||
## 反映対象
|
||||
|
||||
2026-11-01 07:14 JST頃、Compose `app` / `app2` に反映。関連アダプタのコンテナは再作成しない。
|
||||
|
||||
- ブラウザ左下の `cd` / `vi` / `view` バー、文字入力によるフォーカス、TabによるPath補完。
|
||||
- 共通ナビがあるホーム以外の画面での `g` コマンドモード。編集中の入力/Vim操作は保護。
|
||||
- ブラウザのPathアドレス欄をtopbarへ統合。狭い画面では非表示。
|
||||
- エディタ、読み取りコードビューア、言語指定付きコードブロックのテーマ連動シンタックス色。
|
||||
|
||||
イメージは稼働版fix2をベースに、限定した26ファイルをCOPYして再ビルド。全作業ツリーをCOPYしない。電話連絡先およびSQLite初期接続の後続変更は含まない。今回の変更はスキーマ、正本形式、認証設定を変更しない。
|
||||
|
||||
## イメージと復旧点
|
||||
|
||||
- 反映版:`pageswiki-app:command-20261101`
|
||||
- 反映版ID:`sha256:d6c059486c238a1af0c9ebb2b2f3ed51c005a9670a703c55c077ef5a56ca1ec2`
|
||||
- 直前版:`pageswiki-app:rollback-before-command-20261101`(元タグ `pageswiki-app:ux-20261101-fix2`)
|
||||
- 直前版ID:`sha256:aa4336dd677b27966df8732054a27b3544560c6fffb18b232e89d4f764b1551e`
|
||||
- 限定ビルドレシピ:`.deployment-backups/prod-command-20261101/Dockerfile`
|
||||
- 直前版ソース参照コピー:同ディレクトリの `reference/`。本番データではない。
|
||||
- 前回の停止時整合バックアップ/オンラインDBバックアップは保持。今回はDB変更がないため、新たな全データバックアップは取得していない。
|
||||
|
||||
現在の `pageswiki-app:latest` は反映版。Git commit/push、レジストリpush、リリースタグ追加は行っていない。
|
||||
|
||||
## 検証
|
||||
|
||||
- 候補イメージ内で `go test ./... -count=1` 成功。ネットワーク無効、CPU 2、メモリ2GiBで実行し、テストは合成データを使用。
|
||||
- 既存の本番バックアップのリハーサル用コピー2系統を使用。ネットワーク無効、workers無効で起動。両方のhealthと管理対象8コンポーネントのschema check成功。外部取り込みカレンダーの内容は開かない。検証コンテナは切替前に削除。
|
||||
- 実装時にChromiumの1440px/375px操作試験、ホーム・エディタ回帰試験済み。実機iPhone Safariやソフトウェアキーボードは未確認。
|
||||
- 本番両コンテナのイメージIDが反映版と一致。app healthy、両方running/再起動回数0。
|
||||
- localhost3000/3001および公開HTTPSのhealthが200。公開ログイン200。匿名の `/e/` は正規化後にログインページへ遷移。
|
||||
- 公開URLのコマンドJS、アドレスJS、ハイライトJS、コマンドCSS、テーマbase CSS、CodeMirror bundleのSHA-256がローカル配布ファイルと一致。
|
||||
- 切替後の両インスタンスで管理対象スキーマ検査成功。これは全データ完全性検査や長期負荷試験を意味しない。
|
||||
|
||||
## この反映だけを切り戻す場合
|
||||
|
||||
DB/正本の変更がないため、fix2へはデータを巻き戻さずイメージだけで戻す。ユーザの新しい書き込みを削除しない。
|
||||
|
||||
```sh
|
||||
docker image tag pageswiki-app:rollback-before-command-20261101 pageswiki-app:latest
|
||||
docker compose up -d --no-deps --no-build app app2
|
||||
```
|
||||
|
||||
切り戻し後は両イメージID、health、公開ログイン、再起動回数を確認する。この手順は今回のcommand版からfix2への切り戻し専用であり、保存基盤変更前の古い版には適用しない。
|
||||
@@ -0,0 +1,58 @@
|
||||
# 2026-11-01:優先UXの本番反映
|
||||
|
||||
## 対象と復旧点
|
||||
|
||||
- 対象:Compose `app` / `app2`。最新のUXに加え、作業ツリーにあった保存基盤・スキーマ管理・DR・エディタ復旧の変更を含む。
|
||||
- 旧イメージ:`sha256:3ee1b6b5ff24154c05990f02f112db7052b5a9bfb9894e5e9020a55fbb539d8c`。
|
||||
- 旧版タグ:`pageswiki-app:rollback-before-ux-20261101`。
|
||||
- 初回候補:`pageswiki-app:ux-20261101`、`sha256:1efb6fa94ae447e4769fa1056eb88fd34274cd17264646ad22a13327e05567b7`。隔離検証で旧索引との不一致を検出したため本番へは適用しない。
|
||||
- 修正候補:`pageswiki-app:ux-20261101-fix1`、`sha256:1cae0988fdc2a9d008fe971ed7f92bff9e4831b1798d080e4551b9efeca31958`。
|
||||
- 停止時整合バックアップ:`.deployment-backups/prod-ux-20261101/before/{data,data2}`。親ディレクトリ0700。アプリ2台を停止して全データをコピーし、DB本体の一致とsyncを確認。
|
||||
- ソースの復旧点:`.deployment-backups/dev-priority-20261031/`。Gitの未コミット変更は保持し、commit/push/tagは行わない。
|
||||
|
||||
## 実行基盤の障害と復旧
|
||||
|
||||
整合コピー後、旧コンテナの再開が `failed to create TTRPC connection: unsupported protocol` で失敗した。新コード起動・新migration適用の前に発生。
|
||||
|
||||
起動中のDocker 29.5.0 / containerd 2.2.3と、インストール済みDocker 29.8.2 / containerd-shim 2.3.6が不一致だった。実行中の `/proc/.../exe` は削除済み旧バイナリを参照していた。
|
||||
|
||||
このrootless Dockerの稼働コンテナがPagesWiki関連のみであることを確認し、`systemctl --user restart docker` で更新済み実行基盤へ切り替え、既存コンテナを再開。rootful Dockerやホスト全体の再起動は行っていない。旧アプリの起動中、一時的にapp2のenroll接続が拒否されたが、app起動後に回復した。
|
||||
|
||||
旧版復旧後、公開URLとlocalhostの3000/3001双方の `/health` が200、appのDocker healthがhealthyであることを確認した。
|
||||
|
||||
## 検証・反映の進捗
|
||||
|
||||
- [x] 全Goテスト成功、候補イメージのビルド成功。
|
||||
- [x] 旧版・停止時の正本/DB/鍵を保全。
|
||||
- [x] バックアップのコピーを `--network none`、workers無効で起動し、migration/backfillを検証。
|
||||
- [x] 管理対象8 componentがcurrent。双方のSQLite quick_check、メインDBのintegrity_check成功。本文backfillはメイン1,928件・外部側0件で完了。
|
||||
- [x] オブジェクト1,598/Revision1,928/Path1,093/Principal1件が移行前後で一致(外部側は各0件)。認証画面と新規静的アセットの応答を確認。
|
||||
- [x] 05:55 JST頃、停止時の追加バックアップ `cutover/{data,data2}` を取得(beforeから変更のないファイルのみrsync --link-destで共有、ライブデータへのhardlinkではない)。DB一致とsync後、fix1をlatestに付け替え、app/app2のみ再作成。
|
||||
- [x] 両インスタンスのヘルス200、app healthy、公開HTTPSのヘルス200・ログイン200・匿名エディタ303。ホーム入力検索/ブラウザアドレスJSの公開URLとローカルのSHA-256一致。両DBのschema check成功。
|
||||
- [x] 切替直後の監視で両アプリの再起動回数0。外部カレンダーの内容は開かずに確認。継続監視では05:59:59 JSTにscheduler claimのSQLITE_BUSYを1件検出(下記)。
|
||||
|
||||
外部取り込み済みカレンダーの内容は検証対象にしない。リハーサル用データから外部同期・通知送信を行わない。
|
||||
|
||||
この反映に電話連絡先の後続開発は含めない。最終反映済みイメージはfix2に固定し、以後の作業ツリーと区別する。追加機能の本番反映は別途検証して行う。
|
||||
|
||||
### スケジューラの継続検証
|
||||
|
||||
05:59:59 JSTに `event scheduler claim failed: database is locked (5)` が1件発生。以後の直近5分では38ジョブが成功しており、停止/ジョブ失敗ではなかった。旧版にもあった、deferred read transactionからwriteへの昇格競合を除去するため、`ClaimDueEvent` を `UPDATE ... WHERE uuid=(SELECT ...) RETURNING ...` の単一statementへ変更。優先度/実行可能時刻/attemptsを保持し、同時取得をSQLiteが直列化する。
|
||||
|
||||
8つの独立DBハンドル+並行する別書き込み、64ジョブの重複なし全件取得を10回検証。race検査も成功。新規schemaなし。fix1ベースに `internal/store/event_jobs.go` だけを差し替えた `pageswiki-app:ux-20261101-fix2`(`sha256:aa4336dd677b27966df8732054a27b3544560c6fffb18b232e89d4f764b1551e`)を構築。イメージ内の全Goテストと隔離データ2系統の起動・schema checkが成功。
|
||||
|
||||
fix2には電話連絡先/新規SQLite初期接続の後続変更は含まない。`Dockerfile.scheduler` はバックアップディレクトリに保存。切替前のオンラインSQLiteバックアップは `before-scheduler/` に保管(DB単体であり、全正本の整合復旧点はcutover)。fix2→fix1は同一schema/データ契約のためイメージのみで戻せる。cutoverへの全データ復旧とは区別する。
|
||||
|
||||
06:06 JST頃、fix2をlatestとしてapp/app2を再作成。両方の実行イメージIDを照合し、公開HTTPS/localhost3001のヘルス200、app healthy、再起動回数0を確認。初回確認期間でpanic/job failed/database locked該当ログ0件。長期負荷検証を完了した意味ではなく、過長な別writerによるSQLITE_BUSYまで根絶したとの主張ではない。
|
||||
|
||||
後続開発ソースの保全先:`.deployment-backups/dev-followup-20261101/source-after-contacts.tar.gz`。全Goテスト、電話連絡先のChromium操作、初期接続の反復試験はローカルで実施。アプリケーションDBと外部取り込みカレンダーの実データを後続機能テストには使用しない。
|
||||
|
||||
### リハーサルで修正した問題
|
||||
|
||||
旧DBの `idx_event_jobs_due(status,run_at_ms,created_at_ms)` が残るため、`CREATE INDEX IF NOT EXISTS` だけではpriority付き索引にならず、`event-jobs/2 assertion 12` に失敗した。未リリースの採用migrationで、この非一意索引をtransaction内で一度再構築する。両本番バックアップに既存の `schema_migration_steps` がないことを確認し、適用履歴を削除する回避は行っていない。
|
||||
|
||||
`TestEventJobsAdoptLegacyDueIndex` で旧索引からの移行、再実行、job本文・status・attempts・時刻の保持を検証。変更後の全Goテストも成功。
|
||||
|
||||
## ロールバック
|
||||
|
||||
データ形式の互換性を確認する前に旧イメージだけへ戻さない。書き込みを停止し、新版稼働後のデータも別途保全したうえで、切替直前のDB・正本・鍵と旧イメージの組み合わせへ復元する。ユーザの新規書き込みを無断で破棄しない。詳細は [保存基盤反映手順](../storage-schema-rollout.md)。
|
||||
@@ -0,0 +1,125 @@
|
||||
# PagesWiki v0.2.0 のリリースと本番反映
|
||||
|
||||
2026-11-01 15:38:54 JST、Giteaでビルドした `v0.2.0` を本番へ反映した。
|
||||
対象は `app`、`app2`、`adaptor-gateway`、`excalidraw-viewer` の4サービス。
|
||||
code-server、Kroki、Mermaidは再作成していない。
|
||||
|
||||
## ソースと配布物
|
||||
|
||||
- リリースcommit:`d5d21b78418683bc81ed384e0264102e39cd44ab`。
|
||||
- 注釈付きGitタグ:`v0.2.0`。タグobject:`43b66076a98aa9730e722f8f788dcaaa7647498f`。
|
||||
- [イメージビルド run 12](https://git.anya.jp/anya/wikipages/actions/runs/12):全工程成功。
|
||||
- [リリース昇格 run 13](https://git.anya.jp/anya/wikipages/actions/runs/13):全工程成功。
|
||||
- 公開済み `v0.1.1` から、機能追加を含むためSemVer運用規則に従いMINORを更新した。
|
||||
|
||||
8部品の初期分離に加え、未コミットだったエディタ復旧、ナビゲーション・テーマ、CLI、
|
||||
保存基盤・schema管理・DR関連の実装と設計書を含む。
|
||||
各設計書の未チェックTODOまで実装されたことを意味しない。
|
||||
本書の記録用commitはリリースcommitと区別し、公開タグは付け替えない。
|
||||
|
||||
registry prefixは `git.anya.jp/anya/`。以下はmanifest digestであり、ローカルimage IDとは別。
|
||||
|
||||
| イメージ | v0.2.0 のdigest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:35096c46310c5e5d02c1cf56cf94f21f1b6917067c9689c4824c971af9fec1d7` |
|
||||
| pageswiki-adaptor-gateway | `sha256:11f93ae28d00e82a92a0c32be7daee85f569b5b975decd8812be0dbe2baac482` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:ec42a59d47ef731df1492c3db35b44ac9717b2235c8ece3360017d38bbf25f07` |
|
||||
|
||||
3種類すべてでSHAタグとリリースタグのdigestが一致し、OCI revisionラベルもリリースcommitと一致した。
|
||||
昇格時の再ビルドは行っていない。
|
||||
|
||||
## 検証と移行
|
||||
|
||||
commit前に全Goテストをキャッシュなしで実行、全Go vet、8部品のrace検査、
|
||||
主要Chromiumテスト11本、Nodeテスト、Python CLIテスト19件が成功した。
|
||||
エディタ再ビルド後の配布物は既存bundle・map・CSSとSHA-256が一致した。
|
||||
Giteaのtestステージでも全Goテストが成功した。
|
||||
|
||||
本番旧版の管理対象8 componentはcurrent。候補版では `profile-contacts` のみpendingだった。
|
||||
新しいprivate連絡先テーブルとmigration履歴の追加であり、Page本文の変換や既存行の削除はない。
|
||||
確定済みバックアップの独立コピー2系統を、実際のCIイメージで起動した。
|
||||
network none、CPU 2、メモリ2GiB、検証コピーだけのDR設定でworkersを無効にし、
|
||||
外部enroll引数も省略した。本番への同期・通知送信・外部カレンダー同期は検証から実行しない。
|
||||
|
||||
外部インスタンスの検証を最初に `--no-default-campus` 単独で起動した際は、既存の引数制約で終了した。
|
||||
この引数はenroll指定との併用が必要なため、隔離起動ではenrollを含め引数を省略して再試験した。
|
||||
2系統ともhealthと追加後9 componentのschema checkが成功し、起動エラーはなかった。
|
||||
外部enrollの実接続経路は隔離試験の対象外とし、本番起動時の結果を別に確認した。
|
||||
|
||||
本番切替後は次を確認した。
|
||||
|
||||
- 4コンテナのrevisionラベルがリリースcommitと一致。アプリ2台のimage IDも一致。
|
||||
- localhost 3000/3001のhealth、公開HTTPSのhealth・ログインが200。
|
||||
- 匿名エディタはURL正規化後にログイン画面へ誘導される。
|
||||
- gatewayとExcalidrawのhealth成功、4コンテナの再起動回数0。
|
||||
- アプリ2台とも管理対象9 componentがcurrent。
|
||||
- 公開HTTPSから取得したeditor.js、command-bar.js、theme-picker.js、CodeMirror bundle、base CSSが配布元と一致。
|
||||
|
||||
これは全データの完全性検査、実機Safariの操作、長期負荷試験、外部認証providerの実ログインを完了した意味ではない。
|
||||
外部から取り込んだカレンダーの内容は開いていない。
|
||||
|
||||
## バックアップと起動設定
|
||||
|
||||
保全先は `.deployment-backups/release-v0.2.0-20261101/`。親ディレクトリは0700。
|
||||
|
||||
- `before/data`・`before/data2`:事前保全。先行コピー後、アプリ2台とgatewayを停止して差分同期し、DBバイト一致・syncを確認して旧版を再開した。
|
||||
- `cutover/data`・`cutover/data2`:15:38:47 JSTに確定した切替直前の整合コピー。
|
||||
- `config/`:旧Composeファイルと `.env`。秘密値を設計書・Gitへ転記しない。
|
||||
- 未変更ファイルのhardlink共有はbeforeとcutoverの間だけ。本番データとのhardlink共有はない。
|
||||
- 隔離検証コピーと検証コンテナは削除済み。before/cutoverと既存バックアップは保持した。
|
||||
|
||||
初回事前同期では稼働中に変更されたDB等約6GBの再コピーが必要になり、停止時間が延びた。
|
||||
切替直前の停止中同期は約30MB。今後はデータ量に応じた停止時間を事前に見積もる。
|
||||
切替後のホスト空き容量は約33GB。バックアップ世代削除は別途判断し、自動pruneは行わない。
|
||||
|
||||
ローカルのGit無視対象 `.env.release` に `PAGESWIKI_IMAGE_TAG=v0.2.0` を記録した。
|
||||
通常の秘密設定 `.env` と合わせて明示的に利用する。
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env --env-file .env.release \
|
||||
-f docker-compose.yml -f docker-compose.registry.yml \
|
||||
up -d --no-build --no-deps app app2 adaptor-gateway excalidraw-viewer
|
||||
```
|
||||
|
||||
`pageswiki-app:latest`、`pageswiki-adaptor-gateway:latest`、`pageswiki-excalidraw-viewer:latest` の
|
||||
ローカル互換タグもリリースイメージへ合わせた。registryのlatestは作成・更新していない。
|
||||
再ビルドによる混在を避け、本番操作では上のregistry overlayと `--no-build` を使う。
|
||||
|
||||
## 復旧点
|
||||
|
||||
旧イメージはそれぞれ `rollback-before-v0.2.0-20261101` タグで保持した。
|
||||
|
||||
| ローカルrepository | 旧image ID |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:bed6b2d3e497e72c26feba4edf225fd9c57d49546fec43db2f88f297fcd989ee` |
|
||||
| pageswiki-adaptor-gateway | `sha256:b1ed3051eb63c17da8eee6632a7823423707568dd5bd92c77d47de4d85cfae75` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:7fee6cc8c18a6fd6fe9adec91047332f5591d0a90081a8e32e629f4e9437d3d3` |
|
||||
|
||||
profile-contactsのschema追加があるため、旧版へのimage差替えだけで安全とは扱わない。
|
||||
復旧時は新規書込みを停止し、切替後データも保全してからデータ契約の互換性を確認する。
|
||||
cutoverへ戻す場合は切替後の書込みが失われるため、別途承認と復旧対象の確認が必要。
|
||||
schema履歴を削除して旧版のcheckを通す回避はしない。
|
||||
|
||||
## 継続課題
|
||||
|
||||
15:38:47〜15:40:47 JSTの観察で、appのイベント開始ログ保存に
|
||||
`database is locked (517)` を6件検出した。他3サービスは0件。
|
||||
すべて `component=dregarnuhr ... start-log failed` で、claimやfinishの失敗ではなかった。
|
||||
該当する先頭2ジョブは1回目でsucceeded、観察時点の切替後作成ジョブ16件もすべてsucceededだった。
|
||||
panic・fatal・ジョブ失敗・再起動は検出していない。
|
||||
|
||||
`AddEventLog` の実装は直前の本番イメージと同一であることを比較確認した。
|
||||
読み取り後に書き込むdeferred transactionの競合が残っており、DregarnuhrのReportで失敗が可視化された。
|
||||
ジョブ本体が継続しても、開始ログと対応する集約値が欠落するリスクはある。
|
||||
今回のリリースでこの不具合を解消したとは扱わない。
|
||||
|
||||
- [ ] 優先修正:AddEventLogの読取→書込昇格を避けるtransaction方式と、有界な取消・待機・再試行を整備する。
|
||||
- [ ] 独立DB接続・複数writerで、ログと集約値の原子性・重複なし・取りこぼしを検証する。
|
||||
- [ ] 完了ログ等の既存呼出し元で握りつぶしている保存失敗も、本文・秘密を露出しない形で可視化する。
|
||||
- [ ] 修正は新しいPATCH版としてビルド・検証・公開する。v0.2.0タグやdigestは付け替えない。
|
||||
|
||||
### 後続作業(リリース済み内容とは別)
|
||||
|
||||
`0f686aa` を基点に、上記ログ競合の修正をソースへ実装した。
|
||||
契約と検証範囲は [Dregarnuhrのログ保存競合修正](../../design/ja/dregarnuhr.md#v020後の優先修正ログ保存競合) を参照。
|
||||
この追記は本番修正済みを意味しない。v0.2.0のイメージ・タグは変更していない。
|
||||
@@ -0,0 +1,124 @@
|
||||
# 保存基盤のスキーマ変更・反映手順
|
||||
|
||||
2026-09-27。保存基盤の段階移行に関する運用メモ。
|
||||
本書の作成時点では開発用の一時 DB で検証しており、本番 DB への適用を意味しない。
|
||||
詳細は [保存基盤の設計](../design/storage-portability-and-operations.md) を参照。
|
||||
|
||||
## 今回の変更と別の DB 操作との関係
|
||||
|
||||
別の DB 修正、復旧、import、DB-only CLI 書き込みと同時に適用しない。
|
||||
先に使用するバイナリ・スキーマ・保存先の組み合わせを決め、整合バックアップを取得する。
|
||||
ソースの実装完了と、本番への migration 適用完了は別の状態である。
|
||||
|
||||
アプリケーションを新しいコードで起動すると、以下を実行する。
|
||||
|
||||
1. `schema_migration_steps` に component/version/name/checksum/適用時刻を記録する。
|
||||
2. `document_backfills` と保存先の `.document-store-id` により、本文移行の進捗を管理する。
|
||||
3. プレビューのメタデータ、リソース履歴、アナウンス、ブラウザナビゲーション、
|
||||
アダプタセッション、インポート履歴、イベントキュー/ログを migration 管理下へ取り込む。
|
||||
4. 古い DB で不足していれば `browser_navigation_links.is_directory`、
|
||||
`adapter_sessions.root_path` / `principal_uuid`、`import_journal.completed` を追加する。
|
||||
`event_jobs` の既知の追加列も存在を検査してから追加し、ALTER の失敗を握りつぶさない。
|
||||
5. イベントキューのスキーマ検証後、通常起動時のみ中断ジョブを再キューイングする。
|
||||
読み取り専用の事前チェックではこの復旧処理を呼ばない。
|
||||
|
||||
現在の既存コードですでに追加済みの列は重複して追加しない。
|
||||
対象テーブルの再作成、既存行の削除、本文の一括書き換えは行わない。
|
||||
旧式の `schema_migrations` は削除/リネームしない。
|
||||
認証・ACL、City、タスク、カレンダーを今回の 7 component に含めない。
|
||||
別に `document-store` component が本文移行の進捗テーブルを管理する(合計 8 component)。
|
||||
これらの既存起動時処理まで無変更になる、という意味ではない。
|
||||
|
||||
## 反映前の確認
|
||||
|
||||
- SQLite の整合バックアップと Document / calendar 正本 / 鍵を同じ復旧点として保全する。
|
||||
稼働中の DB ファイルだけをコピーして完了としない。
|
||||
- DB とファイルを隔離したコピーを作り、新しいバイナリで起動試験する。
|
||||
本番の FQDN、外部同期先、通知送信先へ接続しない環境で実施する。
|
||||
- 新旧スキーマからの採用テストと全体回帰テストの結果を確認する。
|
||||
- migration 定義の checksum 不一致、必要な列/索引/一意性制約の欠落があれば、
|
||||
適用履歴を削除して回避せず、定義の変更か既存 DB の不整合かを調べる。
|
||||
- 長い SQL transaction、DB-only writer、旧プロセスによる保守操作を停止してから反映する。
|
||||
SQLite の `BEGIN IMMEDIATE` による短時間の排他が必要で、ロック競合はエラーになり得る。
|
||||
- 初回 backfill は保存先内の未移行データを検証するため時間がかかることがある。
|
||||
起動前に完了させ、通常の配信を先に始めない。完了後の起動では全 Revision を走査しない。
|
||||
|
||||
## 読み取り専用で確認できる情報
|
||||
|
||||
### schema CLI
|
||||
|
||||
新しいバイナリを用意した段階で、Web サーバーを起動せず実行できる。
|
||||
|
||||
```sh
|
||||
./pageswiki schema status --data-dir /path/to/data
|
||||
./pageswiki schema check --db /path/to/data/pages.db --json --timeout 30s
|
||||
```
|
||||
|
||||
`--data-dir` を省略した場合は `PAGESWIKI_DATA_DIR`、未設定なら `./data` を使う。
|
||||
`--db` と明示的な `--data-dir` は同時指定しない。
|
||||
|
||||
- `status`:管理対象 component の適用済み/最新 version、未適用 step、契約検査結果を表示する。
|
||||
読み取りに成功すれば終了コード 0。監視などで判定する場合は `check` を使う。
|
||||
- `check`:管理対象すべてが current なら 0、pending があれば 2、
|
||||
blocked/unknown があれば 1。DB 読み取り失敗や不正な引数も 1。
|
||||
- `blocked`:履歴の欠落・checksum 不一致・対応 version より新しい履歴、
|
||||
または適用済みスキーマが最新契約を満たしていない。
|
||||
- `unknown`:DB に記録された component をこのバイナリが認識しない。
|
||||
- `pending`:未適用の定義がある。まだ作られていない列/テーブルによる assertion の失敗も
|
||||
併記するが、DDL の実行成功・失敗を予測した結果ではない。
|
||||
|
||||
`mode=ro` と `query_only` による読み取り専用接続、一つの読み取り transaction を使う。
|
||||
DB/データディレクトリの作成、通常起動処理、鍵生成、本文 backfill、ジョブ復旧を実行しない。
|
||||
稼働中 DB の committed WAL も参照する。SQLite の WAL/SHM ファイルのアクセス要件は必要で、
|
||||
ファイルシステム上の一切のメタデータ変更がないことまで保証するモードではない。
|
||||
|
||||
**このコマンドは完全な移行リハーサルでも、全 DB の健全性検査でもない。**
|
||||
出力の `coverage=managed-components-only` と `legacy_areas` を確認する。
|
||||
終了コード 0 でも、未移行の従来初期化処理、正本ファイル、データ依存の移行、
|
||||
外部接続の正常性は証明しない。隔離コピー上での起動試験を省略しない。
|
||||
|
||||
### SQL による補助確認
|
||||
|
||||
DB のパスは実際の起動設定で確認し、SQLite クライアントを read-only モードで使用する。
|
||||
次の SQL は状態確認用で、テーブルを作成しない。
|
||||
|
||||
```sql
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table'
|
||||
AND name IN ('schema_migration_steps', 'document_backfills');
|
||||
```
|
||||
|
||||
テーブルが存在する場合のみ、続けて確認する。
|
||||
|
||||
```sql
|
||||
SELECT component, version, name, checksum, applied_at_ms
|
||||
FROM schema_migration_steps ORDER BY component, version;
|
||||
|
||||
SELECT store_id, last_uuid, processed, completed, updated_at_ms
|
||||
FROM document_backfills ORDER BY updated_at_ms DESC;
|
||||
```
|
||||
|
||||
`completed=1` は「その保存先への初回移行が完了した」ことを示す。
|
||||
すべての正本の現在の健全性を証明する値ではない。欠落や破損は verify/repair の対象とする。
|
||||
`.document-store-id` は復旧対象に含める。空の保存先へ入れ替えた場合に、このファイルだけを
|
||||
コピーして完了状態を引き継がせない。
|
||||
|
||||
## ロールバック・失敗時
|
||||
|
||||
DDL と migration 履歴の記録は同じ transaction で rollback する。
|
||||
Document backfill はバッチ単位で進捗を確定し、失敗したバッチは次回再実行する。
|
||||
すでに保存した不変 Document が残っていても、検証して再利用する。
|
||||
|
||||
起動失敗時には component/version とエラーを保存し、旧バイナリへの切り戻しを
|
||||
無条件に行わない。旧バイナリが新しい migration 履歴を理解しない可能性があるため、
|
||||
DB と正本のバックアップからの復旧か、互換性を検証済みの切り戻しを選ぶ。
|
||||
DR standby ではこれらの schema 作成・採用を実行しない。
|
||||
|
||||
## 残件
|
||||
|
||||
- 全 Ensure*Schema の集約と、型/CHECK/照合順序/外部キーまで含む schema 契約の拡充。
|
||||
- DB ごとの差異を切り分け、PostgreSQL / MySQL の共通機能テストを整備。
|
||||
- 本文の健全性/backfill 状態の専用診断、保守 CLI、進捗 UI と event queue の接続。
|
||||
- 初回 backfill の非同期化に先立つ、未移行データの配信と readiness の設計。
|
||||
|
||||
外部 DB への接続や、本番 DB の移行は上記を完了・検証した段階で別途実施する。
|
||||
@@ -0,0 +1,15 @@
|
||||
package compiler
|
||||
|
||||
import "pageswiki/internal/grammaratur"
|
||||
|
||||
// HTMLToMarkdownAuthoring delegates loss-preserving conversion to Grammaratur.
|
||||
// Deprecated: use grammaratur.HTMLToMarkdownAuthoring in new application code.
|
||||
func HTMLToMarkdownAuthoring(source string) (string, error) {
|
||||
return grammaratur.HTMLToMarkdownAuthoring(source)
|
||||
}
|
||||
|
||||
// MarkdownAuthoringHTML preserves the existing authoring entry point.
|
||||
// Deprecated: use grammaratur.MarkdownAuthoringHTML in new application code.
|
||||
func MarkdownAuthoringHTML(source string) string {
|
||||
return grammaratur.MarkdownAuthoringHTML(source)
|
||||
}
|
||||
@@ -1,24 +1,8 @@
|
||||
package compiler
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
)
|
||||
import "pageswiki/internal/kunstzeal"
|
||||
|
||||
func DiagramHash(
|
||||
diagramType string,
|
||||
source string,
|
||||
format string,
|
||||
) string {
|
||||
|
||||
sum :=
|
||||
sha256.Sum256(
|
||||
[]byte(
|
||||
diagramType + "\x00" + format + "\x00" + source,
|
||||
),
|
||||
)
|
||||
|
||||
return hex.EncodeToString(
|
||||
sum[:],
|
||||
)
|
||||
// DiagramHash preserves the legacy key format through the rendering component.
|
||||
func DiagramHash(diagramType, source, format string) string {
|
||||
return kunstzeal.DiagramHash(diagramType, source, format)
|
||||
}
|
||||
@@ -1,14 +1,14 @@
|
||||
package compiler
|
||||
|
||||
import (
|
||||
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
|
||||
)
|
||||
import "pageswiki/internal/grammaratur"
|
||||
|
||||
// HTMLToMarkdown preserves the legacy conversion contract (without protection
|
||||
// fences). Deprecated: use grammaratur.HTMLToMarkdown in new application code.
|
||||
func HTMLToMarkdown(
|
||||
html string,
|
||||
) (string, error) {
|
||||
|
||||
return htmltomarkdown.ConvertString(
|
||||
return grammaratur.HTMLToMarkdown(
|
||||
html,
|
||||
)
|
||||
}
|
||||
+17
-1
@@ -1,9 +1,12 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
@@ -24,7 +27,20 @@ func Open(path string) (*sql.DB, error) {
|
||||
},
|
||||
}.Encode(),
|
||||
}).String()
|
||||
return sql.Open("sqlite", dsn)
|
||||
database, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// sql.Open is lazy. Establish WAL once before exposing the pool, otherwise
|
||||
// simultaneous first borrowers race the initial journal_mode transition in
|
||||
// their connection pragmas (SQLITE_BUSY before BEGIN IMMEDIATE is reached).
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if err := database.PingContext(ctx); err != nil {
|
||||
database.Close()
|
||||
return nil, fmt.Errorf("initialize SQLite connection: %w", err)
|
||||
}
|
||||
return database, nil
|
||||
}
|
||||
|
||||
func Init(db *sql.DB) error {
|
||||
|
||||
+87
-90
@@ -4,6 +4,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func Migrate(
|
||||
@@ -96,54 +97,21 @@ func Migrate(
|
||||
}
|
||||
}
|
||||
|
||||
alterStmts := []string{
|
||||
|
||||
`
|
||||
ALTER TABLE paths
|
||||
ADD COLUMN created_at INTEGER
|
||||
`,
|
||||
|
||||
`
|
||||
ALTER TABLE objects
|
||||
ADD COLUMN created_at INTEGER
|
||||
`,
|
||||
|
||||
`
|
||||
ALTER TABLE revisions
|
||||
ADD COLUMN created_at INTEGER
|
||||
`,
|
||||
|
||||
`
|
||||
ALTER TABLE revisions
|
||||
ADD COLUMN document_hash TEXT
|
||||
`,
|
||||
|
||||
`
|
||||
ALTER TABLE revisions
|
||||
ADD COLUMN lang TEXT NOT NULL DEFAULT 'und'
|
||||
`,
|
||||
|
||||
`
|
||||
ALTER TABLE revisions
|
||||
ADD COLUMN created_at_ms INTEGER
|
||||
`,
|
||||
`
|
||||
ALTER TABLE revisions
|
||||
ADD COLUMN content_type TEXT NOT NULL DEFAULT 'text/html; charset=utf-8'
|
||||
`,
|
||||
`
|
||||
ALTER TABLE revisions
|
||||
ADD COLUMN filename TEXT NOT NULL DEFAULT ''
|
||||
`,
|
||||
|
||||
`
|
||||
ALTER TABLE tags
|
||||
ADD COLUMN created_at INTEGER
|
||||
`,
|
||||
columns := []struct{ table, name, declaration string }{
|
||||
{"paths", "created_at", "INTEGER"},
|
||||
{"objects", "created_at", "INTEGER"},
|
||||
{"revisions", "created_at", "INTEGER"},
|
||||
{"revisions", "document_hash", "TEXT"},
|
||||
{"revisions", "lang", "TEXT NOT NULL DEFAULT 'und'"},
|
||||
{"revisions", "created_at_ms", "INTEGER"},
|
||||
{"revisions", "content_type", "TEXT NOT NULL DEFAULT 'text/html; charset=utf-8'"},
|
||||
{"revisions", "filename", "TEXT NOT NULL DEFAULT ''"},
|
||||
{"tags", "created_at", "INTEGER"},
|
||||
}
|
||||
|
||||
for _, stmt := range alterStmts {
|
||||
_, _ = db.Exec(stmt)
|
||||
for _, column := range columns {
|
||||
if err := ensureSQLiteColumn(db, column.table, column.name, column.declaration); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := migrateRevisionMetadata(db); err != nil {
|
||||
@@ -185,54 +153,47 @@ func migrateRevisionMetadata(db *sql.DB) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
rows, err := db.Query(`
|
||||
SELECT
|
||||
uuid,
|
||||
COALESCE(body, '')
|
||||
FROM revisions
|
||||
WHERE document_hash IS NULL
|
||||
OR document_hash = ''
|
||||
`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
type legacyRevision struct {
|
||||
uuid string
|
||||
body string
|
||||
}
|
||||
|
||||
var revisions []legacyRevision
|
||||
|
||||
for rows.Next() {
|
||||
var revision legacyRevision
|
||||
|
||||
if err := rows.Scan(&revision.uuid, &revision.body); err != nil {
|
||||
// Fetch only identifiers in batches, then hydrate one legacy body at a
|
||||
// time. The old implementation accumulated all payloads in memory.
|
||||
lastUUID := ""
|
||||
for {
|
||||
rows, err := db.Query(`SELECT uuid FROM revisions WHERE uuid>? AND (document_hash IS NULL OR document_hash='') ORDER BY uuid LIMIT 128`, lastUUID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
revisions = append(revisions, revision)
|
||||
}
|
||||
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, revision := range revisions {
|
||||
sum := sha256.Sum256([]byte(revision.body))
|
||||
documentHash := hex.EncodeToString(sum[:])
|
||||
|
||||
if _, err := db.Exec(`
|
||||
UPDATE revisions
|
||||
SET document_hash = ?
|
||||
WHERE uuid = ?
|
||||
`, documentHash, revision.uuid); err != nil {
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range ids {
|
||||
var body string
|
||||
if err := db.QueryRow(`SELECT COALESCE(body,'') FROM revisions WHERE uuid=?`, id).Scan(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
sum := sha256.Sum256([]byte(body))
|
||||
if _, err := db.Exec(`UPDATE revisions SET document_hash=? WHERE uuid=? AND (document_hash IS NULL OR document_hash='')`, hex.EncodeToString(sum[:]), id); err != nil {
|
||||
return err
|
||||
}
|
||||
lastUUID = id
|
||||
}
|
||||
if len(ids) < 128 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = db.Exec(`
|
||||
if _, err := db.Exec(`
|
||||
UPDATE revisions
|
||||
SET
|
||||
lang = COALESCE(NULLIF(lang, ''), 'und'),
|
||||
@@ -247,7 +208,7 @@ func migrateRevisionMetadata(db *sql.DB) error {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err = db.Exec(`
|
||||
if _, err := db.Exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_revisions_object_created
|
||||
ON revisions (
|
||||
object_uuid,
|
||||
@@ -257,9 +218,45 @@ func migrateRevisionMetadata(db *sql.DB) error {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = db.Exec(`
|
||||
_, err := db.Exec(`
|
||||
INSERT OR IGNORE INTO schema_migrations (name, applied_at)
|
||||
VALUES ('revision_metadata_v1', strftime('%s','now'))
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
func sqliteColumnExists(database *sql.DB, table, column string) (bool, error) {
|
||||
// All identifiers originate in the fixed legacy bootstrap above.
|
||||
rows, err := database.Query(fmt.Sprintf("PRAGMA table_info(%q)", table))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
found := false
|
||||
for rows.Next() {
|
||||
var cid, notNull, primaryKey int
|
||||
var name, kind string
|
||||
var defaultValue any
|
||||
if err := rows.Scan(&cid, &name, &kind, ¬Null, &defaultValue, &primaryKey); err != nil {
|
||||
return false, err
|
||||
}
|
||||
found = found || name == column
|
||||
}
|
||||
return found, rows.Err()
|
||||
}
|
||||
|
||||
func ensureSQLiteColumn(database *sql.DB, table, column, declaration string) error {
|
||||
exists, err := sqliteColumnExists(database, table, column)
|
||||
if err != nil || exists {
|
||||
return err
|
||||
}
|
||||
_, err = database.Exec(fmt.Sprintf("ALTER TABLE %q ADD COLUMN %q %s", table, column, declaration))
|
||||
if err != nil {
|
||||
// Only tolerate another bootstrap adding the exact column concurrently.
|
||||
if exists, checkErr := sqliteColumnExists(database, table, column); checkErr == nil && exists {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("add column %s.%s: %w", table, column, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type MigrationPlanStep struct {
|
||||
Version int `json:"version"`
|
||||
Name string `json:"name"`
|
||||
Statements int `json:"statements"`
|
||||
AddColumns []SQLiteColumn `json:"add_columns,omitempty"`
|
||||
}
|
||||
|
||||
type MigrationInspection struct {
|
||||
Component string `json:"component"`
|
||||
State string `json:"state"` // current, pending, blocked, unknown
|
||||
AppliedVersion int `json:"applied_version"`
|
||||
LatestVersion int `json:"latest_version"`
|
||||
Pending []MigrationPlanStep `json:"pending,omitempty"`
|
||||
ContractChecked bool `json:"contract_checked"`
|
||||
Issues []string `json:"issues,omitempty"`
|
||||
}
|
||||
|
||||
// InspectSQLiteMigrations takes a read transaction and never applies DDL/DML.
|
||||
// Pending definitions are a plan, not a successful rehearsal: data-dependent
|
||||
// DDL and assertions on not-yet-created objects require a disposable DB copy.
|
||||
func InspectSQLiteMigrations(ctx context.Context, database *sql.DB, plans map[string][]SQLMigration) ([]MigrationInspection, error) {
|
||||
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var ledger bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_migration_steps')`).Scan(&ledger); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type record struct {
|
||||
version int
|
||||
name, checksum string
|
||||
}
|
||||
history := map[string][]record{}
|
||||
if ledger {
|
||||
rows, err := tx.QueryContext(ctx, `SELECT component,version,name,checksum FROM schema_migration_steps ORDER BY component,version`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var component string
|
||||
var r record
|
||||
if err := rows.Scan(&component, &r.version, &r.name, &r.checksum); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
history[component] = append(history[component], r)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
names := make([]string, 0, len(plans)+len(history))
|
||||
for name := range plans {
|
||||
names = append(names, name)
|
||||
}
|
||||
for name := range history {
|
||||
if _, ok := plans[name]; !ok {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
result := make([]MigrationInspection, 0, len(names))
|
||||
for _, name := range names {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
steps, known := plans[name]
|
||||
item := MigrationInspection{Component: name, State: "current", LatestVersion: len(steps)}
|
||||
for i, step := range steps {
|
||||
if step.Version != i+1 || step.Name == "" || (len(step.Statements) == 0 && len(step.AddColumns) == 0 && len(step.Assertions) == 0) {
|
||||
return nil, fmt.Errorf("invalid migration definition %s/%d", name, step.Version)
|
||||
}
|
||||
}
|
||||
if !known {
|
||||
item.State = "unknown"
|
||||
item.Issues = []string{"component is not registered in this binary"}
|
||||
}
|
||||
for i, record := range history[name] {
|
||||
item.AppliedVersion = record.version
|
||||
if known && (record.version != i+1 || record.version > len(steps) || record.name != steps[record.version-1].Name || record.checksum != migrationChecksum(steps[record.version-1])) {
|
||||
item.State = "blocked"
|
||||
item.Issues = append(item.Issues, fmt.Sprintf("migration history mismatch at version %d", record.version))
|
||||
}
|
||||
}
|
||||
if item.State == "current" {
|
||||
for _, step := range steps[len(history[name]):] {
|
||||
item.Pending = append(item.Pending, MigrationPlanStep{Version: step.Version, Name: step.Name, Statements: len(step.Statements), AddColumns: step.AddColumns})
|
||||
}
|
||||
if len(item.Pending) > 0 {
|
||||
item.State = "pending"
|
||||
}
|
||||
if len(steps) > 0 && len(steps[len(steps)-1].Assertions) > 0 {
|
||||
item.ContractChecked = true
|
||||
for i, assertion := range steps[len(steps)-1].Assertions {
|
||||
rows, err := tx.QueryContext(ctx, assertion)
|
||||
if err != nil {
|
||||
item.Issues = append(item.Issues, fmt.Sprintf("assertion %d: %v", i+1, err))
|
||||
continue
|
||||
}
|
||||
violated := rows.Next()
|
||||
err = rows.Err()
|
||||
closeErr := rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return nil, closeErr
|
||||
}
|
||||
if violated {
|
||||
item.Issues = append(item.Issues, fmt.Sprintf("assertion %d failed", i+1))
|
||||
}
|
||||
}
|
||||
if len(item.Issues) > 0 && item.State == "current" {
|
||||
item.State = "blocked"
|
||||
}
|
||||
}
|
||||
}
|
||||
result = append(result, item)
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, tx.Commit()
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInspectMigrationsReadOnlyLifecycle(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "inspect.db")
|
||||
writer, err := Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer writer.Close()
|
||||
if err := writer.Ping(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := OpenReadOnly(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
steps := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample(id INTEGER PRIMARY KEY, value TEXT)`, `INSERT INTO sample VALUES(1,'keep')`}, Assertions: []string{`SELECT id,value FROM sample LIMIT 0`}}}
|
||||
plans := map[string][]SQLMigration{"sample": steps}
|
||||
inspect := func(state string, issues bool) {
|
||||
t.Helper()
|
||||
got, err := InspectSQLiteMigrations(context.Background(), reader, plans)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 1 || got[0].State != state || (len(got[0].Issues) > 0) != issues || !got[0].ContractChecked {
|
||||
t.Fatalf("report: %+v", got)
|
||||
}
|
||||
}
|
||||
inspect("pending", true)
|
||||
var count int
|
||||
if err := writer.QueryRow(`SELECT count(*) FROM sqlite_master WHERE name IN ('sample','schema_migration_steps')`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("inspection created tables: %d %v", count, err)
|
||||
}
|
||||
if _, err := reader.Exec(`CREATE TABLE forbidden(id INTEGER)`); err == nil {
|
||||
t.Fatal("connection is writable")
|
||||
}
|
||||
// Keep the writer open: the reader must see committed WAL contents too.
|
||||
if err := ApplySQLiteMigrations(context.Background(), writer, "sample", steps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inspect("current", false)
|
||||
if _, err := writer.Exec(`ALTER TABLE sample RENAME COLUMN value TO lost`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inspect("blocked", true)
|
||||
var value string
|
||||
if err := writer.QueryRow(`SELECT lost FROM sample WHERE id=1`).Scan(&value); err != nil || value != "keep" {
|
||||
t.Fatalf("inspection changed data: %q %v", value, err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := InspectSQLiteMigrations(ctx, reader, plans); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancel: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectMigrationsRejectHistoryMismatch(t *testing.T) {
|
||||
for _, tc := range []struct{ name, mutation string }{
|
||||
{"checksum", `UPDATE schema_migration_steps SET checksum='changed'`},
|
||||
{"name", `UPDATE schema_migration_steps SET name='changed'`},
|
||||
{"zero", `UPDATE schema_migration_steps SET version=0`},
|
||||
{"negative", `UPDATE schema_migration_steps SET version=-1`},
|
||||
{"newer", `UPDATE schema_migration_steps SET version=2`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
database, err := Open(filepath.Join(t.TempDir(), "inspect.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
steps := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample(id INTEGER)`}}}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "sample", steps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := database.Exec(tc.mutation); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := InspectSQLiteMigrations(context.Background(), database, map[string][]SQLMigration{"sample": steps})
|
||||
if err != nil || len(got) != 1 || got[0].State != "blocked" {
|
||||
t.Fatalf("report=%+v err=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectMigrationsUnknownAndPendingPlan(t *testing.T) {
|
||||
database, err := Open(filepath.Join(t.TempDir(), "inspect.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
steps := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample(id INTEGER)`}}}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "sample", steps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := InspectSQLiteMigrations(context.Background(), database, nil)
|
||||
if err != nil || len(got) != 1 || got[0].State != "unknown" {
|
||||
t.Fatalf("unknown=%+v %v", got, err)
|
||||
}
|
||||
steps = append(steps, SQLMigration{Version: 2, Name: "add_value", AddColumns: []SQLiteColumn{{Table: "sample", Name: "value", Declaration: "TEXT NOT NULL DEFAULT ''"}}, Assertions: []string{`SELECT value FROM sample LIMIT 0`}})
|
||||
got, err = InspectSQLiteMigrations(context.Background(), database, map[string][]SQLMigration{"sample": steps})
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("pending=%+v %v", got, err)
|
||||
}
|
||||
item := got[0]
|
||||
if item.State != "pending" || item.AppliedVersion != 1 || item.LatestVersion != 2 || len(item.Pending) != 1 || len(item.Pending[0].AddColumns) != 1 || len(item.Issues) == 0 {
|
||||
t.Fatalf("pending=%+v", item)
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM pragma_table_info('sample') WHERE name='value'`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("pending DDL applied: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SQLMigration is append-only once released. Edit a new version, never an
|
||||
// applied statement. This runner is SQLite-specific; other DBs need their own
|
||||
// locking/DDL implementations rather than a driver-name substitution.
|
||||
type SQLMigration struct {
|
||||
Version int
|
||||
Name string
|
||||
Statements []string
|
||||
// Omit empty new fields to preserve checksums of previously released steps.
|
||||
AddColumns []SQLiteColumn `json:",omitempty"`
|
||||
// Each assertion must execute successfully and return no rows. The latest
|
||||
// version defines the whole current contract; older assertions are superseded
|
||||
// to permit deliberate column removal in a later, immutable migration.
|
||||
Assertions []string `json:",omitempty"`
|
||||
}
|
||||
|
||||
type SQLiteColumn struct {
|
||||
Table string
|
||||
Name string
|
||||
Declaration string
|
||||
}
|
||||
|
||||
func migrationChecksum(step SQLMigration) string {
|
||||
encoded, _ := json.Marshal(step)
|
||||
sum := sha256.Sum256(encoded)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// ApplySQLiteMigrations serializes processes on a dedicated connection with
|
||||
// BEGIN IMMEDIATE. DDL, data statements and ledger updates commit together.
|
||||
// The legacy schema_migrations table remains untouched for old installations.
|
||||
func ApplySQLiteMigrations(ctx context.Context, database *sql.DB, component string, steps []SQLMigration) error {
|
||||
if component == "" {
|
||||
return fmt.Errorf("migration component is required")
|
||||
}
|
||||
for i, step := range steps {
|
||||
if step.Version != i+1 || step.Name == "" || (len(step.Statements) == 0 && len(step.AddColumns) == 0 && len(step.Assertions) == 0) {
|
||||
return fmt.Errorf("invalid migration sequence for %s", component)
|
||||
}
|
||||
}
|
||||
conn, err := database.Conn(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migration %s acquire connection: %w", component, err)
|
||||
}
|
||||
defer conn.Close()
|
||||
if _, err := conn.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
|
||||
return fmt.Errorf("migration %s begin immediate: %w", component, err)
|
||||
}
|
||||
committed := false
|
||||
defer func() {
|
||||
if committed {
|
||||
return
|
||||
}
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if _, err := conn.ExecContext(cleanup, "ROLLBACK"); err != nil {
|
||||
// Never return a connection with uncertain transaction state to
|
||||
// the pool. A failed/ambiguous COMMIT also takes this path.
|
||||
_ = conn.Raw(func(any) error { return driver.ErrBadConn })
|
||||
}
|
||||
}()
|
||||
if _, err := conn.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_migration_steps (
|
||||
component TEXT NOT NULL, version INTEGER NOT NULL, name TEXT NOT NULL,
|
||||
checksum TEXT NOT NULL, applied_at_ms INTEGER NOT NULL,
|
||||
PRIMARY KEY(component, version))`); err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := conn.QueryContext(ctx, `SELECT version,name,checksum FROM schema_migration_steps WHERE component=? ORDER BY version`, component)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
applied := 0
|
||||
for rows.Next() {
|
||||
var version int
|
||||
var name, checksum string
|
||||
if err := rows.Scan(&version, &name, &checksum); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if version != applied+1 || version > len(steps) || steps[version-1].Name != name || migrationChecksum(steps[version-1]) != checksum {
|
||||
rows.Close()
|
||||
return fmt.Errorf("migration history mismatch: component=%s version=%d (changed, missing or newer migration)", component, version)
|
||||
}
|
||||
applied++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, step := range steps[applied:] {
|
||||
for i, statement := range step.Statements {
|
||||
if _, err := conn.ExecContext(ctx, statement); err != nil {
|
||||
return fmt.Errorf("migration %s/%d %s statement %d: %w", component, step.Version, step.Name, i+1, err)
|
||||
}
|
||||
}
|
||||
for _, column := range step.AddColumns {
|
||||
if err := addSQLiteColumn(ctx, conn, column); err != nil {
|
||||
return fmt.Errorf("migration %s/%d column %s.%s: %w", component, step.Version, column.Table, column.Name, err)
|
||||
}
|
||||
}
|
||||
if _, err := conn.ExecContext(ctx, `INSERT INTO schema_migration_steps(component,version,name,checksum,applied_at_ms) VALUES(?,?,?,?,?)`, component, step.Version, step.Name, migrationChecksum(step), time.Now().UnixMilli()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(steps) > 0 {
|
||||
step := steps[len(steps)-1]
|
||||
for i, assertion := range step.Assertions {
|
||||
rows, err := conn.QueryContext(ctx, assertion)
|
||||
if err != nil {
|
||||
return fmt.Errorf("schema contract %s/%d assertion %d: %w", component, step.Version, i+1, err)
|
||||
}
|
||||
violated := rows.Next()
|
||||
err = rows.Err()
|
||||
closeErr := rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
if violated {
|
||||
return fmt.Errorf("schema contract %s/%d assertion %d failed", component, step.Version, i+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
_, err = conn.ExecContext(ctx, "COMMIT")
|
||||
committed = err == nil
|
||||
return err
|
||||
}
|
||||
|
||||
func addSQLiteColumn(ctx context.Context, conn *sql.Conn, column SQLiteColumn) error {
|
||||
// Identifiers are trusted migration definitions, but validate before SQL
|
||||
// interpolation so accidental punctuation cannot change the statement.
|
||||
for _, identifier := range []string{column.Table, column.Name} {
|
||||
if identifier == "" || strings.IndexFunc(identifier, func(r rune) bool {
|
||||
return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_')
|
||||
}) >= 0 {
|
||||
return fmt.Errorf("invalid schema identifier")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(column.Declaration) == "" {
|
||||
return fmt.Errorf("column declaration is required")
|
||||
}
|
||||
rows, err := conn.QueryContext(ctx, `SELECT name FROM pragma_table_info(?)`, column.Table)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found, tableExists := false, false
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
found, tableExists = found || name == column.Name, true
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !tableExists {
|
||||
return fmt.Errorf("table %s is missing", column.Table)
|
||||
}
|
||||
if found {
|
||||
return nil
|
||||
}
|
||||
_, err = conn.ExecContext(ctx, fmt.Sprintf("ALTER TABLE %q ADD COLUMN %q %s", column.Table, column.Name, column.Declaration))
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSQLMigrationLedgerConcurrencyAndChecksum(t *testing.T) {
|
||||
database, err := Open(filepath.Join(t.TempDir(), "migration.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
steps := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample (id INTEGER PRIMARY KEY)`, `INSERT INTO sample VALUES (1)`}}}
|
||||
var wg sync.WaitGroup
|
||||
errors := make(chan error, 6)
|
||||
for i := 0; i < 6; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
errors <- ApplySQLiteMigrations(context.Background(), database, "test", steps)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errors)
|
||||
for err := range errors {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM sample`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("count=%d err=%v", count, err)
|
||||
}
|
||||
changed := []SQLMigration{{Version: 1, Name: "initial", Statements: []string{`CREATE TABLE sample (id TEXT)`}}}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", changed); err == nil || !strings.Contains(err.Error(), "history mismatch") {
|
||||
t.Fatalf("changed migration accepted: %v", err)
|
||||
}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", nil); err == nil {
|
||||
t.Fatal("downgrade accepted")
|
||||
}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "other", []SQLMigration{{Version: 2, Name: "gap", Statements: []string{`SELECT 1`}}}); err == nil {
|
||||
t.Fatal("version gap accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLMigrationFailureRollsBackDDLAndLedger(t *testing.T) {
|
||||
database, err := Open(filepath.Join(t.TempDir(), "migration.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
steps := []SQLMigration{{Version: 1, Name: "broken", Statements: []string{`CREATE TABLE partial (id INTEGER)`, `NOT VALID SQL`}}}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err == nil {
|
||||
t.Fatal("DDL failure ignored")
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM sqlite_master WHERE name IN ('partial','schema_migration_steps')`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("partial migration remains count=%d err=%v", count, err)
|
||||
}
|
||||
steps[0].Statements = steps[0].Statements[:1]
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
|
||||
t.Fatal("retry after rollback", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := ApplySQLiteMigrations(ctx, database, "test", steps); err == nil {
|
||||
t.Fatal("cancel ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyRevisionHashMigrationSpansBoundedBatches(t *testing.T) {
|
||||
database, err := Open(filepath.Join(t.TempDir(), "legacy.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if _, err := database.Exec(`CREATE TABLE revisions (uuid TEXT PRIMARY KEY,object_uuid TEXT,body TEXT,message TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 260; i++ {
|
||||
if _, err := database.Exec(`INSERT INTO revisions(uuid,body) VALUES(?,?)`, fmt.Sprintf("revision-%04d", i), "body"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM revisions WHERE length(document_hash)=64 AND lang='und' AND created_at_ms=0`).Scan(&count); err != nil || count != 260 {
|
||||
t.Fatalf("migrated=%d err=%v", count, err)
|
||||
}
|
||||
if err := ensureSQLiteColumn(database, "does_not_exist", "created_at", "INTEGER"); err == nil {
|
||||
t.Fatal("ALTER failure swallowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationChecksumPreservesLegacyFormat(t *testing.T) {
|
||||
step := SQLMigration{Version: 1, Name: "legacy", Statements: []string{"SELECT 1"}}
|
||||
sum := sha256.Sum256([]byte(`{"Version":1,"Name":"legacy","Statements":["SELECT 1"]}`))
|
||||
if got := migrationChecksum(step); got != hex.EncodeToString(sum[:]) {
|
||||
t.Fatalf("legacy checksum changed: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationConditionalColumnsAndAssertionsAreAtomic(t *testing.T) {
|
||||
database, err := Open(filepath.Join(t.TempDir(), "schema.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if _, err := database.Exec(`CREATE TABLE sample(id INTEGER PRIMARY KEY); INSERT INTO sample VALUES(1)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
steps := []SQLMigration{{Version: 1, Name: "adopt", AddColumns: []SQLiteColumn{{Table: "sample", Name: "value", Declaration: "TEXT NOT NULL DEFAULT ''"}}, Assertions: []string{`SELECT missing FROM sample LIMIT 0`}}}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err == nil {
|
||||
t.Fatal("invalid schema accepted")
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM pragma_table_info('sample') WHERE name='value'`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatalf("ALTER was not rolled back: %d %v", count, err)
|
||||
}
|
||||
steps[0].Assertions = []string{`SELECT id,value FROM sample LIMIT 0`}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
|
||||
t.Fatal("repeated apply", err)
|
||||
}
|
||||
var value string
|
||||
if err := database.QueryRow(`SELECT value FROM sample WHERE id=1`).Scan(&value); err != nil || value != "" {
|
||||
t.Fatalf("legacy row lost: %q %v", value, err)
|
||||
}
|
||||
steps = append(steps, SQLMigration{Version: 2, Name: "remove_value", Statements: []string{`ALTER TABLE sample DROP COLUMN value`}, Assertions: []string{`SELECT id FROM sample LIMIT 0`}})
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err != nil {
|
||||
t.Fatal("new contract must supersede old contract", err)
|
||||
}
|
||||
if _, err := database.Exec(`DROP TABLE sample`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ApplySQLiteMigrations(context.Background(), database, "test", steps); err == nil {
|
||||
t.Fatal("recorded history masked missing table")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// OpenReadOnly deliberately does not migrate, set journal_mode, or create a DB.
|
||||
func OpenReadOnly(path string) (*sql.DB, error) {
|
||||
path, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dsn := (&url.URL{Scheme: "file", Path: path, RawQuery: url.Values{"mode": {"ro"}, "_pragma": {"query_only(1)", "busy_timeout(5000)"}}.Encode()}).String()
|
||||
database, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = database.Ping(); err != nil {
|
||||
database.Close()
|
||||
return nil, err
|
||||
}
|
||||
return database, nil
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package documentstore_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/documentstore"
|
||||
"pageswiki/internal/geduldh"
|
||||
)
|
||||
|
||||
// These assignments intentionally fail compilation if aliases become wrappers
|
||||
// with different type identities or constructor signatures.
|
||||
var (
|
||||
_ func(string) (*geduldh.Local, error) = documentstore.NewLocal
|
||||
_ func(documentstore.Source, documentstore.MaterializeOptions) (*documentstore.Materializer, error) = geduldh.NewMaterializer
|
||||
_ documentstore.Store = (*geduldh.Local)(nil)
|
||||
_ geduldh.Store = (*documentstore.Local)(nil)
|
||||
)
|
||||
|
||||
func TestGeduldhLegacyLayoutAndSharedIdentity(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
root := t.TempDir()
|
||||
body := []byte("existing Document 日本語\x00\xff")
|
||||
sum := sha256.Sum256(body)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
// Seed the pre-extraction layout independently of either Key implementation.
|
||||
filename := filepath.Join(root, "sha256", hash[:2], hash)
|
||||
if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filename, body, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old, err := documentstore.NewLocal(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current, err := geduldh.NewLocal(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, backend := range []geduldh.Store{old, current} {
|
||||
// The old normalization rules and payload bytes stay unchanged.
|
||||
inputHash := " " + strings.ToUpper(hash) + " "
|
||||
info, err := backend.Stat(ctx, inputHash)
|
||||
if err != nil || info.Hash != hash || info.Size != int64(len(body)) {
|
||||
t.Fatalf("stat=%+v err=%v", info, err)
|
||||
}
|
||||
reader, err := backend.Open(ctx, inputHash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
func() {
|
||||
defer reader.Close()
|
||||
if _, err := reader.Seek(2, io.SeekStart); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
buf := make([]byte, 4)
|
||||
if _, err := reader.ReadAt(buf, 5); err != nil || !bytes.Equal(buf, body[5:9]) {
|
||||
t.Fatalf("ReadAt=%q err=%v", buf, err)
|
||||
}
|
||||
// ReaderAt must not move the sequential stream cursor (ZIP and Range).
|
||||
data, err := io.ReadAll(reader)
|
||||
if err != nil || !bytes.Equal(data, body[2:]) {
|
||||
t.Fatalf("stream=%q err=%v", data, err)
|
||||
}
|
||||
}()
|
||||
if err := backend.PutIfAbsent(ctx, hash, int64(len(body)), bytes.NewReader(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := backend.Verify(ctx, hash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
after, err := os.Stat(filename)
|
||||
if err != nil || !os.SameFile(before, after) {
|
||||
t.Fatalf("canonical inode replaced: %v", err)
|
||||
}
|
||||
oldKey, err := documentstore.Key(hash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newKey, err := geduldh.Key(hash)
|
||||
if err != nil || oldKey != newKey || oldKey != "sha256/"+hash[:2]+"/"+hash {
|
||||
t.Fatalf("key changed: %s %s %v", oldKey, newKey, err)
|
||||
}
|
||||
if documentstore.ErrInvalidHash != geduldh.ErrInvalidHash || documentstore.ErrHashMismatch != geduldh.ErrHashMismatch || documentstore.ErrSizeMismatch != geduldh.ErrSizeMismatch || documentstore.ErrMaterializeLimit != geduldh.ErrMaterializeLimit {
|
||||
t.Fatal("legacy error identity changed")
|
||||
}
|
||||
if err := os.WriteFile(filename, []byte("corrupt"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, backend := range []geduldh.Store{old, current} {
|
||||
if err := backend.PutIfAbsent(ctx, hash, int64(len(body)), bytes.NewReader(body)); !errors.Is(err, documentstore.ErrHashMismatch) {
|
||||
t.Fatalf("corruption repaired or error changed: %v", err)
|
||||
}
|
||||
}
|
||||
corrupt, err := os.ReadFile(filename)
|
||||
if err != nil || string(corrupt) != "corrupt" {
|
||||
t.Fatalf("corrupt canonical overwritten: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeduldhCompatibilityMaterializer(t *testing.T) {
|
||||
root, scratch := t.TempDir(), t.TempDir()
|
||||
backend, err := geduldh.NewLocal(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := []byte("shared scratch bytes")
|
||||
sum := sha256.Sum256(body)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
ctx := context.Background()
|
||||
if err := backend.PutIfAbsent(ctx, hash, int64(len(body)), bytes.NewReader(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var materializer *geduldh.Materializer
|
||||
materializer, err = documentstore.NewMaterializer(backend, documentstore.MaterializeOptions{TempDir: scratch, MaxBytes: 1024, Concurrent: 1, Timeout: time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var first *documentstore.Lease
|
||||
first, err = materializer.Acquire(ctx, hash, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer first.Close()
|
||||
second, err := materializer.Acquire(ctx, hash, 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer second.Close()
|
||||
if first.Path != second.Path {
|
||||
t.Fatal("legacy/current leases no longer share the same copy")
|
||||
}
|
||||
first.Close()
|
||||
data, err := os.ReadFile(second.Path)
|
||||
if err != nil || !bytes.Equal(data, body) {
|
||||
t.Fatalf("active lease lost: %v", err)
|
||||
}
|
||||
second.Close()
|
||||
if _, err := os.Stat(second.Path); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("scratch not reclaimed: %v", err)
|
||||
}
|
||||
if err := backend.Verify(ctx, hash); err != nil {
|
||||
t.Fatal("lease cleanup affected canonical content", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeduldhConstructorsDoNotProvisionRoots(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "missing")
|
||||
for _, create := range []func(string) (*geduldh.Local, error){documentstore.NewLocal, geduldh.NewLocal} {
|
||||
if _, err := create(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("constructor wrote to storage root: %v", err)
|
||||
}
|
||||
if _, err := create(" "); err == nil {
|
||||
t.Fatal("empty root accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// Package documentstore preserves the original Document Store entry points.
|
||||
// Payload storage and scratch materialization are implemented by Geduldh.
|
||||
// New consumers should use pageswiki/internal/geduldh directly.
|
||||
package documentstore
|
||||
|
||||
import "pageswiki/internal/geduldh"
|
||||
|
||||
// Aliases preserve interface/type identity, method sets and error matching.
|
||||
// This package must not acquire its own persistence or validation logic.
|
||||
type (
|
||||
Info = geduldh.Info
|
||||
Reader = geduldh.Reader
|
||||
Store = geduldh.Store
|
||||
Local = geduldh.Local
|
||||
Source = geduldh.Source
|
||||
MaterializeOptions = geduldh.MaterializeOptions
|
||||
Materializer = geduldh.Materializer
|
||||
Lease = geduldh.Lease
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidHash = geduldh.ErrInvalidHash
|
||||
ErrHashMismatch = geduldh.ErrHashMismatch
|
||||
ErrSizeMismatch = geduldh.ErrSizeMismatch
|
||||
ErrMaterializeLimit = geduldh.ErrMaterializeLimit
|
||||
)
|
||||
|
||||
func Key(hash string) (string, error) { return geduldh.Key(hash) }
|
||||
|
||||
func NewLocal(root string) (*Local, error) { return geduldh.NewLocal(root) }
|
||||
|
||||
func NewMaterializer(source Source, options MaterializeOptions) (*Materializer, error) {
|
||||
return geduldh.NewMaterializer(source, options)
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package dr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
func fixture(t *testing.T) string {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
database, err := db.Open(filepath.Join(root, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = database.Exec("CREATE TABLE revisions(document_hash TEXT); INSERT INTO revisions(rowid,document_hash) VALUES(42,'')"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = database.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = Init(root); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(root, "auth.key"), make([]byte, 32), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return root
|
||||
}
|
||||
|
||||
func TestSnapshotRestorePromote(t *testing.T) {
|
||||
root := fixture(t)
|
||||
ctx := context.Background()
|
||||
dest := filepath.Join(t.TempDir(), "snapshot")
|
||||
body := []byte("synthetic DR test document")
|
||||
sum := sha256.Sum256(body)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
path := filepath.Join(root, "documents", "sha256", hash[:2], hash)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, body, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
database, err := db.Open(filepath.Join(root, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Hold a connection open to keep committed WAL pages present. No writer is
|
||||
// active during snapshot; this covers recovery after an uncheckpointed stop.
|
||||
if _, err = database.Exec("PRAGMA wal_autocheckpoint=0; UPDATE revisions SET document_hash=? WHERE rowid=42", hash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err = os.MkdirAll(filepath.Join(root, "previews"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(root, "previews", "ignored"), []byte("cache"), 0600)
|
||||
m, digest, err := Snapshot(ctx, root, dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = Verify(ctx, dest, digest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = Verify(ctx, dest, digest); err != nil {
|
||||
t.Fatalf("verification must not mutate snapshot: %v", err)
|
||||
}
|
||||
restored := filepath.Join(t.TempDir(), "standby")
|
||||
node, err := Restore(ctx, dest, digest, restored)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if node.Role != "standby" || node.NodeID == node.PrimaryNodeID || node.SnapshotID != m.ID || !node.Readable(time.Now()) {
|
||||
t.Fatalf("bad standby: %+v", node)
|
||||
}
|
||||
if _, err = os.Stat(filepath.Join(restored, "previews")); !os.IsNotExist(err) {
|
||||
t.Fatal("copied cache")
|
||||
}
|
||||
ro, err := db.OpenReadOnly(filepath.Join(restored, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ro.Close()
|
||||
var got string
|
||||
if err = ro.QueryRow("SELECT document_hash FROM revisions WHERE rowid=42").Scan(&got); err != nil || got != hash {
|
||||
t.Fatalf("WAL or rowid lost: %s %v", got, err)
|
||||
}
|
||||
if _, err = ro.Exec("DELETE FROM revisions"); err == nil {
|
||||
t.Fatal("standby accepted write")
|
||||
}
|
||||
shared, err := Lock(restored, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = Promote(restored, node.PrimaryNodeID, "test fence", true); err == nil {
|
||||
t.Fatal("promoted running standby")
|
||||
}
|
||||
shared.Close()
|
||||
if _, err = Promote(restored, "wrong", "test fence", true); err == nil {
|
||||
t.Fatal("accepted wrong primary")
|
||||
}
|
||||
if _, err = Promote(restored, node.PrimaryNodeID, "test fence", false); err == nil {
|
||||
t.Fatal("accepted implicit data loss")
|
||||
}
|
||||
promoted, err := Promote(restored, node.PrimaryNodeID, "test fence", true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if promoted.Role != "primary" || promoted.Epoch != node.Epoch+1 || len(promoted.History) != 1 {
|
||||
t.Fatalf("bad promotion: %+v", promoted)
|
||||
}
|
||||
if promoted.WorkersEnabled {
|
||||
t.Fatal("promotion replayed jobs without review")
|
||||
}
|
||||
if _, err = ResumeWorkers(restored, false); err == nil {
|
||||
t.Fatal("resumed jobs without review")
|
||||
}
|
||||
resumed, err := ResumeWorkers(restored, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !resumed.WorkersEnabled || resumed.WorkersResumedAt.IsZero() {
|
||||
t.Fatal("worker resumption not audited")
|
||||
}
|
||||
if _, err = Restore(ctx, dest, digest, restored); err == nil {
|
||||
t.Fatal("overwrote existing restore")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotCalendarReferencesAndRestoreSafety(t *testing.T) {
|
||||
root := fixture(t)
|
||||
dir := filepath.Join(root, "documents", "calendars", "synthetic-domain", "synthetic-calendar")
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := []byte("synthetic opaque monthly generation; no external calendar data")
|
||||
sum := sha256.Sum256(body)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
metadata, _ := json.Marshal(map[string]any{"months": map[string]string{"2026-09": hash}})
|
||||
if err := os.WriteFile(filepath.Join(dir, "calendar.json"), metadata, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest := filepath.Join(t.TempDir(), "snapshot")
|
||||
if _, _, err := Snapshot(context.Background(), root, dest); err == nil {
|
||||
t.Fatal("accepted missing calendar month")
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "2026-09."+hash+".ics"), body, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, digest, err := Snapshot(context.Background(), root, dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = Verify(context.Background(), dest, digest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = Snapshot(context.Background(), root, filepath.Join(root, "inside")); err == nil {
|
||||
t.Fatal("snapshot inside source accepted")
|
||||
}
|
||||
if _, err = Restore(context.Background(), dest, digest, root); err == nil {
|
||||
t.Fatal("restore overwrote existing data")
|
||||
}
|
||||
if _, err = Restore(context.Background(), dest, digest, filepath.Join(dest, "nested")); err == nil {
|
||||
t.Fatal("restore corrupted source snapshot")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err = Verify(ctx, dest, digest); err == nil {
|
||||
t.Fatal("verification ignored cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRefusesActiveMissingAndSymlink(t *testing.T) {
|
||||
root := fixture(t)
|
||||
dest := filepath.Join(t.TempDir(), "snapshot")
|
||||
ctx := context.Background()
|
||||
shared, err := Lock(root, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = Snapshot(ctx, root, dest); err == nil {
|
||||
t.Fatal("snapshotted running instance")
|
||||
}
|
||||
shared.Close()
|
||||
database, err := db.Open(filepath.Join(root, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = database.Exec("UPDATE revisions SET document_hash=?", string(make([]byte, 64)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
database.Close()
|
||||
if _, _, err = Snapshot(ctx, root, dest); err == nil {
|
||||
t.Fatal("accepted missing canonical document")
|
||||
}
|
||||
if _, err = os.Stat(dest); !os.IsNotExist(err) {
|
||||
t.Fatal("published failed snapshot")
|
||||
}
|
||||
if err = os.Symlink(t.TempDir(), filepath.Join(root, "themes")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err = Snapshot(ctx, root, dest); err == nil {
|
||||
t.Fatal("followed source symlink")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotTamperAndPathValidation(t *testing.T) {
|
||||
root := fixture(t)
|
||||
dest := filepath.Join(t.TempDir(), "snapshot")
|
||||
ctx := context.Background()
|
||||
_, digest, err := Snapshot(ctx, root, dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = Verify(ctx, dest, ""); err == nil {
|
||||
t.Fatal("accepted unauthenticated manifest")
|
||||
}
|
||||
manifestPath := filepath.Join(dest, "manifest.json")
|
||||
encoded, err := os.ReadFile(manifestPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m Manifest
|
||||
if err = json.Unmarshal(encoded, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Files[0].Path = "../outside"
|
||||
altered, _ := json.Marshal(m)
|
||||
sum := sha256.Sum256(altered)
|
||||
os.WriteFile(manifestPath, altered, 0600)
|
||||
if _, err = Verify(ctx, dest, digest); err == nil {
|
||||
t.Fatal("accepted changed manifest")
|
||||
}
|
||||
if _, err = Verify(ctx, dest, hex.EncodeToString(sum[:])); err == nil {
|
||||
t.Fatal("accepted traversal even with matching manifest digest")
|
||||
}
|
||||
os.WriteFile(manifestPath, encoded, 0600)
|
||||
os.WriteFile(filepath.Join(dest, "data", "auth.key"), []byte("tampered"), 0600)
|
||||
if _, err = Verify(ctx, dest, digest); err == nil {
|
||||
t.Fatal("accepted payload tamper")
|
||||
}
|
||||
for _, path := range []string{"/etc/passwd", "documents/../auth.key", "documents\\foo", "dr-node.json", "pages.db-wal", "cache/foo"} {
|
||||
if canonical(path) {
|
||||
t.Errorf("accepted %q", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigFailsClosedAndExpiry(t *testing.T) {
|
||||
root := fixture(t)
|
||||
c, err := Load(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Role = "standby"
|
||||
if err = Save(root, *c); err == nil {
|
||||
t.Fatal("accepted inconsistent role")
|
||||
}
|
||||
os.WriteFile(filepath.Join(root, ConfigFile), []byte(`{"role":"broken"}`), 0600)
|
||||
if _, err = Load(root); err == nil {
|
||||
t.Fatal("invalid config accepted")
|
||||
}
|
||||
c.Role = "standby"
|
||||
c.CapturedAt = time.Now().Add(-2 * time.Hour)
|
||||
c.MaxReadAgeSeconds = 3600
|
||||
if c.Readable(time.Now()) {
|
||||
t.Fatal("stale snapshot is readable")
|
||||
}
|
||||
c.CapturedAt = time.Now().Add(time.Hour)
|
||||
if c.Readable(time.Now()) {
|
||||
t.Fatal("future snapshot is readable")
|
||||
}
|
||||
if err = RequireRole(nil, "standby"); err == nil {
|
||||
t.Fatal("empty standby volume would start writable")
|
||||
}
|
||||
if err = RequireRole(c, "primary"); err == nil {
|
||||
t.Fatal("mismatched deployment role accepted")
|
||||
}
|
||||
if err = RequireRole(c, "standby"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = RequireRole(nil, ""); err != nil {
|
||||
t.Fatal("legacy startup broken")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package dr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/geduldh"
|
||||
)
|
||||
|
||||
func TestGeduldhSnapshotRestoreCompatibility(t *testing.T) {
|
||||
root := fixture(t)
|
||||
documents := filepath.Join(root, "documents")
|
||||
if err := os.MkdirAll(documents, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backend, err := geduldh.NewLocal(documents)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := context.Background()
|
||||
body := []byte("Geduldh DR compatibility 日本語\x00\xff")
|
||||
sum := sha256.Sum256(body)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
if err := backend.PutIfAbsent(ctx, hash, int64(len(body)), bytes.NewReader(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
database, err := db.Open(filepath.Join(root, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if _, err := database.Exec(`UPDATE revisions SET document_hash=? WHERE rowid=42`, hash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
snapshot := filepath.Join(t.TempDir(), "snapshot")
|
||||
_, digest, err := Snapshot(ctx, root, snapshot)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Verify(ctx, snapshot, digest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
restored := filepath.Join(t.TempDir(), "standby")
|
||||
if _, err := Restore(ctx, snapshot, digest, restored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recovered, err := geduldh.NewLocal(filepath.Join(restored, "documents"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := recovered.Verify(ctx, hash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reader, err := recovered.Open(ctx, hash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
data, err := io.ReadAll(reader)
|
||||
if err != nil || !bytes.Equal(data, body) {
|
||||
t.Fatalf("restored payload changed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
// Package dr implements offline, operator-fenced recovery, not leader election.
|
||||
package dr
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const ConfigFile = "dr-node.json"
|
||||
const LockFile = ".pageswiki-instance.lock"
|
||||
|
||||
// RequireRole is an optional deployment guard against mounting an empty/wrong
|
||||
// data volume on a DR host and accidentally starting a new writable instance.
|
||||
func RequireRole(c *Config, expected string) error {
|
||||
if expected == "" {
|
||||
return nil
|
||||
}
|
||||
if expected != "primary" && expected != "standby" {
|
||||
return errors.New("PAGESWIKI_DR_EXPECT_ROLE must be primary or standby")
|
||||
}
|
||||
if c == nil || c.Role != expected {
|
||||
return errors.New("DR role does not match PAGESWIKI_DR_EXPECT_ROLE; refusing startup")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Promotion struct {
|
||||
At time.Time `json:"at"`
|
||||
PreviousNode string `json:"previous_node"`
|
||||
FenceReference string `json:"fence_reference"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
}
|
||||
|
||||
// Config is node-local and MUST NOT be overwritten by a primary's snapshot.
|
||||
// Epoch is an audit generation only; it is NOT a distributed fencing token.
|
||||
type Config struct {
|
||||
Version int `json:"version"`
|
||||
ClusterID string `json:"cluster_id"`
|
||||
NodeID string `json:"node_id"`
|
||||
PrimaryNodeID string `json:"primary_node_id"`
|
||||
Role string `json:"role"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
SnapshotID string `json:"snapshot_id,omitempty"`
|
||||
CapturedAt time.Time `json:"captured_at,omitempty"`
|
||||
MaxReadAgeSeconds int64 `json:"max_read_age_seconds"`
|
||||
WorkersEnabled bool `json:"workers_enabled"`
|
||||
WorkersResumedAt time.Time `json:"workers_resumed_at,omitempty"`
|
||||
History []Promotion `json:"promotion_history,omitempty"`
|
||||
}
|
||||
|
||||
func (c Config) Validate() error {
|
||||
for _, id := range []string{c.ClusterID, c.NodeID, c.PrimaryNodeID} {
|
||||
u, err := uuid.Parse(id)
|
||||
if err != nil || u == uuid.Nil || u.String() != id {
|
||||
return errors.New("DR identity must be a canonical nonzero UUID")
|
||||
}
|
||||
}
|
||||
if c.Version != 1 || c.Epoch == 0 || c.MaxReadAgeSeconds < 1 || c.MaxReadAgeSeconds > 86400 {
|
||||
return errors.New("invalid DR version, epoch or max_read_age_seconds (1..86400)")
|
||||
}
|
||||
if c.Role != "primary" && c.Role != "standby" {
|
||||
return errors.New("DR role must be primary or standby")
|
||||
}
|
||||
if (c.Role == "primary") != (c.PrimaryNodeID == c.NodeID) {
|
||||
return errors.New("DR role and primary identity disagree")
|
||||
}
|
||||
if c.Role == "standby" && (c.SnapshotID == "" || c.CapturedAt.IsZero()) {
|
||||
return errors.New("standby requires a verified snapshot")
|
||||
}
|
||||
if c.Role == "standby" && c.WorkersEnabled {
|
||||
return errors.New("standby cannot enable background workers")
|
||||
}
|
||||
if c.SnapshotID != "" {
|
||||
u, err := uuid.Parse(c.SnapshotID)
|
||||
if err != nil || u == uuid.Nil || u.String() != c.SnapshotID {
|
||||
return errors.New("invalid snapshot identity")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Config) Readable(now time.Time) bool {
|
||||
return c.Role == "standby" && !c.CapturedAt.After(now.Add(time.Minute)) && now.Sub(c.CapturedAt) <= time.Duration(c.MaxReadAgeSeconds)*time.Second
|
||||
}
|
||||
|
||||
func (c Config) ReadUntil() time.Time {
|
||||
if c.CapturedAt.After(time.Now().Add(time.Minute)) {
|
||||
return time.Time{}
|
||||
}
|
||||
return c.CapturedAt.Add(time.Duration(c.MaxReadAgeSeconds) * time.Second)
|
||||
}
|
||||
|
||||
func Load(dataDir string) (*Config, error) {
|
||||
f, err := os.Open(filepath.Join(dataDir, ConfigFile))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > 1<<20 {
|
||||
return nil, errors.New("invalid or oversized DR configuration")
|
||||
}
|
||||
var c Config
|
||||
d := json.NewDecoder(io.LimitReader(f, 1<<20))
|
||||
d.DisallowUnknownFields()
|
||||
if err = d.Decode(&c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = d.Decode(new(any)); err != io.EOF {
|
||||
return nil, errors.New("trailing DR configuration data")
|
||||
}
|
||||
return &c, c.Validate()
|
||||
}
|
||||
|
||||
func Save(dataDir string, c Config) error {
|
||||
if err := c.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
b, err := json.MarshalIndent(c, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(dataDir, ".dr-node-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
if _, err = f.Write(append(b, '\n')); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err = f.Sync(); err != nil {
|
||||
f.Close()
|
||||
return err
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = os.Rename(f.Name(), filepath.Join(dataDir, ConfigFile)); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncDir(dataDir)
|
||||
}
|
||||
|
||||
// Lock is shared for a running server/CLI, exclusive for offline maintenance.
|
||||
// Advisory locking cannot fence older binaries or an independent SQLite client.
|
||||
func Lock(dataDir string, exclusive bool) (*os.File, error) {
|
||||
// Shared locks also work with a read-only standby mount.
|
||||
path := filepath.Join(dataDir, LockFile)
|
||||
f, err := os.Open(path)
|
||||
if exclusive || errors.Is(err, os.ErrNotExist) {
|
||||
if f != nil {
|
||||
f.Close()
|
||||
}
|
||||
f, err = os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mode := syscall.LOCK_SH
|
||||
if exclusive {
|
||||
mode = syscall.LOCK_EX
|
||||
}
|
||||
if err = syscall.Flock(int(f.Fd()), mode|syscall.LOCK_NB); err != nil {
|
||||
f.Close()
|
||||
return nil, fmt.Errorf("DR data directory is in use; stop all writers/readers before maintenance: %w", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func Init(dataDir string) (*Config, error) {
|
||||
l, err := Lock(dataDir, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer l.Close()
|
||||
if c, err := Load(dataDir); err != nil || c != nil {
|
||||
return nil, errors.New("DR configuration exists or cannot be read; refusing initialization")
|
||||
}
|
||||
id := uuid.NewString()
|
||||
c := Config{Version: 1, ClusterID: uuid.NewString(), NodeID: id, PrimaryNodeID: id, Role: "primary", Epoch: 1, MaxReadAgeSeconds: 3600, WorkersEnabled: true}
|
||||
return &c, Save(dataDir, c)
|
||||
}
|
||||
|
||||
// Promote records an operator's fencing attestation. It does not contact,
|
||||
// power off, or independently verify the former primary. No automatic promotion.
|
||||
func Promote(dataDir, fencedNode, reference string, acceptLoss bool) (*Config, error) {
|
||||
l, err := Lock(dataDir, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer l.Close()
|
||||
c, err := Load(dataDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c == nil || c.Role != "standby" {
|
||||
return nil, errors.New("only an offline standby can be promoted")
|
||||
}
|
||||
if err = checkAuthKey(dataDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if fencedNode != c.PrimaryNodeID || !acceptLoss || len(strings.TrimSpace(reference)) < 4 || len(reference) > 1024 {
|
||||
return nil, errors.New("promotion requires exact former primary ID, fencing reference and explicit acceptance of snapshot data loss")
|
||||
}
|
||||
if c.Epoch == ^uint64(0) {
|
||||
return nil, errors.New("DR epoch exhausted")
|
||||
}
|
||||
c.Epoch++
|
||||
c.History = append(c.History, Promotion{At: time.Now().UTC(), PreviousNode: fencedNode, FenceReference: strings.TrimSpace(reference), SnapshotID: c.SnapshotID, Epoch: c.Epoch})
|
||||
c.Role, c.PrimaryNodeID = "primary", c.NodeID
|
||||
// Replaying pre-snapshot jobs can duplicate notifications or external writes.
|
||||
// Resume them only after an operator reviews the restored queue.
|
||||
c.WorkersEnabled = false
|
||||
return c, Save(dataDir, *c)
|
||||
}
|
||||
|
||||
func checkAuthKey(dataDir string) error {
|
||||
if strings.TrimSpace(os.Getenv("PAGESWIKI_AUTH_KEY")) != "" {
|
||||
return nil
|
||||
}
|
||||
key, err := os.ReadFile(filepath.Join(dataDir, "auth.key"))
|
||||
if err != nil || len(key) != 32 {
|
||||
return errors.New("original auth.key or PAGESWIKI_AUTH_KEY is required; refusing implicit key regeneration")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ResumeWorkers(dataDir string, reviewed bool) (*Config, error) {
|
||||
if !reviewed {
|
||||
return nil, errors.New("review restored jobs and federation state before resuming workers")
|
||||
}
|
||||
l, err := Lock(dataDir, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer l.Close()
|
||||
c, err := Load(dataDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c == nil || c.Role != "primary" {
|
||||
return nil, errors.New("only an offline primary can resume workers")
|
||||
}
|
||||
c.WorkersEnabled = true
|
||||
c.WorkersResumedAt = time.Now().UTC()
|
||||
return c, Save(dataDir, *c)
|
||||
}
|
||||
|
||||
func syncDir(path string) error {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
return f.Sync()
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
package dr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/sys/unix"
|
||||
"modernc.org/sqlite"
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Path string `json:"path"`
|
||||
Size int64 `json:"size"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
type Manifest struct {
|
||||
Version int `json:"version"`
|
||||
ID string `json:"id"`
|
||||
ClusterID string `json:"cluster_id"`
|
||||
PrimaryNodeID string `json:"primary_node_id"`
|
||||
Epoch uint64 `json:"epoch"`
|
||||
CapturedAt time.Time `json:"captured_at"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
Scope string `json:"scope"`
|
||||
Files []File `json:"files"`
|
||||
}
|
||||
|
||||
// Include canonical stores, auth/signing keys and managed-campus enrollment.
|
||||
// Caches, temporary uploads, editor workspaces and node-local DR state are NOT
|
||||
// recovery authorities. Extra mounted storage/environment secrets are external.
|
||||
func canonical(path string) bool {
|
||||
if !filepath.IsLocal(path) || filepath.ToSlash(path) != path || strings.Contains(path, "\\") || path != filepath.Clean(path) {
|
||||
return false
|
||||
}
|
||||
root := strings.Split(path, "/")[0]
|
||||
switch root {
|
||||
case "documents", "themes", "federation":
|
||||
return true
|
||||
case "pages.db", "auth.key", "instance-ed25519.key":
|
||||
return path == root
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func fileHash(path string) (File, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return File{}, err
|
||||
}
|
||||
defer f.Close()
|
||||
i, err := f.Stat()
|
||||
if err != nil || !i.Mode().IsRegular() {
|
||||
return File{}, errors.New("snapshot entry is not a regular file")
|
||||
}
|
||||
h := sha256.New()
|
||||
n, err := io.CopyBuffer(h, f, make([]byte, 256<<10))
|
||||
return File{Size: n, SHA256: hex.EncodeToString(h.Sum(nil))}, err
|
||||
}
|
||||
|
||||
func copyFile(source, target string) error {
|
||||
i, err := os.Lstat(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !i.Mode().IsRegular() {
|
||||
return fmt.Errorf("refusing nonregular source: %s", source)
|
||||
}
|
||||
in, err := os.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
opened, err := in.Stat()
|
||||
if err != nil || !os.SameFile(i, opened) {
|
||||
return errors.New("source changed during snapshot")
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Dir(target), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.CopyBuffer(out, in, make([]byte, 256<<10))
|
||||
if err == nil {
|
||||
err = out.Sync()
|
||||
}
|
||||
closeErr := out.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Backup API preserves rowids (unlike VACUUM INTO) and includes committed WAL.
|
||||
func backupDB(ctx context.Context, source, target string) error {
|
||||
database, err := db.OpenReadOnly(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer database.Close()
|
||||
conn, err := database.Conn(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = conn.Raw(func(raw any) error {
|
||||
b, err := raw.(interface {
|
||||
NewBackup(string) (*sqlite.Backup, error)
|
||||
}).NewBackup((&url.URL{Scheme: "file", Path: target}).String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
if err = ctx.Err(); err != nil {
|
||||
b.Finish()
|
||||
return err
|
||||
}
|
||||
more, e := b.Step(256)
|
||||
if e != nil {
|
||||
b.Finish()
|
||||
return e
|
||||
}
|
||||
if !more {
|
||||
return b.Finish()
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Do not leave a WAL-mode snapshot that creates sidecars during verification.
|
||||
dst, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: target, RawQuery: "mode=rw"}).String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = dst.ExecContext(ctx, "PRAGMA journal_mode=DELETE")
|
||||
closeErr := dst.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
// Finish leaves a standalone DB; fsync before publishing the generation.
|
||||
f, err := os.OpenFile(target, os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
if err = f.Chmod(0600); err != nil {
|
||||
return err
|
||||
}
|
||||
return f.Sync()
|
||||
}
|
||||
|
||||
// Snapshot requires every writer stopped, including older binaries and CLIs.
|
||||
// The lock enforces this for upgraded PagesWiki processes, not arbitrary tools.
|
||||
func Snapshot(ctx context.Context, dataDir, target string) (*Manifest, string, error) {
|
||||
source, err := filepath.EvalSymlinks(dataDir)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
source, err = filepath.Abs(source)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
target, err = filepath.Abs(target)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
parent, err := filepath.EvalSymlinks(filepath.Dir(target))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
target = filepath.Join(parent, filepath.Base(target))
|
||||
if target == source || strings.HasPrefix(target, source+string(filepath.Separator)) {
|
||||
return nil, "", errors.New("snapshot destination must be outside the data directory")
|
||||
}
|
||||
l, err := Lock(source, true)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer l.Close()
|
||||
c, err := Load(source)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if c == nil || c.Role != "primary" {
|
||||
return nil, "", errors.New("initialize primary DR configuration before snapshot")
|
||||
}
|
||||
if _, err = os.Lstat(target); !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, "", errors.New("snapshot destination must not exist")
|
||||
}
|
||||
stage, err := os.MkdirTemp(parent, ".dr-snapshot-")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer os.RemoveAll(stage)
|
||||
m := &Manifest{Version: 1, ID: uuid.NewString(), ClusterID: c.ClusterID, PrimaryNodeID: c.NodeID, Epoch: c.Epoch, CapturedAt: time.Now().UTC(), Scope: "instance-offline-v1"}
|
||||
root := filepath.Join(stage, "data")
|
||||
if err = os.Mkdir(root, 0700); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
info, err := os.Lstat(filepath.Join(source, "pages.db"))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, "", errors.New("snapshot database must be a regular file, not a symlink")
|
||||
}
|
||||
if err = checkAuthKey(source); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err = backupDB(ctx, filepath.Join(source, "pages.db"), filepath.Join(root, "pages.db")); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
for _, name := range []string{"documents", "themes", "federation", "auth.key", "instance-ed25519.key"} {
|
||||
base := filepath.Join(source, name)
|
||||
if _, e := os.Lstat(base); errors.Is(e, os.ErrNotExist) {
|
||||
continue
|
||||
} else if e != nil {
|
||||
return nil, "", e
|
||||
}
|
||||
err = filepath.WalkDir(base, func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("snapshot refuses symlink: %s", path)
|
||||
}
|
||||
rel, _ := filepath.Rel(source, path)
|
||||
if entry.IsDir() {
|
||||
return os.MkdirAll(filepath.Join(root, rel), 0700)
|
||||
}
|
||||
return copyFile(path, filepath.Join(root, rel))
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
}
|
||||
err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return syncDir(path)
|
||||
}
|
||||
if len(m.Files) >= 100000 {
|
||||
return errors.New("snapshot exceeds 100000 files; partitioned snapshots require a later format")
|
||||
}
|
||||
f, e := fileHash(path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
f.Path, _ = filepath.Rel(root, path)
|
||||
m.Files = append(m.Files, f)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
m.CompletedAt = time.Now().UTC()
|
||||
encoded, err := json.MarshalIndent(m, "", " ")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(stage, "manifest.json"), encoded, 0600); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
manifestFile, err := os.OpenFile(filepath.Join(stage, "manifest.json"), os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
err = manifestFile.Sync()
|
||||
manifestFile.Close()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
hash := sha256.Sum256(encoded)
|
||||
if _, err = Verify(ctx, stage, hex.EncodeToString(hash[:])); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err = syncDir(stage); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err = publish(stage, target); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return m, hex.EncodeToString(hash[:]), syncDir(parent)
|
||||
}
|
||||
|
||||
func Verify(ctx context.Context, root, expectedHash string) (*Manifest, error) {
|
||||
if len(expectedHash) != 64 {
|
||||
return nil, errors.New("expected manifest SHA-256 is required from a trusted channel")
|
||||
}
|
||||
root, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Lstat(filepath.Join(root, "manifest.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > 64<<20 {
|
||||
return nil, errors.New("invalid or oversized snapshot manifest")
|
||||
}
|
||||
encoded, err := os.ReadFile(filepath.Join(root, "manifest.json"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(encoded)
|
||||
if hex.EncodeToString(sum[:]) != expectedHash {
|
||||
return nil, errors.New("manifest SHA-256 mismatch")
|
||||
}
|
||||
var m Manifest
|
||||
if err = json.Unmarshal(encoded, &m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if m.Version != 1 || m.Scope != "instance-offline-v1" || m.Epoch == 0 || len(m.Files) == 0 || len(m.Files) > 100000 || m.CapturedAt.IsZero() || m.CompletedAt.Before(m.CapturedAt) || m.CompletedAt.After(time.Now().Add(time.Minute)) {
|
||||
return nil, errors.New("invalid snapshot manifest")
|
||||
}
|
||||
for _, id := range []string{m.ID, m.ClusterID, m.PrimaryNodeID} {
|
||||
u, e := uuid.Parse(id)
|
||||
if e != nil || u == uuid.Nil || u.String() != id {
|
||||
return nil, errors.New("invalid snapshot identity")
|
||||
}
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
hashes := map[string]string{}
|
||||
for _, item := range m.Files {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !canonical(item.Path) || seen[item.Path] {
|
||||
return nil, errors.New("invalid/duplicate snapshot path")
|
||||
}
|
||||
seen[item.Path] = true
|
||||
hashes[item.Path] = item.SHA256
|
||||
path := filepath.Join(root, "data", item.Path)
|
||||
// Refuse symlinks in every component, including parent directories.
|
||||
for p := path; p != filepath.Dir(root) && p != "."; p = filepath.Dir(p) {
|
||||
info, e := os.Lstat(p)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if info.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, errors.New("snapshot contains symlink")
|
||||
}
|
||||
if p == root || filepath.Dir(p) == p {
|
||||
break
|
||||
}
|
||||
}
|
||||
actual, e := fileHash(path)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if actual.Size != item.Size || actual.SHA256 != item.SHA256 {
|
||||
return nil, fmt.Errorf("snapshot payload mismatch: %s", item.Path)
|
||||
}
|
||||
if strings.HasPrefix(item.Path, "documents/sha256/") && filepath.Base(item.Path) != actual.SHA256 {
|
||||
return nil, errors.New("CAS filename does not match payload hash")
|
||||
}
|
||||
}
|
||||
if !seen["pages.db"] {
|
||||
return nil, errors.New("snapshot database missing")
|
||||
}
|
||||
if err = verifyCalendarFiles(root, hashes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = filepath.WalkDir(filepath.Join(root, "data"), func(path string, entry fs.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
rel, _ := filepath.Rel(filepath.Join(root, "data"), path)
|
||||
if !seen[rel] {
|
||||
return errors.New("unlisted snapshot payload")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
database, err := db.OpenReadOnly(filepath.Join(root, "data", "pages.db"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer database.Close()
|
||||
var integrity string
|
||||
if err = database.QueryRowContext(ctx, "PRAGMA quick_check").Scan(&integrity); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if integrity != "ok" {
|
||||
return nil, errors.New("snapshot database integrity check failed")
|
||||
}
|
||||
if err = verifyReferences(ctx, database, seen); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &m, nil
|
||||
}
|
||||
|
||||
// Restore never merges into or overwrites a running/existing data directory.
|
||||
// It publishes a new generation with a fresh physical node ID, always standby.
|
||||
func Restore(ctx context.Context, snapshot, expectedHash, target string) (*Config, error) {
|
||||
m, err := Verify(ctx, snapshot, expectedHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target, err = filepath.Abs(target)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parent, err := filepath.EvalSymlinks(filepath.Dir(target))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target = filepath.Join(parent, filepath.Base(target))
|
||||
source, err := filepath.EvalSymlinks(snapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source, err = filepath.Abs(source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if target == source || strings.HasPrefix(target, source+string(filepath.Separator)) {
|
||||
return nil, errors.New("restore destination must be outside the snapshot")
|
||||
}
|
||||
if _, err = os.Lstat(target); !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, errors.New("restore target must not exist; use a new generation")
|
||||
}
|
||||
stage, err := os.MkdirTemp(filepath.Dir(target), ".dr-restore-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(stage)
|
||||
for _, item := range m.Files {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = copyFile(filepath.Join(snapshot, "data", item.Path), filepath.Join(stage, item.Path)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
actual, e := fileHash(filepath.Join(stage, item.Path))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if actual.Size != item.Size || actual.SHA256 != item.SHA256 {
|
||||
return nil, errors.New("snapshot changed during restore")
|
||||
}
|
||||
}
|
||||
c := &Config{Version: 1, ClusterID: m.ClusterID, NodeID: uuid.NewString(), PrimaryNodeID: m.PrimaryNodeID, Role: "standby", Epoch: m.Epoch, SnapshotID: m.ID, CapturedAt: m.CapturedAt, MaxReadAgeSeconds: 3600}
|
||||
if err = Save(stage, *c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Join(stage, "documents", "sha256"), 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Create the lock before a read-only data mount is applied.
|
||||
l, err := Lock(stage, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.Close()
|
||||
err = filepath.WalkDir(stage, func(path string, entry fs.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return syncDir(path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = publish(stage, target); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, syncDir(filepath.Dir(target))
|
||||
}
|
||||
|
||||
// Linux deployment: atomically publish without replacing even an empty directory.
|
||||
func publish(stage, target string) error {
|
||||
return unix.Renameat2(unix.AT_FDCWD, stage, unix.AT_FDCWD, target, unix.RENAME_NOREPLACE)
|
||||
}
|
||||
|
||||
func verifyReferences(ctx context.Context, database *sql.DB, seen map[string]bool) error {
|
||||
// Only authoritative references, not derived projection/preview caches. Some
|
||||
// installations predate optional modules, hence the explicit table check.
|
||||
for _, ref := range [][2]string{{"revisions", "document_hash"}, {"assets", "head_document_hash"}, {"asset_head_history", "document_hash"}, {"organizer_items", "document_hash"}, {"organizer_revisions", "document_hash"}} {
|
||||
var exists bool
|
||||
if err := database.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", ref[0]).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
rows, err := database.QueryContext(ctx, "SELECT DISTINCT "+ref[1]+" FROM "+ref[0]+" WHERE "+ref[1]+" IS NOT NULL AND "+ref[1]+"<>''")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for rows.Next() {
|
||||
var hash string
|
||||
if err = rows.Scan(&hash); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if len(hash) != 64 || !seen["documents/sha256/"+hash[:2]+"/"+hash] {
|
||||
rows.Close()
|
||||
return fmt.Errorf("snapshot lacks canonical payload referenced by %s", ref[0])
|
||||
}
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Verify file-based calendar authority without parsing event bodies or making
|
||||
// external calendar requests. Derived calendar indexes may be repaired only
|
||||
// after promotion, never by a standby read request.
|
||||
func verifyCalendarFiles(root string, hashes map[string]string) error {
|
||||
for path := range hashes {
|
||||
if !strings.HasPrefix(path, "documents/calendars/") || filepath.Base(path) != "calendar.json" {
|
||||
continue
|
||||
}
|
||||
filename := filepath.Join(root, "data", path)
|
||||
info, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Size() > 16<<20 {
|
||||
return errors.New("calendar metadata exceeds snapshot verification limit")
|
||||
}
|
||||
encoded, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var metadata struct {
|
||||
Months map[string]string `json:"months"`
|
||||
}
|
||||
if err = json.Unmarshal(encoded, &metadata); err != nil {
|
||||
return errors.New("invalid calendar metadata in snapshot")
|
||||
}
|
||||
for month, hash := range metadata.Months {
|
||||
if _, err = time.Parse("2006-01", month); err != nil {
|
||||
return errors.New("invalid calendar month in snapshot")
|
||||
}
|
||||
if len(hash) != 64 || hashes[filepath.ToSlash(filepath.Join(filepath.Dir(path), month+"."+hash+".ics"))] != hash {
|
||||
return errors.New("snapshot lacks a valid calendar monthly generation")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestComponentBoundary(t *testing.T) {
|
||||
if Component != "dregarnuhr" {
|
||||
t.Fatal("component identity changed")
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(file, "_test.go") {
|
||||
continue
|
||||
}
|
||||
ast, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, spec := range ast.Imports {
|
||||
path, err := strconv.Unquote(spec.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"pageswiki/internal", "database", "net", "os"} {
|
||||
if path == forbidden || strings.HasPrefix(path, forbidden+"/") {
|
||||
t.Errorf("%s imports %s: scheduler core must not own persistence or business I/O", file, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dregarnuhr
|
||||
|
||||
import "time"
|
||||
|
||||
type Timer interface {
|
||||
C() <-chan time.Time
|
||||
Stop() bool
|
||||
}
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
NewTimer(time.Duration) Timer
|
||||
}
|
||||
type SystemClock struct{}
|
||||
|
||||
func (SystemClock) Now() time.Time { return time.Now() }
|
||||
func (SystemClock) NewTimer(d time.Duration) Timer { return systemTimer{time.NewTimer(d)} }
|
||||
|
||||
type systemTimer struct{ *time.Timer }
|
||||
|
||||
func (t systemTimer) C() <-chan time.Time { return t.Timer.C }
|
||||
@@ -0,0 +1,65 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fakeClock struct {
|
||||
mu sync.Mutex
|
||||
now time.Time
|
||||
timers map[*fakeTimer]time.Time
|
||||
created chan struct{}
|
||||
}
|
||||
type fakeTimer struct {
|
||||
clock *fakeClock
|
||||
ch chan time.Time
|
||||
}
|
||||
|
||||
func newFakeClock() *fakeClock {
|
||||
return &fakeClock{now: time.Unix(100000, 0), timers: map[*fakeTimer]time.Time{}, created: make(chan struct{}, 100)}
|
||||
}
|
||||
func (c *fakeClock) Now() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.now }
|
||||
func (c *fakeClock) NewTimer(delay time.Duration) Timer {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
t := &fakeTimer{clock: c, ch: make(chan time.Time, 1)}
|
||||
if delay <= 0 {
|
||||
t.ch <- c.now
|
||||
} else {
|
||||
c.timers[t] = c.now.Add(delay)
|
||||
}
|
||||
c.created <- struct{}{}
|
||||
return t
|
||||
}
|
||||
func (t *fakeTimer) C() <-chan time.Time { return t.ch }
|
||||
func (t *fakeTimer) Stop() bool {
|
||||
t.clock.mu.Lock()
|
||||
defer t.clock.mu.Unlock()
|
||||
_, ok := t.clock.timers[t]
|
||||
delete(t.clock.timers, t)
|
||||
return ok
|
||||
}
|
||||
func (c *fakeClock) advance(d time.Duration) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.now = c.now.Add(d)
|
||||
for timer, at := range c.timers {
|
||||
if !at.After(c.now) {
|
||||
timer.ch <- c.now
|
||||
delete(c.timers, timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
func receive[T any](t *testing.T, ch <-chan T) T {
|
||||
t.Helper()
|
||||
select {
|
||||
case v := <-ch:
|
||||
return v
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for test worker")
|
||||
var zero T
|
||||
return zero
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Trigger struct {
|
||||
Name string
|
||||
After, Every time.Duration
|
||||
Run func(context.Context, time.Time) error
|
||||
}
|
||||
type Loop struct {
|
||||
Clock Clock
|
||||
Every time.Duration
|
||||
Wake <-chan struct{}
|
||||
OnWake func(context.Context, time.Time) error
|
||||
Triggers []Trigger
|
||||
Step func(context.Context, time.Time) error
|
||||
Report func(string, error)
|
||||
}
|
||||
|
||||
// Run coalesces overdue ticks (no catch-up storm), stops its timer on
|
||||
// cancellation, and invokes caller-supplied hooks. It knows no event types.
|
||||
func (l Loop) Run(ctx context.Context) error {
|
||||
if l.Every <= 0 || l.Step == nil {
|
||||
return errors.New("loop requires positive cadence and step")
|
||||
}
|
||||
clock := l.Clock
|
||||
if clock == nil {
|
||||
clock = SystemClock{}
|
||||
}
|
||||
now := clock.Now()
|
||||
next := now.Add(l.Every)
|
||||
due := make([]time.Time, len(l.Triggers))
|
||||
seen := map[string]bool{}
|
||||
for i, t := range l.Triggers {
|
||||
if t.Name == "" || seen[t.Name] || t.Run == nil || t.After < 0 || t.Every < 0 || (t.After == 0 && t.Every == 0) {
|
||||
return fmt.Errorf("invalid trigger %q", t.Name)
|
||||
}
|
||||
seen[t.Name] = true
|
||||
delay := t.After
|
||||
if delay == 0 {
|
||||
delay = t.Every
|
||||
}
|
||||
due[i] = now.Add(delay)
|
||||
}
|
||||
wake := l.Wake
|
||||
call := func(name string, fn func(context.Context, time.Time) error, now time.Time) {
|
||||
if fn != nil {
|
||||
if err := fn(ctx, now); err != nil && l.Report != nil {
|
||||
l.Report(name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for ctx.Err() == nil {
|
||||
at := next
|
||||
for _, d := range due {
|
||||
if !d.IsZero() && d.Before(at) {
|
||||
at = d
|
||||
}
|
||||
}
|
||||
timer := clock.NewTimer(max(time.Duration(0), at.Sub(clock.Now())))
|
||||
woken := false
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case _, ok := <-wake:
|
||||
if !ok {
|
||||
wake = nil
|
||||
timer.Stop()
|
||||
continue
|
||||
}
|
||||
woken = true
|
||||
case <-timer.C():
|
||||
}
|
||||
timer.Stop()
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
now = clock.Now()
|
||||
if woken {
|
||||
call("wake", l.OnWake, now)
|
||||
}
|
||||
for i, t := range l.Triggers {
|
||||
if !due[i].IsZero() && !due[i].After(now) {
|
||||
call(t.Name, t.Run, now)
|
||||
if t.Every > 0 {
|
||||
due[i] = now.Add(t.Every)
|
||||
} else {
|
||||
due[i] = time.Time{}
|
||||
}
|
||||
}
|
||||
}
|
||||
call("step", l.Step, now)
|
||||
if !next.After(now) {
|
||||
next = now.Add(l.Every)
|
||||
}
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLoopFakeClockWakeAndCoalescing(t *testing.T) {
|
||||
clock := newFakeClock()
|
||||
wake := make(chan struct{}, 1)
|
||||
steps := make(chan time.Time, 20)
|
||||
reports := make(chan string, 10)
|
||||
var once, periodic, awakened atomic.Int64
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
loop := Loop{Clock: clock, Every: time.Second, Wake: wake,
|
||||
OnWake: func(context.Context, time.Time) error { awakened.Add(1); return nil },
|
||||
Triggers: []Trigger{
|
||||
{Name: "once", After: 5 * time.Second, Run: func(context.Context, time.Time) error { once.Add(1); return nil }},
|
||||
{Name: "periodic", Every: 10 * time.Second, Run: func(context.Context, time.Time) error { periodic.Add(1); return errors.New("synthetic") }},
|
||||
},
|
||||
Step: func(_ context.Context, at time.Time) error { steps <- at; return nil },
|
||||
Report: func(stage string, _ error) { reports <- stage },
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- loop.Run(ctx) }()
|
||||
receive(t, clock.created)
|
||||
wake <- struct{}{}
|
||||
receive(t, steps)
|
||||
receive(t, clock.created)
|
||||
if awakened.Load() != 1 || once.Load() != 0 {
|
||||
t.Fatal("wake changed timer deadlines")
|
||||
}
|
||||
clock.advance(5 * time.Second)
|
||||
receive(t, steps)
|
||||
receive(t, clock.created)
|
||||
if once.Load() != 1 || periodic.Load() != 0 {
|
||||
t.Fatal("initial cadence")
|
||||
}
|
||||
clock.advance(time.Hour)
|
||||
receive(t, steps)
|
||||
receive(t, clock.created)
|
||||
if once.Load() != 1 || periodic.Load() != 1 {
|
||||
t.Fatal("catch-up storm", once.Load(), periodic.Load())
|
||||
}
|
||||
if receive(t, reports) != "periodic" {
|
||||
t.Fatal("hook failure missing")
|
||||
}
|
||||
close(wake)
|
||||
receive(t, clock.created) // closed wake channel must not spin
|
||||
clock.advance(10 * time.Second)
|
||||
receive(t, steps)
|
||||
receive(t, clock.created)
|
||||
if periodic.Load() != 2 {
|
||||
t.Fatal("periodic stopped after error")
|
||||
}
|
||||
cancel()
|
||||
if !errors.Is(receive(t, done), context.Canceled) {
|
||||
t.Fatal("loop did not stop")
|
||||
}
|
||||
clock.mu.Lock()
|
||||
defer clock.mu.Unlock()
|
||||
if len(clock.timers) != 0 {
|
||||
t.Fatal("timer leaked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoopRejectsInvalidHooks(t *testing.T) {
|
||||
for _, l := range []Loop{{}, {Every: time.Second, Step: func(context.Context, time.Time) error { return nil }, Triggers: []Trigger{{Name: "invalid"}}}} {
|
||||
if l.Run(context.Background()) == nil {
|
||||
t.Fatal("invalid loop accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CanStart retains a single background worker under foreground load, avoiding
|
||||
// starvation by long-lived requests while protecting foreground capacity.
|
||||
func CanStart(s Settings, active int64, foreground bool) bool {
|
||||
return !s.Paused && active < int64(s.Concurrency) && (!foreground || active == 0)
|
||||
}
|
||||
|
||||
// RetryDelay doubles per completed attempt and saturates without overflowing.
|
||||
func RetryDelay(baseSeconds, attempt int) time.Duration {
|
||||
if baseSeconds < 1 {
|
||||
baseSeconds = 1
|
||||
}
|
||||
if baseSeconds >= 86400 {
|
||||
return 24 * time.Hour
|
||||
}
|
||||
delay := time.Duration(baseSeconds) * time.Second
|
||||
for i := 1; i < attempt; i++ {
|
||||
if delay >= 12*time.Hour {
|
||||
return 24 * time.Hour
|
||||
}
|
||||
delay *= 2
|
||||
}
|
||||
return delay
|
||||
}
|
||||
|
||||
type Completion struct {
|
||||
Status, Message, Level string
|
||||
RetryAt time.Time
|
||||
}
|
||||
|
||||
// Complete is independent of DB access. The repository persists this decision.
|
||||
func Complete(job Job, runErr error, baseSeconds int, now time.Time) Completion {
|
||||
out := Completion{Status: "succeeded", Level: "info"}
|
||||
if runErr == nil {
|
||||
return out
|
||||
}
|
||||
out.Message = runErr.Error()
|
||||
switch {
|
||||
case errors.Is(runErr, ErrSkipped):
|
||||
out.Status = "skipped"
|
||||
case job.CancelRequested:
|
||||
out.Status = "cancelled"
|
||||
case job.Attempts < job.MaxAttempts:
|
||||
out.Status = "queued"
|
||||
out.Level = "warning"
|
||||
out.RetryAt = now.Add(RetryDelay(baseSeconds, job.Attempts))
|
||||
default:
|
||||
out.Status = "failed"
|
||||
out.Level = "error"
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetryDelay(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
base, attempt int
|
||||
want time.Duration
|
||||
}{
|
||||
{30, 1, 30 * time.Second}, {30, 2, time.Minute}, {30, 3, 2 * time.Minute},
|
||||
{30, 1000000, 24 * time.Hour}, {86401, 1, 24 * time.Hour}, {math.MaxInt, math.MaxInt, 24 * time.Hour}, {0, 1, time.Second},
|
||||
} {
|
||||
if got := RetryDelay(tc.base, tc.attempt); got != tc.want {
|
||||
t.Errorf("%+v got=%s", tc, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletionPolicy(t *testing.T) {
|
||||
now := time.Unix(1000, 0)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
job Job
|
||||
err error
|
||||
status, level string
|
||||
}{
|
||||
{"success", Job{Attempts: 1, MaxAttempts: 3}, nil, "succeeded", "info"},
|
||||
{"retry", Job{Attempts: 2, MaxAttempts: 3}, errors.New("failed"), "queued", "warning"},
|
||||
{"exhausted", Job{Attempts: 3, MaxAttempts: 3}, errors.New("failed"), "failed", "error"},
|
||||
{"cancel", Job{Attempts: 1, MaxAttempts: 3, CancelRequested: true}, errors.New("cancelled"), "cancelled", "info"},
|
||||
{"skip-before-cancel", Job{Attempts: 1, MaxAttempts: 3, CancelRequested: true}, fmt.Errorf("wrapped: %w", ErrSkipped), "skipped", "info"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := Complete(tc.job, tc.err, 30, now)
|
||||
if got.Status != tc.status || got.Level != tc.level {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
if tc.status == "queued" && !got.RetryAt.Equal(now.Add(time.Minute)) {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if tc.status != "queued" && !got.RetryAt.IsZero() {
|
||||
t.Fatal("terminal job retried")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdmissionPolicy(t *testing.T) {
|
||||
s := Settings{Concurrency: 4}
|
||||
if !CanStart(s, 0, true) || CanStart(s, 1, true) || !CanStart(s, 3, false) || CanStart(s, 4, false) {
|
||||
t.Fatal("admission policy changed")
|
||||
}
|
||||
s.Paused = true
|
||||
if CanStart(s, 0, false) {
|
||||
t.Fatal("paused worker admitted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Handler func(context.Context, *Job) error
|
||||
|
||||
// Registry holds existing event identifiers, not new provider or consumer IDs.
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
handlers map[string]Handler
|
||||
}
|
||||
|
||||
func (r *Registry) Register(kind string, handler Handler) error {
|
||||
if strings.TrimSpace(kind) == "" || handler == nil {
|
||||
return errors.New("event type and handler are required")
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.handlers == nil {
|
||||
r.handlers = make(map[string]Handler)
|
||||
}
|
||||
if _, ok := r.handlers[kind]; ok {
|
||||
return fmt.Errorf("duplicate event type %q", kind)
|
||||
}
|
||||
r.handlers[kind] = handler
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Registry) Run(ctx context.Context, job *Job) error {
|
||||
if job == nil {
|
||||
return errors.New("job is required")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.RLock()
|
||||
handler := r.handlers[job.Type]
|
||||
r.mu.RUnlock()
|
||||
if handler == nil {
|
||||
return fmt.Errorf("unknown event type %q", job.Type)
|
||||
}
|
||||
return handler(ctx, job)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Queue owns atomic priority-ordered claims and persisted completion. ErrNoJob
|
||||
// means no eligible job. The initial adapter is single-writer-process, not HA.
|
||||
type Queue interface {
|
||||
Settings(context.Context) (Settings, error)
|
||||
Claim(context.Context, time.Time) (*Job, error)
|
||||
Cancellation(context.Context, string) (bool, error)
|
||||
Started(context.Context, *Job) error
|
||||
Finish(context.Context, *Job, error, time.Time) error
|
||||
}
|
||||
|
||||
type RunnerOptions struct {
|
||||
Clock Clock
|
||||
// Active is an optional compatibility counter for an existing monitor.
|
||||
Active *atomic.Int64
|
||||
Foreground func() bool
|
||||
Wake func()
|
||||
Report func(stage string, job *Job, err error)
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
queue Queue
|
||||
registry *Registry
|
||||
opts RunnerOptions
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewRunner(queue Queue, registry *Registry, opts RunnerOptions) *Runner {
|
||||
if opts.Clock == nil {
|
||||
opts.Clock = SystemClock{}
|
||||
}
|
||||
if opts.Active == nil {
|
||||
opts.Active = new(atomic.Int64)
|
||||
}
|
||||
return &Runner{queue: queue, registry: registry, opts: opts}
|
||||
}
|
||||
|
||||
func (r *Runner) report(stage string, job *Job, err error) {
|
||||
if err != nil && r.opts.Report != nil {
|
||||
r.opts.Report(stage, job, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) Running() int64 { return r.opts.Active.Load() }
|
||||
|
||||
// Dispatch serializes admission plus claim across concurrent callers. Each
|
||||
// invocation is bounded even if workers finish immediately and refill slots.
|
||||
func (r *Runner) Dispatch(ctx context.Context) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for n := 0; n < 32 && ctx.Err() == nil; n++ {
|
||||
settings, err := r.queue.Settings(ctx)
|
||||
if err != nil {
|
||||
r.report("settings", nil, err)
|
||||
return
|
||||
}
|
||||
foreground := r.opts.Foreground != nil && r.opts.Foreground()
|
||||
if !CanStart(settings, r.Running(), foreground) {
|
||||
return
|
||||
}
|
||||
job, err := r.queue.Claim(ctx, r.opts.Clock.Now())
|
||||
if errors.Is(err, ErrNoJob) || errors.Is(err, context.Canceled) {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
r.report("claim", nil, err)
|
||||
return
|
||||
}
|
||||
if job == nil {
|
||||
r.report("claim", nil, errors.New("queue returned nil job"))
|
||||
return
|
||||
}
|
||||
r.opts.Active.Add(1)
|
||||
r.report("start-log", job, r.queue.Started(ctx, job))
|
||||
go r.execute(ctx, job)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) execute(ctx context.Context, job *Job) {
|
||||
defer func() {
|
||||
r.opts.Active.Add(-1)
|
||||
if r.opts.Wake != nil {
|
||||
r.opts.Wake()
|
||||
}
|
||||
}()
|
||||
runErr := r.invoke(ctx, job)
|
||||
// Completion must still be attempted when the worker context is cancelled.
|
||||
finishCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
r.report("finish", job, r.queue.Finish(finishCtx, job, runErr, r.opts.Clock.Now()))
|
||||
r.report("execute", job, runErr)
|
||||
}
|
||||
|
||||
func (r *Runner) invoke(ctx context.Context, job *Job) (err error) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
err = errors.New("event handler panicked")
|
||||
}
|
||||
}()
|
||||
cancelled, err := r.queue.Cancellation(ctx, job.UUID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cancelled {
|
||||
return errors.New("cancelled before execution")
|
||||
}
|
||||
if err = r.registry.Run(ctx, job); err != nil {
|
||||
return err
|
||||
}
|
||||
cancelled, err = r.queue.Cancellation(ctx, job.UUID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cancelled {
|
||||
return errors.New("cancelled during execution")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package dregarnuhr
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type finishedJob struct {
|
||||
id string
|
||||
err error
|
||||
at time.Time
|
||||
}
|
||||
type fakeQueue struct {
|
||||
mu sync.Mutex
|
||||
settings Settings
|
||||
jobs []Job
|
||||
claimed int
|
||||
cancelled bool
|
||||
cancelErr error
|
||||
finished chan finishedJob
|
||||
claimAt time.Time
|
||||
}
|
||||
|
||||
func newFakeQueue(concurrency int) *fakeQueue {
|
||||
q := &fakeQueue{settings: Settings{Concurrency: concurrency}, finished: make(chan finishedJob, 100)}
|
||||
for n := 0; n < 64; n++ {
|
||||
q.jobs = append(q.jobs, Job{UUID: fmt.Sprint(n), Type: "synthetic"})
|
||||
}
|
||||
return q
|
||||
}
|
||||
func (q *fakeQueue) Settings(context.Context) (Settings, error) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
return q.settings, nil
|
||||
}
|
||||
func (q *fakeQueue) Claim(_ context.Context, at time.Time) (*Job, error) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
if len(q.jobs) == 0 {
|
||||
return nil, ErrNoJob
|
||||
}
|
||||
j := q.jobs[0]
|
||||
q.jobs = q.jobs[1:]
|
||||
q.claimed++
|
||||
q.claimAt = at
|
||||
return &j, nil
|
||||
}
|
||||
func (q *fakeQueue) Cancellation(context.Context, string) (bool, error) {
|
||||
q.mu.Lock()
|
||||
defer q.mu.Unlock()
|
||||
return q.cancelled, q.cancelErr
|
||||
}
|
||||
func (q *fakeQueue) Started(context.Context, *Job) error { return nil }
|
||||
func (q *fakeQueue) Finish(ctx context.Context, j *Job, err error, at time.Time) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
q.finished <- finishedJob{j.UUID, err, at}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestRunnerConcurrentAdmission(t *testing.T) {
|
||||
for _, foreground := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint(foreground), func(t *testing.T) {
|
||||
q := newFakeQueue(4)
|
||||
reg := &Registry{}
|
||||
block := make(chan struct{})
|
||||
started := make(chan struct{}, 4)
|
||||
wakes := make(chan struct{}, 4)
|
||||
clock := newFakeClock()
|
||||
defer close(block)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
if err := reg.Register("synthetic", func(ctx context.Context, _ *Job) error {
|
||||
started <- struct{}{}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-block:
|
||||
return nil
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := NewRunner(q, reg, RunnerOptions{Clock: clock, Foreground: func() bool { return foreground }, Wake: func() { wakes <- struct{}{} }})
|
||||
var wg sync.WaitGroup
|
||||
for n := 0; n < 16; n++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); r.Dispatch(ctx) }()
|
||||
}
|
||||
wg.Wait()
|
||||
want := 4
|
||||
if foreground {
|
||||
want = 1
|
||||
}
|
||||
for n := 0; n < want; n++ {
|
||||
receive(t, started)
|
||||
}
|
||||
if r.Running() != int64(want) || q.claimed != want || !q.claimAt.Equal(clock.Now()) {
|
||||
t.Fatalf("active=%d claimed=%d want=%d", r.Running(), q.claimed, want)
|
||||
}
|
||||
cancel()
|
||||
for n := 0; n < want; n++ {
|
||||
receive(t, q.finished)
|
||||
receive(t, wakes)
|
||||
}
|
||||
if r.Running() != 0 {
|
||||
t.Fatal("worker slots leaked")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerOutcomesAndCancellation(t *testing.T) {
|
||||
for _, mode := range []string{"success", "cancel-before", "cancel-after", "cancellation-read-error", "panic", "unknown", "failure"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
q := newFakeQueue(1)
|
||||
q.jobs = q.jobs[:1]
|
||||
q.cancelled = mode == "cancel-before"
|
||||
if mode == "cancellation-read-error" {
|
||||
q.cancelErr = errors.New("database unavailable")
|
||||
}
|
||||
reg := &Registry{}
|
||||
called := false
|
||||
if mode != "unknown" {
|
||||
if err := reg.Register("synthetic", func(context.Context, *Job) error {
|
||||
called = true
|
||||
if mode == "panic" {
|
||||
panic("sensitive panic payload")
|
||||
}
|
||||
if mode == "failure" {
|
||||
return errors.New("handler failure")
|
||||
}
|
||||
if mode == "cancel-after" {
|
||||
q.mu.Lock()
|
||||
q.cancelled = true
|
||||
q.mu.Unlock()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
wakes := make(chan struct{}, 1)
|
||||
clock := newFakeClock()
|
||||
r := NewRunner(q, reg, RunnerOptions{Clock: clock, Wake: func() { wakes <- struct{}{} }})
|
||||
r.Dispatch(context.Background())
|
||||
out := receive(t, q.finished)
|
||||
receive(t, wakes)
|
||||
if (out.err == nil) != (mode == "success") {
|
||||
t.Fatal(mode, out.err)
|
||||
}
|
||||
if (mode == "cancel-before" || mode == "cancellation-read-error") && called {
|
||||
t.Fatal("handler ran without cancellation check")
|
||||
}
|
||||
if mode == "panic" && out.err.Error() != "event handler panicked" {
|
||||
t.Fatal("panic payload leaked")
|
||||
}
|
||||
if r.Running() != 0 || !out.at.Equal(clock.Now()) {
|
||||
t.Fatal("completion/clock failure")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistryAndPausedRunner(t *testing.T) {
|
||||
r := &Registry{}
|
||||
h := func(context.Context, *Job) error { return nil }
|
||||
if r.Register("", h) == nil || r.Register("nil", nil) == nil {
|
||||
t.Fatal("invalid registration")
|
||||
}
|
||||
if r.Register("synthetic", h) != nil || r.Register("synthetic", h) == nil {
|
||||
t.Fatal("duplicate replaced")
|
||||
}
|
||||
q := newFakeQueue(3)
|
||||
q.settings.Paused = true
|
||||
NewRunner(q, r, RunnerOptions{}).Dispatch(context.Background())
|
||||
if q.claimed != 0 {
|
||||
t.Fatal("paused claim")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Package dregarnuhr owns in-process scheduling, worker admission and retry
|
||||
// policy. Queue provides persistence; Registry provides business operations.
|
||||
// Atomic claims are not cross-instance expiring leases.
|
||||
package dregarnuhr
|
||||
|
||||
import "errors"
|
||||
|
||||
const Component = "dregarnuhr"
|
||||
|
||||
var (
|
||||
ErrNoJob = errors.New("no due job")
|
||||
ErrSkipped = errors.New("event is not applicable")
|
||||
)
|
||||
|
||||
type Job struct {
|
||||
UUID string `json:"uuid"`
|
||||
EventUUID string `json:"event_uuid,omitempty"`
|
||||
Type string `json:"event_type"`
|
||||
Key string `json:"event_key"`
|
||||
Payload string `json:"payload,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Priority int `json:"priority"`
|
||||
Attempts int `json:"attempts"`
|
||||
MaxAttempts int `json:"max_attempts"`
|
||||
RunAtMS int64 `json:"run_at_ms"`
|
||||
StartedAtMS int64 `json:"started_at_ms,omitempty"`
|
||||
FinishedAtMS int64 `json:"finished_at_ms,omitempty"`
|
||||
CancelRequested bool `json:"cancel_requested"`
|
||||
Error string `json:"error,omitempty"`
|
||||
CreatedAt int64 `json:"created_at_ms"`
|
||||
UpdatedAt int64 `json:"updated_at_ms"`
|
||||
}
|
||||
|
||||
type Settings struct {
|
||||
Paused bool `json:"paused"`
|
||||
Concurrency int `json:"concurrency"`
|
||||
MaxDepth int `json:"max_depth"`
|
||||
RetryBaseSeconds int `json:"retry_base_seconds"`
|
||||
RetentionHours int `json:"retention_hours"`
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package geduldh
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestComponentBoundary(t *testing.T) {
|
||||
if Component != "geduldh" {
|
||||
t.Fatal("component identity changed")
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(file, "_test.go") {
|
||||
continue
|
||||
}
|
||||
ast, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, spec := range ast.Imports {
|
||||
path, err := strconv.Unquote(spec.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"pageswiki/internal", "database", "net/http"} {
|
||||
if path == forbidden || strings.HasPrefix(path, forbidden+"/") {
|
||||
t.Errorf("%s imports %s: payload storage must not own metadata, HTTP, authorization or the compatibility facade", file, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Ordinary payload access cannot delete objects or make retention decisions.
|
||||
contract := reflect.TypeFor[Store]()
|
||||
var methods []string
|
||||
for i := 0; i < contract.NumMethod(); i++ {
|
||||
methods = append(methods, contract.Method(i).Name)
|
||||
}
|
||||
if want := []string{"Open", "PutIfAbsent", "Stat", "Verify"}; !reflect.DeepEqual(methods, want) {
|
||||
t.Fatalf("Document Store contract changed: %v", methods)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package geduldh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Local requires hard-link no-replace publication and directory fsync support.
|
||||
// A mounted NFS/SMB/SSHFS share is not certified just because it has a path.
|
||||
// Failed persistence primitives return errors; there is no unsafe rename fallback.
|
||||
type Local struct{ root string }
|
||||
|
||||
var _ Store = (*Local)(nil)
|
||||
|
||||
// NewLocal has no I/O side effects. The root must be provisioned by the caller.
|
||||
func NewLocal(root string) (*Local, error) {
|
||||
if strings.TrimSpace(root) == "" {
|
||||
return nil, errors.New("Document root is required")
|
||||
}
|
||||
absolute, err := filepath.Abs(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Local{root: absolute}, nil
|
||||
}
|
||||
|
||||
func (s *Local) Open(ctx context.Context, hash string) (Reader, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key, err := Key(hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
root, err := os.OpenRoot(s.root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
file, err := root.Open(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := file.Stat()
|
||||
if err != nil || !info.Mode().IsRegular() {
|
||||
file.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.New("Document is not a regular file")
|
||||
}
|
||||
return &localReader{file: file, ctx: ctx}, nil
|
||||
}
|
||||
|
||||
func (s *Local) Stat(ctx context.Context, hash string) (Info, error) {
|
||||
reader, err := s.Open(ctx, hash)
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
defer reader.Close()
|
||||
info, err := reader.(*localReader).file.Stat()
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
return Info{Hash: strings.ToLower(strings.TrimSpace(hash)), Size: info.Size()}, nil
|
||||
}
|
||||
|
||||
func verify(ctx context.Context, hash string, reader io.Reader) error {
|
||||
sum := sha256.New()
|
||||
if _, err := io.CopyBuffer(sum, contextReader{ctx, reader}, make([]byte, 64<<10)); err != nil {
|
||||
return err
|
||||
}
|
||||
if hex.EncodeToString(sum.Sum(nil)) != strings.ToLower(strings.TrimSpace(hash)) {
|
||||
return ErrHashMismatch
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (s *Local) Verify(ctx context.Context, hash string) error {
|
||||
reader, err := s.Open(ctx, hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer reader.Close()
|
||||
return verify(ctx, hash, reader)
|
||||
}
|
||||
|
||||
func (s *Local) PutIfAbsent(ctx context.Context, hash string, size int64, input io.Reader) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := Key(hash)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size < 0 || size == math.MaxInt64 {
|
||||
return ErrSizeMismatch
|
||||
}
|
||||
if input == nil {
|
||||
return errors.New("Document reader is required")
|
||||
}
|
||||
root, err := os.OpenRoot(s.root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Close()
|
||||
// The common retry/backfill path must not rewrite or stage existing blobs.
|
||||
// Still validate the supplied bytes, then verify the stored content.
|
||||
if existing, err := root.Open(key); err == nil {
|
||||
defer existing.Close()
|
||||
info, err := existing.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("Document is not a regular file")
|
||||
}
|
||||
if err := copyValidated(ctx, hash, size, input, io.Discard); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := verify(ctx, hash, existing); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncPublishedDirectories(root, path.Dir(key))
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
dir := path.Dir(key)
|
||||
if err := root.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
var nonce [16]byte
|
||||
if _, err := rand.Read(nonce[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := dir + "/.document-" + hex.EncodeToString(nonce[:])
|
||||
file, err := root.OpenFile(tmp, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer root.Remove(tmp)
|
||||
defer file.Close()
|
||||
if err := copyValidated(ctx, hash, size, input, file); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Chmod(0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := file.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// Link is atomic and fails if the destination exists. Rename would silently
|
||||
// replace an existing payload between an existence check and publication.
|
||||
if err := root.Link(tmp, key); err != nil {
|
||||
if !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
existing, err := root.Open(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer existing.Close()
|
||||
info, err := existing.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("Document is not a regular file")
|
||||
}
|
||||
if err := verify(ctx, hash, existing); err != nil {
|
||||
return fmt.Errorf("existing Document: %w", err)
|
||||
}
|
||||
}
|
||||
// Persist the new entry and newly created shard directories before allowing
|
||||
// a metadata transaction to reference the payload. Errors are not swallowed.
|
||||
if err := syncPublishedDirectories(root, dir); err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func syncPublishedDirectories(root *os.Root, shard string) error {
|
||||
for _, name := range []string{shard, "sha256", "."} {
|
||||
directory, err := root.Open(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = directory.Sync()
|
||||
closeErr := directory.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func copyValidated(ctx context.Context, hash string, size int64, input io.Reader, output io.Writer) error {
|
||||
sum := sha256.New()
|
||||
n, err := io.CopyBuffer(io.MultiWriter(output, sum), contextReader{ctx, io.LimitReader(input, size+1)}, make([]byte, 64<<10))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != size {
|
||||
return ErrSizeMismatch
|
||||
}
|
||||
if hex.EncodeToString(sum.Sum(nil)) != strings.ToLower(strings.TrimSpace(hash)) {
|
||||
return ErrHashMismatch
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r contextReader) Read(p []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.reader.Read(p)
|
||||
}
|
||||
|
||||
type localReader struct {
|
||||
file *os.File
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (r *localReader) Close() error { return r.file.Close() }
|
||||
|
||||
func (r *localReader) Read(p []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.file.Read(p)
|
||||
}
|
||||
func (r *localReader) ReadAt(p []byte, offset int64) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.file.ReadAt(p, offset)
|
||||
}
|
||||
func (r *localReader) Seek(offset int64, whence int) (int64, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.file.Seek(offset, whence)
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package geduldh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func digest(data []byte) string { sum := sha256.Sum256(data); return hex.EncodeToString(sum[:]) }
|
||||
func local(t *testing.T) (*Local, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
s, err := NewLocal(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, root
|
||||
}
|
||||
|
||||
func TestLocalRoundTripAndRange(t *testing.T) {
|
||||
for _, payload := range [][]byte{nil, []byte("text 日本語"), {0, 0xff, 1, 0, 3}} {
|
||||
s, _ := local(t)
|
||||
ctx := context.Background()
|
||||
hash := digest(payload)
|
||||
if err := s.PutIfAbsent(ctx, hash, int64(len(payload)), bytes.NewReader(payload)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info, err := s.Stat(ctx, hash)
|
||||
if err != nil || info.Hash != hash || info.Size != int64(len(payload)) {
|
||||
t.Fatalf("info=%+v err=%v", info, err)
|
||||
}
|
||||
reader, err := s.Open(ctx, hash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := io.ReadAll(reader)
|
||||
if err != nil || !bytes.Equal(data, payload) {
|
||||
t.Fatalf("data=%v err=%v", data, err)
|
||||
}
|
||||
if size, err := reader.Seek(0, io.SeekEnd); err != nil || size != int64(len(payload)) {
|
||||
t.Fatalf("size=%d err=%v", size, err)
|
||||
}
|
||||
if len(payload) > 2 {
|
||||
buf := make([]byte, 2)
|
||||
if _, err := reader.ReadAt(buf, 1); err != nil || !bytes.Equal(buf, payload[1:3]) {
|
||||
t.Fatalf("range=%v err=%v", buf, err)
|
||||
}
|
||||
}
|
||||
reader.Close()
|
||||
if err := s.Verify(ctx, hash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalRejectsIncompleteOrCorruptInput(t *testing.T) {
|
||||
payload := []byte("good")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
size int64
|
||||
want error
|
||||
}{
|
||||
{"hash", []byte("evil"), 4, ErrHashMismatch},
|
||||
{"short", []byte("goo"), 4, ErrSizeMismatch},
|
||||
{"long", []byte("good!"), 4, ErrSizeMismatch},
|
||||
{"negative", payload, -1, ErrSizeMismatch},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, root := local(t)
|
||||
err := s.PutIfAbsent(context.Background(), digest(payload), tc.size, bytes.NewReader(tc.data))
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Fatalf("got %v want %v", err, tc.want)
|
||||
}
|
||||
if _, err := s.Stat(context.Background(), digest(payload)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("published bad content: %v", err)
|
||||
}
|
||||
assertNoTemps(t, root)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalExistingAndConcurrentWritesNeverReplace(t *testing.T) {
|
||||
s, root := local(t)
|
||||
payload := []byte("immutable payload")
|
||||
hash := digest(payload)
|
||||
ctx := context.Background()
|
||||
var wg sync.WaitGroup
|
||||
errorsCh := make(chan error, 12)
|
||||
for range 12 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
errorsCh <- s.PutIfAbsent(ctx, hash, int64(len(payload)), bytes.NewReader(payload))
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errorsCh)
|
||||
for err := range errorsCh {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
key, _ := Key(hash)
|
||||
filename := filepath.Join(root, filepath.FromSlash(key))
|
||||
before, _ := os.Stat(filename)
|
||||
if err := s.PutIfAbsent(ctx, hash, int64(len(payload)), bytes.NewReader(payload)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, _ := os.Stat(filename)
|
||||
if !os.SameFile(before, after) {
|
||||
t.Fatal("existing inode replaced")
|
||||
}
|
||||
if err := os.WriteFile(filename, []byte("corrupt"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Verify(ctx, hash); !errors.Is(err, ErrHashMismatch) {
|
||||
t.Fatalf("verify=%v", err)
|
||||
}
|
||||
if err := s.PutIfAbsent(ctx, hash, int64(len(payload)), bytes.NewReader(payload)); !errors.Is(err, ErrHashMismatch) {
|
||||
t.Fatalf("put=%v", err)
|
||||
}
|
||||
content, _ := os.ReadFile(filename)
|
||||
if string(content) != "corrupt" {
|
||||
t.Fatal("corruption silently overwritten")
|
||||
}
|
||||
assertNoTemps(t, root)
|
||||
}
|
||||
|
||||
func TestLocalCancellationAndReaderFailure(t *testing.T) {
|
||||
s, root := local(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
hash := digest([]byte("data"))
|
||||
if err := s.PutIfAbsent(ctx, hash, 4, strings.NewReader("data")); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Open(ctx, hash); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failure := errors.New("source failed")
|
||||
if err := s.PutIfAbsent(context.Background(), hash, 4, failingReader{failure}); !errors.Is(err, failure) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Stat(context.Background(), hash); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.PutIfAbsent(context.Background(), hash, 4, strings.NewReader("data")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
r, err := s.Open(ctx, hash)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
cancel()
|
||||
if _, err := r.Read(make([]byte, 1)); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.ReadAt(make([]byte, 1), 0); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertNoTemps(t, root)
|
||||
}
|
||||
|
||||
type failingReader struct{ err error }
|
||||
|
||||
func (r failingReader) Read([]byte) (int, error) { return 0, r.err }
|
||||
|
||||
func TestLocalStreamsWithBoundedReadsAndMidStreamCancellation(t *testing.T) {
|
||||
s, root := local(t)
|
||||
payload := bytes.Repeat([]byte("large document\x00"), 100000)
|
||||
hash := digest(payload)
|
||||
input := &boundedReader{reader: bytes.NewReader(payload)}
|
||||
if err := s.PutIfAbsent(context.Background(), hash, int64(len(payload)), input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if input.reads < 2 {
|
||||
t.Fatal("expected multiple bounded reads")
|
||||
}
|
||||
// Cancellation while staging must never publish the final content address.
|
||||
s2, root2 := local(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
input = &boundedReader{reader: bytes.NewReader(payload), cancel: cancel}
|
||||
if err := s2.PutIfAbsent(ctx, hash, int64(len(payload)), input); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("put=%v", err)
|
||||
}
|
||||
if _, err := s2.Stat(context.Background(), hash); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("published canceled upload: %v", err)
|
||||
}
|
||||
assertNoTemps(t, root)
|
||||
assertNoTemps(t, root2)
|
||||
}
|
||||
|
||||
type boundedReader struct {
|
||||
reader io.Reader
|
||||
reads int
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (r *boundedReader) Read(p []byte) (int, error) {
|
||||
if len(p) > 64<<10 {
|
||||
return 0, errors.New("unbounded input read")
|
||||
}
|
||||
r.reads++
|
||||
n, err := r.reader.Read(p)
|
||||
if r.cancel != nil {
|
||||
r.cancel()
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func TestLocalKeysAndSymlinkEscape(t *testing.T) {
|
||||
for _, hash := range []string{"", "../../etc/passwd", strings.Repeat("g", 64), strings.Repeat("a", 63)} {
|
||||
if _, err := Key(hash); !errors.Is(err, ErrInvalidHash) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
hash := digest([]byte("data"))
|
||||
key, err := Key(" " + strings.ToUpper(hash) + " ")
|
||||
if err != nil || key != "sha256/"+hash[:2]+"/"+hash {
|
||||
t.Fatalf("key=%q err=%v", key, err)
|
||||
}
|
||||
s, root := local(t)
|
||||
outside := t.TempDir()
|
||||
if err := os.Symlink(outside, filepath.Join(root, "sha256")); err != nil {
|
||||
t.Skip(err)
|
||||
}
|
||||
if err := s.PutIfAbsent(context.Background(), hash, 4, strings.NewReader("data")); err == nil {
|
||||
t.Fatal("escaped storage root")
|
||||
}
|
||||
if _, err := s.Open(context.Background(), hash); err == nil {
|
||||
t.Fatal("opened escaped path")
|
||||
}
|
||||
entries, err := os.ReadDir(outside)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatalf("outside modified: %v %v", entries, err)
|
||||
}
|
||||
}
|
||||
|
||||
func assertNoTemps(t *testing.T, root string) {
|
||||
t.Helper()
|
||||
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.HasPrefix(entry.Name(), ".document-") {
|
||||
t.Errorf("temporary file left: %s", path)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package geduldh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrMaterializeLimit = errors.New("Document materialization capacity exceeded")
|
||||
|
||||
// Source deliberately excludes mutation. Authorization precedes Acquire.
|
||||
type Source interface {
|
||||
Stat(context.Context, string) (Info, error)
|
||||
Open(context.Context, string) (Reader, error)
|
||||
}
|
||||
|
||||
type MaterializeOptions struct {
|
||||
// TempDir must be node-local scratch, never canonical storage. Empty uses TMPDIR.
|
||||
TempDir string
|
||||
MaxBytes int64
|
||||
Concurrent int
|
||||
// MaxEntries bounds queued/leased objects too, including empty payloads.
|
||||
// Zero selects 64.
|
||||
MaxEntries int
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Materializer shares in-flight/leased copies only. The last lease removes the
|
||||
// copy; it is not a persistent cache and needs no idle cache eviction goroutine.
|
||||
// Limits include both copies being downloaded and copies in use by tools.
|
||||
type Materializer struct {
|
||||
source Source
|
||||
options MaterializeOptions
|
||||
slots chan struct{}
|
||||
mu sync.Mutex
|
||||
entries map[string]*materializedEntry
|
||||
reserved int64
|
||||
active int
|
||||
}
|
||||
|
||||
type materializedEntry struct {
|
||||
hash string
|
||||
size int64
|
||||
refs int
|
||||
ready chan struct{}
|
||||
cancel context.CancelFunc
|
||||
finished bool
|
||||
dir, path string
|
||||
err error
|
||||
}
|
||||
|
||||
// Lease pins an immutable scratch copy until Close. Tools must finish before
|
||||
// Close; never give its path to a detached process. Close is idempotent.
|
||||
type Lease struct {
|
||||
Path string
|
||||
Size int64
|
||||
once sync.Once
|
||||
release func()
|
||||
}
|
||||
|
||||
func (l *Lease) Close() { l.once.Do(l.release) }
|
||||
|
||||
func NewMaterializer(source Source, options MaterializeOptions) (*Materializer, error) {
|
||||
if source == nil || options.MaxBytes <= 0 || options.Concurrent <= 0 || options.Timeout <= 0 {
|
||||
return nil, errors.New("invalid Document materializer configuration")
|
||||
}
|
||||
if options.MaxEntries == 0 {
|
||||
options.MaxEntries = 64
|
||||
}
|
||||
if options.MaxEntries < 0 {
|
||||
return nil, errors.New("invalid materializer entry limit")
|
||||
}
|
||||
return &Materializer{source: source, options: options, slots: make(chan struct{}, options.Concurrent), entries: make(map[string]*materializedEntry)}, nil
|
||||
}
|
||||
|
||||
func (m *Materializer) Acquire(ctx context.Context, hash string, maxBytes int64) (*Lease, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := Key(hash); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash = strings.ToLower(strings.TrimSpace(hash))
|
||||
info, err := m.source.Stat(ctx, hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if info.Size < 0 || maxBytes < 0 || info.Size > maxBytes || info.Size > m.options.MaxBytes {
|
||||
return nil, ErrMaterializeLimit
|
||||
}
|
||||
m.mu.Lock()
|
||||
e := m.entries[hash]
|
||||
if e != nil && e.size != info.Size {
|
||||
m.mu.Unlock()
|
||||
return nil, ErrSizeMismatch
|
||||
}
|
||||
if e == nil {
|
||||
if info.Size > m.options.MaxBytes-m.reserved || m.active >= m.options.MaxEntries {
|
||||
m.mu.Unlock()
|
||||
return nil, ErrMaterializeLimit
|
||||
}
|
||||
// One caller leaving must not cancel another caller's transfer. The
|
||||
// shared deadline is propagated to backend operations. Backends must
|
||||
// honor cancellation; it cannot interrupt an uninterruptible OS syscall.
|
||||
loadCtx, cancel := context.WithTimeout(context.Background(), m.options.Timeout)
|
||||
e = &materializedEntry{hash: hash, size: info.Size, ready: make(chan struct{}), cancel: cancel}
|
||||
m.entries[hash] = e
|
||||
m.reserved += info.Size
|
||||
m.active++
|
||||
go m.load(loadCtx, e)
|
||||
}
|
||||
e.refs++
|
||||
m.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
m.release(e)
|
||||
return nil, ctx.Err()
|
||||
case <-e.ready:
|
||||
if err := ctx.Err(); err != nil {
|
||||
m.release(e)
|
||||
return nil, err
|
||||
}
|
||||
if e.err != nil {
|
||||
m.release(e)
|
||||
return nil, e.err
|
||||
}
|
||||
return &Lease{Path: e.path, Size: e.size, release: func() { m.release(e) }}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Materializer) load(ctx context.Context, e *materializedEntry) {
|
||||
defer e.cancel()
|
||||
var dir, filename string
|
||||
var err error
|
||||
select {
|
||||
case m.slots <- struct{}{}:
|
||||
dir, filename, err = m.copy(ctx, e.hash, e.size)
|
||||
<-m.slots
|
||||
case <-ctx.Done():
|
||||
err = ctx.Err()
|
||||
}
|
||||
m.mu.Lock()
|
||||
e.dir, e.path, e.err, e.finished = dir, filename, err, true
|
||||
close(e.ready)
|
||||
if e.refs == 0 {
|
||||
m.remove(e)
|
||||
}
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Materializer) release(e *materializedEntry) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
e.refs--
|
||||
if e.refs == 0 {
|
||||
e.cancel()
|
||||
// A later caller must not join an already-cancelled download.
|
||||
if m.entries[e.hash] == e {
|
||||
delete(m.entries, e.hash)
|
||||
}
|
||||
if e.finished {
|
||||
m.remove(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Materializer) remove(e *materializedEntry) {
|
||||
if m.entries[e.hash] == e {
|
||||
delete(m.entries, e.hash)
|
||||
}
|
||||
// Failed removal keeps the byte reservation: do not pretend disk space
|
||||
// was reclaimed. Recovery of crash leftovers is an operator/scratch task.
|
||||
if e.dir != "" {
|
||||
if err := os.RemoveAll(e.dir); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
m.reserved -= e.size
|
||||
m.active--
|
||||
}
|
||||
|
||||
func (m *Materializer) copy(ctx context.Context, hash string, size int64) (dir, filename string, err error) {
|
||||
reader, err := m.source.Open(ctx, hash)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer reader.Close()
|
||||
dir, err = os.MkdirTemp(m.options.TempDir, "pageswiki-document-*")
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
// Failed partial copies are retained in dir until load performs cleanup.
|
||||
filename = filepath.Join(dir, hash)
|
||||
file, err := os.OpenFile(filename, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return dir, "", err
|
||||
}
|
||||
err = copyValidated(ctx, hash, size, reader, file)
|
||||
if err == nil {
|
||||
err = file.Chmod(0400)
|
||||
}
|
||||
closeErr := file.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return dir, "", fmt.Errorf("materialize Document: %w", err)
|
||||
}
|
||||
// Scratch is reproducible, not durable canonical storage: no fsync here.
|
||||
return dir, filename, ctx.Err()
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package geduldh
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type materializeSource struct {
|
||||
body []byte
|
||||
size int64
|
||||
gate chan struct{}
|
||||
started chan struct{}
|
||||
opens atomic.Int64
|
||||
}
|
||||
|
||||
func (s *materializeSource) Stat(ctx context.Context, hash string) (Info, error) {
|
||||
return Info{Hash: hash, Size: s.size}, ctx.Err()
|
||||
}
|
||||
func (s *materializeSource) Open(ctx context.Context, hash string) (Reader, error) {
|
||||
s.opens.Add(1)
|
||||
if s.started != nil {
|
||||
s.started <- struct{}{}
|
||||
}
|
||||
if s.gate != nil {
|
||||
select {
|
||||
case <-s.gate:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
return materializeReader{bytes.NewReader(s.body)}, ctx.Err()
|
||||
}
|
||||
|
||||
type materializeReader struct{ *bytes.Reader }
|
||||
|
||||
func (materializeReader) Close() error { return nil }
|
||||
|
||||
func newTestMaterializer(t *testing.T, source Source, quota int64) (*Materializer, string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
m, err := NewMaterializer(source, MaterializeOptions{TempDir: dir, MaxBytes: quota, Concurrent: 1, Timeout: 5 * time.Second})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m, dir
|
||||
}
|
||||
|
||||
func waitMaterializer(t *testing.T, m *Materializer, predicate func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
m.mu.Lock()
|
||||
ok := predicate()
|
||||
m.mu.Unlock()
|
||||
if ok {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
t.Fatal("materializer condition did not become true")
|
||||
}
|
||||
|
||||
func TestMaterializerSharesPinnedCopiesAndCleansLastLease(t *testing.T) {
|
||||
body := []byte("materialized 日本語")
|
||||
s := &materializeSource{body: body, size: int64(len(body))}
|
||||
m, root := newTestMaterializer(t, s, 1024)
|
||||
a, err := m.Acquire(context.Background(), digest(body), 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := m.Acquire(context.Background(), digest(body), 1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if a.Path != b.Path || s.opens.Load() != 1 {
|
||||
t.Fatal("copy was not shared")
|
||||
}
|
||||
data, err := os.ReadFile(a.Path)
|
||||
if err != nil || !bytes.Equal(data, body) {
|
||||
t.Fatalf("body=%q err=%v", data, err)
|
||||
}
|
||||
info, _ := os.Stat(a.Path)
|
||||
if info.Mode().Perm() != 0400 {
|
||||
t.Fatalf("permissions=%v", info.Mode())
|
||||
}
|
||||
dirInfo, _ := os.Stat(filepath.Dir(a.Path))
|
||||
if dirInfo.Mode().Perm() != 0700 {
|
||||
t.Fatalf("directory permissions=%v", dirInfo.Mode())
|
||||
}
|
||||
a.Close()
|
||||
a.Close()
|
||||
if _, err := os.Stat(b.Path); err != nil {
|
||||
t.Fatal("active lease lost its file", err)
|
||||
}
|
||||
b.Close()
|
||||
items, _ := os.ReadDir(root)
|
||||
if len(items) != 0 || m.reserved != 0 || m.active != 0 {
|
||||
t.Fatal("scratch was not reclaimed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaterializerCoalescesDownloadsAndCancelsOnlyLastWaiter(t *testing.T) {
|
||||
body := []byte("shared")
|
||||
s := &materializeSource{body: body, size: int64(len(body)), gate: make(chan struct{}), started: make(chan struct{}, 2)}
|
||||
m, _ := newTestMaterializer(t, s, 1024)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
errA := make(chan error, 1)
|
||||
go func() {
|
||||
lease, err := m.Acquire(ctx, digest(body), 1024)
|
||||
if lease != nil {
|
||||
lease.Close()
|
||||
}
|
||||
errA <- err
|
||||
}()
|
||||
<-s.started
|
||||
leaseB := make(chan *Lease, 1)
|
||||
errB := make(chan error, 1)
|
||||
go func() {
|
||||
lease, err := m.Acquire(context.Background(), digest(body), 1024)
|
||||
leaseB <- lease
|
||||
errB <- err
|
||||
}()
|
||||
waitMaterializer(t, m, func() bool { return m.entries[digest(body)].refs == 2 })
|
||||
cancel()
|
||||
if err := <-errA; !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("first waiter: %v", err)
|
||||
}
|
||||
close(s.gate)
|
||||
b := <-leaseB
|
||||
if err := <-errB; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s.opens.Load() != 1 {
|
||||
t.Fatal("concurrent transfer not coalesced")
|
||||
}
|
||||
b.Close()
|
||||
|
||||
s.gate = make(chan struct{})
|
||||
ctx, cancel = context.WithCancel(context.Background())
|
||||
go func() {
|
||||
lease, err := m.Acquire(ctx, digest(body), 1024)
|
||||
if lease != nil {
|
||||
lease.Close()
|
||||
}
|
||||
errA <- err
|
||||
}()
|
||||
<-s.started
|
||||
cancel()
|
||||
if err := <-errA; !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("last waiter: %v", err)
|
||||
}
|
||||
waitMaterializer(t, m, func() bool { return m.reserved == 0 && m.active == 0 })
|
||||
}
|
||||
|
||||
func TestMaterializerRejectsCorruptionSizeAndCapacity(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body []byte
|
||||
size int64
|
||||
hash string
|
||||
want error
|
||||
}{
|
||||
{"hash", []byte("bad"), 3, digest([]byte("yes")), ErrHashMismatch},
|
||||
{"short", []byte("x"), 2, digest([]byte("x")), ErrSizeMismatch},
|
||||
{"long", []byte("xyz"), 2, digest([]byte("xyz")), ErrSizeMismatch},
|
||||
{"oversize", []byte("xyz"), 3, digest([]byte("xyz")), ErrMaterializeLimit},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s := &materializeSource{body: tc.body, size: tc.size}
|
||||
m, root := newTestMaterializer(t, s, 10)
|
||||
limit := int64(10)
|
||||
if tc.name == "oversize" {
|
||||
limit = 2
|
||||
}
|
||||
lease, err := m.Acquire(context.Background(), tc.hash, limit)
|
||||
if lease != nil || !errors.Is(err, tc.want) {
|
||||
t.Fatalf("lease=%v err=%v", lease, err)
|
||||
}
|
||||
items, _ := os.ReadDir(root)
|
||||
if len(items) != 0 || m.reserved != 0 {
|
||||
t.Fatal("failed input leaked scratch")
|
||||
}
|
||||
})
|
||||
}
|
||||
s := &materializeSource{body: []byte("x"), size: 1}
|
||||
m, _ := newTestMaterializer(t, s, 1)
|
||||
lease, err := m.Acquire(context.Background(), digest(s.body), 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Close()
|
||||
if _, err := m.Acquire(context.Background(), digest([]byte("y")), 1); !errors.Is(err, ErrMaterializeLimit) {
|
||||
t.Fatalf("quota: %v", err)
|
||||
}
|
||||
if s.opens.Load() != 1 {
|
||||
t.Fatal("over-quota transfer started")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaterializerTimeoutAndEntryBound(t *testing.T) {
|
||||
s := &materializeSource{body: []byte("x"), size: 1, gate: make(chan struct{}), started: make(chan struct{}, 3)}
|
||||
m, err := NewMaterializer(s, MaterializeOptions{TempDir: t.TempDir(), MaxBytes: 100, Concurrent: 1, MaxEntries: 1, Timeout: 50 * time.Millisecond})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := m.Acquire(context.Background(), digest(s.body), 10); done <- err }()
|
||||
<-s.started
|
||||
if _, err := m.Acquire(context.Background(), digest([]byte("y")), 10); !errors.Is(err, ErrMaterializeLimit) {
|
||||
t.Fatalf("entry bound: %v", err)
|
||||
}
|
||||
if err := <-done; !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("timeout: %v", err)
|
||||
}
|
||||
waitMaterializer(t, m, func() bool { return m.active == 0 })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := m.Acquire(ctx, digest(s.body), 10); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaterializerConcurrencyBoundAndCanonicalIsolation(t *testing.T) {
|
||||
s := &materializeSource{body: []byte("x"), size: 1, gate: make(chan struct{}), started: make(chan struct{}, 3)}
|
||||
m, _ := newTestMaterializer(t, s, 100)
|
||||
done := make(chan error, 2)
|
||||
for _, data := range []string{"x", "y"} {
|
||||
go func(data string) {
|
||||
lease, err := m.Acquire(context.Background(), digest([]byte(data)), 100)
|
||||
if lease != nil {
|
||||
lease.Close()
|
||||
}
|
||||
done <- err
|
||||
}(data)
|
||||
}
|
||||
<-s.started
|
||||
waitMaterializer(t, m, func() bool { return m.active == 2 })
|
||||
if s.opens.Load() != 1 {
|
||||
t.Fatal("concurrency limit exceeded")
|
||||
}
|
||||
close(s.gate)
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := <-done; err != nil && !errors.Is(err, ErrHashMismatch) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
waitMaterializer(t, m, func() bool { return m.active == 0 })
|
||||
|
||||
canonical, root := local(t)
|
||||
body := []byte("canonical")
|
||||
hash := digest(body)
|
||||
if err := canonical.PutIfAbsent(context.Background(), hash, int64(len(body)), bytes.NewReader(body)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m, _ = newTestMaterializer(t, canonical, 100)
|
||||
lease, err := m.Acquire(context.Background(), hash, 100)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lease.Close()
|
||||
key, _ := Key(hash)
|
||||
sourceInfo, _ := os.Stat(filepath.Join(root, filepath.FromSlash(key)))
|
||||
tempInfo, _ := os.Stat(lease.Path)
|
||||
if os.SameFile(sourceInfo, tempInfo) {
|
||||
t.Fatal("canonical inode exposed to external tools")
|
||||
}
|
||||
if err := os.Chmod(lease.Path, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(lease.Path, []byte("modified!"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := canonical.Verify(context.Background(), hash); err != nil {
|
||||
t.Fatal("scratch mutation affected canonical data", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// Package geduldh stores immutable, content-addressed Document payloads.
|
||||
// Authorization and reference/retention decisions belong to the application,
|
||||
// not to a storage backend. A hash or storage key is never an access token.
|
||||
package geduldh
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const Component = "geduldh"
|
||||
|
||||
var (
|
||||
ErrInvalidHash = errors.New("invalid Document SHA-256")
|
||||
ErrHashMismatch = errors.New("Document payload does not match SHA-256")
|
||||
ErrSizeMismatch = errors.New("Document payload does not match declared size")
|
||||
)
|
||||
|
||||
type Info struct {
|
||||
Hash string
|
||||
Size int64
|
||||
}
|
||||
|
||||
// Reader supports bounded and seekable access, including HTTP Range and ZIP.
|
||||
// A remote backend must not download the entire object merely to open it.
|
||||
type Reader interface {
|
||||
io.ReadSeekCloser
|
||||
io.ReaderAt
|
||||
}
|
||||
|
||||
// Store is the immutable payload boundary, not a filesystem abstraction.
|
||||
// PutIfAbsent must verify the size and SHA-256 before publishing a complete
|
||||
// object, never replace an existing object, and reject corrupt existing bytes.
|
||||
// A successful write must precede the metadata transaction which references it.
|
||||
// Delete is deliberately absent: GC requires reference and retention protection.
|
||||
type Store interface {
|
||||
Stat(context.Context, string) (Info, error)
|
||||
Open(context.Context, string) (Reader, error)
|
||||
PutIfAbsent(context.Context, string, int64, io.Reader) error
|
||||
Verify(context.Context, string) error
|
||||
}
|
||||
|
||||
// Key preserves the existing on-disk layout and is also suitable for S3 keys.
|
||||
// Backend placement never changes Page/Revision identity or public URLs.
|
||||
func Key(hash string) (string, error) {
|
||||
hash = strings.ToLower(strings.TrimSpace(hash))
|
||||
if len(hash) != sha256.Size*2 {
|
||||
return "", ErrInvalidHash
|
||||
}
|
||||
if _, err := hex.DecodeString(hash); err != nil {
|
||||
return "", ErrInvalidHash
|
||||
}
|
||||
return "sha256/" + hash[:2] + "/" + hash, nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package grammaratur
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// HTMLToMarkdownAuthoring keeps source HTML when conversion loses structure,
|
||||
// attributes, comments or text. This is not a sanitization boundary.
|
||||
func HTMLToMarkdownAuthoring(source string) (string, error) {
|
||||
converted, err := HTMLToMarkdown(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
return converted, nil
|
||||
}
|
||||
|
||||
// {=html} is an explicit authoring fence, not an ordinary code sample. The
|
||||
// closing delimiter is longer than any run in the source, so arbitrary HTML
|
||||
// (including Markdown examples) cannot accidentally terminate it.
|
||||
func rawHTMLBlock(source string) string {
|
||||
longest, run := 2, 0
|
||||
for _, c := range source {
|
||||
if c == '`' {
|
||||
run++
|
||||
if run > longest {
|
||||
longest = run
|
||||
}
|
||||
} else {
|
||||
run = 0
|
||||
}
|
||||
}
|
||||
fence := strings.Repeat("`", longest+1)
|
||||
return fence + "{=html}\n" + source + "\n" + fence
|
||||
}
|
||||
|
||||
// MarkdownAuthoringHTML preserves protected HTML byte-for-byte while rendering
|
||||
// ordinary Markdown. Callers must still apply projection sanitization for UI.
|
||||
func MarkdownAuthoringHTML(source string) string {
|
||||
lines := strings.SplitAfter(source, "\n")
|
||||
var markdown strings.Builder
|
||||
type rawBlock struct{ token, html string }
|
||||
var blocks []rawBlock
|
||||
var ordinary byte
|
||||
ordinaryLen := 0
|
||||
for i := 0; i < len(lines); i++ {
|
||||
line := strings.TrimSuffix(strings.TrimSuffix(lines[i], "\n"), "\r")
|
||||
char, n := byte(0), 0
|
||||
if len(line) > 0 && (line[0] == '`' || line[0] == '~') {
|
||||
char = line[0]
|
||||
for n < len(line) && line[n] == char {
|
||||
n++
|
||||
}
|
||||
}
|
||||
if ordinary != 0 {
|
||||
markdown.WriteString(lines[i])
|
||||
if char == ordinary && n >= ordinaryLen && strings.TrimSpace(line[n:]) == "" {
|
||||
ordinary = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if char == '`' && n >= 3 && strings.TrimSpace(line[n:]) == "{=html}" {
|
||||
end := i + 1
|
||||
for ; end < len(lines); end++ {
|
||||
close := strings.TrimSpace(lines[end])
|
||||
if len(close) >= n && strings.Trim(close, "`") == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if end < len(lines) {
|
||||
raw := strings.TrimSuffix(strings.Join(lines[i+1:end], ""), "\n")
|
||||
token := "PAGESWIKIRAW" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
blocks = append(blocks, rawBlock{token, raw})
|
||||
markdown.WriteString("\n\n" + token + "\n\n")
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
if n >= 3 {
|
||||
ordinary, ordinaryLen = char, n
|
||||
}
|
||||
markdown.WriteString(lines[i])
|
||||
}
|
||||
if len(blocks) == 1 && strings.TrimSpace(markdown.String()) == blocks[0].token {
|
||||
return blocks[0].html
|
||||
}
|
||||
out := MarkdownToHTML(markdown.String())
|
||||
for _, block := range blocks {
|
||||
out = strings.Replace(out, "<p>"+block.token+"</p>", block.html, 1)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func htmlStructure(source string) string {
|
||||
n, err := html.Parse(strings.NewReader(source))
|
||||
if err != nil {
|
||||
return source
|
||||
}
|
||||
var out bytes.Buffer
|
||||
var visit func(*html.Node, bool)
|
||||
visit = func(n *html.Node, literal bool) {
|
||||
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
|
||||
data := n.Data
|
||||
if n.Type == html.TextNode && !literal {
|
||||
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
|
||||
return
|
||||
}
|
||||
// Inline whitespace can separate words (including around an inline
|
||||
// element). Never normalize it away when deciding conversion safety.
|
||||
}
|
||||
attrs := append([]html.Attribute(nil), n.Attr...)
|
||||
sort.Slice(attrs, func(i, j int) bool { return attrs[i].Namespace+":"+attrs[i].Key < attrs[j].Namespace+":"+attrs[j].Key })
|
||||
b, _ := json.Marshal([]any{n.Type, n.Namespace, data, attrs})
|
||||
out.Write(b)
|
||||
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
||||
visit(c, literal)
|
||||
}
|
||||
out.WriteByte(')')
|
||||
}
|
||||
visit(n, false)
|
||||
return out.String()
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package grammaratur
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAuthoringRoundTrip(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"<h1>Heading</h1><p>Hello <strong>world</strong>.</p>",
|
||||
"<p>{{children:/guide}}</p>",
|
||||
"<figure data-extra=\"kept\"><img src=\"/photo\" alt=\"Photo\"><figcaption>A caption</figcaption></figure>",
|
||||
"<!-- keep comment --><p id=\"anchor\" class=\"custom\">text</p>",
|
||||
"<table><tr><td rowspan=\"2\">a</td><td>b</td></tr><tr><td>c</td></tr></table>",
|
||||
"<p>a <em>b</em> c</p>",
|
||||
"<pre><code class=\"language-python\"> print('x')\n</code></pre>",
|
||||
"<custom-element data-x=\"1\">opaque</custom-element>",
|
||||
"<div class=\"custom\">\n<p>one</p>\n\n<p>two</p>\n</div>",
|
||||
"<script>const x = '<b>untouched</b>';</script>",
|
||||
} {
|
||||
t.Run(source, func(t *testing.T) {
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if htmlStructure(MarkdownAuthoringHTML(md)) != htmlStructure(source) {
|
||||
t.Fatalf("lossy conversion: %q", md)
|
||||
}
|
||||
})
|
||||
}
|
||||
md, err := HTMLToMarkdownAuthoring("<h1>Hello</h1>")
|
||||
if err != nil || md != "# Hello" {
|
||||
t.Fatalf("simple Markdown conversion: %q %v", md, err)
|
||||
}
|
||||
for _, source := range []string{`<p data-custom="yes">Hello</p>`, `<!-- saved --><h1>Title</h1>`, `<p>a <em>b</em> c</p>`} {
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if htmlStructure(MarkdownAuthoringHTML(md)) != htmlStructure(source) {
|
||||
t.Fatal("whitespace/attributes lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringProtectedHTML(t *testing.T) {
|
||||
for _, raw := range []string{"<figure data-x='a'>a</figure>", "<pre>```\n{=html}\n````</pre>\n", "<script>const raw = `x`</script>", "<p>line\r\n</p>"} {
|
||||
md := rawHTMLBlock(raw)
|
||||
if got := MarkdownAuthoringHTML(md); got != raw {
|
||||
t.Fatalf("raw bytes changed: %q want %q", got, raw)
|
||||
}
|
||||
mixed := MarkdownAuthoringHTML("# Added\n\n" + md + "\n\nTail")
|
||||
if !strings.Contains(mixed, raw) || !strings.Contains(mixed, "<h1>Added</h1>") || !strings.Contains(mixed, "<p>Tail</p>") {
|
||||
t.Fatalf("mixed blocks: %q", mixed)
|
||||
}
|
||||
}
|
||||
code := "````text\n```{=html}\n<script>unsafe()</script>\n```\n````"
|
||||
if strings.Contains(MarkdownAuthoringHTML(code), "<script>") {
|
||||
t.Fatal("HTML escaped out of ordinary code sample")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringWhitespaceComparisonIsConservative(t *testing.T) {
|
||||
if htmlStructure("<p>a <em>b</em> c</p>") == htmlStructure("<p>a<em>b</em>c</p>") {
|
||||
t.Fatal("word boundaries ignored")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package grammaratur
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestComponentBoundary(t *testing.T) {
|
||||
if Component != "grammaratur" {
|
||||
t.Fatal("component identity changed")
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(file, "_test.go") {
|
||||
continue
|
||||
}
|
||||
ast, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, spec := range ast.Imports {
|
||||
path, err := strconv.Unquote(spec.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"pageswiki/internal/", "database/", "net", "os"} {
|
||||
if path == forbidden || strings.HasPrefix(path, strings.TrimSuffix(forbidden, "/")+"/") {
|
||||
t.Errorf("%s imports %s: Grammaratur must not own I/O, persistence or application policy", file, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package grammaratur_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
|
||||
"github.com/gomarkdown/markdown"
|
||||
"pageswiki/internal/compiler"
|
||||
"pageswiki/internal/grammaratur"
|
||||
"pageswiki/internal/render"
|
||||
)
|
||||
|
||||
func TestLegacyMarkdownCompatibility(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"", "# Heading\n\n本文", "{{children:/guide}}", "- one\n- two\n",
|
||||
"```python\nprint('hello')\n```", "[link](/path)\n\n",
|
||||
"<p data-custom='keep'>raw HTML</p>",
|
||||
"```{=html}\n<figure data-x='1'>source</figure>\n```",
|
||||
} {
|
||||
t.Run(source, func(t *testing.T) {
|
||||
want := string(markdown.ToHTML([]byte(source), nil, nil))
|
||||
if got := grammaratur.MarkdownToHTML(source); got != want {
|
||||
t.Fatalf("dialect changed: %q want %q", got, want)
|
||||
}
|
||||
if got := render.Markdown(source); got != want {
|
||||
t.Fatalf("render entry changed: %q want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyHTMLAndAuthoringCompatibility(t *testing.T) {
|
||||
for _, source := range []string{"", "<h1>Heading</h1>", "<p>{{children}}</p>", "<!--retain--><figure data-custom='keep'><figcaption>Caption</figcaption></figure>", "<script>never execute</script>"} {
|
||||
want, err := htmltomarkdown.ConvertString(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, convert := range []func(string) (string, error){grammaratur.HTMLToMarkdown, compiler.HTMLToMarkdown} {
|
||||
got, err := convert(source)
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("ordinary conversion changed: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
protected, err := grammaratur.HTMLToMarkdownAuthoring(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
compat, err := compiler.HTMLToMarkdownAuthoring(source)
|
||||
if err != nil || protected != compat {
|
||||
t.Fatal("authoring facade changed", err)
|
||||
}
|
||||
if compiler.MarkdownAuthoringHTML(compat) != grammaratur.MarkdownAuthoringHTML(protected) {
|
||||
t.Fatal("protected render facade changed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringIsExplicitAndNotASanitizer(t *testing.T) {
|
||||
const source = "```{=html}\n<script>untrusted()</script>\n```"
|
||||
if strings.Contains(grammaratur.MarkdownToHTML(source), "<script>") {
|
||||
t.Fatal("ordinary conversion opted into authoring")
|
||||
}
|
||||
if got := grammaratur.MarkdownAuthoringHTML(source); got != "<script>untrusted()</script>" {
|
||||
t.Fatalf("authoring removed source: %q", got)
|
||||
}
|
||||
// Authorization, macro expansion and sanitization stay in the projection
|
||||
// layer. Grammaratur returns source, not HTML trusted for a browser sink.
|
||||
if got := grammaratur.MarkdownToHTML("{{children}}"); !strings.Contains(got, "{{children}}") {
|
||||
t.Fatal("macro unexpectedly expanded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Package grammaratur owns document-format conversion and authoring fidelity.
|
||||
//
|
||||
// Ordinary conversion and protected authoring conversion are distinct contracts:
|
||||
// callers must opt into {=html} fences. Neither path authorizes content, expands
|
||||
// macros, sanitizes a display projection, persists revisions, or fetches URLs.
|
||||
// Those responsibilities remain with the caller. In particular, preserving
|
||||
// source HTML never grants permission to execute its scripts or event handlers.
|
||||
//
|
||||
// Grammaratur is an in-process component, not a service or a new public API.
|
||||
// The name denotes the words/format-conversion responsibility in PagesWiki's
|
||||
// architecture; see docs/design/ja/component-names.md.
|
||||
package grammaratur
|
||||
|
||||
// Component is the stable component label for diagnostics and instrumentation.
|
||||
// It is not a replacement for API routes, provider IDs or persisted settings.
|
||||
const Component = "grammaratur"
|
||||
@@ -0,0 +1,18 @@
|
||||
package grammaratur
|
||||
|
||||
import (
|
||||
htmltomarkdown "github.com/JohannesKaufmann/html-to-markdown/v2"
|
||||
"github.com/gomarkdown/markdown"
|
||||
)
|
||||
|
||||
// HTMLToMarkdown is the existing ordinary conversion, used by integrations
|
||||
// which do not understand protected authoring blocks. It can be lossy.
|
||||
func HTMLToMarkdown(source string) (string, error) {
|
||||
return htmltomarkdown.ConvertString(source)
|
||||
}
|
||||
|
||||
// MarkdownToHTML preserves the existing Markdown dialect and renderer options.
|
||||
// It neither interprets authoring fences nor sanitizes the returned HTML.
|
||||
func MarkdownToHTML(source string) string {
|
||||
return string(markdown.ToHTML([]byte(source), nil, nil))
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// Package kunstzeal selects projections and executes bounded rendering providers.
|
||||
// Authentication, source provenance and canonical storage remain caller-owned.
|
||||
package kunstzeal
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Delivery string
|
||||
|
||||
const (
|
||||
DeliveryHTML Delivery = "html"
|
||||
DeliveryText Delivery = "text"
|
||||
DeliveryRawMedia Delivery = "raw-media"
|
||||
DeliveryRawFrame Delivery = "raw-frame"
|
||||
DeliveryDownload Delivery = "download"
|
||||
)
|
||||
|
||||
type Descriptor struct {
|
||||
MediaType string
|
||||
Filename string
|
||||
SizeBytes int64
|
||||
}
|
||||
|
||||
type Adapter struct {
|
||||
ID string
|
||||
Kind string
|
||||
Delivery Delivery
|
||||
NeedsText bool
|
||||
WindowableText bool
|
||||
Match func(Descriptor) bool
|
||||
}
|
||||
|
||||
const InlineTextWindowThreshold = int64(2 << 20)
|
||||
|
||||
var projectionAdapters = []Adapter{
|
||||
{
|
||||
ID: "html",
|
||||
Kind: "html",
|
||||
Delivery: DeliveryHTML,
|
||||
Match: mediaTypes("text/html"),
|
||||
},
|
||||
{
|
||||
ID: "excalidraw",
|
||||
Kind: "excalidraw",
|
||||
Delivery: DeliveryText,
|
||||
NeedsText: true,
|
||||
WindowableText: true,
|
||||
Match: extensions(".excalidraw"),
|
||||
},
|
||||
{
|
||||
ID: "csv",
|
||||
Kind: "csv",
|
||||
Delivery: DeliveryText,
|
||||
NeedsText: true,
|
||||
WindowableText: true,
|
||||
Match: matchAny(
|
||||
mediaTypes("text/csv", "application/csv"),
|
||||
extensions(".csv"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "archive",
|
||||
Kind: "archive",
|
||||
Delivery: DeliveryDownload,
|
||||
Match: matchAny(
|
||||
mediaTypes(
|
||||
"application/zip", "application/x-zip-compressed",
|
||||
"application/x-rar-compressed", "application/vnd.rar",
|
||||
"application/x-7z-compressed", "application/x-tar",
|
||||
"application/gzip", "application/x-xz",
|
||||
),
|
||||
extensions(".zip", ".rar", ".7z", ".tar", ".gz", ".tgz", ".xz", ".txz"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "debian-package",
|
||||
Kind: "metadata",
|
||||
Delivery: DeliveryDownload,
|
||||
Match: matchAny(
|
||||
mediaTypes(
|
||||
"application/vnd.debian.binary-package",
|
||||
"application/x-debian-package",
|
||||
),
|
||||
extensions(".deb"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "eml",
|
||||
Kind: "email",
|
||||
Delivery: DeliveryText,
|
||||
Match: matchAny(
|
||||
mediaTypes("message/rfc822"),
|
||||
extensions(".eml"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "pe",
|
||||
Kind: "metadata",
|
||||
Delivery: DeliveryDownload,
|
||||
Match: extensions(".exe", ".dll", ".sys"),
|
||||
},
|
||||
{
|
||||
ID: "json",
|
||||
Kind: "json",
|
||||
Delivery: DeliveryText,
|
||||
WindowableText: true,
|
||||
Match: matchAny(mediaTypes("application/json", "application/ld+json"), extensions(".json", ".jsonl")),
|
||||
},
|
||||
{
|
||||
ID: "text",
|
||||
Kind: "code",
|
||||
Delivery: DeliveryText,
|
||||
NeedsText: true,
|
||||
WindowableText: true,
|
||||
Match: textMediaType,
|
||||
},
|
||||
{
|
||||
ID: "image",
|
||||
Kind: "image",
|
||||
Delivery: DeliveryRawMedia,
|
||||
Match: matchAny(
|
||||
mediaTypePrefix("image/"),
|
||||
extensions(".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".svg"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "audio",
|
||||
Kind: "audio",
|
||||
Delivery: DeliveryRawMedia,
|
||||
Match: matchAny(
|
||||
mediaTypePrefix("audio/"),
|
||||
extensions(".mp3", ".flac", ".wav", ".ogg", ".m4a", ".aac", ".opus"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "video",
|
||||
Kind: "video",
|
||||
Delivery: DeliveryRawMedia,
|
||||
Match: matchAny(
|
||||
mediaTypePrefix("video/"),
|
||||
extensions(".mp4", ".webm", ".mkv", ".mov", ".m4v", ".ogv"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "pdf",
|
||||
Kind: "pdf",
|
||||
Delivery: DeliveryRawFrame,
|
||||
Match: matchAny(
|
||||
mediaTypes("application/pdf"),
|
||||
extensions(".pdf"),
|
||||
),
|
||||
},
|
||||
{
|
||||
ID: "download",
|
||||
Kind: "download",
|
||||
Delivery: DeliveryDownload,
|
||||
Match: func(Descriptor) bool { return true },
|
||||
},
|
||||
}
|
||||
|
||||
func SelectAdapter(descriptor Descriptor) Adapter {
|
||||
for _, adapter := range projectionAdapters {
|
||||
if adapter.Match(descriptor) {
|
||||
return adapter
|
||||
}
|
||||
}
|
||||
return projectionAdapters[len(projectionAdapters)-1]
|
||||
}
|
||||
|
||||
func mediaTypes(types ...string) func(Descriptor) bool {
|
||||
return func(descriptor Descriptor) bool {
|
||||
for _, candidate := range types {
|
||||
if descriptor.MediaType == candidate {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func mediaTypePrefix(prefix string) func(Descriptor) bool {
|
||||
return func(descriptor Descriptor) bool {
|
||||
return strings.HasPrefix(descriptor.MediaType, prefix)
|
||||
}
|
||||
}
|
||||
|
||||
func extensions(values ...string) func(Descriptor) bool {
|
||||
return func(descriptor Descriptor) bool {
|
||||
extension := strings.ToLower(filepath.Ext(descriptor.Filename))
|
||||
for _, candidate := range values {
|
||||
if extension == candidate {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func matchAny(matchers ...func(Descriptor) bool) func(Descriptor) bool {
|
||||
return func(descriptor Descriptor) bool {
|
||||
for _, matcher := range matchers {
|
||||
if matcher(descriptor) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func textMediaType(descriptor Descriptor) bool {
|
||||
switch descriptor.MediaType {
|
||||
case "application/json",
|
||||
"application/xml",
|
||||
"application/javascript",
|
||||
"application/x-javascript",
|
||||
"application/x-sh",
|
||||
"application/x-shellscript",
|
||||
"application/x-yaml",
|
||||
"application/yaml",
|
||||
"application/toml":
|
||||
return true
|
||||
default:
|
||||
return strings.HasPrefix(descriptor.MediaType, "text/")
|
||||
}
|
||||
}
|
||||
|
||||
// Catalog returns a copy; callers cannot reorder or disable the shared registry.
|
||||
func Catalog() []Adapter { return append([]Adapter(nil), projectionAdapters...) }
|
||||
@@ -0,0 +1,105 @@
|
||||
package kunstzeal
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAdapterSelectionAndOrdering(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
mime, filename, id, kind string
|
||||
delivery Delivery
|
||||
needsText, window bool
|
||||
}{
|
||||
{"text/html", "scene.excalidraw", "html", "html", DeliveryHTML, false, false},
|
||||
{"application/json", "scene.EXCALIDRAW", "excalidraw", "excalidraw", DeliveryText, true, true},
|
||||
{"text/plain", "data.CSV", "csv", "csv", DeliveryText, true, true},
|
||||
{"application/zip", "archive", "archive", "archive", DeliveryDownload, false, false},
|
||||
{"application/octet-stream", "package.deb", "debian-package", "metadata", DeliveryDownload, false, false},
|
||||
{"text/plain", "mail.eml", "eml", "email", DeliveryText, false, false},
|
||||
{"application/octet-stream", "program.exe", "pe", "metadata", DeliveryDownload, false, false},
|
||||
{"application/json", "data.json", "json", "json", DeliveryText, false, true},
|
||||
{"text/x-python", "code.py", "text", "code", DeliveryText, true, true},
|
||||
{"image/png", "image", "image", "image", DeliveryRawMedia, false, false},
|
||||
{"audio/flac", "music", "audio", "audio", DeliveryRawMedia, false, false},
|
||||
{"video/mp4", "movie", "video", "video", DeliveryRawMedia, false, false},
|
||||
{"application/pdf", "manual", "pdf", "pdf", DeliveryRawFrame, false, false},
|
||||
{"application/octet-stream", "unknown", "download", "download", DeliveryDownload, false, false},
|
||||
} {
|
||||
got := SelectAdapter(Descriptor{MediaType: test.mime, Filename: test.filename, SizeBytes: InlineTextWindowThreshold + 1})
|
||||
if got.ID != test.id || got.Kind != test.kind || got.Delivery != test.delivery || got.NeedsText != test.needsText || got.WindowableText != test.window {
|
||||
t.Fatalf("%s/%s: %+v", test.mime, test.filename, got)
|
||||
}
|
||||
}
|
||||
if got := SelectAdapter(Descriptor{}); got.ID != "download" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdapterCatalogIsCopyAndConcurrent(t *testing.T) {
|
||||
catalog := Catalog()
|
||||
ids := []string{}
|
||||
for _, a := range catalog {
|
||||
ids = append(ids, a.ID)
|
||||
}
|
||||
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download" {
|
||||
t.Fatal("catalog order changed", ids)
|
||||
}
|
||||
catalog[0].ID = "corrupt"
|
||||
catalog[0].Match = func(Descriptor) bool { return false }
|
||||
if Catalog()[0].ID != "html" || SelectAdapter(Descriptor{MediaType: "text/html"}).ID != "html" {
|
||||
t.Fatal("catalog mutation changed shared selection")
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 100; j++ {
|
||||
Catalog()[0].ID = "copy"
|
||||
if SelectAdapter(Descriptor{MediaType: "text/html"}).ID != "html" {
|
||||
t.Error("registry changed")
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestComponentBoundary(t *testing.T) {
|
||||
if Component != "kunstzeal" {
|
||||
t.Fatal("component identity changed")
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(file, "_test.go") {
|
||||
continue
|
||||
}
|
||||
ast, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, spec := range ast.Imports {
|
||||
path, err := strconv.Unquote(spec.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"pageswiki/internal", "database", "os/exec"} {
|
||||
if path == forbidden || strings.HasPrefix(path, forbidden+"/") {
|
||||
t.Errorf("%s imports %s: providers must not own application state or arbitrary process execution", file, path)
|
||||
}
|
||||
}
|
||||
if file == "adapters.go" && (strings.HasPrefix(path, "net") || path == "os") {
|
||||
t.Error("adapter selection acquired I/O")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package kunstzeal
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
var ErrDiagramCacheLimit = errors.New("diagram cache exceeds limit")
|
||||
|
||||
// ReadDiagramCache reads only a bounded derived artifact. filename must be
|
||||
// constructed by the application after validating kind/hash and authorizing
|
||||
// source provenance. A cache hit is not an access grant or a sanitized SVG.
|
||||
func ReadDiagramCache(filename string) ([]byte, error) {
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(f, DiagramOutputLimit+1))
|
||||
if len(b) > DiagramOutputLimit {
|
||||
return nil, ErrDiagramCacheLimit
|
||||
}
|
||||
return b, err
|
||||
}
|
||||
|
||||
// WriteDiagramCache publishes a complete artifact with same-directory rename.
|
||||
// Concurrent readers observe the old or new file, never a truncated write.
|
||||
// This is disposable cache storage, not a durable canonical Document commit.
|
||||
func WriteDiagramCache(filename string, data []byte) error {
|
||||
if len(data) > DiagramOutputLimit {
|
||||
return ErrDiagramCacheLimit
|
||||
}
|
||||
dir := filepath.Dir(filename)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".diagram-*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(f.Name())
|
||||
defer f.Close()
|
||||
if _, err = f.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = f.Chmod(0644); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(f.Name(), filename)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package kunstzeal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDiagramCacheAtomicReplacement(t *testing.T) {
|
||||
filename := filepath.Join(t.TempDir(), "mermaid", "fixture.svg")
|
||||
a, b := bytes.Repeat([]byte("A"), 64<<10), bytes.Repeat([]byte("B"), 64<<10)
|
||||
if err := WriteDiagramCache(filename, a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
for n := 0; n < 20; n++ {
|
||||
if i%2 == 0 {
|
||||
data := a
|
||||
if n%2 == 0 {
|
||||
data = b
|
||||
}
|
||||
if err := WriteDiagramCache(filename, data); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
} else {
|
||||
data, err := ReadDiagramCache(filename)
|
||||
if err != nil || (!bytes.Equal(data, a) && !bytes.Equal(data, b)) {
|
||||
t.Errorf("partial cache: length=%d err=%v", len(data), err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
files, err := filepath.Glob(filepath.Join(filepath.Dir(filename), ".diagram-*.tmp"))
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatal("temporary artifacts leaked", files, err)
|
||||
}
|
||||
info, err := os.Stat(filename)
|
||||
if err != nil || info.Mode().Perm() != 0644 {
|
||||
t.Fatal(info, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiagramCacheBudgetsAndFailures(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
filename := filepath.Join(root, "fixture.svg")
|
||||
if err := WriteDiagramCache(filename, []byte("complete")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
large := bytes.Repeat([]byte("x"), DiagramOutputLimit+1)
|
||||
if err := WriteDiagramCache(filename, large); !errors.Is(err, ErrDiagramCacheLimit) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := ReadDiagramCache(filename)
|
||||
if err != nil || string(b) != "complete" {
|
||||
t.Fatal("failed write destroyed cache", err)
|
||||
}
|
||||
if err = os.WriteFile(filename, large, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, err = ReadDiagramCache(filename); !errors.Is(err, ErrDiagramCacheLimit) || b != nil {
|
||||
t.Fatal("oversized cache returned", err)
|
||||
}
|
||||
if _, err = ReadDiagramCache(filepath.Join(root, "missing")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = WriteDiagramCache(root, []byte("cannot replace a directory")); err == nil {
|
||||
t.Fatal("rename failure hidden")
|
||||
}
|
||||
// Failed rename removes its temporary artifact too.
|
||||
files, err := filepath.Glob(filepath.Join(filepath.Dir(root), ".diagram-*.tmp"))
|
||||
if err != nil || len(files) != 0 {
|
||||
t.Fatal(files, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package kunstzeal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const Component = "kunstzeal"
|
||||
const DiagramSourceLimit = 1 << 20
|
||||
const DiagramOutputLimit = 4 << 20
|
||||
const DiagramInlineLimit = 32 << 10
|
||||
const DiagramTimeout = 15 * time.Second
|
||||
|
||||
var (
|
||||
ErrDiagramKind = errors.New("unsupported diagram type")
|
||||
ErrDiagramSource = errors.New("diagram source exceeds limit")
|
||||
ErrDiagramOutput = errors.New("diagram output unavailable or exceeds limit")
|
||||
ErrProviderConfig = errors.New("diagram renderer configuration invalid")
|
||||
ErrProviderUnavailable = errors.New("diagram renderer unavailable")
|
||||
ErrProviderFailed = errors.New("diagram renderer failed")
|
||||
)
|
||||
|
||||
// DiagramProvider does not authorize a request or trust its SVG output.
|
||||
// Callers must retain source access checks and the sandbox response policy.
|
||||
type DiagramProvider interface {
|
||||
Render(context.Context, string, string) ([]byte, error)
|
||||
}
|
||||
|
||||
func DiagramHash(kind, source, format string) string {
|
||||
sum := sha256.Sum256([]byte(kind + "\x00" + format + "\x00" + source))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func AllowedDiagramType(kind string) bool {
|
||||
switch kind {
|
||||
case "mermaid", "plantuml", "graphviz", "dot", "d2":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func NormalizeDiagramType(kind string) string {
|
||||
if kind == "dot" {
|
||||
return "graphviz"
|
||||
}
|
||||
return kind
|
||||
}
|
||||
|
||||
type HTTPClient interface {
|
||||
Do(*http.Request) (*http.Response, error)
|
||||
}
|
||||
|
||||
// Kroki receives an administrator-configured service address, never a URL from
|
||||
// document content. Private service-network endpoints are intentional here.
|
||||
// Client must honor context cancellation and reject redirects. No default
|
||||
// client is used, and provider failures never expose its URL or response body.
|
||||
type Kroki struct {
|
||||
Endpoint string
|
||||
Client HTTPClient
|
||||
}
|
||||
|
||||
func (k Kroki) Render(parent context.Context, kind, source string) ([]byte, error) {
|
||||
if err := parent.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kind = NormalizeDiagramType(kind)
|
||||
if !AllowedDiagramType(kind) {
|
||||
return nil, ErrDiagramKind
|
||||
}
|
||||
if len(source) > DiagramSourceLimit {
|
||||
return nil, ErrDiagramSource
|
||||
}
|
||||
u, err := url.Parse(k.Endpoint)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || k.Client == nil {
|
||||
return nil, ErrProviderConfig
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(parent, DiagramTimeout)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(k.Endpoint, "/")+"/"+kind+"/svg", strings.NewReader(source))
|
||||
if err != nil {
|
||||
return nil, ErrProviderConfig
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain; charset=utf-8")
|
||||
resp, err := k.Client.Do(req)
|
||||
if err != nil {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, ErrProviderUnavailable
|
||||
}
|
||||
if resp == nil || resp.Body == nil {
|
||||
return nil, ErrProviderUnavailable
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, ErrProviderFailed
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, DiagramOutputLimit+1))
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if err != nil || len(b) > DiagramOutputLimit {
|
||||
return nil, ErrDiagramOutput
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package kunstzeal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ DiagramProvider = Kroki{}
|
||||
|
||||
type clientFixture func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f clientFixture) Do(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
type trackedReader struct {
|
||||
io.Reader
|
||||
closed bool
|
||||
}
|
||||
|
||||
func (r *trackedReader) Close() error { r.closed = true; return nil }
|
||||
|
||||
func TestDiagramIdentityAndKinds(t *testing.T) {
|
||||
for _, kind := range []string{"mermaid", "plantuml", "graphviz", "dot", "d2"} {
|
||||
if !AllowedDiagramType(kind) {
|
||||
t.Fatal(kind)
|
||||
}
|
||||
for _, source := range []string{"", "graph LR; A-->B;", "日本語\x00source"} {
|
||||
sum := sha256.Sum256([]byte(kind + "\x00svg\x00" + source))
|
||||
if DiagramHash(kind, source, "svg") != hex.EncodeToString(sum[:]) {
|
||||
t.Fatal("cache identity changed")
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, kind := range []string{"", "nwdiag", "../mermaid", "Mermaid", "svg", "graphviz/svg"} {
|
||||
if AllowedDiagramType(kind) {
|
||||
t.Fatal("unknown kind", kind)
|
||||
}
|
||||
}
|
||||
if NormalizeDiagramType("dot") != "graphviz" || NormalizeDiagramType("mermaid") != "mermaid" {
|
||||
t.Fatal("normalization changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestKrokiBoundedRequestAndOutput(t *testing.T) {
|
||||
for _, kind := range []string{"mermaid", "dot", "d2"} {
|
||||
body := &trackedReader{Reader: strings.NewReader("<svg>fixture</svg>")}
|
||||
k := Kroki{Endpoint: "http://renderer.example/prefix/", Client: clientFixture(func(r *http.Request) (*http.Response, error) {
|
||||
b, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Method != "POST" || r.URL.String() != "http://renderer.example/prefix/"+NormalizeDiagramType(kind)+"/svg" || string(b) != "source" || r.Header.Get("Content-Type") != "text/plain; charset=utf-8" {
|
||||
t.Fatal("request contract changed")
|
||||
}
|
||||
if r.Header.Get("Authorization") != "" || r.Header.Get("Cookie") != "" {
|
||||
t.Fatal("credentials forwarded")
|
||||
}
|
||||
deadline, ok := r.Context().Deadline()
|
||||
if !ok || time.Until(deadline) > DiagramTimeout {
|
||||
t.Fatal("unbounded provider")
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: body}, nil
|
||||
})}
|
||||
b, err := k.Render(context.Background(), kind, "source")
|
||||
if err != nil || string(b) != "<svg>fixture</svg>" || !body.closed {
|
||||
t.Fatal(string(b), err, body.closed)
|
||||
}
|
||||
}
|
||||
for _, size := range []int{DiagramOutputLimit, DiagramOutputLimit + 1} {
|
||||
body := &trackedReader{Reader: strings.NewReader(strings.Repeat("x", size))}
|
||||
k := Kroki{Endpoint: "https://renderer.example", Client: clientFixture(func(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: 200, Body: body}, nil })}
|
||||
b, err := k.Render(context.Background(), "mermaid", strings.Repeat("x", DiagramSourceLimit))
|
||||
if size == DiagramOutputLimit {
|
||||
if err != nil || len(b) != size {
|
||||
t.Fatal(len(b), err)
|
||||
}
|
||||
} else if !errors.Is(err, ErrDiagramOutput) || b != nil {
|
||||
t.Fatal("oversized output escaped", err)
|
||||
}
|
||||
if !body.closed {
|
||||
t.Fatal("response leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKrokiFailsClosedBeforeIO(t *testing.T) {
|
||||
client := clientFixture(func(*http.Request) (*http.Response, error) { t.Fatal("invalid request performed I/O"); return nil, nil })
|
||||
for _, endpoint := range []string{"", "file:///etc/passwd", "https://user:secret@renderer.example", "https://renderer.example?token=secret", "https://renderer.example#fragment", "https://renderer.example?", "https:///path", "http://%zz"} {
|
||||
b, err := (Kroki{Endpoint: endpoint, Client: client}).Render(context.Background(), "mermaid", "source")
|
||||
if !errors.Is(err, ErrProviderConfig) || b != nil {
|
||||
t.Fatal("bad provider accepted", err)
|
||||
}
|
||||
}
|
||||
k := Kroki{Endpoint: "http://renderer.example", Client: client}
|
||||
if _, err := k.Render(context.Background(), "../../secret", "source"); !errors.Is(err, ErrDiagramKind) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := k.Render(context.Background(), "mermaid", strings.Repeat("x", DiagramSourceLimit+1)); !errors.Is(err, ErrDiagramSource) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := (Kroki{Endpoint: k.Endpoint}).Render(context.Background(), "mermaid", "source"); !errors.Is(err, ErrProviderConfig) {
|
||||
t.Fatal("default HTTP client used", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := k.Render(ctx, "mermaid", "source"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKrokiFailuresAreOpaqueAndCloseBodies(t *testing.T) {
|
||||
for _, code := range []int{301, 302, 307, 308, 400, 401, 403, 404, 429, 500} {
|
||||
body := &trackedReader{Reader: strings.NewReader("PRIVATE SOURCE OR INTERNAL DIAGNOSTICS")}
|
||||
k := Kroki{Endpoint: "https://private-renderer.example", Client: clientFixture(func(*http.Request) (*http.Response, error) { return &http.Response{StatusCode: code, Body: body}, nil })}
|
||||
b, err := k.Render(context.Background(), "mermaid", "PRIVATE SOURCE")
|
||||
if !errors.Is(err, ErrProviderFailed) || b != nil || !body.closed {
|
||||
t.Fatal(code, err, body.closed)
|
||||
}
|
||||
}
|
||||
for _, mode := range []string{"network", "nil-response", "nil-body", "read-error"} {
|
||||
k := Kroki{Endpoint: "https://private-renderer.example", Client: clientFixture(func(*http.Request) (*http.Response, error) {
|
||||
switch mode {
|
||||
case "network":
|
||||
return nil, errors.New("https://private-renderer.example: secret")
|
||||
case "nil-response":
|
||||
return nil, nil
|
||||
case "nil-body":
|
||||
return &http.Response{StatusCode: 200}, nil
|
||||
default:
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(errorReader{})}, nil
|
||||
}
|
||||
})}
|
||||
b, err := k.Render(context.Background(), "mermaid", "PRIVATE SOURCE")
|
||||
if b != nil || err == nil || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "private-renderer") {
|
||||
t.Fatal(mode, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type errorReader struct{}
|
||||
|
||||
func (errorReader) Read([]byte) (int, error) { return 0, errors.New("secret body read failure") }
|
||||
|
||||
func TestKrokiCancellationDuringSendAndRead(t *testing.T) {
|
||||
for _, duringRead := range []bool{false, true} {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
body := &trackedReader{Reader: strings.NewReader("<svg/>")}
|
||||
k := Kroki{Endpoint: "https://renderer.example", Client: clientFixture(func(*http.Request) (*http.Response, error) {
|
||||
cancel()
|
||||
if duringRead {
|
||||
return &http.Response{StatusCode: 200, Body: body}, nil
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Body: body}, errors.New("cancelled network")
|
||||
})}
|
||||
b, err := k.Render(ctx, "mermaid", "source")
|
||||
cancel()
|
||||
if !errors.Is(err, context.Canceled) || b != nil || !body.closed {
|
||||
t.Fatal(duringRead, err, body.closed)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package mestionora
|
||||
|
||||
import (
|
||||
"go/parser"
|
||||
"go/token"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestComponentBoundary(t *testing.T) {
|
||||
if Component != "mestionora" {
|
||||
t.Fatal("component identity changed")
|
||||
}
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(file, "_test.go") {
|
||||
continue
|
||||
}
|
||||
ast, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, spec := range ast.Imports {
|
||||
path, err := strconv.Unquote(spec.Path.Value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, forbidden := range []string{"pageswiki/internal", "net", "os"} {
|
||||
if path == forbidden || strings.HasPrefix(path, forbidden+"/") {
|
||||
t.Errorf("%s imports %s: search must not own HTTP, filesystem payloads or application policy", file, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, exists := reflect.TypeFor[*SQLite]().MethodByName("SearchPathsInDomain"); exists {
|
||||
t.Fatal("implicit allow-all belongs only in the legacy trusted-caller facade")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package mestionora
|
||||
|
||||
import (
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A display projection only: names, boundaries and manual titles remain stored
|
||||
// unchanged. Legacy generated Spots have no nested Spot semantics.
|
||||
func IsUnclassifiedCitySpot(name, boundary string) bool {
|
||||
return strings.HasSuffix(name, "-undefined") || strings.HasSuffix(boundary, "/_undefined")
|
||||
}
|
||||
|
||||
func CitySpotDisplayTitle(name, title, boundary, parentTitle string) string {
|
||||
if !IsUnclassifiedCitySpot(name, boundary) {
|
||||
if title != "" {
|
||||
return title
|
||||
}
|
||||
return name
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(title)) {
|
||||
case "", "undefined", "未定義", "未分類のpage", "unclassified pages", strings.ToLower(name):
|
||||
if parentTitle != "" {
|
||||
return parentTitle
|
||||
}
|
||||
if parent := path.Base(path.Dir(boundary)); parent != "/" && parent != "." {
|
||||
return parent
|
||||
}
|
||||
return "Spot"
|
||||
default:
|
||||
return title // A manual display title takes precedence.
|
||||
}
|
||||
}
|
||||
|
||||
func (r CitySearchResult) DisplayTitle() string {
|
||||
if r.Kind == "spot" {
|
||||
return CitySpotDisplayTitle(r.Name, r.Title, r.PathPrefix, r.StreetTitle)
|
||||
}
|
||||
if r.Title != "" {
|
||||
return r.Title
|
||||
}
|
||||
return r.Name
|
||||
}
|
||||
|
||||
func (r CitySearchResult) ContentPath() string {
|
||||
if r.NavigationPath != "" {
|
||||
return r.NavigationPath
|
||||
}
|
||||
return r.PathPrefix
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package mestionora
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCityContentExistenceUsesPathIndex(t *testing.T) {
|
||||
database := newSearchTestDB(t)
|
||||
for _, kind := range []string{"quartier", "street", "spot"} {
|
||||
rows, err := database.Query("EXPLAIN QUERY PLAN "+citySearchSQL(kind, ""), sql.Named("domain", "d"), sql.Named("scope", "/"), sql.Named("prefix", "/"), sql.Named("upper", "0"), sql.Named("query", "needle"), sql.Named("limit", 1000))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
indexed := false
|
||||
for rows.Next() {
|
||||
var id, parent, unused int
|
||||
var detail string
|
||||
if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(detail, "SEARCH cp USING") {
|
||||
indexed = true
|
||||
}
|
||||
if strings.Contains(detail, "SCAN cp") {
|
||||
t.Fatalf("unbounded Path lookup: %s", detail)
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows.Close()
|
||||
if !indexed {
|
||||
t.Fatalf("no indexed portal lookup for %s", kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package mestionora
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
CitySearchCandidateLimit = 1000 // Per locality kind, before authorization.
|
||||
CitySearchResultLimit = 30
|
||||
citySearchTimeout = 2 * time.Second
|
||||
)
|
||||
|
||||
// CitySearchResult describes a locality, not its contained Pages. Description
|
||||
// is a bounded plain-text excerpt around the match and is never trusted HTML.
|
||||
type CitySearchResult struct {
|
||||
UUID, Kind, Name, Title, Description, PathPrefix string
|
||||
QuartierTitle, StreetTitle, QuartierName string
|
||||
CreatedAtMS, UpdatedAtMS int64
|
||||
NameMatch, PathMatch, DescriptionMatch bool
|
||||
NavigationPath string
|
||||
HasPage bool
|
||||
}
|
||||
|
||||
type citySearchCandidate struct {
|
||||
CitySearchResult
|
||||
quartierPath, streetPath string
|
||||
}
|
||||
|
||||
// SearchCityInDomain searches locality metadata only. It does not construct a
|
||||
// CityMap, expand descendants, read Page bodies, or count hidden localities.
|
||||
// Scope selects a locality's own boundary, not an ancestor of the scope. Every
|
||||
// boundary in its parent chain must be readable before the result is exposed.
|
||||
func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) (found []CitySearchResult, searchErr error) {
|
||||
if err := options.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
query = strings.TrimSpace(query)
|
||||
if len(query) > 512 || len(strings.Fields(query)) > 16 {
|
||||
return nil, errors.New("search query is too long")
|
||||
}
|
||||
// File filters are intentionally not applied to locality metadata: a Spot
|
||||
// containing a PDF is not itself a PDF and must not claim to match one.
|
||||
if allowed == nil || options.FileType != "" || options.Extension != "" || (query == "" && !options.HasFilters()) {
|
||||
return nil, nil
|
||||
}
|
||||
if limit <= 0 || limit > CitySearchResultLimit {
|
||||
limit = CitySearchResultLimit
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(parent, citySearchTimeout)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
if searchErr != nil && ctx.Err() != nil {
|
||||
searchErr = ctx.Err()
|
||||
}
|
||||
}()
|
||||
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
scope = normalizePath(scope)
|
||||
prefix, upper := strings.TrimRight(scope, "/")+"/", strings.TrimRight(scope, "/")+"0"
|
||||
args := []any{
|
||||
sql.Named("domain", domainUUID), sql.Named("scope", scope),
|
||||
sql.Named("prefix", prefix), sql.Named("upper", upper),
|
||||
sql.Named("query", query), sql.Named("limit", CitySearchCandidateLimit),
|
||||
}
|
||||
dateColumn := "n.updated_at_ms"
|
||||
if options.DateField == "created" {
|
||||
dateColumn = "n.created_at_ms"
|
||||
}
|
||||
dateWhere := ""
|
||||
if options.FromMS != nil {
|
||||
dateWhere += " AND " + dateColumn + ">=:from_ms"
|
||||
args = append(args, sql.Named("from_ms", *options.FromMS))
|
||||
}
|
||||
if options.BeforeMS != nil {
|
||||
dateWhere += " AND " + dateColumn + "<:before_ms"
|
||||
args = append(args, sql.Named("before_ms", *options.BeforeMS))
|
||||
}
|
||||
candidates := make([]citySearchCandidate, 0)
|
||||
for _, kind := range []string{"quartier", "street", "spot"} {
|
||||
rows, err := tx.QueryContext(ctx, citySearchSQL(kind, dateWhere), args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var candidate citySearchCandidate
|
||||
candidate.Kind = kind
|
||||
if err := rows.Scan(&candidate.UUID, &candidate.Name, &candidate.Title, &candidate.Description,
|
||||
&candidate.PathPrefix, &candidate.CreatedAtMS, &candidate.UpdatedAtMS,
|
||||
&candidate.NameMatch, &candidate.PathMatch, &candidate.DescriptionMatch,
|
||||
&candidate.QuartierTitle, &candidate.StreetTitle, &candidate.quartierPath, &candidate.streetPath, &candidate.QuartierName,
|
||||
&candidate.NavigationPath, &candidate.HasPage); err != nil {
|
||||
rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
candidates = append(candidates, candidate)
|
||||
}
|
||||
err = rows.Err()
|
||||
closeErr := rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return nil, closeErr
|
||||
}
|
||||
}
|
||||
// Release the sole read connection before calling authorization, which may
|
||||
// itself need a database connection. HTTP normally passes its cached policy.
|
||||
if err := tx.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) {
|
||||
return nil, err
|
||||
}
|
||||
sort.SliceStable(candidates, func(i, j int) bool {
|
||||
a, b := candidates[i], candidates[j]
|
||||
if a.Kind != b.Kind {
|
||||
return citySearchKindOrder(a.Kind) < citySearchKindOrder(b.Kind)
|
||||
}
|
||||
if a.NameMatch != b.NameMatch {
|
||||
return a.NameMatch
|
||||
}
|
||||
if a.PathMatch != b.PathMatch {
|
||||
return a.PathMatch
|
||||
}
|
||||
if a.PathPrefix != b.PathPrefix {
|
||||
return a.PathPrefix < b.PathPrefix
|
||||
}
|
||||
return a.UUID < b.UUID
|
||||
})
|
||||
readable := make(map[string]bool)
|
||||
canRead := func(path string) bool {
|
||||
if value, exists := readable[path]; exists {
|
||||
return value
|
||||
}
|
||||
value := allowed(path)
|
||||
readable[path] = value
|
||||
return value
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !canRead(candidate.PathPrefix) || (candidate.quartierPath != "" && !canRead(candidate.quartierPath)) || (candidate.streetPath != "" && !canRead(candidate.streetPath)) {
|
||||
continue
|
||||
}
|
||||
found = append(found, candidate.CitySearchResult)
|
||||
if len(found) == limit {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func citySearchKindOrder(kind string) int {
|
||||
switch kind {
|
||||
case "quartier":
|
||||
return 0
|
||||
case "street":
|
||||
return 1
|
||||
default:
|
||||
return 2
|
||||
}
|
||||
}
|
||||
|
||||
// All interpolated SQL fragments are package-owned constants. User input is
|
||||
// bound, so %, _, quotes and backslashes are literal substring characters.
|
||||
func citySearchSQL(kind, dateWhere string) string {
|
||||
from, description := "zones n", "n.description"
|
||||
navigationPath := "n.path_prefix"
|
||||
parentColumns := "'','','','',''"
|
||||
where := "n.kind='quartier'"
|
||||
switch kind {
|
||||
case "street":
|
||||
from += ` JOIN zones q ON q.uuid=n.parent_uuid AND q.domain_uuid=n.domain_uuid AND q.kind='quartier' AND q.state!='archived'`
|
||||
parentColumns = "substr(COALESCE(NULLIF(q.title,''),q.name),1,256),'',q.path_prefix,'',q.name"
|
||||
where = "n.kind='street' AND " + citySearchAbsolutePathSQL("q.path_prefix")
|
||||
case "spot":
|
||||
navigationPath = `CASE WHEN substr(n.path_prefix,-11)='/_undefined' THEN st.path_prefix ELSE n.path_prefix END`
|
||||
from = `spots n JOIN street_spots ss ON ss.spot_uuid=n.uuid
|
||||
JOIN zones st ON st.uuid=ss.street_uuid AND st.domain_uuid=n.domain_uuid AND st.kind='street' AND st.state!='archived'
|
||||
JOIN zones q ON q.uuid=st.parent_uuid AND q.domain_uuid=st.domain_uuid AND q.kind='quartier' AND q.state!='archived'`
|
||||
description = "n.summary"
|
||||
parentColumns = "substr(COALESCE(NULLIF(q.title,''),q.name),1,256),substr(COALESCE(NULLIF(st.title,''),st.name),1,256),q.path_prefix,st.path_prefix,q.name"
|
||||
where = citySearchAbsolutePathSQL("q.path_prefix") + " AND " + citySearchAbsolutePathSQL("st.path_prefix")
|
||||
}
|
||||
nameMatch := `(:query!='' AND (instr(lower(n.name),lower(:query))>0 OR instr(lower(n.title),lower(:query))>0))`
|
||||
pathMatch := `(:query!='' AND instr(lower(n.path_prefix),lower(:query))>0)`
|
||||
descriptionMatch := `(:query!='' AND instr(lower(` + description + `),lower(:query))>0)`
|
||||
return `SELECT n.uuid,substr(n.name,1,256),substr(n.title,1,256),
|
||||
substr(` + description + `,max(1,instr(lower(` + description + `),lower(:query))-160),512),
|
||||
n.path_prefix,n.created_at_ms,n.updated_at_ms,` + nameMatch + `,` + pathMatch + `,` + descriptionMatch + `,` + parentColumns + `,` + navigationPath + `,
|
||||
EXISTS(SELECT 1 FROM paths cp WHERE cp.domain_uuid=n.domain_uuid AND cp.path=(` + navigationPath + `))
|
||||
FROM ` + from + ` WHERE n.domain_uuid=:domain AND n.state!='archived' AND ` + where + `
|
||||
AND ` + citySearchAbsolutePathSQL("n.path_prefix") + `
|
||||
AND (n.path_prefix COLLATE BINARY=:scope OR (n.path_prefix COLLATE BINARY>=:prefix AND n.path_prefix COLLATE BINARY<:upper))
|
||||
AND (:query='' OR ` + nameMatch + ` OR ` + pathMatch + ` OR ` + descriptionMatch + `)` + dateWhere + `
|
||||
ORDER BY ` + nameMatch + ` DESC,` + pathMatch + ` DESC,n.path_prefix COLLATE BINARY,n.uuid LIMIT :limit`
|
||||
}
|
||||
|
||||
func citySearchAbsolutePathSQL(column string) string {
|
||||
// Keep authorization paths intact rather than truncating them. Malformed
|
||||
// legacy boundaries and impractically large metadata are not navigable hits.
|
||||
return `(substr(` + column + `,1,1)='/' AND length(` + column + `)<=4096 AND instr(` + column + `,char(0))=0)`
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package mestionora
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
func newSearchTestDB(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
database, err := db.Open(t.TempDir() + "/search.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { database.Close() })
|
||||
initSearchFixture(t, database)
|
||||
return database
|
||||
}
|
||||
|
||||
// Only the application columns/indexes consumed by search, not application
|
||||
// bootstrap, auth keys, job recovery or external calendar initialization.
|
||||
func initSearchFixture(t *testing.T, database *sql.DB) {
|
||||
t.Helper()
|
||||
_, err := database.Exec(`
|
||||
CREATE TABLE objects(uuid TEXT PRIMARY KEY, created_at INTEGER);
|
||||
CREATE TABLE revisions(uuid TEXT PRIMARY KEY,object_uuid TEXT,filename TEXT,body TEXT,content_type TEXT,document_hash TEXT,created_at_ms INTEGER,created_at INTEGER);
|
||||
CREATE TABLE paths(domain_uuid TEXT NOT NULL,path TEXT NOT NULL,object_uuid TEXT,PRIMARY KEY(domain_uuid,path));
|
||||
CREATE INDEX idx_paths_object_domain_page ON paths(object_uuid,domain_uuid,path);
|
||||
CREATE TABLE zones(uuid TEXT PRIMARY KEY,domain_uuid TEXT,kind TEXT,parent_uuid TEXT,name TEXT,title TEXT,description TEXT,path_prefix TEXT,state TEXT,created_at_ms INTEGER,updated_at_ms INTEGER);
|
||||
CREATE TABLE spots(uuid TEXT PRIMARY KEY,domain_uuid TEXT,name TEXT,title TEXT,summary TEXT,path_prefix TEXT,state TEXT,created_at_ms INTEGER,updated_at_ms INTEGER);
|
||||
CREATE TABLE street_spots(street_uuid TEXT,spot_uuid TEXT);
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := NewSQLite(database).EnsureSearchIndexSchema(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 306 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user