Skip to content

Commit a4201ee

Browse files
Wayland Yangclaude
authored andcommitted
Merge dev into fix/sync-custom-charge-cap
Keeps dev's reads_by_timestamp for the three ticket sources (deeplethe#1508 added gitlab_issues) and the custom checkpoint from this branch beside it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 parents 9b06c4c + 4ed8a59 commit a4201ee

70 files changed

Lines changed: 4248 additions & 467 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.env.example‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ UTOPIA_OPEN_REGISTRATION=true
5757
# 池子小于并发时症状是请求变慢、而不是任何一处说"池子不够"——调高 worker
5858
# 并发时一并考虑这里,也别超过 Postgres 自己的 max_connections(默认 100)。
5959
# UTOPIA_DB_MAX_CONNECTIONS=32
60+
# 被取代的分块(文档新版本不再带的段落)把向量留几天。留空即可——向量一直留着,as-of 的
61+
# 向量检索倒回多久都找得到。设了之后每天清一次超过这个天数的向量,行与正文不动;代价是
62+
# 倒回到更早时刻的向量检索找不到那些被替换的段落。取值收在 1 到 3650 之间。
63+
# 每次同步都整批重推的大库才用得上(0019)。
64+
# UTOPIA_SUPERSEDED_VECTOR_DAYS=30
6065

6166
# --- 以下几项由 docker-compose 读取,不是应用配置 ---
6267
# 数据库口令。默认值只适合本机开发,公开部署务必改。

‎crates/utopia-cli/src/main.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ struct ManifestDataDir {
8282
/// not a side effect of a code change.
8383
// 是迁移文件的**个数**,不是最大的编号(守卫 `schema_version_policy_compares_against_current`
8484
// 按个数比):编号有空缺时两者不同——0071 由一个开放 PR 占着,0072 先落,个数是 71
85-
const CURRENT_SCHEMA_VERSION: u32 = 112;
85+
const CURRENT_SCHEMA_VERSION: u32 = 113;
8686

8787
#[tokio::main]
8888
async fn main() -> anyhow::Result<()> {

‎crates/utopia-core/src/config.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ pub struct AppConfig {
4646
/// `UTOPIA_OIDC_ALLOWED_DOMAINS` 自动开户);打开就是身份提供方出事时的后门。
4747
/// `UTOPIA_PASSWORD_LOGIN`
4848
pub password_login: bool,
49+
/// 被取代的分块把向量留几天。缺省不设:向量一直留着(0019 开放问题②),as-of 的
50+
/// 向量检索倒回多久都找得到。设了之后每天清一次,行与正文不动。取值收在 1 到 3650
51+
/// 之间(`retention::window`)。`UTOPIA_SUPERSEDED_VECTOR_DAYS`
52+
pub superseded_vector_days: Option<i64>,
4953
}
5054

5155
impl Default for AppConfig {
@@ -64,6 +68,7 @@ impl Default for AppConfig {
6468
cookie_secure: false,
6569
open_registration: true,
6670
password_login: true,
71+
superseded_vector_days: None,
6772
}
6873
}
6974
}
@@ -184,9 +189,11 @@ mod tests {
184189
Jail::expect_with(|jail| {
185190
jail.set_env("UTOPIA_DB_MAX_CONNECTIONS", "");
186191
jail.set_env("UTOPIA_COOKIE_SECURE", "");
192+
jail.set_env("UTOPIA_SUPERSEDED_VECTOR_DAYS", "");
187193
let cfg = AppConfig::load().unwrap();
188194
assert_eq!(cfg.db_max_connections, None);
189195
assert!(!cfg.cookie_secure);
196+
assert_eq!(cfg.superseded_vector_days, None);
190197
Ok(())
191198
});
192199
}
@@ -197,9 +204,11 @@ mod tests {
197204
Jail::expect_with(|jail| {
198205
jail.set_env("UTOPIA_DB_MAX_CONNECTIONS", "8");
199206
jail.set_env("UTOPIA_COOKIE_SECURE", "true");
207+
jail.set_env("UTOPIA_SUPERSEDED_VECTOR_DAYS", "30");
200208
let cfg = AppConfig::load().unwrap();
201209
assert_eq!(cfg.db_max_connections, Some(8));
202210
assert!(cfg.cookie_secure);
211+
assert_eq!(cfg.superseded_vector_days, Some(30));
203212
Ok(())
204213
});
205214
}

‎crates/utopia-core/src/models.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,8 @@ pub enum SourceKind {
311311
GithubRepo,
312312
/// gitlab.com 项目默认分支的文件(#1327);自建 GitLab 没有验证过
313313
GitlabRepo,
314+
/// gitlab.com 项目的工单与合并请求(#1327);自建 GitLab 没有验证过
315+
GitlabIssues,
314316
JiraIssues,
315317
S3,
316318
AzureBlob,

‎crates/utopia-server/src/api/graph_routes.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,9 @@ pub struct EntitySearchQuery {
135135
/// 不给就是当下
136136
#[serde(default)]
137137
pub as_of: Option<String>,
138+
/// 只要名字完全相同的(规范名或现行别名),不扫整个库;不给就是子串搜索
139+
#[serde(default)]
140+
pub exact: bool,
138141
}
139142

140143
pub async fn search_entities(
@@ -158,6 +161,7 @@ pub async fn search_entities(
158161
query.limit.unwrap_or(10).clamp(1, 100),
159162
query.offset.unwrap_or(0).max(0),
160163
as_of,
164+
query.exact,
161165
)
162166
.await?;
163167
Ok(Json(json!({ "entities": entities, "total": total })))

‎crates/utopia-server/src/api/sources_routes.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,9 @@ pub async fn sync_now(
413413

414414
#[derive(Deserialize)]
415415
pub struct IngestBody {
416+
/// 墓碑带着 external_id 时用不上文件名(身份是 external_id),缺了也收;
417+
/// 其余情况仍然必填,空串在下面的校验里挡
418+
#[serde(default)]
416419
pub filename: String,
417420
/// 墓碑推送(`deleted: true`)可以不带 content——指南一直这么写,而字段
418421
/// 从前是必填,缺了就在反序列化那一步被拒。其余情况仍然必填:空串在

‎crates/utopia-server/src/api/sources_statements_tests.rs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,42 @@ async fn a_tombstone_marks_the_item_missing_and_a_new_push_revives_it() -> anyho
595595
f.cleanup().await
596596
}
597597

598+
/// api 来源的墓碑按 external_id 认身份,不用再带文件名;正常推送缺文件名照旧不收
599+
#[tokio::test]
600+
async fn an_api_tombstone_needs_only_its_external_id() -> anyhow::Result<()> {
601+
let Some(f) = Fixture::new().await? else {
602+
return Ok(());
603+
};
604+
let (status, body) = f
605+
.push_api(&json!({ "filename": "note-7.md", "content": "Kitchen inventory.", "external_id": "note-7" }))
606+
.await?;
607+
assert_eq!(status, StatusCode::OK, "{body}");
608+
let (status, body) = f
609+
.push_api(&json!({ "external_id": "note-7", "deleted": true }))
610+
.await?;
611+
assert_eq!(status, StatusCode::OK, "{body}");
612+
assert_eq!(body["action"], "marked_missing");
613+
// 回复对没推过的 id 也是 marked_missing,所以要看文档本身真的标了
614+
let doc = documents::find_by_external_key(&f.pool, f.api_source, "api:note-7")
615+
.await?
616+
.expect("the tombstone marks the document, it does not delete it");
617+
let (missing,): (bool,) =
618+
sqlx::query_as("SELECT missing_since IS NOT NULL FROM documents WHERE id = $1")
619+
.bind(doc.id)
620+
.fetch_one(&f.pool)
621+
.await?;
622+
assert!(missing, "api:note-7 is marked missing");
623+
let (status, body) = f
624+
.push_api(&json!({ "content": "Kitchen inventory.", "external_id": "note-8" }))
625+
.await?;
626+
assert_ne!(
627+
status,
628+
StatusCode::OK,
629+
"a push with content still needs its filename: {body}"
630+
);
631+
f.cleanup().await
632+
}
633+
598634
/// 密钥的查看和轮换对 `statements` 来源和 `api` 来源一样可用:创建时给过一次的密钥
599635
/// 之后还查得到,轮换后旧密钥立刻失效、新密钥能推。端到端跑服务时抓到的:这两个接口
600636
/// 原来只认 `api`

‎crates/utopia-server/src/api/token_read_tests.rs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,3 +402,53 @@ async fn an_external_id_prefix_docs_underscore_finds_docs_a_md_but_not_docsxa_md
402402
);
403403
Ok(())
404404
}
405+
406+
#[tokio::test]
407+
async fn an_exact_name_search_by_a_read_token_returns_only_that_entity() -> anyhow::Result<()> {
408+
let Some(f) = Fixture::new().await? else {
409+
return Ok(());
410+
};
411+
let result = async {
412+
sqlx::query(
413+
"INSERT INTO entities(id,kb_id,type_id,canonical_name)
414+
VALUES ($1,$2,$3,'Zhang San Jr')",
415+
)
416+
.bind(Uuid::now_v7())
417+
.bind(f.kb)
418+
.bind(f.person)
419+
.execute(&f.pool)
420+
.await?;
421+
let token = f.read_token(f.kb).await;
422+
let mut answers = Vec::new();
423+
for suffix in ["", "&exact=true"] {
424+
let request = Request::get(format!(
425+
"/api/v1/kbs/{}/entities?q=zhang%20san{suffix}",
426+
f.kb
427+
))
428+
.header("authorization", format!("Bearer {token}"))
429+
.body(Body::empty())?;
430+
let response = f.app.clone().oneshot(request).await?;
431+
anyhow::ensure!(
432+
response.status() == StatusCode::OK,
433+
"{suffix}: {}",
434+
response.status()
435+
);
436+
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await?;
437+
answers.push(serde_json::from_slice::<serde_json::Value>(&bytes)?);
438+
}
439+
anyhow::ensure!(
440+
answers[0]["total"] == 2,
441+
"without exact both are found: {}",
442+
answers[0]
443+
);
444+
anyhow::ensure!(
445+
answers[1]["total"] == 1 && answers[1]["entities"][0]["id"] == json!(f.entity),
446+
"with exact only Zhang San is found: {}",
447+
answers[1]
448+
);
449+
Ok(())
450+
}
451+
.await;
452+
f.cleanup().await?;
453+
result
454+
}

‎crates/utopia-server/src/api/tools_graph.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,8 @@ async fn lookup(
471471
// 现在算——和现状一致,回放图上的搜索框另走 `/kbs/{id}/entities` 自己挂
472472
// 时刻
473473
let (hits, total) =
474-
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, raw, 8, 0, None).await?;
474+
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, raw, 8, 0, None, false)
475+
.await?;
475476
if !hits.is_empty() {
476477
return Ok((hits, Some(total)));
477478
}
@@ -482,7 +483,7 @@ async fn lookup(
482483
let mut pool: Vec<GraphNode> = Vec::new();
483484
for w in &words {
484485
let (found, _) =
485-
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, w, 40, 0, None)
486+
utopia_store::graph::search_entities(&ctx.state.pool, ctx.kb_id, w, 40, 0, None, false)
486487
.await?;
487488
for n in found {
488489
if !pool.iter().any(|p| p.id == n.id) {

‎crates/utopia-server/src/github_repo_sync_tests.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,46 @@ async fn a_repository_sync_takes_each_changed_file_once() -> anyhow::Result<()>
124124
"没变又取了 {refetched} 次"
125125
);
126126

127+
let original = doc(PACKS).await?.unwrap();
128+
let content = state.blob.get(&original.sha256).await?;
129+
let versions = utopia_store::documents::versions(&pool, original.id)
130+
.await?
131+
.len();
132+
utopia_store::documents::delete(&pool, kb, original.id, None).await?;
133+
assert!(doc(PACKS).await?.unwrap().deleted_at.is_some());
134+
135+
let seen = server.received_requests().await.unwrap().len();
136+
let restored = sync().await?;
137+
let document = doc(PACKS).await?.unwrap();
138+
anyhow::ensure!(
139+
document.deleted_at.is_none(),
140+
"unchanged GitHub file stayed in the trash"
141+
);
142+
assert_eq!((restored.created, restored.updated), (0, 1));
143+
assert_eq!(document.id, original.id);
144+
assert_eq!(state.blob.get(&document.sha256).await?, content);
145+
assert_eq!(
146+
utopia_store::documents::versions(&pool, document.id)
147+
.await?
148+
.len(),
149+
versions
150+
);
151+
let blob_path = format!("/git/blobs/{}", crate::github_repo::git_blob_sha(&content));
152+
for request in &server.received_requests().await.unwrap()[seen..] {
153+
let path = request.url.path();
154+
assert!(
155+
path.ends_with("/git/trees/HEAD")
156+
|| path.ends_with(&blob_path)
157+
|| (path.ends_with("/commits")
158+
&& request
159+
.url
160+
.query_pairs()
161+
.any(|(k, v)| k == "path" && v == PACKS)),
162+
"the restore sync refetched an unchanged live file: {}",
163+
request.url,
164+
);
165+
}
166+
127167
*stage.lock().unwrap() = 1;
128168
sync().await?;
129169
let missing = || async { anyhow::Ok(doc(PACKS).await?.unwrap().missing_since) };

0 commit comments

Comments
 (0)