Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbcb8a24b4 | ||
|
|
367bfa3a2a | ||
|
|
aaa0e457bf | ||
|
|
4a863fe63c | ||
|
|
1fd2de4c6b | ||
|
|
fdf6dffc84 | ||
|
|
37c1443219 | ||
|
|
6a67fd9afe | ||
|
|
0c7897d695 | ||
|
|
46c185d928 | ||
|
|
940a9137b4 | ||
|
|
0ba1dcfef0 | ||
|
|
96065d1e89 | ||
|
|
2cbaa9342d | ||
|
|
38b0fe2a94 | ||
|
|
667776e43f | ||
|
|
02edb51b8a | ||
|
|
b61fbc38a4 | ||
|
|
02fb77f72b | ||
|
|
09afb438c9 | ||
|
|
2d6ceac0d7 | ||
|
|
bd80ff6a0c | ||
|
|
b90aef79d0 | ||
|
|
84d52390f9 |
No files matched your search
@@ -35,8 +35,8 @@ jobs:
|
||||
[worker.oci]
|
||||
max-parallelism = 2
|
||||
|
||||
- name: Test release tooling and wallpaper palette
|
||||
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs
|
||||
- name: Test release tooling and browser logic
|
||||
run: node --test tools/ci/release-images.test.mjs static/js/home-palette-core.test.cjs static/js/csv-core.test.cjs
|
||||
|
||||
- name: Test
|
||||
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
@@ -47,6 +47,10 @@ jobs:
|
||||
platforms: linux/amd64
|
||||
push: false
|
||||
|
||||
- name: Test native PostgreSQL 17 before publishing
|
||||
shell: bash
|
||||
run: bash tools/ci/test-postgres.sh
|
||||
|
||||
- name: Log in to registry
|
||||
uses: https://github.com/docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
|
||||
with:
|
||||
@@ -91,13 +95,25 @@ jobs:
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
|
||||
- name: Build Gecko relay
|
||||
uses: https://github.com/docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.gecko-relay
|
||||
platforms: linux/amd64
|
||||
load: true
|
||||
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_OWNER }}/pageswiki-gecko-relay:${{ env.IMAGE_TAG }}
|
||||
labels: |
|
||||
org.opencontainers.image.revision=${{ github.sha }}
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
|
||||
# Publish only after all builds succeed. Use the host daemon for registry
|
||||
# access; BuildKit does not inherit the runner's /etc/hosts entries.
|
||||
- name: Push images
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer; do
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer pageswiki-gecko-relay; do
|
||||
docker push "$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
||||
done
|
||||
|
||||
@@ -105,7 +121,7 @@ jobs:
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer; do
|
||||
for image in pageswiki-app pageswiki-adaptor-gateway pageswiki-excalidraw-viewer pageswiki-gecko-relay; do
|
||||
ref="$REGISTRY/$IMAGE_OWNER/$image:$IMAGE_TAG"
|
||||
if docker image inspect "$ref" >/dev/null 2>&1; then
|
||||
docker image rm "$ref" || echo "Could not remove local CI tag: $ref" >&2
|
||||
|
||||
@@ -5,6 +5,7 @@ data/*
|
||||
!data/test_cli_dr.py
|
||||
!data/pageswiki-remote
|
||||
/data2/
|
||||
/docs/local/
|
||||
/.codex/
|
||||
/.agents/
|
||||
/.env
|
||||
@@ -19,6 +20,7 @@ data/*
|
||||
.tmp/
|
||||
.deployment-backups/
|
||||
*.sh
|
||||
!tools/ci/test-postgres.sh
|
||||
assets/editor/node_modules/
|
||||
assets/city-generator/node_modules/
|
||||
assets/excalidraw-viewer/node_modules/
|
||||
|
||||
@@ -342,6 +342,12 @@ window.PagesWikiEditor = {
|
||||
}),
|
||||
];
|
||||
|
||||
if (options.preserveLineEndings) {
|
||||
// Split only at LF, keeping any CR bytes in the document. This
|
||||
// preserves mixed LF/CRLF CSV sources instead of rewriting them.
|
||||
extensions.push(EditorState.lineSeparator.of("\n"));
|
||||
}
|
||||
|
||||
if (keymapName === "vim") {
|
||||
installVimCommands();
|
||||
extensions.push(vim());
|
||||
|
||||
@@ -66,10 +66,15 @@ func main() {
|
||||
if err := geckorelay.VerifyAssets(assets); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
distribution, err := geckorelay.VerifyDistribution(assets)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
relay, err := geckorelay.New(secret, assets)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
relay.Distribution = distribution
|
||||
s := &http.Server{Addr: addr, Handler: relay, ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 16 << 10}
|
||||
log.Printf("Gecko relay listening; authenticated TCP 80/443 only")
|
||||
log.Fatal(s.ListenAndServe())
|
||||
|
||||
@@ -16,6 +16,13 @@ import (
|
||||
// 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 {
|
||||
backend, err := configuredDatabaseBackend()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if backend != "sqlite" {
|
||||
return errors.New("DR commands require the SQLite backend; use PostgreSQL backup/restore for native instances")
|
||||
}
|
||||
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)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"net/url"
|
||||
@@ -14,18 +15,30 @@ import (
|
||||
|
||||
const managedCampusReconcileInterval = 5 * time.Second
|
||||
|
||||
func startManagedCampusReconciler(dataDir string, st *store.Store) {
|
||||
func startManagedCampusReconciler(ctx context.Context, dataDir string, st *store.Store) <-chan struct{} {
|
||||
done := make(chan struct{})
|
||||
instanceFQDN := strings.TrimSpace(os.Getenv("PAGESWIKI_INSTANCE_FQDN"))
|
||||
if instanceFQDN == "" {
|
||||
return
|
||||
if instanceFQDN == "" || st.ReadOnly || st.BackgroundJobsDisabled {
|
||||
close(done)
|
||||
return done
|
||||
}
|
||||
go func() {
|
||||
defer close(done)
|
||||
ticker := time.NewTicker(managedCampusReconcileInterval)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
reconcileManagedCampuses(dataDir, st, instanceFQDN)
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
reconcileManagedCampusesContext(ctx, dataDir, st, instanceFQDN)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return done
|
||||
}
|
||||
|
||||
func reconcileManagedCampuses(
|
||||
@@ -33,12 +46,19 @@ func reconcileManagedCampuses(
|
||||
st *store.Store,
|
||||
instanceFQDN string,
|
||||
) {
|
||||
reconcileManagedCampusesContext(context.Background(), dataDir, st, instanceFQDN)
|
||||
}
|
||||
|
||||
func reconcileManagedCampusesContext(ctx context.Context, dataDir string, st *store.Store, instanceFQDN string) {
|
||||
campuses, err := st.ListCampuses()
|
||||
if err != nil {
|
||||
log.Printf("managed Campus reconciliation: %v", err)
|
||||
return
|
||||
}
|
||||
for _, campus := range campuses {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if campus.AuthorityMode != "managed" || !campus.Enabled {
|
||||
continue
|
||||
}
|
||||
|
||||
+41
-56
@@ -1,18 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/dr"
|
||||
"pageswiki/internal/server"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "mysql-identity-schema" {
|
||||
if err := runMySQLSchemaCommand(os.Args[2:], os.Stdout, "identity"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "mysql-namespace-schema" {
|
||||
if err := runMySQLComponentSchema(os.Args[2:], os.Stdout, true); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "mysql-ml-schema" {
|
||||
if err := runMySQLMLSchema(os.Args[2:], os.Stdout); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "migrate-postgres" {
|
||||
if err := runPostgreSQLMigration(os.Args[2:], os.Stdout); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "schema" {
|
||||
if err := runSchema(os.Args[2:], os.Stdout); err != nil {
|
||||
log.Print(err)
|
||||
@@ -29,6 +55,8 @@ func main() {
|
||||
}
|
||||
return
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
enrollment, err := parseExternalCampusEnrollment(os.Args[1:])
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -64,6 +92,13 @@ func main() {
|
||||
if err = dr.RequireRole(node, os.Getenv("PAGESWIKI_DR_EXPECT_ROLE")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
backend, err := configuredDatabaseBackend()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if backend == "postgresql" && node != nil {
|
||||
log.Fatal("PostgreSQL currently supports standalone instances only; DR startup refused")
|
||||
}
|
||||
if node != nil && node.Role == "standby" {
|
||||
if len(os.Args) > 1 {
|
||||
log.Fatal("standby does not accept enrollment/startup mutation flags")
|
||||
@@ -79,73 +114,23 @@ func main() {
|
||||
}
|
||||
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 {
|
||||
if err := serveInstance(ctx, dataDir, st, ":3000"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
dbPath :=
|
||||
filepath.Join(
|
||||
dataDir,
|
||||
"pages.db",
|
||||
)
|
||||
|
||||
log.Printf(
|
||||
"pages.db = %s",
|
||||
dbPath,
|
||||
)
|
||||
|
||||
database, err :=
|
||||
db.Open(dbPath)
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
err = db.Migrate(database)
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
documentRoot, err :=
|
||||
store.MigrateLegacyDocumentRoot(
|
||||
dataDir,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
st :=
|
||||
store.NewWithDocumentRoot(
|
||||
database,
|
||||
documentRoot,
|
||||
)
|
||||
|
||||
err = st.EnsureConfigTable()
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
err = st.EnsurePathLinkColumns()
|
||||
|
||||
log.Printf("database backend = %s", backend)
|
||||
database, st, err := openApplicationStore(ctx, dataDir)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := enrollExternalCampus(dataDir, st, enrollment); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
st.BackgroundJobsDisabled = node != nil && !node.WorkersEnabled
|
||||
if !st.BackgroundJobsDisabled {
|
||||
startManagedCampusReconciler(dataDir, st)
|
||||
}
|
||||
|
||||
srv := server.New(st)
|
||||
|
||||
err = srv.Run(":3000")
|
||||
err = serveInstance(ctx, dataDir, st, ":3000")
|
||||
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func runMySQLMLSchema(args []string, out io.Writer) error {
|
||||
return runMySQLComponentSchema(args, out, false)
|
||||
}
|
||||
|
||||
func runMySQLComponentSchema(args []string, out io.Writer, namespace bool) error {
|
||||
component := "ml"
|
||||
if namespace {
|
||||
component = "namespace"
|
||||
}
|
||||
return runMySQLSchemaCommand(args, out, component)
|
||||
}
|
||||
func runMySQLSchemaCommand(args []string, out io.Writer, component string) error {
|
||||
command, scope, label := "mysql-ml-schema", "ml-only", "ML component ONLY"
|
||||
if component == "namespace" {
|
||||
command, scope, label = "mysql-namespace-schema", "namespace-pilot", "Namespace pilot ONLY (includes shared config/ML schema; no Domain mutations or authentication)"
|
||||
} else if component == "identity" {
|
||||
command, scope, label = "mysql-identity-schema", "identity-pilot", "Identity/group persistence pilot ONLY; not a complete authentication server"
|
||||
} else if component != "ml" {
|
||||
return errors.New("unknown MySQL component")
|
||||
}
|
||||
usage := "pageswiki " + command + " {status|check|apply|resume} [--timeout 2m] [--allow-insecure]\nUses PAGESWIKI_MYSQL_DSN. " + label + "; does not make Pages serve from MySQL. status/check are read-only. apply refuses interrupted migrations; resume explicitly verifies and continues."
|
||||
if len(args) == 0 || args[0] == "--help" {
|
||||
_, e := fmt.Fprintln(out, usage)
|
||||
return e
|
||||
}
|
||||
mode := args[0]
|
||||
if mode != "status" && mode != "check" && mode != "apply" && mode != "resume" {
|
||||
return errors.New("invalid MySQL component schema action")
|
||||
}
|
||||
f := flag.NewFlagSet(command, flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
timeout := f.Duration("timeout", 2*time.Minute, "operation deadline")
|
||||
insecure := f.Bool("allow-insecure", false, "isolated disposable database tests only")
|
||||
if e := f.Parse(args[1:]); e != nil {
|
||||
if errors.Is(e, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if f.NArg() != 0 || *timeout <= 0 {
|
||||
return errors.New("invalid MySQL component schema arguments")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
database, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: os.Getenv("PAGESWIKI_MYSQL_DSN"), AllowInsecure: *insecure})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer database.Close()
|
||||
var repo interface {
|
||||
PrepareSchema(context.Context) error
|
||||
InspectSchema(context.Context) (db.MySQLMigrationStatus, error)
|
||||
ResumeSchema(context.Context) error
|
||||
} = store.NewMySQLMLRepository(database)
|
||||
if component == "namespace" {
|
||||
repo = store.NewMySQLNamespaceRepository(database)
|
||||
} else if component == "identity" {
|
||||
repo = store.NewMySQLIdentityRepository(database)
|
||||
}
|
||||
switch mode {
|
||||
case "apply":
|
||||
e = repo.PrepareSchema(ctx)
|
||||
case "resume":
|
||||
e = repo.ResumeSchema(ctx)
|
||||
}
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
status, e := repo.InspectSchema(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if e = json.NewEncoder(out).Encode(struct {
|
||||
Scope string `json:"scope"`
|
||||
db.MySQLMigrationStatus
|
||||
}{scope, status}); e != nil {
|
||||
return e
|
||||
}
|
||||
if mode == "check" && (status.Dirty || status.Pending > 0) {
|
||||
return errors.New("MySQL component schema is pending or interrupted")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
"github.com/google/uuid"
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
func TestMySQLMLSchemaArguments(t *testing.T) {
|
||||
t.Setenv("PAGESWIKI_MYSQL_DSN", "")
|
||||
for _, args := range [][]string{{"bad"}, {"apply", "--timeout", "0s"}, {"resume", "unexpected"}, {"status"}} {
|
||||
var out bytes.Buffer
|
||||
if runMySQLMLSchema(args, &out) == nil {
|
||||
t.Fatal("accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if e := runMySQLMLSchema([]string{"--help"}, &out); e != nil || !strings.Contains(out.String(), "ML component ONLY") {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMySQLMLSchemaCommand(t *testing.T) {
|
||||
for _, component := range []string{"ml", "namespace", "identity"} {
|
||||
t.Run(component, func(t *testing.T) { testMySQLSchemaCommand(t, component) })
|
||||
}
|
||||
}
|
||||
|
||||
func testMySQLSchemaCommand(t *testing.T, component string) {
|
||||
dsn := os.Getenv("PAGESWIKI_TEST_MYSQL_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("set disposable MySQL DSN")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
admin, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: dsn, AllowInsecure: true})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer admin.Close()
|
||||
name := "pages_ml_cmd_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
if _, e = admin.ExecContext(ctx, "CREATE DATABASE "+name+" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() {
|
||||
if _, e := admin.Exec("DROP DATABASE " + name); e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
}()
|
||||
c, e := mysql.ParseDSN(dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
c.DBName = name
|
||||
t.Setenv("PAGESWIKI_MYSQL_DSN", c.FormatDSN())
|
||||
var out bytes.Buffer
|
||||
run := func(action string) error {
|
||||
return runMySQLSchemaCommand([]string{action, "--allow-insecure"}, &out, component)
|
||||
}
|
||||
pending := `"pending":2`
|
||||
if component == "namespace" {
|
||||
pending = `"pending":3`
|
||||
} else if component == "identity" {
|
||||
pending = `"pending":5`
|
||||
}
|
||||
if e = run("status"); e != nil || !strings.Contains(out.String(), pending) {
|
||||
t.Fatal(out.String(), e)
|
||||
}
|
||||
var count int
|
||||
if e = admin.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=?`, name).Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("status wrote schema", count, e)
|
||||
}
|
||||
if e = run("check"); e == nil {
|
||||
t.Fatal("pending check succeeded")
|
||||
}
|
||||
if e = run("apply"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = run("check"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if component != "ml" {
|
||||
if e = admin.QueryRowContext(ctx, "SELECT COUNT(*) FROM "+name+".domains").Scan(&count); e != nil || count != 0 {
|
||||
t.Fatal("schema command created unauthorized Domain data", count, e)
|
||||
}
|
||||
}
|
||||
ledger, version := "machine-learning", 2
|
||||
if component == "namespace" {
|
||||
ledger, version = "store-namespaces", 1
|
||||
} else if component == "identity" {
|
||||
ledger, version = "store-auth-core", 2
|
||||
}
|
||||
if _, e = admin.ExecContext(ctx, "UPDATE "+name+".schema_mysql_migrations SET state='running',next_operation=1 WHERE component=? AND version=?", ledger, version); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = run("apply"); e == nil {
|
||||
t.Fatal("dirty apply succeeded")
|
||||
}
|
||||
if e = run("resume"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/dr"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func runPostgreSQLMigration(args []string, out io.Writer) error {
|
||||
f := flag.NewFlagSet("migrate-postgres", flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
defaultDir := os.Getenv("PAGESWIKI_DATA_DIR")
|
||||
if defaultDir == "" {
|
||||
defaultDir = "./data"
|
||||
}
|
||||
dir := f.String("data-dir", defaultDir, "stopped instance data directory; existing files are retained in place")
|
||||
apply := f.Bool("apply", false, "copy into an empty PostgreSQL schema after source preflight")
|
||||
insecure := f.Bool("allow-insecure", false, "allow unverified PostgreSQL TLS for isolated testing only")
|
||||
timeout := f.Duration("timeout", 30*time.Minute, "migration timeout")
|
||||
if err := f.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if f.NArg() != 0 || *timeout <= 0 {
|
||||
return errors.New("invalid migration arguments")
|
||||
}
|
||||
if info, err := os.Stat(*dir); err != nil || !info.IsDir() {
|
||||
return errors.New("existing data directory required")
|
||||
}
|
||||
lock, err := dr.Lock(*dir, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer lock.Close()
|
||||
if node, err := dr.Load(*dir); err != nil {
|
||||
return err
|
||||
} else if node != nil {
|
||||
return errors.New("PostgreSQL migration does not support a configured DR instance")
|
||||
}
|
||||
source, err := db.OpenReadOnly(filepath.Join(*dir, "pages.db"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer source.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
tables, err := store.InspectSQLiteApplicationImport(ctx, source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !*apply {
|
||||
return json.NewEncoder(out).Encode(map[string]any{"mode": "preflight", "tables": tables, "copied": false})
|
||||
}
|
||||
target, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: os.Getenv("PAGESWIKI_POSTGRES_DSN"), AllowInsecure: *insecure})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer target.Close()
|
||||
root := filepath.Join(*dir, "documents")
|
||||
if err = store.PreparePostgreSQLImport(ctx, target, root); err != nil {
|
||||
return err
|
||||
}
|
||||
report, err := store.ImportSQLiteApplication(ctx, source, target, root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(out).Encode(report)
|
||||
}
|
||||
|
||||
func configuredDatabaseBackend() (string, error) {
|
||||
b := strings.ToLower(strings.TrimSpace(os.Getenv("PAGESWIKI_DB_BACKEND")))
|
||||
switch b {
|
||||
case "", "sqlite":
|
||||
return "sqlite", nil
|
||||
case "postgresql":
|
||||
return b, nil
|
||||
default:
|
||||
return "", errors.New("PAGESWIKI_DB_BACKEND must be sqlite or postgresql")
|
||||
}
|
||||
}
|
||||
|
||||
func openApplicationStore(ctx context.Context, dataDir string) (database *sql.DB, st *store.Store, err error) {
|
||||
backend, err := configuredDatabaseBackend()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer func() {
|
||||
if err != nil && database != nil {
|
||||
database.Close()
|
||||
database = nil
|
||||
}
|
||||
}()
|
||||
if backend == "postgresql" {
|
||||
database, err = db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: os.Getenv("PAGESWIKI_POSTGRES_DSN")})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
root := filepath.Join(dataDir, "documents")
|
||||
if err = store.VerifyPostgreSQLImport(ctx, database, root); err != nil {
|
||||
return database, nil, err
|
||||
}
|
||||
st, err = store.NewPostgreSQLWithDocumentRoot(ctx, database, root)
|
||||
return database, st, err
|
||||
}
|
||||
database, err = db.Open(filepath.Join(dataDir, "pages.db"))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if err = db.Migrate(database); err != nil {
|
||||
return database, nil, err
|
||||
}
|
||||
root, err := store.MigrateLegacyDocumentRoot(dataDir)
|
||||
if err != nil {
|
||||
return database, nil, err
|
||||
}
|
||||
st = store.NewWithDocumentRoot(database, root)
|
||||
if err = st.EnsureConfigTable(); err != nil {
|
||||
return database, nil, err
|
||||
}
|
||||
err = st.EnsurePathLinkColumns()
|
||||
return database, st, err
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/google/uuid"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/dr"
|
||||
"pageswiki/internal/server"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestPostgreSQLMigrationAndTLSStartup(t *testing.T) {
|
||||
dsn := os.Getenv("PAGESWIKI_TEST_POSTGRES_TLS_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("set a disposable PostgreSQL verify-full DSN")
|
||||
}
|
||||
ctx := context.Background()
|
||||
admin, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: dsn})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := "pageswiki_cli_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
if _, err = admin.Exec(`CREATE SCHEMA "` + schema + `"`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = admin.Exec(`DROP SCHEMA "` + schema + `" CASCADE`); admin.Close() })
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("search_path", schema)
|
||||
u.RawQuery = q.Encode()
|
||||
t.Setenv("PAGESWIKI_POSTGRES_DSN", u.String())
|
||||
t.Setenv("PAGESWIKI_AUTH_KEY", "")
|
||||
dir := t.TempDir()
|
||||
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||
if err = s.EnsureConfigTable(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
domain, err := s.GetDefaultDomain()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
owner, err := s.BootstrapOwner(domain.UUID, "owner", "synthetic cli password", "Owner", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := s.CreateAuthSession(domain.UUID, owner.UUID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = database.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err = runPostgreSQLMigration([]string{"--data-dir", dir, "--apply"}, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PAGESWIKI_DB_BACKEND", "postgresql")
|
||||
t.Chdir("../..")
|
||||
for range 2 {
|
||||
database, native, err := openApplicationStore(ctx, dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, err := native.PrincipalForSession(domain.UUID, token); err != nil || got.UUID != owner.UUID {
|
||||
database.Close()
|
||||
t.Fatal("session lost", err)
|
||||
}
|
||||
srv, err := server.NewChecked(native)
|
||||
if err != nil {
|
||||
database.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
closeCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err = srv.Close(closeCtx)
|
||||
cancel()
|
||||
database.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQLMigrationPreflight(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
database, err := db.Open(filepath.Join(dir, "pages.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||
if err = s.EnsureConfigTable(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = database.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// No target is needed for the schema-only preflight.
|
||||
t.Setenv("PAGESWIKI_POSTGRES_DSN", "")
|
||||
var out bytes.Buffer
|
||||
if err = runPostgreSQLMigration([]string{"--data-dir", dir}, &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result struct {
|
||||
Mode string
|
||||
Copied bool
|
||||
Tables []string
|
||||
}
|
||||
if err = json.Unmarshal(out.Bytes(), &result); err != nil || result.Mode != "preflight" || result.Copied || len(result.Tables) < 130 {
|
||||
t.Fatal(result, err)
|
||||
}
|
||||
lock, err := dr.Lock(dir, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer lock.Close()
|
||||
if err = runPostgreSQLMigration([]string{"--data-dir", dir}, &out); err == nil {
|
||||
t.Fatal("active instance maintenance accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQLBackendRefusesFallback(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, backend := range []string{"unsupported", "postgresql"} {
|
||||
t.Setenv("PAGESWIKI_DB_BACKEND", backend)
|
||||
t.Setenv("PAGESWIKI_POSTGRES_DSN", "")
|
||||
if _, _, err := openApplicationStore(context.Background(), dir); err == nil {
|
||||
t.Fatal("invalid configuration accepted")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "pages.db")); !os.IsNotExist(err) {
|
||||
t.Fatal("SQLite fallback created")
|
||||
}
|
||||
if err := runSchema([]string{"status", "--data-dir", dir}, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("legacy inspection accepted")
|
||||
}
|
||||
if err := runDR([]string{"init", "--data-dir", dir}, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("legacy DR accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQLMigrationArguments(t *testing.T) {
|
||||
for _, args := range [][]string{{"--timeout", "0"}, {"unexpected"}, {"--data-dir", filepath.Join(t.TempDir(), "missing")}} {
|
||||
if err := runPostgreSQLMigration(args, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("invalid arguments accepted", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
+51
-2
@@ -12,19 +12,28 @@ import (
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/metadata"
|
||||
"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")
|
||||
var errPostgreSQLNotReady = errors.New("core-only inspection cannot certify application migration; use migrate-postgres; 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."
|
||||
backend, err := configuredDatabaseBackend()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if backend != "sqlite" {
|
||||
return errors.New("legacy schema inspection requires SQLite; PostgreSQL startup validates native migrations and import receipt")
|
||||
}
|
||||
const usage = "pageswiki schema {status|check|portability} [--db FILE | --data-dir DIR] [--json] [--timeout 30s]\nRead-only inspection; no migration is performed.\ncheck exits 2 for pending migrations, 1 for incompatible state, 0 when managed components are current.\nportability reports PostgreSQL migration blockers and exits 1 while full application support is incomplete."
|
||||
if len(args) == 0 || args[0] == "--help" {
|
||||
_, err := fmt.Fprintln(out, usage)
|
||||
return err
|
||||
}
|
||||
if args[0] != "status" && args[0] != "check" {
|
||||
if args[0] != "status" && args[0] != "check" && args[0] != "portability" {
|
||||
return errors.New(usage)
|
||||
}
|
||||
f := flag.NewFlagSet("schema "+args[0], flag.ContinueOnError)
|
||||
@@ -65,6 +74,46 @@ func runSchema(args []string, out io.Writer) error {
|
||||
defer database.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), *timeout)
|
||||
defer cancel()
|
||||
if args[0] == "portability" {
|
||||
repository, err := metadata.New(database, metadata.SQLite)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
report, err := repository.InspectPortability(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if *jsonOutput {
|
||||
encoder := json.NewEncoder(out)
|
||||
encoder.SetIndent("", " ")
|
||||
if err := encoder.Encode(report); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if _, err := fmt.Fprintf(out, "PostgreSQL application ready: %t\nPortable core rehearsal compatible: %t\nScope: %s\n", report.ApplicationReady, report.CoreCompatible, report.Scope); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, table := range report.Tables {
|
||||
if _, err := fmt.Fprintf(out, "%-28s %-20s %s\n", table.Name, table.Component, table.State); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, blocker := range report.Blockers {
|
||||
if _, err := fmt.Fprintln(out, "blocked:", blocker); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !report.ApplicationReady {
|
||||
if _, err := fmt.Fprintln(out, "This legacy diagnostic covers core rehearsal only. Use migrate-postgres for full application preflight and transfer."); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if !report.ApplicationReady {
|
||||
return errPostgreSQLNotReady
|
||||
}
|
||||
return nil
|
||||
}
|
||||
report, err := store.InspectSchema(ctx, database)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -9,9 +9,60 @@ import (
|
||||
"testing"
|
||||
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/metadata"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
func TestPortabilityCommandIsReadOnlyAndNeverClaimsApplicationReady(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.Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := store.NewWithDocumentRoot(database, filepath.Join(dir, "documents"))
|
||||
if _, err := st.CreatePageAtPath("/preserved"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := database.Exec(`CREATE TABLE private_extension_data(secret TEXT); INSERT INTO private_extension_data VALUES ('DO_NOT_PRINT_PRIVATE_VALUE')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out bytes.Buffer
|
||||
if err := runSchema([]string{"portability", "--db", filepath.Join(dir, "pages.db"), "--json"}, &out); !errors.Is(err, errPostgreSQLNotReady) {
|
||||
t.Fatal("unsafe readiness result", err)
|
||||
}
|
||||
var report metadata.PortabilityReport
|
||||
if err := json.Unmarshal(out.Bytes(), &report); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if report.ApplicationReady || report.CoreCompatible || len(report.Blockers) == 0 {
|
||||
t.Fatal("legacy application marked portable", report)
|
||||
}
|
||||
if bytes.Contains(out.Bytes(), []byte("DO_NOT_PRINT_PRIVATE_VALUE")) {
|
||||
t.Fatal("row values leaked")
|
||||
}
|
||||
if _, err := st.ResolvePath("/preserved"); err != nil {
|
||||
t.Fatal("inspection changed existing data", err)
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRow(`SELECT count(*) FROM schema_migration_steps WHERE component='core-metadata'`).Scan(&count); err != nil || count != 0 {
|
||||
t.Fatal("inspection migrated database", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortabilityCommandMissingDatabaseDoesNotCreateFiles(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "not-created")
|
||||
if err := runSchema([]string{"portability", "--data-dir", dir}, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("nonexistent DB accepted")
|
||||
}
|
||||
if _, err := os.Stat(dir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("directory created", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchemaCommandMissingDatabaseDoesNotInitialize(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "missing")
|
||||
var out bytes.Buffer
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"pageswiki/internal/server"
|
||||
"pageswiki/internal/store"
|
||||
)
|
||||
|
||||
// Let an in-flight federation reconciliation finish before releasing the
|
||||
// event-worker owner. Each remote request retains its existing network timeout;
|
||||
// cancellation prevents starting another campus or reconciliation pass.
|
||||
func serveInstance(ctx context.Context, dataDir string, st *store.Store, addr string) error {
|
||||
srv, err := server.NewChecked(st)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reconcileCtx, stopReconciler := context.WithCancel(ctx)
|
||||
reconcilerDone := startManagedCampusReconciler(reconcileCtx, dataDir, st)
|
||||
serveCtx, stopServer := context.WithCancel(context.Background())
|
||||
finished := make(chan struct{})
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
<-reconcilerDone
|
||||
stopServer()
|
||||
case <-finished:
|
||||
}
|
||||
}()
|
||||
err = srv.RunContext(serveCtx, addr)
|
||||
stopReconciler()
|
||||
<-reconcilerDone
|
||||
close(finished)
|
||||
stopServer()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"pageswiki/internal/db"
|
||||
"pageswiki/internal/store"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestServeInstanceCancelled(t *testing.T) {
|
||||
t.Chdir("../..")
|
||||
t.Setenv("PAGESWIKI_INSTANCE_FQDN", "")
|
||||
root := t.TempDir()
|
||||
database, err := db.Open(root + "/pages.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err = db.Migrate(database); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := store.NewWithDocumentRoot(database, root+"/documents")
|
||||
if err = st.EnsureConfigTable(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st.BackgroundJobsDisabled = true
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err = serveInstance(ctx, root, st, "127.0.0.1:0"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = database.Ping(); err != nil {
|
||||
t.Fatal("server closed caller-owned DB", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagedReconcilerCancellationBeforeFirstPass(t *testing.T) {
|
||||
t.Setenv("PAGESWIKI_INSTANCE_FQDN", "synthetic.invalid")
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
// No DB: cancellation must finish without attempting a repository read or
|
||||
// accessing an external campus. This test does not make a network request.
|
||||
done := startManagedCampusReconciler(ctx, t.TempDir(), &store.Store{})
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("reconciler did not stop")
|
||||
}
|
||||
}
|
||||
@@ -312,6 +312,9 @@ class PagesWikiCLI:
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
backend = os.environ.get("PAGESWIKI_DB_BACKEND", "sqlite").strip().lower() or "sqlite"
|
||||
if backend != "sqlite":
|
||||
raise CLIError("Local data CLI requires SQLite; use the HTTP pages-cli for PostgreSQL")
|
||||
script_dir = Path(__file__).resolve().parent
|
||||
self.data_dir = Path(
|
||||
os.environ.get("PAGESWIKI_DATA_DIR", script_dir)
|
||||
|
||||
@@ -10,6 +10,11 @@ from pageswiki_cli_test import pageswiki_cli
|
||||
|
||||
|
||||
class DRGuardTest(unittest.TestCase):
|
||||
def test_postgresql_rejected_before_database_open(self):
|
||||
with patch.dict(os.environ, {"PAGESWIKI_DB_BACKEND": "postgresql"}):
|
||||
with self.assertRaisesRegex(pageswiki_cli.CLIError, "HTTP pages-cli"):
|
||||
pageswiki_cli.PagesWikiCLI()
|
||||
|
||||
def test_standby_rejected_before_database_open(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# 2026年11月・じさばかん展示環境
|
||||
|
||||
展示時の構成と合成データツールを保存する。汎用本番デプロイのテンプレートではない。
|
||||
利用者から展示成功の報告あり。2026-11-30の整理では実クラスタへ接続していない。
|
||||
|
||||
## ファイルの役割
|
||||
|
||||
| ファイル | 用途・注意 |
|
||||
| --- | --- |
|
||||
| `postgres.yaml` | PostgreSQL、専用ディレクトリ初期化、Service、NetworkPolicy。初期化だけroot、常駐は非root |
|
||||
| `bootstrap.yaml` | **新規展示DB向け、一度限り**。emptyDirのSQLiteからPostgreSQLへ初期import。GitOpsの継続同期へ入れない |
|
||||
| `app.yaml` | bootstrap成功後のPages本体とService。1 replica、Recreate、固定digest |
|
||||
| `storage-check.yaml.example` | 非rootで専用一時ディレクトリを使う保存先の検査 |
|
||||
| `root-storage-check.yaml.example` | rootで専用一時ディレクトリを準備し、非rootで検査する別案。運営の許可が必要 |
|
||||
| `pageswiki.yaml.example` | 初期のSQLite向け一般ひな形。**展示NFSには適用しない** |
|
||||
| `demo/` | 架空データのカタログ、生成・投入手順 |
|
||||
|
||||
`kubectl apply -f deploy/kubernetes/exhibition/` のような一括適用は禁止。
|
||||
namespace、PVC、Secret、公開Gateway/TLSは、このディレクトリだけでは準備されない。
|
||||
Secretの値、秘密鍵、kubeconfig、投入済みDBはGitへ含めない。初期化Jobの削除・再実行を更新手段にしない。
|
||||
|
||||
最後に指定された公開名は `pages.anya.jisaba.sh`、Serviceは `pageswiki:80`。
|
||||
公開TLS終端はNOC側。古いFQDNとCloudflare案は
|
||||
[当時の運用記録](../../../docs/operations/exhibition-kubernetes-dns-tls.md)に経緯として残す。
|
||||
固定digest・UID・PVC subPath・Secret名・証明書期限は展示当時の値であり、再利用時に照合が必要。
|
||||
|
||||
## ローカル検証
|
||||
|
||||
```sh
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tools/exhibition-demo -v
|
||||
go test ./tools/exhibition-demo
|
||||
```
|
||||
|
||||
合成データだけでZIP/Markdown/CSV/iCalendar/vCardを検証する。クラスタ、DB、外部カレンダーへ接続しない。
|
||||
YAMLの構文検査だけではRBAC、admission、NFS永続性、TLS、公開経路の成立は保証しない。
|
||||
@@ -0,0 +1,68 @@
|
||||
# Apply only after the one-time bootstrap Job has completed successfully.
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata: {name: pageswiki}
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector:
|
||||
matchLabels: {app: pageswiki}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: pageswiki, pageswiki-db-client: 'true'}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 90
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
runAsGroup: 10001
|
||||
seccompProfile: {type: RuntimeDefault}
|
||||
affinity:
|
||||
podAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchLabels: {app: pageswiki-postgres}
|
||||
topologyKey: kubernetes.io/hostname
|
||||
containers:
|
||||
- name: pageswiki
|
||||
image: git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9
|
||||
env:
|
||||
- {name: PAGESWIKI_DATA_DIR, value: /data}
|
||||
- {name: PAGESWIKI_DB_BACKEND, value: postgresql}
|
||||
- name: PAGESWIKI_AUTH_KEY
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: auth-key}}
|
||||
- name: PAGESWIKI_POSTGRES_DSN
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: postgres-dsn}}
|
||||
ports: [{name: http, containerPort: 3000}]
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
resources:
|
||||
requests: {cpu: 250m, memory: 512Mi}
|
||||
limits: {cpu: '1', memory: 2Gi}
|
||||
startupProbe:
|
||||
httpGet: {path: /health, port: http}
|
||||
periodSeconds: 5
|
||||
failureThreshold: 120
|
||||
readinessProbe:
|
||||
httpGet: {path: /health, port: http}
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /data, subPath: pageswiki-exhibit-v018/wiki}
|
||||
- {name: ca, mountPath: /pg-ca, readOnly: true}
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||
- name: ca
|
||||
secret:
|
||||
secretName: pageswiki-exhibition-tls
|
||||
items: [{key: ca.crt, path: ca.crt}]
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: pageswiki}
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector: {app: pageswiki}
|
||||
ports: [{name: http, port: 80, targetPort: http}]
|
||||
@@ -0,0 +1,94 @@
|
||||
# One-time, fresh exhibition only. SQLite lives on emptyDir, NEVER on NFS.
|
||||
# Refuses any second import. Keep the completed Job until verification ends.
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata: {name: pageswiki-exhibition-bootstrap}
|
||||
spec:
|
||||
backoffLimit: 0
|
||||
activeDeadlineSeconds: 1800
|
||||
template:
|
||||
metadata:
|
||||
labels: {pageswiki-db-client: 'true'}
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
automountServiceAccountToken: false
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
runAsGroup: 10001
|
||||
seccompProfile: {type: RuntimeDefault}
|
||||
affinity:
|
||||
podAffinity:
|
||||
requiredDuringSchedulingIgnoredDuringExecution:
|
||||
- labelSelector:
|
||||
matchLabels: {app: pageswiki-postgres}
|
||||
topologyKey: kubernetes.io/hostname
|
||||
initContainers:
|
||||
- name: initialize-local-source
|
||||
image: python@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
|
||||
command: [python3, -c, "import os; os.chown('/data', 10001, 10001)"]
|
||||
securityContext:
|
||||
runAsNonRoot: false
|
||||
runAsUser: 0
|
||||
runAsGroup: 0
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities: {drop: [ALL], add: [CHOWN]}
|
||||
resources:
|
||||
requests: {cpu: 50m, memory: 32Mi}
|
||||
limits: {cpu: 100m, memory: 64Mi}
|
||||
volumeMounts:
|
||||
- {name: source, mountPath: /data}
|
||||
containers:
|
||||
- name: bootstrap
|
||||
image: git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9
|
||||
command: [/bin/sh, -ec]
|
||||
args:
|
||||
- |
|
||||
umask 077
|
||||
test ! -e /persistent/import-complete.json
|
||||
PAGESWIKI_DB_BACKEND=sqlite /pageswiki >/tmp/bootstrap.log 2>&1 &
|
||||
pid=$!
|
||||
trap 'kill -TERM "$pid" 2>/dev/null || true' EXIT
|
||||
healthy=false
|
||||
for attempt in $(seq 1 120); do
|
||||
if wget -q -O /dev/null http://127.0.0.1:3000/health; then healthy=true; break; fi
|
||||
kill -0 "$pid"
|
||||
sleep 1
|
||||
done
|
||||
test "$healthy" = true
|
||||
kill -TERM "$pid"
|
||||
wait "$pid"
|
||||
trap - EXIT
|
||||
/pageswiki migrate-postgres --data-dir /data --apply --timeout 20m >/persistent/import-report.pending.json
|
||||
mv /persistent/import-report.pending.json /persistent/import-complete.json
|
||||
# Preserve the stopped synthetic source for audit, not runtime use.
|
||||
mkdir /persistent/bootstrap-source
|
||||
cp /data/pages.db /persistent/bootstrap-source/pages.db
|
||||
echo 'Synthetic namespace initialized and verified PostgreSQL import committed.'
|
||||
env:
|
||||
- {name: PAGESWIKI_DATA_DIR, value: /data}
|
||||
- name: PAGESWIKI_AUTH_KEY
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: auth-key}}
|
||||
- name: PAGESWIKI_POSTGRES_DSN
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-app, key: postgres-dsn}}
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
resources:
|
||||
requests: {cpu: 250m, memory: 512Mi}
|
||||
limits: {cpu: '1', memory: 2Gi}
|
||||
volumeMounts:
|
||||
- {name: source, mountPath: /data}
|
||||
- {name: data, mountPath: /data/documents, subPath: pageswiki-exhibit-v018/wiki/documents}
|
||||
- {name: data, mountPath: /persistent, subPath: pageswiki-exhibit-v018/wiki}
|
||||
- {name: ca, mountPath: /pg-ca, readOnly: true}
|
||||
volumes:
|
||||
- name: source
|
||||
emptyDir: {}
|
||||
- name: data
|
||||
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||
- name: ca
|
||||
secret:
|
||||
secretName: pageswiki-exhibition-tls
|
||||
items: [{key: ca.crt, path: ca.crt}]
|
||||
@@ -0,0 +1,94 @@
|
||||
# 展示用合成データの準備と投入前確認
|
||||
|
||||
灯架図書館、雲庭研究街区、帆灯運用街区という架空の街を巡るデータセットです。日本語のWiki 26ページ、合成CSV 1件、タスク8件、予定6件、架空連絡先6件をローカル生成します。実在の人物や団体、実測値、本番データ、認証情報を含みません。連絡先はすべて `example.invalid` です。
|
||||
|
||||
生成ツール `generate.py` にはHTTPクライアント、DB接続、クラスタ操作、投入機能がありません。別の `seed.py` が、展示namespaceと固定releaseイメージを確認し、localhost限定port-forward越しに通常のimport/API/DAVで投入します。
|
||||
|
||||
2026年11月15日に展示環境へ全件投入済みです。PostgreSQLとPagesWikiのPod再作成後にも、ログイン、Wiki/CSV 27文書、予定6件・タスク8件・連絡先6件のUIDとETagを確認しました。再投入は既存DAV20件を上書きせずにスキップします。本番や外部カレンダーのデータは使いません。
|
||||
|
||||
## 配置済み展示環境の検証
|
||||
|
||||
保存済みの展示用kubeconfigを利用し、別の端末で次を起動します。
|
||||
|
||||
```sh
|
||||
kubectl -n exhibit-anya port-forward --address 127.0.0.1 service/pageswiki 18381:80
|
||||
```
|
||||
|
||||
`seed.py` はこのリポジトリの保存済み展示用kubeconfigと、`pageswiki-exhibition-app` Secretの `owner-password` を利用します。接続先は `127.0.0.1:18381` 固定、既定Hostは `pages.anya.jisaba.sh`、管理者は `exhibition-admin` です。トークンやパスワードは表示しません。
|
||||
|
||||
この投入ツールは2026年11月の展示専用です。kubectlとkubeconfigの参照先は
|
||||
Git管理外の `.deployment-backups/exhibition-session/` に固定されており、別環境向けの汎用CLIではありません。
|
||||
当時の資格情報は同梱しません。`verify` もログインを行うため、オフライン検証には下記の単体テストを使います。
|
||||
|
||||
```sh
|
||||
python3 tools/exhibition-demo/seed.py verify
|
||||
```
|
||||
|
||||
新規環境での投入順は `configure --host localhost`、`wiki`、`organizers`、`city-labels`、`verify` です。既存展示への通常確認には `verify` だけを使います。`organizers` の再実行は `If-None-Match: *` により既存項目をスキップし、更新しません。
|
||||
|
||||
Cityの内部名はASCII制約があるため、日本語を識別子として渡しません。現在の展示は `/exhibition-demo` を起点としたURL自動生成を維持し、`city-labels` で表示タイトルだけを日本語化しています。データセットの3領域はこの起点の下に表示され、3つのトップレベルQuartierへ手動分割する構成ではありません。
|
||||
|
||||
## ローカル生成
|
||||
|
||||
リポジトリのルートでPython 3.10以上を使用します。追加パッケージは不要です。`--base-date` は日本時間の展示開始日を明示指定してください。
|
||||
|
||||
```sh
|
||||
python3 tools/exhibition-demo/generate.py \
|
||||
--base-date 2026-11-15 \
|
||||
--output /tmp/pageswiki-exhibition-demo
|
||||
|
||||
python3 -m unittest discover -s tools/exhibition-demo -p 'test_*.py' -v
|
||||
|
||||
go test ./tools/exhibition-demo
|
||||
```
|
||||
|
||||
投入前には独立したPythonテスト(生成6件・投入補助3件)を必ず実行します。Goテストはアプリの既存パーサーとの追加確認です。Pythonを含まない既存CI環境ではGoの追加確認だけをskipし、CIイメージに新しい依存は要求しません。
|
||||
|
||||
予定は基準日の9時、11時、14時と、その翌日、3日後、6日後に配置します。タスクの期限は前日から6日後までに分散し、完了・進行中・未着手の状態を用意しています。JSONには日本時間のオフセットを残し、ICSの時刻はUTCで出力します。
|
||||
|
||||
同じ基準日とprefixからは同じ内容とZIPが生成されます。基準日を変えてもタスク、予定、連絡先のUIDは変わりません。再生成は既存の `manifest.json` と全ファイルのSHA-256を照合し、手編集したファイル、無関係なファイル、symlinkがある出力先を拒否します。生成物を手編集した場合は別の出力先を指定してください。中断で生成が不完全になった場合も、新しいディレクトリで再生成してください。
|
||||
|
||||
## 出力内容
|
||||
|
||||
| 出力 | 用途 |
|
||||
| --- | --- |
|
||||
| `wiki.zip` | 既存Archive Import向け。26個のMarkdownと1個のCSVのみを収録 |
|
||||
| `wiki/` | ZIPと同一内容の閲覧用展開データ |
|
||||
| `fixtures.json` | 日付を解決済みの合成データ。アプリの直接import形式ではない |
|
||||
| `tasks/*.ics` | 1ファイルにつき1個のVTODO。タスクDAVの単一リソース形式を想定 |
|
||||
| `events/*.ics` | 1ファイルにつき1個のVEVENT |
|
||||
| `calendar.ics` | 6予定をまとめた閲覧・import用カレンダー |
|
||||
| `contacts/*.vcf` | 1ファイルにつき1人のvCard 3.0 |
|
||||
| `manifest.json` | 基準日、prefix、件数、生成物のSHA-256 |
|
||||
|
||||
Wikiの階層は「街区 → 通り → 場所 → 個別資料」の最大4階層です。各ページには `children` マクロと内部リンクがあり、風見テラスには表とCSV、再現ノートには集計コードを用意しています。五分の案内コースは `帆灯運用街区/案内通り/案内台本` から始められます。
|
||||
|
||||
## 展示用Wikiへの投入手順
|
||||
|
||||
以下は、展示専用の新規データ領域、利用者、接続先が確定した後に運営者が行う手順です。本番や既存利用者の環境には投入しません。
|
||||
|
||||
1. 展示専用環境のバックアップ方針と権限を確認し、通常の `/v/import` 画面を開きます。
|
||||
2. `wiki.zip` を選び、投入先prefixを **`/exhibition-demo`** に指定します。変更する場合は、生成時にも同じ `--target-prefix` を指定します。内部リンクはこのprefixを含むため、ZIPだけ別prefixに投入しないでください。
|
||||
3. 解析結果の27項目を確認します。Markdownは拡張子が除去されたPathになり、CSVの拡張子は残ります。
|
||||
4. 現在の展示構成ではimportのQuartier、Street、Spotを空欄とし、保存後のURL自動生成に任せます。手動指定する場合はASCIIの内部名を使い、日本語は別途Cityの表示タイトルへ設定します。
|
||||
5. 競合は `skip` を選びます。既存import APIのcommitは `conflict=skip` が既定です。`rename` は複製を作るので再投入には使用しません。
|
||||
6. `/exhibition-demo/展示案内` を開き、children一覧、パンくず、内部リンク、コード、表、CSVを確認します。
|
||||
|
||||
同prefixでの `skip` は既存Pathを上書きしません。日付や内容を変更したZIPの再投入でも既存ページは更新されません。更新や削除が必要な場合は、展示専用データであることを確認して別途計画してください。ローカル再生成の安全性と、サーバ側での再投入の安全性は別の確認事項です。
|
||||
|
||||
## タスクと予定と連絡先の投入前確認
|
||||
|
||||
JSON fixtureはアプリのAPIペイロードを装っていません。通常のタスクDAV、カレンダー、CardDAVのディスカバリと権限確認を経て、展示専用コレクションへ投入する後続作業が必要です。認証設定や外部カレンダー購読はこの準備ツールでは作成しません。
|
||||
|
||||
- タスクDAVには `tasks/` の単一VTODOを使います。全タスクを1個のリソースに連結しないでください。
|
||||
- 予定は対応するimport経路で `calendar.ics` を使うか、通常のDAVリソース操作で `events/` を使います。両方を重複投入しません。
|
||||
- 連絡先は `contacts/` の単一vCardを使います。電話番号、実住所、実在ドメインは含みません。
|
||||
- DAVの新規作成は固定のリソース名・UIDを使い、`If-None-Match: *` で既存リソースの上書きを防ぎます。412応答は内容を確認し、無条件PUTで上書きしないでください。日付を更新する場合は既存ETagの確認と `If-Match` による更新を別途実装・検証します。
|
||||
|
||||
投入後は展示専用アカウントで当日・今週の予定、タスク状態、日本時間の表示を確認してください。実サーバでのimport、条件付き作成、UID/ETagと文書の読み戻しは `seed.py` で検証済みです。公開HTTPS経路を通したブラウザの描画・操作確認は残っています。
|
||||
|
||||
## 仕様の参照先
|
||||
|
||||
- [Archive Importの設計](../../../../docs/design/archive-import.md)
|
||||
- [childrenマクロの設計](../../../../docs/design/projection-adapters.md#children-macro-views)
|
||||
- ソース上の確認箇所は `internal/server/import_handler.go`、`internal/server/task_ical.go`、`internal/server/contact_dav.go` です。
|
||||
@@ -0,0 +1,81 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"dataset_id": "pageswiki-exhibition-fiction-v1",
|
||||
"notice": "すべて架空の展示用データです。実在の人物、団体、設備、観測値とは関係ありません。",
|
||||
"districts": [
|
||||
{
|
||||
"name": "灯架図書館",
|
||||
"intro": "空想の港町にある灯架図書館。物語と設計記録を同じ棚に並べ、読むことから小さな発見を始めます。",
|
||||
"streets": [
|
||||
{"name": "閲覧通り", "intro": "初めての来館者が、書棚と読書の記録を巡る通りです。", "spots": [
|
||||
{"name": "星図の書棚", "intro": "架空の星座を描いた地図帳を集めました。星の位置ではなく、物語のつながりを調べる棚です。", "details": ["銀の帆座は航海日誌の章から探せます。", "青い栞は共同読書で選ばれた資料の目印です。"]},
|
||||
{"name": "読書ラウンジ", "intro": "短い感想を持ち寄る静かな場所。結論を急がず、気になった一文から話を始めます。", "details": ["一回の読書会は二十五分を想定しています。", "紹介カードには作品名と問いを一つ書きます。"]}
|
||||
]},
|
||||
{"name": "記録通り", "intro": "紙の資料を整理し、次の読者に伝えるための作業記録です。", "spots": [
|
||||
{"name": "修復工房", "intro": "破れた架空の航海日誌を題材に、修復前後の記録の残し方を学びます。", "details": ["修復前の状態と作業の判断を分けて記録します。", "展示の作業記録には実物の文化財情報を含めません。"]},
|
||||
{"name": "目録編集室", "intro": "題名、分類、紹介文を揃えて資料を見つけやすくします。", "details": ["分類は星図、航海、暮らしの三種類です。", "略称から正式な架空資料名へのリンクを残します。"]}
|
||||
]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "雲庭研究街区",
|
||||
"intro": "雲庭研究街区は、合成データで観察と分析を練習する架空の研究拠点です。数値は測定結果ではありません。",
|
||||
"streets": [
|
||||
{"name": "観測通り", "intro": "データの意味、単位、欠測を揃えてから図や表に進みます。", "spots": [
|
||||
{"name": "風見テラス", "intro": "紙で作った風車の回転数を想定した、完全合成の観測セットです。", "details": ["回転数は説明用の規則から生成します。", "気象予測や設備判断には利用できません。"]},
|
||||
{"name": "露の温室", "intro": "架空の苗床ごとの観察メモを並べ、記録の粒度を比較します。", "details": ["苗床名は琥珀、翡翠、真珠の三つです。", "成長の違いは物語上の設定で、栽培助言ではありません。"]}
|
||||
]},
|
||||
{"name": "解析通り", "intro": "小さな表から仮説と確認事項を分けて考える通りです。", "spots": [
|
||||
{"name": "比較実験室", "intro": "同じ条件のつもりでも何が異なるか、試行表から探します。", "details": ["条件名、入力、結果を一行にまとめます。", "一つの結果だけで原因を決めない練習に使います。"]},
|
||||
{"name": "再現ノート", "intro": "入力と手順を残し、別の人が同じ合成結果を得られるか確かめます。", "details": ["基準日を固定すると展示データを再現できます。", "実データや認証情報のコピーは使いません。"]}
|
||||
]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "帆灯運用街区",
|
||||
"intro": "帆灯運用街区は、展示を案内する架空の運営チームです。受付、点検、振り返りを一つの流れで紹介します。",
|
||||
"streets": [
|
||||
{"name": "案内通り", "intro": "初めての見学者にも、現在地と次の見どころを伝えます。", "spots": [
|
||||
{"name": "受付デスク", "intro": "三つの街区を巡る見学コースの起点です。参加者の実名や連絡先は収集しません。", "details": ["図書館、研究街区、運用街区の順に巡ります。", "質問は架空の案内係に向けたサンプルとして扱います。"]},
|
||||
{"name": "案内台本", "intro": "階層、内部リンク、タスクと予定の関係を短い説明でつなぎます。", "details": ["まず子ページ一覧から目的の場所へ移動します。", "最後に日付の変わる展示用予定を紹介します。"]}
|
||||
]},
|
||||
{"name": "整備通り", "intro": "点検結果と引き継ぎ事項を分けて記録する運用の練習場です。", "spots": [
|
||||
{"name": "点検室", "intro": "架空の案内灯と展示端末を題材に、確認項目を見える形にします。", "details": ["点検項目は表示、操作、案内文の三つです。", "このページの手順は実設備を操作しません。"]},
|
||||
{"name": "引継ぎ広場", "intro": "終わったこと、残ったこと、次に確かめることを短く残します。", "details": ["未完了の項目には確認する日を添えます。", "担当名は展示専用の架空役名を使います。"]}
|
||||
]}
|
||||
]
|
||||
}
|
||||
],
|
||||
"deep_pages": [
|
||||
{"parent": "灯架図書館/閲覧通り/星図の書棚", "name": "銀の帆座", "intro": "銀の帆座は、迷った船が灯りを持ち寄るという架空の物語です。", "details": ["分類は星図、資料番号は SYN-LIB-001 です。", "関連する読書会は合成カレンダーに収録しています。"]},
|
||||
{"parent": "灯架図書館/記録通り/修復工房", "name": "青い航海日誌", "intro": "青い航海日誌の綴じ直しを想定した、展示専用の修復記録です。", "details": ["作業前の課題は架空の綴じ糸のゆるみです。", "完了条件は記録表の項目が揃っていることです。"]},
|
||||
{"parent": "雲庭研究街区/解析通り/再現ノート", "name": "合成データの読み方", "intro": "CSVの各列が何を表すかを確認します。行の日付は展示の基準日から相対生成されます。", "details": ["sample_id は固定の標本識別子です。", "rotations は説明用の整数、synthetic は常に true です。"]},
|
||||
{"parent": "帆灯運用街区/整備通り/点検室", "name": "開場前チェック", "intro": "実環境を変更せず、展示画面の見どころを確認するチェックリストです。", "details": ["階層を移動して戻れることを確認します。", "図書館から研究街区へのリンクを確認します。"]}
|
||||
],
|
||||
"tasks": [
|
||||
{"id": "task-01", "title": "星図の紹介カードを揃える", "due_offset": -1, "status": "COMPLETED", "page": "灯架図書館/閲覧通り/星図の書棚"},
|
||||
{"id": "task-02", "title": "読書会の問いを一つ選ぶ", "due_offset": 0, "status": "IN-PROCESS", "page": "灯架図書館/閲覧通り/読書ラウンジ"},
|
||||
{"id": "task-03", "title": "合成観測表の単位を確認する", "due_offset": 0, "status": "NEEDS-ACTION", "page": "雲庭研究街区/観測通り/風見テラス"},
|
||||
{"id": "task-04", "title": "再現ノートに基準日を記録する", "due_offset": 1, "status": "NEEDS-ACTION", "page": "雲庭研究街区/解析通り/再現ノート"},
|
||||
{"id": "task-05", "title": "開場前の表示を点検する", "due_offset": 0, "status": "NEEDS-ACTION", "page": "帆灯運用街区/整備通り/点検室"},
|
||||
{"id": "task-06", "title": "案内台本を読み合わせる", "due_offset": 2, "status": "NEEDS-ACTION", "page": "帆灯運用街区/案内通り/案内台本"},
|
||||
{"id": "task-07", "title": "修復記録の分類を揃える", "due_offset": 3, "status": "NEEDS-ACTION", "page": "灯架図書館/記録通り/修復工房"},
|
||||
{"id": "task-08", "title": "見学コースを振り返る", "due_offset": 6, "status": "NEEDS-ACTION", "page": "帆灯運用街区/整備通り/引継ぎ広場"}
|
||||
],
|
||||
"events": [
|
||||
{"id": "event-01", "title": "開場前の読み合わせ", "offset": 0, "hour": 9, "duration_minutes": 30, "location": "帆灯運用街区 受付デスク"},
|
||||
{"id": "event-02", "title": "銀の帆座の読書会", "offset": 0, "hour": 11, "duration_minutes": 45, "location": "灯架図書館 読書ラウンジ"},
|
||||
{"id": "event-03", "title": "合成観測表の見学", "offset": 0, "hour": 14, "duration_minutes": 30, "location": "雲庭研究街区 風見テラス"},
|
||||
{"id": "event-04", "title": "再現ノートの交換会", "offset": 1, "hour": 13, "duration_minutes": 45, "location": "雲庭研究街区 比較実験室"},
|
||||
{"id": "event-05", "title": "青い航海日誌の紹介", "offset": 3, "hour": 10, "duration_minutes": 30, "location": "灯架図書館 修復工房"},
|
||||
{"id": "event-06", "title": "街区横断の振り返り", "offset": 6, "hour": 16, "duration_minutes": 30, "location": "帆灯運用街区 引継ぎ広場"}
|
||||
],
|
||||
"contacts": [
|
||||
{"id": "contact-01", "name": "栞係 ルリ", "organization": "架空の灯架図書館", "email": "ruri@example.invalid"},
|
||||
{"id": "contact-02", "name": "修復係 コハク", "organization": "架空の灯架図書館", "email": "kohaku@example.invalid"},
|
||||
{"id": "contact-03", "name": "観測係 ソラ", "organization": "架空の雲庭研究街区", "email": "sora@example.invalid"},
|
||||
{"id": "contact-04", "name": "記録係 ナギ", "organization": "架空の雲庭研究街区", "email": "nagi@example.invalid"},
|
||||
{"id": "contact-05", "name": "案内係 トワ", "organization": "架空の帆灯運用街区", "email": "towa@example.invalid"},
|
||||
{"id": "contact-06", "name": "点検係 ハル", "organization": "架空の帆灯運用街区", "email": "haru@example.invalid"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
# 旧SQLite用の一般ひな形。現在の展示NFSへは適用しない。
|
||||
# 展示ではpostgres.yaml、初回のみbootstrap.yaml、app.yamlを使う。
|
||||
# 適用前に運営の方針と照合する。
|
||||
# kubectl -n "$NS" apply -f pageswiki.yaml
|
||||
apiVersion: v1
|
||||
kind: PersistentVolumeClaim
|
||||
metadata:
|
||||
name: pageswiki-data
|
||||
spec:
|
||||
storageClassName: REPLACE_WITH_STORAGE_CLASS
|
||||
accessModes:
|
||||
- ReadWriteOnce
|
||||
resources:
|
||||
requests:
|
||||
storage: 20Gi
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: pageswiki
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy:
|
||||
type: Recreate
|
||||
selector:
|
||||
matchLabels:
|
||||
app: pageswiki
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: pageswiki
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 60
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
runAsGroup: 10001
|
||||
fsGroup: 10001
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: pageswiki
|
||||
# 本書の作成時点のrelease例。新しい展示機能を含める場合は別途releaseし検証する。
|
||||
image: git.anya.jp/anya/pageswiki-app:v0.17.3
|
||||
imagePullPolicy: IfNotPresent
|
||||
ports:
|
||||
- name: http
|
||||
containerPort: 3000
|
||||
env:
|
||||
- name: PAGESWIKI_DATA_DIR
|
||||
value: /data
|
||||
resources:
|
||||
requests:
|
||||
cpu: 250m
|
||||
memory: 512Mi
|
||||
limits:
|
||||
cpu: "2"
|
||||
memory: 2Gi
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities:
|
||||
drop:
|
||||
- ALL
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /data
|
||||
- name: tmp
|
||||
mountPath: /tmp
|
||||
startupProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
periodSeconds: 5
|
||||
failureThreshold: 120
|
||||
readinessProbe:
|
||||
httpGet:
|
||||
path: /health
|
||||
port: http
|
||||
periodSeconds: 5
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: pageswiki-data
|
||||
- name: tmp
|
||||
emptyDir: {}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata:
|
||||
name: pageswiki
|
||||
spec:
|
||||
type: ClusterIP
|
||||
selector:
|
||||
app: pageswiki
|
||||
ports:
|
||||
- name: http
|
||||
port: 80
|
||||
targetPort: http
|
||||
@@ -0,0 +1,145 @@
|
||||
apiVersion: v1
|
||||
kind: ConfigMap
|
||||
metadata:
|
||||
name: pageswiki-exhibition-init
|
||||
data:
|
||||
storage.py: |
|
||||
import os, pathlib, shutil, stat
|
||||
root = pathlib.Path('/volume/pageswiki-exhibit-v018')
|
||||
def owned_directory(path, uid, gid, mode):
|
||||
try:
|
||||
path.mkdir(mode=mode)
|
||||
except FileExistsError:
|
||||
s = path.lstat()
|
||||
if not stat.S_ISDIR(s.st_mode) or (s.st_uid, s.st_gid) != (uid, gid):
|
||||
raise RuntimeError('unexpected existing directory ownership: ' + str(path))
|
||||
else:
|
||||
os.chown(path, uid, gid)
|
||||
owned_directory(root, 0, 0, 0o755)
|
||||
owned_directory(root / 'wiki', 10001, 10001, 0o700)
|
||||
owned_directory(root / 'wiki' / 'documents', 10001, 10001, 0o700)
|
||||
owned_directory(root / 'postgres', 70, 70, 0o700)
|
||||
os.chown('/pgsocket', 70, 70)
|
||||
for name in ('server.crt', 'server.key'):
|
||||
shutil.copyfile('/cert-source/' + name, '/tls/' + name)
|
||||
os.chmod('/tls/' + name, 0o600)
|
||||
os.chown('/tls/' + name, 70, 70)
|
||||
print('Dedicated directories and PostgreSQL TLS files ready; existing ownership unchanged.')
|
||||
10-app.sh: |
|
||||
set -eu
|
||||
psql -v ON_ERROR_STOP=1 --username postgres --dbname postgres <<SQL
|
||||
CREATE ROLE pageswiki LOGIN PASSWORD '${APP_DB_PASSWORD}' NOSUPERUSER NOCREATEDB NOCREATEROLE;
|
||||
CREATE DATABASE pageswiki OWNER pageswiki;
|
||||
SQL
|
||||
---
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: pageswiki-postgres
|
||||
spec:
|
||||
replicas: 1
|
||||
strategy: {type: Recreate}
|
||||
selector:
|
||||
matchLabels: {app: pageswiki-postgres}
|
||||
template:
|
||||
metadata:
|
||||
labels: {app: pageswiki-postgres}
|
||||
spec:
|
||||
automountServiceAccountToken: false
|
||||
terminationGracePeriodSeconds: 90
|
||||
securityContext:
|
||||
seccompProfile: {type: RuntimeDefault}
|
||||
initContainers:
|
||||
- name: initialize-storage
|
||||
image: python@sha256:9ef1a599f863231c3d91e941389bfdc4a2d6070557243d54df1a4e57015b960e
|
||||
command: [python3, /scripts/storage.py]
|
||||
securityContext:
|
||||
runAsUser: 0
|
||||
runAsGroup: 0
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities: {drop: [ALL], add: [CHOWN, DAC_OVERRIDE]}
|
||||
resources:
|
||||
requests: {cpu: 50m, memory: 32Mi}
|
||||
limits: {cpu: 250m, memory: 128Mi}
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /volume}
|
||||
- {name: scripts, mountPath: /scripts, readOnly: true}
|
||||
- {name: certificates, mountPath: /cert-source, readOnly: true}
|
||||
- {name: tls, mountPath: /tls}
|
||||
- {name: socket, mountPath: /pgsocket}
|
||||
containers:
|
||||
- name: postgres
|
||||
image: postgres@sha256:005c5c37db96c1e6652a79ea31f9886402fba81ac95dc2db897739121dd7f8f2
|
||||
args:
|
||||
- postgres
|
||||
- -c
|
||||
- ssl=on
|
||||
- -c
|
||||
- ssl_cert_file=/tls/server.crt
|
||||
- -c
|
||||
- ssl_key_file=/tls/server.key
|
||||
- -c
|
||||
- shared_buffers=128MB
|
||||
- -c
|
||||
- max_connections=40
|
||||
env:
|
||||
- {name: PGDATA, value: /var/lib/postgresql/data/pgdata}
|
||||
- name: POSTGRES_PASSWORD
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-db, key: admin-password}}
|
||||
- name: APP_DB_PASSWORD
|
||||
valueFrom: {secretKeyRef: {name: pageswiki-exhibition-db, key: app-password}}
|
||||
- {name: POSTGRES_INITDB_ARGS, value: '--auth-host=scram-sha-256'}
|
||||
ports: [{name: postgres, containerPort: 5432}]
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 70
|
||||
runAsGroup: 70
|
||||
allowPrivilegeEscalation: false
|
||||
capabilities: {drop: [ALL]}
|
||||
resources:
|
||||
requests: {cpu: 250m, memory: 256Mi}
|
||||
limits: {cpu: '1', memory: 1Gi}
|
||||
startupProbe:
|
||||
exec: {command: [pg_isready, -U, postgres, -d, postgres]}
|
||||
periodSeconds: 5
|
||||
failureThreshold: 60
|
||||
readinessProbe:
|
||||
exec: {command: [pg_isready, -U, postgres, -d, postgres]}
|
||||
periodSeconds: 5
|
||||
volumeMounts:
|
||||
- {name: data, mountPath: /var/lib/postgresql/data, subPath: pageswiki-exhibit-v018/postgres}
|
||||
- {name: scripts, mountPath: /docker-entrypoint-initdb.d/10-app.sh, subPath: 10-app.sh, readOnly: true}
|
||||
- {name: tls, mountPath: /tls, readOnly: true}
|
||||
- {name: socket, mountPath: /var/run/postgresql}
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim: {claimName: pageswiki-data}
|
||||
- name: scripts
|
||||
configMap: {name: pageswiki-exhibition-init}
|
||||
- name: certificates
|
||||
secret: {secretName: pageswiki-exhibition-tls, defaultMode: 0400}
|
||||
- name: tls
|
||||
emptyDir: {}
|
||||
- name: socket
|
||||
emptyDir: {}
|
||||
---
|
||||
apiVersion: v1
|
||||
kind: Service
|
||||
metadata: {name: pageswiki-postgres}
|
||||
spec:
|
||||
selector: {app: pageswiki-postgres}
|
||||
ports: [{name: postgres, port: 5432, targetPort: postgres}]
|
||||
---
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: NetworkPolicy
|
||||
metadata: {name: pageswiki-postgres}
|
||||
spec:
|
||||
podSelector:
|
||||
matchLabels: {app: pageswiki-postgres}
|
||||
policyTypes: [Ingress]
|
||||
ingress:
|
||||
- from:
|
||||
- podSelector:
|
||||
matchLabels: {pageswiki-db-client: 'true'}
|
||||
ports: [{protocol: TCP, port: 5432}]
|
||||
@@ -0,0 +1,103 @@
|
||||
# Isolated root initialization followed by a non-root storage test.
|
||||
# Does not inspect or change existing data or the PVC root permissions.
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: pageswiki-root-storage-check
|
||||
spec:
|
||||
backoffLimit: 0
|
||||
activeDeadlineSeconds: 120
|
||||
ttlSecondsAfterFinished: 3600
|
||||
template:
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
automountServiceAccountToken: false
|
||||
securityContext:
|
||||
runAsUser: 0
|
||||
runAsGroup: 0
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: check
|
||||
image: python:3.13-alpine
|
||||
command: [python3, -u, -c]
|
||||
args:
|
||||
- |
|
||||
import hashlib, json, os, pathlib, tempfile
|
||||
mount = None
|
||||
for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines():
|
||||
before, after = line.split(' - ', 1)
|
||||
fields, detail = before.split(), after.split()
|
||||
if fields[4] == '/check':
|
||||
mount = (detail[0], set(fields[5].split(',')) | set(detail[2].split(',')))
|
||||
if mount is None:
|
||||
raise RuntimeError('PVC mount not found')
|
||||
fs, options = mount
|
||||
if fs in ('nfs', 'nfs4') and ('hard' not in options or options & {'soft', 'softerr', 'softreval'}):
|
||||
raise RuntimeError('NFS hard mount required')
|
||||
root = pathlib.Path(tempfile.mkdtemp(prefix='.pageswiki-root-check-', dir='/check'))
|
||||
print(json.dumps({'stage': 'created', 'directory': root.name, 'filesystem': fs, 'hard_mount': 'hard' in options}))
|
||||
try:
|
||||
os.chown(root, 10001, 10001)
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
try:
|
||||
os.setgroups([])
|
||||
os.setgid(10001)
|
||||
os.setuid(10001)
|
||||
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
|
||||
payload = b'PagesWiki isolated non-root storage verification\n'
|
||||
try:
|
||||
with (root / 'source').open('xb') as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.link(root / 'source', root / 'published')
|
||||
try:
|
||||
os.link(root / 'source', root / 'published')
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
raise RuntimeError('no-replace publication failed')
|
||||
os.rename(root / 'source', root / 'renamed')
|
||||
os.fsync(directory)
|
||||
for name in ('published', 'renamed'):
|
||||
if hashlib.sha256((root / name).read_bytes()).digest() != hashlib.sha256(payload).digest():
|
||||
raise RuntimeError('readback mismatch')
|
||||
print(json.dumps({'result': 'passed', 'process_uid': os.getuid(), 'process_gid': os.getgid(), 'server_durability': 'not verified'}))
|
||||
finally:
|
||||
for name in ('source', 'published', 'renamed'):
|
||||
(root / name).unlink(missing_ok=True)
|
||||
os.fsync(directory)
|
||||
os.close(directory)
|
||||
except BaseException:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
os._exit(1)
|
||||
os._exit(0)
|
||||
_, status = os.waitpid(pid, 0)
|
||||
if os.waitstatus_to_exitcode(status) != 0:
|
||||
raise RuntimeError('non-root storage verification failed')
|
||||
finally:
|
||||
# Only remove the empty directory created by this process.
|
||||
root.rmdir()
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
add: [CHOWN, SETUID, SETGID]
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 250m
|
||||
memory: 128Mi
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /check
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: pageswiki-data
|
||||
@@ -0,0 +1,90 @@
|
||||
# Run only in the assigned exhibit-anya namespace after release verification.
|
||||
# kubectl -n exhibit-anya apply --dry-run=server -f storage-check.yaml.example
|
||||
# No database or existing application data is opened by this job.
|
||||
apiVersion: batch/v1
|
||||
kind: Job
|
||||
metadata:
|
||||
name: pageswiki-storage-check
|
||||
spec:
|
||||
backoffLimit: 0
|
||||
activeDeadlineSeconds: 120
|
||||
ttlSecondsAfterFinished: 3600
|
||||
template:
|
||||
spec:
|
||||
restartPolicy: Never
|
||||
automountServiceAccountToken: false
|
||||
securityContext:
|
||||
runAsNonRoot: true
|
||||
runAsUser: 10001
|
||||
runAsGroup: 10001
|
||||
seccompProfile:
|
||||
type: RuntimeDefault
|
||||
containers:
|
||||
- name: check
|
||||
image: python:3.13-alpine
|
||||
imagePullPolicy: IfNotPresent
|
||||
command: [python3, -c]
|
||||
args:
|
||||
- |
|
||||
import hashlib, json, os, pathlib, tempfile
|
||||
mount = None
|
||||
for line in pathlib.Path('/proc/self/mountinfo').read_text().splitlines():
|
||||
before, after = line.split(' - ', 1)
|
||||
fields, detail = before.split(), after.split()
|
||||
if fields[4] == '/check':
|
||||
mount = (detail[0], set(fields[5].split(',')) | set(detail[2].split(',')))
|
||||
if mount is None:
|
||||
raise RuntimeError('PVC mount was not found')
|
||||
fs, options = mount
|
||||
if fs in ('nfs', 'nfs4') and ('hard' not in options or options & {'soft', 'softerr', 'softreval'}):
|
||||
raise RuntimeError('NFS hard mount required; unsafe or unknown options')
|
||||
root = pathlib.Path(tempfile.mkdtemp(prefix='.pageswiki-storage-check-', dir='/check'))
|
||||
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
|
||||
payload = b'PagesWiki isolated storage verification\n'
|
||||
try:
|
||||
with (root / 'source').open('xb') as f:
|
||||
f.write(payload)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.link(root / 'source', root / 'published')
|
||||
try:
|
||||
os.link(root / 'source', root / 'published')
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
raise RuntimeError('link publication replaced an existing entry')
|
||||
os.fsync(directory)
|
||||
os.rename(root / 'source', root / 'renamed')
|
||||
os.fsync(directory)
|
||||
expected = hashlib.sha256(payload).digest()
|
||||
for name in ('published', 'renamed'):
|
||||
if hashlib.sha256((root / name).read_bytes()).digest() != expected:
|
||||
raise RuntimeError('content mismatch')
|
||||
print(json.dumps({'result': 'passed', 'filesystem': fs,
|
||||
'hard_mount': 'hard' in options,
|
||||
'server_durability': 'not verified by this client-side test'}))
|
||||
finally:
|
||||
for name in ('source', 'published', 'renamed'):
|
||||
(root / name).unlink(missing_ok=True)
|
||||
os.fsync(directory)
|
||||
os.close(directory)
|
||||
root.rmdir()
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 64Mi
|
||||
limits:
|
||||
cpu: 250m
|
||||
memory: 128Mi
|
||||
securityContext:
|
||||
allowPrivilegeEscalation: false
|
||||
readOnlyRootFilesystem: true
|
||||
capabilities:
|
||||
drop: [ALL]
|
||||
volumeMounts:
|
||||
- name: data
|
||||
mountPath: /check
|
||||
volumes:
|
||||
- name: data
|
||||
persistentVolumeClaim:
|
||||
claimName: pageswiki-data
|
||||
@@ -14,12 +14,12 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.gecko-relay
|
||||
image: pageswiki-gecko-relay:dev
|
||||
image: ${PAGESWIKI_GECKO_IMAGE:-pageswiki-gecko-relay:dev}
|
||||
environment:
|
||||
PAGESWIKI_GECKO_KEY_FILE: /run/secrets/gecko-key
|
||||
volumes:
|
||||
- ${PAGESWIKI_GECKO_KEY_PATH:?Set absolute relay key path}:/run/secrets/gecko-key:ro
|
||||
- ${PAGESWIKI_GECKO_ASSETS_DIR:?Set verified Gecko dist directory}:/gecko:ro
|
||||
- ${PAGESWIKI_GECKO_ASSETS_DIR:?Set verified complete Gecko bundle directory}:/gecko:ro
|
||||
networks:
|
||||
gecko-front: {}
|
||||
gecko-egress: {}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
services:
|
||||
app:
|
||||
image: pageswiki-app:task-index-20261109
|
||||
app2:
|
||||
image: pageswiki-app:task-index-20261109
|
||||
@@ -0,0 +1,38 @@
|
||||
# Optional pilot only; does not enable indexing or modify the Pages database.
|
||||
# docker compose -f docker-compose.yml -f docker-compose.ml.yml up -d --build machine-learning
|
||||
services:
|
||||
app:
|
||||
networks:
|
||||
ml-front: {}
|
||||
machine-learning:
|
||||
build: ./services/machine-learning
|
||||
image: pageswiki-machine-learning:dev
|
||||
environment:
|
||||
PAGES_ML_TOKEN_FILE: /run/secrets/ml-token
|
||||
PAGES_ML_MODEL_DIR: /models
|
||||
PAGES_ML_ALLOW_OPENAI: "false"
|
||||
volumes:
|
||||
- ${PAGES_ML_TOKEN_PATH:?Set absolute shared token file path}:/run/secrets/ml-token:ro
|
||||
- ${PAGES_ML_MODELS_PATH:?Set absolute trusted model directory path}:/models:ro
|
||||
expose: ["8010"]
|
||||
networks:
|
||||
ml-front: {}
|
||||
read_only: true
|
||||
tmpfs: [/tmp:size=32m,mode=1777]
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
pids_limit: 64
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8010/healthz', timeout=2).read()"]
|
||||
interval: 30s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
networks:
|
||||
ml-front:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${PAGES_ML_FRONT_SUBNET:-172.24.1.0/27}
|
||||
@@ -0,0 +1,142 @@
|
||||
# AI連携とKnowledge Cityの自動整理
|
||||
|
||||
2026-11-17。展示後の要望を受けた実施計画。優先順は
|
||||
**AI向けCLIスキル → CLIに依存しないMCPサーバー → 意味ベースのCity整理**。
|
||||
この文書は設計であり、MCPやベクトル索引が既に稼働していることを意味しない。
|
||||
既存のURL由来の分類・手動編集を置き換えるのではなく、それを補助する。
|
||||
|
||||
同日追記:**Pages Machine Learning** を独立サービスとする方針を採用。
|
||||
`services/machine-learning/` と `internal/machinelearning/` に内部API/クライアントの
|
||||
初期実装を追加した。Doc2Vecの合成データによる学習→HTTP推論→Goクライアントを検証。
|
||||
OpenAIは通信を模擬した契約試験のみ。2026-11-28にDomain別の設定API/UIと予算保存層を追加。
|
||||
文書抽出・推論worker・キュー・ベクトル索引は未接続で、設定保存だけでは推論を開始しない。
|
||||
[サービス境界・運用・残件](../../operations/pages-machine-learning.md)を参照。
|
||||
|
||||
## 1. AI向けスキル(AI-01)
|
||||
|
||||
配布用ソースを `skills/pages-cli/` に置いた。文書の検索・読み取り・編集、タスク、
|
||||
作業記録、メール取り込みを対象にする。初版は独立CLI v0.5.0のhelpと契約を参照。
|
||||
グローバルなエージェント設定や認証状態を変更しない。
|
||||
|
||||
設置時はそのフォルダを利用するエージェントのskillsディレクトリへコピーする。
|
||||
Codexなら通常 `~/.codex/skills/pages-cli/`。CLI自体と接続プロファイルは別に必要。
|
||||
将来はpages-cliリポジトリ/リリースに同梱する。今回は独立リポジトリを変更していない。
|
||||
|
||||
受入:未認証、検索0件、言語分岐、競合、通信断、削除済みcaptureを模擬し、無許可の
|
||||
上書き・公開・資格情報表示をしない。文書/メール中の指示でscopeを変更しない。
|
||||
スキルの文法検証だけを行動試験の完了とは扱わない。
|
||||
|
||||
## 2. MCPサーバー(AI-02、未実装)
|
||||
|
||||
候補URIは `/_/api/v1/mcp`。PagesのGoサーバー内に薄いMCP transport層を置き、既存の
|
||||
業務サービスを呼ぶ。pages-cliの子プロセス起動、HTTPハンドラの文字列出力解析、
|
||||
独自SQLでの認可回避はしない。CLIは人間の端末操作用として継続する。
|
||||
|
||||
### 段階とtool契約
|
||||
|
||||
| 段階 | 候補tool | 必須の結果・制限 |
|
||||
| --- | --- | --- |
|
||||
| M1 読取 | search_pages, list_children, read_page, list_tasks | Page UUID、Revision、言語、出典URL、cursor、truncated。件数・本文量を制限 |
|
||||
| M2 更新 | update_page, create_task, update_task | 基点Revision/version、request ID、変更後ID。競合は明示エラー |
|
||||
| M3 整理 | suggest_city_placement, preview_city_changes, apply_city_changes | まず提案・差分のみ。applyは承認済み計画IDと現行版一致が必要 |
|
||||
|
||||
tool名は案。M1公開時点では書込toolを広告しない。descriptionやreadOnlyHint等の注釈は
|
||||
認可の代わりではない。任意URL取得・shell・SQL実行toolは提供しない。
|
||||
|
||||
### transport・認証のゲート
|
||||
|
||||
- HTTP transportと認証は公式SDK/仕様の特定版に固定し、採用版を実装時に記録する。
|
||||
まず2025-11-25世代との相互運用を調べ、最新版と混在させない。SDKが実装する
|
||||
lifecycle、GET/POST、SSE、protocol negotiationを検証し、自前の部分JSON-RPCを公開しない。
|
||||
- Remote MCPのOAuth discovery、resource/audience、PKCE、client registrationの対応を先に
|
||||
決める。既存のOIDC「ログインできる」ことは、PagesがMCP用OAuth認可サーバーであることを
|
||||
意味しない。通常のWeb CookieやCLI handoff tokenの転用を標準対応とは呼ばない。
|
||||
- 各要求でDomain・Principal・scope・現在の権限を確定する。引数のdomain_uuidで権限を切替えない。
|
||||
読取専用を既定、書込は別scope。セッションがあっても権限失効を反映する。
|
||||
- Origin検査、TLS、要求サイズ、時間制限、キャンセル、同時数、監査の本文/秘密情報非記録を実装。
|
||||
MCP上の文書本文は信頼しないデータとして渡し、tool出力に次の実行命令を埋め込まない。
|
||||
- 受入は対応クライアントの実接続、別Domain・失効・scope不足・巨大入力・再送・キャンセル・
|
||||
更新競合。SQLiteとPostgreSQLの双方で同じ認可結果を要求する。
|
||||
|
||||
## 3. ベクトル化の共通設計(CITY-SEM-01、サービス基盤のみ実装)
|
||||
|
||||
Pages本体が文書選定・認可・抽出・キュー・結果保存・適用を管理する。
|
||||
Pages Machine Learningは渡された入力のベクトル化とモデル計算だけを担当し、
|
||||
PagesのDB/文書ディレクトリをmountしない。MCPやCLIからMLへ直接アクセスしない。
|
||||
永続ジョブは既存イベントスケジューラに一本化する。ML障害は通常閲覧・編集を妨げない。
|
||||
|
||||
プロバイダーはまず **OpenAI Embeddings API** と **ローカルDoc2Vec** の2種類。
|
||||
外部送信は既定OFF。Domain単位に対象prefix、除外、送信可否、件数/トークン予算を
|
||||
管理者が選ぶ。本人の読取権限だけで全Domainの外部送信を許可しない。
|
||||
|
||||
HTMLから本文・見出し・コードを抽出する。script/style、展開済みchildren、外部埋め込みは
|
||||
入力に含めず、リンク先を取りに行かない。長文は節/段落で分割し、モデル別上限で制限。
|
||||
タイトル・Pathは補助特徴とし、URLだけで同じ分類を再生して高精度に見せない。
|
||||
バイナリOCR、添付解析、外部カレンダーは初期対象外。実データの送信・学習は今回行わない。
|
||||
|
||||
### プロバイダーごとの違い
|
||||
|
||||
| 項目 | OpenAI Embeddings | Doc2Vec |
|
||||
| --- | --- | --- |
|
||||
| 初期候補 | text-embedding-3-small、dimensionsは設定 | Gensim PV-DBOWまたはPV-DM、比較して固定 |
|
||||
| 実行場所 | APIへ対象テキストを送信 | ローカルの低優先度worker |
|
||||
| 準備 | API鍵・送信同意・料金予算 | 学習コーパス・日本語tokenizer・学習設定 |
|
||||
| 注意 | 入力長、429、timeout、再送による追加課金 | 少量文書・未知語・短文の精度、学習CPU/RAM |
|
||||
|
||||
Doc2Vecを常に軽い/高精度とは仮定しない。同じtokenizerを学習・推論に使用し、
|
||||
seed、workers、epochs、語彙、学習対象のdigest、モデル世代を固定する。
|
||||
新モデル生成時は旧ベクトルとの混在比較を禁止。modelファイルは信頼済みの自前生成物のみを
|
||||
ロードし、任意アップロードのpickleを読み込まない。Domain/権限境界を越えた学習はしない。
|
||||
削除・権限変更後は結果を即座に読取不可にし、学習済みモデル内の残存情報は再学習で除去する。
|
||||
|
||||
### 保存・キュー・規模
|
||||
|
||||
ベクトルと分類候補は再構築できるデータ。キーはDomain、Page UUID、Revision UUID、言語、
|
||||
chunk、入力hash、provider、model revision、次元、抽出/tokenizer版、設定hash。
|
||||
別provider・別modelの空間を混ぜない。非数・次元不一致・空出力は失敗として扱う。
|
||||
原文や鍵はログに出さず、ベクトルも本文相当の機密性で扱う。
|
||||
|
||||
作成・編集の確定イベントで重複排除付きの低優先度ジョブを投入。削除は索引を無効化し、
|
||||
renameはPath特徴だけの再評価を可能にする。既存schedulerを使い、foregroundへ推論を置かない。
|
||||
夜間backfill、手動実行、停止、進捗・失敗・予算表示を設定画面へ追加する。
|
||||
古いジョブの完了時にRevision・権限・provider設定の世代を再検査する。
|
||||
|
||||
初期は小規模Domainに限定したバッチ比較(件数・メモリ上限付き)。全ペアO(N²)を
|
||||
ページ表示時に実行しない。大規模化はANN索引を別段階にし、PostgreSQLのpgvectorは
|
||||
選択肢として検証するが必須DB拡張にはしない。SQLiteとの差をAPI契約へ漏らさない。
|
||||
|
||||
## 4. Cityへの提案と適用(CITY-SEM-02、未実装)
|
||||
|
||||
1. 既存のStreet/Spotに属する文書の代表ベクトルから候補を提示する。十分な文書が
|
||||
ない場合は候補なし。類似度は確率ではなく、top-k候補・代表文書・根拠の語句を示す。
|
||||
2. 未整理文書は小規模クラスタの候補を表示し、人が名前・親・境界を選ぶ。Embedding自体に
|
||||
生成AIの命名能力はない。初版のラベルは見出し/キーワード候補と手入力にする。
|
||||
3. 閲覧者に見える文書だけで根拠・件数を作る。非公開文書由来のクラスタ名や特徴を公開しない。
|
||||
4. 現行のQuartier→Street→SpotのPath境界を維持。同じ親の境界重複やSpotの任意ネストを
|
||||
類似度のために許可しない。範囲外の類似ページは関連付け候補とし、primary所属とは分ける。
|
||||
5. 初版は提案のみ。自動rename・削除・merge・新規Path作成はしない。適用機能では計画の差分、
|
||||
影響するPath/公開範囲、入力版、承認者、要求IDを固定し、並行編集時は再提案する。
|
||||
6. 手動名・手動配置・拒否した提案を保持する。定期ジョブが手作業を戻さない。
|
||||
|
||||
品質は合成/明示同意データで評価し、top-k採用率、誤配置率、日本語・英語・コード・短文別、
|
||||
遅延、最大メモリ、API費用、同一入力の安定性を両方式で比較する。未知・低信頼は保留する。
|
||||
公開範囲変更と同時の推論、削除後の候補非表示、停止・再開、モデル更新、類似URLだが別内容も試験する。
|
||||
|
||||
## 実施チェックリスト
|
||||
|
||||
- [x] AI-01:CLIスキル初版の配布用ソース(グローバル導入・独立CLIリリースは未実施)
|
||||
- [ ] AI-01受入:エージェント行動テストとpages-cliリリースへの同梱
|
||||
- [ ] AI-02 M1:SDK/プロトコル版・認証方式決定、読取MCP、両DBと実クライアント試験
|
||||
- [ ] AI-02 M2:条件付き保存・冪等なタスク作成・監査
|
||||
- [x] ML-01:独立サービス、認証/入力上限、Goクライアント、両provider、Doc2Vec合成結合試験
|
||||
- [ ] ML-02:モデル失効・配布、設定・予算、既存キューへの接続、実行状態UI
|
||||
- [ ] CITY-SEM-01:本文抽出・永続索引・分類品質評価・差分キュー(provider基盤のみ実装)
|
||||
- [ ] CITY-SEM-02:候補比較UI・手動修正保護・明示適用
|
||||
|
||||
## 一次資料
|
||||
|
||||
- [OpenAI Embeddings](https://developers.openai.com/api/docs/guides/embeddings):関連度・分類向けの数値表現。
|
||||
- [Gensim Doc2Vec](https://radimrehurek.com/gensim/models/doc2vec.html):学習と推論にtoken列を使用。
|
||||
- [MCP 2025-11-25 transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports)
|
||||
/[authorization](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization):初期相互運用の参照版。
|
||||
最新版/SDK対応状況は実装開始時に再照合する。
|
||||
@@ -0,0 +1,219 @@
|
||||
# SQLite依存の縮小とPostgreSQL/MySQL対応
|
||||
|
||||
2026-11-30更新。既存PostgreSQL対応を維持し、新規ML機能からMySQL対応を検証する。
|
||||
SQL文字列をdriverで置換する方式や、未対応時のSQLite自動fallbackは採用しない。
|
||||
既存本番DBの切替・実データ移行は本作業と分離する。
|
||||
|
||||
## 現状と今回の到達点
|
||||
|
||||
| 対象 | SQLite | PostgreSQL | MySQL |
|
||||
| --- | --- | --- | --- |
|
||||
| Pages本体の起動 | 既存 | 既存のnative起動・SQLite import経路あり | 未対応。起動オプションを追加しない |
|
||||
| ML設定/日次予算 | 実DB共通試験成功 | PostgreSQL 17で成功 | MySQL 8.4で成功、限定component pilot |
|
||||
| ML予算schema | 明示migration | 明示migration | native migration、版/checksum台帳、検査・明示再開CLI。実DB試験済み、本番未適用 |
|
||||
| Campus/Domain/設定 | 既存 | 既存 | DB-COREa+b:Campus作成・更新、ホスト解決、設定、standalone Campus内のlocal Domain作成・更新。Domain/Campus削除は未対応 |
|
||||
| ユーザー/グループ | 既存 | 既存 | パスワードアカウント、所属、group/permission、管理者継承・失効の限定保存API。HTTP認証・完全な認可境界は未接続 |
|
||||
| 認証設定/管理 | 既存 | 既存 | provider設定・暗号化secret保持、外部ID、challenge、TOTP、profile/avatarの保存処理。Domain別session一覧・失効を限定APIへ接続。CLI認証handoff・監査は未対応 |
|
||||
| DBバックアップ/DR | 既存SQLite方式 | native backup、現行DR起動は拒否 | 設計・実装未着手 |
|
||||
|
||||
MySQL接続を`internal/db/mysql.go`に追加。既定は検証付きTLSのみ、秘密情報を含むdriverエラーや
|
||||
DSNをログ/応答に出さない。multi-statements、LOCAL INFILEの全ファイル許可、平文fallback等を拒否。
|
||||
TLSを緩める指定は使い捨て試験専用。現在の接続設定は意図的に限定している。
|
||||
各プール接続へ所有コードの厳格sql_modeを設定し、長い値の黙示的な切詰め/不正値の変換を拒否する。
|
||||
|
||||
`MySQLMLRepository`はML設定と予算操作だけを公開する。`*Store`を外へ返さず、
|
||||
未移植のメソッドがSQLite分岐へ流れるのを防ぐ。Domainの認可は既存API側の責務であり、
|
||||
このfacadeを匿名/任意Domainの外部APIへ直接接続しない。
|
||||
|
||||
`MySQLNamespaceRepository`も移植済みメソッドだけを公開する。認可チェックは上位の責務。
|
||||
Campusの外部管理への登録や削除はfederation等が未移植のため公開しない。
|
||||
Domain変更は`MySQLIdentityRepository`で、built-in group/管理者継承と同一transactionに接続した。
|
||||
対象はstandalone Campus/local placementのみ。remote/controller/managedの変更は拒否する。
|
||||
旧SQLite schema初期化やDomain削除は引き続き未対応エラーで停止する。
|
||||
|
||||
`MySQLIdentityRepository`は保存APIであり、呼出元が認証・認可する必要がある。
|
||||
権限評価の下位primitiveを完全なAuthorizeの代用として公開しない。
|
||||
OIDC/LDAP/SMTP設定とsecret保持、外部ID紐付け、challenge、TOTP、profile/avatarの保存処理は
|
||||
MySQLにも移植したが、HTTPサーバーや実providerとは未接続。CLI認証handoff、監査、
|
||||
locality/publication policyまで含む完全な認可境界は未移植。
|
||||
パスワード照合・session purpose/Domain分離・失効のprimitiveは実DB試験済みだが、
|
||||
MySQLで本体ログイン画面が使えることを意味しない。
|
||||
|
||||
## 修正したSQL差異
|
||||
|
||||
- 予約前のロック:SQLiteはwriter確保、PostgreSQL/MySQLは設定行の`SELECT … FOR UPDATE`。
|
||||
値を変えないUPDATEのRowsAffectedへ依存しない。
|
||||
- 予約transaction:PostgreSQL/MySQLはREAD COMMITTED。ロック待機後に最新の予算を見る。
|
||||
- UPSERT:SQLite/PostgreSQLはON CONFLICT、MySQLはON DUPLICATE KEY UPDATE。
|
||||
設定の初回作成はMySQLの重複キーだけを競合へ変換し、INSERT IGNOREで他の不整合を隠さない。
|
||||
- 設定CAS:MySQLではJSON文字列をbinary比較。新世代UUIDで実更新になるためchanged-row semanticsでも動作。
|
||||
- MySQLのキー列:TEXT主キーではなくサイズを定めたVARCHAR/CHAR、ASCII binary collation。
|
||||
本文設定はutf8mb4。InnoDB/CHECK制約を使う。
|
||||
- 共通configのkeyは版2でVARCHAR(255)/utf8mb4_0900_binへ拡張。
|
||||
日本語・大文字小文字・末尾空白・Unicode合成形を区別し、既存値と版1checksumは保持する。
|
||||
- ホスト名の結合はMySQLのCONCATを使用。sql_modeで`||`の意味を変えて互換化しない。
|
||||
- topology更新はMySQLでは専用行のtransaction lockを使う。WHERE 0のUPDATEに排他を期待しない。
|
||||
既存PostgreSQLはadvisory transaction lock、SQLiteはwriter予約を維持する。
|
||||
- MySQLの予約語groupsは識別子として明示quoteする。所有SQLの構築段階で分岐し、driverで書き換えない。
|
||||
- groupメンバー/permission/継承設定は、MySQLのUPSERTのRowsAffected=0/1/2を存在判定に使わない。
|
||||
所有者の降格・最後の所有者の削除は行政用transaction lock内で検査し、同値の再設定は成功とする。
|
||||
- Campus管理者の投影は独立したgrantを入力とし、投影結果を再度の継承元にしない。
|
||||
派生所属の除去とsession失効は元の設定変更と同時commit。MySQLの派生UUIDはUUID()を使う。
|
||||
MySQL replication/HAは未受入(将来はROW形式等も含めて検証する)。
|
||||
- providerの空secret更新では、UPSERT内で既存暗号文を保持する。外部IDは同一所有者の再設定を許し、
|
||||
別principalへの再紐付けを拒否する。MySQLでは共通管理transaction lockで所有者確認と更新を直列化する。
|
||||
- MySQLの単一テーブルUPDATEは代入順の差があるため、TOTPの失敗回数を増やす前に制限到達を判定する。
|
||||
全backendで5回目にchallengeを消費し、コード・challengeの同時利用は一度だけ成功する。
|
||||
- MySQLのDDLは暗黙commitがあるため、PostgreSQLのtransactional migrationを流用しない。
|
||||
専用connectionのGET_LOCKと操作単位のjournalを併用する。通常applyは途中失敗を拒否し、
|
||||
resumeのみが事後条件を確認して再開する。成功済みDDLを無条件に繰り返さない。
|
||||
|
||||
## 実施順と受入ゲート
|
||||
|
||||
1. **DB-ML(実装済み)**:ML設定・予算の3DB共通試験。ドライバ、ロック、照合、CAS差異の検証。
|
||||
2. **DB-MIG(基盤実装済み)**:MySQLの版/checksum台帳、途中DDLからの回復、schema assertion、read-only検査。
|
||||
ML schemaで実証。未知版/履歴改変/主キー欠落を拒否。実行中のschemaを勝手に採用しない。
|
||||
全機能のDDL移植、CHECK式の意味まで含む厳密なschema比較、backup・復旧手順の受入は後続。
|
||||
3. **DB-CORE**:Campus/Domain、config、ユーザー/グループ/認可、document metadata、revision/Path。
|
||||
Pathの大文字小文字、日本語、末尾空白、NULLとunique、UUIDの同一性を両DBで検証する。
|
||||
**DB-COREa実装済み**:Campus作成・設定更新、Domainの読み取り・ホスト解決、config。
|
||||
**DB-COREb基盤実装済み**:principal/membership/built-in group、管理者継承、local Domain書込。
|
||||
次はDB-COREcで文書metadata・Revision・Pathを移植する。
|
||||
COREbの認証保存処理(外部ID/provider・MFA・profile)とsession管理は移植済み。
|
||||
残件(CLI認証handoff・完全な認可snapshot・監査・group編集・認証/管理UI接続)も本体接続前に消化する。
|
||||
部分対応を本体対応と混同しない。
|
||||
4. **DB-JOBS**:activity outbox/イベントキュー/claim/lease/ログ保持を移植。
|
||||
ワーカーの再起動・同時claim・timeout・receipt保持を確認してからML workerを接続する。
|
||||
5. **DB-EXT**:タスク/CalDAV、カレンダー、連絡先、RSS、通知、City、資産、検索。
|
||||
SQLite FTS/PostgreSQL検索を単純にMySQL FULLTEXTへ置換せず、日本語と権限付き検索を比較する。
|
||||
6. **DB-APP**:全機能の起動検査、import/backup/復旧、CI matrix、管理画面の実ブラウザ検証。
|
||||
ここまで通してからMySQLをPages本体の選択可能backendにする。
|
||||
7. **DB-DECOUPLE**:portable repositoryとSQLite実装をパッケージ境界で分離し、
|
||||
PostgreSQL/MySQL-onlyバイナリからSQLite driverを外せる構成を検討する。
|
||||
|
||||
粗い静的走査ではstore内にPRAGMA/sqlite_master/INSERT OR/COLLATE BINARY等の参照が64行ある。
|
||||
これは未対応箇所数ではない(SQLite専用migration/import/分岐も含む)。主な確認先は
|
||||
`schema_modules.go`、`config.go`、`domains.go`、`domain_paths.go`、`activity_outbox.go`、
|
||||
`event_log_write.go`、`tasks*.go`、`feeds.go`、`contacts.go`、`object_listing.go`。
|
||||
さらに`metadata.Repository`がSQLite/PostgreSQLの2backendに限定され、SQLiteのエラー型も直接参照している。
|
||||
MySQL enumを増やしただけで全体対応を宣言せず、各repositoryの受入試験を移植単位とする。
|
||||
|
||||
## 再現試験
|
||||
|
||||
2026-11-30コミット整理時にも、使い捨てのMySQL 8.4/PostgreSQL 17とSQLiteで
|
||||
下記のnamespace・identity・ML・migration契約を`-race -count=1`で再検証した。
|
||||
`TestAccountBackend*`のCLI handoffは引き続きSQLite/PostgreSQLのみであり、
|
||||
MySQL対応済みの範囲には含めない。Goクライアント/設定APIの回帰と
|
||||
`go vet ./internal/db ./internal/machinelearning ./internal/store ./cmd/pageswiki`も成功。
|
||||
全パッケージの全テスト、本番切替、MySQLでのHTTPサーバー起動確認を意味しない。
|
||||
|
||||
使い捨てPostgreSQL/MySQLを起動し、次の環境変数を設定して実行する。
|
||||
本番DSNを渡さない。MySQL試験はCREATE DATABASE権限を要し、一意な試験DBを作成・削除する。
|
||||
PostgreSQL試験は同様に一意schemaを作成・削除する。
|
||||
|
||||
```sh
|
||||
PAGESWIKI_TEST_POSTGRES_DSN='postgres://USER:PASS@127.0.0.1:PORT/postgres?sslmode=disable' \
|
||||
PAGESWIKI_TEST_MYSQL_DSN='USER:PASS@tcp(127.0.0.1:PORT)/mysql' \
|
||||
go test -race ./internal/store ./cmd/pageswiki -run 'TestMLBudget|TestMachineLearningPolicyPersistence|TestMySQL|TestNamespaceCoreThreeBackendContract|TestStoreNamespaceBackendContract|TestDomainWriteBackend' -count=1 -v
|
||||
```
|
||||
|
||||
未設定backendはSKIPとなる。SKIPを成功実績に数えない。2026-11-28の実試験では3backendともPASS。
|
||||
設定の保存・競合・破損拒否、同時予算予約、日付境界、ID重複、世代変更、失敗時非返却を共通検証。
|
||||
今回本番移行・自動migration・ML送信は行っていない。
|
||||
|
||||
2026-11-30:DB-COREaの共通契約もSQLite/PostgreSQL 17/MySQL 8.4で成功。
|
||||
FQDN競合時のrollback、同時作成、取消、read-only、日本語・絵文字、Domain設定分離、
|
||||
configキーのNO PAD比較を検証。MySQLの版1→版2で既存データを保持し、暗黙commit後の再開も試験する。
|
||||
|
||||
同日DB-COREb:`TestAdminInheritanceBackend*`、`TestGeneralGroupBackend*`、
|
||||
`TestGroupPermissionBackend*`、`TestRoleGrantBackend*`、`TestPrincipalStateBackend*`、
|
||||
AccountBackendのbootstrap/login/session/concurrent-bootstrap試験を3DBへ拡張。
|
||||
MySQL専用の`TestMySQLIdentity*`はfacadeからDomain作成→owner作成→継承→Campus移動→session失効、
|
||||
故障注入時のDomain rollback、schema復旧、跨Domain拒否を検証する。
|
||||
上記の使い捨てDSNを設定して、次で再現できる。
|
||||
|
||||
```sh
|
||||
go test -race ./internal/store ./cmd/pageswiki \
|
||||
-run 'TestAdminInheritanceBackend|TestGeneralGroupBackend|TestGroupPermissionBackend|TestRoleGrantBackend|TestPrincipalStateBackend|TestAccountBackend(BootstrapProjectionFailureIsAtomic|LoginAndSession|ConcurrentBootstrap)|TestMySQL|TestDomainWriteBackend' \
|
||||
-count=3
|
||||
```
|
||||
|
||||
この反復試験は3回成功。既存CampusAdmin移行・失効試験とML/namespaceの回帰試験も成功。
|
||||
全機能のMySQL本体受入試験ではない。
|
||||
|
||||
## MySQL migrationの運用境界
|
||||
|
||||
MLの3テーブルは`internal/store/mysql_ml_schema.sql`を版1として管理する。公開後は既存版を編集せず、
|
||||
追加版で変更する。MySQL 8.4で、暗黙commit後のjournal更新漏れ、途中DDL失敗、並行実行、
|
||||
版追加、未知版拒否、schema drift、台帳主キー破損、取消後のロック解放を試験する。
|
||||
`status/check`は台帳を作らず検査する(同時DDLとの競合防止にsession lockのみ取得)。
|
||||
`apply/resume`は明示指定時のみ実行し、Pagesの通常起動へ自動接続しない。
|
||||
|
||||
事後条件は各operationの責務。非冪等DMLをReplaySafeにしてはならない。
|
||||
CHECK制約の現在の検査は個数までであり、同数の別式への差し替えを検出するものではない。
|
||||
台帳検査もDB管理者による任意改ざんを防止するセキュリティ機構ではない。
|
||||
実行前にバックアップを取得し、dirty時は原因調査・必要な修復後に明示resumeする。
|
||||
CLI手順は[ML運用](../../operations/pages-machine-learning.md#mysqlのml-schema管理)を参照。
|
||||
|
||||
### Namespace pilotの操作
|
||||
|
||||
```sh
|
||||
pageswiki mysql-namespace-schema status
|
||||
pageswiki mysql-namespace-schema apply
|
||||
pageswiki mysql-namespace-schema check
|
||||
pageswiki mysql-namespace-schema resume
|
||||
```
|
||||
|
||||
接続先は同じ`PAGESWIKI_MYSQL_DSN`。空の専用DBにだけ明示的に適用する。
|
||||
このコマンドも本体の起動オプションではない。Campus/Domainのデータや管理者を自動作成しない。
|
||||
status/checkは読み取り専用。applied/pendingは依存componentも含む合計、dirty_componentは
|
||||
先に修復するcomponent、next_operationはそのcomponent内の次の操作位置。
|
||||
|
||||
現在のconfigは最初のML移行台帳に所有させたまま、namespace側から依存する。
|
||||
二つの移行履歴で同じテーブルを作成・adoptしない。ML台帳がdirtyなら先に
|
||||
`mysql-ml-schema resume`で修復し、その後namespaceを再開する。
|
||||
これは過渡期の所有境界であり、将来のbase-schema整理でも既存checksumを書き換えない。
|
||||
|
||||
このnamespace facade単体ではDomain変更を公開しない。後述identity facadeを使う。
|
||||
未対応:Domain/Campus削除、個人設定、完全な認可、文書・Path、外部管理の同期、
|
||||
全体import/backup。本番schemaの自動adoptは行わない。MySQL namespaceの制限は名前255文字、
|
||||
設定キー255文字、UUIDはcanonical形式。制限超過はエラーにし、黙って切り詰めない。
|
||||
|
||||
### Identity/group pilotの操作
|
||||
|
||||
```sh
|
||||
pageswiki mysql-identity-schema status
|
||||
pageswiki mysql-identity-schema apply
|
||||
pageswiki mysql-identity-schema check
|
||||
pageswiki mysql-identity-schema resume
|
||||
```
|
||||
|
||||
前提componentのML/config、namespaceも含めて検査・適用する。ユーザーやパスワード、Domainデータは
|
||||
このCLIで自動作成しない。失敗時はdirty_componentを調査し、依存順に各CLIのresumeを明示実行する。
|
||||
authの台帳名はstore-auth-core。版1の14テーブル・checksumを維持し、版2でauth_challenges/
|
||||
auth_providersを追加する。列型・照合・主キー・uniqueを検査する。依存を含む適用済み版数は5。
|
||||
既存principalを持つ版1からの更新、dirty拒否と明示resume、providerのunique欠落拒否も試験対象とする。
|
||||
版2の最終assertionには版1の全table検査を引き継ぎ、追加後も既存permission等のschema driftを検出する。
|
||||
|
||||
保存APIの範囲:初期owner/password account、Domainユーザー一覧・state、group作成/一覧/
|
||||
メンバー追加・除去、Path permission設定、Campus管理者の継承設定、local Domain作成・更新、
|
||||
Domain別session一覧・失効。session操作はcontext取消・read-only失効拒否・跨Domain拒否を検査する。
|
||||
権限profileは既存read/read_write_once/read_write/upload_onlyの意味を維持し、writeはdeleteを含まない。
|
||||
各変更の呼出権限チェックは上位の責務。外部API/MCPへの直接公開は禁止。
|
||||
|
||||
寸法:UUID 36、identity issuer/subject・credential identifier 255、permission scope Path/grant target 512文字。
|
||||
既存データのimportは未対応で、上限を超える値を切り詰めて取り込まない。
|
||||
COREcで文書Pathの最大長とpermission scope/grant targetの上限を整合させる。
|
||||
groupの編集/archive、profile/avatar・provider/MFA等の管理UI接続、CLI認証handoff、監査、
|
||||
完全な認可snapshot、Domain削除・federation・backupは後続。
|
||||
Domain削除は文書・拡張機能の関連データ移植後に扱い、未対応tableを残した部分削除はしない。
|
||||
公開前にこれらと文書metadataを接続する。
|
||||
|
||||
認証保存処理の共通試験は`TestAccountBackendExternalIdentity`、`TestAccountBackendProviderSecrets`、`TestAccountBackendTOTP`、
|
||||
`TestAccountBackendProfileAndSessionManagement`。MySQLを追加し、暗号文保持・同一ID再設定・
|
||||
不正な再紐付け・重複作成rollback・challenge同時消費・TOTP再登録と5回制限・avatarのbinary往復・
|
||||
session Domain分離を検証する。実OIDC/LDAP/SMTPへの接続や既存ユーザーデータの読取は行わない。
|
||||
|
||||
2026-11-30の追加試験:上記4本と`TestMySQLIdentity*`/schema CLIを、SQLite・PostgreSQL 17・
|
||||
MySQL 8.4で`-race -count=3`実行し成功。既存HTTPログイン・LDAP/OIDC設定・trusted session・
|
||||
CLI OIDCの回帰試験も成功。本体MySQL受入や外部サービス接続の成功を意味しない。
|
||||
@@ -55,7 +55,12 @@
|
||||
- `POST /_/api/v1/editor/convert`:作業中 HTML を安全な authoring Markdown に変換。
|
||||
`POST /_/api/v1/render/markdown` の `authoring:true` で保護フェンスを元の HTML に戻す。
|
||||
`projection:true` と併用したプレビューでは従来の sanitizer・macro 展開を適用する。
|
||||
- 変換できない HTML は文書全体を保護する保守的な実装。フェンスは
|
||||
- 2026-11-09から、全体変換が構造を保てない場合はbody直下のブロック単位に変換する。
|
||||
往復で構造が一致する見出し・段落・リスト等はMarkdownへ戻し、不一致のブロックだけを保護する。
|
||||
再結合後も文書全体を比較し、head内要素等を失う場合は全文保護へ戻す。
|
||||
保護ブロックはDOM再シリアライズを避け、原文の引用符・タグ表記をそのまま保持する。
|
||||
分割は最大1024区間。省略終了タグ等で境界を確定できない場合も全文保護へ戻す。
|
||||
リスト・表の構造要素間の空白は比較時に正規化し、インラインの単語境界やコード内空白は保持する。フェンスは
|
||||
`` ```{=html} `` 形式(本文にバッククォートがある場合はそれより長い区切り)。
|
||||
任意の属性、コメント、未知要素、表の結合、画像キャプション、コード内空白を保持。
|
||||
フェンス内を編集でき、外側に Markdown を追記できる。通常のコードフェンス内にある
|
||||
@@ -70,7 +75,7 @@
|
||||
- `+` は挿入・下書き、`文` は言語の編集・分岐、`↶` は旧リビジョンを作業バッファへ
|
||||
読み込む。復元は明示保存で新 Revision を追加し、旧 Revision を書き換えない。
|
||||
履歴は50件ずつ追加取得し、現在言語で絞り込む。分岐は翻訳生成ではなく本文のコピー。
|
||||
- 挿入は子ページ・表・画像キャプション・補足・コード・引用の6種の初期パレット。
|
||||
- 挿入は子ページ・表・画像キャプション・補足・コード・引用・CSV macroの初期パレット。
|
||||
画像 URL 等のプレースホルダーは編集が必要。ファイルピッカー、図形・外部 widget の
|
||||
パラメータ編集、プラグインによる挿入パーツ登録は既存の HTML editor 設計に残る。
|
||||
- touch/coarse pointer + hover 不可の端末ではデスクトップの Vim 設定を上書きせず、
|
||||
@@ -78,11 +83,13 @@
|
||||
|
||||
## 次段階の実装順序
|
||||
|
||||
CSVの表編集は既存保存・下書き・履歴の契約へ接続済みです。CSVはHTML変換と文字列自動マージを行わず、競合時は比較して採否を決めます。BOMと混在改行を保持するため、CSV初期値はHTMLのtextarea解析を通さず安全なJS文字列として渡し、CodeMirrorはLFのみで分割します。初期フォーカスの遅延処理も、表セルなどへ移ったフォーカスを奪いません。詳細な上限と残件は[表設計](extensions.md)を参照してください。
|
||||
|
||||
1. **E6a presence**:編集中リースの共有ストアと認可付き API、別端末を含む表示。
|
||||
管理者にだけ見える監視ではなく、同じ Page/language を編集できる参加者に限定する。
|
||||
2. **E6b realtime**:下記 CRDT 詳細設計・採用ライブラリ・同時変換ルールを確定した後に
|
||||
feature flag 付きで実装。現時点の CAS を最終コミット時の保護として残す。
|
||||
3. **E5b / E3b**:HTML ブロック単位の保護、hosted editor/CLI への保護フェンス対応、
|
||||
3. **E5b / E3b**:入れ子コンポーネント内のより細粒度なMarkdown復元、hosted editor/CLI への保護フェンス対応、
|
||||
アセットピッカーと拡張挿入パーツ。通常の Markdown だけを扱う外部エディタへ
|
||||
このフェンスを無断で渡さない。既存の外部エディタ変換経路は本変更の対象外。
|
||||
4. 保存 API の旧クライアント移行と base 必須化、下書き大容量化・明示破棄 UX、
|
||||
|
||||
@@ -48,11 +48,25 @@ IPアドレス管理(IPAM)、DNSゾーン/レコード管理、機器・
|
||||
|
||||
## CSV/表・スライド拡張(設計TODO)
|
||||
|
||||
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影するmacroを用意します。候補構文は `{{csv:/data/items.csv range=A1:H200 header=true}}` とし、Path、Revision(またはasset hash)、列・行上限、表示モードを正規化してキャッシュキーに含めます。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
|
||||
初期CSV macroは実装済みです。`{{csv:/data/items.csv range=A1:H200 header=true}}` を認証済みProjectionで展開し、`rev=` で同じObjectのRevisionへ固定できます。現在のPath閲覧権限を毎回検査し、外部URL、匿名公開、asset指定、共有キャッシュはこの段階に含めません。入力256 KiB・UTF-8、表示200行×32列、走査2,000行・100列、セル16 KiB、Projection当たり4種類のCSVまでに制限します。引用符・改行・BOMに対応し、セルはHTML escapeしてmacroや数式を実行しません。処理不能時は内容を漏らさない警告に置き換えます。Authoringでは元のmacroを保持します。
|
||||
|
||||
既存CSVの編集は `/e/-/{path}` の組み込みエディタで行います。デスクトップはソースと表を並べ、700px以下では表を全幅表示してソースへ切り替えます。セル編集、行・列追加/削除、20操作までの表のUndo/Redoに対応。表は200行・32列・セル16 KiB以内を25行ずつ描画し、先頭行を自動でヘッダ扱いしません。矩形でない行の欠落セルは表示だけでは補わず、列追加・貼り付けで必要になった部分だけ空セルを補います。全体256 KiB・UTF-8以内を対象とし、超過・不正形式の表を部分編集可能にして保存することはありません。表上限を超えても全体上限内ならソースで編集できます。
|
||||
|
||||
表計算ソフトからの複数セル貼り付けは、フォーカス中のセルを左上として反映します。クリップボードの `text/plain` にタブまたは改行があればタブ区切り表として解析し、引用符内の改行・タブ・二重引用符を保持します。カンマは列区切りにせずセル値として扱い、単一行の通常テキストはセル内への貼り付けです。複数行を一つのセルへ貼る場合は引用符で囲むかソースを編集します。HTML形式のクリップボードは使いません。必要な行・セルの拡張を含めて1操作でUndo/Redoでき、構文・行列・セル・変換後CSV全体の上限を検査してから一括反映します。失敗時は部分反映せず、既存のUndo履歴も変更しません。貼り付け範囲外のセルと改行形式は維持します。
|
||||
|
||||
CSV正本をHTMLへ変換せず、未変更fieldの引用符、BOM、混在LF/CRLFを保持します。セル内のHTML、macro、数式は実行しません。表編集も既存の下書き・認証切れ検出・言語別Revision CAS・履歴復元を使用し、他の保存と競合したCSVは文字列の自動マージをせず比較画面へ送ります。原文と編集済み表の両方を別正本として保存しません。DBスキーマ変更はありません。CSV新規作成ウィザード、TSVファイル/文字コード変換、大容量表のwindow編集、矩形選択/範囲コピー、列型/数式、ODSは残件です。
|
||||
|
||||
CSVをPage本文へ複製せず、認可済みの別Documentをテーブルとして投影します。共有キャッシュを将来追加する際は、Path、Revision(またはasset hash)、列・行上限、表示モードと権限を考慮します。macroは表示時にboundedなProjectionを作るだけで、結果HTMLを正本へ逆流させません。CSV Editorは元Revisionを編集し、表投影とは別の操作・競合・権限として扱います。
|
||||
|
||||
交換形式はRFC 4180互換CSV(UTF-8、CRLF、引用符・改行を含むfield、BOMの扱いを明示)を第一正本とします。複数シート、型、数式、結合セル、書式が必要な場合はODSを別アダプタ/Assetとして扱い、CSVへの不可逆変換を黙って行いません。行数、列数、セル長、総バイト、ネストmacroを制限し、malformed inputは安全なテキスト表示へfallbackします。
|
||||
|
||||
スライドは、Markdown/HTMLの正本からReveal.js互換のProjectionを生成する連携アダプタを設けます。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。外部ランタイム停止時は静的HTML/Markdownへ安全にfallbackし、任意script、remote import、iframe権限を本文から許可しません。
|
||||
スライドはローカル同梱のReveal.js 6.0.2で表示します。`/v/slides/{path}` は通常のPath閲覧権限でHTML/Markdownの最新Revisionを取得し、HTMLページのスライドアイコンや「連携アダプタで開く」から移動できます。組み込みHTML/Markdownエディタのスライドアイコンは、未保存の本文を通常プレビューと同じ変換経路で投影します。表示DOMを保存せず、保存・下書き・競合処理は既存エディタに任せます。Markdownの空行で囲んだ `---`、HTMLの直下の `<hr>` が横方向の区切りで、直下の `<section>` も1枚として扱います。コードブロック内の区切りは分割しません。
|
||||
|
||||
Reveal実行は `allow-scripts allow-popups` のsandbox iframeに隔離し、`allow-same-origin` は付けません。本文のscript・CSS・iframe・フォーム・任意data属性を渡さず、独自プラグインや外部Markdownを読み込みません。画像は同一originだけ、リンクはHTTP(S)だけです。矢印キー・タッチ・画面内コントロールで移動し、履歴やURL hashを変更しません。ビューアは全画面に対応し、背景・文字色はテーマから引き継ぎます。ライブラリ読込失敗時は静的なサニタイズ済み本文へfallbackします。本文256 KiB・100枚・DOM 10,000ノード/深さ64を上限とし、常時バックグラウンド生成や共有キャッシュは持ちません。`viewer.slides` は拡張設定でドメイン単位に停止でき、停止後のページではビューア・編集切替・アダプタ候補を表示しません。MITライセンス・固定版・配布元・hashは `static/vendor/reveal/` に同梱します。DBスキーマ変更はありません。
|
||||
|
||||
700px以下の編集画面ではスライドプレビューを全幅表示し、既存のプレビュー非表示ボタンでソースへ戻ります。小画面で自動スクロール形式に変わらないよう `scrollActivationWidth: null` を指定します([Reveal.js公式仕様](https://revealjs.com/scroll-view/))。
|
||||
|
||||
縦方向のスライド、fragments、発表者ノート、macroの非同期展開、スライド専用印刷、外部画像の承認連携は残件です。HedgeDoc、Slidevは外部originのホスト型アダプタとして、保存・公開・ユーザー情報をPages Wikiの権限へ自動昇格させず、read-only preview→明示的なimport/saveの順にします。JSを使用できない環境向けには、CSS scroll-snap/`:target`/print CSSだけでページ送りできるCSS-only Slide Editorを別実装します。
|
||||
|
||||
ネットワーク図ではnwdiagを追加候補とします。ソースをbounded parserで検証し、renderer version/theme/document hashをキーに静的SVGをキュー生成します。include、外部画像・font、未知directive、危険なSVG属性は拒否し、renderer停止時はescaped sourceまたは最後に検証済みの静的画像へfallbackします。編集アダプタの保存はone-use ticketと楽観的Revision競合を使い、Kroki経由の場合もorigin、timeout、quotaを明示します。
|
||||
|
||||
|
||||
+11
-2
@@ -44,6 +44,13 @@ IDなしRSSは記事URL、URLもなければ題名・日時・本文の組合せ
|
||||
|
||||
### 高密度ビューア
|
||||
|
||||
2026-11-17:記事のX共有は通常クリックで640×720のポップアップを要求する。
|
||||
クリックの同期処理中に一度だけ開き、元画面の遷移を抑止する。`noopener,noreferrer`
|
||||
指定時の戻り値がnullでも別タブへ再試行しない。Ctrl/Cmd等の修飾クリックは通常の
|
||||
リンク操作を保つ。ブラウザ設定やモバイルではタブ表示となる場合がある。
|
||||
Chromiumのデスクトップ/モバイル幅テストで呼出し回数・元画面の保持・修飾クリックを検証。
|
||||
本番反映は別途行う。
|
||||
|
||||
newsboat/neomuttを参考に、デスクトップは左から購読元・一行記事一覧・本文の3ペインとします。
|
||||
一覧には未読/star、日付、配信元、件名を並べます。狭幅は一覧と本文を切り替え、スマホでは
|
||||
行とボタンのタッチ領域を広げます。モバイルの共通ナビはアイコンのみとし、名称はアクセシブル名と
|
||||
@@ -396,11 +403,13 @@ Wiki単独は親Path配下の `rss-{request UUID}` に新規作成します。
|
||||
- [x] RSS-7c:Shift+j/kによるフォルダ選択。空・未分類・端・購読選択中・検索維持・入力/モーダル抑止・連打を合成試験。
|
||||
- [x] RSS-8a:Gecko端末描画+自前Wisp中継の方式決定。公開中継を使わず、独立・既定無効で導入する。
|
||||
- [x] RSS-8b1:upstream v0.0.1/hash固定、最小埋め込みと親documentのisolation、Chromiumで合成記事の描画・遷移確認。
|
||||
- [ ] RSS-8b2:Safari/iPhone SE実機、IME・コピー・find・証明書エラー・HTTPS互換性、配布license/notice整備。
|
||||
- [ ] RSS-8b2:Safari/iPhone SE実機、IME・コピー・実サイト互換性。固定配布物のlicense/notice整備、HTTPSと証明書エラー、日本語findの合成試験は実施済み。
|
||||
- [x] RSS-8c1:認証付きWisp TCP profile、公開IP/port制限、失効・資源上限・管理者/CLI無効化・内部status。
|
||||
- [ ] RSS-8c2:運用ホストの外向きfirewall、設定UIへの中継監視統合、負荷時の長時間受入。
|
||||
- [x] RSS-8d1:個人設定の選択、1ページのpopup閲覧、戻る/進む/再読込/別タブ/終了。
|
||||
- [ ] RSS-8d2:初回/再表示・低メモリ端末の性能評価、失敗/切断・複数タブのUX、本番配備。
|
||||
- [ ] RSS-8d2:初回/再表示・低メモリ端末の性能評価、実行中の切断・複数タブのUX、本番配備。起動上限と起動失敗時のiframe破棄・原文リンクへの退避は実装済み。
|
||||
|
||||
一覧には配信日と配信時刻(HH:mm)を分けて表示します。Domainの設定タイムゾーンを使い、tooltipには年・秒・タイムゾーンを含めます。配信日時不明は「—」とし、取得日時で補いません。モバイルでも時刻欄を残します。
|
||||
|
||||
隔離試験はRSS/Atom・FreshRSS login/read、欠落ID・巨大/不正feed、条件付きGET、失敗時cache保持、
|
||||
本人分離・失効・readonly、二重送信・版競合・旧worker拒否、migration再実行/失敗rollback、
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# ファイル検査と配信制御
|
||||
|
||||
2026-11-30。アップロード受入、ファイル検査、Webへの配信許可を分離する。
|
||||
**現段階は共通評価器・プラグイン契約・実行器のみ実装済み。HTTP配信制限、DB保存、
|
||||
イベント登録、管理画面、実検査エンジンは未接続。現在のアップロードに検査が追加されたわけではない。**
|
||||
|
||||
利用者合意により、今回の実装範囲はSCAN-01/02の骨子までで一旦区切る。
|
||||
SCAN-03以降は設計上の残件として保持し、このコミットを契機に自動で着手・有効化しない。
|
||||
|
||||
## 公開範囲・権限との関係
|
||||
|
||||
公開範囲は既存のDomain → Quartier → Street → Spotと、それらのPath境界に従う。
|
||||
下位の既定値はinherit。上位の制約を下位が緩和できない。
|
||||
公開可能な上限、Revisionの明示/自動公開、認証後のread/writeは別の判定として維持する。
|
||||
検査結果は追加の配信条件であり、cleanになっても非公開文書を公開したり、権限を付与したりしない。
|
||||
|
||||
検査設定も同様に継承する。初期状態はdisabled。下位で明示したdisabledでも、上位の
|
||||
monitor/requiredを解除しない。上位で要求したエンジンを下位で削除・別版へ置換しない。
|
||||
下位で別エンジンを追加する場合は、すべての必要な検査を通す。
|
||||
エンジン更新・検査解除は、その上位設定を変更できる管理者が明示的に行う。
|
||||
|
||||
| モード | 配信判定 |
|
||||
| --- | --- |
|
||||
| inherit | この範囲で追加の指定をせず上位に従う |
|
||||
| disabled | 上位に制約がなければ既存の配信判定を維持 |
|
||||
| monitor | 検査結果を記録・表示するが、検査だけを理由に配信を止めない |
|
||||
| required | 必須エンジンすべてについて、有効なclean結果が必要 |
|
||||
|
||||
monitorはmaliciousでも配信を止めない明示的な観測モード。設定画面でこの性質を説明する。
|
||||
requiredでエンジンが無効・不在・異常・期限切れなら拒否する。プラグイン停止を検査免除と解釈しない。
|
||||
|
||||
## 保存と非同期処理
|
||||
|
||||
1. 認証、create/write権限、条件付き保存、サイズ、MIME等を既存の保存境界で検証する。
|
||||
2. 不変Documentを永続化する。Path・Revision・検査要求outboxは対応するDB transactionで公開する。
|
||||
3. outboxをイベントキューへ転送し、重複を抑止して検査を実行する。
|
||||
4. 現在のポリシー、送信同意、ジョブ所有権を再確認し、結果を条件付きで保存する。
|
||||
5. 配信要求ごとに既存のアクセス権・公開状態と、有効な検査結果を確認する。
|
||||
|
||||
アップロードHTTP要求中にスキャナーの完了を待たない。配信要求から同期スキャンもしない。
|
||||
保存成功と配信可能は別。検査待ちであっても保存済みなら保存APIは失敗扱いにしない。
|
||||
CLIの新規作成PUT契約の201・identityヘッダーを維持し、検査状態は別メタデータとして追加する。
|
||||
CLIは独自サニタイズや自動再送を行わない。スキャナーは保存本文を書き換えない。
|
||||
無害化/CDRを将来追加する場合は、別Document/Revisionと由来を記録し、黙って置換しない。
|
||||
|
||||
## 結果と識別子
|
||||
|
||||
結果キーはDomain UUID、ポリシー世代、保存内容のSHA-256、エンジンID・版・定義版。
|
||||
Path名やUUID単独、ファイル名、アップロード側が申告した検査結果を根拠にしない。
|
||||
エンジンはclean/suspicious/maliciousを返す。本体はpending/error/expiredも管理する。
|
||||
cleanは当該検査で検出なしを意味し、安全性の絶対保証ではない。
|
||||
|
||||
ポリシー世代は設定・関係するtopology・エンジン有効状態の変更時にサーバーが更新する。
|
||||
初版はDomain世代の変更で保守的に無効化する。大規模Domainの再検査負荷は後続でscope単位へ分割する。
|
||||
別Domainの同じhashには結果を流用しない。別エンジン版・定義版・世代や期限切れの結果も使わない。
|
||||
検査開始・終了時刻、期限、監査用ジョブID、worker lease、試行番号、判定を保存する。
|
||||
プラグインの生の例外・ファイル本文・資格情報を通常ログや通知へ出さない。
|
||||
|
||||
DB保存案は`inspection_policies`、`inspection_reports`と既存outbox/queueを使用する。
|
||||
reportsは上記キーをuniqueとし、古い試行や失効leaseによる上書きを拒否する。
|
||||
SQLはSQLite/PostgreSQL/MySQLのnative migrationと共通契約試験で追加する。
|
||||
CHECKや索引を含むschema検査、既存版のchecksum保持を実施し、SQLite専用SQLを共通処理へ増やさない。
|
||||
|
||||
## プラグインと実行制約
|
||||
|
||||
検査はビューア/エディタではなくシステム拡張。拡張カタログへ公開するのは配信ゲート接続後。
|
||||
現段階の`internal/inspection.Registry`はアプリ所有の信頼済み実装のみ登録でき、登録直後は無効。
|
||||
任意コマンド実行、アップロードされたコードのロード、URLからのプラグイン取得は行わない。
|
||||
実際のスキャナーはまだ登録していない。合成テストの模擬スキャナーを製品へ有効化しない。
|
||||
|
||||
実行器はGeduldhの不変Storeから読み、サイズとSHA-256をストリーム検証してからプラグインへ渡す。
|
||||
プラグインには読み取りストリームのみ渡し、Path・Bearer・DB接続や保存変更権限は渡さない。
|
||||
外部送信するプラグインは、Domain管理者の別の同意がないと読み取り開始前に拒否する。
|
||||
送信URL、TLS、SSRF対策、応答上限、送信先サービスの保持・第三者再送方針は実アダプタ接続の受入条件。
|
||||
|
||||
実行枠は1〜4、入力上限は最大256 MiB、協調的timeoutは最大1分、結果TTLは最大24時間に制限する。
|
||||
満杯時は待ち行列をメモリ上に増やさずErrBusyを返し、既存スケジューラで再配置する。
|
||||
実行数、完了・失敗数、検証byte数、累積実行時間を取得可能。現状は実行器単位の値であり、
|
||||
エンジン別永続集計、CPU/メモリ監視、設定画面への接続は後続。
|
||||
|
||||
実行直前・検証後・結果返却前に、呼出元のRecheckで世代・ジョブ・同意を再確認する。
|
||||
結果DBへのcommitでは別途lease/世代CASが必須。コールバックだけでtransactionの代用にしない。
|
||||
実行中のエンジン停止→再有効化も、旧実行結果を採用しない。
|
||||
|
||||
Go内プラグインはプロセス隔離ではない。contextを無視する実装を強制停止する保証はなく、
|
||||
終了までは実行枠を保持する。実際の重い/外部エンジンはsidecarとCPU/メモリ/timeout制限を検討する。
|
||||
恒久停止への対応・lease回収・再試行上限をイベントキュー側で担保してから有効化する。
|
||||
|
||||
## 配信・処理経路の受入ゲート
|
||||
|
||||
検査対象のバイト列を処理する前に共通ゲートを通す。HTTPであればETag/304・Range/206・
|
||||
HEAD・identityヘッダー等を返す前に判定する。拒否応答はprivate,no-storeとする。
|
||||
既にダウンロードされたデータやブラウザに残ったコピーの回収は保証できない。
|
||||
|
||||
| 経路 | 必要な確認 |
|
||||
| --- | --- |
|
||||
| 通常/匿名/ブログ等のビューア、履歴 | 対象Revisionと依存Document、公開・ACL判定を維持 |
|
||||
| RAW、UUID、Revision、Asset、共有リンク | 名前空間やURL種別を変えて迂回しない |
|
||||
| サムネイル、PDF/画像/アーカイブ解析、全文索引 | 未検査データを先にパーサーへ渡さない |
|
||||
| エディタ、連携アダプタ、export、CLI get | バイト列引渡しを同じ条件で制御 |
|
||||
| 生成済みpreview/cache/CDN | 元Documentとpolicy世代を保持し、旧キャッシュからの配信を防ぐ |
|
||||
|
||||
別名Pathを持つObjectは現在の関連範囲すべてを検査する。公開側の別名だけを選んで制約を外さない。
|
||||
`DecidePaths`は渡された全Pathを評価し、空・上限超過・不正snapshotは拒否する。
|
||||
ただし全Pathを列挙できたかは呼出元の責務。省略した配列を完全なsnapshotとして渡してはならない。
|
||||
UUID/Asset/依存Documentの所属を解決できない場合も、ルートのdisabled設定に置き換えてはならない。
|
||||
跨Domainでは各Domainの設定・権限を独立に評価する。
|
||||
隔離ファイルを管理者が取得する操作を設ける場合は、通常RAWを例外化せず、専用監査経路とする。
|
||||
|
||||
## 段階と残件
|
||||
|
||||
| ID | 状態 | 内容 |
|
||||
| --- | --- | --- |
|
||||
| SCAN-01 | 実装済み | Path継承、世代・hash付き結果判定、別名の全件評価、認可と分離した追加ゲート |
|
||||
| SCAN-02 | 実装済み | 無効開始の信頼済みプラグインregistry、制限付き実行器、合成試験 |
|
||||
| SCAN-03 | 未実装 | 3DBの設定・結果保存、CAS/監査、outboxとqueue接続、lease/retry、プラグイン別計測 |
|
||||
| SCAN-04 | 未実装 | 上表の全配信/解析経路への接続、依存物・別名・キャッシュ・HEAD/Range/304の結合試験 |
|
||||
| SCAN-05 | 未実装 | 管理UI/CLI、継承元と実効値表示、監視モードの警告、権限制御、手動再検査 |
|
||||
| SCAN-06 | 未実装 | MWDB/Karton等の実プラグイン、外部同意、隔離、資源制限、実機受入 |
|
||||
|
||||
SCAN-03/04完了まで必須モードをユーザーへ公開しない。本番データのスキャン・外部送信は別途明示的に開始する。
|
||||
合成試験: `go test -race ./internal/inspection ./internal/schutzaria ./internal/geduldh -count=3`。
|
||||
@@ -42,6 +42,42 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
||||
|
||||
## 次の実施順
|
||||
|
||||
2026-11-30追記:利用者合意により[ファイル検査レイヤ](file-inspection.md)のSCAN-01/02を先行実装。
|
||||
公開範囲は既存の上位Path継承を維持し、検査を追加の配信条件とする。
|
||||
DB非依存のポリシー評価と無効開始のプラグイン実行基盤のみ。SCAN-03(3DB保存・queue)、
|
||||
SCAN-04(全配信/解析経路)、SCAN-05/06(設定・実検査)を残件とし、未接続の必須モードは公開しない。
|
||||
並行するpages-cliとの新規作成PUT契約は維持。検査待ちと保存失敗を混同しない。
|
||||
利用者合意により検査レイヤはこの骨子で一旦区切り、SCAN-03以降への接続は保留する。
|
||||
|
||||
2026-11-28:SQLite固有依存を縮小し、PostgreSQL/MySQLへ段階的に移植する。
|
||||
[DB移植計画](database-portability.md)のDB-MLを実DB3種類で検証済み。
|
||||
DB-MIGの基盤(版/checksum台帳、operation journal、専用connection lock、schema検査、
|
||||
明示resume、`mysql-ml-schema` CLI)をML schemaへ適用し、MySQL 8.4で実試験。
|
||||
次はDB-CORE、DB-JOBSの順。CHECK式の厳密比較・全schema移植・backup受入は残件。
|
||||
2026-11-30:DB-COREa(Campus作成・更新、Domain読取/ホスト解決、Domain別config)を限定MySQL facadeへ移植。
|
||||
3DB共通試験とMySQL既存版からのデータ保持更新、名前空間schema CLIを追加。
|
||||
同日DB-COREb基盤:principal/membership/built-in group/管理者継承とlocal Domain書込を一体で移植。
|
||||
取消・独立grant保持・session失効・故障rollbackを3DBで比較、`mysql-identity-schema` CLIを追加。
|
||||
続いてCOREbのprovider設定・暗号化secret保持・外部ID紐付け・challenge・TOTP・profile/avatar保存を移植。
|
||||
Domain別session一覧・失効を限定APIへ接続。auth schema版2を追加し、版1の履歴とデータを保持する。
|
||||
MySQLのUPDATE代入順によるTOTP失敗回数の差も修正し、3DB共通の5回制限を試験する。
|
||||
次はCOREbのCLI認証handoff/監査/group編集と完全な認可snapshot、DB-COREcの文書metadata/Revision/Path。
|
||||
管理UI接続、Domain削除・federationも残る。Domain削除は関連文書・拡張データを含めた移植後に行う。
|
||||
保存pilotをHTTP認証サーバーとして公開しない。
|
||||
ML後続はこの境界と整合させ、MySQL本体対応を宣言するのはDB-APP通過後とする。
|
||||
|
||||
2026-11-17、展示後の新サブプロジェクトは **AI向けpages-cliスキル → MCPサーバー →
|
||||
OpenAI Embeddings/Doc2VecによるCity整理** の順。
|
||||
[詳細設計・受入条件](ai-integration-and-city-organization.md)で AI-01、AI-02、
|
||||
CITY-SEM-01/02を追跡する。CLIスキル初版とPages Machine Learningの内部サービス基盤は
|
||||
ソース実装済み。MCP・文書抽出/ベクトル索引・自動整理UIは未実装。
|
||||
[ML運用・実装境界](../../operations/pages-machine-learning.md)のML-02以降でキュー/設定を接続する。
|
||||
2026-11-28:ML-02aのDomain別設定保存・世代付き競合検出・prefix除外・要求生成を追加。
|
||||
同日ML-02bとして管理API/UI、ML-02cとして日次入力byte予算の永続予約を追加。
|
||||
予算テーブルの本番適用、使用量表示・receipt保持方針、保存イベントへの接続は未実装。
|
||||
既存文書の推論は開始しない。
|
||||
下記2026-11-08の順序は過去の計画として保持し、既存の整合性・認可ゲートも維持する。
|
||||
|
||||
2026-11-08、利用者指定により、大きな機能を提供するサブプロジェクトを以下の順で進める。
|
||||
前案の小規模な回復・基盤改善を先に一巡する順序は、この順序へ置き換える。
|
||||
|
||||
@@ -103,15 +139,15 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
||||
| SHARE-01 / P2 | 未実装:委譲share URL、期限/失効/監査、説明可能な権限総覧 | AUTH-01、PUB-01。login/adapter/federation資格情報と別目的、単一Page投影、caveat・依存物の失効を検証 | [公開](publication.md)、[Schutzaria](schutzaria.md) |
|
||||
| COLLAB-01 / P2 | 一部実装:Page等の変更購読、最近閲覧/編集、集約通知。コメント/反応/評価は未実装 | OUT-01。現在権限で再投影、private履歴のopt-in/保持。inline commentはRevision変更時の孤立・再接続を扱う | [拡張](extensions.md) |
|
||||
| BLOG-01 / P2 | 一部実装:安全なtDiary import、最近コメント、遠隔ブログ射影 | COLLAB-01、遠隔はFED-01。importは再開/重複抑止/dry-run。同一instance射影を再実装しない | [ブログ・日記](blog-diary.md) |
|
||||
| CSV-01 / P2 | viewerのみ実装:別Documentを投影するCSV macro/editor、ODS境界 | 行列・セル・総量上限、Revision固定、権限、CSV引用/改行fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
||||
| DIAGRAM-01 / P2 | 一部実装:nwdiag/Draw.io provider、slide preview/editor | RENDER-01。安全なSVG・include拒否・renderer版固定、ticket/CAS保存、print。既存Excalidraw/Krokiとは分ける | [Kunstzeal](kunstzeal.md) |
|
||||
| CSV-01 / P2 | viewer・有界CSV macro・既存CSVの表編集/複数セル貼り付けを実装。残件:新規作成UI、大容量編集、矩形選択/範囲コピー、匿名投影、asset指定、ODS境界 | BOM/改行保持、25行描画、行列・セル・総量上限、貼り付けの一括検証/Undo、Revision CAS、権限、競合確認/履歴復元fixture。表示HTMLをCSV正本へ逆流させない | [表設計](extensions.md) |
|
||||
| DIAGRAM-01 / P2 | Reveal.jsビューア/編集プレビューを実装。残件:nwdiag/Draw.io provider、縦スライド・notes・専用print | RENDER-01。有界入力、sandbox、固定版ローカル同梱、ドメイン単位停止、Path認可。SVG・include拒否・ticket/CAS保存はprovider別に検証 | [Kunstzeal](kunstzeal.md)、[スライド](extensions.md) |
|
||||
| RECIPE-01 / P2 | 未実装:構造化レシピmetadataとPage投影の初期slice | 材料・数量・未知単位を保持、人数変更は派生値、Asset認可、版競合、出典・公開確認 | [料理レシピ](recipe-management.md) |
|
||||
|
||||
## D. 選定・別サブプロジェクト
|
||||
|
||||
| ID / 優先 | 状態・次の作業 | 着手ゲート・最初の検証 | 詳細 |
|
||||
| --- | --- | --- | --- |
|
||||
| RSS-01 / P2 | 一部実装:内蔵簡易正本、FreshRSS読取connector、3ペインUI・HTML本文、Wiki保存・タスク化・dashboard、OPML確認付き入出力 | 残件はFreshRSS既読/star書戻し、購読/カテゴリnavigation、実接続受入、公平性/backoff。managed schema feeds v3・隔離fixture。本番未反映。二重正本・停止時の自動切替なし | [RSS](feeds.md) |
|
||||
| RSS-01 / P2 | 一部実装:内蔵簡易正本、FreshRSS読取・既読/star書戻し、購読/カテゴリnavigation、3ペインUI・HTML本文、Wiki保存・タスク化・dashboard、OPML、配信時刻 | 残件は実接続受入、公平性/backoff、Gecko実機・運用受入。個別の実装/受入状況はRSS設計を参照。二重正本・停止時の自動切替なし | [RSS](feeds.md) |
|
||||
| IMAP-01 / P3 | 未実装・選定待ち:IMAP読取同期 | provider/認証/保持を決める。UIDVALIDITY/UID、添付量、外部画像、失効をfixture化。neomutt captureは実装済みで別 | [メール](mail.md) |
|
||||
| TICKET-01 / P3 | 未実装:queue/番号/workflow/外部依頼者 | 共有範囲と状態遷移を定義、同時採番・失効・監査。既存個人タスクをticketと呼び替えない | [タスクとticket](tasks-tickets.md) |
|
||||
| EXT-01 / P3 | built-inのみ:第三者manifest/署名/隔離runtime、停止・rollback・観測 | capability・secret・host・予算・export契約。任意コードをGoプロセス内へ直接ロードしない | [拡張](extensions.md) |
|
||||
@@ -126,7 +162,7 @@ P0は認可・整合性・復旧の安全条件、P1は日常利用の回復性
|
||||
- **HOLD-01**:`/tasks/` 配下のメールWikiルーティング調査。利用者の棚上げ指定を維持。関連未コミットファイルを今回の実装・文書コミットへ混ぜない。
|
||||
- **HOLD-02**:vim.wasm runtime改善とnativeアプリ起動。既存設定UIは残すが、自動的に再開しない。
|
||||
- **HOLD-03**:全面WYSIWYG、E6 CRDT/OT共同編集。まずEDIT-01と認可/presence契約、保存量・オフライン・競合モデルを確定する。
|
||||
- **HOLD-04**:本番への反映。作業履歴/日次メールのv3/v4移行を含む同世代保全と隔離復元試験、容量確認、SMTP副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
|
||||
- **HOLD-04**:本番反映は実装と別ゲート。[v0.15.0までの配備](../../operations/releases/2026-11-08-v0.15.0.md)は完了。追加変更には同世代保全と隔離復元試験、容量確認、外部副作用照合が必要。古いbinaryを新schemaへ向ける切戻しは禁止。
|
||||
|
||||
## 実装と分けて管理する受入
|
||||
|
||||
|
||||
@@ -111,7 +111,8 @@ Cache-Control: private, no-store
|
||||
- [ ] ディスクcacheの容量・TTL・清掃、renderer更新時の不整合、障害後の一時ファイル残留を管理する。
|
||||
- [ ] provider宛通信と描画サービス内の外部参照を分け、送信許可・接続先・ネットワーク隔離・バージョン固定を契約化する。
|
||||
- [ ] nwdiagの有界parser・安全なSVG出力・編集preview、Draw.io等のproviderを追加する。現在のregistryにnwdiagは実装されていない。
|
||||
- [ ] Reveal互換・HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
||||
- [x] Reveal.jsの有界ビューア・既存HTML/Markdownエディタ内previewをローカル固定版で接続する。Path認可・sandbox・ドメイン停止を持ち、正本への保存は既存エディタを利用する([スライド設計](extensions.md))。
|
||||
- [ ] Revealの縦スライド・発表者notes・専用print、HedgeDoc・Slidev・CSS-onlyスライドのimport/save/printを独立providerとして設計する。
|
||||
- [ ] Excalidrawのhosted/browser実行とPDF/動画サムネイル・metadata subprocessを、各々の安全境界を維持したまま段階的に接続する。
|
||||
|
||||
## 検証と反映
|
||||
|
||||
@@ -14,6 +14,14 @@ childrenは現在Pathを既定にし、表示形式は本文macroの `view` 引
|
||||
|
||||
`/v/tree/{path}` は範囲を限定します。展開・全展開・全折りたたみ状態の保持、複数選択、rename・移動・削除はPath操作と一致させます。一般の子一覧から予約ユーザー領域を混入させません。再帰操作は事前の全対象確認と競合検出が必要です。
|
||||
|
||||
## Browserのアップロード
|
||||
|
||||
`/v/browser/{path}` の一覧へファイルをドロップすると、現在のPath配下へアップロードします。フォルダ行へのドロップではそのフォルダが宛先になります。既存の内部Path移動・選択操作とは区別します。
|
||||
|
||||
右下のフローティングカードに待機・送信中・完了・失敗・取消と進捗を表示します。追加ドロップは同じキューへ積み、送信は1件ずつ、最大100件・各256 MiBまで。待機中の取消、折りたたみ、終了分のクリアに対応します。終了後は一覧だけを再取得し、キューは残します。
|
||||
|
||||
既存の認可付き `/v/upload` を使用し、`If-None-Match: *` で同名Pathの上書きを防ぎます。通信断は保存結果不明として扱い、自動再送しません。キューはページ内のみで、ページ離脱・再起動後の再開やフォルダの再帰アップロードには未対応です。新規オブジェクト・Path・初回Revisionの一体的なトランザクション化は残課題です。
|
||||
|
||||
## ホームとブックマーク
|
||||
|
||||
通常トップバー型、中央検索型、検索+セクションカード型を選びます。セクションは手動URL/Path、または指定親の子リンクを表示します。設定は歯車のポップアップで、閲覧画面を編集フォームで埋めません。カード列はviewportに適応します。
|
||||
|
||||
@@ -33,6 +33,10 @@ WebDAV/SSHFSの可変ファイルとimmutable CASは別です。最初はread-on
|
||||
|
||||
MWDB/Karton等の接続はpending/clean/suspicious/malicious/error/expiredの状態と、engine・版・hash・時刻・由来を持つ非同期処理を案とします。監査必須の範囲ではcleanがない間のviewer/download/adapterを閉じます。scannerへ機密本文を送る操作には別の送信方針が必要です。
|
||||
|
||||
2026-11-30:[ファイル検査と配信制御](file-inspection.md)へ詳細化。Path継承と追加判定、
|
||||
プラグイン契約・制限付き実行器を実装。DB・queue・配信ゲート・実エンジンは未接続で、
|
||||
現行アップロードを自動検査する状態ではありません。
|
||||
|
||||
## DRとHAの順序
|
||||
|
||||
次段階の詳細設計DR-D1は [役割・再参加](dr-authority-and-rejoin.md)、
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# オーガナイザーのナビゲーションと個人ダッシュボード
|
||||
|
||||
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。以下は2026-11-02のソース実装範囲で、2026-11-04にv0.7.0として本番へ反映した。移行・検証・復旧点は[本番反映記録](../../operations/deployments/2026-11-04-v0.7.0.md)を参照する。
|
||||
タスク・カレンダー・連絡先の入口を共通化し、個人設定と日々の振り返りを分離する。ダッシュボードは本人の作業を見る画面であり、サーバーの実行状態・リソース監視画面とは別に扱う。初期実装は2026-11-04にv0.7.0として本番へ反映した。2026-11-09の追加実装は、明日の予定・コマンドウィジェット、件名Markdown、参照欄、個人の外観設定。これらの追加分は本番未反映。
|
||||
|
||||
## 入口と設定の配置
|
||||
|
||||
@@ -10,13 +10,14 @@
|
||||
| --- | --- |
|
||||
| `/v/plan/dashboard` | ウィジェット形式の個人ダッシュボード |
|
||||
| `/v/plan/tasks` | 既存のインライン編集可能なタスク一覧 |
|
||||
| `/v/plan/tasks/index` | neomutt風のキーボード操作によるタスク一覧 |
|
||||
| `/v/plan` | 既存のカレンダー表示。保存されたビューを尊重 |
|
||||
| `/v/plan/contacts` | 個人アドレス帳・履歴・CardDAV接続 |
|
||||
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー |
|
||||
| `/-/sys/config?panel=organizer` | タスクの既定値、日次メール、既定のカレンダー、個人の外観 |
|
||||
|
||||
旧 `/v/plan/tasks/report` はダッシュボードの達成度ウィジェットへ、旧 `/v/plan/tasks/settings` は個人設定へ303リダイレクトする。カレンダーの表示選択ダイアログはその場の表示変更に使い、既定値の永続化は個人設定へ移す。
|
||||
|
||||
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer` の場合だけ個人向けハンドラーに振り分け、管理用設定やアカウント一覧は取得・描画しない。POSTの管理者チェックは緩和しない。保存先は既存の本人用APIであり、一般利用者に管理権限を付与しない。
|
||||
個人設定は通常の設定画面と同じURI体系・テーマを使うが、専用の軽量な画面として返す。GET/HEADかつ正確な `panel=organizer`、またはPOSTで `panel=organizer§ion=appearance` の場合だけ個人向けハンドラーに振り分ける。管理用設定のPOSTは従来どおり管理者を要求する。個人設定の保存は本人のactiveアカウントに限定し、管理権限を付与しない。
|
||||
|
||||
## タスク編集画面と通知既定値
|
||||
|
||||
@@ -26,6 +27,43 @@
|
||||
|
||||
760px以下では1カラムにし、主な入力と選択ボタンは44px以上のタッチ領域を確保する。個人設定には新規タスクの期限日・取り組む日のInbox通知と通知時刻を設ける。適用条件と既存データの扱いは[タスク通知](task-reminders.md)を参照する。
|
||||
|
||||
## キーボード操作のタスク一覧
|
||||
|
||||
`/v/plan/tasks/index` を既存のインライン編集とは別の表示として提供する。タスク画面の「キーボード一覧」から開く。左側はプロジェクト、右側は状態・件名・期限・取り組む日・優先度・関連Wikiの表。件名Markdownと選択行のテーマ色を使い、サブタスクは矢印で区別する。順序は指定ソートを優先し、親子の隣接は保証しない。
|
||||
|
||||
| キー | 操作 |
|
||||
| --- | --- |
|
||||
| `j` / `k`、上下矢印 | 次/前のタスクを選択 |
|
||||
| `Ctrl+j` / `Ctrl+k` | 次/前のプロジェクトへ表示を切り替え(所属変更ではない) |
|
||||
| `o` / `O` | ソート選択欄へ/昇順・降順を反転 |
|
||||
| `l` / `Esc` | 絞り込み欄へ/一覧へ戻る。絞り込みはEnterで適用 |
|
||||
| `d` | 選択タスクを完了。削除やアーカイブではない |
|
||||
| `s` | 選択タスクで25分Pomodoroを開始。実行中セッションは上書きしない |
|
||||
| `c` / `m` | 作成/既存の編集ダイアログを開く |
|
||||
| `w` | 関連Wikiへ移動。リンクがなければ案内し、暗黙に新規作成しない |
|
||||
| `?` | キーと絞り込み式のヘルプ |
|
||||
|
||||
入力欄、IME変換中、ダイアログ表示中にはショートカットを実行しない。更新系キーはキーリピートを無視する。作成時は選択中のプロジェクトを引き継ぎ、「すべて」では個人の既定値、「プロジェクトなし」では明示的な未所属とする。ブラウザやOSが予約しているキーをページ側へ渡さない環境では、同じ操作を画面のボタンから行う。
|
||||
|
||||
初期絞り込みは `~active`。複数条件はAND、`!` を条件の前に付けると否定する。OR・括弧・正規表現は扱わない。空欄はアーカイブ以外の全状態を表示する。
|
||||
|
||||
| 書式 | 意味 |
|
||||
| --- | --- |
|
||||
| `~s "リリース準備"` | 件名の部分一致。空白を含む値は引用符で囲む |
|
||||
| `~active` / `~todo` / `~doing` / `~done` / `~cancelled` | 未完了/未着手/着手中/完了/取りやめ |
|
||||
| `~overdue` | ドメインの今日より前に期限を迎えた未完了タスク |
|
||||
| `~due <=today` / `~planned tomorrow` / `~start >=2026-11-01` / `~review <today` | 期限・取り組む日・着手日・見直す日。日付はYYYY-MM-DD、today、tomorrow。比較は `= < <= > >=` |
|
||||
| `~due none` | 日付なし。planned、start、reviewにも使用可能 |
|
||||
| `~bucket inbox` / `~bucket backlog` / `~bucket someday` | 整理先 |
|
||||
| `~priority 3` | 優先度0〜3の一致 |
|
||||
| `~wiki` / `~attachment` / `~archived` | 関連Wikiあり/URL・Path参照あり/アーカイブ済み |
|
||||
|
||||
例:`~s "リリース" ~doing !~overdue`。プロジェクト・条件・ソートはURLクエリへreplaceStateで保持し、操作ごとに履歴エントリを増やさない。
|
||||
|
||||
取得は既存 `items` APIの `view=index`。`filter`、`sort`(due/planned/title/status/priority/created/updated)、`order`(asc/desc)、`project`、`before`を使う。未所属は `project=none`。サーバーで対象全体を絞り込み・ソートして100件ずつ取得し、末尾での下移動または追加読込で次を取得する。ソート値とUUIDによる順序を使い、他ユーザーのカーソルから内容を返さない。日付未設定は昇順の末尾、完全な逆順では先頭になる。並行更新時の固定スナップショットではないため、再読込で最新状態を確認する。
|
||||
|
||||
条件は1000バイト・最大64トークン。SQLは値をバインドし、ソート列は許可リストから選ぶ。不正条件は422で、旧表示を残して操作ボタンを無効化する。プロジェクトも検索・50件単位の追加読込とし、一括取得しない。完了は表示時のversionをIf-Matchで送る。別更新があれば412で止め、メモ等を最新取得しても古い選択行からの更新を無条件に通さない。本人の権限・読み取り専用制限は既存APIに従う。この一覧追加にDBスキーマ変更はない。
|
||||
|
||||
## ウィジェット
|
||||
|
||||
初期構成は次の6種類。任意のHTML・iframe・外部URL・スクリプトを登録する機能ではなく、サーバーが許可する組み込みIDを使う。
|
||||
@@ -39,13 +77,15 @@
|
||||
| `schedule` | 既定カレンダーにある今日の予定 |
|
||||
| `activity` | 完了数・ポイント・作業時間・集中時間、日別ヒートマップ |
|
||||
|
||||
追加メニューには `feeds`(RSS)、`tomorrow-schedule`(明日の予定)、`commands`(タスクコマンド)も用意する。既存の保存済み配置に自動追加せず、追加後に「配置を保存」で確定する。予定は時刻範囲・件名・カレンダー名をカード状に配置し、開催中の予定を強調する。終日予定は時刻の代わりに「終日」を表示する。
|
||||
|
||||
タブはウィジェットの枠内で内容を切り替える。iframeを使わず、ページやブラウザ履歴を移動しない。タスク件名や右上の矢印は既存の詳細・一覧へ移動する。タスクの編集操作は従来の一覧・詳細画面を利用する。
|
||||
|
||||
達成率の分母は `planned_on=今日`、分子はそのうち `status=done` の件数。取りやめ・アーカイブ・プロジェクトを除く。日付はドメインのタイムゾーンで判定する。対象0件は100%でなく「—」を表示する。期限超過を含む「本日のタスク」の件数とは意図的に異なり、画面に定義を明記する。ヒートマップのポイント計算は[タスクの集計契約](task-productivity-contacts.md)に従う。
|
||||
|
||||
## 配置と保存
|
||||
|
||||
デスクトップは12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
||||
デスクトップは画面幅いっぱいの12列グリッド。幅は3〜12列、高さは2〜10単位、1単位の表示基準は72pxと12pxの間隔。順序に従ってグリッドへ配置するため、幅の組み合わせによって空白が生じる。任意の絶対座標を保持するレイアウトではない。
|
||||
|
||||
歯車で配置モードを開き、ハンドルのドラッグで並べ替え、右下のハンドルでサイズを変える。矢印ボタンと幅・高さの選択欄でも同じ操作が可能。追加・除去・初期配置への復帰に対応し、「配置を保存」で確定する。タブの選択も配置の一部として保存できる。未保存の離脱を警告し、保存失敗・競合時には編集中の配置を残す。ブラウザ再起動をまたぐ未保存レイアウトの下書きは持たない。
|
||||
|
||||
@@ -69,6 +109,28 @@ APIは `/_/api/v1/extension/organizer.tasks/` 配下。
|
||||
|
||||
## 検証と後続範囲
|
||||
|
||||
### タスク表示と参照
|
||||
|
||||
件名の保存形式は文字列のまま。Web一覧では太字、斜体、取り消し線、インラインコード、リンクのラベルをDOMで描画する。HTML・画像・マクロを実行しない。インライン編集のフォーカス中はMarkdownソースをそのまま入力できる。関連Wikiがある行は塗りつぶした文書アイコンとテーマ色で区別する。
|
||||
|
||||
`TaskRecord.references` はURLまたはWiki Pathの配列(最大20件、1件4096バイト)で、タスクの編集画面の詳細設定から変更する。http/httpsと同一サイトの絶対Pathだけを認め、認証情報入りURL・プロトコル相対URL・制御文字は拒否する。リンク先の取得や公開範囲の変更は行わない。Path参照は文字列のためrenameには追従しない。rename追従が必要な主たる関連Wikiには従来の `page_uuid` を使う。
|
||||
|
||||
正本JSONと変更履歴に参照を保存し、タスクの列追加は不要。旧CLI等がこのフィールドを省略した更新では既存値を維持し、明示的な空配列で解除する。CalDAV更新でも維持するが、VTODOのATTACHへの投影は後続範囲。
|
||||
|
||||
### タスクコマンド
|
||||
|
||||
`add task 件名`、`today UUID`、`tomorrow UUID`、`due UUID YYYY-MM-DD`、`due UUID clear`、`done UUID`、`delete UUID` を提供する。対象は件名検索のサジェストから選ぶとUUIDが入る(250ms debounce、最大10件)。シェルコマンドではない。追加は個人の既定値を読み、通信失敗時は同じUUIDで再試行できる。既存タスクへの操作は取得時のversionをIf-Matchで送信し、競合時は上書きしない。削除は件名を確認してから実行する。今日・明日はダッシュボード読込時のドメイン日付を基準とする。
|
||||
|
||||
### 個人の外観とログイン画面
|
||||
|
||||
壁紙Path・不透明度・グラス透明度・壁紙からの色抽出を個人設定へ追加する。トップ画面の歯車も同じ本人用保存先を使う。初回は既存のドメイン設定を初期値として引き継ぎ、保存後は個人値を優先する。空の壁紙Pathは「壁紙なし」。フォルダ選択時は従来どおり閲覧可能な直下の画像から選ぶ。
|
||||
|
||||
`personal_appearance` はDomain UUIDと本人UUIDを複合キーにしたJSON+versionのテーブル。起動時の設定テーブル初期化で追加する。既存テーブル・正本を破壊せず、保存はversion比較で競合409を返す。タスク既定値・メール同意のversionを変更しない。ドメイン設定画面の外観項目は初期値用として区別する。
|
||||
|
||||
ログイン画面は壁紙なしとし、旧 `/_/auth/wallpaper` は404を返す。個人・ドメインのトップ壁紙をログイン前に公開しない。別のログイン専用背景Pathは今回追加しない。
|
||||
|
||||
### 回帰検証
|
||||
|
||||
合成データで、所有者分離、CAS、読み取り専用、匿名拒否、管理設定への権限拡大がないこと、空配置、禁止ウィジェット、メール設定の不変、今日の集計・予定範囲を検証する。ブラウザではデスクトップとスマホの導線、タブ、設定保存、配置保存、横はみ出しを確認し、デスクトップのドラッグ・リサイズには実ポインター入力を使う。本番の外部取り込みカレンダーは検証に使わない。
|
||||
|
||||
次段階は以下を別途設計する。
|
||||
|
||||
@@ -23,6 +23,12 @@
|
||||
|
||||
### 3. テーマ・アカウント・連絡先
|
||||
|
||||
- [x] 信頼できる端末の長期ログイン(2026-11-08ローカル実装、本番未反映):ログイン画面の明示選択で最大30日。Domain管理者は設定→セッションで0〜30日(0で無効)を指定する。通常ログインは既存の絶対期限を維持。パスワード/TOTP、LDAP、OIDC、SMTPマジックリンクに適用し、選択は認証challengeに固定する。CookieとBearerの期限はDBの発行期限と一致し、ログアウト・管理者失効・アカウント停止で無効になる。既存セッションの延長、TOTPの省略、アクセスによる期限延長は行わない。
|
||||
- [x] 独立CLIの `pages login --remember` / `pages login --oidc --no-browser --remember`。S256 grantに選択を保存し、ブラウザ側のクエリで上書きできない。APIセッションは承認元ブラウザの残存期限を超えない。期限切れ後はlogoutなしで再認証でき、同一アカウントのcwdと未送信タスク下書きを保持する。別アカウントへの下書き移動は拒否する。旧サーバーは選択を無視する場合があるため、実際の期限は応答のexpires_inを正とする。
|
||||
- [x] タスク編集フッターの関連ページ導線(2026-11-08ローカル実装、本番未反映):アーカイブ・削除・保存と同じ並びに関連ページリンクを表示。新規タブで開き、編集中の内容を保持する。保存済みの関連Pageがない場合、解除した場合、Path変更が未保存の場合は非表示。デスクトップ/モバイル4幅のブラウザテストを追加。
|
||||
|
||||
長期ログインのDB変更はmanaged component `cli-auth` v2の `remember` 列追加のみ。既存行はfalse、既存セッションと文書・タスクデータは変更しない。端末名・一覧・個別端末の信頼登録、refresh token rotationは別設計とし、今回は既存セッション管理から失効する。
|
||||
|
||||
- [x] 共通ナビの◐からプリセットを選択、リロードせず切替。host限定Cookieに保持し、Domain既定に戻せる。登録済みテーマのみ許可。Domain設定/アカウントの全端末設定ではなくブラウザ上書き。失敗時は現在テーマを保持する。
|
||||
- [x] 絶対セッション期限:設定→セッション、5〜43200分、既定1440分。Domain単位で新規ブラウザ/APIログイン(OIDC/LDAPを含む)に適用。発行時にDBの期限を固定し、Cookie/APIのexpires_inにも反映。既存セッションの期限とCalDAVアプリパスワードは変更しない。管理者認可とサーバ側失効をfixture検証。
|
||||
- [ ] 無操作タイムアウトとアカウント別の短縮上書き:background pollingを人間の操作とみなさないactivity契約、再認証、既存セッションへの即時適用を別途設計する。
|
||||
|
||||
@@ -26,6 +26,14 @@ v0.3.0のOIDCログインは利用者の動作確認済み。v0.4.0ではOIDC承
|
||||
|
||||
## 利用方法
|
||||
|
||||
### 信頼できる端末でのログイン継続
|
||||
|
||||
2026-11-08ローカル実装、未リリース。独立CLIと対応サーバーを更新すると、`pages login --remember` または `pages login --oidc --no-browser --remember` で最長30日のセッションを要求できる。管理者の `auth_trusted_session_days`(既定30、0で無効)に従い、応答の `expires_in` を期限として保存する。旧サーバーでは通常の期限になる場合がある。
|
||||
|
||||
パスワードログインは必要なTOTPを維持する。選択はTOTP challenge/OIDC grantへ固定し、認証完了時の追加パラメーターで変更できない。CLI grantはmanaged component `cli-auth` v2で `remember` 列を追加し、既存行をfalseとして保持する。承認済みgrantの交換とセッション発行は従来どおり単一トランザクションで処理し、期限は承認元ブラウザの期限を超えない。
|
||||
|
||||
ローカル期限切れ後は `logout` を挟まず再ログインできる。同一アカウントならcwdと未送信タスク下書きを保持し、認証失敗時は従来のローカル状態を変更しない。ログアウト・管理者による失効・アカウント停止は長期セッションにも適用する。共有端末では使用しない。
|
||||
|
||||
```sh
|
||||
# 初回設定。パスワードはlogin時の非表示プロンプト、必要ならTOTPを続けて入力。
|
||||
pages configure --origin https://pages.example.test --username anya
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# 20. 実装順序と受け入れ条件
|
||||
|
||||
2026-11-17追記:展示後の優先順は **AI向けCLIスキル → CLI不要のMCP →
|
||||
OpenAI Embeddings/Doc2VecによるCity整理**。
|
||||
[新サブプロジェクト](ai-integration-and-city-organization.md)と[残件台帳](implementation-backlog.md)を参照。
|
||||
Pages Machine Learningの独立サービス基盤を先行実装。既存PagesのDB変更・自動索引化は未実施。
|
||||
以下の日付付き計画は履歴として残す。
|
||||
|
||||
状態:2026-11-08再照合。旧Phase番号は原ロードマップとの対応用に残し、実装は依存関係とリスク順に進めます。
|
||||
|
||||
現在の作業単位・優先順・受入条件は[実装残件台帳](implementation-backlog.md)に集約しました。
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# スライドショーの再生制御
|
||||
|
||||
状態:ソース実装とブラウザ検証済み。本番未反映。
|
||||
|
||||
pagesのスライドビューアとエディタのスライドプレビューに、再生/一時停止、ページ送り間隔、ループを設ける。正本本文やRevision、公開範囲は変更しない。
|
||||
|
||||
## 操作と時間
|
||||
|
||||
- 初期状態は停止、間隔30秒、ループなし。
|
||||
- 間隔は整数の1〜3600秒。範囲外や空欄では新しい再生設定を送らない。
|
||||
- 再生中にページを手動で切り替えると、次の送りまでの時間を設定秒数から数え直す。
|
||||
- ループなしでは最終ページを設定秒数だけ表示して停止する。停止後、最終ページで再生すると先頭から開始する。
|
||||
- ループありでは最終ページから先頭へ戻る。
|
||||
- ブラウザの非表示中はタイマーを停止し、再表示後に設定秒数から再開する。非表示時間分をまとめて送らない。
|
||||
- 同じプレビューを再描画する間は位置と再生設定を保持する。再読み込み後は停止に戻り、ブラウザへの永続設定保存は行わない。
|
||||
|
||||
ブラウザのタイマーは厳密な実時間保証ではない。表示中の10枚を30秒ずつ送る場合、通常動作で約5分となる。発表者による手動送りやタブの非表示時間は含めない。
|
||||
|
||||
## 信頼境界
|
||||
|
||||
親画面の操作部だけが再生設定を作り、sandbox iframeの固定スクリプトへ送る。iframe側は送信元がparentであること、描画ごとのtoken、固定message type、整数秒数とbooleanの型・範囲を検査する。親側も通知元のWindowとtokenを確認する。本文のdata属性、script、style、任意iframeは引き続き許可しない。
|
||||
|
||||
自動再生に認可権限はなく、読める本文の範囲は既存のPath認可に従う。ブラウザ履歴やURL hashを更新しない。ページを離れればiframeとタイマーを破棄する。全画面でも親の操作部を表示し、停止可能にする。
|
||||
|
||||
## 5分の技術紹介資料
|
||||
|
||||
編集元は `docs/presentations/pages-architecture-5min-ja.md`。10枚、30秒送りを目安にする。図の編集元は `static/diagrams/pages-architecture/*.svg`。構成・identity・City・保存順序を同じ配色で示し、残りは表と短い文章で説明する。
|
||||
|
||||
| 経過時間 | 内容 | 説明の焦点 |
|
||||
| --- | --- | --- |
|
||||
| 0:00〜0:30 | pagesの狙い | 知識の住所と実体を分ける |
|
||||
| 0:30〜1:00 | 全体構成 | Go・SQLite・Document Store・背景処理 |
|
||||
| 1:00〜1:30 | identity | Path変更と複数参照で履歴を複製しない |
|
||||
| 1:30〜2:00 | Knowledge City | 階層の案内と追加参照のグラフを両立する |
|
||||
| 2:00〜2:30 | 保存 | Documentを先に永続化し、期待headを照合する |
|
||||
| 2:30〜3:00 | Projection | 表示・編集形式を別正本にしない |
|
||||
| 3:00〜3:30 | 認可と実行 | identity、read、publication、script実行の境界 |
|
||||
| 3:30〜4:00 | 日々の作業 | タスク・DAV・RSS・メールとWikiを関連付ける |
|
||||
| 4:00〜4:30 | 運用 | 前景優先、設定配信と記事複製の区別、単一writer |
|
||||
| 4:30〜5:00 | まとめ | identity、探索、境界の維持 |
|
||||
|
||||
内容の根拠は `principles.md`、`address-storage.md`、`knowledge-city.md`、`viewer-editor.md`、`auth-permissions.md`、`publication.md`、`scheduler-resources.md`、`campus-federation.md`、`operations.md` とオーガナイザーの詳細契約。初期構想のMacaroon共有・任意プラグイン・自動HAを実装済みとして扱わない。
|
||||
|
||||
静的図版を含むアプリの反映後に、HTML化した5分版を既存の24枚版とは別Pathへ配置する。図版未配信の状態で既存の資料を置き換えない。
|
||||
@@ -53,7 +53,7 @@ UUID検索は追加せず、既存のタスク編集画面で「アーカイブ
|
||||
|
||||
### 削除済みメール取り込みの再作成
|
||||
|
||||
PagesWiki v0.14.1/pages-cli v0.4.2向け実装。サーバーとCLIの両方の更新が必要です。DBスキーマ変更や既存データの削除はありません。
|
||||
PagesWiki v0.14.1/pages-cli v0.4.2で実装、2026-11-08 19:42 JSTに本番反映済み。[配備記録](../../operations/releases/2026-11-08-task-capture-recovery.md)。サーバーとCLIの両方の更新が必要です。DBスキーマ変更や既存データの削除はありません。
|
||||
|
||||
`POST /_/api/v1/extension/organizer.tasks/capture` は、受付記録に対応するタスクの状態を本文ハッシュより先に確認します。削除済みなら同じ内容・異なる内容とも410 `deleted`。タスクと削除記録が両方欠落していれば409 `capture_missing` とし、自動修復・再作成はしません。存続中のタスクへの異内容再送は従来どおり412です。
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 保存基盤の多様化と運用機能の統合
|
||||
|
||||
状態:詳細設計・段階導入。2026-09-27。
|
||||
状態:詳細設計・段階導入。2026-11-15 更新。
|
||||
本書は [基本設計](arch.md) と [拡張契約](platform-extension-architecture.md) を補完する。
|
||||
各 TODO は実装済みを意味しない。本番 DB・保存先の移行は別途承認する。
|
||||
|
||||
@@ -384,6 +384,35 @@ setup 完了後は token 再利用不可。機密欄の再表示・ログ出力
|
||||
|
||||
### S2:外部 backend
|
||||
|
||||
- [x] PostgreSQL 接続層と独立した migration runner(アプリの backend 切替は未接続)。
|
||||
- [x] Object/Path/Revision/Asset の共通 metadata Repository と空 DB 用スキーマ、SQLite/PostgreSQL 共通契約テスト。
|
||||
- [x] 既存 Store の Campus/Domain 取得・ホスト解決・ドメイン別設定・Campus 作成/更新の native SQL 移植と共通契約テスト。
|
||||
- [x] 管理者グループの初期化・メンバー更新・継承切替・projection・派生所属とセッションの失効を共通 SQL と transaction に移植。
|
||||
- [x] 一般グループの作成・一覧・メンバー一覧・Path 権限設定、直接 Role binding と Group 権限の付与判定、Principal 状態更新と失効を共通 SQL に移植。
|
||||
- [x] 初回 owner・パスワードアカウント・プロフィール・セッション管理、TOTP、外部認証の設定と Identity 紐付け、CLI 認証引き継ぎの DB 処理を移植し、SQLite/PostgreSQL 共通契約テストを追加。
|
||||
- [x] 認可と読み取りナビゲーションの Locality 制限、City 所有者・公開範囲の上限制約、ユーザー/グループ ACL 更新、保護 Path/City 構造の DB ガードを移植。
|
||||
- [x] 公開 manifest・自動公開・匿名 navigation、承認要求、ユーザー領域とプロフィール連絡先の公開制御を native SQL に移植し、共通 DB テストを追加。
|
||||
- [x] Domain 作成/更新/削除と Campus 削除、管理者継承、連携トークン・instance 登録・署名 manifest の DB 処理を移植。
|
||||
- [x] 通常 Revision 保存・履歴取得・履歴復元の Store 境界と HTTP 呼び出しを native metadata Repository に接続し、合成データで保存・競合・故障時の rollback を検証。
|
||||
- [x] Path の再帰移動・コピー・snapshot 付き一括削除、alias/primary link と navigator の DB 処理を移植。
|
||||
- [x] City map・所属 Page・Path context・health・監査履歴の取得、タイトル・境界変更、Spot 整理(移動・統合)を移植。
|
||||
- [x] Asset の一覧・参照・履歴、作成/更新・復元・削除を移植し、楽観ロックと履歴保存失敗時の rollback を検証。
|
||||
- [x] City の個別作成・配置・relation・再帰削除、一括変更計画の preview/apply、自動生成候補と名前競合の問い合わせを移植。
|
||||
- [x] Browser・children・Path 補完・権限付き Object metadata 一覧を移植し、native canonical HTML の H1 と複数 Store 間の children cache 失効を検証。
|
||||
- [x] アーカイブ import のセッション・計画・journal・Path rollback を移植。全 DB の SQLite→PostgreSQL インポートとは別機能。
|
||||
- [x] タスク・プロジェクトの保存/取得/履歴/階層付き一覧/削除、DAV resource・collection・資格情報・既定リスト名の Store 操作を移植し、両 DB で契約を検証。
|
||||
- [x] タスク個人設定、作業時間の開始・終了・訂正・取消と監査履歴、Pomodoro と日次集計、ダッシュボード配置・達成率、予定枠の DB 予約を移植。
|
||||
- [x] 通知 Inbox の保存・重複排除・取得・既読、期限/着手日の通知配信、タイマー完了、活動 journal の outbox 補完処理を移植。scheduler と Push 配信は別途接続する。
|
||||
- [x] タスク capture と Wiki 同時作成、削除後の明示的再作成、プロジェクト配下のメモ作成を移植。受付記録・本文参照・Path・outbox の原子性を検証。
|
||||
- [x] 日次メールの送信予約、本人の同意・権限確認、送信履歴、明示的再試行、保持期限処理を移植。SMTP worker と scheduler は別途統合する。
|
||||
- [x] カレンダーの再構築可能な月別索引、予定の取得・更新・削除、DAV resource 操作、タスク予定枠と日次予定の cache 参照を移植。正本 ICS と manifest の形式は維持する。
|
||||
- [x] 連絡先の保存・検索・削除・履歴復元・export、CardDAV の resource 名・差分同期・metadata inventory と資格情報失効を移植。
|
||||
- [x] ブログ・日記の設定、記事作成・登録・解除・一覧、投稿受付の重複排除、公開タイトルと別 Domain への射影設定を移植。本文と埋め込み Asset 参照の固定、監査失敗時の rollback を検証。
|
||||
- [x] RSS/FreshRSS の購読元・既読/スター・記事 cache・分類・購読 import・Wiki 取り込みと受付記録、外部操作の claim・確認・履歴を移植。scheduler 登録は別途接続する。
|
||||
- [ ] 通常 HTTP/scheduler/CLI 起動を経由した認証・公開・federation の PostgreSQL 統合試験。
|
||||
- [x] 読み取り専用の移植診断 CLI と、対応済み core の catalog / 履歴検査。
|
||||
- [x] 停止状態の core SQLite→PostgreSQL→SQLite 往復リハーサル、内容指紋・採番・参照・Document の検証。
|
||||
- [ ] Object/Path/Revision/Asset の全 Store 操作と関連正本更新の接続、既存 DB 移行、共通統合テスト。
|
||||
- [ ] PostgreSQL の全 repository 移植と SQLite との共通機能テスト。
|
||||
- [ ] MySQL の DDL/索引/照合順序/同時書き込み試験。
|
||||
- [ ] S3 adapter と互換サービスで range/条件付き作成/破損/切断/容量制限を検証。
|
||||
@@ -391,6 +420,790 @@ setup 完了後は token 再利用不可。機密欄の再表示・ログ出力
|
||||
- [ ] Redis cache adapter と停止時の制限付き縮退、policy epoch による失効。
|
||||
- [ ] mutable canonical CAS と metadata 参照の回復プロトコル、HA の fencing。
|
||||
|
||||
#### PostgreSQL 対応の実装順序
|
||||
|
||||
2026-11-14 時点では `internal/db.OpenPostgreSQL` と
|
||||
`ApplyPostgreSQLMigrations` を追加した。既存の `Open`、`Migrate`、通常の Store 初期化、
|
||||
通常起動、DR、CLI は引き続き SQLite 用であり、PostgreSQL を本番選択可能にはしない。
|
||||
利用者の DB を自動変換せず、既存 migration の checksum も変更しない。
|
||||
|
||||
接続には pgx の database/sql 実装を使用し、DSN はインスタンスの秘密設定として扱う。
|
||||
既定で検証付き TLS と平文 fallback の禁止を要求する。開発専用の
|
||||
`AllowInsecure` を明示した場合だけ非検証接続を許す。接続確認の timeout、
|
||||
pool の上限、connection の寿命を設け、失敗時は pool を閉じる。
|
||||
エラーは SQLSTATE と操作名だけを公開し、DSN、SQL、サーバの詳細メッセージや
|
||||
constraint 内の個人情報をエラー文字列へ含めない。
|
||||
|
||||
PostgreSQL 用 migration は SQLite の SQL 自動翻訳ではなく、独立した append-only 定義とする。
|
||||
BIGINT の epoch ms、ネイティブの `$1` 引数、明示した conflict target を使う。
|
||||
runner は READ COMMITTED transaction と共通の transaction-level advisory lock で
|
||||
ledger の初回作成を含めて直列化する。異なる component にも同じロックを使う。
|
||||
DDL、checksum 履歴、最新 assertion の検証を同じ transaction に含め、
|
||||
失敗時は rollback、正常終了時は commit と同時にロックを解放する。
|
||||
未知の新しい履歴、欠けた version、変更された定義は適用を停止する。
|
||||
|
||||
| 順序 | 範囲 | 完了条件 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 接続と migration | 実 PostgreSQL で並行適用、rollback、履歴不一致、lock 待ちキャンセルを検証 |
|
||||
| 2 | Object/Path/Revision/Asset | Domain 分離、UUID 不変性、revision 保存、再帰 rename、hash 参照の SQLite 共通契約を通過 |
|
||||
| 3 | 認証と ACL | ユーザー、グループ、セッション、公開範囲の共通契約を通過 |
|
||||
| 4 | タスクと CalDAV | プロジェクト所属、VTODO、ETag と競合更新、通知を検証 |
|
||||
| 5 | ジョブと通知 | claim token、lease、row lock、outbox と重複処理耐性を検証 |
|
||||
| 6 | City と検索と管理 | rowid/PRAGMA/FTS5 依存を分離し、安定した順序・検索・schema 診断を検証 |
|
||||
| 7 | 既存データ移行と運用 | 停止状態の export/import、件数・参照・hash 検査、restore rehearsal、起動設定と readiness を接続 |
|
||||
|
||||
#### 既存 Store の Campus と Domain と設定の移植
|
||||
|
||||
`internal/store` に backend を保持し、既存 API から native PostgreSQL の SQL を使える
|
||||
経路を追加した。既定値は SQLite とし、従来の Store constructor と最小 fixture の
|
||||
振る舞いを維持する。SQL の `?` を一括変換せず、query 構築時に placeholder を生成する。
|
||||
ホスト名の判定は SQLite の `instr` と PostgreSQL の `strpos` を明示的に分ける。
|
||||
|
||||
移植済みの範囲は次のとおり。
|
||||
|
||||
- Campus の既定値取得、UUID 取得、一覧、作成と更新。
|
||||
- Domain の既定値取得、UUID 取得、一覧、件数、Host 解決、実効 FQDN の取得。
|
||||
- Domain ごとの設定の取得と UPSERT。欠けた設定は従来どおり空文字とし、更新時刻は既存の秒単位を維持。
|
||||
- 既存 Store の Path 解決で backend を選択し、Domain が local であることを確認して共通 Repository を呼ぶ。
|
||||
|
||||
Campus の FQDN と Domain の相対ホスト名・FQDN 指定を同じ規則で解決する。
|
||||
未知の Host を既定 Domain へ fallback せず、無効な Campus/Domain と remote Domain の
|
||||
ローカル名前空間へのアクセスを既存の取得規則に従って拒否する。
|
||||
Campus 作成・更新では、移植済み writer が同じ namespace lock を使う範囲で、
|
||||
ホスト名競合の検査と書き込みを一つの transaction に入れる。
|
||||
PostgreSQL では同一 DB の advisory lock、SQLite では書き込みロックを検査前に取得する。
|
||||
transaction の期限とキャンセルは内部の SQL 呼び出しまで伝搬する。
|
||||
|
||||
Domain/Campus の context 付き取得 API を追加し、HTTP のリクエスト単位の Host 解決でも
|
||||
request context を利用する。PostgreSQL の SQL/driver/Scan エラーから個人情報や設定値を
|
||||
出力しないようにし、入力フォームへ返せる固定の validation message は区別して保持する。
|
||||
|
||||
PostgreSQL の初期スキーマは `store-namespaces` migration として独立させる。
|
||||
対象は `campuses`、`domains`、`config`、`personal_appearance` のテーブル定義と索引であり、
|
||||
後者の個人外観 API の移植まで完了したという意味ではない。
|
||||
既知の列不足や適用済み定義の不一致は停止し、既存 SQLite の ALTER/adopt 処理は流用しない。
|
||||
既定 Campus/Domain の初期化は transaction で直列化し、並行実行時の重複と関連付けの欠落を防ぐ。
|
||||
これは旧インスタンスの全データを取り込む import 処理ではない。
|
||||
|
||||
Domain 作成・更新は Campus/実効 Host/配置先の検査、Domain 本体、既定 locale、
|
||||
管理者グループ作成と所属 projection を同じ管理用 writer lock と transaction に含める。
|
||||
同じ実効 Host の同時作成は一つだけ成功し、別 Campus への移動は旧 Campus 由来の管理者権限を取り消す。
|
||||
依存テーブルや projection の障害時は Domain と設定も rollback する。
|
||||
Domain/Campus 削除の参照・最終要素検査も transaction 内で実施する。
|
||||
Campus 削除では連携 token、instance と capability、署名 manifest の checkpoint も削除する。
|
||||
|
||||
`store-federation` は token hash、instance identity、manifest 採番と受信 checkpoint を保持する。
|
||||
登録と token 失効は同じ lock を使用し、登録後に失効済み token を再利用できない。
|
||||
署名の検証後、初回 controller fingerprint の固定、旧 revision と同一 revision の異なる内容の拒否、
|
||||
受信 Campus/Domain/管理者継承と checkpoint の保存を一つの transaction で扱う。
|
||||
`store-domain-entry` は manifest v2 の許可済み entry 設定と日記/ブログの有効化・prefix を保持する。
|
||||
これは日記/ブログ本文の新規作成・検索・projection repository 全体の移植完了ではない。
|
||||
|
||||
現時点の PostgreSQL Store は component 統合テスト内でのみ構築する。
|
||||
本番用 constructor と起動フラグはまだ解放せず、通常のサーバーは SQLite のままとする。
|
||||
core 限定インポートの対象も拡張しておらず、namespace を含む DB は引き続き対象外として拒否する。
|
||||
|
||||
#### 認証と管理者グループの移植
|
||||
|
||||
`store-auth-foundation` の native migration は Principal、Identity、Domain membership、
|
||||
Role、直接 Role binding、Capability grant、Group、Group member と Campus 管理者継承の
|
||||
provenance を定義する。アバターは BYTEA、時刻は BIGINT の Unix milliseconds、
|
||||
識別子と一意制約の比較は C collation とする。既存テーブルの暗黙の取り込みや修復は行わない。
|
||||
適用済み migration の列検査が失敗した場合も既存 Principal を保持したまま停止する。
|
||||
|
||||
既存 Store の `IsBuiltinGroupAdmin` と `IsCampusAdmin` は SQLite と PostgreSQL の
|
||||
両方で動作する。context 付き API は SQL エラーと拒否を区別し、従来の bool API は
|
||||
DB 障害時も権限を与えない。Domain と membership の対応、Principal・membership・Group
|
||||
の有効状態、Domain の enabled、owner/manager role を同じ SQL で検査する。
|
||||
SQLite と実 PostgreSQL の共通テストで状態変更、越境所属、キャンセル、DB 障害を検証する。
|
||||
|
||||
`EnsureBuiltinAdminGroups`、メンバーの追加・更新・削除、`SetCampusAdminInheritance`、
|
||||
`ProjectCampusAdminMemberships` は両 DB 共通の実装を使う。
|
||||
グループの名前・UUID による取得と member role の参照も backend に対応する。
|
||||
PostgreSQL では namespace 更新と同じ advisory lock、SQLite では読み取り前の
|
||||
DB writer lock を使い、元の grant 更新と継承先の再計算を同一 transaction に含める。
|
||||
context 付き API の期限は内部の SQL まで伝搬する。
|
||||
|
||||
継承の入力は独立した grant に限り、派生 grant を新たな継承元にしない。
|
||||
複数の継承元のうち最も強い role を実効値とし、継承解除時には弱いローカル role が再び現れる。
|
||||
派生した membership のみを追跡し、独立した group/role binding で採用済みの所属と session は保持する。
|
||||
派生権限しかない所属は削除し、その Domain の session を同じ transaction で失効する。
|
||||
再有効化しても失効済み session は復活させない。
|
||||
最後の独立 owner の並行削除、継承先での inherited-only grant 削除、owner の通常更新による降格は拒否する。
|
||||
Role からの初期 grant は記録済みの migration marker で再投入を防ぎ、明示的に取り消した権限を
|
||||
再起動で復活させない。Domain の異なる Role binding と別 Domain を指定する manage grant は初期 owner にしない。
|
||||
|
||||
native migration の v2 には失効処理に必要な `auth_sessions` と索引を追加する。
|
||||
管理者継承の共通テストは合成 session 行で取り消しと保持を検査し、
|
||||
projection 後半の故障注入でメンバー追加・削除・継承切替のすべてが rollback することを確認する。
|
||||
|
||||
一般グループの作成は owner の有効な Domain membership と active な Principal を確認し、
|
||||
Group、owner member、派生 membership の独立所属への採用を同一 transaction に含める。
|
||||
一覧の `domain` visibility は単に Principal UUID があるだけでなく、その Domain で有効な所属を要求する。
|
||||
`members` visibility とメンバー一覧、role 参照、Path 権限評価でも membership の Domain 一致を検査する。
|
||||
別 Domain の不正な owner 行を最後の独立 owner の代わりに数えない。
|
||||
一覧は EXISTS で重複を避け、表示名・名前・UUID による安定順を持たせる。
|
||||
|
||||
native migration の v3 は `group_permissions` とメンバーの Identity 参照用索引を追加する。
|
||||
権限設定は既存 Group を要求し、同じ Group/Path の設定を upsert する。
|
||||
`read`、`read_write_once`、`read_write`、`upload_only` の既存 capability と literal Path 境界を保持する。
|
||||
SQL の `%` と `_` を wildcard として扱わず、readonly Principal は read だけを許す。
|
||||
|
||||
直接 Role binding の付与判定も backend に対応し、Domain の異なる Role を拒否する。
|
||||
exact Object モードでは Domain 全体や wildcard の grant を採用しない。
|
||||
この低水準判定は Locality 制限を代替しない。`AuthorizeContext` と
|
||||
`AuthorizeExactObjectContext` は Role/Group grant と Locality cap、Object の別名・別 Domain 制限を
|
||||
同じ read-only transaction で評価する。PostgreSQL は REPEATABLE READ を用い、
|
||||
ナビゲーション用 `LoadReadPathPolicyContext` も同じ snapshot 契約を持つ。
|
||||
公開コンテンツの匿名読み取りとユーザー領域の公開制約も、下記の同一 snapshot 契約を使う。
|
||||
アカウント作成時の Role/binding 書き込みは下記の transaction に含める。
|
||||
それ以外の federation・管理操作からの Role/binding 書き込みは別途移植する。
|
||||
|
||||
`SetPrincipalState` は管理者継承と同じ writer lock を利用する。
|
||||
グローバルな Principal の状態更新、active 以外への変更による全 Domain の session 失効、
|
||||
派生管理者権限の再計算を同じ transaction に含め、失敗時は全体を rollback する。
|
||||
既に失効した session の失効時刻を上書きせず、active へ戻しても session は復活させない。
|
||||
|
||||
アカウント作成は Principal、Identity、Credential、Domain membership、Role/binding を
|
||||
同じ transaction に含める。初回 owner は管理者グループへの projection まで含め、
|
||||
途中の失敗時にはアカウントも残さない。並行 bootstrap は一つだけ成功する。
|
||||
password hash の計算は writer lock を取得する前に行う。
|
||||
native migration v4〜v7 は Credential、Challenge、Provider 設定、CLI 認証引き継ぎを追加する。
|
||||
v8 は既存の Group/Role mapping と認証監査ログ用テーブルを追加する。監査イベントの新しい発行機能を追加する変更ではない。
|
||||
適用済み migration の SQL/checksum は変更しない。
|
||||
|
||||
ブラウザ/API session の発行は停止・継承失効と同じ writer lock を利用する。
|
||||
token の用途 prefix を hash 対象に含め、Domain 境界と有効な所属を検査する。
|
||||
プロフィールと avatar の読み書き、Domain のアカウント一覧、session 一覧・失効も両 DB に対応する。
|
||||
|
||||
TOTP の登録確定と counter 消費は同じ transaction 内で検証・更新する。
|
||||
SQLite の JSON 関数を PostgreSQL 上で代用せず、Go 側で counter を読み、writer lock で
|
||||
再利用を防ぐ。外部認証の設定保存では、空の secret を指定した更新は UPSERT 内で
|
||||
現在の暗号化 secret を保持する。外部 Identity の競合で別 Principal に紐付け直さず、
|
||||
重複するメールアドレスや表示名は曖昧なマッチとして拒否する。
|
||||
|
||||
CLI の認証要求は同時受付でも件数上限を超えないよう transaction で直列化する。
|
||||
承認消費と API session 発行は一括 commit し、発行失敗時には承認も rollback する。
|
||||
同時 exchange の成功は一つに限り、poll 間隔・origin・Domain・trusted choice を保持する。
|
||||
共通テストは合成データだけを用い、実際の LDAP/OIDC/SMTP サーバーには接続しない。
|
||||
|
||||
`store-city-foundation` は階層・所有者・公開設定・監査記録・公開 manifest の保存用 schema を持つ。
|
||||
`CityGovernance`、所有者候補検索、`ChangeCityGovernance`、`LocalityAccess` は native SQL を使う。
|
||||
変更前に管理者継承と同じ advisory lock を取得し、epoch/topology の比較、上位の公開範囲、
|
||||
所有者の委任権限を検査する。preview は rollback し、実変更は policy・epoch・監査を一括 commit する。
|
||||
上位管理者の ACL を下位所有者が広げることは拒否し、対象者の削除などの縮小だけを許可する。
|
||||
|
||||
`store-locality-foundation` は Path と設定のガードに加え、Zone/Spot/Street所属の変更を
|
||||
保護する PostgreSQL trigger を持つ。ACL のある Domain で enforcing を解除できず、
|
||||
保護 Path の移動・削除・別名による脱出を拒否する。新規 Object を保護範囲内に作成することは許可する。
|
||||
Path の比較には C collation の文字列範囲を使い、`%`、`_`、大小文字、日本語を LIKE の wildcard としない。
|
||||
trigger を無効化・削除した状態は migration の assertion と ACL 変更時の検査で拒否する。
|
||||
将来の City/namespace writer も、行ロックより先に同じ管理用 lock を取得する順序に統一する。
|
||||
|
||||
共通テストでは上位公開範囲の制約、所有者委任、ACL 縮小、同時変更の単一成功、
|
||||
preview の非永続化、監査失敗時の rollback、保護 namespace、失効後の次リクエストを確認する。
|
||||
schema の追加は City 全体の対応完了を意味しない。通常 HTTP ハンドラとの PostgreSQL 統合試験、
|
||||
City 全変更系と他の管理経路からの Role/binding 操作の監査は残る。
|
||||
既存 SQLite の他の mutation から呼ばれる旧 transaction wrapper は
|
||||
SQLite 用のままであり、それらの PostgreSQL 化は呼び出し側の lock 契約も含めて行う。
|
||||
`EnsureAuthSchema` は PostgreSQL の認証・Locality schema 初期化へ接続済み。
|
||||
管理対象 migration の未移植 component は `ErrPostgreSQLComponentNotReady` で拒否し、
|
||||
SQLite migration runner を PostgreSQL 接続へ流さない。本番用 PostgreSQL Store は未公開のままとする。
|
||||
|
||||
#### 公開とユーザー領域の移植
|
||||
|
||||
`store-publication` は公開 manifest の失効と navigation generation 用 trigger を持つ。
|
||||
匿名 Revision 読み取りと navigation は、明示承認と自動公開候補を同一 read-only snapshot で確認する。
|
||||
有効な Campus/Domain、HEAD、hash、別名、公開範囲、公開者の状態を検査し、
|
||||
本文更新・別名追加・権限変更後の次リクエストに失効を反映する。
|
||||
上位の手動承認必須設定は下位の自動公開を止める。
|
||||
PostgreSQL の navigation trigger は statement 単位で更新し、generation を行数ではなく失効 token として扱う。
|
||||
|
||||
`store-publication-approval` の要求作成は domain/idempotency key の競合を UPSERT で処理する。
|
||||
承認は状態・generation・期限を検査し、decision 記録と状態更新を一括 commit する。
|
||||
同時承認の成功は一つだけで、期限切れ整理ジョブの実行前でも期限切れ要求は承認できない。
|
||||
|
||||
`store-user-space` は profile/avatar/root/descendant の公開設定、Path ごとの縮小例外、監査記録を持つ。
|
||||
公開読み取りは有効な本人所属と Domain の上限、本文 HEAD を同じ snapshot で評価し、
|
||||
別名付き Object は匿名公開しない。例外 Path の改名は同じ所有者の namespace に制限し、
|
||||
改名・削除に policy を追従させる。policy 更新と監査記録は一括 commit する。
|
||||
`store-profile-contacts` は電話番号を Principal の一般情報と分離し、
|
||||
本人の同意・profile 公開設定・Domain の上限を満たす場合だけ匿名へ公開する。
|
||||
競合した version は拒否し、非公開時は値だけでなく version/visibility も返さない。
|
||||
|
||||
既存 SQLite の同一時刻 Revision は `rowid` で HEAD を決定する一方、native PostgreSQL は UUID を用いる。
|
||||
新規 native 保存は時刻を単調増加させるが、旧 DB の同時刻データにはその保証がない。
|
||||
全件 import は言語別 HEAD とその参照先を移行前後で照合し、順序の保存方法を確定するまで
|
||||
本番切替を許可しない。core の往復試験だけでこの条件を満たしたと判断しない。
|
||||
|
||||
#### 共通 metadata Repository の実装範囲
|
||||
|
||||
`internal/metadata` は Object 作成、Domain ごとの Path 解決と alias、再帰移動、
|
||||
言語別 Revision HEAD の比較更新、履歴 UUID の参照と非破壊復元、Asset HEAD と
|
||||
履歴の原子的更新を提供する。SQL の placeholder を組み立て時に生成し、
|
||||
SQL 文字列の一括置換は行わない。DB には Document 本文を保持せず、
|
||||
低水準の `AppendRevision` は呼び出し側が Geduldh へ先に検証・永続化した SHA-256 を公開する。
|
||||
`SaveDocument` は参照固定と payload 永続化も含めた保存パイプラインを提供する。
|
||||
Revision の `body` 列は既存形式との橋渡し用の空キャッシュであり、正本ではない。
|
||||
|
||||
PostgreSQL の書き込みは Domain 単位の transaction-level advisory lock を取得し、
|
||||
Revision ではその後に Object 単位の lock も取得する。lock の取得順を統一し、
|
||||
異なる Object の保存でも Domain 内の outbox sequence を直列化する。
|
||||
アプリ用の `NewApplication` は、その前に namespace 管理と共通の advisory lock を取り、
|
||||
有効な Campus と Domain、local 配置を transaction 内で再確認する。
|
||||
順序は namespace 管理 → Domain → Object とする。本文の検証・永続化 I/O 中には取得しない。
|
||||
SQLite は読み取り前に書き込みロックを取得する。
|
||||
全 writer が同じ契約を使う前提で、プロセス内の mutex に依存せずに HEAD を比較する。
|
||||
Revision の時刻は同一言語の前の値より必ず後にし、順序付けに隠れた rowid を使わない。
|
||||
復元は新しい Revision UUID で追加し、過去の Revision を変更しない。
|
||||
埋め込み Document の参照も履歴から引き継ぎ、現在の Asset HEAD へ置き換えない。
|
||||
|
||||
再帰移動は移動先が空であることを検査し、一つの UPDATE で配下を移動する。
|
||||
全 Path のメモリ展開や一件ずつの SQL 発行はしない。Path は SQLite の binary、
|
||||
PostgreSQL の C collation とし、配下の検査は索引を使える文字列範囲で行う。
|
||||
日本語、大小文字、`%`、`_`、仮想フォルダ、同名の別 Domain を区別する。
|
||||
同一 Domain 内の alias 追加は既存 Path を上書きしない。Domain を越えるリンクの
|
||||
取り扱いは認可・共有の移植時に別途実装する。
|
||||
|
||||
`InitializeFresh` は専用 migration 履歴で管理する空 DB/schema 用の初期化である。
|
||||
既存の未管理テーブルがある場合は採用や変換をせず失敗し、既存データを保持する。
|
||||
再実行時には必要なテーブルと列の存在を SELECT assertion で検査し、不足時は停止する。
|
||||
列型、照合順序、索引、一意制約の完全な catalog 検査はまだ対象外である。
|
||||
既存 Store の初期化からは呼ばない。Store の PostgreSQL 分岐には Path 解決、
|
||||
Object/Page 作成、通常 Revision 保存と履歴復元を接続した。アプリ用の Page 作成は
|
||||
Object・origin・Path と `page.created` を一括 commit し、イベント保存失敗時は全て rollback する。
|
||||
`NewApplication` 自体は通常起動の constructor や認可処理ではない。
|
||||
|
||||
保存パイプラインの実装と、変更系のアプリ接続前の残件は次のとおり。
|
||||
|
||||
- [x] DB 非依存の Asset freeze を切り出し、既存 SQLite Store からも利用。
|
||||
- [x] 共通 Repository の `SaveDocument` で Document 永続化、埋め込み Asset 検証、参照記録を接続。
|
||||
- [x] 共通 Repository の Revision 保存と activity outbox の追加を同じ transaction に統合。
|
||||
- [x] 通常保存・復元 HTTP API を Domain 明示の Store 境界へ接続し、PostgreSQL 分岐から新パイプラインを呼び出す。
|
||||
- [x] 言語別 HEAD・履歴 cursor・Document 参照一覧の native SQL と欠損 payload の失敗処理を接続。
|
||||
- [x] 通常の Path 再帰変更、native filename Revision とコピー時の埋め込み参照保持、navigator の追従を接続。
|
||||
- [x] Asset Store API の native SQL と履歴復元を接続。
|
||||
- [ ] Web/API/CLI の変更系を新保存パイプラインへ切り替え。
|
||||
- [ ] Path/City の残る入口・reconciler と関連 metadata を監査し、通常 HTTP と cache invalidation を統合試験。
|
||||
- [ ] 既存 Store の残りの取得・一覧・専用リンク操作・import writer を移植。
|
||||
- [ ] 既存 schema の移行計画、schema drift の assertions、整合性検査を整備。
|
||||
- [ ] 同時 GC との pin 契約、巨大 Asset の検証 I/O の予算と再検証 cache を整備。
|
||||
|
||||
`internal/documentrefs.Freeze` は可変 `asset:` を HTML の参照属性から解決し、
|
||||
SHA-256 URL と出自属性へ固定する。同一 address の解決と同一 hash の参照記録は重複させない。
|
||||
通常テキスト、コード例、非 HTML payload は解決せず、変更不要の HTML token は元の byte 列を維持する。
|
||||
既存 Store は従来の resolver を adapter として使い、PostgreSQL 用の保存では Domain を明示した resolver を使う。
|
||||
外部 URL へアクセスする機能ではない。
|
||||
|
||||
`SaveDocument` は対象 Object の Domain 内の Path と言語別 HEAD を先に確認し、
|
||||
解決した埋め込み payload を検証してから、凍結済み Document を Geduldh へ永続化する。
|
||||
この間に DB transaction や lock は保持しない。その後に HEAD を再比較し、
|
||||
Revision、`revision_document_refs`、`revision.created` の pending outbox、型別 watermark を
|
||||
一つの transaction で確定する。outbox の sequence は型別 watermark から割り当て、
|
||||
増え続けるイベント履歴全体を走査しない。イベント配信と worker lease の移植は別工程である。
|
||||
|
||||
アプリ用 Repository は未紐付け Object に限り作成元 Domain の origin を認め、
|
||||
create/save/bind の順序を維持する。別 Domain に Path が存在する Object へ origin だけで書き込めない。
|
||||
Object のみを渡す旧呼び出しは所属 Domain が一意の場合に限り解決し、複数なら明示指定を要求する。
|
||||
これは認可の代替ではなく、HTTP 側の read/write 権限検査は維持する。
|
||||
|
||||
`SaveRevisionContentInDomain` は期待 HEAD の有無を区別する。空文字の期待値は未作成を要求し、
|
||||
期待値なしは無条件 append とする。CAS 失敗を無条件 append で自動再試行しない。
|
||||
PostgreSQL の `RestoreRevisionInDomain` は過去の本文と埋め込み参照の payload を検証し、
|
||||
現在の Asset HEAD を再解決せず新しい Revision に引き継ぐ。
|
||||
DocumentRoot を必須とし、正本の欠損を空の DB body cache で補修しない。
|
||||
SQLite の既存 writer と復元の参照固定動作は維持しており、その統一は別の変更単位とする。
|
||||
|
||||
Path の native 変更処理は namespace 管理 lock を取得してから snapshot を再検証する。
|
||||
移動・コピー・一括 unlink は最大 10,000 Path、30 秒の transaction 予算で実行し、
|
||||
`%`・`_` をワイルドカードにしない索引範囲を使う。予算超過時に部分適用はしない。
|
||||
再帰移動では City 境界、ユーザー領域の公開例外、保存した navigator の Path を同じ transaction で更新する。
|
||||
既存の locality ACL によって保護された namespace の移動・削除は引き続き拒否する。
|
||||
ACL を自動的に別の Path へ拡張する機能や DB guard の迂回は追加しない。
|
||||
公開 manifest と navigation generation は既存の native trigger で失効する。
|
||||
|
||||
native のファイル名変更は、言語別 HEAD の参照 hash を保つ新 Revision を追加する。
|
||||
コピーでは新 Object/Revision UUID を割り当て、全 Revision と埋め込み参照の対応を同じ transaction で複製する。
|
||||
本文 blob は再利用する。unlink は履歴と blob を消さず、City の定義も自動削除しない。
|
||||
コピー履歴で同時刻の旧 HEAD を維持する条件は、全件 import の順序問題と合わせて確認する。
|
||||
|
||||
City の読み取りは PostgreSQL の repeatable-read snapshot を利用する。
|
||||
整理操作は topology version を管理 lock 内で照合し、Page placement、Spot relation、監査記録を一括更新する。
|
||||
Page の URL は Spot 整理では変更しない。境界検査は最大 4,096 node に制限し、
|
||||
Spot 整理の既存の選択数・展開 Page 数・relation 数上限も維持する。
|
||||
Asset 復元は payload の hash を検証してから期待 HEAD を比較更新する。
|
||||
削除は mutable Asset を取り除くが、履歴と既存 Revision からの参照は保持する。
|
||||
|
||||
payload 永続化後に競合や DB エラーが起きた場合、参照のない不変 blob が残ることは許容する。
|
||||
同じ hash を別 writer が利用する可能性があるため、保存失敗時に blob を削除しない。
|
||||
参照のない blob の回収は pin と保持期間を持つ GC の役割とし、同時削除を行う構成では
|
||||
pin 契約の接続が済むまで新パイプラインを有効にしない。
|
||||
|
||||
portable core の v1 定義は変更せず、参照と outbox のスキーマを v2 として追加した。
|
||||
試験用 v1 の既存行を維持した移行、DDL 途中失敗時の rollback、再試行を共通テストで確認する。
|
||||
これは本番 SQLite からのデータ移行機能ではない。
|
||||
|
||||
既存 SQLite Store では、Revision の outbox 用 Domain 取得時に未知の SQL エラーを
|
||||
無視しないよう是正した。outbox 自体がない最小 fixture は従来どおり扱うが、
|
||||
outbox がある状態での取得・書き込みエラーは Revision と一緒に rollback する。
|
||||
|
||||
共通テストでは Domain 分離、言語の分離、同時 CAS、重複作成時の orphan 防止、
|
||||
Revision の不変性、復元時の競合、Asset 履歴の故障注入 rollback を検証する。
|
||||
保存パイプラインでは payload 書き込み失敗、埋め込み検証失敗、保存 I/O 中の別編集、
|
||||
参照・outbox の故障注入、異なる Object の並行 sequence 採番も検証する。
|
||||
これらは変更系 Web/API の PostgreSQL 対応完了を意味しない。
|
||||
|
||||
`PAGESWIKI_TEST_POSTGRES_DSN` に使い捨て PostgreSQL の URL を指定すると、
|
||||
`go test -race -count=1 ./internal/db ./internal/metadata ./internal/documentrefs` が実 DB と参照固定のテストを実行する。
|
||||
各テストはランダムな schema を作成し、終了時にその schema だけを削除する。
|
||||
試験用ユーザーには CREATE SCHEMA 権限が必要で、本番 DSN は使用しない。
|
||||
DSN を指定しない通常テストでは実 DB 部分だけが skip されるため、
|
||||
PostgreSQL 対応のリリースゲートでは DSN 指定を必須とする。
|
||||
初期検証対象は PostgreSQL 17。最低対応版の確約は CI matrix の整備後とする。
|
||||
|
||||
展示環境では metadata の PostgreSQL 化だけで NFS 対応完了とはしない。
|
||||
Document の no-replace publish と directory fsync、カレンダー正本の lock と atomic rename、
|
||||
秘密鍵とバックアップの配置を別々に検証する。PostgreSQL 自体の PGDATA を
|
||||
未検証の共有 NFS へ移すことで SQLite の問題を置き換える運用は採用しない。
|
||||
DB 用の適切な永続領域または外部 PostgreSQL を確保する。
|
||||
|
||||
#### 移植診断と停止状態の往復リハーサル
|
||||
|
||||
`pageswiki schema portability --db FILE --json` は既存 SQLite を読み取り専用で開き、
|
||||
テーブルの担当領域、未対応テーブル・view・trigger・index、portable migration 履歴、
|
||||
既知 core の catalog の差を報告する。行の値、DDL 本文、DSN、秘密鍵は出力しない。
|
||||
DB がなければ作成せず終了し、初期化や migration は行わない。
|
||||
アプリ全体が未対応の間は `application_ready=false` と終了コード 1 を返す。
|
||||
`core_compatible=true` は下記の限定リハーサルに必要な契約であり、本番移行の許可ではない。
|
||||
未対応テーブルを削除してこの診断を通すことはしない。
|
||||
|
||||
`InspectPortability` は SQLite では既知 core の生成 DDL と索引を厳密に照合し、
|
||||
PostgreSQL では列型、NOT NULL、default、collation、identity、主キー・一意制約・外部キー・CHECK、
|
||||
通常索引の定義と有効状態、sequence の設定を検査する。未知の unique index も無視しない。
|
||||
PostgreSQL の RLS、独自 policy・trigger・routine・rule・sequence、継承・partition 等の未移植の状態は拒否する。
|
||||
trigger は情報スキーマの権限による非表示に依存せず catalog から確認する。
|
||||
PostgreSQL で検査する範囲は現在の schema であり、別 schema のアプリを含む全 DB の認証評価ではない。
|
||||
backend 固有の migration ledger は checksum を検査するが、相手側へコピーしない。
|
||||
|
||||
`CloneCoreForRehearsal` は内部テスト用の core コピーであり、本番用 CLI には公開しない。
|
||||
対象は Object、origin、Path、Revision、Asset、Asset 履歴、Revision の Document 参照、
|
||||
activity outbox と型別 watermark の 9 テーブルに限る。認証、設定、タスク等の
|
||||
追加テーブルがある実稼働 DB は拒否する。全 writer と GC の停止を呼び出し側の前提とし、
|
||||
オンライン移行や二重書き込みを行う機能ではない。
|
||||
|
||||
コピーでは一つの source snapshot から主キー順に行を読み、型付きの値を保って
|
||||
空の staging DB/schema に挿入する。一度に保持するのは一行分であり、最大の一行自体の
|
||||
メモリ使用量は別の制約になる。移行元の DB を変更せず、移行先が空でない場合、
|
||||
同じ DB を別 connection pool から指定した場合、未知の schema がある場合は拒否する。
|
||||
移行先の全 core テーブルを保護し、途中でエラーが起きた場合はコピーした全行を rollback する。
|
||||
文字コード不正、NUL、TEXT 列の BLOB、整数型の不整合、参照欠損を黙って変換しない。
|
||||
|
||||
照合は件数だけではなく、テーブル名・列順・主キー順の各行を長さ付きで SHA-256 に入力する。
|
||||
64bit 整数を浮動小数へ変換せず、日本語、大小文字、異なる Unicode 表現、`%`・`_` を保つ。
|
||||
履歴の採番は現存する最大 ID と generator の保持状態の両方から次の値を決め、
|
||||
過去の ID が再利用されないようにする。PostgreSQL では非 transactional な `setval` ではなく、
|
||||
コピー transaction 内で identity を `RESTART` する。
|
||||
|
||||
参照先の不変 Document は、別途保持する同一の Geduldh Store で SHA-256 を検証する。
|
||||
この関数は blob、カレンダー正本、鍵、インスタンス設定をコピーしない。
|
||||
SQL だけの指紋一致をインスタンス全体のバックアップや復元の成功とは扱わない。
|
||||
実 DB テストでは PostgreSQL 側の追加更新を含めて別の SQLite へ戻し、内容指紋の一致と
|
||||
その後の採番を確認する。未知の制約・RLS・索引の拒否、コピー途中失敗の rollback、
|
||||
source の不変性、Document 欠損、同一 DB への自己コピーも検証する。
|
||||
|
||||
#### 本番 PostgreSQL 移行の受入ゲート
|
||||
|
||||
今回の対象は、全 writer を停止した状態での SQLite→PostgreSQL の片方向インポートと、
|
||||
移行後の通常運用である。PostgreSQL→SQLite の逆移行、自動切り戻し、二重書き込み、
|
||||
オンライン差分同期は今回の実装・受入条件から除外する。
|
||||
既存の core 往復テストは回帰テストとして残すが、本番全件の逆移行へ拡張する作業は行わない。
|
||||
移行前バックアップと片方向インポートの整合性検証は引き続き必須とする。
|
||||
|
||||
2026-11-14 の棚卸しでは Store の SQL 呼び出し点は約 100 ファイル・967 か所ある。
|
||||
これはすべてが SQLite 固有であるという意味ではないが、接続層と core だけでは
|
||||
通常起動・認可・全アプリ機能を満たさない。次の未完了ゲートを残す。
|
||||
|
||||
2026-11-15 時点の受入条件は以下の 8 工程に整理する。1 と 2 の主要 DB 処理は共通テストを通過したが、
|
||||
通常 HTTP/scheduler/CLI 経由の PostgreSQL 統合は工程 7 と合わせて検証する。
|
||||
工程数は受入ゲートの区分であり、8 回の変更や応答で完了するという工数見積もりではない。
|
||||
|
||||
| 順序 | 残工程 | 本番切替前の受入条件 |
|
||||
| --- | --- | --- |
|
||||
| 1 | 認証と権限の統合 | 認証・公開・承認・ユーザー領域の DB 処理は移植済み。残る管理経路の直接 SQL、通常 HTTP 認証と navigation cache の PostgreSQL 統合を確認 |
|
||||
| 2 | Domain と Campus と federation の統合 | namespace CRUD・管理者継承・token・instance・署名 manifest は移植済み。controller/managed プロセスの再起動、鍵・instance identity の保持と HTTP 配信を確認 |
|
||||
| 3 | core と Document と City の接続 | 全 Store 変更系、GC pin、検証 I/O の予算、Document root identity、Asset 復元、Path 移動・削除時の City 境界・ACL・関連リンク・filename Revision・snapshot 検査・cache 失効を接続 |
|
||||
| 4 | タスクと CalDAV と各拡張 | プロジェクト所属、VTODO、ETag/ctag/sync-token、通知、連絡先・RSS・ブログ等の repository と対応テーブルを移植 |
|
||||
| 5 | ジョブと通知 | claim/lease/fencing、キャンセル、outbox 消費、重複排除、再起動時の処理、ログ保持を検証 |
|
||||
| 6 | 検索と管理 | FTS5/rowid/PRAGMA/JSON 関数・照合順序への依存を分離し、権限付き検索・一覧と管理設定を検証 |
|
||||
| 7 | 通常起動と設定 | backend 別 bootstrap、全 Ensure、secret 参照、schema 診断、readiness、CLI/standby の接続を統一し、PostgreSQL で全体試験を通過 |
|
||||
| 8 | 全件インポートと切替 | 全正本テーブルの片方向インポート、再生成可能 cache の分類と再構築、canonical files・鍵の保持、件数・参照・内容指紋・採番の整合性、移行前 backup と PostgreSQL backup/restore を検証し、停止状態で本番切替 |
|
||||
|
||||
MySQL、S3、Redis、HA、逆移行はこの 8 工程の完了条件に追加しない。
|
||||
|
||||
#### 初回切替を短縮する場合の残件
|
||||
|
||||
初回は単一インスタンス・ローカル Document root・停止状態での片方向 import を対象とする。
|
||||
利用者は必須残件を先行し、任意機能をリリース後へ回す方針を了承した。
|
||||
Push 配信・zombie GC・ログの保持期限処理・hosted editor session には native 停止ゲートを実装した。
|
||||
その他の機能を停止する場合も利用者へ制限を示したうえで、
|
||||
起動時・HTTP・CLI・worker の全入口を同じ機能ゲートで拒否する。
|
||||
`NewPostgreSQLWithDocumentRoot` で native の通常 Store を初期化し、
|
||||
合成データによる Server 起動・HTTP 操作・停止後の再初期化まで接続した。
|
||||
`cmd/pageswiki/main.go` は `PAGESWIKI_DB_BACKEND=postgresql` による選択と、
|
||||
全件 import の完了記録・鍵・Document root の一致検査を接続した。未指定時は SQLite のままである。
|
||||
全件転送は `pageswiki migrate-postgres` を使用する。
|
||||
`internal/metadata/portability.go` の core 限定リハーサルとは別の実装である。
|
||||
|
||||
切替に直結する実装順序は次のとおりとする。
|
||||
|
||||
1. ジョブ基盤と outbox の統合。DB 層の claim・完了 token・再起動時の中断扱い・重複排除、
|
||||
Task/Calendar/RSS のイベント登録は移植済み。Server の起動で worker owner を取得し、
|
||||
停止と join 後に解放する。native 通常 Store による HTTP・再初期化・worker 二重起動拒否を検証済み。
|
||||
2. 通常起動・検索・管理経路の接続。backend 明示の Store 初期化、主要画面、
|
||||
内蔵エディタ保存、認証失効、DAV discovery まで接続済み。
|
||||
本番用 backend 選択も接続済み。認証、ACL、公開範囲は省略しない。
|
||||
3. 全件 import。全正本テーブル・鍵・設定・受付/操作履歴・同期番号を列挙し、
|
||||
cache と区別して保全する。identity 採番、本文参照、件数・内容指紋と再実行を検証する。
|
||||
4. 隔離した通常 HTTP 起動と再起動試験、backup/restore 検証後に停止移行する。
|
||||
実行する機能の CRUD、DAV 条件付き更新、権限失効、失敗時の rollback を通してからリリースする。
|
||||
|
||||
| 後回しにできる候補 | 初回切替で必要な条件と制限 |
|
||||
| --- | --- |
|
||||
| HA/LB/DR、無停止・オンライン移行 | 単一インスタンス、旧系の writer を停止した import に限定。PostgreSQL の backup/restore は省略しない |
|
||||
| PostgreSQL から SQLite への逆移行 | 既定どおり対象外。旧 backup からの復旧は、切替後の更新を引き継ぐ逆移行とは別物 |
|
||||
| 自動 GC の同時実行と pin 機構 | native zombie GC は定期実行・手動 API・Store の全入口を拒否する。本文ファイルの GC を新設せず、容量を監視する。本文参照・hash の整合性検証は残す |
|
||||
| 高度な全文検索・ランキング最適化 | native は権限付き Path/ファイル名検索と City メタデータ検索を実装。Page 本文・H1 の検索とサジェストへの H1 付与は未対応。FTS5 や全本文走査で代用しない |
|
||||
| hosted editor | native は起動・ticket 交換・session 取得・保存を拒否し、選択肢から除外する。設定と既存 session は保全し、内蔵エディタを使用する。session の base revision 更新と本文保存をまたぐ整合性は後続対応 |
|
||||
| サムネイル再生成・リソース履歴のグラフ | 対象イベントと API を明示的に無効化。正本と派生 cache/履歴の分類を先に確定し、未分類テーブルを捨てない |
|
||||
| Push/SMTP/外部サービスへの送信 | 配信だけを停止する制限運用は可能だが、Inbox と受付履歴は保持する。不明な送信結果を成功や再送待ちへ変換しない |
|
||||
| ログの自動保持期限処理 | native では定期 cleanup を実行せず、手動呼び出しも拒否する。ログと集計を保全する代わりに容量監視が必要。policy 別の件数・実行時間を制限した cleanup は後続対応 |
|
||||
| MySQL、S3、Redis 等の追加 backend | 今回の PostgreSQL 切替とは別プロジェクトとして扱う |
|
||||
|
||||
全件 import、通常起動、認証/公開権限、正本ファイルと鍵の保全、必要機能の統合試験、
|
||||
移行前 backup は短縮対象にしない。機能縮小で省けるのは各機能の稼働対応であり、
|
||||
その機能が持つユーザーデータの保全ではない。
|
||||
|
||||
#### ジョブと HTTP 接続の移植状況
|
||||
|
||||
`store-event-jobs` は PostgreSQL 用の独立 migration とし、定義、キュー、ログ、集計と設定を作成する。
|
||||
native worker は専用接続の advisory lock により同一 DB/schema に一つだけ起動できる。
|
||||
これは単一インスタンス用の排他であり、HA の lease/failover を提供するものではない。
|
||||
接続が利用不能なら新規 claim を拒否する。
|
||||
`Server.NewChecked` は worker owner 取得・イベント登録の失敗を起動エラーとして返す。
|
||||
`Runner.Stop` は受付を止めて実行中処理を cancel し、完了状態保存を待つ。
|
||||
`Server.Close` は scheduler loop・保守処理・worker の終了後に排他を解放する。
|
||||
停止待ちの timeout は終了完了を意味せず、実行中処理が残る間は排他を保持する。
|
||||
main の SIGTERM/Ctrl+C は Campus 同期の新規開始を止め、進行中同期の終了を待ち、
|
||||
HTTP と worker の停止へ接続した。各外部同期要求は従来の network timeout を使う。
|
||||
|
||||
ジョブの claim、同時実行数とキュー深さの検査、再試行は writer transaction 内で行う。
|
||||
完了には claim ごとの token を要求し、再試行・再起動前の worker の完了を拒否する。
|
||||
完了状態の保存後にログ保存が失敗しても、副作用のあるジョブを自動で再実行しない。
|
||||
再起動時に残る running は結果不明として failed にし、明示的な再試行を待つ。
|
||||
schema 初期化だけで稼働中のジョブを奪わない。
|
||||
|
||||
定期イベントの enqueue と次回日時の更新は同一 transaction で行い、キュー満杯なら両方を rollback する。
|
||||
組み込みイベントの登録は管理者による無効化や周期変更を上書きしない。
|
||||
Task の活動通知、期限通知、Focus、日次メール、RSS、Calendar sweep の登録を接続した。
|
||||
外部配信の実行可否は別の制限であり、登録の移植完了をもって配信を有効化しない。
|
||||
|
||||
outbox の正本 journal と型別 watermark は core 所有のままとし、
|
||||
`store-activity-consumers` が通知先ごとの checkpoint と検索 index を追加する。
|
||||
型別に件数を制限して読み込み、別 consumer の処理済み状態に影響されず、
|
||||
checkpoint の更新は単調増加とする。投影処理と同一 transaction で rollback できる API を維持する。
|
||||
|
||||
HTTP に残っていた Object alias、Calendar の active member、City zone kind、ブログ射影先、
|
||||
設定変更対象の Campus 解決、個人表示設定の直接 SQL は Store API に移した。
|
||||
参照は件数/時間を制限し、alias と射影先の権限判定は引き続き HTTP 側で行う。
|
||||
管理対象を解決できない場合は現在の Campus へ fallback せず拒否する。
|
||||
個人表示設定は現在の membership を再検査し、CAS と read-only 拒否を適用する。
|
||||
`EnsureTasksSchema` は native foundation と productivity migration へ接続した。
|
||||
|
||||
アナウンス、プレビュー解析 cache、リソース履歴も native migration と Store API に接続した。
|
||||
アナウンスは Domain を跨いだ同一 UUID の上書きを拒否し、削除時は Inbox との transaction を維持する。
|
||||
プレビュー解析 cache は PostgreSQL の byte 長で容量を制限し、resource sample は job UUID で重複排除する。
|
||||
これらの変更は起動依存の移植であり、新しい表示機能の追加ではない。
|
||||
|
||||
Push は鍵・購読・配送状態を保持する schema のみ作成し、Inbox INSERT trigger は設置しない。
|
||||
Store の登録・claim・完了・cleanup、HTTP、キー生成、配信の入口で拒否する。
|
||||
native 定期 enqueue と claim は Push を除外し、既存定義の日時や不明な配送状態を書き換えない。
|
||||
停止されたログの期限処理と zombie GC も、機能設定の変更で再有効化できない backend 制限とする。
|
||||
|
||||
HTTP 検索の SQLite 直接生成を Store 経由に変更し、native では Path と元ファイル名を検索する。
|
||||
最新 revision の MIME/拡張子/更新日時、Object 作成日時による絞り込みを候補 LIMIT 前に適用する。
|
||||
候補は最大 1,000 件、返却は最大 200 件、SQL と権限判定の予算は 2 秒とし、
|
||||
本文ファイル・legacy body 列を検索やタイトル補完のために走査しない。
|
||||
候補 cursor を閉じてから権限判定するため、1 接続の pool でも権限問い合わせを実行できる。
|
||||
検索・サジェスト HTTP の `X-PagesWiki-Search-Profile: metadata-only` はこの制限を表す。
|
||||
対象範囲に候補が 1,000 件を超える場合、候補制限による取りこぼしはあり得る。
|
||||
|
||||
City 検索は native の read snapshot 内で種類ごと最大 1,000 件のメタデータを集め、
|
||||
transaction を閉じてから Quartier・Street を含む親階層の権限を確認する。
|
||||
Domain/Path 境界、日付条件、未定義 Spot の Street へのリンクを維持する。
|
||||
Page のファイル種別指定時には City 要素を混ぜない。
|
||||
|
||||
hosted editor は `store-adapter-sessions` に ticket/session/base revision を保全する。
|
||||
native では Store と HTTP の操作入口を拒否し、アダプタ選択肢から editor plugin を除外する。
|
||||
閲覧用 plugin と内蔵エディタはこの制限の対象外である。
|
||||
既定 editor の設定を削除したり、残存 ticket を期限切れ cleanup で消したりしない。
|
||||
|
||||
この検索・保全ガードは合成データの PostgreSQL 17 と SQLite で検証した。
|
||||
`go test ./...`、対象の race 検査、`go vet ./...`、`cmd/pageswiki` のビルドを通過した。
|
||||
検索検査には 1 接続での権限問い合わせ、Domain・親階層の拒否、文字列のリテラル一致、
|
||||
1,100 件の候補に対する LIMIT 前の絞り込み、過去 revision の除外、cancel を含む。
|
||||
検索の repository 統合検証とは別に、次の通常 HTTP 起動検証を行う。
|
||||
|
||||
`NewPostgreSQLWithDocumentRoot` は鍵と Document root を先に検査し、native schema を依存順に初期化する。
|
||||
欠落・不正な `auth.key` を生成し直さず、`PAGESWIKI_AUTH_KEY` を指定しない場合は既存の 32 byte 鍵を要求する。
|
||||
Campus/Domain 未配置、所有 Campus が存在しない Domain、Domain が存在しない Path は起動を拒否する。
|
||||
既存の無効 Campus を既定 Campus へ付け替えず、SQLite の legacy body backfill も実行しない。
|
||||
`BackfillDocuments` の native 呼び出しは明示的に拒否する。
|
||||
正本ファイル全件の hash 照合は import/restore 工程の責務であり、この constructor だけでは保証しない。
|
||||
|
||||
合成データの PostgreSQL 17 で通常 Store と `Server.NewChecked` を組み合わせ、
|
||||
実 HTTP listener の本文取得、主要画面と管理パネル、内蔵エディタ保存と競合 409、
|
||||
無効・失効セッションの 401、CalDAV/Task DAV/CardDAV の discovery を検証した。
|
||||
同じ DB と Document root で Server を停止・再初期化し、本文と認証 session の継続を確認する。
|
||||
稼働中の別 worker 起動は拒否し、停止完了後に再取得できる。
|
||||
resource event の保存は同じ job UUID で再実行しても重複しない。
|
||||
管理画面の最近の Object は native query に分岐し、Domain 内の代表 Path と最新 revision のみを扱う。
|
||||
返却上限 200 件・SQL 予算 2 秒とし、Page 本文は読み込まない。
|
||||
|
||||
全件 import と内容照合、本番 backend 選択、合成データの PostgreSQL dump/restore は接続した。
|
||||
停止切替のコマンドと制限は [PostgreSQL 移行手順](../operations/postgresql-migration.md) にまとめる。
|
||||
本番切替には、移行前の一貫したバックアップと、そのインスタンスの schema preflight・全件 import の成功が必要である。
|
||||
合成データの試験通過は、本番データの移行完了を意味しない。
|
||||
|
||||
`application_import_catalog.go` は保全対象と SQLite 専用索引・migration ledger の列を固定する。
|
||||
未知のテーブル・列・trigger/view 定義を検出したら拒否し、cache と推測して捨てない。
|
||||
移行先に既存データがある場合は schema 準備の前に拒否する。
|
||||
データ転送は単一 transaction とし、schema が用意した既定行のみを置換する。
|
||||
一時停止するのは派生状態を更新する user trigger だけで、FK・CHECK・UNIQUE は維持する。
|
||||
各テーブルの型付き内容指紋・件数、Document の SHA-256、namespace の参照を照合する。
|
||||
SQLite の削除済み最大採番も保持し、transactional identity restart で番号の再利用を防ぐ。
|
||||
タスク DAV の内部索引キーと削除 tombstone は NUL 区切りから native v1 base64url 形式に変換する。
|
||||
この変換を report に明示し、正本 JSON とクライアントに公開する href は変更しない。
|
||||
失敗時の全件 rollback、修正後の再試行、重複 import 拒否、認証 session・画像・日本語タグ、
|
||||
プロジェクト別タスク・連絡先 sync-token の継続を合成データで検証する。
|
||||
同じ正本ファイルを保持した schema 単位の `pg_dump`/`pg_restore` 後も本文・認証・DAV を検証する。
|
||||
|
||||
#### 次の実装単位と検証状況
|
||||
|
||||
工程 3 の通常保存・履歴取得・復元は Store 境界へ接続済みである。
|
||||
エディタ保存 API は Domain と期待 HEAD を明示し、PostgreSQL 分岐から本文永続化・参照固定・
|
||||
Revision・outbox を一つの契約で扱う。SQLite は既存保存動作を維持する。
|
||||
PostgreSQL の通常 HTTP 経路では保存と期待 HEAD 競合を確認済み。
|
||||
履歴復元を含む残る操作の HTTP 確認は工程 7 に残る。
|
||||
|
||||
`path_mutation.go`/`path_snapshot.go` の通常操作、`city_operations.go`/`city_organize.go`、
|
||||
City map 読み取りと Asset Store API は移植済みである。
|
||||
`city.go` の個別作成・削除・relation、`city_plan.go` の一括変更計画、ページ一覧と
|
||||
アーカイブ import 管理も移植済みである。City の作成・配置・再帰削除と計画適用は
|
||||
共通 namespace lock の中で topology version と監査イベントを更新し、途中の SQL 失敗は rollback する。
|
||||
`EnsureCitySchema` は native schema と公開制御の migration へ接続した。
|
||||
|
||||
自動生成の候補取得と名前判定は Store API に集約し、候補 cursor を閉じてから階層を解決する。
|
||||
同じ境界の解決結果は一回の plan 構築中に再利用し、DB 故障を「既存要素なし」として扱わない。
|
||||
候補は 20,000 件を上限とし、超過時に途中までの City を適用しない。
|
||||
定期・編集イベントからの実行は scheduler 移植と統合して検証する。
|
||||
|
||||
children は Domain 全件を Go へ読み込まず、対象 subtree から直下要素を SQL で抽出する。
|
||||
DB generation とプロセス内の cache epoch で別 Store の変更・取得中の失効に追従する。
|
||||
Browser と children の列挙上限は 20,000 件、問い合わせは timeout 付きとし、超過を明示する。
|
||||
PostgreSQL の Browser title は本文 cache ではなく canonical HTML の先頭 64 KiB から取得する。
|
||||
一回の title 読み取りは 32 MiB と timeout で制限するが、DocumentSize の個別 I/O は残る。
|
||||
権限付き Object metadata 一覧は既存の候補・alias 上限と継続 cursor を維持する。
|
||||
|
||||
アーカイブ import は独立 migration `store-imports` でセッション、計画、journal を作成する。
|
||||
Path rollback とセッション状態更新は一つの transaction とし、import 時と Object が一致する
|
||||
binding だけを削除する。City cleanup はそれに先行する再試行可能な別フェーズであり、
|
||||
City と Path を一括 rollback する transaction ではない。
|
||||
旧 worker の void 状態更新 API は失敗を呼び出し元へ返せないため、scheduler 移植時に
|
||||
エラー伝播・状態遷移・再試行を併せて整理する。
|
||||
|
||||
工程 3 の残件は
|
||||
`domain_paths.go` 等の legacy schema adoption と bootstrap の分離、残る直接 SQL writer の棚卸し、
|
||||
import worker のエラー伝播、Path 変更を消費するイベント処理との統合である。
|
||||
同時 GC の pin、Document root identity、巨大 payload 検証の I/O 予算も起動前のゲートとして残す。
|
||||
すべての Path/Revision writer の同じ排他契約への接続が済むまで PostgreSQL の通常起動は許可しない。
|
||||
|
||||
工程 4 は task/CalDAV、calendar、contacts/CardDAV、feeds、periodicals の順に
|
||||
保存スキーマ・変更処理・一覧・ETag/同期 token を一組ずつ移植する。
|
||||
タスクやカレンダーの処理を停止して起動検証だけを通す方式は採用しない。
|
||||
工程 5 と 6 の job claim、notification、全文検索も同様に機能契約を保つ。
|
||||
|
||||
タスク本体は `store-tasks-foundation` の native 空 DB schema と Store 操作を追加した。
|
||||
保存・削除・DAV 設定更新は権限の再確認前に共通 namespace lock を取得する。
|
||||
task head、履歴、変更 journal、outbox、DAV index、通知予約、達成度 index は
|
||||
一つの保存 transaction に含める。削除は tombstone を残し、Wiki とカレンダーを削除しない。
|
||||
一覧では JSON 抽出、文字列検索、パラメータ番号、階層 cursor の真偽値を backend 別に扱う。
|
||||
|
||||
SQLite の DAV 内部索引は NUL 区切りを含むが、PostgreSQL の TEXT は NUL を格納できない。
|
||||
native 内部キーは `v1:{base64url(project)}:{base64url(value)}` とし、既定 collection も同じ方式にする。
|
||||
外部 URI・resource 名・UID・canonical JSON は変更しない。全件 import では derived DAV index を
|
||||
canonical head から再構築し、削除 tombstone の `dav_name`/`dav_uid` も旧 NUL 形式から変換する。
|
||||
この変換なしに SQLite の該当列をそのままコピーしてはならない。
|
||||
|
||||
個人既定値、作業時間、Pomodoro、日次集計、ダッシュボードと予定枠の DB 予約は移植済みである。
|
||||
設定と配置の version を独立させ、作業時間の訂正・取消は監査履歴と同時に commit する。
|
||||
writer は権限確認前に共通 namespace lock を取り、対話的な更新は 5 秒で timeout する。
|
||||
`store-task-productivity` の追加 migration で Focus span と予定枠の title を導入し、
|
||||
既存の `store-tasks-foundation` migration は変更しない。
|
||||
|
||||
`store-notification-inbox` は Inbox のみを作成する。通知挿入は一意キーの競合を
|
||||
transaction 内で処理し、別プロセスからの重複要求も同じ UUID を返す。
|
||||
タイマー完了・期限/着手日の通知は、Inbox 挿入と元の状態更新を同じ transaction に含める。
|
||||
通知保存が失敗した場合は元の状態も rollback し、次回に再試行できる。
|
||||
活動 journal の補完は既存 outbox の冪等キーを再利用する。
|
||||
配信候補は最大 100 件・3 秒に制限し、読めなくなった所属先の情報を通知へ複製しない。
|
||||
|
||||
タスク capture/Wiki 同時作成と再作成、プロジェクト配下のメモ作成は移植済みである。
|
||||
native では Object の作成元 Domain と primary Path を明示し、本文は canonical Document に置く。
|
||||
Task・受付記録・Object・Path・Revision・outbox は同じ transaction で commit する。
|
||||
入力本文は HTML とマクロをエスケープし、削除後の明示的再作成でも既存の Wiki 本文を変更しない。
|
||||
受付記録だけ残っている不整合は自動復活させず、修復が必要なエラーとして扱う。
|
||||
|
||||
メールダイジェストの claim・送信履歴・明示的再試行も移植済みである。
|
||||
共通 namespace lock と状態条件で scheduled/manual claim を一意にし、同意・設定 version・
|
||||
所属権限を再確認する。送信結果が不明な試行は自動再送せず、本人の重複送信了承を必要とする。
|
||||
90 日経過で詳細履歴を削除しても、日次予約と再試行の受付記録は重複防止のため保持する。
|
||||
保守処理は 3 秒・中断判定 100 件・履歴削除 500 件に制限する。
|
||||
|
||||
カレンダーは `calendar-cache` migration で PostgreSQL の月別/イベント索引を作成する。
|
||||
正本は従来どおり月別 ICS と `calendar.json` の manifest であり、DB には移さない。
|
||||
明示的な backend 選択を HTTP の Repository 初期化へ接続し、予約済みタスク予定枠の
|
||||
正本作成・移動後の再試行と日次予定の cache projection を検証する。
|
||||
manifest 更新後の索引再構築失敗は transaction を rollback し、次回アクセスで修復する。
|
||||
cache 更新は 30 秒で打ち切る。全 writer は同じ正本 root と有効な flock を共有する必要があり、
|
||||
独立した filesystem を持つ replica 間の HA は未対応である。
|
||||
任意の DAV filename を UID として復号する際は UTF-8 と制御文字を検証し、
|
||||
非テキストの復号結果を PostgreSQL の TEXT パラメータへ渡さない。
|
||||
|
||||
連絡先は `store-contacts` migration で native schema と変更 journal の trigger を導入する。
|
||||
vCard 正本・履歴 hash・任意 resource 名・tombstone を維持し、更新と変更番号を同時 commit する。
|
||||
CardDAV の inventory と sync-token は PostgreSQL の REPEATABLE READ で同じ snapshot から取得する。
|
||||
metadata inventory は vCard 本文を返さず、UTF-8 の byte 長を返す。
|
||||
保存と snapshot 取得は 5 秒で timeout し、保存は権限・資格情報確認前に共通 namespace lock を取る。
|
||||
全 DB import 時は contact epoch と変更番号を保全し、identity sequence を最大値に合わせる。
|
||||
|
||||
ブログ・日記は `store-domain-entry` の設定 schema を再利用し、追加の `store-periodicals`
|
||||
migration で記事索引・変更履歴・投稿受付記録・射影設定を作成する。
|
||||
書き込みは権限確認前に共通 namespace lock を取得する。記事新規作成では Object・primary Path・
|
||||
Revision・埋め込み参照・受付記録・記事 metadata・変更履歴・outbox を同じ transaction で確定する。
|
||||
本文は canonical Document に保存し、Asset 名は当該 Domain の HEAD を不変 hash に解決して保持する。
|
||||
記事の登録解除は索引だけを削除し、Page 自体は残す。再登録は変更履歴から version を継続する。
|
||||
公開タイトルの問い合わせは許可済み navigation の UUID と Domain に限定し、入力件数も予算内に制限する。
|
||||
射影は同じ Campus の有効な local Domain 同士に限り、多段射影・循環と無効な配信元を拒否する。
|
||||
全件 import では投稿受付記録と記事変更履歴も正本として保全し、履歴の identity 採番を復元する。
|
||||
|
||||
RSS は `store-feeds` migration で購読元・記事 cache・ローカル既読状態・取り込み受付と
|
||||
FreshRSS の明示的操作 receipt を保持する。書き込みは namespace lock 取得後に
|
||||
native actor と拡張設定を検証する。読み取りは 3 秒、書き込みは 5 秒で制限する。
|
||||
FreshRSS 分類は PostgreSQL の JSONB 関数で検索し、カテゴリなしの null/空配列を扱う。
|
||||
壊れた拡張設定は当該 Domain を処理対象から外し、他の購読元の候補検索を中断させない。
|
||||
送信結果が不明な操作は購読元の変更・削除後も履歴として保持し、自動再送しない。
|
||||
期限切れ claim の回収は 1 transaction あたり 100 件・3 秒に制限する。
|
||||
次の実装単位は scheduler の native schema と claim/lease/ログ保持、各イベント登録である。
|
||||
Push 配信と scheduler のイベント登録・実行は未統合である。
|
||||
外部カレンダーの内容は検証に用いない。
|
||||
`EnsureTasksSchema` と `EnsureNotificationSchema` の native 通常起動は引き続き未対応として拒否する。
|
||||
旧 free helper を使う未移植の呼び出し元は SQLite 用であり、native Store の receiver へ順次接続する。
|
||||
DAV HTTP の discovery/REPORT/条件付き PUT/DELETE、ETag・ctag の再起動後整合性と
|
||||
カレンダー共通 endpoint の実機統合も残る。task payload 永続化中に writer transaction を保持する
|
||||
既存動作と GC pin は、Document の I/O 予算・参照固定の残件として扱う。
|
||||
|
||||
2026-11-15 の合成データによる検証では、SQLite とローカル PostgreSQL 17 を使った
|
||||
全 Go テスト、移植済み Store の共通契約・PostgreSQL migration テストの race 検出、
|
||||
`go vet ./...`、ローカルバイナリ生成が成功した。
|
||||
公開・承認、ユーザー領域・電話番号の同意、Domain 同時作成・移動、管理者継承の取消、
|
||||
Federation の token 失効・署名改ざん・replay・同時初回受信・checkpoint 故障時の rollback を含む。
|
||||
通常保存の追加試験では別 Store からの同時 CAS と無条件 append、言語別履歴、
|
||||
create/save/bind の origin 制約、別 Domain への移動後の拒否、現在の Asset HEAD を変更した後の
|
||||
履歴復元、本文・埋め込み payload の欠損、Page/Revision の outbox 故障時の rollback を確認する。
|
||||
Path/City/Asset の追加共通試験では、再帰移動・コピー・重複選択の削除、literal な `%`/`_`、
|
||||
stale snapshot の拒否、保護 namespace の拒否、コピーと filename Revision の参照保持、
|
||||
navigator の移動先重複解消、Spot 統合後の所属と URL 保持、同時 topology version 更新、
|
||||
Asset の同時 CAS・履歴復元・欠損拒否・監査保存故障時の rollback を確認する。
|
||||
City CRUD・一覧・アーカイブ import の追加試験では、stale plan、再帰削除中の監査故障、
|
||||
archived 名の再利用、literal prefix、12 件以上の指定順序、canonical H1、metadata cursor の
|
||||
重複防止、別 Store からの cache 失効、import 番号重複時の計画保持、Domain 分離、
|
||||
Path rollback と状態更新の原子性、付け替え済み Path の保護、read-only 拒否を確認する。
|
||||
タスクの追加試験では、プロジェクト別の同一 DAV UID、同一 collection 内の衝突拒否、
|
||||
既定 collection の分離、親子階層、日付・優先度・添付の絞り込みと pagination、履歴、
|
||||
完了時の通知予約削除、削除の再試行と復活拒否、DAV 資格情報の発行・失効を確認する。
|
||||
PostgreSQL の別 Store からの同時保存は一方だけ成功し、outbox 故障では保存と削除が rollback する。
|
||||
readonly Principal の書き込み拒否と、Membership 失効後の読み取り拒否も確認する。
|
||||
生産性機能の共通試験では、個人設定と配置の独立した CAS、作業時間の訂正・取消・履歴の
|
||||
pagination、Pomodoro の停止区間を除いた集計、完了通知の一度だけの登録、予定枠の状態変更、
|
||||
期限通知の再送防止と活動 journal の重複排除を確認する。
|
||||
PostgreSQL では別 Store の同時設定更新・作業開始・タイマー開始・完了処理も試験し、
|
||||
監査失敗時に作業時間/Focus span が途中で更新されないこと、Inbox 故障後の再試行、
|
||||
同時通知挿入の一意性、受信者 scope と失効後の拒否を確認する。
|
||||
capture/メモの共通試験では日本語 Path と本文、HTML/マクロの無害化、受付の再送、
|
||||
同一 Path の衝突拒否、削除後の明示的再作成と本文保持、stale project の拒否を確認する。
|
||||
PostgreSQL では受付記録の故障による全関連 metadata の rollback、別 Store からの同時 capture、
|
||||
canonical 本文の読み戻し、作成元 Domain・primary Path・cache generation を確認する。
|
||||
メール管理の共通試験では日次 claim の重複拒否、重複送信了承・受付再送・履歴 pagination、
|
||||
同意変更後の取消、保持期限後の予約・受付保持を確認する。PostgreSQL では複数 Store の
|
||||
scheduled/manual claim と、送信結果保存失敗時の rollback、中断試行の自動再送防止を確認する。
|
||||
カレンダーの共通試験では月またぎ移動、ETag 競合、DAV filename 保持、既定 calendar、
|
||||
共同編集者の読み取り権限と失効、全 cache 消去後の再構築、削除を確認する。
|
||||
PostgreSQL では別 Repository の同時編集、再構築・削除の DB 故障時の正本保持と再試行を検証する。
|
||||
タスク予定枠の再送が移動済み予定を上書きしないこと、日次 projection が現在の時刻を返すこと、
|
||||
外部 source は snapshot 読み込み前に拒否されることも合成 metadata で確認する。
|
||||
連絡先の共通試験では日本語検索、未知の vCard property 保持、同一 UID import の再送、
|
||||
削除の差分配信、履歴復元、metadata の byte 長、差分 pagination、資格情報失効を確認する。
|
||||
PostgreSQL では同時 CAS と履歴保存故障時の連絡先・同期番号の rollback を確認する。
|
||||
ブログ・日記の共通試験では日本語記事の作成・再送、変更された再送入力の拒否、
|
||||
記事 metadata の CAS、登録解除後の Page 保持と再登録、Asset HEAD 更新後の本文参照固定、
|
||||
欠損 Asset の拒否、公開タイトルの Domain 分離と件数上限、射影の循環・無効な配信元の拒否を確認する。
|
||||
PostgreSQL では変更履歴の保存故障時に Path と受付記録が rollback すること、
|
||||
別 Store からの同時投稿要求が一つの記事となること、Campus 無効化後の投稿拒否を確認する。
|
||||
RSS の共通試験では日本語・literal 検索、日時 cursor、既読状態の CAS、
|
||||
FreshRSS のカテゴリ/未分類/空フォルダ、購読 import と Wiki 取り込みの再送、
|
||||
削除済み購読元の復活拒否、外部操作の確認・期限切れ・読み取り専用再確認を検証する。
|
||||
購読元を変更・削除しても不明な外部操作を保持し、履歴の metadata 欠損を許容する。
|
||||
PostgreSQL では複数 Store の同時 claim、cache 保存故障時の lease rollback、
|
||||
100 件ずつの期限切れ回収、破損設定と Campus 無効化後の拒否を確認する。
|
||||
ジョブの共通試験では claim・完了・再試行・キャンセル・一覧・ログ・集計と read-only 拒否を確認する。
|
||||
PostgreSQL では同時定期登録の一意性、同時 claim の上限、二つ目の worker owner の拒否、
|
||||
再起動後の結果不明ジョブの保留、古い完了 token の拒否、完了ログ故障時の状態保持を確認する。
|
||||
outbox は型別・Domain 別の取得、consumer の独立性、同時 checkpoint の単調性、
|
||||
rollback と read-only 拒否を両 backend で検証する。
|
||||
HTTP 用 lookup と個人表示設定の共通試験では Domain 分離、無効 Principal、対象欠損時の拒否、
|
||||
設定 CAS を確認する。scheduler/outbox/lookup の対象テストは race detector でも検証する。
|
||||
これらは component テストであり、PostgreSQL を指定した通常アプリ起動や本番データ import の成功ではない。
|
||||
|
||||
検証は `GOPROXY=off GOSUMDB=off` とし、実 PostgreSQL の共通テストには
|
||||
`PAGESWIKI_TEST_POSTGRES_DSN` で使い捨て DB を指定する。各テストは専用 schema を作成・削除するため、
|
||||
本番 DB を指定してはならない。実際の外部カレンダー、OIDC/LDAP/SMTP、Gitea へのアクセスは不要。
|
||||
|
||||
2026-11-15 に Gitea の復旧連絡を受領した。移植中は引き続きローカルビルドで検証し、
|
||||
全 repository・通常起動・インポートのリリースゲートを満たした後に、commit/push、
|
||||
SemVer タグ、Gitea CI の image build とリリースへ進む。復旧だけを理由に未完の移植を配布しない。
|
||||
ローカルビルドの成功は DB 切替の許可条件ではなく、上記ゲートと停止状態の全件インポート検証を
|
||||
満たした後、移行前 backup を確保し、同じ成果物で隔離起動試験を経て本番を起動する。
|
||||
|
||||
未対応機能を暗黙に初期化したり、読めないテーブルを cache とみなして捨てたりしない。
|
||||
外部 RDB 障害時に SQLite へ自動 fallback する設定は作らず、二つの DB が別々に
|
||||
更新を受ける状態を防ぐ。最低 PostgreSQL 対応版と CI matrix の確定も切替条件とする。
|
||||
|
||||
#### 片方向インポートと切替の設計
|
||||
|
||||
本番切替は全ゲートが通った後、次の順で行う。全件移行ツールは
|
||||
`pageswiki migrate-postgres` であり、core リハーサルをその代用にしない。
|
||||
|
||||
1. HTTP/CalDAV/CLI、scheduler、federation を含めた全 writer と GC を停止し、保守状態を確認する。
|
||||
2. SQLite の整合した snapshot、Document、カレンダー正本、設定・鍵・instance identity を保全し、復元検証する。
|
||||
3. 空の専用 PostgreSQL へ全件移行し、件数・内容指紋・参照・採番・payload を照合する。
|
||||
4. 読み取り検証でログイン、権限、公開ナビゲーション、検索、タスク/CalDAV、管理・配信を確認する。
|
||||
5. 反映する全プロセスを一斉に PostgreSQL 側へ向け、旧 SQLite は凍結したまま、書き込み再開時点を記録する。
|
||||
|
||||
書き込み再開前にインポートや検証が失敗した場合は移行を中止し、元の SQLite を維持する。
|
||||
書き込み再開後は PostgreSQL を正本とし、障害時は PostgreSQL 側の復旧・修正を基本とする。
|
||||
移行後の更新を SQLite に反映する機能は今回提供せず、接続先を旧 SQLite へ自動で戻さない。
|
||||
この制約を運用手順にも明記し、逆移行の完成を本番切替の前提条件にはしない。
|
||||
|
||||
### S3:運用と移行
|
||||
|
||||
- [ ] 編集可能な設定例と薄い backup / release / deploy script。
|
||||
@@ -404,6 +1217,10 @@ setup 完了後は token 再利用不可。機密欄の再表示・ログ出力
|
||||
## 12. 根拠資料
|
||||
|
||||
- [SQLite WAL:network filesystem の制約](https://sqlite.org/wal.html)
|
||||
- [PostgreSQL の transaction-level advisory lock](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS)
|
||||
- [PostgreSQL の identity 変更](https://www.postgresql.org/docs/current/sql-altertable.html)
|
||||
- [PostgreSQL の RESTART と transaction](https://www.postgresql.org/docs/current/sql-altersequence.html)
|
||||
- [pgx の database/sql 接続](https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib)
|
||||
- [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)
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
# 展示用PagesWikiのKubernetes配置とDNS認証
|
||||
|
||||
## 記録の位置づけ(2026-11-30整理)
|
||||
|
||||
展示は完了し、利用者から成功の報告を受けている。以下は準備・配置時点の記録で、
|
||||
途中の疎通失敗や未確認項目も経緯として残す。現在の障害・稼働状態を示すものではない。
|
||||
今回の整理ではクラスタ・公開URLへ接続せず、再配置・データ投入・Secret操作も行っていない。
|
||||
|
||||
最後に指定された入口は `https://pages.anya.jisaba.sh/`。初期の
|
||||
`pages.jsb.anya.jp`/Cloudflare DNS-01案やHTTP公開案は採用済み設定ではない。
|
||||
[展示ファイル一覧](../../deploy/kubernetes/exhibition/README.md)から用途別に参照する。
|
||||
再利用時は当日の権限・保存先・証明書期限・イメージを確認し、ディレクトリ全体を一括applyしない。
|
||||
|
||||
## 最終指定の入口:HTTPS・pages.anya.jisaba.sh(当時の確認記録)
|
||||
|
||||
2026-11-15、利用者指定により入口を `https://pages.anya.jisaba.sh/` に再変更した。
|
||||
展示キャンパスのFQDNを通常の設定APIで変更し、既存のドメインUUID・空ホスト指定・データを維持。
|
||||
新しいHostでlocalhost限定port-forward越しのログイン、27文書、8タスク、6予定、6連絡先の
|
||||
UID/ETagを確認済み。Serviceは引き続きHTTP port 80、アプリは3000。公開TLS終端はNOC管理。
|
||||
|
||||
この端末からDNS A `202.226.7.202` とHTTP 301による同一ホストHTTPSへの転送を確認した。
|
||||
HTTPSは `/` と `/health` の両方で `Connection reset by peer`(curl exit 35)。
|
||||
証明書検証の成功・公開ログイン・ブラウザ描画は未確認で、公開接続へ資格情報は送っていない。
|
||||
TLS終端/経路/アクセス制御のどこが原因かは未確定。証明書検証を無効化して回避しない。
|
||||
以前の `*.pages.jisaba.sh` とは別のホスト階層なので、新FQDNのListener・Route・証明書が必要。
|
||||
PostgreSQL向けverified TLSは引き続き維持する。
|
||||
|
||||
## 旧公開案:HTTP・wiki.pages.jisaba.sh(上記で置換済み)
|
||||
|
||||
2026-11-15、利用者の確認により入口を `http://wiki.pages.jisaba.sh/` に変更した。
|
||||
NOCへ `*.pages.jisaba.sh` のHTTP・80番転送を依頼済み(利用者報告)。
|
||||
接続先は namespace `exhibit-anya`、Service `pageswiki`、port 80。
|
||||
ワイルドカードに含まれない `pages.jisaba.sh` 自体は入口に使わない。
|
||||
以下の `pages.jsb.anya.jp`・Cloudflare証明書の記述は旧案であり、現行の公開設定ではない。
|
||||
|
||||
既存キャンパスのFQDNだけを通常の設定APIで更新し、ドメインの空ホスト指定、UUID、
|
||||
文書・設定・ユーザーは保持した。localhost限定port-forward経由で新Host名によるログインと
|
||||
27文書、8タスク、6予定、6連絡先のUID/ETagを再確認した。外部カレンダーへはアクセスしていない。
|
||||
公開DNSと会場からのHTTP到達・ブラウザ描画は別の確認事項。
|
||||
HTTPRouteの参照権限はなく、NOC側の適用状況を直接確認できない。
|
||||
|
||||
公開HTTPではログイン資格情報・本文が暗号化されない。展示専用アカウント・合成データだけを使い、
|
||||
本番の認証・秘密情報は持ち込まない。Web Push等のsecure context必須機能は利用できない。
|
||||
これはブラウザ側の通信方針であり、アプリからPostgreSQLへのverified TLSは維持する。
|
||||
任意のサブドメインがPagesのサイトとして自動作成されるわけではない。追加する場合はDomainの登録が必要。
|
||||
|
||||
## 2026年11月15日の配置記録(FQDN変更前を含む)
|
||||
|
||||
以下の初期案よりも、[運営の最新公開手順](https://github.com/cniajp/jisabakan-exhibit/blob/main/docs/publishing.md)と
|
||||
[接続手順](https://github.com/cniajp/jisabakan-exhibit/blob/main/docs/omni-login.md)を優先する。
|
||||
今回の展示は `anya/` → `exhibit-anya` の GitOps 配置であり、Gateway・HTTPRoute・TLS は NOC 管理。
|
||||
この文書の Ingress・Certificate・公開用 LoadBalancer を参加者側で作る手順は適用しない。
|
||||
独自ドメイン `pages.jsb.anya.jp` と Cloudflare DNS-01 を希望する場合も、公開先・TLS の受渡しを NOC と調整する。
|
||||
|
||||
保存済みの別端末用 kubeconfig で読取り・Deployment 作成権限を確認した。
|
||||
`pageswiki-data` は `nfs-csi` の20Gi RWOで Bound、storage quotaの20Giを消費済み。
|
||||
PagesWikiとPostgreSQLをそれぞれ1 replicaで起動済み。requests上限はCPU 2、メモリ4Gi、limits.memoryは8Gi、PVC上限は5。
|
||||
SQLite WALをNFS上で動かさないため、PostgreSQL対応リリースを使って配置する。
|
||||
本番のデータ・鍵・外部カレンダーは展示へ持ち込まない。
|
||||
|
||||
v0.18.0 は通常テスト・PostgreSQL 17実DBテスト・4イメージの公開とrelease昇格が成功済み。
|
||||
アプリの固定イメージは `git.anya.jp/anya/pageswiki-app@sha256:a999fe16f11ef91dbdb9904c63bb43d9ec3caef93f77cc07b1fe4a80460f67f9`。
|
||||
展示用の26ページ・8タスク・6予定・6連絡先は[合成データ手順](../../deploy/kubernetes/exhibition/demo/README.md)で生成できる。
|
||||
通常のimport/API/DAV経路でWiki 26ページ、CSV 1件、タスク8件、予定6件、連絡先6件を投入済み。
|
||||
DBとアプリのPod再作成後も認証・27文書・20 DAVリソースのUID/ETagを確認した。
|
||||
公開FQDNのDNSは手元の名前解決では未登録。NOCのGateway/HTTPRoute/TLS設定と公開ブラウザ確認は残件。
|
||||
|
||||
PVC最上位はroot:root / 0755のまま保持し、承認されたroot初期化で新設した
|
||||
`pageswiki-exhibit-v018/wiki` を10001:10001、`postgres`を70:70として分離した。
|
||||
NFSv4のhard mount、非rootでのhard-link/no-replace・fsync・rename・読み戻しは隔離試験で成功。
|
||||
既存領域の再帰的なchownは行っていない。NFS server側の障害時永続性はこの試験では保証しない。
|
||||
root初期化にはPodSecurity restrictedの警告が出るが、現namespaceのadmissionは許可する。
|
||||
常駐プロセスは非root。クラスタのポリシー自体は変更していない。
|
||||
|
||||
配置済みのマニフェストは `deploy/kubernetes/exhibition/postgres.yaml` と `app.yaml`。
|
||||
今回はkubectlで直接適用しており、運営GitHubの `anya/` へのGitOps反映は未実施。
|
||||
`bootstrap.yaml` は一度限りの初期化用で、継続同期するディレクトリへ入れない。
|
||||
空のSQLiteはemptyDirで起動・停止し、verified TLSで全件importした。
|
||||
停止した合成SQLiteはアプリPVC内の `bootstrap-source/pages.db` に監査用として保存するが、通常起動では開かない。
|
||||
`import-complete.json` が完了記録。初期化Jobを削除・再作成して再移行しない。
|
||||
|
||||
Secretは `pageswiki-exhibition-app`、`pageswiki-exhibition-db`、`pageswiki-exhibition-tls`。
|
||||
新規生成した展示専用値のみを使い、public repositoryへは記録しない。
|
||||
PostgreSQLのサーバー証明書は90日、専用CAは180日で失効するため、長期展示では更新が必要。
|
||||
管理者名は `exhibition-admin`。パスワードはapp Secretの `owner-password` を管理端末で確認する。
|
||||
アプリのFQDN設定は `pages.jsb.anya.jp`。内部確認はlocalhost限定port-forwardとHostヘッダーで行う。
|
||||
|
||||
レジストリ `git.anya.jp` は当初IPv6のみでノードから到達できなかった。
|
||||
IPv4追加後にpullが成功し、release digestを固定して起動した。
|
||||
|
||||
公開までの残件:
|
||||
|
||||
- NOCに `exhibit-anya` のService `pageswiki`、HTTP port 80、全Path、希望ホスト `pages.jsb.anya.jp` を接続先として伝え、DNS・Gateway・TLSを調整する。管理画面はログイン必須であり、展示管理者パスワードを公開しない。
|
||||
- 公開HTTPSからのログイン・各ビューアの描画・操作をブラウザで確認する。現時点の確認はport-forward越しのHTTP/API検証。
|
||||
- 運営GitHubの `anya/` に通常運用のConfigMap・Deployment・Service・NetworkPolicyを移管する。Secretと一度限りのbootstrap Jobは含めず、既存PVCを削除する差分も作らない。GitHubのpush権限はOmni認証とは別に確認する。
|
||||
- NFS server側の永続化保証・保全方針はNOCと確認する。[PostgreSQLのNFS要件](https://www.postgresql.org/docs/17/creating-cluster.html#CREATING-CLUSTER-NFS)に従い、`fsync`は無効化しない。証明書の期限・更新と展示撤収時のSecret/PVCの扱いも決める。
|
||||
|
||||
以降は当初の一般手順として残す。保存と公開経路に関しては上記の実環境に合わせて読み替える。
|
||||
|
||||
運営のKubernetes Clusterを借りる方式Aを第一希望とし、展示用の独立したPagesWikiを1 replicaで配置する。公開名は `pages.jsb.anya.jp`。グローバルDNSに会場から到達できるローカルIPを登録し、Cloudflare DNS-01で取得した証明書をIngressへ設定する。
|
||||
|
||||
本書は実施手順であり、DNS登録・証明書発行・クラスタ操作はまだ実行していない。IP、Namespace、StorageClass、IngressClass、リソース上限は運営との相談後に確定する。本番データ・認証鍵・外部サービス資格情報は流用しない。
|
||||
|
||||
## 1 構成と役割
|
||||
|
||||
| 対象 | 方針 |
|
||||
| --- | --- |
|
||||
| 利用者の入口 | `https://pages.jsb.anya.jp/` |
|
||||
| 追加Domainの例 | `https://blog.pages.jsb.anya.jp/` |
|
||||
| 公開DNS | 入口のローカルIPv4をAへ登録。CloudflareはDNS only |
|
||||
| TLS証明書のSAN | `pages.jsb.anya.jp` と `*.pages.jsb.anya.jp` |
|
||||
| TLS終端 | 運営のIngress Controller等 |
|
||||
| PagesWiki本体 | 1 replica、HTTP 3000、`/data`をPVCへ保存 |
|
||||
| 初期の周辺機能 | code-server・Kroki・外部Campus等は追加せず、本体確認後に判断 |
|
||||
| 証明書の取得 | 自分の管理端末でCertbotとCloudflare pluginを使用 |
|
||||
| 更新 | 証明書更新とTLS Secret反映を一組で行う |
|
||||
|
||||
通信経路は、会場端末からIngressの443、Serviceの80、PagesWiki Podの3000、保存先PVCの順。DNSは入口の住所を知らせるだけで、ネットワーク到達性や経路を作らない。
|
||||
|
||||
DNS-01は公開DNSのTXTを検証するため、Webサーバーへのインターネットからの着信を必要とせず、ワイルドカードも取得できる。[Let's Encrypt DNS-01](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge)
|
||||
|
||||
### ローカルIPを公開DNSへ入れる場合の注意
|
||||
|
||||
- Aへ入れるのは、来場者用ネットワークから到達できるIngressのVIP等。Pod IP、ClusterIP、`127.0.0.1`は使用しない。Node IPを使う場合も443の受け口を運営に確認する。
|
||||
- プライベートIPはインターネット全体から到達できない。会場LANやVPN等で経路がある利用者向けの公開となる。
|
||||
- 公開DNS上に名前とローカルIPが掲載される。公開CAの証明書に含めた名前もCTログの対象となる。[Let's Encrypt CT](https://letsencrypt.org/docs/ct-logs/)
|
||||
- DNSリバインディング対策で公開DNSからのプライベートIP応答を遮断する環境がある。会場の実利用DNSと端末で確認し、必要なら限定的な許可または運営管理のsplit DNSを相談する。防御機能全体を無効にしない。
|
||||
- Cloudflareの通常のオレンジ雲proxyは使わずDNS onlyとする。private originへの接続には別の構成が必要。[Cloudflare proxy status](https://developers.cloudflare.com/dns/proxy-status/)
|
||||
- 証明書の取得成功と、会場からのHTTPS到達成功は別々に検証する。
|
||||
|
||||
## 2 運営から受け取る情報
|
||||
|
||||
| 確認項目 | 必要な情報 |
|
||||
| --- | --- |
|
||||
| 接続 | kubeconfig、Namespace、接続可能な期間・ネットワーク |
|
||||
| 権限 | Deployment、Service、PVC、ConfigMap、Secret、Ingress等の操作、ログとport-forward |
|
||||
| ノード | `linux/amd64`対応。現在のリリースイメージの対象architecture |
|
||||
| リソース | CPU・メモリQuota、PVC容量、ephemeral storage制限 |
|
||||
| 保存 | StorageClass名、実体、SQLiteのlocking/fsyncに適するか、PVC保持・撤収時の扱い |
|
||||
| 公開 | IngressまたはGateway API、Class、入口のローカルIP、会場LANから443の到達性 |
|
||||
| TLS | 自分のNamespaceでTLS Secretを作れるか、終端の所有者、証明書更新の反映方法 |
|
||||
| 通信 | イメージレジストリへのpull、必要な外向き通信、会場DNSでの名前解決 |
|
||||
| セキュリティ | 非root UID、fsGroup、Pod Security、NetworkPolicy等の制約 |
|
||||
| 検証 | 展示前に同じ制約でデプロイ・再起動・HTTPS確認できる期間 |
|
||||
|
||||
最初の相談値は合計CPU 2〜4 vCPU、メモリ4〜8 GiB、PVC 20 GiB程度。計測済みの必要量ではなく、展示データと連携機能の選択後に調整する。NamespaceやIngress Controller、cert-managerを自分でクラスタ全体へ新設する前提にはしない。
|
||||
|
||||
## 3 手元の接続設定
|
||||
|
||||
対応バージョンのkubectlを手元へインストールする。受領したkubeconfigはGitへ入れず、信頼できる運営から受け取ったものだけを使用する。[kubeconfig](https://kubernetes.io/docs/tasks/access-application-cluster/configure-access-multiple-clusters/)
|
||||
|
||||
```bash
|
||||
chmod 600 "$HOME/.kube/jsb-exhibition.yaml"
|
||||
export KUBECONFIG="$HOME/.kube/jsb-exhibition.yaml"
|
||||
export NS='REPLACE_WITH_ASSIGNED_NAMESPACE'
|
||||
|
||||
kubectl config current-context
|
||||
kubectl -n "$NS" get pods
|
||||
kubectl -n "$NS" auth can-i create deployments.apps
|
||||
kubectl -n "$NS" auth can-i create persistentvolumeclaims
|
||||
kubectl -n "$NS" auth can-i create secrets
|
||||
kubectl -n "$NS" auth can-i create ingresses.networking.k8s.io
|
||||
```
|
||||
|
||||
Forbiddenが出たら運営へ相談する。別の管理者contextへ切り替えて回避しない。
|
||||
|
||||
## 4 CloudflareにDNSを登録する
|
||||
|
||||
前提として、対象の実際の権威DNS zoneを自分がCloudflareで管理できることを確認する。`jsb.anya.jp`が別のDNSへ委譲されている場合、親zoneの画面へレコードを追加しただけでは有効にならない。
|
||||
|
||||
```bash
|
||||
dig +short NS anya.jp
|
||||
dig +short SOA pages.jsb.anya.jp
|
||||
dig +trace pages.jsb.anya.jp A
|
||||
```
|
||||
|
||||
`anya.jp`がCloudflare上の対象zoneで、途中のNS委譲がない場合の入力例:
|
||||
|
||||
| 種別 | Name | Content | Proxy | TTL |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| A | `pages.jsb` | 運営指定のIngress入口IPv4 | DNS only | 300秒を目安に選択 |
|
||||
| A | `*.pages.jsb` | 同じIngress入口IPv4 | DNS only | 同上 |
|
||||
|
||||
最初は本体のAだけでもよい。追加Domainを展示する場合にワイルドカードAを使う。不要なAAAAや旧A、競合するCNAMEがあれば影響を確認する。既存の別サービスのレコードを無断で消さない。
|
||||
|
||||
証明書のワイルドカードとDNSのワイルドカードは別設定。`*.pages.jsb.anya.jp`の証明書は `blog.pages.jsb.anya.jp`を含むが、`pages.jsb.anya.jp`自身や `a.b.pages.jsb.anya.jp`はカバーしない。
|
||||
|
||||
```bash
|
||||
# 公開DNSの応答を確認。これは会場の実利用DNSでの確認とは別。
|
||||
dig @1.1.1.1 pages.jsb.anya.jp A +short
|
||||
dig @1.1.1.1 blog.pages.jsb.anya.jp A +short
|
||||
dig @1.1.1.1 pages.jsb.anya.jp AAAA +short
|
||||
|
||||
# CA制限が設定されている場合は親からの継承も含めて確認する
|
||||
dig pages.jsb.anya.jp CAA
|
||||
dig jsb.anya.jp CAA
|
||||
dig anya.jp CAA
|
||||
```
|
||||
|
||||
## 5 自分の管理端末で証明書を取得する
|
||||
|
||||
共有クラスタへCloudflareのzone更新権限を置かないことを基本とする。運営へ渡すのは展示用の証明書・秘密鍵を格納したTLS Secretであり、Cloudflare API Tokenや本番サービスの秘密は渡さない。ただし運営のクラスタ管理者はTLS Secretへアクセス可能なため、鍵の管理責任は事前に合意する。
|
||||
|
||||
### 5.1 CertbotとCloudflare plugin
|
||||
|
||||
以下は自分が管理するUbuntu/Debianホストの例。運営のノードへSSHして実行しない。他のOSでは公式の導入手順を使い、Snap・pip・ディストリビューションpackageのpluginを混在させない。
|
||||
|
||||
```bash
|
||||
sudo apt-get update
|
||||
sudo apt-get install certbot python3-certbot-dns-cloudflare
|
||||
sudo certbot plugins
|
||||
```
|
||||
|
||||
`dns-cloudflare`が利用可能であることを確認する。[Certbot導入](https://eff-certbot.readthedocs.io/en/stable/install.html)、[Cloudflare plugin](https://certbot-dns-cloudflare.readthedocs.io/en/stable/)
|
||||
|
||||
### 5.2 専用API Token
|
||||
|
||||
CloudflareでDNS更新用のAPI Tokenを作る。Global API Keyは使わない。対象は実際に権威を持つ特定のzoneだけに限定し、全zoneを許可しない。DNS編集と、利用するclientがzone検出に必要とするzone読取を確認する。
|
||||
|
||||
Cloudflare Tokenの典型的な権限は `Zone / DNS / Edit` と `Zone / Zone / Read`。zoneを `anya.jp`へ限定しても、このTokenは `pages.jsb`のレコードだけに限定された権限とは限らない。より狭い委譲が必要なら認証専用zoneへの委譲を別途設計する。cert-managerの設定例をそのままCertbotへ流用しない。[Cloudflare認証設定](https://cert-manager.io/docs/configuration/acme/dns01/cloudflare/)
|
||||
|
||||
```bash
|
||||
install -d -m 700 "$HOME/.config/pageswiki-exhibition"
|
||||
```
|
||||
|
||||
エディタで `$HOME/.config/pageswiki-exhibition/cloudflare.ini` を作成する:
|
||||
|
||||
```ini
|
||||
dns_cloudflare_api_token = REPLACE_WITH_DEDICATED_TOKEN
|
||||
```
|
||||
|
||||
```bash
|
||||
chmod 600 "$HOME/.config/pageswiki-exhibition/cloudflare.ini"
|
||||
export ACME_EMAIL='REPLACE_WITH_YOUR_EMAIL'
|
||||
```
|
||||
|
||||
Tokenをコマンド引数、Git、チャット、一般ログへ書かない。作業端末からCloudflare API・ACMEへのHTTPSと、必要な公開DNS問い合わせが通ることを確認する。
|
||||
|
||||
### 5.3 stagingで確認する
|
||||
|
||||
```bash
|
||||
sudo certbot certonly \
|
||||
--test-cert \
|
||||
--non-interactive --agree-tos \
|
||||
--email "$ACME_EMAIL" \
|
||||
--cert-name pages-jsb-staging \
|
||||
--dns-cloudflare \
|
||||
--dns-cloudflare-credentials "$HOME/.config/pageswiki-exhibition/cloudflare.ini" \
|
||||
--dns-cloudflare-propagation-seconds 60 \
|
||||
-d 'pages.jsb.anya.jp' \
|
||||
-d '*.pages.jsb.anya.jp'
|
||||
```
|
||||
|
||||
DNS-01のTXT名は `_acme-challenge.pages.jsb.anya.jp`。親名とワイルドカードの認証で、同じ名前に複数TXT値を使う場合がある。clientが作った値を手で上書き・削除しない。propagation待ちは環境に応じて調整する。
|
||||
|
||||
staging証明書はブラウザに信頼されないため、本番用TLS Secretには使わない。
|
||||
|
||||
### 5.4 本番CAで発行する
|
||||
|
||||
```bash
|
||||
sudo certbot certonly \
|
||||
--non-interactive --agree-tos \
|
||||
--email "$ACME_EMAIL" \
|
||||
--cert-name pages-jsb \
|
||||
--dns-cloudflare \
|
||||
--dns-cloudflare-credentials "$HOME/.config/pageswiki-exhibition/cloudflare.ini" \
|
||||
--dns-cloudflare-propagation-seconds 60 \
|
||||
-d 'pages.jsb.anya.jp' \
|
||||
-d '*.pages.jsb.anya.jp'
|
||||
|
||||
sudo openssl x509 \
|
||||
-in /etc/letsencrypt/live/pages-jsb/fullchain.pem \
|
||||
-noout -subject -issuer -dates -ext subjectAltName
|
||||
```
|
||||
|
||||
CAが発行した実際の有効期限を確認する。固定の日数を前提に展示予定を組まない。失敗時にforce-renewalを連打せず、DNS・CAA・API権限・通信を確認する。
|
||||
|
||||
## 6 PagesWikiを先に内部確認する
|
||||
|
||||
Namespace内にPVC、1 replicaのDeployment、ClusterIP Serviceを配置する。[マニフェストひな形](../../deploy/kubernetes/exhibition/pageswiki.yaml.example)を作業領域の `pageswiki.yaml` にコピーし、`REPLACE_WITH_STORAGE_CLASS`、使用するreleaseタグ、運営指定のUID・Quota等を確認してから適用する。
|
||||
|
||||
| 設定 | 方針 |
|
||||
| --- | --- |
|
||||
| image | 検証済みのreleaseタグまたはdigestで固定。latestを使わない |
|
||||
| 本体 | `replicas: 1`、通常更新は `strategy.type: Recreate` |
|
||||
| port | `3000`。DockerfileのEXPOSEだけを待受の根拠にしない |
|
||||
| env | `PAGESWIKI_DATA_DIR=/data` |
|
||||
| 保存 | `/data`をPVC、必要な一時領域は別途確保 |
|
||||
| health | `/health`にstartup/readiness probe。起動処理中の再起動連発を避ける |
|
||||
| 権限 | 運営の非root・fsGroup等の方針で新規volumeの書き込みを検証する |
|
||||
|
||||
SQLite向け保存のlocking/fsyncを確認する。`ReadWriteOnce`自体は1 Podだけの排他保証ではない。対応CSIならReadWriteOncePodも相談し、いずれも手動の二重writerを作らない。[Volume access modes](https://kubernetes.io/docs/concepts/storage/persistent-volumes/)
|
||||
|
||||
```bash
|
||||
kubectl -n "$NS" apply --dry-run=server -f pageswiki.yaml
|
||||
kubectl -n "$NS" apply -f pageswiki.yaml
|
||||
kubectl -n "$NS" rollout status deployment/pageswiki --timeout=10m
|
||||
kubectl -n "$NS" get pods,pvc,svc
|
||||
kubectl -n "$NS" port-forward service/pageswiki 8080:80
|
||||
```
|
||||
|
||||
別ターミナルで `curl http://localhost:8080/health`。ブラウザで `http://localhost:8080/_/auth/login` を開き、初期管理者を作成する。初回画面要求時に生成されるbootstrap tokenは自分だけでログを確認し、貼り付け・共有しない。アカウント作成後はenforcing等の認可設定を確認し、外部公開前にログイン・匿名拒否を試す。
|
||||
|
||||
PagesWikiのCampus FQDNを `pages.jsb.anya.jp`、本体Domainのホスト名を空として、Campus FQDN自身を本体へ対応させる。既存の本番Campusへ参加させない。Wiki名等も展示用にする。FQDN変更後にlocalhostでDomainを解決できなくなる場合は、公開経路または適切なHostを用いて検証する。`PAGESWIKI_INSTANCE_FQDN`はCampus/Domain設定の代わりにはならない。
|
||||
|
||||
## 7 TLS Secretを作成する
|
||||
|
||||
証明書・秘密鍵を持つ管理端末にkubectlと運営用kubeconfigがある場合の例。証明書ファイルだけを保護した一時領域へコピーし、kubectl自体は通常の利用者として実行する。kubeconfigのcontext、Namespaceを必ず確認する。
|
||||
|
||||
```bash
|
||||
kubectl config current-context
|
||||
|
||||
# bashのサブシェル内で実行し、終了時に一時コピーを消す
|
||||
(
|
||||
set -euo pipefail
|
||||
TLS_TMP="$(mktemp -d)"
|
||||
chmod 700 "$TLS_TMP"
|
||||
trap 'rm -f "$TLS_TMP/tls.crt" "$TLS_TMP/tls.key"; rmdir "$TLS_TMP"' EXIT
|
||||
sudo install -m 600 -o "$(id -u)" -g "$(id -g)" \
|
||||
/etc/letsencrypt/live/pages-jsb/fullchain.pem "$TLS_TMP/tls.crt"
|
||||
sudo install -m 600 -o "$(id -u)" -g "$(id -g)" \
|
||||
/etc/letsencrypt/live/pages-jsb/privkey.pem "$TLS_TMP/tls.key"
|
||||
kubectl -n "$NS" create secret tls pages-jsb-tls \
|
||||
--cert="$TLS_TMP/tls.crt" --key="$TLS_TMP/tls.key" \
|
||||
--dry-run=client -o yaml | \
|
||||
kubectl -n "$NS" apply --server-side --field-manager=pageswiki-exhibition-tls -f -
|
||||
)
|
||||
|
||||
kubectl -n "$NS" describe secret pages-jsb-tls
|
||||
```
|
||||
|
||||
shellでpipelineを使う作業は `set -o pipefail` を有効にする。上記をログ収集用の `tee` へ流さない。server-side applyは秘密値をlast-applied annotationへ重複保存しないために使う。競合時は所有者を確認し、`--force-conflicts`で他の管理主体を奪わない。運営のRBAC・admissionでこの方法が許可されない場合は、運営指定の秘密投入手順へ切り替える。
|
||||
|
||||
SecretとIngressは同じNamespaceに置く。証明書の公開部分と秘密鍵は用途が異なり、TLS Secret全体のYAMLやbase64値を公開しない。[kubectl create secret tls](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_create/kubectl_create_secret_tls/)
|
||||
|
||||
## 8 Ingressを作成する
|
||||
|
||||
以下を `pageswiki-ingress.yaml` として保存する。`REPLACE_WITH_INGRESS_CLASS`を実際の値へ変更する。運営がIngressを所有する場合、この設定内容を渡して運営に反映を依頼する。Gateway APIの場合は同等のHTTPRouteとTLS設定へ読み替える。
|
||||
|
||||
```yaml
|
||||
apiVersion: networking.k8s.io/v1
|
||||
kind: Ingress
|
||||
metadata:
|
||||
name: pageswiki
|
||||
spec:
|
||||
ingressClassName: REPLACE_WITH_INGRESS_CLASS
|
||||
tls:
|
||||
- hosts:
|
||||
- pages.jsb.anya.jp
|
||||
- "*.pages.jsb.anya.jp"
|
||||
secretName: pages-jsb-tls
|
||||
rules:
|
||||
- host: pages.jsb.anya.jp
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: pageswiki
|
||||
port:
|
||||
number: 80
|
||||
- host: "*.pages.jsb.anya.jp"
|
||||
http:
|
||||
paths:
|
||||
- path: /
|
||||
pathType: Prefix
|
||||
backend:
|
||||
service:
|
||||
name: pageswiki
|
||||
port:
|
||||
number: 80
|
||||
```
|
||||
|
||||
```bash
|
||||
kubectl -n "$NS" apply --dry-run=server -f pageswiki-ingress.yaml
|
||||
kubectl -n "$NS" apply -f pageswiki-ingress.yaml
|
||||
kubectl -n "$NS" describe ingress pageswiki
|
||||
```
|
||||
|
||||
ワイルドカードIngressがあっても、未知HostをPagesWikiの本体Domainへフォールバックさせない。`blog`等を使う場合はPagesWiki側でもDomainを作成し、ホスト名を登録する。設定しない子Domainが404等になることは正常な拒否である。
|
||||
|
||||
Ingressでは元のHostを保ち、TLS終端後の `X-Forwarded-Proto: https` 等の扱いを確認する。転送ヘッダは信頼したIngressで上書きし、利用者からの偽装値をそのまま通さない。HTTPS redirect、アップロードサイズ、長い要求、将来のadapter接続はController固有の設定として相談する。
|
||||
|
||||
## 9 会場から検証する
|
||||
|
||||
```bash
|
||||
# 実際に利用者が使うDNSの答えと、経路を確認する
|
||||
dig pages.jsb.anya.jp A +short
|
||||
curl -I https://pages.jsb.anya.jp/
|
||||
|
||||
# DNS反映前でも、正しいSNIとHostを維持して入口だけ指定できる
|
||||
export INGRESS_IP='REPLACE_WITH_ASSIGNED_INGRESS_IP'
|
||||
curl --resolve "pages.jsb.anya.jp:443:$INGRESS_IP" \
|
||||
-I https://pages.jsb.anya.jp/
|
||||
|
||||
# 信頼チェーンとホスト名を検証する。検証失敗を-kで隠さない
|
||||
openssl s_client \
|
||||
-connect "$INGRESS_IP:443" \
|
||||
-servername pages.jsb.anya.jp \
|
||||
-verify_hostname pages.jsb.anya.jp \
|
||||
-verify_return_error </dev/null
|
||||
```
|
||||
|
||||
合格条件:展示LANの端末で名前解決とTCP443が通る、SAN・有効期限・信頼チェーンが正しい、ログインとログアウトが動く、非公開文書へ匿名アクセスできない、編集保存とPod再起動後の永続化が動く、必要な追加Domainだけが正しい。会場外から接続不可であることはプライベートIP構成では想定内。
|
||||
|
||||
## 10 更新と撤収
|
||||
|
||||
証明書更新後も、クラスタのTLS Secretは自動的には更新されない。まずstagingで試した後、必要な時期にCertbotの `renew --cert-name pages-jsb` を実施し、手順7で同じSecretへ反映する。Ingress ControllerがSecret更新を取り込んだことを実接続で確認する。自動更新するなら、更新とSecret反映の両方を自分の管理ホストで監視付きに運用する。
|
||||
|
||||
```bash
|
||||
sudo certbot renew --cert-name pages-jsb --dry-run
|
||||
sudo certbot renew --cert-name pages-jsb
|
||||
```
|
||||
|
||||
cert-managerを使う場合は代わりに運営の許可を得て既設controllerを利用する。Namespace内のIssuer、Cloudflare Token Secret、Certificateを同じNamespaceに置き、CertificateのdnsNamesを親名とワイルドカード、secretNameを `pages-jsb-tls` とする。Secretへ手動投入する方式とcert-managerに同じSecretを同時管理させない。ClusterIssuer作成権限やcert-manager新設を要求しない。[Issuerのscope](https://cert-manager.io/docs/concepts/issuer/)、[Certificate](https://cert-manager.io/docs/usage/certificate/)
|
||||
|
||||
ただしAPI Tokenを共有クラスタへ置く権限・影響、Cloudflare/ACMEへの外向き通信、DNS self-checkを事前確認する。外部で発行してTLSだけ持ち込む方式なら、これらをクラスタへ追加する必要はない。
|
||||
|
||||
撤収時は、展示データを整合した手段で保全し、公開経路停止、展示用のAレコード整理、TLS鍵・専用Token・kubeconfigの保持/失効、PVCの保持/削除を運営と合意する。NamespaceやPVCの削除を再起動の代わりに使わない。
|
||||
|
||||
## 参考資料
|
||||
|
||||
- [certbot-dns-cloudflare](https://certbot-dns-cloudflare.readthedocs.io/en/stable/)
|
||||
- [Let's Encryptの認証方式](https://letsencrypt.org/docs/challenge-types/)
|
||||
- [Cloudflare DNS onlyとproxy](https://developers.cloudflare.com/dns/proxy-status/)
|
||||
- [Kubernetes Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/)
|
||||
- [単一インスタンスの配置例](https://kubernetes.io/docs/tasks/run-application/run-single-instance-stateful-application/)
|
||||
- [PagesWikiの運用・保全設計](../design/ja/operations.md)
|
||||
|
||||
公式資料確認日:2026-11-12。記載例は実クラスタへ適用していない。運営指定のClass、証明書終端方式、UID、Quotaが確定してからマニフェストを検証する。
|
||||
@@ -0,0 +1,32 @@
|
||||
# 展示環境についてのNOCへの返信案
|
||||
|
||||
> 初期相談時の草案を保存したもの。実際の展示ではPostgreSQLとNOC管理の公開経路を利用し、
|
||||
> 最終指定URLは `https://pages.anya.jisaba.sh/` となった。以下を現在の依頼文として再送しない。
|
||||
> 配置の経緯は [展示運用記録](exhibition-kubernetes-dns-tls.md) を参照。
|
||||
|
||||
ぼいどさん
|
||||
|
||||
ご連絡ありがとうございます。
|
||||
PagesWikiの展示について、Aの運営側で用意されているKubernetes Clusterを利用させていただければと思っています。
|
||||
|
||||
こちらでコンテナイメージとデプロイ用のマニフェストを用意し、割り当ていただいたNamespace内へ配置する想定です。クラスタ全体の管理権限や特権コンテナは必要としない構成で考えています。Kubernetesの利用経験がまだ少ないため、事前に動作確認できる期間をいただけると助かります。
|
||||
|
||||
アプリは現在SQLiteとファイル保存を使う単一writer構成のため、本体は1 replicaとし、永続ボリュームを利用したいです。リソースはひとまず合計CPU 2〜4 vCPU、メモリ4〜8 GiB、永続ストレージ20 GiB程度を目安に相談させてください。展示する機能を絞って検証し、必要量を調整する予定です。
|
||||
|
||||
アクセス先は、こちらで管理する `pages.jsb.anya.jp` を使用したいと考えています。グローバルDNSに、会場ネットワークから到達できるIngress等のローカルIPをAレコードとして登録する想定です。追加のドメイン展示用に `*.pages.jsb.anya.jp` も同じ入口へ向けられると助かります。DNSはCloudflareのDNS onlyとし、Cloudflare経由の通信中継は利用しません。
|
||||
|
||||
証明書はこちらでCloudflareのDNS-01認証を使い、`pages.jsb.anya.jp` と `*.pages.jsb.anya.jp` を含むものを取得する予定です。DNS操作用のAPI Tokenは共有クラスタへ置かず、証明書と秘密鍵だけをTLS Secretとして持ち込み、Ingress側でTLS終端する形を第一案としています。
|
||||
|
||||
以下について教えていただけますでしょうか。
|
||||
|
||||
- Namespaceの割り当てと接続方法、利用できるリソース・権限の範囲
|
||||
- linux/amd64のイメージが動くことと、外部レジストリ `git.anya.jp` からのpull可否
|
||||
- 利用可能なStorageClassと、そのストレージがSQLiteの保存先に適しているか
|
||||
- Ingress等の利用方法と、DNSへ登録できるローカルIP、会場端末からの到達性
|
||||
- 持ち込み証明書によるTLS終端の可否と、Secretの投入・更新方法
|
||||
- 会場DNSで、公開DNSに登録したプライベートIPがリバインディング対策等で遮断されないか
|
||||
- Podの実行権限・ネットワーク等の制約と、事前検証できる期間
|
||||
|
||||
もしストレージや公開経路などの制約でAが難しい場合は、BのVM提供も含めて相談させていただければと思います。
|
||||
|
||||
よろしくお願いいたします。
|
||||
@@ -1,8 +1,9 @@
|
||||
# Gecko連携の再配布条件
|
||||
|
||||
PagesWiki v0.13.0は、自作の連携コードと中継サービスのソースを配布し、Geckoエンジンは同梱しません。
|
||||
実験機能`viewer.gecko`は既定無効のままです。既存3イメージのリリースにエンジンを追加せず、
|
||||
専用relayも上流エンジンを含まないDockerfileとして提供します。
|
||||
PagesWiki v0.13.0ではGeckoエンジンの配布を保留しました。
|
||||
現在は固定版のエンジン、対応ソース、第三者NOTICE、日本語フォントを含む配布bundleを生成できます。
|
||||
実験機能`viewer.gecko`は既定無効のままです。relayイメージとbundleは別物で、
|
||||
起動時にbundle全体を検証してから資産を配信します。
|
||||
本書は今回追加した部品の配布判断と残件を整理するもので、プロジェクト全体の法務監査ではありません。
|
||||
|
||||
## 部品と適用条件
|
||||
@@ -17,6 +18,8 @@ PagesWiki v0.13.0は、自作の連携コードと中継サービスのソース
|
||||
| Emscripten runtime / WasmFS | 6.0.1と上流のpatch | Emscripten本体はMITまたはUIUC/NCSA。libc等のruntime依存には別noticeがあるため、ツールチェーンの最上位LICENSEだけでは棚卸し完了としない |
|
||||
| zstddec | 0.2.0 | npm metadataは`MIT AND BSD-3-Clause`。JS wrapperと組み込まれたdecoderの両noticeを保持 |
|
||||
| Liberation fonts | 上記Firefox commit内のPDF.js standard_fonts | SIL OFL 1.1。著作権表示・OFL本文・Reserved Font Namesを保持 |
|
||||
| Rust standard libraryと依存crate | 1.95.0と`library/Cargo.lock` | RustのMIT/Apache-2.0と各crateの個別条件。lockに記載された全registry crateのsource・noticeを保持 |
|
||||
| Noto Sans CJK JP | Sans2.004、`523d033d6cb47f4a80c58a35753646f5c3608a78` | SIL OFL 1.1。未改変OTF、Adobeの埋込著作権表示、OFL本文を保持 |
|
||||
|
||||
relayのruntimeイメージは`FROM scratch`とし、Goバイナリとlicenseだけを含めます。
|
||||
Alpine/BusyBoxを新たに再配布する構成にはしません。`go list -deps`でrelayにリンクされる外部Go moduleは
|
||||
@@ -62,9 +65,28 @@ MPLはファイル単位の義務であり、別実装のWiki全体をMPLへ変
|
||||
4. 提供するsourceとnoticeの可用性・保全、配布物とのhash対応を検査する。
|
||||
5. Mozillaの商標はコードlicenseとは別に扱い、Firefoxの公式配布であるとの表現やロゴの流用をしない。
|
||||
|
||||
現時点では2・3・4の配布用bundleが未完成です。今回のrelease artifactにエンジンは載せず、
|
||||
本番では中継用鍵・資産mount・`viewer.gecko`の有効化を追加しません。
|
||||
エンジン非同梱の連携コードと、通常のRSSフォルダショートカットはリリース対象です。
|
||||
### 配布bundle
|
||||
|
||||
`tools/gecko/sources.lock.json`に取得元とSHA-256を固定し、`tools/gecko/bundle.py`で組み立てます。
|
||||
生成物は98ファイル、合計1,196,102,561 bytes(manifest自身を除く)です。
|
||||
manifestのSHA-256は`84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381`。
|
||||
同じ値をrelay側で固定し、列挙された全ファイルのサイズ・hash・通常ファイルであることを起動時に検査します。
|
||||
不足、改変、symlink、別版混入を許可しません。
|
||||
|
||||
元のsource archiveを変更せず保存し、license/copying/copyright/notice/authorsファイルを別の閲覧用テキストにも集約します。
|
||||
Mozillaの条件付きnoticeは**全分岐を含む保守的な上位集合**としてテキスト化し、元のHTMLはsource archiveに保持します。
|
||||
Rustの追加依存はCargo.lockのチェックサムで検証します。crateから欠けていたFortanixのMPLヘッダと
|
||||
vex-sdkのMIT本文も、元ソース・固定commitから補完しています。
|
||||
Notoの未改変フォントには`© 2014-2021 Adobe (http://www.adobe.com/).`が埋め込まれ、READMEにも保持します。
|
||||
|
||||
閲覧画面のⓘは`/_/api/v1/extension/organizer.feeds/browser/distribution/v0.0.1/index.html`を開きます。
|
||||
同じ入口からNOTICE、manifest、ソース一式を取得できます。認証は必要ですが、RSS・Geckoを無効化した後も、
|
||||
認証済みの受領者はソースを取得できます。readonly利用者も取得可能です。
|
||||
relay自体を撤去する場合は、先にbundleと取得先を保全・移設してください。無効化はソース提供の撤回を意味しません。
|
||||
|
||||
CIは中継バイナリの4番目のイメージを配布しますが、約1.2GBのbundleを通常イメージへ重複同梱しません。
|
||||
検証済みbundleをread-onlyでmountする運用です。再配布条件の充足はこの固定版・未改変バイナリ・
|
||||
保持したsource/noticeを前提とします。依存更新時はlockとnoticeを再確認し、公開済みbundleを上書きしません。
|
||||
|
||||
## 一次資料
|
||||
|
||||
@@ -75,3 +97,5 @@ MPLはファイル単位の義務であり、別実装のWiki全体をMPLへ変
|
||||
- [zstddec 0.2.0 metadata](https://registry.npmjs.org/zstddec/0.2.0)
|
||||
- [Go LICENSE](https://go.dev/LICENSE)
|
||||
- [golang.org/x/net v0.35.0 LICENSE](https://go.googlesource.com/net/+/refs/tags/v0.35.0/LICENSE)
|
||||
- [Noto CJK固定版OFL](https://github.com/notofonts/noto-cjk/blob/523d033d6cb47f4a80c58a35753646f5c3608a78/LICENSE)
|
||||
- [vex-sdk固定版MIT](https://github.com/vexide/vex-sdk/blob/6c0b83d35b6fc31a7607efe456e387df45476314/LICENSE.md)
|
||||
@@ -28,7 +28,8 @@ WebSocketではOriginも検査し、grantは一回限りです。既存接続の
|
||||
bac28056a00ef6e5fb4345117e73d3629e75aca00dac71389fabbce39c018a73
|
||||
```
|
||||
|
||||
展開後の`gecko.js/dist/`をread-onlyで`/gecko`へmountします。起動時に次の両ファイルのhashを確認し、
|
||||
エンジン単体の`dist/`ではなく、後述するsource/notice付きbundleをread-onlyで`/gecko`へmountします。
|
||||
起動時に次の両ファイルに加え、manifestに列挙された全ソース・NOTICE・フォントをhash検査し、
|
||||
欠損・改変・異なる版の混在があれば中継は起動しません。
|
||||
|
||||
| ファイル | SHA-256 |
|
||||
@@ -37,13 +38,27 @@ bac28056a00ef6e5fb4345117e73d3629e75aca00dac71389fabbce39c018a73
|
||||
| gecko.wasm.zst | ebd6c75179152624d9644865e11792ed25cadc714d9e0985f412baf9c637a086 |
|
||||
|
||||
資産URLにも`assets/v0.0.1/`を含め、版をまたいだJS/WASMのcache混在を避けます。
|
||||
初回にはJSと圧縮WASMの合計38,175,359 bytes(約36.4MiB)の転送とWASMの展開・compileが必要です。
|
||||
初回にはJS・圧縮WASM・日本語フォントの合計54,643,095 bytes(約52.1MiB)の転送とWASMの展開・compileが必要です。
|
||||
約1.2GBの対応ソースは閲覧の起動時には取得せず、ⓘから明示的にダウンロードするときだけ配信します。
|
||||
本体のDocker buildにFirefoxのソースビルドを加えません。
|
||||
|
||||
`Dockerfile.gecko-relay`は自前の中継バイナリだけを含みます。エンジンは同梱・再配布しません。
|
||||
**エンジンをイメージへ同梱する場合だけでなく、mountした資産を利用者へ配信する前にもnoticeと対応sourceの提供が必要です。**
|
||||
固定版のMPL宣言、第三者依存物、今回の配布範囲は[再配布条件](gecko-redistribution.md)を参照してください。
|
||||
v0.13.0の本番配備ではエンジンを配信せず、機能の有効化も行いません。
|
||||
v0.13.0の本番配備ではエンジンを配信していません。新しいrelayは完成したbundleを必須とします。
|
||||
|
||||
### bundle生成
|
||||
|
||||
Python 3.11以降を使い、十分な空き容量のあるディスク上で実行します。ソースarchiveは展開せず保持します。
|
||||
|
||||
```sh
|
||||
python tools/gecko/bundle.py --cache /srv/gecko-cache --output /srv/gecko/v0.0.1-bundle1
|
||||
# 同一入力からの再生成。出力先はまだ存在しない新しいディレクトリを指定する。
|
||||
python tools/gecko/bundle.py --cache /srv/gecko-cache --output /srv/gecko/rebuilt --offline
|
||||
```
|
||||
|
||||
出力manifestのSHA-256が`84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381`と一致することを確認します。
|
||||
稼働中のmount先を上書きせず、source/noticeの提供を含めて不変の単位で保全します。
|
||||
|
||||
## 配置
|
||||
|
||||
@@ -55,7 +70,8 @@ v0.13.0の本番配備ではエンジンを配信せず、機能の有効化も
|
||||
| 変数 | 内容 |
|
||||
| --- | --- |
|
||||
| PAGESWIKI_GECKO_KEY_PATH | 32文字以上の十分ランダムな共有鍵のファイル絶対Path。appとrelayへ同じread-only mount |
|
||||
| PAGESWIKI_GECKO_ASSETS_DIR | hash確認した`gecko.js/dist`の絶対Path |
|
||||
| PAGESWIKI_GECKO_ASSETS_DIR | 全ファイルを検証したbundleの絶対Path。engineだけのdistは禁止 |
|
||||
| PAGESWIKI_GECKO_IMAGE | Giteaで配布した`pageswiki-gecko-relay:sha-...`またはrelease tag。省略時は開発用image |
|
||||
| PAGESWIKI_GECKO_FRONT_SUBNET | 内部接続網。既定`172.24.0.0/27`。既存LANとの重複を避ける |
|
||||
| PAGESWIKI_GECKO_EGRESS_SUBNET | 中継の外向き網。既定`172.24.0.32/27` |
|
||||
|
||||
@@ -100,7 +116,8 @@ UDP、80/443以外のTCP、単一ラベルのホスト名は拒否します。
|
||||
| WebSocket受信idle | 90秒 |
|
||||
| 宛先接続 | 名前解決込み8秒、個別dial 2秒 |
|
||||
| relayコンテナ | 256MiB、0.5 CPU、64 PIDs、read-only、capabilitiesなし |
|
||||
| 閲覧プロファイル | volatileな32MiB・2,048 entries、端末のOPFSへ永続化しない |
|
||||
| 閲覧プロファイル | 日本語フォントを含むvolatileな32MiB・2,048 entries、端末のOPFSへ永続化しない |
|
||||
| source/noticeダウンロード | 全体2接続まで。ETag・Range対応。閲覧streamの枠とは分離 |
|
||||
|
||||
relayの稼働状態・接続数・送受信bytes・拒否数は、コンテナ内の次の操作でJSON取得できます。
|
||||
鍵はファイルから読み、標準出力には含めません。counterは再起動でリセットします。
|
||||
@@ -134,7 +151,10 @@ extension viewer.gecko off
|
||||
|
||||
```sh
|
||||
go test -race ./internal/geckorelay ./internal/server -run 'TestGrant|TestDestinations|TestRelay|TestAssets|TestFeedGeckoAuthorization|TestFeedGeckoWebsocket'
|
||||
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/gecko.js/dist go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/bundle go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||
PAGESWIKI_GECKO_TEST_BUNDLE=/verified/bundle go test ./internal/geckorelay -run TestDistribution
|
||||
# 公開テストサイトへの実通信。実RSS・外部カレンダー・メールは使用しない。
|
||||
PAGESWIKI_BROWSER_TEST=1 PAGESWIKI_GECKO_TEST_ASSETS=/verified/bundle PAGESWIKI_GECKO_PUBLIC_HTTPS_TEST=1 go test ./internal/server -run '^TestFeedGeckoChromium$' -count=1
|
||||
node internal/server/testdata/feed-gecko-profile.mjs
|
||||
```
|
||||
|
||||
@@ -144,6 +164,12 @@ node internal/server/testdata/feed-gecko-profile.mjs
|
||||
標準のhistory.back()が失敗するため、フォーム内容やスクロール位置を復元する履歴ではありません。
|
||||
画面のcanvasは最大1920×1080、experimental WASM JITとGPUは無効です。
|
||||
|
||||
本番の標準機能に昇格する前に、HTTPSサイトと証明書エラーの表示、Safari/iPhone SE、IME、コピー、
|
||||
find、実サイト互換性、複数タブ・起動失敗時のUX、低メモリ端末の測定、コンテナ外向きfirewallを検証します。
|
||||
HTTPSの実描画と期限切れ証明書の拒否を確認しました。上流最小GREはエラーページの部品が不足するため、
|
||||
`about:neterror`/`about:certerror`を検知してcanvasを隠し、PagesWiki側で説明します。証明書の無視・例外追加は提供しません。
|
||||
Noto CJKをメモリプロファイルのfontsに置き、エンジンを改変せず日本語描画も確認しています。
|
||||
|
||||
検索アイコンまたはCtrl/Cmd+Fからページ内検索できます。検索語は256文字まで、前後検索と一致なしの表示に対応し、合成記事で日本語検索を確認しています。起動失敗または120秒の起動上限到達時はiframeを破棄し、元記事を別タブで開く導線を残します。上流のdestroy呼出しだけではWASM資源の解放にならないため、親側のiframe破棄まで行います。`TestFeedGeckoStartupFailureChromium` はフォント取得失敗時の破棄と代替導線を検証します。
|
||||
|
||||
本番の標準機能に昇格する前に、Safari/iPhone SE、IME、コピー、実サイト互換性、
|
||||
複数タブ・低メモリ端末の測定、コンテナ外向きfirewallを検証します。
|
||||
外部ページのiframe拒否とは別の仕組みですが、すべてのサイトでの動作や軽さを保証するものではありません。
|
||||
@@ -11,6 +11,9 @@ runner の環境構築や Gitea の事前疎通診断は行わず、本番へ自
|
||||
| `pageswiki-app`(app / app2 共通) | `Dockerfile` |
|
||||
| `pageswiki-adaptor-gateway` | `Dockerfile.adapter-gateway` |
|
||||
| `pageswiki-excalidraw-viewer` | `Dockerfile.excalidraw-viewer` |
|
||||
| `pageswiki-gecko-relay`(任意) | `Dockerfile.gecko-relay` |
|
||||
|
||||
v0.15.0以降はGecko relayを含む4イメージをビルド・昇格します。以下の「3イメージ」は通常配備するapp・gateway・Excalidrawの組を指します。Gecko relayは別overlayで明示的に配備するもので、通常の本番更新では起動しません。
|
||||
|
||||
Kroki、Mermaid、code-server は upstream の配布イメージを使用する。
|
||||
`main` / `mk_district` への push、手動実行でビルド・公開する。
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# メールWikiのPath依存404の調査
|
||||
|
||||
## 状態と回避策
|
||||
|
||||
2026年11月6日、別インスタンスでNeoMuttから作成したWikiが一覧には見える一方、`/tasks` とその配下への直接アクセスで `{"detail":"Not Found"}` になる報告があった。同じオブジェクトに `/prj/awesome` 側のリンクを追加すると表示できた。原因は未確定で、修正済みとは扱わない。
|
||||
|
||||
回避策は表示できるWiki親prefixを既定値にし、既存オブジェクトには別Pathのリンクを使うこと。メールの再取り込み、オブジェクトの削除、既存Pathの一括移動は不要。Pathごとに権限が異なりうるため、新しいリンク先の公開範囲も確認する。
|
||||
|
||||
## アプリ内で確認した境界
|
||||
|
||||
タスク画面は `/v/plan/tasks`、APIは `/_/api/v1/extension/organizer.tasks/`。`/tasks` は予約ルートではなく、通常のWiki Pathとして解決する。末尾スラッシュは301で取り除く。
|
||||
|
||||
NeoMuttの `pipe_decode=no`・`pipe_split=yes` 相当の標準入力を使い、CLIプロセスから一時DBのフルHTTPハンドラへ取り込む試験を追加した。42パターンは、親prefix7種類、UTF-8/ISO-2022-JPの件名、ML連番/Message-ID/原文hashの組合せ。公開CLI v0.4.0でも一覧のdata-path、直接表示、末尾スラッシュ、言語指定を確認し、代表3パターンをChromiumで表示した。実メール・実アカウント設定は使用しない。
|
||||
|
||||
Python・Chromiumに依存しないGoテストでは、実際のAPIへ既定prefix `/tasks` を設定して取り込み、同一オブジェクトの `/tasks/...` と `/prj/awesome` の両方がHTMLの200を返すことを検証する。未認証閲覧のログイン誘導、一覧表示、旧CLI形式も対象。CIでPythonがない場合もこのテストは実行される。
|
||||
|
||||
親に文書がない場合は、仮想フォルダページ無効ならHTMLの404、有効ならchildren一覧の200となる。これは作成済み子ページまでJSONの404になる報告とは区別する。設定箇所は `/-/sys/config?panel=home` の「仮想フォルダページ」。設定は対象ドメイン単位で、調査のために自動変更しない。
|
||||
|
||||
## 機密情報を共有しない切り分け
|
||||
|
||||
以下は問題のインスタンス内で行う。実URL・メール本文・Cookie・Bearer token・ログ全文を外部へ共有しない。
|
||||
|
||||
1. 問題のPathへのGET時刻を控え、PagesWikiプロセスのアクセスログに同じ要求が到達するか確認する。到達しない場合はプロキシ、ブラウザ、キャッシュなどアプリより手前を調べる。ログ出力先の取り違えにも注意する。
|
||||
2. 公開HTTPSとPagesWikiの直接待受で応答を比較する。Domainの振り分けが変わらないよう、同じHostとPathを使う。まず資格情報なし・リダイレクトを追わないGETのstatusとContent-Typeを比較すれば、メール本文を取得せずに判断できる。認証後の比較が必要ならローカル環境内の安全な手順を使い、コマンド履歴に資格情報を残さない。
|
||||
3. 直接待受は正常でプロキシ経由だけ失敗する場合、`/tasks` に一致するlocation、正規表現location、rewrite、別upstream、Custom Locationsを確認する。実際の設定で確認できるまではプロキシが原因と断定しない。
|
||||
4. PagesWikiへの直接要求も失敗する場合は、稼働イメージrevision、HostによるDomain選択、Path別ACL、既存リンクの対象UUIDをローカルで確認する。同一オブジェクトの別名が読めても、元Pathの権限が同じとは限らない。
|
||||
|
||||
X-Request-IDやServerヘッダーだけで応答元を断定しない。プロキシによる付加・上書きがありうる。原因が判明するまで、推測による `/tasks` 専用ルート追加や権限の緩和はしない。
|
||||
|
||||
## 回帰テストと残件
|
||||
|
||||
```sh
|
||||
go test ./internal/server -run 'TestTaskWikiPrefixRouting|TestNeoMuttMailViewerFlow' -count=1
|
||||
# Chromiumがある開発環境のみ
|
||||
PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
|
||||
# 配布ELFでも同じ一時プロファイルを用いて確認する場合
|
||||
PAGES_CLI_TEST_BINARY=/absolute/path/to/pages PAGESWIKI_BROWSER_TEST=1 go test ./internal/server -run '^TestNeoMuttMailViewerFlow$' -count=1
|
||||
```
|
||||
|
||||
- [x] `/tasks` 配下のメール作成から通常ビューアまでの合成HTTP試験。
|
||||
- [x] 同一オブジェクトの別名、親の仮想フォルダ設定、認証境界のGo回帰テスト。
|
||||
- [ ] 問題インスタンスで、直接待受とプロキシ経由の差分を確定する。
|
||||
- [ ] 特定された原因に修正を適用し、元の `/tasks` でも表示できることを確認する。
|
||||
|
||||
テストと調査記録の追加は障害修正リリースではない。既存の回避策とデータを維持する。
|
||||
@@ -0,0 +1,242 @@
|
||||
# Pages Machine Learning:内部サービスと運用
|
||||
|
||||
2026-11-17。状態:**開発用の最小サービスとGoクライアントを実装、Pagesの保存処理には未接続**。
|
||||
本番へ自動起動・外部送信・学習を追加しない。予算用migrationは明示適用のみで、本番未適用。MCPも別途未実装。
|
||||
|
||||
2026-11-28:ML-02の設定契約・永続化を追加。`internal/machinelearning/policy.go`で
|
||||
許可prefix/除外prefix、モデル・scope、外部送信同意、batch byte上限を検証する。
|
||||
`internal/store/machine_learning.go`は既存のDomain別configテーブルに
|
||||
`machine_learning_policy_v1`として保存する。設定がなければ無効、壊れていればエラーで拒否。
|
||||
新規テーブル/migrationは追加しない。同日、管理API・設定UIへ接続。イベントworkerにはまだ未接続。
|
||||
|
||||
設定保存は前回のgenerationを条件にした原子的な更新。毎回新しいgenerationを発行し、
|
||||
無効化後に再有効化しても古い処理要求を再利用できない。`Policy.Prepare`は読み直した設定から
|
||||
要求のモデル・scope・外部送信可否を構築する。prefixは文字列前方一致ではなくPath境界で照合し、
|
||||
除外を優先する。入力はデコード済みの論理Pathとし、URL/曖昧なpercent表記/dot-segmentを拒否する。
|
||||
これは文書ACLの代替ではない。管理者認可・文書権限・学習範囲・結果保存時の再検査は呼出側の責務。
|
||||
保存関数は内部用とし、外部からの操作は下記の管理者認可付きAPIを経由する。
|
||||
|
||||
設定画面:`/-/sys/config?panel=machine-learning`(運用 → Machine Learning)。
|
||||
日本語/英語、既存テーマの表組み・トグルで表示する。パネルを開いた時だけ読み込み、
|
||||
保存はパネルを移動しない。競合時は入力を保持し、確認付きの再読込を用意する。
|
||||
|
||||
管理API:`GET /_/api/v1/ml/settings`、`PUT /_/api/v1/ml/settings`。
|
||||
active状態のdomain_adminまたは当該campus管理者のみ。DomainはHostから決定し、
|
||||
要求本文でDomainを指定できない。更新はJSON・同一Origin検査・64KiB上限・未知field拒否。
|
||||
PUT本文は`{base_generation, policy}`で、policy内のgeneration指定は拒否する。
|
||||
競合409、不正設定422、読書き不可503。応答はprivate/no-store、秘密鍵や接続トークンは含めない。
|
||||
設定を保存しても学習/外部送信/ジョブ投入は起きない。
|
||||
|
||||
batch byte上限は一回分の送信量制限で、日次token予算・課金上限ではない。
|
||||
永続的な予算予約とタイムアウト時の扱いは次の追記のとおり実装。worker接続は後続ML-03で実装する。
|
||||
|
||||
2026-11-28追記:日次予約の保存層を実装。設定`daily_input_bytes`はDomain全体・UTC日付単位の
|
||||
入力UTF-8 byte上限で、0(既存設定の既定値を含む)は実行禁止。通貨/正確なtoken予算ではない。
|
||||
モデル・scope・設定世代が変わっても同日の枠は共有する。今回のスライスでworkerへの接続は行わない。
|
||||
|
||||
`EnsureMLBudgetSchema`が専用migration `machine-learning-budget` v1を明示的に適用する。
|
||||
通常起動/設定保存ではまだ呼び出さないため、本番DBは今回変更しない。専用テーブルは
|
||||
`ml_daily_budget`(Domain+UTC日)と`ml_budget_receipts`(Domain+要求UUID)。
|
||||
予約処理は設定行のロック下で現行世代・Path・同意を再検査し、上限確認とreceipt挿入を同一transactionで行う。
|
||||
MLへのHTTP処理はtransaction外で行う必要がある。重複要求IDは成功応答として返さず、再送禁止エラーにする。
|
||||
|
||||
状態はreserved→completed/unknownの一回遷移。成功時のactual_tokensは参考値として保存する。
|
||||
失敗・timeout・プロセス停止でも予約byteを返却せず、当日再送による重複課金の余地を減らす。
|
||||
日付が変わっても同じ要求IDは再利用不可。receiptに本文や秘密情報は保存しない。
|
||||
保持期間・日次集約の削除・receiptのtombstone化は未実装。receiptを削除すると再送防止を失うため、
|
||||
worker接続前に保持方針を確定し、安易な時限削除を行わない。
|
||||
|
||||
## 境界
|
||||
|
||||
| Pages本体 | Pages Machine Learning |
|
||||
| --- | --- |
|
||||
| Domain/利用者/対象prefix/公開範囲の認可 | 認証されたPagesサービスの入力だけを計算 |
|
||||
| HTML抽出、chunk、Revision・権限世代の管理 | OpenAI EmbeddingsまたはDoc2Vecのベクトル化 |
|
||||
| 永続イベントキュー、取消・再試行・予算 | 実行中処理のみ。永続キューや自動retryなし |
|
||||
| ベクトル保存、候補UI、承認、City適用 | 自前生成したモデルの読取。文書URL取得なし |
|
||||
|
||||
MLにはDB資格情報も文書ストレージも渡さない。共有トークンはサービス間専用で、
|
||||
ユーザー認証やDomain認可を代替しない。ブラウザ/pages-cli/MCPからの直接接続は禁止。
|
||||
本番Pagesから呼ぶ前に、対象選定・外部送信許可・予算をサーバー側で検査する。
|
||||
文書が読める利用者だからといって全Domainの学習・送信を許可しない。
|
||||
|
||||
## 内部API v1
|
||||
|
||||
- `GET /healthz`:無認証のlivenessのみ。モデルが配置済み/推論可能とは保証しない。
|
||||
- `POST /v1/embeddings`:`Authorization: Bearer <専用トークン>`、JSON。本文上限128KiB。
|
||||
- それ以外は認証後404。モデルupload/train/任意URLアクセスのHTTP APIはない。
|
||||
|
||||
要求例(すべて合成ID):
|
||||
|
||||
```json
|
||||
{
|
||||
"protocol": "1",
|
||||
"domain_uuid": "11111111-1111-4111-8111-111111111111",
|
||||
"scope_uuid": "22222222-2222-4222-8222-222222222222",
|
||||
"provider": "doc2vec",
|
||||
"model": "<学習出力のmodel_sha256:64桁hex>",
|
||||
"dimensions": 128,
|
||||
"allow_external": false,
|
||||
"inputs": [{"id": "page-revision:chunk0", "text": "抽出済みの本文"}]
|
||||
}
|
||||
```
|
||||
|
||||
1要求1〜16chunk、各6000 UTF-8 bytes、次元1〜1536。`id`は要求内一意。
|
||||
OpenAI初版は`text-embedding-3-small`のみ。入力byte上限をtoken上限より小さく抑えるが、
|
||||
適切な節分割・ドメイン予算はPages側の次段階で実装する。元の長文を黙って切り捨てない。
|
||||
|
||||
応答はprotocol/Domain/scope/provider/model/model_revision/dimensions/tokenizer、
|
||||
`outputs[{id,input_sha256,vector}]`、`usage.total_tokens`。
|
||||
Goクライアントは入力順・ID・SHA256・次元・モデル・有限かつ非ゼロのvectorを検査する。
|
||||
Doc2Vecのmodel_revisionはモデルファイルSHA256。OpenAIは返されたモデル名であり、
|
||||
提供元の重みを固定したsnapshot IDではない。運用側の索引世代を別に持たせる必要がある。
|
||||
|
||||
主な失敗:400入力、401サービス認証、403外部送信OFF、404モデルなし、409モデル不整合、
|
||||
413サイズ、415形式、422既知語なし、429実行中/provider制限、502provider失敗。
|
||||
エラーに入力本文・API鍵・上流response bodyを含めない。Go側もstatus以外の上流本文を返さない。
|
||||
timeoutで請求や実行の有無は確定しない。自動retry/別providerへのfallbackは行わない。
|
||||
|
||||
## Doc2Vecモデル
|
||||
|
||||
Gensim PV-DBOWを固定し、初版はNFKC+casefold+CJK文字bigramの決定的な前処理。
|
||||
これは軽量な比較用baselineであり、高品質な日本語形態素解析や分類精度を保証しない。
|
||||
語彙が全く一致しない入力はランダムな候補を返さず422。学習workers=1、seed=0。
|
||||
推論も入力hashでseedを固定する。同一実行環境での安定性を試験し、異なる依存版/CPUの
|
||||
bit単位一致までは保証しない。前処理や依存版を変える際はモデル・索引世代を更新する。
|
||||
|
||||
保管先:`/models/{domain_uuid}/{scope_uuid}/{model_sha256}/`。
|
||||
scopeは一つの学習許可範囲を表すID。Domain内でも非公開データと公開データを無条件で混ぜない。
|
||||
`manifest.json`と`model.bin`を生成し、APIからはread-only。
|
||||
SHA256は破損検査であり、モデルの安全性を証明する署名ではない。
|
||||
Gensimモデルはpickleを利用するため、**自前で学習した信頼済みモデル以外は配置禁止**。
|
||||
モデルを一般のWikiアップロードやassetsディレクトリから読み込まない。
|
||||
|
||||
学習は管理者のオフラインコマンドのみ。入力は許可済みJSONL(各行`{"text":"…"}`)、
|
||||
最大1万文書/16MiB、文書あたり6000bytes。モデルは別世代のディレクトリへ作り、既存世代を上書きしない。
|
||||
2文書以上で学習できることと分類品質が十分であることは別。
|
||||
|
||||
```sh
|
||||
PYTHONHASHSEED=0 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 \
|
||||
python train.py corpus.jsonl --model-dir /models \
|
||||
--domain DOMAIN_UUID --scope SCOPE_UUID --dimensions 128
|
||||
```
|
||||
|
||||
削除/権限変更時はPagesが当該scopeの利用を即座に停止し、再学習後に世代を切り替える設計。
|
||||
モデルファイルだけでなくmanifestを除去すれば、読み込み済みでも次回要求を拒否する。
|
||||
この失効処理のPages接続は未実装。モデルは1世代だけメモリ保持し、別scope要求時に入れ替える。
|
||||
大きな複数モデルを使う場合はインスタンス分離を検討する。
|
||||
|
||||
## 起動と制限
|
||||
|
||||
`services/machine-learning/Dockerfile`、任意overlay `docker-compose.ml.yml` を用意。
|
||||
既存の通常Composeだけでは起動しない。イメージの公開/registry pushはまだ行わない。
|
||||
|
||||
1. 32〜256文字のURL-safeランダムトークンをファイルに保存する。コマンド履歴へ直接入れない。
|
||||
2. `PAGES_ML_TOKEN_PATH`と`PAGES_ML_MODELS_PATH`にホストの絶対パスを指定する。
|
||||
3. コンテナUID/GID `65532:65532` が読める権限を設定する。他ユーザー全員に公開しない。
|
||||
学習出力は作成ユーザー専用ディレクトリなので、別UIDで生成したモデルは専用グループ/所有権を調整する。
|
||||
4. 開発環境で次を実行する(基底Composeの既存必須変数も必要)。
|
||||
|
||||
```sh
|
||||
docker compose -f docker-compose.yml -f docker-compose.ml.yml \
|
||||
up -d --build machine-learning
|
||||
```
|
||||
|
||||
ホストport非公開、専用internal bridge `/27`、read-only root、非root、capability削除、
|
||||
1CPU/1GiB/64PID、BLAS 1thread。既存ネットワークと競合すれば`PAGES_ML_FRONT_SUBNET`を変更する。
|
||||
Gunicorn 1worker・2threads、推論は全provider共通で同時1件。混雑は429+Retry-Afterを返す。
|
||||
別プロセス/replicaは別の同時枠なので、将来Pages側でも総同時数・予算を制限する。
|
||||
in-flight要求の厳密な取消は未実装。Goのcontext取消はクライアント待機を止めるが、
|
||||
MLで開始済みの計算・外部請求を取り消すものではない。
|
||||
|
||||
OpenAIは`PAGES_ML_ALLOW_OPENAI=true`、`PAGES_ML_OPENAI_KEY_FILE`への秘密mount、
|
||||
要求内`allow_external:true`の全条件が必要。既定overlayはネットワークも外向き接続を許さない。
|
||||
利用時は管理者がegress経路を別途追加・制限し、固定先`https://api.openai.com/v1/embeddings`を許可する。
|
||||
任意base URL・TLS検証無効・HTTP redirect追従は提供しない。
|
||||
Pages→MLのHTTPは同一の隔離ネットワーク限定。別ホストならHTTPS+ネットワーク認可を設ける。
|
||||
|
||||
## 検証
|
||||
|
||||
Python 3.12とrequirements.txtを入れた仮想環境で:
|
||||
|
||||
```sh
|
||||
PYTHONHASHSEED=0 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 \
|
||||
python -m unittest discover -s services/machine-learning -v
|
||||
go test -race ./internal/machinelearning
|
||||
PYTHONHASHSEED=0 OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 \
|
||||
python services/machine-learning/smoke_test.py
|
||||
```
|
||||
|
||||
smokeは合成文書の学習→一時Gunicorn→Goクライアントまで実行し、終了時に一時データとプロセスを破棄する。
|
||||
実データを使わず、OpenAIはmock契約試験のみ。Doc2Vecの分類品質評価はまだ行っていない。
|
||||
|
||||
## 配布前ゲート
|
||||
|
||||
依存はrequirements.txtで固定。Gensim 4.4.0(LGPL-2.1)、NumPy/SciPy(BSD系、wheel同梱の
|
||||
BLAS等に個別条件)、Gunicorn(MIT)、Python/Debian基底を含むため、イメージ公開前に
|
||||
実際のwheel/基底imageのlicense・notice・対応sourceの提供条件、SBOMと脆弱性検査を整理する。
|
||||
モデル・コーパスはイメージに含めない。Docker contextも許可したソースファイルだけに限定。
|
||||
ライセンス記載だけで再配布条件を満たしたとは扱わない。
|
||||
|
||||
## 次の実装単位
|
||||
|
||||
2026-11-28:ML設定・予算についてSQLite/PostgreSQL 17/MySQL 8.4の実DB共通試験を実施し、
|
||||
3backendとも成功。MySQLはMLだけの限定facadeによるpilotで、Pages本体の起動には未対応。
|
||||
[DB移植計画・実装境界](../design/ja/database-portability.md)を参照。
|
||||
PostgreSQL/MySQLの予約ロックはSELECT FOR UPDATE+READ COMMITTEDへ変更し、
|
||||
同じ値のUPDATEのRowsAffectedに依存しない。MySQL ML schemaはjournal付きの明示migrationへ移行済み。
|
||||
本番適用とPages全体のMySQL migrationは未実施。
|
||||
|
||||
## MySQLのML schema管理
|
||||
|
||||
接続先は専用の空DBを用意し、秘密管理経由で`PAGESWIKI_MYSQL_DSN`環境変数を設定する。
|
||||
DSNは`USER:PASS@tcp(HOST:3306)/DATABASE?tls=true`形式。実際の秘密を履歴や資料に記載しない。
|
||||
このコマンドはML専用であり、実行してもPages全体がMySQLで起動できるようにはならない。
|
||||
既存PagesのDB/他サービスのDBへ試しに適用しない。
|
||||
|
||||
```sh
|
||||
pageswiki mysql-ml-schema status
|
||||
pageswiki mysql-ml-schema check
|
||||
pageswiki mysql-ml-schema apply --timeout 2m
|
||||
pageswiki mysql-ml-schema check
|
||||
```
|
||||
|
||||
- `status`:適用数・未適用数・dirty・再開位置をJSONで表示。schema/台帳を作らない。
|
||||
- `check`:同じ検査に加えて、未適用またはdirtyなら非0終了。デプロイ前ゲート用。
|
||||
- `apply`:通常の適用。途中失敗している場合は拒否。既存tableを無断で移行履歴へ取り込まない。
|
||||
- `resume`:原因を調査・修復した後の明示再開。成功済み操作は事後条件で確認し、
|
||||
未完了操作は再実行安全と宣言されたものだけ再試行する。自動rollbackではない。
|
||||
|
||||
```sh
|
||||
pageswiki mysql-ml-schema resume --timeout 2m
|
||||
pageswiki mysql-ml-schema check
|
||||
```
|
||||
|
||||
履歴のchecksum不一致や未知版、schema不整合では停止する。台帳の行を削除したり、
|
||||
dirtyを手動でappliedへ書き換えて回避しない。schema変更前にはDBバックアップを取得する。
|
||||
試験専用の`--allow-insecure`は隔離された使い捨てDB以外では使わない。
|
||||
MySQL 8.4の実DB試験でCLI、再開、並行実行、版更新を確認する。
|
||||
SQLite/PostgreSQLの既存起動・migration経路には変更を加えない。
|
||||
|
||||
2026-11-30:共通configのkeyをUnicode/NO PAD対応する版2を追加。
|
||||
版1のchecksumや保存済み値を変更せず更新する。MLのCAS・予算契約も3DBで再検証。
|
||||
名前空間pilot用`mysql-namespace-schema`も追加したが、本体起動対応ではない。
|
||||
適用範囲と依存componentの再開順は[DB移植計画](../design/ja/database-portability.md#namespace-pilotの操作)を参照。
|
||||
|
||||
## 残件
|
||||
|
||||
- [x] ML-01:サービス間認証、provider、オフライン学習、Go契約、合成HTTP結合試験
|
||||
- [x] ML-02a:Domain別設定の内部保存、世代付きCAS、prefix除外、要求生成時の同意・byte上限
|
||||
- [x] ML-02b:管理者API・設定パネル、Origin/不正入力/競合の検証、Chromium読込試験
|
||||
- [x] ML-02c:日次入力byte上限・永続予約・重複拒否・失敗時非返却(worker未接続)
|
||||
- [ ] ML-02:モデル配布・失効、予算使用量の表示、receipt保持方針、監視接続
|
||||
- [ ] ML-03:既存イベントキュー接続、差分抽出、取消・再試行・世代再確認、保存層(両DB)
|
||||
- [ ] ML-04:City候補・根拠・比較UI、手動修正保護、権限付き確認・明示適用
|
||||
- [ ] ML-05:コーパス別精度/負荷計測、同時数調整、配布条件・イメージbuild/本番受入
|
||||
|
||||
Pages接続時は`page.created`/`revision.created`等の既存activity outboxを別consumerで処理する。
|
||||
`city.reconcile`をそのまま重い推論に置き換えない。保存完了を待たせず、処理結果保存前に
|
||||
Revision・scope・設定世代を再確認する。MLエラー時に通常の保存・閲覧を失敗させない。
|
||||
|
||||
参照:[OpenAI Embeddings API](https://developers.openai.com/api/reference/resources/embeddings/methods/create)、
|
||||
[Gensim Doc2Vec](https://radimrehurek.com/gensim/models/doc2vec.html)。
|
||||
@@ -0,0 +1,103 @@
|
||||
# PostgreSQL への停止移行
|
||||
|
||||
SQLite から PostgreSQL への片方向移行を、単一インスタンス・ローカルの正本ファイル配置で行う。
|
||||
全 writer を停止し、空の専用 PostgreSQL database/schema へ転送する。既存 DB への merge、
|
||||
オンライン差分同期、PostgreSQL から SQLite への逆移行は提供しない。
|
||||
|
||||
## 対応範囲と制限
|
||||
|
||||
検証対象は PostgreSQL 17。通常起動の既定値は引き続き SQLite である。
|
||||
PostgreSQL 起動は verified TLS、全件 import の完了記録、既存の鍵と同じ絶対 Document root を必須とする。
|
||||
DB 接続障害や検査失敗で SQLite に自動 fallback しない。
|
||||
|
||||
- native 検索は権限付きの Path・ファイル名・City メタデータ検索。本文全文検索は後続対応。
|
||||
- hosted editor、Web Push 配信、zombie GC、ログの自動保持期限処理は native の停止ゲート対象。
|
||||
設定・受付記録・既存データは保全する。内蔵エディタと Inbox を使用し、ログ・ファイル容量を監視する。
|
||||
- DR/HA 構成への移行は拒否する。`pageswiki dr` と旧 `schema` コマンドは PostgreSQL 設定時に拒否する。
|
||||
- DB 直結の `data/pageswiki-cli` は SQLite 専用。PostgreSQL では HTTP の `pages-cli` を使用する。
|
||||
すべてのプロセスに backend 設定を統一し、旧 SQLite 用 CLI を起動しない。
|
||||
- 外部カレンダーの実データを使った検査・再取得は行わない。検証用の予定・連絡先・タスクは合成データを使う。
|
||||
|
||||
## 移行前の準備
|
||||
|
||||
1. HTTP、CalDAV/CardDAV、CLI、scheduler、federation、外部の直接 DB writer を停止する。
|
||||
コマンドは data directory の排他ロックを取るが、旧バイナリや直接 SQLite client の停止を代替しない。
|
||||
2. 停止状態の data directory 全体を別の場所に保全する。SQLite と WAL、`documents`、カレンダー・タスク等の
|
||||
正本ファイル、設定、`auth.key`、instance identity を同じ時点で保全する。
|
||||
`PAGESWIKI_AUTH_KEY` を使用していた場合はその secret も別途保全し、移行時・起動時に同じ値を渡す。
|
||||
3. 専用 PostgreSQL database/schema と、それを所有する移行ユーザーを用意する。
|
||||
schema/table/trigger/identity の作成・変更権限が必要。共有アプリ DB を移行先にしない。
|
||||
4. PostgreSQL の CA とホスト名を検証できる DSN を secret として用意する。
|
||||
`PAGESWIKI_POSTGRES_DSN` に `sslmode=verify-full` と必要な `sslrootcert` を設定する。
|
||||
DSN はコマンドラインやログに出さない。移行先の管理者による同時 schema 変更も停止する。
|
||||
|
||||
## コマンド
|
||||
|
||||
以下は、稼働時にも `/data` を使う場合の例。移行と起動で data directory の絶対パスを一致させる。
|
||||
Docker では同じ `/data` マウントを使用する。別のホスト側絶対パスで import してから
|
||||
コンテナ内 `/data` に切り替えると、root 検査により起動を拒否する。
|
||||
|
||||
```sh
|
||||
# schema の読取り検査。移行先への接続・データコピーは行わない。
|
||||
./pageswiki migrate-postgres --data-dir /data
|
||||
|
||||
# DSN は保護された環境設定から注入済みとする。
|
||||
./pageswiki migrate-postgres --data-dir /data --apply --timeout 30m
|
||||
|
||||
# import 成功・保全確認後、同じ正本 root と鍵で起動する。
|
||||
PAGESWIKI_DB_BACKEND=postgresql PAGESWIKI_DATA_DIR=/data ./pageswiki
|
||||
```
|
||||
|
||||
`--apply` がない場合は schema preflight のみで、payload の検証成功を意味しない。
|
||||
`--allow-insecure` は隔離試験専用の移行オプションであり、通常起動の TLS 検証は緩和しない。
|
||||
未知のテーブル・列・trigger/view がある場合は処理を止め、保全分類と schema を修正して再試行する。
|
||||
不明なデータを削除して検査を通さない。
|
||||
|
||||
## 転送と照合
|
||||
|
||||
保全対象は `internal/store/application_import_catalog.go` に列挙する。
|
||||
SQLite 専用 FTS 索引・派生 latest revision index・SQLite migration ledger は除外するが、
|
||||
設定、鍵への参照、認証、ACL、タスク、連絡先、同期番号、受付履歴、ジョブ・ログ等は保持する。
|
||||
正本ファイルは同じ場所に残す。ファイル自体を別の volume へコピーするコマンドではない。
|
||||
|
||||
転送は単一 transaction。転送前に移行先の空状態を検査し、型を区別した各行の内容指紋・件数、
|
||||
参照される Document の SHA-256、namespace の参照整合性を commit 前に検査する。
|
||||
タスク DAV の内部索引だけは backend 形式の違いを明示的に変換する。変換後の内容指紋を照合し、
|
||||
クライアント用 href・正本 JSON は保持する。削除履歴と削除済み最大採番も保全する。
|
||||
|
||||
JSON report は対象テーブルの件数と指紋、除外一覧、変換内容、Document 数、採番情報を返す。
|
||||
本文や資格情報は含まない。成功時の report をバックアップと一緒に保管する。
|
||||
失敗時はデータ転送を rollback する。準備済み schema は残り得るが、既定行だけの状態なら再試行できる。
|
||||
完了済み import や既存データへの上書きは拒否する。
|
||||
|
||||
## 起動確認と復旧
|
||||
|
||||
書き込み再開前に、同じバイナリと設定で起動し、ログイン・既存 session・権限・本文・内蔵編集・
|
||||
タスクのプロジェクト所属・DAV discovery/条件付き更新・連絡先・管理画面を確認する。
|
||||
外部送信や取得を伴う worker の再開対象は事前に点検する。
|
||||
この実装は import 済み DB を開くためのもので、空の PostgreSQL から既定 Campus を新規生成しない。
|
||||
|
||||
移行前 SQLite は凍結したまま保管する。書き込み再開後の新しい更新は PostgreSQL 側にしか存在しない。
|
||||
旧 SQLite へ接続を戻すことはデータを引き継ぐ切り戻しではない。
|
||||
|
||||
PostgreSQL 運用のバックアップは、writer を停止した同じ時点の `pg_dump -Fc` と data directory 全体、
|
||||
鍵・secret を組にする。復元先は空の専用 database/schema とし、`pg_restore --exit-on-error` で復元する。
|
||||
ファイルを元と同じ絶対 mount path に復元し、接続先 DSN のみ変更する。
|
||||
import 完了記録も dump に含める。DB 単独や正本ファイル単独のバックアップでは復元条件を満たさない。
|
||||
復元後は停止状態で本文・参照・認証・DAV 同期の検証を実施してから writer を再開する。
|
||||
|
||||
## 検証とリリース前チェック
|
||||
|
||||
- 合成データで全件移行、途中失敗の rollback、再試行、上書き拒否、schema drift 拒否を検証する。
|
||||
- 日本語本文・タグ、バイナリ画像、認証 session、プロジェクト別 DAV、削除 tombstone、連絡先 sync-token を照合する。
|
||||
- 隔離した PostgreSQL 17 に対し schema 単位の dump/restore と、同じ正本 root の読み戻しを検証する。
|
||||
- `go test ./...`、対象 race test、`go vet ./...`、通常バイナリ build を通す。
|
||||
- 実インスタンスの停止バックアップと import 結果は、合成データ試験とは別に確認する。
|
||||
- image build workflow は `tools/ci/test-postgres.sh` で PostgreSQL 17 の全 Go テストを実行してから publish する。
|
||||
DB container は外部ネットワーク・公開 port を持たず、テスト container がその network namespace を共有する。
|
||||
DSN 未設定で実行したローカルテストの skip を移植検証の成功として扱わない。
|
||||
|
||||
任意のテスト DSN に本番を指定しない。`PAGESWIKI_TEST_POSTGRES_DSN` は使い捨て DB に限定する。
|
||||
CLI と verified TLS の試験は `PAGESWIKI_TEST_POSTGRES_TLS_DSN` を指定する。
|
||||
`PAGESWIKI_TEST_POSTGRES_CONTAINER` を追加指定すると、同じ隔離 DB を持つ Docker container 内の
|
||||
`pg_dump`/`pg_restore` でテスト専用 schema の復元試験を実行する。
|
||||
@@ -0,0 +1,77 @@
|
||||
# PagesWiki v0.14.1とpages-cli v0.4.2
|
||||
|
||||
削除済みタスクの受付記録が残り、変更した下書きの再送で412になっていた問題を修正します。
|
||||
削除済みなら410、受付記録に対応するタスクと削除記録が両方欠落していれば409 `capture_missing` で停止します。
|
||||
存続中のタスクを異内容のcaptureで上書きすることは許可しません。
|
||||
|
||||
2026-11-08 19:42:51 JSTに本番配備後の確認を完了しました。
|
||||
DBスキーマ変更・既存データの削除・実タスクの再取り込みは行っていません。
|
||||
Gecko等の未コミット変更は含みません。
|
||||
|
||||
## 再取り込み
|
||||
|
||||
サーバーをv0.14.1、利用するCLIをv0.4.2に更新してから実行します。
|
||||
別インスタンスへ接続している場合は、その接続先サーバーの更新も必要です。
|
||||
|
||||
```sh
|
||||
pages --version
|
||||
pages task retry REQUEST_UUID --recreate-deleted
|
||||
```
|
||||
|
||||
保持した下書きから、新UUIDのタスクを作成します。旧UUIDの削除記録とDAV識別子予約を残し、
|
||||
通常の再送で古いタスクが復活するのを防ぎます。再取り込み用IDは決定的で、応答消失や並行再送でも重複作成しません。
|
||||
既存Wikiが保存先にあれば本文・リビジョンは変更せず、新タスクから関連付けます。
|
||||
ページがなければ保留本文から作ります。移動済みページの自動探索や旧作業記録の復元ではありません。
|
||||
|
||||
通信失敗時はCLIが表示する新IDで `pages task retry NEW_REQUEST_UUID` を実行します。
|
||||
セッションファイルや受付記録を手動で消さないでください。
|
||||
詳細は[実装契約](../../design/ja/tasks-implementation.md#削除済みメール取り込みの再作成)と
|
||||
[CLIのNeoMutt手順](https://git.anya.jp/anya/pages-cli/src/tag/v0.4.2/docs/neomutt.md)を参照してください。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
| 対象 | タグ | commit | CI |
|
||||
| --- | --- | --- | --- |
|
||||
| PagesWiki | [v0.14.1](https://git.anya.jp/anya/pages/releases/tag/v0.14.1) | `4049acf76e36c12b8f3c506de5eaf1e920ac7e86` | [build 72](https://git.anya.jp/anya/pages/actions/runs/72)、[release 75](https://git.anya.jp/anya/pages/actions/runs/75) success |
|
||||
| pages-cli | [v0.4.2](https://git.anya.jp/anya/pages-cli/releases/tag/v0.4.2) | `e27c023d66a61b73d3fe47e982daa6f34213c41f` | [build 73](https://git.anya.jp/anya/pages-cli/actions/runs/73)、[release 74](https://git.anya.jp/anya/pages-cli/actions/runs/74) success |
|
||||
|
||||
- 正確なリリースソースで `go test ./...`。server/storeのgo vet、削除・再取り込み・並行再送のrace検査が成功。
|
||||
- CLIの52単体テスト、サーバーとCLIのHTTP結合テストが成功。Wiki本文・版の保全、他所有者拒否、readonly、kill switch、入力上限、保存途中のロールバックを検証。
|
||||
- 公開されたCLIの4配布ファイルをSHA256SUMSで照合し、Pythonソースとcommitを照合。
|
||||
- 配布Linux ELFでバージョン、メール取り込み、下書き差し替え、削除済み再取り込み、認証・ファイル権限のスモークテストとTLS関連6テストが成功。
|
||||
- Linux ELFはglibc 2.36以降。macOS/Windowsの未検証バイナリは配布していません。
|
||||
|
||||
## 本番切り替えと復旧点
|
||||
|
||||
app・app2・adaptor-gateway・excalidraw-viewerを同じv0.14.1へ更新しました。
|
||||
`.env.release` の選択は `PAGESWIKI_IMAGE_TAG=v0.14.1` です。
|
||||
|
||||
- 19:40:36 JSTに停止開始。
|
||||
- 19:42:17 JSTに、停止時点のdata/data2についてchecksum同期、再走査の差分ゼロ、DBファイル一致を確認。
|
||||
- 19:42:23 JSTに新版の起動と両アプリのhealth応答を確認。
|
||||
- 設定と停止時データは `.deployment-backups/release-v0.14.1-20261108/` の `config/` と `cutover/data`、`cutover/data2` に保存。DBのinodeは稼働元と独立しています。
|
||||
- 旧3イメージを `rollback-before-v0.14.1-20261108` タグで保持。旧バックアップも残しています。
|
||||
|
||||
v0.14.0への切り戻しはイメージ選択のみで行い、DBを過去へ戻しません。
|
||||
その場合は再取り込みAPIが利用できなくなるため、CLIの再取り込み操作を止めてください。
|
||||
v0.14.0より前への切り戻しは削除記録の扱いが異なり、[v0.14.0の注意点](2026-11-08-task-deletion.md#dbと切り戻し)が引き続き適用されます。
|
||||
|
||||
## 配備後確認
|
||||
|
||||
- 4サービスのrevisionが対象commitと一致、running、再起動回数0。
|
||||
- app/app2のhealth正常。管理対象13スキーマはcurrent。これはlegacy領域を含む全移行検証ではありませんが、今回の変更にスキーマ移行はありません。
|
||||
- 両DBの `quick_check` はok。
|
||||
- 外部HTTPSのhealth・ログイン画面200。匿名のタスク/ダッシュボード/RSS画面303、タスクAPI401。匿名DELETEとcapture POSTも401。
|
||||
- tasks.js、tasks.css、organizer-dashboard.js、feeds.js、feed-gecko.jsのSHA-256がリリースcommitと一致。
|
||||
- 起動直後のfatal/panic、DB lock、schema/migration failure、event job failureは両アプリとも0件。
|
||||
- 実際のメール本文・利用者の保留下書きを使った再取り込みは実施していません。
|
||||
|
||||
## 配布イメージ
|
||||
|
||||
SHAタグから再ビルドせず昇格。本番で取得したdigestとCI結果は一致しています。
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`、タグ`v0.14.1`) | manifest digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:11488fb958db12ec5a25aa265fc8179a31ab5728800f47605759822a44eb81e6` |
|
||||
| pageswiki-adaptor-gateway | `sha256:ca17704eb5e88a4e73827ff2a5fafda7c4bb7d9be3987b5a83a3a5ae0c780098` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:a2b692c3864b8c4f13412e746fcea7cd9a2c03d49e0d5ead252432f37930c4c4` |
|
||||
@@ -0,0 +1,48 @@
|
||||
# PagesWiki v0.15.0とpages-cli v0.5.0
|
||||
|
||||
ブラウザアップロード、信頼端末ログイン、RSSの配信時刻、CSV投影とタスクの関連ページ導線を追加します。Geckoの整備コードと配布イメージも含みますが、専用relayの本番有効化は行いません。
|
||||
|
||||
## 変更内容
|
||||
|
||||
- `/v/browser` のファイルドロップと右下のキュー。逐次送信、待機取消、折りたたみ、同名保護、一覧だけの更新。ページを閉じた後の再開とフォルダ再帰アップロードは未対応。
|
||||
- ログイン時の信頼端末選択。管理者指定の最大30日・絶対期限で、既存セッションは延長しません。パスワード/TOTP、OIDC、LDAP、マジックリンクに選択を引き継ぎます。
|
||||
- CLIの `login --remember` と期限切れ再ログイン時の作業パス/保留下書き保持。
|
||||
- RSS一覧の配信時刻とDomainタイムゾーン。本文の日付表示も同じタイムゾーンへ統一。
|
||||
- 保存済みタスクの関連Wikiページを開くボタン。
|
||||
- 認証済み閲覧者の権限を確認する有界CSV macro。`{{csv:/data/items.csv range=A1:H200 header=true}}` と同じObjectのRevision固定に対応。CSV編集・匿名投影・外部URL取得は含みません。
|
||||
- Geckoの日本語ページ内検索、起動上限・失敗時のiframe破棄、固定ソース/notice付き配布物検査。Safari実機、IME・コピー、運用firewallと低メモリ受入は残件。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
本体commitは `b90aef79d03c21332cd49a47aba015a30f6de1a0`。Gitea [build 76](https://git.anya.jp/anya/pages/actions/runs/76)、[release 79](https://git.anya.jp/anya/pages/actions/runs/79) が成功し、SHAイメージを再ビルドせず `v0.15.0` へ昇格しました。
|
||||
|
||||
CLI commitは `bee03094f3bf2fa0c2dab80313d2f4bd15452c3d`。[v0.5.0](https://git.anya.jp/anya/pages-cli/releases/tag/v0.5.0) のCIと55単体テストが成功。公開した4ファイルのSHA256SUMS照合、Pythonソース一致、取得したLinux ELFのバージョン・ログイン・タスク/メール取り込み・下書き回復等の合成スモークテストを確認しました。未検証のmacOS/Windowsバイナリは追加していません。
|
||||
|
||||
本体は `go test ./...`、`go vet ./...`、リリースツールと壁紙テスト、Gecko配布ツールのテストが成功。Chromiumで認証・タスク・RSS・Gecko・アップロードの合成試験を実施しました。アップロードキューは1280px/390px幅、逐次送信、同名保護、取消、一覧更新を検証しています。
|
||||
|
||||
## DBと復旧
|
||||
|
||||
`cli-auth` v1→v2で `auth_cli_requests.remember` を既定0・0/1制約付きで追加します。他の管理対象componentのversionは変わりません。両インスタンスの独立コピーで、ネットワークを遮断しworkerを停止して新イメージを起動し、schema checkとSQLite integrity_checkが成功しました。実外部カレンダーやメール内容は検証に使用していません。
|
||||
|
||||
保全先は `.deployment-backups/release-v0.15.0-20261108/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のデータを保存します。旧3イメージの `rollback-before-v0.15.0-20261108` タグと既存バックアップを保持します。
|
||||
|
||||
新しいmigration履歴を旧版が受け付けるとは限らないため、旧イメージだけのダウングレードは行いません。切戻しが必要ならwriterを止め、切替後データも保全し、停止時バックアップとの変更差分を扱ってからDB・ファイル・設定・イメージを同じ復旧点へ戻します。運用開始後の書き込みを黙って破棄しません。
|
||||
|
||||
## 本番反映
|
||||
|
||||
2026-11-08 20:41:33 JSTに配備後確認を完了しました。20:40:05に停止し、20:41:10に停止時バックアップを検証、20:41:16に新版の起動とhealthを確認しています。
|
||||
|
||||
- app・app2・adaptor-gateway・excalidraw-viewerはすべて対象commitと一致し、running・再起動回数0。
|
||||
- 両DBのquick_checkはok、管理対象13componentはcurrent。legacy領域全体の検証を意味するものではありません。
|
||||
- 外部HTTPSのhealth・ログイン画面200。匿名タスク/dashboard/RSS画面303、タスクAPI・DELETE・captureは401。
|
||||
- tasks、RSS、Gecko、アップロードキュー、信頼端末UIの配信JS/CSSはリリースcommitとSHA-256一致。公開ログイン画面の信頼端末選択も確認。
|
||||
- 起動直後のfatal/panic、DB/schema failure、event job failureは両アプリとも0件。
|
||||
- `.env.release` は `PAGESWIKI_IMAGE_TAG=v0.15.0`。Gecko relayコンテナは起動せず、通常3イメージ・4サービスだけを更新。
|
||||
|
||||
配備イメージのmanifest digest:
|
||||
|
||||
| イメージ(`git.anya.jp/anya/`) | digest |
|
||||
| --- | --- |
|
||||
| pageswiki-app | `sha256:43c398f2c294c7802987aaae1bfdf27b3d0c7ea24fa73df912ac03ea312366b0` |
|
||||
| pageswiki-adaptor-gateway | `sha256:aebc515c3b3e36b58b03ecab1646e6d95b0dd21074a1a863ca5806cb7fde4df1` |
|
||||
| pageswiki-excalidraw-viewer | `sha256:4a80354aa4567abe52ff17e32a6f224e85d8cd2e0f1a466e5690b4b353d901cc` |
|
||||
@@ -0,0 +1,39 @@
|
||||
# PagesWiki v0.16.0
|
||||
|
||||
2026-11-09 05:58:14 JSTに本番の配備後確認を完了しました。CSVの表編集・複数セル貼り付けと、Reveal.jsのビューア・編集プレビューを追加します。
|
||||
|
||||
## 変更と利用方法
|
||||
|
||||
- 既存CSVを `/e/-/{path}` で表編集。行列操作、Undo/Redo、タブ区切りの複数セル貼り付け、既存の下書き・履歴・競合確認に対応します。未変更セルの引用符・BOM・改行を保持し、上限超過時は部分反映しません。
|
||||
- HTMLページのスライドアイコン、または `/v/slides/{path}` でReveal.js表示。エディタのスライドアイコンで未保存HTML/Markdownをプレビューします。Markdownの空行で囲んだ `---`、HTML直下の `<hr>` で区切ります。
|
||||
- Reveal.js 6.0.2をMITライセンスとともにローカル同梱。sandbox、Path認可、入力上限、テーマ追従、スマホの全幅プレビューに対応。拡張設定の `viewer.slides` でドメイン単位に停止できます。
|
||||
|
||||
CSVは全体256 KiB、表200行・32列・セル16 KiB以内。スライドは256 KiB・100枚以内です。縦スライド・発表者ノート・専用印刷・外部画像承認連携は含みません。通常HTMLの自動表示をスライドへ置き換えません。
|
||||
|
||||
## リリースと検証
|
||||
|
||||
対象commitは `02fb77f72b45c342c6b458d733f840b38cc3ae56`。[build 80](https://git.anya.jp/anya/pages/actions/runs/80)と[release 81](https://git.anya.jp/anya/pages/actions/runs/81)が成功し、同じSHAのイメージを再ビルドせずv0.16.0へ昇格しました。
|
||||
|
||||
開発環境で全Goテスト・go vet・JS単体テスト、1280px/390pxのChromium試験を実施しました。CSV保存・競合・履歴・貼り付け拒否、スライドのライブ更新・通常プレビュー復帰・左右キー・履歴非変更・隔離を確認しています。
|
||||
|
||||
本番ではapp・app2・adaptor-gateway・excalidraw-viewerのrevision一致、running、再起動0を確認。両アプリのhealth、外部HTTPSのhealth/login 200、匿名タスク・スライドの303、タスクAPIの401を確認しました。CSV/Reveal.js関連の11配信ファイルはリリースcommitとSHA-256一致。両DBのquick_checkはok、管理対象13componentはcurrentで版変更なしです。legacy領域全体の移行検証を意味しません。起動直後のpanic・fatal・DB/schema失敗・event job失敗に該当するログはありませんでした。
|
||||
|
||||
本番の実コンテンツを編集する試験、外部カレンダー・メール内容の取得は行っていません。pages-cliは変更せず、Gecko relayも起動していません。
|
||||
|
||||
## 保全と切替
|
||||
|
||||
DBスキーマ・ストレージ形式の変更はありません。保全先は `.deployment-backups/release-v0.16.0-20261109/`。`config/` に旧設定、`cutover/data` と `cutover/data2` に停止時点のファイルを保持しています。DBだけは容量を考慮して `pages.db.gz` とし、gzip検査と展開内容のバイト一致を確認しました。他のファイルは停止時checksum比較で一致しています。復旧用に展開する場合は、稼働DBを上書きせず別の停止済み復旧領域に `pages.db` として展開します。
|
||||
|
||||
初回は圧縮で変わったバックアップ先フォルダmtimeを厳密差分検査が検出し、新版起動前にv0.15.0へ自動復帰しました。圧縮後にフォルダmtimeを元に合わせる修正を行い、内容の検証は省略せず再実行しています。再試行は05:54:59 JSTに停止、05:57:28にバックアップ検証完了、05:57:34に新版health確認完了です。
|
||||
|
||||
旧イメージは `rollback-before-v0.16.0-20261109` タグで保持し、過去のバックアップも削除していません。今回のUI機能を切り戻す場合はwriterを止め、現データを保持してv0.15.0のイメージへ戻せます。バックアップ時点へのデータ復旧を選ぶ場合は、切替後の書き込みを別途保全して差分を扱い、黙って破棄しません。
|
||||
|
||||
`.env.release` は `PAGESWIKI_IMAGE_TAG=v0.16.0`。配備後の空き容量は約8.1 GiBのため、次の大きなビルド・バックアップの前に保持世代と不要キャッシュの整理が必要です。
|
||||
|
||||
## 配備イメージ
|
||||
|
||||
- `pageswiki-app`: `sha256:428f4c38297e7d2b529af13b32d45e6a9b40f58915fbd170148a0ad07958a034`
|
||||
- `pageswiki-adaptor-gateway`: `sha256:cdf99b4f02a9abade8862caea1c23cfe775f229118c5c1aabf2584d84a02be50`
|
||||
- `pageswiki-excalidraw-viewer`: `sha256:854fa1d0bb931642e81af394ab4631b47397a94264eb1b34d4f8ff0ca5435e25`
|
||||
|
||||
レジストリのprefixは `git.anya.jp/anya/`、共通タグは `v0.16.0` です。
|
||||
@@ -0,0 +1,32 @@
|
||||
# PagesWiki v0.19.0
|
||||
|
||||
リリース対象:v0.18.0以降の実装整理。ビルド・タグ昇格・本番配備の結果は別途記録する。
|
||||
|
||||
## 利用者向け変更
|
||||
|
||||
- RSSのX共有をクリック時のポップアップに変更。元ページの遷移と二重オープンを防ぐ。
|
||||
- スライドビューアとエディタプレビューに再生/停止、1〜3600秒の間隔、ループを追加。
|
||||
- Domain管理にMachine Learning設定パネルを追加。設定保存だけでは学習・文書送信は開始しない。
|
||||
|
||||
## 基盤と境界
|
||||
|
||||
- MySQL 8.4向けにML予算、Campus/Domain、ユーザー/グループ、認証情報保存の限定実装を追加。
|
||||
schemaのstatus/check/apply/resumeは明示CLIのみ。本体のMySQL起動は未対応。
|
||||
- Pages Machine Learningは任意の独立サービス。通常の配備には含めず、自動起動しない。
|
||||
- DB検査では未導入のML予算schemaを任意機能として扱う。部分導入・導入後のテーブル欠落は引き続き異常として検出する。
|
||||
- ファイル検査のpolicy/plugin実行基盤は未接続。今回の更新で検査済み保証を追加しない。
|
||||
- CLIスキル初版、展示マニフェスト・合成データ・紹介資料を保存。展示クラスタは配備対象外。
|
||||
|
||||
## データ互換性と配備条件
|
||||
|
||||
今回の機能用ML予算migrationは通常起動に接続していない。MySQLやMLサービスへ本番データを移さない。
|
||||
既存のDB種別・保存先・稼働サービスを維持する。未起動の外部インスタンスを更新の副作用で起動しない。
|
||||
実際の稼働イメージがv0.18.0と同一とは限らないため、旧イメージと停止時点の保存領域・設定を保全する。
|
||||
復旧時は切替後の書込みを保全し、バックアップを稼働中の保存領域へ上書きしない。
|
||||
|
||||
## 検証
|
||||
|
||||
整理時にSQLite/PostgreSQL 17/MySQL 8.4の対象契約をrace付きで確認。
|
||||
RSSとスライドはPC・モバイルのChromium試験、MLは隔離環境の合成データ試験を実施。
|
||||
リリース判定はGiteaの全Goテスト・PostgreSQL試験・4イメージ公開の成功後に行う。
|
||||
任意のMLサービスとGecko relayは本番更新で起動しない。
|
||||
@@ -0,0 +1,44 @@
|
||||
# Pages / pages-cli 紹介資料
|
||||
|
||||
2026年11月の展示に向けて作った資料を、編集元・図版・配布成果物と一緒に保存する。
|
||||
現行バージョンの対応表ではない。機能の実装状況は [残件台帳](../design/ja/implementation-backlog.md)、
|
||||
DBの対応範囲は [DB移植計画](../design/ja/database-portability.md) を参照する。
|
||||
|
||||
## Pagesのスライド機能用
|
||||
|
||||
| 編集元 | 用途 |
|
||||
| --- | --- |
|
||||
| `pages-architecture-ja.md` | 技術説明の詳細な構成案 |
|
||||
| `pages-architecture-5min-ja.md` | 10枚・約5分の紹介。30秒送りを想定 |
|
||||
| `../../static/diagrams/pages-architecture/*.svg` | 5分版で参照する編集可能な構成図 |
|
||||
|
||||
Markdownの `---` をスライド境界として使用する。Pagesへ通常の権限確認・保存を行い、
|
||||
スライドビューアで開く。Gitへの保存だけでは公開Wikiの作成・更新にはならない。
|
||||
図版はアプリと一緒に配信する必要がある。
|
||||
[再生・ループの操作](../design/ja/slideshow.md)も参照。
|
||||
|
||||
## A4配布資料
|
||||
|
||||
`../../output/pdf/` のPDFとSVGは、展示時の配布成果物として意図的にGitへ保存する。
|
||||
レンダリング用PNGや一時ファイルは含めない。ファイル名は既存の配布リンクを維持するため変更しない。
|
||||
|
||||
- `pages-pages-cli-four-sheets-a4-ja.pdf`:技術・思想・画面設計・ディスカッションの4枚組。
|
||||
- `pages-pages-cli-discussion-a4-ja.pdf`:ディスカッション単独版。
|
||||
- `architecture`、`design`、`interface` の単独PDF、および `technical-and-design`、`three-sheets`:
|
||||
段階的に作成した既存配布版。過去の成果物として保持し、4枚組から機械的に切り出したものとは扱わない。
|
||||
- 同ディレクトリのSVG:A4資料の構成図。スライド用SVGとは別の図版。
|
||||
|
||||
`build-pages-onepager.py` が現在生成するPDFは **4枚組とディスカッションの2ファイル**。
|
||||
加えてA4用SVGを出力する。その他の既存PDFは上書き・再生成しない。
|
||||
|
||||
再生成にはPython、ReportLab、DejaVu Sans/Sans MonoとDroidSansFallbackFullのフォントが必要。
|
||||
フォントパスはスクリプト冒頭で指定する。日付・機能記述は展示時点のままなので、
|
||||
現在版へ更新する場合は本文を再確認してから実行する。
|
||||
|
||||
```sh
|
||||
python3 docs/presentations/build-pages-onepager.py
|
||||
# 一時ディレクトリで4ページすべてを描画し、重なり・文字欠けを確認する
|
||||
pdftoppm -png output/pdf/pages-pages-cli-four-sheets-a4-ja.pdf /tmp/pages-handout
|
||||
```
|
||||
|
||||
2026-11-30の整理では既存4枚組を描画確認し、PDF自体は再生成していない。
|
||||
@@ -0,0 +1,533 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the A4 technical handout and its editable vector diagrams.
|
||||
|
||||
Requires reportlab. Source: repository design/operations docs and sibling
|
||||
pages-cli README + docs/neomutt.md, reviewed 2026-11-15.
|
||||
All coordinates are points, measured from the top left. Diagram primitives
|
||||
are emitted to both SVG and PDF so the standalone figures match the handout.
|
||||
"""
|
||||
from pathlib import Path
|
||||
from html import escape
|
||||
import math
|
||||
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
from reportlab.lib.colors import HexColor
|
||||
from reportlab.lib.pagesizes import A4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
OUT = ROOT / "output/pdf"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
INK, MUTED, LINE = "#172433", "#526171", "#b6c2cd"
|
||||
ACCENT, PALE, WHITE = "#244d70", "#f1f5f8", "#ffffff"
|
||||
FONT_DIR = Path("/usr/share/fonts/truetype")
|
||||
pdfmetrics.registerFont(TTFont("Latin", str(FONT_DIR / "dejavu/DejaVuSans.ttf")))
|
||||
pdfmetrics.registerFont(TTFont("LatinBold", str(FONT_DIR / "dejavu/DejaVuSans-Bold.ttf")))
|
||||
pdfmetrics.registerFont(TTFont("Mono", str(FONT_DIR / "dejavu/DejaVuSansMono.ttf")))
|
||||
pdfmetrics.registerFont(TTFont("JP", str(FONT_DIR / "droid/DroidSansFallbackFull.ttf")))
|
||||
|
||||
|
||||
def runs(s, bold=False, mono=False):
|
||||
current, buf = None, ""
|
||||
for ch in s:
|
||||
font = "JP" if ord(ch) > 0x2FFF else ("Mono" if mono else "LatinBold" if bold else "Latin")
|
||||
if current is not None and font != current:
|
||||
yield current, buf
|
||||
buf = ""
|
||||
current, buf = font, buf + ch
|
||||
if buf:
|
||||
yield current, buf
|
||||
|
||||
|
||||
def width(s, size, bold=False, mono=False):
|
||||
return sum(pdfmetrics.stringWidth(t, f, size) for f, t in runs(s, bold, mono))
|
||||
|
||||
|
||||
class Drawing:
|
||||
def __init__(self, w, h, title):
|
||||
self.w, self.h, self.title, self.items = w, h, title, []
|
||||
|
||||
def box(self, x, y, w, h, fill=WHITE, stroke=LINE, radius=2):
|
||||
self.items.append(("box", x, y, w, h, fill, stroke, radius))
|
||||
|
||||
def line(self, x1, y1, x2, y2, color=LINE, dashed=False):
|
||||
self.items.append(("line", x1, y1, x2, y2, color, dashed))
|
||||
|
||||
def arrow(self, x1, y1, x2, y2, color=MUTED, dashed=False):
|
||||
self.line(x1, y1, x2, y2, color, dashed)
|
||||
a = math.atan2(y2-y1, x2-x1)
|
||||
for delta in (-0.45, 0.45):
|
||||
self.line(x2, y2, x2-4*math.cos(a+delta), y2-4*math.sin(a+delta), color)
|
||||
|
||||
def text(self, x, y, s, size=9, bold=False, color=INK, align="left", mono=False):
|
||||
self.items.append(("text", x, y, s, size, bold, color, align, mono))
|
||||
|
||||
def pdf(self, c, x=0, y=0):
|
||||
ph = A4[1]
|
||||
for p in self.items:
|
||||
if p[0] == "box":
|
||||
_, bx, by, w, h, fill, stroke, r = p
|
||||
c.setFillColor(HexColor(fill)); c.setStrokeColor(HexColor(stroke)); c.setLineWidth(.6)
|
||||
c.roundRect(x+bx, ph-y-by-h, w, h, r, fill=1, stroke=1)
|
||||
elif p[0] == "line":
|
||||
_, x1,y1,x2,y2,col,dash=p
|
||||
c.setStrokeColor(HexColor(col)); c.setLineWidth(.65); c.setDash([2,2] if dash else [])
|
||||
c.line(x+x1,ph-y-y1,x+x2,ph-y-y2); c.setDash([])
|
||||
else:
|
||||
_, tx,ty,s,size,bold,col,align,mono=p
|
||||
w=width(s,size,bold,mono)
|
||||
tx -= w/2 if align=="center" else w if align=="right" else 0
|
||||
c.setFillColor(HexColor(col))
|
||||
for f,t in runs(s,bold,mono):
|
||||
c.setFont(f,size); c.drawString(x+tx,ph-y-ty,t)
|
||||
tx += pdfmetrics.stringWidth(t,f,size)
|
||||
|
||||
def svg(self, path):
|
||||
a=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{self.w}pt" height="{self.h}pt" viewBox="0 0 {self.w} {self.h}" role="img" aria-labelledby="title">',
|
||||
f'<title id="title">{escape(self.title)}</title>', '<rect width="100%" height="100%" fill="white"/>']
|
||||
for p in self.items:
|
||||
if p[0]=="box":
|
||||
_,x,y,w,h,fill,stroke,r=p
|
||||
a.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{r}" fill="{fill}" stroke="{stroke}" stroke-width="0.6"/>')
|
||||
elif p[0]=="line":
|
||||
_,x1,y1,x2,y2,col,dash=p
|
||||
d=' stroke-dasharray="2 2"' if dash else ''
|
||||
a.append(f'<line x1="{x1}" y1="{y1}" x2="{x2}" y2="{y2}" stroke="{col}" stroke-width="0.65"{d}/>')
|
||||
else:
|
||||
_,x,y,s,size,bold,col,align,mono=p
|
||||
anchor={"left":"start","center":"middle","right":"end"}[align]
|
||||
family="DejaVu Sans Mono,monospace" if mono else "DejaVu Sans,Noto Sans CJK JP,sans-serif"
|
||||
a.append(f'<text x="{x}" y="{y}" font-family="{family}" font-size="{size}" font-weight="{700 if bold else 400}" text-anchor="{anchor}" fill="{col}">{escape(s)}</text>')
|
||||
path.write_text('\n'.join(a)+"\n</svg>\n",encoding="utf-8")
|
||||
|
||||
|
||||
def architecture():
|
||||
d=Drawing(535,179,"Pages and pages-cli: application, extensions, APIs and storage")
|
||||
for x,w,title,sub in [(0,163,"Web / PWA","Wiki · City · Organizer"),(186,163,"pages-cli / pages","Shell · $EDITOR · NeoMutt"),(372,163,"DAV clients","CalDAV · CardDAV")]:
|
||||
d.box(x,0,w,32,PALE); d.text(x+8,13,title,9,True); d.text(x+8,25,sub,7.4,color=MUTED)
|
||||
d.arrow(x+w/2,32,x+w/2,55)
|
||||
d.text(91,46,"HTTPS",6.8,color=MUTED)
|
||||
d.text(278,46,"HTTPS / Bearer",6.8,color=MUTED)
|
||||
d.text(465,46,"HTTPS / DAV",6.8,color=MUTED)
|
||||
d.box(0,55,535,70,WHITE,ACCENT)
|
||||
d.text(10,70,"PagesWiki / Go application",10,True,ACCENT)
|
||||
d.text(525,70,"Host-based routing / HTTP API",7.6,color=MUTED,align="right")
|
||||
d.line(10,77,525,77)
|
||||
components=[("Wiki / files","Editor · viewers · City Map"),("System extensions","Tasks · calendar · contacts · RSS"),("Integration / jobs","DAV · plugins · background jobs")]
|
||||
for i,(name,role) in enumerate(components):
|
||||
x=10+i*173; y=84
|
||||
d.box(x,y,169,32,PALE,LINE)
|
||||
d.text(x+7,y+13,name,8.7,True); d.text(x+7,y+25,role,7.1,color=MUTED)
|
||||
d.arrow(130,125,130,145); d.arrow(403,125,403,145)
|
||||
d.box(0,145,260,34,PALE); d.box(275,145,260,34,PALE)
|
||||
d.text(9,159,"SQLite / PostgreSQL 17",9,True)
|
||||
d.text(9,172,"Metadata · revisions · settings · indexes",7.5,color=MUTED)
|
||||
d.text(284,159,"Persistent files",9,True)
|
||||
d.text(284,172,"HTML · attachments · calendar / task data",7.5,color=MUTED)
|
||||
return d
|
||||
|
||||
|
||||
def domains():
|
||||
d=Drawing(252,92,"Campus manages domains independently of application instances")
|
||||
d.box(0,0,252,23,PALE)
|
||||
d.text(126,15,"Campus / configuration controller",8.4,True,align="center")
|
||||
d.arrow(60,23,60,42,dashed=True); d.arrow(192,23,192,42,dashed=True)
|
||||
for x,label,hosts in [(0,"Instance A",["wiki.example.test","lab.example.test"]),(132,"Instance B",["team.example.test"])]:
|
||||
d.box(x,42,120,49,WHITE,ACCENT); d.text(x+7,55,label,8.3,True)
|
||||
for i,host in enumerate(hosts):
|
||||
d.text(x+7,69+13*i,host,7,mono=True)
|
||||
return d
|
||||
|
||||
|
||||
def editing():
|
||||
d=Drawing(252,92,"HTML and Markdown editing, conversion and preview")
|
||||
for x,w,title,sub in [(0,76,"Markdown","editing"),(102,64,"HTML","stored content")]:
|
||||
d.box(x,11,w,35,PALE); d.text(x+w/2,25,title,9,True,align="center"); d.text(x+w/2,38,sub,7,color=MUTED,align="center")
|
||||
d.arrow(76,22,102,22); d.arrow(102,35,76,35)
|
||||
d.text(87,7,"convert",6.4,align="center",color=MUTED)
|
||||
d.box(192,11,60,35,PALE); d.text(222,25,"Viewer",8.6,True,align="center"); d.text(222,38,"Preview",7,color=MUTED,align="center")
|
||||
d.arrow(166,29,192,29)
|
||||
d.line(134,46,134,64); d.arrow(134,64,222,64)
|
||||
d.text(0,83,"HTML fragments retained in Markdown",7.2,color=MUTED)
|
||||
d.text(222,76,"Slides",7.7,True,align="center")
|
||||
d.text(222,89,"Reveal.js",7,color=MUTED,align="center")
|
||||
return d
|
||||
|
||||
|
||||
def identity():
|
||||
d=Drawing(252,79,"Paths resolve to a stable Page, immutable revisions and content hashes")
|
||||
for y,label in [(0,"/guide/api"),(33,"/project/ref")]:
|
||||
d.box(0,y,66,24,PALE); d.text(33,y+15,label,7,align="center",mono=True)
|
||||
d.box(83,15,49,29,PALE); d.text(107.5,27,"Page",8,True,align="center"); d.text(107.5,38,"UUID",7,color=MUTED,align="center")
|
||||
d.arrow(66,12,83,24); d.arrow(66,45,83,35)
|
||||
d.box(147,15,47,29,PALE); d.text(170.5,27,"Revision",7.2,True,align="center"); d.text(170.5,38,"UUID / lang",6.2,color=MUTED,align="center")
|
||||
d.arrow(132,29,147,29)
|
||||
d.box(209,15,43,29,PALE); d.text(230.5,27,"Document",6.4,True,align="center"); d.text(230.5,38,"SHA-256",6.6,color=MUTED,align="center")
|
||||
d.arrow(194,29,209,29)
|
||||
d.text(0,74,"mutable address",7,color=MUTED)
|
||||
d.text(83,74,"stable identity / immutable history",7,color=MUTED)
|
||||
return d
|
||||
|
||||
|
||||
def city():
|
||||
d=Drawing(252,79,"Campus and Domain organize Quartier, Street, Spot and Pages")
|
||||
d.text(0,9,"Campus",8.5,True); d.arrow(45,6,60,6); d.text(65,9,"Domain = FQDN / namespace",8.2,True)
|
||||
boxes=[(0,72,"Quartier","/lab"),(90,72,"Street","/lab/web"),(180,72,"Spot","/lab/web/api")]
|
||||
for x,w,title,sub in boxes:
|
||||
d.box(x,24,w,32,PALE); d.text(x+w/2,37,title,8,True,align="center"); d.text(x+w/2,49,sub,6.6,color=MUTED,align="center",mono=True)
|
||||
d.arrow(72,40,90,40); d.arrow(162,40,180,40)
|
||||
d.arrow(216,56,216,66); d.text(216,77,"Pages",8,True,align="center")
|
||||
d.text(0,76,"path boundaries / map navigation",7,color=MUTED)
|
||||
return d
|
||||
|
||||
|
||||
def body(d,x,y,lines,size=8.7,leading=13):
|
||||
for i,s in enumerate(lines):
|
||||
d.text(x,y+i*leading,s,size)
|
||||
|
||||
|
||||
def section(d,y,number,title):
|
||||
d.text(30,y,number,8.5,True,ACCENT)
|
||||
d.text(51,y,title,10.3,True)
|
||||
|
||||
|
||||
def technical_page():
|
||||
page=Drawing(*A4,"Pages / pages-cli architecture handout")
|
||||
page.text(30,33,"01 / TECHNICAL ARCHITECTURE",8,True,ACCENT)
|
||||
page.text(565,33,"2026-11-15 / PagesWiki v0.18.0",7.6,color=MUTED,align="right")
|
||||
page.text(30,64,"Pages",28,True)
|
||||
page.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||
page.text(30,86,"Wiki・ファイル・タスク・予定を、ブラウザとターミナルで扱う。",10.7)
|
||||
page.line(30,99,565,99,ACCENT)
|
||||
section(page,117,"01","全体構成:Go製サーバー + Python製CLI + 形式別の表示・編集機能")
|
||||
arch=architecture(); domain=domains(); editor=editing()
|
||||
|
||||
section(page,333,"02","ドメイン:サイトと配置先を分ける")
|
||||
page.text(313,333,"03",8.5,True,ACCENT)
|
||||
page.text(334,333,"エディタとトランスパイル",10.3,True)
|
||||
body(page,30,456,["ドメインはFQDNごとのWiki。パス・設定・メンバーを分離。",
|
||||
"キャンパスは複数ドメインと配置先インスタンスを管理。",
|
||||
"一つのインスタンスに複数サイトを収容でき、別配置も可能。",
|
||||
"配信するのは設定であり、記事の複製機能ではない。",
|
||||
"HTTPのHostからサイトを選択。パスの重複はサイト間で許容。",
|
||||
"設定配信は署名付き。配置先は参加・承認済みから選択。"],8.05,12.5)
|
||||
body(page,313,456,["内蔵エディタはHTML/Markdown切替とライブプレビュー。",
|
||||
"Wiki本文はHTMLで保存。編集時にMarkdownへ変換し、",
|
||||
"Markdownで表せない属性・構造はHTMLのまま残す。",
|
||||
"children・CSVマクロは編集時に保持し、表示時に展開。",
|
||||
"同じ文書を通常ページ・印刷・Reveal.jsスライドで表示。",
|
||||
"外部編集にはcode-server連携。vim.wasmは改善保留。"],8.05,12.5)
|
||||
|
||||
page.line(30,535,565,535)
|
||||
section(page,556,"04","プラグイン:文書操作と機能追加")
|
||||
page.text(313,556,"05",8.5,True,ACCENT)
|
||||
page.text(334,556,"pages-cli:端末からの操作",10.3,True)
|
||||
page.text(30,578,"表示・編集アダプタ",9,True,ACCENT)
|
||||
body(page,30,595,["MIME・拡張子からビューア/エディタを選択する。",
|
||||
"CSV・PDF・画像・動画・アーカイブ・Excalidraw等に対応。",
|
||||
"外部エディタは別コンテナで動作し、ゲートウェイ経由で",
|
||||
"ファイルを受け渡す。保存結果はWikiの履歴へ追加。"],8.05,12.5)
|
||||
page.text(30,660,"システム拡張",9,True,ACCENT)
|
||||
body(page,30,677,["タスク・カレンダー・連絡先・ブログ・日記・RSSを提供。",
|
||||
"例:RSS記事をWiki/タスクへ、予定・連絡先をDAVで同期。",
|
||||
"設定画面で有効/無効を切替。外部表示・編集サービスは",
|
||||
"URL登録で追加できる。任意コードの動的ロードは未対応。"],8.05,12.5)
|
||||
body(page,313,578,["独立リポジトリで配布するHTTPクライアント。実行名 pages。",
|
||||
"対話シェル、$EDITOR/$PAGER、言語指定、OIDC承認。",
|
||||
"タスクの作成・計画・作業時間記録・レポート、連絡先検索。",
|
||||
"NeoMuttから本文をWikiへ保存し、関連タスクを作成する。"],8.05,12.5)
|
||||
page.box(313,631,252,89,PALE)
|
||||
for y,s in [(646,"pages login --oidc --no-browser"),(662,"pages edit /lab/guide --lang ja"),(678,"pages task from-mail < message.eml"),(694,"pages task start TASK_UUID"),(710,"pages task stop")]:
|
||||
page.text(322,y,s,7.3,mono=True)
|
||||
|
||||
page.line(30,738,565,738)
|
||||
page.text(30,755,"現行の制約",8.2,True,ACCENT)
|
||||
body(page,30,770,["v0.18.0は単一書込インスタンス構成。PostgreSQL版は本文全文検索・外部エディタ連携・Web Push等が未対応。",
|
||||
"内蔵エディタとInboxは利用可能。プラグインの利用可否はDB構成・追加サービスの配置に依存する。"],7.8,12)
|
||||
page.line(30,798,565,798)
|
||||
page.text(30,812,"設計資料:docs/design/ja/{campus-federation,viewer-editor,editor-resilience,extensions}.md",6.8,color=MUTED)
|
||||
page.text(30,824,"構成制約:docs/operations/postgresql-migration.md | CLI:git.anya.jp/anya/pages-cli",6.8,color=MUTED)
|
||||
|
||||
for name,d in [("pages-system-architecture",arch),("pages-domain-deployment",domain),("pages-editor-conversion",editor)]:
|
||||
d.svg(OUT/(name+".svg"))
|
||||
return [(page,0,0),(arch,30,130),(domain,30,346),(editor,313,346)]
|
||||
|
||||
|
||||
def city_navigation():
|
||||
d=Drawing(535,128,"URL hierarchy as districts, streets and places: conceptual navigation")
|
||||
d.box(0,0,535,127,WHITE,ACCENT)
|
||||
d.text(12,17,"wiki.example.test",10,True)
|
||||
d.text(523,17,"One domain / one city",8,color=MUTED,align="right")
|
||||
for x,title,path,street,spot in [(12,"Research","/lab","/lab/web","/lab/web/api"),(187,"Operations","/ops","/ops/network","/ops/network/dns"),(362,"Projects","/projects","/projects/wiki","/projects/wiki/editor")]:
|
||||
d.box(x,29,161,86,PALE)
|
||||
d.text(x+9,44,title,9,True); d.text(x+152,44,path,7.2,align="right",mono=True)
|
||||
d.line(x+10,62,x+151,62,LINE)
|
||||
d.text(x+9,57,street,7.1,mono=True)
|
||||
d.line(x+26,62,x+26,78,ACCENT)
|
||||
d.box(x+11,79,139,25,WHITE)
|
||||
d.text(x+80.5,95,spot,7,align="center",mono=True)
|
||||
return d
|
||||
|
||||
|
||||
def work_connections():
|
||||
d=Drawing(252,79,"Email and RSS connect to Wiki, tasks and work records")
|
||||
for x,title,sub in [(0,"Mail / RSS","capture"),(90,"Wiki + task","link"),(180,"Work log","report")]:
|
||||
d.box(x,16,72,37,PALE)
|
||||
d.text(x+36,31,title,8,True,align="center")
|
||||
d.text(x+36,44,sub,7,color=MUTED,align="center")
|
||||
d.arrow(72,34,90,34); d.arrow(162,34,180,34)
|
||||
d.text(0,74,"NeoMutt / pages-cli / Web dashboard",7.2,color=MUTED)
|
||||
return d
|
||||
|
||||
|
||||
def multiple_contexts():
|
||||
d=Drawing(252,79,"Two navigation paths open the same page")
|
||||
for y,path in [(0,"/guide/api"),(35,"/project/ref")]:
|
||||
d.box(0,y,83,26,PALE)
|
||||
d.text(41.5,y+17,path,8,align="center",mono=True)
|
||||
d.box(119,10,133,42,PALE)
|
||||
d.text(185.5,28,"One page",10,True,align="center")
|
||||
d.text(185.5,43,"Shared content / history",7,align="center",color=MUTED)
|
||||
d.arrow(83,13,119,22); d.arrow(83,48,119,40)
|
||||
d.text(0,76,"Multiple paths, no document copies",7.4,color=MUTED)
|
||||
return d
|
||||
|
||||
|
||||
def design_page():
|
||||
p=Drawing(*A4,"Pages / pages-cli design choices")
|
||||
p.text(30,33,"02 / DESIGN CONCEPT",8,True,ACCENT)
|
||||
p.text(565,33,"2026-11-15 / PagesWiki",7.6,color=MUTED,align="right")
|
||||
p.text(30,64,"Pages",28,True); p.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||
p.text(30,86,"URLの階層を街の案内図に。文書を日々の作業につなぐ。",10.7)
|
||||
p.line(30,99,565,99,ACCENT)
|
||||
section(p,117,"01","フォルダの階層に、地図という入口を重ねる")
|
||||
town=city_navigation(); ident=multiple_contexts(); work=work_connections()
|
||||
body(p,30,278,["Knowledge City Modelは、ドメインを街、URLの配下を街区(Quartier)・通り(Street)・拠点(Spot)として扱う。",
|
||||
"検索語が浮かばないときも、分野や周辺のページから探せる。地図・ツリー・検索は同じ文書群の別の入口。",
|
||||
"URLからの自動分類を起点に、名前や範囲を調整する。地図のためだけに別の分類体系を作り直さない。",
|
||||
"用途や公開範囲が異なるサイトはドメインを分け、各サイトの設定・メンバーを個別に管理する。"],8.4,13)
|
||||
p.text(565,263,"図は階層の概念図。実際のCity Map画面ではない。",6.6,color=MUTED,align="right")
|
||||
|
||||
section(p,337,"02","一つのページを複数の文脈に置く")
|
||||
p.text(313,337,"03",8.5,True,ACCENT); p.text(334,337,"文書を作業の流れへ組み込む",10.3,True)
|
||||
body(p,30,444,["手順書を「技術分野」と「プロジェクト」の両方から参照。",
|
||||
"コピーではなく、複数のパスで同じページを指す。",
|
||||
"内容を更新すれば、どちらの入口からも同じ版を読める。",
|
||||
"「分類し直す」と「別の文書を作る」を分けることで、",
|
||||
"整理のための複製や、コピー先だけの更新漏れを減らす。"],8.05,13)
|
||||
body(p,313,444,["メールやRSSを読んだ場所から、Wiki保存とタスク化へ。",
|
||||
"タスクから関連メモを開き、作業時間や予定と結び付ける。",
|
||||
"予定・連絡先はCalDAV/CardDAVで既存アプリとも接続。",
|
||||
"Webでは一覧・カレンダー・ウィジェット、端末では短い",
|
||||
"コマンドを使い、作業環境に合わせて入口を選ぶ。"],8.05,13)
|
||||
p.line(30,512,565,512)
|
||||
section(p,534,"04","文書形式と、使う道具を固定しない")
|
||||
p.text(30,558,"編集はMarkdown、表示は用途に合わせる",9.2,True,ACCENT)
|
||||
body(p,30,578,["Wiki本文の保存形式はHTML。Markdownで書き、必要な部分はHTMLを残して編集できる。",
|
||||
"文書をページ・印刷・スライドとして使い分ける。CSVや図は専用の表示・編集機能で扱う。"],8.6,14)
|
||||
p.text(30,618,"プラグインは二つの役割に分ける",9.2,True,ACCENT)
|
||||
p.box(30,631,252,61,PALE); p.box(313,631,252,61,PALE)
|
||||
p.text(41,648,"文書の表示・編集",9,True)
|
||||
body(p,41,665,["CSV表、Excalidraw、Reveal.js、外部エディタ。",
|
||||
"同じ内容を、その形式に向いた道具で扱う。"],8.1,13)
|
||||
p.text(324,648,"アプリケーション機能の追加",9,True)
|
||||
body(p,324,665,["タスク、カレンダー、連絡先、ブログ、日記、RSS。",
|
||||
"文書以外の画面・操作・設定を追加する。"],8.1,13)
|
||||
body(p,30,715,["内蔵エディタで完結する使い方も、code-serverやpages-cliの $EDITOR を使う選択肢も用意する。",
|
||||
"必要な機能を有効にして使う。外部サービスの配置・DB構成による対応範囲は技術編に記載。"],8.4,14)
|
||||
p.line(30,748,565,748)
|
||||
p.text(30,766,"デザインの軸",8.5,True,ACCENT)
|
||||
p.text(112,766,"街として探す / コピーせず参照する / 作業につなぐ / 道具を選ぶ",9.4,True)
|
||||
p.line(30,798,565,798)
|
||||
p.text(30,812,"設計資料:docs/design/ja/{principles,campus-federation,viewer-editor,extensions}.md / pages-cli README",6.8,color=MUTED)
|
||||
p.text(30,824,"Knowledge City Model:『とある科学の超電磁砲』の学舎の園に着想。構成・実装制約は別紙「技術編」を参照。",6.8,color=MUTED)
|
||||
for name,d in [("pages-design-city-navigation",town),("pages-design-multiple-paths",ident),("pages-design-workflow",work)]:
|
||||
d.svg(OUT/(name+".svg"))
|
||||
return [(p,0,0),(town,30,130),(ident,30,350),(work,313,350)]
|
||||
|
||||
|
||||
def export_pdf(path, pages, title):
|
||||
c=canvas.Canvas(str(path),pagesize=A4,pageCompression=1)
|
||||
c.setTitle(title); c.setAuthor("PagesWiki project")
|
||||
c.setSubject("Pages / pages-cli:技術構成とデザインの説明資料")
|
||||
for drawings in pages:
|
||||
for d,x,y in drawings:
|
||||
d.pdf(c,x,y)
|
||||
c.showPage()
|
||||
c.save()
|
||||
print(path)
|
||||
|
||||
|
||||
def screen_layout():
|
||||
d=Drawing(535,144,"Desktop information density and mobile touch layout: conceptual wireframes")
|
||||
d.box(0,0,350,143,WHITE,ACCENT)
|
||||
d.box(0,0,350,24,PALE,LINE)
|
||||
d.text(8,16,"Pages",9,True)
|
||||
d.box(54,5,140,14,WHITE)
|
||||
d.text(61,15,"Search / command",7,color=MUTED)
|
||||
d.text(341,15,"Plan Inbox Theme User",7,align="right")
|
||||
d.box(7,31,70,104,PALE)
|
||||
d.text(13,44,"Projects",8,True)
|
||||
for i,s in enumerate(["All tasks","Wiki","Exhibition","Personal"]):
|
||||
if i==2: d.box(11,76,61,16,"#dce8f0",LINE)
|
||||
d.text(14,61+i*15,s,7.2)
|
||||
d.text(87,43,"Status / Subject",7.5,True)
|
||||
d.text(340,43,"Due / Wiki",7.5,True,align="right")
|
||||
for i,(s,date) in enumerate([("Review API design","11-15"),("Prepare exhibit","11-16"),("Write deployment notes","11-17"),("Update diagrams","11-18")]):
|
||||
y=50+i*20
|
||||
if i==1: d.box(83,y,259,20,"#dce8f0",LINE)
|
||||
d.text(88,y+13,s,7.4); d.text(337,y+13,date,7.2,align="right")
|
||||
d.line(83,y+20,342,y+20)
|
||||
d.box(374,0,161,143,WHITE,ACCENT)
|
||||
d.box(374,0,161,24,PALE)
|
||||
d.text(383,16,"Pages / Tasks",8.5,True)
|
||||
for i,(s,sub) in enumerate([("Review API design","In progress / Nov 15"),("Prepare exhibit","To do / Nov 16")]):
|
||||
y=32+i*52
|
||||
d.box(382,y,145,44,PALE)
|
||||
d.text(389,y+14,s,8,True); d.text(389,y+28,sub,7,color=MUTED)
|
||||
d.text(389,y+39,"Edit Date Wiki",7)
|
||||
return d
|
||||
|
||||
|
||||
def theme_variants():
|
||||
d=Drawing(535,70,"Same layout with light, dark and wallpaper-derived colors; illustrative palettes")
|
||||
for x,label,bg,fg,accent in [(0,"LIGHT","#f1f5f8","#172433","#dce8f0"),(186,"DARK","#26303d","#e3eaf1","#405569"),(372,"WALLPAPER COLOR","#f0ebe5","#42392e","#d3c2ac")]:
|
||||
d.box(x,0,163,69,bg)
|
||||
d.text(x+8,14,label,7.5,True,fg)
|
||||
d.box(x+8,22,147,15,accent,accent)
|
||||
d.text(x+14,32,"Search / command",7,color=fg)
|
||||
d.line(x+8,45,x+155,45,fg); d.line(x+8,54,x+109,54,fg)
|
||||
d.text(x+8,64,"Same controls / layout",6.6,color=fg)
|
||||
return d
|
||||
|
||||
|
||||
def screen_page():
|
||||
p=Drawing(*A4,"Pages / pages-cli screen and interaction design")
|
||||
p.text(30,33,"03 / INTERFACE & INTERACTION",8,True,ACCENT)
|
||||
p.text(565,33,"2026-11-15 / PagesWiki",7.6,color=MUTED,align="right")
|
||||
p.text(30,64,"Pages",28,True); p.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||
p.text(30,86,"一覧で見渡し、キーで動かす。配色と入口は使う人に合わせる。",10.7)
|
||||
p.line(30,99,565,99,ACCENT)
|
||||
section(p,117,"01","デスクトップは一覧密度、モバイルはタッチ操作を優先")
|
||||
layout=screen_layout(); themes=theme_variants()
|
||||
p.text(30,285,"デスクトップ:プロジェクト+表形式の一覧",7.5,color=MUTED)
|
||||
p.text(404,285,"モバイル:カード型の操作領域",7.5,color=MUTED)
|
||||
body(p,30,304,["タスクは1行ずつ比較し、通常一覧では件名・状態・日付をその場で編集。キーボード一覧は別表示として用意。",
|
||||
"設定・詳細だけをダイアログへ。ダッシュボードはウィジェットを並べ替え、サイズを変更できる。"],8.3,13)
|
||||
|
||||
section(p,343,"02","ショートカット:画面ごとの操作")
|
||||
p.text(313,343,"03",8.5,True,ACCENT); p.text(334,343,"検索欄をコマンドの入口にも",10.3,True)
|
||||
for i,(key,label) in enumerate([
|
||||
("/ e ?","閲覧:検索 / 編集 / ヘルプ"),
|
||||
("Ctrl+↑ / ↓","閲覧:親パス / 子ページ一覧"),
|
||||
("j / k","タスク:次行 / 前行"),
|
||||
("Ctrl+j / k","タスク:プロジェクト移動"),
|
||||
("o / O / l","タスク:ソート / 逆順 / 絞込"),
|
||||
("d / s","タスク:完了 / Pomodoro"),
|
||||
("c / m / w","タスク:作成 / 編集 / Wiki")]):
|
||||
y=363+18*i
|
||||
p.box(30,y-10,80,15,PALE)
|
||||
p.text(36,y,key,8,mono=True)
|
||||
p.text(118,y,label,8.2)
|
||||
p.text(30,492,"タスクの操作表は /v/plan/tasks/index が対象。",7.2,color=MUTED)
|
||||
p.box(313,354,252,69,PALE)
|
||||
for y,s in [(370,'add task "設計レビュー"'),(385,' project:Wiki cost:2h'),(406,'add cal 会議 from:... to:...')]:
|
||||
p.text(322,y,s,8,mono=True)
|
||||
body(p,313,442,["トップの検索候補からページへ直接移動。",
|
||||
"add task / add cal でタスク・予定を作成する。",
|
||||
"project: にはプロジェクト候補、cost: には見積時間。",
|
||||
"予定は from: / to: に日時を入力する。"],8.1,13)
|
||||
|
||||
section(p,523,"04","テーマ:画面内で切替、トップの外観は個別に調整")
|
||||
body(p,30,626,["ナビバーのテーマ選択は再読み込み不要。選択はブラウザに保持し、配色を変えても操作の配置は維持する。",
|
||||
"トップの歯車から、壁紙のパス・濃さ、グラス効果の透明度を個人設定として変更できる。",
|
||||
"壁紙の色から配色を調整するモードと強度も用意。配色と透明度はプレビューしてから保存する。"],8.4,14)
|
||||
p.text(565,613,"配色比較は概念図。特定テーマのスクリーンショットではない。",6.7,color=MUTED,align="right")
|
||||
|
||||
section(p,695,"05","操作を切り替えても、入力の流れを保つ")
|
||||
body(p,30,716,["内蔵エディタは本文とプレビューを並べ、非表示時は編集領域を広げる。タッチ端末ではVimモードを解除。",
|
||||
"単キー操作は入力欄や開いたダイアログでは抑止。タスク一覧は ? から、その画面のキー操作を確認できる。",
|
||||
"ターミナルでは pages の対話シェル・Tab補完・$EDITOR を利用。Webの短い操作とCLIのコマンドを併用する。"],8.2,14)
|
||||
p.text(30,772,"図は画面構成の説明用。キーの役割は画面に依存し、ブラウザ/OSのキー割り当てと競合する場合がある。",7.3,color=MUTED)
|
||||
p.line(30,798,565,798)
|
||||
p.text(30,812,"実装参照:static/js/{viewer-shortcuts,task-index,home-command-parser,theme-picker,home-appearance}.js",6.7,color=MUTED)
|
||||
p.text(30,824,"設計資料:docs/design/ja/{organizer-dashboard,calendar-mobile,editor-resilience}.md / pages-cli README",6.7,color=MUTED)
|
||||
layout.svg(OUT/"pages-interface-layout.svg"); themes.svg(OUT/"pages-interface-themes.svg")
|
||||
return [(p,0,0),(layout,30,130),(themes,30,537)]
|
||||
|
||||
|
||||
def main():
|
||||
tech=technical_page(); design=design_page(); interface=screen_page(); discussion=discussion_page()
|
||||
export_pdf(OUT/"pages-pages-cli-discussion-a4-ja.pdf",[discussion],"Pages / pages-cli - ディスカッション")
|
||||
export_pdf(OUT/"pages-pages-cli-four-sheets-a4-ja.pdf",[tech,design,interface,discussion],"Pages / pages-cli - 技術・デザイン・画面設計・ディスカッション")
|
||||
|
||||
|
||||
def discussion_page():
|
||||
p=Drawing(*A4,"Discussion: what else do you want from a Wiki?")
|
||||
p.text(30,33,"04 / DISCUSSION",8,True,ACCENT)
|
||||
p.text(565,33,"2026-11-15 / PagesWiki",7.6,color=MUTED,align="right")
|
||||
p.text(30,64,"Pages",28,True); p.text(137,64,"/ pages-cli",20,color=MUTED)
|
||||
p.text(30,91,"あなたはWikiに、あと何が欲しいですか?",17,True)
|
||||
p.line(30,105,565,105,ACCENT)
|
||||
p.text(30,123,"気になる機能に○を。機能の追加だけでなく、使いにくさ・不要な機能の意見も歓迎。",9)
|
||||
p.box(30,138,252,28,PALE)
|
||||
p.box(313,138,252,28,PALE)
|
||||
p.text(41,157,"追加している機能",11,True,ACCENT)
|
||||
p.text(271,157,"実装あり",7.5,color=MUTED,align="right")
|
||||
p.text(324,157,"追加予定・検討中",11,True,ACCENT)
|
||||
p.text(554,157,"時期未定",7.5,color=MUTED,align="right")
|
||||
existing=[
|
||||
("文書の編集","HTML/Markdown、下書き、履歴復元、言語別編集"),
|
||||
("探す・整理する","検索、ツリー、City Map、ブックマーク"),
|
||||
("ファイルを扱う","CSV表編集、PDF・画像・動画・アーカイブ閲覧"),
|
||||
("図・発表資料","Excalidraw表示、Reveal.jsスライド・プレビュー"),
|
||||
("タスクと作業記録","親子タスク、日別計画、Pomodoro、実績集計"),
|
||||
("予定と連絡先","カレンダー、アドレス帳、CalDAV/CardDAV"),
|
||||
("情報収集・発信","RSS/FreshRSS連携、ブログ・日記、記事のRSS配信"),
|
||||
("端末・メールとの接続","pages-cli、$EDITOR、NeoMuttからWiki保存・タスク化"),
|
||||
("画面のカスタマイズ","テーマ、壁紙、ショートカット、ウィジェット配置"),
|
||||
("サイト管理・ログイン","複数ドメイン、グループ、公開設定、OIDC/LDAP"),
|
||||
]
|
||||
planned=[
|
||||
("コメント・評価","インラインコメント、スレッド、いいね、品質評価"),
|
||||
("共同編集・編集体験","同時編集、見たまま編集の検討(現在は保留)"),
|
||||
("共有・公開の拡充","期限付き共有URL、承認UI、権限の一覧表示"),
|
||||
("図表・記法の追加","Draw.io、nwdiag、ODS、他Wiki記法の取り込み"),
|
||||
("チームの仕事管理","共有タスク、日課、チケット管理、共有アドレス帳"),
|
||||
("さらに情報を集める","IMAP取り込み、他Wiki・外部検索、Linkding連携"),
|
||||
("外部ストレージ","S3互換、WebDAV、SSHFS等との連携"),
|
||||
("用途別の管理機能","料理レシピ、IPアドレス、DNS、資産管理"),
|
||||
("プラグイン・運用の拡充","第三者プラグイン実行、冗長化、自動切替、監視"),
|
||||
("既存機能をもっと使いやすく","検索・大容量データ・同期互換性・モバイルの改善"),
|
||||
]
|
||||
for x,items in [(30,existing),(313,planned)]:
|
||||
for i,(title,detail) in enumerate(items):
|
||||
y=184+i*31
|
||||
p.box(x+2,y-7,6,6,WHITE,LINE,0)
|
||||
p.text(x+16,y,title,9,True)
|
||||
p.text(x+16,y+13,detail,7.8)
|
||||
if i<9: p.line(x,y+20,x+252,y+20,"#e1e7ec")
|
||||
body(p,30,498,["左欄は一部機能を含む実装一覧で、全環境での提供を保証するものではありません。DB構成による制約は技術編へ。",
|
||||
"右欄は設計TODO・既存機能の拡充候補です。実装や提供時期の確約ではなく、優先順位を議論するための一覧です。"],7.2,11)
|
||||
p.line(30,521,565,521)
|
||||
section(p,542,"01","どんな場面で使いたい?")
|
||||
p.text(30,562,"個人メモ / チームの手順書 / プロジェクト / 調査・学習 / 公開ブログ / その他",9)
|
||||
p.text(30,581,"今使っているツールと、そこで困っていることは?",8.6,color=MUTED)
|
||||
p.line(30,601,565,601,LINE)
|
||||
section(p,626,"02","一覧にないものは? 逆に、いらないものは?")
|
||||
p.text(30,646,"外せない機能、つなぎたいサービス、変えたい操作、Wikiに持たせたくない役割。",9)
|
||||
p.line(30,670,565,670,LINE)
|
||||
p.line(30,691,565,691,LINE)
|
||||
section(p,717,"03","一つだけ先に実装するなら?")
|
||||
p.text(30,739,"欲しい機能:",9,True); p.line(91,743,282,743,LINE)
|
||||
p.text(313,739,"解決したい困りごと:",9,True); p.line(408,743,565,743,LINE)
|
||||
p.text(30,771,"機能名だけでなく、「誰が・いつ・何に困るか」を教えてください。",10,True,ACCENT)
|
||||
p.line(30,798,565,798)
|
||||
p.text(30,812,"参照:docs/design/ja/implementation-backlog.md、extensions.md、organizer-dashboard.md、各機能設計書",6.7,color=MUTED)
|
||||
p.text(30,824,"展示・対話用シート。予定には未着手・保留を含みます。一般的なWikiへの要望も、Pages固有の要望も歓迎します。",6.7,color=MUTED)
|
||||
return [(p,0,0)]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,100 @@
|
||||
# pages
|
||||
|
||||
## 知識の住所と実体を分ける
|
||||
|
||||
Knowledge City Model を持つ知識管理基盤
|
||||
|
||||
技術者向け 5分
|
||||
|
||||
---
|
||||
|
||||
## 全体構成
|
||||
|
||||

|
||||
|
||||
単一writerを基本に、保存・表示・外部連携の責務を分ける。
|
||||
|
||||
---
|
||||
|
||||
## 住所が変わっても同じ知識
|
||||
|
||||

|
||||
|
||||
Path、Page UUID、Revision UUID、Document SHA-256は別の役割。
|
||||
|
||||
---
|
||||
|
||||
## Knowledge Cityによる案内
|
||||
|
||||

|
||||
|
||||
街区から探索し、同じPageを複数の拠点から参照する。
|
||||
|
||||
---
|
||||
|
||||
## 保存の順序が履歴を守る
|
||||
|
||||

|
||||
|
||||
復元も新しい版として追記する。過去の内容を上書きしない。
|
||||
|
||||
---
|
||||
|
||||
## 同じ知識を複数の形式で利用
|
||||
|
||||
| 正本・状態 | 利用するProjection |
|
||||
| --- | --- |
|
||||
| HTML文書と不変Revision | 閲覧・Markdown編集・印刷・このスライド |
|
||||
| PDF・画像・CSV等の固有形式 | MIMEに応じたビューア・編集アダプタ |
|
||||
| Macro宣言 | 表示時だけ認可済みの一覧や表を展開 |
|
||||
|
||||
表示結果を別の正本にしない。変換で表現できないHTMLは保持する。
|
||||
|
||||
---
|
||||
|
||||
## 認証と権限を表示まで貫く
|
||||
|
||||
| 判断するもの | 境界 |
|
||||
| --- | --- |
|
||||
| 誰か | OIDC・LDAP・パスワード等でPrincipalを識別 |
|
||||
| 何ができるか | Domain・グループ・Path・Localityの権限 |
|
||||
| 何を公開するか | 上位の公開上限とRevision・範囲ごとの公開 |
|
||||
| 何を実行するか | sanitizer・CSP・sandboxで制限 |
|
||||
|
||||
UUIDやhashを知っていても権限は得られない。検索・City・cacheも認可対象。
|
||||
|
||||
---
|
||||
|
||||
## Wikiを日々の作業へ接続
|
||||
|
||||
| 入口 | Wikiとの接続 |
|
||||
| --- | --- |
|
||||
| タスク・プロジェクト | 関連Page、作業記録、Pomodoro |
|
||||
| カレンダー・連絡先 | CalDAV・CardDAVの実装プロファイル |
|
||||
| RSS・メール | 明示的なWiki保存・タスク化 |
|
||||
| Web・pages-cli | 同じ業務データを異なる操作環境で利用 |
|
||||
|
||||
外部原本とローカル正本、再取得できるcacheを区別する。
|
||||
|
||||
---
|
||||
|
||||
## 重い処理と復旧の境界
|
||||
|
||||
- previewや同期は背景キューへ送り、閲覧を優先する
|
||||
- Campusは署名付き設定manifestを配信する。記事複製とは別
|
||||
- 現行基盤はSQLiteとローカル保存、単一writer
|
||||
- 自動HA・外部保存・任意プラグイン実行は後続課題
|
||||
|
||||
現行DRは停止snapshotと、外部fenceを前提とした手動昇格。
|
||||
|
||||
---
|
||||
|
||||
## pages の設計上の特色
|
||||
|
||||
**住所が変わっても、知識の実体と履歴を保つ。**
|
||||
|
||||
**街の案内図と多重参照で、複数の文脈から同じ知識へ到達する。**
|
||||
|
||||
**正本・派生データ・権限の境界を、表示や外部連携にも適用する。**
|
||||
|
||||
[設計資料](/lab/pageswiki-dev) [詳細版](/lab/pageswiki-dev/architecture-slides)
|
||||
@@ -0,0 +1,279 @@
|
||||
# pages のアーキテクチャと特色
|
||||
|
||||
Knowledge City Model を持つ知識管理基盤
|
||||
|
||||
技術者向け構成案 2026年11月
|
||||
|
||||
---
|
||||
|
||||
## 1 扱う課題と設計方針
|
||||
|
||||
- 文書の移動や分類変更で、知識の実体と履歴を分断しない
|
||||
- 同じ知識を、複数の場所・言語・表示形式から利用する
|
||||
- Wikiと日々のタスク・予定・受信情報を関連付ける
|
||||
- 認可、正本、派生データの境界を機能追加後も維持する
|
||||
|
||||
---
|
||||
|
||||
## 2 論理モデルの全体像
|
||||
|
||||
| 層 | 責務 |
|
||||
| --- | --- |
|
||||
| Campus / Domain | 管理・配置とFQDN・Path名前空間 |
|
||||
| Quartier / Street / Spot | 知識の整理、案内、管理範囲 |
|
||||
| Page / Revision | 安定した実体と不変の履歴 |
|
||||
| Document | SHA-256で識別する内容バイト列 |
|
||||
| Projection | 閲覧、編集、検索、印刷、スライド |
|
||||
|
||||
---
|
||||
|
||||
## 3 住所と実体と内容の分離
|
||||
|
||||
| 識別子 | 意味 | 変更との関係 |
|
||||
| --- | --- | --- |
|
||||
| Domain + Path | 人が使う住所 | rename・別名追加が可能 |
|
||||
| Page UUID | 知識の実体 | 移動後も維持 |
|
||||
| Revision UUID | 言語を持つ特定の版 | 新しい版を追記 |
|
||||
| Document SHA-256 | 内容の同一性 | 同じバイト列を識別 |
|
||||
|
||||
ハッシュやUUIDを知っていることは、閲覧権限の根拠にならない。
|
||||
|
||||
---
|
||||
|
||||
## 4 Knowledge City Model
|
||||
|
||||
Domainを一つの街として扱う。
|
||||
|
||||
| 単位 | 知識の配置例 |
|
||||
| --- | --- |
|
||||
| Quartier 学区・街区 | `/engineering` |
|
||||
| Street 通り | `/engineering/network` |
|
||||
| Spot 拠点 | `/engineering/network/dns` |
|
||||
| Page 文書 | `/engineering/network/dns/runbook` |
|
||||
|
||||
子のPath境界は親の厳密な子孫。同階層のprimary境界は重複を制限する。
|
||||
|
||||
---
|
||||
|
||||
## 5 階層による案内と多重参照
|
||||
|
||||
- primary所属はPath境界から決定する
|
||||
- 同じPageを別のSpotからも参照できる
|
||||
- 参照を追加しても本文・Revision履歴は複製しない
|
||||
- Spotへの所属と、そのPageを読む権限は別に評価する
|
||||
|
||||
例:運用手順を「DNS」と「障害対応」の両方から紹介する。
|
||||
|
||||
---
|
||||
|
||||
## 6 City Mapによる探索
|
||||
|
||||
- Domain全体の街からQuartier・Street・Spotへ拡大する
|
||||
- Spotの周囲にPageを配置し、拠点と文書の関係を示す
|
||||
- Page数を街の規模に反映し、未整理Pageは個別のポイントにする
|
||||
- 検索・Tree・Browserと併用し、地図だけに到達経路を限定しない
|
||||
|
||||
自動整理には手動編集の保護、再試行時の収束、大規模化の残件がある。
|
||||
|
||||
---
|
||||
|
||||
## 7 実行時の構成
|
||||
|
||||
| 実行単位 | 主な役割 |
|
||||
| --- | --- |
|
||||
| Goアプリケーション | HTTP、認証・認可、保存、検索、ジョブ実行 |
|
||||
| SQLite | identity、Revision参照、権限、設定、キュー等 |
|
||||
| ローカルDocument Store | 不変の内容と拡張ごとのファイル正本 |
|
||||
| Adapter Gateway | ホスト型エディタ等への接続 |
|
||||
| 必要な外部サービス | code-server、Excalidraw、Kroki等 |
|
||||
|
||||
内部パッケージの分離は、マイクロサービスへの分割を意味しない。
|
||||
|
||||
---
|
||||
|
||||
## 8 文書保存の整合性
|
||||
|
||||
1. 対象・言語・形式と書き込み権限を検証する
|
||||
2. 内容のSHA-256を計算し、Documentを先に永続化する
|
||||
3. DBで期待Revisionと照合し、Revisionと必要な参照を確定する
|
||||
4. 接続済みの変更経路ではoutboxを同じtransactionに記録する
|
||||
|
||||
DBの競合で未参照blobが残る場合はある。内容が存在しないRevisionは確定させない。
|
||||
|
||||
---
|
||||
|
||||
## 9 文書とアセットの履歴
|
||||
|
||||
- Revisionは不変。復元も新しいRevisionの追加として扱う
|
||||
- Asset名は編集用の可変HEADとして扱う
|
||||
- 文書保存時にAsset参照を固定ハッシュへ解決する
|
||||
- 過去Revisionの表示を、最新Asset HEADへ追従させない
|
||||
|
||||
GCには現在参照だけでなく、履歴・依存物・保全中データの保護が必要。
|
||||
|
||||
---
|
||||
|
||||
## 10 言語とProjection
|
||||
|
||||
- 言語はRevisionの属性。通常Pathに言語別階層を強制しない
|
||||
- 閲覧時は要求言語とフォールバック方針から版を選ぶ
|
||||
- 編集時は対象言語を明示し、別言語の本文を暗黙に上書きしない
|
||||
- 同じPageを通常表示・RAW・印刷・スライド等で利用する
|
||||
|
||||
文章の正本はHTML。PDFや画像、CSV等の固有形式は元の形式を保持する。
|
||||
|
||||
---
|
||||
|
||||
## 11 エディタの保存と情報保全
|
||||
|
||||
- HTMLとMarkdownを切り替え、プレビューは表示用Projectionを使う
|
||||
- 往復変換で保持できないHTMLは保護ブロックに残す
|
||||
- Macroは編集時に宣言を保持し、表示時に認可済み結果を展開する
|
||||
- 下書き、認証・通信失敗の検知、条件付き保存、競合確認を扱う
|
||||
|
||||
保存時の競合対策と、リアルタイム共同編集は別。共有presence・CRDTは後続課題。
|
||||
|
||||
---
|
||||
|
||||
## 12 認証と認可の境界
|
||||
|
||||
認証器でPrincipalを識別し、Domain membershipと対象操作の権限を別途評価する。
|
||||
|
||||
- パスワード・TOTP、OIDC、LDAP、SMTPマジックリンク
|
||||
- ブラウザCookie、API Bearer、DAV資格情報の用途を分離
|
||||
- グループ・capability・Path・Localityの上限制約を組み合わせる
|
||||
- 閲覧、更新、削除、公開、管理を同一権限として扱わない
|
||||
|
||||
キャッシュやUUID経由の取得でも認可を省略しない。
|
||||
|
||||
---
|
||||
|
||||
## 13 公開範囲と匿名ナビゲーション
|
||||
|
||||
- 上位管理者が公開可能な上限を設定し、下位管理者は狭められる
|
||||
- 特定Revisionの公開と、確認済み範囲の自動公開を区別する
|
||||
- children・Tree・Cityも現在読めるPageで絞る
|
||||
- 公開停止や権限失効後に、古いキャッシュから情報を復活させない
|
||||
|
||||
承認運用の完成、依存物の全影響レビュー、期限付き共有URL管理は残件。
|
||||
|
||||
---
|
||||
|
||||
## 14 保存HTMLと実行可能コンテンツ
|
||||
|
||||
- 保存したHTMLを、そのままアプリの権限で実行しない
|
||||
- Viewer・履歴・印刷・Previewに共通の許可リストとCSPを適用する
|
||||
- 外部画像・CSS・JavaScriptは管理方針による明示的な許可を必要とする
|
||||
- スライドやホスト型ツールは、用途ごとのsandbox・sessionで扱う
|
||||
|
||||
原文の保存、閲覧の許可、スクリプトの実行許可は異なる判断。
|
||||
|
||||
---
|
||||
|
||||
## 15 アダプタとシステム拡張
|
||||
|
||||
| 種別 | 対象 | 例 |
|
||||
| --- | --- | --- |
|
||||
| 連携アダプタ | Documentを開く・編集する | PDF、CSV、Excalidraw、code-server |
|
||||
| システム拡張 | 状態と業務処理を持つ | タスク、予定、RSS、通知 |
|
||||
|
||||
有効化・無効化をデータ削除と分離する。
|
||||
|
||||
現行は信頼済みビルトインが中心。任意の第三者コードを安全に実行する基盤は未完成。
|
||||
|
||||
---
|
||||
|
||||
## 16 Wikiとオーガナイザーの接続
|
||||
|
||||
- タスク・プロジェクトをWiki Pageへ関連付ける
|
||||
- 予定・タスクは共通CalDAV入口、連絡先はCardDAVで外部クライアントと接続する
|
||||
- RSS・メールから、明示的にWikiへ保存・タスク化する
|
||||
- Webとpages-cliで操作し、作業記録や日次メール、ダッシュボードを利用する
|
||||
|
||||
外部サービスの原本、Pages内の正本、表示用cacheを区別する。
|
||||
|
||||
---
|
||||
|
||||
## 17 拡張ごとの正本
|
||||
|
||||
| 対象 | 正本・権威の所在 |
|
||||
| --- | --- |
|
||||
| Wiki本文 | 不変DocumentとRevision等のDBメタデータ |
|
||||
| カレンダー | manifestと月別ICS。DBは再構築可能な索引 |
|
||||
| FreshRSS連携 | FreshRSS。Pagesはクライアントと表示用cache |
|
||||
| 内蔵RSS | Pagesの購読・既読等の状態 |
|
||||
|
||||
CalDAV・CardDAVは実装プロファイルに制限があり、全クライアントへの完全互換は保証しない。
|
||||
|
||||
---
|
||||
|
||||
## 18 背景処理と前景の優先
|
||||
|
||||
- サムネイル、PDF情報、同期、City再整理等を永続キューで処理する
|
||||
- 優先度、同時実行数、入力・出力、実行時間、再試行を制限する
|
||||
- outboxとconsumer checkpointで接続済みの変更処理を配送する
|
||||
- CPU・メモリ・I/O履歴と実行中ジョブを運用画面で確認する
|
||||
|
||||
配送はat-least-onceを前提とする。分散lease・重み付き予算・全書込経路の接続は残件。
|
||||
|
||||
---
|
||||
|
||||
## 19 Campusによる設定連携
|
||||
|
||||
- CampusがDomainの配置と管理情報を持つ
|
||||
- DomainのFQDNと配置先インスタンスを分離する
|
||||
- 参加トークンと承認済みインスタンスidentityを使う
|
||||
- 署名・単調sequence付きmanifestを受信側で原子的に適用する
|
||||
|
||||
設定配信は記事の複製・バックアップ・HAではない。Domain間の任意の権限同期も別契約。
|
||||
|
||||
---
|
||||
|
||||
## 20 運用上の制約と拡張順序
|
||||
|
||||
- 現行の基本はSQLiteとローカル保存、単一writer運用
|
||||
- 複数インスタンスを配置しても共有writerのHAにはならない
|
||||
- DR初版は停止snapshot、検証付き復元、外部fenceを前提とする手動昇格
|
||||
- 次段階は局所取得・索引改善、認可の一貫性、lease、外部保存・HAの順に境界を固める
|
||||
|
||||
RPO・RTO、無停止更新、無損失切替は、復旧訓練と運用条件なしに保証しない。
|
||||
|
||||
---
|
||||
|
||||
## 補足A 内部コンポーネント
|
||||
|
||||
| 部品 | 役割 |
|
||||
| --- | --- |
|
||||
| Grammaratur | 文書形式変換・情報保全 |
|
||||
| Geduldh | 不変Documentの保存と取得 |
|
||||
| Mestionora | 検索と索引 |
|
||||
| Schutzaria | 権限・公開ポリシー評価 |
|
||||
| Dregarnuhr | ジョブ実行制御 |
|
||||
| Ordoschnellic | 通知配送 |
|
||||
| Kunstzeal | Projection選択と描画provider |
|
||||
| Seheweit | リソース収集と観測 |
|
||||
|
||||
---
|
||||
|
||||
## 補足B 説明時に区別する実装状態
|
||||
|
||||
| 初期実装あり | 設計・後続実装 |
|
||||
| --- | --- |
|
||||
| City Map、URL境界、複数参照 | 全自動整理の整合性と大規模化 |
|
||||
| エディタの下書き・CAS・履歴 | 共有presence・リアルタイム共同編集 |
|
||||
| ビルトイン拡張・ホスト型エディタ | 任意プラグインの隔離実行 |
|
||||
| 匿名表示・公開ルール | 承認フロー全体・Macaroon共有 |
|
||||
| ローカル保存・停止snapshot | S3等の外部保存・自動HA |
|
||||
|
||||
---
|
||||
|
||||
## 補足C 設計資料
|
||||
|
||||
- [設計思想と責務の分離](/lab/pageswiki-dev/principles)
|
||||
- [アドレス・保存・アセット](/lab/pageswiki-dev/address-storage)
|
||||
- [Knowledge City](/lab/pageswiki-dev/knowledge-city)
|
||||
- [認証・権限と公開](/lab/pageswiki-dev/auth-permissions)
|
||||
- [イベント・リソース監視](/lab/pageswiki-dev/scheduler-resources)
|
||||
- [運用・外部保存・HAとDR](/lab/pageswiki-dev/operations)
|
||||
|
||||
技術詳細と実装残件の索引:`docs/design/ja/index.md`
|
||||
@@ -7,11 +7,21 @@ require (
|
||||
github.com/go-ldap/ldap/v3 v3.4.8
|
||||
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.13.0
|
||||
github.com/microcosm-cc/bluemonday v1.0.27
|
||||
golang.org/x/text v0.22.0
|
||||
golang.org/x/text v0.41.0
|
||||
modernc.org/sqlite v1.32.0
|
||||
)
|
||||
|
||||
require (
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.9.3
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.3 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/SherClockHolmes/webpush-go v1.4.0
|
||||
@@ -30,9 +40,9 @@ require (
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/teambition/rrule-go v1.8.2
|
||||
golang.org/x/crypto v0.33.0
|
||||
golang.org/x/crypto v0.37.0
|
||||
golang.org/x/net v0.35.0
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
golang.org/x/sys v0.32.0
|
||||
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
@@ -23,6 +25,8 @@ github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoM
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ=
|
||||
github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk=
|
||||
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
|
||||
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df h1:Mwihr/o+v4L5h56rwHLOE20+hh7Okhwno5BHz3zDuao=
|
||||
@@ -41,6 +45,14 @@ github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/C
|
||||
github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao=
|
||||
github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
||||
@@ -70,11 +82,14 @@ github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NF
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/teambition/rrule-go v1.8.2 h1:lIjpjvWTj9fFUZCmuoVDrKVOtdiyzbzc93qTmRVe/J8=
|
||||
github.com/teambition/rrule-go v1.8.2/go.mod h1:Ieq5AbrKGciP1V//Wq8ktsTXwSwJHDD5mD/wLBGl3p4=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
@@ -88,14 +103,15 @@ golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDf
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
|
||||
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
@@ -116,8 +132,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
||||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
@@ -130,8 +146,8 @@ golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
@@ -151,15 +167,16 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg=
|
||||
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
|
||||
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package calendar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"pageswiki/internal/db"
|
||||
)
|
||||
|
||||
// NewPostgreSQL initializes disposable indexes, not canonical calendar data.
|
||||
// All writers sharing this DB must share Root and its working flock semantics.
|
||||
// Separate replicas with independent filesystems are not a supported HA mode.
|
||||
func NewPostgreSQL(ctx context.Context, root string, database *sql.DB) (*Repository, error) {
|
||||
if root == "" || database == nil {
|
||||
return nil, errors.New("calendar storage unavailable")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
err := db.ApplyPostgreSQLMigrations(ctx, database, "calendar-cache", []db.PostgreSQLMigration{{Version: 1, Name: "rebuildable monthly calendar indexes", Statements: []string{
|
||||
`CREATE TABLE calendar_index_state(domain TEXT COLLATE "C" NOT NULL,calendar TEXT COLLATE "C" NOT NULL,version TEXT NOT NULL,PRIMARY KEY(domain,calendar))`,
|
||||
`CREATE TABLE calendar_month_cache(domain TEXT COLLATE "C" NOT NULL,calendar TEXT COLLATE "C" NOT NULL,month TEXT COLLATE "C" NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(domain,calendar,month))`,
|
||||
`CREATE TABLE calendar_event_cache(domain TEXT COLLATE "C" NOT NULL,calendar TEXT COLLATE "C" NOT NULL,uid TEXT COLLATE "C" NOT NULL,month TEXT COLLATE "C" NOT NULL,start BIGINT NOT NULL,"end" BIGINT NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid))`,
|
||||
`CREATE INDEX calendar_event_range ON calendar_event_cache(domain,calendar,start,"end")`,
|
||||
}, Assertions: []string{
|
||||
`SELECT domain,calendar,version FROM calendar_index_state WHERE 1=0`,
|
||||
`SELECT domain,calendar,month,hash FROM calendar_month_cache WHERE 1=0`,
|
||||
`SELECT domain,calendar,uid,month,start,"end",etag,data FROM calendar_event_cache WHERE 1=0`,
|
||||
}}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Repository{Root: root, DB: database, postgres: true}, nil
|
||||
}
|
||||
|
||||
// Compose source-owned SQL; never translate arbitrary SQL at runtime.
|
||||
func (r *Repository) p(n int) string {
|
||||
if r.postgres {
|
||||
return fmt.Sprintf("$%d", n)
|
||||
}
|
||||
return "?"
|
||||
}
|
||||
|
||||
func (r *Repository) failure(err error) error {
|
||||
if !r.postgres || err == nil {
|
||||
return err
|
||||
}
|
||||
for _, known := range []error{ErrForbidden, ErrConflict, ErrPreconditionRequired, ErrMissing, ErrLimit, ErrInvalid, ErrNameTaken, sql.ErrNoRows, context.Canceled, context.DeadlineExceeded} {
|
||||
if errors.Is(err, known) {
|
||||
return known
|
||||
}
|
||||
}
|
||||
var safe *db.PostgreSQLError
|
||||
if errors.As(err, &safe) {
|
||||
return safe
|
||||
}
|
||||
var pg *pgconn.PgError
|
||||
if errors.As(err, &pg) {
|
||||
return &db.PostgreSQLError{Operation: "calendar cache", SQLState: pg.Code}
|
||||
}
|
||||
// Encoding/Scan errors can contain event contents too.
|
||||
return errors.New("calendar operation failed")
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func DAVFilename(c Calendar, uid string) string {
|
||||
@@ -36,7 +38,7 @@ func DAVUID(c Calendar, name string) (string, error) {
|
||||
}
|
||||
}
|
||||
b, err := base64.RawURLEncoding.DecodeString(strings.TrimSuffix(name, ".ics"))
|
||||
if err != nil || len(b) == 0 || len(b) > 512 {
|
||||
if err != nil || len(b) == 0 || len(b) > 512 || !utf8.Valid(b) || strings.IndexFunc(string(b), unicode.IsControl) >= 0 {
|
||||
return "", ErrMissing
|
||||
}
|
||||
return string(b), nil
|
||||
@@ -44,7 +46,8 @@ func DAVUID(c Calendar, name string) (string, error) {
|
||||
|
||||
// DAVSnapshot is complete or fails; a truncated listing can cause client deletes.
|
||||
// The metadata lock keeps href mappings and event generations in one snapshot.
|
||||
func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string, withData bool) (Calendar, []Event, error) {
|
||||
func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string, withData bool) (result Calendar, itemsResult []Event, resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
c, _, unlock, err := r.locked(ctx, domain, id, actor)
|
||||
if err != nil {
|
||||
return c, nil, err
|
||||
@@ -54,7 +57,7 @@ func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string,
|
||||
if withData {
|
||||
cols = "uid,etag,data"
|
||||
}
|
||||
rows, err := r.DB.QueryContext(ctx, `SELECT `+cols+` FROM calendar_event_cache WHERE domain=? AND calendar=? ORDER BY uid LIMIT 10001`, domain, id)
|
||||
rows, err := r.DB.QueryContext(ctx, `SELECT `+cols+` FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` ORDER BY uid LIMIT 10001`, domain, id)
|
||||
if err != nil {
|
||||
return c, nil, err
|
||||
}
|
||||
@@ -77,7 +80,8 @@ func (r *Repository) DAVSnapshot(ctx context.Context, domain, id, actor string,
|
||||
|
||||
// ChangeDAV reserves resource identities in the same manifest commit as the
|
||||
// monthly snapshots. Existing resources still require an exact strong ETag.
|
||||
func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, match string, item *Event, authorize func() error) (Event, bool, error) {
|
||||
func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, match string, item *Event, authorize func() error) (eventResult Event, created bool, resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
if !ValidDAVFilename(name) {
|
||||
return Event{}, false, ErrInvalid
|
||||
}
|
||||
@@ -94,7 +98,7 @@ func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, mat
|
||||
uid, _ := DAVUID(c, name)
|
||||
var exists bool
|
||||
if uid != "" {
|
||||
if err = r.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?)`, domain, id, uid).Scan(&exists); err != nil {
|
||||
if err = r.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3)+`)`, domain, id, uid).Scan(&exists); err != nil {
|
||||
return Event{}, false, err
|
||||
}
|
||||
}
|
||||
@@ -114,7 +118,7 @@ func (r *Repository) ChangeDAV(ctx context.Context, domain, id, actor, name, mat
|
||||
}
|
||||
uid = item.UID
|
||||
var tag string
|
||||
err = r.DB.QueryRowContext(ctx, `SELECT etag FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&tag)
|
||||
err = r.DB.QueryRowContext(ctx, `SELECT etag FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&tag)
|
||||
if err == nil {
|
||||
return Event{}, false, ErrConflict
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package calendar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -9,6 +10,22 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestDAVUIDRejectsBinaryFallback(t *testing.T) {
|
||||
for _, raw := range []string{"\xff\xfe", "uid\x00value", "uid\nvalue"} {
|
||||
name := base64.RawURLEncoding.EncodeToString([]byte(raw)) + ".ics"
|
||||
if _, err := DAVUID(Calendar{}, name); !errors.Is(err, ErrMissing) {
|
||||
t.Fatalf("binary UID accepted: %v", err)
|
||||
}
|
||||
}
|
||||
name := "client.ics"
|
||||
if _, err := DAVUID(Calendar{}, name); !errors.Is(err, ErrMissing) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if uid, err := DAVUID(Calendar{DAVNames: map[string]string{"日本語@example.invalid": name}}, name); err != nil || uid != "日本語@example.invalid" {
|
||||
t.Fatal(uid, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCalendarDAVIdentityAtomicAndRebuild(t *testing.T) {
|
||||
r, domain, actor, c := fixture(t)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -51,6 +51,7 @@ type Repository struct {
|
||||
Root string
|
||||
DB *sql.DB
|
||||
PublicAllowed func(string) bool
|
||||
postgres bool
|
||||
}
|
||||
|
||||
func (r *Repository) canRead(domain string, c Calendar, actor string) bool {
|
||||
@@ -66,8 +67,8 @@ func New(root string, db *sql.DB) (*Repository, error) {
|
||||
}
|
||||
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS calendar_index_state(domain TEXT NOT NULL,calendar TEXT NOT NULL,version TEXT NOT NULL,PRIMARY KEY(domain,calendar));
|
||||
CREATE TABLE IF NOT EXISTS calendar_month_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,month TEXT NOT NULL,hash TEXT NOT NULL,PRIMARY KEY(domain,calendar,month));
|
||||
CREATE TABLE IF NOT EXISTS calendar_event_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,uid TEXT NOT NULL,month TEXT NOT NULL,start INTEGER NOT NULL,end INTEGER NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid));
|
||||
CREATE INDEX IF NOT EXISTS calendar_event_range ON calendar_event_cache(domain,calendar,start,end);`)
|
||||
CREATE TABLE IF NOT EXISTS calendar_event_cache(domain TEXT NOT NULL,calendar TEXT NOT NULL,uid TEXT NOT NULL,month TEXT NOT NULL,start INTEGER NOT NULL,"end" INTEGER NOT NULL,etag TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(domain,calendar,uid));
|
||||
CREATE INDEX IF NOT EXISTS calendar_event_range ON calendar_event_cache(domain,calendar,start,"end");`)
|
||||
return &Repository{Root: root, DB: db}, err
|
||||
}
|
||||
func validID(s string) bool { u, err := uuid.Parse(s); return err == nil && u.String() == s }
|
||||
@@ -347,7 +348,10 @@ func (r *Repository) Settings(ctx context.Context, domain, id, actor, version, n
|
||||
// with event/source writes. Cache rows are disposable, but deleting them
|
||||
// before the atomic directory rename means a failed rename can safely rebuild
|
||||
// them from the still-visible canonical files on the next access.
|
||||
func (r *Repository) Delete(ctx context.Context, domain, id, actor, version string) error {
|
||||
func (r *Repository) Delete(ctx context.Context, domain, id, actor, version string) (resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
dir, err := r.dir(domain, id)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -382,7 +386,7 @@ func (r *Repository) Delete(ctx context.Context, domain, id, actor, version stri
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for _, table := range []string{"calendar_event_cache", "calendar_month_cache", "calendar_index_state"} {
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE domain=? AND calendar=?`, domain, id); err != nil {
|
||||
if _, err = tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -413,9 +417,12 @@ func syncDirectory(path string) error {
|
||||
|
||||
// refresh reconciles only changed monthly generations. A crash after manifest
|
||||
// commit but before index commit repairs itself on the next request.
|
||||
func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir string) error {
|
||||
func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir string) (resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
var version string
|
||||
if err := r.DB.QueryRowContext(ctx, `SELECT version FROM calendar_index_state WHERE domain=? AND calendar=?`, domain, c.ID).Scan(&version); err == nil && version == c.Version {
|
||||
if err := r.DB.QueryRowContext(ctx, `SELECT version FROM calendar_index_state WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, c.ID).Scan(&version); err == nil && version == c.Version {
|
||||
return nil
|
||||
} else if err != nil && err != sql.ErrNoRows {
|
||||
return err
|
||||
@@ -425,7 +432,7 @@ func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir
|
||||
return e
|
||||
}
|
||||
defer tx.Rollback()
|
||||
rows, e := tx.QueryContext(ctx, `SELECT month,hash FROM calendar_month_cache WHERE domain=? AND calendar=?`, domain, c.ID)
|
||||
rows, e := tx.QueryContext(ctx, `SELECT month,hash FROM calendar_month_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2), domain, c.ID)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
@@ -445,10 +452,10 @@ func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir
|
||||
}
|
||||
for m, h := range known {
|
||||
if c.Months[m] != h {
|
||||
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_event_cache WHERE domain=? AND calendar=? AND month=?`, domain, c.ID, m); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3), domain, c.ID, m); e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_month_cache WHERE domain=? AND calendar=? AND month=?`, domain, c.ID, m); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `DELETE FROM calendar_month_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3), domain, c.ID, m); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
@@ -480,15 +487,15 @@ func (r *Repository) refresh(ctx context.Context, domain string, c Calendar, dir
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_event_cache(domain,calendar,uid,month,start,end,etag,data) VALUES(?,?,?,?,?,?,?,?)`, domain, c.ID, event.UID, m, event.Start.Unix(), event.End.Unix(), event.ETag, event.Data); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_event_cache(domain,calendar,uid,month,start,"end",etag,data) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`,`+r.p(5)+`,`+r.p(6)+`,`+r.p(7)+`,`+r.p(8)+`)`, domain, c.ID, event.UID, m, event.Start.Unix(), event.End.Unix(), event.ETag, event.Data); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_month_cache(domain,calendar,month,hash) VALUES(?,?,?,?)`, domain, c.ID, m, h); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_month_cache(domain,calendar,month,hash) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`,`+r.p(4)+`)`, domain, c.ID, m, h); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_index_state(domain,calendar,version) VALUES(?,?,?) ON CONFLICT(domain,calendar) DO UPDATE SET version=excluded.version`, domain, c.ID, c.Version); e != nil {
|
||||
if _, e = tx.ExecContext(ctx, `INSERT INTO calendar_index_state(domain,calendar,version) VALUES(`+r.p(1)+`,`+r.p(2)+`,`+r.p(3)+`) ON CONFLICT(domain,calendar) DO UPDATE SET version=excluded.version`, domain, c.ID, c.Version); e != nil {
|
||||
return e
|
||||
}
|
||||
return tx.Commit()
|
||||
@@ -540,7 +547,8 @@ func (r *Repository) query(ctx context.Context, domain, id, actor string, start,
|
||||
func (r *Repository) Upcoming(ctx context.Context, domain, id, actor string, start, end time.Time) ([]Event, error) {
|
||||
return r.queryLimit(ctx, domain, id, actor, start, end, true, 20)
|
||||
}
|
||||
func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, start, end time.Time, withData bool, limit int) ([]Event, error) {
|
||||
func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, start, end time.Time, withData bool, limit int) (result []Event, resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
if !end.After(start) || end.Sub(start) > 370*24*time.Hour {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
@@ -553,7 +561,7 @@ func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, s
|
||||
if withData {
|
||||
columns = "data"
|
||||
}
|
||||
rows, e := r.DB.QueryContext(ctx, `SELECT `+columns+` FROM calendar_event_cache WHERE domain=? AND calendar=? AND start<? AND (end>? OR (start=end AND start>=?)) ORDER BY start,uid LIMIT ?`, domain, id, end.Unix(), start.Unix(), start.Unix(), limit)
|
||||
rows, e := r.DB.QueryContext(ctx, `SELECT `+columns+` FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND start<`+r.p(3)+` AND ("end">`+r.p(4)+` OR (start="end" AND start>=`+r.p(5)+`)) ORDER BY start,uid LIMIT `+r.p(6), domain, id, end.Unix(), start.Unix(), start.Unix(), limit)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
@@ -583,14 +591,15 @@ func (r *Repository) queryLimit(ctx context.Context, domain, id, actor string, s
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
func (r *Repository) Event(ctx context.Context, domain, id, actor, uid string) (Event, error) {
|
||||
func (r *Repository) Event(ctx context.Context, domain, id, actor, uid string) (result Event, resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
_, _, unlock, e := r.locked(ctx, domain, id, actor)
|
||||
if e != nil {
|
||||
return Event{}, e
|
||||
}
|
||||
defer unlock()
|
||||
var data string
|
||||
e = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&data)
|
||||
e = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&data)
|
||||
if e == sql.ErrNoRows {
|
||||
e = ErrMissing
|
||||
}
|
||||
@@ -611,13 +620,14 @@ func (r *Repository) Change(ctx context.Context, domain, id, actor, uid, match s
|
||||
return r.changeLocked(ctx, domain, actor, uid, match, item, c, dir)
|
||||
}
|
||||
|
||||
func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match string, item *Event, c Calendar, dir string) (Event, error) {
|
||||
func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match string, item *Event, c Calendar, dir string) (result Event, resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
id := c.ID
|
||||
if !c.CanWrite(actor) {
|
||||
return Event{}, ErrForbidden
|
||||
}
|
||||
var oldData, oldMonth, oldTag string
|
||||
e := r.DB.QueryRowContext(ctx, `SELECT data,month,etag FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&oldData, &oldMonth, &oldTag)
|
||||
e := r.DB.QueryRowContext(ctx, `SELECT data,month,etag FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&oldData, &oldMonth, &oldTag)
|
||||
exists := e == nil
|
||||
if e != nil && e != sql.ErrNoRows {
|
||||
return Event{}, e
|
||||
@@ -650,7 +660,7 @@ func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match
|
||||
months[newMonth] = true
|
||||
}
|
||||
for month := range months {
|
||||
rows, e := r.DB.QueryContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=? AND calendar=? AND month=? AND uid<>? ORDER BY uid`, domain, id, month, uid)
|
||||
rows, e := r.DB.QueryContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND month=`+r.p(3)+` AND uid<>`+r.p(4)+` ORDER BY uid`, domain, id, month, uid)
|
||||
if e != nil {
|
||||
return Event{}, e
|
||||
}
|
||||
@@ -717,7 +727,7 @@ func (r *Repository) changeLocked(ctx context.Context, domain, actor, uid, match
|
||||
_ = os.Remove(file)
|
||||
}
|
||||
}
|
||||
// The committed files, not SQLite, determine success. A subsequent read
|
||||
// The committed files, not the database cache, determine success. A subsequent read
|
||||
// reconciles the cache; retries with the old ETag correctly get 412.
|
||||
return next, nil
|
||||
}
|
||||
@@ -25,14 +25,15 @@ func (r *Repository) ReadPersonalLocalIndex(ctx context.Context, domain, id, act
|
||||
// TaskBlock gets a current event, or creates it if absent and a draft is supplied.
|
||||
// Retries NEVER overwrite an event moved/edited in the calendar. Metadata policy
|
||||
// is checked under the same lock as snapshot access and the eventual commit.
|
||||
func (r *Repository) TaskBlock(ctx context.Context, domain, id, actor, uid string, draft *Event) (Calendar, Event, error) {
|
||||
func (r *Repository) TaskBlock(ctx context.Context, domain, id, actor, uid string, draft *Event) (calendarResult Calendar, eventResult Event, resultErr error) {
|
||||
defer func() { resultErr = r.failure(resultErr) }()
|
||||
c, dir, unlock, err := r.lockedWithGuard(ctx, domain, id, actor, func(c Calendar) bool { return c.PersonalLocal(actor) })
|
||||
if err != nil {
|
||||
return Calendar{}, Event{}, err
|
||||
}
|
||||
defer unlock()
|
||||
var data string
|
||||
err = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=? AND calendar=? AND uid=?`, domain, id, uid).Scan(&data)
|
||||
err = r.DB.QueryRowContext(ctx, `SELECT data FROM calendar_event_cache WHERE domain=`+r.p(1)+` AND calendar=`+r.p(2)+` AND uid=`+r.p(3), domain, id, uid).Scan(&data)
|
||||
if err == nil {
|
||||
event, e := Parse(data)
|
||||
return c, event, e
|
||||
|
||||
@@ -28,6 +28,13 @@ type MigrationInspection struct {
|
||||
// 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) {
|
||||
return InspectSQLiteMigrationsWithOptional(ctx, database, plans, nil)
|
||||
}
|
||||
|
||||
// Optional components are omitted only when neither a migration record nor any
|
||||
// owned schema object exists. Detection and inspection share one read snapshot;
|
||||
// partial installation or a missing table after installation is never ignored.
|
||||
func InspectSQLiteMigrationsWithOptional(ctx context.Context, database *sql.DB, plans map[string][]SQLMigration, optional map[string][]string) ([]MigrationInspection, error) {
|
||||
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -80,6 +87,19 @@ func InspectSQLiteMigrations(ctx context.Context, database *sql.DB, plans map[st
|
||||
return nil, err
|
||||
}
|
||||
steps, known := plans[name]
|
||||
if objects, opt := optional[name]; opt && len(history[name]) == 0 && len(objects) > 0 {
|
||||
present := false
|
||||
for _, object := range objects {
|
||||
var exists bool
|
||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE name=?)`, object).Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
present = present || exists
|
||||
}
|
||||
if !present {
|
||||
continue
|
||||
}
|
||||
}
|
||||
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) {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/go-sql-driver/mysql"
|
||||
)
|
||||
|
||||
// MySQL is currently a component-pilot backend, not a Pages serving backend.
|
||||
// Credentials are instance configuration and must never be logged.
|
||||
type MySQLOptions struct {
|
||||
DSN string
|
||||
AllowInsecure bool
|
||||
}
|
||||
|
||||
func OpenMySQL(ctx context.Context, options MySQLOptions) (*sql.DB, error) {
|
||||
c, e := mysql.ParseDSN(options.DSN)
|
||||
if e != nil || options.DSN == "" {
|
||||
return nil, errors.New("invalid MySQL configuration")
|
||||
}
|
||||
if c.DBName == "" || c.Net != "tcp" || c.MultiStatements || c.AllowAllFiles || c.AllowCleartextPasswords || c.AllowFallbackToPlaintext || len(c.Params) != 0 {
|
||||
return nil, errors.New("unsupported MySQL configuration")
|
||||
}
|
||||
if !options.AllowInsecure && c.TLSConfig != "true" {
|
||||
return nil, errors.New("MySQL requires verified TLS (tls=true)")
|
||||
}
|
||||
c.Timeout = 10 * time.Second
|
||||
c.ReadTimeout = 30 * time.Second
|
||||
c.WriteTimeout = 30 * time.Second
|
||||
c.Collation = "utf8mb4_bin"
|
||||
// Set on EVERY new pooled connection. Relying on a server's permissive
|
||||
// sql_mode can silently truncate identifiers or coerce invalid values.
|
||||
// User-supplied session variables remain rejected above.
|
||||
c.Params = map[string]string{"sql_mode": "'STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"}
|
||||
c.Logger = log.New(io.Discard, "", 0)
|
||||
connector, e := mysql.NewConnector(c)
|
||||
if e != nil {
|
||||
return nil, errors.New("invalid MySQL connector configuration")
|
||||
}
|
||||
database := sql.OpenDB(connector)
|
||||
database.SetMaxOpenConns(8)
|
||||
database.SetMaxIdleConns(2)
|
||||
database.SetConnMaxLifetime(10 * time.Minute)
|
||||
ping, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
defer cancel()
|
||||
if e = database.PingContext(ping); e != nil {
|
||||
database.Close()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, errors.New("MySQL connection failed")
|
||||
}
|
||||
return database, nil
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"database/sql/driver"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MySQLOperation is owned SQL, never user input. Check must return exactly one
|
||||
// boolean describing the operation's postcondition. ReplaySafe permits explicit
|
||||
// resume when Check is false; never mark non-idempotent data updates replay-safe.
|
||||
type MySQLOperation struct {
|
||||
SQL, Check string
|
||||
ReplaySafe bool
|
||||
}
|
||||
type MySQLMigration struct {
|
||||
Version int
|
||||
Name string
|
||||
Operations []MySQLOperation
|
||||
Assertions []string
|
||||
}
|
||||
type MySQLMigrationStatus struct {
|
||||
Applied int `json:"applied"`
|
||||
Pending int `json:"pending"`
|
||||
Dirty bool `json:"dirty"`
|
||||
NextOperation int `json:"next_operation"`
|
||||
DirtyComponent string `json:"dirty_component,omitempty"`
|
||||
}
|
||||
|
||||
var ErrMySQLMigrationDirty = errors.New("MySQL migration interrupted; inspect and explicitly resume")
|
||||
var ErrMySQLMigrationMismatch = errors.New("MySQL migration history or schema mismatch")
|
||||
|
||||
func mysqlMigrationHash(m MySQLMigration) string {
|
||||
b, _ := json.Marshal(m)
|
||||
h := sha256.Sum256(b)
|
||||
return hex.EncodeToString(h[:])
|
||||
}
|
||||
func validateMySQLPlan(component string, steps []MySQLMigration) error {
|
||||
if !regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`).MatchString(component) {
|
||||
return errors.New("invalid MySQL migration component")
|
||||
}
|
||||
for i, s := range steps {
|
||||
if s.Version != i+1 || s.Name == "" || len(s.Name) > 128 || len(s.Operations) == 0 || len(s.Assertions) == 0 {
|
||||
return errors.New("invalid MySQL migration plan")
|
||||
}
|
||||
for _, op := range s.Operations {
|
||||
if strings.TrimSpace(op.SQL) == "" || strings.TrimSpace(op.Check) == "" {
|
||||
return errors.New("missing MySQL operation postcondition")
|
||||
}
|
||||
}
|
||||
for _, assertion := range s.Assertions {
|
||||
if strings.TrimSpace(assertion) == "" {
|
||||
return errors.New("missing MySQL schema assertion")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Every operation, including GET_LOCK/RELEASE_LOCK, uses this one connection.
|
||||
// MySQL DDL commits implicitly: a transaction cannot replace this lock/journal.
|
||||
func mysqlMigrationConnection(ctx context.Context, database *sql.DB) (*sql.Conn, func(), error) {
|
||||
c, e := database.Conn(ctx)
|
||||
if e != nil {
|
||||
return nil, nil, errors.New("MySQL migration connection failed")
|
||||
}
|
||||
var name string
|
||||
if e = c.QueryRowContext(ctx, `SELECT DATABASE()`).Scan(&name); e != nil || name == "" {
|
||||
c.Close()
|
||||
return nil, nil, errors.New("MySQL migration database required")
|
||||
}
|
||||
h := sha256.Sum256([]byte(name))
|
||||
key := "pages:migration:" + hex.EncodeToString(h[:20])
|
||||
var locked sql.NullInt64
|
||||
if e = c.QueryRowContext(ctx, `SELECT GET_LOCK(?,10)`, key).Scan(&locked); e != nil || !locked.Valid || locked.Int64 != 1 {
|
||||
// An interrupted lock request may have acquired the session lock.
|
||||
_ = c.Raw(func(any) error { return driver.ErrBadConn })
|
||||
c.Close()
|
||||
return nil, nil, errors.New("MySQL migration lock unavailable")
|
||||
}
|
||||
release := func() {
|
||||
releaseCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
var released sql.NullInt64
|
||||
if e := c.QueryRowContext(releaseCtx, `SELECT RELEASE_LOCK(?)`, key).Scan(&released); e != nil || !released.Valid || released.Int64 != 1 {
|
||||
_ = c.Raw(func(any) error { return driver.ErrBadConn })
|
||||
}
|
||||
c.Close()
|
||||
}
|
||||
return c, release, nil
|
||||
}
|
||||
|
||||
func mysqlCheck(ctx context.Context, c *sql.Conn, q string) (bool, error) {
|
||||
rows, e := c.QueryContext(ctx, q)
|
||||
if e != nil {
|
||||
return false, errors.New("MySQL schema check failed")
|
||||
}
|
||||
defer rows.Close()
|
||||
var yes bool
|
||||
if !rows.Next() {
|
||||
return false, errors.New("MySQL schema check returned no result")
|
||||
}
|
||||
if rows.Scan(&yes) != nil || rows.Next() || rows.Err() != nil {
|
||||
return false, errors.New("invalid MySQL schema check result")
|
||||
}
|
||||
return yes, nil
|
||||
}
|
||||
|
||||
func inspectMySQLLocked(ctx context.Context, c *sql.Conn, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) {
|
||||
status := MySQLMigrationStatus{Pending: len(steps)}
|
||||
var exists int
|
||||
if e := c.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations'`).Scan(&exists); e != nil {
|
||||
return status, errors.New("MySQL migration inspection failed")
|
||||
}
|
||||
if exists == 0 {
|
||||
return status, nil
|
||||
}
|
||||
// The journal itself must remain durable and uniquely keyed. Do not repair
|
||||
// a damaged journal automatically, or trust history read from a view.
|
||||
valid, e := mysqlCheck(ctx, c, `SELECT
|
||||
(SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND engine='InnoDB' AND table_type='BASE TABLE')=1
|
||||
AND COALESCE((SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND index_name='PRIMARY'),'')='component,version'
|
||||
AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND is_nullable='NO' AND column_name IN ('component','version','name','checksum','state','next_operation','updated_ms'))=7`)
|
||||
if e != nil {
|
||||
return status, e
|
||||
}
|
||||
if !valid {
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
rows, e := c.QueryContext(ctx, `SELECT version,name,checksum,state,next_operation FROM schema_mysql_migrations WHERE component=? ORDER BY version`, component)
|
||||
if e != nil {
|
||||
return status, errors.New("MySQL migration history unavailable")
|
||||
}
|
||||
seen := 0
|
||||
for rows.Next() {
|
||||
var version, next int
|
||||
var name, hash, state string
|
||||
if rows.Scan(&version, &name, &hash, &state, &next) != nil {
|
||||
rows.Close()
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
if version != seen+1 || version > len(steps) || status.Dirty {
|
||||
rows.Close()
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
s := steps[version-1]
|
||||
if name != s.Name || hash != mysqlMigrationHash(s) || next < 0 || next > len(s.Operations) {
|
||||
rows.Close()
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
switch state {
|
||||
case "applied":
|
||||
if next != len(s.Operations) {
|
||||
rows.Close()
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
status.Applied++
|
||||
case "running":
|
||||
status.Dirty = true
|
||||
status.DirtyComponent = component
|
||||
status.NextOperation = next
|
||||
default:
|
||||
rows.Close()
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
seen++
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return status, errors.New("MySQL migration history read failed")
|
||||
}
|
||||
status.Pending = len(steps) - status.Applied
|
||||
// Later migrations may intentionally replace an older schema. Validate only
|
||||
// the latest clean contract, not intermediate versions of a dirty migration.
|
||||
if !status.Dirty && status.Applied > 0 {
|
||||
for _, q := range steps[status.Applied-1].Assertions {
|
||||
ok, e := mysqlCheck(ctx, c, q)
|
||||
if e != nil {
|
||||
return status, e
|
||||
}
|
||||
if !ok {
|
||||
return status, ErrMySQLMigrationMismatch
|
||||
}
|
||||
}
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// Inspect is read-only: it never creates the ledger or adopts an existing table.
|
||||
func InspectMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) {
|
||||
if e := validateMySQLPlan(component, steps); e != nil {
|
||||
return MySQLMigrationStatus{}, e
|
||||
}
|
||||
c, release, e := mysqlMigrationConnection(ctx, database)
|
||||
if e != nil {
|
||||
return MySQLMigrationStatus{}, e
|
||||
}
|
||||
defer release()
|
||||
return inspectMySQLLocked(ctx, c, component, steps)
|
||||
}
|
||||
|
||||
func ApplyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error {
|
||||
return applyMySQLMigrations(ctx, database, component, steps, false)
|
||||
}
|
||||
|
||||
// Resume is explicitly separate from normal startup. It does not blindly repeat
|
||||
// a statement: the postcondition must prove success, or ReplaySafe must be set.
|
||||
func ResumeMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error {
|
||||
return applyMySQLMigrations(ctx, database, component, steps, true)
|
||||
}
|
||||
func applyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration, resume bool) error {
|
||||
if e := validateMySQLPlan(component, steps); e != nil {
|
||||
return e
|
||||
}
|
||||
c, release, e := mysqlMigrationConnection(ctx, database)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
defer release()
|
||||
status, e := inspectMySQLLocked(ctx, c, component, steps)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if status.Dirty && !resume {
|
||||
return ErrMySQLMigrationDirty
|
||||
}
|
||||
_, e = c.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_mysql_migrations(component VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,version BIGINT NOT NULL,name VARCHAR(128) NOT NULL,checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,state VARCHAR(16) NOT NULL,next_operation BIGINT NOT NULL,updated_ms BIGINT NOT NULL,PRIMARY KEY(component,version)) ENGINE=InnoDB`)
|
||||
if e != nil {
|
||||
return errors.New("MySQL migration ledger creation failed")
|
||||
}
|
||||
for _, s := range steps[status.Applied:] {
|
||||
resuming := status.Dirty
|
||||
cursor := 0
|
||||
if resuming {
|
||||
cursor = status.NextOperation
|
||||
} else {
|
||||
// Do not implicitly adopt an already-existing schema with no history.
|
||||
for _, op := range s.Operations {
|
||||
ok, e := mysqlCheck(ctx, c, op.Check)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if ok {
|
||||
return ErrMySQLMigrationMismatch
|
||||
}
|
||||
}
|
||||
_, e = c.ExecContext(ctx, `INSERT INTO schema_mysql_migrations(component,version,name,checksum,state,next_operation,updated_ms) VALUES(?,?,?,?,'running',0,?)`, component, s.Version, s.Name, mysqlMigrationHash(s), time.Now().UnixMilli())
|
||||
if e != nil {
|
||||
return errors.New("MySQL migration journal failed")
|
||||
}
|
||||
}
|
||||
for i := cursor; i < len(s.Operations); i++ {
|
||||
op := s.Operations[i]
|
||||
ok, e := mysqlCheck(ctx, c, op.Check)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !ok {
|
||||
if resuming && i == cursor && !op.ReplaySafe {
|
||||
return ErrMySQLMigrationDirty
|
||||
}
|
||||
if _, e = c.ExecContext(ctx, op.SQL); e != nil {
|
||||
return fmt.Errorf("MySQL migration operation %d failed; journal retained", i+1)
|
||||
}
|
||||
ok, e = mysqlCheck(ctx, c, op.Check)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !ok {
|
||||
return ErrMySQLMigrationMismatch
|
||||
}
|
||||
}
|
||||
_, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET next_operation=?,updated_ms=? WHERE component=? AND version=?`, i+1, time.Now().UnixMilli(), component, s.Version)
|
||||
if e != nil {
|
||||
return errors.New("MySQL migration progress failed")
|
||||
}
|
||||
}
|
||||
for _, q := range s.Assertions {
|
||||
ok, e := mysqlCheck(ctx, c, q)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if !ok {
|
||||
return ErrMySQLMigrationMismatch
|
||||
}
|
||||
}
|
||||
_, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET state='applied',updated_ms=? WHERE component=? AND version=?`, time.Now().UnixMilli(), component, s.Version)
|
||||
if e != nil {
|
||||
return errors.New("MySQL migration completion failed")
|
||||
}
|
||||
status.Dirty = false
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestMySQLMigrationPlanValidation(t *testing.T) {
|
||||
valid := func() MySQLMigration {
|
||||
return MySQLMigration{Version: 1, Name: "initial", Operations: []MySQLOperation{{SQL: "CREATE TABLE example(id BIGINT)", Check: "SELECT 0", ReplaySafe: true}}, Assertions: []string{"SELECT 1"}}
|
||||
}
|
||||
if e := validateMySQLPlan("machine-learning", []MySQLMigration{valid()}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, component := range []string{"", "../schema", "has space", "MixedCase"} {
|
||||
if e := validateMySQLPlan(component, []MySQLMigration{valid()}); e == nil {
|
||||
t.Fatal("invalid component accepted", component)
|
||||
}
|
||||
}
|
||||
for _, mutate := range []func(*MySQLMigration){
|
||||
func(m *MySQLMigration) { m.Version = 2 },
|
||||
func(m *MySQLMigration) { m.Name = "" },
|
||||
func(m *MySQLMigration) { m.Operations = nil },
|
||||
func(m *MySQLMigration) { m.Operations[0].SQL = " " },
|
||||
func(m *MySQLMigration) { m.Operations[0].Check = " " },
|
||||
func(m *MySQLMigration) { m.Assertions = nil },
|
||||
func(m *MySQLMigration) { m.Assertions[0] = " " },
|
||||
} {
|
||||
m := valid()
|
||||
mutate(&m)
|
||||
if e := validateMySQLPlan("test", []MySQLMigration{m}); e == nil {
|
||||
t.Fatal("invalid plan accepted", m)
|
||||
}
|
||||
}
|
||||
before := valid()
|
||||
after := valid()
|
||||
after.Operations[0].ReplaySafe = false
|
||||
if mysqlMigrationHash(before) == mysqlMigrationHash(after) {
|
||||
t.Fatal("replay policy not covered by checksum")
|
||||
}
|
||||
if mysqlMigrationHash(before) != mysqlMigrationHash(valid()) {
|
||||
t.Fatal("unstable checksum")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMySQLRejectsUnsafeConfiguration(t *testing.T) {
|
||||
for _, dsn := range []string{"", "private-secret@bad", "u:private-secret@tcp(localhost:3306)/pages", "u:p@tcp(localhost:3306)/pages?tls=skip-verify", "u:p@tcp(localhost:3306)/pages?tls=preferred", "u:p@tcp(localhost:3306)/pages?tls=true&multiStatements=true", "u:p@tcp(localhost:3306)/pages?tls=true&allowAllFiles=true", "u:p@tcp(localhost:3306)/pages?tls=true&sql_mode=bad"} {
|
||||
connection, err := OpenMySQL(context.Background(), MySQLOptions{DSN: dsn})
|
||||
if connection != nil {
|
||||
connection.Close()
|
||||
t.Fatal("unexpected connection")
|
||||
}
|
||||
if err == nil || strings.Contains(err.Error(), "private-secret") {
|
||||
t.Fatalf("configuration not safely rejected: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
// PostgreSQLOptions is an instance-level secret-bearing configuration. Do not
|
||||
// log it. Application startup additionally requires a verified full-import
|
||||
// receipt; opening a connection alone does not authorize backend cutover.
|
||||
type PostgreSQLOptions struct {
|
||||
DSN string
|
||||
MaxOpenConns int
|
||||
MaxIdleConns int
|
||||
ConnectTimeout time.Duration
|
||||
// AllowInsecure permits plaintext or unverified TLS for isolated development
|
||||
// only. Production defaults require verified TLS and no plaintext fallback.
|
||||
AllowInsecure bool
|
||||
}
|
||||
|
||||
// PostgreSQLError deliberately excludes server messages, SQL, connection
|
||||
// strings and constraint details, all of which can contain credentials or data.
|
||||
// SQLState remains available for retry/conflict classification.
|
||||
type PostgreSQLError struct {
|
||||
Operation string
|
||||
SQLState string
|
||||
}
|
||||
|
||||
func (e *PostgreSQLError) Error() string {
|
||||
if e.SQLState != "" {
|
||||
return fmt.Sprintf("PostgreSQL %s failed (SQLSTATE %s)", e.Operation, e.SQLState)
|
||||
}
|
||||
return "PostgreSQL " + e.Operation + " failed"
|
||||
}
|
||||
|
||||
func postgresError(operation string, err error) error {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return context.Canceled
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
result := &PostgreSQLError{Operation: operation}
|
||||
if errors.As(err, &pgErr) {
|
||||
result.SQLState = pgErr.Code
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func OpenPostgreSQL(ctx context.Context, options PostgreSQLOptions) (*sql.DB, error) {
|
||||
if options.DSN == "" {
|
||||
return nil, fmt.Errorf("PostgreSQL DSN is required")
|
||||
}
|
||||
if options.MaxOpenConns < 0 || options.MaxIdleConns < 0 || options.ConnectTimeout < 0 {
|
||||
return nil, fmt.Errorf("invalid PostgreSQL pool or timeout configuration")
|
||||
}
|
||||
config, err := pgx.ParseConfig(options.DSN)
|
||||
if err != nil {
|
||||
return nil, postgresError("configuration", err)
|
||||
}
|
||||
if !options.AllowInsecure {
|
||||
if config.TLSConfig == nil || config.TLSConfig.InsecureSkipVerify {
|
||||
return nil, fmt.Errorf("PostgreSQL requires verified TLS; use sslmode=verify-full")
|
||||
}
|
||||
for _, fallback := range config.Fallbacks {
|
||||
if fallback.TLSConfig == nil || fallback.TLSConfig.InsecureSkipVerify {
|
||||
return nil, fmt.Errorf("PostgreSQL insecure connection fallback is not allowed")
|
||||
}
|
||||
}
|
||||
}
|
||||
timeout := options.ConnectTimeout
|
||||
if timeout == 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
config.ConnectTimeout = timeout
|
||||
config.RuntimeParams["application_name"] = "pageswiki"
|
||||
database := stdlib.OpenDB(*config)
|
||||
maxOpen := options.MaxOpenConns
|
||||
if maxOpen == 0 {
|
||||
maxOpen = 10
|
||||
}
|
||||
maxIdle := options.MaxIdleConns
|
||||
if maxIdle == 0 {
|
||||
maxIdle = 2
|
||||
}
|
||||
if maxIdle > maxOpen {
|
||||
maxIdle = maxOpen
|
||||
}
|
||||
database.SetMaxOpenConns(maxOpen)
|
||||
database.SetMaxIdleConns(maxIdle)
|
||||
database.SetConnMaxLifetime(30 * time.Minute)
|
||||
database.SetConnMaxIdleTime(5 * time.Minute)
|
||||
pingCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
if err := database.PingContext(pingCtx); err != nil {
|
||||
_ = database.Close()
|
||||
return nil, postgresError("connect", err)
|
||||
}
|
||||
return database, nil
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PostgreSQLMigration contains native PostgreSQL SQL ($1 parameters, BIGINT
|
||||
// timestamps). SQLite migration definitions must not be translated implicitly.
|
||||
// Definitions are append-only after release. Assertions return no rows on success.
|
||||
type PostgreSQLMigration struct {
|
||||
Version int
|
||||
Name string
|
||||
Statements []string
|
||||
Assertions []string `json:",omitempty"`
|
||||
}
|
||||
|
||||
func postgresMigrationChecksum(step PostgreSQLMigration) string {
|
||||
encoded, _ := json.Marshal(step)
|
||||
sum := sha256.Sum256(encoded)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// ApplyPostgreSQLMigrations uses one transaction-scoped advisory lock for the
|
||||
// migration namespace, including ledger creation. Component-specific locks
|
||||
// would race concurrent first creation of the shared ledger. READ COMMITTED
|
||||
// ensures a waiter sees the previous owner's committed migration history.
|
||||
// Callers must use the same search_path and lock convention for a database.
|
||||
func ApplyPostgreSQLMigrations(ctx context.Context, database *sql.DB, component string, steps []PostgreSQLMigration) error {
|
||||
if strings.TrimSpace(component) == "" {
|
||||
return fmt.Errorf("migration component is required")
|
||||
}
|
||||
for i, step := range steps {
|
||||
if step.Version != i+1 || strings.TrimSpace(step.Name) == "" || len(step.Statements)+len(step.Assertions) == 0 {
|
||||
return fmt.Errorf("invalid PostgreSQL migration sequence for %s", component)
|
||||
}
|
||||
}
|
||||
tx, err := database.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
||||
if err != nil {
|
||||
return postgresError("migration begin", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// Stable application-specific key, independent of Go hashes and versions.
|
||||
if _, err := tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1835624306)`); err != nil {
|
||||
return postgresError("migration lock", err)
|
||||
}
|
||||
if _, err := tx.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 BIGINT NOT NULL,
|
||||
PRIMARY KEY(component,version))`); err != nil {
|
||||
return postgresError("migration ledger", err)
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `SELECT version,name,checksum FROM schema_migration_steps WHERE component=$1 ORDER BY version`, component)
|
||||
if err != nil {
|
||||
return postgresError("migration history", 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 postgresError("migration history", err)
|
||||
}
|
||||
if version != applied+1 || version > len(steps) || steps[version-1].Name != name || postgresMigrationChecksum(steps[version-1]) != checksum {
|
||||
rows.Close()
|
||||
return fmt.Errorf("PostgreSQL migration history mismatch: component=%s version=%d", component, version)
|
||||
}
|
||||
applied++
|
||||
}
|
||||
err = rows.Err()
|
||||
closeErr := rows.Close()
|
||||
if err != nil {
|
||||
return postgresError("migration history", err)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return postgresError("migration history close", closeErr)
|
||||
}
|
||||
for _, step := range steps[applied:] {
|
||||
for i, statement := range step.Statements {
|
||||
if _, err := tx.ExecContext(ctx, statement); err != nil {
|
||||
return postgresError(fmt.Sprintf("migration %s/%d statement %d", component, step.Version, i+1), err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO schema_migration_steps(component,version,name,checksum,applied_at_ms) VALUES($1,$2,$3,$4,$5)`, component, step.Version, step.Name, postgresMigrationChecksum(step), time.Now().UnixMilli()); err != nil {
|
||||
return postgresError("migration record", err)
|
||||
}
|
||||
}
|
||||
if len(steps) > 0 {
|
||||
step := steps[len(steps)-1]
|
||||
for i, assertion := range step.Assertions {
|
||||
rows, err := tx.QueryContext(ctx, assertion)
|
||||
if err != nil {
|
||||
return postgresError("schema assertion", err)
|
||||
}
|
||||
violated := rows.Next()
|
||||
err = rows.Err()
|
||||
closeErr := rows.Close()
|
||||
if err != nil {
|
||||
return postgresError("schema assertion", err)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return postgresError("schema assertion close", closeErr)
|
||||
}
|
||||
if violated {
|
||||
return fmt.Errorf("PostgreSQL schema contract %s/%d assertion %d failed", component, step.Version, i+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return postgresError("migration commit", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
func TestPostgreSQLConfigurationAndRedaction(t *testing.T) {
|
||||
for _, options := range []PostgreSQLOptions{
|
||||
{}, {DSN: "postgres://test:secret@localhost/db", MaxOpenConns: -1},
|
||||
{DSN: "postgres://test:secret@localhost/db?sslmode=disable"},
|
||||
{DSN: "postgres://test:secret@localhost/db?sslmode=require"},
|
||||
{DSN: "postgres://test:secret@localhost/db?sslmode=prefer"},
|
||||
{DSN: "postgres://test:secret@localhost/db?sslmode=invalid"},
|
||||
} {
|
||||
database, err := OpenPostgreSQL(context.Background(), options)
|
||||
if database != nil || err == nil {
|
||||
t.Fatal("invalid configuration accepted")
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret") {
|
||||
t.Fatal("password disclosed")
|
||||
}
|
||||
}
|
||||
err := postgresError("write", &pgconn.PgError{Code: "23505", Message: "secret", Detail: "private row"})
|
||||
var safe *PostgreSQLError
|
||||
if !errors.As(err, &safe) || safe.SQLState != "23505" || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatal("unsafe error classification")
|
||||
}
|
||||
if !errors.Is(postgresError("read", context.Canceled), context.Canceled) {
|
||||
t.Fatal("cancellation lost")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
database, err := OpenPostgreSQL(ctx, PostgreSQLOptions{DSN: "postgres://test:secret@127.0.0.1:1/db?sslmode=disable", AllowInsecure: true})
|
||||
if database != nil || !errors.Is(err, context.Canceled) {
|
||||
t.Fatal("connection cancellation lost")
|
||||
}
|
||||
}
|
||||
|
||||
// These tests create and drop only a random schema. Use a disposable database
|
||||
// and URL DSN, never a production connection. No fixtures contain real events.
|
||||
func postgresTestDatabase(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("PAGESWIKI_TEST_POSTGRES_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("set PAGESWIKI_TEST_POSTGRES_DSN to a disposable PostgreSQL URL")
|
||||
}
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil || (u.Scheme != "postgres" && u.Scheme != "postgresql") {
|
||||
t.Fatal("test DSN must be a PostgreSQL URL")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
root, err := OpenPostgreSQL(ctx, PostgreSQLOptions{DSN: dsn, AllowInsecure: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
schema := "pageswiki_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
if _, err := root.ExecContext(ctx, `CREATE SCHEMA "`+schema+`"`); err != nil {
|
||||
root.Close()
|
||||
t.Fatal(postgresError("test schema", err))
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if _, err := root.ExecContext(cleanup, `DROP SCHEMA "`+schema+`" CASCADE`); err != nil {
|
||||
t.Error(postgresError("test cleanup", err))
|
||||
}
|
||||
root.Close()
|
||||
})
|
||||
query := u.Query()
|
||||
query.Set("search_path", schema)
|
||||
u.RawQuery = query.Encode()
|
||||
database, err := OpenPostgreSQL(ctx, PostgreSQLOptions{DSN: u.String(), AllowInsecure: true, MaxOpenConns: 6})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { database.Close() })
|
||||
return database
|
||||
}
|
||||
|
||||
func TestPostgreSQLMigrationConcurrencyAndHistory(t *testing.T) {
|
||||
database := postgresTestDatabase(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
steps := []PostgreSQLMigration{{Version: 1, Name: "initial", Statements: []string{
|
||||
`CREATE TABLE sample (uuid TEXT PRIMARY KEY, created_at_ms BIGINT NOT NULL)`,
|
||||
`INSERT INTO sample VALUES ('synthetic', 1800000000000)`,
|
||||
}, Assertions: []string{`SELECT 1 WHERE NOT EXISTS (SELECT 1 FROM sample WHERE created_at_ms=1800000000000)`}}}
|
||||
var wg sync.WaitGroup
|
||||
errs := make(chan error, 6)
|
||||
for i := 0; i < 6; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); errs <- ApplyPostgreSQLMigrations(ctx, database, "test", steps) }()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
for err := range errs {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var count int
|
||||
if err := database.QueryRowContext(ctx, `SELECT count(*) FROM sample`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("rows=%d error=%v", count, err)
|
||||
}
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", nil); err == nil {
|
||||
t.Fatal("downgrade accepted")
|
||||
}
|
||||
changed := append([]PostgreSQLMigration(nil), steps...)
|
||||
changed[0].Name = "changed"
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", changed); err == nil {
|
||||
t.Fatal("changed history accepted")
|
||||
}
|
||||
changed = append([]PostgreSQLMigration(nil), steps...)
|
||||
changed[0].Statements = []string{`SELECT 1`}
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", changed); err == nil {
|
||||
t.Fatal("changed SQL checksum accepted")
|
||||
}
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "other", []PostgreSQLMigration{{Version: 2, Name: "gap", Statements: []string{`SELECT 1`}}}); err == nil {
|
||||
t.Fatal("version gap accepted")
|
||||
}
|
||||
// Assertions are checked again even when no migrations remain to apply.
|
||||
if _, err := database.ExecContext(ctx, `DELETE FROM sample`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", steps); err == nil {
|
||||
t.Fatal("schema assertion skipped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgreSQLMigrationRollbackAndLockCancellation(t *testing.T) {
|
||||
database := postgresTestDatabase(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
broken := []PostgreSQLMigration{{Version: 1, Name: "broken", Statements: []string{`CREATE TABLE partial (id INTEGER)`, `NOT VALID SQL`}}}
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", broken); err == nil {
|
||||
t.Fatal("SQL error ignored")
|
||||
}
|
||||
var name sql.NullString
|
||||
if err := database.QueryRowContext(ctx, `SELECT to_regclass('partial')::text`).Scan(&name); err != nil || name.Valid {
|
||||
t.Fatal("DDL not rolled back", err)
|
||||
}
|
||||
if err := database.QueryRowContext(ctx, `SELECT to_regclass('schema_migration_steps')::text`).Scan(&name); err != nil || name.Valid {
|
||||
t.Fatal("ledger not rolled back", err)
|
||||
}
|
||||
broken[0].Statements = broken[0].Statements[:1]
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", broken); err != nil {
|
||||
t.Fatal("retry failed", err)
|
||||
}
|
||||
assertionFailure := append(append([]PostgreSQLMigration(nil), broken...), PostgreSQLMigration{
|
||||
Version: 2, Name: "assertion failure", Statements: []string{`CREATE TABLE should_rollback (id INTEGER)`}, Assertions: []string{`SELECT 1`},
|
||||
})
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", assertionFailure); err == nil {
|
||||
t.Fatal("assertion failure ignored")
|
||||
}
|
||||
if err := database.QueryRowContext(ctx, `SELECT to_regclass('should_rollback')::text`).Scan(&name); err != nil || name.Valid {
|
||||
t.Fatal("assertion DDL not rolled back", err)
|
||||
}
|
||||
var version int
|
||||
if err := database.QueryRowContext(ctx, `SELECT max(version) FROM schema_migration_steps WHERE component=$1`, "test").Scan(&version); err != nil || version != 1 {
|
||||
t.Fatal("assertion ledger not rolled back", err)
|
||||
}
|
||||
tx, err := database.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1835624306)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitCtx, stop := context.WithTimeout(ctx, 100*time.Millisecond)
|
||||
defer stop()
|
||||
if err := ApplyPostgreSQLMigrations(waitCtx, database, "test", broken); err == nil {
|
||||
t.Fatal("blocked migration ignored deadline")
|
||||
}
|
||||
if err := tx.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ApplyPostgreSQLMigrations(ctx, database, "test", broken); err != nil {
|
||||
t.Fatal(fmt.Sprintf("lock not released: %v", err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Package documentrefs freezes mutable Asset references without interpreting
|
||||
// ordinary text or code examples. Resolvers must authorize the source Domain.
|
||||
package documentrefs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
var ErrUnavailable = errors.New("embedded asset is unavailable")
|
||||
|
||||
type Resolver func(context.Context, string) (string, error)
|
||||
|
||||
// Freeze retains original bytes for unchanged tokens and deduplicates hashes
|
||||
// in appearance order. Repeated addresses resolve only once per payload.
|
||||
func Freeze(ctx context.Context, payload []byte, contentType string, resolve Resolver) ([]byte, []string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil || !strings.EqualFold(mediaType, "text/html") {
|
||||
return payload, nil, nil
|
||||
}
|
||||
z := html.NewTokenizer(bytes.NewReader(payload))
|
||||
var output bytes.Buffer
|
||||
seen := map[string]bool{}
|
||||
resolved := map[string]string{}
|
||||
var hashes []string
|
||||
lookup := func(address string) (string, error) {
|
||||
if hash := resolved[address]; hash != "" {
|
||||
return hash, nil
|
||||
}
|
||||
if resolve == nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
hash, err := resolve(ctx, address)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(hash) != 64 {
|
||||
return "", fmt.Errorf("%w: %s", ErrUnavailable, address)
|
||||
}
|
||||
if _, err := hex.DecodeString(hash); err != nil {
|
||||
return "", fmt.Errorf("%w: %s", ErrUnavailable, address)
|
||||
}
|
||||
hash = strings.ToLower(hash)
|
||||
resolved[address] = hash
|
||||
if !seen[hash] {
|
||||
seen[hash] = true
|
||||
hashes = append(hashes, hash)
|
||||
}
|
||||
return hash, nil
|
||||
}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
typ := z.Next()
|
||||
if typ == html.ErrorToken {
|
||||
if errors.Is(z.Err(), io.EOF) {
|
||||
return output.Bytes(), hashes, nil
|
||||
}
|
||||
return nil, nil, z.Err()
|
||||
}
|
||||
if typ != html.StartTagToken && typ != html.SelfClosingTagToken {
|
||||
output.Write(z.Raw())
|
||||
continue
|
||||
}
|
||||
// Token() may alter the tokenizer buffer. Copy original bytes first.
|
||||
raw := append([]byte(nil), z.Raw()...)
|
||||
token := z.Token()
|
||||
changed := false
|
||||
assetRef := attribute(token.Attr, "asset-ref")
|
||||
legacy := attribute(token.Attr, "immutable-ref")
|
||||
if assetRef == "" && strings.HasPrefix(legacy, "asset:") {
|
||||
assetRef = legacy
|
||||
}
|
||||
if strings.HasPrefix(assetRef, "asset:") {
|
||||
hash, err := lookup(assetRef)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
setAttribute(&token, "asset-ref", assetRef)
|
||||
setAttribute(&token, "immutable-ref", "sha256:"+hash)
|
||||
changed = true
|
||||
}
|
||||
for _, name := range []string{"src", "href", "poster", "data"} {
|
||||
provenance := "data-pageswiki-asset-" + name
|
||||
address := attribute(token.Attr, provenance)
|
||||
if address == "" {
|
||||
candidate := attribute(token.Attr, name)
|
||||
if strings.HasPrefix(candidate, "asset:") {
|
||||
address = candidate
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(address, "asset:") {
|
||||
continue
|
||||
}
|
||||
hash, err := lookup(address)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
setAttribute(&token, provenance, address)
|
||||
setAttribute(&token, name, "/_/obj/sha256:"+hash)
|
||||
changed = true
|
||||
}
|
||||
if changed {
|
||||
output.WriteString(token.String())
|
||||
} else {
|
||||
output.Write(raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func attribute(attrs []html.Attribute, name string) string {
|
||||
for _, a := range attrs {
|
||||
if strings.EqualFold(a.Key, name) {
|
||||
return strings.TrimSpace(a.Val)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func setAttribute(token *html.Token, name, value string) {
|
||||
for i := range token.Attr {
|
||||
if strings.EqualFold(token.Attr[i].Key, name) {
|
||||
token.Attr[i].Key = name
|
||||
token.Attr[i].Val = value
|
||||
return
|
||||
}
|
||||
}
|
||||
token.Attr = append(token.Attr, html.Attribute{Key: name, Val: value})
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package documentrefs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFreezePreservesUnchangedHTML(t *testing.T) {
|
||||
body := `<!DOCTYPE html><!-- sample --><DIV class='A' title="&">日本語<code><img src="asset:image:example"></code><script>const x="asset:image:sample";</script><a HREF='/plain?a=1&b=2'>Link</a></DIV>`
|
||||
got, refs, err := Freeze(context.Background(), []byte(body), "text/html; charset=utf-8", func(context.Context, string) (string, error) { t.Fatal("ordinary text resolved"); return "", nil })
|
||||
if err != nil || string(got) != body || len(refs) != 0 {
|
||||
t.Fatal("unchanged HTML lost bytes", err, string(got))
|
||||
}
|
||||
for _, mime := range []string{"text/plain", "application/octet-stream", "text/html-not-really"} {
|
||||
got, refs, err := Freeze(context.Background(), []byte(`<img src="asset:image:sample">`), mime, nil)
|
||||
if err != nil || len(refs) != 0 || string(got) != `<img src="asset:image:sample">` {
|
||||
t.Fatal("non-HTML modified", mime, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreezeDeduplicatesAndFollowsProvenance(t *testing.T) {
|
||||
hash := strings.Repeat("a", 64)
|
||||
calls := 0
|
||||
resolve := func(context.Context, string) (string, error) { calls++; return hash, nil }
|
||||
body := `<img src="asset:image:a"><video poster="asset:image:a"></video><object data="asset:image:b"></object><a href="asset:image:a">a</a><embedded-object immutable-ref="asset:image:a"></embedded-object>`
|
||||
got, refs, err := Freeze(context.Background(), []byte(body), "text/html", resolve)
|
||||
if err != nil || len(refs) != 1 || refs[0] != hash || calls != 2 {
|
||||
t.Fatal("deduplication", err, refs, calls)
|
||||
}
|
||||
if !strings.Contains(string(got), `immutable-ref="sha256:`+hash+`"`) || !strings.Contains(string(got), `data-pageswiki-asset-src="asset:image:a"`) {
|
||||
t.Fatal("provenance missing")
|
||||
}
|
||||
hash = strings.Repeat("b", 64)
|
||||
calls = 0
|
||||
updated, refs, err := Freeze(context.Background(), got, "text/html", resolve)
|
||||
if err != nil || len(refs) != 1 || refs[0] != hash || calls != 2 || strings.Contains(string(updated), strings.Repeat("a", 64)) {
|
||||
t.Fatal("resave did not follow HEAD", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFreezeRejectsMissingInvalidAndCanceled(t *testing.T) {
|
||||
for _, hash := range []string{"", strings.Repeat("x", 64)} {
|
||||
if _, _, err := Freeze(context.Background(), []byte(`<img src="asset:image:a">`), "text/html", func(context.Context, string) (string, error) { return hash, nil }); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal("invalid hash accepted", err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, _, err := Freeze(ctx, []byte("text"), "text/plain", nil); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal("cancellation ignored", err)
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,12 @@ type Runner struct {
|
||||
registry *Registry
|
||||
opts RunnerOptions
|
||||
mu sync.Mutex
|
||||
stopping bool
|
||||
stopCtx context.Context
|
||||
cancel context.CancelFunc
|
||||
workers sync.WaitGroup
|
||||
stopOnce sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func NewRunner(queue Queue, registry *Registry, opts RunnerOptions) *Runner {
|
||||
@@ -41,7 +47,30 @@ func NewRunner(queue Queue, registry *Registry, opts RunnerOptions) *Runner {
|
||||
if opts.Active == nil {
|
||||
opts.Active = new(atomic.Int64)
|
||||
}
|
||||
return &Runner{queue: queue, registry: registry, opts: opts}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
return &Runner{queue: queue, registry: registry, opts: opts, stopCtx: ctx, cancel: cancel, done: make(chan struct{})}
|
||||
}
|
||||
|
||||
// Stop closes admission permanently, cancels handlers and waits for persisted
|
||||
// completions. A timeout does not mean workers have exited: callers must keep
|
||||
// ownership/database resources alive and may call Stop again to await them.
|
||||
func (r *Runner) Stop(ctx context.Context) error {
|
||||
r.stopOnce.Do(func() {
|
||||
r.cancel()
|
||||
go func() {
|
||||
r.mu.Lock()
|
||||
r.stopping = true
|
||||
r.mu.Unlock()
|
||||
r.workers.Wait()
|
||||
close(r.done)
|
||||
}()
|
||||
})
|
||||
select {
|
||||
case <-r.done:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) report(stage string, job *Job, err error) {
|
||||
@@ -57,7 +86,10 @@ func (r *Runner) Running() int64 { return r.opts.Active.Load() }
|
||||
func (r *Runner) Dispatch(ctx context.Context) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
for n := 0; n < 32 && ctx.Err() == nil; n++ {
|
||||
if r.stopping || r.stopCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
for n := 0; n < 32 && ctx.Err() == nil && r.stopCtx.Err() == nil; n++ {
|
||||
settings, err := r.queue.Settings(ctx)
|
||||
if err != nil {
|
||||
r.report("settings", nil, err)
|
||||
@@ -81,7 +113,15 @@ func (r *Runner) Dispatch(ctx context.Context) {
|
||||
}
|
||||
r.opts.Active.Add(1)
|
||||
r.report("start-log", job, r.queue.Started(ctx, job))
|
||||
go r.execute(ctx, job)
|
||||
workerCtx, cancel := context.WithCancel(ctx)
|
||||
stop := context.AfterFunc(r.stopCtx, cancel)
|
||||
r.workers.Add(1)
|
||||
go func() {
|
||||
defer r.workers.Done()
|
||||
defer cancel()
|
||||
defer stop()
|
||||
r.execute(workerCtx, job)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,53 @@ type finishedJob struct {
|
||||
err error
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func TestRunnerStopWaitsAndClosesAdmission(t *testing.T) {
|
||||
q := newFakeQueue(1)
|
||||
reg := &Registry{}
|
||||
started := make(chan struct{})
|
||||
cancelled := make(chan struct{})
|
||||
exit := make(chan struct{})
|
||||
if err := reg.Register("synthetic", func(ctx context.Context, _ *Job) error {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
close(cancelled)
|
||||
<-exit // simulate cleanup that cannot be interrupted
|
||||
return ctx.Err()
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := NewRunner(q, reg, RunnerOptions{})
|
||||
r.Dispatch(context.Background())
|
||||
receive(t, started)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if err := r.Stop(ctx); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
receive(t, cancelled)
|
||||
if r.Running() != 1 {
|
||||
t.Fatal("worker exited before cleanup")
|
||||
}
|
||||
r.Dispatch(context.Background())
|
||||
if q.claimed != 1 {
|
||||
t.Fatal("admission remained open")
|
||||
}
|
||||
close(exit)
|
||||
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := r.Stop(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
receive(t, q.finished)
|
||||
if r.Running() != 0 {
|
||||
t.Fatal("worker slot retained after stop")
|
||||
}
|
||||
if err := r.Stop(ctx); err != nil {
|
||||
t.Fatal("idempotent stop", err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeQueue struct {
|
||||
mu sync.Mutex
|
||||
settings Settings
|
||||
|
||||
@@ -13,6 +13,8 @@ var (
|
||||
)
|
||||
|
||||
type Job struct {
|
||||
// ClaimToken fences native database completion; never expose it to clients.
|
||||
ClaimToken string `json:"-"`
|
||||
UUID string `json:"uuid"`
|
||||
EventUUID string `json:"event_uuid,omitempty"`
|
||||
Type string `json:"event_type"`
|
||||
|
||||
@@ -21,6 +21,7 @@ type Manifest struct {
|
||||
|
||||
func Catalog() []Manifest {
|
||||
return []Manifest{
|
||||
{ID: "viewer.slides", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "slides.title", DescriptionKey: "slides.help", Capabilities: []string{"path.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "client-compute+bounded-read"},
|
||||
{ID: "viewer.gecko", APIVersion: 1, Version: "0.1.0", Kind: "viewer", Scope: "domain", NameKey: "feeds.gecko", DescriptionKey: "feeds.gecko_help", Capabilities: []string{"feeds.own.read"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: false, ResourceClass: "client-compute+relay-network"},
|
||||
{ID: "organizer.feeds", APIVersion: 1, Version: "0.1.0", Kind: "feeds", Scope: "domain", NameKey: "feeds.title", DescriptionKey: "feeds.help", Capabilities: []string{"feeds.own.read", "feeds.own.write"}, Events: []string{"feed.source.sync"}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "background+network+index"},
|
||||
{ID: "organizer.contacts", APIVersion: 1, Version: "0.2.0", Kind: "contacts", Scope: "domain", NameKey: "contacts.title", DescriptionKey: "contacts.help", Capabilities: []string{"contacts.own.read", "contacts.own.write"}, Events: []string{}, SettingsPanel: "extensions", Builtin: true, Enabled: true, ResourceClass: "foreground+index"},
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const DistributionPrefix = "/distribution/v0.0.1/"
|
||||
|
||||
// Updated only after the reproducible source/notice bundle has been reviewed.
|
||||
const DistributionManifestSHA256 = "84953114f5e393dd97d9f948a5bc51c95b9355b58461dd3355e068a96cb2e381"
|
||||
|
||||
type DistributionFile struct {
|
||||
File string `json:"file"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Size int64 `json:"size"`
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
|
||||
var distributionName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._+-]{0,150}$`)
|
||||
|
||||
func VerifyDistribution(dir string) (map[string]DistributionFile, error) {
|
||||
return verifyDistribution(dir, DistributionManifestSHA256)
|
||||
}
|
||||
|
||||
func verifyDistribution(dir, expected string) (map[string]DistributionFile, error) {
|
||||
path := filepath.Join(dir, "manifest.json")
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() > 1<<20 {
|
||||
return nil, fmt.Errorf("Gecko distribution manifest missing or invalid")
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
if hex.EncodeToString(sum[:]) != expected {
|
||||
return nil, fmt.Errorf("Gecko distribution manifest checksum mismatch")
|
||||
}
|
||||
var manifest struct {
|
||||
Format string `json:"format"`
|
||||
Version string `json:"version"`
|
||||
Files []DistributionFile `json:"files"`
|
||||
}
|
||||
if json.Unmarshal(raw, &manifest) != nil || manifest.Format != "pageswiki.gecko-distribution.v1" || manifest.Version != "v0.0.1" || len(manifest.Files) > 512 {
|
||||
return nil, fmt.Errorf("invalid Gecko distribution format")
|
||||
}
|
||||
files := map[string]DistributionFile{}
|
||||
for _, entry := range manifest.Files {
|
||||
if !distributionName.MatchString(entry.File) || entry.File == "manifest.json" || entry.Size < 1 || entry.Size > 2<<30 || len(entry.SHA256) != 64 {
|
||||
return nil, fmt.Errorf("invalid distribution entry")
|
||||
}
|
||||
if _, exists := files[entry.File]; exists {
|
||||
return nil, fmt.Errorf("duplicate distribution entry")
|
||||
}
|
||||
info, err := os.Lstat(filepath.Join(dir, entry.File))
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() != entry.Size {
|
||||
return nil, fmt.Errorf("distribution file missing or invalid: %s", entry.File)
|
||||
}
|
||||
file, err := os.Open(filepath.Join(dir, entry.File))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hash := sha256.New()
|
||||
_, err = io.Copy(hash, io.LimitReader(file, entry.Size+1))
|
||||
file.Close()
|
||||
if err != nil || hex.EncodeToString(hash.Sum(nil)) != entry.SHA256 {
|
||||
return nil, fmt.Errorf("distribution file checksum mismatch: %s", entry.File)
|
||||
}
|
||||
files[entry.File] = entry
|
||||
}
|
||||
for _, name := range []string{"index.html", "README.txt", "gecko.js", "gecko.wasm.zst", "firefox.tar.gz", "firefox.tar.gz.notices.txt", "wrapper.tar.gz", "wrapper-MPL.txt", "emscripten.tar.gz", "emscripten.tar.gz.notices.txt", "rust-src.tar.xz", "rust-src.tar.xz.notices.txt", "zstddec.tgz", "zstddec.tgz.notices.txt", "NotoSansCJKjp-Regular.otf", "NotoSansCJK-LICENSE.txt"} {
|
||||
if _, ok := files[name]; !ok {
|
||||
return nil, fmt.Errorf("distribution incomplete: %s", name)
|
||||
}
|
||||
}
|
||||
files["manifest.json"] = DistributionFile{File: "manifest.json", SHA256: expected, Size: int64(len(raw)), Kind: "manifest"}
|
||||
return files, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package geckorelay
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDistribution(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := VerifyDistribution(dir); err == nil {
|
||||
t.Fatal("missing distribution accepted")
|
||||
}
|
||||
names := []string{"index.html", "README.txt", "gecko.js", "gecko.wasm.zst", "firefox.tar.gz", "firefox.tar.gz.notices.txt", "wrapper.tar.gz", "wrapper-MPL.txt", "emscripten.tar.gz", "emscripten.tar.gz.notices.txt", "rust-src.tar.xz", "rust-src.tar.xz.notices.txt", "zstddec.tgz", "zstddec.tgz.notices.txt", "NotoSansCJKjp-Regular.otf", "NotoSansCJK-LICENSE.txt"}
|
||||
content := []byte("synthetic source and notice")
|
||||
hash := sha256.Sum256(content)
|
||||
var entries []DistributionFile
|
||||
for _, name := range names {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), content, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries = append(entries, DistributionFile{File: name, Size: int64(len(content)), SHA256: hex.EncodeToString(hash[:])})
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]any{"format": "pageswiki.gecko-distribution.v1", "version": "v0.0.1", "files": entries})
|
||||
if err := os.WriteFile(filepath.Join(dir, "manifest.json"), raw, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
want := hex.EncodeToString(sum[:])
|
||||
files, err := verifyDistribution(dir, want)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
relay, _ := New(testKey, dir)
|
||||
relay.Distribution = files
|
||||
for _, name := range []string{"index.html", "firefox.tar.gz", "manifest.json", "unknown", "../manifest.json"} {
|
||||
req := httptest.NewRequest("GET", DistributionPrefix+name, nil)
|
||||
req.Header.Set(GrantHeader, Sign(testKey, Grant{Subject: "test:user", Nonce: "download-test-0123456789", Expires: time.Now().Add(30 * time.Second).Unix()}))
|
||||
rec := httptest.NewRecorder()
|
||||
relay.ServeHTTP(rec, req)
|
||||
expected := 200
|
||||
if strings.Contains(name, "unknown") || strings.Contains(name, "../") {
|
||||
expected = 404
|
||||
}
|
||||
if rec.Code != expected {
|
||||
t.Fatalf("%s: %d", name, rec.Code)
|
||||
}
|
||||
if expected == 200 && rec.Header().Get("ETag") == "" {
|
||||
t.Fatal("no ETag")
|
||||
}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "README.txt"), []byte("tampered"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := verifyDistribution(dir, want); err == nil {
|
||||
t.Fatal("tampered notice accepted")
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, "README.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(filepath.Join(dir, "gecko.js"), filepath.Join(dir, "README.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := verifyDistribution(dir, want); err == nil {
|
||||
t.Fatal("symlink accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributionRealBundle(t *testing.T) {
|
||||
dir := os.Getenv("PAGESWIKI_GECKO_TEST_BUNDLE")
|
||||
if dir == "" {
|
||||
t.Skip("opt-in complete distribution")
|
||||
}
|
||||
if _, err := VerifyDistribution(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -28,6 +29,8 @@ const (
|
||||
|
||||
type Relay struct {
|
||||
Key, Assets string
|
||||
Distribution map[string]DistributionFile
|
||||
downloads chan struct{}
|
||||
mu sync.Mutex
|
||||
active map[string]bool
|
||||
used map[string]int64
|
||||
@@ -40,7 +43,7 @@ func New(key, assets string) (*Relay, error) {
|
||||
if len(key) < 32 {
|
||||
return nil, errors.New("relay key must contain at least 32 bytes")
|
||||
}
|
||||
r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}}
|
||||
r := &Relay{Key: key, Assets: assets, active: map[string]bool{}, used: map[string]int64{}, downloads: make(chan struct{}, 2)}
|
||||
r.dial = func(ctx context.Context, host string, port uint16) (net.Conn, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
|
||||
defer cancel()
|
||||
@@ -72,6 +75,47 @@ func (r *Relay) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]any{"active_sessions": active, "received_bytes": r.rx.Load(), "sent_bytes": r.tx.Load(), "rejected": r.rejected.Load(), "profile": "tcp-80-443", "max_sessions": 4, "max_streams": maxStreams, "bytes_per_second": bytesPerSecond, "max_session_bytes": maxBytes})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(req.URL.Path, DistributionPrefix) {
|
||||
name := strings.TrimPrefix(req.URL.Path, DistributionPrefix)
|
||||
entry, ok := r.Distribution[name]
|
||||
if !ok {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case r.downloads <- struct{}{}:
|
||||
defer func() { <-r.downloads }()
|
||||
default:
|
||||
http.Error(w, "download limit", 429)
|
||||
return
|
||||
}
|
||||
w.Header().Set("ETag", `"`+entry.SHA256+`"`)
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'self'")
|
||||
w.Header().Set("Referrer-Policy", "no-referrer")
|
||||
switch {
|
||||
case name == "index.html":
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
case strings.HasSuffix(name, ".txt"):
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
case name == "manifest.json":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="`+name+`"`)
|
||||
}
|
||||
// ServeContent avoids ServeFile's /index.html -> ./ redirect, which
|
||||
// would escape the explicit file allowlist at the proxy boundary.
|
||||
file, err := os.Open(filepath.Join(r.Assets, name))
|
||||
if err != nil {
|
||||
http.NotFound(w, req)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
http.ServeContent(w, req, name, time.Time{}, file)
|
||||
return
|
||||
}
|
||||
if req.URL.Path == AssetsPrefix+"gecko.js" || req.URL.Path == AssetsPrefix+"gecko.wasm.zst" {
|
||||
w.Header().Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
w.Header().Set("Cache-Control", "private, max-age=86400, immutable")
|
||||
|
||||
@@ -3,6 +3,8 @@ package grammaratur
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
@@ -12,17 +14,93 @@ import (
|
||||
|
||||
// HTMLToMarkdownAuthoring keeps source HTML when conversion loses structure,
|
||||
// attributes, comments or text. This is not a sanitization boundary.
|
||||
var nestedListGap = regexp.MustCompile(`\n[\t ]*\n([\t ]+(?:[-+*]|[0-9]+\.) )`)
|
||||
|
||||
func authoringMarkdown(source string) (string, error) {
|
||||
md, err := HTMLToMarkdown(source)
|
||||
if err != nil {
|
||||
return md, err
|
||||
}
|
||||
// The converter inserts a loose-list gap before nested lists. Only accept
|
||||
// tightening when the resulting DOM matches; code and real paragraphs stay protected.
|
||||
tight := nestedListGap.ReplaceAllString(md, "\n$1")
|
||||
if tight != md && htmlStructure(source) == htmlStructure(MarkdownToHTML(tight)) {
|
||||
return tight, nil
|
||||
}
|
||||
return md, nil
|
||||
}
|
||||
|
||||
func HTMLToMarkdownAuthoring(source string) (string, error) {
|
||||
converted, err := HTMLToMarkdown(source)
|
||||
converted, err := authoringMarkdown(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownToHTML(converted)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
// Protect only the blocks which cannot round-trip. One custom component
|
||||
// must not turn the headings, lists and paragraphs around it into HTML.
|
||||
blocks, ok := authoringBlocks(source)
|
||||
if !ok {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
var parts []string
|
||||
for _, raw := range blocks {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
continue
|
||||
}
|
||||
md, e := authoringMarkdown(raw)
|
||||
if e != nil || htmlStructure(raw) != htmlStructure(MarkdownToHTML(md)) {
|
||||
md = rawHTMLBlock(raw)
|
||||
}
|
||||
parts = append(parts, md)
|
||||
}
|
||||
mixed := strings.Join(parts, "\n\n")
|
||||
// Includes head content, comments outside body and fragment edge cases.
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(mixed)) {
|
||||
return rawHTMLBlock(source), nil
|
||||
}
|
||||
return mixed, nil
|
||||
}
|
||||
return converted, nil
|
||||
}
|
||||
|
||||
// Token boundaries retain the exact source of protected components (including
|
||||
// attribute quoting and void-element syntax). Never serialize the parsed DOM
|
||||
// back over their source. Malformed/implicit nesting uses whole-document fallback.
|
||||
func authoringBlocks(source string) ([]string, bool) {
|
||||
z := html.NewTokenizer(strings.NewReader(source))
|
||||
var stack, blocks []string
|
||||
start, offset := 0, 0
|
||||
for {
|
||||
kind := z.Next()
|
||||
if kind == html.ErrorToken {
|
||||
return blocks, z.Err() == io.EOF && len(stack) == 0 && offset == len(source)
|
||||
}
|
||||
offset += len(z.Raw())
|
||||
switch kind {
|
||||
case html.StartTagToken:
|
||||
name, _ := z.TagName()
|
||||
switch string(name) {
|
||||
case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr":
|
||||
default:
|
||||
stack = append(stack, string(name))
|
||||
}
|
||||
case html.EndTagToken:
|
||||
name, _ := z.TagName()
|
||||
if len(stack) == 0 || stack[len(stack)-1] != string(name) {
|
||||
return nil, false
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
if len(stack) == 0 {
|
||||
blocks = append(blocks, source[start:offset])
|
||||
start = offset
|
||||
if len(blocks) > 1024 {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// {=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.
|
||||
@@ -110,6 +188,28 @@ func htmlStructure(source string) string {
|
||||
literal = literal || n.Data == "pre" || n.Data == "code" || n.Data == "script" || n.Data == "style"
|
||||
data := n.Data
|
||||
if n.Type == html.TextNode && !literal {
|
||||
// Formatting whitespace beside a nested block is not an inline word
|
||||
// separator. Keep all whitespace between inline siblings significant.
|
||||
if n.Parent != nil && n.Parent.Data == "li" {
|
||||
isList := func(x *html.Node) bool {
|
||||
return x != nil && x.Type == html.ElementNode && (x.Data == "ul" || x.Data == "ol")
|
||||
}
|
||||
if isList(n.NextSibling) {
|
||||
data = strings.TrimRight(data, " \t\r\n")
|
||||
}
|
||||
if isList(n.PrevSibling) {
|
||||
data = strings.TrimLeft(data, " \t\r\n")
|
||||
}
|
||||
if data == "" {
|
||||
return
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(data) == "" && n.Parent != nil {
|
||||
switch n.Parent.Data {
|
||||
case "ul", "ol", "table", "thead", "tbody", "tfoot", "tr":
|
||||
return
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(data) == "" && (n.Parent == nil || n.Parent.Data == "body" || n.Parent.Data == "html") {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -65,3 +65,19 @@ func TestAuthoringWhitespaceComparisonIsConservative(t *testing.T) {
|
||||
t.Fatal("word boundaries ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringPartialMarkdownRecovery(t *testing.T) {
|
||||
source := `<h1>Title</h1><p>Some <strong>bold</strong> text.</p><figure data-x="keep"><img src="/image"><figcaption>Caption</figcaption></figure><ul><li>First</li><li>Second</li></ul>`
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil || !strings.HasPrefix(md, "# Title") || !strings.Contains(md, "**bold**") || strings.Count(md, "{=html}") != 1 || !strings.Contains(md, "- First") {
|
||||
t.Fatalf("markdown not recovered: %q %v", md, err)
|
||||
}
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||
t.Fatal("HTML lost during partial conversion")
|
||||
}
|
||||
protected := `<figure data-x='original'><img src=/image><figcaption>Caption</figcaption></figure>`
|
||||
md, err = HTMLToMarkdownAuthoring("<h1>Title</h1>" + protected + "<p>Tail</p>")
|
||||
if err != nil || !strings.Contains(MarkdownAuthoringHTML(md), protected) || !strings.HasPrefix(md, "# Title") {
|
||||
t.Fatalf("protected bytes changed: %q %v", md, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package grammaratur
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAuthoringNestedLists(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"<ul><li>Parent<ul><li>Child</li></ul></li></ul>",
|
||||
"<ul>\n<li>Parent\n<ul>\n<li>Child</li>\n</ul>\n</li>\n</ul>",
|
||||
"<ul><li>Parent<ul><li>Child<ul><li>Grandchild</li></ul></li></ul></li><li>Sibling</li></ul>",
|
||||
"<ol><li>Parent<ul><li>Child</li></ul></li></ol>",
|
||||
"<ul><li><strong>Parent</strong><ul><li>Child</li></ul></li></ul>",
|
||||
} {
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if htmlStructure(source) != htmlStructure(MarkdownAuthoringHTML(md)) {
|
||||
t.Errorf("list structure changed: %q", md)
|
||||
}
|
||||
if err != nil || strings.Contains(md, "{=html}") {
|
||||
plain, _ := HTMLToMarkdown(source)
|
||||
t.Errorf("source=%q md=%q plain=%q rendered=%q err=%v", source, md, plain, MarkdownToHTML(plain), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthoringNestedListPreservesAttributes(t *testing.T) {
|
||||
source := `<ul><li data-custom="keep">Parent<ul><li>Child</li></ul></li></ul>`
|
||||
md, err := HTMLToMarkdownAuthoring(source)
|
||||
if err != nil || MarkdownAuthoringHTML(md) != source {
|
||||
t.Fatalf("protected list changed: %q %v", md, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
// Package inspection implements file inspection contracts, not authorization
|
||||
// or a malware scanner. No HTTP route, worker or external service is enabled
|
||||
// by importing it. Callers must load complete, trusted policy snapshots.
|
||||
package inspection
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrPolicy = errors.New("invalid inspection policy")
|
||||
|
||||
type Mode string
|
||||
|
||||
const (
|
||||
Inherit Mode = "inherit"
|
||||
Disabled Mode = "disabled"
|
||||
Monitor Mode = "monitor"
|
||||
Required Mode = "required"
|
||||
)
|
||||
|
||||
type State string
|
||||
|
||||
const (
|
||||
Pending State = "pending"
|
||||
Clean State = "clean"
|
||||
Suspicious State = "suspicious"
|
||||
Malicious State = "malicious"
|
||||
Error State = "error"
|
||||
Expired State = "expired"
|
||||
)
|
||||
|
||||
// Engine identifies both the executable and its signature/model definitions.
|
||||
// Definitions must change when the engine's detection data changes.
|
||||
type Engine struct {
|
||||
ID string `json:"id"`
|
||||
Version string `json:"version"`
|
||||
Definitions string `json:"definitions"`
|
||||
}
|
||||
|
||||
func (e Engine) valid() bool {
|
||||
return label(e.ID) && label(e.Version) && label(e.Definitions)
|
||||
}
|
||||
func label(s string) bool {
|
||||
return s != "" && len(s) <= 128 && utf8.ValidString(s) && strings.TrimSpace(s) == s && strings.IndexFunc(s, unicode.IsControl) < 0
|
||||
}
|
||||
func validUUID(s string) bool {
|
||||
id, err := uuid.Parse(s)
|
||||
return err == nil && id.String() == s && id != uuid.Nil
|
||||
}
|
||||
func validHash(s string) bool {
|
||||
if len(s) != 64 || strings.ToLower(s) != s {
|
||||
return false
|
||||
}
|
||||
_, err := hex.DecodeString(s)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// Paths are already-decoded semantic Paths. Literal '%' and '+' are valid;
|
||||
// never percent-decode a second time. Scope tests use segment boundaries.
|
||||
func canonical(p string) bool {
|
||||
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p && !strings.Contains(p, "\\") && strings.IndexFunc(p, unicode.IsControl) < 0
|
||||
}
|
||||
func under(p, root string) bool {
|
||||
return root == "/" || p == root || strings.HasPrefix(p, root+"/")
|
||||
}
|
||||
|
||||
type Rule struct {
|
||||
Path string `json:"path"`
|
||||
Mode Mode `json:"mode"`
|
||||
Engines []Engine `json:"engines"`
|
||||
}
|
||||
|
||||
// Policy is a Domain-local snapshot. Generation must change on policy OR
|
||||
// relevant topology/engine-enable changes. Rules come from authorized locality settings,
|
||||
// not from uploader-controlled data. External consent is Domain-admin owned.
|
||||
type Policy struct {
|
||||
Domain string `json:"domain"`
|
||||
Generation string `json:"generation"`
|
||||
AllowExternal bool `json:"allow_external"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
|
||||
type Effective struct {
|
||||
Domain string
|
||||
Generation string
|
||||
Mode Mode
|
||||
AllowExternal bool
|
||||
Engines []Engine
|
||||
}
|
||||
|
||||
func rank(m Mode) int {
|
||||
switch m {
|
||||
case Inherit, Disabled:
|
||||
return 0
|
||||
case Monitor:
|
||||
return 1
|
||||
case Required:
|
||||
return 2
|
||||
default:
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve never weakens an ancestor's mode or drops ancestor engines. A lower
|
||||
// rule can add engines but cannot replace an inherited engine's version.
|
||||
func (p Policy) Resolve(logicalPath string) (Effective, error) {
|
||||
out := Effective{Domain: p.Domain, Generation: p.Generation, Mode: Disabled, AllowExternal: p.AllowExternal}
|
||||
if !validUUID(p.Domain) || !validUUID(p.Generation) || !canonical(logicalPath) || len(p.Rules) > 128 {
|
||||
return Effective{}, ErrPolicy
|
||||
}
|
||||
rules := append([]Rule(nil), p.Rules...)
|
||||
sort.Slice(rules, func(i, j int) bool { return len(rules[i].Path) < len(rules[j].Path) })
|
||||
seen := map[string]bool{}
|
||||
engines := map[string]Engine{}
|
||||
for _, r := range rules {
|
||||
if !canonical(r.Path) || seen[r.Path] || rank(r.Mode) < 0 || len(r.Engines) > 16 || ((r.Mode == Inherit || r.Mode == Disabled) && len(r.Engines) > 0) {
|
||||
return Effective{}, ErrPolicy
|
||||
}
|
||||
seen[r.Path] = true
|
||||
local := map[string]bool{}
|
||||
for _, e := range r.Engines {
|
||||
if !e.valid() || local[e.ID] {
|
||||
return Effective{}, ErrPolicy
|
||||
}
|
||||
local[e.ID] = true
|
||||
}
|
||||
if !under(logicalPath, r.Path) {
|
||||
continue
|
||||
}
|
||||
if rank(r.Mode) > rank(out.Mode) {
|
||||
out.Mode = r.Mode
|
||||
}
|
||||
for _, e := range r.Engines {
|
||||
if old, ok := engines[e.ID]; ok && old != e {
|
||||
return Effective{}, ErrPolicy
|
||||
}
|
||||
engines[e.ID] = e
|
||||
}
|
||||
}
|
||||
if len(engines) > 16 || (out.Mode != Disabled && len(engines) == 0) {
|
||||
return Effective{}, ErrPolicy
|
||||
}
|
||||
for _, e := range engines {
|
||||
out.Engines = append(out.Engines, e)
|
||||
}
|
||||
sort.Slice(out.Engines, func(i, j int) bool { return out.Engines[i].ID < out.Engines[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Key is the minimum cache/job identity. Never reuse a result across Domains,
|
||||
// policy generations, content hashes, or engine/definition versions.
|
||||
type Key struct {
|
||||
Domain string `json:"domain"`
|
||||
Generation string `json:"generation"`
|
||||
Hash string `json:"sha256"`
|
||||
Engine Engine `json:"engine"`
|
||||
}
|
||||
|
||||
func (k Key) valid() bool {
|
||||
return validUUID(k.Domain) && validUUID(k.Generation) && validHash(k.Hash) && k.Engine.valid()
|
||||
}
|
||||
|
||||
// Report is trusted worker output, never supplied by an uploader. Publication
|
||||
// must additionally CAS the job lease/generation when persisting this record.
|
||||
type Report struct {
|
||||
Key Key
|
||||
State State
|
||||
Finished time.Time
|
||||
Expires time.Time
|
||||
}
|
||||
type Decision struct {
|
||||
Allowed bool
|
||||
State State
|
||||
Reason string
|
||||
}
|
||||
|
||||
// Decide is an ADDITIONAL gate. accessAllowed is the application's existing
|
||||
// ACL/publication decision; an inspection result can never grant that access.
|
||||
// active is a fresh snapshot of enabled engines, not the queued job's snapshot.
|
||||
func Decide(accessAllowed bool, p Effective, hash string, reports []Report, active []Engine, now time.Time) Decision {
|
||||
if !accessAllowed {
|
||||
return Decision{Reason: "access_denied"}
|
||||
}
|
||||
if !validUUID(p.Domain) || !validUUID(p.Generation) || !validHash(hash) || now.IsZero() || rank(p.Mode) < 0 || p.Mode == Inherit || len(p.Engines) > 16 || len(reports) > 64 || len(active) > 64 {
|
||||
return Decision{State: Error, Reason: "invalid_policy"}
|
||||
}
|
||||
if p.Mode == Disabled {
|
||||
return Decision{Allowed: true, Reason: "inspection_disabled"}
|
||||
}
|
||||
if len(p.Engines) == 0 {
|
||||
return Decision{State: Error, Reason: "missing_engine"}
|
||||
}
|
||||
status, reason := Clean, "inspection_clean"
|
||||
seen := map[string]bool{}
|
||||
for _, e := range p.Engines {
|
||||
if !e.valid() || seen[e.ID] {
|
||||
return Decision{State: Error, Reason: "invalid_policy"}
|
||||
}
|
||||
seen[e.ID] = true
|
||||
key := Key{p.Domain, p.Generation, hash, e}
|
||||
state, why := Pending, "inspection_pending"
|
||||
enabled := false
|
||||
for _, a := range active {
|
||||
if a == e {
|
||||
enabled = true
|
||||
}
|
||||
}
|
||||
var matches []Report
|
||||
for _, r := range reports {
|
||||
if r.Key == key {
|
||||
matches = append(matches, r)
|
||||
}
|
||||
}
|
||||
if !enabled {
|
||||
state, why = Error, "engine_unavailable"
|
||||
} else if len(matches) > 1 {
|
||||
state, why = Error, "ambiguous_result"
|
||||
} else if len(matches) == 1 {
|
||||
r := matches[0]
|
||||
switch r.State {
|
||||
case Pending, Error, Expired:
|
||||
state, why = r.State, "inspection_"+string(r.State)
|
||||
case Clean, Suspicious, Malicious:
|
||||
if r.Finished.IsZero() || r.Finished.After(now) || !r.Expires.After(r.Finished) {
|
||||
state, why = Error, "invalid_result"
|
||||
} else if !r.Expires.After(now) {
|
||||
state, why = Expired, "inspection_expired"
|
||||
} else {
|
||||
state, why = r.State, "inspection_"+string(r.State)
|
||||
}
|
||||
default:
|
||||
state, why = Error, "invalid_result"
|
||||
}
|
||||
}
|
||||
if severity(state) > severity(status) {
|
||||
status, reason = state, why
|
||||
}
|
||||
}
|
||||
return Decision{Allowed: p.Mode == Monitor || status == Clean, State: status, Reason: reason}
|
||||
}
|
||||
func severity(s State) int {
|
||||
switch s {
|
||||
case Clean:
|
||||
return 0
|
||||
case Pending:
|
||||
return 1
|
||||
case Expired:
|
||||
return 2
|
||||
case Error:
|
||||
return 3
|
||||
case Suspicious:
|
||||
return 4
|
||||
case Malicious:
|
||||
return 5
|
||||
}
|
||||
return 3
|
||||
}
|
||||
|
||||
// DecidePaths evaluates all supplied current bindings, not just the requested
|
||||
// alias. The caller must load a complete Domain-local binding snapshot, including
|
||||
// source/dependency policy when appropriate. An empty/truncated set cannot stand
|
||||
// for an unrestricted UUID/Asset. Cross-Domain bindings need a separate decision
|
||||
// per Domain. This method performs no lookup and is not a routing middleware.
|
||||
func DecidePaths(accessAllowed bool, p Policy, bindings []string, hash string, reports []Report, active []Engine, now time.Time) Decision {
|
||||
if !accessAllowed {
|
||||
return Decision{Reason: "access_denied"}
|
||||
}
|
||||
if len(bindings) == 0 || len(bindings) > 128 {
|
||||
return Decision{State: Error, Reason: "incomplete_bindings"}
|
||||
}
|
||||
decision := Decision{Allowed: true, Reason: "inspection_disabled"}
|
||||
for _, binding := range bindings {
|
||||
effective, err := p.Resolve(binding)
|
||||
if err != nil {
|
||||
return Decision{State: Error, Reason: "invalid_policy"}
|
||||
}
|
||||
next := Decide(true, effective, hash, reports, active, now)
|
||||
if !next.Allowed {
|
||||
return next
|
||||
}
|
||||
if next.State != "" && (decision.State == "" || severity(next.State) > severity(decision.State)) {
|
||||
decision = next
|
||||
}
|
||||
}
|
||||
return decision
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package inspection
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
const domain = "00000000-0000-4000-8000-000000000001"
|
||||
const generation = "00000000-0000-4000-8000-000000000002"
|
||||
|
||||
var engine = Engine{"test.local", "1", "definitions-1"}
|
||||
|
||||
func TestPolicyInheritance(t *testing.T) {
|
||||
p := Policy{Domain: domain, Generation: generation, Rules: []Rule{
|
||||
{Path: "/private", Mode: Required, Engines: []Engine{engine}},
|
||||
{Path: "/private/child", Mode: Disabled},
|
||||
{Path: "/private/child/deep", Mode: Inherit},
|
||||
}}
|
||||
for _, path := range []string{"/private", "/private/child", "/private/child/deep/page"} {
|
||||
e, err := p.Resolve(path)
|
||||
if err != nil || e.Mode != Required || len(e.Engines) != 1 || e.Engines[0] != engine {
|
||||
t.Fatalf("inherit %q: %+v %v", path, e, err)
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/", "/private2/page", "/private_%/page"} {
|
||||
e, err := p.Resolve(path)
|
||||
if err != nil || e.Mode != Disabled {
|
||||
t.Fatalf("scope %q: %+v %v", path, e, err)
|
||||
}
|
||||
}
|
||||
p.Rules = append(p.Rules, Rule{Path: "/private/child/deep/page", Mode: Required, Engines: []Engine{{"test.second", "1", "defs"}}})
|
||||
e, err := p.Resolve("/private/child/deep/page")
|
||||
if err != nil || len(e.Engines) != 2 {
|
||||
t.Fatal("child dropped ancestor engine", e, err)
|
||||
}
|
||||
p.Rules[3].Engines = []Engine{{engine.ID, "2", engine.Definitions}}
|
||||
if _, err := p.Resolve("/private/child/deep/page"); err == nil {
|
||||
t.Fatal("child replaced required engine")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyValidationAndExactPaths(t *testing.T) {
|
||||
for _, path := range []string{"/日本語/100%+完了", "/a/%2e%2e/b", "/a_b/page"} {
|
||||
p := Policy{Domain: domain, Generation: generation, Rules: []Rule{{Path: path, Mode: Required, Engines: []Engine{engine}}}}
|
||||
if e, err := p.Resolve(path + "/child"); err != nil || e.Mode != Required {
|
||||
t.Fatal(path, e, err)
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"", "relative", "/a/../b", "/a//b", "/a/", "/a\\b", "/a\x00b", "/\xff", "/" + strings.Repeat("a", 4096)} {
|
||||
if _, err := (Policy{Domain: domain, Generation: generation}).Resolve(path); err == nil {
|
||||
t.Fatalf("invalid path %q", path)
|
||||
}
|
||||
}
|
||||
for _, rules := range [][]Rule{
|
||||
{{Path: "/", Mode: "unknown"}},
|
||||
{{Path: "/", Mode: Required}},
|
||||
{{Path: "/", Mode: Inherit, Engines: []Engine{engine}}},
|
||||
{{Path: "/", Mode: Monitor, Engines: []Engine{engine, engine}}},
|
||||
{{Path: "/", Mode: Disabled}, {Path: "/", Mode: Disabled}},
|
||||
} {
|
||||
if _, err := (Policy{Domain: domain, Generation: generation, Rules: rules}).Resolve("/p"); err == nil {
|
||||
t.Fatal("invalid policy accepted", rules)
|
||||
}
|
||||
}
|
||||
if _, err := (Policy{}).Resolve("/"); err == nil {
|
||||
t.Fatal("missing snapshot accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecisionCannotGrantAccess(t *testing.T) {
|
||||
p := Effective{Domain: domain, Generation: generation, Mode: Required, Engines: []Engine{engine}}
|
||||
hash := strings.Repeat("a", 64)
|
||||
now := time.Unix(1000, 0)
|
||||
good := Report{Key: Key{domain, generation, hash, engine}, State: Clean, Finished: now.Add(-time.Second), Expires: now.Add(time.Hour)}
|
||||
for _, mode := range []Mode{Disabled, Monitor, Required} {
|
||||
p.Mode = mode
|
||||
if d := Decide(false, p, hash, []Report{good}, []Engine{engine}, now); d.Allowed || d.Reason != "access_denied" {
|
||||
t.Fatal(d)
|
||||
}
|
||||
}
|
||||
p.Mode = Required
|
||||
if d := Decide(true, p, hash, []Report{good}, []Engine{engine}, now); !d.Allowed || d.State != Clean {
|
||||
t.Fatal(d)
|
||||
}
|
||||
for _, state := range []State{Pending, Suspicious, Malicious, Error, Expired, "unknown"} {
|
||||
r := good
|
||||
r.State = state
|
||||
if d := Decide(true, p, hash, []Report{r}, []Engine{engine}, now); d.Allowed {
|
||||
t.Fatal(state, d)
|
||||
}
|
||||
}
|
||||
for _, mutate := range []func(*Report){
|
||||
func(r *Report) { r.Key.Domain = generation },
|
||||
func(r *Report) { r.Key.Generation = domain },
|
||||
func(r *Report) { r.Key.Hash = strings.Repeat("b", 64) },
|
||||
func(r *Report) { r.Key.Engine.Definitions = "new" },
|
||||
func(r *Report) { r.Expires = now },
|
||||
func(r *Report) { r.Finished = now.Add(time.Hour) },
|
||||
} {
|
||||
r := good
|
||||
mutate(&r)
|
||||
if d := Decide(true, p, hash, []Report{r}, []Engine{engine}, now); d.Allowed {
|
||||
t.Fatal("stale/wrong evidence accepted", d)
|
||||
}
|
||||
}
|
||||
if d := Decide(true, p, hash, []Report{good}, nil, now); d.Allowed || d.Reason != "engine_unavailable" {
|
||||
t.Fatal(d)
|
||||
}
|
||||
if d := Decide(true, p, hash, []Report{good, good}, []Engine{engine}, now); d.Allowed {
|
||||
t.Fatal("ambiguous evidence", d)
|
||||
}
|
||||
p.Mode = Monitor
|
||||
bad := good
|
||||
bad.State = Malicious
|
||||
if d := Decide(true, p, hash, []Report{bad}, []Engine{engine}, now); !d.Allowed || d.State != Malicious {
|
||||
t.Fatal("monitor changed access or hid verdict", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryRequiredEngineMustPass(t *testing.T) {
|
||||
second := Engine{"test.second", "1", "defs"}
|
||||
now := time.Now()
|
||||
hash := strings.Repeat("b", 64)
|
||||
p := Effective{Domain: domain, Generation: generation, Mode: Required, Engines: []Engine{engine, second}}
|
||||
r := Report{Key: Key{domain, generation, hash, engine}, State: Clean, Finished: now.Add(-time.Second), Expires: now.Add(time.Minute)}
|
||||
if d := Decide(true, p, hash, []Report{r}, []Engine{engine, second}, now); d.Allowed {
|
||||
t.Fatal(d)
|
||||
}
|
||||
r2 := r
|
||||
r2.Key.Engine = second
|
||||
if d := Decide(true, p, hash, []Report{r, r2}, []Engine{engine, second}, now); !d.Allowed {
|
||||
t.Fatal(d)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package inspection
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/geduldh"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnavailable = errors.New("inspection engine unavailable or changed")
|
||||
ErrExternal = errors.New("external inspection is not permitted")
|
||||
ErrBusy = errors.New("inspection capacity exhausted")
|
||||
ErrInput = errors.New("inspection input invalid or too large")
|
||||
ErrEngine = errors.New("inspection engine failed")
|
||||
)
|
||||
|
||||
type Manifest struct {
|
||||
Engine Engine
|
||||
External bool
|
||||
}
|
||||
|
||||
// Scanner implementations are trusted, registered by application code. A
|
||||
// manifest is not permission to run a command, import code or connect a URL.
|
||||
// Inspect must honor ctx; in-process plugins are NOT a process sandbox.
|
||||
// The reader is valid only during Inspect and contains no Path or credential.
|
||||
type Scanner interface {
|
||||
Inspect(context.Context, io.Reader) (State, error)
|
||||
}
|
||||
type registration struct {
|
||||
manifest Manifest
|
||||
scanner Scanner
|
||||
enabled bool
|
||||
epoch uint64
|
||||
}
|
||||
type Registry struct {
|
||||
mu sync.RWMutex
|
||||
entries map[string]registration
|
||||
}
|
||||
|
||||
func NewRegistry() *Registry { return &Registry{entries: map[string]registration{}} }
|
||||
|
||||
// Register always starts disabled. Changing a definition version requires a
|
||||
// new registry registration/application lifecycle, never an in-place mutation.
|
||||
func (r *Registry) Register(m Manifest, scanner Scanner) error {
|
||||
if !m.Engine.valid() || scanner == nil {
|
||||
return ErrPolicy
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if _, ok := r.entries[m.Engine.ID]; ok {
|
||||
return ErrPolicy
|
||||
}
|
||||
if len(r.entries) >= 64 {
|
||||
return ErrPolicy
|
||||
}
|
||||
if r.entries == nil {
|
||||
r.entries = map[string]registration{}
|
||||
}
|
||||
r.entries[m.Engine.ID] = registration{manifest: m, scanner: scanner}
|
||||
return nil
|
||||
}
|
||||
func (r *Registry) SetEnabled(id string, enabled bool) error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
e, ok := r.entries[id]
|
||||
if !ok {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if e.enabled != enabled {
|
||||
e.epoch++
|
||||
e.enabled = enabled
|
||||
r.entries[id] = e
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (r *Registry) Active() []Engine {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
var out []Engine
|
||||
for _, e := range r.entries {
|
||||
if e.enabled {
|
||||
out = append(out, e.manifest.Engine)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out
|
||||
}
|
||||
func (r *Registry) acquire(engine Engine) (registration, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
e, ok := r.entries[engine.ID]
|
||||
if !ok || !e.enabled || e.manifest.Engine != engine {
|
||||
return registration{}, ErrUnavailable
|
||||
}
|
||||
return e, nil
|
||||
}
|
||||
|
||||
type Limits struct {
|
||||
Workers int
|
||||
MaxBytes int64
|
||||
Timeout time.Duration
|
||||
ResultTTL time.Duration
|
||||
}
|
||||
type Metrics struct {
|
||||
Running int64
|
||||
Completed uint64
|
||||
Failed uint64
|
||||
BytesVerified uint64
|
||||
DurationNS uint64
|
||||
}
|
||||
type Runner struct {
|
||||
registry *Registry
|
||||
limits Limits
|
||||
slots chan struct{}
|
||||
running atomic.Int64
|
||||
completed atomic.Uint64
|
||||
failed atomic.Uint64
|
||||
bytes atomic.Uint64
|
||||
duration atomic.Uint64
|
||||
}
|
||||
|
||||
func NewRunner(registry *Registry, limits Limits) (*Runner, error) {
|
||||
if registry == nil || limits.Workers < 1 || limits.Workers > 4 || limits.MaxBytes < 1 || limits.MaxBytes > 256<<20 || limits.Timeout <= 0 || limits.Timeout > time.Minute || limits.ResultTTL <= 0 || limits.ResultTTL > 24*time.Hour {
|
||||
return nil, ErrPolicy
|
||||
}
|
||||
return &Runner{registry: registry, limits: limits, slots: make(chan struct{}, limits.Workers)}, nil
|
||||
}
|
||||
func (r *Runner) Metrics() Metrics {
|
||||
return Metrics{r.running.Load(), r.completed.Load(), r.failed.Load(), r.bytes.Load(), r.duration.Load()}
|
||||
}
|
||||
|
||||
// Recheck reloads current job ownership, policy generation, topology and
|
||||
// external-transmission consent. It runs before opening bytes and again before
|
||||
// returning a report. The persistence layer must still CAS the lease/generation
|
||||
// on commit; this callback is not an atomic database transaction.
|
||||
type Recheck func(context.Context, Key) error
|
||||
|
||||
// Run is for a background worker, never a synchronous HTTP request. Capacity
|
||||
// exhaustion returns immediately so the existing scheduler can defer the job.
|
||||
// Documents must satisfy Geduldh's immutable Store contract. Verify before
|
||||
// handing bytes to a scanner (especially an external service).
|
||||
func (r *Runner) Run(ctx context.Context, documents geduldh.Store, key Key, allowExternal bool, recheck Recheck) (report Report, err error) {
|
||||
if !key.valid() || documents == nil || recheck == nil {
|
||||
return Report{}, ErrInput
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
entry, err := r.registry.acquire(key.Engine)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
if entry.manifest.External && !allowExternal {
|
||||
return Report{}, ErrExternal
|
||||
}
|
||||
select {
|
||||
case r.slots <- struct{}{}:
|
||||
default:
|
||||
return Report{}, ErrBusy
|
||||
}
|
||||
start := time.Now()
|
||||
r.running.Add(1)
|
||||
defer func() {
|
||||
// Never leak a plugin panic or diagnostic (which may contain payloads).
|
||||
if recover() != nil {
|
||||
report = Report{}
|
||||
err = ErrEngine
|
||||
}
|
||||
r.running.Add(-1)
|
||||
<-r.slots
|
||||
r.duration.Add(uint64(time.Since(start)))
|
||||
if err != nil {
|
||||
report = Report{}
|
||||
r.failed.Add(1)
|
||||
} else {
|
||||
r.completed.Add(1)
|
||||
}
|
||||
}()
|
||||
ctx, cancel := context.WithTimeout(ctx, r.limits.Timeout)
|
||||
defer cancel()
|
||||
check := func() error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := r.registry.acquire(key.Engine)
|
||||
if err != nil || current.epoch != entry.epoch {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if recheck(ctx, key) != nil {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err = check(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
info, err := documents.Stat(ctx, key.Hash)
|
||||
if ctx.Err() != nil {
|
||||
return Report{}, ctx.Err()
|
||||
}
|
||||
if err != nil || info.Hash != key.Hash || info.Size < 0 || info.Size > r.limits.MaxBytes {
|
||||
return Report{}, ErrInput
|
||||
}
|
||||
reader, err := documents.Open(ctx, key.Hash)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return Report{}, ctx.Err()
|
||||
}
|
||||
return Report{}, ErrInput
|
||||
}
|
||||
defer reader.Close()
|
||||
hash := sha256.New()
|
||||
n, err := io.Copy(hash, io.LimitReader(contextReader{ctx, reader}, info.Size+1))
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return Report{}, ctx.Err()
|
||||
}
|
||||
return Report{}, ErrInput
|
||||
}
|
||||
if n != info.Size || hex.EncodeToString(hash.Sum(nil)) != key.Hash {
|
||||
return Report{}, ErrInput
|
||||
}
|
||||
r.bytes.Add(uint64(n))
|
||||
if _, err = reader.Seek(0, io.SeekStart); err != nil {
|
||||
return Report{}, ErrInput
|
||||
}
|
||||
if err = check(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
state, err := entry.scanner.Inspect(ctx, io.LimitReader(contextReader{ctx, reader}, info.Size))
|
||||
if ctx.Err() != nil {
|
||||
return Report{}, ctx.Err()
|
||||
}
|
||||
if err != nil {
|
||||
return Report{}, ErrEngine
|
||||
}
|
||||
if state != Clean && state != Suspicious && state != Malicious {
|
||||
return Report{}, ErrEngine
|
||||
}
|
||||
if err = check(); err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
now := time.Now()
|
||||
return Report{Key: key, State: state, Finished: now, Expires: now.Add(r.limits.ResultTTL)}, nil
|
||||
}
|
||||
|
||||
type contextReader struct {
|
||||
ctx context.Context
|
||||
reader io.Reader
|
||||
}
|
||||
|
||||
func (r contextReader) Read(b []byte) (int, error) {
|
||||
if err := r.ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return r.reader.Read(b)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package inspection
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"pageswiki/internal/geduldh"
|
||||
)
|
||||
|
||||
type scanFunc func(context.Context, io.Reader) (State, error)
|
||||
|
||||
func (f scanFunc) Inspect(ctx context.Context, r io.Reader) (State, error) { return f(ctx, r) }
|
||||
|
||||
type testReader struct{ *bytes.Reader }
|
||||
|
||||
func (*testReader) Close() error { return nil }
|
||||
|
||||
type testDocuments struct {
|
||||
payload []byte
|
||||
size int64
|
||||
opens atomic.Int64
|
||||
}
|
||||
|
||||
func (d *testDocuments) Stat(_ context.Context, h string) (geduldh.Info, error) {
|
||||
return geduldh.Info{Hash: h, Size: d.size}, nil
|
||||
}
|
||||
func (d *testDocuments) Open(context.Context, string) (geduldh.Reader, error) {
|
||||
d.opens.Add(1)
|
||||
return &testReader{bytes.NewReader(d.payload)}, nil
|
||||
}
|
||||
func (*testDocuments) Verify(context.Context, string) error {
|
||||
panic("runner must verify the bytes itself")
|
||||
}
|
||||
func (*testDocuments) PutIfAbsent(context.Context, string, int64, io.Reader) error {
|
||||
panic("runner must never modify documents")
|
||||
}
|
||||
func fixture(t *testing.T, external bool, fn scanFunc) (*Runner, *Registry, *testDocuments, Key) {
|
||||
t.Helper()
|
||||
reg := NewRegistry()
|
||||
if err := reg.Register(Manifest{engine, external}, fn); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r, err := NewRunner(reg, Limits{Workers: 1, MaxBytes: 1024, Timeout: time.Second, ResultTTL: time.Hour})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := []byte("synthetic input, not a real user document")
|
||||
sum := sha256.Sum256(body)
|
||||
return r, reg, &testDocuments{payload: body, size: int64(len(body))}, Key{domain, generation, hex.EncodeToString(sum[:]), engine}
|
||||
}
|
||||
func current(context.Context, Key) error { return nil }
|
||||
|
||||
func TestRunnerDisabledExternalAndHashGates(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
r, reg, docs, key := fixture(t, true, func(ctx context.Context, reader io.Reader) (State, error) {
|
||||
calls.Add(1)
|
||||
_, err := io.Copy(io.Discard, reader)
|
||||
return Clean, err
|
||||
})
|
||||
if _, err := r.Run(context.Background(), docs, key, true, current); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := reg.SetEnabled(engine.ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Run(context.Background(), docs, key, false, current); !errors.Is(err, ErrExternal) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if docs.opens.Load() != 0 || calls.Load() != 0 {
|
||||
t.Fatal("read before consent")
|
||||
}
|
||||
bad := key
|
||||
bad.Hash = strings.Repeat("a", 64)
|
||||
if _, err := r.Run(context.Background(), docs, bad, true, current); !errors.Is(err, ErrInput) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls.Load() != 0 {
|
||||
t.Fatal("corrupt content sent to plugin")
|
||||
}
|
||||
report, err := r.Run(context.Background(), docs, key, true, current)
|
||||
if err != nil || report.State != Clean || report.Key != key || calls.Load() != 1 || !report.Expires.After(report.Finished) {
|
||||
t.Fatal(report, err)
|
||||
}
|
||||
m := r.Metrics()
|
||||
if m.Completed != 1 || m.Failed != 1 || m.Running != 0 || m.BytesVerified != uint64(docs.size) {
|
||||
t.Fatal(m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerCapacityAndDisableDuringScan(t *testing.T) {
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
r, reg, docs, key := fixture(t, false, func(ctx context.Context, reader io.Reader) (State, error) {
|
||||
close(started)
|
||||
<-release
|
||||
return Clean, nil
|
||||
})
|
||||
if err := reg.SetEnabled(engine.ID, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := r.Run(context.Background(), docs, key, false, current); done <- err }()
|
||||
<-started
|
||||
_, busy := r.Run(context.Background(), docs, key, false, current)
|
||||
_ = reg.SetEnabled(engine.ID, false)
|
||||
_ = reg.SetEnabled(engine.ID, true) // Even an immediate toggle invalidates this run.
|
||||
close(release)
|
||||
err := <-done
|
||||
if !errors.Is(busy, ErrBusy) || !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal(busy, err)
|
||||
}
|
||||
if m := r.Metrics(); m.Running != 0 || m.Completed != 0 || m.Failed != 1 {
|
||||
t.Fatal(m)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerBoundedFailureAndRecheck(t *testing.T) {
|
||||
for _, kind := range []string{"panic", "error", "invalid", "timeout", "stale", "oversize", "wrong-size"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
var calls atomic.Int64
|
||||
r, reg, docs, key := fixture(t, false, func(ctx context.Context, _ io.Reader) (State, error) {
|
||||
calls.Add(1)
|
||||
switch kind {
|
||||
case "panic":
|
||||
panic("private document text")
|
||||
case "error":
|
||||
return Clean, errors.New("private text")
|
||||
case "invalid":
|
||||
return Pending, nil
|
||||
case "timeout":
|
||||
<-ctx.Done()
|
||||
return Clean, nil
|
||||
}
|
||||
return Clean, nil
|
||||
})
|
||||
_ = reg.SetEnabled(engine.ID, true)
|
||||
if kind == "oversize" {
|
||||
docs.size = 1025
|
||||
}
|
||||
if kind == "wrong-size" {
|
||||
docs.size--
|
||||
}
|
||||
if kind == "timeout" {
|
||||
r.limits.Timeout = 10 * time.Millisecond
|
||||
}
|
||||
checks := 0
|
||||
recheck := func(context.Context, Key) error {
|
||||
checks++
|
||||
if kind == "stale" && checks == 3 {
|
||||
return errors.New("private policy")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
report, err := r.Run(context.Background(), docs, key, false, recheck)
|
||||
if err == nil || strings.Contains(err.Error(), "private") || report != (Report{}) {
|
||||
t.Fatal(report, err)
|
||||
}
|
||||
if (kind == "oversize" || kind == "wrong-size") && calls.Load() != 0 {
|
||||
t.Fatal("invalid data reached plugin")
|
||||
}
|
||||
if kind == "timeout" && !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Metrics().Running != 0 {
|
||||
t.Fatal("worker slot leaked")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerRequiresFreshSnapshot(t *testing.T) {
|
||||
r, reg, docs, key := fixture(t, false, func(context.Context, io.Reader) (State, error) { t.Fatal("plugin called"); return Clean, nil })
|
||||
_ = reg.SetEnabled(engine.ID, true)
|
||||
if _, err := r.Run(context.Background(), docs, key, false, nil); !errors.Is(err, ErrInput) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.Run(context.Background(), docs, key, false, func(context.Context, Key) error { return ErrPolicy }); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := r.Run(ctx, docs, key, false, current); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if docs.opens.Load() != 0 {
|
||||
t.Fatal("stale job opened payload")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectionLifecycleDoesNotPublishOrBypassAliases(t *testing.T) {
|
||||
r, registry, docs, key := fixture(t, false, func(_ context.Context, reader io.Reader) (State, error) {
|
||||
_, err := io.Copy(io.Discard, reader)
|
||||
return Clean, err
|
||||
})
|
||||
p := Policy{Domain: domain, Generation: generation, Rules: []Rule{{Path: "/private", Mode: Required, Engines: []Engine{engine}}}}
|
||||
bindings := []string{"/open/alias", "/private/source"}
|
||||
gate := func(acl bool, reports []Report) Decision {
|
||||
return DecidePaths(acl, p, bindings, key.Hash, reports, registry.Active(), time.Now())
|
||||
}
|
||||
_ = registry.SetEnabled(engine.ID, true)
|
||||
if d := gate(true, nil); d.Allowed || d.State != Pending {
|
||||
t.Fatal("unscanned alias allowed", d)
|
||||
}
|
||||
report, err := r.Run(context.Background(), docs, key, false, current)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := gate(true, []Report{report}); !d.Allowed {
|
||||
t.Fatal(d)
|
||||
}
|
||||
if d := gate(false, []Report{report}); d.Allowed {
|
||||
t.Fatal("scan published private file", d)
|
||||
}
|
||||
_ = registry.SetEnabled(engine.ID, false)
|
||||
if d := gate(true, []Report{report}); d.Allowed {
|
||||
t.Fatal("disabled plugin bypass", d)
|
||||
}
|
||||
_ = registry.SetEnabled(engine.ID, true)
|
||||
p.Generation = "00000000-0000-4000-8000-000000000003"
|
||||
if d := gate(true, []Report{report}); d.Allowed {
|
||||
t.Fatal("stale policy result", d)
|
||||
}
|
||||
if d := DecidePaths(true, p, nil, key.Hash, nil, registry.Active(), time.Now()); d.Allowed {
|
||||
t.Fatal("missing bindings accepted", d)
|
||||
}
|
||||
}
|
||||
@@ -227,4 +227,9 @@ func textMediaType(descriptor Descriptor) bool {
|
||||
}
|
||||
|
||||
// Catalog returns a copy; callers cannot reorder or disable the shared registry.
|
||||
func Catalog() []Adapter { return append([]Adapter(nil), projectionAdapters...) }
|
||||
func Catalog() []Adapter {
|
||||
items := append([]Adapter(nil), projectionAdapters...)
|
||||
// Explicitly selected projection. It must not replace normal HTML/text
|
||||
// viewing in the automatic MIME classifier.
|
||||
return append(items, Adapter{ID: "reveal", Kind: "slides", Delivery: DeliveryRawFrame, Match: func(Descriptor) bool { return false }})
|
||||
}
|
||||
@@ -47,7 +47,7 @@ func TestAdapterCatalogIsCopyAndConcurrent(t *testing.T) {
|
||||
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" {
|
||||
if strings.Join(ids, ",") != "html,excalidraw,csv,archive,debian-package,eml,pe,json,text,image,audio,video,pdf,download,reveal" {
|
||||
t.Fatal("catalog order changed", ids)
|
||||
}
|
||||
catalog[0].ID = "corrupt"
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// Package machinelearning implements the private Pages Machine Learning v1
|
||||
// transport. Callers must authorize corpus scope and external transmission,
|
||||
// enqueue work, and recheck revision/policy generations before persisting results.
|
||||
// This package does not discover documents, retry requests, or change City paths.
|
||||
package machinelearning
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const maxBody = 128 * 1024
|
||||
const maxResponse = 2 * 1024 * 1024
|
||||
|
||||
var safeToken = regexp.MustCompile(`^[A-Za-z0-9_-]{32,256}$`)
|
||||
var safeID = regexp.MustCompile(`^[A-Za-z0-9_.:-]{1,128}$`)
|
||||
var modelHash = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||
|
||||
type Input struct {
|
||||
ID string `json:"id"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
Protocol string `json:"protocol"`
|
||||
DomainUUID string `json:"domain_uuid"`
|
||||
ScopeUUID string `json:"scope_uuid"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
Dimensions int `json:"dimensions"`
|
||||
Inputs []Input `json:"inputs"`
|
||||
AllowExternal bool `json:"allow_external"`
|
||||
}
|
||||
|
||||
type Output struct {
|
||||
ID string `json:"id"`
|
||||
InputSHA256 string `json:"input_sha256"`
|
||||
Vector []float64 `json:"vector"`
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Protocol string `json:"protocol"`
|
||||
DomainUUID string `json:"domain_uuid"`
|
||||
ScopeUUID string `json:"scope_uuid"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
ModelRevision string `json:"model_revision"`
|
||||
Dimensions int `json:"dimensions"`
|
||||
Tokenizer string `json:"tokenizer"`
|
||||
Outputs []Output `json:"outputs"`
|
||||
Usage struct {
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
|
||||
// StatusError intentionally excludes the remote response body and request URL.
|
||||
// Retry scheduling belongs to Pages; failures can include uncertain API charges.
|
||||
type StatusError struct{ Status int }
|
||||
|
||||
func (e *StatusError) Error() string { return fmt.Sprintf("machine learning HTTP status %d", e.Status) }
|
||||
|
||||
type Client struct {
|
||||
endpoint string
|
||||
token string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// NewClient accepts an operator-configured private service origin, never a
|
||||
// document-provided URL. HTTP is for an isolated local network only; use HTTPS
|
||||
// and network access control for remote hosts. There is no insecure TLS option.
|
||||
func NewClient(origin, token string) (*Client, error) {
|
||||
u, err := url.Parse(origin)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || (u.Path != "" && u.Path != "/") || !safeToken.MatchString(token) {
|
||||
return nil, errors.New("invalid machine learning service configuration")
|
||||
}
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.Proxy = nil // Do not leak the private shared token to an env proxy.
|
||||
return &Client{endpoint: strings.TrimSuffix(origin, "/") + "/v1/embeddings", token: token,
|
||||
http: &http.Client{Transport: transport, Timeout: 40 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
|
||||
}
|
||||
|
||||
func validUUID(s string) bool { id, err := uuid.Parse(s); return err == nil && id.String() == s }
|
||||
|
||||
func validate(req Request) error {
|
||||
if req.Protocol != "1" || !validUUID(req.DomainUUID) || !validUUID(req.ScopeUUID) || req.Dimensions < 1 || req.Dimensions > 1536 || len(req.Inputs) < 1 || len(req.Inputs) > 16 {
|
||||
return errors.New("invalid machine learning request")
|
||||
}
|
||||
if req.Provider == "openai" {
|
||||
if !req.AllowExternal || req.Model != "text-embedding-3-small" {
|
||||
return errors.New("external embeddings not permitted or unsupported model")
|
||||
}
|
||||
} else if req.Provider != "doc2vec" || !modelHash.MatchString(req.Model) {
|
||||
return errors.New("invalid machine learning provider/model")
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
for _, input := range req.Inputs {
|
||||
if !safeID.MatchString(input.ID) || seen[input.ID] || strings.TrimSpace(input.Text) == "" || !utf8.ValidString(input.Text) || len(input.Text) > 6000 {
|
||||
return errors.New("invalid machine learning input")
|
||||
}
|
||||
seen[input.ID] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Embed(ctx context.Context, input Request) (*Result, error) {
|
||||
if err := validate(input); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil || len(body) > maxBody {
|
||||
return nil, errors.New("machine learning input too large")
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, errors.New("machine learning request failed")
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
response, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return nil, errors.New("machine learning transport failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, &StatusError{Status: response.StatusCode}
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(response.Body, maxResponse+1))
|
||||
if err != nil || len(raw) > maxResponse {
|
||||
return nil, errors.New("invalid machine learning response")
|
||||
}
|
||||
var result Result
|
||||
if json.Unmarshal(raw, &result) != nil || result.Protocol != input.Protocol || result.DomainUUID != input.DomainUUID || result.ScopeUUID != input.ScopeUUID || result.Provider != input.Provider || result.Model != input.Model || result.ModelRevision != input.Model || result.Dimensions != input.Dimensions || len(result.Outputs) != len(input.Inputs) || result.Usage.TotalTokens < 0 {
|
||||
return nil, errors.New("machine learning result metadata mismatch")
|
||||
}
|
||||
expectedTokenizer := "provider"
|
||||
if input.Provider == "doc2vec" {
|
||||
expectedTokenizer = "unicode-cjk-bigram-v1"
|
||||
}
|
||||
if result.Tokenizer != expectedTokenizer {
|
||||
return nil, errors.New("machine learning tokenizer mismatch")
|
||||
}
|
||||
for i, output := range result.Outputs {
|
||||
hash := sha256.Sum256([]byte(input.Inputs[i].Text))
|
||||
if output.ID != input.Inputs[i].ID || output.InputSHA256 != hex.EncodeToString(hash[:]) || len(output.Vector) != input.Dimensions {
|
||||
return nil, errors.New("machine learning output mismatch")
|
||||
}
|
||||
nonzero := false
|
||||
for _, value := range output.Vector {
|
||||
if math.IsNaN(value) || math.IsInf(value, 0) {
|
||||
return nil, errors.New("non-finite machine learning vector")
|
||||
}
|
||||
nonzero = nonzero || value != 0
|
||||
}
|
||||
if !nonzero {
|
||||
return nil, errors.New("empty machine learning vector")
|
||||
}
|
||||
}
|
||||
return &result, nil
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package machinelearning
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func fixture() Request {
|
||||
return Request{Protocol: "1", DomainUUID: "11111111-1111-4111-8111-111111111111", ScopeUUID: "22222222-2222-4222-8222-222222222222", Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 2, Inputs: []Input{{ID: "page:chunk0", Text: "合成文書 library books"}}}
|
||||
}
|
||||
|
||||
func resultFor(req Request) Result {
|
||||
r := Result{Protocol: req.Protocol, DomainUUID: req.DomainUUID, ScopeUUID: req.ScopeUUID, Provider: req.Provider, Model: req.Model, ModelRevision: req.Model, Dimensions: req.Dimensions, Tokenizer: "unicode-cjk-bigram-v1"}
|
||||
for _, item := range req.Inputs {
|
||||
hash := sha256.Sum256([]byte(item.Text))
|
||||
r.Outputs = append(r.Outputs, Output{ID: item.ID, InputSHA256: hex.EncodeToString(hash[:]), Vector: []float64{0.5, -0.2}})
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestClient(t *testing.T) {
|
||||
req := fixture()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
mutate func(*Result)
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid", func(*Result) {}, false},
|
||||
{"wrong-domain", func(r *Result) { r.DomainUUID = req.ScopeUUID }, true},
|
||||
{"wrong-scope", func(r *Result) { r.ScopeUUID = req.DomainUUID }, true},
|
||||
{"wrong-hash", func(r *Result) { r.Outputs[0].InputSHA256 = "wrong" }, true},
|
||||
{"wrong-dimensions", func(r *Result) { r.Outputs[0].Vector = []float64{1} }, true},
|
||||
{"wrong-model", func(r *Result) { r.ModelRevision = "other" }, true},
|
||||
{"wrong-tokenizer", func(r *Result) { r.Tokenizer = "other" }, true},
|
||||
{"zero", func(r *Result) { r.Outputs[0].Vector = []float64{0, 0} }, true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/embeddings" || r.Method != "POST" || r.Header.Get("Authorization") != "Bearer "+strings.Repeat("t", 40) {
|
||||
t.Error("request contract")
|
||||
}
|
||||
var sent Request
|
||||
if err := json.NewDecoder(r.Body).Decode(&sent); err != nil || sent.Inputs[0].Text != req.Inputs[0].Text {
|
||||
t.Error("input changed")
|
||||
}
|
||||
result := resultFor(req)
|
||||
test.mutate(&result)
|
||||
_ = json.NewEncoder(w).Encode(result)
|
||||
}))
|
||||
defer server.Close()
|
||||
client, err := NewClient(server.URL, strings.Repeat("t", 40))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = client.Embed(context.Background(), req)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoRedirectRetryOrSecretErrors(t *testing.T) {
|
||||
calls := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
w.Header().Set("Location", "/secret")
|
||||
w.WriteHeader(307)
|
||||
_, _ = w.Write([]byte("secret provider body"))
|
||||
}))
|
||||
defer server.Close()
|
||||
client, _ := NewClient(server.URL, strings.Repeat("t", 40))
|
||||
_, err := client.Embed(context.Background(), fixture())
|
||||
var status *StatusError
|
||||
if !errors.As(err, &status) || status.Status != 307 || calls != 1 || strings.Contains(err.Error(), "secret") {
|
||||
t.Fatalf("redirect/error handling: %v calls=%d", err, calls)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err = client.Embed(ctx, fixture())
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestValidation(t *testing.T) {
|
||||
for _, mutate := range []func(*Request){
|
||||
func(r *Request) { r.DomainUUID = "../" }, func(r *Request) { r.Inputs[0].Text = strings.Repeat("x", 6001) },
|
||||
func(r *Request) { r.Provider = "openai"; r.Model = "text-embedding-3-small" },
|
||||
func(r *Request) { r.Inputs = append(r.Inputs, r.Inputs[0]) }, func(r *Request) { r.Dimensions = 1537 },
|
||||
} {
|
||||
req := fixture()
|
||||
mutate(&req)
|
||||
if validate(req) == nil {
|
||||
t.Fatal("accepted invalid request")
|
||||
}
|
||||
}
|
||||
for _, origin := range []string{"file:///tmp/x", "http://user:pass@localhost", "https://ml.invalid/path", "https://ml.invalid?x=1"} {
|
||||
if _, err := NewClient(origin, strings.Repeat("t", 40)); err == nil {
|
||||
t.Fatal("accepted origin", origin)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Optional end-to-end contract test against a local synthetic fixture service.
|
||||
// No real Pages documents, credentials, or paid OpenAI requests are used.
|
||||
func TestLocalDoc2VecService(t *testing.T) {
|
||||
origin := os.Getenv("PAGES_ML_TEST_ORIGIN")
|
||||
if origin == "" {
|
||||
t.Skip("set PAGES_ML_TEST_ORIGIN for synthetic service integration")
|
||||
}
|
||||
client, err := NewClient(origin, strings.Repeat("t", 40))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := fixture()
|
||||
req.Model = os.Getenv("PAGES_ML_TEST_MODEL")
|
||||
req.Dimensions = 8
|
||||
result, err := client.Embed(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Outputs) != 1 || len(result.Outputs[0].Vector) != 8 {
|
||||
t.Fatal("wrong result shape")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package machinelearning
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var ErrPolicy = errors.New("invalid machine learning policy")
|
||||
var ErrNotAllowed = errors.New("machine learning scope is disabled, stale or excluded")
|
||||
|
||||
// Policy contains no credentials. Generation changes on every saved update,
|
||||
// including disable/re-enable, so queued work cannot reuse old consent.
|
||||
type Policy struct {
|
||||
Generation string `json:"generation"`
|
||||
Enabled bool `json:"enabled"`
|
||||
ScopeUUID string `json:"scope_uuid"`
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
Dimensions int `json:"dimensions"`
|
||||
Prefixes []string `json:"prefixes"`
|
||||
Exclude []string `json:"exclude"`
|
||||
AllowExternal bool `json:"allow_external"`
|
||||
MaxBatchBytes int `json:"max_batch_bytes"`
|
||||
DailyInputBytes int64 `json:"daily_input_bytes"`
|
||||
}
|
||||
|
||||
// Canonical paths are decoded logical Wiki paths, not URLs or raw request URIs.
|
||||
// Reject ambiguous encodings instead of silently broadening a configured scope.
|
||||
func canonicalPath(p string) bool {
|
||||
return utf8.ValidString(p) && len(p) <= 4096 && strings.HasPrefix(p, "/") && path.Clean(p) == p &&
|
||||
!strings.ContainsAny(p, "%?#\\") && strings.IndexFunc(p, unicode.IsControl) < 0
|
||||
}
|
||||
|
||||
func (p Policy) Validate() error {
|
||||
if p.DailyInputBytes < 0 || p.DailyInputBytes > 1000000000 {
|
||||
return ErrPolicy
|
||||
}
|
||||
if !validUUID(p.Generation) {
|
||||
return ErrPolicy
|
||||
}
|
||||
// A new disabled configuration may have no model yet.
|
||||
if !p.Enabled && p.Provider == "" && p.ScopeUUID == "" && p.Model == "" && p.Dimensions == 0 && len(p.Prefixes) == 0 && len(p.Exclude) == 0 && !p.AllowExternal && p.MaxBatchBytes == 0 {
|
||||
return nil
|
||||
}
|
||||
if !validUUID(p.ScopeUUID) || p.Dimensions < 1 || p.Dimensions > 1536 || len(p.Prefixes) < 1 || len(p.Prefixes) > 64 || len(p.Exclude) > 64 || p.MaxBatchBytes < 1 || p.MaxBatchBytes > 96000 {
|
||||
return ErrPolicy
|
||||
}
|
||||
switch p.Provider {
|
||||
case "doc2vec":
|
||||
if !modelHash.MatchString(p.Model) || p.AllowExternal {
|
||||
return ErrPolicy
|
||||
}
|
||||
case "openai":
|
||||
if p.Model != "text-embedding-3-small" || (p.Enabled && !p.AllowExternal) {
|
||||
return ErrPolicy
|
||||
}
|
||||
default:
|
||||
return ErrPolicy
|
||||
}
|
||||
for _, paths := range [][]string{p.Prefixes, p.Exclude} {
|
||||
seen := map[string]bool{}
|
||||
for _, prefix := range paths {
|
||||
if !canonicalPath(prefix) || seen[prefix] {
|
||||
return ErrPolicy
|
||||
}
|
||||
seen[prefix] = true
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func under(p, prefix string) bool {
|
||||
return prefix == "/" || p == prefix || strings.HasPrefix(p, prefix+"/")
|
||||
}
|
||||
|
||||
// Allows is an additional scope check, NOT document authorization. Callers must
|
||||
// still check the current principal, revision, and learning cohort membership.
|
||||
func (p Policy) Allows(logicalPath, generation string) bool {
|
||||
if p.Validate() != nil || !p.Enabled || generation != p.Generation || !canonicalPath(logicalPath) {
|
||||
return false
|
||||
}
|
||||
for _, prefix := range p.Exclude {
|
||||
if under(logicalPath, prefix) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for _, prefix := range p.Prefixes {
|
||||
if under(logicalPath, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Prepare binds model and consent to a freshly loaded policy rather than to
|
||||
// caller-provided JSON. Inputs must be authorized chunks of this one document.
|
||||
// The batch limit is not a daily budget or a monetary cost ceiling.
|
||||
func (p Policy) Prepare(domain, logicalPath, generation string, inputs []Input) (Request, error) {
|
||||
if !p.Allows(logicalPath, generation) {
|
||||
return Request{}, ErrNotAllowed
|
||||
}
|
||||
bytes := 0
|
||||
for _, input := range inputs {
|
||||
bytes += len(input.Text)
|
||||
if bytes > p.MaxBatchBytes {
|
||||
return Request{}, ErrNotAllowed
|
||||
}
|
||||
}
|
||||
req := Request{Protocol: "1", DomainUUID: domain, ScopeUUID: p.ScopeUUID, Provider: p.Provider, Model: p.Model, Dimensions: p.Dimensions, Inputs: inputs, AllowExternal: p.AllowExternal}
|
||||
if err := validate(req); err != nil {
|
||||
return Request{}, err
|
||||
}
|
||||
// Do not retain caller-owned slice memory across a queued operation.
|
||||
req.Inputs = append([]Input(nil), inputs...)
|
||||
return req, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package machinelearning
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func policyFixture() Policy {
|
||||
return Policy{Generation: "33333333-3333-4333-8333-333333333333", Enabled: true, ScopeUUID: fixture().ScopeUUID, Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, Exclude: []string{"/lab/private"}, MaxBatchBytes: 12000}
|
||||
}
|
||||
|
||||
func TestPolicyPaths(t *testing.T) {
|
||||
p := policyFixture()
|
||||
for _, tc := range []struct {
|
||||
path string
|
||||
allow bool
|
||||
}{
|
||||
{"/lab", true}, {"/lab/文書", true}, {"/labs", false}, {"/lab/private", false}, {"/lab/private/child", false},
|
||||
{"/lab/private-other", true}, {"/lab/../secret", false}, {"/lab/%70rivate", false}, {"/lab//a", false}, {"https://example.com/lab", false}, {"/lab/a?b", false},
|
||||
} {
|
||||
if p.Allows(tc.path, p.Generation) != tc.allow {
|
||||
t.Errorf("path %q", tc.path)
|
||||
}
|
||||
}
|
||||
p.Prefixes = []string{"/"}
|
||||
if !p.Allows("/other", p.Generation) || p.Allows("/lab/private/x", p.Generation) {
|
||||
t.Fatal("root/exclusion")
|
||||
}
|
||||
if p.Allows("/lab", "stale") {
|
||||
t.Fatal("stale generation accepted")
|
||||
}
|
||||
p.Enabled = false
|
||||
if p.Allows("/lab", p.Generation) {
|
||||
t.Fatal("disabled scope accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyValidationAndPrepare(t *testing.T) {
|
||||
for _, mutate := range []func(*Policy){
|
||||
func(p *Policy) { p.Prefixes = []string{"/lab/"} }, func(p *Policy) { p.Exclude = []string{"relative"} },
|
||||
func(p *Policy) { p.AllowExternal = true }, func(p *Policy) { p.MaxBatchBytes = 0 },
|
||||
func(p *Policy) { p.Provider = "openai"; p.Model = "text-embedding-3-small" },
|
||||
} {
|
||||
p := policyFixture()
|
||||
mutate(&p)
|
||||
if p.Validate() == nil {
|
||||
t.Fatal("invalid policy accepted")
|
||||
}
|
||||
}
|
||||
p := policyFixture()
|
||||
inputs := []Input{{ID: "chunk:0", Text: "合成文書"}}
|
||||
req, err := p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
inputs[0].Text = "changed"
|
||||
if req.Inputs[0].Text == "changed" || req.AllowExternal {
|
||||
t.Fatal("input/consent binding")
|
||||
}
|
||||
p.MaxBatchBytes = 2
|
||||
if _, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs); err == nil {
|
||||
t.Fatal("batch budget")
|
||||
}
|
||||
p = policyFixture()
|
||||
p.Provider = "openai"
|
||||
p.Model = "text-embedding-3-small"
|
||||
p.AllowExternal = true
|
||||
req, err = p.Prepare(fixture().DomainUUID, "/lab/page", p.Generation, inputs)
|
||||
if err != nil || !req.AllowExternal {
|
||||
t.Fatalf("explicit external policy: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -36,6 +37,14 @@ type citySearchCandidate struct {
|
||||
// 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) {
|
||||
return searchCity(s.db, false, parent, domainUUID, scope, query, limit, allowed, options)
|
||||
}
|
||||
|
||||
func (s *PostgreSQL) SearchCityInDomain(parent context.Context, domainUUID, scope, query string, limit int, allowed func(string) bool, options SearchOptions) ([]CitySearchResult, error) {
|
||||
return searchCity(s.db, true, parent, domainUUID, scope, query, limit, allowed, options)
|
||||
}
|
||||
|
||||
func searchCity(database *sql.DB, native bool, 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
|
||||
}
|
||||
@@ -58,7 +67,7 @@ func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, q
|
||||
searchErr = ctx.Err()
|
||||
}
|
||||
}()
|
||||
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
|
||||
tx, err := database.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -70,22 +79,35 @@ func (s *SQLite) SearchCityInDomain(parent context.Context, domainUUID, scope, q
|
||||
sql.Named("prefix", prefix), sql.Named("upper", upper),
|
||||
sql.Named("query", query), sql.Named("limit", CitySearchCandidateLimit),
|
||||
}
|
||||
if native {
|
||||
args = []any{domainUUID, scope, prefix, upper, query, 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 native {
|
||||
args = append(args, *options.FromMS)
|
||||
dateWhere += " AND " + dateColumn + ">=" + fmt.Sprintf("$%d", len(args))
|
||||
} else {
|
||||
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))
|
||||
if native {
|
||||
args = append(args, *options.BeforeMS)
|
||||
dateWhere += " AND " + dateColumn + "<" + fmt.Sprintf("$%d", len(args))
|
||||
} else {
|
||||
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...)
|
||||
rows, err := tx.QueryContext(ctx, citySearchDialectSQL(kind, dateWhere, native), args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -173,6 +195,18 @@ func citySearchKindOrder(kind string) int {
|
||||
// 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 {
|
||||
return citySearchDialectSQL(kind, dateWhere, false)
|
||||
}
|
||||
|
||||
func citySearchDialectSQL(kind, dateWhere string, native bool) string {
|
||||
domain, scope, prefix, upper, query, limit := ":domain", ":scope", ":prefix", ":upper", ":query", ":limit"
|
||||
collation, position, greatest := " COLLATE BINARY", "instr", "max"
|
||||
absolute := citySearchAbsolutePathSQL
|
||||
if native {
|
||||
domain, scope, prefix, upper, query, limit = "$1", "$2", "$3", "$4", "$5", "$6"
|
||||
collation, position, greatest = ` COLLATE "C"`, "strpos", "greatest"
|
||||
absolute = func(column string) string { return `(substr(` + column + `,1,1)='/' AND length(` + column + `)<=4096)` }
|
||||
}
|
||||
from, description := "zones n", "n.description"
|
||||
navigationPath := "n.path_prefix"
|
||||
parentColumns := "'','','','',''"
|
||||
@@ -181,28 +215,32 @@ func citySearchSQL(kind, dateWhere string) string {
|
||||
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")
|
||||
where = "n.kind='street' AND " + absolute("q.path_prefix")
|
||||
case "spot":
|
||||
navigationPath = `CASE WHEN substr(n.path_prefix,-11)='/_undefined' THEN st.path_prefix ELSE n.path_prefix END`
|
||||
if native {
|
||||
navigationPath = `CASE WHEN right(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")
|
||||
where = absolute("q.path_prefix") + " AND " + absolute("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)`
|
||||
contains := func(column string) string { return position + "(lower(" + column + "),lower(" + query + "))" }
|
||||
nameMatch := `(` + query + `!='' AND (` + contains("n.name") + `>0 OR ` + contains("n.title") + `>0))`
|
||||
pathMatch := `(` + query + `!='' AND ` + contains("n.path_prefix") + `>0)`
|
||||
descriptionMatch := `(` + query + `!='' AND ` + contains(description) + `>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),
|
||||
substr(` + description + `,` + greatest + `(1,` + contains(description) + `-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`
|
||||
FROM ` + from + ` WHERE n.domain_uuid=` + domain + ` AND n.state!='archived' AND ` + where + `
|
||||
AND ` + absolute("n.path_prefix") + `
|
||||
AND (n.path_prefix` + collation + `=` + scope + ` OR (n.path_prefix` + collation + `>=` + prefix + ` AND n.path_prefix` + collation + `<` + upper + `))
|
||||
AND (` + query + `='' OR ` + nameMatch + ` OR ` + pathMatch + ` OR ` + descriptionMatch + `)` + dateWhere + `
|
||||
ORDER BY ` + nameMatch + ` DESC,` + pathMatch + ` DESC,n.path_prefix` + collation + `,n.uuid LIMIT ` + limit
|
||||
}
|
||||
|
||||
func citySearchAbsolutePathSQL(column string) string {
|
||||
|
||||
Loaded 100 of 498 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user