update

package
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package update compares the running build against the latest published release.

Index

Constants

View Source
const CheckInterval = 24 * time.Hour

CheckInterval is how often the background check runs while the application stays up. A launch checks regardless of when the last one was.

View Source
const DownloadsURL = "https://mq-studio.amigoer.com/#download"

DownloadsURL is the human-facing downloads page. It points at the site rather than at GitHub Releases: the site offers the same packages and is reachable on networks that cannot open github.com.

View Source
const Event = "update:state"

Event is emitted whenever State changes. Keep in step with the name the renderer subscribes to in frontend/src/api/updates.ts.

View Source
const MirrorPreferenceTTL = 7 * 24 * time.Hour

MirrorPreferenceTTL is how long a remembered winner is reused without being re-measured. It bounds two opposite mistakes: staying on a mirror that has since got worse, and never discovering one that was added later.

View Source
const MirrorStagger = 400 * time.Millisecond

MirrorStagger is how long each mirror gets before the next one is started. It is what keeps a healthy first choice from costing anything: when the preferred mirror answers inside this window, no other request is ever made.

View Source
const PreferenceTimeout = 2 * time.Second

PreferenceTimeout is how long a mirror that won last time gets to answer on its own before the full race starts. Short on purpose: the cost of being wrong is one wasted request, and the cost of waiting is the whole check.

View Source
const RaceTimeout = 12 * time.Second

RaceTimeout bounds a whole race, so one mirror that accepts a connection and then says nothing cannot hold up the check indefinitely.

View Source
const StartupDelay = 5 * time.Second

StartupDelay lets the launch sequence finish before anything is spent on a check nobody is waiting for.

View Source
const SupportedSchema = 1

SupportedSchema is the newest manifest layout this build understands. A manifest above it is refused rather than guessed at, which is what lets an old build say "download it by hand" instead of misreading a future release.

Variables

View Source
var ErrChecksumMismatch = errors.New("downloaded file does not match its published checksum")

ErrChecksumMismatch reports a download whose content is not what the release attested to. The partial file is removed before it is returned.

View Source
var ErrElevationDeclined = errors.New("the update was not given permission to install")

ErrElevationDeclined reports that the user dismissed the Windows elevation prompt. Nothing was installed because nothing was permitted to start, which is a different thing to tell someone than a failure.

View Source
var ErrNotInstallable = errors.New("this installation cannot be updated in place")

ErrNotInstallable is returned when an update is applied to a build that cannot replace itself: a package-manager install, a read-only location, or something that was never installed at all.

View Source
var ErrSchemaTooNew = errors.New("this build is too old to read the release index")

ErrSchemaTooNew reports a manifest written for a later build than this one.

Functions

func Apply

func Apply(ctx context.Context, commander Commander, location Location, packagePath string) error

Apply replaces the installation at location with the verified package, and reports whether the caller still has to quit for the change to take effect. It always does -- the running image is what is being replaced -- so the return exists only to keep the call sites from having to remember.

func CompareStable

func CompareStable(left, right string) (int, error)

CompareStable orders two stable SemVer strings numerically.

func Download

func Download(
	ctx context.Context,
	client *http.Client,
	url, dest, want string,
	progress func(done, total int64),
) error

Download fetches url into dest and verifies it against want, a lowercase hex SHA-256. progress may be nil; total is -1 while the server sends no length.

The bytes land in a sibling `.part` file and are renamed into place only after the digest matches, so dest never names a half-written or wrong file.

func Relaunch

func Relaunch(commander Commander, location Location) error

Relaunch starts the installed application again once this process is gone.

The wait is what makes it a relaunch rather than a second instance: the trampoline polls for the current pid to disappear and only then starts the application, so the two never overlap. Windows is left out -- its installer owns what happens after the install.

func ValidPolicy

func ValidPolicy(value string) bool

ValidPolicy reports whether value names a policy.

Types

type Blocker

type Blocker string

Blocker says why the running build cannot install an update itself. The values are keys, not prose: the renderer translates them.

const (
	// BlockerNone means the update can be applied in place.
	BlockerNone Blocker = ""
	// BlockerPackageManager means apt/dnf owns the files and needs root.
	BlockerPackageManager Blocker = "packageManager"
	// BlockerReadOnly means the install location is not writable by this user.
	BlockerReadOnly Blocker = "readOnly"
	// BlockerNotPackaged means this is not an installed application.
	BlockerNotPackaged Blocker = "notPackaged"
	// BlockerUnsupported means no release is built for this OS or architecture.
	BlockerUnsupported Blocker = "unsupported"
)

type Commander

