《分布式系统架构原理和实践指南》1.3 让骨架跑起来:Go 模块与 lab 首条断言

Go 模块与骨架首跑:go.mod 零依赖、目录注册表建表→主键→键空间约定,dslab 首条断言 boot:catalog-create-accounts 以 go run ./cmd/runall 的 TOTAL 78 为验证边界(lab 实测)。

让骨架从纸面变成能跑的模块

前面两节讲了动机与拼图,这一节只有一件事:让骨架在终端里跑起来。跑法的验收标准很朴素——三条命令全部通过,一条输出被断言钉住,最后的权威输出是 TOTAL: 78 passed, 0 failed。如果这三条命令今天能跑通,后面 14 章就都有了落脚点;跑不通,问题也只圈在 boot 一个包内。

对本节的读者,这三条命令不该是「照着抄」,而应是「读懂了再跑」——跑之前清楚每一步在验证什么,跑之后能解释输出里的每一行。第 1 章的产物是一张目录注册表 Catalog:建表、读主键、拒绝非法注册;它的四条断言就是这张表能否成为「键空间约定的事实来源」的最低证明。

lab 的代码聚在私有目录 private/labs/dsarch-txdb-lab/。它的内部布局如下,第 1 章只占其中一个包:

private/labs/dsarch-txdb-lab/
├── go.mod
├── README.md
├── cmd/
│   └── runall/          # 全卷断言权威出口
└── internal/
    ├── dslab/           # Check 类型与 RunAll 收口
    └── platform/
        ├── engine/      # 汇总 15 包断言
        ├── boot/        # 本节的目录注册表
        │   ├── catalog.go
        │   └── checks_test.go
        ├── store/       # 第 2 章起,逐章补齐
        └── …

目录本身就在讲一个约束:boot 之下只放机制代码,cmd/ 之下才是入口。任何断言都能在包级被 go test 驱动,任何演示都能从 cmd/ 出发——关注点从第 1 章就分开。

从空目录到绿测试的五步

无论起点是仓库里已有的 private/labs/dsarch-txdb-lab/,还是你本地新建的一个空目录,让骨架跑起来都只有五步:

  1. 建 go.mod,声明 module dsarchtxdblab 与 go 1.26;
  2. 建 internal/platform/boot/,写入 catalog.go 与 checks_test.go;
  3. 跑 go test ./internal/platform/boot/ -count=1,看到绿色;
  4. 把 boot.Checks() 收进 engine,跑 go run ./cmd/runall;
  5. 看到收敛的 TOTAL 行与 ALL GREEN。

前四步只碰骨架自己,第五步才与全卷接合。这样设计的好处是:第 1 章的学习闭环最短,任何一步出错都能在几秒内定位。五步里最容易漏掉的是第二步的一部分:Checks() 里的断言名字。名字是与读者沟通的接口,boot:catalog-create-accounts 这种「包:属性」命名会贯穿 15 章——读到第 9 章的 shard:route-... 时,立刻能猜到它验证的是哪一类属性。

go.mod:零依赖的起点

先看模块声明的完整内容——它短到不需要任何说明,但也重要到决定全书的技术底座:

// file: go.mod
module dsarchtxdblab

go 1.26

dsarchtxdblab 是模块名,go 1.26 声明了语言版本与最小标准库面。整卷没有 require 段:没有第三方中间件,没有民间工具库。这意味着任何机制包的 go test 都不会因为「网络问题装不上依赖」而失败,也不会有 go.sum 需要维护模块校验和——这是从零建构能跑起来的第一个前提。

模块名同时也是 import 路径的根:代码里 internal/platform/boot 全写为 dsarchtxdblab/internal/platform/boot。模块名一旦改变,全部 import 都要跟着改;把它固定下来,是为后面 14 章免掉一次全局重构。boot 包引用 dsarchtxdblab/internal/dslab,这条引用让第一章的断言与全卷的断言口径从第一行代码起就是同一套。

目录注册表:catalog.go 全貌

第 1 章的包叫 boot,它唯一的机制文件是 catalog.go。三行验证头写死了「构造产物与验证命令」的对应关系,之后每一章都沿用这条纪律:

// file: internal/platform/boot/catalog.go
// tier: L1
// verify: go test ./internal/platform/boot/ -count=1
package boot

import (
	"fmt"

	"dsarchtxdblab/internal/dslab"
)

// Table is one registered relation.
type Table struct {
	Name string
	Cols []string
	PK   string
}

// Catalog is the single source of truth for table keyspaces.
type Catalog struct {
	tables map[string]Table
}

func NewCatalog() *Catalog { return &Catalog{tables: map[string]Table{}} }

// CreateTable registers a table; a primary key must name one of its columns.
func (c *Catalog) CreateTable(name string, cols []string, pk string) error {
	found := false
	for _, col := range cols {
		if col == pk {
			found = true
		}
	}
	if !found {
		return fmt.Errorf("pk %q not in columns %v", pk, cols)
	}
	if _, dup := c.tables[name]; dup {
		return fmt.Errorf("table %q already exists", name)
	}
	c.tables[name] = Table{Name: name, Cols: cols, PK: pk}
	return nil
}

