fix(all): repair update application, notices and development startup

Add schedules as a branch of the existing signed update flow and support same-version GameData updates with fingerprint-checked handoffs.

Fix development plugin caching, cancellation handling, plugin compatibility reporting and notice navigation.
This commit is contained in:
Flechazo committed 2026-10-16 22:04:32 +08:00
1 parent e96232b779
commit 17a467043a
38 files changed
+1191 -220

No files matched your search

+4 -1
View File
@@ -15,6 +15,9 @@ import (
func main() {
if err := run(os.Args[1:]); err != nil {
if errors.Is(err, context.Canceled) {
os.Exit(130)
}
fmt.Fprintln(os.Stderr, "bd2w:", err)
var child *exec.ExitError
if errors.As(err, &child) && child.ExitCode() > 0 {
@@ -27,7 +30,7 @@ func main() {
func usage() {
fmt.Println(`Usage:
bd2w build [-GameDir directory] [-SkipTests] [-SchedulesOnly]
bd2w release changelog --component server|client [--bump patch] | publish [--no-announcement]
bd2w release changelog --component server|client [--bump patch] | publish [--no-announcement] [--component all|schedules]
bd2w runClient [client options]
bd2w runClient2 [--instance player2] [--game-dir directory]
bd2w plugins [--game-dir directory]
+1 -1
View File
@@ -60,7 +60,7 @@ func (t task) command(program string, args ...string) error {
cmd.Stderr = os.Stderr
cmd.Env = replaceEnvironment(os.Environ(), map[string]string{"GOCACHE": filepath.Join(t.root, "go", ".cache", "go-build"), "GOOS": t.target.goos, "GOARCH": t.target.goarch, "GOARM": t.target.goarm})
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s %s: %w", program, strings.Join(args, " "), err)
return fmt.Errorf("%s %s: %w", program, strings.Join(args, " "), errors.Join(err, t.ctx.Err()))
}
return nil
}
+16 -3
View File
@@ -34,7 +34,7 @@ func (t task) release(args []string) error {
if len(args) == 0 || isHelp(args[0]) {
fmt.Println(`Usage:
bd2w release changelog --component server|client [--bump patch|minor|major|none]
bd2w release publish [-GameDir dir] [-SkipTests] [--output dir] [--image ref] [--allow-dirty] [--no-announcement]
bd2w release publish [-GameDir dir] [-SkipTests] [--output dir] [--image ref] [--allow-dirty] [--no-announcement] [--component all|schedules]
publish builds unsigned release materials described by versions.json and
CHANGELOG.md. Signing and uploading are independent publisher operations.`)
@@ -137,6 +137,7 @@ func (t task) releaseChangelog(args []string) error {
}
type publishOptions struct {
component string
build buildOptions
output string
image string
@@ -145,7 +146,7 @@ type publishOptions struct {
}
func parsePublish(args []string) (publishOptions, error) {
var opts publishOptions
opts := publishOptions{component: "all"}
var rest []string
for i := 0; i < len(args); i++ {
name, value, assigned := strings.Cut(args[i], "=")
@@ -161,6 +162,8 @@ func parsePublish(args []string) (publishOptions, error) {
}
var err error
switch name {
case "--component":
opts.component, err = take()
case "--output":
opts.output, err = take()
case "--image":
@@ -176,6 +179,9 @@ func parsePublish(args []string) (publishOptions, error) {
return opts, err
}
}
if opts.component != "all" && opts.component != "schedules" {
return opts, errors.New("--component must be all or schedules")
}
build, err := parseOptions(rest)
opts.build = build
return opts, err
@@ -224,6 +230,9 @@ func (t task) releasePublish(args []string) error {
if err != nil {
return err
}
if opts.component == "schedules" {
return t.publishSchedules(opts)
}
commit, err := t.releaseCommit(opts.allowDirty)
if err != nil {
return err
@@ -343,8 +352,12 @@ func (t task) releasePublish(args []string) error {
plugins.Files = append(plugins.Files, f)
}
schedules, err := t.stageSchedules(site, versions)
if err != nil {
return err
}
manifest := releasepkg.Manifest{Schema: releasepkg.SchemaVersion, Channel: releasepkg.BuiltinChannel().Name, PublishedAt: time.Now().UTC().Truncate(time.Second), Commit: commit,
Launcher: launcher, Plugins: plugins, Server: server, Fingerprint: fingerprint}
Launcher: launcher, Plugins: plugins, Server: server, Schedules: schedules, Fingerprint: fingerprint}
if err := manifest.Validate(); err != nil {
return err
}
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"encoding/json"
"fmt"
"os"
"path"
"path/filepath"
"time"
releasepkg "bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/domain/events/calendar"
)
func (t task) publishSchedules(opts publishOptions) error {
commit, err := t.releaseCommit(opts.allowDirty)
if err != nil {
return err
}
output := opts.output
if output == "" {
output = filepath.Join(t.root, ".build", "release-site")
}
versions, err := versionconfig.Load(filepath.Join(t.root, "versions.json"))
if err != nil {
return err
}
raw, err := os.ReadFile(filepath.Join(output, "manifest.json"))
if err != nil {
return fmt.Errorf("load existing release materials before replacing schedules: %w", err)
}
var manifest releasepkg.Manifest
if err := json.Unmarshal(raw, &manifest); err != nil {
return err
}
if err := manifest.Validate(); err != nil {
return err
}
if manifest.Channel != releasepkg.BuiltinChannel().Name {
return fmt.Errorf("release materials belong to a different channel")
}
schedules, err := t.stageSchedules(output, versions)
if err != nil {
return err
}
if manifest.Schedules != nil {
schedules.Notes = manifest.Schedules.Notes
}
manifest.Schedules, manifest.Commit, manifest.PublishedAt = schedules, commit, time.Now().UTC().Truncate(time.Second)
if err := manifest.Validate(); err != nil {
return err
}
raw, err = json.MarshalIndent(manifest, "", " ")
if err != nil {
return err
}
if err := os.MkdirAll(output, 0o755); err != nil {
return err
}
if err := os.WriteFile(filepath.Join(output, "manifest.json"), append(raw, '\n'), 0o644); err != nil {
return err
}
fmt.Println("Unsigned release materials:", output)
fmt.Println("Schedule content ID:", schedules.ID)
fmt.Println("Sign independently with tools/release/sign.py; publish files before the signed manifest.")
return nil
}
func (t task) stageSchedules(output string, versions versionconfig.Config) (*releasepkg.Schedules, error) {
source := filepath.Join(t.root, "schedules")
set, err := calendar.LoadDirectory(source, versions.GameVersion, versions.GameDataVersion)
if err != nil {
return nil, err
}
if set.RegularService == nil || set.MonsterHunt == nil || len(set.MonsterHunt.Seasons) == 0 {
return nil, fmt.Errorf("schedules require regular content and monster hunt seasons")
}
schedules := &releasepkg.Schedules{GameVersion: versions.GameVersion, GameDataVersion: versions.GameDataVersion}
entries, err := os.ReadDir(source)
if err != nil {
return nil, err
}
for _, entry := range entries {
file := filepath.Join(source, entry.Name())
sum, err := releasepkg.HashFile(file)
if err != nil {
return nil, err
}
info, err := entry.Info()
if err != nil {
return nil, err
}
relative := path.Join("files", sum, entry.Name())
schedules.Files = append(schedules.Files, releasepkg.File{Name: entry.Name(), Size: info.Size(), SHA256: sum, URL: "../" + relative})
}
schedules.ID = schedules.ContentID()
for _, f := range schedules.Files {
target := filepath.Join(output, "files", f.SHA256, f.Name)
if err := copyFile(filepath.Join(source, f.Name), target); err != nil {
return nil, err
}
if !releasepkg.Matches(target, f) {
return nil, fmt.Errorf("schedule %s changed while preparing materials", f.Name)
}
}
return schedules, nil
}
+8
View File
@@ -2,6 +2,7 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
@@ -48,6 +49,9 @@ func main() {
return
}
relaunched, err := relaunchDevelopmentIfNeeded(os.Args[1:])
if errors.Is(err, context.Canceled) {
return
}
if err != nil {
clientapp.ShowFatalError(err)
fmt.Fprintln(os.Stderr, "bd2client:", err)
@@ -60,6 +64,9 @@ func main() {
if !handled && err == nil {
err = runClient(os.Args[1:], clientRunOptions{})
}
if errors.Is(err, context.Canceled) {
return
}
if err != nil {
clientapp.ShowFatalError(err)
fmt.Fprintln(os.Stderr, "bd2client:", err)
@@ -108,6 +115,7 @@ func runClient(args []string, options clientRunOptions) error {
Logger: logger,
LogPath: logPath,
Versions: versions,
Development: options.versionConfigPath != "",
LocalIdentityPlugin: options.localIdentityPlugin,
LoginUIPlugin: options.loginUIPlugin,
CashShopPlugin: options.cashShopPlugin,
+1 -1
View File
@@ -70,7 +70,7 @@ Usage:
bd2server serve [--data-dir DIR] [--version-config FILE] [options]
bd2server resources fetch --output DIR [--version-config FILE]
bd2server state check [options]
bd2server update status|check|apply|cancel [--data-dir DIR] [--in 10m | --now] [--confirm-irreversible] [--json]
bd2server update status|check|apply|cancel [--component server|schedules] [--data-dir DIR] [--in 10m | --now] [--confirm-irreversible] [--json]
The server binds to loopback by default.
Logging: --log-level trace|debug|info|warn|error; --log-color auto|always|never.
+32 -2
View File
@@ -25,9 +25,13 @@ func runUpdate(args []string) error {
delay := fs.Duration("in", -1, "apply: start maintenance after this countdown, e.g. 10m (default from updates.json)")
now := fs.Bool("now", false, "apply: start maintenance as soon as the release is ready")
confirm := fs.Bool("confirm-irreversible", false, "apply: accept a release whose save migration cannot be rolled back")
component := fs.String("component", updates.ComponentServer, "apply: server or schedules")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if *component != updates.ComponentServer && *component != updates.ComponentSchedules {
return errors.New("--component must be server or schedules")
}
if *dataDir == "" {
executable, err := os.Executable()
if err != nil {
@@ -53,7 +57,7 @@ func runUpdate(args []string) error {
printStatus(status)
return nil
case "check", "apply", "cancel":
control := updates.Control{ID: requestID(), Action: args[0], ConfirmIrreversible: *confirm, RequestedAt: time.Now().UTC()}
control := updates.Control{ID: requestID(), Action: args[0], Component: *component, ConfirmIrreversible: *confirm, RequestedAt: time.Now().UTC()}
if args[0] == updates.ActionApply {
config, err := updates.Document.Load(updates.Document.Path(filepath.Join(directory, "config")))
if err != nil {
@@ -94,6 +98,32 @@ func printStatus(s updates.Status) {
if s.LastError != "" {
fmt.Printf("Check error %s\n", s.LastError)
}
if schedules := s.Schedules; schedules != nil {
current := schedules.CurrentID
if current == "" {
current = "bundled"
}
fmt.Printf("Schedules %s (game %s / GameData %s)\n", current, schedules.GameVersion, schedules.GameDataVersion)
if a := schedules.Available; a != nil {
state := "not downloaded"
if a.Downloaded {
state = "downloaded and verified"
}
if a.DownloadError != "" {
state = "download failed: " + a.DownloadError
}
if a.Incompatible != "" {
state = "incompatible: " + a.Incompatible
}
fmt.Printf("Schedule update %s (%s)\n", a.Component.ID, state)
if notes := a.Component.Notes.In(i18n.Fallback); notes != "" {
fmt.Println(notes)
}
}
if r := schedules.LastResult; r != nil {
fmt.Printf("Last schedules %s -> %s: %s %s\n", r.From, r.To, r.Outcome, r.Message)
}
}
if a := s.Available; a != nil {
state := "not downloaded"
if a.Downloaded {
@@ -116,7 +146,7 @@ func printStatus(s updates.Status) {
if !m.At.IsZero() {
at = m.At.Local().Format(time.DateTime)
}
fmt.Printf("Maintenance %s -> %s (%s, %s)\n", m.Phase, m.Version, at, m.RequestedBy)
fmt.Printf("Maintenance %s %s -> %s (%s, %s)\n", m.Component, m.Phase, m.Version, at, m.RequestedBy)
}
if r := s.LastResult; r != nil {
fmt.Printf("Last switch %s -> %s: %s %s\n", r.From, r.To, r.Outcome, r.Message)
+10 -3
View File
@@ -15,6 +15,7 @@ import (
clientconfig "bd2server/internal/client/config"
clientlayout "bd2server/internal/client/layout"
clientplugin "bd2server/internal/client/plugin"
clientsetup "bd2server/internal/client/setup"
clientupdate "bd2server/internal/client/update"
"bd2server/internal/common/versionconfig"
@@ -30,6 +31,7 @@ type Options struct {
Logger *slog.Logger
LogPath string
Versions versionconfig.Config
Development bool
LocalIdentityPlugin string
LoginUIPlugin string
CashShopPlugin string
@@ -90,8 +92,13 @@ type Studio struct {
func NewStudio(options Options, host NativeHost) *Studio {
s := &Studio{options: options, host: host, ctx: context.Background(), launch: launchGame, savePreferences: clientconfig.SavePreferences}
if executable, err := os.Executable(); err == nil {
var developmentPlugins []string
if options.Development {
developmentPlugins = []string{options.LocalIdentityPlugin, options.LoginUIPlugin, options.CashShopPlugin, options.FChatPlugin, filepath.Join(filepath.Dir(options.LocalIdentityPlugin), clientplugin.GameNames.FileName())}
}
s.updates = clientupdate.New(clientupdate.Options{
Versions: options.Versions, Directory: filepath.Dir(executable), Logger: options.Logger,
Versions: options.Versions, Directory: filepath.Dir(executable), Logger: options.Logger, Development: options.Development,
DevelopmentPlugins: developmentPlugins,
Games: func() string {
preferences, err := clientconfig.LoadPreferences()
if err != nil {
@@ -388,10 +395,10 @@ func (s *Studio) CheckUpdates() (Response, error) {
if err := s.updates.Download(ctx); err != nil {
return Response{}, err
}
if err := s.updates.CommitGame(ctx); err != nil {
if err := s.updates.CommitPlugins(); err != nil {
return Response{}, err
}
if err := s.updates.CommitPlugins(); err != nil {
if err := s.updates.CommitGame(ctx); err != nil {
return Response{}, err
}
return success("Update check completed", s.updates.Status()), nil
+5 -3
View File
@@ -85,7 +85,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
}
sdkKey := digestInputs(sdkInputsKey)
sdkManifestPath := filepath.Join(work, "sdk-build.json")
sdkTool := filepath.Join(root, "plugins", "GameSdk", "bin", "Release", "net8.0", "GameSdk.dll")
sdkTool := filepath.Join(work, "sdk-tool", "GameSdk.dll")
var sdkReused bool
var shared string
prepareStarted := time.Now()
@@ -106,7 +106,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
return nil
}
_, _ = fmt.Fprintln(progress, "Client plugins: preparing the shared game SDK...")
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-v:quiet", "-clp:NoSummary", "-p:BD2SdkCompileInputsFile="+sdkInputs); err != nil {
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "-o", filepath.Dir(sdkTool), "--nologo", "-v:quiet", "-clp:NoSummary", "-p:BD2SdkCompileInputsFile="+sdkInputs); err != nil {
return err
}
@@ -155,6 +155,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(root, "plugins", "ClientPlugins.proj"), "-m", "-c", "Release", "--nologo",
"-p:GameDir="+installation.Root, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+installation.BepInEx,
"-p:BD2SdkPrepared=true", "-p:BD2SdkDir="+sdkDir, "-p:BD2SharedSdkDir="+shared,
"-p:BD2SdkTool="+sdkTool,
"-p:BD2PreparedVersionDir="+versionDir, "-p:BD2CompileInputsDir="+compileInputsDir, "-p:BD2NamesCompileInputsFile="+namesInputs, "-v:quiet", "-clp:NoSummary"); err != nil {
return err
}
@@ -163,7 +164,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
return nil
}},
taskgraph.Task{Name: "cacheCommit", DependsOn: []string{"pluginsCompile"}, Run: func(context.Context) error {
outputs := []string{sdkTool, sdkInputs, namesInputs, strings.TrimSuffix(sdkTool, ".dll") + ".deps.json", strings.TrimSuffix(sdkTool, ".dll") + ".runtimeconfig.json",
outputs := []string{sdkTool, sdkInputs, strings.TrimSuffix(sdkTool, ".dll") + ".deps.json", strings.TrimSuffix(sdkTool, ".dll") + ".runtimeconfig.json",
filepath.Join(sdkDir, "GameSdkIdentity.g.cs"), filepath.Join(sdkDir, "shared-sdk.txt"), filepath.Join(sdkDir, "GameSourceNavigation.props"),
filepath.Join(shared, "ref", "Assembly-CSharp.Readable.dll"), filepath.Join(shared, "names.json"), filepath.Join(shared, "names.json.gz")}
for _, name := range []string{"ready.txt", "navigation.json", "GameSourceNavigation.props", "Assembly-CSharp.Readable.dll", "Assembly-CSharp.Readable.xml",
@@ -176,6 +177,7 @@ func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Wri
}
outputs = append(outputs, toolDependencies...)
sdkOutputs := append([]string(nil), outputs...)
outputs = append(outputs, namesInputs)
for _, project := range developmentProjects {
output := filepath.Join(root, "plugins", project.name, "bin", "Release", "netstandard2.1")
outputs = append(outputs, filepath.Join(output, "BD2"+project.name+".dll"), filepath.Join(output, GameNames.fileName), filepath.Join(versionDir, project.key+".g.cs"), filepath.Join(compileInputsDir, project.key+".g.cs"))
+42 -21
View File
@@ -81,10 +81,12 @@ type Message struct {
func message(key string, args ...string) *Message { return &Message{Key: key, Args: args} }
type Options struct {
Versions versionconfig.Config
Directory string
Logger *slog.Logger
Client *http.Client
Versions versionconfig.Config
Directory string
Logger *slog.Logger
Client *http.Client
Development bool
DevelopmentPlugins []string
// Games returns the main game directory the launcher manages.
Games func() string
}
@@ -114,7 +116,7 @@ func New(options Options) *Manager {
address = release.BuiltinChannel().ManifestURL
}
m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}}
m.status.Enabled = address != ""
m.status.Enabled = address != "" && !options.Development
m.loadPackagedFingerprint()
if result := TakeResult(options.Directory); result != nil {
if result.OK {
@@ -223,16 +225,20 @@ func (m *Manager) refresh(ctx context.Context) {
m.options.Logger.Warn("update download failed", "error", err)
return
}
if err := m.CommitGame(ctx); err != nil {
m.options.Logger.Warn("game resources not installed", "error", err)
}
if err := m.CommitPlugins(); err != nil {
m.options.Logger.Warn("plugin update not installed", "error", err)
return
}
if err := m.CommitGame(ctx); err != nil {
m.options.Logger.Warn("game resources not installed", "error", err)
}
}
// Check fetches the manifest and works out what this launcher lacks.
func (m *Manager) Check(ctx context.Context) error {
if m.options.Development {
return errors.New("development builds use locally compiled updates")
}
if !m.begin("checking") {
return operationBusy()
}
@@ -264,7 +270,7 @@ func (m *Manager) Check(ctx context.Context) error {
}
m.envelope = envelope
m.status.Launcher, m.status.Plugins = nil, nil
if c := manifest.Launcher; c != nil && newer(m.options.Versions.ClientVersion, c.Version) {
if c := manifest.Launcher; c != nil && !newer(c.Version, m.options.Versions.ClientVersion) {
if files := m.missing(c.FilesFor(release.Platform()), m.options.Directory); len(files) != 0 {
m.status.Launcher = offer(c, files, m.launcherStaging(c.Version))
}
@@ -400,6 +406,9 @@ func (m *Manager) Download(ctx context.Context) error {
// CommitPlugins moves a downloaded plugin set into the launcher's store and
// installs it into every closed game instance; running ones wait.
func (m *Manager) CommitPlugins() error {
if m.options.Development {
return nil
}
if !m.begin("installing") {
return operationBusy()
}
@@ -539,14 +548,23 @@ func (m *Manager) EnsurePlugins(game string) error {
}
func (m *Manager) ensurePlugins(game string) error {
sources, err := m.storeSources()
var sources []string
var err error
if m.options.Development {
sources = m.options.DevelopmentPlugins
if len(sources) == 0 {
return errors.New("development plugin sources are missing")
}
} else {
sources, err = m.storeSources()
}
if errors.Is(err, os.ErrNotExist) {
return nil // development builds install plugins explicitly
return nil
}
if err != nil {
return err
}
if versions := m.Versions(game); versions.GameVersion != "" {
if versions := m.Versions(game); versions.GameVersion != "" && !m.options.Development {
store, err := ReadStore(m.options.Directory)
if err != nil {
return err
@@ -717,9 +735,18 @@ type Compatibility struct {
func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin string) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
store, err := ReadStore(m.options.Directory)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
installed := m.options.Versions.Plugins.ByID()
if !m.options.Development {
installed = map[string]string{}
store, err := ReadStore(m.options.Directory)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
for _, f := range store.Files {
if f.ID != "" {
installed[f.ID] = f.Version
}
}
}
address, err := url.JoinPath(origin, "client", "compatibility")
if err != nil {
@@ -775,12 +802,6 @@ func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin s
if compat.GameVersion != "" && versions.GameVersion != "" && compat.GameVersion != versions.GameVersion && (fp == nil || fp.Game == nil || fp.Game.GameVersion != compat.GameVersion) {
return fmt.Errorf("Server game version %s does not match client game version %s", compat.GameVersion, versions.GameVersion) //nolint:staticcheck // ST1005: shown to players
}
installed := map[string]string{}
for _, f := range store.Files {
if f.ID != "" {
installed[f.ID] = f.Version
}
}
var stale []string
for id, minimum := range compat.MinimumPlugins {
current := installed[id]
+6
View File
@@ -35,6 +35,7 @@ type Manifest struct {
Launcher *Component `json:"launcher,omitempty"`
Plugins *Component `json:"plugins,omitempty"`
Server *Component `json:"server,omitempty"`
Schedules *Schedules `json:"schedules,omitempty"`
Fingerprint *Fingerprint `json:"fingerprint,omitempty"`
}
@@ -96,6 +97,11 @@ func (m Manifest) Validate() error {
return err
}
}
if m.Schedules != nil {
if err := m.Schedules.Validate(); err != nil {
return err
}
}
if m.Fingerprint != nil {
if err := m.Fingerprint.Validate(); err != nil {
return err
+54
View File
@@ -0,0 +1,54 @@
package release
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"path"
"slices"
"strings"
"bd2server/internal/common/i18n"
)
// Schedules is the schedule component of the release manifest.
// ID identifies content and compatibility; it is independent of program versions.
type Schedules struct {
ID string `json:"id"`
GameVersion string `json:"game_version"`
GameDataVersion string `json:"game_data_version"`
Notes i18n.Text `json:"notes,omitempty"`
Files []File `json:"files"`
}
func (s Schedules) ContentID() string {
files := slices.Clone(s.Files)
slices.SortFunc(files, func(a, b File) int { return strings.Compare(a.Name, b.Name) })
h := sha256.New()
_, _ = fmt.Fprintf(h, "bd2-schedules-v1\n%s\n%s\n", s.GameVersion, s.GameDataVersion)
for _, f := range files {
_, _ = fmt.Fprintf(h, "%s\n%d\n%s\n", f.Name, f.Size, f.SHA256)
}
return hex.EncodeToString(h.Sum(nil))
}
func (s Schedules) Validate() error {
if strings.TrimSpace(s.GameVersion) == "" || strings.TrimSpace(s.GameDataVersion) == "" || len(s.Files) == 0 || len(s.Files) > 128 {
return fmt.Errorf("release: schedules need compatible game and GameData versions and 1 to 128 files")
}
seen := map[string]bool{}
for _, f := range s.Files {
name := strings.ToLower(f.Name)
if f.Name == "" || path.Base(f.Name) != f.Name || strings.ContainsAny(f.Name, "\\:\r\n") || !strings.HasSuffix(f.Name, ".bd2schedule") || strings.HasSuffix(strings.TrimSuffix(f.Name, ".bd2schedule"), ".") || seen[name] {
return fmt.Errorf("release: invalid or duplicate schedule filename %q", f.Name)
}
seen[name] = true
if f.Platform != "" || f.ID != "" || f.Version != "" || f.Size <= 0 || f.Size > 8*1024*1024 || !digestPattern.MatchString(f.SHA256) || f.URL == "" {
return fmt.Errorf("release: invalid schedule file %q", f.Name)
}
}
if !digestPattern.MatchString(s.ID) || s.ID != s.ContentID() {
return fmt.Errorf("release: schedules content ID does not match its file set")
}
return nil
}
+15 -3
View File
@@ -14,6 +14,7 @@ type Updates interface {
Status() updates.Status
CheckNow()
Schedule(delay time.Duration, confirmIrreversible bool, by string) error
ScheduleSchedules(delay time.Duration, by string) error
Cancel(by string) error
}
@@ -52,14 +53,25 @@ func (c *Console) registerUpdates(mux *http.ServeMux, owner func(session) bool)
return
}
var request struct {
DelayMinutes int `json:"delay_minutes"`
ConfirmIrreversible bool `json:"confirm_irreversible"`
Component string `json:"component"`
DelayMinutes int `json:"delay_minutes"`
ConfirmIrreversible bool `json:"confirm_irreversible"`
}
if !decode(w, r, &request) {
return
}
by := "console:" + current.AccountID
if err := service.Schedule(time.Duration(request.DelayMinutes)*time.Minute, request.ConfirmIrreversible, by); err != nil {
var err error
switch request.Component {
case "", updates.ComponentServer:
err = service.Schedule(time.Duration(request.DelayMinutes)*time.Minute, request.ConfirmIrreversible, by)
case updates.ComponentSchedules:
err = service.ScheduleSchedules(time.Duration(request.DelayMinutes)*time.Minute, by)
default:
fail(w, http.StatusBadRequest, "unsupported", "unknown update component")
return
}
if err != nil {
rejected(w, err)
return
}
+27 -12
View File
@@ -1032,7 +1032,7 @@ const config = (() => {
/* ---------- Updates ---------- */
const updatesView = (() => {
let timer = null, status = null;
let timer = null, status = null, component = null;
const when = value => value ? dateTime(value) : '';
const named = (group, value) => tr(`console.updates.${group}.${value}`, value);
// Release notes arrive as {locale: text}; older servers send one string.
@@ -1042,16 +1042,27 @@ const updatesView = (() => {
try {
const s = status;
if (!s) return;
const facts = [['current_version', s.current_version], ['method', named('method', s.method)], ['auto_check', t(s.check_enabled ? 'console.updates.enabled' : 'console.updates.disabled')],
if (component == null) component = !s.available && s.schedules && s.schedules.available ? 'schedules' : 'server';
const scheduleBranch = component === 'schedules';
const schedules = s.schedules;
const selected = $('update-component');
selected.value = component;
const source = scheduleBranch ? schedules && schedules.available : s.available;
const a = scheduleBranch && source ? {...source, version: source.component.id, notes: source.component.notes} : source;
const current = scheduleBranch ? schedules && schedules.current_id || t('console.updates.schedules.bundled') : s.current_version;
const lastResult = scheduleBranch ? schedules && schedules.last_result : s.last_result;
const facts = [['current_version', current], ['method', named('method', s.method)], ['auto_check', t(s.check_enabled ? 'console.updates.enabled' : 'console.updates.disabled')],
['last_check', when(s.last_check) || t('console.updates.never_checked')], ['check_error', s.last_error]];
if (s.last_result) {
const r = s.last_result, outcome = named('outcome', r.outcome);
if (scheduleBranch && schedules) {
facts.push(['game_version', schedules.game_version], ['game_data_version', schedules.game_data_version]);
}
if (lastResult) {
const r = lastResult, outcome = named(scheduleBranch ? 'schedule_outcome' : 'outcome', r.outcome);
facts.push(['last_switch', r.message ? rendered(await dynamicText('console.updates.last_switch_message', r.from, r.to, outcome, r.message), renderPass) : rendered(await dynamicText('console.updates.last_switch_value', r.from, r.to, outcome), renderPass)]);
}
$('update-facts').replaceChildren(...facts.filter(f => f[1]).flatMap(([k, v]) => [el('dt', {}, t('console.updates.fact.' + k)), el('dd', {}, v)]));
const a = s.available;
$('update-facts').replaceChildren(...facts.filter(f => f[1]).flatMap(([k, v]) => [el('dt', {}, t(k === 'game_version' ? 'console.updates.schedules.game' : k === 'game_data_version' ? 'console.updates.schedules.gamedata' : 'console.updates.fact.' + k)), el('dd', {}, v)]));
if (!a) {
$('update-available').replaceChildren(el('p', {class: 'muted'}, s.last_error ? '' : t('console.updates.up_to_date')));
$('update-available').replaceChildren(el('p', {class: 'muted'}, s.last_error ? '' : t(scheduleBranch ? 'console.updates.schedules.up_to_date' : 'console.updates.up_to_date')));
} else {
const download = a.downloaded ? t('console.updates.downloaded') : a.download_error ? rendered(await dynamicText('console.updates.download_failed', a.download_error), renderPass) : t('console.updates.not_downloaded');
const migration = a.migration || {}, migrationNote = localized(migration.note), notes = localized(a.notes);
@@ -1059,7 +1070,9 @@ const updatesView = (() => {
el('h3', {}, rendered(await dynamicText('console.updates.available', a.version), renderPass)),
el('p', {class: 'muted'}, [a.published_at && rendered(await dynamicText('console.updates.published', when(a.published_at)), renderPass), migration.kind && named('migration', migration.kind), download].filter(Boolean).join(' · ')),
migrationNote ? el('p', {class: migration.kind === 'irreversible' ? 'status err' : 'status'}, migrationNote) : null,
notes ? el('pre', {class: 'notes'}, notes) : null].filter(Boolean));
a.game_data_version ? el('p', {class: 'muted'}, t('console.updates.schedules.gamedata') + ': ' + a.game_data_version) : null,
notes ? el('pre', {class: 'notes'}, notes) : null,
a.incompatible ? el('p', {class: 'status err'}, a.incompatible) : null].filter(Boolean));
}
const actions = [];
const m = s.maintenance;
@@ -1068,7 +1081,7 @@ const updatesView = (() => {
const phase = named('phase', m.phase);
actions.push(el('p', {}, m.at ? rendered(await dynamicText('console.updates.maintenance_at', phase, m.version, when(m.at), m.requested_by), renderPass) : rendered(await dynamicText('console.updates.maintenance', phase, m.version, m.requested_by), renderPass)));
if (m.phase !== 'closing') actions.push(el('button', {type: 'button', class: 'btn', onclick: cancel}, t('console.updates.cancel')));
} else if (a && s.method !== 'none') {
} else if (a && !a.incompatible && s.method !== 'none') {
const delay = el('input', {type: 'number', id: 'update-delay', min: '0', max: '1440', value: delayInput ? delayInput.value : String(s.countdown_minutes ?? 10)});
const confirm = a.migration && a.migration.kind === 'irreversible' ? el('label', {}, el('input', {type: 'checkbox', id: 'update-confirm', checked: !!(confirmInput && confirmInput.checked)}), ' ' + t('console.updates.confirm_irreversible')) : null;
actions.push(el('label', {}, t('console.updates.delay') + ' ', delay), confirm, el('button', {type: 'button', class: 'btn seal', onclick: apply}, t('console.updates.apply')));
@@ -1082,13 +1095,14 @@ const updatesView = (() => {
catch (error) { await say($('update-status'), error, 'err'); }
}
async function apply() {
const selectedComponent = component;
const minutes = Number($('update-delay').value || 0);
const confirmIrreversible = !!($('update-confirm') && $('update-confirm').checked);
const target = status.available.version;
const body = minutes ? await dynamicText('console.updates.apply.body_countdown', fmt(minutes), target) : await dynamicText('console.updates.apply.body_now', target);
const target = selectedComponent === 'schedules' ? status.schedules.available.component.id : status.available.version;
const body = selectedComponent === 'schedules' ? await dynamicText('console.updates.schedules.confirm', fmt(minutes), target) : minutes ? await dynamicText('console.updates.apply.body_countdown', fmt(minutes), target) : await dynamicText('console.updates.apply.body_now', target);
if (!await ask({title: t('console.updates.apply.title'), body, ok: t('console.updates.apply')})) return;
try {
status = (await api('updates/apply', {method: 'POST', body: {delay_minutes: minutes, confirm_irreversible: confirmIrreversible}})).value;
status = (await api('updates/apply', {method: 'POST', body: {component: selectedComponent, delay_minutes: minutes, confirm_irreversible: confirmIrreversible}})).value;
await render(); await say($('update-status'), Component.translatable('console.updates.scheduled'), 'ok');
} catch (error) { await say($('update-status'), error, 'err'); }
}
@@ -1096,6 +1110,7 @@ const updatesView = (() => {
try { status = (await api('updates/cancel', {method: 'POST'})).value; await render(); await say($('update-status'), Component.translatable('console.updates.cancelled'), 'ok'); }
catch (error) { await say($('update-status'), error, 'err'); }
}
$('update-component').onchange = async event => { component = event.target.value; await render(); };
$('update-check').onclick = async () => {
try { await api('updates/check', {method: 'POST'}); await say($('update-status'), Component.translatable('console.updates.checking')); setTimeout(load, 3000); }
catch (error) { await say($('update-status'), error, 'err'); }
@@ -9,7 +9,6 @@
"console.copy.failed": "Couldn't copy. Please select the text manually.",
"console.dialog.ok": "OK",
"console.dialog.cancel": "Cancel",
"console.error.unauthorized": "Your session has expired. Please sign in again.",
"console.error.forbidden": "You don't have permission to do this.",
"console.error.csrf": "This page has expired. Please reload and try again.",
@@ -35,7 +34,6 @@
"console.error.no_maintenance": "No maintenance is scheduled.",
"console.error.maintenance_closing": "The maintenance is already draining and can no longer be cancelled.",
"console.error.http": "Request failed (%[1]s).",
"console.nav.mail": "Mail",
"console.nav.players": "Players",
"console.nav.config": "Server settings",
@@ -51,7 +49,6 @@
"console.leave.title": "Save settings before leaving?",
"console.leave.body": "You have unsaved configuration changes. They stay on this page until you reload or sign out.",
"console.leave.ok": "Leave anyway",
"console.signin.title": "Enter the console",
"console.signin.loading": "Reading server information…",
"console.signin.local": "This server uses local authentication. Open the one-time sign-in link printed in the server console at startup.",
@@ -63,7 +60,6 @@
"console.signin.open_page": "Open the sign-in page",
"console.signin.success": "Signed in.",
"console.signin.no_permissions": "The server owner hasn't given you any permissions yet.",
"console.mail.recipient": "Recipient",
"console.mail.copy_uid": "Click to copy the UID",
"console.mail.switch_player": "Switch player",
@@ -146,7 +142,6 @@
"console.mail.log.again_title": "Put this item and quantity back on the slip",
"console.mail.log.identity": "Grant ID",
"console.mail.log.identity_title": "Click to copy the grant ID",
"console.roster.title": "Players",
"console.roster.lead": "Appoint administrators by game account; they sign in to the console with their own game account. Administrators can send mail and view players by default; the owner grants any other permission one by one.",
"console.roster.search.placeholder": "UID or name",
@@ -192,7 +187,6 @@
"console.permissions.write": "Edit",
"console.permissions.read_aria": "View %[1]s %[2]s",
"console.permissions.write_aria": "Edit %[1]s %[2]s",
"console.config.documents": "Configuration files",
"console.config.show_diff": "Review changes",
"console.config.discard": "Discard",
@@ -257,7 +251,6 @@
"console.overview.data_dir": "Data directory",
"console.overview.mail_spool": "Mail queue",
"console.overview.dev_tools": "Development overrides",
"config.problem.item": "Item %[1]s: %[2]s",
"config.problem.enum": "This value isn't allowed",
"config.problem.enum_options": "Choose one of: %[1]s",
@@ -300,7 +293,6 @@
"config.problem.message.object": "Must be an object",
"config.problem.message.present": "Must be written explicitly in the file",
"config.problem.message.hidden_section": "A group you can't access has a problem. Ask the server owner to fix it.",
"config.game.title": "Game rules",
"config.game.summary": "Server-wide gameplay rules. Changes take effect after the server restarts.",
"config.game.section.story.title": "Opening chapter",
@@ -388,7 +380,6 @@
"config.game.field.text_moderation.provider.severity_threshold.help": "Text is rejected when any category reaches this severity; 0 rejects even results with severity 0.",
"config.game.section.format.title": "Format",
"config.game.field.schema_version.label": "Format version",
"config.authentication.title": "Sign-in and authentication",
"config.authentication.summary": "How players sign in. Changes take effect after the server restarts; secrets are read only from environment variables and never written to this file.",
"config.authentication.section.mode.title": "Authentication mode",
@@ -411,7 +402,6 @@
"config.authentication.field.session.access_ttl.label": "Access token lifetime",
"config.authentication.field.session.refresh_ttl.label": "Refresh token lifetime",
"config.authentication.field.session.device_transaction_ttl.label": "Sign-in transaction lifetime",
"config.resources.title": "Client resources",
"config.resources.summary": "Where the client downloads ServerData and GameData. Changes take effect after the server restarts; version numbers come from versions.json and aren't set here.",
"config.resources.section.source.title": "Resource source",
@@ -424,7 +414,6 @@
"config.resources.field.server_data_url.help": "An absolute HTTP(S) address without a trailing slash; must use HTTPS except for loopback addresses.",
"config.resources.field.game_data_url.label": "GameData URL",
"config.resources.field.game_data_url.help": "An absolute HTTP(S) address without a trailing slash; must use HTTPS except for loopback addresses.",
"config.updates.title": "Updates",
"config.updates.summary": "How new releases are checked, pre-downloaded and installed during maintenance. Checking and downloading don't affect the game; applying an update must be confirmed in the console or on the command line. Changes take effect after the server restarts.",
"config.updates.section.check.title": "Checking and downloading",
@@ -450,7 +439,6 @@
"config.updates.field.maintenance_minutes.label": "Expected maintenance length (minutes)",
"config.updates.field.webhook_url_env.label": "Webhook environment variable",
"config.updates.field.webhook_url_env.help": "When a new release is found, POSTs JSON once to the address held in this environment variable; leave empty to send nothing.",
"console.updates.title": "Updates",
"console.updates.lead": "The server checks the signed release manifest at an interval and can download and verify releases ahead of time. Applying an update first notifies online players, closes new sign-ins, drains requests and saves, then switches to the new version.",
"console.updates.check": "Check now",
@@ -498,5 +486,21 @@
"console.updates.apply.body_now": "Once preparation finishes, the server immediately closes new sign-ins, drains, saves and switches to %[1]s.",
"console.updates.scheduled": "Maintenance scheduled.",
"console.updates.cancelled": "Maintenance cancelled.",
"console.updates.checking": "Checking…"
"console.updates.checking": "Checking…",
"console.updates.schedules.title": "Schedules",
"console.updates.schedules.bundled": "Bundled schedules",
"console.updates.schedules.game": "Game version",
"console.updates.schedules.gamedata": "GameData version",
"console.updates.schedules.up_to_date": "No schedule update available.",
"console.updates.schedules.confirm": "After preparation, wait %[1]s minutes, drain and save, then restart the current server with schedule set %[2]s.",
"console.updates.schedule_outcome.succeeded": "Succeeded",
"console.updates.schedule_outcome.rolled_back": "Previous schedules restored",
"console.updates.schedule_outcome.needs_operator": "Needs manual attention",
"console.updates.schedule_outcome.switch_failed": "Switch failed",
"console.updates.schedule_outcome.cancelled": "Cancelled",
"console.updates.schedule_outcome.restarting": "Restarting",
"console.error.incompatible_schedules": "This schedule set does not match the running game and GameData versions.",
"console.error.confirming_update": "The previous update is still being checked. Wait until it is confirmed healthy.",
"console.updates.component": "Update content",
"console.updates.component.server": "Server program"
}
@@ -486,5 +486,21 @@
"console.updates.apply.body_now": "準備が完了すると、直ちに新規ログインを停止し、処理の終了を待って保存してから %[1]s に切り替えます。",
"console.updates.scheduled": "メンテナンスを予定しました。",
"console.updates.cancelled": "メンテナンスをキャンセルしました。",
"console.updates.checking": "確認中…"
"console.updates.checking": "確認中…",
"console.updates.schedules.title": "スケジュール更新",
"console.updates.schedules.bundled": "同梱スケジュール",
"console.updates.schedules.game": "ゲームバージョン",
"console.updates.schedules.gamedata": "GameData バージョン",
"console.updates.schedules.up_to_date": "スケジュール更新はありません。",
"console.updates.schedules.confirm": "準備完了後 %[1]s 分待ち、処理を完了して保存し、スケジュールセット %[2]s で現在のサーバーを再起動します。",
"console.updates.schedule_outcome.succeeded": "成功",
"console.updates.schedule_outcome.rolled_back": "以前のスケジュールを復元",
"console.updates.schedule_outcome.needs_operator": "手動対応が必要",
"console.updates.schedule_outcome.switch_failed": "切り替え失敗",
"console.updates.schedule_outcome.cancelled": "キャンセル済み",
"console.updates.schedule_outcome.restarting": "再起動中",
"console.error.incompatible_schedules": "このセットは現在のゲームおよび GameData バージョンと互換性がありません。",
"console.error.confirming_update": "前回の更新の動作確認中です。正常動作の確認が完了するまでお待ちください。",
"console.updates.component": "更新内容",
"console.updates.component.server": "サーバープログラム"
}
@@ -486,5 +486,21 @@
"console.updates.apply.body_now": "준비가 완료되면 즉시 신규 로그인을 차단하고 진행 중인 요청을 마무리한 뒤 저장하여 %[1]s(으)로 전환합니다.",
"console.updates.scheduled": "점검을 예약했습니다.",
"console.updates.cancelled": "점검을 취소했습니다.",
"console.updates.checking": "확인 중…"
"console.updates.checking": "확인 중…",
"console.updates.schedules.title": "일정 업데이트",
"console.updates.schedules.bundled": "기본 제공 일정",
"console.updates.schedules.game": "게임 버전",
"console.updates.schedules.gamedata": "GameData 버전",
"console.updates.schedules.up_to_date": "일정 업데이트가 없습니다.",
"console.updates.schedules.confirm": "준비 후 %[1]s분 동안 대기하고 요청 처리와 저장을 마친 다음 일정 세트 %[2]s로 현재 서버를 다시 시작합니다.",
"console.updates.schedule_outcome.succeeded": "성공",
"console.updates.schedule_outcome.rolled_back": "이전 일정 복원됨",
"console.updates.schedule_outcome.needs_operator": "수동 조치 필요",
"console.updates.schedule_outcome.switch_failed": "전환 실패",
"console.updates.schedule_outcome.cancelled": "취소됨",
"console.updates.schedule_outcome.restarting": "다시 시작 중",
"console.error.incompatible_schedules": "현재 게임 및 GameData 버전과 호환되지 않는 일정입니다.",
"console.error.confirming_update": "이전 업데이트의 정상 작동을 확인하는 중입니다. 확인이 완료될 때까지 기다려 주세요.",
"console.updates.component": "업데이트 내용",
"console.updates.component.server": "서버 프로그램"
}
@@ -9,7 +9,6 @@
"console.copy.failed": "复制失败,请手动选择",
"console.dialog.ok": "确定",
"console.dialog.cancel": "取消",
"console.error.unauthorized": "登录已过期,请重新登录。",
"console.error.forbidden": "没有权限执行这个操作。",
"console.error.csrf": "页面已过期,请刷新后重试。",
@@ -35,7 +34,6 @@
"console.error.no_maintenance": "当前没有安排维护。",
"console.error.maintenance_closing": "维护已进入排空阶段,不能再取消。",
"console.error.http": "请求失败(%[1]s)",
"console.nav.mail": "邮件发放",
"console.nav.players": "玩家",
"console.nav.config": "服务器配置",
@@ -51,7 +49,6 @@
"console.leave.title": "离开前保存配置?",
"console.leave.body": "有尚未保存的配置改动。离开后改动会保留在本页,直到刷新或退出。",
"console.leave.ok": "仍然离开",
"console.signin.title": "进入管理台",
"console.signin.loading": "正在读取服务器信息……",
"console.signin.local": "这台服务器使用本地认证。请打开服务端启动时在控制台打印的一次性登录链接。",
@@ -63,7 +60,6 @@
"console.signin.open_page": "打开登录页面",
"console.signin.success": "登录成功。",
"console.signin.no_permissions": "服主还没有给你分配任何权限。",
"console.mail.recipient": "收件人",
"console.mail.copy_uid": "点击复制 UID",
"console.mail.switch_player": "切换玩家",
@@ -146,7 +142,6 @@
"console.mail.log.again_title": "把这件物品和数量重新放进包裹单",
"console.mail.log.identity": "发放标识",
"console.mail.log.identity_title": "点击复制发放标识",
"console.roster.title": "玩家",
"console.roster.lead": "按游戏账号任命管理员,对方用自己的游戏账号登录管理台。管理员默认可以寄件和查看玩家,其余权限由服主逐项授予。",
"console.roster.search.placeholder": "UID 或名称",
@@ -192,7 +187,6 @@
"console.permissions.write": "修改",
"console.permissions.read_aria": "%[1]s %[2]s 查看",
"console.permissions.write_aria": "%[1]s %[2]s 修改",
"console.config.documents": "配置文件",
"console.config.show_diff": "查看改动",
"console.config.discard": "放弃",
@@ -257,7 +251,6 @@
"console.overview.data_dir": "数据目录",
"console.overview.mail_spool": "邮件队列",
"console.overview.dev_tools": "开发覆盖",
"config.problem.item": "第 %[1]s 项:%[2]s",
"config.problem.enum": "不支持这个值",
"config.problem.enum_options": "只能选择:%[1]s",
@@ -300,7 +293,6 @@
"config.problem.message.object": "必须是对象",
"config.problem.message.present": "文件中必须写明这一项",
"config.problem.message.hidden_section": "你无权查看的分组中存在问题,请联系服主处理",
"config.game.title": "游戏规则",
"config.game.summary": "服务端统一的玩法规则。修改后重启服务端生效。",
"config.game.section.story.title": "开局章节",
@@ -388,7 +380,6 @@
"config.game.field.text_moderation.provider.severity_threshold.help": "任一类别达到该严重程度即拒绝;0 表示连严重程度 0 的结果也拒绝。",
"config.game.section.format.title": "格式",
"config.game.field.schema_version.label": "格式版本",
"config.authentication.title": "登录与认证",
"config.authentication.summary": "玩家登录方式。修改后重启服务端生效;密钥只从环境变量读取,不写入此文件。",
"config.authentication.section.mode.title": "认证模式",
@@ -411,7 +402,6 @@
"config.authentication.field.session.access_ttl.label": "访问令牌有效期",
"config.authentication.field.session.refresh_ttl.label": "刷新令牌有效期",
"config.authentication.field.session.device_transaction_ttl.label": "登录事务有效期",
"config.resources.title": "客户端资源",
"config.resources.summary": "客户端下载 ServerData 与 GameData 的来源。修改后重启服务端生效;版本号来自 versions.json,不在此配置。",
"config.resources.section.source.title": "资源来源",
@@ -424,7 +414,6 @@
"config.resources.field.server_data_url.help": "绝对 HTTP(S) 地址,末尾不带斜杠;除回环地址外必须使用 HTTPS。",
"config.resources.field.game_data_url.label": "GameData 地址",
"config.resources.field.game_data_url.help": "绝对 HTTP(S) 地址,末尾不带斜杠;除回环地址外必须使用 HTTPS。",
"config.updates.title": "版本更新",
"config.updates.summary": "检查新版、预下载与维护更新方式。检查与下载不影响游戏;更新需要在管理台或命令行确认。修改后重启服务端生效。",
"config.updates.section.check.title": "检查与下载",
@@ -450,7 +439,6 @@
"config.updates.field.maintenance_minutes.label": "预计维护时长(分钟)",
"config.updates.field.webhook_url_env.label": "Webhook 环境变量",
"config.updates.field.webhook_url_env.help": "发现新版时向该环境变量中的地址 POST 一次 JSON;留空不发送。",
"console.updates.title": "版本更新",
"console.updates.lead": "服务端按间隔检查签名的发布清单,可提前下载并校验。应用更新会先通知在线玩家、关闭新登录、排空请求并保存,再切换到新版。",
"console.updates.check": "立即检查",
@@ -498,5 +486,21 @@
"console.updates.apply.body_now": "准备完成后立即关闭新登录、排空、保存并切换到 %[1]s。",
"console.updates.scheduled": "已安排维护。",
"console.updates.cancelled": "已取消维护。",
"console.updates.checking": "正在检查……"
"console.updates.checking": "正在检查……",
"console.updates.schedules.title": "排期更新",
"console.updates.schedules.bundled": "随程序附带的排期",
"console.updates.schedules.game": "游戏版本",
"console.updates.schedules.gamedata": "GameData 版本",
"console.updates.schedules.up_to_date": "暂无排期更新。",
"console.updates.schedules.confirm": "准备完成后倒计时 %[1]s 分钟,排空和保存,然后使用排期集 %[2]s 重启当前服务端。",
"console.updates.schedule_outcome.succeeded": "成功",
"console.updates.schedule_outcome.rolled_back": "已恢复之前的排期",
"console.updates.schedule_outcome.needs_operator": "需要人工处理",
"console.updates.schedule_outcome.switch_failed": "切换失败",
"console.updates.schedule_outcome.cancelled": "已取消",
"console.updates.schedule_outcome.restarting": "正在重启",
"console.error.incompatible_schedules": "此排期集与当前游戏及 GameData 版本不兼容。",
"console.error.confirming_update": "上一次更新仍在进行健康检查,请等待确认完成。",
"console.updates.component": "更新内容",
"console.updates.component.server": "服务端程序"
}
@@ -486,5 +486,21 @@
"console.updates.apply.body_now": "準備完成後會立即停止接受新登入,等待進行中的請求完成、儲存並切換至 %[1]s。",
"console.updates.scheduled": "已安排維護。",
"console.updates.cancelled": "已取消維護。",
"console.updates.checking": "正在檢查……"
"console.updates.checking": "正在檢查……",
"console.updates.schedules.title": "排期更新",
"console.updates.schedules.bundled": "程式隨附的排期",
"console.updates.schedules.game": "遊戲版本",
"console.updates.schedules.gamedata": "GameData 版本",
"console.updates.schedules.up_to_date": "暫無排期更新。",
"console.updates.schedules.confirm": "準備完成後倒數 %[1]s 分鐘,排空及儲存,再使用排期集 %[2]s 重新啟動目前伺服器。",
"console.updates.schedule_outcome.succeeded": "成功",
"console.updates.schedule_outcome.rolled_back": "已還原先前排期",
"console.updates.schedule_outcome.needs_operator": "需要人工處理",
"console.updates.schedule_outcome.switch_failed": "切換失敗",
"console.updates.schedule_outcome.cancelled": "已取消",
"console.updates.schedule_outcome.restarting": "正在重新啟動",
"console.error.incompatible_schedules": "此排期集與目前遊戲及 GameData 版本不相容。",
"console.error.confirming_update": "上次更新仍在進行健康檢查,請等待確認完成。",
"console.updates.component": "更新內容",
"console.updates.component.server": "伺服器程式"
}
+6
View File
@@ -142,6 +142,12 @@
<div><h2 data-i18n="console.updates.title"></h2><p class="muted" data-i18n="console.updates.lead"></p></div>
<button type="button" class="btn" id="update-check" data-i18n="console.updates.check"></button>
</div>
<label><span data-i18n="console.updates.component"></span>
<select id="update-component">
<option value="server" data-i18n="console.updates.component.server"></option>
<option value="schedules" data-i18n="console.updates.schedules.title"></option>
</select>
</label>
<dl class="update-facts" id="update-facts"></dl>
<div id="update-available"></div>
<div class="update-actions" id="update-actions"></div>
+14 -10
View File
@@ -47,6 +47,7 @@ type configuration struct {
versions versionconfig.Config
compatibility updateCompatibility
calendars *calendar.Set
scheduleID string
gameRules gameconfig.Config
gameFile *commonconfig.File[gameconfig.Config]
authFile *commonconfig.File[authconfig.Config]
@@ -113,15 +114,6 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
}
}
versionconfig.Use(versions)
calendarDirectory := versions.Resolve("schedules")
calendars, err := calendar.LoadDirectory(calendarDirectory, versions.GameVersion, versions.GameDataVersion)
if err != nil {
return nil, fmt.Errorf("load project calendars: %w", err)
}
if calendars.RegularService == nil || calendars.MonsterHunt == nil || len(calendars.MonsterHunt.Seasons) == 0 {
return nil, errors.New("project calendars require regular content and monster hunt schedules")
}
slog.Info("project calendars loaded", "directory", calendarDirectory, "revisions", calendars.Revisions, "events", len(calendars.Events))
if *dataDir == "" {
executable, executableErr := os.Executable()
if executableErr != nil {
@@ -133,6 +125,18 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
if err != nil {
return nil, fmt.Errorf("resolve server data directory: %w", err)
}
calendarDirectory, scheduleID, err := updates.ScheduleDirectory(*dataDir, versions.Resolve("schedules"), versions.GameVersion, versions.GameDataVersion)
if err != nil {
return nil, fmt.Errorf("select project calendars: %w", err)
}
calendars, err := calendar.LoadDirectory(calendarDirectory, versions.GameVersion, versions.GameDataVersion)
if err != nil {
return nil, fmt.Errorf("load project calendars: %w", err)
}
if calendars.RegularService == nil || calendars.MonsterHunt == nil || len(calendars.MonsterHunt.Seasons) == 0 {
return nil, errors.New("project calendars require regular content and monster hunt schedules")
}
slog.Info("project calendars loaded", "directory", calendarDirectory, "revisions", calendars.Revisions, "events", len(calendars.Events))
configDirectory := filepath.Join(*dataDir, "config")
if *gameConfigPath == "" {
*gameConfigPath = gameconfig.Document.Path(configDirectory)
@@ -259,7 +263,7 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
deckSeed: *deckSeed,
worldSeed: *worldSeed,
devToolsConfig: *devToolsConfig,
versions: versions, calendars: calendars, gameRules: gameRules, gameFile: gameFile, authFile: authFile, resourceFile: resourceFile, updateFile: updateFile, updates: updateConfig, notices: notice.NewBoard(nil), serveArgs: args, authentication: authentication, authRuntime: authRuntime, publicResources: publicResources, bootstrap: cfg, gameData: gameData, verifiedGameData: verifiedGameData,
versions: versions, calendars: calendars, scheduleID: scheduleID, gameRules: gameRules, gameFile: gameFile, authFile: authFile, resourceFile: resourceFile, updateFile: updateFile, updates: updateConfig, notices: notice.NewBoard(nil), serveArgs: args, authentication: authentication, authRuntime: authRuntime, publicResources: publicResources, bootstrap: cfg, gameData: gameData, verifiedGameData: verifiedGameData,
compatibility: compatibility,
}, nil
}
+14 -1
View File
@@ -5,6 +5,7 @@ import (
"bd2server/internal/common/i18n"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/events/calendar"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/gateway/auth"
"bd2server/internal/server/gateway/session"
@@ -134,9 +135,21 @@ func Serve(args []string) (serveErr error) {
defer func() { serveErr = errors.Join(serveErr, consoleStore.Close()) }()
var stopOnce sync.Once
stopForUpdate := make(chan struct{})
updater := updates.New(updates.Options{
fingerprintID := ""
if c.compatibility.fingerprint != nil {
fingerprintID = c.compatibility.fingerprint.ID
}
updater := updates.New(updates.Options{FingerprintID: fingerprintID,
Config: c.updates, DataDir: c.dataDir, StateDirs: []string{c.stateDirectory, filepath.Join(c.dataDir, "config")},
ServerVersion: c.versions.ServerVersion, ServeArgs: c.serveArgs, Board: c.notices, BundledChangelog: c.versions.Resolve("CHANGELOG.md"),
GameVersion: c.versions.GameVersion, BundleVersion: c.versions.BundleVersion, GameDataVersion: c.versions.GameDataVersion, CurrentSchedules: c.scheduleID,
ValidateSchedules: func(directory string) error {
set, err := calendar.LoadDirectory(directory, c.versions.GameVersion, c.versions.GameDataVersion)
if err != nil {
return err
}
return set.ValidateDesign(c.gameData, c.gameDataVersion)
},
Shutdown: func() { stopOnce.Do(func() { close(stopForUpdate) }) },
})
console.AttachUpdates(updater)
@@ -98,12 +98,14 @@ var Document = commonconfig.Document[Config]{
default:
problems = append(problems, commonconfig.Problem{Path: "method", Rule: commonconfig.RuleEnum, Message: "部署方式必须是 native、docker 或 none"})
}
for i, address := range append([]string{c.ManifestURL}, c.ChangelogURLs...) {
if address == "" && i == 0 {
continue
}
if _, err := release.Resolve(address, address); err != nil {
problems = append(problems, commonconfig.Problem{Path: map[bool]string{true: "manifest_url", false: "changelog_urls"}[i == 0], Rule: commonconfig.RuleFormat, Message: err.Error()})
for field, addresses := range map[string][]string{"manifest_url": {c.ManifestURL}, "changelog_urls": c.ChangelogURLs} {
for _, address := range addresses {
if address == "" && field != "changelog_urls" {
continue
}
if _, err := release.Resolve(address, address); err != nil {
problems = append(problems, commonconfig.Problem{Path: field, Rule: commonconfig.RuleFormat, Message: err.Error()})
}
}
}
return problems
@@ -2,5 +2,8 @@
"maintenance.title": "Server maintenance",
"maintenance.banner": "The server goes down for maintenance at %[2]s to update to %[1]s, for about %[3]d minutes. Please finish your battles before then.",
"maintenance.body": "Maintenance starts at %[2]s and updates the server to %[1]s. It should take about %[3]d minutes.\nPlease finish any battle or room before it starts; saved progress is not affected. See the update notes for what changes.",
"maintenance.login": "The server is updating to %[1]s and should be back in about %[3]d minutes."
"maintenance.login": "The server is updating to %[1]s and should be back in about %[3]d minutes.",
"maintenance.schedules.banner": "The server goes down at %[2]s to update schedules (%[1]s), for about %[3]d minutes. Please finish your battles before then.",
"maintenance.schedules.body": "Schedule maintenance starts at %[2]s and should take about %[3]d minutes. The server will save and restart with schedule set %[1]s. Please finish battles and rooms before then.",
"maintenance.schedules.login": "Schedule maintenance (%[1]s) is in progress. The server should be back in about %[3]d minutes."
}
@@ -2,5 +2,8 @@
"maintenance.title": "サーバーメンテナンスのお知らせ",
"maintenance.banner": "%[2]s からメンテナンスを行い、サーバーを %[1]s に更新します(約 %[3]d 分)。それまでに戦闘を終えてください。",
"maintenance.body": "%[2]s からメンテナンスを開始し、サーバーを %[1]s に更新します。所要時間は約 %[3]d 分の予定です。\n開始前に進行中の戦闘やルームを終えてください。保存済みの進行状況には影響ありません。変更内容は更新のお知らせをご確認ください。",
"maintenance.login": "サーバーを %[1]s に更新中です。約 %[3]d 分後に再開予定です。"
"maintenance.login": "サーバーを %[1]s に更新中です。約 %[3]d 分後に再開予定です。",
"maintenance.schedules.banner": "スケジュール(%[1]s)更新のため %[2]s にメンテナンスを開始します。約 %[3]d 分かかります。事前に戦闘を終了してください。",
"maintenance.schedules.body": "スケジュールのメンテナンスは %[2]s 開始、約 %[3]d 分の予定です。保存後にセット %[1]s で再起動します。事前に戦闘とルームを終了してください。",
"maintenance.schedules.login": "スケジュール(%[1]s)更新中です。約 %[3]d 分で再開する予定です。"
}
@@ -2,5 +2,8 @@
"maintenance.title": "서버 점검 안내",
"maintenance.banner": "%[2]s에 서버 점검이 시작되어 %[1]s(으)로 업데이트됩니다. 약 %[3]d분 소요 예정이니 전투를 미리 마쳐 주세요.",
"maintenance.body": "%[2]s에 점검이 시작되며 서버가 %[1]s(으)로 업데이트됩니다. 약 %[3]d분 소요될 예정입니다.\n점검 시작 전에 진행 중인 전투를 끝내고 방에서 나와 주세요. 저장된 진행 상황에는 영향이 없습니다. 변경 사항은 업데이트 공지를 확인해 주세요.",
"maintenance.login": "서버가 %[1]s(으)로 업데이트 중입니다. 약 %[3]d분 후에 다시 이용할 수 있습니다."
"maintenance.login": "서버가 %[1]s(으)로 업데이트 중입니다. 약 %[3]d분 후에 다시 이용할 수 있습니다.",
"maintenance.schedules.banner": "일정(%[1]s) 업데이트를 위해 %[2]s에 점검을 시작합니다. 약 %[3]d분이 소요됩니다. 미리 전투를 끝내 주세요.",
"maintenance.schedules.body": "일정 점검은 %[2]s에 시작하며 약 %[3]d분이 소요됩니다. 저장 후 일정 세트 %[1]s로 다시 시작합니다. 미리 전투와 방을 종료해 주세요.",
"maintenance.schedules.login": "일정(%[1]s) 업데이트 점검 중입니다. 약 %[3]d분 후에 재개될 예정입니다."
}
@@ -2,5 +2,8 @@
"maintenance.title": "服务器维护公告",
"maintenance.banner": "服务器将于 %[2]s 维护更新至 %[1]s,预计 %[3]d 分钟,请提前结束战斗。",
"maintenance.body": "服务器将于 %[2]s 开始维护,更新至 %[1]s,预计持续 %[3]d 分钟。\n维护开始前请结束正在进行的战斗与房间;已保存的进度不受影响。更新内容见更新日志公告。",
"maintenance.login": "服务器正在维护更新至 %[1]s,预计 %[3]d 分钟后恢复。"
"maintenance.login": "服务器正在维护更新至 %[1]s,预计 %[3]d 分钟后恢复。",
"maintenance.schedules.banner": "服务器将于 %[2]s 维护更新排期(%[1]s),预计 %[3]d 分钟,请提前结束战斗。",
"maintenance.schedules.body": "排期维护将于 %[2]s 开始,预计持续 %[3]d 分钟。服务器将保存并使用排期集 %[1]s 重启,请提前结束战斗与房间。",
"maintenance.schedules.login": "服务器正在维护更新排期(%[1]s),预计 %[3]d 分钟后恢复。"
}
@@ -2,5 +2,8 @@
"maintenance.title": "伺服器維護公告",
"maintenance.banner": "伺服器將於 %[2]s 進行維護並更新至 %[1]s,預計 %[3]d 分鐘,請提前結束戰鬥。",
"maintenance.body": "伺服器將於 %[2]s 開始維護,更新至 %[1]s,預計持續 %[3]d 分鐘。\n維護開始前請結束進行中的戰鬥與房間;已儲存的進度不受影響。更新內容請參閱更新日誌公告。",
"maintenance.login": "伺服器正在維護並更新至 %[1]s,預計 %[3]d 分鐘後恢復。"
"maintenance.login": "伺服器正在維護並更新至 %[1]s,預計 %[3]d 分鐘後恢復。",
"maintenance.schedules.banner": "伺服器將於 %[2]s 維護更新排期(%[1]s),預計 %[3]d 分鐘,請提前結束戰鬥。",
"maintenance.schedules.body": "排期維護將於 %[2]s 開始,預計持續 %[3]d 分鐘。伺服器將儲存並使用排期集 %[1]s 重新啟動,請提前結束戰鬥及房間。",
"maintenance.schedules.login": "伺服器正在維護更新排期(%[1]s),預計 %[3]d 分鐘後恢復。"
}
@@ -0,0 +1,373 @@
package updates
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"path/filepath"
"strings"
"time"
"bd2server/internal/common/release"
"bd2server/internal/server/domain/events/calendar"
)
const (
ComponentSchedules = "schedules"
ComponentServer = "server"
scheduleSelectionFile = "schedules-active.json"
schedulePendingFile = "schedules-pending.json"
scheduleResultFile = "schedules-result.json"
)
type ScheduleStatus struct {
CurrentID string `json:"current_id"`
GameVersion string `json:"game_version"`
GameDataVersion string `json:"game_data_version"`
Available *ScheduleAvailable `json:"available,omitempty"`
LastResult *Result `json:"last_result,omitempty"`
}
type ScheduleAvailable struct {
Component release.Schedules `json:"component"`
PublishedAt time.Time `json:"published_at"`
Downloaded bool `json:"downloaded"`
DownloadError string `json:"download_error,omitempty"`
Incompatible string `json:"incompatible,omitempty"`
ManifestURL string `json:"-"`
SignedManifest []byte `json:"-"`
}
type scheduleSelection struct {
ID string `json:"id"`
GameVersion string `json:"game_version"`
GameDataVersion string `json:"game_data_version"`
}
type SchedulePlan struct {
ID string
GameVersion string
GameDataVersion string
}
type schedulePending struct {
From string `json:"from"`
To string `json:"to"`
Previous *scheduleSelection `json:"previous,omitempty"`
Attempts int `json:"attempts"`
}
func scheduleRoot(dataDir, id string) (string, error) {
if len(id) != 64 || strings.Trim(id, "0123456789abcdef") != "" {
return "", errors.New("invalid schedules content ID")
}
return filepath.Join(directory(dataDir), "schedules", id), nil
}
func scheduleCompatible(s release.Schedules, game, gameData string) error {
if s.GameVersion != game || s.GameDataVersion != gameData {
return fmt.Errorf("schedules require game %s / GameData %s; running %s / %s", s.GameVersion, s.GameDataVersion, game, gameData)
}
return nil
}
func (s *Service) updateSchedulesLocked(manifest release.Manifest, signed []byte, address string) *ScheduleAvailable {
candidate := manifest.Schedules
if candidate == nil || candidate.ID == s.options.CurrentSchedules {
s.status.Schedules.Available = nil
return nil
}
previous := s.status.Schedules.Available
a := &ScheduleAvailable{Component: *candidate, PublishedAt: manifest.PublishedAt, ManifestURL: address, SignedManifest: append([]byte(nil), signed...)}
if err := scheduleCompatible(*candidate, s.options.GameVersion, s.options.GameDataVersion); err != nil {
a.Incompatible = err.Error()
}
if previous != nil && previous.Component.ID == candidate.ID {
a.Downloaded, a.DownloadError = previous.Downloaded, previous.DownloadError
} else {
slog.Info("schedule update available", "current", s.options.CurrentSchedules, "available", candidate.ID, "compatible", a.Incompatible == "", "apply", "bd2server update apply --component schedules")
}
s.status.Schedules.Available = a
return a
}
func (s *Service) preDownloadSchedules(ctx context.Context, a *ScheduleAvailable) {
if a == nil || a.Incompatible != "" || !s.options.Config.Download || s.options.Config.Method == MethodNone {
return
}
if _, err := s.prepareSchedules(ctx, a); err != nil {
slog.Warn("schedule pre-download failed", "id", a.Component.ID, "error", err)
}
}
func verifyScheduleFiles(root string, s release.Schedules) error {
entries, err := os.ReadDir(root)
if err != nil {
return err
}
if len(entries) != len(s.Files) {
return errors.New("schedules directory differs from signed file set")
}
for _, f := range s.Files {
path := filepath.Join(root, f.Name)
info, err := os.Lstat(path)
if err != nil {
return err
}
if !info.Mode().IsRegular() || info.Size() != f.Size {
return fmt.Errorf("schedule %s is not a regular file of the signed size", f.Name)
}
sum, err := release.HashFile(path)
if err != nil {
return err
}
if sum != f.SHA256 {
return fmt.Errorf("schedule %s differs from signed digest", f.Name)
}
}
set, err := calendar.LoadDirectory(root, s.GameVersion, s.GameDataVersion)
if err != nil {
return err
}
if set.RegularService == nil || set.MonsterHunt == nil || len(set.MonsterHunt.Seasons) == 0 {
return errors.New("schedules require regular content and monster hunt seasons")
}
return nil
}
func loadScheduleSet(dataDir, id, game, gameData string) (string, error) {
root, err := scheduleRoot(dataDir, id)
if err != nil {
return "", err
}
info, err := os.Lstat(root)
if err != nil {
return "", err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return "", errors.New("schedules root must be a directory")
}
raw, err := os.ReadFile(filepath.Join(root, "manifest.json"))
if err != nil {
return "", err
}
manifest, err := release.Verify(raw, release.BuiltinChannel().TrustedKeys)
if err != nil {
return "", err
}
if manifest.Channel != release.BuiltinChannel().Name || manifest.Schedules == nil || manifest.Schedules.ID != id {
return "", errors.New("cached schedules do not match signed manifest")
}
if err := scheduleCompatible(*manifest.Schedules, game, gameData); err != nil {
return "", err
}
files := filepath.Join(root, "files")
info, err = os.Lstat(files)
if err != nil {
return "", err
}
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
return "", errors.New("schedules files must be a directory")
}
return files, verifyScheduleFiles(files, *manifest.Schedules)
}
// ScheduleDirectory selects an installed signed set for this exact data version.
// A program/GameData upgrade uses its bundled schedules until a compatible set
// is explicitly applied; it never tries to reinterpret an older set.
func ScheduleDirectory(dataDir, bundled, game, gameData string) (string, string, error) {
var selected scheduleSelection
if err := readJSON(filepath.Join(directory(dataDir), scheduleSelectionFile), &selected); errors.Is(err, os.ErrNotExist) {
return bundled, "", nil
} else if err != nil {
return "", "", err
}
if selected.GameVersion != game || selected.GameDataVersion != gameData {
return bundled, "", nil
}
path, err := loadScheduleSet(dataDir, selected.ID, game, gameData)
return path, selected.ID, err
}
func (s *Service) prepareSchedules(ctx context.Context, a *ScheduleAvailable) (string, error) {
if a == nil {
return "", errors.New("no schedule update available")
}
s.stageMu.Lock()
defer s.stageMu.Unlock()
root, err := s.stageSchedules(ctx, a)
s.mu.Lock()
if current := s.status.Schedules.Available; current != nil && current.Component.ID == a.Component.ID {
current.Downloaded = err == nil
current.DownloadError = ""
if err != nil {
current.DownloadError = err.Error()
}
s.persistLocked()
}
s.mu.Unlock()
return root, err
}
func (s *Service) stageSchedules(ctx context.Context, a *ScheduleAvailable) (string, error) {
if a == nil {
return "", errors.New("no schedule update available")
}
manifest, err := release.Verify(a.SignedManifest, s.keys)
if err != nil {
return "", err
}
if manifest.Schedules == nil || manifest.Schedules.ID != a.Component.ID || manifest.Channel != release.BuiltinChannel().Name {
return "", errors.New("schedule candidate does not match signed manifest")
}
candidate := *manifest.Schedules
if err := scheduleCompatible(candidate, s.options.GameVersion, s.options.GameDataVersion); err != nil {
return "", err
}
root, err := scheduleRoot(s.options.DataDir, candidate.ID)
if err != nil {
return "", err
}
if _, err := os.Lstat(root); err == nil {
files, err := loadScheduleSet(s.options.DataDir, candidate.ID, s.options.GameVersion, s.options.GameDataVersion)
if err == nil && s.options.ValidateSchedules != nil {
err = s.options.ValidateSchedules(files)
}
return files, err
} else if !errors.Is(err, os.ErrNotExist) {
return "", err
}
if err := os.MkdirAll(filepath.Dir(root), 0o700); err != nil {
return "", err
}
temporary, err := os.MkdirTemp(filepath.Dir(root), ".staging-")
if err != nil {
return "", err
}
defer func() { _ = os.RemoveAll(temporary) }()
files := filepath.Join(temporary, "files")
for _, file := range candidate.Files {
if _, err := release.Download(ctx, s.options.Client, a.ManifestURL, file, files, nil); err != nil {
return "", err
}
}
if err := verifyScheduleFiles(files, candidate); err != nil {
return "", err
}
if s.options.ValidateSchedules != nil {
if err := s.options.ValidateSchedules(files); err != nil {
return "", err
}
}
if err := os.WriteFile(filepath.Join(temporary, "manifest.json"), a.SignedManifest, 0o600); err != nil {
return "", err
}
if err := ctx.Err(); err != nil {
return "", err
}
if err := os.Rename(temporary, root); err != nil {
return "", err
}
return filepath.Join(root, "files"), nil
}
func (p *Plan) switchSchedules(now time.Time) error {
s := p.Schedules
if _, err := loadScheduleSet(p.DataDir, s.ID, s.GameVersion, s.GameDataVersion); err != nil {
return err
}
var previous scheduleSelection
err := readJSON(filepath.Join(directory(p.DataDir), scheduleSelectionFile), &previous)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
record := schedulePending{From: p.From, To: s.ID}
if err == nil {
record.Previous = &previous
}
if err := writeJSON(filepath.Join(directory(p.DataDir), schedulePendingFile), record); err != nil {
return err
}
selected := scheduleSelection{ID: s.ID, GameVersion: s.GameVersion, GameDataVersion: s.GameDataVersion}
if err := writeJSON(filepath.Join(directory(p.DataDir), scheduleSelectionFile), selected); err != nil {
_ = os.Remove(filepath.Join(directory(p.DataDir), schedulePendingFile))
return err
}
recordScheduleResult(p.DataDir, Result{From: p.From, To: p.To, Outcome: "restarting", At: now.UTC()})
return nil
}
func scheduleStartup(dataDir string) (*Confirmation, int, error) {
path := filepath.Join(directory(dataDir), schedulePendingFile)
var record schedulePending
if err := readJSON(path, &record); errors.Is(err, os.ErrNotExist) {
return nil, 0, nil
} else if err != nil {
return nil, ExitNeedsOperator, err
}
var selected scheduleSelection
if err := readJSON(filepath.Join(directory(dataDir), scheduleSelectionFile), &selected); err != nil {
if errors.Is(err, os.ErrNotExist) && record.Previous == nil {
return nil, 0, os.Remove(path)
}
return nil, ExitNeedsOperator, err
}
if selected.ID != record.To {
if record.Previous != nil && selected == *record.Previous {
return nil, 0, os.Remove(path)
}
return nil, ExitNeedsOperator, errors.New("pending schedules differ from active selection")
}
record.Attempts++
if record.Attempts > maxStartAttempts {
code, err := rollbackSchedules(dataDir, record, "repeated startup failures")
return nil, code, err
}
if err := writeJSON(path, record); err != nil {
return nil, ExitNeedsOperator, err
}
return &Confirmation{dataDir: dataDir, schedules: &record}, 0, nil
}
func rollbackSchedules(dataDir string, record schedulePending, reason string) (int, error) {
path := filepath.Join(directory(dataDir), scheduleSelectionFile)
var err error
if record.Previous == nil {
err = os.Remove(path)
if errors.Is(err, os.ErrNotExist) {
err = nil
}
} else {
err = writeJSON(path, record.Previous)
}
if err != nil {
return ExitNeedsOperator, fmt.Errorf("restore previous schedules: %w", err)
}
if err := os.Remove(filepath.Join(directory(dataDir), schedulePendingFile)); err != nil && !errors.Is(err, os.ErrNotExist) {
return ExitNeedsOperator, err
}
message := "previous schedule selection restored: " + reason
recordScheduleResult(dataDir, Result{From: record.From, To: record.To, Outcome: OutcomeRolledBack, Message: message, At: time.Now().UTC()})
return ExitRestart, errors.New(message)
}
func recordScheduleResult(dataDir string, result Result) {
if err := writeJSON(filepath.Join(directory(dataDir), scheduleResultFile), result); err != nil {
slog.Warn("schedule result could not be saved", "error", err)
}
}
func mergeScheduleResult(dataDir string, status *Status) {
var result Result
if err := readJSON(filepath.Join(directory(dataDir), scheduleResultFile), &result); err != nil {
return
}
if status.Schedules == nil {
status.Schedules = &ScheduleStatus{}
}
if previous := status.Schedules.LastResult; previous == nil || result.At.After(previous.At) {
status.Schedules.LastResult = &result
}
}
+148 -34
View File
@@ -33,8 +33,14 @@ type Options struct {
Config Config
DataDir string
// StateDirs are copied before a release that requires a backup.
StateDirs []string
ServerVersion string
StateDirs []string
FingerprintID string
ServerVersion string
GameVersion string
BundleVersion string
GameDataVersion string
CurrentSchedules string
ValidateSchedules func(string) error
// ServeArgs are the running serve flags, reused to preflight a staged package.
ServeArgs []string
Board *notice.Board
@@ -66,11 +72,15 @@ func New(options Options) *Service {
}
s := &Service{options: options, keys: release.BuiltinChannel().TrustedKeys, wake: make(chan struct{}, 1)}
s.status = Status{CurrentVersion: options.ServerVersion, Method: options.Config.Method, CheckEnabled: options.Config.Check, Countdown: options.Config.CountdownMinutes, ManifestURL: options.Config.manifestURL()}
s.status.Schedules = &ScheduleStatus{CurrentID: options.CurrentSchedules, GameVersion: options.GameVersion, GameDataVersion: options.GameDataVersion}
var previous Status
if err := readJSON(filepath.Join(directory(options.DataDir), stateFile), &previous); err == nil {
s.status.Notified = previous.Notified
s.status.LastResult = previous.LastResult
s.status.LastCheck = previous.LastCheck
if previous.Schedules != nil {
s.status.Schedules.LastResult = previous.Schedules.LastResult
}
}
return s
}
@@ -85,6 +95,14 @@ func (s *Service) Status() Status {
s.mu.Lock()
defer s.mu.Unlock()
out := s.status
if out.Schedules != nil {
copy := *out.Schedules
if copy.Available != nil {
a := *copy.Available
copy.Available = &a
}
out.Schedules = &copy
}
if out.Available != nil {
copy := *out.Available
out.Available = &copy
@@ -94,10 +112,12 @@ func (s *Service) Status() Status {
out.Maintenance = &copy
}
mergeHostResult(s.options.DataDir, &out)
mergeScheduleResult(s.options.DataDir, &out)
return out
}
func (s *Service) persistLocked() {
mergeScheduleResult(s.options.DataDir, &s.status)
s.status.UpdatedAt = s.options.Now().UTC()
if err := writeJSON(filepath.Join(directory(s.options.DataDir), stateFile), s.status); err != nil {
slog.Warn("update status could not be saved", "error", err)
@@ -208,7 +228,7 @@ func (s *Service) check(ctx context.Context) {
}
address := s.options.Config.manifestURL()
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
manifest, _, err := release.FetchManifest(fetchCtx, s.options.Client, address, s.keys)
manifest, signed, err := release.FetchManifest(fetchCtx, s.options.Client, address, s.keys)
cancel()
s.mu.Lock()
s.status.LastCheck = s.options.Now().UTC()
@@ -228,27 +248,43 @@ func (s *Service) check(ctx context.Context) {
s.mu.Unlock()
return
}
schedule := s.updateSchedulesLocked(manifest, signed, address)
server := manifest.Server
if server == nil || !newer(s.options.ServerVersion, server.Version) {
resourceRevision := server != nil && server.Version == s.options.ServerVersion && manifest.Fingerprint != nil &&
s.options.FingerprintID != "" && manifest.Fingerprint.ID != s.options.FingerprintID && manifest.Fingerprint.RequireGameUpdate && manifest.Fingerprint.Game != nil &&
manifest.Fingerprint.Game.GameVersion == s.options.GameVersion &&
manifest.Fingerprint.Game.GameDataVersion >= s.options.GameDataVersion && manifest.Fingerprint.Game.BundleVersion >= s.options.BundleVersion &&
(manifest.Fingerprint.Game.GameDataVersion > s.options.GameDataVersion || manifest.Fingerprint.Game.BundleVersion > s.options.BundleVersion)
if server == nil || !newer(s.options.ServerVersion, server.Version) && !resourceRevision {
s.status.Available = nil
s.persistLocked()
s.mu.Unlock()
s.preDownloadSchedules(ctx, schedule)
return
}
if s.status.Available == nil || s.status.Available.Version != server.Version {
if s.status.Available == nil || s.status.Available.Version != server.Version ||
manifest.Fingerprint != nil && (s.status.Available.Fingerprint == nil || s.status.Available.Fingerprint.ID != manifest.Fingerprint.ID) {
s.status.Available = &Available{Version: server.Version, Date: server.Date, Notes: server.Notes, PublishedAt: manifest.PublishedAt, Commit: manifest.Commit, Image: server.Image, Migration: *server.Migration, Component: server, ManifestURL: address, Fingerprint: manifest.Fingerprint}
}
announce := s.logged != server.Version
s.logged = server.Version
notify := s.status.Notified != server.Version
identity := server.Version
if manifest.Fingerprint != nil {
identity += ":" + manifest.Fingerprint.ID
}
if s.status.Available.Fingerprint != nil && s.status.Available.Fingerprint.Game != nil {
s.status.Available.GameDataVersion = s.status.Available.Fingerprint.Game.GameDataVersion
}
announce := s.logged != identity
s.logged = identity
notify := s.status.Notified != identity
s.persistLocked()
s.mu.Unlock()
s.preDownloadSchedules(ctx, schedule)
if announce {
slog.Info("server update available", "current", s.options.ServerVersion, "available", server.Version, "published_at", manifest.PublishedAt, "migration", server.Migration.Kind,
"apply", "admin console or `bd2server update apply`")
}
if notify {
s.sendWebhook(ctx, server, manifest.PublishedAt)
s.sendWebhook(ctx, server, manifest.PublishedAt, identity)
}
if s.options.Config.Download && s.options.Config.Method != MethodNone {
if _, err := s.prepareFiles(ctx, s.Status().Available); err != nil {
@@ -257,7 +293,7 @@ func (s *Service) check(ctx context.Context) {
}
}
func (s *Service) sendWebhook(ctx context.Context, server *release.Component, published time.Time) {
func (s *Service) sendWebhook(ctx context.Context, server *release.Component, published time.Time, identity string) {
address := s.options.Config.webhook()
if address != "" {
body, _ := json.Marshal(map[string]any{
@@ -282,7 +318,7 @@ func (s *Service) sendWebhook(ctx context.Context, server *release.Component, pu
}
}
s.mu.Lock()
s.status.Notified = server.Version
s.status.Notified = identity
s.persistLocked()
s.mu.Unlock()
}
@@ -309,7 +345,7 @@ func (s *Service) prepareFiles(ctx context.Context, available *Available) (strin
_, err = resourcefetch.Fetch(ctx, resourcefetch.Options{OutputRoot: ResourceDirectory(s.options.DataDir, *g), Client: s.options.Client, Pinned: g})
}
s.mu.Lock()
if s.status.Available != nil && s.status.Available.Version == available.Version {
if s.status.Available != nil && candidateIdentity(s.status.Available) == candidateIdentity(available) {
s.status.Available.Downloaded = err == nil
s.status.Available.DownloadError = ""
if err != nil {
@@ -321,6 +357,13 @@ func (s *Service) prepareFiles(ctx context.Context, available *Available) (strin
return staged, err
}
func candidateIdentity(a *Available) string {
if a.Fingerprint != nil {
return a.Version + "-" + a.Fingerprint.ID
}
return a.Version
}
func stage(ctx context.Context, client *http.Client, available *Available, dataDir string) (string, error) {
var archive *release.File
for _, f := range available.Component.FilesFor(release.Platform()) {
@@ -332,7 +375,7 @@ func stage(ctx context.Context, client *http.Client, available *Available, dataD
if archive == nil {
return "", fmt.Errorf("the release has no server package for %s", release.Platform())
}
downloads := filepath.Join(directory(dataDir), "downloads", available.Version)
downloads := filepath.Join(directory(dataDir), "downloads", candidateIdentity(available))
path, err := release.Download(ctx, client, available.ManifestURL, *archive, downloads, nil)
if err != nil {
return "", err
@@ -341,7 +384,7 @@ func stage(ctx context.Context, client *http.Client, available *Available, dataD
if err != nil {
return "", err
}
target := filepath.Join(install, ".update-staged", available.Version)
target := filepath.Join(install, ".update-staged", candidateIdentity(available))
temporary := target + ".tmp"
if err := os.RemoveAll(temporary); err != nil {
return "", err
@@ -378,43 +421,86 @@ func stage(ctx context.Context, client *http.Client, available *Available, dataD
// Schedule prepares the available release and, once it is ready, warns
// players and starts maintenance after delay.
func (s *Service) Schedule(delay time.Duration, confirmIrreversible bool, by string) error {
return s.schedule(ComponentServer, delay, confirmIrreversible, by)
}
func (s *Service) ScheduleSchedules(delay time.Duration, by string) error {
return s.schedule(ComponentSchedules, delay, false, by)
}
func (s *Service) schedule(component string, delay time.Duration, confirmIrreversible bool, by string) error {
s.mu.Lock()
defer s.mu.Unlock()
available := s.status.Available
var schedule *ScheduleAvailable
if component == ComponentSchedules {
schedule = s.status.Schedules.Available
}
switch {
case s.options.Config.Method == MethodNone:
return reject(RejectNotifyOnly, "the install method is notify-only")
case available == nil:
case component == ComponentServer && available == nil, component == ComponentSchedules && schedule == nil:
return reject(RejectNoUpdate, "no newer server release is available")
case s.status.Maintenance != nil:
return reject(RejectAlreadyScheduled, "a maintenance is already scheduled")
case available.Migration.Kind == release.MigrationIrreversible && !confirmIrreversible:
case component == ComponentSchedules && schedule.Incompatible != "":
return reject("incompatible_schedules", "%s", schedule.Incompatible)
case component == ComponentServer && available.Migration.Kind == release.MigrationIrreversible && !confirmIrreversible:
return reject(RejectIrreversible, "%s contains a save migration that cannot be rolled back: %s; confirm it explicitly", available.Version, available.Migration.Note.In(i18n.Fallback))
case delay < 0 || delay > 24*time.Hour:
return reject(RejectInvalidDelay, "the countdown must be between 0 and 24 hours")
}
if s.options.Config.Method == MethodNative {
for _, file := range []string{pendingFile, schedulePendingFile} {
if _, err := os.Stat(filepath.Join(directory(s.options.DataDir), file)); err == nil {
return reject("confirming_update", "the previous update is still being confirmed; retry once it is healthy")
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
}
if component == ComponentServer && s.options.Config.Method == MethodNative {
if err := checkWritable(); err != nil {
return err
}
}
ctx, cancel := context.WithCancel(context.Background())
s.cancelMaint = cancel
s.status.Maintenance = &Maintenance{Version: available.Version, Phase: PhasePreparing, RequestedBy: by, Delay: int(delay / time.Minute)}
version := ""
if component == ComponentSchedules {
version = schedule.Component.ID
} else {
version = available.Version
}
s.status.Maintenance = &Maintenance{Component: component, Version: version, Phase: PhasePreparing, RequestedBy: by, Delay: int(delay / time.Minute)}
s.persistLocked()
slog.Info("server update scheduled", "version", available.Version, "delay", delay, "by", by)
go s.runMaintenance(ctx, available, delay)
slog.Info("update scheduled", "component", component, "version", version, "delay", delay, "by", by)
go s.runMaintenance(ctx, available, schedule, delay)
return nil
}
func (s *Service) runMaintenance(ctx context.Context, available *Available, delay time.Duration) {
staged, err := s.prepareFiles(ctx, available)
if err == nil && s.options.Config.Method == MethodNative {
err = s.preflight(ctx, staged)
func (s *Service) runMaintenance(ctx context.Context, available *Available, schedule *ScheduleAvailable, delay time.Duration) {
var staged, version string
var plan *Plan
var err error
if schedule != nil {
version = schedule.Component.ID
_, err = s.prepareSchedules(ctx, schedule)
plan = &Plan{DataDir: s.options.DataDir, From: s.options.CurrentSchedules, To: version, Method: s.options.Config.Method,
Schedules: &SchedulePlan{ID: version, GameVersion: s.options.GameVersion, GameDataVersion: s.options.GameDataVersion}}
} else {
version = available.Version
staged, err = s.prepareFiles(ctx, available)
if err == nil && s.options.Config.Method == MethodNative {
err = s.preflight(ctx, staged)
}
plan = &Plan{DataDir: s.options.DataDir, From: s.options.ServerVersion, To: version, Method: s.options.Config.Method, Staged: staged, Migration: available.Migration, Image: available.Image, Commit: available.Commit, StateDirs: s.options.StateDirs}
if available.Fingerprint != nil {
plan.FingerprintID = available.Fingerprint.ID
plan.FromFingerprintID = s.options.FingerprintID
}
}
if err != nil {
if ctx.Err() == nil {
slog.Error("server update preparation failed; maintenance cancelled", "version", available.Version, "error", err)
slog.Error("update preparation failed; maintenance cancelled", "version", version, "error", err)
s.finishMaintenance(ctx, fmt.Sprintf("preparation failed: %v", err))
}
return
@@ -428,9 +514,9 @@ func (s *Service) runMaintenance(ctx context.Context, available *Available, dela
s.status.Maintenance.Phase = PhaseCountdown
s.status.Maintenance.At = at.UTC()
s.persistLocked()
s.publishMaintenance(available.Version, at)
s.publishMaintenance(version, at)
s.mu.Unlock()
slog.Info("maintenance countdown started", "version", available.Version, "at", at.UTC())
slog.Info("maintenance countdown started", "version", version, "at", at.UTC())
timer := time.NewTimer(time.Until(at))
defer timer.Stop()
select {
@@ -444,10 +530,10 @@ func (s *Service) runMaintenance(ctx context.Context, available *Available, dela
return
}
s.status.Maintenance.Phase = PhaseClosing
s.plan = &Plan{DataDir: s.options.DataDir, From: s.options.ServerVersion, To: available.Version, Method: s.options.Config.Method, Staged: staged, Migration: available.Migration, Image: available.Image, Commit: available.Commit, StateDirs: s.options.StateDirs}
s.plan = plan
s.persistLocked()
s.mu.Unlock()
slog.Info("maintenance started; draining for update", "version", available.Version)
slog.Info("maintenance started; draining for update", "version", version)
s.options.Shutdown()
}
@@ -490,8 +576,12 @@ func (s *Service) publishMaintenance(version string, at time.Time) {
detail := notice.Notice{ID: id + 1, Type: notice.TypeNotice, Start: now, End: at.Add(time.Duration(minutes) * time.Minute), Pinned: true, Text: map[string]notice.Content{}}
for _, locale := range i18n.Locales {
title := texts.Translate(locale, "maintenance.title")
banner.Text[locale] = notice.Content{Title: title, Blocks: []notice.Block{{Value: maintenanceText(locale, "maintenance.banner", version, at, minutes)}}}
detail.Text[locale] = notice.Content{Title: title, Blocks: []notice.Block{{Value: maintenanceText(locale, "maintenance.body", version, at, minutes)}}}
prefix, target := "maintenance.", version
if s.status.Maintenance != nil && s.status.Maintenance.Component == ComponentSchedules {
prefix, target = "maintenance.schedules.", version[:12]
}
banner.Text[locale] = notice.Content{Title: title, Blocks: []notice.Block{{Value: maintenanceText(locale, prefix+"banner", target, at, minutes)}}}
detail.Text[locale] = notice.Content{Title: title, Blocks: []notice.Block{{Value: maintenanceText(locale, prefix+"body", target, at, minutes)}}}
}
s.options.Board.Replace(SourceMaintenance, []notice.Notice{banner, detail})
}
@@ -526,7 +616,13 @@ func (s *Service) finishMaintenanceLocked(failure string) {
s.cancelMaint = nil
}
if s.status.Maintenance != nil && failure != "" {
s.status.LastResult = &Result{From: s.options.ServerVersion, To: s.status.Maintenance.Version, Outcome: "cancelled", Message: failure, At: s.options.Now().UTC()}
result := &Result{From: s.options.ServerVersion, To: s.status.Maintenance.Version, Outcome: "cancelled", Message: failure, At: s.options.Now().UTC()}
if s.status.Maintenance.Component == ComponentSchedules {
result.From = s.options.CurrentSchedules
s.status.Schedules.LastResult = result
} else {
s.status.LastResult = result
}
}
s.status.Maintenance = nil
s.persistLocked()
@@ -552,7 +648,11 @@ func (s *Service) LoginsClosed(locale string) (bool, string) {
if m == nil || m.At.IsZero() || s.options.Now().Before(m.At.Add(-loginCloseLead)) {
return false, ""
}
return true, maintenanceText(locale, "maintenance.login", m.Version, m.At, s.options.Config.MaintenanceMinutes)
key, target := "maintenance.login", m.Version
if m.Component == ComponentSchedules {
key, target = "maintenance.schedules.login", m.Version[:12]
}
return true, maintenanceText(locale, key, target, m.At, s.options.Config.MaintenanceMinutes)
}
// TakePlan returns the switch to perform after the drained server stopped.
@@ -584,11 +684,25 @@ func (s *Service) serveControl(ctx context.Context) {
ack.OK, ack.Message = false, status.LastError
} else if status.Available != nil {
ack.Message = "new version available: " + status.Available.Version
} else if status.Schedules != nil && status.Schedules.Available != nil {
ack.Message = "schedule update available: " + status.Schedules.Available.Component.ID
if message := status.Schedules.Available.Incompatible; message != "" {
ack.Message += " (incompatible: " + message + ")"
}
} else {
ack.Message = "already up to date"
}
case ActionApply:
if err := s.Schedule(time.Duration(control.DelayMinutes)*time.Minute, control.ConfirmIrreversible, "cli"); err != nil {
var err error
switch control.Component {
case "", ComponentServer:
err = s.Schedule(time.Duration(control.DelayMinutes)*time.Minute, control.ConfirmIrreversible, "cli")
case ComponentSchedules:
err = s.ScheduleSchedules(time.Duration(control.DelayMinutes)*time.Minute, "cli")
default:
err = errors.New("unknown update component")
}
if err != nil {
ack.OK, ack.Message = false, err.Error()
} else {
ack.Message = fmt.Sprintf("maintenance scheduled; it starts %d minutes after the release is prepared", control.DelayMinutes)
+30 -25
View File
@@ -25,34 +25,36 @@ const (
// Status is what the console, the CLI and state.json show.
type Status struct {
CurrentVersion string `json:"current_version"`
Method string `json:"method"`
CheckEnabled bool `json:"check_enabled"`
Countdown int `json:"countdown_minutes"`
ManifestURL string `json:"manifest_url"`
LastCheck time.Time `json:"last_check,omitzero"`
LastError string `json:"last_error,omitempty"`
Available *Available `json:"available,omitempty"`
Maintenance *Maintenance `json:"maintenance,omitempty"`
LastResult *Result `json:"last_result,omitempty"`
Control *ControlAck `json:"control,omitempty"`
Notified string `json:"notified_version,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
CurrentVersion string `json:"current_version"`
Method string `json:"method"`
CheckEnabled bool `json:"check_enabled"`
Countdown int `json:"countdown_minutes"`
ManifestURL string `json:"manifest_url"`
LastCheck time.Time `json:"last_check,omitzero"`
LastError string `json:"last_error,omitempty"`
Available *Available `json:"available,omitempty"`
Schedules *ScheduleStatus `json:"schedules,omitempty"`
Maintenance *Maintenance `json:"maintenance,omitempty"`
LastResult *Result `json:"last_result,omitempty"`
Control *ControlAck `json:"control,omitempty"`
Notified string `json:"notified_version,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
}
type Available struct {
Version string `json:"version"`
Date string `json:"date,omitempty"`
Notes i18n.Text `json:"notes,omitempty"`
PublishedAt time.Time `json:"published_at"`
Commit string `json:"commit"`
Image string `json:"image,omitempty"`
Migration release.Migration `json:"migration"`
Downloaded bool `json:"downloaded"`
DownloadError string `json:"download_error,omitempty"`
Component *release.Component `json:"component"`
ManifestURL string `json:"manifest_url"`
Fingerprint *release.Fingerprint `json:"-"`
GameDataVersion string `json:"game_data_version,omitempty"`
Version string `json:"version"`
Date string `json:"date,omitempty"`
Notes i18n.Text `json:"notes,omitempty"`
PublishedAt time.Time `json:"published_at"`
Commit string `json:"commit"`
Image string `json:"image,omitempty"`
Migration release.Migration `json:"migration"`
Downloaded bool `json:"downloaded"`
DownloadError string `json:"download_error,omitempty"`
Component *release.Component `json:"component"`
ManifestURL string `json:"manifest_url"`
Fingerprint *release.Fingerprint `json:"-"`
}
// Maintenance phases.
@@ -63,6 +65,7 @@ const (
)
type Maintenance struct {
Component string `json:"component,omitempty"`
Version string `json:"version"`
Phase string `json:"phase"`
At time.Time `json:"at,omitzero"`
@@ -92,6 +95,7 @@ const (
// Control is one CLI request.
type Control struct {
Component string `json:"component,omitempty"`
ID string `json:"id"`
Action string `json:"action"`
DelayMinutes int `json:"delay_minutes"`
@@ -137,6 +141,7 @@ func ReadStatus(dataDir string) (Status, error) {
return status, errors.New("no update status yet; start the server at least once with this data directory")
}
mergeHostResult(dataDir, &status)
mergeScheduleResult(dataDir, &status)
return status, err
}
+86 -30
View File
@@ -40,13 +40,16 @@ const hostWait = 10 * time.Minute
// Plan is a switch decided by the running server and performed after it has
// drained, saved and closed every store.
type Plan struct {
DataDir string
From, To string
Method string
Staged string
Migration release.Migration
Image string
Commit string
FromFingerprintID string
FingerprintID string
Schedules *SchedulePlan
DataDir string
From, To string
Method string
Staged string
Migration release.Migration
Image string
Commit string
// StateDirs are backed up first when the release requires a backup.
StateDirs []string
}
@@ -57,23 +60,26 @@ type RestartError struct{ Plan *Plan }
func (e *RestartError) Error() string { return "server stopped to update to " + e.Plan.To }
type pending struct {
Install string `json:"install"`
From string `json:"from"`
To string `json:"to"`
Names []string `json:"names"`
Rollback string `json:"rollback"`
Migration release.Migration `json:"migration"`
Attempts int `json:"attempts"`
At time.Time `json:"at"`
FingerprintID string `json:"fingerprint_id,omitempty"`
Install string `json:"install"`
From string `json:"from"`
To string `json:"to"`
Names []string `json:"names"`
Rollback string `json:"rollback"`
Migration release.Migration `json:"migration"`
Attempts int `json:"attempts"`
At time.Time `json:"at"`
}
type dockerRequest struct {
From string `json:"from"`
To string `json:"to"`
Image string `json:"image,omitempty"`
Commit string `json:"commit"`
Migration release.Migration `json:"migration"`
At time.Time `json:"at"`
FromFingerprintID string `json:"from_fingerprint_id,omitempty"`
FingerprintID string `json:"fingerprint_id,omitempty"`
From string `json:"from"`
To string `json:"to"`
Image string `json:"image,omitempty"`
Commit string `json:"commit"`
Migration release.Migration `json:"migration"`
At time.Time `json:"at"`
}
func executableName() string {
@@ -115,12 +121,20 @@ func checkWritable() error {
func (p *Plan) Execute(now time.Time) error {
err := p.execute(now)
if err != nil {
recordResult(p.DataDir, Result{From: p.From, To: p.To, Outcome: OutcomeSwitchFailed, Message: err.Error(), At: now.UTC()})
result := Result{From: p.From, To: p.To, Outcome: OutcomeSwitchFailed, Message: err.Error(), At: now.UTC()}
if p.Schedules != nil {
recordScheduleResult(p.DataDir, result)
} else {
recordResult(p.DataDir, result)
}
}
return err
}
func (p *Plan) execute(now time.Time) error {
if p.Schedules != nil {
return p.switchSchedules(now)
}
if p.Migration.Backup {
target := filepath.Join(p.DataDir, "backups", fmt.Sprintf("update-%s-%s-to-%s", now.UTC().Format("20060102T150405Z"), p.From, p.To))
if err := backup(p.StateDirs, target); err != nil {
@@ -129,7 +143,7 @@ func (p *Plan) execute(now time.Time) error {
slog.Info("state backed up before update", "path", target)
}
if p.Method == MethodDocker {
request := dockerRequest{From: p.From, To: p.To, Image: p.Image, Commit: p.Commit, Migration: p.Migration, At: now.UTC()}
request := dockerRequest{FromFingerprintID: p.FromFingerprintID, FingerprintID: p.FingerprintID, From: p.From, To: p.To, Image: p.Image, Commit: p.Commit, Migration: p.Migration, At: now.UTC()}
if err := writeJSON(filepath.Join(directory(p.DataDir), dockerFile), request); err != nil {
return err
}
@@ -140,12 +154,16 @@ func (p *Plan) execute(now time.Time) error {
if err != nil {
return err
}
rollback := filepath.Join(install, ".update-rollback", p.From)
rollbackID := p.From
if p.FromFingerprintID != "" {
rollbackID += "-" + p.FromFingerprintID
}
rollback := filepath.Join(install, ".update-rollback", rollbackID)
names, err := swap(install, p.Staged, rollback)
if err != nil {
return err
}
record := pending{Install: install, From: p.From, To: p.To, Names: names, Rollback: rollback, Migration: p.Migration, At: now.UTC()}
record := pending{FingerprintID: p.FingerprintID, Install: install, From: p.From, To: p.To, Names: names, Rollback: rollback, Migration: p.Migration, At: now.UTC()}
if err := writeJSON(filepath.Join(directory(p.DataDir), pendingFile), record); err != nil {
if restoreErr := restore(install, rollback, names); restoreErr != nil {
return errors.Join(err, restoreErr)
@@ -221,6 +239,9 @@ func restore(install, rollback string, names []string) error {
// of a freshly switched version and, for Docker, waits for a requested host
// switch. A returned error must stop the process with the returned exit code.
func Startup(ctx context.Context, dataDir, version string) (*Confirmation, int, error) {
if confirmation, code, err := scheduleStartup(dataDir); confirmation != nil || err != nil {
return confirmation, code, err
}
if hold, err := awaitHost(ctx, dataDir, version); hold || err != nil {
var exit *ExitError
if errors.As(err, &exit) {
@@ -240,6 +261,13 @@ func Startup(ctx context.Context, dataDir, version string) (*Confirmation, int,
_ = os.Remove(path)
return nil, 0, nil
}
if record.FingerprintID != "" {
fingerprint, err := release.LoadFingerprint(filepath.Join(record.Install, release.FingerprintFileName), release.BuiltinChannel().TrustedKeys)
if err != nil || fingerprint == nil || fingerprint.ID != record.FingerprintID {
code, rollbackErr := rollBack(dataDir, record, "installed update fingerprint differs from the selected release")
return nil, code, errors.Join(err, rollbackErr)
}
}
record.Attempts++
if record.Attempts > maxStartAttempts {
code, err := rollBack(dataDir, record, fmt.Sprintf("it failed to start %d times in a row", maxStartAttempts))
@@ -253,10 +281,11 @@ func Startup(ctx context.Context, dataDir, version string) (*Confirmation, int,
// Confirmation finishes a switch once the new version has been healthy.
type Confirmation struct {
dataDir string
record pending
mu sync.Mutex
settled bool
schedules *schedulePending
dataDir string
record pending
mu sync.Mutex
settled bool
}
// AfterHealthy marks the switch successful once ready has stayed true for a
@@ -296,6 +325,11 @@ healthy:
return
}
c.settled = true
if c.schedules != nil {
recordScheduleResult(c.dataDir, Result{From: c.schedules.From, To: c.schedules.To, Outcome: OutcomeSucceeded, At: time.Now().UTC()})
_ = os.Remove(filepath.Join(directory(c.dataDir), schedulePendingFile))
return
}
recordResult(c.dataDir, Result{From: c.record.From, To: c.record.To, Outcome: OutcomeSucceeded, At: time.Now().UTC()})
_ = os.Remove(filepath.Join(directory(c.dataDir), pendingFile))
parent := filepath.Dir(c.record.Rollback)
@@ -321,6 +355,9 @@ func (c *Confirmation) Failed(cause error) (int, error) {
return 1, cause
}
c.settled = true
if c.schedules != nil {
return rollbackSchedules(c.dataDir, *c.schedules, cause.Error())
}
return rollBack(c.dataDir, c.record, cause.Error())
}
@@ -368,7 +405,26 @@ func awaitHost(ctx context.Context, dataDir, version string) (bool, error) {
return true, err
}
if request.To == version {
return false, nil
if request.From != request.To {
return false, nil
}
install, err := InstallDirectory()
if err != nil {
return true, err
}
fingerprint, err := release.LoadFingerprint(filepath.Join(install, release.FingerprintFileName), release.BuiltinChannel().TrustedKeys)
if err != nil {
return true, err
}
if request.FingerprintID == "" {
return true, errors.New("same-version Docker update has no target fingerprint")
}
if fingerprint != nil && fingerprint.ID == request.FingerprintID {
return false, nil
}
if fingerprint == nil || fingerprint.ID != request.FromFingerprintID {
return true, errors.New("the running resource fingerprint matches neither side of the Docker update")
}
}
if version != request.From {
return true, errors.New("the running program does not match either version of the Docker update request")
@@ -1,25 +1,3 @@
[General]
## Redirect the official comparison client to the already downloaded local resources.
# Setting type: Boolean
# Default value: true
Enabled = true
## ServerData root. The selected version must exist below
## StandaloneWindows64/HD/<BundleVersion>/.
# Setting type: String
LocalCDN = <RESOURCE_ROOT>\ServerData
## GameData root. The selected version must contain
## <GameDataVersion>/release/common-dbdata.bin.
# Setting type: String
LocalGameData = <RESOURCE_ROOT>\GameData
# Setting type: String
BundleVersion = <BUNDLE_VERSION>
# Setting type: String
GameDataVersion = <GAME_DATA_VERSION>
# Setting type: String
Resolution = HD
@@ -0,0 +1,44 @@
using System;
using System.Reflection;
using BD2.GameNames;
using HarmonyLib;
using UnityEngine;
namespace Bd2LocalIdentity;
internal static class NoticePresentation
{
internal static void Install(Harmony harmony)
{
const BindingFlags declared = BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly;
MethodInfo click = typeof(NewsUI).GetGameMethod(nameof(NewsUI.OnClickUI), declared, null, [typeof(GameObject)], null);
MethodInfo close = typeof(NewsUI).GetGameMethod(nameof(NewsUI.CloseUI), declared, null, Type.EmptyTypes, null);
MethodInfo refresh = typeof(NewsPopupUI).GetGameMethod(nameof(NewsPopupUI.Refresh), declared, null, Type.EmptyTypes, null);
if (click?.DeclaringType != typeof(NewsUI) || close?.DeclaringType != typeof(NewsUI) ||
refresh?.DeclaringType != typeof(NewsPopupUI) || click.ReturnType != typeof(void) ||
close.ReturnType != typeof(void) || refresh.ReturnType != typeof(void))
throw new MissingMethodException("Declared news presentation methods were not found");
harmony.Patch(click,
prefix: new HarmonyMethod(typeof(NoticePresentation), nameof(ClickPrefix)));
harmony.Patch(close,
prefix: new HarmonyMethod(typeof(NoticePresentation), nameof(ClosePrefix)));
harmony.Patch(refresh,
prefix: new HarmonyMethod(typeof(NoticePresentation), nameof(RefreshPrefix)));
}
private static bool ClickPrefix(UIBase __instance, GameObject __0)
{
if (__instance is not NewsUI news || !news.IsNewsPopupUI || !news.IsClickedBackButton(__0)) return true;
news.CloseUI();
return false;
}
private static void ClosePrefix(UIBase __instance)
{
if (__instance is not NewsUI news || !news.IsNewsPopupUI || !news.CanCloseUI()) return;
news.IsNewsPopupUI = false;
UIManager.AddUI<NewsPopupUI>(popup => popup.Refresh());
}
private static void RefreshPrefix(NewsPopupUI __instance) => __instance.NoticeDBInfoList.Clear();
}
+1
View File
@@ -72,6 +72,7 @@ public sealed class Plugin : BaseUnityPlugin
TryInstall("battle checkpoint", () => BattleCheckpoint.Install(harmony, Logger));
TryInstall("field transition diagnostics", () => FieldTransitionDiagnostics.Install(harmony, Logger));
TryInstall("event hub presentation", () => EventHubPresentation.Install(harmony, Logger));
TryInstall("notice presentation", () => NoticePresentation.Install(harmony));
TryInstall("event request diagnostics", () => EventRequestDiagnostics.Install(harmony, Logger));
Logger.LogInfo("Local identity active: AppManager.IsPlatformLogin => false");
}
+18 -6
View File
@@ -51,7 +51,7 @@ internal static class UpdateCompatibility
if (headers != null) return headers;
plugins = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (KeyValuePair<string, string> id in PluginIds)
if (Chainloader.PluginInfos.TryGetValue(id.Value, out BepInEx.PluginInfo info) && info.Instance != null)
if (Chainloader.PluginInfos.TryGetValue(id.Value, out BepInEx.PluginInfo info))
plugins.Add(id.Key, info.Metadata.Version.ToString());
using var stream = new MemoryStream();
Serializer(typeof(Dictionary<string, string>)).WriteObject(stream, plugins);
@@ -138,8 +138,15 @@ internal static class UpdateCompatibility
MatchesResource(policy.BundleVersion, BundleVersion) && MatchesResource(policy.GameDataVersion, GameDataVersion) &&
MatchesPlugins(policy.MinimumPlugins);
if (string.IsNullOrWhiteSpace(update.ID)) throw new InvalidDataException("Missing update fingerprint identity");
if (update.RequireClientUpdate &&
(!AtLeast(ClientVersion, update.ClientVersion, "+client.") || !MatchesPlugins(update.MinimumPlugins))) return false;
if (update.RequireClientUpdate)
{
if (!AtLeast(ClientVersion, update.ClientVersion, "+client."))
{
Log?.LogWarning($"Client update required: launcher={ClientVersion}, minimum={update.ClientVersion}");
return false;
}
if (!MatchesPlugins(update.MinimumPlugins)) return false;
}
if (update.RequireGameUpdate)
{
if (update.Game == null || string.IsNullOrEmpty(update.Game.GameVersion) ||
@@ -161,7 +168,11 @@ internal static class UpdateCompatibility
{
// CaptureEnvironment is an official-client evidence tool, never a player plugin.
if (item.Key == "capture_environment") continue;
if (!plugins.TryGetValue(item.Key, out string current) || !AtLeast(current, item.Value, null)) return false;
if (!plugins.TryGetValue(item.Key, out string current) || !AtLeast(current, item.Value, null))
{
Log?.LogWarning($"Client update required: plugin={item.Key}, loaded={current ?? "missing"}, minimum={item.Value}");
return false;
}
}
return true;
}
@@ -199,7 +210,8 @@ internal static class UpdateCompatibility
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0031", Justification = "UnityEngine.Object null checks also detect destroyed native objects.")]
internal static void ShowPendingPopup()
{
if (!IsBlocked || Interlocked.CompareExchange(ref popupShown, 1, 0) != 0 || ApplicationQuitting) return;
if (!IsBlocked || ApplicationQuitting || UIManager.IsShowingNetworkErrorPopup ||
Interlocked.CompareExchange(ref popupShown, 1, 0) != 0) return;
FinishRecovery(false, verificationFailed ? "client compatibility could not be verified" : "server requires a client update");
LoginController.LoginInProgress = false;
LoginController.AccessTokens.Clear();
@@ -210,9 +222,9 @@ internal static class UpdateCompatibility
if (network != null) network.Refresh();
DisposeGameRelay();
string key = verificationFailed ? "loginui.update.check_failed" : "loginui.update.required";
UIManager.IsShowingNetworkErrorPopup = true;
UIManager.OpenErrorMessagePopupUI(TextComponent.Translatable(key).GetString(), LocalTextInfo.GetIntroText(-9998),
TextComponent.Translatable("loginui.update.exit").GetString(), null, true, Application.Quit);
UIManager.IsShowingNetworkErrorPopup = true;
}
private static DataContractJsonSerializer Serializer(Type type) =>
+1 -1
View File
@@ -6,7 +6,7 @@
<ItemGroup>
<Compile Include="$(BD2GeneratedVersionSource)" />
<Compile Include="$(BD2CompileInputsDir)/$(BD2PluginVersionKey).g.cs" Condition="'$(BD2CompileInputsDir)' != ''" />
<BD2VersionGeneratorInput Include="$(BD2RepositoryDir)go/build/**/*.go;$(BD2RepositoryDir)go/internal/buildversion/**/*.go;$(BD2RepositoryDir)go/go.mod;$(BD2RepositoryDir)go/go.sum;$(BD2RepositoryDir)bd2w;$(BD2RepositoryDir)bd2w.cmd;$(MSBuildThisFileFullPath)" />
<BD2VersionGeneratorInput Include="$(BD2RepositoryDir)go/build/version_source.go;$(BD2RepositoryDir)go/internal/buildversion/**/*.go;$(BD2RepositoryDir)go/go.mod;$(BD2RepositoryDir)go/go.sum;$(MSBuildThisFileFullPath)" />
</ItemGroup>
<Target Name="CheckBD2VersionSource" BeforeTargets="CoreCompile">
<Error Condition="!Exists('$(BD2VersionConfig)')" Text="Missing repository version config: $(BD2VersionConfig)" />
+14 -1
View File
@@ -95,6 +95,10 @@ jq -e '(.from | type == "string" and length > 0) and
((.image // "") | type == "string") and
(.migration.kind == "none" or .migration.kind == "reversible" or .migration.kind == "irreversible")' \
"$PROCESSING" >/dev/null 2>&1 || fail 'invalid Docker update request (full commit and migration kind required)'
expected_fingerprint=$(jq -r '.fingerprint_id // ""' "$PROCESSING")
if [ -n "$expected_fingerprint" ]; then
printf '%s\n' "$expected_fingerprint" | jq -Re 'test("^[0-9a-f]{64}$")' >/dev/null || fail 'invalid target fingerprint'
fi
image=$(jq -r '.image // ""' "$PROCESSING")
migration=$(jq -r '.migration.kind' "$PROCESSING")
for dependency in docker curl nsenter git mktemp stat cp; do
@@ -156,6 +160,7 @@ use_image() {
ready() {
expected_image=$1
replaced_id=$2
required_fingerprint=${3:-}
attempts=0
while [ "$attempts" -lt 60 ]; do
candidate=$(compose ps -q "$SERVICE") || candidate=
@@ -168,6 +173,14 @@ ready() {
nsenter -t "$pid" -n curl --noproxy '*' -fsS --max-time 3 "$READY_URL" >/dev/null 2>&1 &&
[ "$(compose ps -q "$SERVICE")" = "$candidate" ] &&
[ "$(docker inspect --format '{{.Image}} {{.State.Running}} {{.State.Pid}}' "$candidate")" = "$identity" ]; then
if [ -n "$required_fingerprint" ]; then
actual_fingerprint=$(nsenter -t "$pid" -n curl --noproxy '*' -fsS --max-time 3 "${READY_URL%/readyz}/client/update-fingerprint" | jq -r '.fingerprint.id // ""') || actual_fingerprint=
if [ "$actual_fingerprint" != "$required_fingerprint" ]; then
attempts=$((attempts + 1))
sleep 3
continue
fi
fi
container=$candidate
return 0
fi
@@ -178,7 +191,7 @@ ready() {
return 1
}
switched=true
if use_image "$target" && ready "$target" "$old_container"; then
if use_image "$target" && ready "$target" "$old_container" "$expected_fingerprint"; then
outcome=succeeded
message='requested image is ready in the new container'
exit 0