mirror of
https://github.com/iamxvbaba/gramsrv.git
synced 2026-11-19 05:16:55 +03:00
fix(factcheck): preserve visibility, ordering and update delivery
This commit is contained in:
@@ -71,6 +71,11 @@ jobs:
|
||||
TELESRV_TEST_POSTGRES_DSN: postgres://inventory:inventory-test@127.0.0.1:5432/gift_inventory_test?sslmode=disable
|
||||
run: go test ./cmd/telesrv-admin -run '^(TestOperatorCommand|TestOperatorCreateRoute|TestOperatorUniqueness|TestNamedOperator|TestDemotion|TestAuditTrail)' -count=1 -timeout=5m
|
||||
|
||||
- name: Verify fact-check persistence and visibility against PostgreSQL
|
||||
env:
|
||||
TELESRV_TEST_POSTGRES_DSN: postgres://inventory:inventory-test@127.0.0.1:5432/gift_inventory_test?sslmode=disable
|
||||
run: go test ./internal/store/postgres -run '^TestChannelFactCheck' -count=1 -timeout=3m
|
||||
|
||||
admin-web:
|
||||
name: Admin web build
|
||||
runs-on: ubuntu-24.04
|
||||
|
||||
@@ -1527,15 +1527,16 @@ func (s *Service) EditFactCheck(ctx context.Context, userID int64, req domain.Ed
|
||||
}
|
||||
|
||||
// GetFactChecks 批量读取一组消息的事实核查标签(Layer 231)。
|
||||
// 读取需要频道成员身份:非成员看不到该频道的消息,自然也拿不到标签。
|
||||
// Reuse the exact-message read boundary, including public preview and cleared history.
|
||||
func (s *Service) GetFactChecks(ctx context.Context, userID, channelID int64, messageIDs []int) (domain.FactCheckList, error) {
|
||||
if s == nil || s.channels == nil || userID == 0 || channelID == 0 || len(messageIDs) == 0 {
|
||||
return domain.FactCheckList{}, nil
|
||||
}
|
||||
if _, err := s.channels.ResolveChannel(ctx, userID, channelID); err != nil {
|
||||
history, err := s.GetMessages(ctx, userID, channelID, messageIDs)
|
||||
if err != nil {
|
||||
return domain.FactCheckList{}, err
|
||||
}
|
||||
return s.channels.GetFactChecks(ctx, channelID, messageIDs)
|
||||
return domain.FactChecksForMessages(history.Messages, messageIDs), nil
|
||||
}
|
||||
|
||||
// EditMessage edits a channel/supergroup text message.
|
||||
|
||||
@@ -3,7 +3,7 @@ package domain
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -23,7 +23,7 @@ type FactCheck struct {
|
||||
Text string
|
||||
// Entities 是 Text 的富文本实体(text_url/mention/...)。
|
||||
Entities []MessageEntity
|
||||
// Hash 是稳定标识:同一条消息的同一份结论文本始终得到同一个 hash,
|
||||
// Hash 是稳定标识:同一条消息的同一份完整结论始终得到同一个 hash,
|
||||
// 客户端用它识别“这条事实核查是不是已经改过”。
|
||||
Hash int64
|
||||
}
|
||||
@@ -59,11 +59,19 @@ func isAlpha2Country(country string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// FactCheckHash 计算事实核查的稳定标识:绑定频道、消息与结论文本,
|
||||
// 同一份内容永远得到同一个值,改写文本则得到新值。
|
||||
func FactCheckHash(channelID int64, messageID int, text string) int64 {
|
||||
payload := fmt.Sprintf("%d:%d:%s", channelID, messageID, text)
|
||||
sum := sha256.Sum256([]byte(payload))
|
||||
// FactCheckHash covers every visible field, including link targets and formatting.
|
||||
// Only fixed primitive fields are encoded; Hash itself is deliberately excluded.
|
||||
func FactCheckHash(channelID int64, messageID int, check FactCheck) int64 {
|
||||
entities := append([]MessageEntity{}, check.Entities...)
|
||||
payload, _ := json.Marshal(struct {
|
||||
ChannelID int64
|
||||
MessageID int
|
||||
NeedCheck bool
|
||||
Country string
|
||||
Text string
|
||||
Entities []MessageEntity
|
||||
}{channelID, messageID, check.NeedCheck, check.Country, check.Text, entities})
|
||||
sum := sha256.Sum256(payload)
|
||||
hash := int64(binary.BigEndian.Uint64(sum[:8]) &^ (1 << 63))
|
||||
if hash == 0 {
|
||||
hash = 1
|
||||
@@ -71,6 +79,21 @@ func FactCheckHash(channelID int64, messageID int, text string) int64 {
|
||||
return hash
|
||||
}
|
||||
|
||||
func FactChecksEqual(a, b *FactCheck) bool {
|
||||
if a == nil || b == nil {
|
||||
return a == b
|
||||
}
|
||||
if a.Text != b.Text || a.Country != b.Country || a.NeedCheck != b.NeedCheck || len(a.Entities) != len(b.Entities) {
|
||||
return false
|
||||
}
|
||||
for i := range a.Entities {
|
||||
if a.Entities[i] != b.Entities[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// EditFactCheckRequest 是写一条事实核查的业务请求。
|
||||
type EditFactCheckRequest struct {
|
||||
UserID int64
|
||||
@@ -97,3 +120,22 @@ type EditFactCheckResult struct {
|
||||
type FactCheckList struct {
|
||||
FactChecks []FactCheck
|
||||
}
|
||||
|
||||
// FactChecksForMessages projects an already-authorized message batch without
|
||||
// shifting positions when a message is missing, deleted or has no verdict.
|
||||
func FactChecksForMessages(messages []ChannelMessage, ids []int) FactCheckList {
|
||||
byID := make(map[int]*FactCheck, len(messages))
|
||||
for _, msg := range messages {
|
||||
if !msg.Deleted && msg.Action == nil && msg.FactCheck != nil {
|
||||
byID[msg.ID] = msg.FactCheck
|
||||
}
|
||||
}
|
||||
out := FactCheckList{FactChecks: make([]FactCheck, len(ids))}
|
||||
for i, id := range ids {
|
||||
if check := byID[id]; check != nil {
|
||||
out.FactChecks[i] = *check
|
||||
out.FactChecks[i].Entities = append([]MessageEntity(nil), check.Entities...)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -25,20 +25,45 @@ func TestValidateFactCheck(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFactCheckHashIsStablePerMessage(t *testing.T) {
|
||||
first := FactCheckHash(42, 7, "verdict")
|
||||
if first != FactCheckHash(42, 7, "verdict") {
|
||||
first := FactCheckHash(42, 7, FactCheck{Text: "verdict"})
|
||||
if first != FactCheckHash(42, 7, FactCheck{Text: "verdict"}) {
|
||||
t.Fatal("FactCheckHash is not stable for the same message and text")
|
||||
}
|
||||
if first == FactCheckHash(42, 8, "verdict") {
|
||||
if first == FactCheckHash(42, 8, FactCheck{Text: "verdict"}) {
|
||||
t.Fatal("FactCheckHash collides across message ids")
|
||||
}
|
||||
if first == FactCheckHash(43, 7, "verdict") {
|
||||
if first == FactCheckHash(43, 7, FactCheck{Text: "verdict"}) {
|
||||
t.Fatal("FactCheckHash collides across channels")
|
||||
}
|
||||
if first == FactCheckHash(42, 7, "other verdict") {
|
||||
if first == FactCheckHash(42, 7, FactCheck{Text: "other verdict"}) {
|
||||
t.Fatal("FactCheckHash collides across texts")
|
||||
}
|
||||
if first == 0 {
|
||||
t.Fatal("FactCheckHash must never be zero")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckHashCoversVisibleContent(t *testing.T) {
|
||||
base := FactCheck{Text: "source", Country: "DE", Entities: []MessageEntity{{Type: MessageEntityTextURL, Offset: 0, Length: 6, URL: "https://example.com/a"}}}
|
||||
before := FactCheckHash(42, 7, base)
|
||||
for _, change := range []func(*FactCheck){
|
||||
func(c *FactCheck) { c.Country = "US" },
|
||||
func(c *FactCheck) { c.NeedCheck = true },
|
||||
func(c *FactCheck) { c.Entities[0].URL = "https://example.com/b" },
|
||||
func(c *FactCheck) { c.Entities[0].Type = MessageEntityBold },
|
||||
} {
|
||||
copy := base
|
||||
copy.Entities = append([]MessageEntity(nil), base.Entities...)
|
||||
change(©)
|
||||
if FactCheckHash(42, 7, copy) == before {
|
||||
t.Fatal("visible content changed without changing hash")
|
||||
}
|
||||
}
|
||||
base.Hash = 123
|
||||
if FactCheckHash(42, 7, base) != before {
|
||||
t.Fatal("stored hash affected the content hash")
|
||||
}
|
||||
if FactCheckHash(42, 7, FactCheck{Text: "x"}) != FactCheckHash(42, 7, FactCheck{Text: "x", Entities: []MessageEntity{}}) {
|
||||
t.Fatal("nil and empty entity vectors have different hashes")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,6 +275,8 @@ func messageEditErr(err error) error {
|
||||
// factCheckErr 把事实核查的领域错误映射成客户端可识别的 rpc_error。
|
||||
func factCheckErr(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrMessageNotModified):
|
||||
return messageNotModifiedErr()
|
||||
case errors.Is(err, domain.ErrMessageIDInvalid):
|
||||
return messageIDInvalidErr()
|
||||
case errors.Is(err, domain.ErrFactCheckInvalid):
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// need_check 置位时按协议只带 hash:country/text 由客户端用
|
||||
// messages.getFactCheck 懒加载;已经有结论时直接带上国家与文本。
|
||||
func tgFactCheck(check *domain.FactCheck) *tg.FactCheck {
|
||||
if check == nil {
|
||||
if check == nil || check.Hash == 0 {
|
||||
return nil
|
||||
}
|
||||
out := &tg.FactCheck{Hash: check.Hash}
|
||||
@@ -118,10 +118,10 @@ func (r *Router) onMessagesGetFactCheck(ctx context.Context, req *tg.MessagesGet
|
||||
if err != nil {
|
||||
return nil, factCheckErr(err)
|
||||
}
|
||||
out := make([]tg.FactCheck, 0, len(list.FactChecks))
|
||||
for _, check := range list.FactChecks {
|
||||
out := make([]tg.FactCheck, len(list.FactChecks))
|
||||
for i, check := range list.FactChecks {
|
||||
if projected := tgFactCheck(&check); projected != nil {
|
||||
out = append(out, *projected)
|
||||
out[i] = *projected
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
@@ -129,23 +129,10 @@ func (r *Router) onMessagesGetFactCheck(ctx context.Context, req *tg.MessagesGet
|
||||
|
||||
// factCheckUpdates 把事实核查写入产生的结果投影成 tg.Updates。
|
||||
func (r *Router) factCheckUpdates(ctx context.Context, viewerUserID int64, res domain.EditFactCheckResult) *tg.Updates {
|
||||
updates := make([]tg.UpdateClass, 0, 1)
|
||||
userIDs := make(map[int64]struct{})
|
||||
channelIDs := make(map[int64]struct{})
|
||||
if res.Event.Pts != 0 {
|
||||
if update := tgChannelUpdate(viewerUserID, res.Event); update != nil {
|
||||
updates = append(updates, update)
|
||||
}
|
||||
collectChannelUpdatePeerRefs(res.Event, res.Channel.ID, userIDs, channelIDs)
|
||||
collectChannelMessagePeerRefs(res.Message, res.Channel.ID, userIDs, channelIDs)
|
||||
}
|
||||
chats := []tg.ChatClass{tgChannelChatMin(viewerUserID, res.Channel)}
|
||||
cache := newViewerPeerCache(r)
|
||||
chats = append(chats, tgChannels(viewerUserID, cache.channelsForIDs(ctx, viewerUserID, peerIDMapKeys(channelIDs)))...)
|
||||
return &tg.Updates{
|
||||
Updates: updates,
|
||||
Users: tgUsersForViewer(viewerUserID, cache.usersForIDs(ctx, viewerUserID, peerIDMapKeys(userIDs))),
|
||||
Chats: chats,
|
||||
Date: int(r.clock.Now().Unix()),
|
||||
edit := domain.EditChannelMessageResult{
|
||||
Channel: res.Channel, Message: res.Message, Event: res.Event, Recipients: res.Recipients,
|
||||
}
|
||||
updates := r.channelEditMessageUpdates(ctx, viewerUserID, edit)
|
||||
r.enqueueChannelEditMessageFanout(ctx, viewerUserID, edit)
|
||||
return updates
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
package rpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/iamxvbaba/td/tg"
|
||||
"github.com/iamxvbaba/td/tlprofile"
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
func TestFactCheckRegressionBatchKeepsMessagePositions(t *testing.T) {
|
||||
r, _, owner, channel, post := factCheckTestRouter(t)
|
||||
ctx := WithUserID(context.Background(), owner.ID)
|
||||
peer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
||||
if _, err := r.onMessagesEditFactCheck(ctx, &tg.MessagesEditFactCheckRequest{
|
||||
Peer: peer, MsgID: post.ID, Text: tg.TextWithEntities{Text: "belongs to post"},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := r.onMessagesGetFactCheck(ctx, &tg.MessagesGetFactCheckRequest{Peer: peer, MsgID: []int{999999, post.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("requested [missing, post], got %d result(s): %+v; desktop assigns result[0] to the missing message", len(got), got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckRegressionExactProfiles(t *testing.T) {
|
||||
for layer := 225; layer <= 231; layer++ {
|
||||
t.Run(strconv.Itoa(layer), func(t *testing.T) {
|
||||
r, _, owner, channel, post := factCheckTestRouter(t)
|
||||
ctx := WithUserID(context.Background(), owner.ID)
|
||||
peer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
||||
dispatchExactLayerRPCTest(t, r, ctx, tlprofile.Profile(layer), &tg.MessagesEditFactCheckRequest{Peer: peer, MsgID: post.ID, Text: tg.TextWithEntities{Text: "verdict"}})
|
||||
dispatchExactLayerRPCTest(t, r, ctx, tlprofile.Profile(layer), &tg.MessagesGetFactCheckRequest{Peer: peer, MsgID: []int{999999, post.ID, post.ID}})
|
||||
dispatchExactLayerRPCTest(t, r, ctx, tlprofile.Profile(layer), &tg.MessagesDeleteFactCheckRequest{Peer: peer, MsgID: post.ID})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckRegressionRepeatedWriteDoesNotAllocatePts(t *testing.T) {
|
||||
r, store, owner, channel, post := factCheckTestRouter(t)
|
||||
ctx := WithUserID(context.Background(), owner.ID)
|
||||
req := &tg.MessagesEditFactCheckRequest{Peer: &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}, MsgID: post.ID, Text: tg.TextWithEntities{Text: "same verdict"}}
|
||||
if _, err := r.onMessagesEditFactCheck(ctx, req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := store.ResolveChannel(ctx, owner.ID, channel.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := r.onMessagesEditFactCheck(ctx, req); err == nil || !strings.Contains(err.Error(), "MESSAGE_NOT_MODIFIED") {
|
||||
t.Fatalf("repeat write: %v", err)
|
||||
}
|
||||
after, err := store.ResolveChannel(ctx, owner.ID, channel.ID)
|
||||
if err != nil || after.Channel.Pts != before.Channel.Pts {
|
||||
t.Fatalf("repeat write advanced pts: %d -> %d, %v", before.Channel.Pts, after.Channel.Pts, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckRegressionEntityOnlyEditChangesHash(t *testing.T) {
|
||||
r, _, owner, channel, post := factCheckTestRouter(t)
|
||||
ctx := WithUserID(context.Background(), owner.ID)
|
||||
peer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
||||
save := func(url string) tg.FactCheck {
|
||||
_, err := r.onMessagesEditFactCheck(ctx, &tg.MessagesEditFactCheckRequest{
|
||||
Peer: peer, MsgID: post.ID, Text: tg.TextWithEntities{Text: "source", Entities: []tg.MessageEntityClass{&tg.MessageEntityTextURL{Offset: 0, Length: 6, URL: url}}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := r.onMessagesGetFactCheck(ctx, &tg.MessagesGetFactCheckRequest{Peer: peer, MsgID: []int{post.ID}})
|
||||
if err != nil || len(got) != 1 {
|
||||
t.Fatalf("read: %+v %v", got, err)
|
||||
}
|
||||
return got[0]
|
||||
}
|
||||
a, b := save("https://example.com/a"), save("https://example.com/b")
|
||||
if a.Hash == b.Hash {
|
||||
t.Fatalf("link target changed but hash stayed %d: desktop ignores the new verdict", a.Hash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckRegressionDeletedMessageHidesFactCheck(t *testing.T) {
|
||||
r, store, owner, channel, post := factCheckTestRouter(t)
|
||||
ctx := WithUserID(context.Background(), owner.ID)
|
||||
peer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
||||
if _, err := r.onMessagesEditFactCheck(ctx, &tg.MessagesEditFactCheckRequest{Peer: peer, MsgID: post.ID, Text: tg.TextWithEntities{Text: "removed verdict"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.DeleteChannelMessages(ctx, domain.DeleteChannelMessagesRequest{UserID: owner.ID, ChannelID: channel.ID, IDs: []int{post.ID}, Date: 1700100999}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := r.onMessagesGetFactCheck(ctx, &tg.MessagesGetFactCheckRequest{Peer: peer, MsgID: []int{post.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, check := range got {
|
||||
if check.Text.Text != "" {
|
||||
t.Fatalf("deleted message still exposes verdict: %+v", check)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckRegressionWritePushesOtherSessions(t *testing.T) {
|
||||
r, store, owner, channel, post := factCheckTestRouter(t)
|
||||
subscriber := domain.User{ID: owner.ID + 1, AccessHash: 92, FirstName: "Subscriber"}
|
||||
r.deps.Users = &prefetchRecordingUsersService{mapUsersService: mapUsersService{users: map[int64]domain.User{owner.ID: owner, subscriber.ID: subscriber}}}
|
||||
if _, err := store.JoinChannel(context.Background(), channel.ID, subscriber.ID, 1700100000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sessions := &captureSessions{onlineUserIDs: []int64{owner.ID, subscriber.ID}, channelMembers: map[int64][]int64{channel.ID: {owner.ID, subscriber.ID}}}
|
||||
r.deps.Sessions = sessions
|
||||
bg, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go r.RunChannelFanout(bg)
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !r.channelFanout.started.Load() && time.Now().Before(deadline) {
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if !r.channelFanout.started.Load() {
|
||||
t.Fatal("fanout did not start")
|
||||
}
|
||||
ctx := WithSessionID(WithRawAuthKeyID(WithUserID(context.Background(), owner.ID), [8]byte{1, 2, 3}), 123)
|
||||
before, err := store.ResolveChannel(ctx, owner.ID, channel.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
echo, err := r.onMessagesEditFactCheck(ctx, &tg.MessagesEditFactCheckRequest{
|
||||
Peer: &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}, MsgID: post.ID, Text: tg.TextWithEntities{Text: "new verdict"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(echo.(*tg.Updates).Updates) != 1 {
|
||||
t.Fatal("current device did not receive one edit echo")
|
||||
}
|
||||
assertPush := func(wantText string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
ids := sessions.pushedUserIDs()
|
||||
if fanoutHasID(ids, owner.ID) && fanoutHasID(ids, subscriber.ID) {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
ids := sessions.pushedUserIDs()
|
||||
if !fanoutHasID(ids, owner.ID) || !fanoutHasID(ids, subscriber.ID) {
|
||||
t.Fatalf("missing online delivery: %v", ids)
|
||||
}
|
||||
updates := sessions.lastUserPush().(*tg.Updates)
|
||||
msg := updates.Updates[0].(*tg.UpdateEditChannelMessage).Message.(*tg.Message)
|
||||
check, exists := msg.GetFactcheck()
|
||||
if exists != (wantText != "") || (exists && check.Text.Text != wantText) {
|
||||
t.Fatalf("pushed fact check = %+v, exists=%v", check, exists)
|
||||
}
|
||||
if sessions.snapshot().sessionID != 123 {
|
||||
t.Fatal("origin session exclusion lost")
|
||||
}
|
||||
}
|
||||
assertPush("new verdict")
|
||||
sessions.clearMessages()
|
||||
if _, err := r.onMessagesDeleteFactCheck(ctx, &tg.MessagesDeleteFactCheckRequest{Peer: &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}, MsgID: post.ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertPush("")
|
||||
difference, err := store.ListChannelDifference(ctx, domain.ChannelDifferenceRequest{UserID: subscriber.ID, ChannelID: channel.ID, Pts: before.Channel.Pts, Limit: 10})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(difference.Events) != 2 || difference.Events[0].Message.FactCheck == nil || difference.Events[1].Message.FactCheck != nil {
|
||||
t.Fatalf("offline edit/delete recovery = %+v", difference.Events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFactCheckRegressionClearedHistoryAndBatchOrder(t *testing.T) {
|
||||
r, store, owner, channel, post := factCheckTestRouter(t)
|
||||
ctx := WithUserID(context.Background(), owner.ID)
|
||||
second, err := store.SendChannelMessage(ctx, domain.SendChannelMessageRequest{UserID: owner.ID, ChannelID: channel.ID, RandomID: 2, Message: "second", Date: post.Date + 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, msg := range []domain.ChannelMessage{post, second.Message} {
|
||||
if _, err := store.EditFactCheck(ctx, domain.EditFactCheckRequest{UserID: owner.ID, ChannelID: channel.ID, MessageID: msg.ID, Text: msg.Body}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
peer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
|
||||
checks, err := r.onMessagesGetFactCheck(ctx, &tg.MessagesGetFactCheckRequest{Peer: peer, MsgID: []int{second.Message.ID, post.ID, second.Message.ID, 999999}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(checks) != 4 || checks[0].Text.Text != "second" || checks[1].Text.Text != "post" || checks[2].Hash != checks[0].Hash || checks[3].Hash != 0 {
|
||||
t.Fatalf("ordered batch = %+v", checks)
|
||||
}
|
||||
if _, err := store.DeleteChannelHistory(ctx, domain.DeleteChannelHistoryRequest{UserID: owner.ID, ChannelID: channel.ID, MaxID: post.ID, Date: post.Date + 2}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
checks, err = r.onMessagesGetFactCheck(ctx, &tg.MessagesGetFactCheckRequest{Peer: peer, MsgID: []int{post.ID, second.Message.ID}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(checks) != 2 || checks[0].Hash != 0 || checks[1].Hash == 0 {
|
||||
t.Fatalf("cleared-history batch = %+v", checks)
|
||||
}
|
||||
}
|
||||
@@ -103,8 +103,6 @@ type ChannelStore interface {
|
||||
EditChannelMessage(ctx context.Context, req domain.EditChannelMessageRequest) (domain.EditChannelMessageResult, error)
|
||||
// EditFactCheck 写入或删除消息上的 Layer 231 事实核查标签;空文本表示删除。
|
||||
EditFactCheck(ctx context.Context, req domain.EditFactCheckRequest) (domain.EditFactCheckResult, error)
|
||||
// GetFactChecks 批量读取消息上的事实核查标签;没有标签的消息不返回。
|
||||
GetFactChecks(ctx context.Context, channelID int64, messageIDs []int) (domain.FactCheckList, error)
|
||||
DeleteChannelMessages(ctx context.Context, req domain.DeleteChannelMessagesRequest) (domain.DeleteChannelMessagesResult, error)
|
||||
DeleteChannelHistory(ctx context.Context, req domain.DeleteChannelHistoryRequest) (domain.DeleteChannelHistoryResult, error)
|
||||
DeleteChannelParticipantHistory(ctx context.Context, req domain.DeleteChannelParticipantHistoryRequest) (domain.DeleteChannelHistoryResult, error)
|
||||
|
||||
@@ -20,6 +20,9 @@ func (s *ChannelStore) EditFactCheck(_ context.Context, req domain.EditFactCheck
|
||||
return domain.EditFactCheckResult{}, err
|
||||
}
|
||||
member := s.members[req.ChannelID][req.UserID]
|
||||
if !channel.Broadcast {
|
||||
return domain.EditFactCheckResult{}, domain.ErrChannelInvalid
|
||||
}
|
||||
idx, ok := s.findMessageIndexLocked(req.ChannelID, req.MessageID)
|
||||
if !ok || s.messages[req.ChannelID][idx].Deleted || s.messages[req.ChannelID][idx].Action != nil {
|
||||
return domain.EditFactCheckResult{}, domain.ErrMessageIDInvalid
|
||||
@@ -39,10 +42,13 @@ func (s *ChannelStore) EditFactCheck(_ context.Context, req domain.EditFactCheck
|
||||
if err := domain.ValidateFactCheck(candidate); err != nil {
|
||||
return domain.EditFactCheckResult{}, err
|
||||
}
|
||||
candidate.Hash = domain.FactCheckHash(req.ChannelID, req.MessageID, candidate.Text)
|
||||
candidate.Hash = domain.FactCheckHash(req.ChannelID, req.MessageID, candidate)
|
||||
check = &candidate
|
||||
}
|
||||
date := req.Date
|
||||
if domain.FactChecksEqual(msg.FactCheck, check) {
|
||||
return domain.EditFactCheckResult{}, domain.ErrMessageNotModified
|
||||
}
|
||||
if date == 0 {
|
||||
date = msg.Date
|
||||
}
|
||||
@@ -76,25 +82,3 @@ func (s *ChannelStore) EditFactCheck(_ context.Context, req domain.EditFactCheck
|
||||
Recipients: s.activeMemberIDsLocked(req.ChannelID, 0, 0),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetFactChecks 批量读取一组消息的事实核查标签。
|
||||
func (s *ChannelStore) GetFactChecks(_ context.Context, channelID int64, messageIDs []int) (domain.FactCheckList, error) {
|
||||
if channelID == 0 || len(messageIDs) == 0 {
|
||||
return domain.FactCheckList{}, nil
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
out := make([]domain.FactCheck, 0, len(messageIDs))
|
||||
for _, id := range messageIDs {
|
||||
idx, ok := s.findMessageIndexLocked(channelID, id)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
msg := s.messages[channelID][idx]
|
||||
if msg.FactCheck == nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, *msg.FactCheck)
|
||||
}
|
||||
return domain.FactCheckList{FactChecks: out}, nil
|
||||
}
|
||||
|
||||
@@ -31,6 +31,11 @@ func cloneChannelMessage(in domain.ChannelMessage) domain.ChannelMessage {
|
||||
in.Forward = cloneMessageForward(in.Forward)
|
||||
in.ReplyMarkup = cloneReplyMarkup(in.ReplyMarkup)
|
||||
in.RichMessage = cloneRichMessage(in.RichMessage)
|
||||
if in.FactCheck != nil {
|
||||
check := *in.FactCheck
|
||||
check.Entities = append([]domain.MessageEntity(nil), check.Entities...)
|
||||
in.FactCheck = &check
|
||||
}
|
||||
in.Discussion = cloneChannelDiscussionRef(in.Discussion)
|
||||
in.Replies = cloneChannelMessageReplies(in.Replies)
|
||||
in.Reactions = cloneChannelMessageReactionsPtr(in.Reactions)
|
||||
|
||||
@@ -2,9 +2,12 @@ package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
@@ -31,7 +34,7 @@ func (s *ChannelStore) EditFactCheck(ctx context.Context, req domain.EditFactChe
|
||||
if err := domain.ValidateFactCheck(candidate); err != nil {
|
||||
return domain.EditFactCheckResult{}, err
|
||||
}
|
||||
candidate.Hash = domain.FactCheckHash(req.ChannelID, req.MessageID, candidate.Text)
|
||||
candidate.Hash = domain.FactCheckHash(req.ChannelID, req.MessageID, candidate)
|
||||
check = &candidate
|
||||
}
|
||||
if req.Date == 0 {
|
||||
@@ -59,6 +62,9 @@ func (s *ChannelStore) EditFactCheck(ctx context.Context, req domain.EditFactChe
|
||||
if err != nil {
|
||||
return domain.EditFactCheckResult{}, err
|
||||
}
|
||||
if !channel.Broadcast {
|
||||
return domain.EditFactCheckResult{}, domain.ErrChannelInvalid
|
||||
}
|
||||
msg, err := s.getChannelMessage(ctx, tx, req.ChannelID, req.MessageID)
|
||||
if err != nil {
|
||||
return domain.EditFactCheckResult{}, err
|
||||
@@ -69,21 +75,27 @@ func (s *ChannelStore) EditFactCheck(ctx context.Context, req domain.EditFactChe
|
||||
if msg.SenderUserID != req.UserID && !canEditChannelMessage(member) {
|
||||
return domain.EditFactCheckResult{}, domain.ErrFactCheckForbidden
|
||||
}
|
||||
if domain.FactChecksEqual(msg.FactCheck, check) {
|
||||
return domain.EditFactCheckResult{}, domain.ErrMessageNotModified
|
||||
}
|
||||
pts, err := s.reserveChannelPts(ctx, tx, req.ChannelID)
|
||||
if err != nil {
|
||||
return domain.EditFactCheckResult{}, fmt.Errorf("allocate channel fact check pts: %w", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
msg, err = scanChannelMessage(tx.QueryRow(ctx, `
|
||||
UPDATE channel_messages
|
||||
SET factcheck = $3,
|
||||
pts = $4,
|
||||
updated_at = now()
|
||||
WHERE channel_id = $1 AND id = $2 AND NOT deleted`,
|
||||
req.ChannelID, req.MessageID, string(payload), pts); err != nil {
|
||||
WHERE channel_id = $1 AND id = $2 AND NOT deleted
|
||||
RETURNING `+channelMessageColumns,
|
||||
req.ChannelID, req.MessageID, string(payload), pts))
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.EditFactCheckResult{}, domain.ErrMessageIDInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return domain.EditFactCheckResult{}, fmt.Errorf("update channel fact check: %w", err)
|
||||
}
|
||||
msg.FactCheck = check
|
||||
msg.Pts = pts
|
||||
event := domain.ChannelUpdateEvent{
|
||||
ChannelID: req.ChannelID,
|
||||
Type: domain.ChannelUpdateEditMessage,
|
||||
@@ -103,43 +115,7 @@ WHERE channel_id = $1 AND id = $2 AND NOT deleted`,
|
||||
return domain.EditFactCheckResult{}, fmt.Errorf("commit edit fact check: %w", err)
|
||||
}
|
||||
committed = true
|
||||
channel.Pts = pts
|
||||
recipients, _ := s.ListActiveChannelMemberIDs(ctx, req.UserID, req.ChannelID, 0)
|
||||
return domain.EditFactCheckResult{Channel: channel, Message: msg, FactCheck: check, Event: event, Recipients: recipients}, nil
|
||||
}
|
||||
|
||||
// GetFactChecks 批量读取一组消息的事实核查标签。
|
||||
// 没有标签的消息不出现在结果里,因此顺序由请求决定、长度可能更短。
|
||||
func (s *ChannelStore) GetFactChecks(ctx context.Context, channelID int64, messageIDs []int) (domain.FactCheckList, error) {
|
||||
if channelID == 0 || len(messageIDs) == 0 {
|
||||
return domain.FactCheckList{}, nil
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT id, factcheck::text
|
||||
FROM channel_messages
|
||||
WHERE channel_id = $1 AND id = ANY($2::int[]) AND factcheck <> '{}'::jsonb`,
|
||||
channelID, messageIDs)
|
||||
if err != nil {
|
||||
return domain.FactCheckList{}, fmt.Errorf("read channel fact checks: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make([]domain.FactCheck, 0, len(messageIDs))
|
||||
for rows.Next() {
|
||||
var id int
|
||||
var raw string
|
||||
if err := rows.Scan(&id, &raw); err != nil {
|
||||
return domain.FactCheckList{}, fmt.Errorf("scan channel fact check: %w", err)
|
||||
}
|
||||
check, err := decodeFactCheck(raw)
|
||||
if err != nil {
|
||||
return domain.FactCheckList{}, err
|
||||
}
|
||||
if check == nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, *check)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return domain.FactCheckList{}, fmt.Errorf("read channel fact checks: %w", err)
|
||||
}
|
||||
return domain.FactCheckList{FactChecks: out}, nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
appchannels "telesrv/internal/app/channels"
|
||||
"telesrv/internal/domain"
|
||||
)
|
||||
|
||||
@@ -101,13 +102,29 @@ func TestChannelFactCheckSurvivesReadPaths(t *testing.T) {
|
||||
}
|
||||
|
||||
// 批量读取返回同一条结论。
|
||||
list, err := channels.GetFactChecks(ctx, channelID, []int{post.Message.ID})
|
||||
list, err := appchannels.NewService(channels).GetFactChecks(ctx, owner.ID, channelID, []int{post.Message.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("getFactChecks: %v", err)
|
||||
}
|
||||
if len(list.FactChecks) != 1 || list.FactChecks[0].Text != "The claim is false." {
|
||||
t.Fatalf("getFactChecks = %+v", list.FactChecks)
|
||||
}
|
||||
service := appchannels.NewService(channels)
|
||||
ordered, err := service.GetFactChecks(ctx, member.ID, channelID, []int{999999, post.Message.ID, post.Message.ID})
|
||||
if err != nil || len(ordered.FactChecks) != 3 || ordered.FactChecks[0].Hash != 0 || ordered.FactChecks[1].Hash != got.Hash || ordered.FactChecks[2].Hash != got.Hash {
|
||||
t.Fatalf("ordered/duplicate batch = %+v, %v", ordered, err)
|
||||
}
|
||||
if _, err := channels.DeleteChannelHistory(ctx, domain.DeleteChannelHistoryRequest{UserID: member.ID, ChannelID: channelID, MaxID: post.Message.ID, Date: 1_700_100_450}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cleared, err := service.GetFactChecks(ctx, member.ID, channelID, []int{post.Message.ID})
|
||||
if err != nil || len(cleared.FactChecks) != 1 || cleared.FactChecks[0].Hash != 0 {
|
||||
t.Fatalf("cleared history verdict = %+v, %v", cleared, err)
|
||||
}
|
||||
ownerRead, err := service.GetFactChecks(ctx, owner.ID, channelID, []int{post.Message.ID})
|
||||
if err != nil || ownerRead.FactChecks[0].Hash == 0 {
|
||||
t.Fatalf("other viewer lost verdict: %+v, %v", ownerRead, err)
|
||||
}
|
||||
|
||||
// 删除后标签消失。
|
||||
if _, err := channels.EditFactCheck(ctx, domain.EditFactCheckRequest{
|
||||
@@ -122,4 +139,28 @@ func TestChannelFactCheckSurvivesReadPaths(t *testing.T) {
|
||||
if history.Messages[0].FactCheck != nil {
|
||||
t.Fatalf("message still carries a fact check: %+v", history.Messages[0].FactCheck)
|
||||
}
|
||||
// A fresh store reads both committed edits from the durable channel stream.
|
||||
difference, err := NewChannelStore(pool).ListChannelDifference(ctx, domain.ChannelDifferenceRequest{UserID: owner.ID, ChannelID: channelID, Pts: res.Event.Pts - 1, Limit: 20})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var editChecks []*domain.FactCheck
|
||||
for _, event := range difference.Events {
|
||||
if event.Type == domain.ChannelUpdateEditMessage {
|
||||
editChecks = append(editChecks, event.Message.FactCheck)
|
||||
}
|
||||
}
|
||||
if len(editChecks) != 2 || editChecks[0] == nil || editChecks[1] != nil {
|
||||
t.Fatalf("durable edit/delete snapshots = %+v", editChecks)
|
||||
}
|
||||
if _, err := channels.EditFactCheck(ctx, domain.EditFactCheckRequest{UserID: owner.ID, ChannelID: channelID, MessageID: post.Message.ID, Text: "must disappear with the message"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := channels.DeleteChannelMessages(ctx, domain.DeleteChannelMessagesRequest{UserID: owner.ID, ChannelID: channelID, IDs: []int{post.Message.ID}, Date: 1_700_100_600}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
deleted, err := service.GetFactChecks(ctx, owner.ID, channelID, []int{post.Message.ID})
|
||||
if err != nil || len(deleted.FactChecks) != 1 || deleted.FactChecks[0].Hash != 0 {
|
||||
t.Fatalf("deleted message verdict = %+v, %v", deleted, err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user