aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/app/app_linux.go
blob: eebfacdcade89aa23c4cae8bc249bdb4ca994770 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package app

import (
	"context"
	"fmt"
	"log"
	"sync"

	"hakurei.app/hst"
	"hakurei.app/internal/app/state"
	"hakurei.app/internal/sys"
)

func New(ctx context.Context, os sys.State) (*App, error) {
	a := new(App)
	a.sys = os
	a.ctx = ctx

	id := new(state.ID)
	err := state.NewAppID(id)
	a.id = newID(id)

	return a, err
}

func MustNew(ctx context.Context, os sys.State) *App {
	a, err := New(ctx, os)
	if err != nil {
		log.Fatalf("cannot create app: %v", err)
	}
	return a
}

type App struct {
	id  *stringPair[state.ID]
	sys sys.State
	ctx context.Context

	*outcome
	mu sync.RWMutex
}

// ID returns a copy of [state.ID] held by App.
func (a *App) ID() state.ID { a.mu.RLock(); defer a.mu.RUnlock(); return a.id.unwrap() }

func (a *App) String() string {
	if a == nil {
		return "(invalid app)"
	}

	a.mu.RLock()
	defer a.mu.RUnlock()

	if a.outcome != nil {
		if a.outcome.user.uid == nil {
			return fmt.Sprintf("(sealed app %s with invalid uid)", a.id)
		}
		return fmt.Sprintf("(sealed app %s as uid %s)", a.id, a.outcome.user.uid)
	}

	return fmt.Sprintf("(unsealed app %s)", a.id)
}

// Seal determines the outcome of [hst.Config] as a [SealedApp].
// Values stored in and referred to by [hst.Config] might be overwritten and must not be used again.
func (a *App) Seal(config *hst.Config) (SealedApp, error) {
	a.mu.Lock()
	defer a.mu.Unlock()

	if a.outcome != nil {
		panic("app sealed twice")
	}

	seal := new(outcome)
	seal.id = a.id
	err := seal.finalise(a.ctx, a.sys, config)
	if err == nil {
		a.outcome = seal
	}
	return seal, err
}