type Commander interface {
	Run(ctx context.Context, name string, args ...string) error
	Start(name string, args ...string) error
	// Elevate starts a program that may need administrator rights. On Windows
	// that is a different system call from Start, because the one Start uses
	// cannot raise a privilege prompt; everywhere else the two are the same.
	Elevate(name string, args ...string) error
}

Commander runs external tools. Run waits for the command; Start spawns it and returns, which is what the trampolines below need -- they outlive the process that started them on purpose.

var SystemCommander Commander = execCommander{}

SystemCommander runs updates through the real operating system.

type FailedStep

type FailedStep string

FailedStep names which part of the last failure, so the renderer can offer the right way out -- retry a download, open the releases page for the rest.

const (
	StepNone     FailedStep = ""
	StepCheck    FailedStep = "check"
	StepDownload FailedStep = "download"
	StepInstall  FailedStep = "install"
)

type Fetched added in v0.0.7

type Fetched struct {
	Manifest Manifest
	// Mirror is the one that answered, and where the download starts.
	Mirror Mirror
	// Order is the winner followed by the rest in preference order, which is
	// the sequence a download falls through on failure.
	Order []Mirror
}

Fetched is a manifest and where it came from.

func RaceManifest added in v0.0.7

func RaceManifest(
	ctx context.Context,
	client *http.Client,
	mirrors []Mirror,
	stagger time.Duration,
) (Fetched, error)

RaceManifest starts each mirror stagger apart and returns the first manifest to arrive, cancelling the rest.

Starting them apart rather than together is the whole point: with a working first choice the later requests are never made, so having several mirrors costs nothing until one is actually needed.

type Kind

type Kind string

Kind is how the running build was installed. It decides both the asset to fetch and the way it is applied.

const (
	// KindAppBundle is a macOS .app, shipped inside a .dmg.
	KindAppBundle Kind = "appBundle"
	// KindInstaller is a Windows install, replaced by re-running the NSIS
	// installer.
	KindInstaller Kind = "installer"
	// KindAppImage is a Linux single-file AppImage, replaced in place.
	KindAppImage Kind = "appImage"
	// KindManaged is a Linux .deb or .rpm install, owned by the package
	// manager.
	KindManaged Kind = "managed"
	// KindUnknown is a bare binary or a `wails3 dev` run.
	KindUnknown Kind = "unknown"
)

type Location

type Location struct {
	Kind   Kind   `json:"kind"`
	Target Target `json:"target"`
	// Root is what applying an update replaces: the .app bundle on macOS, the
	// AppImage file on Linux, the installed executable on Windows. Empty when
	// nothing can be replaced.
	Root string `json:"root"`
	// Blocker is why this build cannot install an update itself, "" when it can.
	Blocker Blocker `json:"blocker"`
}

Location is where the running build lives and what may be done to it.

func Locate

func Locate() Location

Locate resolves where this build is installed and whether it can update itself. APPIMAGE is set by the AppImage runtime to the image's own path.

func (Location) CanInstall

func (l Location) CanInstall() bool

CanInstall reports whether the app may download and apply an update itself.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager owns the update lifecycle.

func New

func New(options Options) *Manager

New builds a Manager and restores what the last session left behind.

func (*Manager) Cancel

func (m *Manager) Cancel()

Cancel stops a download in flight. It is a no-op otherwise.

func (*Manager) Check

func (m *Manager) Check(ctx context.Context, manual bool) (State, error)

Check resolves the release and folds the answer into the state. A manual check reports every outcome; a scheduled one is silent unless something is found.

When the policy downloads on its own and the check finds a release that is neither skipped nor already downloaded, the download starts before this returns to the caller -- in the background, so the call itself does not wait.

func (*Manager) Close

func (m *Manager) Close()

Close stops the schedule and any download in flight.

func (*Manager) Download

func (m *Manager) Download(ctx context.Context, release Result) error

Download fetches and verifies the package for a release. Passing the zero Result re-checks first, which is what the renderer's download button does.

func (*Manager) Install

func (m *Manager) Install(ctx context.Context) error

Install applies the downloaded package and arranges for the application to come back. The caller quits once this returns: the running image is what has just been replaced.

func (*Manager) InstallOnQuit

func (m *Manager) InstallOnQuit(ctx context.Context) (bool, error)

InstallOnQuit applies a ready package without relaunching, for the auto policy: the swap happens as the application closes, and the next launch is the new version. It reports whether anything was installed.

func (*Manager) Skip

func (m *Manager) Skip(version string)

Skip stops a release from being announced again. The next one still is.

func (*Manager) Start

func (m *Manager) Start(ctx context.Context)

