perf(inventory): 优化物品首屏和移位记录查询
This commit is contained in:
parent
5472dc85a2
commit
565d37ccf7
|
|
@ -18,6 +18,7 @@ import org.springframework.dao.DuplicateKeyException;
|
||||||
import org.springframework.jdbc.core.RowMapper;
|
import org.springframework.jdbc.core.RowMapper;
|
||||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Isolation;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
|
@ -65,7 +66,7 @@ class InventoryService {
|
||||||
) matches GROUP BY id
|
) matches GROUP BY id
|
||||||
)
|
)
|
||||||
""";
|
""";
|
||||||
private static final String SELECT_ITEMS = """
|
private static final String ITEM_COLUMNS = """
|
||||||
SELECT i.*, COALESCE(p.path, '') AS path,
|
SELECT i.*, COALESCE(p.path, '') AS path,
|
||||||
(post.id IS NOT NULL) AS published, post.id AS post_id,
|
(post.id IS NOT NULL) AS published, post.id AS post_id,
|
||||||
ARRAY(SELECT a.alias FROM item_alias a
|
ARRAY(SELECT a.alias FROM item_alias a
|
||||||
|
|
@ -73,10 +74,10 @@ class InventoryService {
|
||||||
(SELECT photo.id FROM item_photo photo
|
(SELECT photo.id FROM item_photo photo
|
||||||
WHERE (photo.household_id,photo.item_id)=(i.household_id,i.id)
|
WHERE (photo.household_id,photo.item_id)=(i.household_id,i.id)
|
||||||
ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id
|
ORDER BY photo.created_at,photo.id LIMIT 1) AS cover_photo_id
|
||||||
FROM item i LEFT JOIN paths p ON p.household_id=i.household_id AND p.id=i.location_id
|
""";
|
||||||
|
private static final String ITEM_DECORATIONS = """
|
||||||
|
LEFT JOIN paths p ON p.household_id=i.household_id AND p.id=i.location_id
|
||||||
LEFT JOIN community_post post ON (post.household_id,post.item_id)=(i.household_id,i.id)
|
LEFT JOIN community_post post ON (post.household_id,post.item_id)=(i.household_id,i.id)
|
||||||
%s
|
|
||||||
WHERE i.household_id=:household AND i.archived_at IS NULL
|
|
||||||
""";
|
""";
|
||||||
private final JdbcClient db;
|
private final JdbcClient db;
|
||||||
private final HouseholdAccess access;
|
private final HouseholdAccess access;
|
||||||
|
|
@ -275,14 +276,22 @@ class InventoryService {
|
||||||
? "AND i.location_id IN (SELECT id FROM paths WHERE :location = ANY(ancestors))"
|
? "AND i.location_id IN (SELECT id FROM paths WHERE :location = ANY(ancestors))"
|
||||||
: "AND i.location_id = :location";
|
: "AND i.location_id = :location";
|
||||||
}
|
}
|
||||||
var query = db.sql(SCOPED_PATHS + (searching ? SEARCH_HITS : "")
|
String order = searching ? "score DESC,lower(i.name),i.id" : "lower(i.name),i.id";
|
||||||
+ SELECT_ITEMS.formatted(searching ? "JOIN hits ON hits.id=i.id" : "") + """
|
// Select a page before reading aliases, cover photos and publication details.
|
||||||
AND (NOT :favorites OR EXISTS (SELECT FROM item_preference pref
|
var query = db.sql(SCOPED_PATHS + (searching ? SEARCH_HITS : "") + """
|
||||||
WHERE (pref.household_id,pref.item_id)=(i.household_id,i.id)
|
, page AS MATERIALIZED (
|
||||||
AND pref.subject=:actor AND pref.favorite))
|
SELECT i.*%s FROM item i
|
||||||
%s
|
%s
|
||||||
ORDER BY %s lower(i.name),i.id LIMIT :limit OFFSET :offset
|
WHERE i.household_id=:household AND i.archived_at IS NULL
|
||||||
""".formatted(locationFilter, searching ? "hits.score DESC," : ""))
|
AND (NOT :favorites OR EXISTS (SELECT FROM item_preference pref
|
||||||
|
WHERE (pref.household_id,pref.item_id)=(i.household_id,i.id)
|
||||||
|
AND pref.subject=:actor AND pref.favorite))
|
||||||
|
%s
|
||||||
|
ORDER BY %s LIMIT :limit OFFSET :offset
|
||||||
|
)
|
||||||
|
""".formatted(searching ? ",hits.score" : "", searching ? "JOIN hits ON hits.id=i.id" : "",
|
||||||
|
locationFilter, order)
|
||||||
|
+ ITEM_COLUMNS + "FROM page i\n" + ITEM_DECORATIONS + "ORDER BY " + order)
|
||||||
.param("household", household).param("limit", limit).param("offset", offset)
|
.param("household", household).param("limit", limit).param("offset", offset)
|
||||||
.param("favorites", favorites).param("actor", actor);
|
.param("favorites", favorites).param("actor", actor);
|
||||||
if (location != null) {
|
if (location != null) {
|
||||||
|
|
@ -296,11 +305,15 @@ class InventoryService {
|
||||||
}
|
}
|
||||||
|
|
||||||
private Item item(UUID household, UUID id) {
|
private Item item(UUID household, UUID id) {
|
||||||
return db.sql(SCOPED_PATHS + SELECT_ITEMS.formatted("") + " AND i.id=:id")
|
return db.sql(SCOPED_PATHS + ITEM_COLUMNS + "FROM item i\n" + ITEM_DECORATIONS + """
|
||||||
|
WHERE i.household_id=:household AND i.archived_at IS NULL AND i.id=:id
|
||||||
|
""")
|
||||||
.param("household", household).param("id", id)
|
.param("household", household).param("id", id)
|
||||||
.query(ITEM).optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在"));
|
.query(ITEM).optional().orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "物品不存在"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A concurrent move can change the item and its history between these queries.
|
||||||
|
@Transactional(readOnly = true, isolation = Isolation.REPEATABLE_READ)
|
||||||
Detail detail(UUID household, String actor, UUID id) {
|
Detail detail(UUID household, String actor, UUID id) {
|
||||||
access.role(household, actor);
|
access.role(household, actor);
|
||||||
Item item = item(household, id);
|
Item item = item(household, id);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
CREATE INDEX item_active_name_order ON item(household_id, lower(name), id)
|
||||||
|
WHERE archived_at IS NULL;
|
||||||
|
|
||||||
|
CREATE INDEX item_move_recent ON item_move(household_id, item_id, id DESC);
|
||||||
|
|
@ -1,8 +1,10 @@
|
||||||
"""Validate iOS workflows in a disposable environment with a native_account row for viewer."""
|
"""Validate iOS workflows in a disposable environment with a native_account row for viewer."""
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
import os
|
import os
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
from urllib.parse import urlencode
|
from urllib.parse import urlencode
|
||||||
from uuid import uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from smoke import RUN, await_operation, call, ready
|
from smoke import RUN, await_operation, call, ready
|
||||||
|
|
||||||
|
|
@ -17,6 +19,8 @@ def verify():
|
||||||
verify_inventory_appearance(root)
|
verify_inventory_appearance(root)
|
||||||
verify_search_and_voice(root)
|
verify_search_and_voice(root)
|
||||||
verify_optional_locations(root)
|
verify_optional_locations(root)
|
||||||
|
if dsn := os.environ.get("ATLAS_SMOKE_INVENTORY_DSN"):
|
||||||
|
verify_detail_snapshot(root, dsn)
|
||||||
verify_direct_invitations(root)
|
verify_direct_invitations(root)
|
||||||
verify_location_order(root)
|
verify_location_order(root)
|
||||||
verify_location_layout(root)
|
verify_location_layout(root)
|
||||||
|
|
@ -129,6 +133,15 @@ def verify_search_and_voice(root):
|
||||||
return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))]
|
return [row["id"] for row in call("GET", root + "/items?" + urlencode({"q": term}))]
|
||||||
|
|
||||||
assert search("数据线") == [exact, alias, prefix, contains]
|
assert search("数据线") == [exact, alias, prefix, contains]
|
||||||
|
paged = [
|
||||||
|
call("GET", root + "/items?" + urlencode({"q": "数据线", "limit": 1, "offset": offset}))
|
||||||
|
for offset in range(5)
|
||||||
|
]
|
||||||
|
assert [[item["id"] for item in page] for page in paged] == [[exact], [alias], [prefix], [contains], []]
|
||||||
|
matches = call("GET", root + "/items?" + urlencode(
|
||||||
|
{"q": "数据线", "location": room, "includeDescendants": "true", "favorites": "true", "limit": 1}
|
||||||
|
))
|
||||||
|
assert len(matches) == 1 and matches[0]["id"] == exact and matches[0]["locationPath"] == "书房 / 右抽屉"
|
||||||
assert set(search("书房 / 右抽屉")) == {exact, alias, contains}
|
assert set(search("书房 / 右抽屉")) == {exact, alias, contains}
|
||||||
assert search("%") == [percent]
|
assert search("%") == [percent]
|
||||||
call("GET", root + "/items?" + urlencode({"q": "数据线"}), user="other", status=404)
|
call("GET", root + "/items?" + urlencode({"q": "数据线"}), user="other", status=404)
|
||||||
|
|
@ -212,6 +225,14 @@ def verify_optional_locations(root):
|
||||||
latest, initial = call("GET", address)["moves"]
|
latest, initial = call("GET", address)["moves"]
|
||||||
assert (initial["fromPath"], initial["toPath"]) == ("", place["name"])
|
assert (initial["fromPath"], initial["toPath"]) == ("", place["name"])
|
||||||
assert (latest["fromPath"], latest["toPath"]) == (place["name"], "")
|
assert (latest["fromPath"], latest["toPath"]) == (place["name"], "")
|
||||||
|
edit = {"name": manual["name"], "quantity": 2, "notes": "补记数量",
|
||||||
|
"aliases": ["照明,备用", "手电"], "version": moved["version"]}
|
||||||
|
call("PUT", address, edit, status=409)
|
||||||
|
revised = call("PUT", address, dict(edit, version=cleared["version"]))
|
||||||
|
detail = call("GET", address)
|
||||||
|
assert detail["item"] == revised and revised["locationId"] is None
|
||||||
|
assert revised["quantity"] == 2 and sorted(revised["aliases"]) == sorted(edit["aliases"])
|
||||||
|
assert detail["moves"] == [latest, initial]
|
||||||
|
|
||||||
name = "录入无位置手表 " + RUN
|
name = "录入无位置手表 " + RUN
|
||||||
draft = call("POST", root + "/drafts", {"text": "记录两只手表", "source": "VOICE"}, status=201)
|
draft = call("POST", root + "/drafts", {"text": "记录两只手表", "source": "VOICE"}, status=201)
|
||||||
|
|
@ -228,10 +249,58 @@ def verify_optional_locations(root):
|
||||||
assert actual["locationId"] is None and actual["locationPath"] == ""
|
assert actual["locationId"] is None and actual["locationPath"] == ""
|
||||||
with_location, = call("GET", items + "?" + urlencode({"q": payload["items"][1]["name"]}))
|
with_location, = call("GET", items + "?" + urlencode({"q": payload["items"][1]["name"]}))
|
||||||
assert with_location["locationId"] == place["id"]
|
assert with_location["locationId"] == place["id"]
|
||||||
call("DELETE", address + "?version=" + str(cleared["version"]), status=204)
|
call("DELETE", address + "?version=" + str(revised["version"]), status=204)
|
||||||
print("PASS unset positions in manual creation, search, links, move history and mixed draft confirmation", flush=True)
|
print("PASS unset positions in manual creation, search, links, move history and mixed draft confirmation", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_detail_snapshot(root, dsn):
|
||||||
|
room = call("POST", root + "/locations", {"name": "并发测试柜"}, status=201)
|
||||||
|
item = call("POST", root + "/items", {"name": "并发测试钥匙", "quantity": 1}, status=201)
|
||||||
|
detail_path = root + "/items/" + item["id"]
|
||||||
|
space_id, room_id, item_id = UUID(root.rsplit("/", 1)[1]), UUID(room["id"]), UUID(item["id"])
|
||||||
|
psql = ["psql", dsn, "-XAtq", "-v", "ON_ERROR_STOP=1"]
|
||||||
|
waiting_lock = """
|
||||||
|
SELECT EXISTS (SELECT FROM pg_locks WHERE relation='item_move'::regclass
|
||||||
|
AND database=(SELECT oid FROM pg_database WHERE datname=current_database())
|
||||||
|
AND mode='AccessShareLock' AND NOT granted);
|
||||||
|
"""
|
||||||
|
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||||
|
with subprocess.Popen(psql, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as writer:
|
||||||
|
writer.stdin.write("BEGIN; LOCK TABLE item_move IN ACCESS EXCLUSIVE MODE; SELECT 'locked';\n")
|
||||||
|
writer.stdin.flush()
|
||||||
|
assert writer.stdout.readline().strip() == "locked"
|
||||||
|
detail = pool.submit(call, "GET", detail_path)
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 8
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
probe = subprocess.run(psql, input=waiting_lock, text=True,
|
||||||
|
capture_output=True, timeout=4, check=True)
|
||||||
|
if probe.stdout.strip() == "t":
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
else:
|
||||||
|
raise AssertionError("Detail read did not reach the history query")
|
||||||
|
|
||||||
|
# Commit a move after the detail request has already read the item.
|
||||||
|
writer.stdin.write(f"""
|
||||||
|
UPDATE item SET location_id='{room_id}',version=1
|
||||||
|
WHERE household_id='{space_id}' AND id='{item_id}';
|
||||||
|
INSERT INTO item_move(household_id,item_id,from_path,to_path)
|
||||||
|
VALUES ('{space_id}','{item_id}','','并发测试柜');
|
||||||
|
COMMIT;
|
||||||
|
""")
|
||||||
|
writer.stdin.flush()
|
||||||
|
finally:
|
||||||
|
writer.stdin.close()
|
||||||
|
assert writer.wait(timeout=5) == 0
|
||||||
|
older = detail.result(timeout=10)
|
||||||
|
assert older["item"]["version"] == 0 and older["moves"] == []
|
||||||
|
latest = call("GET", detail_path)
|
||||||
|
assert latest["item"]["version"] == 1 and latest["item"]["locationId"] == str(room_id)
|
||||||
|
assert [move["toPath"] for move in latest["moves"]] == ["并发测试柜"]
|
||||||
|
print("PASS detail snapshot stays consistent while a move commits", flush=True)
|
||||||
|
|
||||||
|
|
||||||
def verify_direct_invitations(root):
|
def verify_direct_invitations(root):
|
||||||
sent = root + "/direct-invitations"
|
sent = root + "/direct-invitations"
|
||||||
inbox = "/api/households/direct-invitations"
|
inbox = "/api/households/direct-invitations"
|
||||||
|
|
|
||||||
|
|
@ -47,6 +47,21 @@ PostgreSQL `pg_trgm` 给活跃物品名称和别名提供 GIN 索引,短中文
|
||||||
|
|
||||||
当前部署用一个 SSD PostgreSQL。先按空间大小和查询长度观察网关、物品接口的 P95,再用真实类别和同音词样本检查命中。压测时分别覆盖小空间、单大空间、多空间并发和两字词。需要中文分词、拼写容错、复杂召回,或索引压测达到 PostgreSQL 的资源边界时,再用相同样本对比 Elasticsearch 的字段权重和 BM25。引入时保留 PostgreSQL 为主库,用 Outbox 增量同步并支持重建索引,服务端继续验证空间访问权限。 [Elastic 相关性调优](https://www.elastic.co/docs/troubleshoot/elasticsearch/troubleshooting-search-relevance)
|
当前部署用一个 SSD PostgreSQL。先按空间大小和查询长度观察网关、物品接口的 P95,再用真实类别和同音词样本检查命中。压测时分别覆盖小空间、单大空间、多空间并发和两字词。需要中文分词、拼写容错、复杂召回,或索引压测达到 PostgreSQL 的资源边界时,再用相同样本对比 Elasticsearch 的字段权重和 BM25。引入时保留 PostgreSQL 为主库,用 Outbox 增量同步并支持重建索引,服务端继续验证空间访问权限。 [Elastic 相关性调优](https://www.elastic.co/docs/troubleshoot/elasticsearch/troubleshooting-search-relevance)
|
||||||
|
|
||||||
|
### 物品首屏和移位记录
|
||||||
|
|
||||||
|
列表先筛选空间、归档状态、关键词、位置和收藏,再按原顺序取当前页。别名、封面、完整位置路径和发布状态在分页之后组装。空关键词的首屏可以利用 `item_active_name_order` 的空间、名称和 ID 顺序。详情中的移位记录使用 `item_move_recent`,按空间和物品定位后取最近 100 条。 [PostgreSQL 索引与排序](https://www.postgresql.org/docs/17/indexes-ordering.html)
|
||||||
|
|
||||||
|
详情的物品、移位、关联和个人评价在同一只读 `REPEATABLE READ` 事务中返回。并发移位提交时,一个请求内显示同一数据库快照。编辑和移位仍使用物品版本校验,旧版本提交返回 409。 [PostgreSQL 事务隔离](https://www.postgresql.org/docs/17/transaction-iso.html#XACT-REPEATABLE-READ)
|
||||||
|
|
||||||
|
2026-11-29 使用本机 PostgreSQL 17.12、同一空间 32,000 件物品、210 个位置和 80,000 条移位记录对比。先执行 `ANALYZE`,再用 `EXPLAIN (ANALYZE, BUFFERS)` 各执行五次,取执行计划中 `Execution Time` 的中位数。首屏 30 条记录的内容和顺序逐条一致。 [PostgreSQL 执行计划](https://www.postgresql.org/docs/17/using-explain.html)
|
||||||
|
|
||||||
|
| 查询 | 优化前 | 优化后 | 访问的共享缓冲块数 |
|
||||||
|
| --- | ---: | ---: | ---: |
|
||||||
|
| 空关键词首屏 30 条 | 34.227 ms | 0.422 ms | 551 → 83 |
|
||||||
|
| 单件物品的最近移位(该物品有 2 条) | 2.829 ms | 0.019 ms | 991 → 4 |
|
||||||
|
|
||||||
|
Flyway V18 增加两个索引。本次数据规模下额外占用约 6.6 MiB。写入活跃物品或移位时会维护对应索引。正式迁移前按环境的表规模评估建索引期间的写入等待。回退服务可保留这两个索引。
|
||||||
|
|
||||||
## 按账号邀请
|
## 按账号邀请
|
||||||
|
|
||||||
所有者按完整见物账号提交,服务端只匹配启用的原生账号。公开接口无模糊账号搜索。发送端每天最多 20 次,空间最多 20 个活跃邀请。发送返回 202,发出的有效邀请可以由发送方查看和撤销,邀请只在对应接收者的收件列表出现。收到邀请本身不会获得物品权限。
|
所有者按完整见物账号提交,服务端只匹配启用的原生账号。公开接口无模糊账号搜索。发送端每天最多 20 次,空间最多 20 个活跃邀请。发送返回 202,发出的有效邀请可以由发送方查看和撤销,邀请只在对应接收者的收件列表出现。收到邀请本身不会获得物品权限。
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue