Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: move the app version check to the backend (#473)
Kyle Mendelld7ecb69b0ae8
diff --git a/backend/internal/api/version_handler.go b/backend/internal/api/version_handler.gonew file mode 100644index 000000000..6b86ff1c2--- /dev/null+++ b/backend/internal/api/version_handler.go@@ -0,0 +1,30 @@+package api++import (+ "log/slog"+ "net/http"+ "strings"++ "github.com/gin-gonic/gin"+ "github.com/ofkm/arcane-backend/internal/services"+)++type VersionHandler struct {+ version *services.VersionService+}++func NewVersionHandler(api *gin.RouterGroup, version *services.VersionService) *VersionHandler {+ h := &VersionHandler{version: version}+ api.GET("/version", h.Get)+ return h+}++func (h *VersionHandler) Get(c *gin.Context) {+ current := strings.TrimSpace(c.Query("current"))++ info, err := h.version.GetVersionInformation(c.Request.Context(), current)+ if err != nil {+ slog.Warn("version information fetch error", "error", err)+ }+ c.JSON(http.StatusOK, info)+}diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex 622211bf0..497d59ddd 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -50,7 +50,9 @@ func InitializeApp() (*App, error) {return nil, fmt.Errorf("db initialization failed: %w", err)}- appServices, dockerClientService, err := initializeServices(db, cfg)+ httpClient := newHTTPClient()++ appServices, dockerClientService, err := initializeServices(db, cfg, httpClient)if err != nil {db.Close()cancelApp()@@ -178,3 +180,18 @@ func (app *App) Start() {slog.InfoContext(app.AppCtx, "Server exiting")}++// newHTTPClient returns a shared HTTP client for outbound requests.+func newHTTPClient() *http.Client {+ transport := &http.Transport{+ Proxy: http.ProxyFromEnvironment,+ MaxIdleConns: 100,+ IdleConnTimeout: 90 * time.Second,+ TLSHandshakeTimeout: 5 * time.Second,+ ExpectContinueTimeout: 1 * time.Second,+ }+ return &http.Client{+ Transport: transport,+ Timeout: 10 * time.Second,+ }+}diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex ec077455e..69993b57d 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -70,6 +70,7 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {}api.NewHealthHandler(apiGroup)+ api.NewVersionHandler(apiGroup, appServices.Version)api.NewAuthHandler(apiGroup, appServices.User, appServices.Auth, appServices.Oidc, authMiddleware)api.NewContainerHandler(apiGroup, appServices.Docker, appServices.Container, appServices.Image, authMiddleware)api.NewContainerRegistryHandler(apiGroup, appServices.ContainerRegistry, authMiddleware)diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex a877e10d3..3a3634da2 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -1,6 +1,8 @@package bootstrapimport (+ "net/http"+"github.com/ofkm/arcane-backend/internal/config""github.com/ofkm/arcane-backend/internal/database""github.com/ofkm/arcane-backend/internal/services"@@ -25,9 +27,10 @@ type Services struct {System *services.SystemServiceUpdater *services.UpdaterServiceEvent *services.EventService+ Version *services.VersionService}-func initializeServices(db *database.DB, cfg *config.Config) (*Services, *services.DockerClientService, error) {+func initializeServices(db *database.DB, cfg *config.Config, httpClient *http.Client) (*Services, *services.DockerClientService, error) {svc := &Services{}svc.Event = services.NewEventService(db)@@ -49,6 +52,7 @@ func initializeServices(db *database.DB, cfg *config.Config) (*Services, *servicsvc.Oidc = services.NewOidcService(svc.Auth, cfg)svc.Updater = services.NewUpdaterService(db, svc.Settings, svc.Docker, svc.Stack, svc.ImageUpdate, svc.ContainerRegistry, svc.Event, svc.Image)svc.System = services.NewSystemService(db, svc.Docker, svc.Container, svc.Image, svc.Volume, svc.Network, svc.Settings)+ svc.Version = services.NewVersionService(httpClient, cfg.UpdateCheckDisabled)return svc, dockerClient, nil}diff --git a/backend/internal/config/config.go b/backend/internal/config/config.goindex 4af50ef1e..cb662da51 100644--- a/backend/internal/config/config.go+++ b/backend/internal/config/config.go@@ -31,6 +31,7 @@ type Config struct {AgentMode boolAgentToken stringAgentBootstrapToken string+ UpdateCheckDisabled bool}func Load() *Config {@@ -55,6 +56,7 @@ func Load() *Config {AgentMode: getBoolEnvOrDefault("AGENT_MODE", false),AgentToken: os.Getenv("AGENT_TOKEN"),AgentBootstrapToken: os.Getenv("AGENT_BOOTSTRAP_TOKEN"),+ UpdateCheckDisabled: getBoolEnvOrDefault("UPDATE_CHECK_DISABLED", false),}}diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.gonew file mode 100644index 000000000..30507c765--- /dev/null+++ b/backend/internal/services/version_service.go@@ -0,0 +1,172 @@+package services++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "log/slog"+ "net/http"+ "strings"+ "time"++ "github.com/ofkm/arcane-backend/internal/utils/cache"+)++const (+ versionTTL = 3 * time.Hour+ versionCheckURL = "https://api.github.com/repos/ofkm/arcane/releases/latest"+ defaultRequestTimeout = 5 * time.Second+)++type VersionService struct {+ httpClient *http.Client+ cache *cache.Cache[string]+ disabled bool+}++func NewVersionService(httpClient *http.Client, disabled bool) *VersionService {+ if httpClient == nil {+ httpClient = http.DefaultClient+ }+ return &VersionService{+ httpClient: httpClient,+ cache: cache.New[string](versionTTL),+ disabled: disabled,+ }+}++func (s *VersionService) GetLatestVersion(ctx context.Context) (string, error) {+ version, err := s.cache.GetOrFetch(ctx, func(ctx context.Context) (string, error) {+ reqCtx, cancel := context.WithTimeout(ctx, defaultRequestTimeout)+ defer cancel()++ req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, versionCheckURL, nil)+ if err != nil {+ return "", fmt.Errorf("create GitHub request: %w", err)+ }++ resp, err := s.httpClient.Do(req)+ if err != nil {+ return "", fmt.Errorf("get latest release: %w", err)+ }+ defer resp.Body.Close()++ if resp.StatusCode != http.StatusOK {+ return "", fmt.Errorf("GitHub API returned status %d", resp.StatusCode)+ }++ var payload struct {+ TagName string `json:"tag_name"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {+ return "", fmt.Errorf("decode payload: %w", err)+ }+ if payload.TagName == "" {+ return "", fmt.Errorf("GitHub API returned empty tag name")+ }++ return strings.TrimPrefix(payload.TagName, "v"), nil+ })++ var staleErr *cache.ErrStale+ if errors.As(err, &staleErr) {+ slog.Warn("Failed to fetch latest version, returning stale cache", "error", staleErr.Err)+ return version, nil+ }++ return version, err+}++func (s *VersionService) IsNewer(latest, current string) bool {+ lp := parseSemver(latest)+ cp := parseSemver(current)+ for i := 0; i < 3; i++ {+ if lp[i] > cp[i] {+ return true+ }+ if lp[i] < cp[i] {+ return false+ }+ }+ return false+}++func (s *VersionService) ReleaseURL(version string) string {+ if strings.TrimSpace(version) == "" {+ return "https://github.com/ofkm/arcane/releases/latest"+ }+ return "https://github.com/ofkm/arcane/releases/tag/v" + version+}++type VersionInformation struct {+ CurrentVersion string `json:"currentVersion"`+ NewestVersion string `json:"newestVersion,omitempty"`+ UpdateAvailable bool `json:"updateAvailable"`+ ReleaseURL string `json:"releaseUrl,omitempty"`+}++func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersion string) (*VersionInformation, error) {+ cur := strings.TrimPrefix(strings.TrimSpace(currentVersion), "v")++ if s.disabled {+ return &VersionInformation{+ CurrentVersion: cur,+ NewestVersion: "",+ UpdateAvailable: false,+ ReleaseURL: s.ReleaseURL(""),+ }, nil+ }++ latest, err := s.GetLatestVersion(ctx)+ if err != nil {+ var staleErr *cache.ErrStale+ if errors.As(err, &staleErr) {+ slog.Warn("Failed to refresh latest version; using stale cache", "error", staleErr.Err)+ } else {+ return &VersionInformation{+ CurrentVersion: cur,+ ReleaseURL: s.ReleaseURL(""),+ }, err+ }+ }++ return &VersionInformation{+ CurrentVersion: cur,+ NewestVersion: latest,+ UpdateAvailable: s.IsNewer(latest, cur),+ ReleaseURL: s.ReleaseURL(latest),+ }, nil+}++func parseSemver(s string) [3]int {+ var out [3]int+ part := 0+ num := 0+ sign := 1++ flush := func() {+ if part < 3 {+ out[part] = sign * num+ part+++ }+ num = 0+ sign = 1+ }++ for i := 0; i < len(s); i++ {+ switch c := s[i]; {+ case c == '-':+ i = len(s)+ case c == '.':+ flush()+ case c >= '0' && c <= '9':+ num = num*10 + int(c-'0')+ case c == '+' || c == 'v' || c == 'V':+ default:+ i = len(s)+ }+ }+ flush()+ return out+}diff --git a/backend/internal/utils/cache/cache_util.go b/backend/internal/utils/cache/cache_util.gonew file mode 100644index 000000000..c09335962--- /dev/null+++ b/backend/internal/utils/cache/cache_util.go@@ -0,0 +1,68 @@+package cache++import (+ "context"+ "sync"+ "time"++ "golang.org/x/sync/singleflight"+)++type ErrStale struct {+ Err error+}++func (e *ErrStale) Error() string { return "stale cache value: " + e.Err.Error() }+func (e *ErrStale) Unwrap() error { return e.Err }++type Cache[T any] struct {+ ttl time.Duration++ mu sync.RWMutex+ val T+ exp time.Time+ set bool++ sf singleflight.Group+}++func New[T any](ttl time.Duration) *Cache[T] {+ return &Cache[T]{ttl: ttl}+}++func (c *Cache[T]) GetOrFetch(ctx context.Context, fetch func(ctx context.Context) (T, error)) (T, error) {+ c.mu.RLock()+ if c.set && time.Now().Before(c.exp) {+ v := c.val+ c.mu.RUnlock()+ return v, nil+ }++ hasStale := c.set+ stale := c.val+ c.mu.RUnlock()++ res, err, _ := c.sf.Do("singleton", func() (any, error) {+ v, err := fetch(ctx)+ if err != nil {+ return nil, err+ }++ c.mu.Lock()+ c.val = v+ c.set = true+ c.exp = time.Now().Add(c.ttl)+ c.mu.Unlock()+ return v, nil+ })+ if err != nil {+ if hasStale {+ return stale, &ErrStale{Err: err}+ }+ var zero T+ return zero, err+ }++ v, _ := res.(T)+ return v, nil+}diff --git a/frontend/src/lib/services/app-version-service.ts b/frontend/src/lib/services/app-version-service.tsdeleted file mode 100644index 4be23eeab..000000000--- a/frontend/src/lib/services/app-version-service.ts+++ /dev/null@@ -1,78 +0,0 @@-import { version as currentVersion } from '$app/environment';-import type { AppVersionInformation } from '$lib/types/application-configuration';--export class AppVersionService {- private cachedVersionInfo: AppVersionInformation | null = null;- private lastFetchTime: number = 0;- private readonly cacheExpiry = 1000 * 60 * 60 * 3; // 3 hours-- private getReleaseUrl(version?: string): string {- if (!version) return 'https://github.com/ofkm/arcane/releases/latest';- return `https://github.com/ofkm/arcane/releases/tag/v${version}`;- }-- getCurrentVersion(): string {- return currentVersion;- }-- async getNewestVersion(): Promise<string> {- try {- const response = await fetch('https://api.github.com/repos/ofkm/arcane/releases/latest');- if (!response.ok) throw new Error(`Failed to fetch: ${response.status}`);-- const data = await response.json();- return data.tag_name.replace(/^v/, '');- } catch (error) {- console.error('Error fetching newest version:', error);- return this.getCurrentVersion();- }- }-- async isUpToDate(): Promise<boolean> {- const newest = await this.getNewestVersion();- const current = this.getCurrentVersion().replace(/^v/, '');- return !this.isNewerVersion(newest, current);- }-- async getVersionInformation(): Promise<AppVersionInformation> {- const cacheExpired = Date.now() - this.lastFetchTime > this.cacheExpiry;-- if (!this.cachedVersionInfo || cacheExpired) {- try {- const [newestVersion, isUpToDate] = await Promise.all([this.getNewestVersion(), this.isUpToDate()]);-- this.cachedVersionInfo = {- currentVersion: this.getCurrentVersion(),- newestVersion,- updateAvailable: !isUpToDate,- releaseUrl: this.getReleaseUrl(newestVersion)- };- this.lastFetchTime = Date.now();- } catch (error) {- console.error('Error fetching version information:', error);- return {- currentVersion: this.getCurrentVersion(),- releaseUrl: this.getReleaseUrl()- };- }- }-- return this.cachedVersionInfo;- }-- private isNewerVersion(latest: string, current: string): boolean {- if (!latest || !current) return false;-- const latestParts = latest.split('.').map(Number);- const currentParts = current.split('.').map(Number);-- for (let i = 0; i < 3; i++) {- if ((latestParts[i] || 0) > (currentParts[i] || 0)) return true;- if ((latestParts[i] || 0) < (currentParts[i] || 0)) return false;- }-- return false;- }-}--export const versionService = new AppVersionService();diff --git a/frontend/src/lib/services/version-service.ts b/frontend/src/lib/services/version-service.tsnew file mode 100644index 000000000..42c6803fa--- /dev/null+++ b/frontend/src/lib/services/version-service.ts@@ -0,0 +1,48 @@+import { version as currentVersion } from '$app/environment';+import axios from 'axios';+import type { AppVersionInformation } from '$lib/types/application-configuration';++function getCurrentVersion() {+ return currentVersion;+}++async function getVersionInformation(): Promise<AppVersionInformation> {+ const res = await axios.get('/api/version', {+ params: { current: getCurrentVersion() },+ timeout: 2000+ });+ const data = res.data as {+ currentVersion?: string;+ newestVersion?: string;+ updateAvailable?: boolean;+ releaseUrl?: string;+ };++ const current = getCurrentVersion();+ const newest = data.newestVersion;+ const updateAvailable = newest ? newest !== current : false;++ return {+ currentVersion: current,+ newestVersion: newest,+ updateAvailable,+ releaseUrl: data.releaseUrl+ };+}++async function getNewestVersion(): Promise<string | undefined> {+ const info = await getVersionInformation();+ return info.newestVersion;+}++async function getReleaseUrl(): Promise<string | undefined> {+ const info = await getVersionInformation();+ return info.releaseUrl;+}++export default {+ getVersionInformation,+ getNewestVersion,+ getReleaseUrl,+ getCurrentVersion+};diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.tsindex 2bb03ea30..07491f9d7 100644--- a/frontend/src/routes/+layout.ts+++ b/frontend/src/routes/+layout.ts@@ -1,17 +1,15 @@-import { env } from '$env/dynamic/public';import { settingsAPI, userAPI, environmentManagementAPI } from '$lib/services/api';import { environmentStore } from '$lib/stores/environment.store';-import { versionService } from '$lib/services/app-version-service';+import versionService from '$lib/services/version-service';import { tryCatch } from '$lib/utils/try-catch';import userStore from '$lib/stores/user-store';import settingsStore from '$lib/stores/config-store';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import type { AppVersionInformation } from '$lib/types/application-configuration';export const ssr = false;export const load = async () => {- const updateCheckDisabled = env.PUBLIC_UPDATE_CHECK_DISABLED === 'true';-const userPromise = userAPI.getCurrentUser().catch(() => null);const settingsPromise = settingsAPI.getSettings().catch((e) => {console.error('Error fetching settings:', e);@@ -35,16 +33,21 @@ export const load = async () => {return null;});- const versionPromise = updateCheckDisabled- ? Promise.resolve({ currentVersion: versionService.getCurrentVersion() })- : versionService.getVersionInformation();+ let versionInformation: AppVersionInformation = {+ currentVersion: versionService.getCurrentVersion()+ };++ try {+ const info = await versionService.getVersionInformation();+ versionInformation = {+ currentVersion: info.currentVersion,+ newestVersion: info.newestVersion,+ updateAvailable: info.newestVersion ? info.newestVersion !== info.currentVersion : false,+ releaseUrl: info.releaseUrl+ };+ } catch {}- const [user, settings, , versionInformation] = await Promise.all([- userPromise,- settingsPromise,- environmentsPromise,- versionPromise- ]);+ const [user, settings] = await Promise.all([userPromise, settingsPromise, environmentsPromise]);if (user) {await userStore.setUser(user);@@ -57,7 +60,6 @@ export const load = async () => {return {user,settings,- versionInformation,- updateCheckDisabled+ versionInformation};};