Start runs the background schedule until Close. Every launch checks, once StartupDelay has let the window come up, and every CheckInterval after that.

A launch used to wait out whatever was left of the interval instead. An application that is opened and closed a few times a day never reaches the end of one, so the only check that ever ran was the one the user pressed for -- which is no way to hear about a release.

func (*Manager) State

func (m *Manager) State() State

State returns the current state.

type Manifest added in v0.0.7

type Manifest struct {
	Schema      int                     `json:"schema"`
	Version     string                  `json:"version"`
	Tag         string                  `json:"tag"`
	PublishedAt string                  `json:"publishedAt"`
	ReleaseURL  string                  `json:"releaseURL"`
	Notes       string                  `json:"notes"`
	Mirrors     []Mirror                `json:"mirrors"`
	Checksums   string                  `json:"checksums"`
	Files       map[string]ManifestFile `json:"files"`
	// Signature is reserved for an ed25519 signature over this object. Empty
	// means unsigned, which is accepted while every mirror is first-party.
	Signature string `json:"signature"`
}

Manifest is the release description every mirror serves. It replaces the GitHub releases API: the digests are inlined rather than left in a separate SHA256SUMS.txt, so it is the only thing a client has to trust and the only request a check has to make.

func FetchManifest added in v0.0.7

func FetchManifest(ctx context.Context, client *http.Client, mirror Mirror) (Manifest, error)

FetchManifest reads one mirror's manifest.

func ParseManifest added in v0.0.7

func ParseManifest(content []byte) (Manifest, error)

ParseManifest reads and checks a manifest. A mirror that answers with something malformed is treated as a failure, so the race moves on to the next one rather than the app acting on half a release.

type ManifestFile added in v0.0.7

type ManifestFile struct {
	// Path is relative to a mirror's AssetBase, which is what lets one manifest
	// describe every mirror.
	Path   string `json:"path"`
	Size   int64  `json:"size"`
	SHA256 string `json:"sha256"`
}

ManifestFile is one package in a release.

type Mirror added in v0.0.7

type Mirror struct {
	Name        string `json:"name"`
	ManifestURL string `json:"manifest"`
	AssetBase   string `json:"assets"`
}

Mirror is one place a release can be fetched from. The two URLs are separate because they need not share a prefix: GitHub serves the manifest from the latest release and the packages from a tag directory.

func BootstrapMirrors added in v0.0.7

func BootstrapMirrors() []Mirror

BootstrapMirrors is the list compiled into the build. Anything learned from a manifest is added to it and can never replace it, so a build always retains a path it was shipped knowing about.

func MergeMirrors added in v0.0.7

func MergeMirrors(known, learned []Mirror) []Mirror

MergeMirrors folds a manifest's mirror list into the ones already known.

Merging only: an entry from a manifest can neither remove a mirror nor redefine one that is already known. That bounds what a manifest can do to the list to adding a mirror it already served itself, and keeps the compiled-in path reachable no matter what any mirror says.

func (Mirror) AssetURL added in v0.0.7

func (m Mirror) AssetURL(path string) string

AssetURL resolves a manifest path against this mirror.

func (Mirror) Valid added in v0.0.7

func (m Mirror) Valid() bool

Valid reports whether a mirror is usable. Plain HTTP is rejected: a mirror carries the digests that authorise an install, so the transport is the only thing standing between a hostile network and a chosen update.

type Options

type Options struct {
	// Version is the running build, as injected at link time.
	Version string
	// Directory is where downloaded packages are kept.
	Directory string
	// Policy reads the current setting. Required.
	Policy func() Policy
	// Emit publishes a state change to the renderer. Optional.
	Emit func(State)
	// Client, Commander, Location, Now and Delay are seams for the tests.
	Client    *http.Client
	Commander Commander
	Location  *Location
	Now       func() time.Time
	// Delay is how long Start waits before the launch check. Zero means
	// StartupDelay.
	Delay time.Duration
	// Check replaces the network call. Optional.
	Check func(ctx context.Context, version string, client *http.Client, mirrors []Mirror) (Result, error)
}

Options configures a Manager. Only Version and Directory are required; the rest have working defaults and exist so the tests can stand in for the world.

type Phase

type Phase string

Phase is what the updater is doing.

const (
	// PhaseIdle means nothing newer is known of.
	PhaseIdle Phase = "idle"
	// PhaseChecking means a check is in flight.
	PhaseChecking Phase = "checking"
	// PhaseAvailable means a newer release exists and nothing is downloaded.
	PhaseAvailable Phase = "available"
	// PhaseDownloading means the package is being fetched.
	PhaseDownloading Phase = "downloading"
	// PhaseReady means a verified package is waiting to be installed.
	PhaseReady Phase = "ready"
	// PhaseInstalling means the package is being applied.
	PhaseInstalling Phase = "installing"
	// PhaseError means the last operation failed; Error says which and why.
	PhaseError Phase = "error"
)

