Compare commits
76
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e539cf6e99 | ||
|
|
17e1bfb6d3 | ||
|
|
cd17899328 | ||
|
|
5153e5fdc2 | ||
|
|
1712612729 | ||
|
|
dd9b4a10f5 | ||
|
|
ac50980ba1 | ||
|
|
d859380669 | ||
|
|
8f86aedeae | ||
|
|
9a3149df88 | ||
|
|
8ca052a0c7 | ||
|
|
349ef43a36 | ||
|
|
a74afe71f3 | ||
|
|
bd6dcdcd0c | ||
|
|
717f8ec2e5 | ||
|
|
a94f9f14aa | ||
|
|
397e627b02 | ||
|
|
55a90d963e | ||
|
|
42b5a7aef3 | ||
|
|
77602d8586 | ||
|
|
ae7d0f874b | ||
|
|
691ad760d3 | ||
|
|
0c2a95aacd | ||
|
|
e20d3c7548 | ||
|
|
dd35217275 | ||
|
|
20c53a14db | ||
|
|
9f5614b35e | ||
|
|
dc27af2227 | ||
|
|
1dec6eb02c | ||
|
|
786a23638b | ||
|
|
b694c5e2a5 | ||
|
|
f6646c7254 | ||
|
|
a4169a2325 | ||
|
|
a40d7fb1c4 | ||
|
|
fee3f8ab8b | ||
|
|
c12d0027e8 | ||
|
|
2b0b234db2 | ||
|
|
f7b918faea | ||
|
|
dc59860541 | ||
|
|
98b73461e5 | ||
|
|
a8dfe343a2 | ||
|
|
03bf70a22b | ||
|
|
324ff5215c | ||
|
|
8edc9233c0 | ||
|
|
8f21a7a5de | ||
|
|
527676ccb4 | ||
|
|
0f648e26dd | ||
|
|
008ac6332f | ||
|
|
5526873138 | ||
|
|
51a6ac3461 | ||
|
|
fe2bed92e6 | ||
|
|
cc1140ba36 | ||
|
|
d5161c93ef | ||
|
|
4c290476f8 | ||
|
|
e5be3c464e | ||
|
|
841afa5853 | ||
|
|
263b5d9aba | ||
|
|
1ced7fce14 | ||
|
|
7b325126da | ||
|
|
2b8e2526f2 | ||
|
|
09f66c5f5c | ||
|
|
b117e4ab55 | ||
|
|
0e35d32669 | ||
|
|
d625008c57 | ||
|
|
8b8b0f6669 | ||
|
|
f1f09151c0 | ||
|
|
1a16a42f18 | ||
|
|
69d2b0d278 | ||
|
|
c9554e4b91 | ||
|
|
a3db292b8d | ||
|
|
bf972d1d34 | ||
|
|
837cd2570a | ||
|
|
338813219e | ||
|
|
3ff4df5c6e | ||
|
|
7fd6d89567 | ||
|
|
cddfeba266 |
@@ -1,12 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// blueman's shape (novox/hq ADR 0208, ADR 0210): one official package, no seat, the X display on its
|
||||
@@ -14,40 +15,16 @@ import (
|
||||
// bluetooth module's (bluez, its utilities, its daemon), and the Go bundle serving exactly the listed
|
||||
// blueman_ tools.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Tools []string `json:"tools"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Claims []any `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Shell []any `json:"shell"`
|
||||
Contributions []any `json:"contributions"`
|
||||
Environment any `json:"environment"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) (manifest, string) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
func TestItInstallsTheAppletAndNothingElse(t *testing.T) {
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
return m, string(raw)
|
||||
}
|
||||
|
||||
func TestItInstallsTheAppletAndNothingElse(t *testing.T) {
|
||||
m, _ := readManifest(t)
|
||||
if m.Module != "blueman" || !reflect.DeepEqual(m.Requires, []string{"x11-display"}) ||
|
||||
!reflect.DeepEqual(m.Capabilities, []string{"package-manager"}) {
|
||||
t.Fatalf("%+v", m)
|
||||
@@ -55,13 +32,22 @@ func TestItInstallsTheAppletAndNothingElse(t *testing.T) {
|
||||
if len(m.Resources) != 1 || m.Resources[0]["type"] != "package" || m.Resources[0]["package"] != packageFor {
|
||||
t.Fatalf("resources: %v", m.Resources)
|
||||
}
|
||||
if m.Claims != nil || m.Seats != nil || m.Environment != nil {
|
||||
if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil {
|
||||
t.Fatal("it holds no seat and sets no environment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestItAddsNoSecondStartAndDeclaresNothingOfTheBluetoothModule(t *testing.T) {
|
||||
m, raw := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
raw := string(manifestJSON)
|
||||
// The package ships its XDG autostart entry, which the session's dex runs: an xinitrc slot or a
|
||||
// window-manager exec would start it twice.
|
||||
if m.Shell != nil || m.Contributions != nil {
|
||||
@@ -75,7 +61,16 @@ func TestItAddsNoSecondStartAndDeclaresNothingOfTheBluetoothModule(t *testing.T)
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m, raw := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
raw := string(manifestJSON)
|
||||
served := map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
served[tool.Name] = true
|
||||
@@ -96,8 +91,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
t.Fatalf("%v", m.Build.Artifacts)
|
||||
}
|
||||
b := m.Build.Artifacts[0]
|
||||
if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" ||
|
||||
b["from"] != "cmd/blueman-tools" || b["binary"] != "blueman-tools" {
|
||||
if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" ||
|
||||
b.From != "cmd/blueman-tools" || b.Binary != "blueman-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", b)
|
||||
}
|
||||
s := strings.ToLower(raw)
|
||||
|
||||
@@ -1,66 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
|
||||
// every desktop module that carries it.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Moved bool `json:"moved"`
|
||||
Items []item `json:"items"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Claims []claim `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Tools []string `json:"tools"`
|
||||
Environment *environment `json:"environment"`
|
||||
Shell []shellCode `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
|
||||
Contributions []any `json:"contributions"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
type claim struct {
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
Serves []string `json:"serves"`
|
||||
}
|
||||
|
||||
type environment struct {
|
||||
Variables map[string]string `json:"variables"`
|
||||
Path []map[string]any `json:"path"`
|
||||
}
|
||||
|
||||
type shellCode struct {
|
||||
For string `json:"for"`
|
||||
Slot string `json:"slot"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
|
||||
type item struct {
|
||||
Collection string `json:"collection"`
|
||||
Name string `json:"name"`
|
||||
Attributes map[string]string `json:"attributes"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
|
||||
// the collections shell:<file>:<slot>, in the order they are declared.
|
||||
func (m manifest) shell(t *testing.T) []shellCode {
|
||||
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
|
||||
t.Helper()
|
||||
var out []shellCode
|
||||
var out []catalogue.ShellCode
|
||||
for _, it := range m.Items {
|
||||
parts := strings.Split(it.Collection, ":")
|
||||
if len(parts) != 3 || parts[0] != "shell" {
|
||||
@@ -70,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
|
||||
func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
|
||||
t.Helper()
|
||||
var env *environment
|
||||
var env *catalogue.Environment
|
||||
for _, it := range m.Items {
|
||||
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
|
||||
continue
|
||||
@@ -88,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env == nil {
|
||||
env = &environment{Variables: map[string]string{}}
|
||||
env = &catalogue.Environment{Variables: map[string]string{}}
|
||||
}
|
||||
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
m.Environment = m.environmentOf(t)
|
||||
return m
|
||||
}
|
||||
|
||||
func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == id {
|
||||
@@ -122,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m manifest) packages() (present, absent []string) {
|
||||
func packages(m catalogue.Manifest) (present, absent []string) {
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "package" {
|
||||
if r["absent"] == true {
|
||||
@@ -138,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
|
||||
// fromTemplate checks that a file resource takes its text from its template file in the module's
|
||||
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
|
||||
// template is there. The readable file in the repository is the one place the machine's text is written.
|
||||
func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
|
||||
t.Helper()
|
||||
r := m.resource(t, id)
|
||||
r := resource(t, m, id)
|
||||
if r["type"] != "file" {
|
||||
t.Fatalf("%s is a %v, not a file", id, r["type"])
|
||||
}
|
||||
@@ -160,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
|
||||
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
|
||||
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
|
||||
func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if _, inline := r["content"]; inline {
|
||||
@@ -169,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
packs := 0
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "archive" && a["from"] == "files" {
|
||||
if a.Kind == "archive" && a.From == "files" {
|
||||
packs++
|
||||
if a["name"] != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a["name"])
|
||||
if a.Name != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
|
||||
// text is the text a file resource places on the machine: its template file's.
|
||||
func (m manifest) text(t *testing.T, id string) string {
|
||||
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
|
||||
t.Helper()
|
||||
name, _ := m.resource(t, id)["template"].(string)
|
||||
name, _ := resource(t, m, id)["template"].(string)
|
||||
if name == "" {
|
||||
t.Fatalf("resource %s names no template", id)
|
||||
}
|
||||
@@ -197,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
|
||||
|
||||
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
|
||||
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
|
||||
func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
own, seat := map[string]bool{}, map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
@@ -239,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
t.Errorf("the bundle serves %s, which no claim promises", name)
|
||||
}
|
||||
}
|
||||
var bundle map[string]any
|
||||
var bundle *catalogue.Artifact
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "bundle" {
|
||||
bundle = a
|
||||
if a.Kind == "bundle" {
|
||||
bundle = &a
|
||||
}
|
||||
}
|
||||
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
|
||||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
|
||||
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
|
||||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", bundle)
|
||||
}
|
||||
}
|
||||
@@ -271,7 +208,7 @@ const displaySession = "contribution:node-display-session:config"
|
||||
|
||||
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
|
||||
// contribution:node-display-session:config (design 57 L3, issue 848).
|
||||
func (m manifest) i3Lines() string {
|
||||
func i3Lines(m catalogue.Manifest) string {
|
||||
var out string
|
||||
for _, it := range m.Items {
|
||||
if it.Collection == displaySession {
|
||||
@@ -287,7 +224,7 @@ func (m manifest) i3Lines() string {
|
||||
|
||||
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
|
||||
// old-form contribution to node-display-session is left.
|
||||
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
|
||||
t.Helper()
|
||||
if len(m.Contributions) != 0 {
|
||||
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
|
||||
@@ -301,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
if len(templates) != 1 || templates[0] != source {
|
||||
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
|
||||
}
|
||||
if m.i3Lines() == "" {
|
||||
if i3Lines(m) == "" {
|
||||
t.Fatalf("the template %s holds no line", source)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,12 +6,15 @@ import (
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// clipmenu's shape (novox/hq ADR 0208, research 026/04): it claims node-clipboard serving history
|
||||
@@ -19,28 +22,44 @@ import (
|
||||
// from the session's start, and binds its menu as an i3 drop-in through the launcher's dmenu command.
|
||||
|
||||
func TestItClaimsTheClipboardSeatServingHistoryAndCopy(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if m.Module != "clipmenu" || m.Seats != nil {
|
||||
t.Fatalf("module %q declares seats %v", m.Module, m.Seats)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-clipboard", Scope: "node", Serves: []string{"history", "copy"}}}) {
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if m.Module != "clipmenu" || m.DefinesSeats != nil {
|
||||
t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-clipboard", Scope: "node", Serves: []string{"history", "copy"}}}) {
|
||||
t.Fatalf("claims: %+v", m.Claims)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) {
|
||||
t.Fatalf("requires: %v", m.Requires)
|
||||
}
|
||||
present, absent := m.packages()
|
||||
present, absent := packages(m)
|
||||
if !reflect.DeepEqual(present, []string{"clipmenu"}) || !reflect.DeepEqual(absent, []string{"rofi-greenclip"}) {
|
||||
t.Fatalf("packages: %v, absent %v", present, absent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if len(m.shell(t)) != 0 {
|
||||
t.Fatalf("a second start from the session: %+v", m.shell(t))
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc := m.resource(t, "daemon")
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if len(shell(t, m)) != 0 {
|
||||
t.Fatalf("a second start from the session: %+v", shell(t, m))
|
||||
}
|
||||
svc := resource(t, m, "daemon")
|
||||
want := map[string]any{"id": "daemon", "type": "service", "unit": "clipmenud.service", "scope": "user",
|
||||
"user": "${machine:account}", "state": "running", "boot": "enabled", "reload-on": nil}
|
||||
for k, v := range want {
|
||||
@@ -53,15 +72,15 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
|
||||
if h, _ := svc["health"].(map[string]any); h["kind"] != "unit" {
|
||||
t.Fatalf("daemon health = %v, want kind unit", svc["health"])
|
||||
}
|
||||
dropin := m.resource(t, "daemon-dropin")
|
||||
content := m.text(t, "daemon-dropin")
|
||||
dropin := resource(t, m, "daemon-dropin")
|
||||
content := templateText(t, m, "daemon-dropin")
|
||||
if dropin["path"] != "${machine:account-home}/.config/systemd/user/clipmenud.service.d/mesh.conf" ||
|
||||
dropin["owner"] != "${machine:account}" ||
|
||||
!strings.Contains(content, "ExecStart=/usr/local/lib/mesh-clipmenu/clipmenud-session") ||
|
||||
strings.Contains(content, "greenclip") {
|
||||
t.Fatalf("drop-in: %v", dropin)
|
||||
}
|
||||
launcher := m.text(t, "launcher")
|
||||
launcher := templateText(t, m, "launcher")
|
||||
if !strings.Contains(launcher, "DISPLAY") || !strings.Contains(launcher, "/tmp/.X11-unix") ||
|
||||
!strings.Contains(launcher, `PATH="/usr/local/lib/mesh-clipmenu:$PATH"`) || !strings.Contains(launcher, "exec clipmenud") {
|
||||
t.Fatalf("launcher: %q", launcher)
|
||||
@@ -74,7 +93,7 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
|
||||
if !strings.Contains(content, "StartLimitIntervalSec=0") || !strings.Contains(content, "RestartSec=2s") {
|
||||
t.Fatalf("drop-in lacks the safety net: %q", content)
|
||||
}
|
||||
for k, v := range m.environmentOf(t).Variables {
|
||||
for k, v := range environmentOf(t, m).Variables {
|
||||
if !strings.Contains(content, "Environment="+k+"="+v) {
|
||||
t.Fatalf("the unit lacks %s=%s", k, v)
|
||||
}
|
||||
@@ -82,34 +101,67 @@ func TestTheDaemonIsTheOperatorsUserUnitEnabledAndRunning(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestItsSettingsAreEnvironmentAndItsMenuIsTheLaunchersDmenu(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if !reflect.DeepEqual(m.Environment.Variables, map[string]string{"CM_SELECTIONS": "clipboard", "CM_MAX_CLIPS": "500", "CM_HISTLENGTH": "15"}) {
|
||||
t.Fatalf("%v", m.Environment.Variables)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, set := m.Environment.Variables["CM_LAUNCHER"]; set {
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(environmentOf(t, m).Variables, map[string]string{"CM_SELECTIONS": "clipboard", "CM_MAX_CLIPS": "500", "CM_HISTLENGTH": "15"}) {
|
||||
t.Fatalf("%v", environmentOf(t, m).Variables)
|
||||
}
|
||||
if _, set := environmentOf(t, m).Variables["CM_LAUNCHER"]; set {
|
||||
t.Fatal("the launcher is clipmenu's default, dmenu: the seat's command")
|
||||
}
|
||||
m.i3LinesAreSource(t, "files/i3/50-clipmenu.conf")
|
||||
if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") {
|
||||
i3LinesAreSource(t, m, "files/i3/50-clipmenu.conf")
|
||||
if c := i3Lines(m); !strings.Contains(c, "bindsym $mod+period exec --no-startup-id clipmenu") {
|
||||
t.Fatalf("%s", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
checkTheToolsAgree(t, m)
|
||||
checkNoSecretsOrInstallationNames(t)
|
||||
}
|
||||
|
||||
// No file resource carries its text inline (novox/hq ADR 0349 §2).
|
||||
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
readManifest(t).everyFileIsATemplate(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
everyFileIsATemplate(t, m)
|
||||
}
|
||||
|
||||
// Run for real: DISPLAY from the manager is used at once; several sockets and no DISPLAY wait.
|
||||
func TestTheLauncherUsesTheManagersDisplayAndWaitsOtherwise(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
script := m.text(t, "launcher")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
script := templateText(t, m, "launcher")
|
||||
dir := t.TempDir()
|
||||
file := dir + "/launcher"
|
||||
// clipmenud and the socket directory are faked: the script's own paths are rewritten.
|
||||
@@ -162,8 +214,16 @@ func TestTheLauncherWaitsQuietlyWhileAnotherClipmenudHoldsTheLock(t *testing.T)
|
||||
if _, err := exec.LookPath("flock"); err != nil {
|
||||
t.Skip("flock is missing here")
|
||||
}
|
||||
m := readManifest(t)
|
||||
script := m.text(t, "launcher")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
script := templateText(t, m, "launcher")
|
||||
dir := t.TempDir()
|
||||
body := strings.Replace(script, "exec clipmenud", `echo "started"`, 1)
|
||||
file := dir + "/launcher"
|
||||
|
||||
@@ -34,7 +34,7 @@ func jsonFields(v any) map[string]bool {
|
||||
func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
|
||||
inputs := map[string]any{reg.VerbPublish: reg.PublishInput{}, reg.VerbPublishPart: reg.PublishPartInput{},
|
||||
reg.VerbVersions: reg.VersionsInput{}, reg.VerbRemove: reg.RemoveInput{}, reg.VerbHold: reg.HoldInput{},
|
||||
reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbTags: reg.TagsInput{}}
|
||||
reg.VerbRelease: reg.ReleaseInput{}, reg.VerbMirror: reg.MirrorInput{}, reg.VerbNameOf: reg.NameOfInput{}, reg.VerbTags: reg.TagsInput{}}
|
||||
seen := 0
|
||||
for _, tool := range tools(&holder.Verbs{}, kept[holder.Window]{}, nil) {
|
||||
seat, verb, ok := strings.Cut(tool.Name, ".")
|
||||
@@ -51,8 +51,8 @@ func TestTheVerbsSpeakTheSeatsContract(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if seen != 14 {
|
||||
t.Errorf("%d seat verbs served, want 14 (8 on the image seat, 6 on the artifact seat)", seen)
|
||||
if seen != 15 {
|
||||
t.Errorf("%d seat verbs served, want 15 (9 on the image seat, 6 on the artifact seat)", seen)
|
||||
}
|
||||
for event, want := range map[string]any{holder.EventPublished: ®.Outcome{}, holder.EventKept: ®.KeptEvent{}, holder.EventHeld: ®.Hold{}, holder.EventReleased: ®.Hold{}} {
|
||||
b, _ := json.Marshal(eventBody(event, holder.Event{Name: "m/a", Kind: holder.KindArchive, Digest: "sha256:aa", Holder: holder.Self, By: "x.artifact-store-tools"}))
|
||||
|
||||
@@ -364,6 +364,19 @@ func tools(v *holder.Verbs, windows kept[holder.Window], taken *asks) []stdio.To
|
||||
}
|
||||
return reg.MirrorAnswer{Digest: in.Digest, Reference: ref}, nil
|
||||
}},
|
||||
stdio.Tool{Name: holder.ImageSeat + "." + holder.VerbNameOf, Description: "The reference an outside image, as a manifest's from names it pinned by its digest, is kept under in the store (upstream/<host>/<path>@<digest> in the seat's form), the one mirror answers; reads only, asks no copy, refuses a from with no digest.",
|
||||
Input: obj(map[string]any{"from": s("<name>[:<tag>]@sha256:…")}, "from"),
|
||||
Run: func(args map[string]any) (any, error) {
|
||||
in, err := arg[reg.NameOfInput](args)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ref, err := v.NameOf(holder.ImageSeat, in.From)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return reg.NameOfAnswer{Reference: ref}, nil
|
||||
}},
|
||||
stdio.Tool{Name: "registry_health", Description: "distribution's health check, run by the runtime each minute: versions of each seat asked through the store's read side (the program's port 5100); fails naming the program when it does not answer.",
|
||||
Input: obj(map[string]any{}),
|
||||
Run: func(map[string]any) (any, error) {
|
||||
|
||||
@@ -823,6 +823,18 @@ func TestTheHolderOfTheTwoImageSeats(t *testing.T) {
|
||||
if strings.ContainsAny(key, ":@") {
|
||||
t.Errorf("the ask's key %q holds characters a key may not", key)
|
||||
}
|
||||
// name-of answers the same reference for a manifest's pinned from, asking no copy (H-A-513); a from with no digest,
|
||||
// and the artifact seat, are refused.
|
||||
for _, from := range []string{"nats:2.11.17-alpine@" + d, "docker.io/library/nats@" + d} {
|
||||
if named, err := b.v.NameOf(ImageSeat, from); err != nil || named != want || len(asked) != 1 {
|
||||
t.Errorf("name-of %s = %q, %v, asks %d: want %s and no copy asked", from, named, err, len(asked), want)
|
||||
}
|
||||
}
|
||||
for seat, from := range map[string]string{ImageSeat: "nats:2.11.17-alpine", ArtifactSeat: "nats@" + d} {
|
||||
if named, err := b.v.NameOf(seat, from); err == nil {
|
||||
t.Errorf("name-of %s on %s = %q: want a refusal", from, seat, named)
|
||||
}
|
||||
}
|
||||
if err := b.v.Mirrored(asked[key]); err != nil || len(b.said) != 1 || b.said[0].event != EventPublished ||
|
||||
b.said[0].body.Reference != want || b.said[0].body.Kind != KindUpstream || len(asked) != 0 {
|
||||
t.Fatalf("the copy's end = %v, said %+v, asks %v: want published with the reference and the ask gone", err, b.said, asked)
|
||||
|
||||
@@ -26,6 +26,7 @@ const (
|
||||
VerbVersions = "versions"
|
||||
VerbRemove = "remove"
|
||||
VerbMirror = "mirror"
|
||||
VerbNameOf = "name-of"
|
||||
VerbTags = "tags"
|
||||
VerbHold = "hold"
|
||||
VerbRelease = "release"
|
||||
@@ -34,11 +35,11 @@ const (
|
||||
// Seats are the seats distribution answers verbs on.
|
||||
var Seats = []string{ImageSeat, ArtifactSeat}
|
||||
|
||||
// VerbsOf are a seat's verbs: mirror and tags on the image seat alone; hold, release and list on both of distribution's.
|
||||
// VerbsOf are a seat's verbs: mirror, name-of and tags on the image seat alone; hold, release and list on both of distribution's.
|
||||
func VerbsOf(seat string) []string {
|
||||
v := []string{VerbPublish, VerbPublishPart, VerbVersions, VerbRemove, VerbHold, VerbRelease, VerbList}
|
||||
if seat == ImageSeat {
|
||||
v = append(v, VerbMirror, VerbTags)
|
||||
v = append(v, VerbMirror, VerbNameOf, VerbTags)
|
||||
}
|
||||
sort.Strings(v)
|
||||
return v
|
||||
|
||||
@@ -333,6 +333,25 @@ func (v *Verbs) Mirror(seat, caller string, r MirrorRequest) (string, error) {
|
||||
return SeatReference(seat, v.Catalog.Reference(src.Name(), r.Digest)), nil
|
||||
}
|
||||
|
||||
// NameOf is `name-of` on the image seat (design 47 H2 H-A-513): the reference mirror answers, and keeps the copy under, for an
|
||||
// outside image as a manifest's from names it, pinned (<name>[:<tag>]@sha256:<digest>): the holder's own name for the copy,
|
||||
// upstream/<host>/<path>, with that digest, in the seat's form. It reads only and asks no copy; a from that pins no digest is
|
||||
// refused, as mirror refuses it.
|
||||
func (v *Verbs) NameOf(seat, from string) (string, error) {
|
||||
if seat != ImageSeat {
|
||||
return "", fmt.Errorf("name-of: %s serves no name-of", seat)
|
||||
}
|
||||
_, digest, pinned := strings.Cut(strings.TrimSpace(from), "@")
|
||||
if !pinned || !strings.HasPrefix(digest, "sha256:") || len(digest) != len("sha256:")+64 {
|
||||
return "", fmt.Errorf("name-of: refused: %q pins no digest, and an upstream image is named only by its pinned digest", from)
|
||||
}
|
||||
src, err := ParseSource(from)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return SeatReference(seat, v.Catalog.Reference(src.Name(), digest)), nil
|
||||
}
|
||||
|
||||
// Mirrored runs one asked copy and says its outcome on the image seat's events: published with the reference, or
|
||||
// refused with the reason; the ask leaves the state either way. An outcome that cannot be said keeps the ask, so the
|
||||
// next watch takes it on again.
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"hold",
|
||||
"list",
|
||||
"mirror",
|
||||
"name-of",
|
||||
"publish",
|
||||
"publish-part",
|
||||
"release",
|
||||
|
||||
@@ -1,85 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
|
||||
// every desktop module that carries it.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Moved bool `json:"moved"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Claims []claim `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Tools []string `json:"tools"`
|
||||
Config map[string]config `json:"config"`
|
||||
Emits []string `json:"emits"`
|
||||
Items []item `json:"items"`
|
||||
Contributions []any `json:"contributions"`
|
||||
Environment *environment `json:"environment"`
|
||||
Shell []shellCode `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
// config is one config value as the definition declares it (novox/hq ADR 0348 §4).
|
||||
type config struct {
|
||||
Type string `json:"type"`
|
||||
Description string `json:"description"`
|
||||
Enum []any `json:"enum"`
|
||||
Minimum *float64 `json:"minimum"`
|
||||
Maximum *float64 `json:"maximum"`
|
||||
Pattern string `json:"pattern"`
|
||||
Trusted bool `json:"trusted"`
|
||||
Predefined string `json:"predefined"`
|
||||
Default any `json:"default"`
|
||||
Required bool `json:"required"`
|
||||
Runtime bool `json:"runtime"`
|
||||
}
|
||||
|
||||
type claim struct {
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
Serves []string `json:"serves"`
|
||||
}
|
||||
|
||||
type environment struct {
|
||||
Variables map[string]string `json:"variables"`
|
||||
Path []map[string]any `json:"path"`
|
||||
}
|
||||
|
||||
type shellCode struct {
|
||||
For string `json:"for"`
|
||||
Slot string `json:"slot"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == id {
|
||||
@@ -90,7 +20,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m manifest) packages() (present, absent []string) {
|
||||
func packages(m catalogue.Manifest) (present, absent []string) {
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "package" {
|
||||
if r["absent"] == true {
|
||||
@@ -106,9 +36,9 @@ func (m manifest) packages() (present, absent []string) {
|
||||
// fromTemplate checks that a file resource takes its text from its template file in the module's
|
||||
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
|
||||
// template is there. The readable file in the repository is the one place the machine's text is written.
|
||||
func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
|
||||
t.Helper()
|
||||
r := m.resource(t, id)
|
||||
r := resource(t, m, id)
|
||||
if r["type"] != "file" {
|
||||
t.Fatalf("%s is a %v, not a file", id, r["type"])
|
||||
}
|
||||
@@ -128,7 +58,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
|
||||
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
|
||||
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
|
||||
func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if _, inline := r["content"]; inline {
|
||||
@@ -137,10 +67,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
packs := 0
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "archive" && a["from"] == "files" {
|
||||
if a.Kind == "archive" && a.From == "files" {
|
||||
packs++
|
||||
if a["name"] != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a["name"])
|
||||
if a.Name != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,9 +80,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
|
||||
// text is the text a file resource places on the machine: its template file's.
|
||||
func (m manifest) text(t *testing.T, id string) string {
|
||||
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
|
||||
t.Helper()
|
||||
name, _ := m.resource(t, id)["template"].(string)
|
||||
name, _ := resource(t, m, id)["template"].(string)
|
||||
if name == "" {
|
||||
t.Fatalf("resource %s names no template", id)
|
||||
}
|
||||
@@ -165,7 +95,7 @@ func (m manifest) text(t *testing.T, id string) string {
|
||||
|
||||
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
|
||||
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
|
||||
func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
own, seat := map[string]bool{}, map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
@@ -207,14 +137,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
t.Errorf("the bundle serves %s, which no claim promises", name)
|
||||
}
|
||||
}
|
||||
var bundle map[string]any
|
||||
var bundle *catalogue.Artifact
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "bundle" {
|
||||
bundle = a
|
||||
if a.Kind == "bundle" {
|
||||
bundle = &a
|
||||
}
|
||||
}
|
||||
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
|
||||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
|
||||
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
|
||||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", bundle)
|
||||
}
|
||||
}
|
||||
@@ -239,7 +169,7 @@ const displaySession = "contribution:node-display-session:config"
|
||||
|
||||
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
|
||||
// contribution:node-display-session:config (design 57 L3, issue 848).
|
||||
func (m manifest) i3Lines() string {
|
||||
func i3Lines(m catalogue.Manifest) string {
|
||||
var out string
|
||||
for _, it := range m.Items {
|
||||
if it.Collection == displaySession {
|
||||
@@ -255,7 +185,7 @@ func (m manifest) i3Lines() string {
|
||||
|
||||
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
|
||||
// old-form contribution to node-display-session is left.
|
||||
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
|
||||
t.Helper()
|
||||
if len(m.Contributions) != 0 {
|
||||
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
|
||||
@@ -269,14 +199,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
if len(templates) != 1 || templates[0] != source {
|
||||
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
|
||||
}
|
||||
if m.i3Lines() == "" {
|
||||
if i3Lines(m) == "" {
|
||||
t.Fatalf("the template %s holds no line", source)
|
||||
}
|
||||
}
|
||||
|
||||
type item struct {
|
||||
Collection string `json:"collection"`
|
||||
Name string `json:"name"`
|
||||
Attributes map[string]string `json:"attributes"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// dunst's shape (novox/hq ADR 0208): it claims node-notifier serving send and history, owns its
|
||||
@@ -12,28 +16,44 @@ import (
|
||||
// activation, so it requires no display of its own.
|
||||
|
||||
func TestItClaimsTheNotifierSeatServingSendAndHistory(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if m.Module != "dunst" || m.Seats != nil {
|
||||
t.Fatalf("module %q declares seats %v", m.Module, m.Seats)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-notifier", Scope: "node", Serves: []string{"send", "history"}}}) {
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if m.Module != "dunst" || m.DefinesSeats != nil {
|
||||
t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-notifier", Scope: "node", Serves: []string{"send", "history"}}}) {
|
||||
t.Fatalf("claims: %+v", m.Claims)
|
||||
}
|
||||
// rofi, the context menu the dunstrc calls by name, is the rofi module's package: two modules on one
|
||||
// machine may not declare the same package, and the rofi module holds node-launcher on every
|
||||
// machine dunst serves.
|
||||
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"dunst", "libnotify"}) || absent != nil {
|
||||
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"dunst", "libnotify"}) || absent != nil {
|
||||
t.Fatalf("packages: %v, absent %v", present, absent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestItOwnsItsFileAndTheDropInDirectory(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
m.fromTemplate(t, "configuration", "files/dunstrc")
|
||||
if p := m.resource(t, "configuration")["path"]; p != "${machine:account-home}/.config/dunst/dunstrc" {
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
fromTemplate(t, m, "configuration", "files/dunstrc")
|
||||
if p := resource(t, m, "configuration")["path"]; p != "${machine:account-home}/.config/dunst/dunstrc" {
|
||||
t.Fatalf("path: %v", p)
|
||||
}
|
||||
if d := m.resource(t, "dropins"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/dunst/dunstrc.d" {
|
||||
if d := resource(t, m, "dropins"); d["type"] != "directory" || d["path"] != "${machine:account-home}/.config/dunst/dunstrc.d" {
|
||||
t.Fatalf("drop-ins: %v", d)
|
||||
}
|
||||
for _, r := range m.Resources {
|
||||
@@ -44,8 +64,16 @@ func TestItOwnsItsFileAndTheDropInDirectory(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTheFileIsTheDecidedOneAndCallsRofi(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
c := m.text(t, "configuration")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
c := templateText(t, m, "configuration")
|
||||
for _, want := range []string{"origin = top-right", "transparency = 0", "corner_radius = 0", "font = Inter ${config:font-size}",
|
||||
"width = ${config:width}", "dmenu = rofi -dmenu -no-custom -p dunst"} {
|
||||
if !strings.Contains(c, " "+want+"\n") {
|
||||
@@ -66,8 +94,16 @@ func TestTheFileIsTheDecidedOneAndCallsRofi(t *testing.T) {
|
||||
// of them (dunst holds it open until the menu answers, and an Escape leaves it shown), and one without
|
||||
// actions closes. Every other click is as it was.
|
||||
func TestATapChoosesTheNotificationsAction(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
c := m.text(t, "configuration")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
c := templateText(t, m, "configuration")
|
||||
for _, want := range []string{"mouse_left_click = do_action, close_current",
|
||||
"mouse_middle_click = do_action, close_current", "mouse_right_click = close_all"} {
|
||||
if !strings.Contains(c, " "+want+"\n") {
|
||||
@@ -82,9 +118,17 @@ func TestATapChoosesTheNotificationsAction(t *testing.T) {
|
||||
// The key that chooses from the keyboard is a line i3 places from this contribution (novox/hq ADR
|
||||
// 0212): a binding only, never a start, so the bus stays the only thing that starts dunst.
|
||||
func TestTheMenuKeyIsABindingI3Places(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
m.i3LinesAreSource(t, "files/i3/50-dunst.conf")
|
||||
lines := m.i3Lines()
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
i3LinesAreSource(t, m, "files/i3/50-dunst.conf")
|
||||
lines := i3Lines(m)
|
||||
if !strings.Contains(lines, "bindsym $mod+n exec --no-startup-id dunstctl context\n") {
|
||||
t.Fatalf("no key for the context menu: %s", lines)
|
||||
}
|
||||
@@ -100,23 +144,31 @@ func TestTheMenuKeyIsABindingI3Places(t *testing.T) {
|
||||
// predefined font-size (ADR 0348 §2), so a machine with a denser screen sets its own and every other
|
||||
// machine's file is unchanged. Neither is trusted: the file says "trusted": false.
|
||||
func TestTheFontSizeAndWidthAreConfigValuesWithTodaysDefaults(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
want := map[string]float64{"font-size": 10, "width": 250}
|
||||
if len(m.Config) != len(want) {
|
||||
t.Fatalf("config: %+v", m.Config)
|
||||
if len(m.Settings) != len(want) {
|
||||
t.Fatalf("config: %+v", m.Settings)
|
||||
}
|
||||
for key, value := range want {
|
||||
s, ok := m.Config[key]
|
||||
s, ok := m.Settings[key]
|
||||
if !ok || s.Type != "number" || s.Default != value || s.Required || s.Trusted ||
|
||||
strings.TrimSpace(s.Description) == "" || s.Minimum == nil || s.Maximum == nil {
|
||||
t.Errorf("%s: %+v, want an untrusted number defaulting to %v, with a description and bounds", key, s, value)
|
||||
}
|
||||
}
|
||||
if p := m.Config["font-size"].Predefined; p != "font-size" {
|
||||
if p := m.Settings["font-size"].Predefined; p != "font-size" {
|
||||
t.Errorf("the font size falls back to %q, want the predefined font-size", p)
|
||||
}
|
||||
// Filled with the defaults, the file is the one every machine had before it took config values.
|
||||
c := m.text(t, "configuration")
|
||||
c := templateText(t, m, "configuration")
|
||||
c = strings.ReplaceAll(c, "${config:font-size}", "10")
|
||||
c = strings.ReplaceAll(c, "${config:width}", "250")
|
||||
for _, want := range []string{"font = Inter 10", "width = 250"} {
|
||||
@@ -130,7 +182,15 @@ func TestTheFontSizeAndWidthAreConfigValuesWithTodaysDefaults(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestNothingStartsItButTheBus(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if m.Shell != nil {
|
||||
t.Fatalf("a session start: %+v", m.Shell)
|
||||
}
|
||||
@@ -147,25 +207,50 @@ func TestNothingStartsItButTheBus(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
checkTheToolsAgree(t, m)
|
||||
checkNoSecretsOrInstallationNames(t)
|
||||
}
|
||||
|
||||
// No file resource carries its text inline (novox/hq ADR 0349 §2).
|
||||
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
readManifest(t).everyFileIsATemplate(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
everyFileIsATemplate(t, m)
|
||||
}
|
||||
|
||||
// dunst moves first (design 57 P6, issue 672): marked moved, its dunstrc is filled on the node by the provisioner's
|
||||
// client from its template, and reloaded as the file declares.
|
||||
func TestItIsHandedToTheProvisioner(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if !m.Moved {
|
||||
t.Fatal("dunst is not marked moved")
|
||||
}
|
||||
m.fromTemplate(t, "configuration", "files/dunstrc")
|
||||
if on := m.resource(t, "notifier")["reload-on"]; !reflect.DeepEqual(on, []any{"configuration"}) {
|
||||
fromTemplate(t, m, "configuration", "files/dunstrc")
|
||||
if on := resource(t, m, "notifier")["reload-on"]; !reflect.DeepEqual(on, []any{"configuration"}) {
|
||||
t.Fatalf("the notifier is not reloaded on its dunstrc: %v", on)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The running dunst reads its file again when the file changes (novox/hq ADR 0262: a setting the
|
||||
@@ -83,8 +85,16 @@ func TestAReloadDunstRefusesIsAFailure(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTheRunningDunstIsReloadedWhenItsFileChanges(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
s := m.resource(t, "notifier")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
s := resource(t, m, "notifier")
|
||||
want := map[string]any{
|
||||
"id": "notifier", "type": "service", "unit": "dunst.service",
|
||||
"scope": "user", "user": "${machine:account}",
|
||||
|
||||
@@ -1,66 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
|
||||
// every desktop module that carries it.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Moved bool `json:"moved"`
|
||||
Items []item `json:"items"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Claims []claim `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Tools []string `json:"tools"`
|
||||
Environment *environment `json:"environment"`
|
||||
Shell []shellCode `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
|
||||
Contributions []any `json:"contributions"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
type claim struct {
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
Serves []string `json:"serves"`
|
||||
}
|
||||
|
||||
type environment struct {
|
||||
Variables map[string]string `json:"variables"`
|
||||
Path []map[string]any `json:"path"`
|
||||
}
|
||||
|
||||
type shellCode struct {
|
||||
For string `json:"for"`
|
||||
Slot string `json:"slot"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
|
||||
type item struct {
|
||||
Collection string `json:"collection"`
|
||||
Name string `json:"name"`
|
||||
Attributes map[string]string `json:"attributes"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
|
||||
// the collections shell:<file>:<slot>, in the order they are declared.
|
||||
func (m manifest) shell(t *testing.T) []shellCode {
|
||||
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
|
||||
t.Helper()
|
||||
var out []shellCode
|
||||
var out []catalogue.ShellCode
|
||||
for _, it := range m.Items {
|
||||
parts := strings.Split(it.Collection, ":")
|
||||
if len(parts) != 3 || parts[0] != "shell" {
|
||||
@@ -70,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
|
||||
func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
|
||||
t.Helper()
|
||||
var env *environment
|
||||
var env *catalogue.Environment
|
||||
for _, it := range m.Items {
|
||||
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
|
||||
continue
|
||||
@@ -88,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env == nil {
|
||||
env = &environment{Variables: map[string]string{}}
|
||||
env = &catalogue.Environment{Variables: map[string]string{}}
|
||||
}
|
||||
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
m.Environment = m.environmentOf(t)
|
||||
return m
|
||||
}
|
||||
|
||||
func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == id {
|
||||
@@ -122,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m manifest) packages() (present, absent []string) {
|
||||
func packages(m catalogue.Manifest) (present, absent []string) {
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "package" {
|
||||
if r["absent"] == true {
|
||||
@@ -138,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
|
||||
// fromTemplate checks that a file resource takes its text from its template file in the module's
|
||||
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
|
||||
// template is there. The readable file in the repository is the one place the machine's text is written.
|
||||
func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
|
||||
t.Helper()
|
||||
r := m.resource(t, id)
|
||||
r := resource(t, m, id)
|
||||
if r["type"] != "file" {
|
||||
t.Fatalf("%s is a %v, not a file", id, r["type"])
|
||||
}
|
||||
@@ -160,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
|
||||
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
|
||||
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
|
||||
func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if _, inline := r["content"]; inline {
|
||||
@@ -169,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
packs := 0
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "archive" && a["from"] == "files" {
|
||||
if a.Kind == "archive" && a.From == "files" {
|
||||
packs++
|
||||
if a["name"] != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a["name"])
|
||||
if a.Name != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -182,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
|
||||
// text is the text a file resource places on the machine: its template file's.
|
||||
func (m manifest) text(t *testing.T, id string) string {
|
||||
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
|
||||
t.Helper()
|
||||
name, _ := m.resource(t, id)["template"].(string)
|
||||
name, _ := resource(t, m, id)["template"].(string)
|
||||
if name == "" {
|
||||
t.Fatalf("resource %s names no template", id)
|
||||
}
|
||||
@@ -197,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
|
||||
|
||||
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
|
||||
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
|
||||
func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
own, seat := map[string]bool{}, map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
@@ -239,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
t.Errorf("the bundle serves %s, which no claim promises", name)
|
||||
}
|
||||
}
|
||||
var bundle map[string]any
|
||||
var bundle *catalogue.Artifact
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "bundle" {
|
||||
bundle = a
|
||||
if a.Kind == "bundle" {
|
||||
bundle = &a
|
||||
}
|
||||
}
|
||||
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
|
||||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
|
||||
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
|
||||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", bundle)
|
||||
}
|
||||
}
|
||||
@@ -271,7 +208,7 @@ const displaySession = "contribution:node-display-session:config"
|
||||
|
||||
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
|
||||
// contribution:node-display-session:config (design 57 L3, issue 848).
|
||||
func (m manifest) i3Lines() string {
|
||||
func i3Lines(m catalogue.Manifest) string {
|
||||
var out string
|
||||
for _, it := range m.Items {
|
||||
if it.Collection == displaySession {
|
||||
@@ -287,7 +224,7 @@ func (m manifest) i3Lines() string {
|
||||
|
||||
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
|
||||
// old-form contribution to node-display-session is left.
|
||||
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
|
||||
t.Helper()
|
||||
if len(m.Contributions) != 0 {
|
||||
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
|
||||
@@ -301,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
if len(templates) != 1 || templates[0] != source {
|
||||
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
|
||||
}
|
||||
if m.i3Lines() == "" {
|
||||
if i3Lines(m) == "" {
|
||||
t.Fatalf("the template %s holds no line", source)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// feh's shape (novox/hq ADR 0208): no seat; it requires the X display on its own machine, carries
|
||||
@@ -13,27 +15,43 @@ import (
|
||||
// the session's start.
|
||||
|
||||
func TestItRequiresTheXDisplayAndClaimsNothing(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if m.Module != "feh" || m.Seats != nil || m.Claims != nil {
|
||||
t.Fatalf("module %q, seats %v, claims %v", m.Module, m.Seats, m.Claims)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if m.Module != "feh" || m.DefinesSeats != nil || m.Claims != nil {
|
||||
t.Fatalf("module %q, seats %v, claims %v", m.Module, m.DefinesSeats, m.Claims)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) {
|
||||
t.Fatalf("requires: %v", m.Requires)
|
||||
}
|
||||
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"feh"}) || absent != nil {
|
||||
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"feh"}) || absent != nil {
|
||||
t.Fatalf("packages: %v, absent %v", present, absent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheWallpaperIsTheModulesOwnArchive(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
a := m.resource(t, "wallpapers")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
a := resource(t, m, "wallpapers")
|
||||
if a["type"] != "archive" || a["artifact"] != "wallpapers" || a["path"] != "${machine:account-home}/.local/share/feh/wallpapers" || a["owner"] != "${machine:account}" {
|
||||
t.Fatalf("%v", a)
|
||||
}
|
||||
found := false
|
||||
for _, art := range m.Build.Artifacts {
|
||||
if art["name"] == "wallpapers" && art["kind"] == "archive" && art["from"] == "wallpaper" {
|
||||
if art.Name == "wallpapers" && art.Kind == "archive" && art.From == "wallpaper" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
@@ -47,38 +65,71 @@ func TestTheWallpaperIsTheModulesOwnArchive(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFehbgIsOwnedAndTheSessionStartRunsItOnce(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
m.fromTemplate(t, "fehbg", "files/fehbg")
|
||||
f := m.resource(t, "fehbg")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
fromTemplate(t, m, "fehbg", "files/fehbg")
|
||||
f := resource(t, m, "fehbg")
|
||||
if f["path"] != "${machine:account-home}/.fehbg" || f["mode"] != "0755" {
|
||||
t.Fatalf("%v", f)
|
||||
}
|
||||
if c := m.text(t, "fehbg"); !strings.Contains(c, "$HOME/.local/share/feh/wallpapers/default.jpg") || strings.Contains(c, ".hal") {
|
||||
if c := templateText(t, m, "fehbg"); !strings.Contains(c, "$HOME/.local/share/feh/wallpapers/default.jpg") || strings.Contains(c, ".hal") {
|
||||
t.Fatalf("%s", c)
|
||||
}
|
||||
if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" || strings.Count(m.shell(t)[0].Code, `"$HOME/.fehbg"`) != 1 {
|
||||
t.Fatalf("%+v", m.shell(t))
|
||||
if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" || strings.Count(shell(t, m)[0].Code, `"$HOME/.fehbg"`) != 1 {
|
||||
t.Fatalf("%+v", shell(t, m))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheKeyThatRestoresTheWallpaperIsAnI3DropIn(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
m.i3LinesAreSource(t, "files/i3/50-feh.conf")
|
||||
if p := m.i3Lines(); p == "" {
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
i3LinesAreSource(t, m, "files/i3/50-feh.conf")
|
||||
if p := i3Lines(m); p == "" {
|
||||
t.Fatalf("path: %v", p)
|
||||
}
|
||||
if c := m.i3Lines(); !strings.Contains(c, "bindsym $mod+Shift+b exec --no-startup-id ~/.fehbg\n") {
|
||||
if c := i3Lines(m); !strings.Contains(c, "bindsym $mod+Shift+b exec --no-startup-id ~/.fehbg\n") {
|
||||
t.Fatalf("%s", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
checkTheToolsAgree(t, m)
|
||||
checkNoSecretsOrInstallationNames(t)
|
||||
}
|
||||
|
||||
// No file resource carries its text inline (novox/hq ADR 0349 §2).
|
||||
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
readManifest(t).everyFileIsATemplate(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
everyFileIsATemplate(t, m)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// forticlient's shape (novox/hq ADR 0205, ADR 0207, ADR 0208): no package (the client is outside the
|
||||
@@ -15,48 +16,17 @@ import (
|
||||
// start), nothing of the VPN's configuration, and the Go bundle serving exactly the listed forticlient_
|
||||
// tools.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Upgrade struct {
|
||||
Policy string `json:"policy"`
|
||||
Why string `json:"why"`
|
||||
} `json:"upgrade"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Tools []string `json:"tools"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Claims []any `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Shell []any `json:"shell"`
|
||||
Contributions []struct {
|
||||
Seat string `json:"seat"`
|
||||
Kind string `json:"kind"`
|
||||
Content string `json:"content"`
|
||||
} `json:"contributions"`
|
||||
Environment any `json:"environment"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) (manifest, string) {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
return m, string(raw)
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m, raw := readManifest(t)
|
||||
raw := string(manifestJSON)
|
||||
served := map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
served[tool.Name] = true
|
||||
@@ -77,8 +47,8 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
t.Fatalf("%v", m.Build.Artifacts)
|
||||
}
|
||||
b := m.Build.Artifacts[0]
|
||||
if b["kind"] != "bundle" || b["language"] != "go" || b["system"] != "arch" ||
|
||||
b["from"] != "cmd/forticlient-tools" || b["binary"] != "forticlient-tools" {
|
||||
if b.Kind != "bundle" || b.Language != "go" || b.System != "arch" ||
|
||||
b.From != "cmd/forticlient-tools" || b.Binary != "forticlient-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", b)
|
||||
}
|
||||
s := strings.ToLower(raw)
|
||||
@@ -90,7 +60,16 @@ func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestItDeclaresTheServiceAndNothingOfTheConfiguration(t *testing.T) {
|
||||
m, raw := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
raw := string(manifestJSON)
|
||||
// split-dns (novox/hq ADR 0247): the machine's own resolver, which its adapter hands the client's
|
||||
// resolver file to. Required at the machine's reach, so the module is assigned only beside one.
|
||||
if m.Module != "forticlient" || !reflect.DeepEqual(m.Requires, []string{"x11-display", "split-dns"}) ||
|
||||
@@ -110,7 +89,7 @@ func TestItDeclaresTheServiceAndNothingOfTheConfiguration(t *testing.T) {
|
||||
if m.Upgrade.Policy != "record" || m.Upgrade.Why == "" {
|
||||
t.Error("a build of what routes the person's work names rolls out on its own")
|
||||
}
|
||||
if m.Claims != nil || m.Seats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil {
|
||||
if m.Claims != nil || m.DefinesSeats != nil || m.Environment != nil || m.Shell != nil || m.Contributions != nil {
|
||||
t.Fatal("no seat, no environment, and no second start")
|
||||
}
|
||||
for _, never := range []string{"/etc/forticlient", "/opt/forticlient", "autostart", "\"package\"", "vpn.", "gateway", "profile"} {
|
||||
|
||||
@@ -694,6 +694,13 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
|
||||
"cmd/forge": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER"},
|
||||
"cmd/package-registry": {"MESH_GITEA_URL", "MESH_GITEA_TOOLS_USER", "MESH_GITEA_PACKAGES_USER"},
|
||||
}
|
||||
// H-A-564: until gitea runs as its own account, each Go bundle is handed the token files gitea's TypeScript bundle
|
||||
// keeps under its state directory, read when the vault refuses the caller's account.
|
||||
files := map[string]map[string]string{
|
||||
"cmd/forge": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token"},
|
||||
"cmd/package-registry": {"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
||||
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token"},
|
||||
}
|
||||
for _, a := range m.Build.Artifacts {
|
||||
want, ok := wants[a.From]
|
||||
if !ok {
|
||||
@@ -713,10 +720,9 @@ func TestToolsAreTheOnesTheReadmeNamesAndTheManifestBuilds(t *testing.T) {
|
||||
t.Errorf("%s is given %s: it acts as an account of its own, not the administrator", a.From, k)
|
||||
}
|
||||
}
|
||||
// Design 47 H2 §808, H-A-422 (1): the token is read through the vault seat's get, never from a file.
|
||||
for _, k := range []string{"MESH_GITEA_TOKEN_FILE", "MESH_GITEA_PACKAGES_TOKEN_FILE"} {
|
||||
if a.Env[k] != "" {
|
||||
t.Errorf("%s is given %s: its token is read from the vault", a.From, k)
|
||||
if a.Env[k] != files[a.From][k] {
|
||||
t.Errorf("%s is given %s %q, want %q (H-A-564)", a.From, k, a.Env[k], files[a.From][k])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,20 @@ package forgehttp
|
||||
// The forge module's tokens as its Go bundles read them (design 47 H2 §808; H-A-422 (1), H-A-426): kept in the vault as
|
||||
// the module's own, `module/gitea/<account>`, written by the TypeScript bundle's minter through own-put, and read here
|
||||
// through the seat `mesh-vault`'s `get`, sealed to this process's own key (the Go SDK's seal opens it), at start and at
|
||||
// each `secret-changed` that names it. Never a file: the bundle holds the token in memory only, and says nothing of it.
|
||||
// each `secret-changed` that names it. The bundle holds the token in memory only, and says nothing of it.
|
||||
//
|
||||
// Until gitea runs as its own account (H-A-543), the vault refuses the tool runner's account these bundles are called
|
||||
// under, so (H-A-564) when the vault refuses the caller's account, the token is read from the file gitea's TypeScript
|
||||
// bundle keeps it in under its state directory (MESH_GITEA_TOKEN_FILE for the tools' account,
|
||||
// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, each with its scopes line beside it), and Follow says once
|
||||
// at start which source each token came from. The fallback ends with H-A-543's delivery.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
@@ -28,15 +36,41 @@ func VaultName(account string) string { return "module/gitea/" + account }
|
||||
// Ask asks one seat verb and answers its reply (stdio.Ask).
|
||||
type Ask func(address string, args any) (json.RawMessage, error)
|
||||
|
||||
// VaultToken is one account's token as this process holds it, read from the vault.
|
||||
// Refusals are what the vault answers when it refuses the caller's account a module's own secret (mesh-vault's
|
||||
// callerModule and its own-secret judgement): the only answers the token file is read after (H-A-564).
|
||||
var Refusals = []string{"is no module's account", "handed only to an account of"}
|
||||
|
||||
// refused is whether err is the vault refusing the caller's account.
|
||||
func refused(err error) bool {
|
||||
for _, r := range Refusals {
|
||||
if strings.Contains(err.Error(), r) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Sources of a token: the vault, or the file gitea's TypeScript bundle keeps (H-A-564).
|
||||
const (
|
||||
SourceVault = "the vault"
|
||||
SourceFile = "the file gitea keeps"
|
||||
)
|
||||
|
||||
// VaultToken is one account's token as this process holds it, read from the vault, or from File when the vault
|
||||
// refuses the caller's account (H-A-564).
|
||||
type VaultToken struct {
|
||||
Account string
|
||||
ask Ask
|
||||
keys seal.KeyPair
|
||||
// File is the token file gitea's TypeScript bundle keeps for Account, "" when the manifest names none.
|
||||
File string
|
||||
// FileByDefault says File is DefaultStateDir's, the manifest naming none.
|
||||
FileByDefault bool
|
||||
ask Ask
|
||||
keys seal.KeyPair
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
generation int
|
||||
source string
|
||||
}
|
||||
|
||||
// NewVaultToken is an account's token read through ask, sealed to a key made for this process.
|
||||
@@ -48,10 +82,20 @@ func NewVaultToken(account string, ask Ask) (*VaultToken, error) {
|
||||
return &VaultToken{Account: account, ask: ask, keys: keys}, nil
|
||||
}
|
||||
|
||||
// Load reads the account's token from the vault again.
|
||||
// Load reads the account's token from the vault again; from File when the vault refuses the caller's account.
|
||||
func (t *VaultToken) Load() error {
|
||||
raw, err := t.ask(VaultGet, map[string]any{"name": VaultName(t.Account), "public_key": t.keys.PublicKey})
|
||||
if err != nil {
|
||||
if t.File != "" && refused(err) {
|
||||
token, ferr := t.fromFile()
|
||||
if ferr != nil {
|
||||
return fmt.Errorf("the vault did not hand %s (%v), and %w", VaultName(t.Account), err, ferr)
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.token, t.generation, t.source = token, 0, SourceFile
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("the vault did not hand %s: %w", VaultName(t.Account), err)
|
||||
}
|
||||
var got struct {
|
||||
@@ -77,16 +121,45 @@ func (t *VaultToken) Load() error {
|
||||
return fmt.Errorf("the vault's %s is empty", VaultName(t.Account))
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.token, t.generation = token, got.Generation
|
||||
t.token, t.generation, t.source = token, got.Generation, SourceVault
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// fromFile is the token gitea's TypeScript bundle keeps in File, refused unless its scopes line names Account (as the
|
||||
// bundle writes it: "<scopes> for <account>").
|
||||
func (t *VaultToken) fromFile() (string, error) {
|
||||
raw, err := os.ReadFile(t.File)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("the token file gitea keeps for %s cannot be read: %w", t.Account, err)
|
||||
}
|
||||
line, err := os.ReadFile(t.File + ".scopes")
|
||||
if err != nil || !strings.HasSuffix(strings.TrimSpace(string(line)), " for "+t.Account) {
|
||||
return "", fmt.Errorf("the token kept at %s is not %s's (its scopes line does not name it); nothing is sent", t.File, t.Account)
|
||||
}
|
||||
token := strings.TrimSpace(string(raw))
|
||||
if token == "" {
|
||||
return "", fmt.Errorf("the token kept at %s is empty; nothing is sent", t.File)
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// Source is where the token held came from, SourceVault or SourceFile; "" when none is held.
|
||||
func (t *VaultToken) Source() string {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
return t.source
|
||||
}
|
||||
|
||||
// Token is the token held; read from the vault when none is yet (the module mints it first).
|
||||
func (t *VaultToken) Token() (string, error) {
|
||||
t.mu.Lock()
|
||||
token := t.token
|
||||
token, source := t.token, t.source
|
||||
t.mu.Unlock()
|
||||
if source == SourceFile {
|
||||
// gitea's TypeScript bundle mints into its file again on a refusal: the file is read at each call, as before C4.
|
||||
return t.fromFile()
|
||||
}
|
||||
if token != "" {
|
||||
return token, nil
|
||||
}
|
||||
@@ -135,12 +208,46 @@ func TokenOf(account string) (*VaultToken, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t.File, t.FileByDefault = TokenFile(account)
|
||||
processTokens[account] = t
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// DefaultStateDir is gitea's runtime-state directory (the manifest's `${dir:mesh-state}/state`), where its TypeScript
|
||||
// bundle keeps the token files, for a composition that hands the Go bundles no token file (gitea 0.1.316 hands them
|
||||
// no variable naming that directory either; H-A-564).
|
||||
const DefaultStateDir = "/var/lib/mesh/gitea/state"
|
||||
|
||||
// TokenFile is the file the manifest names for account's token as gitea's TypeScript bundle keeps it (H-A-564):
|
||||
// MESH_GITEA_PACKAGES_TOKEN_FILE for the packages account, MESH_GITEA_TOKEN_FILE for the tools' account; when the
|
||||
// variable is not handed, the file in DefaultStateDir, and byDefault says so. "" for any other account.
|
||||
func TokenFile(account string) (file string, byDefault bool) {
|
||||
packages := os.Getenv("MESH_GITEA_PACKAGES_USER")
|
||||
if packages == "" {
|
||||
packages = PackagesAccount
|
||||
}
|
||||
tools := os.Getenv("MESH_GITEA_TOOLS_USER")
|
||||
if tools == "" {
|
||||
tools = ToolsAccount
|
||||
}
|
||||
variable, name := "", ""
|
||||
switch account {
|
||||
case packages:
|
||||
variable, name = "MESH_GITEA_PACKAGES_TOKEN_FILE", "packages-token"
|
||||
case tools:
|
||||
variable, name = "MESH_GITEA_TOKEN_FILE", "token"
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
if f := os.Getenv(variable); f != "" {
|
||||
return f, false
|
||||
}
|
||||
return filepath.Join(DefaultStateDir, name), true
|
||||
}
|
||||
|
||||
// Follow reads each account's token once the runtime serves, and again at each `secret-changed` naming it, saying
|
||||
// through logf what it read (never the token). It returns when the subscription ends.
|
||||
// through logf what it read and, once at start, from which source (never the token). It returns when the
|
||||
// subscription ends.
|
||||
func Follow(logf func(format string, args ...any), accounts ...string) error {
|
||||
var held []*VaultToken
|
||||
for _, a := range accounts {
|
||||
@@ -151,13 +258,7 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
|
||||
held = append(held, t)
|
||||
}
|
||||
<-stdio.Served()
|
||||
for _, t := range held {
|
||||
if err := t.Load(); err != nil {
|
||||
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
|
||||
} else {
|
||||
logf("read %s at generation %d", VaultName(t.Account), t.Generation())
|
||||
}
|
||||
}
|
||||
Start(logf, held...)
|
||||
return stdio.Subscribe(SecretChanged, func(e stdio.Envelope) error {
|
||||
var errs []error
|
||||
for _, t := range held {
|
||||
@@ -171,3 +272,22 @@ func Follow(logf func(format string, args ...any), accounts ...string) error {
|
||||
return errors.Join(errs...)
|
||||
})
|
||||
}
|
||||
|
||||
// Start reads each token once and says, through logf, from which source it came (H-A-564), never the token.
|
||||
func Start(logf func(format string, args ...any), held ...*VaultToken) {
|
||||
for _, t := range held {
|
||||
switch err := t.Load(); {
|
||||
case err != nil:
|
||||
logf("%s is not read at the start (the module mints it): %v", VaultName(t.Account), err)
|
||||
case t.Source() == SourceFile:
|
||||
how := "named by the manifest"
|
||||
if t.FileByDefault {
|
||||
how = "the default path, the manifest naming none"
|
||||
}
|
||||
logf("the vault refuses %s to this process's account, so %s's token is read from %s, %s (%s; H-A-564)",
|
||||
VaultName(t.Account), t.Account, SourceFile, t.File, how)
|
||||
default:
|
||||
logf("read %s at generation %d from %s", VaultName(t.Account), t.Generation(), SourceVault)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
package forgehttp
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/seal"
|
||||
)
|
||||
|
||||
// H-A-564: until gitea runs as its own account, a Go bundle the vault refuses reads the token gitea's TypeScript
|
||||
// bundle keeps in its state directory, and says once at start which source it used; any other refusal reads no file.
|
||||
func TestATokenComesFromTheVaultOrWhenTheVaultRefusesTheCallersAccountFromTheFileGiteaKeeps(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
keep := func(name, token, scopes string) string {
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, []byte(token+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if scopes != "" {
|
||||
if err := os.WriteFile(p+".scopes", []byte(scopes+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
tools := keep("token", "file-tools", "read:package,read:user,write:issue,write:repository for mesh-tools")
|
||||
packages := keep("packages-token", "file-packages", "write:package for mesh-packages")
|
||||
admins := keep("admins-token", "file-admin", "write:admin")
|
||||
vaultHolds := func(token string) Ask {
|
||||
return func(address string, args any) (json.RawMessage, error) {
|
||||
a := args.(map[string]any)
|
||||
value, _ := json.Marshal(map[string]any{"token": token})
|
||||
box, err := seal.Seal(string(value), a["public_key"].(string))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.Marshal(map[string]any{"generation": 3, "sealed": box})
|
||||
}
|
||||
}
|
||||
vaultSays := func(said string) Ask {
|
||||
return func(string, any) (json.RawMessage, error) { return nil, errors.New(said) }
|
||||
}
|
||||
notModule := vaultSays("novox.node-tools is no module's account (<machine>.<module>), so it has no own secret here")
|
||||
for _, c := range []struct {
|
||||
name, account, file string
|
||||
ask Ask
|
||||
token, source, err string
|
||||
}{
|
||||
{"the vault hands it", "mesh-tools", tools, vaultHolds("vault-tools"), "vault-tools", SourceVault, ""},
|
||||
{"the vault refuses the tool runner: the tools' file", "mesh-tools", tools, notModule, "file-tools", SourceFile, ""},
|
||||
{"the vault refuses the tool runner: the packages file", "mesh-packages", packages, notModule, "file-packages", SourceFile, ""},
|
||||
{"another module's account: the file", "mesh-tools", tools,
|
||||
vaultSays("module/gitea/mesh-tools is gitea's own secret, handed only to an account of gitea"), "file-tools", SourceFile, ""},
|
||||
{"the vault holds none: no file is read", "mesh-tools", tools, vaultSays("the vault holds no secret named module/gitea/mesh-tools"), "", "", "holds no secret"},
|
||||
{"no file named: the refusal stands", "mesh-tools", "", notModule, "", "", "no module's account"},
|
||||
{"a file whose scopes line names another account is not sent", "mesh-tools", admins, notModule, "", "", "is not mesh-tools's"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
v, err := NewVaultToken(c.account, c.ask)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
v.File = c.file
|
||||
var said []string
|
||||
Start(func(f string, a ...any) { said = append(said, fmt.Sprintf(f, a...)) }, v)
|
||||
got, err := v.Token()
|
||||
if c.err != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), c.err) {
|
||||
t.Fatalf("token %q, error %v; want an error saying %q", got, err, c.err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != c.token || v.Source() != c.source {
|
||||
t.Fatalf("token %q from %q (%v); want %q from %q", got, v.Source(), err, c.token, c.source)
|
||||
}
|
||||
if len(said) != 1 || !strings.Contains(said[0], c.source) || strings.Contains(said[0], c.token) {
|
||||
t.Fatalf("said %q: one line naming %q, never the token", said, c.source)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A token gitea mints into its file again is the one sent next.
|
||||
v, _ := NewVaultToken("mesh-tools", notModule)
|
||||
v.File = tools
|
||||
Start(func(string, ...any) {}, v)
|
||||
keep("token", "file-tools-2", "read:package for mesh-tools")
|
||||
if got, _ := v.Token(); got != "file-tools-2" {
|
||||
t.Fatalf("after gitea minted again, %q is sent", got)
|
||||
}
|
||||
}
|
||||
|
||||
// H-A-564: the manifest's file for each account wins; without it, the file in gitea's runtime-state directory, said
|
||||
// as the default.
|
||||
func TestTheTokenFileOfAnAccountIsTheOneTheManifestNamesForItElseTheDefault(t *testing.T) {
|
||||
type file struct {
|
||||
path string
|
||||
byDefault bool
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
tools, packs string
|
||||
want map[string]file
|
||||
}{
|
||||
{"named by the manifest", "/s/token", "/s/packages-token", map[string]file{
|
||||
"mesh-tools": {"/s/token", false}, "mesh-packages": {"/s/packages-token", false}, "other": {"", false}}},
|
||||
{"named by none: the default", "", "", map[string]file{
|
||||
"mesh-tools": {"/var/lib/mesh/gitea/state/token", true},
|
||||
"mesh-packages": {"/var/lib/mesh/gitea/state/packages-token", true}, "other": {"", false}}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
t.Setenv("MESH_GITEA_TOKEN_FILE", c.tools)
|
||||
t.Setenv("MESH_GITEA_PACKAGES_TOKEN_FILE", c.packs)
|
||||
for account, want := range c.want {
|
||||
if p, d := TokenFile(account); (file{p, d}) != want {
|
||||
t.Errorf("TokenFile(%s) = %q, %v; want %q, %v", account, p, d, want.path, want.byDefault)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// The start line says the default as such.
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "token")
|
||||
_ = os.WriteFile(p, []byte("t\n"), 0o600)
|
||||
_ = os.WriteFile(p+".scopes", []byte("read:user for mesh-tools\n"), 0o600)
|
||||
v, _ := NewVaultToken("mesh-tools", func(string, any) (json.RawMessage, error) {
|
||||
return nil, errors.New("novox.node-tools is no module's account")
|
||||
})
|
||||
v.File, v.FileByDefault = p, true
|
||||
var said string
|
||||
Start(func(f string, a ...any) { said = fmt.Sprintf(f, a...) }, v)
|
||||
if !strings.Contains(said, "the default path") {
|
||||
t.Fatalf("said %q, not that the file is the default", said)
|
||||
}
|
||||
}
|
||||
@@ -544,7 +544,9 @@
|
||||
"env": {
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
||||
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
||||
"MESH_GITEA_PACKAGES_USER": "mesh-packages",
|
||||
"MESH_GITEA_PACKAGES_TOKEN_FILE": "${dir:runtime-state}/packages-token",
|
||||
"MESH_NPM_OWNER": "novox"
|
||||
}
|
||||
},
|
||||
@@ -561,6 +563,7 @@
|
||||
"env": {
|
||||
"MESH_GITEA_URL": "http://127.0.0.1:${port:3000}",
|
||||
"MESH_GITEA_TOOLS_USER": "mesh-tools",
|
||||
"MESH_GITEA_TOKEN_FILE": "${dir:runtime-state}/token",
|
||||
"MESH_GITEA_PATCH_DIR": "${dir:forge-patches}"
|
||||
}
|
||||
},
|
||||
|
||||
@@ -374,8 +374,15 @@ test("the manifest hands the tools their account, and the Go forge bundle holds
|
||||
const packages = manifest.build.artifacts.find((a: any) => a.name === "package-registry");
|
||||
assert.equal(packages.env.MESH_GITEA_PACKAGES_USER, PACKAGES_ACCOUNT);
|
||||
assert.equal(packages.env.MESH_GITEA_ADMIN_PASSWORD_FILE, undefined);
|
||||
// H-A-564: until gitea runs as its own account, the Go bundles are handed the token files the TypeScript bundle keeps
|
||||
// under its state directory, read when the vault refuses the caller's account; no other artifact is.
|
||||
const files: Record<string, [string | undefined, string | undefined]> = {
|
||||
forge: ["${dir:runtime-state}/token", undefined],
|
||||
"package-registry": ["${dir:runtime-state}/token", "${dir:runtime-state}/packages-token"],
|
||||
};
|
||||
for (const a of manifest.build.artifacts) {
|
||||
assert.equal(a.env?.MESH_GITEA_TOKEN_FILE ?? a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE, undefined, `${a.name} is handed a token file`);
|
||||
assert.deepEqual([a.env?.MESH_GITEA_TOKEN_FILE, a.env?.MESH_GITEA_PACKAGES_TOKEN_FILE], files[a.name] ?? [undefined, undefined],
|
||||
`${a.name}'s token files`);
|
||||
}
|
||||
assert.ok(manifest.invokes.includes("seat:mesh-vault.own-put") && manifest.invokes.includes("seat:mesh-vault.get"), manifest.invokes.join(","));
|
||||
assert.ok(manifest.consumes.includes("mesh-vault.secret-changed"), "the Go bundles hear the vault's changes");
|
||||
|
||||
@@ -1,64 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
|
||||
// every desktop module that carries it.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Moved bool `json:"moved"`
|
||||
Items []item `json:"items"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Claims []claim `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Tools []string `json:"tools"`
|
||||
Environment *environment `json:"environment"`
|
||||
Shell []shellCode `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
type claim struct {
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
Serves []string `json:"serves"`
|
||||
}
|
||||
|
||||
type environment struct {
|
||||
Variables map[string]string `json:"variables"`
|
||||
Path []map[string]any `json:"path"`
|
||||
}
|
||||
|
||||
type shellCode struct {
|
||||
For string `json:"for"`
|
||||
Slot string `json:"slot"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
|
||||
type item struct {
|
||||
Collection string `json:"collection"`
|
||||
Name string `json:"name"`
|
||||
Attributes map[string]string `json:"attributes"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
|
||||
// the collections shell:<file>:<slot>, in the order they are declared.
|
||||
func (m manifest) shell(t *testing.T) []shellCode {
|
||||
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
|
||||
t.Helper()
|
||||
var out []shellCode
|
||||
var out []catalogue.ShellCode
|
||||
for _, it := range m.Items {
|
||||
parts := strings.Split(it.Collection, ":")
|
||||
if len(parts) != 3 || parts[0] != "shell" {
|
||||
@@ -68,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
|
||||
func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
|
||||
t.Helper()
|
||||
var env *environment
|
||||
var env *catalogue.Environment
|
||||
for _, it := range m.Items {
|
||||
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
|
||||
continue
|
||||
@@ -86,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env == nil {
|
||||
env = &environment{Variables: map[string]string{}}
|
||||
env = &catalogue.Environment{Variables: map[string]string{}}
|
||||
}
|
||||
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
m.Environment = m.environmentOf(t)
|
||||
return m
|
||||
}
|
||||
|
||||
func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == id {
|
||||
@@ -120,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m manifest) packages() (present, absent []string) {
|
||||
func packages(m catalogue.Manifest) (present, absent []string) {
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "package" {
|
||||
if r["absent"] == true {
|
||||
@@ -136,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
|
||||
// fromTemplate checks that a file resource takes its text from its template file in the module's
|
||||
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
|
||||
// template is there. The readable file in the repository is the one place the machine's text is written.
|
||||
func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
|
||||
t.Helper()
|
||||
r := m.resource(t, id)
|
||||
r := resource(t, m, id)
|
||||
if r["type"] != "file" {
|
||||
t.Fatalf("%s is a %v, not a file", id, r["type"])
|
||||
}
|
||||
@@ -158,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
|
||||
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
|
||||
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
|
||||
func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if _, inline := r["content"]; inline {
|
||||
@@ -167,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
packs := 0
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "archive" && a["from"] == "files" {
|
||||
if a.Kind == "archive" && a.From == "files" {
|
||||
packs++
|
||||
if a["name"] != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a["name"])
|
||||
if a.Name != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
|
||||
// text is the text a file resource places on the machine: its template file's.
|
||||
func (m manifest) text(t *testing.T, id string) string {
|
||||
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
|
||||
t.Helper()
|
||||
name, _ := m.resource(t, id)["template"].(string)
|
||||
name, _ := resource(t, m, id)["template"].(string)
|
||||
if name == "" {
|
||||
t.Fatalf("resource %s names no template", id)
|
||||
}
|
||||
@@ -195,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
|
||||
|
||||
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
|
||||
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
|
||||
func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
own, seat := map[string]bool{}, map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
@@ -237,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
t.Errorf("the bundle serves %s, which no claim promises", name)
|
||||
}
|
||||
}
|
||||
var bundle map[string]any
|
||||
var bundle *catalogue.Artifact
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "bundle" {
|
||||
bundle = a
|
||||
if a.Kind == "bundle" {
|
||||
bundle = &a
|
||||
}
|
||||
}
|
||||
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
|
||||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
|
||||
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
|
||||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", bundle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// gnome-keyring's shape (novox/hq ADR 0208, ADR 0102): it claims node-secret-service, writes its PAM
|
||||
@@ -11,31 +15,47 @@ import (
|
||||
// of its own: PAM and D-Bus do.
|
||||
|
||||
func TestItClaimsTheSecretServiceSeat(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if m.Module != "gnome-keyring" || m.Seats != nil || m.Requires != nil {
|
||||
t.Fatalf("module %q, seats %v, requires %v", m.Module, m.Seats, m.Requires)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Claims, []claim{{Name: "node-secret-service", Scope: "node"}}) {
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if m.Module != "gnome-keyring" || m.DefinesSeats != nil || m.Requires != nil {
|
||||
t.Fatalf("module %q, seats %v, requires %v", m.Module, m.DefinesSeats, m.Requires)
|
||||
}
|
||||
if !reflect.DeepEqual(m.Claims, []catalogue.Claim{{Name: "node-secret-service", Scope: "node"}}) {
|
||||
t.Fatalf("claims: %+v", m.Claims)
|
||||
}
|
||||
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"gnome-keyring", "libsecret", "seahorse"}) || absent != nil {
|
||||
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"gnome-keyring", "libsecret", "seahorse"}) || absent != nil {
|
||||
t.Fatalf("packages: %v, absent %v", present, absent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThePAMLinesAreBlocksWrittenIntoTheStacks(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
for id, want := range map[string]struct{ path, source string }{
|
||||
"pam-login": {"/etc/pam.d/login", "files/pam/login"},
|
||||
"pam-passwd": {"/etc/pam.d/passwd", "files/pam/passwd"},
|
||||
} {
|
||||
m.fromTemplate(t, id, want.source)
|
||||
r := m.resource(t, id)
|
||||
fromTemplate(t, m, id, want.source)
|
||||
r := resource(t, m, id)
|
||||
if r["path"] != want.path || r["into"] != "block" || r["at"] != "end" || r["owner"] != nil {
|
||||
t.Errorf("%s: %v", id, r)
|
||||
}
|
||||
}
|
||||
login := m.text(t, "pam-login")
|
||||
login := templateText(t, m, "pam-login")
|
||||
if !strings.Contains(login, "\nauth optional pam_gnome_keyring.so\n") ||
|
||||
!strings.Contains(login, "\nsession optional pam_gnome_keyring.so auto_start\n") {
|
||||
t.Fatalf("%s", login)
|
||||
@@ -43,27 +63,52 @@ func TestThePAMLinesAreBlocksWrittenIntoTheStacks(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestItStartsNoDaemonAndOnlyNamesTheAgentsSocket(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "first" {
|
||||
t.Fatalf("%+v", m.shell(t))
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code := m.shell(t)[0].Code
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "first" {
|
||||
t.Fatalf("%+v", shell(t, m))
|
||||
}
|
||||
code := shell(t, m)[0].Code
|
||||
if strings.Contains(code, "gnome-keyring-daemon") || strings.Contains(code, "--unlock") ||
|
||||
!strings.Contains(code, `SSH_AUTH_SOCK="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/gcr/ssh"`) {
|
||||
t.Fatalf("%q", code)
|
||||
}
|
||||
if m.Environment != nil {
|
||||
if environmentOf(t, m) != nil {
|
||||
t.Fatal("SSH_AUTH_SOCK needs the runtime directory, which ADR 0203 forbids in a value; it is not an environment contribution yet")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
checkTheToolsAgree(t, m)
|
||||
checkNoSecretsOrInstallationNames(t)
|
||||
}
|
||||
|
||||
// No file resource carries its text inline (novox/hq ADR 0349 §2).
|
||||
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
readManifest(t).everyFileIsATemplate(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
everyFileIsATemplate(t, m)
|
||||
}
|
||||
|
||||
+30
-1
@@ -5,7 +5,8 @@ The window manager as a module (novox/hq ADR 0208, research 026, to-be 42 phase
|
||||
- **Claims `node-display-session`** and serves its verbs `reload`, `workspaces` and `windows`.
|
||||
- **Requires `x11-display`**, which only `xorg` on the same machine provides.
|
||||
- **Packages:** `i3-wm`, and `dex`, which the configuration has always run for XDG autostart. `dex`
|
||||
was missing on the desktop, so its autostart entries never started there.
|
||||
was missing on the desktop, so its autostart entries never started there. `xdg-utils` (ADR 0303 §2),
|
||||
for `open`'s `xdg-mime` and `xdg-open`.
|
||||
- **Environment** (ADR 0203): `XDG_CURRENT_DESKTOP=i3` and `XDG_SESSION_DESKTOP=i3`. They reach
|
||||
shells, the session (through `xorg`'s block) and the user manager (`environment.d`). The portal
|
||||
keys off the first.
|
||||
@@ -49,6 +50,7 @@ own business.
|
||||
| `node-display-session.reload` | a | checks, then reloads, keeping windows. Refused with the errors when the check fails; `force` reloads anyway |
|
||||
| `node-display-session.workspaces` | r | number, name, output, visible, focused, urgent |
|
||||
| `node-display-session.windows` | r | container id, X id, class, instance, role, title, workspace, output, focused, urgent, floating, fullscreen, scratchpad, marks; narrowed to one workspace |
|
||||
| `node-display-session.open` | a | opens an http or https address in the session's default browser, for any caller over the bus |
|
||||
| `i3_focus` | d | a window by criteria, or a workspace |
|
||||
| `i3_move` | d | windows to a workspace or output; a workspace to an output |
|
||||
| `i3_layout_save` | d | a workspace's arrangement as a named layout of placeholders (class, instance, role), in `~/.local/state/mesh/i3/layouts/` |
|
||||
@@ -65,6 +67,33 @@ value a caller gives is quoted before it reaches an i3 command. With no i3 runni
|
||||
`{"error": "no-graphical-session", …}`. The bundle's binary is `i3-tools`, so nothing that looks for
|
||||
`i3` by name finds it.
|
||||
|
||||
## `open` (novox/hq design 08 sign-in-page §3, §29, §30, §31; issue 935)
|
||||
|
||||
Opens an address in the session's default browser, for any caller over the bus — the sign-in
|
||||
reaction (`networkmanager`'s watcher) never calls it, so this is for every other caller. It does not
|
||||
go through i3's IPC `exec`, which hands a shell a command line; instead it asks the account's own
|
||||
program chooser (`xdg-mime query default x-scheme-handler/<scheme>`) and starts the program through
|
||||
the account's service manager (`systemd-run --user --collect --quiet --wait -- xdg-open <address>`),
|
||||
the address as one argument, never a shell. The run is bound to 10 s: within it, success answers
|
||||
`opened` and a failure is refused naming the opener's status; still running at the bound, the page
|
||||
may still be opening, so the run is left to go on and the answer says `opening`. `program` and
|
||||
`command` (the desktop entry and the first word of its `Exec` line) are given only once the opener
|
||||
started.
|
||||
|
||||
**Refused**, naming the reason: a scheme other than `http` or `https` (named), no scheme (a file
|
||||
path), no host, an address over 2048 bytes once encoded, no graphical session running, no default
|
||||
program for the scheme, the opener ending with a failure (its status named).
|
||||
|
||||
**The encoding** (RFC 3986): letters, digits, `-` `.` `_` `~` and the separators `:` `/` `?` `#` `[`
|
||||
`]` `@` `&` `=` `+` `%` are kept as they are; every other character — a space, a quote, `;`, `$(`,
|
||||
a comma among them — is percent-encoded, as the bytes of its UTF-8 form. Nothing is refused for a
|
||||
character, and no shell ever reads the address.
|
||||
|
||||
**Every call that is acted on is written to the log of acts done by hand**
|
||||
(`seat:mesh-hand-acts.hand-act`), with its caller and why; a call refused before the opener ran
|
||||
writes no act. It hears nothing of the uplink and reads no kept event at its own start: `i3` consumes
|
||||
no `node-uplink` event (ADR 0689 §3).
|
||||
|
||||
## What it improves over today's configuration
|
||||
|
||||
Both workstations ran the same configuration. These changes are against it:
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
"i3/internal/desktop"
|
||||
@@ -53,7 +54,8 @@ func machine() *i3 {
|
||||
if state == "" {
|
||||
state = filepath.Join(home, ".local", "state")
|
||||
}
|
||||
t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts")}
|
||||
t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"),
|
||||
handAct: liveHandAct, opener: openerRun}
|
||||
t.socket = func() (string, error) {
|
||||
runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid()))
|
||||
i3sock := ""
|
||||
@@ -83,6 +85,16 @@ func tools(t *i3) []stdio.Tool {
|
||||
Input: desktop.Schema(map[string]any{"force": desktop.Flag("reload even when the check finds errors")}),
|
||||
Run: call(t.reload),
|
||||
},
|
||||
{
|
||||
Name: nodedisplaysession.Seat + "." + nodedisplaysession.VerbOpen,
|
||||
Description: "Open an http or https address in the person's default browser, for any caller over the bus " +
|
||||
"(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " +
|
||||
"too long once encoded, no graphical session or no default program for the scheme; the opener's " +
|
||||
"failure is refused naming its status. Answers once the opener has started: opened within its bound, " +
|
||||
"or opening when it still runs. Every call is an act, recorded in the log of acts done by hand.",
|
||||
Input: desktop.Schema(map[string]any{"address": desktop.Str("the http or https address to open")}, "address"),
|
||||
Run: call(t.open),
|
||||
},
|
||||
{
|
||||
Name: "node-display-session.workspaces",
|
||||
Description: "The session's workspaces: number, name, output, and whether each is visible, focused or urgent.",
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
type manifest struct {
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Invokes []string `json:"invokes"`
|
||||
Claims []struct {
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
@@ -82,7 +83,7 @@ func resource(t *testing.T, m manifest, id string) map[string]any {
|
||||
|
||||
func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows" {
|
||||
if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows,open" {
|
||||
t.Fatalf("%+v", m.Claims)
|
||||
}
|
||||
if strings.Join(m.Requires, ",") != "x11-display" {
|
||||
@@ -97,7 +98,7 @@ func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) {
|
||||
t.Errorf("the seat's %s is not served", v)
|
||||
}
|
||||
}
|
||||
if len(served) != len(m.Tools)+3 {
|
||||
if len(served) != len(m.Tools)+4 {
|
||||
t.Fatalf("served %d, listed %d", len(served), len(m.Tools))
|
||||
}
|
||||
for _, n := range m.Tools {
|
||||
@@ -175,6 +176,23 @@ func TestTheConfigurationIsTheModulesFileImprovedAndEndsWithTheDropIns(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
// open is an act (design 08 sign-in-page §29, DQ-7): the manifest invokes the hand-act log, the
|
||||
// package the opener needs is present (ADR 0303 §2), and open is among node-display-session's
|
||||
// served verbs.
|
||||
func TestOpenIsAnActWithItsPackageAndInvoke(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
if strings.Join(m.Invokes, ",") != "seat:mesh-hand-acts.hand-act" {
|
||||
t.Fatalf("invokes: %v", m.Invokes)
|
||||
}
|
||||
served := map[string]bool{}
|
||||
for _, v := range m.Claims[0].Serves {
|
||||
served[v] = true
|
||||
}
|
||||
if !served["open"] {
|
||||
t.Fatal("node-display-session does not serve open")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
r := resource(t, m, "session")
|
||||
@@ -194,7 +212,7 @@ func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) {
|
||||
pkgs[x["package"].(string)] = true
|
||||
}
|
||||
}
|
||||
if !pkgs["i3-wm"] || !pkgs["dex"] || len(pkgs) != 2 {
|
||||
if !pkgs["i3-wm"] || !pkgs["dex"] || !pkgs["xdg-utils"] || len(pkgs) != 3 {
|
||||
t.Fatalf("%v", pkgs)
|
||||
}
|
||||
a := m.Build.Artifacts[0]
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https
|
||||
// address in the person's default browser, outside i3's own IPC (which hands a shell a command
|
||||
// line); this verb takes the address as one argument, through the account's own program chooser
|
||||
// (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act
|
||||
// (ADR 0565 §10): every call, refused or not, is written to the log of acts done by hand (lead
|
||||
// answer note (b), DQ-7: "each call").
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
|
||||
"i3/internal/desktop"
|
||||
)
|
||||
|
||||
// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a
|
||||
// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener
|
||||
// is left to go on and the answer says opening. A test shortens it with the i3's openBound field.
|
||||
const defaultOpenTimeout = 10 * time.Second
|
||||
|
||||
// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3).
|
||||
const openMaxAddress = 2048
|
||||
|
||||
// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter,
|
||||
// ended by a colon.
|
||||
var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`)
|
||||
|
||||
// openKept are the characters open's encoding never touches, beside the unreserved ones (letters,
|
||||
// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is
|
||||
// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9).
|
||||
const openKept = "-._~:/?#[]@&=+%"
|
||||
|
||||
// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme
|
||||
// other than http or https, no scheme (a file path), no host.
|
||||
func checkAddressShape(address string) (scheme string, err error) {
|
||||
m := schemePattern.FindStringSubmatch(address)
|
||||
if m == nil {
|
||||
return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address)
|
||||
}
|
||||
scheme = strings.ToLower(m[1])
|
||||
if scheme != "http" && scheme != "https" {
|
||||
return "", fmt.Errorf("a scheme other than http or https: %s", scheme)
|
||||
}
|
||||
afterScheme := address[len(m[0]):]
|
||||
if !strings.HasPrefix(afterScheme, "//") {
|
||||
return "", fmt.Errorf("no host: %s has no // after its scheme", scheme)
|
||||
}
|
||||
rest := afterScheme[2:]
|
||||
end := strings.IndexAny(rest, "/?#")
|
||||
authority := rest
|
||||
if end >= 0 {
|
||||
authority = rest[:end]
|
||||
}
|
||||
if at := strings.LastIndex(authority, "@"); at >= 0 {
|
||||
authority = authority[at+1:]
|
||||
}
|
||||
if authority == "" {
|
||||
return "", fmt.Errorf("no host")
|
||||
}
|
||||
return scheme, nil
|
||||
}
|
||||
|
||||
// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs
|
||||
// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form.
|
||||
// Nothing is refused for a character, and the result is never read by a shell.
|
||||
func encodeAddress(address string) string {
|
||||
var b strings.Builder
|
||||
for i := 0; i < len(address); i++ {
|
||||
c := address[i]
|
||||
switch {
|
||||
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9':
|
||||
b.WriteByte(c)
|
||||
case strings.IndexByte(openKept, c) >= 0:
|
||||
b.WriteByte(c)
|
||||
default:
|
||||
fmt.Fprintf(&b, "%%%02X", c)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason:
|
||||
// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is
|
||||
// none.
|
||||
func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) {
|
||||
res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme)
|
||||
name := strings.TrimSpace(res.Stdout)
|
||||
if !res.OK() || name == "" {
|
||||
return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data
|
||||
// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes
|
||||
// and arguments.
|
||||
func entryCommand(entry string) string {
|
||||
for _, dir := range xdgDataDirs() {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "applications", entry))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
inEntry := false
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
switch {
|
||||
case strings.HasPrefix(line, "["):
|
||||
inEntry = line == "[Desktop Entry]"
|
||||
case inEntry:
|
||||
if exec, ok := strings.CutPrefix(line, "Exec="); ok {
|
||||
if fields := strings.Fields(exec); len(fields) > 0 {
|
||||
return fields[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the
|
||||
// system's (XDG_DATA_DIRS, or its default).
|
||||
func xdgDataDirs() []string {
|
||||
dirs := []string{os.Getenv("XDG_DATA_HOME")}
|
||||
if dirs[0] == "" {
|
||||
dirs[0] = filepath.Join(desktop.Home(), ".local", "share")
|
||||
}
|
||||
extra := os.Getenv("XDG_DATA_DIRS")
|
||||
if extra == "" {
|
||||
extra = "/usr/local/share:/usr/share"
|
||||
}
|
||||
for _, d := range strings.Split(extra, ":") {
|
||||
if d != "" {
|
||||
dirs = append(dirs, d)
|
||||
}
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
// openerRun runs the opener (systemd-run --wait -- xdg-open ...) through runWithoutKilling: it
|
||||
// stops waiting at its bound without killing what it started (design 08 sign-in-page §18, §29;
|
||||
// DMC-8, lead answer C-5), unlike internal/desktop's Exec (run.go), which kills the command's
|
||||
// process group at its deadline. A page still opening at the bound is left to open: the browser
|
||||
// outlives this call either way, since it runs under the account's own service manager
|
||||
// (systemd-run --user), not as this process's child.
|
||||
func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd.Env = env
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
if stdin != nil {
|
||||
cmd.Stdin = bytes.NewReader(stdin)
|
||||
}
|
||||
return runWithoutKilling(ctx, cmd)
|
||||
}
|
||||
|
||||
// runWithoutKilling starts cmd and waits for it, but stops waiting at ctx's deadline without
|
||||
// sending cmd any signal (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5): left to go on,
|
||||
// never torn down by the bound that only governs how long this call waits. A test calls this
|
||||
// directly, with a command of its own whose Stdin and ExtraFiles it controls, to prove the started
|
||||
// process is never killed, without a real sleep on either side.
|
||||
func runWithoutKilling(ctx context.Context, cmd *exec.Cmd) desktop.Result {
|
||||
res := desktop.Result{Command: append([]string{cmd.Path}, cmd.Args[1:]...)}
|
||||
var out, errb bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = &out, &errb
|
||||
if err := cmd.Start(); err != nil {
|
||||
res.Code = 127
|
||||
res.Stderr = err.Error()
|
||||
return res
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
select {
|
||||
case err := <-done:
|
||||
res.Stdout, res.Stderr = out.String(), errb.String()
|
||||
var exit *exec.ExitError
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.As(err, &exit):
|
||||
res.Code = exit.ExitCode()
|
||||
if res.Code < 0 {
|
||||
res.Code = 128
|
||||
}
|
||||
default:
|
||||
res.Code = 1
|
||||
if res.Stderr == "" {
|
||||
res.Stderr = err.Error()
|
||||
}
|
||||
}
|
||||
case <-ctx.Done():
|
||||
// Left to go on (DMC-8, C-5): no signal is sent, so the process it started keeps running;
|
||||
// the goroutine above still reads its exit, harmlessly, once it does.
|
||||
res.TimedOut = true
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's
|
||||
// default browser for the scheme, and answers once the opener has started.
|
||||
func (t *i3) open(ctx context.Context, a desktop.Args) (ret any, err error) {
|
||||
caller := stdio.CallerOf(map[string]any(a))
|
||||
why := fmt.Sprintf("asked by %s", caller)
|
||||
var address, encoded, program, started string
|
||||
|
||||
defer func() {
|
||||
switch {
|
||||
case err != nil:
|
||||
t.journalOpen(address, "refused", err.Error())
|
||||
t.recordHandAct(fmt.Sprintf("refused %s: %s", address, err), why)
|
||||
default:
|
||||
t.journalOpen(address, started, program)
|
||||
t.recordHandAct(fmt.Sprintf("%s %s in %s", started, encoded, program), why)
|
||||
}
|
||||
}()
|
||||
|
||||
address, err = a.Text("address")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scheme, err := checkAddressShape(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoded = encodeAddress(address)
|
||||
if len(encoded) > openMaxAddress {
|
||||
err = fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s, err := t.d.Find()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
env := s.Env(t.d.Base)
|
||||
|
||||
program, err = defaultProgram(ctx, t.d, env, scheme)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bound := t.openBound
|
||||
if bound == 0 {
|
||||
bound = defaultOpenTimeout
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, bound)
|
||||
defer cancel()
|
||||
runner := t.opener
|
||||
if runner == nil {
|
||||
runner = openerRun
|
||||
}
|
||||
res := runner(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded)
|
||||
|
||||
if !res.OK() && !res.TimedOut {
|
||||
err = fmt.Errorf("the opener failed: %s", res.Err().Error())
|
||||
return nil, err
|
||||
}
|
||||
|
||||
started = nodedisplaysession.OpenAnswerStartedOpened
|
||||
if res.TimedOut {
|
||||
started = nodedisplaysession.OpenAnswerStartedOpening
|
||||
}
|
||||
command := entryCommand(program)
|
||||
return nodedisplaysession.OpenAnswer{Address: encoded, Program: program, Command: command, Started: started}, nil
|
||||
}
|
||||
|
||||
// journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14):
|
||||
// the address, opened or refused, and the program or the reason.
|
||||
func (t *i3) journalOpen(address, outcome, programOrReason string) {
|
||||
fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason)
|
||||
}
|
||||
|
||||
// recordHandAct writes one call of open to the log of acts done by hand (design 08 sign-in-page
|
||||
// §29; ADR 0565 §10; lead answer note (b)): every call, refused or not, with its caller and why.
|
||||
func (t *i3) recordHandAct(what, why string) {
|
||||
if t.handAct == nil {
|
||||
return
|
||||
}
|
||||
if err := t.handAct(what, why); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err)
|
||||
}
|
||||
}
|
||||
|
||||
// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module
|
||||
// (design 08 sign-in-page §29).
|
||||
func liveHandAct(what, why string) error {
|
||||
_, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"})
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
|
||||
|
||||
"i3/internal/desktop"
|
||||
)
|
||||
|
||||
// runCall records one call the stood-in opener saw, so a test can check the exact argv it was
|
||||
// handed (design 08 sign-in-page §29, R2-9: one argument, no shell).
|
||||
type runCall struct {
|
||||
name string
|
||||
args []string
|
||||
}
|
||||
|
||||
// stubOpener builds an i3 whose session is found (unless find answers an error), whose xdg-mime
|
||||
// query answers xdgMime, and whose opener answers the systemd-run call with opener (nil runs it is
|
||||
// never reached). Every call, to either, is recorded in calls.
|
||||
func stubOpener(t *testing.T, find func() (*desktop.Session, error), xdgMime desktop.Result, opener desktop.Runner) (*i3, *[]runCall) {
|
||||
t.Helper()
|
||||
calls := &[]runCall{}
|
||||
run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
|
||||
*calls = append(*calls, runCall{name, args})
|
||||
if name != "xdg-mime" {
|
||||
t.Fatalf("unexpected command on the session's own run: %s %v", name, args)
|
||||
}
|
||||
return xdgMime
|
||||
}
|
||||
var wrapped desktop.Runner
|
||||
if opener != nil {
|
||||
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
|
||||
*calls = append(*calls, runCall{name, args})
|
||||
return opener(ctx, env, stdin, name, args...)
|
||||
}
|
||||
} else {
|
||||
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
|
||||
t.Fatalf("the opener never runs: %s %v", name, args)
|
||||
return desktop.Result{}
|
||||
}
|
||||
}
|
||||
return &i3{d: desktop.Desk{Find: find, Run: run}, opener: wrapped, openBound: 50 * time.Millisecond}, calls
|
||||
}
|
||||
|
||||
// resultOpener is an opener stub that answers res, blocking on ctx when res.TimedOut (as a real
|
||||
// still-running opener would appear to this call).
|
||||
func resultOpener(res desktop.Result) desktop.Runner {
|
||||
return func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
|
||||
if res.TimedOut {
|
||||
<-ctx.Done()
|
||||
return desktop.Result{TimedOut: true}
|
||||
}
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
func foundSession() (*desktop.Session, error) {
|
||||
return &desktop.Session{}, nil
|
||||
}
|
||||
|
||||
func writeDesktopEntry(t *testing.T, entry, execLine string) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_DATA_HOME", dir)
|
||||
apps := filepath.Join(dir, "applications")
|
||||
if err := os.MkdirAll(apps, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text := "[Desktop Entry]\nType=Application\nName=Browser\nExec=" + execLine + "\n"
|
||||
if err := os.WriteFile(filepath.Join(apps, entry), []byte(text), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-1: every scheme but http and https, and a file path, is refused.
|
||||
func TestOpenRefusesEveryOtherScheme(t *testing.T) {
|
||||
x, calls := stubOpener(t, foundSession, desktop.Result{}, nil)
|
||||
for _, address := range []string{
|
||||
"/etc/passwd", // no scheme: a file path
|
||||
"file:///etc/passwd", // a scheme other than http or https
|
||||
"ftp://example.net/f", // a scheme other than http or https
|
||||
"mailto:a@example.net", // a scheme other than http or https, no //
|
||||
"http://", // no host
|
||||
"https:///path", // no host
|
||||
} {
|
||||
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
|
||||
t.Errorf("%s: not refused", address)
|
||||
}
|
||||
}
|
||||
if len(*calls) != 0 {
|
||||
t.Fatalf("a refused address never reaches xdg-mime or the opener: %v", *calls)
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-1: an address over 2048 bytes once encoded is refused.
|
||||
func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) {
|
||||
x, _ := stubOpener(t, foundSession, desktop.Result{}, nil)
|
||||
address := "https://example.net/" + strings.Repeat("a", 2048)
|
||||
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
|
||||
t.Fatal("not refused")
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-1: with no graphical session it refuses, as its other tools answer.
|
||||
func TestOpenRefusesWithNoGraphicalSession(t *testing.T) {
|
||||
x, _ := stubOpener(t, func() (*desktop.Session, error) {
|
||||
return nil, &desktop.NoSession{Reason: "none"}
|
||||
}, desktop.Result{}, nil)
|
||||
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
|
||||
if !desktop.IsNoSession(err) {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-1: no default program for the scheme is refused.
|
||||
func TestOpenRefusesWithNoDefaultProgram(t *testing.T) {
|
||||
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: ""}, nil)
|
||||
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil {
|
||||
t.Fatal("not refused")
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its
|
||||
// UTF-8 form, and the address reaches the opener as one argument, never a shell command line.
|
||||
func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) {
|
||||
writeDesktopEntry(t, "browser.desktop", "firefox %u")
|
||||
x, calls := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
|
||||
address := `https://example.net/a'b;c d$(e),f"g`
|
||||
got, err := run(t, x, "node-display-session.open", map[string]any{"address": address})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g`
|
||||
answer := got.(nodedisplaysession.OpenAnswer)
|
||||
if answer.Address != want {
|
||||
t.Fatalf("got %q, want %q", answer.Address, want)
|
||||
}
|
||||
var last runCall
|
||||
for _, c := range *calls {
|
||||
if c.name == "systemd-run" {
|
||||
last = c
|
||||
}
|
||||
}
|
||||
if len(last.args) == 0 || last.args[len(last.args)-1] != want {
|
||||
t.Fatalf("the address is not the opener's last, whole argument: %v", last.args)
|
||||
}
|
||||
for _, a := range last.args {
|
||||
if strings.Contains(a, "'") || strings.Contains(a, ";") || strings.Contains(a, " ") {
|
||||
t.Fatalf("an argument still carries a shell character: %q", a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-3: an opener that fails is refused with its status and names no program.
|
||||
func TestOpenRefusesWhenTheOpenerFails(t *testing.T) {
|
||||
writeDesktopEntry(t, "browser.desktop", "firefox %u")
|
||||
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"},
|
||||
resultOpener(desktop.Result{Code: 1, Stderr: "no such unit"}))
|
||||
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
|
||||
if err == nil || !strings.Contains(err.Error(), "no such unit") {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-3: an opener that ends well answers opened with the program.
|
||||
func TestOpenAnswersOpenedWithTheProgram(t *testing.T) {
|
||||
writeDesktopEntry(t, "browser.desktop", "firefox %u")
|
||||
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
|
||||
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer := got.(nodedisplaysession.OpenAnswer)
|
||||
if answer.Started != nodedisplaysession.OpenAnswerStartedOpened || answer.Program != "browser.desktop" || answer.Command != "firefox" {
|
||||
t.Fatalf("%+v", answer)
|
||||
}
|
||||
}
|
||||
|
||||
// 935/I-3: one still running at its bound answers opening, with the program (H-M2: the answer
|
||||
// names the program only once the opener started).
|
||||
func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) {
|
||||
writeDesktopEntry(t, "browser.desktop", "firefox %u")
|
||||
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{TimedOut: true}))
|
||||
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
answer := got.(nodedisplaysession.OpenAnswer)
|
||||
if answer.Started != nodedisplaysession.OpenAnswerStartedOpening || answer.Program != "browser.desktop" {
|
||||
t.Fatalf("%+v", answer)
|
||||
}
|
||||
}
|
||||
|
||||
// C-5: cmd/i3-tools runs the opener with its own run (runWithoutKilling, not internal/desktop's
|
||||
// Exec, which kills a command's process group at its deadline, run.go:82-86): it stops waiting at
|
||||
// its bound without killing what it started. The child blocks reading its stdin, a pipe this test
|
||||
// holds open past the bound and only then closes; once unblocked, the child writes one byte on an
|
||||
// extra file before it exits, its own end, which this test waits on instead of sleeping — a byte
|
||||
// the child could reach only by surviving the bound, never by being killed at it.
|
||||
func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) {
|
||||
stdinR, stdinW, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stdinW.Close()
|
||||
doneR, doneW, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer doneR.Close()
|
||||
|
||||
cmd := exec.Command("sh", "-c", "cat >/dev/null; printf x >&3")
|
||||
cmd.Stdin = stdinR
|
||||
cmd.ExtraFiles = []*os.File{doneW}
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // as openerRun starts it
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
res := runWithoutKilling(ctx, cmd)
|
||||
stdinR.Close()
|
||||
doneW.Close() // this process's own copy: only the child's, closed when it exits, is left
|
||||
if !res.TimedOut {
|
||||
t.Fatalf("expected TimedOut, got %+v", res)
|
||||
}
|
||||
|
||||
// Unblock the child: were it killed at the bound, this would reach nobody.
|
||||
if err := stdinW.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Wait on the child's own end: blocks until the child writes its byte and exits, closing its
|
||||
// copy of doneW: never a timer, never a kill.
|
||||
b := make([]byte, 1)
|
||||
n, _ := doneR.Read(b)
|
||||
if n != 1 || b[0] != 'x' {
|
||||
t.Fatalf("the opener process was killed instead of left to finish: read %d byte(s)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its
|
||||
// caller and why — a successful one and a refused one alike.
|
||||
func TestOpenWritesOneActDoneByHandForEveryCall(t *testing.T) {
|
||||
writeDesktopEntry(t, "browser.desktop", "firefox %u")
|
||||
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
|
||||
var recorded []string
|
||||
x.handAct = func(what, why string) error {
|
||||
recorded = append(recorded, what+"|"+why)
|
||||
return nil
|
||||
}
|
||||
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recorded) != 1 || !strings.Contains(recorded[0], "https://example.net") {
|
||||
t.Fatalf("%v", recorded)
|
||||
}
|
||||
|
||||
recorded = nil
|
||||
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil {
|
||||
t.Fatal("expected a refusal")
|
||||
}
|
||||
if len(recorded) != 1 || !strings.Contains(recorded[0], "refused") || !strings.Contains(recorded[0], "ftp://example.net") {
|
||||
t.Fatalf("a refusal writes an act too (note (b)): %v", recorded)
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,15 @@ type i3 struct {
|
||||
configDir string
|
||||
layouts string
|
||||
watcher *Watcher
|
||||
// handAct writes one call of open to the log of acts done by hand (design 08 sign-in-page §29);
|
||||
// nil in a test that does not check it.
|
||||
handAct func(what, why string) error
|
||||
// openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens
|
||||
// it so a still-running opener is seen without waiting out the real bound.
|
||||
openBound time.Duration
|
||||
// opener runs the opener command: openerRun (design 08 sign-in-page §29; DMC-8, lead answer C-5)
|
||||
// unless a test replaces it to control the opener's outcome directly.
|
||||
opener desktop.Runner
|
||||
}
|
||||
|
||||
func (t *i3) ask(kind uint32, payload string, out any) error {
|
||||
|
||||
+4
-1
@@ -2,7 +2,10 @@ module i3
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
|
||||
require (
|
||||
git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/klauspost/compress v1.20.1 // indirect
|
||||
|
||||
+10
-1
@@ -16,10 +16,14 @@
|
||||
"serves": [
|
||||
"reload",
|
||||
"workspaces",
|
||||
"windows"
|
||||
"windows",
|
||||
"open"
|
||||
]
|
||||
}
|
||||
],
|
||||
"invokes": [
|
||||
"seat:mesh-hand-acts.hand-act"
|
||||
],
|
||||
"tools": [
|
||||
"i3_focus",
|
||||
"i3_move",
|
||||
@@ -68,6 +72,11 @@
|
||||
"type": "package",
|
||||
"package": "dex"
|
||||
},
|
||||
{
|
||||
"id": "package-xdg-utils",
|
||||
"type": "package",
|
||||
"package": "xdg-utils"
|
||||
},
|
||||
{
|
||||
"id": "config-dir",
|
||||
"type": "directory",
|
||||
|
||||
@@ -5,15 +5,25 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The blocks other modules contribute are a collection of text (design 57 L3, novox/hq ADR 0349 clause 13): each
|
||||
// contributor gives its block in i3status-rust's grammar, and the bars place the collection where they want it.
|
||||
|
||||
func TestEachBarPlacesBothPlacesOnce(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
for _, bar := range []string{"bottom", "top"} {
|
||||
content := m.text(t, bar+"-bar")
|
||||
content := templateText(t, m, bar+"-bar")
|
||||
for _, place := range []string{"resources", "status"} {
|
||||
ph := "${collected:contribution:node-bar:block:bar=" + bar + ",place=" + place + "}"
|
||||
if strings.Count(content, ph) != 1 {
|
||||
@@ -21,7 +31,7 @@ func TestEachBarPlacesBothPlacesOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
bottom := m.text(t, "bottom-bar")
|
||||
bottom := templateText(t, m, "bottom-bar")
|
||||
resources := strings.Index(bottom, "place=resources")
|
||||
if !(strings.Index(bottom, `block = "memory"`) < resources && resources < strings.Index(bottom, `block = "docker"`)) ||
|
||||
!(strings.Index(bottom, `block = "sound"`) < strings.Index(bottom, "place=status") &&
|
||||
@@ -31,7 +41,16 @@ func TestEachBarPlacesBothPlacesOnce(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTheMemoryIsWhatProgramsHoldNotTheCache(t *testing.T) {
|
||||
bottom := readManifest(t).text(t, "bottom-bar")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
bottom := templateText(t, m, "bottom-bar")
|
||||
if !strings.Contains(bottom, `format = "$icon $mem_used.eng(w:2) ($mem_used_percents.eng(w:2))"`) ||
|
||||
strings.Contains(bottom, "mem_total_used") {
|
||||
t.Fatal("the memory block counts the cache as used")
|
||||
@@ -39,9 +58,17 @@ func TestTheMemoryIsWhatProgramsHoldNotTheCache(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestABarNamesNoTemplateOfItsOwnForTheBlocksItPlaces(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
for _, id := range []string{"top-bar", "bottom-bar"} {
|
||||
if strings.Contains(m.text(t, id), "${contribution:") {
|
||||
if strings.Contains(templateText(t, m, id), "${contribution:") {
|
||||
t.Errorf("the %s still places a contribution the old way", id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,68 +1,19 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// The module's manifest, read the way the catalogue reads it, for the manifest tests. The same in
|
||||
// every desktop module that carries it.
|
||||
|
||||
type manifest struct {
|
||||
Module string `json:"module"`
|
||||
Version string `json:"version"`
|
||||
Moved bool `json:"moved"`
|
||||
Items []item `json:"items"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
Requires []string `json:"requires"`
|
||||
Claims []claim `json:"claims"`
|
||||
Seats []any `json:"seats"`
|
||||
Tools []string `json:"tools"`
|
||||
Environment *environment `json:"environment"`
|
||||
Shell []shellCode `json:"shell"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
// Lines for other modules' seats (novox/hq ADR 0212): the window manager's, here.
|
||||
Contributions []any `json:"contributions"`
|
||||
Build struct {
|
||||
Artifacts []map[string]any `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
|
||||
type claim struct {
|
||||
Name string `json:"name"`
|
||||
Scope string `json:"scope"`
|
||||
Serves []string `json:"serves"`
|
||||
// How the holder renders each kind its seat receives as data (novox/hq ADR 0255).
|
||||
Renders map[string]string `json:"renders"`
|
||||
}
|
||||
|
||||
type environment struct {
|
||||
Variables map[string]string `json:"variables"`
|
||||
Path []map[string]any `json:"path"`
|
||||
}
|
||||
|
||||
type shellCode struct {
|
||||
For string `json:"for"`
|
||||
Slot string `json:"slot"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// An item of a collection (novox/hq ADR 0349 clause 13): its text is the template file beside the manifest.
|
||||
type item struct {
|
||||
Collection string `json:"collection"`
|
||||
Name string `json:"name"`
|
||||
Attributes map[string]string `json:"attributes"`
|
||||
Template string `json:"template"`
|
||||
}
|
||||
|
||||
// shell is the code the module adds to a shell's or the session's start, read from the templates of its items of
|
||||
// the collections shell:<file>:<slot>, in the order they are declared.
|
||||
func (m manifest) shell(t *testing.T) []shellCode {
|
||||
func shell(t *testing.T, m catalogue.Manifest) []catalogue.ShellCode {
|
||||
t.Helper()
|
||||
var out []shellCode
|
||||
var out []catalogue.ShellCode
|
||||
for _, it := range m.Items {
|
||||
parts := strings.Split(it.Collection, ":")
|
||||
if len(parts) != 3 || parts[0] != "shell" {
|
||||
@@ -72,15 +23,15 @@ func (m manifest) shell(t *testing.T) []shellCode {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out = append(out, shellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
out = append(out, catalogue.ShellCode{For: parts[1], Slot: parts[2], Code: string(text)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// environmentOf is the variables the module sets, read from the templates of its items of the environment.
|
||||
func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
func environmentOf(t *testing.T, m catalogue.Manifest) *catalogue.Environment {
|
||||
t.Helper()
|
||||
var env *environment
|
||||
var env *catalogue.Environment
|
||||
for _, it := range m.Items {
|
||||
if it.Collection != "environment" || it.Attributes["kind"] != "variable" {
|
||||
continue
|
||||
@@ -90,30 +41,14 @@ func (m manifest) environmentOf(t *testing.T) *environment {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if env == nil {
|
||||
env = &environment{Variables: map[string]string{}}
|
||||
env = &catalogue.Environment{Variables: map[string]string{}}
|
||||
}
|
||||
env.Variables[it.Attributes["name"]] = strings.TrimSuffix(string(text), "\n")
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func readManifest(t *testing.T) manifest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dec := json.NewDecoder(strings.NewReader(string(raw)))
|
||||
dec.DisallowUnknownFields()
|
||||
var m manifest
|
||||
if err := dec.Decode(&m); err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
m.Environment = m.environmentOf(t)
|
||||
return m
|
||||
}
|
||||
|
||||
func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
func resource(t *testing.T, m catalogue.Manifest, id string) map[string]any {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if r["id"] == id {
|
||||
@@ -124,7 +59,7 @@ func (m manifest) resource(t *testing.T, id string) map[string]any {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m manifest) packages() (present, absent []string) {
|
||||
func packages(m catalogue.Manifest) (present, absent []string) {
|
||||
for _, r := range m.Resources {
|
||||
if r["type"] == "package" {
|
||||
if r["absent"] == true {
|
||||
@@ -140,9 +75,9 @@ func (m manifest) packages() (present, absent []string) {
|
||||
// fromTemplate checks that a file resource takes its text from its template file in the module's
|
||||
// repository (novox/hq ADR 0349 §2): it names the template, carries no text of its own beside it, and the
|
||||
// template is there. The readable file in the repository is the one place the machine's text is written.
|
||||
func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
func fromTemplate(t *testing.T, m catalogue.Manifest, id, template string) {
|
||||
t.Helper()
|
||||
r := m.resource(t, id)
|
||||
r := resource(t, m, id)
|
||||
if r["type"] != "file" {
|
||||
t.Fatalf("%s is a %v, not a file", id, r["type"])
|
||||
}
|
||||
@@ -162,7 +97,7 @@ func (m manifest) fromTemplate(t *testing.T, id, template string) {
|
||||
|
||||
// everyFileIsATemplate checks that no file resource carries its text inline, and that the build packs
|
||||
// files/ into the one archive the controller reads the templates back from (novox/hq ADR 0349 §2).
|
||||
func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
func everyFileIsATemplate(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
for _, r := range m.Resources {
|
||||
if _, inline := r["content"]; inline {
|
||||
@@ -171,10 +106,10 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
packs := 0
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "archive" && a["from"] == "files" {
|
||||
if a.Kind == "archive" && a.From == "files" {
|
||||
packs++
|
||||
if a["name"] != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a["name"])
|
||||
if a.Name != "files" {
|
||||
t.Errorf("the templates archive is named %v, not files", a.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,9 +119,9 @@ func (m manifest) everyFileIsATemplate(t *testing.T) {
|
||||
}
|
||||
|
||||
// text is the text a file resource places on the machine: its template file's.
|
||||
func (m manifest) text(t *testing.T, id string) string {
|
||||
func templateText(t *testing.T, m catalogue.Manifest, id string) string {
|
||||
t.Helper()
|
||||
name, _ := m.resource(t, id)["template"].(string)
|
||||
name, _ := resource(t, m, id)["template"].(string)
|
||||
if name == "" {
|
||||
t.Fatalf("resource %s names no template", id)
|
||||
}
|
||||
@@ -199,7 +134,7 @@ func (m manifest) text(t *testing.T, id string) string {
|
||||
|
||||
// checkTheToolsAgree checks that the manifest lists the module's own tools exactly, that the bundle
|
||||
// serves each seat verb the claims promise as <seat>.<verb>, and that the Go bundle is declared.
|
||||
func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
func checkTheToolsAgree(t *testing.T, m catalogue.Manifest) {
|
||||
t.Helper()
|
||||
own, seat := map[string]bool{}, map[string]bool{}
|
||||
for _, tool := range tools() {
|
||||
@@ -241,14 +176,14 @@ func checkTheToolsAgree(t *testing.T, m manifest) {
|
||||
t.Errorf("the bundle serves %s, which no claim promises", name)
|
||||
}
|
||||
}
|
||||
var bundle map[string]any
|
||||
var bundle *catalogue.Artifact
|
||||
for _, a := range m.Build.Artifacts {
|
||||
if a["kind"] == "bundle" {
|
||||
bundle = a
|
||||
if a.Kind == "bundle" {
|
||||
bundle = &a
|
||||
}
|
||||
}
|
||||
if bundle == nil || bundle["language"] != "go" || bundle["system"] != "arch" ||
|
||||
bundle["from"] != "cmd/"+m.Module+"-tools" || bundle["binary"] != m.Module+"-tools" {
|
||||
if bundle == nil || bundle.Language != "go" || bundle.System != "arch" ||
|
||||
bundle.From != "cmd/"+m.Module+"-tools" || bundle.Binary != m.Module+"-tools" {
|
||||
t.Errorf("the Go tools bundle: %v", bundle)
|
||||
}
|
||||
}
|
||||
@@ -273,7 +208,7 @@ const displaySession = "contribution:node-display-session:config"
|
||||
|
||||
// i3Lines is what the module contributes to the window manager: the text of its item of the collection
|
||||
// contribution:node-display-session:config (design 57 L3, issue 848).
|
||||
func (m manifest) i3Lines() string {
|
||||
func i3Lines(m catalogue.Manifest) string {
|
||||
var out string
|
||||
for _, it := range m.Items {
|
||||
if it.Collection == displaySession {
|
||||
@@ -289,7 +224,7 @@ func (m manifest) i3Lines() string {
|
||||
|
||||
// i3LinesAreSource checks the window-manager lines are one item whose template is the source file, and that no
|
||||
// old-form contribution to node-display-session is left.
|
||||
func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
func i3LinesAreSource(t *testing.T, m catalogue.Manifest, source string) {
|
||||
t.Helper()
|
||||
if len(m.Contributions) != 0 {
|
||||
t.Fatalf("the module still holds contributions: the lines are an item of %s", displaySession)
|
||||
@@ -303,7 +238,7 @@ func (m manifest) i3LinesAreSource(t *testing.T, source string) {
|
||||
if len(templates) != 1 || templates[0] != source {
|
||||
t.Fatalf("the items of %s are %v, want the one template %s", displaySession, templates, source)
|
||||
}
|
||||
if m.i3Lines() == "" {
|
||||
if i3Lines(m) == "" {
|
||||
t.Fatalf("the template %s holds no line", source)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// i3status-rust's shape (novox/hq ADR 0208): it claims node-bar, requires the X display on its own
|
||||
@@ -12,12 +16,20 @@ import (
|
||||
// devices.
|
||||
|
||||
func TestItClaimsTheBarSeatAndRequiresTheXDisplay(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
if !m.Moved {
|
||||
t.Fatal("the module is not marked moved")
|
||||
}
|
||||
if m.Module != "i3status-rust" || m.Seats != nil {
|
||||
t.Fatalf("module %q declares seats %v", m.Module, m.Seats)
|
||||
if m.Module != "i3status-rust" || m.DefinesSeats != nil {
|
||||
t.Fatalf("module %q declares seats %v", m.Module, m.DefinesSeats)
|
||||
}
|
||||
if len(m.Claims) != 1 || m.Claims[0].Name != "node-bar" || m.Claims[0].Scope != "node" ||
|
||||
len(m.Claims[0].Renders) != 0 {
|
||||
@@ -26,25 +38,41 @@ func TestItClaimsTheBarSeatAndRequiresTheXDisplay(t *testing.T) {
|
||||
if !reflect.DeepEqual(m.Requires, []string{"x11-display"}) {
|
||||
t.Fatalf("requires: %v", m.Requires)
|
||||
}
|
||||
if present, absent := m.packages(); !reflect.DeepEqual(present, []string{"i3status-rust"}) || absent != nil {
|
||||
if present, absent := packages(m); !reflect.DeepEqual(present, []string{"i3status-rust"}) || absent != nil {
|
||||
t.Fatalf("packages: %v, absent %v", present, absent)
|
||||
}
|
||||
}
|
||||
|
||||
func TestItOwnsItsFilesAsWrittenInTheModule(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
for id, src := range map[string]string{
|
||||
"top-bar": "files/top-bar.toml", "bottom-bar": "files/bottom-bar.toml", "icons": "files/icons/custom-icons.toml",
|
||||
"updates": "files/bin/i3status-updates", "watchdog": "files/bin/i3bar-watchdog",
|
||||
"value": "files/bin/i3status-value",
|
||||
} {
|
||||
m.fromTemplate(t, id, src)
|
||||
fromTemplate(t, m, id, src)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoBlockFollowsAMachinesHardwareOrAPersonsDevicesOrCarriesAKey(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
bottom := m.text(t, "bottom-bar")
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
bottom := templateText(t, m, "bottom-bar")
|
||||
for _, never := range []string{`block = "battery"`, `block = "amd_gpu"`, `block = "nvidia_gpu"`, "mac = ", "api_key", "city_id", "openweathermap", "~/scripts/"} {
|
||||
if strings.Contains(bottom, never) {
|
||||
t.Errorf("the bottom bar has %s", never)
|
||||
@@ -53,26 +81,51 @@ func TestNoBlockFollowsAMachinesHardwareOrAPersonsDevicesOrCarriesAKey(t *testin
|
||||
}
|
||||
|
||||
func TestTheBarsAreAContributionToTheWindowManagerAndTheWatchdogRunsOncePerSession(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
m.i3LinesAreSource(t, "files/i3/60-i3status-rust.conf")
|
||||
c := m.i3Lines()
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
i3LinesAreSource(t, m, "files/i3/60-i3status-rust.conf")
|
||||
c := i3Lines(m)
|
||||
if strings.Count(c, "bar {") != 2 || !strings.Contains(c, "status_command i3status-rs ~/.config/i3status-rust/bottom-bar.toml") ||
|
||||
!strings.Contains(c, "font pango:JetBrainsMono Nerd Font 11") {
|
||||
t.Fatalf("%s", c)
|
||||
}
|
||||
if len(m.shell(t)) != 1 || m.shell(t)[0].For != "xinitrc" || m.shell(t)[0].Slot != "normal" ||
|
||||
!strings.Contains(m.shell(t)[0].Code, `"$HOME/.local/bin/i3bar-watchdog" "$$" &`) {
|
||||
t.Fatalf("%+v", m.shell(t))
|
||||
if len(shell(t, m)) != 1 || shell(t, m)[0].For != "xinitrc" || shell(t, m)[0].Slot != "normal" ||
|
||||
!strings.Contains(shell(t, m)[0].Code, `"$HOME/.local/bin/i3bar-watchdog" "$$" &`) {
|
||||
t.Fatalf("%+v", shell(t, m))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheToolsAgreeWithTheManifest(t *testing.T) {
|
||||
m := readManifest(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
checkTheToolsAgree(t, m)
|
||||
checkNoSecretsOrInstallationNames(t)
|
||||
}
|
||||
|
||||
// No file resource carries its text inline (novox/hq ADR 0349 §2).
|
||||
func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
readManifest(t).everyFileIsATemplate(t)
|
||||
manifestJSON, err := os.ReadFile(filepath.Join("..", "..", "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// manifest strictness is the catalog check's (H-A-498): the SDK's reader sets an unknown field aside.
|
||||
m, err := catalogue.Decode(manifestJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("module.json: %v", err)
|
||||
}
|
||||
everyFileIsATemplate(t, m)
|
||||
}
|
||||
|
||||
@@ -37,7 +37,11 @@ Three read tools answer what the module stored in its own states, without the gu
|
||||
forge-account provision's ssh name, so the account's own ssh files and git rewrite are used) into a workspace of the
|
||||
work directory, then runs `go mod download` and `go mod verify` in every directory with a `go.mod` that does not vendor,
|
||||
with `GOTOOLCHAIN=local`, `GOFLAGS=-mod=mod` and the module's cache directory. Every command runs with an
|
||||
environment built from scratch (`StepRunner`): `PATH`, `HOME` and what the step passes.
|
||||
environment built from scratch (`StepRunner`): `PATH`, `HOME` and what the step passes. The fetch downloads in two
|
||||
passes: each pinned mesh package from the Go package registry seat alone (`GOPROXY=<seat>,off`; a version the seat does
|
||||
not hold fails as `the Go package registry holds no <package>@<version>`, and with no binding of the seat the fetch
|
||||
refuses: `no Go package registry bound`), then the rest of the build list through Go's public proxy alone, never `direct`;
|
||||
every other go command runs with `GOPROXY=off` (design 47 H, H-A-494).
|
||||
|
||||
## Room to work and the workspace's end
|
||||
|
||||
@@ -53,11 +57,13 @@ The programs this module builds from a commit and keeps in its cache (composers
|
||||
asks) are read by `build_go_kept` (kind, key, size, last use) and removed by `build_go_kept_drop {kind, key}`; one no ask used
|
||||
for 30 days is swept with the workspaces (issue 1921).
|
||||
|
||||
A pin on a pull request's head (issue 1148): when `go mod download` fails on a `git.novox.be/novox/*` pseudo-version, the
|
||||
fetch looks for that commit among the forge's `refs/pull/*/head`, places the repository at it under the workspace's
|
||||
`pinned/beside/` as a plain directory, and hands it to Go (the fetch's commands, and the build with `GOPROXY=off`) through a
|
||||
temporary `-modfile` in the workspace's `pins/` that replaces the module by that directory. A pin Go can fetch is left as
|
||||
it is, a pin on no ref fails naming the module and the commit, and a directory that vendors is never resolved.
|
||||
A pin on a pull request's head (issue 1148): when the ask pins a mesh package at a commit the Go package registry does not
|
||||
hold, the fetch looks for that commit among the forge's `refs/pull/*/head`, places the repository at it under the
|
||||
workspace's `pinned/beside/` as a plain directory, and hands it to Go (the fetch's commands, and the build with
|
||||
`GOPROXY=off`) through a temporary `-modfile` in the workspace's `pins/` that replaces the module by that directory. A pin
|
||||
on no ref fails naming the module and the commit, and a directory that vendors is never resolved. A go.mod names a mesh
|
||||
package at the zero version only: one it names at another version is refused before any download (`<module> names
|
||||
<package>@<version>; a mesh package is required at the zero version`), never placed (design 47 H, H-A-494).
|
||||
|
||||
The asked versions of the mesh's packages (novox/hq ADR 0573 §2, §4; issue 1585): a fetch given `packages` (a full commit
|
||||
by Go module path, which the builder and the checker fill from the indexer's trunk values or a group's heads) writes each
|
||||
|
||||
@@ -51,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
Lint: m.lintStep,
|
||||
Node: m.Node,
|
||||
SayStep: m.sayStep(),
|
||||
Outputs: m.outputs(),
|
||||
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
|
||||
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
|
||||
SayImports: m.sayImports(),
|
||||
Outputs: m.outputs(),
|
||||
}
|
||||
}
|
||||
|
||||
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
|
||||
// SayEvent; nil when the module says no event.
|
||||
func (m *Module) sayImports() func(seat.ImportsReported) error {
|
||||
if m.SayEvent == nil {
|
||||
return nil
|
||||
}
|
||||
return steprun.SayImportsOn(sdkstep.AskGo, m.Node, m.SayEvent)
|
||||
}
|
||||
|
||||
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
|
||||
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
|
||||
func (m *Module) outputs() steprun.OutputObjects {
|
||||
|
||||
@@ -4,6 +4,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -11,6 +12,7 @@ import (
|
||||
"github.com/nats-io/nats.go"
|
||||
"github.com/nats-io/nats.go/jetstream"
|
||||
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
"git.novox.be/novox/mesh-sdk/go/testbus"
|
||||
@@ -30,6 +32,9 @@ const checkCommit = "89abcdef0123456789abcdef0123456789abcdef"
|
||||
// **The order is read from the record.** At capacity 1 the puller starts the check the instant the delivery ask's step
|
||||
// ends, well before any poll, so "the check key holds a state" is true on correct behaviour (issue 1887). The test
|
||||
// waits for both asks to end and compares the step records' own Started and Ended times, and the fetch order by commit.
|
||||
//
|
||||
// G1/AC2 (design 47 H2 H-A-517, H-A-532 DQ-2): each build that read its imports says imports-reported, and the
|
||||
// delivery ask's is on the bus, on the seat's subject of the node.
|
||||
func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
|
||||
nc, err := nats.Connect(testbus.URL(t))
|
||||
if err != nil {
|
||||
@@ -64,9 +69,24 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
|
||||
states := newStates()
|
||||
m := moduleWith(states, "go1.26.0")
|
||||
m.Capacity = func() int { return 1 }
|
||||
reported := make(chan *nats.Msg, 4)
|
||||
sub, err := nc.ChanSubscribe(seat.SubjectImportsReportedAll, reported)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = sub.Unsubscribe() }()
|
||||
m.SayEvent = func(subject string, body any, _ string) error {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nc.Publish(subject, raw)
|
||||
}
|
||||
var mu sync.Mutex
|
||||
var order []string
|
||||
steps := fakeSteps(new([]string))
|
||||
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
|
||||
return ImportsResult{Imports: []string{"git.novox.be/novox/mesh-sdk/go"}}, nil
|
||||
}})
|
||||
for i := range steps {
|
||||
if steps[i].Name == "build_go_fetch" {
|
||||
run := steps[i].Run
|
||||
@@ -113,8 +133,26 @@ func TestTheModuleTakesADeliveryAskBeforeAnEarlierCheck(t *testing.T) {
|
||||
t.Fatalf("the check ask started at %v, before the delivery ask ended at %v at capacity 1", checkStarted, deliveryEnded)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(order) != 2 || order[0] != askCommit || order[1] != checkCommit {
|
||||
t.Fatalf("fetched %v, want the delivery ask's commit %s first, then the check's %s", order, askCommit, checkCommit)
|
||||
}
|
||||
mu.Unlock()
|
||||
for timeout := time.After(10 * time.Second); ; {
|
||||
select {
|
||||
case msg := <-reported:
|
||||
var r seat.ImportsReported
|
||||
if err := json.Unmarshal(msg.Data, &r); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Commit != askCommit {
|
||||
continue
|
||||
}
|
||||
if msg.Subject != seat.SubjectImportsReported("ace") || r.Module != "mesh-delivery-view" || len(r.Imports) != 1 {
|
||||
t.Fatalf("imports-reported on %s: %+v", msg.Subject, r)
|
||||
}
|
||||
return
|
||||
case <-timeout:
|
||||
t.Fatal("the delivery ask's imports-reported never reached the bus")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
)
|
||||
@@ -28,3 +31,47 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// G1/AC1 (design 47 H2 H-A-517, H-A-532 DQ-2): a build ask of a module with Go bundles that ends done says one
|
||||
// imports-reported on the seat's subject of the node, naming the module, the fingerprint, the commit and the imports
|
||||
// the imports step read.
|
||||
func TestADoneBuildSaysItsImportSetOnTheNodesSubject(t *testing.T) {
|
||||
type said struct {
|
||||
subject, id string
|
||||
body seat.ImportsReported
|
||||
}
|
||||
var events []said
|
||||
m := moduleWith(newStates(), "go1.26.0")
|
||||
m.SayEvent = func(subject string, body any, id string) error {
|
||||
r, ok := body.(seat.ImportsReported)
|
||||
if !ok {
|
||||
raw, _ := json.Marshal(body)
|
||||
t.Fatalf("said %s with %T: %s", subject, body, raw)
|
||||
}
|
||||
events = append(events, said{subject, id, r})
|
||||
return nil
|
||||
}
|
||||
imports := []string{"git.novox.be/novox/mesh-sdk/go", "git.novox.be/novox/mesh-sdk/go/busstate"}
|
||||
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
|
||||
return ImportsResult{Imports: imports}, nil
|
||||
}})
|
||||
a := deliveryAsk()
|
||||
a.Build.Fp = "src2:0123"
|
||||
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(events) != 1 {
|
||||
t.Fatalf("said %d imports-reported, want 1: %+v", len(events), events)
|
||||
}
|
||||
e := events[0]
|
||||
if e.subject != seat.SubjectImportsReported("ace") {
|
||||
t.Errorf("said on %s, want %s", e.subject, seat.SubjectImportsReported("ace"))
|
||||
}
|
||||
if e.id != "imports-reported.mesh-delivery-view.src2:0123" {
|
||||
t.Errorf("id %s", e.id)
|
||||
}
|
||||
if e.body.Node != "ace" || e.body.Module != "mesh-delivery-view" || e.body.Fingerprint != "src2:0123" || e.body.Commit != askCommit ||
|
||||
len(e.body.Imports) != 2 || e.body.Imports[0] != imports[0] || e.body.Imports[1] != imports[1] {
|
||||
t.Errorf("said %+v", e.body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,6 +195,10 @@ func TestManifestClaimsTheGoBuildSeatAndReadsItsCapacity(t *testing.T) {
|
||||
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
|
||||
t.Errorf("the build-hours description names a node pair")
|
||||
}
|
||||
// Design 47 H2 H-A-539: no prefix tells a mesh package apart, so the module declares no setting import-prefix.
|
||||
if _, ok := doc.Config["import-prefix"]; ok {
|
||||
t.Errorf("the manifest declares import-prefix, which H-A-539 withdrew")
|
||||
}
|
||||
var capacity float64
|
||||
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
|
||||
if capacity != 0 {
|
||||
|
||||
@@ -194,40 +194,63 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str
|
||||
}
|
||||
// The directories download side by side, up to the bound (ADR 0536 §2); the first failure in directory order is the
|
||||
// step's. Resolving a pin places a repository beside the workspace, which two directories may share: one at a time.
|
||||
// Two passes (design 47 H, H-A-494 addendum): every directory's mesh packages from the Go package registry first,
|
||||
// then every directory's rest through the public proxy, so the module cache holds each mesh package before any
|
||||
// download of the rest.
|
||||
var pins sync.Mutex
|
||||
errs := make([]error, len(dirs))
|
||||
taken := make([][]TakenVersion, len(dirs))
|
||||
slots := make(chan struct{}, m.parallel())
|
||||
var wg sync.WaitGroup
|
||||
for i, d := range dirs {
|
||||
if _, err := os.Stat(filepath.Join(tree, d, "vendor", "modules.txt")); err == nil {
|
||||
continue // a module that vendors resolves nothing
|
||||
sideBySide := func(pass func(i int, d string)) {
|
||||
var wg sync.WaitGroup
|
||||
for i, d := range dirs {
|
||||
if _, err := os.Stat(filepath.Join(tree, d, "vendor", "modules.txt")); err == nil {
|
||||
continue // a module that vendors resolves nothing
|
||||
}
|
||||
if errs[i] != nil {
|
||||
continue // failed in the first pass
|
||||
}
|
||||
wg.Add(1)
|
||||
slots <- struct{}{}
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-slots }()
|
||||
pass(i, d)
|
||||
}()
|
||||
}
|
||||
wg.Add(1)
|
||||
slots <- struct{}{}
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
defer func() { <-slots }()
|
||||
// The checked repository's own modules come from the fetched tree, at whatever version go.mod names them
|
||||
// (pins.go takeOwnRequirements; design 47 H, S31).
|
||||
if taken[i], errs[i] = m.takeOwnRequirements(root, repository, filepath.Join(tree, d), d); errs[i] != nil {
|
||||
return
|
||||
}
|
||||
// The asked versions of the mesh's packages go into the modfile before anything is downloaded (versions.go).
|
||||
more, err := m.takeVersions(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, &pins)
|
||||
if taken[i], errs[i] = append(taken[i], more...), err; errs[i] != nil {
|
||||
return
|
||||
}
|
||||
// Then what only a module the directory replaces names, which the download would not miss (pins.go).
|
||||
more, errs[i] = m.takeReplacedZeroPins(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, taken[i], &pins)
|
||||
if taken[i] = append(taken[i], more...); errs[i] != nil {
|
||||
return
|
||||
}
|
||||
more, errs[i] = m.downloadModules(ctx, root, repository, filepath.Join(tree, d), d, &pins, req.Packages)
|
||||
taken[i] = append(taken[i], more...)
|
||||
}()
|
||||
wg.Wait()
|
||||
}
|
||||
wg.Wait()
|
||||
sideBySide(func(i int, d string) {
|
||||
// A mesh package is required at the zero version only: one a go.mod names at another version is refused
|
||||
// before either download, so the second can never carry a forge path to the public proxy (H-A-494 second addendum).
|
||||
if errs[i] = namedForgeVersion(repository, filepath.Join(tree, d)); errs[i] != nil {
|
||||
return
|
||||
}
|
||||
// The checked repository's own modules come from the fetched tree, at whatever version go.mod names them
|
||||
// (pins.go takeOwnRequirements; design 47 H, S31).
|
||||
if taken[i], errs[i] = m.takeOwnRequirements(root, repository, filepath.Join(tree, d), d); errs[i] != nil {
|
||||
return
|
||||
}
|
||||
// The asked versions of the mesh's packages go into the modfile before anything is downloaded (versions.go).
|
||||
more, err := m.takeVersions(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, &pins)
|
||||
if taken[i], errs[i] = append(taken[i], more...), err; errs[i] != nil {
|
||||
return
|
||||
}
|
||||
// Then every requirement at the zero version of the directory's graph the asked versions did not take, its own
|
||||
// and what only a module it replaces names, taken or refused before any download of the rest, so no forge
|
||||
// path reaches the public proxy first (pins.go; H-A-494 third addendum).
|
||||
more, errs[i] = m.takeZeroPinsFirst(ctx, root, repository, filepath.Join(tree, d), d, req.Packages, taken[i], &pins)
|
||||
taken[i] = append(taken[i], more...)
|
||||
})
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
sideBySide(func(i int, d string) {
|
||||
more, err := m.downloadModules(ctx, root, repository, filepath.Join(tree, d), d, &pins, req.Packages)
|
||||
taken[i], errs[i] = append(taken[i], more...), err
|
||||
})
|
||||
for _, err := range errs {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -242,10 +265,10 @@ func (m *Module) fetchInto(ctx context.Context, req sdkstep.FetchRequest, id str
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// downloadModules downloads and verifies the Go modules of the directory dir (d in the tree). A pin of a forge module
|
||||
// that Go cannot fetch is looked for among the forge's pull request heads and handed to Go by a modfile (pins.go); a
|
||||
// failure that names no such pin is the first failure. A requirement at the zero version is taken from the asked
|
||||
// versions (pins.go takeZeroPins).
|
||||
// downloadModules downloads and verifies the Go modules of the directory dir (d in the tree): the fetch's second
|
||||
// download, after every mesh package was taken. A requirement at the zero version a failure still names is taken from
|
||||
// the asked versions (pins.go takeZeroPins); any other failure is the first failure. A version a go.mod names is never
|
||||
// placed from a pull request's head (H-A-494 third addendum): namedForgeVersion refused it before.
|
||||
func (m *Module) downloadModules(ctx context.Context, root, repository, dir, d string, pins *sync.Mutex, asked sdkstep.PackageVersions) ([]TakenVersion, error) {
|
||||
var taken []TakenVersion
|
||||
for {
|
||||
@@ -261,13 +284,7 @@ func (m *Module) downloadModules(ctx context.Context, root, repository, dir, d s
|
||||
if err != nil {
|
||||
return taken, err
|
||||
}
|
||||
pins.Lock()
|
||||
progress, err := m.resolvePins(ctx, root, dir, failure.Error())
|
||||
pins.Unlock()
|
||||
if err != nil {
|
||||
return taken, err
|
||||
}
|
||||
if !progress && len(took) == 0 {
|
||||
if len(took) == 0 {
|
||||
return taken, failure
|
||||
}
|
||||
}
|
||||
@@ -444,10 +461,11 @@ func (m *Module) downloadAndVerify(ctx context.Context, dir, d string) error {
|
||||
}
|
||||
}
|
||||
}
|
||||
cmd, env := []string{"-C", dir, "mod", verb}, m.goEnvFor(dir)
|
||||
// The second download: the rest of the build list through Go's public proxy alone (publicEnv).
|
||||
cmd, env := []string{"-C", dir, "mod", verb}, publicEnv(m.goEnvFor(dir))
|
||||
if modfile, ok := m.pinModfile(dir); ok && verb == "verify" {
|
||||
// go mod verify takes no -modfile: it is run on the modfile itself, which names the placed repositories.
|
||||
cmd, env = []string{"-C", filepath.Dir(modfile), "mod", verb}, m.goEnv()
|
||||
cmd, env = []string{"-C", filepath.Dir(modfile), "mod", verb}, publicEnv(m.goEnv())
|
||||
}
|
||||
r := m.Run(ctx, env, "go", cmd...)
|
||||
if r.Status != 0 || r.Err != "" {
|
||||
@@ -521,8 +539,10 @@ func inTestdata(path string) bool {
|
||||
}
|
||||
|
||||
// goEnv is what a go command of a step is given beyond the base environment: the installed go alone (GOTOOLCHAIN=local, ADR 0477 §1: no toolchain is ever downloaded),
|
||||
// modules resolved by their go.mod and go.sum, the module's own caches, the mesh's own modules fetched directly (by
|
||||
// git, through the account's rewrite of the forge's address to ssh), and nothing that asks a question. For a directory
|
||||
// modules resolved by their go.mod and go.sum, the module's own caches, the checksum database off for the forge's paths
|
||||
// (go.sum and the builder's h1: digest guard them, ADR 0605 §6), and no proxy at all (GOPROXY=off): only the fetch's two
|
||||
// downloads reach the network, each with its own proxy (registryEnv, publicEnv; design 47 H, H-A-494 and its addendum),
|
||||
// and every other step (the test and lint steps, the compile) reads the module cache the fetch filled. For a directory
|
||||
// that vendors, see goEnvFor.
|
||||
func (m *Module) goEnv() []string {
|
||||
modcache := filepath.Join(m.Cache, "gomod")
|
||||
@@ -534,20 +554,48 @@ func (m *Module) goEnv() []string {
|
||||
"GOFLAGS=-mod=mod",
|
||||
"GOMODCACHE=" + modcache,
|
||||
"GOCACHE=" + filepath.Join(m.Cache, "gobuild"),
|
||||
"GONOSUMDB=" + ForgeGoPaths,
|
||||
"GOPROXY=off",
|
||||
}
|
||||
if proxy := m.goSeat(); proxy != "" {
|
||||
// The Go seat first, the public proxy second, the forge's git last (CAT-BG3, E11: direct goes in the first
|
||||
// change after mesh-sdk's and mesh-contracts' first numbered versions are in the Go seat); no GOPRIVATE, and
|
||||
// the checksum database off for the forge's paths, which go.sum and the builder's h1: digest guard instead.
|
||||
// The seat goes on to the public proxy only on a 404 or 410 (",": a package it does not hold), so a seat that
|
||||
// fails otherwise (5xx, refused, timeout) fails the fetch loudly; the public proxy goes on to direct on any
|
||||
// failure ("|"): a public proxy the node cannot reach stopped the fetch before direct, and direct reaches the
|
||||
// forge's git for a package the seat does not hold (issue 1966, ADR 0605 §6).
|
||||
env = append(env, "GOPROXY="+proxy+","+PublicGoProxy+"|direct", "GONOSUMDB="+ForgeGoPaths, "GOPRIVATE=")
|
||||
} else {
|
||||
env = append(env, "GOPRIVATE="+ForgeGoPaths)
|
||||
return append(env, m.threadEnv()...)
|
||||
}
|
||||
|
||||
// errNoRegistry is a fetch that needs a mesh package with no binding of the Go package registry seat: the package
|
||||
// comes from that seat alone (design 47 H, H-A-494), never from the public proxy nor the forge's git.
|
||||
var errNoRegistry = errors.New("no Go package registry bound")
|
||||
|
||||
// registryEnv is env for the fetch's first download, of each pinned mesh package (takeVersion): the Go package registry
|
||||
// seat alone and nothing behind it (GOPROXY=<seat>,off), so a version the seat does not hold fails as its miss
|
||||
// (registryMiss), never reaching the public proxy, which serves the forge's paths from git tags, nor the forge's git
|
||||
// (design 47 H, H-A-494 addendum). With no binding it refuses (errNoRegistry).
|
||||
func (m *Module) registryEnv(env []string) ([]string, error) {
|
||||
seat := m.goSeat()
|
||||
if seat == "" {
|
||||
return nil, errNoRegistry
|
||||
}
|
||||
return append(append(env, "GIT_TERMINAL_PROMPT=0", "GIT_SSH_COMMAND=ssh -o BatchMode=yes"), m.threadEnv()...)
|
||||
return withProxy(env, seat+",off"), nil
|
||||
}
|
||||
|
||||
// publicEnv is env for the fetch's second download, of the rest of the build list: Go's public proxy alone, no direct
|
||||
// (design 47 H, H-A-494 addendum). The module cache already holds the mesh packages the first download took, so a forge
|
||||
// path never reaches the public proxy.
|
||||
func publicEnv(env []string) []string { return withProxy(env, PublicGoProxy) }
|
||||
|
||||
// withProxy is env with its GOPROXY set to proxy, once.
|
||||
func withProxy(env []string, proxy string) []string {
|
||||
out := make([]string, 0, len(env)+1)
|
||||
for _, e := range env {
|
||||
if !strings.HasPrefix(e, "GOPROXY=") {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return append(out, "GOPROXY="+proxy)
|
||||
}
|
||||
|
||||
// registryMiss says whether a failure of the first download is the Go package registry seat not holding the version:
|
||||
// the seat answered 404 or 410, and Go, with nothing behind the seat but off, words it as the lookup off.
|
||||
func registryMiss(failure string) bool {
|
||||
return strings.Contains(failure, "disabled by GOPROXY=off") || strings.Contains(failure, "404 Not Found") || strings.Contains(failure, "410 Gone")
|
||||
}
|
||||
|
||||
// PublicGoProxy is Go's public module proxy; ForgeGoPaths the module paths the forge serves.
|
||||
@@ -556,7 +604,7 @@ const (
|
||||
ForgeGoPaths = "git.novox.be"
|
||||
)
|
||||
|
||||
// goSeat is the Go seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the
|
||||
// goSeat is the Go package registry seat's proxy URL from its binding (`at`, and `serves` scheme, port and go-path), empty when the
|
||||
// module holds no binding of it or the binding names no address.
|
||||
func (m *Module) goSeat() string {
|
||||
if m.GoSeatFile == "" {
|
||||
|
||||
@@ -95,9 +95,33 @@ func fetchModule(t *testing.T, f *fakeStep) (*Module, *keptStates) {
|
||||
states := newStates()
|
||||
m := moduleWith(states, "go1.27.1")
|
||||
m.Run, m.Home, m.Work, m.Cache = f.run, t.TempDir(), t.TempDir(), t.TempDir()
|
||||
bindRegistry(t, m)
|
||||
return m, states
|
||||
}
|
||||
|
||||
// testRegistry is the Go package registry seat's proxy a test binding names (bindRegistry).
|
||||
const testRegistry = "http://forge.mesh:3000/api/packages/novox/go"
|
||||
|
||||
// bindRegistry gives m a binding of the Go package registry seat, as every build node has (go-package-registry).
|
||||
func bindRegistry(t *testing.T, m *Module) {
|
||||
t.Helper()
|
||||
m.GoSeatFile = filepath.Join(t.TempDir(), "go-package-registry.json")
|
||||
if err := os.WriteFile(m.GoSeatFile, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// proxyValues are the GOPROXY settings of env.
|
||||
func proxyValues(env []string) []string {
|
||||
var out []string
|
||||
for _, e := range env {
|
||||
if strings.HasPrefix(e, "GOPROXY=") {
|
||||
out = append(out, e)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// fetchTool is the fetch tool as a build module is asked, always with its module's directory (A-447b): the root of the
|
||||
// tree unless the args name one. rawFetchTool is the tool as it is.
|
||||
func fetchTool(t *testing.T, m *Module) func(map[string]any) (any, error) {
|
||||
@@ -132,10 +156,20 @@ var fetchArgs = map[string]any{"repository": "novox/mesh-sdk", "commit": commitS
|
||||
// directory (not in one that vendors) with GOTOOLCHAIN=local, GOFLAGS=-mod=mod and the module's cache paths.
|
||||
func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) {
|
||||
// The root go.mod replaces the other two by directory: a fetch asked with a module's directory chooses what it replaces.
|
||||
// Each Go module requires a mesh package at the zero version, which the ask pins (H-A-494 addendum: the first download).
|
||||
const contracts = "git.novox.be/novox/mesh-contracts/go/x"
|
||||
f := &fakeStep{gomods: "go.mod\nsub/dir/go.mod\nvend/go.mod\n", vendors: []string{"vend"},
|
||||
files: map[string]string{"go.mod": "module fake\nreplace a => ./sub/dir\nreplace b => ./vend\n"}}
|
||||
files: map[string]string{"go.mod": "module fake\nrequire " + contracts + " " + zeroVersion + "\nreplace a => ./sub/dir\nreplace b => ./vend\n",
|
||||
"sub/dir/go.mod": "module fake/sub\nrequire " + contracts + " " + zeroVersion + "\n"},
|
||||
goRule: func(line string) forgekey.Ran {
|
||||
if strings.Contains(line, " mod download -json "+contracts+"@") {
|
||||
return forgekey.Ran{Stdout: `{"Path":"` + contracts + `","Version":"v0.1.85","Sum":"h1:zip=","GoModSum":"h1:mod="}`}
|
||||
}
|
||||
return forgekey.Ran{}
|
||||
}}
|
||||
m, states := fetchModule(t, f)
|
||||
if _, err := fetchTool(t, m)(fetchArgs); err != nil {
|
||||
m.Parallel = 1 // one directory at a time, so the order of the commands is the fetch's own
|
||||
if _, err := fetchTool(t, m)(map[string]any{"repository": "novox/mesh-sdk", "commit": commitSHA, "packages": map[string]any{contracts: "v0.1.85"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := states.waitEnd(t)
|
||||
@@ -165,27 +199,47 @@ func TestFetchAsksGitForTheSshRemoteAndDownloadsEachModule(t *testing.T) {
|
||||
if strings.Contains(c.line, "vend") {
|
||||
t.Errorf("a module that vendors was downloaded: %s", c.line)
|
||||
}
|
||||
// The second download (H-A-494 addendum): the rest of the build list through Go's public proxy alone.
|
||||
env := strings.Join(c.env, " ")
|
||||
for _, want := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), "GOPRIVATE=git.novox.be"} {
|
||||
for _, want := range []string{"GOTOOLCHAIN=local", "GOFLAGS=-mod=mod", "GOMODCACHE=" + filepath.Join(m.Cache, "gomod"), "GOCACHE=" + filepath.Join(m.Cache, "gobuild"), "GOPROXY=" + PublicGoProxy} {
|
||||
if !strings.Contains(env, want) {
|
||||
t.Errorf("%s: environment lacks %s: %s", c.line, want, env)
|
||||
}
|
||||
}
|
||||
}
|
||||
// CAT-BG3: with the Go seat bound, the fetch goes through it first, Go's public proxy second and the forge's git
|
||||
// last, with no GOPRIVATE and the checksum database off for the forge's paths.
|
||||
seat := filepath.Join(t.TempDir(), "go-package-registry.json")
|
||||
if err := os.WriteFile(seat, []byte(`{"at":"forge.mesh","serves":{"scheme":"http","port":3000,"go-path":"/api/packages/novox/go"}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.GoSeatFile = seat
|
||||
env := strings.Join(m.goEnv(), " ")
|
||||
for _, want := range []string{"GOPROXY=http://forge.mesh:3000/api/packages/novox/go,https://proxy.golang.org|direct", "GONOSUMDB=git.novox.be", "GOPRIVATE= "} {
|
||||
if !strings.Contains(env+" ", want) {
|
||||
t.Errorf("with the Go seat bound the environment lacks %q: %s", want, env)
|
||||
if got := proxyValues(c.env); len(got) != 1 || got[0] != "GOPROXY="+PublicGoProxy {
|
||||
t.Errorf("%s: GOPROXY settings %v, want the public proxy alone", c.line, got)
|
||||
}
|
||||
}
|
||||
m.GoSeatFile = ""
|
||||
// Design 51 *Go packages*, H-A-494: no go command of the fetch reaches the forge's git (Go's direct), and none is
|
||||
// handed GOPRIVATE or the account's ssh; the checksum database stays off for the forge's paths (ADR 0605 §6), and a
|
||||
// step's own environment has no proxy at all.
|
||||
for _, c := range f.calls {
|
||||
if !strings.HasPrefix(c.line, "go ") {
|
||||
continue
|
||||
}
|
||||
for _, e := range c.env {
|
||||
if strings.HasPrefix(e, "GOPROXY=") && strings.Contains(e, "direct") || strings.HasPrefix(e, "GOPRIVATE=") || strings.HasPrefix(e, "GIT_SSH_COMMAND=") {
|
||||
t.Errorf("%s: the environment says %s", c.line, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
// H-A-494 addendum: every download of the Go package registry seat comes before every download through the public proxy.
|
||||
lastRegistry, firstPublic, registry := -1, -1, 0
|
||||
for i, c := range f.calls {
|
||||
switch got := proxyValues(c.env); {
|
||||
case len(got) == 1 && got[0] == "GOPROXY="+testRegistry+",off":
|
||||
lastRegistry, registry = i, registry+1
|
||||
case len(got) == 1 && got[0] == "GOPROXY="+PublicGoProxy && firstPublic < 0:
|
||||
firstPublic = i
|
||||
}
|
||||
}
|
||||
if registry != 2 || firstPublic < 0 || lastRegistry > firstPublic {
|
||||
t.Errorf("%d downloads from the seat, the last at %d, the first public at %d: want both directories' seat downloads before every public one:\n%s", registry, lastRegistry, firstPublic, lines)
|
||||
}
|
||||
env := strings.Join(m.goEnv(), " ")
|
||||
if got := proxyValues(m.goEnv()); len(got) != 1 || got[0] != "GOPROXY=off" || !strings.Contains(env, "GONOSUMDB=git.novox.be") {
|
||||
t.Errorf("a step's environment says GOPROXY %v, want off once, and GONOSUMDB=git.novox.be: %s", got, env)
|
||||
}
|
||||
if downloads != 2 || verifies != 2 {
|
||||
t.Errorf("%d downloads and %d verifies, want 2 each (go.mod and sub/dir/go.mod):\n%s", downloads, verifies, lines)
|
||||
}
|
||||
@@ -265,18 +319,18 @@ func TestAVerifyThatFailsEndsTheStepNamingTheDirectoryAndTheLine(t *testing.T) {
|
||||
loadedModuleMark + "github.com/nats-io/nats.go v1.54.0\n",
|
||||
tagged: loadedModuleMark + "github.com/nats-io/nats-server/v2 v2.11.17\n",
|
||||
files: map[string]string{
|
||||
"tools/go.mod": "module fixture/tools\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\tgithub.com/nats-io/nats.go v1.54.0\n)\n",
|
||||
"tools/go.mod": "module fixture/tools\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\tgithub.com/nats-io/nats.go v1.54.0\n)\n\nreplace git.novox.be/novox/mesh-sdk/go => ./sdk\n",
|
||||
"tools/go.sum": "github.com/nats-io/nats.go v1.54.0 h1:a=\ngithub.com/nats-io/nats.go v1.54.0/go.mod h1:b=\n",
|
||||
},
|
||||
want: []string{"tools", "go.mod: require github.com/nats-io/nats-server/v2 v2.11.17",
|
||||
"go.sum: github.com/nats-io/nats-server/v2 v2.11.17 h1:", "go.sum: github.com/nats-io/nats-server/v2 v2.11.17/go.mod h1:"},
|
||||
notWant: "nats.go"},
|
||||
// Issue 1966's kind: a mesh module reached only through another, which go.mod does not require, is lacked at the zero
|
||||
// version (ADR 0573 §2); one go.mod names at a commit (§4) is not.
|
||||
// version (ADR 0573 §2); one go.mod requires is not.
|
||||
{name: "a mesh module the load reaches is not required", ran: "tools list -e -deps -test",
|
||||
out: loadedModuleMark + seatPkg + " " + zeroVersion + "\n" +
|
||||
loadedModuleMark + "git.novox.be/novox/mesh-sdk/go v0.0.0-20261112000000-0123456789ab\n",
|
||||
files: map[string]string{"tools/go.mod": "module fixture/tools\n\nrequire git.novox.be/novox/mesh-sdk/go v0.0.0-20261112000000-0123456789ab\n"},
|
||||
loadedModuleMark + "git.novox.be/novox/mesh-sdk/go " + zeroVersion + " /tree/sdk \n",
|
||||
files: map[string]string{"tools/go.mod": "module fixture/tools\n\nrequire git.novox.be/novox/mesh-sdk/go " + zeroVersion + "\n\nreplace git.novox.be/novox/mesh-sdk/go => ./sdk\n"},
|
||||
want: []string{"tools", "go.mod: require " + seatPkg + " " + zeroVersion}, notWant: "mesh-sdk"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package main
|
||||
|
||||
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which mesh packages the module's Go programs
|
||||
// import, so the indexer can take the fingerprint over those packages' content and no other. It is `go list -deps` of
|
||||
// each Go bundle artifact's program, the tests left out, kept to the packages of the mesh's forge that lie outside the
|
||||
// module's own directory (a sibling package of the module's own repository counts, a package under the module itself
|
||||
// comes with its tree).
|
||||
// The imports step (novox/hq ADR 0593 §2): at a build's end the module says which packages the module's Go programs
|
||||
// import, so the indexer can take the fingerprint over the ones a module of the module graph publishes and no other. It
|
||||
// is `go list -deps` of each Go bundle artifact's program and of the packages each Go package artifact's paths hold
|
||||
// (design 47 H2 H-A-532 DQ-5), the tests left out: the import path of every package of the import closure (H-A-517,
|
||||
// H-A-541) but the standard library's, with no prefix telling a mesh package apart (H-A-539: mesh modules come from the
|
||||
// seat go-package-registry), and none of the module's own (its main module, or a module that lies under its own
|
||||
// directory, which comes with its tree).
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -14,7 +16,6 @@ import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
trunk "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/trunk"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
"git.novox.be/novox/mesh-sdk/go/forgekey"
|
||||
)
|
||||
@@ -27,8 +28,9 @@ type ImportsResult struct {
|
||||
func (m *Module) importsTool() StepTool {
|
||||
return StepTool{
|
||||
Name: ImportsTool,
|
||||
Description: "Read the mesh packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
|
||||
"bundle artifact, without tests, kept to the forge's packages outside the module's own directory, sorted and each once. " +
|
||||
Description: "Read the packages the Go programs of a module of a fetched workspace import: `go list -deps` of each Go " +
|
||||
"bundle artifact and of the packages each Go package artifact's paths hold, without tests, the import path of every " +
|
||||
"package but the standard library's and the module's own, sorted and each once. " +
|
||||
"It is what a build says at its end for the fingerprint (ADR 0593 §2). Read-only.",
|
||||
Input: map[string]any{
|
||||
"type": "object",
|
||||
@@ -65,27 +67,49 @@ func (m *Module) imports(ctx context.Context, args map[string]any) (any, error)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ModuleImports(ctx, run, m.buildEnv(dir), dir, manifest)
|
||||
return ModuleImports(ctx, run, m.buildEnv, dir, manifest)
|
||||
}
|
||||
|
||||
// ModuleImports are the mesh packages the Go bundle artifacts of manifest, in the module directory dir, import.
|
||||
func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
|
||||
// ModuleImports are the packages the Go bundle and package artifacts of manifest, in the module directory dir, import:
|
||||
// one sorted union of import paths (design 47 H2 H-A-518, H-A-541), the standard library, the tests and the module's
|
||||
// own left out. Each listing runs with env of the directory it runs in, the environment the build gives that directory
|
||||
// (its own module file of the fetch's pins, and the tree a module of the module's own repository is built from; design
|
||||
// 47 H2 H-A-633), never one environment for them all.
|
||||
func ModuleImports(ctx context.Context, run forgekey.Runner, env func(dir string) []string, dir string, manifest catalogue.Manifest) (ImportsResult, error) {
|
||||
seen := map[string]bool{}
|
||||
if manifest.Build != nil {
|
||||
for _, a := range manifest.Build.Artifacts {
|
||||
if a.Kind != "bundle" || a.Language != "go" || strings.TrimSpace(a.From) == "" {
|
||||
if a.Language != "go" {
|
||||
continue
|
||||
}
|
||||
r := run(ctx, env, "go", "-C", dir, "list", "-deps", "-f", "{{.ImportPath}} {{.Dir}}", "./"+strings.Trim(a.From, "./"))
|
||||
if r.Status != 0 || r.Err != "" {
|
||||
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
|
||||
// A bundle lists its program; a package (design 47 H2 H-A-532 DQ-5) lists every package each of its paths
|
||||
// holds, in the Go module that path is, so a contracts module reports its import set too.
|
||||
var lists [][2]string
|
||||
switch a.Kind {
|
||||
case "bundle":
|
||||
if strings.TrimSpace(a.From) != "" {
|
||||
lists = append(lists, [2]string{dir, "./" + strings.Trim(a.From, "./")})
|
||||
}
|
||||
case "package":
|
||||
for _, p := range a.Paths {
|
||||
if strings.TrimSpace(p) != "" {
|
||||
lists = append(lists, [2]string{filepath.Join(dir, filepath.FromSlash(strings.Trim(p, "./"))), "./..."})
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, l := range strings.Split(r.Stdout, "\n") {
|
||||
pkg, where, ok := strings.Cut(strings.TrimSpace(l), " ")
|
||||
if !ok || !meshPackage(pkg) || ownedBy(dir, where) {
|
||||
continue
|
||||
for _, l := range lists {
|
||||
r := run(ctx, env(l[0]), "go", "-C", l[0], "list", "-deps", "-f", listFormat, l[1])
|
||||
if r.Status != 0 || r.Err != "" {
|
||||
return ImportsResult{}, fmt.Errorf("go list of %s: %s", a.Name, causeLine(r.Err+"\n"+r.Stderr+"\n"+r.Stdout))
|
||||
}
|
||||
for _, line := range strings.Split(r.Stdout, "\n") {
|
||||
// <import path> <dir> <module path> <main>; a package of the standard library has no module.
|
||||
f := strings.Fields(line)
|
||||
if len(f) != 4 || f[3] == "true" || ownedBy(dir, f[1]) {
|
||||
continue
|
||||
}
|
||||
seen[f[0]] = true
|
||||
}
|
||||
seen[pkg] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -94,16 +118,12 @@ func ModuleImports(ctx context.Context, run forgekey.Runner, env []string, dir s
|
||||
out = append(out, p)
|
||||
}
|
||||
slices.Sort(out)
|
||||
if err := trunk.CheckImports(out); err != nil {
|
||||
return ImportsResult{}, err
|
||||
}
|
||||
return ImportsResult{Imports: out}, nil
|
||||
}
|
||||
|
||||
func meshPackage(pkg string) bool {
|
||||
_, _, ok := trunk.PackageRepository(pkg)
|
||||
return ok
|
||||
}
|
||||
// listFormat is what go list says of each package a program reaches: its import path, its directory and, outside the
|
||||
// standard library, its module's path and whether that is the main module.
|
||||
const listFormat = "{{.ImportPath}} {{.Dir}}{{with .Module}} {{.Path}} {{.Main}}{{end}}"
|
||||
|
||||
// ownedBy says the package directory where lies under the module directory dir and is not a vendored copy.
|
||||
func ownedBy(dir, where string) bool {
|
||||
|
||||
@@ -12,33 +12,39 @@ import (
|
||||
"git.novox.be/novox/mesh-sdk/go/forgekey"
|
||||
)
|
||||
|
||||
// ADR 0593 §2 (C3): a fixture whose program imports announce, a sibling package of its own repository and a package of its
|
||||
// own directory reports the first two; a test's import never appears (go list is run without -test), and the standard
|
||||
// library, a package of another host and the module's own packages are left out.
|
||||
func TestModuleImportsAreTheMeshPackagesOutsideTheModule(t *testing.T) {
|
||||
// noEnv is the environment of a listing a test's fake compiler reads nothing from.
|
||||
func noEnv(string) []string { return nil }
|
||||
|
||||
// ADR 0593 §2 (C3), design 47 H2 H-A-517, H-A-539, H-A-541: a fixture whose program imports packages of other Go
|
||||
// modules reports the import path of each package, whatever its host (a mesh module comes from the seat
|
||||
// go-package-registry, never told apart by a forge prefix): a sibling module's package and an outside package count,
|
||||
// each once; the standard library (no module), the module's own packages (its main module, or a module under its own
|
||||
// directory) and a test's import (go list runs without -test) are left out.
|
||||
func TestModuleImportsAreTheModulesItsBuildResolved(t *testing.T) {
|
||||
dir := "/w/ws1/tree/modules/demo"
|
||||
var line string
|
||||
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
line = name + " " + strings.Join(args, " ")
|
||||
return forgekey.Ran{Stdout: strings.Join([]string{
|
||||
"fmt /usr/lib/go/src/fmt",
|
||||
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
|
||||
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce",
|
||||
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib",
|
||||
"git.novox.be/novox/mesh-catalog/modules/demo/internal/own " + dir + "/internal/own",
|
||||
"git.novox.be/novox/mesh-sdk/go/vendored " + dir + "/vendor/git.novox.be/novox/mesh-sdk/go/vendored",
|
||||
"github.com/nats-io/nats.go /cache/nats.go",
|
||||
"git.novox.be/novox/mesh-sdk/go/announce /cache/mesh-sdk@v1/go/announce git.novox.be/novox/mesh-sdk/go false",
|
||||
"git.novox.be/novox/mesh-sdk/go/busstate /cache/mesh-sdk@v1/go/busstate git.novox.be/novox/mesh-sdk/go false",
|
||||
"git.novox.be/novox/mesh-catalog/modules/sibling/lib /w/ws1/tree/modules/sibling/lib git.novox.be/novox/mesh-catalog/modules/sibling/lib false",
|
||||
"demo/internal/own " + dir + "/internal/own demo true",
|
||||
"git.novox.be/novox/mesh-catalog/modules/demo/inner " + dir + "/inner git.novox.be/novox/mesh-catalog/modules/demo/inner false",
|
||||
"github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
|
||||
}, "\n")}
|
||||
}
|
||||
m, err := catalogue.Decode([]byte(`{"module":"demo","version":"1","build":{"artifacts":[` + goBundle + `,{"name":"files","kind":"archive","from":"files"}]}}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := ModuleImports(context.Background(), run, nil, dir, m)
|
||||
got, err := ModuleImports(context.Background(), run, noEnv, dir, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce", "git.novox.be/novox/mesh-sdk/go/vendored"}
|
||||
want := []string{"git.novox.be/novox/mesh-catalog/modules/sibling/lib", "git.novox.be/novox/mesh-sdk/go/announce",
|
||||
"git.novox.be/novox/mesh-sdk/go/busstate", "github.com/nats-io/nats.go"}
|
||||
if !slices.Equal(got.Imports, want) {
|
||||
t.Errorf("imports %v, want %v", got.Imports, want)
|
||||
}
|
||||
@@ -60,4 +66,116 @@ func TestImportsStepReadsTheWorkspace(t *testing.T) {
|
||||
if got := out.(ImportsResult).Imports; len(got) != 0 {
|
||||
t.Errorf("a fake compiler's go list names no package, and the answer was %v", got)
|
||||
}
|
||||
|
||||
// Issue 1984 (design 47 H2 H-A-633): each listing runs with the environment the build gives its directory. A
|
||||
// package path's Go module requires a module of its own repository at the zero version, which only the path's own
|
||||
// temporary modfile of the fetch (its replace to the tree) resolves; the module directory's environment names no
|
||||
// such modfile, and Go's lookup is shut off (GOPROXY=off), as main.510 met on mesh-delivery-contracts' paths.
|
||||
t.Run("a path resolved only through its own module file", func(t *testing.T) {
|
||||
const sdk = "git.novox.be/novox/mesh-delivery/modules/demo-sdk"
|
||||
pkg := `{"name":"clients","kind":"package","language":"go","paths":["go/clients/registry"],"series":"0.1"}`
|
||||
m, _, _ := buildModule(t, manifestWith(pkg), "x")
|
||||
tree := filepath.Join(m.Work, "ws1", "tree", "modules")
|
||||
path, own := filepath.Join(tree, "demo", "go", "clients", "registry"), filepath.Join(tree, "demo-sdk")
|
||||
for dir, body := range map[string]string{
|
||||
path: "module git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry\n\nrequire " + sdk + " " + zeroVersion + "\n",
|
||||
own: "module " + sdk + "\n",
|
||||
} {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
// What the fetch does for a same-repository requirement: a modfile of the path's directory replacing the module.
|
||||
if err := m.replaceInModfile(path, sdk, own); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Go, as far as the listing needs it: the module file it reads is the one -modfile names, else the directory's
|
||||
// own go.mod, and a required module no replace of that file points at is looked up, which GOPROXY=off refuses.
|
||||
m.Run = throughBubblewrap(t, func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
modfile := filepath.Join(args[1], "go.mod")
|
||||
for _, e := range env {
|
||||
if flags, ok := strings.CutPrefix(e, "GOFLAGS="); ok {
|
||||
for _, f := range strings.Fields(flags) {
|
||||
if file, ok := strings.CutPrefix(f, "-modfile="); ok {
|
||||
modfile = file
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
body, err := os.ReadFile(modfile)
|
||||
if err != nil {
|
||||
return forgekey.Ran{Status: 1, Stderr: err.Error()}
|
||||
}
|
||||
if !strings.Contains(string(body), "replace "+sdk+" => "+own) {
|
||||
return forgekey.Ran{Status: 1, Stderr: "go: " + sdk + "@" + zeroVersion + ": module lookup disabled by GOPROXY=off"}
|
||||
}
|
||||
return forgekey.Ran{Stdout: strings.Join([]string{
|
||||
"git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry " + path + " git.novox.be/novox/mesh-delivery/modules/demo/go/clients/registry true",
|
||||
sdk + "/buildstep " + own + "/buildstep " + sdk + " false",
|
||||
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
|
||||
}, "\n")}
|
||||
}, &[]shutOff{})
|
||||
out, err := m.imports(context.Background(), map[string]any{"workspace": "ws1", "module": "modules/demo"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{sdk + "/buildstep", "git.novox.be/novox/mesh-sdk/go/stdio"}
|
||||
if got := out.(ImportsResult).Imports; !slices.Equal(got, want) {
|
||||
t.Errorf("imports %v, want %v: the sibling module's imports as the path's own module file resolves them", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// G2 (design 47 H2 H-A-532 DQ-5, H-A-518, H-A-541): a Go package artifact reports the packages the packages its paths
|
||||
// hold import, listed in the Go module each path is, without tests and without the module's own directory; a module
|
||||
// with both kinds reports one sorted union.
|
||||
func TestAPackageArtifactReportsItsImportSet(t *testing.T) {
|
||||
dir := "/w/ws1/tree/modules/contracts"
|
||||
pkg := `{"name":"seat","kind":"package","language":"go","paths":["go/seats/demo"],"series":"0.1"}`
|
||||
listed := map[string]string{
|
||||
dir + "/go/seats/demo ./...": strings.Join([]string{
|
||||
"encoding/json /usr/lib/go/src/encoding/json",
|
||||
"git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo " + dir + "/go/seats/demo git.novox.be/novox/mesh-catalog/modules/contracts/go/seats/demo true",
|
||||
"git.novox.be/novox/mesh-sdk/go/stdio /cache/mesh-sdk@v1/go/stdio git.novox.be/novox/mesh-sdk/go false",
|
||||
}, "\n"),
|
||||
dir + " ./cmd/demo-tools": "github.com/nats-io/nats.go /cache/nats.go github.com/nats-io/nats.go false",
|
||||
}
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
artifacts string
|
||||
want []string
|
||||
}{
|
||||
// G2/AC1: a contracts module whose artifact is of kind package.
|
||||
{"package", pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio"}},
|
||||
// G2/AC2: a module with a bundle and a package reports one sorted union.
|
||||
{"both", goBundle + "," + pkg, []string{"git.novox.be/novox/mesh-sdk/go/stdio", "github.com/nats-io/nats.go"}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
run := func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
line := args[1] + " " + args[len(args)-1]
|
||||
if slices.Contains(args, "-test") || args[2] != "list" {
|
||||
t.Errorf("go ran as %v: it lists dependencies without tests", args)
|
||||
}
|
||||
out, ok := listed[line]
|
||||
if !ok {
|
||||
t.Errorf("go list in %q, not asked", line)
|
||||
}
|
||||
return forgekey.Ran{Stdout: out}
|
||||
}
|
||||
m, err := catalogue.Decode([]byte(`{"module":"contracts","version":"1","build":{"artifacts":[` + c.artifacts + `]}}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := ModuleImports(context.Background(), run, noEnv, dir, m)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(got.Imports, c.want) {
|
||||
t.Errorf("imports %v, want %v", got.Imports, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,13 @@ func TestEveryStepEnvironmentSaysGotoolchainLocal(t *testing.T) {
|
||||
if got := toolchainValues(env); len(got) != 1 || got[0] != "GOTOOLCHAIN=local" {
|
||||
t.Errorf("%s: GOTOOLCHAIN settings %v, want exactly GOTOOLCHAIN=local", name, got)
|
||||
}
|
||||
// H-A-494: a step's own go commands reach no proxy (the test and lint steps, the compile); only the fetch's two
|
||||
// downloads do, each with its own.
|
||||
if strings.HasPrefix(name, "goEnv") {
|
||||
if got := proxyValues(env); len(got) != 1 || got[0] != "GOPROXY=off" {
|
||||
t.Errorf("%s: GOPROXY settings %v, want exactly GOPROXY=off", name, got)
|
||||
}
|
||||
}
|
||||
// Issue 1806: and its threads, its part of the node's processor cap (probeEnv runs no build).
|
||||
if procs := strings.Count(strings.Join(env, "\n"), "GOMAXPROCS="); name != "probeEnv" && procs != 1 {
|
||||
t.Errorf("%s: GOMAXPROCS said %d times, want once: %v", name, procs, env)
|
||||
|
||||
@@ -83,9 +83,9 @@ type Module struct {
|
||||
// Inside is the integration level's own process, started shut off in bubblewrap by a test step (level.go): its
|
||||
// commands run as they are, never shut off a second time.
|
||||
Inside bool
|
||||
// GoSeatFile is the binding of the provision go-package-registry, the Go seat's read side (design 51 *Go
|
||||
// packages*): bound, the mesh's Go modules are fetched through it first, Go's public proxy second, and the forge's
|
||||
// git over the account's ssh last (Go's direct, kept for this milestone only); unbound, as before, directly.
|
||||
// GoSeatFile is the binding of the provision go-package-registry, the Go package registry seat's read side (design
|
||||
// 51 *Go packages*): the mesh's Go packages are fetched through it alone (design 47 H, H-A-494); unbound, a fetch
|
||||
// that needs one refuses (errNoRegistry).
|
||||
GoSeatFile string
|
||||
// ArtifactStoreFile is the binding of the provision artifact-store, read for a group run's package members (§465).
|
||||
ArtifactStoreFile string
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
package main
|
||||
|
||||
// Pins on a pull request's head (novox/hq ADR 0482 §2, ADR 0500 §2; issue 1148): a group's Go members pin the head of
|
||||
// the group's mesh-sdk pull request, a commit that only refs/pull/<n>/head of the forge carries until the merge. Go
|
||||
// cannot fetch it by its pseudo-version, so a fetch that meets "unknown revision" for such a pin finds the commit among
|
||||
// the forge's pull request heads, places that repository beside the workspace as a plain directory, and hands it to
|
||||
// Go through a temporary -modfile, a copy of the directory's go.mod that replaces the module by that directory. The
|
||||
// fetch's go commands and the build use the same modfile, and the build still runs with GOPROXY=off. A pin Go can
|
||||
// fetch is not touched, and a directory that vendors is never resolved.
|
||||
// Pins on a pull request's head (novox/hq ADR 0482 §2, ADR 0500 §2, ADR 0573 §4; issue 1148): a group's check asks a
|
||||
// mesh package at the head of the group's pull request, a commit that only refs/pull/<n>/head of the forge carries until
|
||||
// the merge. The Go package registry does not hold it, so the fetch finds the commit among the forge's pull request
|
||||
// heads, places that repository beside the workspace as a plain directory, and hands it to Go through a temporary
|
||||
// -modfile, a copy of the directory's go.mod that replaces the module by that directory. The fetch's go commands and
|
||||
// the build use the same modfile, and the build still runs with GOPROXY=off. Only a pin the ask gives as a commit is
|
||||
// placed; a version a go.mod names is refused, never placed (design 47 H, H-A-494 second and third addenda), and a
|
||||
// directory that vendors is never resolved.
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -111,44 +112,6 @@ func (m *Module) pinModfile(dir string) (string, bool) {
|
||||
return p, err == nil
|
||||
}
|
||||
|
||||
// resolvePins resolves the pins of dir that a go command failed on: those whose commit the failure names. It answers
|
||||
// false when there is none, and the failure is then the caller's.
|
||||
func (m *Module) resolvePins(ctx context.Context, root, dir, failure string) (bool, error) {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "go.mod"))
|
||||
if err != nil {
|
||||
return false, nil
|
||||
}
|
||||
modfile, _ := m.pinModfile(dir)
|
||||
done := ""
|
||||
if modfile != "" {
|
||||
if b, err := os.ReadFile(modfile); err == nil {
|
||||
done = string(b)
|
||||
}
|
||||
}
|
||||
progress := false
|
||||
for _, p := range forgePins(string(raw)) {
|
||||
if p.short == zeroShort {
|
||||
continue // takeZeroPins': a requirement at the zero version names no commit to look for
|
||||
}
|
||||
if !strings.Contains(failure, p.short) || strings.Contains(done, "replace "+p.module+" =>") {
|
||||
continue
|
||||
}
|
||||
where, err := m.placePin(ctx, root, p, failure)
|
||||
if errors.Is(err, errNotAHead) {
|
||||
// On no pull request head: go's failure is the caller's, in go's own words (issue 1748).
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err := m.replaceInModfile(dir, p.module, where); err != nil {
|
||||
return false, err
|
||||
}
|
||||
progress = true
|
||||
}
|
||||
return progress, nil
|
||||
}
|
||||
|
||||
// errNotAHead is a pin whose commit no pull request head of the forge carries, when go's failure was not go knowing no
|
||||
// such revision: the failure is the network's or the forge's, and the caller says it in go's words (issue 1748).
|
||||
var errNotAHead = errors.New("on no pull request head")
|
||||
@@ -359,21 +322,72 @@ func (m *Module) takeZeroPins(ctx context.Context, root, repository, dir, d, fai
|
||||
return m.takeZeroRequirements(ctx, root, repository, dir, d, zeroRequirementsOf(dir), asked, pins)
|
||||
}
|
||||
|
||||
// takeReplacedZeroPins takes, before anything is downloaded, the requirements at the zero version that only a module
|
||||
// dir replaces by a directory names (zeroRequirementsOf): go mod download loads only what dir's own go.mod names, so it
|
||||
// passes without them, and the shut-off steps would look them up on the network (issue 1966). One the asked versions
|
||||
// took (before, takeVersions) is left as it is.
|
||||
func (m *Module) takeReplacedZeroPins(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, before []TakenVersion, pins *sync.Mutex) ([]TakenVersion, error) {
|
||||
var replaced []zeroRequirement
|
||||
// takeZeroPinsFirst takes or refuses, before anything else is downloaded, every requirement at the zero version of
|
||||
// dir's module graph (zeroRequirementsOf) the asked versions did not take (before, takeVersions): dir's own, and those
|
||||
// only a module dir replaces by a directory names, which go mod download would not miss and the shut-off steps would
|
||||
// look up on the network (issue 1966). So no forge path reaches the second download, the public proxy's, first (design
|
||||
// 47 H, H-A-494 third addendum).
|
||||
func (m *Module) takeZeroPinsFirst(ctx context.Context, root, repository, dir, d string, asked sdkstep.PackageVersions, before []TakenVersion, pins *sync.Mutex) ([]TakenVersion, error) {
|
||||
raw, _ := os.ReadFile(filepath.Join(dir, "go.mod"))
|
||||
_, replaced := goModRequirements(string(raw))
|
||||
var reqs []zeroRequirement
|
||||
for _, r := range zeroRequirementsOf(dir) {
|
||||
if r.by != "" && !slices.ContainsFunc(before, func(tv TakenVersion) bool { return tv.Package == r.module }) {
|
||||
replaced = append(replaced, r)
|
||||
// One dir's go.mod replaces is decided by its replace.
|
||||
if !replaced[r.module] && !slices.ContainsFunc(before, func(tv TakenVersion) bool { return tv.Package == r.module }) {
|
||||
reqs = append(reqs, r)
|
||||
}
|
||||
}
|
||||
if len(replaced) == 0 {
|
||||
if len(reqs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return m.takeZeroRequirements(ctx, root, repository, dir, d, replaced, asked, pins)
|
||||
return m.takeZeroRequirements(ctx, root, repository, dir, d, reqs, asked, pins)
|
||||
}
|
||||
|
||||
// namedForgeVersion refuses a mesh package (a module of the forge) that dir's module graph names at a version other
|
||||
// than the zero version (ADR 0573 §4; design 47 H, H-A-494 second addendum), in the graph zeroRequirementsOf reads: dir's
|
||||
// go.mod, then each module it replaces by a directory. A module of the checked repository (built from its tree) and one
|
||||
// dir's go.mod replaces are left out. The first such requirement is named, before either download.
|
||||
func namedForgeVersion(repository, dir string) error {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "go.mod"))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
_, replaced := goModRequirements(string(raw))
|
||||
check := func(gomod string) error {
|
||||
required, _ := goModRequirements(gomod)
|
||||
for _, pkg := range slices.Sorted(maps.Keys(required)) {
|
||||
v := required[pkg]
|
||||
if !strings.HasPrefix(pkg, forgePrefix) || v == zeroVersion || replaced[pkg] || sameRepository(pkg, repository) {
|
||||
continue
|
||||
}
|
||||
return fmt.Errorf("%s names %s@%s; a mesh package is required at the zero version", modulePathOf(gomod), pkg, v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := check(string(raw)); err != nil {
|
||||
return err
|
||||
}
|
||||
local := localReplaces(string(raw))
|
||||
for _, module := range slices.Sorted(maps.Keys(local)) {
|
||||
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(local[module]), "go.mod"))
|
||||
if err != nil {
|
||||
continue // a replace to a directory with no go.mod: Go says so in its own words
|
||||
}
|
||||
if err := check(string(b)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// modulePathOf is the module path a go.mod declares, "" when it declares none.
|
||||
func modulePathOf(gomod string) string {
|
||||
for _, line := range strings.Split(gomod, "\n") {
|
||||
if f := strings.Fields(line); len(f) >= 2 && f[0] == "module" {
|
||||
return strings.Trim(f[1], `"`)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// takeZeroRequirements takes, for each requirement at the zero version, the version it is built against (ADR 0573 §2,
|
||||
|
||||
@@ -17,9 +17,9 @@ import (
|
||||
)
|
||||
|
||||
// 1148/AC2 as issue 1585 S15 has it (novox/hq ADR 0573 §4): given a forge with a mesh-sdk-like pull request whose branch
|
||||
// is deleted (only refs/pull/7/head carries its commit) and a Go member whose go.mod names an older commit of it, when
|
||||
// is deleted (only refs/pull/7/head carries its commit) and a Go member whose go.mod names it at the zero version, when
|
||||
// build_go_fetch is asked that head as the package's version and build_go_build runs on the member, then both pass, the
|
||||
// build with GOPROXY=off against the head: the older commit holds no Go package at all.
|
||||
// build with GOPROXY=off against the head (a go.mod names a mesh package at the zero version only, design 47 H, H-A-494).
|
||||
func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.T) {
|
||||
t.Parallel()
|
||||
// Not skipped when a tool is missing: a pass of the check must mean this test ran (the check prints no test log).
|
||||
@@ -36,7 +36,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.
|
||||
}, "refs/pull/7/head")
|
||||
git(t, work, "checkout", "-q", "main") // no branch of the repository carries the head
|
||||
member := map[string]string{
|
||||
"go.mod": "module fixture/member\n\ngo 1.25.0\n\nrequire git.novox.be/novox/dep/go v0.0.0-20261021120000-" + fork[:12] + "\n",
|
||||
"go.mod": "module fixture/member\n\ngo 1.25.0\n\nrequire git.novox.be/novox/dep/go " + zeroVersion + "\n",
|
||||
"cmd/prog/main.go": "package main\n\nimport (\n\t\"fmt\"\n\n\tdep \"git.novox.be/novox/dep/go\"\n)\n\n" +
|
||||
"func main() { fmt.Println(dep.Name) }\n",
|
||||
"module.json": `{"module":"fixture-member","version":"1","build":{"artifacts":[{"name":"tools","kind":"bundle","language":"go","system":"arch","from":"cmd/prog","binary":"prog-bin","loads":["prog-bin"]}]}}`,
|
||||
@@ -50,7 +50,7 @@ func TestRealFetchAndBuildOfAMemberAskedAPullHeadItsGoModDoesNotName(t *testing.
|
||||
if st.State != sdkstep.StepPassed {
|
||||
t.Fatalf("the fetch ended %s: %s", st.State, st.Reason)
|
||||
}
|
||||
if len(res.Packages) != 1 || res.Packages[0].Built != head || res.Packages[0].Named != "v0.0.0-20261021120000-"+fork[:12] {
|
||||
if len(res.Packages) != 1 || res.Packages[0].Built != head || res.Packages[0].Named != zeroVersion {
|
||||
t.Errorf("the fetch names what it built against: %+v, want the asked head %s", res.Packages, head)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(m.Work, res.Workspace, "pinned", "dep@"+head, "beside", "dep", "go", "dep.go")); err != nil {
|
||||
|
||||
@@ -18,7 +18,11 @@ import (
|
||||
// pinShort is the 12 digits of commitSHA a pseudo-version ends in.
|
||||
const pinShort = "0123456789ab"
|
||||
|
||||
const pinnedGoMod = "module fixture/member\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go v0.1.15-0.20261022120000-" + pinShort + "\n)\n"
|
||||
// pinnedGoMod requires mesh-sdk at the zero version (ADR 0573 §4); the ask pins it (pinAsk).
|
||||
const pinnedGoMod = "module fixture/member\n\ngo 1.26\n\nrequire (\n\tgit.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-" + zeroShort + "\n)\n"
|
||||
|
||||
// pinAsk asks mesh-sdk at the head of a group's pull request, commitSHA: only refs/pull/7/head of pullList carries it.
|
||||
var pinAsk = map[string]any{"git.novox.be/novox/mesh-sdk/go": commitSHA}
|
||||
|
||||
// pinHarness runs a fetch of a tree whose only go.mod is gomod (a vendoring one when vendor is set) against a runner
|
||||
// that stands for the forge and for go: a pull request's head is listed by ls-remote when pulls says so, and go mod
|
||||
@@ -84,7 +88,7 @@ func (h *pinHarness) fetch(states *keptStates) (FetchResult, sdkstep.Step) {
|
||||
h.t.Helper()
|
||||
// A member of a repository other than mesh-sdk's, whose packages it pins: one of its own repository is built from the
|
||||
// tree (S31).
|
||||
if _, err := fetchTool(h.t, h.m)(map[string]any{"repository": "novox/mesh-member", "commit": commitSHA}); err != nil {
|
||||
if _, err := fetchTool(h.t, h.m)(map[string]any{"repository": "novox/mesh-member", "commit": commitSHA, "packages": pinAsk}); err != nil {
|
||||
h.t.Fatal(err)
|
||||
}
|
||||
st := states.waitEnd(h.t)
|
||||
@@ -149,26 +153,40 @@ func TestAPinOnAPullHeadIsPlacedBesideAndHandedToGoByAModfile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 1148/AC3: a pin go downloads as it is (on the trunk or a tag) behaves as today: no listing of pull requests, no
|
||||
// repository placed, no -modfile in the fetch or the build.
|
||||
func TestAPinGoCanDownloadIsLeftAsToday(t *testing.T) {
|
||||
h, states := newPinHarness(t, pinnedGoMod, false, pullList)
|
||||
h.onTrunk = true
|
||||
res, st := h.fetch(states)
|
||||
if st.State != sdkstep.StepPassed {
|
||||
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
|
||||
// H-A-494 second addendum: a go.mod naming a mesh package at a version other than the zero version (a pseudo-version, a
|
||||
// release) is refused before either download, naming the module and the version, whether its own go.mod names it or a
|
||||
// module it replaces by a directory; a module of the checked repository, and one the go.mod replaces, are not refused.
|
||||
func TestAMeshPackageNamedAtARealVersionIsRefusedBeforeEitherDownload(t *testing.T) {
|
||||
const sdk = "git.novox.be/novox/mesh-sdk/go"
|
||||
for _, c := range []struct{ name, gomod, sib, refused string }{
|
||||
{name: "a pseudo-version", gomod: "module fixture/member\n\nrequire " + sdk + " v0.1.15-0.20261022120000-" + pinShort + "\n",
|
||||
refused: "fixture/member names " + sdk + "@v0.1.15-0.20261022120000-" + pinShort + "; a mesh package is required at the zero version"},
|
||||
{name: "a release named by a module it replaces", gomod: "module fixture/member\n\nrequire fixture/sib " + zeroVersion + "\n\nreplace fixture/sib => ./sib\n",
|
||||
sib: "module fixture/sib\n\nrequire " + sdk + " v0.1.85\n", refused: "fixture/sib names " + sdk + "@v0.1.85"},
|
||||
{name: "replaced by the go.mod", gomod: "module fixture/member\n\nrequire " + sdk + " v0.1.85\n\nreplace " + sdk + " => ./sdk\n"},
|
||||
{name: "of the checked repository", gomod: "module fixture/member\n\nrequire git.novox.be/novox/mesh-member/go v0.1.85\n"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
os.WriteFile(filepath.Join(dir, "go.mod"), []byte(c.gomod), 0o644)
|
||||
if c.sib != "" {
|
||||
os.MkdirAll(filepath.Join(dir, "sib"), 0o755)
|
||||
os.WriteFile(filepath.Join(dir, "sib", "go.mod"), []byte(c.sib), 0o644)
|
||||
}
|
||||
err := namedForgeVersion("novox/mesh-member", dir)
|
||||
if (err != nil) != (c.refused != "") || (err != nil && !strings.Contains(err.Error(), c.refused)) {
|
||||
t.Fatalf("refused: %v, want %q", err, c.refused)
|
||||
}
|
||||
})
|
||||
}
|
||||
if h.ran("ls-remote") || h.ran("pinned") {
|
||||
t.Errorf("a pin on the trunk made the fetch look for a pull request or place a repository:\n%s", strings.Join(h.f.lines(), "\n"))
|
||||
// In a fetch: the step fails so, and runs no download at all.
|
||||
h, states := newPinHarness(t, "module fixture/member\n\nrequire "+sdk+" v0.1.85\n", false, pullList)
|
||||
_, st := h.fetch(states)
|
||||
if st.State != sdkstep.StepFailed || !strings.Contains(st.Reason, "fixture/member names "+sdk+"@v0.1.85; a mesh package is required at the zero version") {
|
||||
t.Fatalf("the step ended %s: %q", st.State, st.Reason)
|
||||
}
|
||||
dir := filepath.Join(h.m.Work, res.Workspace, "tree")
|
||||
for _, e := range append(h.m.goEnvFor(dir), h.m.buildEnv(dir)...) {
|
||||
if strings.Contains(e, "-modfile") {
|
||||
t.Errorf("a -modfile is handed to go: %s", e)
|
||||
}
|
||||
}
|
||||
if !h.ran(" mod download") || !h.ran(" mod verify") {
|
||||
t.Errorf("go mod download and verify did not run as before")
|
||||
if h.ran(" mod download") || h.ran("ls-remote") {
|
||||
t.Errorf("a download or a listing ran before the refusal:\n%s", strings.Join(h.f.lines(), "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,42 +243,6 @@ func TestTwoDirectoriesPinningOneHeadShareOneCopy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 1148/AC1: two directories pinning two different commits of one repository get two copies, each its own.
|
||||
func TestTwoCommitsOfOneRepositoryGetTwoCopies(t *testing.T) {
|
||||
other := "fedcba9876543210fedcba9876543210fedcba98"
|
||||
h, states := newPinHarness(t, pinnedGoMod, false, commitSHA+"\trefs/pull/7/head\n"+other+"\trefs/pull/8/head\n")
|
||||
h.f.gomods = "go.mod\nsub/go.mod\n"
|
||||
base := h.m.Run
|
||||
h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
if name == "git" && strings.Contains(strings.Join(args, " "), "pinned/mesh-sdk@"+other+"/") && strings.Contains(strings.Join(args, " "), " rev-parse HEAD") {
|
||||
return forgekey.Ran{Stdout: other + "\n"}
|
||||
}
|
||||
// the second directory pins the other commit
|
||||
if name == "git" && strings.Contains(strings.Join(args, " "), " checkout ") && !strings.Contains(strings.Join(args, " "), "pinned") {
|
||||
r := base(ctx, env, name, args...)
|
||||
for i, a := range args {
|
||||
if a == "-C" {
|
||||
os.WriteFile(filepath.Join(args[i+1], "sub", "go.mod"), []byte(strings.ReplaceAll(pinnedGoMod, pinShort, other[:12])), 0o644)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
if name == "go" && strings.Contains(strings.Join(args, " "), "/sub mod download") && !strings.Contains(strings.Join(env, " "), "-modfile=") {
|
||||
return forgekey.Ran{Status: 1, Stderr: "go: git.novox.be/novox/mesh-sdk/go@v0.1.15-0.20261022120000-" + other[:12] + ": invalid version: unknown revision " + other[:12] + "\n"}
|
||||
}
|
||||
return base(ctx, env, name, args...)
|
||||
}
|
||||
_, st := h.fetch(states)
|
||||
if st.State != sdkstep.StepPassed {
|
||||
t.Fatalf("the step ended %s: %s", st.State, st.Reason)
|
||||
}
|
||||
for _, c := range []string{commitSHA, other} {
|
||||
if !h.ran("pinned/mesh-sdk@" + c) {
|
||||
t.Errorf("no copy of mesh-sdk at %s", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A relative replace of a go.mod (a package of the module's own repository in a sibling directory, ADR 0593 §1) must still
|
||||
// resolve in the temporary modfile, which `go mod verify` runs in its own directory: every relative target is made absolute
|
||||
// under the tree it came from. The route-proxy failure of 2026-11-02 13:53 was a ./ replace met there; this takes real go.
|
||||
@@ -340,8 +322,13 @@ func TestARequirementAtTheZeroVersionIsTakenFromItsPinOrRefused(t *testing.T) {
|
||||
}
|
||||
h, states := newPinHarness(t, gomod, false, pullList)
|
||||
base := h.m.Run
|
||||
var mu sync.Mutex
|
||||
var ran []string // every command, in order
|
||||
h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
line := name + " " + strings.Join(args, " ")
|
||||
mu.Lock()
|
||||
ran = append(ran, line)
|
||||
mu.Unlock()
|
||||
switch {
|
||||
case c.replaced && name == "git" && strings.Contains(line, " checkout "):
|
||||
r := base(ctx, env, name, args...)
|
||||
@@ -381,6 +368,12 @@ func TestARequirementAtTheZeroVersionIsTakenFromItsPinOrRefused(t *testing.T) {
|
||||
if h.ran(" mod download -json " + sdk + "@") {
|
||||
t.Errorf("go was asked for a version of %s with no pin:\n%s", sdk, strings.Join(h.f.lines(), "\n"))
|
||||
}
|
||||
// H-A-494 third addendum: refused before any download of the rest, so no forge path reaches the public proxy.
|
||||
for _, line := range ran {
|
||||
if strings.HasSuffix(line, " mod download") {
|
||||
t.Errorf("the rest was downloaded before the refusal: %s", line)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
if st.State != sdkstep.StepPassed {
|
||||
|
||||
@@ -127,9 +127,18 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
|
||||
tagged := sdkstep.PackageSemver.MatchString(tv.Asked)
|
||||
var r forgekey.Ran
|
||||
var info downloadInfo
|
||||
r = m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "download", "-json", tv.Package+"@"+tv.Asked)
|
||||
// The first download: a mesh package from the Go package registry seat alone (design 47 H, H-A-494 and its addendum).
|
||||
env, err := m.registryEnv(m.goEnv())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s@%s: %w", tv.Package, tv.Asked, err)
|
||||
}
|
||||
r = m.Run(ctx, env, "go", "-C", pinsDir, "mod", "download", "-json", tv.Package+"@"+tv.Asked)
|
||||
_ = json.Unmarshal([]byte(r.Stdout), &info)
|
||||
failed := r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != ""
|
||||
if failed && registryMiss(info.Error+"\n"+r.Err+"\n"+r.Stderr) && !commitOK.MatchString(tv.Asked) {
|
||||
// Only a commit may still be a pull request's head (placePin); any other version the seat does not hold is its miss.
|
||||
return registryMissed(tv.Package, tv.Asked, info.Error+"\n"+r.Err+"\n"+r.Stderr)
|
||||
}
|
||||
if failed && tagged {
|
||||
failure := strings.TrimSpace(info.Error + "\n" + r.Err + "\n" + r.Stderr)
|
||||
return downloadFailure(failure, "downloading the group's tagged version %s of %s through the Go seat failed", tv.Asked, tv.Package)
|
||||
@@ -148,6 +157,9 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
|
||||
where, err := m.placePin(ctx, root, p, failure)
|
||||
if errors.Is(err, errNotAHead) {
|
||||
pins.Unlock()
|
||||
if registryMiss(failure) {
|
||||
return registryMissed(tv.Package, tv.Asked, failure)
|
||||
}
|
||||
// On no head, and go failed for another cause (the forge or the resolver did not answer): it fails with go's own
|
||||
// words, and not as a kind the builder holds until the module changes (issue 1748).
|
||||
return downloadFailure(failure, "downloading the asked version %s of %s failed", tv.Asked, tv.Package)
|
||||
@@ -188,6 +200,12 @@ func (m *Module) takeVersion(ctx context.Context, root, dir string, tv *TakenVer
|
||||
return m.takeRequirementsOf(ctx, pinsDir, info.GoMod)
|
||||
}
|
||||
|
||||
// registryMissed is the first download's miss: the Go package registry seat holds no such version of the package, said
|
||||
// in the module's words with Go's beside them (design 47 H, H-A-494: a missing version fails loudly as the registry's miss).
|
||||
func registryMissed(pkg, version, failure string) error {
|
||||
return fmt.Errorf("the Go package registry holds no %s@%s: %s", pkg, version, causeLine(strings.TrimSpace(failure)))
|
||||
}
|
||||
|
||||
// appendSums writes the checksums of one download (the module's and its go.mod's) into the go.sum in pinsDir.
|
||||
func appendSums(pinsDir, module string, info downloadInfo) error {
|
||||
sums := ""
|
||||
@@ -232,7 +250,8 @@ func (m *Module) takeRequirementsOf(ctx context.Context, pinsDir, gomodPath stri
|
||||
if strings.HasPrefix(module, forgePrefix) || (named[module] != "" && compareVersions(named[module], version) >= 0) {
|
||||
continue
|
||||
}
|
||||
r := m.Run(ctx, m.goEnv(), "go", "-C", pinsDir, "mod", "download", "-json", module+"@"+version)
|
||||
// Never a module of the forge (above): the rest of the build list, through Go's public proxy alone (publicEnv).
|
||||
r := m.Run(ctx, publicEnv(m.goEnv()), "go", "-C", pinsDir, "mod", "download", "-json", module+"@"+version)
|
||||
var info downloadInfo
|
||||
_ = json.Unmarshal([]byte(r.Stdout), &info)
|
||||
if r.Status != 0 || r.Err != "" || info.Version == "" || info.Error != "" {
|
||||
|
||||
@@ -32,6 +32,7 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
passing bool // the step ends failed as a transport fault, which the bus gives again (ADR 0664 §1)
|
||||
downloads int // the downloads asked in all (0: not counted)
|
||||
requires string // the go.mod of the version taken, its requirements to be taken too
|
||||
unbound bool // the module holds no binding of the Go package registry seat
|
||||
}{
|
||||
{name: "a trunk commit newer than go.mod's", asked: trunk,
|
||||
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod="}`,
|
||||
@@ -42,9 +43,6 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
answer: `{"Path":"` + sdk + `","Version":"v0.1.16-0.20261116170327-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod=","GoMod":"GOMOD"}`,
|
||||
built: "v0.1.16-0.20261116170327-aaaaaaaaaaaa", edit: "-require=" + sdk + "@v0.1.16-0.20261116170327-aaaaaaaaaaaa",
|
||||
requires: "module " + sdk + "\n\ngo 1.26\n\nrequire (\n\tgithub.com/nats-io/nats.go v1.54.0\n\tgithub.com/klauspost/compress v1.20.0\n\tgit.novox.be/novox/mesh-contracts/go/x v0.1.0\n)\n"},
|
||||
{name: "go.mod names a newer one", asked: trunk,
|
||||
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261001000000-aaaaaaaaaaaa","Sum":"h1:zip="}`,
|
||||
built: "v0.1.15-0.20261022120000-" + pinShort, said: "newer than the asked"},
|
||||
{name: "a group's head Go cannot fetch", asked: commitSHA, failing: true,
|
||||
answer: `{"Path":"` + sdk + `","Error":"invalid version: unknown revision ` + pinShort + `"}`,
|
||||
built: commitSHA, said: "placed from the pull request's head"},
|
||||
@@ -70,11 +68,17 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
{name: "a group's tagged version", asked: "v0.1.15-feat-x.2",
|
||||
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-feat-x.2","Sum":"h1:zip=","GoModSum":"h1:mod="}`,
|
||||
built: "v0.1.15-feat-x.2", edit: "-require=" + sdk + "@v0.1.15-feat-x.2"},
|
||||
{name: "a group's tagged version older than go.mod's", asked: "v0.1.14-feat-x.2",
|
||||
answer: `{"Path":"` + sdk + `","Version":"v0.1.14-feat-x.2","Sum":"h1:zip=","GoModSum":"h1:mod="}`,
|
||||
built: "v0.1.14-feat-x.2", said: "the group's tagged version", edit: "-require=" + sdk + "@v0.1.14-feat-x.2"},
|
||||
{name: "a tagged version the Go seat lacks", asked: "v0.1.15-feat-x.3", failing: true, failsWith: "the group's tagged version v0.1.15-feat-x.3",
|
||||
// H-A-494: a version the Go package registry seat does not hold fails as its miss, naming <pkg>@<v>: the seat's 404,
|
||||
// or, as Go words it with off behind the seat, the lookup off; a commit only once no pull request head carries it.
|
||||
{name: "a tagged version the Go seat lacks", asked: "v0.1.15-feat-x.3", failing: true, failsWith: "the Go package registry holds no " + sdk + "@v0.1.15-feat-x.3",
|
||||
answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@v0.1.15-feat-x.3: reading https://seat/go/@v/v0.1.15-feat-x.3.info: 404 Not Found"}`},
|
||||
{name: "a release the Go seat lacks", asked: "v0.1.85", failing: true, failsWith: "the Go package registry holds no " + sdk + "@v0.1.85", downloads: 1,
|
||||
answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@v0.1.85: module lookup disabled by GOPROXY=off"}`},
|
||||
{name: "a commit the Go seat lacks on no head", asked: offHead, failing: true, failsWith: "the Go package registry holds no " + sdk + "@" + offHead, downloads: 1,
|
||||
answer: `{"Path":"` + sdk + `","Error":"` + sdk + `@` + offHead + `: module lookup disabled by GOPROXY=off"}`},
|
||||
// H-A-494: with no binding of the seat, a mesh package is fetched from nowhere else: the fetch refuses.
|
||||
{name: "no Go package registry bound", asked: trunk, unbound: true, failsWith: "no Go package registry bound",
|
||||
answer: `{"Path":"` + sdk + `","Version":"v0.1.15-0.20261101000000-aaaaaaaaaaaa","Sum":"h1:zip=","GoModSum":"h1:mod="}`},
|
||||
// ADR 0664 §1 (issue 1748): one download; a failure of the network is a transport fault the bus gives the ask again for after a
|
||||
// delay, no retry here; another failure is not one.
|
||||
{name: "an unknown revision is not taken again", asked: offHead, failing: true, failsWith: "on no pull request head", downloads: 1,
|
||||
@@ -85,6 +89,9 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
h, states := newPinHarness(t, pinnedGoMod, false, pullList)
|
||||
h.f.gomods = "go.mod\nother/go.mod\n"
|
||||
if c.unbound {
|
||||
h.m.GoSeatFile = ""
|
||||
}
|
||||
downloads := 0
|
||||
base := h.m.Run
|
||||
h.m.Run = func(ctx context.Context, env []string, name string, args ...string) forgekey.Ran {
|
||||
@@ -130,6 +137,14 @@ func TestAnAskedVersionIsWrittenIntoTheModfileWhateverGoModNames(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := states.waitEnd(t)
|
||||
// H-A-494 addendum: a mesh package is downloaded from the Go package registry seat alone, off behind it.
|
||||
for _, cmd := range h.cmds {
|
||||
if strings.Contains(cmd.line, " mod download -json "+sdk+"@") {
|
||||
if got := proxyValues(cmd.env); len(got) != 1 || got[0] != "GOPROXY="+testRegistry+",off" {
|
||||
t.Errorf("%s: GOPROXY settings %v, want the seat alone and off", cmd.line, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.downloads != 0 && downloads != c.downloads {
|
||||
t.Errorf("go downloaded %d times, want %d: no retry here", downloads, c.downloads)
|
||||
}
|
||||
|
||||
@@ -167,7 +167,8 @@ func (m *Module) downloadBeside(ctx context.Context, root, tree string, dirs []s
|
||||
if err := os.WriteFile(file, []byte(work), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
env := append(m.goEnv(), "GOWORK="+file, "GOFLAGS=-mod=readonly") // a workspace takes no -mod=mod
|
||||
// The rest of a build list: through Go's public proxy alone (publicEnv; design 47 H, H-A-494 addendum).
|
||||
env := publicEnv(append(m.goEnv(), "GOWORK="+file, "GOFLAGS=-mod=readonly")) // a workspace takes no -mod=mod
|
||||
if res := m.Run(ctx, env, "go", "-C", r, "mod", "download"); res.Status != 0 || res.Err != "" {
|
||||
return fmt.Errorf("go mod download of the graph of %s beside: %s", filepath.Base(r), causeLine(res.Err+"\n"+res.Stdout+"\n"+res.Stderr))
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
|
||||
seat "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode"
|
||||
buildrun "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildrun"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
@@ -32,6 +33,9 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
}
|
||||
return steprun.AskSteps{
|
||||
Fetch: byName["build_node_fetch"], Build: byName["build_node_build"], Test: byName["build_node_test"],
|
||||
// The npm packages its bundles import, read after the build and said as imports-reported (design 47 H2 H-A-523,
|
||||
// H-A-532 DQ-6, H-A-539).
|
||||
Imports: byName[ImportsTool],
|
||||
Compare: steprun.CompareStep(steprun.GeneratedRootTS, func(ws string) string { return filepath.Join(m.Work, ws, "tree") }),
|
||||
Toolchain: func(ctx context.Context) (sdkstep.ToolchainUsed, error) {
|
||||
installed, err := m.Probe(ctx)
|
||||
@@ -47,10 +51,22 @@ func (m *Module) askSteps(steps []StepTool) steprun.AskSteps {
|
||||
Lint: m.lintStep,
|
||||
Node: m.Node,
|
||||
SayStep: m.sayStep(),
|
||||
Outputs: m.outputs(),
|
||||
// A build that read its imports says them as the seat's imports-reported on this node (design 47 H2 H-A-517,
|
||||
// H-A-532 DQ-2, DMC-2), published as the puller's other events are (SayEvent; nil says none, a test's).
|
||||
SayImports: m.sayImports(),
|
||||
Outputs: m.outputs(),
|
||||
}
|
||||
}
|
||||
|
||||
// sayImports says a build's import set on this node's subject of the seat (design 47 H2 H-A-517, H-A-532 DQ-2), with
|
||||
// SayEvent; nil when the module says no event.
|
||||
func (m *Module) sayImports() func(nodebuildgo.ImportsReported) error {
|
||||
if m.SayEvent == nil {
|
||||
return nil
|
||||
}
|
||||
return steprun.SayImportsOn(sdkstep.AskNode, m.Node, m.SayEvent)
|
||||
}
|
||||
|
||||
// outputs are the outputs objects a test step keeps its run's output in and the verb output reads (design 47 H2 §791,
|
||||
// §820): Outputs when a test sets it, else the module's own objects store on the bus.
|
||||
func (m *Module) outputs() steprun.OutputObjects {
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
nodebuildgo "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo"
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
"git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/steprun"
|
||||
)
|
||||
@@ -28,3 +32,43 @@ func TestPullerSaysTheSeatsEventsOnItsNodesSubject(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// N1/AC1, N1/AC3 (design 47 H2 H-A-517, H-A-523, H-A-534): a done build of a TypeScript module says one imports-reported
|
||||
// on the Node build seat's subject of the node, naming the mesh npm packages the imports step read; a failed build says
|
||||
// none.
|
||||
func TestADoneNodeBuildSaysItsImportSetAndAFailedOneNone(t *testing.T) {
|
||||
var said []nodebuildgo.ImportsReported
|
||||
var subjects []string
|
||||
m := moduleWith(newStates(), "v26.10.0")
|
||||
m.Outputs = kitObjects{} // a failed build keeps its error text as an output object, never on a bus here
|
||||
m.SayEvent = func(subject string, body any, _ string) error {
|
||||
subjects = append(subjects, subject)
|
||||
said = append(said, body.(nodebuildgo.ImportsReported))
|
||||
return nil
|
||||
}
|
||||
steps := append(fakeSteps(new([]string)), StepTool{Name: ImportsTool, Run: func(context.Context, map[string]any) (any, error) {
|
||||
return ImportsResult{Imports: []string{"@novox/mesh-sdk"}}, nil
|
||||
}})
|
||||
a := nodeAsk(sdkstep.AskDelivery)
|
||||
a.Build.Fp = "src2:0456"
|
||||
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "mesh.seat.node-build-node.event.imports-reported.ace"
|
||||
if len(said) != 1 || subjects[0] != want || said[0].Module != "gitea" || said[0].Fingerprint != "src2:0456" ||
|
||||
said[0].Commit != askCommit || !slices.Equal(said[0].Imports, []string{"@novox/mesh-sdk"}) {
|
||||
t.Fatalf("said %v on %v, want one imports-reported of gitea naming @novox/mesh-sdk on %s", said, subjects, want)
|
||||
}
|
||||
said = nil
|
||||
for i := range steps {
|
||||
if steps[i].Name == "build_node_build" {
|
||||
steps[i].Run = func(context.Context, map[string]any) (any, error) { return nil, errors.New("tsc failed") }
|
||||
}
|
||||
}
|
||||
if _, err := steprun.RunAsk(context.Background(), m.askSteps(steps), a); err == nil {
|
||||
t.Fatal("the failed build passed")
|
||||
}
|
||||
if len(said) != 0 {
|
||||
t.Errorf("a failed build said %v", said)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,6 +115,10 @@ func TestManifestTakesTheBuildCapacity(t *testing.T) {
|
||||
if strings.Contains(doc.Config[steprun.BuildHoursSetting].Description, "=") {
|
||||
t.Errorf("the build-hours description names a node pair")
|
||||
}
|
||||
// Design 47 H2 H-A-539: no scope tells a mesh package apart, so the module declares no setting import-scope.
|
||||
if _, ok := doc.Config["import-scope"]; ok {
|
||||
t.Errorf("the manifest declares import-scope, which H-A-539 withdrew")
|
||||
}
|
||||
var capacity float64
|
||||
_ = json.Unmarshal(doc.Config[sdkstep.CapacitySetting].Default, &capacity)
|
||||
if capacity != 0 {
|
||||
|
||||
@@ -89,7 +89,8 @@ var fetchedSDK = map[string]string{
|
||||
// fixture pass the unit level; a package whose test imports its own build output (as mesh-sdk's do) passes the unit level,
|
||||
// the test step emitting it with the real tsc, shut off, before the test script runs; and the fixture TypeScript bundle
|
||||
// importing @novox/mesh-sdk, built twice by the real tsc and esbuild, has equal digests, its archive holding the bundled
|
||||
// .js, the .serve.mjs launcher and package.json. The unit levels run in w3, so the two builds' workspaces stay alike.
|
||||
// .js, the .serve.mjs launcher and package.json, and its imports step names the SDK. The unit levels run in w3, so the
|
||||
// two builds' workspaces stay alike.
|
||||
func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
|
||||
m, work := realMachine(t)
|
||||
out, err := m.test(context.Background(), map[string]any{"workspace": "w3", "module": "modules/m", "level": "unit"})
|
||||
@@ -130,6 +131,15 @@ func TestTheFixturePassesTheUnitLevelAndBuildsTwiceToOneDigest(t *testing.T) {
|
||||
if digests[0] != digests[1] {
|
||||
t.Errorf("digests differ: %v", digests)
|
||||
}
|
||||
// N1/AC1 (design 47 H2 H-A-523, H-A-532 DQ-6): the real esbuild's metafile of the built bundle names the SDK it
|
||||
// imports, by its package name.
|
||||
out, err = m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := out.(ImportsResult).Imports; !slices.Equal(got, []string{"@novox/mesh-sdk"}) {
|
||||
t.Errorf("the bundle's imports = %v, want [@novox/mesh-sdk]", got)
|
||||
}
|
||||
if links := symlinksUnder(t, work); len(links) != 0 {
|
||||
t.Errorf("symlinks in the workspaces: %v", links)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"maps"
|
||||
"os"
|
||||
@@ -361,3 +362,73 @@ func TestTheBundleCarriesTheAsksVersionInItsPackageJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// N1/AC1, N1/AC2 (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): after a bundle's build, the imports step runs esbuild
|
||||
// over the staged entrypoint and launcher with a metafile and answers every npm package among its inputs and external
|
||||
// imports, each by its package name once (the SDK's stdio sub-path is the SDK), with no scope filter: a mesh package is
|
||||
// told apart by the indexer, never by its scope. Node's own modules (node:module, fs) are no package; a bundle reaching
|
||||
// only those answers none. Node's own modules are the probed toolchain's module.builtinModules, read at the step
|
||||
// (principle 11), here holding sqlite, which no fixed list of Node 22 holds.
|
||||
func TestTheImportsStepNamesTheNpmPackagesABundleReaches(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
metafile string
|
||||
want []string
|
||||
}{
|
||||
{"packages", `{"inputs":{
|
||||
".mesh-build/tools/tools/index.js":{"imports":[{"path":"../../node_modules/@novox/mesh-sdk/dist/stdio.js"},{"path":"@novox/mesh-other/x","external":true},{"path":"pg","external":true},{"path":"node:module","external":true},{"path":"fs","external":true},{"path":"sqlite","external":true}]},
|
||||
"../../node_modules/@novox/mesh-sdk/dist/stdio.js":{"imports":[]},
|
||||
"../../node_modules/@novox/mesh-sdk/dist/index.js":{"imports":[]},
|
||||
"../../node_modules/nats/lib/index.js":{"imports":[]}}}`, []string{"@novox/mesh-other", "@novox/mesh-sdk", "nats", "pg"}},
|
||||
{"none", `{"inputs":{".mesh-build/tools/tools/index.js":{"imports":[{"path":"node:module","external":true},{"path":"path","external":true}]}}}`, []string{}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
m, f, work := builtMachine(t, `,"external":["pg"]`)
|
||||
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs", "module", "path", "sqlite"}, nil }
|
||||
bundled := f.effect
|
||||
var metaRun []string
|
||||
f.effect = func(cl call) {
|
||||
bundled(cl)
|
||||
for _, a := range cl.args {
|
||||
if p, ok := strings.CutPrefix(a, "--metafile="); ok {
|
||||
metaRun = cl.args
|
||||
write(t, filepath.Join(cl.dir, p), c.metafile, 0o644)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := m.build(context.Background(), buildArgs()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if metaRun != nil {
|
||||
t.Fatalf("the build itself ran esbuild with a metafile: %v", metaRun)
|
||||
}
|
||||
out, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := out.(ImportsResult).Imports; !slices.Equal(got, c.want) {
|
||||
t.Errorf("imports %v, want %v", got, c.want)
|
||||
}
|
||||
last := f.calls[len(f.calls)-1]
|
||||
if dir := filepath.Join(work, "w1", "stage-tools", "modules", "module"); last.dir != dir ||
|
||||
!slices.Contains(last.args, ".mesh-build/tools/tools/index.js") || !slices.Contains(last.args, ".mesh-build/tools/tools/index.serve.mjs") ||
|
||||
!slices.Contains(last.args, "--external:pg") || !slices.Contains(last.args, "--metafile=.mesh-build/tools.imports.json") {
|
||||
t.Errorf("esbuild ran in %s as %v", last.dir, last.args)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// N1 (H-A-517): a workspace whose bundle was not built has no import set to read, and the step says so; a toolchain whose
|
||||
// own modules cannot be read fails the step loud, never answering them as packages.
|
||||
func TestTheImportsStepRefusesABundleNotBuilt(t *testing.T) {
|
||||
m, _, _ := builtMachine(t, ``)
|
||||
m.Builtins = func(context.Context) ([]string, error) { return nil, errors.New("no node") }
|
||||
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "Node's own modules") {
|
||||
t.Errorf("imports with no builtins read: %v", err)
|
||||
}
|
||||
m.Builtins = func(context.Context) ([]string, error) { return []string{"fs"}, nil }
|
||||
if _, err := m.imports(context.Background(), map[string]any{"workspace": "w1", "module": "modules/m"}); err == nil || !strings.Contains(err.Error(), "was not built") {
|
||||
t.Errorf("imports of an unbuilt bundle: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package main
|
||||
|
||||
// The imports step (design 47 H2 H-A-523, H-A-532 DQ-6, H-A-539): at a build's end the module says which npm packages
|
||||
// its TypeScript bundles import, so the indexer can take the fingerprint over the ones a module of the module graph
|
||||
// publishes and no other. It is what esbuild's metafile names as each bundle's inputs, read from the bundle's compiled
|
||||
// entrypoints and launchers as the build step staged them: every npm package among them, each by its package name once
|
||||
// (@novox/mesh-sdk, never a sub-path of it), with no scope telling a mesh package apart, and none of Node's own modules.
|
||||
// A bundle's inputs are what its entrypoints reach, so no test file is among them.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
sdkstep "git.novox.be/novox/mesh-delivery/modules/mesh-delivery-sdk/buildstep"
|
||||
)
|
||||
|
||||
// ImportsTool reads the npm packages a module's bundles import (design 47 H2 H-A-532 DQ-6).
|
||||
const ImportsTool = "build_node_imports"
|
||||
|
||||
// ImportsResult is what the imports step answers; a BuildAnswer carries Imports as it is.
|
||||
type ImportsResult struct {
|
||||
Imports []string `json:"imports"`
|
||||
}
|
||||
|
||||
func (m *Module) importsTool() StepTool {
|
||||
return StepTool{
|
||||
Name: ImportsTool,
|
||||
Description: "Read the npm packages the TypeScript bundles of a module of a workspace import, after its build: " +
|
||||
"esbuild's inputs of each bundle's compiled entrypoints and launchers, every npm package among them but Node's own " +
|
||||
"modules, each by its package name, sorted and each once. It is what a build says at its end " +
|
||||
"for the fingerprint (design 47 H2 H-A-523). Writes only esbuild's scratch output in the workspace.",
|
||||
Input: map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"workspace": map[string]any{"type": "string", "description": "the workspace id build_node_fetch answered, its bundles built"},
|
||||
"module": map[string]any{"type": "string", "description": "the module's directory in the workspace, '.' when it is the root"},
|
||||
},
|
||||
"required": []string{"workspace", "module"},
|
||||
},
|
||||
Run: m.imports,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Module) imports(ctx context.Context, args map[string]any) (any, error) {
|
||||
workspace, _ := args["workspace"].(string)
|
||||
module, _ := args["module"].(string)
|
||||
root, dir, err := m.moduleDirOf(workspace, module)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "module.json"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the module has no module.json: %w", err)
|
||||
}
|
||||
var manifest struct {
|
||||
Build struct {
|
||||
Artifacts []artifact `json:"artifacts"`
|
||||
} `json:"build"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &manifest); err != nil {
|
||||
return nil, fmt.Errorf("module.json is not JSON: %w", err)
|
||||
}
|
||||
probe := m.Builtins
|
||||
if probe == nil {
|
||||
probe = ProbeBuiltins
|
||||
}
|
||||
builtins, err := probe(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("the imports cannot be told from Node's own modules: %w", err)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, a := range manifest.Build.Artifacts {
|
||||
if a.Kind != "bundle" || a.Language != "typescript" {
|
||||
continue
|
||||
}
|
||||
names, err := m.bundleImports(ctx, root, a, builtins)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, n := range names {
|
||||
seen[n] = true
|
||||
}
|
||||
}
|
||||
out := []string{}
|
||||
for n := range seen {
|
||||
out = append(out, n)
|
||||
}
|
||||
slices.Sort(out)
|
||||
return ImportsResult{Imports: out}, nil
|
||||
}
|
||||
|
||||
// bundleImports are the npm packages esbuild names as inputs of bundle a, read in the stage its build left
|
||||
// (build.go: <root>/stage-<artifact>/modules/module), from the same entries and externals the build bundled.
|
||||
func (m *Module) bundleImports(ctx context.Context, root string, a artifact, builtins []string) ([]string, error) {
|
||||
dir := filepath.Join(root, "stage-"+a.Name, "modules", "module")
|
||||
out := Out(a.Name)
|
||||
if _, err := os.Stat(filepath.Join(dir, out)); err != nil {
|
||||
return nil, fmt.Errorf("the bundle %s was not built in this workspace, so its imports cannot be read: %w", a.Name, err)
|
||||
}
|
||||
var entries []string
|
||||
for _, e := range a.Entrypoints {
|
||||
if strings.HasSuffix(e, ".js") {
|
||||
entries = append(entries, out+"/"+e)
|
||||
}
|
||||
}
|
||||
for _, l := range sortedValues(sdkstep.Launchers(a.Language, a.Entrypoints)) {
|
||||
entries = append(entries, out+"/"+l)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
meta := out + ".imports.json"
|
||||
args := append(append([]string{}, entries...), "--bundle", "--platform=node", "--format=esm", "--target=node22",
|
||||
"--outbase="+out, "--outdir="+out+".imports", "--log-level=warning", "--metafile="+meta)
|
||||
for _, x := range a.External {
|
||||
args = append(args, "--external:"+x)
|
||||
}
|
||||
if why := ranFailed(m.runIn(ctx, root, false, dir, nil, m.esbuild(), args...)); why != "" {
|
||||
return nil, fmt.Errorf("esbuild's inputs of %s: %s", a.Name, why)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(dir, meta))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("esbuild wrote no metafile for %s: %w", a.Name, err)
|
||||
}
|
||||
return packagesOf(raw, builtins)
|
||||
}
|
||||
|
||||
// packagesOf are the npm packages an esbuild metafile names: each input under a node_modules directory and each external
|
||||
// import, by its package name, but Node's own modules.
|
||||
func packagesOf(metafile []byte, builtins []string) ([]string, error) {
|
||||
var meta struct {
|
||||
Inputs map[string]struct {
|
||||
Imports []struct {
|
||||
Path string `json:"path"`
|
||||
External bool `json:"external"`
|
||||
} `json:"imports"`
|
||||
} `json:"inputs"`
|
||||
}
|
||||
if err := json.Unmarshal(metafile, &meta); err != nil {
|
||||
return nil, fmt.Errorf("esbuild's metafile is not JSON: %w", err)
|
||||
}
|
||||
var out []string
|
||||
keep := func(name string) {
|
||||
if name != "" && !nodeBuiltin(name, builtins) && !slices.Contains(out, name) {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
for input, in := range meta.Inputs {
|
||||
filePath := filepath.ToSlash(input)
|
||||
if i := strings.LastIndex(filePath, "node_modules/"); i >= 0 {
|
||||
keep(packageName(filePath[i+len("node_modules/"):]))
|
||||
}
|
||||
for _, imp := range in.Imports {
|
||||
if imp.External {
|
||||
keep(packageName(imp.Path))
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// packageName is the npm package a module specifier or a path under node_modules names: its first segment, or its
|
||||
// first two for a scoped package (@novox/mesh-sdk/stdio is @novox/mesh-sdk).
|
||||
func packageName(spec string) string {
|
||||
parts := strings.SplitN(spec, "/", 3)
|
||||
if strings.HasPrefix(spec, "@") {
|
||||
if len(parts) < 2 {
|
||||
return ""
|
||||
}
|
||||
return parts[0] + "/" + parts[1]
|
||||
}
|
||||
return parts[0]
|
||||
}
|
||||
|
||||
// nodeBuiltin says whether name is one of Node's own modules (node:<name>, or a name of the probed toolchain's
|
||||
// module.builtinModules), which is the runtime's standard library and no npm package.
|
||||
func nodeBuiltin(name string, builtins []string) bool {
|
||||
return strings.HasPrefix(name, "node:") || slices.Contains(builtins, name)
|
||||
}
|
||||
@@ -45,6 +45,9 @@ type Module struct {
|
||||
Reload func() (Recipe, error)
|
||||
// Probe reads the installed Node version (ProbeNode).
|
||||
Probe func(ctx context.Context) (string, error)
|
||||
// Builtins reads the installed Node's own module names, its module.builtinModules (ProbeBuiltins), at each imports
|
||||
// step; nil reads them with ProbeBuiltins.
|
||||
Builtins func(ctx context.Context) ([]string, error)
|
||||
// Toolchain installs the toolchain directory; nil in a module that only guards.
|
||||
Toolchain *Toolchain
|
||||
// Work is the work directory, outside the home: a workspace is <Work>/<step id>/tree. Run runs the commands of a
|
||||
|
||||
@@ -2,6 +2,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
@@ -22,6 +23,22 @@ func ProbeNode(ctx context.Context) (string, error) {
|
||||
return parseNodeVersion(string(out))
|
||||
}
|
||||
|
||||
// ProbeBuiltins reads the installed Node's own modules, its module.builtinModules, so the imports step leaves out exactly
|
||||
// what the probed toolchain holds (principle 11: read, never a fixed list).
|
||||
func ProbeBuiltins(ctx context.Context) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, ProbeTimeout)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "node", "-p", "JSON.stringify(require('module').builtinModules)").Output()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("node's builtinModules cannot be read: %w", err)
|
||||
}
|
||||
var names []string
|
||||
if err := json.Unmarshal(out, &names); err != nil || len(names) == 0 {
|
||||
return nil, fmt.Errorf("node's builtinModules answered %q", strings.TrimSpace(string(out)))
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func parseNodeVersion(out string) (string, error) {
|
||||
v := strings.TrimSpace(out)
|
||||
if len(v) < 2 || v[0] != 'v' || v[1] < '0' || v[1] > '9' || strings.ContainsAny(v, " \n\t") {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package main
|
||||
|
||||
// **The verb `steps`** (design 47 G §22, §307, §326, §328): which pipeline steps a TypeScript artifact can run, by the
|
||||
// convention check.go tests by. The type-check is the lint step (§328) and is always one; the unit step is the packages
|
||||
// convention check.go tests by. The type-check is the lint step (§328), answered only when one of the artifact's packages
|
||||
// holds a TypeScript file, by the test the lint step itself uses (lint.go; design 47 H2 H-A-515 second addendum), so the
|
||||
// pipeline runner ends a lint with nothing to type-check at placement, never asking it (H-A-515 addendum); the unit step is the packages
|
||||
// holding a package.json script `test`, the integration step those holding `test:integration`. A level with none is not
|
||||
// answered. The answer is kept in the state detected-steps by the artifact's fingerprint, replaced by a newer one and by
|
||||
// again, as the Go build module keeps it.
|
||||
@@ -51,7 +53,15 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
|
||||
return nil, err
|
||||
}
|
||||
unit, integration := []string{}, []string{}
|
||||
lint := false
|
||||
for _, tg := range targets {
|
||||
if !lint {
|
||||
sources, err := typeScriptFiles(tg.dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lint = len(sources) > 0
|
||||
}
|
||||
scripts, err := packageScripts(tg.dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -63,7 +73,10 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
|
||||
integration = append(integration, tg.where)
|
||||
}
|
||||
}
|
||||
steps := []DetectedStep{{Step: StepLint}}
|
||||
steps := []DetectedStep{}
|
||||
if lint {
|
||||
steps = append(steps, DetectedStep{Step: StepLint})
|
||||
}
|
||||
for _, l := range []struct {
|
||||
step string
|
||||
pkgs []string
|
||||
@@ -79,7 +92,7 @@ func detectSteps(dir string, narrowedTree bool) ([]DetectedStep, error) {
|
||||
// stepsTool is the seat's verb `steps`.
|
||||
func (m *Module) stepsTool() stdio.Tool {
|
||||
return stdio.Tool{Name: Seat + "." + seat.VerbSteps,
|
||||
Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, always; unit tests where a package has a test script; " +
|
||||
Description: "Which pipeline steps a TypeScript artifact can run: the type-check as lint, where one of its packages holds a TypeScript file; unit tests where a package has a test script; " +
|
||||
"integration tests where one has a test:integration script. A level with no test is not answered.",
|
||||
Input: map[string]any{"type": "object", "required": []string{"module", "artifact"}, "properties": map[string]any{
|
||||
"module": map[string]any{"type": "string"},
|
||||
|
||||
@@ -10,8 +10,9 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint always, the packages with a test script as
|
||||
// unit, those with test:integration as integration, and leaves out a level with none.
|
||||
// Design 47 G §22, §307, §328 (BLD7): steps answers the type-check as lint where a package holds a TypeScript file (design 47
|
||||
// H2 H-A-515 second addendum: none for a tree with none, whose lint would end nothing to run), the packages with a test
|
||||
// script as unit, those with test:integration as integration, and leaves out a level with none.
|
||||
func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
|
||||
put := func(dir, name, body string) {
|
||||
if err := os.MkdirAll(filepath.Join(dir), 0o755); err != nil {
|
||||
@@ -23,15 +24,18 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
|
||||
}
|
||||
for name, c := range map[string]struct {
|
||||
pkg string
|
||||
noTS bool
|
||||
narrowed bool
|
||||
want []DetectedStep
|
||||
}{
|
||||
"both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false,
|
||||
"both levels": {`{"scripts":{"test":"node t.js","test:integration":"node i.js"}}`, false, false,
|
||||
[]DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}, {Step: "integration", Packages: []string{"."}}}},
|
||||
"unit only": {`{"scripts":{"test":"node t.js"}}`, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}},
|
||||
"no script": {`{"scripts":{}}`, false, []DetectedStep{{Step: "lint"}}},
|
||||
"unit only": {`{"scripts":{"test":"node t.js"}}`, false, false, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"."}}}},
|
||||
"no script": {`{"scripts":{}}`, false, false, []DetectedStep{{Step: "lint"}}},
|
||||
// No TypeScript file (only a declaration, as a generated package of JavaScript has): nothing to type-check, no lint.
|
||||
"no TypeScript file": {`{"scripts":{}}`, true, false, []DetectedStep{}},
|
||||
// A folder module's tree narrowed to ts/seats/a (H-A-136): the steps are those the narrowed levels run there.
|
||||
"narrowed folder": {"", true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}},
|
||||
"narrowed folder": {"", false, true, []DetectedStep{{Step: "lint"}, {Step: "unit", Packages: []string{"ts/seats/a"}}}},
|
||||
} {
|
||||
dir := t.TempDir()
|
||||
if c.narrowed {
|
||||
@@ -42,6 +46,12 @@ func TestTheStepsOfATypeScriptArtifactAreFoundByItsScripts(t *testing.T) {
|
||||
}
|
||||
} else {
|
||||
put(dir, "package.json", c.pkg)
|
||||
if c.noTS {
|
||||
put(dir, "index.d.ts", "export declare const v: number;\n")
|
||||
put(dir, "index.js", "export const v = 1;\n")
|
||||
} else {
|
||||
put(dir, "index.ts", "export const v = 1;\n")
|
||||
}
|
||||
}
|
||||
got, err := detectSteps(dir, c.narrowed)
|
||||
if err != nil || !reflect.DeepEqual(got, c.want) {
|
||||
|
||||
@@ -25,7 +25,7 @@ type StepTool struct {
|
||||
|
||||
// StepTools are the module's step tools. Each step's issue adds its own.
|
||||
func (m *Module) StepTools() []StepTool {
|
||||
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool()}
|
||||
return []StepTool{m.fetchTool(), m.testTool(), m.buildTool(), m.importsTool()}
|
||||
}
|
||||
|
||||
// Tools is every tool the module serves: its step tools behind the guard, its status and its health.
|
||||
|
||||
@@ -5,6 +5,7 @@ go 1.26.0
|
||||
require (
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/containerimageregistryclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/containerimageregistry v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildnode v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/clients/meshhandactsclient v0.0.0-00010101000000-000000000000
|
||||
git.novox.be/novox/mesh-contracts/health-and-repair/go/seats/meshhandacts v0.0.0-00010101000000-000000000000
|
||||
@@ -101,7 +102,6 @@ require (
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/clients/ociartifactregistryclient v0.0.0-00010101000000-000000000000 // indirect
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/gopackageregistry v0.0.0-00010101000000-000000000000 // indirect
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/meshcatalog v0.0.0-00010101000000-000000000000 // indirect
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/nodebuildgo v0.0.0-00010101000000-000000000000 // indirect
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/npmpackageregistry v0.0.0-00010101000000-000000000000 // indirect
|
||||
git.novox.be/novox/mesh-delivery/modules/mesh-delivery-contracts/go/seats/ociartifactregistry v0.0.0-00010101000000-000000000000 // indirect
|
||||
)
|
||||
|
||||
@@ -78,6 +78,7 @@
|
||||
"build_node_fetch",
|
||||
"build_node_test",
|
||||
"build_node_build",
|
||||
"build_node_imports",
|
||||
"build_node_release",
|
||||
"build_node_step",
|
||||
"build_node_steps",
|
||||
|
||||
+16
-12
@@ -35,21 +35,24 @@ puts the call on the bus, as every agent session on the machine does. The consol
|
||||
|
||||
- **Who judges.** The seat that owns the job: a change of assignments is a proposal the operator approves
|
||||
(`mesh-module-assigner.propose`), a config value is set with its why (`mesh-config.config`), a silence or a hand act is
|
||||
recorded as one. Until novox/hq issue 1126 the controller ran these lines and judged the account (ADR 0272); with
|
||||
the controller unassigned, that judgement went with it.
|
||||
- **The map.** Every line the controller ran, and the seat verb or tool that does its job now, or none, is
|
||||
`commands.go`'s table (and hq's `.work/1126/nox-map.md` while issue 1126 runs). A line no seat or module owns says
|
||||
that it was the controller's, that the controller is unassigned, and what to use instead, and exits 1 having called
|
||||
nothing. A line nox cannot read says how it is written and exits 2.
|
||||
recorded as one.
|
||||
- **The map.** Every line nox takes, and the seat verb or tool that does its job, is `commands.go`'s table. A line
|
||||
nox does not know, or cannot read, says so and how lines are found or written, and exits 2 having called nothing.
|
||||
- **Any address.** `nox call <address> [json]` calls any seat verb or tool; `nox search <words>` and
|
||||
`nox describe <address>` find one and its arguments.
|
||||
- **What is printed.** The owner's answer as the console gave it (JSON), on standard output with exit 0; an answer the
|
||||
- **What is printed.** The owner's answer as the console gave it (JSON), or the line's table (`nox nodes`,
|
||||
`nox licence`, `nox licence usage`; `--json` prints the answer raw), on standard output with exit 0; an answer the
|
||||
console marks an error (a refusal, nothing serving, no answer within its bound) on standard error with exit 1. A
|
||||
console that does not answer is said as nothing having been called; no answer in time is said as a call that may
|
||||
have run.
|
||||
- **`nox status`** is the delivery view's (`mesh-delivery-view.view_status`). When the view does not answer, nox says
|
||||
so first, shows the open conditions and the deliveries under their own addresses, and exits 1: they are never
|
||||
passed off as the status.
|
||||
- **`nox licence`** (and `nox licence list`) is the operator's overview of the licences in one line
|
||||
(one-question-one-tool): the licence manager's `licences` as one table (licence, kind, bound nodes, weekly, session
|
||||
and sonnet usage with their resets, the token's expiry, failures, conditions, whether it is the target), then its
|
||||
`bindings` (node, licence, since, why), every time local; with `--json` the two answers as one object
|
||||
`{licences, bindings}`. `nox licence usage [<licence>]` is the manager's `usage` readings as a table.
|
||||
- **`nox enrol open --key <file>`** runs here and asks nothing of the mesh (ADR 0587 §8).
|
||||
|
||||
A process that runs for a verb (it carries `MESH_VERB`) is refused before anything is called: a verb is never the
|
||||
@@ -57,15 +60,16 @@ operator.
|
||||
|
||||
## What it does not do yet
|
||||
|
||||
- **No formatting beyond `nox nodes`.** Answers are the owners' JSON.
|
||||
- **Lines with no owner.** Accepting a secret from a person, making or setting the operator key, opening a sealed
|
||||
secret locally, registering a module from another repository and forgetting a module have no seat verb yet; nox
|
||||
names what to use meanwhile.
|
||||
- **No formatting beyond `nox nodes` and the licence lines.** Answers are the owners' JSON.
|
||||
- **No line without a seat verb.** Accepting a secret from a person, making or setting the operator key, opening a
|
||||
sealed secret locally, registering a module from another repository and forgetting a module have no seat verb yet,
|
||||
so nox has no line for them.
|
||||
|
||||
## Tests
|
||||
|
||||
`go test ./...`: every owned line calls its owner's address with the arguments it reads, against a stand-in console
|
||||
answering MCP `tools/call` as node-tools does; a line with no owner or not read calls nothing and says why; an error
|
||||
answering MCP `tools/call` as node-tools does; a line not known or not read calls nothing and says why; the licence
|
||||
lines print their tables from the manager's answers; an error
|
||||
answer, a silent console and a verb's process are said; the status's fallback is labelled and exits 1; the console's
|
||||
address is found; `enrol open` opens a sealed token locally; the module places the program and the console's address
|
||||
and nothing else.
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package main
|
||||
|
||||
// Every command line nox takes, and the seat verb or module tool that owns its job now that the controller is
|
||||
// unassigned (novox/hq issue 1126; the map is hq's .work/1126/nox-map.md). A line no seat or module owns says so and
|
||||
// names what to use instead: it never fails silently, and it never pretends to have run.
|
||||
// Every command line nox takes, and the seat verb or module tool that owns its job. A line nox does not know says so
|
||||
// and calls nothing: it never fails silently, and it never pretends to have run.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
@@ -93,18 +92,25 @@ type command struct {
|
||||
words []string
|
||||
usage string
|
||||
does string
|
||||
// build reads the line and answers the call; nil for a line no seat owns.
|
||||
// build reads the line and answers the call.
|
||||
build func(l line) (call, error)
|
||||
// allowed are the flags the line reads; any other is refused before anything is called.
|
||||
allowed []string
|
||||
// instead says, for a line with no owner, what to use; empty for one that is owned.
|
||||
instead string
|
||||
// render shapes a successful answer for reading; nil prints it as the console gave it.
|
||||
// render shapes a successful answer for reading; nil prints it as the console gave it. With --json the answer is
|
||||
// printed raw.
|
||||
render func(text string) string
|
||||
// also is a second call the line makes after the first, its answer read beside the first's; nil for a line of one
|
||||
// call.
|
||||
also *second
|
||||
}
|
||||
|
||||
// gone is the reason every unowned line gives.
|
||||
const gone = "this was the controller's, and the controller is unassigned (novox/hq issue 1126). Nothing was called"
|
||||
// second is a line's second call: its address, asked with no arguments, the keys the two raw answers are printed
|
||||
// under with --json, and the render that reads both answers.
|
||||
type second struct {
|
||||
address string
|
||||
keys [2]string
|
||||
render func(first, second string) string
|
||||
}
|
||||
|
||||
// commands is every line, longest words first within a word.
|
||||
var commands = []command{
|
||||
@@ -120,8 +126,6 @@ var commands = []command{
|
||||
{words: []string{"node", "public-domain"}, usage: "<node> [<domain> | --clear] [--why <text>]",
|
||||
does: "the domain a node composes its routed names under; with a domain or --clear, proposed to assignments",
|
||||
allowed: []string{"clear", "why"}, build: publicDomain},
|
||||
{words: []string{"node", "add"}, instead: "a new machine joins through the seat mesh-node-enroller: nox enrol issue <node> --why <text>"},
|
||||
{words: []string{"node", "networks"}, instead: "no seat keeps a node's routed networks yet; mesh-module-assigner.assignments shows what a node decides"},
|
||||
{words: []string{"plan"}, usage: "<node>", does: "what the assigner wants the node to run", build: optNode("mesh-delivery-view.assigner_wants")},
|
||||
{words: []string{"haves"}, usage: "[<node>]", does: "what each node runs, as its node-engine said", build: optNode("mesh-delivery-view.node_haves")},
|
||||
{words: []string{"switch"}, does: "what each node runs, as its node-engine said", build: fixed("mesh-delivery-view.node_haves")},
|
||||
@@ -135,7 +139,6 @@ var commands = []command{
|
||||
{words: []string{"seats"}, does: "who holds each seat, and where", build: func(line) (call, error) {
|
||||
return call{"mesh-module-assigner.assignments", map[string]any{"seats": "true"}}, nil
|
||||
}},
|
||||
{words: []string{"seat"}, instead: "a seat is held by placing its module: nox assign <node> <module> --why <text> (mesh-module-assigner.propose)"},
|
||||
{words: []string{"assign"}, usage: "<node> <module>... --why <text>", does: "propose placing modules on a node",
|
||||
allowed: []string{"why"}, build: placeModules("place")},
|
||||
{words: []string{"unassign"}, usage: "<node> <module>... --why <text>", does: "propose taking modules off a node",
|
||||
@@ -157,7 +160,6 @@ var commands = []command{
|
||||
}},
|
||||
{words: []string{"proposals"}, usage: "[<id>]", does: "the open proposals of assignments", build: optArg("mesh-module-assigner.proposals", "id")},
|
||||
{words: []string{"overlay", "show"}, does: "every node's assignments, with its tunnel", build: fixed("mesh-module-assigner.assignments")},
|
||||
{words: []string{"overlay"}, instead: "a node's tunnel is a decided field of its assignments: mesh-module-assigner.propose with op decide"},
|
||||
|
||||
// Deliveries and builds.
|
||||
{words: []string{"deliveries"}, usage: "[--state s] [--repository owner/repo] [--group g] [--all]",
|
||||
@@ -291,11 +293,7 @@ var commands = []command{
|
||||
c, err := fixed("mesh-vault.secret_vault_export")(l)
|
||||
return warranted(c, "the vault's sealed copies"), err
|
||||
}},
|
||||
{words: []string{"secret", "accept"}, instead: "mesh-vault.accept takes a value from the controller alone, and no seat takes one from a person yet; a module's own secret is asked at a desk (mesh-vault.secret-ask)"},
|
||||
{words: []string{"secret", "recover"}, instead: "opening a sealed copy locally is not built yet (beside nox enrol open); nox secret export gives the sealed copies"},
|
||||
{words: []string{"secret"}, instead: "nox secret export; mesh-vault.rotate makes one anew"},
|
||||
{words: []string{"operator", "key", "show"}, does: "what needs a person's eye in the vault, the operator key among it", build: fixed("mesh-vault.vault_status")},
|
||||
{words: []string{"operator"}, instead: "no seat sets or makes the operator key yet; nox operator key show reads it (mesh-vault.vault_status)"},
|
||||
{words: []string{"rotate"}, usage: "[--node n --module m --name s | --provider n --provision p] --why <text>",
|
||||
does: "make a secret anew", allowed: []string{"node", "module", "name", "provider", "provision", "consumer", "consumer_module", "why"},
|
||||
build: func(l line) (call, error) {
|
||||
@@ -353,7 +351,13 @@ var commands = []command{
|
||||
}},
|
||||
{words: []string{"images"}, usage: "<node>", does: "every container image a machine's wants and haves name", build: needArg("mesh-artifact-sweep.images", "node")},
|
||||
{words: []string{"mirrors"}, does: "the bases the mesh copied into its store", build: fixed("mesh-artifact-sweep.mirrors")},
|
||||
{words: []string{"licence", "list"}, does: "every licence the manager holds", build: fixed("anthropic-licence-manager.licences")},
|
||||
// The operator's overview of the licences, in one line (one-question-one-tool).
|
||||
{words: []string{"licence"}, does: "every licence: kind, bound nodes, usage and its resets, token expiry, failures, conditions, target; then the bindings",
|
||||
build: fixed("anthropic-licence-manager.licences"), also: licenceBindings},
|
||||
{words: []string{"licence", "list"}, does: "every licence: kind, bound nodes, usage and its resets, token expiry, failures, conditions, target; then the bindings",
|
||||
build: fixed("anthropic-licence-manager.licences"), also: licenceBindings},
|
||||
{words: []string{"licence", "usage"}, usage: "[<licence>]", does: "the usage readings, the latest first, of every licence or one",
|
||||
build: optArg("anthropic-licence-manager.usage", "licence"), render: renderUsage},
|
||||
{words: []string{"licence", "use"}, usage: "<consumer> <licence>", does: "move a node's agent to another licence",
|
||||
build: func(l line) (call, error) {
|
||||
if len(l.pos) != 2 {
|
||||
@@ -363,7 +367,6 @@ var commands = []command{
|
||||
}},
|
||||
{words: []string{"licence", "refresh"}, usage: "[<licence>]", does: "refresh a licence now, or every due one", build: optArg("anthropic-licence-manager.refresh", "licence")},
|
||||
{words: []string{"licence", "key"}, does: "the manager's public key", build: fixed("anthropic-licence-manager.public-key")},
|
||||
{words: []string{"licence"}, instead: "anthropic-licence-manager.adopt takes an API key from a file on the manager's node; nox licence list|use|refresh|key"},
|
||||
{words: []string{"module", "list"}, does: "every module the indexer holds", build: fixed("mesh-delivery-view.indexer_modules")},
|
||||
{words: []string{"module", "show"}, usage: "<module>", does: "what the indexer holds of one module", build: needArg("mesh-delivery-view.indexer_module", "module")},
|
||||
{words: []string{"head", "take"}, usage: "<owner/repository> <branch> --why <text>", does: "take a held head in by hand (design 47 H §742, H-A-105)", allowed: []string{"why"},
|
||||
@@ -374,8 +377,6 @@ var commands = []command{
|
||||
return call{"mesh-delivery-gate.gate_head_take", map[string]any{"repository": l.pos[0], "branch": l.pos[1], "why": l.flags["why"]}}, nil
|
||||
}},
|
||||
{words: []string{"head", "list"}, does: "every untaken head the gate holds", build: fixed("mesh-delivery-gate.gate_heads")},
|
||||
{words: []string{"module"}, instead: "the indexer takes modules in from their repositories; nox module list|show, nox head take for a held head, and nothing forgets one by hand yet"},
|
||||
{words: []string{"register"}, instead: "no seat registers a module from another repository yet (novox/hq ADR 0501 §4); nox head take <repository> <branch> takes a held head in"},
|
||||
{words: []string{"account", "issue"}, usage: "<user>", does: "mint one bus account the grants part wants, now", build: needArg("mesh-vault.issue-account", "user")},
|
||||
|
||||
// Issues and records.
|
||||
@@ -479,21 +480,6 @@ var commands = []command{
|
||||
}},
|
||||
}
|
||||
|
||||
// unowned are the controller's own lines that no seat or module took over, and what to use where there is anything.
|
||||
var unowned = map[string]string{
|
||||
"migrate": "", "prepare": "", "serve": "", "declare": "", "broker": "", "board": "", "api": "", "facts": "",
|
||||
"rehearse": "", "take": "", "converge": "", "adopt": "", "move-placement": "", "move-config": "", "durations": "",
|
||||
"data": "each machine's backups: nox call <node>/node-backup.backed-up",
|
||||
"forget-checks": "nox checks <owner/repo>", "queue": "nox builds; nox stuck", "cancel": "nox deliveries",
|
||||
"clear": "nox deliveries", "kill": "nox deliveries", "replay": "nox dead-letters",
|
||||
"pause": "nox call <node>/node-build-go.pause (or node-build-node, node-build-image)",
|
||||
"resume": "nox call <node>/node-build-go.resume (or node-build-node, node-build-image)",
|
||||
"push": "a merge is delivered by mesh-delivery: nox deliveries; one version on one machine is mesh-delivery-assigner.assigner_put",
|
||||
"deliver": "nox deliveries", "plans": "nox deliveries", "delivery-stop": "nox stalled",
|
||||
"delivery-backups-again": "nox deliveries", "delivery-walks": "nox deliveries", "delivery-order": "nox deliveries",
|
||||
"rollout": "nox upgrade <module>; delivery is mesh-delivery's: nox deliveries",
|
||||
}
|
||||
|
||||
// find answers the command whose words begin the line, the longest first, and what follows them.
|
||||
func find(args []string) (*command, []string) {
|
||||
var best *command
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
package main
|
||||
|
||||
// How mesh-cli reaches the mesh now that the controller is unassigned (novox/hq issue 1126): through this machine's
|
||||
// console, the mesh MCP server the module node-tools serves on loopback (provision mcp-endpoint, ADR 0152: the
|
||||
// machine's login is the authority). mesh-cli calls `mesh_call` with a seat verb's or a module tool's address, and the
|
||||
// How mesh-cli reaches the mesh: through this machine's console, the mesh MCP server the module node-tools serves on
|
||||
// loopback (provision mcp-endpoint, ADR 0152: the machine's login is the authority). mesh-cli calls `mesh_call` with a seat verb's or a module tool's address, and the
|
||||
// console puts the call on the bus, the way every agent session on the machine does. mesh-cli holds no credential and
|
||||
// keeps no bus account of its own.
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ package main
|
||||
//
|
||||
// The seat mesh-node-enroller's `tokens` answers the token sealed to the operator key, which only the operator's private key
|
||||
// opens; the mesh never holds it. This subcommand is local: it asks nothing of the node-engine's socket and nothing of
|
||||
// the controller or the bus. It reads the sealed token (the base64 of the sealed box) on standard input and the private
|
||||
// the bus. It reads the sealed token (the base64 of the sealed box) on standard input and the private
|
||||
// key from a file (`--key`, the raw X25519 key in base64 that `operator key make` wrote), opens the box, and prints the
|
||||
// token text a joining machine's `enrol` takes. The key is read from the file named and nowhere else, and never printed.
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
package main
|
||||
|
||||
// The operator's overview of the licences in one line (one-question-one-tool): the licence manager's licences and
|
||||
// bindings as two tables, and its usage readings as one; every time is local.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
"time"
|
||||
)
|
||||
|
||||
// licenceBindings is the second call of `nox licence`: which licence each node is bound to, since when and why.
|
||||
var licenceBindings = &second{address: "anthropic-licence-manager.bindings", keys: [2]string{"licences", "bindings"},
|
||||
render: renderLicences}
|
||||
|
||||
// splitAnswer is the console's answer as its first JSON value and what the console said after it ("answered by ace").
|
||||
func splitAnswer(text string) (json.RawMessage, string) {
|
||||
dec := json.NewDecoder(strings.NewReader(text))
|
||||
var v json.RawMessage
|
||||
if err := dec.Decode(&v); err != nil {
|
||||
return nil, text
|
||||
}
|
||||
return v, strings.TrimSpace(text[dec.InputOffset():])
|
||||
}
|
||||
|
||||
// localTime is an RFC 3339 time in this machine's zone, to the minute; "-" for none, and the text itself when it is
|
||||
// not one.
|
||||
func localTime(s string) string {
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, s)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return t.Local().Format("2006-01-02 15:04")
|
||||
}
|
||||
|
||||
// percent is a reading with its reset when it has one; "-" for a reading the vendor did not give.
|
||||
func percent(pct *float64, resets string) string {
|
||||
if pct == nil {
|
||||
return "-"
|
||||
}
|
||||
if resets == "" {
|
||||
return fmt.Sprintf("%g %%", *pct)
|
||||
}
|
||||
return fmt.Sprintf("%g %% (resets %s)", *pct, localTime(resets))
|
||||
}
|
||||
|
||||
func dashed(s string) string {
|
||||
if s == "" {
|
||||
return "-"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// conditionNames are a licence's open conditions as their keys; a condition that is not a key is said as given.
|
||||
func conditionNames(cs []json.RawMessage) string {
|
||||
names := make([]string, 0, len(cs))
|
||||
for _, c := range cs {
|
||||
var s string
|
||||
if json.Unmarshal(c, &s) == nil {
|
||||
names = append(names, s)
|
||||
continue
|
||||
}
|
||||
var o struct {
|
||||
Key string `json:"key"`
|
||||
}
|
||||
if json.Unmarshal(c, &o) == nil && o.Key != "" {
|
||||
names = append(names, o.Key)
|
||||
continue
|
||||
}
|
||||
names = append(names, string(c))
|
||||
}
|
||||
return dashed(strings.Join(names, " "))
|
||||
}
|
||||
|
||||
// renderLicences is the licences as one table, then the bindings as another; an answer it cannot read is printed as
|
||||
// given.
|
||||
func renderLicences(licences, bindings string) string {
|
||||
var ls []struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Bound []string `json:"bound"`
|
||||
Usage struct {
|
||||
WeeklyPct *float64 `json:"weeklyPct"`
|
||||
WeeklyResetsAt string `json:"weeklyResetsAt"`
|
||||
SessionPct *float64 `json:"sessionPct"`
|
||||
SessionResetsAt string `json:"sessionResetsAt"`
|
||||
SonnetPct *float64 `json:"sonnetPct"`
|
||||
} `json:"usage"`
|
||||
AccessExpiresAt string `json:"accessExpiresAt"`
|
||||
Failures int `json:"failures"`
|
||||
Conditions []json.RawMessage `json:"conditions"`
|
||||
Target bool `json:"target"`
|
||||
}
|
||||
var bs []struct {
|
||||
Consumer string `json:"consumer"`
|
||||
Licence string `json:"licence"`
|
||||
Since string `json:"since"`
|
||||
Why string `json:"why"`
|
||||
}
|
||||
lv, lafter := splitAnswer(licences)
|
||||
bv, bafter := splitAnswer(bindings)
|
||||
if lv == nil || json.Unmarshal(lv, &ls) != nil || bv == nil || json.Unmarshal(bv, &bs) != nil {
|
||||
return licences + "\n" + bindings
|
||||
}
|
||||
var b strings.Builder
|
||||
w := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "LICENCE\tKIND\tBOUND\tWEEKLY\tSESSION\tSONNET\tTOKEN EXPIRES\tFAILURES\tCONDITIONS\tTARGET")
|
||||
for _, l := range ls {
|
||||
target := "no"
|
||||
if l.Target {
|
||||
target = "yes"
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%d\t%s\t%s\n", l.Name, dashed(l.Kind), dashed(strings.Join(l.Bound, " ")),
|
||||
percent(l.Usage.WeeklyPct, l.Usage.WeeklyResetsAt), percent(l.Usage.SessionPct, l.Usage.SessionResetsAt),
|
||||
percent(l.Usage.SonnetPct, ""), localTime(l.AccessExpiresAt), l.Failures, conditionNames(l.Conditions), target)
|
||||
}
|
||||
w.Flush()
|
||||
b.WriteString("\n")
|
||||
w = tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "NODE\tLICENCE\tSINCE\tWHY")
|
||||
for _, x := range bs {
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", x.Consumer, x.Licence, localTime(x.Since), dashed(x.Why))
|
||||
}
|
||||
w.Flush()
|
||||
// Which machine answered each call, said once when both say the same.
|
||||
for i, a := range []string{lafter, bafter} {
|
||||
if a != "" && (i == 0 || a != lafter) {
|
||||
b.WriteString(a + "\n")
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// renderUsage is the usage readings as one table, the latest first as the manager answers them; an answer it cannot
|
||||
// read is printed as given.
|
||||
func renderUsage(text string) string {
|
||||
var rs []struct {
|
||||
At int64 `json:"at"`
|
||||
Licence string `json:"licence"`
|
||||
Reading struct {
|
||||
WeeklyPct *float64 `json:"weeklyPct"`
|
||||
WeeklyResetsAt string `json:"weeklyResetsAt"`
|
||||
SessionPct *float64 `json:"sessionPct"`
|
||||
SessionResetsAt string `json:"sessionResetsAt"`
|
||||
SonnetResetsAt string `json:"sonnetResetsAt"`
|
||||
} `json:"reading"`
|
||||
}
|
||||
v, after := splitAnswer(text)
|
||||
if v == nil || json.Unmarshal(v, &rs) != nil {
|
||||
return text
|
||||
}
|
||||
var b strings.Builder
|
||||
w := tabwriter.NewWriter(&b, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(w, "LICENCE\tREAD AT\tWEEKLY\tSESSION\tRESETS")
|
||||
for _, r := range rs {
|
||||
var resets []string
|
||||
for _, x := range [][2]string{{"weekly", r.Reading.WeeklyResetsAt}, {"session", r.Reading.SessionResetsAt},
|
||||
{"sonnet", r.Reading.SonnetResetsAt}} {
|
||||
if x[1] != "" {
|
||||
resets = append(resets, x[0]+" "+localTime(x[1]))
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", r.Licence, time.UnixMilli(r.At).Local().Format("2006-01-02 15:04"),
|
||||
percent(r.Reading.WeeklyPct, ""), percent(r.Reading.SessionPct, ""), dashed(strings.Join(resets, ", ")))
|
||||
}
|
||||
w.Flush()
|
||||
if after != "" {
|
||||
b.WriteString(after + "\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
// Command mesh-cli is the operator's command on every node: `mesh-cli <command line>`, in interactive zsh also `nox`.
|
||||
//
|
||||
// Each line calls the seat verb or the module tool that owns its job (novox/hq issue 1126: the controller that ran
|
||||
// these lines before is unassigned), through this machine's console, the mesh MCP server on loopback (console.go).
|
||||
// A line no seat or module owns says so and names what to use instead. `enrol open` runs here and asks nothing.
|
||||
// Each line calls the seat verb or the module tool that owns its job, through this machine's console, the mesh MCP
|
||||
// server on loopback (console.go). A line nox does not know says so and calls nothing. `enrol open` runs here and asks
|
||||
// nothing.
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -75,16 +75,10 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||
}
|
||||
c, rest := find(args)
|
||||
if c == nil {
|
||||
if instead, ok := unowned[args[0]]; ok {
|
||||
return noOwner(args[0], instead, stderr)
|
||||
}
|
||||
fmt.Fprintf(stderr, "mesh-cli: %q is not a command. nox help lists them; nox search <words> finds a seat verb "+
|
||||
"or a tool, and nox call <address> calls it\n", args[0])
|
||||
return 2
|
||||
}
|
||||
if c.build == nil {
|
||||
return noOwner(strings.Join(c.words, " "), c.instead, stderr)
|
||||
}
|
||||
k, err := c.read(rest)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "mesh-cli: %v. Nothing was called\n nox %s %s\n", err, strings.Join(c.words, " "), c.usage)
|
||||
@@ -100,7 +94,59 @@ func run(ctx context.Context, args []string, stdout, stderr io.Writer) int {
|
||||
if k.Address == "mesh-delivery-view.view_status" {
|
||||
return status(ctx, stdout, stderr)
|
||||
}
|
||||
return show(ctx, "mesh_call", map[string]any{"address": k.Address, "arguments": k.Args}, c.render, stdout, stderr)
|
||||
render := c.render
|
||||
l, _ := parseLine(rest)
|
||||
if l.has("json") {
|
||||
render = nil
|
||||
}
|
||||
if c.also != nil {
|
||||
return showTwo(ctx, k, c.also, !l.has("json"), stdout, stderr)
|
||||
}
|
||||
return show(ctx, "mesh_call", map[string]any{"address": k.Address, "arguments": k.Args}, render, stdout, stderr)
|
||||
}
|
||||
|
||||
// showTwo calls a line's two addresses in turn and prints both answers: through the line's render, or raw as one
|
||||
// object under the line's two keys. The second is not called when the first fails, and either failing is said with
|
||||
// exit 1.
|
||||
func showTwo(ctx context.Context, first call, also *second, rendered bool, stdout, stderr io.Writer) int {
|
||||
var texts [2]string
|
||||
for i, k := range []call{first, {also.address, map[string]any{}}} {
|
||||
a, err := consoleTool(ctx, "mesh_call", map[string]any{"address": k.Address, "arguments": k.Args})
|
||||
if err != nil {
|
||||
return failed(err, stderr)
|
||||
}
|
||||
if a.IsError {
|
||||
fmt.Fprintln(stderr, "mesh-cli: "+k.Address+": "+strings.TrimRight(a.Text, "\n"))
|
||||
return 1
|
||||
}
|
||||
texts[i] = a.Text
|
||||
}
|
||||
if rendered {
|
||||
fmt.Fprintln(stdout, strings.TrimRight(also.render(texts[0], texts[1]), "\n"))
|
||||
return 0
|
||||
}
|
||||
whole := map[string]json.RawMessage{}
|
||||
var after []string
|
||||
for i, text := range texts {
|
||||
v, rest := splitAnswer(text)
|
||||
if v == nil {
|
||||
fmt.Fprintf(stderr, "mesh-cli: %s answered no JSON: %q\n", []string{first.Address, also.address}[i], text)
|
||||
return 1
|
||||
}
|
||||
whole[also.keys[i]] = v
|
||||
if rest != "" && (len(after) == 0 || after[0] != rest) {
|
||||
after = append(after, rest)
|
||||
}
|
||||
}
|
||||
b, err := json.MarshalIndent(whole, "", " ")
|
||||
if err != nil {
|
||||
return failed(err, stderr)
|
||||
}
|
||||
fmt.Fprintln(stdout, string(b))
|
||||
for _, a := range after {
|
||||
fmt.Fprintln(stdout, a)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// recordAct records the hand act a sensitive vault verb is warranted by, through mesh-hand-acts, and answers its id;
|
||||
@@ -127,17 +173,6 @@ func recordAct(ctx context.Context, h handAct, stderr io.Writer) (string, int) {
|
||||
return rec.Act.ID, 0
|
||||
}
|
||||
|
||||
// noOwner says a line has no owner since the controller went, and what to use.
|
||||
func noOwner(what, instead string, stderr io.Writer) int {
|
||||
fmt.Fprintf(stderr, "mesh-cli: nox %s: %s.\n", what, gone)
|
||||
if instead != "" {
|
||||
fmt.Fprintf(stderr, " instead: %s\n", instead)
|
||||
} else {
|
||||
fmt.Fprintln(stderr, " no seat or module does this now; nox search <words> finds what does nearby")
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// show calls one of the console's tools and prints what it answered: an answer marked an error on standard error, with
|
||||
// exit 1.
|
||||
func show(ctx context.Context, tool string, args map[string]any, render func(string) string, stdout, stderr io.Writer) int {
|
||||
@@ -218,14 +253,11 @@ func usage() string {
|
||||
b.WriteString(`mesh-cli: the operator's command (nox in interactive zsh)
|
||||
|
||||
Each line calls the seat verb or module tool that owns the job, through this machine's console (the mesh MCP
|
||||
server on loopback). The controller that ran these lines before is unassigned (novox/hq issue 1126).
|
||||
server on loopback).
|
||||
|
||||
`)
|
||||
lines := make([]string, 0, len(commands))
|
||||
for _, c := range commands {
|
||||
if c.build == nil {
|
||||
continue
|
||||
}
|
||||
lines = append(lines, fmt.Sprintf(" nox %s %s\n %s", strings.Join(c.words, " "), c.usage, c.does))
|
||||
}
|
||||
sort.Strings(lines)
|
||||
@@ -239,7 +271,7 @@ server on loopback). The controller that ran these lines before is unassigned (n
|
||||
open an enrolment token sealed to the operator key, here; asks nothing of the mesh
|
||||
nox version
|
||||
|
||||
Every answer is the owner's own, as JSON. A line the controller ran that no seat owns says so and what to use.
|
||||
Every answer is the owner's own, as JSON, or a table where the line says so; --json prints it raw.
|
||||
`)
|
||||
return b.String()
|
||||
}
|
||||
|
||||
@@ -77,8 +77,8 @@ func runLine(args ...string) (int, string, string) {
|
||||
return code, out.String(), errOut.String()
|
||||
}
|
||||
|
||||
// Every owned line calls the seat verb or module tool that owns its job, with the arguments the owner reads
|
||||
// (novox/hq issue 1126; hq .work/1126/nox-map.md), and prints its answer.
|
||||
// Every line calls the seat verb or module tool that owns its job, with the arguments the owner reads, and prints its
|
||||
// answer.
|
||||
func TestEachLineCallsItsOwner(t *testing.T) {
|
||||
now = func() time.Time { return time.Date(2026, 11, 2, 10, 0, 0, 0, time.UTC) }
|
||||
t.Cleanup(func() { now = time.Now })
|
||||
@@ -121,14 +121,14 @@ func TestEachLineCallsItsOwner(t *testing.T) {
|
||||
{"settings clear zsh execute --node g14 --why test", "mesh-config.config", `{"action":"clear","key":"execute","module":"zsh","node":"g14","why":"test"}`},
|
||||
{"config history --key k --limit 5", "mesh-config.config", `{"action":"history","key":"k","limit":5}`},
|
||||
{"operator key show", "mesh-vault.vault_status", `{}`},
|
||||
// A cleanup without --confirm deletes nothing, so no hand act is recorded for it (issue 1126 review 2).
|
||||
// A cleanup without --confirm deletes nothing, so no hand act is recorded for it.
|
||||
{"cleanup delete ace.plex --why dry", "mesh-vault.provisioner_delete", `{"consumer":"ace.plex","why":"dry"}`},
|
||||
{"collect --confirm --why space", "mesh-artifact-sweep.collect", `{"confirm":"true","why":"space"}`},
|
||||
{"images ace", "mesh-artifact-sweep.images", `{"node":"ace"}`},
|
||||
{"licence use g14 work", "anthropic-licence-manager.switch", `{"consumer":"g14","licence":"work"}`},
|
||||
{"module show plex", "mesh-delivery-view.indexer_module", `{"module":"plex"}`},
|
||||
{"issues apostrophe bug --status open --limit 5", "issue-tracker.list", `{"limit":5,"search":"apostrophe bug","status":"open"}`},
|
||||
{"issue 1126 --brief", "issue-tracker.get", `{"brief":true,"number":1126}`},
|
||||
{"issue 294 --brief", "issue-tracker.get", `{"brief":true,"number":294}`},
|
||||
{"kb ask what holds about the merge window", "knowledge-base.ask", `{"question":"what holds about the merge window"}`},
|
||||
{"kb get 587 --reasoning", "knowledge-base.get", `{"number":587,"reasoning":true}`},
|
||||
{"progress 47", "knowledge-base.progress", `{"of":"design 47"}`},
|
||||
@@ -154,42 +154,43 @@ func TestEachLineCallsItsOwner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A line the controller ran that no seat owns says so and what to use, exits 1 and calls nothing; a line nox cannot
|
||||
// read says how it is written, exits 2 and calls nothing.
|
||||
func TestALineWithNoOwnerOrNotReadCallsNothingAndSaysWhy(t *testing.T) {
|
||||
// 1126/AC4: a line nox cannot read says how it is written, exits 2 and calls nothing; the controller's retired lines are gone with
|
||||
// it, not mapped to a refusal (the operator, 2026-11-22: "why are there still references to the controller?"), and
|
||||
// nothing nox says names the controller.
|
||||
func TestALineNotReadCallsNothingAndSaysWhy(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
line string
|
||||
code int
|
||||
err string
|
||||
}{
|
||||
{"push ace", 1, "mesh-delivery-assigner.assigner_put"},
|
||||
{"migrate", 1, "no seat or module does this now"},
|
||||
{"secret accept ace plex token", 1, "mesh-vault.secret-ask"},
|
||||
{"node add new1", 1, "nox enrol issue"},
|
||||
{"pause", 1, "node-build-go.pause"},
|
||||
{"operator key make", 1, "operator key show"},
|
||||
{"assign ace plex", 2, "needs --why"},
|
||||
{"issue twelve", 2, "not an issue's number"},
|
||||
{"conditions --bogus x", 2, "--bogus is not a flag"},
|
||||
{"settings set zsh {\"execute\":\"withhold\"} --node g14 --why x", 2, "set each key"},
|
||||
{"healers --days soon", 2, "takes a number"},
|
||||
{"config propose --pull novox/x#1", 2, "--pull is not a flag"},
|
||||
{"frobnicate", 2, "is not a command"},
|
||||
{"push ace", "is not a command"},
|
||||
{"migrate", "is not a command"},
|
||||
{"secret accept ace plex token", "is not a command"},
|
||||
{"node add new1", "is not a command"},
|
||||
{"pause", "is not a command"},
|
||||
{"operator key make", "is not a command"},
|
||||
{"module forget plex", "is not a command"},
|
||||
{"assign ace plex", "needs --why"},
|
||||
{"issue twelve", "not an issue's number"},
|
||||
{"conditions --bogus x", "--bogus is not a flag"},
|
||||
{"settings set zsh {\"execute\":\"withhold\"} --node g14 --why x", "set each key"},
|
||||
{"healers --days soon", "takes a number"},
|
||||
{"config propose --pull novox/x#1", "--pull is not a flag"},
|
||||
{"frobnicate", "is not a command"},
|
||||
// The checker and the groups go whole (design 47 H §764): nox calls neither.
|
||||
{"try novox/mesh-catalog abc123 --level unit", 2, "is not a command"},
|
||||
{"groups", 2, "is not a command"},
|
||||
{"checks novox/mesh-catalog --number 591", 2, "is not a command"},
|
||||
{"try novox/mesh-catalog abc123 --level unit", "is not a command"},
|
||||
{"groups", "is not a command"},
|
||||
{"checks novox/mesh-catalog --number 591", "is not a command"},
|
||||
} {
|
||||
got := console(t, nil)
|
||||
args := strings.Fields(c.line)
|
||||
code, _, errOut := runLine(args...)
|
||||
if code != c.code || len(*got) != 0 || !strings.Contains(errOut, c.err) {
|
||||
t.Errorf("nox %s: exit %d, asked %+v, stderr %q; want exit %d saying %q", c.line, code, *got, errOut, c.code, c.err)
|
||||
}
|
||||
if c.code == 1 && !strings.Contains(errOut, "issue 1126") {
|
||||
t.Errorf("nox %s does not say the controller is unassigned: %q", c.line, errOut)
|
||||
if code != 2 || len(*got) != 0 || !strings.Contains(errOut, c.err) || strings.Contains(errOut, "controller") {
|
||||
t.Errorf("nox %s: exit %d, asked %+v, stderr %q; want exit 2 saying %q", c.line, code, *got, errOut, c.err)
|
||||
}
|
||||
}
|
||||
if strings.Contains(usage(), "controller") {
|
||||
t.Errorf("the help still names the controller:\n%s", usage())
|
||||
}
|
||||
}
|
||||
|
||||
// What the console says is printed as said: an answer it marks an error on standard error with exit 1, a console that
|
||||
@@ -279,16 +280,13 @@ func TestEveryLineIsInTheHelpOnce(t *testing.T) {
|
||||
if c.build != nil && !strings.Contains(help, "nox "+w+" ") {
|
||||
t.Errorf("nox %s is not in the help", w)
|
||||
}
|
||||
if c.build == nil && c.instead == "" {
|
||||
t.Errorf("nox %s has neither an owner nor an instead", w)
|
||||
}
|
||||
if _, dup := unowned[c.words[0]]; dup && len(c.words) == 1 {
|
||||
t.Errorf("nox %s is both owned and unowned", w)
|
||||
if c.build == nil {
|
||||
t.Errorf("nox %s has no owner", w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ADR 0590 §8 (issue 1126 review 1): each sensitive vault verb judges its own caller, and nox reaches the vault as its
|
||||
// ADR 0590 §8: each sensitive vault verb judges its own caller, and nox reaches the vault as its
|
||||
// machine's runtime, so nox first records the hand act that warrants the line through mesh-hand-acts (the vault verb as
|
||||
// its verb, what it acts on as its what) and names it as `act`; a recording refused calls the vault not at all.
|
||||
func TestASensitiveLineRecordsItsHandActAndNamesIt(t *testing.T) {
|
||||
@@ -322,3 +320,82 @@ func TestASensitiveLineRecordsItsHandActAndNamesIt(t *testing.T) {
|
||||
t.Errorf("a refused recording: exit %d, asked %+v, %q", code, *got, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
// 1126/AC1, 1126/AC2, 1126/AC3: the operator's overview of the licences is one line (one-question-one-tool): `nox licence` and
|
||||
// `nox licence list` call the licence manager's licences and bindings and print one table of each, every time local;
|
||||
// `nox licence usage` prints the readings; --json prints the raw answers, the two as one object.
|
||||
func TestTheLicencesAreOneTable(t *testing.T) {
|
||||
local := time.Local
|
||||
time.Local = time.FixedZone("CET", 3600)
|
||||
t.Cleanup(func() { time.Local = local })
|
||||
licences := `[{"name":"work","account":"a@example.org","kind":"subscription","bound":["ace","novox"],
|
||||
"usage":{"readAt":"2026-11-22T19:32:27Z","weeklyPct":2,"weeklyResetsAt":"2026-11-25T01:59:59.5+00:00",
|
||||
"sessionPct":7,"sessionResetsAt":"2026-11-23T00:29:59+00:00","sonnetPct":null},
|
||||
"accessExpiresAt":"2026-11-23T01:56:57Z","refreshExpiresAt":"2026-12-14T01:48:16Z","room":98,
|
||||
"failures":0,"conditions":[],"target":true},
|
||||
{"name":"home","account":"b@example.org","kind":"subscription","bound":[],
|
||||
"usage":{"weeklyPct":99,"weeklyResetsAt":"2026-11-25T10:59:59+00:00","sessionPct":null,"sonnetPct":40},
|
||||
"accessExpiresAt":"2026-11-23T02:02:57Z","failures":2,"conditions":["licence.home.full"],"target":false}]`
|
||||
bindings := `[{"consumer":"g14","licence":"home","kind":"subscription","generation":3,"since":"2026-11-22T19:32:28Z",
|
||||
"why":"work reached 99 % of its weekly window","by":"usage"}]`
|
||||
usage := `[{"at":1795376250078,"licence":"work","reading":{"weeklyPct":4,"weeklyResetsAt":"2026-11-29T17:59:59+00:00",
|
||||
"sessionPct":null,"sonnetPct":null}}]`
|
||||
answers := map[string]string{"anthropic-licence-manager.licences": licences,
|
||||
"anthropic-licence-manager.bindings": bindings, "anthropic-licence-manager.usage": usage}
|
||||
for _, words := range []string{"licence", "licence list"} {
|
||||
got := console(t, answers)
|
||||
code, out, errOut := runLine(strings.Fields(words)...)
|
||||
if code != 0 || errOut != "" || len(*got) != 2 || (*got)[0].Address != "anthropic-licence-manager.licences" ||
|
||||
(*got)[1].Address != "anthropic-licence-manager.bindings" || (*got)[1].Args != `{}` {
|
||||
t.Fatalf("nox %s: exit %d, stderr %q, asked %+v", words, code, errOut, *got)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"LICENCE", "KIND", "BOUND", "WEEKLY", "SESSION", "SONNET", "TOKEN EXPIRES", "FAILURES", "CONDITIONS", "TARGET",
|
||||
"work", "ace novox", "2 % (resets 2026-11-25 02:59)", "7 % (resets 2026-11-23 01:29)", "2026-11-23 02:56", "yes",
|
||||
"home", "99 % (resets 2026-11-25 11:59)", "40 %", "licence.home.full",
|
||||
"NODE", "SINCE", "WHY", "g14", "2026-11-22 20:32", "work reached 99 % of its weekly window",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("nox %s does not print %q:\n%s", words, want, out)
|
||||
}
|
||||
}
|
||||
if strings.Contains(out, "2026-12-14") || strings.Contains(out, "98") {
|
||||
t.Errorf("nox %s prints the refresh-token expiry or the room:\n%s", words, out)
|
||||
}
|
||||
}
|
||||
|
||||
// 1126/AC3: --json prints the raw answers, the two calls' as one object.
|
||||
console(t, answers)
|
||||
code, out, _ := runLine("licence", "--json")
|
||||
var raw struct {
|
||||
Licences []map[string]any `json:"licences"`
|
||||
Bindings []map[string]any `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(strings.SplitN(out, "\nanswered by", 2)[0]), &raw); code != 0 || err != nil ||
|
||||
len(raw.Licences) != 2 || len(raw.Bindings) != 1 {
|
||||
t.Errorf("nox licence --json: exit %d, %v:\n%s", code, err, out)
|
||||
}
|
||||
|
||||
// 1126/AC3: on every rendered line, as on the nodes.
|
||||
nodes := `{"keys":{"ace":{"assignments":{"decided":{"address":"10.0.0.1"},"modules":[]}}}}`
|
||||
console(t, map[string]string{"mesh-module-assigner.assignments": nodes})
|
||||
if code, out, _ := runLine("nodes", "--json"); code != 0 || !strings.HasPrefix(out, nodes) {
|
||||
t.Errorf("nox nodes --json: exit %d, does not print the raw answer:\n%s", code, out)
|
||||
}
|
||||
|
||||
// 1126/AC2: the usage readings as one table.
|
||||
got := console(t, answers)
|
||||
code, out, errOut := runLine("licence", "usage", "work")
|
||||
if code != 0 || len(*got) != 1 || (*got)[0].Address != "anthropic-licence-manager.usage" || (*got)[0].Args != `{"licence":"work"}` {
|
||||
t.Fatalf("nox licence usage work: exit %d, stderr %q, asked %+v", code, errOut, *got)
|
||||
}
|
||||
for _, want := range []string{"LICENCE", "READ AT", "WEEKLY", "SESSION", "RESETS", "work",
|
||||
time.UnixMilli(1795376250078).Local().Format("2006-01-02 15:04"), "4 %", "weekly 2026-11-29 18:59"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("nox licence usage does not print %q:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
if code, _, _ := runLine("licence", "usage", "--limit", "5"); code != 2 {
|
||||
t.Errorf("nox licence usage --limit is read (exit %d); it takes no limit", code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,8 +24,8 @@ func TestTheArchivePlacesExactlyOneFileAndTheConsolesAddressOne(t *testing.T) {
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Beside the program, one directory and one file: the console's address, from the mcp-endpoint it requires
|
||||
// (novox/hq issue 1126). Nothing else.
|
||||
// Beside the program, one directory and one file: the console's address, from the mcp-endpoint it requires.
|
||||
// Nothing else.
|
||||
var r map[string]any
|
||||
for _, res := range m.Resources {
|
||||
switch {
|
||||
@@ -43,7 +43,7 @@ func TestTheArchivePlacesExactlyOneFileAndTheConsolesAddressOne(t *testing.T) {
|
||||
if len(m.Resources) != 3 || r == nil || r["path"] != "/usr/local/bin" {
|
||||
t.Fatalf("its resources are %v", m.Resources)
|
||||
}
|
||||
// The build has a second artifact, the files archive the controller reads the templates back from; it
|
||||
// The build has a second artifact, the files archive the templates are read back from; it
|
||||
// places no file. The artifact the resource unpacks is the one that does.
|
||||
var a map[string]any
|
||||
for _, candidate := range m.Build.Artifacts {
|
||||
|
||||
@@ -108,10 +108,9 @@ var Homes = map[string]Home{
|
||||
// An owner's change not said on its views family past its bound (mesh-sdk views.UnsaidFinding, id <owner>.<state>):
|
||||
// written by each owner of a views family in its own findings (the indexer, the assigner), so no one observer.
|
||||
"view-unsaid": {Source: "views", Why: "every owner of a views family writes its own"},
|
||||
// The builder's own (design 51): a build that ended failed, a floor whose holder said nothing past its bound, an old
|
||||
// form held seven days by a counted node-engine, a tag's removal asked and not done.
|
||||
// The builder's own (design 51): a build that ended failed, an old form held seven days by a counted node-engine, a tag's
|
||||
// removal asked and not done. Its floor-silent went with its version floor (design 47 H2 H-A-553 (2)).
|
||||
"build-failed": {Source: "builder", Observer: builder},
|
||||
"floor-silent": {Source: "builder", Observer: builder},
|
||||
"old-form-held": {Source: "builder", Observer: builder},
|
||||
"tag-removal-not-done": {Source: "builder", Observer: builder},
|
||||
// The builder's publishing (design 51): a holder refused the publish, or said nothing past its bound (about the name);
|
||||
|
||||
@@ -366,7 +366,7 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
|
||||
}
|
||||
for kind, observer := range map[string]string{"needs-operator": watchman, "machine-network": watchman, "lease-split": selfCheck,
|
||||
"data-shrank": selfCheck, "retire-waiting": provisioner, "asks-undelivered": messenger,
|
||||
"image-missing": artifactStore, "build-failed": builder, "floor-silent": builder, "old-form-held": builder,
|
||||
"image-missing": artifactStore, "build-failed": builder, "old-form-held": builder,
|
||||
"tag-removal-not-done": builder, "seat-definition-unparsed": indexer, "generated-types-out-of-step": indexer,
|
||||
"seat-defined-twice": indexer, "accepted-unsaid": indexer, "manifest-held": indexer, "packages-token-refused": gitea,
|
||||
"publish-refused": builder, "publish-unanswered": builder, "seat-outcome-unread": builder} {
|
||||
@@ -374,6 +374,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
|
||||
t.Errorf("%s's home is %+v", kind, h)
|
||||
}
|
||||
}
|
||||
// Design 47 H2 H-A-553 (2): the builder's floor-silent went with its version floor, so no home names it.
|
||||
if h, ok := Homes["floor-silent"]; ok {
|
||||
t.Errorf("floor-silent still has a home: %+v", h)
|
||||
}
|
||||
for _, kind := range []string{"resolver-wrong", "holder-silent", "archives-missing", "archives-unheld", "binding-kept",
|
||||
"binding-moved", "binding-moving", "grant-composes-nothing", "root-not-free", "cleanup-waiting", "data-held-twice"} {
|
||||
if h := Homes[kind]; !h.Carried || h.Observer != "" || h.Why != Dropped {
|
||||
@@ -397,9 +401,10 @@ func TestEveryControllerKindHasItsHome(t *testing.T) {
|
||||
// first view, the owners' view too large, the builder's four, the indexer's four and the package seats' token refused.
|
||||
// And the builder's three publishing kinds and the delivery parts' family not heard: 103.
|
||||
// And the owners' changes not said, view-unsaid: 104. And the indexer's mesh-wide hold past its bound, manifest-held
|
||||
// (ADR 0632 §2): 105. (The bus module's own conditions, nats.status-unwritten among them, are said to the keeper
|
||||
// directly, never through findings, so they have no home here.)
|
||||
if len(Homes) != 105 || carried != 37 {
|
||||
// (ADR 0632 §2): 105. Less the builder's floor-silent, gone with its floor (design 47 H2 H-A-553 (2)): 104. (The bus
|
||||
// module's own conditions, nats.status-unwritten among them, are said to the keeper directly, never through findings, so
|
||||
// they have no home here.)
|
||||
if len(Homes) != 104 || carried != 37 {
|
||||
t.Errorf("the table holds %d kinds, %d carried", len(Homes), carried)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +169,11 @@ type testLog struct{ t *testing.T }
|
||||
func (w testLog) Write(p []byte) (int, error) {
|
||||
defer func() { _ = recover() }() // the bundle may speak after the test ended
|
||||
w.t.Logf("bundle: %s", strings.TrimRight(string(p), "\n"))
|
||||
// Built with -race, the bundle is too: a race it reports fails the test (issue 721 note 11: two events applied at once
|
||||
// to one record lost its delivery time).
|
||||
if strings.Contains(string(p), "WARNING: DATA RACE") {
|
||||
w.t.Error("the bundle reports a data race, above")
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ type Holder struct {
|
||||
refusals []string
|
||||
// tried counts the owed effects tried since this owner started, by how each ended (novox/hq issue 407).
|
||||
tried owedTries
|
||||
// applying keeps one event or tool call at a time on the delivery records the gate holds in memory (issue 721 note 11):
|
||||
// the runtime hands each event and each call to a goroutine of its own, and each is applied whole under this lock (take,
|
||||
// applied), so none reads a record another is halfway through writing. A record's entry is written to the ledger and then
|
||||
// to memory under it, so an event heard once that write lands (a pipeline-wanted after the running it ends on) is applied
|
||||
// only after memory holds it too. Taken before h.mu, never under it.
|
||||
applying sync.Mutex
|
||||
// reactMu keeps one React at a time; poke asks for a look (react.go); wanted is when the next is wanted, and its timer.
|
||||
reactMu sync.Mutex
|
||||
poke chan struct{}
|
||||
|
||||
@@ -7,6 +7,7 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -125,7 +126,33 @@ func handle(h *Holder, e stdio.Envelope) error {
|
||||
return taken
|
||||
}
|
||||
|
||||
// applied is a call applied whole, one at a time with the events (Holder.applying), its answer taken under the same lock: a
|
||||
// view of a record the gate keeps is written out before the next event writes that record. A verb that changes a delivery
|
||||
// asks for a look at what it makes possible (react.go).
|
||||
func (h *Holder) applied(run func(map[string]any) (any, error)) func(map[string]any) (any, error) {
|
||||
return func(a map[string]any) (any, error) {
|
||||
out, err := func() (any, error) {
|
||||
h.applying.Lock()
|
||||
defer h.applying.Unlock()
|
||||
out, err := run(a)
|
||||
if err != nil || out == nil {
|
||||
return out, err
|
||||
}
|
||||
raw, err := json.Marshal(out)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return json.RawMessage(raw), nil
|
||||
}()
|
||||
h.Poke()
|
||||
return out, err
|
||||
}
|
||||
}
|
||||
|
||||
// take applies one event whole, one at a time (Holder.applying).
|
||||
func take(h *Holder, e stdio.Envelope) error {
|
||||
h.applying.Lock()
|
||||
defer h.applying.Unlock()
|
||||
if h.Consumer != nil && h.Consumer.Takes(e.Key) {
|
||||
return h.Consumer.Hear(e)
|
||||
}
|
||||
@@ -265,14 +292,9 @@ func tools(h *Holder, l *listening) []stdio.Tool {
|
||||
list = append(list, headTools(h, meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
// The prune of heads by hand, now or kept from it (design 47 H2 §812, H-A-380 (3)).
|
||||
list = append(list, headsPruneTools(meshhandactsclient.Recorder{Ask: stdio.Ask})...)
|
||||
// A verb that changes a delivery asks for a look at what it makes possible (react.go).
|
||||
// Each call is applied whole, one at a time with the events, and asks for a look after (applied).
|
||||
for i := range list {
|
||||
run := list[i].Run
|
||||
list[i].Run = func(a map[string]any) (any, error) {
|
||||
out, err := run(a)
|
||||
h.Poke()
|
||||
return out, err
|
||||
}
|
||||
list[i].Run = h.applied(list[i].Run)
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
@@ -2,11 +2,14 @@ package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
)
|
||||
|
||||
// pipelineBed is a gate with one record open, of main at source revision 1, and its consumer.
|
||||
@@ -105,6 +108,121 @@ func TestARecordFollowsItsPipelineToTheMachines(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// hookedLedger is the ledger fake, told after each operation it took.
|
||||
type hookedLedger struct {
|
||||
*ledgerFake
|
||||
after func(instance, operation string, body any)
|
||||
}
|
||||
|
||||
func (l *hookedLedger) Apply(instance, operation string, body any) (uint64, error) {
|
||||
seq, err := l.ledgerFake.Apply(instance, operation, body)
|
||||
if err == nil && l.after != nil {
|
||||
l.after(instance, operation, body)
|
||||
}
|
||||
return seq, err
|
||||
}
|
||||
|
||||
// 721/AC1 (issue 721 note 11; design 47 H2 §810): the runtime hands each event and each call to a goroutine of its own, so
|
||||
// one can be heard once a running's outcome is in the ledger and before the gate's memory holds it. Heard then, it waits
|
||||
// until the running is applied whole: a pipeline-wanted ends the record with its delivery time and class (applied at once it
|
||||
// ended the record with neither, the delivery time lost), and the call show answers the record with the running, its answer
|
||||
// taken before the next event writes the record.
|
||||
func TestWhatIsHeardWhileAnEventIsWrittenWaitsUntilItIsApplied(t *testing.T) {
|
||||
running := func(node string) stdio.Envelope {
|
||||
return stdio.Envelope{Key: "node-engine.running." + node + ".app", Node: node, Body: json.RawMessage(
|
||||
`{"v":1,"at":"2026-11-20T03:05:00Z","module":"app","node":"` + node + `","fingerprint":"f","healthy":true}`)}
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
heard func(h *Holder) (any, error)
|
||||
check func(t *testing.T, h *Holder, answer any)
|
||||
}{
|
||||
{"pipeline-wanted", func(h *Holder) (any, error) {
|
||||
return nil, take(h, stdio.Envelope{Key: "mesh-wants.pipeline-wanted.main.1", Body: json.RawMessage(
|
||||
`{"v":1,"pipeline":"main.1","branch":"main","source":1,"outcome":"running"}`)})
|
||||
}, func(t *testing.T, h *Holder, _ any) {
|
||||
r, err := h.Records.ByKey("main", 1)
|
||||
if err != nil || r == nil || r.Ended == nil || r.DeliveryTime != "5m0s" || r.Class != catalogue.ClassCore {
|
||||
t.Fatalf("the record ended %+v keeping the delivery time %q and the class %q (%v); want 5m0s and core", r.Ended,
|
||||
r.DeliveryTime, r.Class, err)
|
||||
}
|
||||
}},
|
||||
{"the call show", func(h *Holder) (any, error) {
|
||||
for _, tool := range tools(h, &listening{}) {
|
||||
if tool.Name == Seat+".show" {
|
||||
return tool.Run(map[string]any{"id": "main.1"})
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("the gate serves no %s.show", Seat)
|
||||
}, func(t *testing.T, h *Holder, answer any) {
|
||||
if err := take(h, running("g14")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := json.Marshal(answer)
|
||||
if !strings.Contains(string(raw), OutcomeKey("app", "f", "ace", StepRunning)) || strings.Contains(string(raw), "g14") {
|
||||
t.Fatalf("show answered %.600s: want the running on ace, and nothing the next event wrote", raw)
|
||||
}
|
||||
// Every call runs under the lock the events take.
|
||||
if _, err := h.applied(func(map[string]any) (any, error) {
|
||||
if h.applying.TryLock() {
|
||||
h.applying.Unlock()
|
||||
return nil, errors.New("a call runs while an event can write the records")
|
||||
}
|
||||
return nil, nil
|
||||
})(nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
now := time.Date(2026, 11, 20, 3, 0, 0, 0, time.UTC)
|
||||
h := &Holder{Now: func() time.Time { return now }}
|
||||
ledger := &hookedLedger{ledgerFake: newLedgerFake(t)}
|
||||
h.Records = &Records{Ledger: ledger, Now: h.Now, Class: func(string) (string, error) { return catalogue.ClassCore, nil }}
|
||||
h.Consumer = &StepConsumer{Records: h.Records, Families: stepFamilies, Now: h.Now, Taken: h.TakenIn, Follow: h.Follow}
|
||||
if _, _, err := h.Records.Open(opening("main", 1, map[string]string{"novox/app@5": strings.Repeat("a", 40)})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := h.Records.Kept(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := take(h, stdio.Envelope{Key: "mesh-pipeline-runner.pipeline-started.main.1", Body: json.RawMessage(
|
||||
`{"v":1,"branch":"main","source":1,"pipeline":"main.1","call":"0000000000000001","movers":[{"module":"app","commit":"c","fingerprint":"f","repository":"novox/app","tier":1}]}`)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = now.Add(5 * time.Minute)
|
||||
type heardOut struct {
|
||||
answer any
|
||||
err error
|
||||
}
|
||||
heard := make(chan heardOut, 1)
|
||||
ledger.after = func(_, operation string, body any) {
|
||||
if o, ok := body.(RecordOutcome); !ok || operation != OpOutcome || o.Step != StepRunning {
|
||||
return
|
||||
}
|
||||
ledger.after = nil
|
||||
// Heard as the running's write lands: taken there and then when nothing holds the records, as the runtime's
|
||||
// goroutines allow, else on a goroutine of its own, as the runtime hands it.
|
||||
hear := func() { answer, err := tc.heard(h); heard <- heardOut{answer, err} }
|
||||
if h.applying.TryLock() {
|
||||
h.applying.Unlock()
|
||||
hear()
|
||||
return
|
||||
}
|
||||
go hear()
|
||||
}
|
||||
if err := take(h, running("ace")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := <-heard
|
||||
if out.err != nil {
|
||||
t.Fatal(out.err)
|
||||
}
|
||||
tc.check(t, h, out.answer)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// GATE-5/AC (design 47 H §738, §751; H-A-75, H-A-89 (3), (4)): a pipeline-ended not passed ends the record failed naming
|
||||
// the pipeline's why, and pipeline-wanted tier-late ends it failed naming the movers and machines not running.
|
||||
func TestARecordEndsFailedOnAPipelineNotPassedOrATierLate(t *testing.T) {
|
||||
|
||||
@@ -327,6 +327,11 @@ func entry(name, storage, template string, options map[string]string) catalogue.
|
||||
func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) {
|
||||
ledger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "16"})
|
||||
ledger.Types = []catalogue.LedgerType{{Name: "decision", Indexes: []catalogue.LedgerIndex{{Name: "by-topic", On: []string{"topic"}}}}}
|
||||
// A ledger's state and index buckets take its max-mib and no other option of it (design 47 H2's corrections, item 12, H-A-636).
|
||||
bigLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, map[string]string{"max-mib": "1024", "history": "5"})
|
||||
bigLedger.Types = ledger.Types
|
||||
plainLedger := entry("records", catalogue.StorageLedger, catalogue.TemplateLedger, nil)
|
||||
plainLedger.Types = ledger.Types
|
||||
bare := entry("raw", catalogue.StorageStream, "", nil)
|
||||
bare.Configuration = map[string]json.RawMessage{"when-full": json.RawMessage(`"drop-oldest"`), "max-mib": json.RawMessage("8"), "max-age-days": json.RawMessage("3")}
|
||||
forGood := entry("reviews", catalogue.StorageStream, "", nil)
|
||||
@@ -368,9 +373,21 @@ func TestEachTemplateIsPlannedUnderTheModulesNames(t *testing.T) {
|
||||
binding: "objects mesh-knowledge_outputs"},
|
||||
{name: "ledger", entry: ledger,
|
||||
objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {16 MiB, age 0, history 0, new, size 262144}; " +
|
||||
"key-value mesh-knowledge_records_state {16 MiB, age 0, history 1, new, size 262144}; " +
|
||||
"key-value mesh-knowledge_records_index-by-topic {16 MiB, age 0, history 1, new, size 262144}; " +
|
||||
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}",
|
||||
binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"},
|
||||
{name: "ledger naming max-mib 1024 and past values: its state and index buckets at 1 GiB, no other option reaching them (H-A-636)", entry: bigLedger,
|
||||
objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " +
|
||||
"key-value mesh-knowledge_records_state {1024 MiB, age 0, history 1, new, size 262144}; " +
|
||||
"key-value mesh-knowledge_records_index-by-topic {1024 MiB, age 0, history 1, new, size 262144}; " +
|
||||
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}",
|
||||
binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"},
|
||||
{name: "ledger naming no max-mib: its state and index buckets at the state default (H-A-636)", entry: plainLedger,
|
||||
objects: "stream mesh-knowledge_records [mesh.ledger.mesh-knowledge.records.history.>] {1024 MiB, age 0, history 0, new, size 262144}; " +
|
||||
"key-value mesh-knowledge_records_state {64 MiB, age 0, history 1, new, size 262144}; " +
|
||||
"key-value mesh-knowledge_records_index-by-topic {64 MiB, age 0, history 1, new, size 262144}; " +
|
||||
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {16 MiB, age 0, history 1, old, size 0}",
|
||||
"stream mesh-knowledge_records_snapshot [mesh.ledger.mesh-knowledge.records.snapshot.>] {1024 MiB, age 0, history 1, old, size 0}",
|
||||
binding: "history mesh-knowledge_records on mesh.ledger.mesh-knowledge.records.history, state mesh-knowledge_records_state, indexes map[by-topic:mesh-knowledge_records_index-by-topic], snapshot mesh.ledger.mesh-knowledge.records.snapshot"},
|
||||
{name: "bare stream", entry: bare,
|
||||
objects: "stream mesh-knowledge_raw [mesh.bus.mesh-knowledge.raw.>] {8 MiB, age 259200, history 0, old, size 0}",
|
||||
|
||||
@@ -229,7 +229,13 @@ func PlanOf(module string, e catalogue.BusStateEntry) (Plan, error) {
|
||||
return Plan{}, err
|
||||
}
|
||||
history.MaxAgeSeconds = days(age)
|
||||
state, err := stateSettings(options{})
|
||||
// The state bucket and each index bucket take the ledger's own max-mib, as its history and snapshot do, and no
|
||||
// other option of it; with none they keep the state default (design 47 H2's corrections, item 12, H-A-636).
|
||||
stateOpts := options{}
|
||||
if raw, ok := opts.raw[catalogue.OptionCapMiB]; ok {
|
||||
stateOpts.raw = map[string]json.RawMessage{catalogue.OptionCapMiB: raw}
|
||||
}
|
||||
state, err := stateSettings(stateOpts)
|
||||
if err != nil {
|
||||
return Plan{}, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# networkmanager
|
||||
|
||||
The machine's network, managed by NetworkManager: this module holds the node seat `node-uplink` (novox/hq ADR 0241),
|
||||
answering its verbs `resolvers` and `links`, writes the machine's resolver file from the mesh's resolvers (ADR 0117,
|
||||
ADR 0223), and reacts when the network asks the person to sign in on its **sign-in page** (ADR 0687, ADR 0689; design
|
||||
08 sign-in-page §11 to §27).
|
||||
|
||||
## Two parts and the folder they share
|
||||
|
||||
Behind a sign-in page the private network's tunnel, and with it the bus, is out of reach, and the tool runner starts
|
||||
no bundle before it has reached the bus. So the reaction runs in two parts:
|
||||
|
||||
- **the watcher**, the process `networkmanager-sign-in` (`uplink-tools watch`), started by the machine's service
|
||||
manager at boot as the machine's account and kept running, needing no bus. It hears NetworkManager's rating of the
|
||||
network, opens the sign-in page, tells the person, and keeps the events.
|
||||
- **the bundle** `uplink-tools`, in the tool runner once it has reached the bus: it answers `resolvers` and `links`,
|
||||
serves the tools below, publishes the kept events and calls `uplink-names`.
|
||||
|
||||
They share only the module's own folder, `~/.local/state/mesh/networkmanager` (the account's, mode 0700), every file
|
||||
written whole (beside, then renamed over):
|
||||
|
||||
| file | what |
|
||||
|---|---|
|
||||
| `watch.sock` | the watcher's socket: one JSON line asked, one answered; `state` answers its state, `rating-again` makes it subscribe again and act on the rating read now |
|
||||
| `check-address` | NetworkManager's check address, written by the watcher at its start and at each change |
|
||||
| `pending/` | the kept changes, one `<sequence>.json` each holding the event, its sequence and its body with no node, written by the watcher and deleted by the bundle once the bus acknowledged it |
|
||||
| `names.json` | the bundle's last `uplink-names` call: the names, its result (`ok`, `no holder` or the failure) and when |
|
||||
| `sequence` | the next sequence of the watcher's kept changes, never reset while the folder lives |
|
||||
|
||||
The folder's `unknown` is `module`: the node-engine does nothing inside it, and the watcher leaves any other path it
|
||||
finds there as it is and writes it to its journal once per path. When the module leaves, the node-engine keeps the
|
||||
folder while it holds files, and nothing reads it then.
|
||||
|
||||
## The watcher opens the page on its own machine, without the bus
|
||||
|
||||
It hears NetworkManager's `PropertiesChanged` on the system bus for the rating (`Connectivity`), the active connection
|
||||
and the check (`ConnectivityCheckEnabled`, `ConnectivityCheckAvailable`, `ConnectivityCheckUri`); nothing runs on a
|
||||
timer, and the check itself stays NetworkManager's. When its system bus connection drops it subscribes again as the
|
||||
bus's socket comes back.
|
||||
|
||||
With the check on, it opens the check address in the person's default browser and shows a notification saying why at
|
||||
three moments: when the rating becomes PORTAL on the active connection, at its own start while the rating is PORTAL,
|
||||
and when the person's graphical session starts while it is. It acts once per ask: again only after the rating left
|
||||
PORTAL, a session's start and its own restart excepted. When the rating leaves PORTAL for FULL it says the network is
|
||||
open. An open that failed gives a critical notification naming the reason and the address.
|
||||
|
||||
It opens with `systemd-run --user --collect --quiet --wait -- xdg-open <address>`, the address one argument and never
|
||||
through a shell, after asking `xdg-mime query default x-scheme-handler/<scheme>` for the program: the browser runs
|
||||
under the person's user manager and outlives the watcher. An open still running after 10 s is said as opening.
|
||||
|
||||
**How it finds the person's session.** Over the system bus it asks logind for its account's sessions: the one of type
|
||||
`x11` or `wayland`, not remote, active or online. Its session bus is `<RuntimePath>/bus`, and its display is in the user
|
||||
manager's environment (`DISPLAY` and `XAUTHORITY`, which the X11 start block imports; `WAYLAND_DISPLAY` for a Wayland
|
||||
start block). No such session, or no display named there, is no session: then it opens and shows nothing, and still
|
||||
keeps the events. **How it hears a session start:** logind's `SessionNew`; for a graphical session of its account it
|
||||
reads the user manager's environment again at each file event in `/tmp/.X11-unix` (an X server's socket) and in the
|
||||
session's runtime directory (a Wayland socket), for at most 60 s, since the user manager says no change of its
|
||||
`Environment`; past that it writes that the start was not acted on.
|
||||
|
||||
## The events: kept by the watcher, published by the bundle
|
||||
|
||||
From NetworkManager's own rating the watcher keeps `node-uplink`'s two events, `sign-in-asked` (node, link, network,
|
||||
the address opened, when) and `sign-in-ended` (node, link, network, when, and why: `signed-in`, `left` or
|
||||
`no-longer-asked`), at most 256 of them, the oldest dropped past that with a journal line. With the check switched
|
||||
off (not enabled, or not available) it neither opens nor keeps anything. The bundle publishes them in order on the
|
||||
seat's subject `mesh.seat.node-uplink.event.<event>.<node>`, each under the message id `<node>.<event>.<sequence>`,
|
||||
the bundle's own node filled into the subject, the id and the body (the watcher names no node), awaiting the stream's
|
||||
acknowledgement, at its start, at each new kept event and when its bus connection comes back; a refused one waits for
|
||||
the next moment. Nothing in the mesh consumes them: they are its record, read with `nats.nats_stream_messages`
|
||||
filtered to `mesh.seat.node-uplink.event.*.<node>`, their time in `at`.
|
||||
|
||||
## The bundle gives the resolver the check's host name
|
||||
|
||||
Where a module holds `node-resolver` on this node (the assignments say which), the bundle calls its `uplink-names`
|
||||
with the check address's host name, so NetworkManager's own check resolves through the network it tests: at its start,
|
||||
when `check-address` changes, when its bus connection comes back and when the node-engine says that holder runs. With no holder it calls nothing, and that is no failure.
|
||||
|
||||
## Tools
|
||||
|
||||
| tool | what |
|
||||
|---|---|
|
||||
| `uplink_sign_in` | the reaction as it stands: the watcher's state, the events waiting and the publishes refused, the last `uplink-names` call, the resolver's refusal of the names |
|
||||
| `uplink_names_again` | call `uplink-names` now |
|
||||
| `uplink_rating_again` | make the watcher subscribe again and act on the rating now |
|
||||
| `uplink_publish_again` | publish the kept events now |
|
||||
| `uplink_health` | whether the reaction works: unhealthy while the watcher's socket does not answer, while it is not subscribed, or while the last `uplink-names` call stands failed; a tool to read, not a health check |
|
||||
|
||||
**The watcher's health is its unit's state** (`networkmanager-sign-in` active), judged on the machine without the bus,
|
||||
so it holds behind a sign-in page. When the system bus comes back and the watcher cannot subscribe on it again, it
|
||||
writes the reason to its journal and exits non-zero, so its unit shows failing and the service manager restarts it.
|
||||
`uplink_health` is a tool, not a health check; the watcher not subscribed and a failed `uplink-names` call are also
|
||||
shown by `uplink_sign_in` and written to the journal.
|
||||
@@ -0,0 +1,108 @@
|
||||
package main
|
||||
|
||||
// The bundle's own work beside the seat's verbs (design 08 sign-in-page §11, §13, §20): started by the tool runner
|
||||
// once it reached the bus. It acts at its start, at file events of the kernel in the module's folder, and when its bus
|
||||
// connection comes back: the first heartbeat of its consumer answered after a missed one (DMC-4).
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
type bundle struct {
|
||||
folder Folder
|
||||
pub *publisher
|
||||
names *namer
|
||||
|
||||
mu sync.Mutex
|
||||
missed bool
|
||||
lastAt time.Time
|
||||
}
|
||||
|
||||
// bundleRuns is what the bundle hears through: file events of the kernel, its consumer's heartbeat and its
|
||||
// subscription.
|
||||
type bundleRuns struct {
|
||||
files func(dirs []string, stop <-chan struct{}) <-chan struct{}
|
||||
fileMade func(dir, name string, stop <-chan struct{}) <-chan struct{}
|
||||
onHeartbeat func(func(stdio.Heartbeat)) error
|
||||
subscribe func(pattern string, handle func(stdio.Envelope) error) error
|
||||
}
|
||||
|
||||
func newBundle(f Folder) *bundle {
|
||||
return &bundle{folder: f, pub: &publisher{folder: f, publish: seatPublish},
|
||||
names: &namer{folder: f, ask: stdio.Ask, now: time.Now}}
|
||||
}
|
||||
|
||||
// seatPublish says a kept event through the runtime, which awaits the stream's acknowledgement.
|
||||
func seatPublish(subject string, body json.RawMessage, id string) error {
|
||||
return stdio.SeatPublish(subject, body, id)
|
||||
}
|
||||
|
||||
// start publishes what is kept and gives the resolver the check's host name, then does each again at its moments: a
|
||||
// file event on pending/ publishes, a changed check-address gives the names, node-resolver's holder running gives the
|
||||
// names, and the bus connection's return does both (§13, §20).
|
||||
func (b *bundle) start(runs bundleRuns) {
|
||||
pending := filepath.Join(b.folder.Dir, pendingName)
|
||||
if err := os.MkdirAll(pending, 0o700); err != nil {
|
||||
journal("making %s failed: %v", pending, err)
|
||||
}
|
||||
kept := runs.files([]string{pending}, nil)
|
||||
check := runs.fileMade(b.folder.Dir, checkName, nil)
|
||||
b.pub.publishKept("the bundle's start")
|
||||
b.names.give("the bundle's start")
|
||||
if err := runs.subscribe(runningPattern, b.names.running); err != nil {
|
||||
journal("subscribing to %s failed: %v", runningPattern, err)
|
||||
}
|
||||
if err := runs.onHeartbeat(b.heartbeat); err != nil {
|
||||
journal("hearing the bus connection's heartbeat failed: %v", err)
|
||||
}
|
||||
for kept != nil || check != nil {
|
||||
select {
|
||||
case _, ok := <-kept:
|
||||
if !ok {
|
||||
kept = nil
|
||||
continue
|
||||
}
|
||||
b.pub.publishKept("a kept event")
|
||||
case _, ok := <-check:
|
||||
if !ok {
|
||||
check = nil
|
||||
continue
|
||||
}
|
||||
b.names.give("a changed check address")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// heartbeat hears the consumer's heartbeat: the first one answered after a missed one is the connection come back.
|
||||
func (b *bundle) heartbeat(hb stdio.Heartbeat) {
|
||||
b.mu.Lock()
|
||||
if !hb.At.IsZero() && hb.At.Before(b.lastAt) {
|
||||
b.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if !hb.At.IsZero() {
|
||||
b.lastAt = hb.At
|
||||
}
|
||||
back := !hb.Missed && b.missed
|
||||
b.missed = hb.Missed
|
||||
b.mu.Unlock()
|
||||
if hb.Missed {
|
||||
journal("the bus connection's heartbeat was missed: %s", hb.Why)
|
||||
}
|
||||
if back {
|
||||
journal("the bus connection came back")
|
||||
b.reconnected()
|
||||
}
|
||||
}
|
||||
|
||||
// reconnected is the work at the bus connection's return.
|
||||
func (b *bundle) reconnected() {
|
||||
b.pub.publishKept("the bus connection's return")
|
||||
b.names.give("the bus connection's return")
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
package main
|
||||
|
||||
// The watcher's system bus, through godbus: the network manager's properties and its PropertiesChanged, logind's
|
||||
// SessionNew, and the system bus's socket coming back, heard as a file event of the kernel on its folder.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unsafe"
|
||||
|
||||
"github.com/godbus/dbus/v5"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const (
|
||||
nmName = "org.freedesktop.NetworkManager"
|
||||
nmPath = dbus.ObjectPath("/org/freedesktop/NetworkManager")
|
||||
nmActive = "org.freedesktop.NetworkManager.Connection.Active"
|
||||
nmDevice = "org.freedesktop.NetworkManager.Device"
|
||||
propsIface = "org.freedesktop.DBus.Properties"
|
||||
login1Name = "org.freedesktop.login1"
|
||||
login1Path = dbus.ObjectPath("/org/freedesktop/login1")
|
||||
login1Iface = "org.freedesktop.login1.Manager"
|
||||
)
|
||||
|
||||
// systemSocket is the system bus's socket, whose folder the watcher watches when its connection dropped.
|
||||
var systemSocket = "/run/dbus/system_bus_socket"
|
||||
|
||||
// ratingProperties are the network manager's properties whose change the watcher acts on (§14).
|
||||
var ratingProperties = map[string]bool{"Connectivity": true, "PrimaryConnection": true,
|
||||
"ConnectivityCheckEnabled": true, "ConnectivityCheckAvailable": true, "ConnectivityCheckUri": true}
|
||||
|
||||
type dbusSystem struct {
|
||||
conn *dbus.Conn
|
||||
}
|
||||
|
||||
func dialSystemBus() (systemBus, error) {
|
||||
conn, err := dbus.ConnectSystemBus()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dbusSystem{conn: conn}, nil
|
||||
}
|
||||
|
||||
func (d *dbusSystem) close() { d.conn.Close() }
|
||||
|
||||
func (d *dbusSystem) listen() (<-chan signal, error) {
|
||||
if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(nmPath), dbus.WithMatchInterface(propsIface),
|
||||
dbus.WithMatchMember("PropertiesChanged")); err != nil {
|
||||
return nil, fmt.Errorf("hearing the network manager: %w", err)
|
||||
}
|
||||
if err := d.conn.AddMatchSignal(dbus.WithMatchObjectPath(login1Path), dbus.WithMatchInterface(login1Iface),
|
||||
dbus.WithMatchMember("SessionNew")); err != nil {
|
||||
return nil, fmt.Errorf("hearing logind: %w", err)
|
||||
}
|
||||
in := make(chan *dbus.Signal, 64)
|
||||
d.conn.Signal(in)
|
||||
out := make(chan signal)
|
||||
go func() {
|
||||
// godbus closes in when the connection drops.
|
||||
for s := range in {
|
||||
if heard, ok := readSignal(s); ok {
|
||||
out <- heard
|
||||
}
|
||||
}
|
||||
close(out)
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// readSignal is what the watcher hears in a signal of the system bus: the network manager's PropertiesChanged naming
|
||||
// a property of the rating, or logind's SessionNew with the new session's object.
|
||||
func readSignal(s *dbus.Signal) (signal, bool) {
|
||||
switch {
|
||||
case s.Path == nmPath && s.Name == propsIface+".PropertiesChanged" && len(s.Body) >= 3:
|
||||
if iface, _ := s.Body[0].(string); iface != nmName {
|
||||
return signal{}, false
|
||||
}
|
||||
changed, _ := s.Body[1].(map[string]dbus.Variant)
|
||||
for name := range changed {
|
||||
if ratingProperties[name] {
|
||||
return signal{Rating: true}, true
|
||||
}
|
||||
}
|
||||
invalidated, _ := s.Body[2].([]string)
|
||||
for _, name := range invalidated {
|
||||
if ratingProperties[name] {
|
||||
return signal{Rating: true}, true
|
||||
}
|
||||
}
|
||||
case s.Path == login1Path && s.Name == login1Iface+".SessionNew" && len(s.Body) >= 2:
|
||||
if path, ok := s.Body[1].(dbus.ObjectPath); ok {
|
||||
return signal{Session: string(path)}, true
|
||||
}
|
||||
}
|
||||
return signal{}, false
|
||||
}
|
||||
|
||||
func (d *dbusSystem) rating() (Rating, error) {
|
||||
nm := d.conn.Object(nmName, nmPath)
|
||||
var r Rating
|
||||
for name, into := range map[string]any{"Connectivity": &r.Connectivity, "ConnectivityCheckEnabled": &r.CheckEnabled,
|
||||
"ConnectivityCheckAvailable": &r.CheckAvailable, "ConnectivityCheckUri": &r.CheckURI} {
|
||||
v, err := nm.GetProperty(nmName + "." + name)
|
||||
if err != nil {
|
||||
return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err)
|
||||
}
|
||||
if err := v.Store(into); err != nil {
|
||||
return Rating{}, fmt.Errorf("the network manager's %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
v, err := nm.GetProperty(nmName + ".PrimaryConnection")
|
||||
if err != nil {
|
||||
return Rating{}, fmt.Errorf("the network manager's PrimaryConnection: %w", err)
|
||||
}
|
||||
path, _ := v.Value().(dbus.ObjectPath)
|
||||
r.Connection = string(path)
|
||||
if !r.active() {
|
||||
return r, nil
|
||||
}
|
||||
// A connection that went between the two reads is read as it is said: its name and link empty.
|
||||
active := d.conn.Object(nmName, path)
|
||||
if v, err := active.GetProperty(nmActive + ".Id"); err == nil {
|
||||
r.Network, _ = v.Value().(string)
|
||||
}
|
||||
if v, err := active.GetProperty(nmActive + ".Devices"); err == nil {
|
||||
if devices, _ := v.Value().([]dbus.ObjectPath); len(devices) > 0 {
|
||||
if v, err := d.conn.Object(nmName, devices[0]).GetProperty(nmDevice + ".Interface"); err == nil {
|
||||
r.Link, _ = v.Value().(string)
|
||||
}
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// systemSocketExists says whether the system bus's socket is there now.
|
||||
func systemSocketExists() bool {
|
||||
_, err := os.Stat(systemSocket)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// systemSocketThere fires at each file event of the kernel that makes the system bus's socket in its folder, until stop
|
||||
// closes: the one moment, beside rating-again, the watcher dials the system bus again (§14; note d). It never fires
|
||||
// for a socket that is merely there, so a bus that refuses the watcher is not dialled again in a loop.
|
||||
func systemSocketThere(stop <-chan struct{}) <-chan struct{} {
|
||||
return fileMade(filepath.Dir(systemSocket), filepath.Base(systemSocket), stop)
|
||||
}
|
||||
|
||||
// readInotify reads the names of one read's file events; an error once the descriptor is closed.
|
||||
func readInotify(f *os.File) ([]string, error) {
|
||||
buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1))
|
||||
n, err := f.Read(buf)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrClosed) {
|
||||
journal("a watch of file events failed: %v", err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
for off := 0; off+unix.SizeofInotifyEvent <= n; {
|
||||
ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off]))
|
||||
nameAt := off + unix.SizeofInotifyEvent
|
||||
end := nameAt + int(ev.Len)
|
||||
if end > n {
|
||||
break
|
||||
}
|
||||
name := buf[nameAt:end]
|
||||
for i, b := range name {
|
||||
if b == 0 {
|
||||
name = name[:i]
|
||||
break
|
||||
}
|
||||
}
|
||||
names = append(names, string(name))
|
||||
off = end
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (d *dbusSystem) sessions(uid uint32) ([]loginSession, error) {
|
||||
var listed []struct {
|
||||
ID string
|
||||
UID uint32
|
||||
User string
|
||||
Seat string
|
||||
Path dbus.ObjectPath
|
||||
}
|
||||
if err := d.conn.Object(login1Name, login1Path).Call(login1Iface+".ListSessions", 0).Store(&listed); err != nil {
|
||||
return nil, fmt.Errorf("logind's sessions: %w", err)
|
||||
}
|
||||
var out []loginSession
|
||||
for _, l := range listed {
|
||||
if l.UID != uid {
|
||||
continue
|
||||
}
|
||||
s, err := d.session(string(l.Path))
|
||||
if err != nil {
|
||||
journal("reading session %s failed: %v", l.ID, err)
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (d *dbusSystem) session(path string) (loginSession, error) {
|
||||
o := d.conn.Object(login1Name, dbus.ObjectPath(path))
|
||||
s := loginSession{Path: path}
|
||||
var user struct {
|
||||
UID uint32
|
||||
Path dbus.ObjectPath
|
||||
}
|
||||
for name, into := range map[string]any{"Id": &s.ID, "Type": &s.Type, "Remote": &s.Remote, "State": &s.State,
|
||||
"User": &user} {
|
||||
v, err := o.GetProperty("org.freedesktop.login1.Session." + name)
|
||||
if err != nil {
|
||||
return s, fmt.Errorf("session %s's %s: %w", path, name, err)
|
||||
}
|
||||
if err := dbus.Store([]any{v.Value()}, into); err != nil {
|
||||
return s, fmt.Errorf("session %s's %s: %w", path, name, err)
|
||||
}
|
||||
}
|
||||
s.UID = user.UID
|
||||
v, err := d.conn.Object(login1Name, user.Path).GetProperty("org.freedesktop.login1.User.RuntimePath")
|
||||
if err != nil {
|
||||
return s, fmt.Errorf("the user %d's RuntimePath: %w", user.UID, err)
|
||||
}
|
||||
s.RuntimePath, _ = v.Value().(string)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// userEnvironment is the user manager's Environment, read over the session bus at bus.
|
||||
func userEnvironment(bus string) ([]string, error) {
|
||||
conn, err := dbus.Connect(bus)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
v, err := conn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1").
|
||||
GetProperty("org.freedesktop.systemd1.Manager.Environment")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
env, _ := v.Value().([]string)
|
||||
return env, nil
|
||||
}
|
||||
|
||||
// fileEvents fires at each file event of the kernel that makes a file in one of dirs (a burst is one), until stop
|
||||
// closes. A folder that is not there is not watched, and said.
|
||||
func fileEvents(dirs []string, stop <-chan struct{}) <-chan struct{} {
|
||||
return watchFiles(dirs, nil, stop)
|
||||
}
|
||||
|
||||
// fileMade fires at each file event of the kernel that makes name in dir, until stop closes.
|
||||
func fileMade(dir, name string, stop <-chan struct{}) <-chan struct{} {
|
||||
return watchFiles([]string{dir}, func(made string) bool { return made == name }, stop)
|
||||
}
|
||||
|
||||
// watchFiles fires at each file event that makes a file in dirs whose name match takes (any, when nil).
|
||||
func watchFiles(dirs []string, match func(string) bool, stop <-chan struct{}) <-chan struct{} {
|
||||
out := make(chan struct{}, 1)
|
||||
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
|
||||
if err != nil {
|
||||
journal("watching %v failed: %v", dirs, err)
|
||||
return out
|
||||
}
|
||||
for _, dir := range dirs {
|
||||
if _, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO); err != nil {
|
||||
journal("watching %s failed: %v", dir, err)
|
||||
}
|
||||
}
|
||||
f := os.NewFile(uintptr(fd), "inotify")
|
||||
go func() {
|
||||
<-stop
|
||||
f.Close()
|
||||
}()
|
||||
go func() {
|
||||
defer f.Close()
|
||||
for {
|
||||
names, err := readInotify(f)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
matched := match == nil
|
||||
for _, name := range names {
|
||||
matched = matched || match(name)
|
||||
}
|
||||
if !matched {
|
||||
continue
|
||||
}
|
||||
select {
|
||||
case out <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
// pathsMade hands each path a file event of the kernel makes in one of dirs, until stop closes; a folder that is not
|
||||
// there is not watched, and said.
|
||||
func pathsMade(dirs []string, stop <-chan struct{}) <-chan string {
|
||||
out := make(chan string, 16)
|
||||
fd, err := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK)
|
||||
if err != nil {
|
||||
journal("watching %v failed: %v", dirs, err)
|
||||
return out
|
||||
}
|
||||
wds := map[int32]string{}
|
||||
for _, dir := range dirs {
|
||||
wd, err := unix.InotifyAddWatch(fd, dir, unix.IN_CREATE|unix.IN_MOVED_TO)
|
||||
if err != nil {
|
||||
journal("watching %s failed: %v", dir, err)
|
||||
continue
|
||||
}
|
||||
wds[int32(wd)] = dir
|
||||
}
|
||||
f := os.NewFile(uintptr(fd), "inotify")
|
||||
go func() {
|
||||
<-stop
|
||||
f.Close()
|
||||
}()
|
||||
go func() {
|
||||
defer f.Close()
|
||||
buf := make([]byte, 64*(unix.SizeofInotifyEvent+unix.NAME_MAX+1))
|
||||
for {
|
||||
n, err := f.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for off := 0; off+unix.SizeofInotifyEvent <= n; {
|
||||
ev := (*unix.InotifyEvent)(unsafe.Pointer(&buf[off]))
|
||||
nameAt := off + unix.SizeofInotifyEvent
|
||||
end := nameAt + int(ev.Len)
|
||||
if end > n {
|
||||
break
|
||||
}
|
||||
name := string(bytes.TrimRight(buf[nameAt:end], "\x00"))
|
||||
off = end
|
||||
if dir, ok := wds[ev.Wd]; ok && name != "" {
|
||||
select {
|
||||
case out <- filepath.Join(dir, name):
|
||||
case <-stop:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// The uplink holder's tools bundle: the node-uplink seat's verbs (novox/hq ADR 0241), served by the node's
|
||||
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own. stdout is
|
||||
// runtime as the operator account. uplink.go is every holder's; manager.go is this holder's own, and gives the
|
||||
// holder's own subcommands, tools and the work its bundle starts beside them (design 08 sign-in-page §11). stdout is
|
||||
// the MCP channel; this says nothing else.
|
||||
package main
|
||||
|
||||
@@ -11,8 +12,16 @@ import (
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func tools(m Machine) []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
// holderOwn is what a holder adds to the seat's verbs, from its manager.go: its subcommands (a process of the module
|
||||
// runs one, as `uplink-tools <name>`), its own tools and the work its bundle starts once it serves.
|
||||
type holderOwn struct {
|
||||
Commands map[string]func(args []string) error
|
||||
Tools []stdio.Tool
|
||||
Start func()
|
||||
}
|
||||
|
||||
func tools(m Machine, own holderOwn) []stdio.Tool {
|
||||
return append([]stdio.Tool{
|
||||
{Name: seat + ".resolvers",
|
||||
Description: "The machine's resolver file as it is now: the resolvers, search domains and options it lists, " +
|
||||
"whether it is the file the mesh declares, and when it is not, who wrote it as far as the machine shows " +
|
||||
@@ -23,12 +32,40 @@ func tools(m Machine) []stdio.Tool {
|
||||
"leaves through it, and the resolvers and search domains the network manager knows for it — a VPN's " +
|
||||
"tunnel included. (r)",
|
||||
Run: func(map[string]any) (any, error) { return m.Links(context.Background()) }},
|
||||
}, own.Tools...)
|
||||
}
|
||||
|
||||
// command is the holder's subcommand args name, or an error naming it when the holder has none such; nil with no args,
|
||||
// which is the bundle.
|
||||
func command(own holderOwn, args []string) (func(args []string) error, error) {
|
||||
if len(args) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if run, ok := own.Commands[args[0]]; ok {
|
||||
return run, nil
|
||||
}
|
||||
return nil, fmt.Errorf("uplink-tools has no subcommand %q", args[0])
|
||||
}
|
||||
|
||||
func main() {
|
||||
m := Machine{ResolvPath: ResolvConf, Run: execRunner, Running: running, LinkDNS: managerDNS}
|
||||
if err := stdio.Serve("", tools(m)); err != nil {
|
||||
own := holder(m)
|
||||
run, err := command(own, os.Args[1:])
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(2)
|
||||
}
|
||||
if run != nil {
|
||||
if err := run(os.Args[2:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if own.Start != nil {
|
||||
go own.Start()
|
||||
}
|
||||
if err := stdio.Serve("", tools(m, own)); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ package main
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
func managerDNS(ctx context.Context) (map[string]LinkDNS, error) {
|
||||
@@ -50,3 +52,20 @@ func parseNmcli(out string) map[string]LinkDNS {
|
||||
flush()
|
||||
return links
|
||||
}
|
||||
|
||||
// holder is what networkmanager adds to the seat's verbs (design 08 sign-in-page §11): the watcher, `uplink-tools
|
||||
// watch`.
|
||||
func holder(m Machine) holderOwn {
|
||||
own := holderOwn{Commands: map[string]func([]string) error{"watch": watch}}
|
||||
f, err := theFolder()
|
||||
if err != nil {
|
||||
journal("the module's folder: %v", err)
|
||||
return own
|
||||
}
|
||||
b := newBundle(f)
|
||||
own.Tools = b.tools()
|
||||
own.Start = func() {
|
||||
b.start(bundleRuns{files: fileEvents, fileMade: fileMade, onHeartbeat: stdio.OnHeartbeat, subscribe: stdio.Subscribe})
|
||||
}
|
||||
return own
|
||||
}
|
||||
|
||||
@@ -16,3 +16,10 @@ func TestNmcliIsReadPerDevice(t *testing.T) {
|
||||
t.Fatal("a link with no names was said")
|
||||
}
|
||||
}
|
||||
|
||||
// networkmanager's own part: the watcher's subcommand (design 08 sign-in-page §11).
|
||||
func TestNetworkManagerRunsItsWatcherAsASubcommand(t *testing.T) {
|
||||
if run, err := command(holder(Machine{}), []string{"watch"}); err != nil || run == nil {
|
||||
t.Fatalf("uplink-tools watch is not the watcher: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package main
|
||||
|
||||
// The bundle gives the resolver the check's host name (design 08 sign-in-page §13): it calls
|
||||
// `<node>/node-resolver.uplink-names` with the check address's host name, or an empty list when there is no address,
|
||||
// and writes the call to names.json. Which module holds node-resolver on its node it reads from the seat
|
||||
// mesh-module-assigner's assignments; none is `no holder`, which is no failure (DQ-8). A failed call is written to the
|
||||
// journal, stands failed in names.json and is asked again at the next moment, never on a timer.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
const (
|
||||
// runningPattern is node-engine's running event, as the manifest consumes it: node-engine.running.<node>.<module>.
|
||||
runningPattern = "node-engine.running.*.*"
|
||||
assignmentsKey = "seat:mesh-module-assigner.assignments"
|
||||
)
|
||||
|
||||
// namer calls uplink-names, one call at a time.
|
||||
type namer struct {
|
||||
folder Folder
|
||||
// ask calls a verb on the mesh as the module, through the runtime.
|
||||
ask func(key string, body any) (json.RawMessage, error)
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// hostOf is the check address's host name, lower-cased, as uplink-names takes it: none for an empty address.
|
||||
func hostOf(address string) ([]string, error) {
|
||||
if address == "" {
|
||||
return []string{}, nil
|
||||
}
|
||||
u, err := url.Parse(address)
|
||||
if err != nil || u.Hostname() == "" {
|
||||
return nil, fmt.Errorf("the check address %q names no host", address)
|
||||
}
|
||||
return []string{strings.ToLower(u.Hostname())}, nil
|
||||
}
|
||||
|
||||
// resolverHolder is the module that holds node-resolver on this node, "" when none does (DQ-8).
|
||||
func (n *namer) resolverHolder() (string, error) {
|
||||
raw, err := n.ask(assignmentsKey, map[string]string{"node": n.folder.Node, "seats": "true"})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reading the assignments: %w", err)
|
||||
}
|
||||
var answer struct {
|
||||
Seats []struct {
|
||||
Seat string `json:"seat"`
|
||||
Holders []struct {
|
||||
Module string `json:"module"`
|
||||
Node string `json:"node"`
|
||||
} `json:"holders"`
|
||||
} `json:"seats"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &answer); err != nil {
|
||||
return "", fmt.Errorf("the assignments answered in no form this reads: %w", err)
|
||||
}
|
||||
for _, s := range answer.Seats {
|
||||
if s.Seat != noderesolver.Seat {
|
||||
continue
|
||||
}
|
||||
for _, h := range s.Holders {
|
||||
if h.Node == n.folder.Node {
|
||||
return h.Module, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// give calls uplink-names now with the check address's host name and writes the call to names.json.
|
||||
func (n *namer) give(moment string) NamesCall {
|
||||
n.mu.Lock()
|
||||
defer n.mu.Unlock()
|
||||
call := NamesCall{Names: []string{}, At: n.now()}
|
||||
address, err := n.folder.checkAddress()
|
||||
if err == nil {
|
||||
call.Names, err = hostOf(address)
|
||||
}
|
||||
if err == nil {
|
||||
call.Result, err = n.call(call.Names)
|
||||
}
|
||||
if err != nil {
|
||||
call.Result = err.Error()
|
||||
}
|
||||
if call.Names == nil {
|
||||
call.Names = []string{}
|
||||
}
|
||||
if err := n.folder.writeNames(call); err != nil {
|
||||
journal("writing names.json failed: %v", err)
|
||||
}
|
||||
journal("uplink-names %v at %s: %s", call.Names, moment, call.Result)
|
||||
return call
|
||||
}
|
||||
|
||||
func (n *namer) call(names []string) (string, error) {
|
||||
holder, err := n.resolverHolder()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if holder == "" {
|
||||
return resultNoHolder, nil
|
||||
}
|
||||
raw, err := n.ask(uplinkNamesKey(n.folder.Node), noderesolver.UplinkNamesInput{Names: names})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s/%s.%s: %w", n.folder.Node, noderesolver.Seat, noderesolver.VerbUplinkNames, err)
|
||||
}
|
||||
if _, _, err := noderesolver.DecodeUplinkNamesAnswer(raw); err != nil {
|
||||
return "", fmt.Errorf("uplink-names answered in no form this reads: %w", err)
|
||||
}
|
||||
return resultOK, nil
|
||||
}
|
||||
|
||||
func uplinkNamesKey(node string) string {
|
||||
return "seat:" + noderesolver.Seat + "." + noderesolver.VerbUplinkNames + "@" + node
|
||||
}
|
||||
|
||||
// running hears node-engine's running: one for this node's holder of node-resolver, running, is a moment to call
|
||||
// uplink-names; every other is dropped, another node's first (§13).
|
||||
func (n *namer) running(e stdio.Envelope) error {
|
||||
parts := strings.Split(e.Key, ".")
|
||||
if len(parts) != 4 || parts[2] != n.folder.Node {
|
||||
return nil
|
||||
}
|
||||
var body struct {
|
||||
Module string `json:"module"`
|
||||
Stopped bool `json:"stopped"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Body, &body); err != nil || body.Stopped {
|
||||
return nil
|
||||
}
|
||||
holder, err := n.resolverHolder()
|
||||
if err != nil {
|
||||
journal("hearing %s: %v", e.Key, err)
|
||||
return nil
|
||||
}
|
||||
if holder != "" && holder == parts[3] {
|
||||
n.give(holder + " running")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The mesh stood in for the bundle's asks: the assignments naming this node's holder of node-resolver (none when
|
||||
// holder is empty), and node-resolver's uplink-names, failing while fail is set.
|
||||
type fakeMesh struct {
|
||||
mu sync.Mutex
|
||||
holder string
|
||||
fail error
|
||||
calls []string
|
||||
routes string
|
||||
// given, when set, hears each uplink-names call once made, so a test acts after it and never on a guess of when.
|
||||
given chan string
|
||||
}
|
||||
|
||||
func (m *fakeMesh) ask(key string, body any) (json.RawMessage, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
switch key {
|
||||
case assignmentsKey:
|
||||
in := body.(map[string]string)
|
||||
if in["node"] != "laptop" || in["seats"] != "true" {
|
||||
return nil, errors.New("asked the assignments of another node")
|
||||
}
|
||||
seats := `{"seats":[{"seat":"node-uplink","holders":[{"module":"networkmanager","node":"laptop"}]}`
|
||||
if m.holder != "" {
|
||||
seats += `,{"seat":"node-resolver","holders":[{"module":"` + m.holder + `","node":"laptop"}]}`
|
||||
}
|
||||
return json.RawMessage(seats + `]}`), nil
|
||||
case "seat:node-resolver.uplink-names@laptop":
|
||||
raw, _ := json.Marshal(body)
|
||||
m.calls = append(m.calls, string(raw))
|
||||
if m.given != nil {
|
||||
m.given <- string(raw)
|
||||
}
|
||||
if m.fail != nil {
|
||||
return nil, m.fail
|
||||
}
|
||||
return json.RawMessage(`{"names":["check.example.net"],"link":"wlan0","set_at":"2026-11-24T19:00:00Z"}`), nil
|
||||
case "seat:node-resolver.routes@laptop":
|
||||
if m.routes == "" {
|
||||
return nil, errors.New("no routes")
|
||||
}
|
||||
return json.RawMessage(m.routes), nil
|
||||
}
|
||||
return nil, errors.New("no such verb " + key)
|
||||
}
|
||||
|
||||
func (m *fakeMesh) called() []string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return append([]string(nil), m.calls...)
|
||||
}
|
||||
|
||||
// uplink-names is called at the bundle's start, on a changed check-address, when the bus connection comes back and on
|
||||
// a running holder of node-resolver on its own node; every other running is dropped; no holder is recorded and is
|
||||
// healthy, a failed call stands failed (design 08 sign-in-page §13, §25).
|
||||
func TestUplinkNamesIsCalledAtEachMoment(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
f := aFolder(t)
|
||||
if err := f.writeCheckAddress("http://Check.Example.net/connecttest"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mesh := &fakeMesh{holder: "systemd-resolved", given: make(chan string, 16)}
|
||||
b := &bundle{folder: f, pub: &publisher{folder: f, publish: (&fakeStream{}).publish},
|
||||
names: &namer{folder: f, ask: mesh.ask, now: time.Now}}
|
||||
check := make(chan struct{})
|
||||
// The bundle runs beside the test: each check address is changed only once the call made from the one before was
|
||||
// heard, so the test never races the bundle's read of check-address (a call never made ends the run at its bound).
|
||||
heard := func() { <-mesh.given }
|
||||
var running func(stdio.Envelope) error
|
||||
var hook func(stdio.Heartbeat)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
b.start(bundleRuns{files: func([]string, <-chan struct{}) <-chan struct{} { return nil },
|
||||
fileMade: func(dir, name string, _ <-chan struct{}) <-chan struct{} {
|
||||
if dir != f.Dir || name != "check-address" {
|
||||
t.Errorf("watched %s in %s", name, dir)
|
||||
}
|
||||
return check
|
||||
},
|
||||
onHeartbeat: func(h func(stdio.Heartbeat)) error { hook = h; return nil },
|
||||
subscribe: func(pattern string, h func(stdio.Envelope) error) error {
|
||||
if pattern != "node-engine.running.*.*" {
|
||||
t.Errorf("subscribed to %s", pattern)
|
||||
}
|
||||
running = h
|
||||
return nil
|
||||
}})
|
||||
close(done)
|
||||
}()
|
||||
heard()
|
||||
if err := f.writeCheckAddress(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check <- struct{}{}
|
||||
heard()
|
||||
f.writeCheckAddress("https://other.example.net/")
|
||||
close(check)
|
||||
<-done
|
||||
want := []string{`{"names":["check.example.net"]}`, `{"names":[]}`}
|
||||
if got := mesh.called(); strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Fatalf("at the start and a changed check address: called %q", got)
|
||||
}
|
||||
hook(stdio.Heartbeat{Missed: true})
|
||||
hook(stdio.Heartbeat{})
|
||||
for _, e := range []stdio.Envelope{
|
||||
{Key: "node-engine.running.other.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved"}`)},
|
||||
{Key: "node-engine.running.laptop.i3", Body: json.RawMessage(`{"module":"i3"}`)},
|
||||
{Key: "node-engine.running.laptop.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved","stopped":true}`)},
|
||||
{Key: "node-engine.running.laptop.systemd-resolved", Body: json.RawMessage(`{"module":"systemd-resolved","healthy":true}`)},
|
||||
} {
|
||||
if err := running(e); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
want = append(want, `{"names":["other.example.net"]}`, `{"names":["other.example.net"]}`)
|
||||
if got := mesh.called(); strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Fatalf("at the connection's return and a running holder: called %q", got)
|
||||
}
|
||||
if c, _ := f.names(); c == nil || c.Result != resultOK || strings.Join(c.Names, " ") != "other.example.net" {
|
||||
t.Fatalf("names.json holds %+v", c)
|
||||
}
|
||||
|
||||
mesh.holder = ""
|
||||
if c := b.names.give("a test"); c.Result != resultNoHolder || c.Failed() || len(mesh.called()) != 4 {
|
||||
t.Fatalf("no holder gave %+v after %d calls", c, len(mesh.called()))
|
||||
}
|
||||
mesh.holder, mesh.fail = "systemd-resolved", errors.New("no answer within its bound")
|
||||
if c := b.names.give("a test"); !c.Failed() || !strings.Contains(c.Result, "no answer within its bound") {
|
||||
t.Fatalf("a failed call gave %+v", c)
|
||||
}
|
||||
if c, _ := f.names(); c == nil || !c.Failed() {
|
||||
t.Fatalf("names.json holds %+v", c)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), "uplink-names [other.example.net] at a test: laptop/node-resolver.uplink-names: no answer") {
|
||||
t.Fatalf("the failed call is not in the journal: %q", lines())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
// Telling the person (design 08 sign-in-page §19): org.freedesktop.Notifications.Notify on the session's bus, the
|
||||
// desktop notification service, app_name mesh.
|
||||
|
||||
import "github.com/godbus/dbus/v5"
|
||||
|
||||
func notifyOn(bus string, n note) error {
|
||||
conn, err := dbus.Connect(bus)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
hints := map[string]dbus.Variant{}
|
||||
if n.Critical {
|
||||
hints["urgency"] = dbus.MakeVariant(byte(2))
|
||||
}
|
||||
return conn.Object("org.freedesktop.Notifications", "/org/freedesktop/Notifications").
|
||||
Call("org.freedesktop.Notifications.Notify", 0, "mesh", uint32(0), "", n.Summary, n.Body, []string{}, hints,
|
||||
int32(-1)).Err
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package main
|
||||
|
||||
// Opening the page and telling the person (design 08 sign-in-page §15, §18, §19): at the three moments, once per ask,
|
||||
// in the person's session. The open runs beside the watch; rating changes heard meanwhile are handled after it, in the
|
||||
// order they came.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// openBound is how long the watcher waits for the opener: ended within it, its status decides; still running at it,
|
||||
// the page is opening and the run is left to go on (§18).
|
||||
const openBound = 10 * time.Second
|
||||
|
||||
// desk is the person's desktop as the watcher reaches it: an address opened in their session, a notification shown.
|
||||
type desk interface {
|
||||
open(s Session, address string) openOutcome
|
||||
notify(s Session, n note) error
|
||||
}
|
||||
|
||||
// openOutcome is how an open ended: opened, opening (still running at its bound) or failed, with the program and the
|
||||
// reason of a failure.
|
||||
type openOutcome struct {
|
||||
Address string `json:"address"`
|
||||
Program string `json:"program,omitempty"`
|
||||
Outcome string `json:"outcome"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// The outcomes of an open.
|
||||
const (
|
||||
outcomeOpened = "opened"
|
||||
outcomeOpening = "opening"
|
||||
outcomeFailed = "failed"
|
||||
)
|
||||
|
||||
// note is one notification: its summary and body, critical or not, and, once shown, when and whether it failed.
|
||||
type note struct {
|
||||
Summary string `json:"summary"`
|
||||
Body string `json:"body"`
|
||||
Critical bool `json:"critical,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
const askedSummary = "This network asks you to sign in"
|
||||
|
||||
// signInNote is what the person is told after an open, by its outcome (§19).
|
||||
func signInNote(network, address string, o openOutcome) note {
|
||||
switch o.Outcome {
|
||||
case outcomeOpened:
|
||||
return note{Summary: askedSummary, Body: fmt.Sprintf("%s: its sign-in page is open in %s.", network, o.Program)}
|
||||
case outcomeOpening:
|
||||
return note{Summary: askedSummary, Body: fmt.Sprintf("%s: its sign-in page is opening in %s.", network, o.Program)}
|
||||
}
|
||||
return note{Summary: askedSummary, Critical: true,
|
||||
Body: fmt.Sprintf("%s: the page did not open (%s); open %s in a browser.", network, o.Reason, address)}
|
||||
}
|
||||
|
||||
// signedInNote is what the person is told when the rating leaves PORTAL for FULL (§19).
|
||||
func signedInNote(network string) note {
|
||||
return note{Summary: "The network is open", Body: network + ": signed in."}
|
||||
}
|
||||
|
||||
// present opens the address in the person's session, s or the one found now, and then tells them (§15, §18, §19),
|
||||
// beside the watch; with no session found it opens and shows nothing, and the events are kept all the same (§15,
|
||||
// §16).
|
||||
func (w *Watcher) present(s *Session, network, address string) {
|
||||
if w.opening {
|
||||
w.later = append(w.later, func() { w.present(s, network, address) })
|
||||
return
|
||||
}
|
||||
if s = w.sessionNow(s, "the sign-in page of "+network+" is not opened"); s == nil {
|
||||
return
|
||||
}
|
||||
session := *s
|
||||
w.opening = true
|
||||
w.Beside(func() func() {
|
||||
o := w.Desk.open(session, address)
|
||||
n := signInNote(network, address, o)
|
||||
err := w.Desk.notify(session, n)
|
||||
return func() {
|
||||
o.At = w.Now()
|
||||
w.state.LastOpen = &o
|
||||
if o.Outcome == outcomeFailed {
|
||||
journal("opening %s in session %s failed: %s", address, session.ID, o.Reason)
|
||||
} else {
|
||||
journal("the sign-in page %s is %s in %s", address, o.Outcome, o.Program)
|
||||
}
|
||||
w.shown(n, err)
|
||||
w.opening = false
|
||||
w.drain()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// tellSignedIn tells the person the network is open, in their session; with none, nothing (§19).
|
||||
func (w *Watcher) tellSignedIn(network string) {
|
||||
s := w.sessionNow(nil, "the network being open is not shown")
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
session, n := *s, signedInNote(network)
|
||||
w.Beside(func() func() {
|
||||
err := w.Desk.notify(session, n)
|
||||
return func() { w.shown(n, err) }
|
||||
})
|
||||
}
|
||||
|
||||
// sessionNow is s, or the person's session found now; nil with a journal line saying what is not done.
|
||||
func (w *Watcher) sessionNow(s *Session, notDone string) *Session {
|
||||
if s != nil {
|
||||
return s
|
||||
}
|
||||
found, err := w.findSession()
|
||||
if err != nil {
|
||||
journal("finding the person's session failed: %v; %s", err, notDone)
|
||||
return nil
|
||||
}
|
||||
if found == nil {
|
||||
journal("no graphical session: %s", notDone)
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
func (w *Watcher) shown(n note, err error) {
|
||||
n.At = w.Now()
|
||||
if err != nil {
|
||||
n.Error = err.Error()
|
||||
journal("showing the notification %q failed: %v", n.Summary, err)
|
||||
} else {
|
||||
journal("showed the notification %q: %s", n.Summary, n.Body)
|
||||
}
|
||||
w.state.LastNotification = &n
|
||||
}
|
||||
|
||||
// drain handles, in the order they came, what was heard during an open, until one starts another open.
|
||||
func (w *Watcher) drain() {
|
||||
for len(w.later) > 0 && !w.opening {
|
||||
next := w.later[0]
|
||||
w.later = w.later[1:]
|
||||
next()
|
||||
}
|
||||
}
|
||||
|
||||
// besideLoop runs work beside the loop and hands its end back to the loop, which runs it.
|
||||
func (w *Watcher) besideLoop(work func() func()) {
|
||||
go func() { w.ends <- work() }()
|
||||
}
|
||||
|
||||
// sessionDesk opens and tells in the person's session: the programs run with the session's bus and runtime directory
|
||||
// in their environment.
|
||||
type sessionDesk struct {
|
||||
// query runs a program to its end, within openBound, and answers its output.
|
||||
query func(env []string, name string, args ...string) (string, error)
|
||||
// start starts a program; its end, with its status, comes on the channel.
|
||||
start func(env []string, name string, args ...string) (<-chan error, error)
|
||||
after func(time.Duration) <-chan time.Time
|
||||
show func(bus string, n note) error
|
||||
}
|
||||
|
||||
func newSessionDesk() sessionDesk {
|
||||
return sessionDesk{query: queryProgram, start: startProgram, after: time.After, show: notifyOn}
|
||||
}
|
||||
|
||||
// open asks xdg-mime for the scheme's program, then runs `systemd-run --user --collect --quiet --wait -- xdg-open
|
||||
// <address>`, the address one argument and no shell, so the browser runs under the person's user manager and outlives
|
||||
// the watcher (§18).
|
||||
func (d sessionDesk) open(s Session, address string) openOutcome {
|
||||
o := openOutcome{Address: address, Outcome: outcomeFailed}
|
||||
u, err := url.Parse(address)
|
||||
if err != nil {
|
||||
o.Reason = err.Error()
|
||||
return o
|
||||
}
|
||||
program, err := d.query(s.Env(), "xdg-mime", "query", "default", "x-scheme-handler/"+u.Scheme)
|
||||
if err != nil {
|
||||
o.Reason = "xdg-mime: " + err.Error()
|
||||
return o
|
||||
}
|
||||
if program = strings.TrimSpace(program); program == "" {
|
||||
o.Reason = "no default program for " + u.Scheme
|
||||
return o
|
||||
}
|
||||
done, err := d.start(s.Env(), "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", address)
|
||||
if err != nil {
|
||||
o.Reason = "systemd-run: " + err.Error()
|
||||
return o
|
||||
}
|
||||
o.Program = program
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
o.Program, o.Reason = "", "xdg-open "+status(err)
|
||||
return o
|
||||
}
|
||||
o.Outcome = outcomeOpened
|
||||
case <-d.after(openBound):
|
||||
o.Outcome = outcomeOpening
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func (d sessionDesk) notify(s Session, n note) error { return d.show(s.Bus(), n) }
|
||||
|
||||
// status names how a program ended: its exit status, or why it did not end with one.
|
||||
func status(err error) string {
|
||||
var exit *exec.ExitError
|
||||
if errors.As(err, &exit) {
|
||||
return fmt.Sprintf("ended with status %d", exit.ExitCode())
|
||||
}
|
||||
return "failed: " + err.Error()
|
||||
}
|
||||
|
||||
func queryProgram(env []string, name string, args ...string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), openBound)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
cmd.Env = env
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
return "", errors.New(status(err))
|
||||
}
|
||||
return string(out), nil
|
||||
}
|
||||
|
||||
func startProgram(env []string, name string, args ...string) (<-chan error, error) {
|
||||
cmd := exec.Command(name, args...)
|
||||
cmd.Env = env
|
||||
if err := cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- cmd.Wait() }()
|
||||
return done, nil
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// aDeskWatcher is a watcher with the person's session found and the desktop stood in; it starts subscribed, the rating
|
||||
// at its start being start.
|
||||
func aDeskWatcher(t *testing.T, start Rating) (*Watcher, *fakeSystem, *fakeDesk) {
|
||||
t.Helper()
|
||||
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
|
||||
sys.set(start)
|
||||
w := aWatcher(t, sys)
|
||||
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1", "XAUTHORITY=/x"}, nil }
|
||||
w.subscribe()
|
||||
return w, sys, w.Desk.(*fakeDesk)
|
||||
}
|
||||
|
||||
const openedNote = "This network asks you to sign in: guest-example: its sign-in page is open in browser.desktop."
|
||||
|
||||
// PORTAL at a join and PORTAL at the watcher's start each open the page and show one notification; a second PORTAL
|
||||
// without a leave does nothing; PORTAL to FULL shows that the network is open, PORTAL to any other rating shows nothing
|
||||
// (design 08 sign-in-page §15, §19, §25).
|
||||
func TestTheRatingOpensThePageAndTellsThePersonOncePerAsk(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
start Rating
|
||||
then []Rating
|
||||
opens int
|
||||
notes []string
|
||||
journal string
|
||||
}{
|
||||
{"PORTAL at a join", guest(ratingFull), []Rating{guest(ratingPortal)}, 1, []string{openedNote},
|
||||
"showed the notification"},
|
||||
{"PORTAL at the start", guest(ratingPortal), nil, 1, []string{openedNote}, "the sign-in page http://check.example.net/ is opened in browser.desktop"},
|
||||
{"a second PORTAL", guest(ratingPortal), []Rating{guest(ratingPortal), guest(ratingPortal)}, 1,
|
||||
[]string{openedNote}, ""},
|
||||
{"PORTAL to FULL", guest(ratingPortal), []Rating{guest(ratingFull)}, 1,
|
||||
[]string{openedNote, "The network is open: guest-example: signed in."}, ""},
|
||||
{"PORTAL to LIMITED", guest(ratingPortal), []Rating{guest(ratingLimited)}, 1, []string{openedNote}, ""},
|
||||
{"PORTAL, left, PORTAL on another", guest(ratingPortal), []Rating{other(ratingPortal)}, 2,
|
||||
[]string{openedNote, "This network asks you to sign in: home-example: its sign-in page is open in browser.desktop."}, ""},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
w, sys, desk := aDeskWatcher(t, c.start)
|
||||
for _, r := range c.then {
|
||||
sys.set(r)
|
||||
w.heardSignal(signal{Rating: true})
|
||||
}
|
||||
if got := desk.opened(); len(got) != c.opens {
|
||||
t.Fatalf("opened %q", got)
|
||||
}
|
||||
if got := desk.shown(); strings.Join(got, "|") != strings.Join(c.notes, "|") {
|
||||
t.Fatalf("showed %q, want %q", got, c.notes)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), c.journal) {
|
||||
t.Fatalf("the journal does not say %q: %q", c.journal, lines())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An opener that fails gives the critical notification naming the reason and the address (§19, §25).
|
||||
func TestAFailingOpenerGivesTheCriticalNotification(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1"}, nil }
|
||||
desk := w.Desk.(*fakeDesk)
|
||||
desk.outcome = openOutcome{Address: "http://check.example.net/", Outcome: outcomeFailed, Reason: "xdg-open ended with status 4"}
|
||||
w.subscribe()
|
||||
sys.set(guest(ratingPortal))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
want := "critical This network asks you to sign in: guest-example: the page did not open (xdg-open ended with status 4); " +
|
||||
"open http://check.example.net/ in a browser."
|
||||
if got := desk.shown(); len(got) != 1 || got[0] != want {
|
||||
t.Fatalf("showed %q", got)
|
||||
}
|
||||
if w.state.LastOpen == nil || w.state.LastOpen.Outcome != outcomeFailed || w.state.LastNotification == nil {
|
||||
t.Fatalf("the state says %+v", w.state)
|
||||
}
|
||||
}
|
||||
|
||||
// A rating change heard while the page opens is handled after the open, in the order heard (§18, §25).
|
||||
func TestARatingChangeHeardDuringAnOpenIsHandledAfterIt(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{sessions: []loginSession{personsSession()}}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
w.Environment = func(string) ([]string, error) { return []string{"DISPLAY=:1"}, nil }
|
||||
var beside []func() func()
|
||||
w.Beside = func(work func() func()) { beside = append(beside, work) }
|
||||
w.subscribe()
|
||||
sys.set(guest(ratingPortal))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
sys.set(guest(ratingLimited))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
sys.set(guest(ratingFull))
|
||||
w.heardSignal(signal{Rating: true})
|
||||
if got := keptSaid(t, w.Folder); len(got) != 2 || len(beside) != 1 {
|
||||
t.Fatalf("during the open: kept %q, %d run beside", got, len(beside))
|
||||
}
|
||||
beside[0]()()
|
||||
got := keptSaid(t, w.Folder)
|
||||
if len(got) != 3 || got[2] != "sign-in-ended no-longer-asked guest-example wlan0" {
|
||||
t.Fatalf("after the open: kept %q", got)
|
||||
}
|
||||
if w.opening || len(w.later) != 0 {
|
||||
t.Fatal("what was heard is still waiting")
|
||||
}
|
||||
}
|
||||
|
||||
// The opener in the person's session: xdg-mime asked for the scheme's program, then systemd-run --user with the address
|
||||
// as one argument, both with the session's bus and runtime directory; its status, or its bound, decides (§18).
|
||||
func TestTheOpenerRunsInThePersonsSession(t *testing.T) {
|
||||
s := Session{ID: "2", Type: "x11", RuntimePath: "/run/user/1000"}
|
||||
address := "http://check.example.net/a'b;c"
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
program string
|
||||
ends error
|
||||
running bool
|
||||
want openOutcome
|
||||
}{
|
||||
{"opened", "browser.desktop\n", nil, false, openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpened}},
|
||||
{"opening", "browser.desktop\n", nil, true, openOutcome{Address: address, Program: "browser.desktop", Outcome: outcomeOpening}},
|
||||
{"failed", "browser.desktop\n", exitStatus(t, 3), false,
|
||||
openOutcome{Address: address, Outcome: outcomeFailed, Reason: "xdg-open ended with status 3"}},
|
||||
{"no program", "\n", nil, false, openOutcome{Address: address, Outcome: outcomeFailed, Reason: "no default program for http"}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
var ran []string
|
||||
envOf := func(env []string) string {
|
||||
var out []string
|
||||
for _, kv := range env {
|
||||
if strings.HasPrefix(kv, "DBUS_SESSION_BUS_ADDRESS=") || strings.HasPrefix(kv, "XDG_RUNTIME_DIR=") {
|
||||
out = append(out, kv)
|
||||
}
|
||||
}
|
||||
return strings.Join(out, " ")
|
||||
}
|
||||
bound := make(chan time.Time, 1)
|
||||
d := sessionDesk{
|
||||
query: func(env []string, name string, args ...string) (string, error) {
|
||||
ran = append(ran, envOf(env)+" | "+name+" "+strings.Join(args, " "))
|
||||
return c.program, nil
|
||||
},
|
||||
start: func(env []string, name string, args ...string) (<-chan error, error) {
|
||||
ran = append(ran, envOf(env)+" | "+name+" "+strings.Join(args, " "))
|
||||
if args[len(args)-1] != address {
|
||||
t.Errorf("the address is not one argument: %q", args)
|
||||
}
|
||||
done := make(chan error, 1)
|
||||
if c.running {
|
||||
bound <- time.Now()
|
||||
} else {
|
||||
done <- c.ends
|
||||
}
|
||||
return done, nil
|
||||
},
|
||||
after: func(d time.Duration) <-chan time.Time {
|
||||
if d != 10*time.Second {
|
||||
t.Errorf("the open's bound is %s", d)
|
||||
}
|
||||
return bound
|
||||
},
|
||||
}
|
||||
got := d.open(s, address)
|
||||
if got != c.want {
|
||||
t.Fatalf("answered %+v, want %+v", got, c.want)
|
||||
}
|
||||
env := "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus XDG_RUNTIME_DIR=/run/user/1000 | "
|
||||
want := []string{env + "xdg-mime query default x-scheme-handler/http"}
|
||||
if c.program != "\n" {
|
||||
want = append(want, env+"systemd-run --user --collect --quiet --wait -- xdg-open "+address)
|
||||
}
|
||||
if strings.Join(ran, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("ran\n%s\nwant\n%s", strings.Join(ran, "\n"), strings.Join(want, "\n"))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// exitStatus is the error of a program that ended with status n.
|
||||
func exitStatus(t *testing.T, n int) error {
|
||||
t.Helper()
|
||||
err := exec.Command("sh", "-c", "exit "+string(rune('0'+n))).Run()
|
||||
var exit *exec.ExitError
|
||||
if !errors.As(err, &exit) {
|
||||
t.Fatalf("no exit status: %v", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package main
|
||||
|
||||
// The bundle publishes the kept events (design 08 sign-in-page §20): in sequence order, on the seat's subject, each
|
||||
// with its message id as the bus's message id (the runtime prefixes it with the module), awaiting the stream's
|
||||
// acknowledgement, and deletes each file once acknowledged. A publish refused or unacknowledged stays in pending/, is
|
||||
// written to the journal and counted, and is published again at the next moment: the bundle's start, a file event of
|
||||
// the kernel on pending/, its bus connection coming back, or uplink_publish_again.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// publisher publishes the kept events, one round at a time.
|
||||
type publisher struct {
|
||||
folder Folder
|
||||
// publish says one event on the seat, de-duplicated by id, and answers once the stream acknowledged it.
|
||||
publish func(subject string, body json.RawMessage, id string) error
|
||||
|
||||
mu sync.Mutex
|
||||
refused int
|
||||
}
|
||||
|
||||
// publishResult is one round: how many were published and how many still wait.
|
||||
type publishResult struct {
|
||||
Published int `json:"published"`
|
||||
Waiting int `json:"waiting"`
|
||||
Refused string `json:"refused,omitempty"`
|
||||
}
|
||||
|
||||
// publishKept publishes every kept event in order; the first refused stops the round, so none is published before an
|
||||
// older one.
|
||||
func (p *publisher) publishKept(moment string) publishResult {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
var out publishResult
|
||||
kept, err := p.folder.pending()
|
||||
if err != nil {
|
||||
journal("reading the kept events at %s failed: %v", moment, err)
|
||||
out.Refused = err.Error()
|
||||
return out
|
||||
}
|
||||
for i, k := range kept {
|
||||
subject, id, body, err := p.outgoing(k)
|
||||
if err == nil {
|
||||
err = p.publish(subject, body, id)
|
||||
}
|
||||
if err != nil {
|
||||
p.refused++
|
||||
out.Waiting, out.Refused = len(kept)-i, err.Error()
|
||||
journal("publishing %s at %s was refused or not acknowledged: %v; %d left waiting", k.Name(), moment, err,
|
||||
out.Waiting)
|
||||
return out
|
||||
}
|
||||
journal("published %s on %s", id, subject)
|
||||
out.Published++
|
||||
if err := p.folder.drop(k); err != nil {
|
||||
journal("deleting the published %s failed: %v", id, err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// outgoing is a kept change as the bundle publishes it on its own node: the seat's subject, the message id
|
||||
// `<node>.<event>.<sequence>` and the body with its node (§20; lead answer L-3).
|
||||
func (p *publisher) outgoing(k Kept) (string, string, json.RawMessage, error) {
|
||||
node := p.folder.Node
|
||||
if node == "" {
|
||||
return "", "", nil, errors.New("no node named: the tool runner names the bundle's in MESH_NODE")
|
||||
}
|
||||
if k.Event != eventAsked && k.Event != eventEnded {
|
||||
return "", "", nil, fmt.Errorf("the kept change %s is of no event of the seat", k.Name())
|
||||
}
|
||||
var body map[string]json.RawMessage
|
||||
if err := json.Unmarshal(k.Body, &body); err != nil {
|
||||
return "", "", nil, fmt.Errorf("the kept change %s holds no body: %w", k.Name(), err)
|
||||
}
|
||||
body["node"], _ = json.Marshal(node)
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
return eventSubject(k.Event, node), fmt.Sprintf("%s.%s.%d", node, k.Event, k.Sequence), raw, nil
|
||||
}
|
||||
|
||||
// refusedSince is the publishes refused since the bundle's start.
|
||||
func (p *publisher) refusedSince() int {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.refused
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/nodeuplink"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
)
|
||||
|
||||
// The bus stood in: every publish asked, the ids it refuses once, as the runtime answers a publish the stream did not
|
||||
// acknowledge.
|
||||
type fakeStream struct {
|
||||
mu sync.Mutex
|
||||
asked []string
|
||||
refuse map[string]bool
|
||||
}
|
||||
|
||||
func (s *fakeStream) publish(subject string, body json.RawMessage, id string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.asked = append(s.asked, id)
|
||||
if s.refuse[id] {
|
||||
delete(s.refuse, id)
|
||||
return errors.New("no acknowledgement")
|
||||
}
|
||||
if !json.Valid(body) || !strings.HasPrefix(subject, "mesh.seat.node-uplink.event.") {
|
||||
return errors.New("not an event of the seat")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *fakeStream) publishes() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return strings.Join(s.asked, " ")
|
||||
}
|
||||
|
||||
func keepThree(t *testing.T, f Folder) {
|
||||
t.Helper()
|
||||
for _, event := range []string{eventEnded, eventAsked, eventEnded} {
|
||||
if _, err := f.keep(event, map[string]string{"link": "wlan0"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The bundle publishes the kept events in order with their message ids and deletes each once acknowledged; a refused
|
||||
// one stays, with the ones after it, and is published at the next moment under the same id (design 08 sign-in-page
|
||||
// §20, §25).
|
||||
func TestTheBundlePublishesTheKeptEventsInOrder(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
f := aFolder(t)
|
||||
keepThree(t, f)
|
||||
stream := &fakeStream{refuse: map[string]bool{"laptop.sign-in-asked.2": true}}
|
||||
p := &publisher{folder: f, publish: stream.publish}
|
||||
if r := p.publishKept("the bundle's start"); r.Published != 1 || r.Waiting != 2 || p.refusedSince() != 1 {
|
||||
t.Fatalf("first round %+v, refused %d", r, p.refusedSince())
|
||||
}
|
||||
if kept, _ := f.pending(); len(kept) != 2 || kept[0].Name() != "sign-in-asked.2" {
|
||||
t.Fatalf("waiting %+v", kept)
|
||||
}
|
||||
if !strings.Contains(strings.Join(lines(), "\n"), "publishing sign-in-asked.2 at the bundle's start was refused") {
|
||||
t.Fatalf("the refusal was not written to the journal: %q", lines())
|
||||
}
|
||||
if r := p.publishKept("a kept event"); r.Published != 2 || r.Waiting != 0 {
|
||||
t.Fatalf("second round %+v", r)
|
||||
}
|
||||
if got := stream.publishes(); got != "laptop.sign-in-ended.1 laptop.sign-in-asked.2 laptop.sign-in-asked.2 laptop.sign-in-ended.3" {
|
||||
t.Fatalf("published %s", got)
|
||||
}
|
||||
if kept, _ := f.pending(); len(kept) != 0 {
|
||||
t.Fatalf("left %+v", kept)
|
||||
}
|
||||
}
|
||||
|
||||
// The bundle publishes at its start, at each file event on pending/ and when its bus connection comes back: the first
|
||||
// heartbeat answered after a missed one; an older heartbeat arriving late changes nothing (§20, DMC-4).
|
||||
func TestTheBundlePublishesAtEachMoment(t *testing.T) {
|
||||
journalLines(t)
|
||||
f := aFolder(t)
|
||||
keepThree(t, f)
|
||||
stream := &fakeStream{refuse: map[string]bool{"laptop.sign-in-ended.1": true}}
|
||||
b := &bundle{folder: f, pub: &publisher{folder: f, publish: stream.publish}, names: &namer{folder: f, now: time.Now,
|
||||
ask: func(string, any) (json.RawMessage, error) { return json.RawMessage(`{"seats":[]}`), nil }}}
|
||||
files := make(chan struct{})
|
||||
var hook func(stdio.Heartbeat)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
b.start(bundleRuns{files: func(dirs []string, _ <-chan struct{}) <-chan struct{} {
|
||||
if len(dirs) != 1 || !strings.HasSuffix(dirs[0], "/pending") {
|
||||
t.Errorf("watched %v", dirs)
|
||||
}
|
||||
return files
|
||||
}, fileMade: func(string, string, <-chan struct{}) <-chan struct{} { return nil },
|
||||
onHeartbeat: func(h func(stdio.Heartbeat)) error { hook = h; return nil },
|
||||
subscribe: func(string, func(stdio.Envelope) error) error { return nil }})
|
||||
close(done)
|
||||
}()
|
||||
files <- struct{}{} // the start's round ran and was refused; this one publishes what waits
|
||||
if _, err := f.keep(eventAsked, map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files <- struct{}{}
|
||||
close(files)
|
||||
<-done
|
||||
if kept, _ := f.pending(); len(kept) != 0 {
|
||||
t.Fatalf("a file event published nothing: %+v", kept)
|
||||
}
|
||||
keepThree(t, f)
|
||||
at := time.Date(2026, 11, 24, 20, 0, 0, 0, time.UTC)
|
||||
hook(stdio.Heartbeat{At: at})
|
||||
if kept, _ := f.pending(); len(kept) != 3 {
|
||||
t.Fatal("a heartbeat with none missed published")
|
||||
}
|
||||
hook(stdio.Heartbeat{At: at.Add(time.Second), Missed: true, Why: "no heartbeat"})
|
||||
hook(stdio.Heartbeat{At: at.Add(-time.Second)})
|
||||
if kept, _ := f.pending(); len(kept) != 3 {
|
||||
t.Fatal("an older heartbeat arriving late was taken for the connection's return")
|
||||
}
|
||||
hook(stdio.Heartbeat{At: at.Add(2 * time.Second)})
|
||||
if kept, _ := f.pending(); len(kept) != 0 {
|
||||
t.Fatalf("the connection's return published nothing: %+v", kept)
|
||||
}
|
||||
if got := stream.publishes(); !strings.HasPrefix(got, "laptop.sign-in-ended.1 laptop.sign-in-ended.1 laptop.sign-in-asked.2") {
|
||||
t.Fatalf("published %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The bundle publishes a change the watcher kept with no node under its own: the subject `<event>.<node>`, the message
|
||||
// id `<node>.<event>.<sequence>` and the body's node, the same at every publish of one file; a bundle that names no node
|
||||
// publishes nothing and keeps the change (design 08 sign-in-page §20; lead answer L-3).
|
||||
func TestTheBundleFillsItsNodeIntoAKeptChange(t *testing.T) {
|
||||
journalLines(t)
|
||||
watcher := Folder{Dir: t.TempDir()}
|
||||
if _, err := watcher.keep(eventAsked, nodeuplink.SignInAsked{Link: "wlan0", Network: "guest-example",
|
||||
Address: "http://check.example.net/", At: "2026-11-24T10:00:00Z"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var said []string
|
||||
publish := func(subject string, body json.RawMessage, id string) error {
|
||||
said = append(said, subject+" "+id+" "+string(body))
|
||||
return errors.New("no acknowledgement")
|
||||
}
|
||||
unnamed := &publisher{folder: watcher, publish: publish}
|
||||
if r := unnamed.publishKept("a test"); r.Waiting != 1 || !strings.Contains(r.Refused, "no node named") || len(said) != 0 {
|
||||
t.Fatalf("a bundle with no node: %+v, said %q", r, said)
|
||||
}
|
||||
p := &publisher{folder: Folder{Dir: watcher.Dir, Node: "laptop"}, publish: publish}
|
||||
p.publishKept("a test")
|
||||
p.publishKept("a test")
|
||||
want := `mesh.seat.node-uplink.event.sign-in-asked.laptop laptop.sign-in-asked.1 ` +
|
||||
`{"address":"http://check.example.net/","at":"2026-11-24T10:00:00Z","link":"wlan0","network":"guest-example","node":"laptop"}`
|
||||
if len(said) != 2 || said[0] != want || said[1] != want {
|
||||
t.Fatalf("published %q, want twice %s", said, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package main
|
||||
|
||||
// The person's graphical session (design 08 sign-in-page §16, §17): found over the system bus from logind, its
|
||||
// session bus at the user's RuntimePath and its display in the user manager's environment; its start heard as
|
||||
// logind's SessionNew, then waited for until the user manager's environment names a display. The user manager sends
|
||||
// no PropertiesChanged for its Environment (EmitsChangedSignal false), so the environment is read again at each file
|
||||
// event of the kernel on the X server's socket folder and on the session's RuntimePath, for at most 60 s (§17).
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// sessionWait is the most the watcher waits, after a session started, for the user manager's environment to name a
|
||||
// display (§17).
|
||||
const sessionWait = 60 * time.Second
|
||||
|
||||
// x11Sockets is the folder an X server makes its socket in.
|
||||
var x11Sockets = "/tmp/.X11-unix"
|
||||
|
||||
// loginSession is what logind says of one session: its id and object, its account, type, whether it is remote, its
|
||||
// state, and its user's runtime directory.
|
||||
type loginSession struct {
|
||||
ID string
|
||||
Path string
|
||||
UID uint32
|
||||
Type string
|
||||
Remote bool
|
||||
State string
|
||||
RuntimePath string
|
||||
}
|
||||
|
||||
// graphical says whether the session is one the person sits at: x11 or wayland, not remote, active or online.
|
||||
func (s loginSession) graphical() bool {
|
||||
return (s.Type == "x11" || s.Type == "wayland") && !s.Remote && (s.State == "active" || s.State == "online")
|
||||
}
|
||||
|
||||
// Session is the person's graphical session as the watcher reaches it: its session bus, its runtime directory and the
|
||||
// display its user manager's environment names.
|
||||
type Session struct {
|
||||
ID string
|
||||
Type string
|
||||
RuntimePath string
|
||||
Display []string
|
||||
}
|
||||
|
||||
// Bus is the session's bus address.
|
||||
func (s Session) Bus() string { return "unix:path=" + s.RuntimePath + "/bus" }
|
||||
|
||||
// Env is the environment a program run in the session gets: the watcher's own, with the session's bus and runtime
|
||||
// directory.
|
||||
func (s Session) Env() []string {
|
||||
var env []string
|
||||
for _, kv := range os.Environ() {
|
||||
if !strings.HasPrefix(kv, "DBUS_SESSION_BUS_ADDRESS=") && !strings.HasPrefix(kv, "XDG_RUNTIME_DIR=") {
|
||||
env = append(env, kv)
|
||||
}
|
||||
}
|
||||
return append(env, "DBUS_SESSION_BUS_ADDRESS="+s.Bus(), "XDG_RUNTIME_DIR="+s.RuntimePath)
|
||||
}
|
||||
|
||||
// displayIn is the display an environment names for a session of its type: DISPLAY and XAUTHORITY for x11,
|
||||
// WAYLAND_DISPLAY for wayland; none when it names none.
|
||||
func displayIn(env []string, sessionType string) []string {
|
||||
want := map[string]bool{"DISPLAY": sessionType == "x11", "XAUTHORITY": sessionType == "x11",
|
||||
"WAYLAND_DISPLAY": sessionType == "wayland"}
|
||||
var out []string
|
||||
named := false
|
||||
for _, kv := range env {
|
||||
name, value, _ := strings.Cut(kv, "=")
|
||||
if want[name] && value != "" {
|
||||
out = append(out, kv)
|
||||
named = named || name == "DISPLAY" || name == "WAYLAND_DISPLAY"
|
||||
}
|
||||
}
|
||||
if !named {
|
||||
return nil
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// findSession is the person's graphical session now, or nil: a session of the watcher's account that is graphical,
|
||||
// whose user manager's environment names a display (§16).
|
||||
func (w *Watcher) findSession() (*Session, error) {
|
||||
if w.bus == nil {
|
||||
return nil, fmt.Errorf("not subscribed on the system bus")
|
||||
}
|
||||
sessions, err := w.bus.sessions(w.UID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, s := range sessions {
|
||||
if !s.graphical() {
|
||||
continue
|
||||
}
|
||||
if found := w.sessionWithDisplay(s); found != nil {
|
||||
return found, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// sessionWithDisplay is s reached, when its user manager's environment names a display; else nil.
|
||||
func (w *Watcher) sessionWithDisplay(s loginSession) *Session {
|
||||
found := Session{ID: s.ID, Type: s.Type, RuntimePath: s.RuntimePath}
|
||||
env, err := w.Environment(found.Bus())
|
||||
if err != nil {
|
||||
journal("reading the user manager's environment of session %s failed: %v", s.ID, err)
|
||||
return nil
|
||||
}
|
||||
if found.Display = displayIn(env, s.Type); found.Display == nil {
|
||||
return nil
|
||||
}
|
||||
return &found
|
||||
}
|
||||
|
||||
// sessionStart is the session start being waited for: the session, until when, and the wait's file events.
|
||||
type sessionStart struct {
|
||||
session loginSession
|
||||
files <-chan struct{}
|
||||
bound <-chan time.Time
|
||||
stop chan struct{}
|
||||
}
|
||||
|
||||
// sessionNew acts on logind's SessionNew: for a graphical session of the watcher's account, it waits for the user
|
||||
// manager's environment to name a display, reading it again at each file event (§17).
|
||||
func (w *Watcher) sessionNew(path string) {
|
||||
s, err := w.bus.session(path)
|
||||
if err != nil {
|
||||
journal("reading the new session %s failed: %v", path, err)
|
||||
return
|
||||
}
|
||||
if s.UID != w.UID || (s.Type != "x11" && s.Type != "wayland") || s.Remote {
|
||||
return
|
||||
}
|
||||
w.endSessionWait()
|
||||
stop := make(chan struct{})
|
||||
w.starting = &sessionStart{session: s, stop: stop, bound: w.After(sessionWait),
|
||||
files: w.FileEvents([]string{x11Sockets, s.RuntimePath}, stop)}
|
||||
journal("session %s (%s) started; waiting for its display", s.ID, s.Type)
|
||||
}
|
||||
|
||||
// sessionFiles acts on a file event during the wait: the environment is read again, and once it names a display the
|
||||
// session's start is acted on (§15's third moment).
|
||||
func (w *Watcher) sessionFiles() {
|
||||
if w.starting == nil {
|
||||
return
|
||||
}
|
||||
found := w.sessionWithDisplay(w.starting.session)
|
||||
if found == nil {
|
||||
return
|
||||
}
|
||||
w.endSessionWait()
|
||||
w.sessionStarted(*found)
|
||||
}
|
||||
|
||||
// sessionBound ends a wait that found no display within its bound.
|
||||
func (w *Watcher) sessionBound() {
|
||||
if w.starting == nil {
|
||||
return
|
||||
}
|
||||
journal("session %s's start was not acted on: its user manager's environment named no display within %s",
|
||||
w.starting.session.ID, sessionWait)
|
||||
w.noteSession("not acted on: no display named within " + sessionWait.String())
|
||||
w.endSessionWait()
|
||||
}
|
||||
|
||||
func (w *Watcher) endSessionWait() {
|
||||
if w.starting != nil {
|
||||
close(w.starting.stop)
|
||||
w.starting = nil
|
||||
}
|
||||
}
|
||||
|
||||
// sessionStarted is §15's third moment: with the present rating PORTAL, the check on and a connection active, the page
|
||||
// is opened and the person told; else nothing. It reads the present rating, never a kept event.
|
||||
func (w *Watcher) sessionStarted(s Session) {
|
||||
if w.bus == nil {
|
||||
journal("session %s started while not subscribed on the system bus: nothing opened", s.ID)
|
||||
w.noteSession("nothing: not subscribed on the system bus")
|
||||
return
|
||||
}
|
||||
r, err := w.bus.rating()
|
||||
if err != nil {
|
||||
journal("session %s started; reading the rating failed: %v", s.ID, err)
|
||||
w.noteSession("nothing: the rating did not read")
|
||||
return
|
||||
}
|
||||
if !r.checkOn() || !webAddress(r.CheckURI) || r.Connectivity != ratingPortal || !r.active() {
|
||||
journal("session %s started with the rating %s: nothing opened", s.ID, ratingName(r.Connectivity))
|
||||
w.noteSession("nothing: the rating is " + ratingName(r.Connectivity))
|
||||
return
|
||||
}
|
||||
journal("session %s started with the rating PORTAL: opening the sign-in page", s.ID)
|
||||
w.noteSession("opened the sign-in page")
|
||||
w.present(&s, r.Network, r.CheckURI)
|
||||
}
|
||||
|
||||
func (w *Watcher) noteSession(did string) {
|
||||
w.state.LastSession = &sessionNote{At: w.Now(), Did: did}
|
||||
}
|
||||
|
||||
// sessionNote is the last session start and what the watcher did.
|
||||
type sessionNote struct {
|
||||
At time.Time `json:"at"`
|
||||
Did string `json:"did"`
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The person's session as logind says it: x11, local, active, of the watcher's account.
|
||||
func personsSession() loginSession {
|
||||
return loginSession{ID: "2", Path: "/org/freedesktop/login1/session/_32", UID: 1000, Type: "x11", State: "active",
|
||||
RuntimePath: "/run/user/1000"}
|
||||
}
|
||||
|
||||
// aSessionWatcher is a subscribed watcher whose stood-in user manager names a display once named is set; the test acts
|
||||
// as its loop, calling what a file event and the bound's end call.
|
||||
func aSessionWatcher(t *testing.T, sys *fakeSystem, named *bool) *Watcher {
|
||||
t.Helper()
|
||||
w := aWatcher(t, sys)
|
||||
files, bound := make(chan struct{}, 1), make(chan time.Time, 1)
|
||||
w.FileEvents = func(dirs []string, stop <-chan struct{}) <-chan struct{} {
|
||||
if strings.Join(dirs, " ") != "/tmp/.X11-unix /run/user/1000" {
|
||||
t.Errorf("the session's start is waited for on %v", dirs)
|
||||
}
|
||||
return files
|
||||
}
|
||||
w.After = func(d time.Duration) <-chan time.Time {
|
||||
if d != 60*time.Second {
|
||||
t.Errorf("the session's start is waited for %s", d)
|
||||
}
|
||||
return bound
|
||||
}
|
||||
w.Environment = func(bus string) ([]string, error) {
|
||||
if bus != "unix:path=/run/user/1000/bus" {
|
||||
t.Errorf("the environment is read over %s", bus)
|
||||
}
|
||||
if *named {
|
||||
return []string{"HOME=/home/person", "DISPLAY=:1", "XAUTHORITY=/home/person/.Xauthority"}, nil
|
||||
}
|
||||
return []string{"HOME=/home/person"}, nil
|
||||
}
|
||||
w.subscribe()
|
||||
return w
|
||||
}
|
||||
|
||||
// A session that starts while the rating is PORTAL opens the page once, when the user manager's environment names its
|
||||
// display; one that starts while it is not opens nothing; one whose display is not named within the bound is not acted
|
||||
// on, and says so (design 08 sign-in-page §15, §16, §17, §25).
|
||||
func TestASessionStartingWhilePortalOpensThePageOnce(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
rating Rating
|
||||
named bool
|
||||
opens int
|
||||
did string
|
||||
}{
|
||||
{"PORTAL", guest(ratingPortal), true, 1, "opened the sign-in page"},
|
||||
{"FULL", guest(ratingFull), true, 0, "nothing: the rating is FULL"},
|
||||
{"no display named", guest(ratingPortal), false, 0, "not acted on: no display named within 1m0s"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
sys := &fakeSystem{}
|
||||
sys.set(guest(ratingFull))
|
||||
named := false
|
||||
w := aSessionWatcher(t, sys, &named)
|
||||
desk := w.Desk.(*fakeDesk)
|
||||
sys.sessions = []loginSession{personsSession(), {ID: "9", Path: "/org/freedesktop/login1/session/_39", UID: 1001,
|
||||
Type: "x11", State: "active", RuntimePath: "/run/user/1001"}}
|
||||
w.heardSignal(signal{Session: "/org/freedesktop/login1/session/_39"})
|
||||
if w.starting != nil {
|
||||
t.Fatal("another account's session is waited for")
|
||||
}
|
||||
sys.set(c.rating)
|
||||
w.heardSignal(signal{Session: personsSession().Path})
|
||||
w.sessionFiles()
|
||||
if len(desk.opened()) != 0 || w.starting == nil {
|
||||
t.Fatal("acted on a session whose display is not named yet")
|
||||
}
|
||||
named = c.named
|
||||
w.sessionFiles()
|
||||
if w.starting != nil {
|
||||
w.sessionBound()
|
||||
}
|
||||
if got := desk.opened(); len(got) != c.opens || (c.opens == 1 && got[0] != "2 http://check.example.net/") {
|
||||
t.Fatalf("opened %q", got)
|
||||
}
|
||||
if w.state.LastSession == nil || w.state.LastSession.Did != c.did {
|
||||
t.Fatalf("the session's start is said as %+v", w.state.LastSession)
|
||||
}
|
||||
if c.named == false && !strings.Contains(strings.Join(lines(), "\n"), "start was not acted on") {
|
||||
t.Fatal("a start not acted on was not written to the journal")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// With no graphical session found the watcher opens nothing and still keeps the events: a remote session, one in no
|
||||
// graphical type and one whose environment names no display are no session (§15, §16, §25).
|
||||
func TestNoSessionOpensNothingAndStillKeeps(t *testing.T) {
|
||||
journalLines(t)
|
||||
sys := &fakeSystem{}
|
||||
named := false
|
||||
w := aSessionWatcher(t, sys, &named)
|
||||
remote, tty := personsSession(), personsSession()
|
||||
remote.Remote, tty.Type = true, "tty"
|
||||
sys.sessions = []loginSession{remote, tty, personsSession()}
|
||||
w.heard(guest(ratingFull), false)
|
||||
w.heard(guest(ratingPortal), false)
|
||||
w.present(nil, "guest-example", "http://check.example.net/")
|
||||
if got := w.Desk.(*fakeDesk).opened(); len(got) != 0 {
|
||||
t.Fatalf("opened %q with no session", got)
|
||||
}
|
||||
if kept := keptSaid(t, w.Folder); len(kept) == 0 || kept[len(kept)-1] != "sign-in-asked guest-example wlan0" {
|
||||
t.Fatalf("kept %q", kept)
|
||||
}
|
||||
named = true
|
||||
if s, err := w.findSession(); err != nil || s == nil || s.ID != "2" || strings.Join(s.Display, " ") != "DISPLAY=:1 XAUTHORITY=/home/person/.Xauthority" {
|
||||
t.Fatalf("found %+v %v", s, err)
|
||||
}
|
||||
if got := displayIn([]string{"WAYLAND_DISPLAY=wayland-0", "DISPLAY=:0"}, "wayland"); strings.Join(got, " ") != "WAYLAND_DISPLAY=wayland-0" {
|
||||
t.Fatalf("a wayland session's display is %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package main
|
||||
|
||||
// The module's own local state, the one folder its two parts share (design 08 sign-in-page §12): the watcher's socket,
|
||||
// the network manager's check address, the kept events in pending/, the bundle's last uplink-names call and the next
|
||||
// sequence of the watcher's message ids. Every file is written whole: beside, then renamed over. Nothing else reads or
|
||||
// writes the folder.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// stateHome is the folder under the account's home, as the manifest declares it: owner the account, mode 0700.
|
||||
const stateHome = ".local/state/mesh/networkmanager"
|
||||
|
||||
// The folder's names.
|
||||
const (
|
||||
socketName = "watch.sock"
|
||||
checkName = "check-address"
|
||||
pendingName = "pending"
|
||||
namesName = "names.json"
|
||||
sequenceName = "sequence"
|
||||
)
|
||||
|
||||
// The watcher's socket's asks.
|
||||
const (
|
||||
askState = "state"
|
||||
askRatingAgain = "rating-again"
|
||||
)
|
||||
|
||||
// socketBound is how long one ask on the watcher's socket may take, a stated constant (design 08 sign-in-page §12;
|
||||
// lead answer C-8): a bundle's ask past it counts as no answer, and the watcher drops a line not asked within it.
|
||||
const socketBound = 5 * time.Second
|
||||
|
||||
// journal writes one line to the part's journal: its standard error, which the service manager keeps.
|
||||
var journal = func(format string, args ...any) {
|
||||
fmt.Fprintf(os.Stderr, "[networkmanager] "+format+"\n", args...)
|
||||
}
|
||||
|
||||
// Folder is the module's own local state, at Dir, on the node named Node.
|
||||
type Folder struct {
|
||||
Dir string
|
||||
Node string
|
||||
}
|
||||
|
||||
// theFolder is the account's folder, on the node the tool runner names the bundle (MESH_NODE).
|
||||
func theFolder() (Folder, error) {
|
||||
f, err := accountFolder()
|
||||
f.Node = os.Getenv("MESH_NODE")
|
||||
return f, err
|
||||
}
|
||||
|
||||
// accountFolder is the account's folder with no node: the watcher's, which names none (L-3).
|
||||
func accountFolder() (Folder, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return Folder{}, err
|
||||
}
|
||||
return Folder{Dir: filepath.Join(home, stateHome)}, nil
|
||||
}
|
||||
|
||||
func (f Folder) path(name string) string { return filepath.Join(f.Dir, name) }
|
||||
|
||||
// writeWhole writes data to path whole: into a file beside it, synced, then renamed over it, so a reader sees the old
|
||||
// text or the new, never a part.
|
||||
func writeWhole(path string, data []byte, mode os.FileMode) error {
|
||||
beside := path + ".new"
|
||||
out, err := os.OpenFile(beside, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = out.Write(data)
|
||||
if err == nil {
|
||||
err = out.Sync()
|
||||
}
|
||||
if cerr := out.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err == nil {
|
||||
err = os.Rename(beside, path)
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(beside)
|
||||
return fmt.Errorf("writing %s: %w", path, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// nextSequence is the next sequence of the watcher's message ids and kept files, written whole as one more before it is
|
||||
// used, so no id is used twice while the folder lives, a restart included (R3-1).
|
||||
func (f Folder) nextSequence() (uint64, error) {
|
||||
n := uint64(1)
|
||||
raw, err := os.ReadFile(f.path(sequenceName))
|
||||
switch {
|
||||
case err == nil:
|
||||
if n, err = strconv.ParseUint(strings.TrimSpace(string(raw)), 10, 64); err != nil || n == 0 {
|
||||
return 0, fmt.Errorf("%s holds no sequence: %q", f.path(sequenceName), raw)
|
||||
}
|
||||
case !errors.Is(err, os.ErrNotExist):
|
||||
return 0, err
|
||||
}
|
||||
if err := writeWhole(f.path(sequenceName), []byte(strconv.FormatUint(n+1, 10)+"\n"), 0o600); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Kept is one change the watcher kept for the bundle to publish: the event's name, its sequence and its body, all
|
||||
// without the node. The watcher names no node; the bundle fills its own into the subject, the message id and the body's
|
||||
// node when it publishes (lead answer L-3).
|
||||
type Kept struct {
|
||||
Sequence uint64 `json:"sequence"`
|
||||
Event string `json:"event"`
|
||||
Body json.RawMessage `json:"body"`
|
||||
}
|
||||
|
||||
// Name is the kept change as the journal names it: `<event>.<sequence>`.
|
||||
func (k Kept) Name() string { return fmt.Sprintf("%s.%d", k.Event, k.Sequence) }
|
||||
|
||||
func pendingFile(seq uint64) string { return fmt.Sprintf("%010d.json", seq) }
|
||||
|
||||
// keep writes one change into pending/ under the next sequence, made once (§20; L-3).
|
||||
func (f Folder) keep(event string, body any) (Kept, error) {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
if err := os.MkdirAll(f.path(pendingName), 0o700); err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
seq, err := f.nextSequence()
|
||||
if err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
k := Kept{Sequence: seq, Event: event, Body: raw}
|
||||
data, err := json.Marshal(k)
|
||||
if err != nil {
|
||||
return Kept{}, err
|
||||
}
|
||||
return k, writeWhole(filepath.Join(f.path(pendingName), pendingFile(seq)), append(data, '\n'), 0o600)
|
||||
}
|
||||
|
||||
// pending is every kept event, in sequence order. A file that is not a kept event (a write beside one) is skipped; one
|
||||
// that does not read is an error naming it.
|
||||
func (f Folder) pending() ([]Kept, error) {
|
||||
entries, err := os.ReadDir(f.path(pendingName))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []Kept
|
||||
for _, e := range entries {
|
||||
name, ok := strings.CutSuffix(e.Name(), ".json")
|
||||
if !ok || e.IsDir() {
|
||||
continue
|
||||
}
|
||||
seq, err := strconv.ParseUint(name, 10, 64)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(f.path(pendingName), e.Name()))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var k Kept
|
||||
if err := json.Unmarshal(raw, &k); err != nil {
|
||||
return nil, fmt.Errorf("the kept event %s does not read: %w", e.Name(), err)
|
||||
}
|
||||
k.Sequence = seq
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Sequence < out[j].Sequence })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// drop deletes one kept event; one already gone is no error.
|
||||
func (f Folder) drop(k Kept) error {
|
||||
err := os.Remove(filepath.Join(f.path(pendingName), pendingFile(k.Sequence)))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// writeCheckAddress writes the network manager's check address on one line, empty when there is none.
|
||||
func (f Folder) writeCheckAddress(address string) error {
|
||||
return writeWhole(f.path(checkName), []byte(address+"\n"), 0o600)
|
||||
}
|
||||
|
||||
// checkAddress is the check address the watcher wrote; empty when it wrote none or none is set.
|
||||
func (f Folder) checkAddress() (string, error) {
|
||||
raw, err := os.ReadFile(f.path(checkName))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", nil
|
||||
}
|
||||
return strings.TrimSpace(string(raw)), err
|
||||
}
|
||||
|
||||
// The results of an uplink-names call besides a failure's text.
|
||||
const (
|
||||
resultOK = "ok"
|
||||
resultNoHolder = "no holder"
|
||||
)
|
||||
|
||||
// NamesCall is the bundle's last uplink-names call: the names given, its result (ok, no holder or the failure) and
|
||||
// when.
|
||||
type NamesCall struct {
|
||||
Names []string `json:"names"`
|
||||
Result string `json:"result"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
// Failed says whether the call stands failed: no holder is not a failure.
|
||||
func (c NamesCall) Failed() bool {
|
||||
return c.Result != "" && c.Result != resultOK && c.Result != resultNoHolder
|
||||
}
|
||||
|
||||
func (f Folder) writeNames(c NamesCall) error {
|
||||
if c.Names == nil {
|
||||
c.Names = []string{}
|
||||
}
|
||||
data, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return writeWhole(f.path(namesName), append(data, '\n'), 0o600)
|
||||
}
|
||||
|
||||
// names is the last uplink-names call, nil when none was written.
|
||||
func (f Folder) names() (*NamesCall, error) {
|
||||
raw, err := os.ReadFile(f.path(namesName))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var c NamesCall
|
||||
return &c, json.Unmarshal(raw, &c)
|
||||
}
|
||||
|
||||
// socketAsk is the one line asked on the watcher's socket, socketAnswer the one answered.
|
||||
type socketAsk struct {
|
||||
Ask string `json:"ask"`
|
||||
}
|
||||
|
||||
type socketAnswer struct {
|
||||
Answer json.RawMessage `json:"answer,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// listen makes the watcher's socket, mode 0600, in place of one a stopped watcher left.
|
||||
func (f Folder) listen() (net.Listener, error) {
|
||||
path := f.path(socketName)
|
||||
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
l, err := net.Listen("unix", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// serveSocket answers each connection's one asked line with handle's answer, until l is closed.
|
||||
func serveSocket(l net.Listener, handle func(ask string) (any, error)) {
|
||||
for {
|
||||
conn, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(socketBound))
|
||||
line, err := bufio.NewReader(io.LimitReader(conn, 4096)).ReadBytes('\n')
|
||||
if err != nil && len(line) == 0 {
|
||||
return
|
||||
}
|
||||
var ask socketAsk
|
||||
var out socketAnswer
|
||||
if err := json.Unmarshal(line, &ask); err != nil {
|
||||
out.Error = "the line asked is no JSON: " + err.Error()
|
||||
} else if answer, err := handle(ask.Ask); err != nil {
|
||||
out.Error = err.Error()
|
||||
} else if out.Answer, err = json.Marshal(answer); err != nil {
|
||||
out.Error = err.Error()
|
||||
}
|
||||
data, _ := json.Marshal(out)
|
||||
conn.Write(append(data, '\n'))
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// askWatcher asks the watcher one ask on its socket and reads its answer into into (nil to drop it).
|
||||
func (f Folder) askWatcher(ask string, into any) error {
|
||||
conn, err := net.DialTimeout("unix", f.path(socketName), socketBound)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the watcher's socket does not answer: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(socketBound))
|
||||
data, _ := json.Marshal(socketAsk{Ask: ask})
|
||||
if _, err := conn.Write(append(data, '\n')); err != nil {
|
||||
return fmt.Errorf("the watcher's socket does not answer: %w", err)
|
||||
}
|
||||
line, err := bufio.NewReader(conn).ReadBytes('\n')
|
||||
if err != nil {
|
||||
return fmt.Errorf("the watcher's socket does not answer: %w", err)
|
||||
}
|
||||
var out socketAnswer
|
||||
if err := json.Unmarshal(line, &out); err != nil {
|
||||
return fmt.Errorf("the watcher answered no JSON: %w", err)
|
||||
}
|
||||
if out.Error != "" {
|
||||
return fmt.Errorf("the watcher refused %s: %s", ask, out.Error)
|
||||
}
|
||||
if into == nil || len(out.Answer) == 0 {
|
||||
return nil
|
||||
}
|
||||
return json.Unmarshal(out.Answer, into)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func aFolder(t *testing.T) Folder {
|
||||
t.Helper()
|
||||
return Folder{Dir: t.TempDir(), Node: "laptop"}
|
||||
}
|
||||
|
||||
// A watcher restarted after its events were published and pending/ emptied makes message ids it never used, so the
|
||||
// bus keeps them rather than dropping them as duplicates (design 08 sign-in-page §12, §25; R3-1). The watcher's folder
|
||||
// names no node, and a kept change holds its event, its sequence and its body (L-3).
|
||||
func TestARestartedWatcherMakesIdsItNeverUsed(t *testing.T) {
|
||||
f := Folder{Dir: t.TempDir()}
|
||||
used := map[uint64]bool{}
|
||||
for range 3 {
|
||||
k, err := f.keep("sign-in-asked", map[string]string{"link": "wlan0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
used[k.Sequence] = true
|
||||
}
|
||||
kept, err := f.pending()
|
||||
if err != nil || len(kept) != 3 || kept[0].Name() != "sign-in-asked.1" || kept[2].Sequence != 3 {
|
||||
t.Fatalf("kept %+v %v", kept, err)
|
||||
}
|
||||
for _, k := range kept {
|
||||
if err := f.drop(k); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
restarted := Folder{Dir: f.Dir}
|
||||
k, err := restarted.keep("sign-in-ended", map[string]string{})
|
||||
if err != nil || used[k.Sequence] || k.Name() != "sign-in-ended.4" {
|
||||
t.Fatalf("the restarted watcher made %q (%v), having used %v", k.Name(), err, used)
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(f.Dir, pendingName, "0000000004.json"))
|
||||
if string(raw) != `{"sequence":4,"event":"sign-in-ended","body":{}}`+"\n" {
|
||||
t.Fatalf("the kept file holds %s", raw)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(f.Dir, pendingName, "0000000004.json")); err != nil {
|
||||
t.Fatalf("the kept file is not named by its ten-digit sequence: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Every file of the folder is written whole, beside and renamed over: a write that fails leaves the old text and no
|
||||
// part of the new, and a file being written beside a kept event is not read as one (§12).
|
||||
func TestTheFoldersFilesAreWrittenWhole(t *testing.T) {
|
||||
f := aFolder(t)
|
||||
if err := f.writeCheckAddress("http://check.example.net/"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Mkdir(f.path(checkName)+".new", 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.writeCheckAddress("http://other.example.net/"); err == nil {
|
||||
t.Fatal("a write that could not be made beside was taken")
|
||||
}
|
||||
if got, _ := f.checkAddress(); got != "http://check.example.net/" {
|
||||
t.Fatalf("a failed write left %q", got)
|
||||
}
|
||||
os.Remove(f.path(checkName) + ".new")
|
||||
if err := f.writeNames(NamesCall{Result: resultNoHolder}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c, err := f.names(); err != nil || c.Result != resultNoHolder || c.Names == nil || c.Failed() {
|
||||
t.Fatalf("names read %+v %v", c, err)
|
||||
}
|
||||
if _, err := f.keep("sign-in-asked", map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(filepath.Join(f.Dir, pendingName, "0000000009.json.new"), []byte("{"), 0o600)
|
||||
entries, _ := os.ReadDir(f.Dir)
|
||||
for _, e := range entries {
|
||||
if strings.HasSuffix(e.Name(), ".new") {
|
||||
t.Errorf("%s was left beside", e.Name())
|
||||
}
|
||||
}
|
||||
if kept, err := f.pending(); err != nil || len(kept) != 1 {
|
||||
t.Fatalf("pending read %+v %v", kept, err)
|
||||
}
|
||||
if raw, _ := os.ReadFile(f.path(sequenceName)); string(raw) != "2\n" {
|
||||
t.Fatalf("the sequence file holds %q", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// The watcher's socket answers one JSON line asked with one line, its refusal named (§12).
|
||||
func TestTheWatchersSocketAnswersOneLine(t *testing.T) {
|
||||
f := aFolder(t)
|
||||
l, err := f.listen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
go serveSocket(l, func(ask string) (any, error) {
|
||||
if ask == askState {
|
||||
return map[string]bool{"subscribed": true}, nil
|
||||
}
|
||||
return nil, errors.New("no such ask")
|
||||
})
|
||||
if fi, err := os.Stat(f.path(socketName)); err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("the socket is %v %v", fi, err)
|
||||
}
|
||||
var state struct{ Subscribed bool }
|
||||
if err := f.askWatcher(askState, &state); err != nil || !state.Subscribed {
|
||||
t.Fatalf("state answered %+v %v", state, err)
|
||||
}
|
||||
if err := f.askWatcher("other", nil); err == nil || !strings.Contains(err.Error(), "no such ask") {
|
||||
t.Fatalf("a refusal answered %v", err)
|
||||
}
|
||||
l.Close()
|
||||
if err := f.askWatcher(askState, nil); err == nil {
|
||||
t.Fatal("a closed socket answered")
|
||||
}
|
||||
}
|
||||
|
||||
// A path in the folder the watcher does not know is left as it is and written to its journal once per path: what is
|
||||
// there at its start, and what a file event makes after (§12; lead answer L-1).
|
||||
func TestAPathTheWatcherDoesNotKnowIsLeftAndSaidOnce(t *testing.T) {
|
||||
lines := journalLines(t)
|
||||
sys := &fakeSystem{}
|
||||
sys.set(guest(ratingFull))
|
||||
w := aWatcher(t, sys)
|
||||
f := w.Folder
|
||||
if _, err := f.keep(eventEnded, map[string]string{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.writeCheckAddress("http://check.example.net/")
|
||||
for _, p := range []string{filepath.Join(f.Dir, "notes.txt"), filepath.Join(f.Dir, pendingName, "stray")} {
|
||||
if err := os.WriteFile(p, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
made := make(chan string)
|
||||
w.Made = func(dirs []string, stop <-chan struct{}) <-chan string {
|
||||
if len(dirs) != 2 || dirs[0] != f.Dir || dirs[1] != filepath.Join(f.Dir, pendingName) {
|
||||
t.Errorf("watched %v", dirs)
|
||||
}
|
||||
return made
|
||||
}
|
||||
stop, done := make(chan struct{}), make(chan struct{})
|
||||
go func() { _ = w.run(stop); close(done) }()
|
||||
for _, p := range []string{filepath.Join(f.Dir, "other"), filepath.Join(f.Dir, "other"), filepath.Join(f.Dir, "sequence.new"),
|
||||
filepath.Join(f.Dir, pendingName, "0000000002.json")} {
|
||||
made <- p
|
||||
}
|
||||
w.askLoop(askState)
|
||||
close(stop)
|
||||
<-done
|
||||
var said []string
|
||||
for _, l := range lines() {
|
||||
if strings.Contains(l, "is not the module's") {
|
||||
said = append(said, strings.TrimPrefix(l, f.Dir+"/"))
|
||||
}
|
||||
}
|
||||
want := []string{"notes.txt is not the module's: left as it is", "pending/stray is not the module's: left as it is",
|
||||
"other is not the module's: left as it is"}
|
||||
if strings.Join(said, "|") != strings.Join(want, "|") {
|
||||
t.Fatalf("said %q", said)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(f.Dir, "notes.txt")); err != nil {
|
||||
t.Fatal("a path the watcher does not know was not left")
|
||||
}
|
||||
}
|
||||
|
||||
// The bounds the design states, each a constant and none a setting: the socket's 5 s, the open's 10 s, the session
|
||||
// start's 60 s and the 256 kept events (design 08 sign-in-page §12, §17, §18, §20; R2-7, C-8).
|
||||
func TestTheStatedBounds(t *testing.T) {
|
||||
if socketBound != 5*time.Second || openBound != 10*time.Second || sessionWait != 60*time.Second || keptBound != 256 {
|
||||
t.Fatalf("the bounds are %s, %s, %s and %d", socketBound, openBound, sessionWait, keptBound)
|
||||
}
|
||||
}
|
||||
|
||||
// The watcher reads no MESH_NODE: its folder names no node, whatever the environment says (L-3).
|
||||
func TestTheWatchersFolderNamesNoNode(t *testing.T) {
|
||||
t.Setenv("MESH_NODE", "laptop")
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
if f, err := accountFolder(); err != nil || f.Node != "" {
|
||||
t.Fatalf("the watcher's folder is %+v (%v)", f, err)
|
||||
}
|
||||
if f, err := theFolder(); err != nil || f.Node != "laptop" {
|
||||
t.Fatalf("the bundle's folder is %+v (%v)", f, err)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -62,3 +63,67 @@ func TestEveryFileTakesItsTextFromATemplate(t *testing.T) {
|
||||
t.Errorf("the build packs files/ into %d archives, not one", packs)
|
||||
}
|
||||
}
|
||||
|
||||
// The manifest declares the watcher's process as the account, its health its unit's state; the folder the two parts
|
||||
// share, the account's alone; the event the bundle consumes and the verbs it invokes; and the five tools. NetworkManager's
|
||||
// unit keeps no state and no health (design 08 sign-in-page §11, §12, §13, §27; lead answer C-2c).
|
||||
func TestTheManifestDeclaresTheSignInParts(t *testing.T) {
|
||||
raw, err := os.ReadFile(filepath.Join(moduleDir, "module.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m struct {
|
||||
Consumes []string `json:"consumes"`
|
||||
Invokes []string `json:"invokes"`
|
||||
Tools []string `json:"tools"`
|
||||
Claims []map[string]any `json:"claims"`
|
||||
Resources []map[string]any `json:"resources"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
same := func(got []string, want ...string) bool {
|
||||
return strings.Join(got, " ") == strings.Join(want, " ")
|
||||
}
|
||||
if !same(m.Consumes, "node-engine.running") {
|
||||
t.Errorf("consumes %v", m.Consumes)
|
||||
}
|
||||
if !same(m.Invokes, "seat:mesh-module-assigner.assignments", "seat:node-resolver.uplink-names", "seat:node-resolver.routes") {
|
||||
t.Errorf("invokes %v", m.Invokes)
|
||||
}
|
||||
var served []string
|
||||
for _, tool := range (&bundle{}).tools() {
|
||||
served = append(served, tool.Name)
|
||||
}
|
||||
if !same(m.Tools, served...) {
|
||||
t.Errorf("lists the tools %v, serves %v", m.Tools, served)
|
||||
}
|
||||
if len(m.Claims) != 1 || m.Claims[0]["name"] != "node-uplink" {
|
||||
t.Errorf("claims %v", m.Claims)
|
||||
}
|
||||
byID := map[string]map[string]any{}
|
||||
for _, r := range m.Resources {
|
||||
byID[r["id"].(string)] = r
|
||||
}
|
||||
dir := byID["sign-in-state"]
|
||||
if dir["type"] != "directory" || dir["path"] != "${machine:account-home}/"+stateHome ||
|
||||
dir["owner"] != "${machine:account}" || dir["mode"] != "0700" || dir["unknown"] != "module" {
|
||||
t.Errorf("the folder is %v", dir)
|
||||
}
|
||||
p := byID["sign-in"]
|
||||
run, _ := json.Marshal(p["run"])
|
||||
h, _ := json.Marshal(p["health"])
|
||||
if p["type"] != "process" || p["name"] != "networkmanager-sign-in" || p["artifact"] != "tools" ||
|
||||
string(run) != `["./uplink-tools","watch"]` || p["user"] != "${machine:account}" ||
|
||||
string(h) != `{"kind":"unit"}` {
|
||||
t.Errorf("the watcher is %v", p)
|
||||
}
|
||||
if byID["service"]["health"] != nil || byID["service"]["state"] != nil {
|
||||
t.Errorf("NetworkManager's unit carries a state or a health: %v", byID["service"])
|
||||
}
|
||||
for _, id := range []string{"package", "config", "service"} {
|
||||
if byID[id] == nil {
|
||||
t.Errorf("the resource %s is gone", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
// networkmanager's own tools, served by the bundle (design 08 sign-in-page §23): the read of the sign-in reaction, the
|
||||
// three acts that start by hand what the two parts do by themselves, and the health tool of the watcher's process.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver"
|
||||
stdio "git.novox.be/novox/mesh-sdk/go"
|
||||
"git.novox.be/novox/mesh-sdk/go/health"
|
||||
)
|
||||
|
||||
// signInRead is uplink_sign_in's answer.
|
||||
type signInRead struct {
|
||||
Watcher *watcherState `json:"watcher,omitempty"`
|
||||
WatcherError string `json:"watcher_error,omitempty"`
|
||||
Waiting int `json:"waiting"`
|
||||
RefusedSince int `json:"publishes_refused_since_start"`
|
||||
Names *NamesCall `json:"names,omitempty"`
|
||||
ResolverRefused *string `json:"resolver_refused,omitempty"`
|
||||
ResolverError string `json:"resolver_error,omitempty"`
|
||||
}
|
||||
|
||||
func (b *bundle) tools() []stdio.Tool {
|
||||
return []stdio.Tool{
|
||||
{Name: "uplink_sign_in",
|
||||
Description: "The network's sign-in page as this machine reacts to it: whether the watcher hears the network " +
|
||||
"manager, the last rating it heard and when, the sign-in asked now (network, link, since), the asks opened " +
|
||||
"and ended since its start, the last page opened with its outcome, the last notification, the last session " +
|
||||
"start and what it did, the kept events dropped past the bound of 256, the events waiting to be published " +
|
||||
"and the publishes refused since the bundle's start, the last uplink-names call with its result, and the " +
|
||||
"resolver's refusal of the names where a holder of node-resolver runs here. (r)",
|
||||
Run: func(map[string]any) (any, error) { return b.signIn(), nil }},
|
||||
{Name: "uplink_names_again",
|
||||
Description: "Give this machine's resolver the network manager's check host now, as the bundle does at its " +
|
||||
"moments: calls node-resolver's uplink-names on this node and answers the call as names.json keeps it. (a)",
|
||||
Run: func(map[string]any) (any, error) { return b.names.give("uplink_names_again"), nil }},
|
||||
{Name: "uplink_rating_again",
|
||||
Description: "Make the watcher subscribe on the system bus again, read the network manager's rating now and " +
|
||||
"act on it as on a change; answers the watcher's state after it. (a)",
|
||||
Run: func(map[string]any) (any, error) {
|
||||
var s watcherState
|
||||
if err := b.folder.askWatcher(askRatingAgain, &s); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}},
|
||||
{Name: "uplink_publish_again",
|
||||
Description: "Publish the kept sign-in events now, in order under their own message ids, as the bundle does at " +
|
||||
"its moments: answers how many were published and how many still wait. (a)",
|
||||
Run: func(map[string]any) (any, error) { return b.pub.publishKept("uplink_publish_again"), nil }},
|
||||
{Name: "uplink_health",
|
||||
Description: "Whether the sign-in reaction works: unhealthy while the watcher's socket does not answer, while " +
|
||||
"the watcher is not subscribed on the system bus, or while the last uplink-names call stands failed, naming " +
|
||||
"which; no holder of node-resolver is healthy. A tool to read, not the watcher's health check, which is its " +
|
||||
"unit's state. (r)",
|
||||
Run: func(map[string]any) (any, error) { return b.health(), nil }},
|
||||
}
|
||||
}
|
||||
|
||||
// signIn reads the watcher's state, the folder and, where a holder of node-resolver runs here, the resolver's refusal.
|
||||
func (b *bundle) signIn() signInRead {
|
||||
var out signInRead
|
||||
var s watcherState
|
||||
if err := b.folder.askWatcher(askState, &s); err != nil {
|
||||
out.WatcherError = err.Error()
|
||||
} else {
|
||||
out.Watcher = &s
|
||||
}
|
||||
if kept, err := b.folder.pending(); err == nil {
|
||||
out.Waiting = len(kept)
|
||||
}
|
||||
out.RefusedSince = b.pub.refusedSince()
|
||||
out.Names, _ = b.folder.names()
|
||||
routes, held, err := b.resolverRoutes()
|
||||
switch {
|
||||
case err != nil:
|
||||
out.ResolverError = err.Error()
|
||||
case held:
|
||||
out.ResolverRefused = &routes.UplinkNames.Refused
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// resolverRoutes is node-resolver's routes on this node, held false when no module holds the seat here.
|
||||
func (b *bundle) resolverRoutes() (noderesolver.RoutesAnswer, bool, error) {
|
||||
holder, err := b.names.resolverHolder()
|
||||
if err != nil || holder == "" {
|
||||
return noderesolver.RoutesAnswer{}, false, err
|
||||
}
|
||||
raw, err := b.names.ask("seat:"+noderesolver.Seat+"."+noderesolver.VerbRoutes+"@"+b.folder.Node, struct{}{})
|
||||
if err != nil {
|
||||
return noderesolver.RoutesAnswer{}, true, fmt.Errorf("%s/%s.%s: %w", b.folder.Node, noderesolver.Seat,
|
||||
noderesolver.VerbRoutes, err)
|
||||
}
|
||||
routes, _, err := noderesolver.DecodeRoutesAnswer(raw)
|
||||
return routes, true, err
|
||||
}
|
||||
|
||||
// health is uplink_health's answer, a tool of the bundle and not a node-engine check (§23; lead answer C-2c).
|
||||
func (b *bundle) health() health.Answer {
|
||||
var faults []string
|
||||
var s watcherState
|
||||
if err := b.folder.askWatcher(askState, &s); err != nil {
|
||||
faults = append(faults, err.Error())
|
||||
} else if !s.Subscribed {
|
||||
faults = append(faults, "the watcher is not subscribed on the system bus")
|
||||
}
|
||||
call, err := b.folder.names()
|
||||
if err != nil {
|
||||
faults = append(faults, "names.json does not read: "+err.Error())
|
||||
}
|
||||
if call != nil && call.Failed() {
|
||||
faults = append(faults, "the last uplink-names call failed: "+call.Result)
|
||||
}
|
||||
if len(faults) > 0 {
|
||||
return health.Unhealthy(strings.Join(faults, "; ") + ".")
|
||||
}
|
||||
why := "the watcher hears the network manager"
|
||||
if call != nil {
|
||||
why += "; the last uplink-names call: " + call.Result
|
||||
}
|
||||
return health.Healthy(why + ".")
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/health"
|
||||
)
|
||||
|
||||
// aToolBundle is a bundle over the stood-in mesh and stream, with a watcher's socket answering state as subscribed
|
||||
// says, and recording the asks it was given.
|
||||
func aToolBundle(t *testing.T, mesh *fakeMesh, subscribed *bool, asked *[]string) (*bundle, *fakeStream) {
|
||||
t.Helper()
|
||||
f := aFolder(t)
|
||||
stream := &fakeStream{refuse: map[string]bool{}}
|
||||
b := &bundle{folder: f, pub: &publisher{folder: f, publish: stream.publish},
|
||||
names: &namer{folder: f, ask: mesh.ask, now: time.Now}}
|
||||
if subscribed == nil {
|
||||
return b, stream
|
||||
}
|
||||
l, err := f.listen()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { l.Close() })
|
||||
go serveSocket(l, func(ask string) (any, error) {
|
||||
*asked = append(*asked, ask)
|
||||
return watcherState{Subscribed: *subscribed, Rating: "PORTAL", AsksOpened: 1, DroppedPastBound: 2}, nil
|
||||
})
|
||||
return b, stream
|
||||
}
|
||||
|
||||
func runTool(t *testing.T, b *bundle, name string) any {
|
||||
t.Helper()
|
||||
for _, tool := range b.tools() {
|
||||
if tool.Name == name {
|
||||
out, err := tool.Run(map[string]any{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", name, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
t.Fatalf("no tool %s", name)
|
||||
return nil
|
||||
}
|
||||
|
||||
// The health tool is unhealthy while the watcher's socket does not answer, while the watcher is not subscribed and
|
||||
// while the last uplink-names call stands failed, naming which; no holder is healthy. It is a tool that reads and calls
|
||||
// nothing on the bus: the names are not given again at a look (design 08 sign-in-page §13, §23, §25; C-2c).
|
||||
func TestTheHealthToolSaysWhatIsWrong(t *testing.T) {
|
||||
journalLines(t)
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
socket bool
|
||||
subscribed bool
|
||||
holder string
|
||||
fail bool
|
||||
healthy bool
|
||||
why string
|
||||
}{
|
||||
{"no socket", false, false, "", false, false, "the watcher's socket does not answer"},
|
||||
{"not subscribed", true, false, "", false, false, "the watcher is not subscribed on the system bus"},
|
||||
{"a failed call", true, true, "systemd-resolved", true, false, "the last uplink-names call failed"},
|
||||
{"no holder", true, true, "", false, true, "no holder"},
|
||||
{"given", true, true, "systemd-resolved", false, true, "ok"},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
mesh := &fakeMesh{holder: c.holder,
|
||||
routes: `{"links":[],"mesh":{"domains":[],"servers":[]},"mesh_resolvers":{"silent":false},"uplink_names":{"names":["check.example.net"],"link":"wlan0","refused":""}}`}
|
||||
var asked []string
|
||||
subscribed := c.subscribed
|
||||
var b *bundle
|
||||
if c.socket {
|
||||
b, _ = aToolBundle(t, mesh, &subscribed, &asked)
|
||||
} else {
|
||||
b, _ = aToolBundle(t, mesh, nil, nil)
|
||||
}
|
||||
b.folder.writeCheckAddress("http://check.example.net/")
|
||||
if c.fail {
|
||||
mesh.fail = errors.New("no answer within its bound")
|
||||
}
|
||||
b.names.give("the bundle's start")
|
||||
mesh.fail = nil
|
||||
got := runTool(t, b, "uplink_health").(health.Answer)
|
||||
if got.Healthy != c.healthy || !strings.Contains(got.Why, c.why) {
|
||||
t.Fatalf("answered %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
mesh := &fakeMesh{holder: "systemd-resolved",
|
||||
routes: `{"uplink_names":{"names":[],"link":"","refused":"resolved refused the domains"}}`}
|
||||
subscribed, asked := true, []string{}
|
||||
b, _ := aToolBundle(t, mesh, &subscribed, &asked)
|
||||
b.folder.writeCheckAddress("http://check.example.net/")
|
||||
b.names.give("the bundle's start")
|
||||
if got := runTool(t, b, "uplink_health").(health.Answer); !got.Healthy || len(mesh.called()) != 1 {
|
||||
t.Fatalf("the health tool answered %+v and called uplink-names %d times", got, len(mesh.called()))
|
||||
}
|
||||
}
|
||||
|
||||
// Each tool answers: the read of the sign-in reaction, the names given again, the watcher asked rating-again, and the
|
||||
// kept events published again (§23, §25; R3-5).
|
||||
func TestEachToolAnswers(t *testing.T) {
|
||||
journalLines(t)
|
||||
mesh := &fakeMesh{holder: "systemd-resolved",
|
||||
routes: `{"uplink_names":{"names":["check.example.net"],"link":"wlan0","refused":"resolved refused the domains"}}`}
|
||||
subscribed, asked := true, []string{}
|
||||
b, stream := aToolBundle(t, mesh, &subscribed, &asked)
|
||||
b.folder.writeCheckAddress("http://check.example.net/")
|
||||
keepThree(t, b.folder)
|
||||
stream.refuse["laptop.sign-in-ended.1"] = true
|
||||
b.pub.publishKept("the bundle's start")
|
||||
|
||||
read := runTool(t, b, "uplink_sign_in").(signInRead)
|
||||
raw, _ := json.Marshal(read)
|
||||
if read.Watcher == nil || read.Watcher.Rating != "PORTAL" || read.Watcher.DroppedPastBound != 2 || read.Waiting != 3 ||
|
||||
read.RefusedSince != 1 || read.Names != nil || read.ResolverRefused == nil ||
|
||||
*read.ResolverRefused != "resolved refused the domains" {
|
||||
t.Fatalf("uplink_sign_in answered %s", raw)
|
||||
}
|
||||
if c := runTool(t, b, "uplink_names_again").(NamesCall); c.Result != resultOK || len(mesh.called()) != 1 {
|
||||
t.Fatalf("uplink_names_again answered %+v", c)
|
||||
}
|
||||
if s := runTool(t, b, "uplink_rating_again").(watcherState); !s.Subscribed || asked[len(asked)-1] != askRatingAgain {
|
||||
t.Fatalf("uplink_rating_again answered %+v, asked %v", s, asked)
|
||||
}
|
||||
if r := runTool(t, b, "uplink_publish_again").(publishResult); r.Published != 3 || r.Waiting != 0 {
|
||||
t.Fatalf("uplink_publish_again answered %+v", r)
|
||||
}
|
||||
var names []string
|
||||
for _, tool := range b.tools() {
|
||||
names = append(names, tool.Name)
|
||||
}
|
||||
if strings.Join(names, " ") != "uplink_sign_in uplink_names_again uplink_rating_again uplink_publish_again uplink_health" {
|
||||
t.Fatalf("serves %v", names)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
// A path in the module's folder the watcher does not know (design 08 sign-in-page §12; lead answer L-1): the folder's
|
||||
// `unknown` is `module`, so the node-engine does nothing inside it and the watcher reacts. It leaves such a path as it
|
||||
// is and writes it to its journal once per path: at its start for what is there, and at each file event of the kernel
|
||||
// that makes one.
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// keptFile is a kept event's name in pending/, or one being written beside it.
|
||||
var keptFile = regexp.MustCompile(`^[0-9]{10}\.json(\.new)?$`)
|
||||
|
||||
// knownPath says whether path is one of the folder's own: watch.sock, check-address, pending/ and its files,
|
||||
// names.json, sequence, or a file being written beside one of them.
|
||||
func (f Folder) knownPath(path string) bool {
|
||||
rel, err := filepath.Rel(f.Dir, path)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return false
|
||||
}
|
||||
dir, name := filepath.Split(rel)
|
||||
switch dir {
|
||||
case "":
|
||||
name = strings.TrimSuffix(name, ".new")
|
||||
return name == socketName || name == checkName || name == pendingName || name == namesName || name == sequenceName
|
||||
case pendingName + "/":
|
||||
return keptFile.MatchString(name)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// unknownAtStart is every path in the folder and in pending/ the watcher does not know.
|
||||
func (f Folder) unknownAtStart() []string {
|
||||
var out []string
|
||||
for _, dir := range []string{f.Dir, filepath.Join(f.Dir, pendingName)} {
|
||||
entries, _ := os.ReadDir(dir)
|
||||
for _, e := range entries {
|
||||
if p := filepath.Join(dir, e.Name()); !f.knownPath(p) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// strange writes a path the watcher does not know to its journal, once per path, and leaves it as it is.
|
||||
func (w *Watcher) strange(path string) {
|
||||
if w.Folder.knownPath(path) || w.told[path] {
|
||||
return
|
||||
}
|
||||
if w.told == nil {
|
||||
w.told = map[string]bool{}
|
||||
}
|
||||
w.told[path] = true
|
||||
journal("%s is not the module's: left as it is", path)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user