helix-im 0.1.20

基于 Helix Core 的确定性 MessageV3 IM 业务模块
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! posts 读族 outbound 扩展(bookmark / announcement / read/list)——从 posts_read.rs 外提 sibling。
//!
//! 与 `posts_read.rs` 分文件(§1 单文件 ≤300 行硬顶;posts_read.rs 已满)。
//! 注册方式与 posts_read.rs 完全相同(`inventory` + 本地 `read_cmd!` 宏)。
//! endpoint / body 真源同 posts_read.rs 头注释(mattermost csesapi 逐字,不自造 fixture)。

use serde_json::{json, Value};

use crate::error::ImError;
use crate::outbound::registry::{require_str, OutboundCommand, OutboundRegistration};
// helpers 经 pub(super) 从 posts_read 引入
use super::read::require_str_array;

/// 校验批量回执查询的公开边界,只允许 `post_ids` 与宿主追踪键 `req_id`。
fn require_post_read_list_args(args: &Value, cmd: &str) -> Result<Value, ImError> {
    let object = args
        .as_object()
        .ok_or_else(|| ImError::Parse(format!("{cmd}: payload 必须是 JSON 对象")))?;
    for key in object.keys() {
        if !matches!(key.as_str(), "post_ids" | "req_id") {
            return Err(ImError::Parse(format!("{cmd}: 未知或内部字段 '{key}'")));
        }
    }
    if let Some(req_id) = object.get("req_id") {
        if !req_id.is_string() {
            return Err(ImError::Parse(format!("{cmd}: req_id 必须是字符串")));
        }
    }
    require_str_array(args, "post_ids", cmd)
}

/// 拒绝书签命令的 user/offset 等内部字段,冻结 Helix 到最小公开边界。
fn require_bookmark_keys(args: &Value, allowed: &[&str], cmd: &str) -> Result<(), ImError> {
    let object = args
        .as_object()
        .ok_or_else(|| ImError::Parse(format!("{cmd}: payload 必须是 JSON 对象")))?;
    if let Some(unknown) = object.keys().find(|key| !allowed.contains(&key.as_str())) {
        return Err(ImError::Parse(format!("{cmd}: 未知或内部字段 '{unknown}'")));
    }
    if let Some(req_id) = object.get("req_id") {
        if req_id.as_str().is_none_or(str::is_empty) {
            return Err(ImError::Parse(format!("{cmd}: req_id 必须是非空字符串")));
        }
    }
    Ok(())
}

/// 读取 1-based bookmark 页参数;offset 不属于公开命令,因此不在此处计算或接收。
fn require_positive_page(args: &Value, key: &str, cmd: &str) -> Result<i64, ImError> {
    args.get(key)
        .and_then(Value::as_i64)
        .filter(|value| *value > 0)
        .ok_or_else(|| ImError::Parse(format!("{cmd}: {key} 必须是正整数")))
}

/// 公告列表只允许 channel、可选 post 兼容键和请求关联键。
fn require_announcement_list_keys(args: &Value, cmd: &str) -> Result<(), ImError> {
    let object = args
        .as_object()
        .ok_or_else(|| ImError::Parse(format!("{cmd}: payload 必须是 JSON 对象")))?;
    if let Some(unknown) = object
        .keys()
        .find(|key| !matches!(key.as_str(), "channel_id" | "post_id" | "req_id"))
    {
        return Err(ImError::Parse(format!("{cmd}: 未知或内部字段 '{unknown}'")));
    }
    if let Some(req_id) = object.get("req_id") {
        if req_id.as_str().is_none_or(str::is_empty) {
            return Err(ImError::Parse(format!("{cmd}: req_id 必须是非空字符串")));
        }
    }
    Ok(())
}

/// 把 Go 公告列表回包归一为带版本的绝对集合;Go 初始频道允许权威 version=0。
pub fn announcement_list_projection(channel_id: &str, body: &Value) -> Option<Value> {
    let payload = body
        .get("data")
        .filter(|value| value.is_object())
        .unwrap_or(body);
    let version = payload.get("version").and_then(Value::as_u64)?;
    let source_channel_id = payload
        .get("channelId")
        .or_else(|| payload.get("channel_id"))
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())
        .unwrap_or(channel_id);
    if source_channel_id != channel_id {
        return None;
    }
    let items = payload.get("announcements").and_then(Value::as_array)?;
    let announcements = items
        .iter()
        .map(announcement_projection)
        .collect::<Option<Vec<_>>>()?;
    Some(json!({
        "channelId": channel_id,
        "version": version,
        "announcements": announcements,
    }))
}

/// 归一公告删除的结构化回执;version=0 或显式 noOp 是合法幂等未命中。
pub fn announcement_delete_projection(channel_id: &str, body: &Value) -> Option<Value> {
    let payload = body
        .get("data")
        .filter(|value| value.is_object())
        .unwrap_or(body);
    let result_channel_id = payload
        .get("channelId")
        .or_else(|| payload.get("channel_id"))
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())?;
    if result_channel_id != channel_id {
        return None;
    }
    let deleted_id = payload
        .get("deletedAnnouncementId")
        .or_else(|| payload.get("deleted_announcement_id"))
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())?;
    let version = payload.get("version").and_then(Value::as_u64)?;
    let explicit_no_op = payload
        .get("noOp")
        .or_else(|| payload.get("no_op"))
        .or_else(|| payload.get("noop"))
        .map(Value::as_bool);
    if explicit_no_op.is_some_and(|value| value.is_none()) {
        return None;
    }
    let no_op = version == 0 || explicit_no_op.flatten().unwrap_or(false);
    let mut result = json!({
        "channelId": channel_id,
        "deletedAnnouncementId": deleted_id,
        "version": version,
    });
    if no_op {
        result["noOp"] = Value::Bool(true);
    }
    Some(result)
}

/// 将一条 Go 公告记录压缩为 Angular 所需的绝对字段;缺主键时拒绝整份快照。
fn announcement_projection(item: &Value) -> Option<Value> {
    let announcement_id = item
        .get("announcementId")
        .or_else(|| item.get("announcement_id"))
        .or_else(|| item.get("id"))
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())?;
    let post_id = item
        .get("postId")
        .or_else(|| item.get("post_id"))
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())?;
    let channel_id = item
        .get("channelId")
        .or_else(|| item.get("channel_id"))
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())?;
    let content = item
        .get("content")
        .or_else(|| item.get("message"))
        .or_else(|| item.get("simpleMessage"))
        .and_then(Value::as_str)?;
    let create_at = item
        .get("createAt")
        .or_else(|| item.get("create_at"))
        .and_then(Value::as_i64)
        .or_else(|| {
            item.get("createAt")
                .or_else(|| item.get("create_at"))
                .and_then(Value::as_u64)
                .and_then(|value| i64::try_from(value).ok())
        })?;
    let create_by = item
        .get("createBy")
        .or_else(|| item.get("create_by"))
        .or_else(|| item.get("userId"))
        .and_then(Value::as_str)?;
    Some(json!({
        "announcementId": announcement_id,
        "postId": post_id,
        "channelId": channel_id,
        "content": content,
        "createAt": create_at,
        "createBy": create_by,
    }))
}

/// 注册读命令样板(与 posts_read.rs 的 read_cmd! 同构,is_read=true)。
macro_rules! read_cmd {
    ($cmd_struct:ident, $reg:ident, $name:literal, $build:expr) => {
        struct $cmd_struct;
        impl OutboundCommand for $cmd_struct {
            fn name(&self) -> &'static str {
                $name
            }
            fn build(&self, args: &Value) -> Result<(&'static str, Value), ImError> {
                let f: fn(&Value, &'static str) -> Result<(&'static str, Value), ImError> = $build;
                f(args, $name)
            }
            fn is_read(&self) -> bool {
                true
            }
        }
        inventory::submit! {
            OutboundRegistration {
                name: $name,
                command: &$cmd_struct,
            }
        }
    };
}

// ── post/bookmark/* 读族(注意 endpoint 走 `post/`(单数)+ `/bookmark/` 子路由)────────

// #11 bookmark/create:保存书签。actor 由 Go session.currentUserId 派生,wire 只含 channel/post。
read_cmd!(
    BookmarkCreateCommand,
    BOOKMARK_CREATE_REG,
    "im_bookmark_create",
    |args, cmd| {
        require_bookmark_keys(args, &["channel_id", "post_ids", "req_id"], cmd)?;
        let channel_id = require_str(args, "channel_id", cmd)?;
        let post_ids = require_str_array(args, "post_ids", cmd)?;
        Ok((
            "post/bookmark/create",
            json!({ "channelId": channel_id, "postIds": post_ids }),
        ))
    }
);

#[cfg(test)]
mod tests {
    use super::*;

    /// 公告 list 回包必须带非负版本,并归一为固定的频道绝对集合。
    #[test]
    fn announcement_list_projection_requires_version_and_canonical_fields() {
        let body = json!({
            "status": "SUCCESS",
            "data": {
                "channelId": "c1",
                "version": 3,
                "announcements": [{
                    "announcementId": "a1",
                    "postId": "p1",
                    "channelId": "c1",
                    "content": "公告",
                    "createAt": 42,
                    "createBy": "u1",
                    "extra": "discarded"
                }]
            }
        });
        assert_eq!(
            announcement_list_projection("c1", &body),
            Some(json!({
                "channelId": "c1",
                "version": 3,
                "announcements": [{
                    "announcementId": "a1",
                    "postId": "p1",
                    "channelId": "c1",
                    "content": "公告",
                    "createAt": 42,
                    "createBy": "u1"
                }]
            }))
        );
        assert!(announcement_list_projection(
            "c1",
            &json!({
                "data": { "channelId": "c1", "announcements": [] }
            })
        )
        .is_none());
        assert!(announcement_list_projection(
            "c1",
            &json!({
                "data": {
                    "channelId": "c1",
                    "version": 3,
                    "announcements": [{ "postId": "p1" }]
                }
            })
        )
        .is_none());
        assert_eq!(
            announcement_list_projection(
                "c1",
                &json!({
                    "data": { "channelId": "c1", "version": 0, "announcements": [] }
                })
            ),
            Some(json!({ "channelId": "c1", "version": 0, "announcements": [] }))
        );
    }

    /// 公告 delete 的 Go 初始版本零与显式 noOp 都归一为成功幂等结果。
    #[test]
    fn announcement_delete_projection_accepts_version_zero_and_explicit_noop() {
        assert_eq!(
            announcement_delete_projection(
                "c1",
                &json!({
                    "data": {
                        "channelId": "c1",
                        "deletedAnnouncementId": "missing",
                        "version": 0
                    }
                })
            ),
            Some(json!({
                "channelId": "c1",
                "deletedAnnouncementId": "missing",
                "version": 0,
                "noOp": true
            }))
        );
        assert_eq!(
            announcement_delete_projection(
                "c1",
                &json!({
                    "channelId": "c1",
                    "deletedAnnouncementId": "already-gone",
                    "version": 4,
                    "no_op": true
                })
            )
            .and_then(|result| result.get("noOp").cloned()),
            Some(Value::Bool(true))
        );
        assert_eq!(
            announcement_delete_projection(
                "c1",
                &json!({
                    "channelId": "c1",
                    "deletedAnnouncementId": "go-noop",
                    "version": 0,
                    "noop": true
                })
            )
            .and_then(|result| result.get("noOp").cloned()),
            Some(Value::Bool(true))
        );
        assert_eq!(
            announcement_delete_projection(
                "c1",
                &json!({
                    "channelId": "c1",
                    "deletedAnnouncementId": "version-zero",
                    "version": 0,
                    "noOp": false
                })
            )
            .and_then(|result| result.get("noOp").cloned()),
            Some(Value::Bool(true))
        );
        assert!(announcement_delete_projection(
            "c1",
            &json!({
                "channelId": "c1",
                "deletedAnnouncementId": "bad-marker",
                "version": 0,
                "noOp": "true"
            })
        )
        .is_none());
    }