type Policy

type Policy string

Policy is how much the app may do without being asked.

const (
	// PolicyOff never checks. A manual check still works.
	PolicyOff Policy = "off"
	// PolicyNotify checks and reports; downloading is the user's call.
	PolicyNotify Policy = "notify"
	// PolicyDownload fetches and verifies in the background, then waits to be
	// told to install.
	PolicyDownload Policy = "download"
	// PolicyAuto also installs, at quit, so an update never interrupts a
	// session it was not asked for.
	PolicyAuto Policy = "auto"
)

type Result

type Result struct {
	Status         Status `json:"status"`
	CurrentVersion string `json:"currentVersion"`
	LatestVersion  string `json:"latestVersion"`
	// Release notes, as written in the changelog the workflow publishes.
	Notes string `json:"notes"`
	// RFC3339, or empty when the release names no publication date.
	PublishedAt string `json:"publishedAt"`
	ReleaseURL  string `json:"releaseURL"`
	// Manifest is the whole release as the winning mirror described it.
	// Resolving which package this build installs is the caller's job --
	// CheckLatest knows nothing about the host it is running on.
	Manifest Manifest `json:"manifest"`
	// Mirror answered the check and is where the download starts; Order is the
	// sequence to fall through if it stops answering partway.
	Mirror Mirror   `json:"mirror"`
	Order  []Mirror `json:"order"`
}

Result is the outcome of an update check.

func CheckLatest

func CheckLatest(
	ctx context.Context,
	currentVersion string,
	client *http.Client,
	mirrors []Mirror,
) (Result, error)

CheckLatest races the mirrors for the release manifest and compares what the winner reports to the running build. An empty mirror list falls back to the ones compiled in.

It takes the whole list rather than one URL because reaching a release is the thing that fails: the check and the download that follows both go to whichever mirror answers, and that is not knowable ahead of time.

type State

type State struct {
	Phase  Phase  `json:"phase"`
	Policy Policy `json:"policy"`
	// The build that is running.
	CurrentVersion string `json:"currentVersion"`
	// True for a build with no release to compare against -- `wails3 dev`, or
	// anything else that did not get a version at link time. The updater is
	// inert, and the panel says so rather than claiming to be up to date.
	Development bool `json:"development"`
	// The newest release, or "" when none is known or it is not newer.
	LatestVersion string `json:"latestVersion"`
	Notes         string `json:"notes"`
	// RFC3339, or "" when unknown.
	PublishedAt string `json:"publishedAt"`
	ReleaseURL  string `json:"releaseURL"`
	// Bytes fetched and expected. Total is -1 when the server sent no length.
	Downloaded int64 `json:"downloaded"`
	Total      int64 `json:"total"`
	// Mirror is the one currently being read from, "" before any has been
	// chosen. It is in the state so a failure can be diagnosed after the fact:
	// which route a user took is otherwise invisible to everyone.
	Mirror string `json:"mirror"`
	// What the last check concluded. Empty until one has run: it is a fact
	// about a check, not a phase, which is why it sits beside Phase rather
	// than in it.
	Outcome Status `json:"outcome"`
	// RFC3339 of the last completed check, successful or not.
	CheckedAt string `json:"checkedAt"`
	// A release the user asked not to be told about again.
	Skipped string `json:"skipped"`
	// Where this build is installed and whether it can replace itself.
	Location Location `json:"location"`
	// Human-readable failure for PhaseError, and the step it happened in.
	Error      string     `json:"error"`
	FailedStep FailedStep `json:"failedStep"`
}

State is everything the renderer draws. It is a value: callers get a copy.

type Status

type Status string

Status reports how the running build relates to the latest release.

const (
	// StatusAvailable means a newer release exists.
	StatusAvailable Status = "available"
	// StatusCurrent means the running build is the latest release.
	StatusCurrent Status = "current"
	// StatusAhead means the running build is newer than the latest release.
	StatusAhead Status = "ahead"
)

type Target

type Target struct {
	OS   string `json:"os"`
	Arch string `json:"arch"`
	Ext  string `json:"ext"`
}

Target names the release asset a build installs from.

func (Target) PackageName

func (t Target) PackageName(version string) string

PackageName is the canonical release asset name for a version. Keep in step with PACKAGE_BASE in .github/workflows/package.yml.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL