Elffuss BraidHub

kikocis/utopia public

A Notion page keeps its own clock, and the title hides under a type (#213)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Changeset49653d3b68899d3b4366b1e07fced91506f7a529bcb8ec79e163d2762d2d4eef
AuthorWaylandYang <145302500+WaylandYang@users.noreply.github.com> · 2026-09-03 02:21 +08:00
CommitterGitHub <noreply@github.com> · 2026-09-03 02:21 +08:00
Parentsc53d009cfc64

Browse the files at this changeset

8 files changed

modified crates/utopia-server/src/ingest_sources.rs +40 −0
@@ -56,6 +56,7 @@
5656 "jira_issues" => sync_jira_issues(state, &source).await,
5757 "s3" | "azure_blob" | "gcs" => sync_object_storage(state, &source).await,
5858 "webdav" => sync_webdav(state, &source).await,
59+ "notion" => sync_notion(state, &source).await,
5960 // folder / api 无拉取语义
6061 _ => Ok(SyncStats::default()),
6162 };
@@ -850,6 +851,45 @@
850851 Ok(stats)
851852 }
852853
854+/// Notion 同步:把 integration 能看见的页面摄进来。
855+///
856+/// `doc_time` 取 `last_edited_time`——**这是页面自己的编辑时刻**,比对象存储
857+/// 那边的写入时刻实在:一份 2019 年的合同今天传进 S3 会落在今天,而 Notion
858+/// 页面的编辑时刻就是它内容变化的时刻。
859+async fn sync_notion(state: &AppState, source: &Source) -> anyhow::Result<SyncStats> {
860+ let token = source.config["token"]
861+ .as_str()
862+ .map(str::trim)
863+ .filter(|s| !s.is_empty())
864+ .ok_or_else(|| anyhow::anyhow!("notion source is missing config.token"))?;
865+ let query = source.config["query"]
866+ .as_str()
867+ .map(str::trim)
868+ .filter(|s| !s.is_empty());
869+
870+ let (pages, truncated) = crate::notion::fetch(token, query).await?;
871+ if truncated {
872+ tracing::warn!("页面数到达单次上限,其余留给下一次同步");
873+ }
874+
875+ let mut stats = SyncStats::default();
876+ for p in pages {
877+ let action = ingest_item(
878+ state,
879+ source.kb_id,
880+ source.id,
881+ &p.external_key,
882+ &p.filename,
883+ "text/markdown",
884+ p.text.as_bytes(),
885+ p.last_edited,
886+ )
887+ .await?;
888+ stats.absorb(action);
889+ }
890+ Ok(stats)
891+}
892+
853893 /// 标题无扩展名时按 mime 补一个,接入解析矩阵的分派。
854894 fn ensure_extension(title: &str, mime: &str) -> String {
855895 let has_ext = title
modified crates/utopia-server/src/main.rs +1 −0
@@ -14,6 +14,7 @@
1414 mod live;
1515 mod llm_util;
1616 mod mappings;
17+mod notion;
1718 mod object_storage;
1819 mod ontology_index;
1920 mod ontology_packs;
added crates/utopia-server/src/notion.rs +350 −0
@@ -0,0 +1,350 @@
1+//! Notion 来源:把 integration 能看见的页面同步进来。
2+//!
3+//! 按 [0013](../../docs/decisions/0013-a-source-should-hand-over-its-history.md)
4+//! 的四条判据,它比对象存储强一档:
5+//!
6+//! | 判据 | Notion |
7+//! |---|---|
8+//! | 真实时间戳 | `last_edited_time`,**是文档自己的编辑时刻**,不是我们抓它的时刻 |
9+//! | 会不会自我推翻 | 页面被反复改写正是它的常态 |
10+//! | 稳定身份 | 页面 UUID,改标题、挪位置都不变 |
11+//! | 企业知识住不住在那儿 | 制度、会议纪要、决策记录——正是这套系统要的东西 |
12+//!
13+//! **但它只交出现状,不交出历史。** Notion 的版本历史不在公开 API 里,
14+//! 所以跟工单系统不同:一次同步只能看见此刻,之前的编辑全靠一次次同步慢慢攒。
15+//! 这跟 `url` / `rss` 是同一个形状,而工单那两个能一次把变更史拿全。
16+//!
17+//! ## 两个容易踩的
18+//!
19+//! **`Notion-Version` 头是必填的**,而且值是日期。少了它接口直接 400,
20+//! 而错误信息只说 "missing version",不会告诉你该填哪个。
21+//!
22+//! **限流是每秒三次**(官方说法是「平均三次」)。所以取页面内容时是顺序而不是
23+//! 并发——并发上去只会换来一串 429,而我们的重试退避是为抽取那条路设计的,
24+//! 不该被摄入路径借用。
25+
26+use anyhow::Context as _;
27+use chrono::{DateTime, Utc};
28+
29+/// 请求头里的 API 版本。**写死而不是留给配置**:响应的形状跟着它变,
30+/// 让用户填一个我们没适配过的版本,换来的是解析静默失配。
31+const NOTION_VERSION: &str = "2026-03-11";
32+
33+/// 一次同步最多取多少页。理由同别的来源:摄入不可逆,而一个 workspace
34+/// 可以有几万页。
35+const MAX_PAGES_PER_SYNC: usize = 500;
36+
37+/// 每页最多取多少个 block。再深的页面截断,比让一次同步卡在一页上好。
38+const MAX_BLOCKS_PER_PAGE: usize = 500;
39+
40+/// 一个待摄入的页面。
41+pub struct NotionPage {
42+ /// `notion://{page_id}`——页面 UUID 是它最稳的身份
43+ pub external_key: String,
44+ pub filename: String,
45+ pub text: String,
46+ pub last_edited: Option<DateTime<Utc>>,
47+}
48+
49+fn client(token: &str) -> anyhow::Result<reqwest::Client> {
50+ let mut h = reqwest::header::HeaderMap::new();
51+ h.insert("Notion-Version", NOTION_VERSION.parse()?);
52+ h.insert(
53+ reqwest::header::AUTHORIZATION,
54+ format!("Bearer {token}").parse()?,
55+ );
56+ Ok(reqwest::Client::builder()
57+ .default_headers(h)
58+ .timeout(std::time::Duration::from_secs(60))
59+ .build()?)
60+}
61+
62+/// 取 integration 能看见的所有页面。
63+///
64+/// **只搜页面,不搜 data source。** 后者是表格的容器,它自己没有正文;
65+/// 表格里的每一行是一个页面,会在同一次搜索里出现。
66+pub async fn fetch(token: &str, query: Option<&str>) -> anyhow::Result<(Vec<NotionPage>, bool)> {
67+ let http = client(token)?;
68+ let mut out = Vec::new();
69+ let mut cursor: Option<String> = None;
70+ let mut truncated = false;
71+
72+ loop {
73+ let mut body = serde_json::json!({
74+ "filter": { "property": "object", "value": "page" },
75+ "page_size": 100,
76+ });
77+ if let Some(q) = query {
78+ body["query"] = serde_json::Value::String(q.to_string());
79+ }
80+ if let Some(c) = &cursor {
81+ body["start_cursor"] = serde_json::Value::String(c.clone());
82+ }
83+
84+ let resp = http
85+ .post("https://api.notion.com/v1/search")
86+ .json(&body)
87+ .send()
88+ .await
89+ .context("notion search")?;
90+ let status = resp.status();
91+ let v: serde_json::Value = resp.json().await.context("notion search 响应")?;
92+ if !status.is_success() {
93+ anyhow::bail!(
94+ "notion search 回了 {status}: {}",
95+ v["message"].as_str().unwrap_or("unknown")
96+ );
97+ }
98+
99+ for p in v["results"].as_array().unwrap_or(&vec![]).clone() {
100+ // 回收站里的和归档的都不要——它们在界面上已经不算数了
101+ if p["in_trash"].as_bool() == Some(true) || p["is_archived"].as_bool() == Some(true) {
102+ continue;
103+ }
104+ if out.len() >= MAX_PAGES_PER_SYNC {
105+ truncated = true;
106+ break;
107+ }
108+ let Some(id) = p["id"].as_str() else { continue };
109+ let title = page_title(&p);
110+ let text = page_text(&http, id).await.unwrap_or_else(|e| {
111+ tracing::warn!(%id, error = %e, "页面正文取不回来,只留标题");
112+ String::new()
113+ });
114+
115+ out.push(NotionPage {
116+ external_key: format!("notion://{id}"),
117+ filename: format!("{}.md", slug(&title)),
118+ text: format!("# {title}\n\n{text}"),
119+ last_edited: p["last_edited_time"]
120+ .as_str()
121+ .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
122+ .map(|d| d.with_timezone(&Utc)),
123+ });
124+ }
125+
126+ if truncated || v["has_more"].as_bool() != Some(true) {
127+ break;
128+ }
129+ cursor = v["next_cursor"].as_str().map(str::to_string);
130+ if cursor.is_none() {
131+ break;
132+ }
133+ }
134+ Ok((out, truncated))
135+}
136+
137+/// 页面标题。
138+///
139+/// **标题藏在 `properties` 里那个 `type == "title"` 的属性下,而它的名字不固定**:
140+/// 数据库里的页面可能叫 `Name`、`名称`、`任务`,普通页面叫 `title`。
141+/// 按名字找会在别人的 workspace 上找不到,所以按类型找。
142+fn page_title(page: &serde_json::Value) -> String {
143+ let props = page["properties"].as_object();
144+ let t = props.and_then(|m| {
145+ m.values()
146+ .find(|v| v["type"] == "title")
147+ .and_then(|v| v["title"].as_array())
148+ });
149+ let s = t
150+ .map(|arr| {
151+ arr.iter()
152+ .filter_map(|r| r["plain_text"].as_str())
153+ .collect::<String>()
154+ })
155+ .unwrap_or_default();
156+ if s.trim().is_empty() {
157+ "untitled".into()
158+ } else {
159+ s
160+ }
161+}
162+
163+/// 取一页的正文,逐层展开 block。
164+async fn page_text(http: &reqwest::Client, page_id: &str) -> anyhow::Result<String> {
165+ let mut out = String::new();
166+ let mut n = 0usize;
167+ let mut cursor: Option<String> = None;
168+
169+ loop {
170+ let mut url = format!("https://api.notion.com/v1/blocks/{page_id}/children?page_size=100");
171+ if let Some(c) = &cursor {
172+ url.push_str(&format!("&start_cursor={c}"));
173+ }
174+ let resp = http.get(&url).send().await?;
175+ if !resp.status().is_success() {
176+ anyhow::bail!("blocks 回了 {}", resp.status());
177+ }
178+ let v: serde_json::Value = resp.json().await?;
179+
180+ for b in v["results"].as_array().unwrap_or(&vec![]) {
181+ if n >= MAX_BLOCKS_PER_PAGE {
182+ return Ok(out);
183+ }
184+ n += 1;
185+ if let Some(line) = render_block(b) {
186+ out.push_str(&line);
187+ out.push('\n');
188+ }
189+ }
190+ if v["has_more"].as_bool() != Some(true) {
191+ break;
192+ }
193+ cursor = v["next_cursor"].as_str().map(str::to_string);
194+ if cursor.is_none() {
195+ break;
196+ }
197+ }
198+ Ok(out)
199+}
200+
201+/// 把一个 block 渲染成一行文本。
202+///
203+/// **认不出的类型返回它的纯文本而不是丢掉。** Notion 的 block 类型一直在加,
204+/// 硬编码一张白名单意味着新类型静默消失;而所有带文字的 block 都把文字放在
205+/// `{type}.rich_text` 下,这个形状很稳。
206+fn render_block(b: &serde_json::Value) -> Option<String> {
207+ let t = b["type"].as_str()?;
208+ let inner = &b[t];
209+ let text = rich_text(&inner["rich_text"]);
210+
211+ Some(match t {
212+ "heading_1" => format!("## {text}"),
213+ "heading_2" => format!("### {text}"),
214+ "heading_3" => format!("#### {text}"),
215+ "bulleted_list_item" => format!("- {text}"),
216+ "numbered_list_item" => format!("1. {text}"),
217+ "to_do" => {
218+ let done = inner["checked"].as_bool() == Some(true);
219+ format!("- [{}] {text}", if done { "x" } else { " " })
220+ }
221+ "quote" => format!("> {text}"),
222+ "code" => {
223+ let lang = inner["language"].as_str().unwrap_or("");
224+ format!("```{lang}\n{text}\n```")
225+ }
226+ // 分割线与图片没有 rich_text,但它们在正文里也没有信息量
227+ "divider" | "image" | "video" | "file" => return None,
228+ // child_page 的标题在 `title` 而不是 rich_text
229+ "child_page" => format!("- {}", inner["title"].as_str().unwrap_or("")),
230+ _ if text.trim().is_empty() => return None,
231+ _ => text,
232+ })
233+}
234+
235+/// rich_text 数组拼成纯文本。
236+fn rich_text(v: &serde_json::Value) -> String {
237+ v.as_array()
238+ .map(|arr| {
239+ arr.iter()
240+ .filter_map(|r| r["plain_text"].as_str())
241+ .collect::<String>()
242+ })
243+ .unwrap_or_default()
244+}
245+
246+/// 标题变成能当文件名的东西。
247+fn slug(title: &str) -> String {
248+ let s: String = title
249+ .chars()
250+ .map(|c| if c.is_alphanumeric() { c } else { '-' })
251+ .collect();
252+ let s = s.trim_matches('-').to_string();
253+ if s.is_empty() {
254+ "untitled".into()
255+ } else {
256+ s.chars().take(60).collect()
257+ }
258+}
259+
260+#[cfg(test)]
261+mod tests {
262+ use super::*;
263+
264+ /// **标题属性的名字是任意的。** 数据库里的页面可能把它叫 `Name`、`名称`、
265+ /// `任务`;按名字找会在别人的 workspace 上返回 untitled,而那看起来
266+ /// 像是「页面没有标题」而不是「我们找错了地方」。
267+ #[test]
268+ fn a_title_is_found_by_type_not_by_name() {
269+ for key in ["title", "Name", "名称", "任务"] {
270+ let page = serde_json::json!({
271+ "properties": {
272+ key: { "type": "title", "title": [{ "plain_text": "季度复盘" }] },
273+ "Status": { "type": "select", "select": { "name": "Done" } }
274+ }
275+ });
276+ assert_eq!(page_title(&page), "季度复盘", "属性名 {key} 时找不到标题");
277+ }
278+ }
279+
280+ /// 富文本是分段的——加粗、链接都会把一句话切开。拼不全就会丢字。
281+ #[test]
282+ fn rich_text_segments_join_back_into_one_line() {
283+ let v = serde_json::json!([
284+ { "plain_text": "把总部搬到" },
285+ { "plain_text": "深圳" },
286+ { "plain_text": "了" }
287+ ]);
288+ assert_eq!(rich_text(&v), "把总部搬到深圳了");
289+ }
290+
291+ /// **认不出的 block 类型不能丢。** Notion 一直在加类型,而带文字的
292+ /// block 都把文字放在 `{type}.rich_text` 下——按白名单渲染会让新类型
293+ /// 静默消失。
294+ #[test]
295+ fn an_unknown_block_keeps_its_text() {
296+ let b = serde_json::json!({
297+ "type": "some_new_block_type_2027",
298+ "some_new_block_type_2027": { "rich_text": [{ "plain_text": "还是有内容的" }] }
299+ });
300+ assert_eq!(render_block(&b).as_deref(), Some("还是有内容的"));
301+ }
302+
303+ /// 没有文字的装饰性 block 该消失,否则正文里全是空行。
304+ #[test]
305+ fn a_divider_renders_to_nothing() {
306+ let b = serde_json::json!({ "type": "divider", "divider": {} });
307+ assert!(render_block(&b).is_none());
308+ }
309+
310+ /// 文件名不能带路径分隔符或换行。
311+ #[test]
312+ fn a_slug_is_safe_as_a_filename() {
313+ assert_eq!(slug("2026 Q3 / 复盘"), "2026-Q3---复盘");
314+ assert_eq!(slug("///"), "untitled");
315+ assert!(slug(&"x".repeat(200)).chars().count() <= 60);
316+ }
317+
318+ /// 真连一个 Notion workspace。**没有模拟器**——Notion 是闭源 SaaS,
319+ /// 开源的替代品(AppFlowy、AFFiNE)不说这套 API。所以这条只有在
320+ /// 有人给出真 token 时才跑,CI 上永远跳过。
321+ ///
322+ /// ```text
323+ /// # 设置 → 我的连接 → 新建内部集成,然后把一个页面分享给它
324+ /// UTOPIA_NOTION_TEST_TOKEN=ntn_xxx cargo test -p utopia-server notion
325+ /// ```
326+ #[tokio::test]
327+ async fn it_reads_from_a_real_workspace() -> anyhow::Result<()> {
328+ let Ok(token) = std::env::var("UTOPIA_NOTION_TEST_TOKEN") else {
329+ eprintln!("跳过:未设 UTOPIA_NOTION_TEST_TOKEN");
330+ return Ok(());
331+ };
332+ let (pages, _) = fetch(&token, None).await?;
333+ assert!(
334+ !pages.is_empty(),
335+ "一页都没有——integration 可能没有被分享任何页面"
336+ );
337+ let p = &pages[0];
338+ assert!(
339+ p.external_key.starts_with("notion://"),
340+ "{}",
341+ p.external_key
342+ );
343+ assert!(p.text.starts_with("# "), "正文该以标题开头");
344+ assert!(
345+ p.last_edited.is_some(),
346+ "last_edited_time 是 doc_time 的来源"
347+ );
348+ Ok(())
349+ }
350+}
modified web/src/api.ts +1 −0
@@ -189,6 +189,7 @@
189189 | "azure_blob"
190190 | "gcs"
191191 | "webdav"
192+ | "notion"
192193 | "memory"
193194 | "upload";
194195 name: string;
modified web/src/i18n/en.ts +7 −0
@@ -463,6 +463,7 @@
463463 azure_blob: "Azure Blob",
464464 gcs: "Google Cloud Storage",
465465 webdav: "WebDAV",
466+ notion: "Notion",
466467 },
467468 sourceKindHints: {
468469 folder:
@@ -491,6 +492,10 @@
491492 "Reads documents off a WebDAV share — Nextcloud, ownCloud, Synology, or anything " +
492493 "else speaking the protocol. Walks folders one level at a time; each file becomes " +
493494 "a document dated by its last modification.",
495+ notion:
496+ "Syncs the pages a Notion integration can see — share a page with the integration " +
497+ "and it appears here. Dated by when the page was last edited, which is the page's " +
498+ "own clock rather than ours.",
494499 api: "External systems push JSON documents here, authenticated with this source's own token.",
495500 custom:
496501 "Polls a URL you control on a schedule — your service returns JSON items and Utopia keeps them in sync.",
@@ -550,6 +555,8 @@
550555 davPathField: "Folder (optional — defaults to the root)",
551556 davUserField: "Username",
552557 davPassField: "Password",
558+ notionTokenField: "Internal integration token",
559+ notionQueryField: "Search term (optional — empty takes every shared page)",
553560 tokenField: "GitHub token (optional, never shown again)",
554561 includePullRequests: "Treat pull requests as tickets too",
555562 interval: "Sync schedule",
modified web/src/i18n/zh.ts +6 −0
@@ -429,6 +429,7 @@
429429 azure_blob: "Azure Blob",
430430 gcs: "Google Cloud Storage",
431431 webdav: "WebDAV",
432+ notion: "Notion",
432433 },
433434 sourceKindHints: {
434435 folder:
@@ -455,6 +456,9 @@
455456 webdav:
456457 "从 WebDAV 网盘读文档——Nextcloud、ownCloud、群晖,以及一切说这套协议的。" +
457458 "逐层走目录,每个文件成为一篇文档,日期取它最后一次修改的时刻。",
459+ notion:
460+ "同步一个 Notion 集成能看见的页面——把页面分享给集成,它就会出现在这里。" +
461+ "日期取页面最后一次编辑的时刻,那是页面自己的时钟,不是我们抓它的时刻。",
458462 api: "外部系统把 JSON 文档推送到这里,用这个来源自己的令牌认证。",
459463 custom:
460464 "按计划轮询一个你控制的 URL——你的服务返回 JSON 条目,Utopia 保持同步。",
@@ -513,6 +517,8 @@
513517 davPathField: "目录(可选——默认从根开始)",
514518 davUserField: "用户名",
515519 davPassField: "密码",
520+ notionTokenField: "内部集成令牌",
521+ notionQueryField: "搜索词(可选——留空则取全部已分享页面)",
516522 tokenField: "GitHub 令牌(可选,不再显示)",
517523 includePullRequests: "把 PR 也当工单收进来",
518524 interval: "同步计划",
modified web/src/pages/Library.tsx +40 −4
@@ -1274,6 +1274,7 @@
12741274 | "azure_blob"
12751275 | "gcs"
12761276 | "webdav"
1277+ | "notion"
12771278 >("folder");
12781279 const [name, setName] = useState("");
12791280 const [icon, setIcon] = useState<string | null>(null);
@@ -1297,6 +1298,8 @@
12971298 const [davPath, setDavPath] = useState("");
12981299 const [davUser, setDavUser] = useState("");
12991300 const [davPass, setDavPass] = useState("");
1301+ const [notionToken, setNotionToken] = useState("");
1302+ const [notionQuery, setNotionQuery] = useState("");
13001303 // PR 在 GitHub 的模型里也是工单。默认不收——问「工单」要的是工单;
13011304 // 但有些仓库的决策记录实际写在 PR 描述里,所以给个开关
13021305 const [includePrs, setIncludePrs] = useState(false);
@@ -1314,7 +1317,8 @@
13141317 kind === "s3" ||
13151318 kind === "azure_blob" ||
13161319 kind === "gcs" ||
1317- kind === "webdav";
1320+ kind === "webdav" ||
1321+ kind === "notion";
13181322
13191323 const create = useMutation({
13201324 mutationFn: () => {
@@ -1374,7 +1378,14 @@
13741378 ...(davUser.trim() ? { username: davUser.trim() } : {}),
13751379 ...(davPass ? { password: davPass } : {}),
13761380 }
1377- : {};
1381+ : kind === "notion"
1382+ ? {
1383+ token: notionToken.trim(),
1384+ ...(notionQuery.trim()
1385+ ? { query: notionQuery.trim() }
1386+ : {}),
1387+ }
1388+ : {};
13781389 return api.createSource(kbId, {
13791390 kind,
13801391 name: name.trim(),
@@ -1396,8 +1407,10 @@
13961407 ? feedUrl.trim()
13971408 : kind === "custom"
13981409 ? endpoint.trim()
1399- : kind === "webdav"
1400- ? davUrl.trim()
1410+ : kind === "notion"
1411+ ? notionToken.trim()
1412+ : kind === "webdav"
1413+ ? davUrl.trim()
14011414 : kind === "s3" || kind === "azure_blob" || kind === "gcs"
14021415 ? s3Bucket.trim()
14031416 : true);
@@ -1440,6 +1453,7 @@
14401453 "azure_blob",
14411454 "gcs",
14421455 "webdav",
1456+ "notion",
14431457 "api",
14441458 "custom",
14451459 ] as const
@@ -1714,6 +1728,28 @@
17141728 )}
17151729 </>
17161730 )}
1731+ {kind === "notion" && (
1732+ <>
1733+ {field(
1734+ S.library.notionTokenField,
1735+ <input
1736+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1737+ type="password"
1738+ placeholder="ntn_..."
1739+ value={notionToken}
1740+ onChange={(e) => setNotionToken(e.target.value)}
1741+ />,
1742+ )}
1743+ {field(
1744+ S.library.notionQueryField,
1745+ <input
1746+ className="input-dark w-full px-3 py-2 text-sm font-mono"
1747+ value={notionQuery}
1748+ onChange={(e) => setNotionQuery(e.target.value)}
1749+ />,
1750+ )}
1751+ </>
1752+ )}
17171753 {kind === "github_issues" && (
17181754 <>
17191755 {field(
modified web/src/pages/SourcesRail.tsx +2 −0
@@ -71,6 +71,7 @@
7171 azure_blob: Cloud,
7272 gcs: Cloud,
7373 webdav: FolderOpen,
74+ notion: Notebook,
7475 memory: Brain,
7576 upload: Upload,
7677 } as const;
@@ -86,6 +87,7 @@
8687 "azure_blob",
8788 "gcs",
8889 "webdav",
90+ "notion",
8991 ]);
9092
9193 export const SYNC_DOT: Record<SourceView["last_sync_status"], string> = {