    /// 公告 delete 回包禁止跨频道结果伪装成本频道成功。
    #[test]
    fn announcement_delete_projection_rejects_wrong_channel() {
        let body = json!({
            "data": {
                "channelId": "c2",
                "deletedAnnouncementId": "a1",
                "version": 4
            }
        });
        assert!(announcement_delete_projection("c1", &body).is_none());
    }
}

// #12 bookmark/delete:删书签。channelId 与 postId 同时进入 wire,避免跨频道误删。
read_cmd!(
    BookmarkDeleteCommand,
    BOOKMARK_DELETE_REG,
    "im_bookmark_delete",
    |args, cmd| {
        require_bookmark_keys(args, &["channel_id", "post_id", "req_id"], cmd)?;
        let channel_id = require_str(args, "channel_id", cmd)?;
        let post_id = require_str(args, "post_id", cmd)?;
        Ok((
            "post/bookmark/delete",
            json!({ "channelId": channel_id, "postId": post_id }),
        ))
    }
);

// #13 bookmark/load:拉书签列表;Go 从 1-based pageNumber/pageSize 计算内部 offset。
read_cmd!(
    BookmarkLoadCommand,
    BOOKMARK_LOAD_REG,
    "im_bookmark_load",
    |args, cmd| {
        require_bookmark_keys(
            args,
            &["channel_id", "page_number", "page_size", "req_id"],
            cmd,
        )?;
        let channel_id = require_str(args, "channel_id", cmd)?;
        let page_number = require_positive_page(args, "page_number", cmd)?;
        let page_size = require_positive_page(args, "page_size", cmd)?;
        Ok((
            "post/bookmark/load",
            json!({
                "channelId": channel_id,
                "pageNumber": page_number,
                "pageSize": page_size,
            }),
        ))
    }
);

// ── post/announcement/* 读族(走 `post/`(单数)子路由)────────────────────────────

// #14 announcement/acceptList:公告接收列表。真源 {postId}(posts.go AnnouncementAcceptList)。
read_cmd!(
    AnnounceAcceptListCommand,
    ANNOUNCE_ACCEPT_LIST_REG,
    "im_announcement_accept_list",
    |args, cmd| {
        let post_id = require_str(args, "post_id", cmd)?;
        Ok(("post/announcement/acceptList", json!({ "postId": post_id })))
    }
);

// #15 announcement/list:公告列表。真源 {channelId,postId?}(前端实测 postId 实传 channelId)。
read_cmd!(
    AnnounceListCommand,
    ANNOUNCE_LIST_REG,
    "im_announcement_list",
    |args, cmd| {
        require_announcement_list_keys(args, cmd)?;
        let channel_id = require_str(args, "channel_id", cmd)?;
        let mut b = json!({ "channelId": channel_id });
        if let Some(post_id) = args.get("post_id").and_then(Value::as_str) {
            b["postId"] = json!(post_id);
        }
        Ok(("post/announcement/list", b))
    }
);

// #16 announcement/detail:公告详情。真源 {postIds:[]string}(posts.go AnnouncementDetail)。
read_cmd!(
    AnnounceDetailCommand,
    ANNOUNCE_DETAIL_REG,
    "im_announcement_detail",
    |args, cmd| {
        let post_ids = require_str_array(args, "post_ids", cmd)?;
        Ok(("post/announcement/detail", json!({ "postIds": post_ids })))
    }
);

// ── post/read/list receipt snapshot 读(走 post/ 单数)──────────────────────────────

// #17 post/read/list:批量取 post receipt snapshot。真源 entity.PostReadListParam{postIds:[]string}
// (post.go:554,postReadList → post/read/list 路由 posts.go:31);Helix 后续只投影有序 ID、
// 绝对计数和 snapshotId,Go 内部 bitmap 不进入公开事件。
read_cmd!(
    PostReadListCommand,
    POST_READ_LIST_REG,
    "im_post_read_list",
    |args, cmd| {
        let post_ids = require_post_read_list_args(args, cmd)?;
        Ok(("post/read/list", json!({ "postIds": post_ids })))
    }
);