Skip to content

Commit 17b423f

Browse files
committed
fix(export): stream concepts and render bundle locally
1 parent 4a3afbe commit 17b423f

13 files changed

Lines changed: 473 additions & 72 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ GET /api/v1/concepts — list/search(domain/type/tag/status/
4141
GET /api/v1/concepts/* — 单取
4242
GET /api/v1/links/* — 出链 + 反向引用(links 拆为独立顶层资源)
4343
PUT /api/v1/links/* — 替换概念的出链
44-
GET /api/v1/domains/{domain}/export — OKF bundle 导出
44+
GET /api/v1/domains/{domain}/export — OKF bundle 导出(NDJSON 概念流,由客户端本地渲染文件树)
4545
GET /api/v1/domains — 领域清单
4646
PUT /api/v1/domains/{domain} — 创建/更新 README、schema、visibility
4747
DELETE /api/v1/domains/{domain} — 级联删除 domain 全部数据
@@ -68,7 +68,7 @@ okp get <id> — 单取
6868
okp search <query> — 搜索
6969
okp batch <file> — 批量导入(NDJSON)
7070
okp links <id> — 查看关系
71-
okp export <domain> — OKF 导出
71+
okp export <domain> — 导出 OKF bundle 文件树到本地
7272
okp lint <file> — 本地校验
7373
okp domains — 领域清单
7474
okp delete <id> — 删除 concept

‎cmd/cli/commands.go‎

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -311,26 +311,56 @@ func cmdExport() *cobra.Command {
311311
cmd := &cobra.Command{
312312
Use: "export <domain>",
313313
Short: "导出为 OKF bundle 文件树",
314-
Args: cobra.ExactArgs(1),
314+
Long: `从 API 拉取 domain 的全部 concept(NDJSON 流),
315+
在本地渲染 OKF bundle 文件树:{out}/{domain}/index.md + {type}/{slug}.md`,
316+
Args: cobra.ExactArgs(1),
315317
RunE: func(cmd *cobra.Command, args []string) error {
318+
domain := args[0]
316319
if outDir == "" {
317320
outDir = "./okp-export"
318321
}
319-
params := url.Values{"out": {outDir}}
320-
path := "/api/v1/domains/" + url.PathEscape(args[0]) + "/export?" + params.Encode()
321-
resp, err := doRequest("GET", path, nil)
322+
323+
resp, err := doRequest("GET", "/api/v1/domains/"+url.PathEscape(domain)+"/export", nil)
322324
if err != nil {
323325
return fmt.Errorf("请求失败: %w", err)
324326
}
325-
var result map[string]any
326-
if err := readJSON(resp, &result); err != nil {
327+
defer resp.Body.Close()
328+
if resp.StatusCode >= 400 {
329+
b, _ := io.ReadAll(resp.Body)
330+
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(b))
331+
}
332+
333+
// 逐行解码 NDJSON 概念流(与 GET /api/v1/concepts/* 同一数据结构)。
334+
var concepts []model.Concept
335+
dec := json.NewDecoder(resp.Body)
336+
for {
337+
var c model.Concept
338+
if err := dec.Decode(&c); err != nil {
339+
if err == io.EOF {
340+
break
341+
}
342+
return fmt.Errorf("导出流解析失败: %w", err)
343+
}
344+
concepts = append(concepts, c)
345+
}
346+
if len(concepts) == 0 {
347+
return fmt.Errorf("导出内容为空")
348+
}
349+
350+
bundleDir, err := service.WriteDomainBundle(domain, concepts, outDir)
351+
if err != nil {
327352
return err
328353
}
329-
prettyPrint(result)
354+
fmt.Fprintf(os.Stderr, "导出 %d 个 concept → %s\n", len(concepts), bundleDir)
355+
prettyPrint(map[string]any{
356+
"domain": domain,
357+
"path": bundleDir,
358+
"files": len(concepts),
359+
})
330360
return nil
331361
},
332362
}
333-
cmd.Flags().StringVarP(&outDir, "out", "o", "", "输出目录")
363+
cmd.Flags().StringVarP(&outDir, "out", "o", "", "输出目录(bundle 写入 {out}/{domain}/)")
334364
return cmd
335365
}
336366

‎cmd/cli/export_test.go‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
"net/http/httptest"
7+
"os"
8+
"path/filepath"
9+
"strings"
10+
"testing"
11+
12+
"github.com/talesofai/okp/internal/model"
13+
)
14+
15+
func TestCmdExportWritesBundleLocally(t *testing.T) {
16+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17+
if r.URL.Path != "/api/v1/domains/demo/export" {
18+
http.NotFound(w, r)
19+
return
20+
}
21+
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
22+
enc := json.NewEncoder(w)
23+
for _, c := range []model.Concept{
24+
{ID: "demo/Note/alpha", Domain: "demo", Type: "Note", Title: "Alpha", Body: "Alpha body", Provenance: model.JSONMap{"source": "t", "agent": "t"}},
25+
{ID: "demo/Note/beta", Domain: "demo", Type: "Note", Title: "Beta", Body: "Beta body", Provenance: model.JSONMap{"source": "t", "agent": "t"}},
26+
} {
27+
if err := enc.Encode(c); err != nil {
28+
t.Errorf("encode: %v", err)
29+
}
30+
}
31+
}))
32+
defer srv.Close()
33+
34+
apiBase = srv.URL
35+
apiToken = ""
36+
defer func() { apiBase = "" }()
37+
38+
outDir := filepath.Join(t.TempDir(), "out")
39+
cmd := cmdExport()
40+
cmd.SetArgs([]string{"demo"})
41+
if err := cmd.Flags().Set("out", outDir); err != nil {
42+
t.Fatal(err)
43+
}
44+
if err := cmd.Execute(); err != nil {
45+
t.Fatalf("export: %v", err)
46+
}
47+
48+
index, err := os.ReadFile(filepath.Join(outDir, "demo", "index.md"))
49+
if err != nil {
50+
t.Fatal(err)
51+
}
52+
if !strings.Contains(string(index), "[Alpha](Note/alpha.md)") || !strings.Contains(string(index), "[Beta](Note/beta.md)") {
53+
t.Fatalf("index missing links: %s", index)
54+
}
55+
56+
alpha, err := os.ReadFile(filepath.Join(outDir, "demo", "Note", "alpha.md"))
57+
if err != nil {
58+
t.Fatal(err)
59+
}
60+
if !strings.Contains(string(alpha), "Alpha body") {
61+
t.Fatalf("alpha body missing: %s", alpha)
62+
}
63+
}
64+
65+
func TestCmdExportPropagatesHTTPErrors(t *testing.T) {
66+
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
67+
w.WriteHeader(http.StatusNotFound)
68+
_, _ = w.Write([]byte(`{"error":"domain 'missing' 下无 concept"}`))
69+
}))
70+
defer srv.Close()
71+
72+
apiBase = srv.URL
73+
apiToken = ""
74+
defer func() { apiBase = "" }()
75+
76+
cmd := cmdExport()
77+
cmd.SetArgs([]string{"missing"})
78+
if err := cmd.Flags().Set("out", t.TempDir()); err != nil {
79+
t.Fatal(err)
80+
}
81+
if err := cmd.Execute(); err == nil {
82+
t.Fatal("expected error for HTTP 404")
83+
}
84+
}

‎internal/handler/export_test.go‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
package handler
2+
3+
import (
4+
"bufio"
5+
"encoding/json"
6+
"net/http"
7+
"strings"
8+
"testing"
9+
10+
"github.com/talesofai/okp/internal/config"
11+
"github.com/talesofai/okp/internal/model"
12+
"github.com/talesofai/okp/internal/testutil"
13+
)
14+
15+
func TestExportDomainStreamsConcepts(t *testing.T) {
16+
db := testutil.OpenDatabase(t)
17+
previousConfig := config.C
18+
config.C = config.Config{ExecutionGrantKey: "test-key"}
19+
t.Cleanup(func() { config.C = previousConfig })
20+
21+
if err := db.Create(&model.User{UUID: "admin", AuthType: "test", Role: "admin"}).Error; err != nil {
22+
t.Fatal(err)
23+
}
24+
if err := db.Create(&model.DomainMeta{Domain: "public", Visibility: "public"}).Error; err != nil {
25+
t.Fatal(err)
26+
}
27+
for _, c := range []model.Concept{
28+
{ID: "public/Note/zeta", Domain: "public", Type: "Note", Title: "Zeta", Provenance: model.JSONMap{"source": "t", "agent": "t"}},
29+
{ID: "public/Guide/alpha", Domain: "public", Type: "Guide", Title: "Alpha", Provenance: model.JSONMap{"source": "t", "agent": "t"}},
30+
{ID: "public/Note/beta", Domain: "public", Type: "Note", Title: "Beta", Provenance: model.JSONMap{"source": "t", "agent": "t"}},
31+
} {
32+
if err := db.Create(&c).Error; err != nil {
33+
t.Fatal(err)
34+
}
35+
}
36+
37+
router := NewRouter()
38+
token := testExecutionToken(t, "test-key", "admin")
39+
res := testRequest(t, router, token, http.MethodGet, "/api/v1/domains/public/export", nil)
40+
assertStatus(t, res, http.StatusOK)
41+
if got := res.Header().Get("Content-Type"); !strings.HasPrefix(got, "application/x-ndjson") {
42+
t.Fatalf("content type = %q", got)
43+
}
44+
if got := res.Header().Get("X-Total-Count"); got != "3" {
45+
t.Fatalf("X-Total-Count = %q", got)
46+
}
47+
48+
var ids []string
49+
scanner := bufio.NewScanner(res.Body)
50+
for scanner.Scan() {
51+
var c model.Concept
52+
if err := json.Unmarshal(scanner.Bytes(), &c); err != nil {
53+
t.Fatalf("line %q: %v", scanner.Text(), err)
54+
}
55+
ids = append(ids, c.ID)
56+
}
57+
if err := scanner.Err(); err != nil {
58+
t.Fatal(err)
59+
}
60+
want := []string{"public/Guide/alpha", "public/Note/beta", "public/Note/zeta"}
61+
if strings.Join(ids, ",") != strings.Join(want, ",") {
62+
t.Fatalf("ids = %v, want %v", ids, want)
63+
}
64+
}
65+
66+
func TestExportDomainHidesPrivateAndRejectsEmpty(t *testing.T) {
67+
db := testutil.OpenDatabase(t)
68+
previousConfig := config.C
69+
config.C = config.Config{ExecutionGrantKey: "test-key"}
70+
t.Cleanup(func() { config.C = previousConfig })
71+
72+
for _, u := range []model.User{
73+
{UUID: "creator", AuthType: "test", Role: "reader"},
74+
{UUID: "admin", AuthType: "test", Role: "admin"},
75+
} {
76+
if err := db.Create(&u).Error; err != nil {
77+
t.Fatal(err)
78+
}
79+
}
80+
81+
router := NewRouter()
82+
creatorToken := testExecutionToken(t, "test-key", "creator")
83+
adminToken := testExecutionToken(t, "test-key", "admin")
84+
85+
res := testRequest(t, router, creatorToken, http.MethodPut, "/api/v1/domains/private-team", map[string]any{
86+
"readme": "# Private",
87+
"visibility": "private",
88+
})
89+
assertStatus(t, res, http.StatusCreated)
90+
res = testRequest(t, router, creatorToken, http.MethodPut, "/api/v1/concepts/private-team/Note/plan", map[string]any{
91+
"domain": "private-team",
92+
"type": "Note",
93+
"title": "Plan",
94+
"provenance": map[string]any{"source": "t", "agent": "t"},
95+
})
96+
assertStatus(t, res, http.StatusOK)
97+
98+
// 非成员(含全局 admin)不可导出私有域
99+
assertStatus(t, testRequest(t, router, adminToken, http.MethodGet, "/api/v1/domains/private-team/export", nil), http.StatusNotFound)
100+
// host 可导出
101+
res = testRequest(t, router, creatorToken, http.MethodGet, "/api/v1/domains/private-team/export", nil)
102+
assertStatus(t, res, http.StatusOK)
103+
if got := res.Header().Get("X-Total-Count"); got != "1" {
104+
t.Fatalf("X-Total-Count = %q, want 1", got)
105+
}
106+
107+
// 可见但空的 domain → 404
108+
assertStatus(t, testRequest(t, router, adminToken, http.MethodPut, "/api/v1/domains/empty-public", map[string]any{"readme": "# Empty"}), http.StatusCreated)
109+
assertStatus(t, testRequest(t, router, adminToken, http.MethodGet, "/api/v1/domains/empty-public/export", nil), http.StatusNotFound)
110+
}

‎internal/handler/router.go‎

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"crypto/sha256"
66
"encoding/hex"
77
"encoding/json"
8+
"fmt"
89
"log/slog"
910
"net/http"
1011
"strings"
@@ -490,30 +491,44 @@ func listDomains(w http.ResponseWriter, r *http.Request) {
490491
}
491492

492493
// GET /api/v1/domains/{domain}/export
494+
// 以 NDJSON 流返回该 domain 的全部 concept(每行一个 concept JSON,按 type, id 排序)。
495+
// 由调用方(如 okp CLI)负责在本地渲染 OKF bundle 文件树,服务端不写任何文件。
493496
func exportDomain(w http.ResponseWriter, r *http.Request) {
494497
domain := chi.URLParam(r, "domain")
495498
if !requireReadableDomain(w, r, domain) {
496499
return
497500
}
498-
outDir := r.URL.Query().Get("out")
499-
if outDir == "" {
500-
outDir = "./okp-export"
501+
502+
var count int64
503+
if err := store.DB.Model(&model.Concept{}).Where("domain = ?", domain).Count(&count).Error; err != nil {
504+
slog.Error("导出计数失败", "domain", domain, "error", err)
505+
writeError(w, http.StatusInternalServerError, "导出失败")
506+
return
507+
}
508+
if count == 0 {
509+
writeError(w, http.StatusNotFound, fmt.Sprintf("domain '%s' 下无 concept", domain))
510+
return
501511
}
502512

503-
bundlePath, err := service.ExportDomain(domain, outDir)
513+
w.Header().Set("Content-Type", "application/x-ndjson; charset=utf-8")
514+
w.Header().Set("X-Total-Count", itoa(count))
515+
enc := json.NewEncoder(w)
516+
enc.SetEscapeHTML(false)
517+
518+
var batch []model.Concept
519+
err := store.DB.Where("domain = ?", domain).Order("type, id").
520+
FindInBatches(&batch, 500, func(tx *gorm.DB, n int) error {
521+
for i := range batch {
522+
if err := enc.Encode(&batch[i]); err != nil {
523+
return err
524+
}
525+
}
526+
return nil
527+
}).Error
504528
if err != nil {
505-
if strings.Contains(err.Error(), "无 concept") {
506-
writeError(w, http.StatusNotFound, err.Error())
507-
} else {
508-
slog.Error("导出失败", "error", err)
509-
writeError(w, http.StatusInternalServerError, "导出失败: "+err.Error())
510-
}
511-
return
529+
// 响应头已发出,无法再返回结构化错误;客户端会因流截断而失败。
530+
slog.Error("导出流失败", "domain", domain, "error", err)
512531
}
513-
writeJSON(w, http.StatusOK, map[string]string{
514-
"domain": domain,
515-
"path": bundlePath,
516-
})
517532
}
518533

519534
// ── 工具函数 ────────────────────────────────────────────────

0 commit comments

Comments
 (0)