// Table returns the registered table.
func (c *Catalog) Table(name string) (Table, bool) {
	t, ok := c.tables[name]
	return t, ok
}

// PrimaryKey answers the primary-key column of a table, if registered.
func (c *Catalog) PrimaryKey(name string) (string, bool) {
	t, ok := c.tables[name]
	if !ok {
		return "", false
	}
	return t.PK, true
}

// Checks enumerates chapter-1 assertions.
func Checks() []dslab.Check {
	return []dslab.Check{
		{Name: "boot:catalog-create-accounts", Fn: func() error {
			c := NewCatalog()
			if err := c.CreateTable("accounts", []string{"id", "balance"}, "id"); err != nil {
				return err
			}
			if got, ok := c.PrimaryKey("accounts"); !ok || got != "id" {
				return fmt.Errorf("pk=%q ok=%v want id true", got, ok)
			}
			return nil
		}},
		{Name: "boot:catalog-pk-must-be-column", Fn: func() error {
			c := NewCatalog()
			if err := c.CreateTable("orders", []string{"order_id", "user_id"}, "missing"); err == nil {
				return fmt.Errorf("pk not in columns should be rejected")
			}
			return nil
		}},
		{Name: "boot:catalog-reject-duplicate", Fn: func() error {
			c := NewCatalog()
			_ = c.CreateTable("accounts", []string{"id", "balance"}, "id")
			if err := c.CreateTable("accounts", []string{"id", "balance"}, "id"); err == nil {
				return fmt.Errorf("duplicate table should be rejected")
			}
			return nil
		}},
		{Name: "boot:unknown-table-misses", Fn: func() error {
			c := NewCatalog()
			if _, ok := c.Table("nope"); ok {
				return fmt.Errorf("unknown table must not resolve")
			}
			return nil
		}},
	}
}

这段代码每一处都值得停下来读一遍。Catalog 只持有一个字段 tables map[string]Table——没有锁、没有索引、没有持久化,第 1 章刻意保持最小;并发与磁盘要等到第 3、2 章才各自引入。CreateTable 的两条错误路径顺序有讲究:先验主键属不属于列,再验重复注册。先挡「拼错键空间」,再挡「覆盖键空间」,两条各自独立、都不产生副作用。

Checks() 的四条断言里,boot:catalog-create-accounts 就是全卷的「第一条断言」:建出 accounts 表(列 id、balance,主键 id),再读回主键。它把「目录确实记住了键空间约定」这件事从「我写了」变成「能跑通」。另外三条分别钉住非法主键、重复注册与未知表——它们共同保证目录在任何合法使用下都不会给出错误的主键回答。

首条断言的验证边界

让骨架「跑起来」的第一条断言不是打印一句 “hello”,而是把正确性写进测试。boot 包把四条断言交给标准的 go test 驱动:

// file: internal/platform/boot/checks_test.go
// tier: L1
// verify: go test ./internal/platform/boot/ -count=1
package boot

import "testing"

// TestChecks runs every assertion in this mechanism package through the
// standard Go test driver, so `go test ./internal/platform/boot/` and the
// dslab harness agree on the same expected properties.
func TestChecks(t *testing.T) {
	for _, c := range Checks() {
		if err := c.Fn(); err != nil {
			t.Fatalf("%s: %v", c.Name, err)
		}
	}
}

四条必须写进测试的边界:

  • boot:catalog-create-accounts:建表并读回主键 id,验证「正路走得通」;
  • boot:catalog-pk-must-be-column:主键 missing 不在列里时拒绝,验证「错键空间进不了目录」;
  • boot:catalog-reject-duplicate:同名二次注册拒绝,验证「目录不可静默改写」;
  • boot:unknown-table-misses:查 nope 返回 ok=false,验证「未知表可区分」。

这四条边界合起来回答一个问题:目录在任何合法路径下都不会给出错误的主键。错误路径返回的错误是 fmt.Errorf 构造的普通字符串,第 9 章看到 shard:... 的断言风格时,会说「这套命名我认识」。

dslab:断言 harness 如何打印 TOTAL

go test 只验证当前包,全卷需要一条权威出口把 15 个包拼起来。dslab 包定义了极简的断言类型与执行方法,第一章的断言正是从这里走向 TOTAL 的第一块砖:

// Package dslab provides the assertion harness for the from-scratch
// distributed-transaction-database lab. Each mechanism package exposes Checks()
// and the engine package aggregates them; RunAll prints the single
// authoritative TOTAL line used across the book.
package dslab

import "fmt"

// Check is one named assertion.
type Check struct {
	Name string
	Fn   func() error
}

// RunAll executes every check and prints the canonical TOTAL line.
// It returns the number of failures.
func RunAll(checks []Check) int {
	passed, failed := 0, 0
	for _, c := range checks {
		if err := c.Fn(); err != nil {
			fmt.Printf("FAIL %s: %v\n", c.Name, err)
			failed++
		} else {
			passed++
		}
	}
	fmt.Printf("TOTAL: %d passed, %d failed\n", passed, failed)
	if failed == 0 {
		fmt.Println("ALL GREEN")
	}
	return failed
}

