boundary_test.go RawHistoryFolder

1package main_test
2
3import (
4	"fmt"
5	"go/ast"
6	"go/parser"
7	"go/token"
8	"io/fs"
9	"path/filepath"
10	"sort"
11	"strconv"
12	"strings"
13	"testing"
14)
15
16const modulePath = "github.com/bnema/vev"
17
18type packageLayer string
19
20const (
21	layerRoot        packageLayer = "root"
22	layerCommand     packageLayer = "command"
23	layerScript      packageLayer = "script"
24	layerApp         packageLayer = "app"
25	layerAdapter     packageLayer = "adapter"
26	layerUsecase     packageLayer = "usecase"
27	layerPorts       packageLayer = "ports"
28	layerProtocol    packageLayer = "protocol"
29	layerCatalogue   packageLayer = "catalogue"
30	layerWire        packageLayer = "wire"
31	layerDomain      packageLayer = "domain"
32	layerPersist     packageLayer = "persist"
33	layerSnapshot    packageLayer = "snapshot-codec"
34	layerPlatform    packageLayer = "platform"
35	layerLogging     packageLayer = "logging"
36	layerPkg         packageLayer = "pkg"
37	layerTestSupport packageLayer = "test-support"
38)
39
40var productionDependencies = map[packageLayer]map[packageLayer]bool{
41	layerRoot:      {layerApp: true},
42	layerCommand:   {layerPkg: true},
43	layerScript:    {layerAdapter: true, layerDomain: true, layerPorts: true, layerProtocol: true, layerCatalogue: true, layerWire: true, layerPkg: true},
44	layerApp:       {layerAdapter: true, layerDomain: true, layerPorts: true, layerProtocol: true, layerCatalogue: true, layerWire: true, layerUsecase: true, layerPersist: true, layerSnapshot: true, layerPlatform: true, layerLogging: true, layerPkg: true},
45	layerAdapter:   {layerAdapter: true, layerDomain: true, layerPorts: true, layerProtocol: true, layerCatalogue: true, layerWire: true, layerSnapshot: true, layerPlatform: true, layerPkg: true},
46	layerUsecase:   {layerUsecase: true, layerDomain: true, layerPorts: true, layerProtocol: true, layerCatalogue: true, layerSnapshot: true},
47	layerPorts:     {layerDomain: true, layerProtocol: true, layerCatalogue: true},
48	layerProtocol:  {layerDomain: true},
49	layerCatalogue: {layerDomain: true, layerProtocol: true},
50	layerWire:      {layerDomain: true, layerProtocol: true},
51	layerDomain:    {layerDomain: true},
52	layerPersist:   {layerDomain: true, layerPorts: true, layerProtocol: true, layerPkg: true},
53	layerSnapshot:  {layerDomain: true, layerPorts: true},
54	layerPlatform:  {},
55	layerLogging:   {layerPkg: true},
56	layerPkg:       {layerPkg: true},
57}
58
59func TestImportBoundaries(t *testing.T) {
60	violations, packages := inspectRepositoryDependencies(t)
61	if len(violations) != 0 {
62		t.Fatalf("invalid package dependencies:\n%s", strings.Join(violations, "\n"))
63	}
64	if len(packages) == 0 {
65		t.Fatal("package inventory is empty")
66	}
67}
68
69// externalDependencyOwners confines technology imports to their owning
70// layers. Use cases never touch protobuf runtime APIs, generated wire
71// envelopes, QUIC, stream framing, or concrete adapters; the wire package
72// never touches QUIC either (carriage lives in adapters).
73var externalDependencyOwners = map[string][]packageLayer{
74	"google.golang.org/protobuf/": {layerAdapter, layerApp, layerWire, layerTestSupport, layerScript},
75	"github.com/quic-go/quic-go":  {layerAdapter, layerApp},
76}
77
78func TestExternalDependencyBoundaries(t *testing.T) {
79	violations := inspectExternalDependencies(t)
80	if len(violations) != 0 {
81		t.Fatalf("invalid external dependencies:\n%s", strings.Join(violations, "\n"))
82	}
83}
84
85func TestImportBoundaryNegativeFixtures(t *testing.T) {
86	tests := []struct {
87		name, source, target string
88		testFile             bool
89		want                 bool
90	}{
91		{"usecase accepts semantic protocol", modulePath + "/internal/usecase/client", modulePath + "/internal/protocol", false, true},
92		{"usecase rejects wire", modulePath + "/internal/usecase/daemon", modulePath + "/internal/protocol/wire", false, false},
93		{"usecase rejects adapter", modulePath + "/internal/usecase/client", modulePath + "/internal/adapters/ipc", false, false},
94		{"domain rejects ports", modulePath + "/internal/domain", modulePath + "/internal/ports", false, false},
95		{"pkg rejects internal", modulePath + "/pkg/rawterm", modulePath + "/internal/domain", false, false},
96		{"snapshot adapter accepts codec", modulePath + "/internal/adapters/snapshot", modulePath + "/internal/snapshotcodec", false, true},
97		{"daemon accepts snapshot codec", modulePath + "/internal/usecase/daemon", modulePath + "/internal/snapshotcodec", false, true},
98		{"other adapter rejects snapshot codec", modulePath + "/internal/adapters/ipc", modulePath + "/internal/snapshotcodec", false, false},
99		{"snapshot codec rejects usecase", modulePath + "/internal/snapshotcodec", modulePath + "/internal/usecase/daemon", false, false},
100		{"snapshot codec rejects adapter", modulePath + "/internal/snapshotcodec", modulePath + "/internal/adapters/snapshot", false, false},
101		{"snapshot adapter rejects usecase", modulePath + "/internal/adapters/snapshot", modulePath + "/internal/usecase/daemon", false, false},
102		{"other adapter rejects usecase", modulePath + "/internal/adapters/ipc", modulePath + "/internal/usecase/client", false, false},
103		{"usecase test may use wire fixture", modulePath + "/internal/usecase/client", modulePath + "/internal/protocol/wire", true, true},
104		{"pkg test still rejects internal", modulePath + "/pkg/rawterm", modulePath + "/internal/domain", true, false},
105		// P1.1 broker ownership: broker consumes ports/protocol/domain
106		// (catalogue counts as protocol family) and no sibling use case.
107		{"broker accepts ports", modulePath + "/internal/usecase/broker", modulePath + "/internal/ports", false, true},
108		{"broker accepts protocol", modulePath + "/internal/usecase/broker", modulePath + "/internal/protocol", false, true},
109		{"broker accepts domain", modulePath + "/internal/usecase/broker", modulePath + "/internal/domain", false, true},
110		{"broker accepts catalogue", modulePath + "/internal/usecase/broker", modulePath + "/internal/protocol/catalogue", false, true},
111		{"broker accepts own subpackage", modulePath + "/internal/usecase/broker", modulePath + "/internal/usecase/broker/streams", false, true},
112		{"broker subpackage accepts broker root", modulePath + "/internal/usecase/broker/streams", modulePath + "/internal/usecase/broker", false, true},
113		{"broker rejects client", modulePath + "/internal/usecase/broker", modulePath + "/internal/usecase/client", false, false},
114		{"broker rejects daemon", modulePath + "/internal/usecase/broker", modulePath + "/internal/usecase/daemon", false, false},
115		{"broker rejects sibling usecase", modulePath + "/internal/usecase/broker", modulePath + "/internal/usecase/picker", false, false},
116		{"broker rejects adapter", modulePath + "/internal/usecase/broker", modulePath + "/internal/adapters/ipc", false, false},
117		{"broker rejects wire", modulePath + "/internal/usecase/broker", modulePath + "/internal/protocol/wire", false, false},
118		{"broker rejects app", modulePath + "/internal/usecase/broker", modulePath + "/internal/app", false, false},
119		{"broker rejects persist", modulePath + "/internal/usecase/broker", modulePath + "/internal/persist", false, false},
120		// P1.1 client/daemon must not own broker, each other, or remote discovery.
121		{"client rejects daemon", modulePath + "/internal/usecase/client", modulePath + "/internal/usecase/daemon", false, false},
122		{"client rejects broker", modulePath + "/internal/usecase/client", modulePath + "/internal/usecase/broker", false, false},
123		{"daemon rejects client", modulePath + "/internal/usecase/daemon", modulePath + "/internal/usecase/client", false, false},
124		{"daemon rejects broker", modulePath + "/internal/usecase/daemon", modulePath + "/internal/usecase/broker", false, false},
125		{"daemon rejects app", modulePath + "/internal/usecase/daemon", modulePath + "/internal/app", false, false},
126		// Shared color-profile policy is a leaf use case both sides may import.
127		{"client accepts colorprofile", modulePath + "/internal/usecase/client", modulePath + "/internal/usecase/colorprofile", false, true},
128		{"daemon accepts colorprofile", modulePath + "/internal/usecase/daemon", modulePath + "/internal/usecase/colorprofile", false, true},
129	}
130	for _, tt := range tests {
131		t.Run(tt.name, func(t *testing.T) {
132			got, err := dependencyAllowed(tt.source, tt.target, tt.testFile)
133			if err != nil {
134				t.Fatalf("dependencyAllowed: %v", err)
135			}
136			if got != tt.want {
137				t.Fatalf("dependencyAllowed(%q, %q, test=%t) = %t, want %t", tt.source, tt.target, tt.testFile, got, tt.want)
138			}
139		})
140	}
141}
142
143func inspectRepositoryDependencies(t *testing.T) ([]string, map[string]struct{}) {
144	t.Helper()
145	var violations []string
146	packages := make(map[string]struct{})
147	fset := token.NewFileSet()
148	err := filepath.WalkDir(".", func(path string, entry fs.DirEntry, walkErr error) error {
149		if walkErr != nil {
150			return walkErr
151		}
152		if entry.IsDir() {
153			name := entry.Name()
154			if name == ".git" || name == ".worktrees" || name == "vendor" {
155				return filepath.SkipDir
156			}
157			return nil
158		}
159		if !strings.HasSuffix(path, ".go") {
160			return nil
161		}
162		source := importPathForFile(path)
163		packages[source] = struct{}{}
164		if _, err := classifyPackage(source); err != nil {
165			violations = append(violations, path+": "+err.Error())
166			return nil
167		}
168		file, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
169		if err != nil {
170			return err
171		}
172		testFile := strings.HasSuffix(path, "_test.go")
173		for _, spec := range file.Imports {
174			target, err := strconv.Unquote(spec.Path.Value)
175			if err != nil || (target != modulePath && !strings.HasPrefix(target, modulePath+"/")) {
176				continue
177			}
178			allowed, err := dependencyAllowed(source, target, testFile)
179			if err != nil {
180				violations = append(violations, fmt.Sprintf("%s: %v", path, err))
181				continue
182			}
183			if !allowed {
184				violations = append(violations, fmt.Sprintf("%s: %s may not import %s", path, source, target))
185			}
186		}
187		return nil
188	})
189	if err != nil {
190		t.Fatalf("walking repository: %v", err)
191	}
192	sort.Strings(violations)
193	return violations, packages
194}
195
196func dependencyAllowed(source, target string, testFile bool) (bool, error) {
197	sourceLayer, err := classifyPackage(source)
198	if err != nil {
199		return false, err
200	}
201	targetLayer, err := classifyPackage(target)
202	if err != nil {
203		return false, err
204	}
205	if testFile {
206		return sourceLayer != layerPkg, nil
207	}
208	if sourceLayer == layerTestSupport {
209		return testSupportDependencyAllowed(source, targetLayer), nil
210	}
211	if packageImportDenied(source, target) {
212		return false, nil
213	}
214	return productionDependencies[sourceLayer][targetLayer], nil
215}
216
217// packageImportDenied encodes ADR 001 ownership at package granularity for
218// production files. Layer rules alone permit any usecase-to-usecase import;
219// other, and keep the broker free of every sibling use case. Test files stay
220// exempt so composition tests can wire adapters and orchestrators together.
221func packageImportDenied(source, target string) bool {
222	brokerPkg := modulePath + "/internal/usecase/broker"
223	clientPkg := modulePath + "/internal/usecase/client"
224	daemonPkg := modulePath + "/internal/usecase/daemon"
225	usecasePrefix := modulePath + "/internal/usecase/"
226	under := func(path, root string) bool {
227		return path == root || strings.HasPrefix(path, root+"/")
228	}
229	// The durable snapshot format is shared by the daemon and its one
230	// repository adapter; no other adapter may depend on it.
231	if target == modulePath+"/internal/snapshotcodec" && strings.HasPrefix(source, modulePath+"/internal/adapters/") {
232		return source != modulePath+"/internal/adapters/snapshot"
233	}
234	switch {
235	case under(source, brokerPkg):
236		return !under(target, brokerPkg) && strings.HasPrefix(target, usecasePrefix)
237	case under(source, clientPkg):
238		return under(target, daemonPkg) || under(target, brokerPkg)
239	case under(source, daemonPkg):
240		return under(target, clientPkg) || under(target, daemonPkg) || under(target, brokerPkg)
241	default:
242		return false
243	}
244}
245
246func testSupportDependencyAllowed(source string, target packageLayer) bool {
247	switch {
248	case source == modulePath+"/internal/ports/mocks":
249		return target == layerPorts || target == layerDomain || target == layerProtocol || target == layerCatalogue
250	case source == modulePath+"/internal/protocol/wire/mocks":
251		return target == layerWire
252	case strings.HasPrefix(source, modulePath+"/internal/testutil"):
253		return target == layerDomain || target == layerProtocol || target == layerWire
254	default:
255		return false
256	}
257}
258
259func classifyPackage(path string) (packageLayer, error) {
260	switch {
261	case path == modulePath:
262		return layerRoot, nil
263	case strings.HasPrefix(path, modulePath+"/cmd/"):
264		return layerCommand, nil
265	case strings.HasPrefix(path, modulePath+"/scripts/"):
266		return layerScript, nil
267	case path == modulePath+"/internal/app":
268		return layerApp, nil
269	case strings.HasPrefix(path, modulePath+"/internal/adapters/"):
270		return layerAdapter, nil
271	case path == modulePath+"/internal/ports/mocks", path == modulePath+"/internal/protocol/wire/mocks", strings.HasPrefix(path, modulePath+"/internal/testutil"):
272		return layerTestSupport, nil
273	case path == modulePath+"/internal/ports":
274		return layerPorts, nil
275	case path == modulePath+"/internal/protocol/wire":
276		return layerWire, nil
277	case path == modulePath+"/internal/protocol/catalogue":
278		return layerCatalogue, nil
279	case path == modulePath+"/internal/protocol":
280		return layerProtocol, nil
281	case path == modulePath+"/internal/domain" || strings.HasPrefix(path, modulePath+"/internal/domain/"):
282		return layerDomain, nil
283	case path == modulePath+"/internal/usecase" || strings.HasPrefix(path, modulePath+"/internal/usecase/"):
284		return layerUsecase, nil
285	case path == modulePath+"/internal/persist":
286		return layerPersist, nil
287	case path == modulePath+"/internal/snapshotcodec":
288		return layerSnapshot, nil
289	case path == modulePath+"/internal/platform":
290		return layerPlatform, nil
291	case path == modulePath+"/internal/logging":
292		return layerLogging, nil
293	case path == modulePath+"/pkg" || strings.HasPrefix(path, modulePath+"/pkg/"):
294		return layerPkg, nil
295	default:
296		return "", fmt.Errorf("unclassified package %q", path)
297	}
298}
299
300func importPathForFile(path string) string {
301	dir := filepath.ToSlash(filepath.Dir(path))
302	if dir == "." {
303		return modulePath
304	}
305	return modulePath + "/" + strings.TrimPrefix(dir, "./")
306}
307
308func inspectExternalDependencies(t *testing.T) []string {
309	t.Helper()
310	var violations []string
311	fset := token.NewFileSet()
312	err := filepath.WalkDir(".", func(path string, entry fs.DirEntry, walkErr error) error {
313		if walkErr != nil {
314			return walkErr
315		}
316		if entry.IsDir() {
317			name := entry.Name()
318			if name == ".git" || name == ".worktrees" || name == "vendor" {
319				return filepath.SkipDir
320			}
321			return nil
322		}
323		if !strings.HasSuffix(path, ".go") {
324			return nil
325		}
326		source := importPathForFile(path)
327		sourceLayer, err := classifyPackage(source)
328		if err != nil {
329			violations = append(violations, path+": "+err.Error())
330			return nil
331		}
332		// Test files may use any external dependency except inside pkg,
333		// mirroring the internal test-import policy.
334		if strings.HasSuffix(path, "_test.go") && sourceLayer != layerPkg {
335			return nil
336		}
337		file, err := parser.ParseFile(fset, path, nil, parser.ImportsOnly)
338		if err != nil {
339			return err
340		}
341		for _, spec := range file.Imports {
342			target, err := strconv.Unquote(spec.Path.Value)
343			if err != nil {
344				continue
345			}
346			for prefix, owners := range externalDependencyOwners {
347				if !strings.HasPrefix(target, prefix) {
348					continue
349				}
350				allowed := false
351				for _, owner := range owners {
352					if sourceLayer == owner {
353						allowed = true
354						break
355					}
356				}
357				if !allowed {
358					violations = append(violations, fmt.Sprintf("%s: %s may not import %s", path, source, target))
359				}
360			}
361		}
362		return nil
363	})
364	if err != nil {
365		t.Fatalf("walking repository: %v", err)
366	}
367	sort.Strings(violations)
368	return violations
369}
370
371// TestProductionDaemonBindingComposition pins the daemon authority composition
372// at the source level: the daemon's process binding may only be built by the one
373// production site that provisions the daemon's closed policy set, and the
374// single-policy shorthand must not reappear outside test fixtures.
375//
376// The multi-policy constructor exists because a daemon serves one exact policy
377// per accepted carriage shape (its own local Unix daemonmux policy, plus each
378// provisioned remote transport policy). A production composition that used the
379// single-policy shorthand would publish an authority that refuses every remote
380// carriage, so the composition is pinned to the multi-policy call, and the
381// shorthand stays a fixtures-only convenience.
382func TestProductionDaemonBindingComposition(t *testing.T) {
383	const runFile = "internal/app/daemon_run.go"
384
385	var (
386		bindingSites []string
387		runBindings  int
388	)
389	fset := token.NewFileSet()
390	err := filepath.WalkDir(".", func(path string, entry fs.DirEntry, walkErr error) error {
391		if walkErr != nil {
392			return walkErr
393		}
394		name := entry.Name()
395		if entry.IsDir() {
396			if name == ".git" || name == ".worktrees" || name == "vendor" {
397				return filepath.SkipDir
398			}
399			return nil
400		}
401		if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
402			return nil
403		}
404		file, err := parser.ParseFile(fset, path, nil, 0)
405		if err != nil {
406			return err
407		}
408		slashed := filepath.ToSlash(path)
409		for _, decl := range file.Decls {
410			fn, ok := decl.(*ast.FuncDecl)
411			if !ok || fn.Body == nil {
412				continue
413			}
414			ast.Inspect(fn.Body, func(node ast.Node) bool {
415				call, ok := node.(*ast.CallExpr)
416				if !ok {
417					return true
418				}
419				selector, ok := call.Fun.(*ast.SelectorExpr)
420				if !ok {
421					return true
422				}
423				// Only the adapter's own constructors count: a method spelled
424				// the same way elsewhere is unrelated.
425				ident, ok := selector.X.(*ast.Ident)
426				if !ok || ident.Name != "daemonmux" {
427					return true
428				}
429				switch selector.Sel.Name {
430				case "NewServerBinding":
431					bindingSites = append(bindingSites, fmt.Sprintf("%s:%d: %s must build the closed policy set with NewServerBindings", slashed, fset.Position(call.Pos()).Line, selector.Sel.Name))
432				case "NewServerBindings":
433					if slashed == runFile {
434						runBindings++
435					}
436				}
437				return true
438			})
439		}
440		return nil
441	})
442	if err != nil {
443		t.Fatalf("walking repository: %v", err)
444	}
445	if len(bindingSites) != 0 {
446		t.Fatalf("production code uses the single-policy daemon binding shorthand:\n%s", strings.Join(bindingSites, "\n"))
447	}
448	if runBindings == 0 {
449		t.Fatalf("%s must compose the daemon authority with daemonmux.NewServerBindings", runFile)
450	}
451}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 12

Tags 11

↑↓ moveenter openesc close