docs: annotate Foundry source and deployment lifecycle in Chinese [skip ci]

This commit is contained in:
2026-11-16 17:52:11 +08:00
parent 30829eeb86
commit 1090591503
123 changed files with 1279 additions and 3 deletions
+29
View File
@@ -1,3 +1,5 @@
// 平台综合数据库回归:需要 PLATFORM_TEST_DATABASE_URL 指向已迁移的隔离测试库,缺省会跳过。
// 使用随机项目和真实 HTTP handler 覆盖权限、版本、子图事务与资源生命周期,不连接真实 OAuth 或邮件服务。
package platform
import (
@@ -27,6 +29,8 @@ import (
_ "github.com/jackc/pgx/v5/stdlib"
)
// TestOnboardingAndSharing 是跨模块流程测试,后续画布/资产/邮箱检查复用最初创建的三个账户。
// tokens[0] 为所有者,tokens[1] 经邀请成为 viewer,tokens[2] 只按阶段授予局部素材权限。
func TestOnboardingAndSharing(t *testing.T) {
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
if dsn == "" {
@@ -60,6 +64,7 @@ func TestOnboardingAndSharing(t *testing.T) {
}
tokens = append(tokens, token)
}
// 按引用关系先删除资产绑定、事务和子图,再删除工作区/账户,避免回归数据残留。
defer func() {
_, _ = db.ExecContext(ctx, "DELETE FROM canvas_asset_bindings WHERE project=$1", project)
_, _ = db.ExecContext(ctx, "DELETE FROM canvas_assets WHERE project=$1", project)
@@ -79,6 +84,7 @@ func TestOnboardingAndSharing(t *testing.T) {
Register(mux, db, callbacks, "https://api.example.com", map[string]OnboardingConfig{
project: {RequireWorkspace: true, Questions: []Question{{Key: "purpose", Required: true}}},
})
// call 在内存 recorder 上走真实路由;可选参数依次代表 If-Match、Accept 和幂等键。
call := func(method, path, token string, body any, status int, versions ...string) response {
t.Helper()
encoded, err := json.Marshal(body)
@@ -111,6 +117,7 @@ func TestOnboardingAndSharing(t *testing.T) {
}
return out
}
// 首段验证引导重试不重复建工作区,以及分享次数、重复兑换、owner 不可降级和撤销效果。
base := "/projects/" + project
call("GET", base+"/workspaces", "", nil, 401)
call("POST", base+"/onboarding", tokens[0], response{"answers": response{}}, 400)
@@ -145,6 +152,7 @@ func TestOnboardingAndSharing(t *testing.T) {
contentShare := call("POST", workspacePath+"/shares", tokens[0], response{"role": "editor", "material_id": material}, 201)
call("POST", base+"/shares/redeem", tokens[2], response{"token": contentShare["token"]}, 200)
call("GET", workspacePath, tokens[2], nil, 404)
// 素材局部授权不授予工作区可见性;随后验证 viewer/editor 区别与 If-Match 防止旧版本覆盖。
articleContent := response{"schema_version": 1, "article": response{"sections": []any{response{
"id": "chapter-1", "title": "Chapter", "description": "Chapter summary", "paragraphs": []any{response{"id": "p1", "text": "Paragraph", "description": "Paragraph summary"}},
}}}}
@@ -173,6 +181,7 @@ func TestOnboardingAndSharing(t *testing.T) {
board := call("POST", workspacePath+"/materials", tokens[0], response{"kind": "board", "title": "Board", "content": response{}}, 201)
boardPath := workspacePath + "/materials/" + board["id"].(string)
// 画布快照版本与素材元数据版本相互独立,保存/改名各自只推进对应版本。
canvasPath := boardPath + "/canvas"
empty := call("GET", canvasPath, tokens[0], nil, 200)
if empty["version"] != float64(1) {
@@ -221,6 +230,7 @@ func TestOnboardingAndSharing(t *testing.T) {
// Restore the material version expected by the pre-existing layout checks below.
// Exercise two independent HTTP transactions against the same expected version.
// 同一旧版本的两个并发保存必须一成一败,不能都成功或出现部分持久化。
encodedSnapshot, _ := json.Marshal(snapshot)
statuses := make(chan int, 2)
start := make(chan struct{})
@@ -253,6 +263,7 @@ func TestOnboardingAndSharing(t *testing.T) {
}
// Frames round-trip through PostgreSQL with all label modes and explicit memberships.
// 三种框标签模式逐次落库并回读;失效成员引用必须拒绝且不推进版本。
for index, mode := range []string{"hidden", "fixed", "scaled"} {
version := strconv.Itoa(4 + index)
raw := strings.Replace(frameFixture, `"labelMode":"fixed"`, `"labelMode":"`+mode+`"`, 1)
@@ -304,6 +315,7 @@ func TestOnboardingAndSharing(t *testing.T) {
// Subgraph creation is atomic and idempotent, and cannot be undone by
// a stale or legacy whole-document save.
// 子图创建将文档、子素材、关系和事务回执原子保存;同键重放只返回原结果,不再递增版本。
subBoard := call("POST", workspacePath+"/materials", tokens[0], response{"kind": "board", "title": "Subgraphs", "content": response{}}, 201)
subPath := workspacePath + "/materials/" + subBoard["id"].(string) + "/canvas"
accept := "application/vnd.foundry.canvas+json;version=2"
@@ -367,6 +379,7 @@ func TestOnboardingAndSharing(t *testing.T) {
call("POST", dissolveUndoPath, tokens[0], response{"expected_versions": map[string]int64{subBoard["id"].(string): 3, childID: 2}}, 200, "", accept, "88888888-8888-4888-8888-888888888888")
call("GET", childPath, tokens[0], nil, 200, "", accept)
// 旧框迁移先 dry-run 生成计划,陈旧计划不得留下孤儿素材;执行与撤销都验证幂等回执。
migrationBoard := call("POST", workspacePath+"/materials", tokens[0], response{"kind": "board", "title": "Legacy migration", "content": response{}}, 201)
migrationPath := workspacePath + "/materials/" + migrationBoard["id"].(string) + "/canvas"
call("PATCH", migrationPath, tokens[0], response{"document": json.RawMessage(legacyMigrationFixture)}, 200, `"1"`)
@@ -423,6 +436,7 @@ func TestOnboardingAndSharing(t *testing.T) {
}
parentID := migrationBoard["id"].(string)
memberPath := migrationPath + "/subgraphs/f/members"
// 多画布移动携带完整预期版本及来源局部坐标,要求节点所有权、几何位置和撤销一起生效。
moveCommand := response{"source_board_id": membersSource, "target_board_id": membersTarget, "node_ids": []string{"a"}, "positions": map[string]memberDropPosition{"a": {X: 40, Y: 50}}, "expected_versions": map[string]int64{parentID: 5, membersSource: 1, membersTarget: 1}}
call("POST", memberPath, tokens[0], response{"source_board_id": membersSource, "target_board_id": membersTarget, "node_ids": []string{"a"}, "positions": response{"wrong": response{"x": 1, "y": 2}}, "expected_versions": map[string]int64{parentID: 5, membersSource: 1, membersTarget: 1}}, 400, "", accept, "eeeeeeee-1111-4111-8111-111111111111")
movedMembers := call("POST", memberPath, tokens[0], moveCommand, 200, "", accept, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")
@@ -448,6 +462,7 @@ func TestOnboardingAndSharing(t *testing.T) {
parentMove := call("POST", memberPath, tokens[0], response{"source_board_id": parentID, "target_board_id": membersSource, "node_ids": []string{"outside"}, "expected_versions": map[string]int64{parentID: 7, membersSource: 3}}, 200, "", accept, "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee")
call("POST", migrationPath+"/transactions/"+parentMove["transaction_id"].(string)+"/undo", tokens[0], response{"expected_versions": map[string]int64{parentID: 8, membersSource: 4}}, 200, "", accept, "ffffffff-ffff-4fff-8fff-ffffffffffff")
innerCreated := call("POST", sourceCanvasPath+"/subgraphs", tokens[0], response{"frame": response{"id": "inner-frame", "title": "Inner", "position": response{"x": 20, "y": 40}, "width": 400, "height": 300, "labelMode": "fixed"}}, 201, `"5"`, accept, "10000000-0000-4000-8000-000000000001")
// 移动包含子图的框必须重挂原子图关系,而非复制孩子;撤销要恢复原父级。
innerID := innerCreated["child_board"].(map[string]any)["id"].(string)
nestedMove := call("POST", memberPath, tokens[0], response{"source_board_id": membersSource, "target_board_id": membersTarget, "node_ids": []string{"inner-frame"}, "expected_versions": map[string]int64{parentID: 9, membersSource: 6, membersTarget: 3, innerID: 1}}, 200, "", accept, "10000000-0000-4000-8000-000000000002")
var nestedParent string
@@ -461,6 +476,7 @@ func TestOnboardingAndSharing(t *testing.T) {
// Moving an externally exposed node inside a nested frame must repair the
// ancestor boundary atomically and preserve its port/edge identities.
// 嵌套移动和解散需同时修复祖先端口,保留逻辑端点身份;漏报祖先版本应返回 428。
innerMemberPath := sourceCanvasPath + "/subgraphs/inner-frame/members"
nestedMemberCommand := response{"source_board_id": membersSource, "target_board_id": innerID, "node_ids": []string{"b"}, "expected_versions": map[string]int64{parentID: 11, membersSource: 8, innerID: 3}}
nestedMemberMove := call("POST", innerMemberPath, tokens[0], nestedMemberCommand, 200, "", accept, "30000000-0000-4000-8000-000000000001")
@@ -495,6 +511,7 @@ func TestOnboardingAndSharing(t *testing.T) {
if err := png.Encode(&assetPNG, image.NewRGBA(image.Rect(0, 0, 3, 2))); err != nil {
t.Fatal(err)
}
// 上传使用故意错误的文件扩展名验证真实 MIME 嗅探,并可指定客户端预分配资源 ID。
upload := func(encoded []byte, key string, status int, resourceIDs ...string) response {
t.Helper()
var body bytes.Buffer
@@ -538,6 +555,7 @@ func TestOnboardingAndSharing(t *testing.T) {
if !modelEqual(managed, repeated) {
t.Fatal("resource retry changed receipt")
}
// 模拟响应丢失后查询回执:已应用可恢复原资产,未知请求不能被误报为已确定零写入。
lookup := call("GET", workspacePath+"/assets/operations/"+resourceKey, tokens[0], nil, 200)
if lookup["status"] != "applied" || !modelEqual(lookup["asset"], managed["asset"]) {
t.Fatal("lost upload acknowledgment cannot be recovered")
@@ -613,6 +631,7 @@ func TestOnboardingAndSharing(t *testing.T) {
}
// Neither a snapshot nor an asset response may keep the workspace locked
// while a slow downstream consumer is accepting its body.
// 在真正写出响应体时另开事务 NOWAIT 抢工作区锁,防止慢消费者拖长数据库锁生命周期。
for _, path := range []string{canvasPath, workspacePath + "/assets/" + uploaded["id"].(string), metadataPath} {
var probeErr error
writer := &readLockProbe{ResponseRecorder: httptest.NewRecorder(), probe: func() {
@@ -634,6 +653,7 @@ func TestOnboardingAndSharing(t *testing.T) {
}
// A slow multipart body must not hold the workspace lock either.
func() {
// 管道先交付 multipart 头再暂停正文,探测接收慢上传期间是否错误持有工作区锁。
reader, pipe := io.Pipe()
defer reader.Close()
defer pipe.Close()
@@ -688,6 +708,7 @@ func TestOnboardingAndSharing(t *testing.T) {
download(tokens[0], 200)
download(tokens[1], 404)
download(tokens[2], 404)
// 资产由上传者可读,写入可访问画布并绑定后才允许该画布协作者读取。
assetBoard := call("POST", workspacePath+"/materials", tokens[0], response{"kind": "board", "title": "Assets", "content": response{}}, 201)
assetDoc := response{"schema_version": 2, "nodes": []any{response{"id": "asset-node", "type": "plainImage", "position": response{"x": 0, "y": 0}, "data": response{"kind": "plain-image", "title": "Image", "text": "", "src": uploaded["url"], "assetId": uploaded["id"]}}}, "edges": []any{}, "viewport": response{"x": 0, "y": 0, "zoom": 1}}
call("PATCH", workspacePath+"/materials/"+assetBoard["id"].(string)+"/canvas", tokens[0], response{"document": assetDoc}, 200, `"1"`, accept)
@@ -709,6 +730,7 @@ func TestOnboardingAndSharing(t *testing.T) {
// A warm metadata/original cache is not a future permission grant. An external
// collaborator can read through a source board grant, but a new canonical
// target write must recheck asset readability after that grant is revoked.
// 先暖元数据/原图缓存再撤销来源权限,确保新目标写入实时检查授权而非信任缓存命中。
sourceGrantPath := workspacePath + "/materials/" + assetBoard["id"].(string) + "/grants"
call("POST", sourceGrantPath, tokens[0], response{"account_id": accounts[2], "role": "viewer"}, 204)
call("GET", metadataPath, tokens[2], nil, 200)
@@ -752,6 +774,7 @@ func TestOnboardingAndSharing(t *testing.T) {
if !modelEqual(denied, replayedDenial) {
t.Fatal("permission restoration changed a terminal receipt")
}
// 恢复权限后必须新建请求才可成功;目标获得独立绑定后,撤销来源不应破坏目标读权限。
acceptedID := modelTestID(9204)
call("POST", targetPath+"/canvas/model/operations", tokens[2], adoptionRequest(acceptedID, modelTestID(9205)), 200, "", accept, acceptedID)
call("DELETE", sourceGrantPath+"/"+accounts[2], tokens[0], nil, 204)
@@ -765,6 +788,7 @@ func TestOnboardingAndSharing(t *testing.T) {
download(tokens[1], 200)
upload([]byte("not an image"), "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", 400)
// 超出节点预算要求确定拒绝且版本不变;UUID 幂等键大小写应归一到同一次操作。
limitBoard := call("POST", workspacePath+"/materials", tokens[0], response{"kind": "board", "title": "Limits", "content": response{}}, 201)
limitPath := workspacePath + "/materials/" + limitBoard["id"].(string) + "/canvas"
oversizedNodes := []any{}
@@ -787,6 +811,7 @@ func TestOnboardingAndSharing(t *testing.T) {
code int
body []byte
}
// 四条并发同键请求应收敛到同一 transaction 和一个子图,而不是各创建一次。
results := make(chan concurrentResult, 4)
startConcurrent := make(chan struct{})
encodedFrame, _ := json.Marshal(caseFrame)
@@ -821,6 +846,7 @@ func TestOnboardingAndSharing(t *testing.T) {
if err := db.QueryRowContext(ctx, `SELECT count(*) FROM canvas_subgraphs WHERE project=$1 AND parent_board_id=$2`, project, concurrentBoard["id"]).Scan(&concurrentChildren); err != nil || concurrentChildren != 1 {
t.Fatalf("concurrent retry duplicated children: %d %v", concurrentChildren, err)
}
// 让父文档接近字节预算,使创建子图在最终父文档校验失败,验证孩子和父版本共同回滚。
rollbackBoard := call("POST", workspacePath+"/materials", tokens[0], response{"kind": "board", "title": "Rollback", "content": response{}}, 201)
rollbackPath := workspacePath + "/materials/" + rollbackBoard["id"].(string) + "/canvas"
nearLimit := []any{}
@@ -851,6 +877,7 @@ func TestOnboardingAndSharing(t *testing.T) {
t.Fatal("failed create changed parent version")
}
// 最后用 outbox 内链接完成邮箱验证:未验证不能登录,验证码不可重放,注销后的会话不可访问资料。
email := "fixture@example.invalid"
password := "a-long-fixture-password"
call("POST", base+"/auth/register", "", response{"email": email, "password": password}, 202)
@@ -882,11 +909,13 @@ func TestOnboardingAndSharing(t *testing.T) {
// A real SQL NOWAIT probe at the response-write boundary catches locks that
// would otherwise remain invisible in a buffered httptest recorder.
// readLockProbe 在首个 Write 前执行外部锁探测;只运行一次以免多段响应反复探测。
type readLockProbe struct {
*httptest.ResponseRecorder
probe func()
}
// Write 先清空 probe 再调用,随后交给 recorder 保存实际响应体。
func (w *readLockProbe) Write(body []byte) (int, error) {
if w.probe != nil {
probe := w.probe