这条代码就是全卷验证的「宪法」:每条断言有名字、有可执行函数;RunAll 逐个执行并汇总,失败打印 FAIL 行,全绿打印 ALL GREEN。注意 RunAll 不做并行、不懂重试,它只要一件事——把 78 条断言一个字符不差地逐个跑完。读取失败名 boot:... 时,章与包一目了然。

engine 与 runall:把 4 收进 78

boot.Checks() 只有四条,它们要被收进总账。engine 包按章序把每个包的 Checks() append 成一张列表,承诺「顺序即章序」——boot 永远在列表第一位,e2e 永远在最后一位:

// Checks returns all checks in chapter order.
func Checks() []dslab.Check {
	var out []dslab.Check
	out = append(out, boot.Checks()...)    // ch 1 骨架与注册表
	out = append(out, store.Checks()...)   // ch 2 存储底座
	// …
	out = append(out, e2e.Checks()...)     // ch 15 端到端收口
	return out
}

cmd/runall/main.go 再把 engine 的列表交给 dslab:

// Command runall is the authoritative harness for the transaction-database
// lab: it runs every assertion of the book and prints the canonical TOTAL line.
//
//	go run ./cmd/runall
package main

import (
	"fmt"
	"os"

	"dsarchtxdblab/internal/dslab"
	"dsarchtxdblab/internal/platform/engine"
)

func main() {
	failed := dslab.RunAll(engine.Checks())
	if failed != 0 {
		fmt.Printf("%d checks failed\n", failed)
		os.Exit(1)
	}
}

一切收口到 TOTAL: 78 passed, 0 failed。这条输出的纪律意义在于:全卷统一引用 78,是逐条跑出来的数,由 engine 汇总、runall 打印,不需任何额外进程或网络。每一章新增的断言都先进入自己的 Checks(),再被 engine 收编;第 1 章时它还是 4,全部完成后是 78。

验证:三条命令把 4 与 78 跑出来

第 1 章的验收就三条命令。第一条只验证骨架包:

$ go test ./internal/platform/boot/ -count=1
ok      dsarchtxdblab/internal/platform/boot  (cached)

第一行输出如果带着 (cached),先别急着排除问题:-count=1 只保证本次不读旧缓存,若仍看到缓存字样,多半是把命令跑在了别的模块目录里。遇到时先 cd 到 private/labs/dsarch-txdb-lab/ 再执行。

第二条验证全卷。engine 包按章序把 15 个包的 Checks() 拼成一张列表,权威出口输出(Go 1.26 本机实测):

$ go run ./cmd/runall
…
TOTAL: 78 passed, 0 failed
ALL GREEN

第三条是「前序没被改坏」的巡检:go test ./...,把模块内 15 个包连同 engine 一起过一遍。若某一步失败,按五步法倒着排查:先 go test ./internal/platform/boot/ -count=1,再 go test ./...,最后才是 go run ./cmd/runall——三条命令像探针一样把问题圈在最小范围内。

常见错误与边界

把骨架跑起来不难,但有三处边界值得提前说明:

  • 不要为了一条断言去搬中间件。boot 不依赖任何第三方包;若某章测试因为「装不上依赖」失败,先怀疑环境或模块缓存,而不是去加 require;
  • 不要手改 Checks() 里的表名与主键断言的数值。accounts、id、balance 这些名字贯穿第 2 章键空间与第 11 章 SQL 映射,改掉会静默破坏后续章节引用的前提;
  • 不要跳过 -count=1。不带它,go test 会命中缓存,「每次真实重跑」的承诺就被绕过了。

边界之外还有一条不变量没有写进测试,因为它由 Go 语义保证:Catalog 的 map 读写在第 1 章不并发,所操的键只在 CreateTable 内部写入。这个约束在读到第 3 章加锁时会重新讨论,现在先接受它的存在。

小结

骨架跑起来的标准很简单:go.mod 零依赖,目录注册表四条断言钉住「建表→主键→键空间约定」,go test 验证单包、go run ./cmd/runall 验证全卷。以此为界,第 1 章完成——竖切的地基正式打桩。从下一章开始,这张目录要长出第一层存储:store 包的键空间约定把 table:pk 前缀变成真正的有序键值。复制与一致性的机制原理仍留在 bd 卷七、卷八,本卷只负责把它们一个个亲手接上。

阅读导航:上一节:1.2 系统轮廓:一条 SQL 的全路径 · 下一节:2.1 键空间:table:pk 与有序键值 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《分布式系统架构原理和实践指南》9.3 降级与恢复:fallback 与半开探测
  2. 《分布式系统架构原理和实践指南》9.2 舱壁隔离:并发池与信号量
  3. 《分布式系统架构原理和实践指南》9.1 熔断三态:闭合、打开与半开