Elffuss BraidHub

kikocis/utopia public

Every source kind the UI offers can be created (#253)

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Changeset8c8c67ee3608120cd38250890781984a7fa736235602990c5ef588a9be9e602c
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 15:16 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-03 15:16 +08:00
Parentsffe9e37e55e3

Browse the files at this changeset

12 files changed

modified Cargo.lock +24 −2
@@ -4180,13 +4180,34 @@
41804180 source = "registry+https://github.com/rust-lang/crates.io-index"
41814181 checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
41824182
4183+[[package]]
4184+name = "strum"
4185+version = "0.27.2"
4186+source = "registry+https://github.com/rust-lang/crates.io-index"
4187+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
4188+dependencies = [
4189+ "strum_macros 0.27.2",
4190+]
4191+
41834192 [[package]]
41844193 name = "strum"
41854194 version = "0.28.0"
41864195 source = "registry+https://github.com/rust-lang/crates.io-index"
41874196 checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
41884197 dependencies = [
4189- "strum_macros",
4198+ "strum_macros 0.28.0",
4199+]
4200+
4201+[[package]]
4202+name = "strum_macros"
4203+version = "0.27.2"
4204+source = "registry+https://github.com/rust-lang/crates.io-index"
4205+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
4206+dependencies = [
4207+ "heck",
4208+ "proc-macro2",
4209+ "quote",
4210+ "syn 2.0.119",
41904211 ]
41914212
41924213 [[package]]
@@ -4464,7 +4485,7 @@
44644485 "icu_segmenter",
44654486 "itertools 0.14.0",
44664487 "memchr",
4467- "strum",
4488+ "strum 0.28.0",
44684489 "thiserror 2.0.20",
44694490 ]
44704491
@@ -4908,6 +4929,7 @@
49084929 "serde",
49094930 "serde_json",
49104931 "sqlx",
4932+ "strum 0.27.2",
49114933 "thiserror 2.0.20",
49124934 "uuid",
49134935 ]
modified Cargo.toml +2 −0
@@ -41,6 +41,8 @@
4141 tracing = "0.1"
4242 tracing-subscriber = { version = "0.3", features = ["env-filter"] }
4343 flate2 = "1"
44+# 枚举的字符串化与遍历(来源种类 `SourceKind`)——手写两份清单的漂移就是 #247
45+strum = { version = "0.27", features = ["derive"] }
4446
4547 # Phase 1: 摄入/检索/LLM
4648 utopia-ingest = { path = "crates/utopia-ingest" }
modified crates/utopia-core/Cargo.toml +1 −0
@@ -14,3 +14,4 @@
1414 sqlx.workspace = true
1515 figment.workspace = true
1616 pgvector.workspace = true
17+strum.workspace = true
modified crates/utopia-core/src/models.rs +61 −0
@@ -165,6 +165,67 @@
165165 }
166166 }
167167
168+/// 来源的种类。**一处定义,三处消费**:创建时的白名单、同步时的分派(按枚举穷举匹配,
169+/// 加一种就得决定它怎么同步)、前端的下拉框(`web/src/sourceKinds.ts`,由
170+/// `utopia-store` 的测试对表)。
171+///
172+/// 此前后端两张手写清单各自演进:五种连接器加了同步分支、进了界面,却没进创建的
173+/// 白名单,界面上选得到、建的时候报「kind must be one of…」(#247)。变体顺序就是
174+/// 对话框里的顺序;字符串形式由 strum 按 snake_case 生成,不再手写
175+#[derive(
176+ Debug,
177+ Clone,
178+ Copy,
179+ PartialEq,
180+ Eq,
181+ Hash,
182+ strum::EnumIter,
183+ strum::IntoStaticStr,
184+ strum::EnumString,
185+)]
186+#[strum(serialize_all = "snake_case")]
187+pub enum SourceKind {
188+ Folder,
189+ Url,
190+ Rss,
191+ GithubIssues,
192+ JiraIssues,
193+ S3,
194+ AzureBlob,
195+ Gcs,
196+ Webdav,
197+ Notion,
198+ Api,
199+ Custom,
200+ /// 每个库自带的记忆来源,不可建不可删(0015)
201+ Memory,
202+ /// 老数据里 `sources.kind` 的默认值,没有对应的界面
203+ Upload,
204+}
205+
206+impl SourceKind {
207+ pub fn as_str(self) -> &'static str {
208+ self.into()
209+ }
210+
211+ pub fn parse(s: &str) -> Option<Self> {
212+ s.parse().ok()
213+ }
214+
215+ pub fn all() -> impl Iterator<Item = Self> {
216+ <Self as strum::IntoEnumIterator>::iter()
217+ }
218+
219+ /// 人能从界面建的:`memory` 与 `upload` 之外的全部
220+ pub fn creatable_by_hand(self) -> bool {
221+ !matches!(self, Self::Memory | Self::Upload)
222+ }
223+
224+ pub fn creatable() -> impl Iterator<Item = Self> {
225+ Self::all().filter(|k| k.creatable_by_hand())
226+ }
227+}
228+
168229 /// 来源同步运行记录(渠道审计历史)。
169230 #[derive(Debug, Clone, Serialize, sqlx::FromRow)]
170231 pub struct SyncRun {
modified crates/utopia-server/src/ingest_sources.rs +18 −11
@@ -8,6 +8,7 @@
88 use chrono::{DateTime, Utc};
99 use sha2::{Digest, Sha256};
1010 use utopia_core::models::Source;
11+use utopia_core::models::SourceKind;
1112 use uuid::Uuid;
1213
1314 /// 单次同步的新文档上限(防超长 feed/URL 列表拖垮任务)
@@ -48,17 +49,23 @@
4849 let run_id = utopia_store::sources::start_run(&state.pool, source_id).await?;
4950 state.emit_source(source.kb_id);
5051
51- let outcome = match source.kind.as_str() {
52- "url" => sync_urls(state, &source).await,
53- "rss" => sync_rss(state, &source).await,
54- "custom" => sync_custom(state, &source).await,
55- "github_issues" => sync_github_issues(state, &source).await,
56- "jira_issues" => sync_jira_issues(state, &source).await,
57- "s3" | "azure_blob" | "gcs" => sync_object_storage(state, &source).await,
58- "webdav" => sync_webdav(state, &source).await,
59- "notion" => sync_notion(state, &source).await,
60- // folder / api 无拉取语义
61- _ => Ok(SyncStats::default()),
52+ // 按枚举穷举:加一种来源就得在这里决定它怎么同步,编译器不放过漏掉的那一支
53+ let outcome = match SourceKind::parse(&source.kind) {
54+ Some(SourceKind::Url) => sync_urls(state, &source).await,
55+ Some(SourceKind::Rss) => sync_rss(state, &source).await,
56+ Some(SourceKind::Custom) => sync_custom(state, &source).await,
57+ Some(SourceKind::GithubIssues) => sync_github_issues(state, &source).await,
58+ Some(SourceKind::JiraIssues) => sync_jira_issues(state, &source).await,
59+ Some(SourceKind::S3 | SourceKind::AzureBlob | SourceKind::Gcs) => {
60+ sync_object_storage(state, &source).await
61+ }
62+ Some(SourceKind::Webdav) => sync_webdav(state, &source).await,
63+ Some(SourceKind::Notion) => sync_notion(state, &source).await,
64+ // 被动容器:folder / api / memory / upload 没有拉取语义
65+ Some(SourceKind::Folder | SourceKind::Api | SourceKind::Memory | SourceKind::Upload) => {
66+ Ok(SyncStats::default())
67+ }
68+ None => Err(anyhow::anyhow!("unknown source kind `{}`", source.kind)),
6269 };
6370
6471 match outcome {
modified crates/utopia-store/src/sources.rs +10 −16
@@ -2,28 +2,22 @@
22
33 use chrono::{DateTime, Utc};
44 use sqlx::PgPool;
5-use utopia_core::models::{Role, Source, SourceView, SyncRun, SOURCE_SECRET_KEYS};
5+use utopia_core::models::{Role, Source, SourceKind, SourceView, SyncRun, SOURCE_SECRET_KEYS};
66 use utopia_core::{AppError, AppResult};
77 use uuid::Uuid;
88
99 /// folder = 纯容器(上传/拖拽入内,无同步语义);url/rss = 拉取型;api = 推送型。
1010 /// 本机目录监听(watch_folder)已否决——自部署用户看不到服务器磁盘;
11-/// 未来的 watch 形态是对象存储/网盘(P5 连接器,与 BlobStore 接缝配套)。
11+/// 对象存储 / WebDAV / Notion 是它的替代形态(0013)。
1212 /// custom = 自定义拉取器:任何实现 Utopia ingest 接口的 URL(返回 items JSON)即可定时摄取。
1313 /// github_issues / jira_issues = 工单:一张工单连同它的状态变更史成为一篇文档。
1414 ///
15-/// **改这里就得改前端那份清单**(`Library.tsx` 的建来源对话框与 `api.ts` 的
16-/// `SourceView["kind"]`)。两处对不上时的症状是:界面上选得到、建的时候报
17-/// 「kind must be one of…」——单元测试与 tsc 都看不见,只有端到端会撞上。
18-pub const KINDS: &[&str] = &[
19- "folder",
20- "url",
21- "rss",
22- "api",
23- "custom",
24- "github_issues",
25- "jira_issues",
26-];
15+/// 种类的清单**不在这里写**:`SourceKind`(utopia-core)一个枚举出全部——创建的白名单、
16+/// 同步的分派、前端的下拉框(有测试对表)。从前这里有一张手写的 `KINDS`,五种连接器
17+/// 加了同步却没进这张表,界面上选得到、建不出来(#247)
18+pub fn creatable_kinds() -> Vec<&'static str> {
19+ SourceKind::creatable().map(|k| k.as_str()).collect()
20+}
2721
2822 /// 校验并规范化标准 5 段 cron 表达式(内部用 cron crate 的 6 段:补秒位)。
2923 pub fn validate_cron(expr: &str) -> AppResult<String> {
@@ -93,10 +87,10 @@
9387 sync_interval_minutes: Option<i32>,
9488 sync_cron: Option<&str>,
9589 ) -> AppResult<Source> {
96- if !KINDS.contains(&kind) {
90+ if !SourceKind::parse(kind).is_some_and(|k| k.creatable_by_hand()) {
9791 return Err(AppError::Validation(format!(
9892 "kind must be one of: {}",
99- KINDS.join(", ")
93+ creatable_kinds().join(", ")
10094 )));
10195 }
10296 if name.trim().is_empty() {
added crates/utopia-store/tests/a_source_kind_is_listed_once.rs +53 −0
@@ -0,0 +1,53 @@
1+//! #247:来源的种类只在一处定义,前后端对表。
2+//!
3+//! 后端 `SourceKind`(utopia-core)一个枚举出两份清单:创建时的白名单、同步时的分派
4+//! (后者按枚举穷举匹配,编译器保证加了种类就得决定它怎么同步)。前端那一份在
5+//! `web/src/sourceKinds.ts`,这个测试把它读出来跟枚举比——此前两边各自手写,五种
6+//! 连接器进了界面、进了同步,却没进创建白名单,界面上选得到、建的时候报
7+//! 「kind must be one of…」。单元测试与 tsc 都看不见的那种漂移,这里看得见。
8+//!
9+//! 不需要数据库。
10+
11+use std::path::Path;
12+use utopia_core::models::SourceKind;
13+
14+/// 从 `CREATABLE_SOURCE_KINDS = [ "…", … ] as const` 里把引号里的字面量按顺序读出来
15+fn frontend_kinds(src: &str) -> Vec<String> {
16+ let start = src
17+ .find("CREATABLE_SOURCE_KINDS = [")
18+ .expect("web/src/sourceKinds.ts declares CREATABLE_SOURCE_KINDS");
19+ let body = &src[start..];
20+ let end = body.find(']').expect("the array closes");
21+ body[..end]
22+ .split('"')
23+ .skip(1)
24+ .step_by(2)
25+ .map(str::to_string)
26+ .collect()
27+}
28+
29+#[test]
30+fn the_frontend_list_matches_the_backend_enum() {
31+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../web/src/sourceKinds.ts");
32+ let src =
33+ std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
34+ let frontend = frontend_kinds(&src);
35+ let backend: Vec<String> = SourceKind::creatable()
36+ .map(|k| k.as_str().to_string())
37+ .collect();
38+ assert_eq!(
39+ frontend, backend,
40+ "web/src/sourceKinds.ts and utopia_core::models::SourceKind list different kinds (order matters: it is the dialog's order)"
41+ );
42+}
43+
44+#[test]
45+fn every_kind_round_trips_through_its_string() {
46+ for k in SourceKind::all() {
47+ assert_eq!(SourceKind::parse(k.as_str()), Some(k), "{k:?}");
48+ }
49+ assert_eq!(SourceKind::parse("watch_folder"), None);
50+ assert!(!SourceKind::Memory.creatable_by_hand());
51+ assert!(!SourceKind::Upload.creatable_by_hand());
52+ assert!(SourceKind::S3.creatable_by_hand());
53+}
modified docs/decisions/0013-a-source-should-hand-over-its-history.md +1 −0
@@ -111,3 +111,4 @@
111111 ## Revisions
112112
113113 - 2026-09-03: every connector's credentials stay on the server (#246). Until now only `auth_header` was stripped from responses; the object-storage, WebDAV and Notion keys went out to every viewer. The keys now live in one list, `SOURCE_SECRET_KEYS`, shared by the listing, the create / update responses and the update merge (blank or missing keeps the stored value, an explicit `null` removes it). Adding a connector means adding its keys there first.
114+- 2026-09-03: the five connectors added under this record could not be created (#247): the store's hand-written `KINDS` allowlist stopped at seven kinds while the sync dispatcher and the UI knew twelve. The kinds now come from one enum, `SourceKind` in `utopia-core`; the allowlist is derived from it, the dispatcher matches it exhaustively, and a test compares the frontend's `web/src/sourceKinds.ts` against it, so the three can no longer drift apart.
modified web/src/api.ts +2 −15
@@ -1,3 +1,4 @@
1+import type { SourceKind } from "./sourceKinds";
12 import { S, lang } from "./i18n";
23
34 export class ApiError extends Error {
@@ -179,21 +180,7 @@
179180
180181 export interface SourceView {
181182 id: string;
182- kind:
183- | "folder"
184- | "url"
185- | "rss"
186- | "api"
187- | "custom"
188- | "github_issues"
189- | "jira_issues"
190- | "s3"
191- | "azure_blob"
192- | "gcs"
193- | "webdav"
194- | "notion"
195- | "memory"
196- | "upload";
183+ kind: SourceKind;
197184 name: string;
198185 config: {
199186 urls?: string[];
modified web/src/pages/Library.tsx +6 −30
@@ -14,6 +14,10 @@
1414 } from "lucide-react";
1515 import { api, type Doc, type ExtractionDrop, type SourceView } from "../api";
1616 import { S } from "../i18n";
17+import {
18+ CREATABLE_SOURCE_KINDS,
19+ type CreatableSourceKind,
20+} from "../sourceKinds";
1721 import { useKb, useKbId } from "../kb";
1822 import { toast } from "../toast";
1923 import { Chip, type ChipTone, DangerConfirm, Loading, Pager } from "../ui";
@@ -1267,20 +1271,7 @@
12671271 /** isApi=true 时父级紧接着打开密钥弹窗 */
12681272 onDone: (id?: string, isApi?: boolean) => void;
12691273 }) {
1270- const [kind, setKind] = useState<
1271- | "folder"
1272- | "url"
1273- | "rss"
1274- | "custom"
1275- | "api"
1276- | "github_issues"
1277- | "jira_issues"
1278- | "s3"
1279- | "azure_blob"
1280- | "gcs"
1281- | "webdav"
1282- | "notion"
1283- >("folder");
1274+ const [kind, setKind] = useState<CreatableSourceKind>("folder");
12841275 const [name, setName] = useState("");
12851276 const [icon, setIcon] = useState<string | null>(null);
12861277 const [urls, setUrls] = useState("");
@@ -1447,22 +1438,7 @@
14471438 <div className="px-5 py-4">
14481439 {/* 类型 */}
14491440 <div className="flex gap-2 mb-2">
1450- {(
1451- [
1452- "folder",
1453- "url",
1454- "rss",
1455- "github_issues",
1456- "jira_issues",
1457- "s3",
1458- "azure_blob",
1459- "gcs",
1460- "webdav",
1461- "notion",
1462- "api",
1463- "custom",
1464- ] as const
1465- ).map((k) => {
1441+ {CREATABLE_SOURCE_KINDS.map((k) => {
14661442 const Icon = KIND_ICON[k];
14671443 return (
14681444 <button
modified web/src/pages/SourcesRail.tsx +4 −2
@@ -1,4 +1,5 @@
11 /* 来源栏("来源即文件夹"):Library 与 DocViewer 共用的左侧导航。 */
2+import type { SourceKind } from "../sourceKinds";
23 import { useQuery } from "@tanstack/react-query";
34 import {
45 Archive,
@@ -59,7 +60,8 @@
5960 users: Users,
6061 };
6162
62-export const KIND_ICON = {
63+// 按 SourceKind 键全:加一种来源没配图标,tsc 就红
64+export const KIND_ICON: Record<SourceKind, LucideIcon> = {
6365 folder: FolderOpen,
6466 url: Globe,
6567 rss: Rss,
@@ -74,7 +76,7 @@
7476 notion: Notebook,
7577 memory: Brain,
7678 upload: Upload,
77-} as const;
79+};
7880
7981 /** 有拉取/同步语义的来源类型(folder/api 无同步概念) */
8082 export const SYNCING_KINDS = new Set([
added web/src/sourceKinds.ts +29 −0
@@ -0,0 +1,29 @@
1+/**
2+ * 来源的种类——**前端这一份清单只在这里写一次**。
3+ *
4+ * 后端的那一份是 `crates/utopia-core` 里的 `SourceKind` 枚举,创建时的校验与同步时的
5+ * 分派都从它出;`utopia-store` 的测试会读这个文件,把两边对一遍——任何一边多一种
6+ * 少一种,`cargo test` 就红。此前两边各自手写,五种连接器加了同步分支、进了界面,
7+ * 却没进创建的白名单:选得到、建不出来(#247)。
8+ *
9+ * 顺序就是建来源对话框里的顺序。
10+ */
11+export const CREATABLE_SOURCE_KINDS = [
12+ "folder",
13+ "url",
14+ "rss",
15+ "github_issues",
16+ "jira_issues",
17+ "s3",
18+ "azure_blob",
19+ "gcs",
20+ "webdav",
21+ "notion",
22+ "api",
23+ "custom",
24+] as const;
25+
26+export type CreatableSourceKind = (typeof CREATABLE_SOURCE_KINDS)[number];
27+
28+/** 库里还会有两种人建不出来的:每个库自带的 `memory`,与老数据的 `upload` */
29+export type SourceKind = CreatableSourceKind | "memory" | "upload";