helix-im 0.1.39

基于 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
//! 本机最近搜索/转发;身份只取运行时,读改写串行且 PersistOk 后才返回新状态。
//! 入口:Tick::Command(im_recent_history),kind=search|forward,action=read|record|remove|clear|import。
//! 运行时身份生成 scope;写请求必须回传 read 得到的 scope,targets 只含 type/id。
//! 本地确定性命令:ScopedGet → 可选 BatchUpsert → PersistOk → im:read:result。
//! 校验失败返回 ModuleError;存储失败/身份变化发出带 req_id 的读取错误并释放队列。
//! corr 在统一 PortReply 分发中消费,重复/迟到回包不再执行;模块销毁释放在途状态。
//! HTTP、WS、远程业务失败和重连:N/A;等待超时及取消由 Host 查询生命周期处理。
//! 已验证:公开 Module 单测及真实 HostStorage SQLite;PRE UI 尚未验证。
//! ponytail: 最多十条的低频偏好使用整行 JSON;不用于消息热路径或无界集合。
use crate::{error::ImError, event::MessageV3Event, module::ImModule, state::CorrelationContext};
use helix_core::{
    effect::{Effect, ScopedGetSpec, SqlValue, StorageOp, UpsertSpec},
    tick::PortOutcome,
    EffectSink,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{HashSet, VecDeque};

pub const COMMAND: &str = "im_recent_history";
const TABLE: &str = "im_recent_history";

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Target {
    #[serde(rename = "type")]
    pub kind: String,
    pub id: String,
}
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Command {
    pub kind: String,
    pub action: String,
    pub scope: Option<String>,
    #[serde(default)]
    pub targets: Vec<Target>,
    pub req_id: String,
}
#[derive(Debug, Default)]
pub struct HistoryState {
    pub busy: bool,
    pub queue: VecDeque<Command>,
}
fn scope(module: &ImModule) -> Result<String, ImError> {
    let c = &module.config;
    if c.auth_user_id.is_empty() || c.company_id.is_empty() || c.api_base_url.is_empty() {
        return Err(ImError::Parse(
            "recent history requires runtime identity".into(),
        ));
    }
    Ok(json!([c.api_base_url, c.company_id, c.auth_user_id]).to_string())
}
fn normalize(targets: Vec<Target>) -> Vec<Target> {
    let mut seen = HashSet::new();
    targets
        .into_iter()
        .filter(|t| seen.insert((t.kind.clone(), t.id.clone())))
        .take(10)
        .collect()
}
fn validate(c: &Command) -> Result<(), ImError> {
    if !["search", "forward"].contains(&c.kind.as_str())
        || !["read", "record", "remove", "clear", "import"].contains(&c.action.as_str())
        || c.req_id.is_empty()
        || c.targets.len() > 100
        || c.targets.iter().any(|t| {
            t.id.trim().is_empty()
                || t.id.len() > 512
                || !["user", "channel"].contains(&t.kind.as_str())
                || (c.kind == "forward" && t.kind != "channel")
        })
        || (c.action == "record" && c.targets.is_empty())
        || (c.action == "remove" && c.targets.len() != 1)
        || (["read", "clear"].contains(&c.action.as_str()) && !c.targets.is_empty())
    {
        return Err(ImError::Parse("invalid recent history command".into()));
    }
    Ok(())
}
pub fn handle(module: &mut ImModule, payload: &[u8], out: &mut EffectSink) -> Result<(), ImError> {
    let mut c: Command =
        serde_json::from_slice(payload).map_err(|e| ImError::Parse(e.to_string()))?;
    validate(&c)?;
    let current = scope(module)?;
    if c.action != "read" && c.scope.as_ref() != Some(&current) {
        return Err(ImError::Parse("recent history scope changed".into()));
    }
    c.scope = Some(current);
    if module.state.recent_history.queue.len() >= 64 {
        return Err(ImError::Parse("recent history queue full".into()));
    }
    module.state.recent_history.queue.push_back(c);
    start_next(module, out);
    Ok(())
}
fn start_next(module: &mut ImModule, out: &mut EffectSink) {
    if module.state.recent_history.busy {
        return;
    }
    let Some(c) = module.state.recent_history.queue.pop_front() else {
        return;
    };
    module.state.recent_history.busy = true;
    let corr = module.alloc_corr_internal();
    let op = StorageOp::ScopedGet(ScopedGetSpec {
        table: TABLE,
        scope_col: "scope",
        scope_val: SqlValue::Text(c.scope.clone().unwrap_or_default()),
        key_col: "kind",
        key_val: SqlValue::Text(c.kind.clone()),
    });
    module.state.corr_map.insert(
        corr,
        CorrelationContext::RecentHistoryRead {
            command: Box::new(c),
        },
    );
    out.push(Effect::Persist {
        corr,
        ops: vec![op],
    });
}
fn finish(module: &mut ImModule, out: &mut EffectSink) {
    module.state.recent_history.busy = false;
    start_next(module, out);
}
fn fail(module: &mut ImModule, c: &Command, out: &mut EffectSink) {
    out.push(crate::read_relay::emit_read_error(
        &c.req_id,
        "recent history storage or scope failure",
    ));
    finish(module, out);
}
fn text<'a>(row: &'a helix_core::effect::Row, col: &str) -> Option<&'a str> {
    row.iter().find_map(|(k, v)| match v {
        SqlValue::Text(s) if k == col => Some(s.as_str()),
        _ => None,
    })
}
fn emit(c: &Command, result: Value, out: &mut EffectSink) -> Result<(), ImError> {
    out.push(
        MessageV3Event::new(
            "im:read:result",
            json!({"req_id": c.req_id, "body": result}),
        )?
        .into_effect(),
    );
    Ok(())
}
pub fn read_reply(
    module: &mut ImModule,
    c: Box<Command>,
    outcome: &PortOutcome,
    out: &mut EffectSink,
) -> Result<(), ImError> {
    if scope(module).ok().as_ref() != c.scope.as_ref() {
        fail(module, &c, out);
        return Ok(());
    }
    let PortOutcome::Ok(reply) = outcome else {
        fail(module, &c, out);
        return Ok(());
    };
    let Ok(rows) = helix_core::port_codec::rows_from_reply_bytes(&reply.0) else {
        fail(module, &c, out);
        return Ok(());
    };
    let row = rows.iter().find(|r| {
        text(r, "scope") == c.scope.as_deref() && text(r, "kind") == Some(c.kind.as_str())
    });
    let existing: Vec<Target> = match row {
        Some(r) => match text(r, "items").and_then(|s| serde_json::from_str(s).ok()) {
            Some(items) => items,
            None => {
                fail(module, &c, out);
                return Ok(());
            }
        },
        None => vec![],
    };
    let items = match c.action.as_str() {
        "record" => normalize(c.targets.iter().cloned().chain(existing).collect()),
        "remove" => existing
            .into_iter()
            .filter(|t| !c.targets.contains(t))
            .collect(),
        "clear" => vec![],
        "import" if row.is_none() => normalize(c.targets.clone()),
        _ => existing,
    };
    let result = json!({"scope": c.scope, "items": items, "initialized": row.is_some() || c.action != "read"});
    if c.action == "read" || (c.action == "import" && row.is_some()) {
        emit(&c, result, out)?;
        finish(module, out);
        return Ok(());
    }
    let corr = module.alloc_corr_internal();
    let row = vec![
        (
            "scope".into(),
            SqlValue::Text(c.scope.clone().unwrap_or_default()),
        ),
        ("kind".into(), SqlValue::Text(c.kind.clone())),
        (
            "items".into(),
            SqlValue::Text(
                serde_json::to_string(&items).map_err(|e| ImError::Parse(e.to_string()))?,
            ),
        ),
    ];
    module.state.corr_map.insert(
        corr,
        CorrelationContext::RecentHistoryWrite { command: c, result },
    );
    out.push(Effect::Persist {
        corr,
        ops: vec![StorageOp::BatchUpsert(UpsertSpec {
            table: TABLE,
            rows: vec![row],
            conflict_key: None,
            exclude_from_update: vec![],
            update_guard: None,
            version_column: None,
        })],
    });
    Ok(())
}
pub fn write_reply(
    module: &mut ImModule,
    c: Box<Command>,
    result: Value,
    outcome: &PortOutcome,
    out: &mut EffectSink,
) -> Result<(), ImError> {
    if !matches!(outcome, PortOutcome::Ok(_)) || scope(module).ok().as_ref() != c.scope.as_ref() {
        fail(module, &c, out);
        return Ok(());
    }
    emit(&c, result, out)?;
    finish(module, out);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use helix_core::{
        effect::Row,
        tick::{AppCommand, PortError, ReplyBytes},
        Module, Tick,
    };
    use std::collections::HashMap;

    fn module() -> ImModule {
        ImModule::new(crate::module::ImConfig {
            auth_user_id: "actor".into(),
            company_id: "company".into(),
            api_base_url: "https://im.test".into(),
            ..Default::default()
        })
    }
    fn enqueue(m: &mut ImModule, sink: &mut EffectSink, action: &str, targets: Value) {
        let tick = Tick::Command(AppCommand::new(COMMAND, serde_json::to_vec(&json!({
            "kind":"search","action":action,"scope":scope(m).unwrap(),"targets":targets,"req_id":action
        })).unwrap()));
        assert!(m.accepts(&tick));
        m.handle(&tick, 0, sink).unwrap();
    }
    // 模拟通用 StorageOp 驱动,不复制业务规则;返回实际 rows codec。
    fn drain(
        m: &mut ImModule,
        sink: &mut EffectSink,
        db: &mut HashMap<(String, String), Row>,
        fail_write: bool,
    ) -> Vec<Value> {
        let mut effects = std::mem::take(sink);
        let mut results = vec![];
        while !effects.is_empty() {
            for effect in effects.as_slice() {
                match effect {
                    Effect::Persist { corr, ops } => {
                        let mut rows = vec![];
                        let mut failed = false;
                        for op in ops.clone() {
                            match op {
                                StorageOp::ScopedGet(spec) => {
                                    if let (SqlValue::Text(s), SqlValue::Text(k)) =
                                        (spec.scope_val, spec.key_val)
                                    {
                                        rows.extend(db.get(&(s, k)).cloned());
                                    } else {
                                        panic!("bad key")
                                    }
                                }
                                StorageOp::BatchUpsert(spec) => {
                                    if fail_write {
                                        failed = true;
                                        continue;
                                    }
                                    for row in spec.rows {
                                        db.insert(
                                            (
                                                text(&row, "scope").unwrap().into(),
                                                text(&row, "kind").unwrap().into(),
                                            ),
                                            row,
                                        );
                                    }
                                }
                                _ => panic!("unexpected op"),
                            }
                        }
                        let outcome = if failed {
                            PortOutcome::Err(PortError::Storage(1))
                        } else {
                            PortOutcome::Ok(ReplyBytes(
                                helix_core::port_codec::rows_to_reply_bytes(&rows),
                            ))
                        };
                        m.handle(
                            &Tick::PortReply {
                                corr: *corr,
                                outcome,
                            },
                            0,
                            sink,
                        )
                        .unwrap();
                    }
                    Effect::Emit { event } => {
                        results.push(serde_json::from_slice(&event.0).unwrap())
                    }
                    _ => panic!("local preference must not use network"),
                }
            }
            effects = std::mem::take(sink);
        }
        results
    }
    #[test]
    fn serial_record_limit_delete_clear_and_restart() {
        let mut m = module();
        let mut sink = EffectSink::new();
        let mut db = HashMap::new();
        let rows: Vec<_> = (0..12)
            .map(|i| json!({"type":"user","id":i.to_string()}))
            .collect();
        enqueue(&mut m, &mut sink, "record", json!(rows));
        enqueue(
            &mut m,
            &mut sink,
            "record",
            json!([{"type":"user","id":"5"}]),
        );
        assert_eq!(sink.as_slice().len(), 1);
        let results = drain(&mut m, &mut sink, &mut db, false);
        let last = &results.last().unwrap()["data"]["body"]["items"];
        assert_eq!(last.as_array().unwrap().len(), 10);
        assert_eq!(last[0]["id"], "5");
        let mut m = module();
        enqueue(&mut m, &mut sink, "read", json!([]));
        assert_eq!(
            drain(&mut m, &mut sink, &mut db, false)[0]["data"]["body"]["items"],
            *last
        );
        enqueue(
            &mut m,
            &mut sink,
            "remove",
            json!([{"type":"user","id":"5"}]),
        );
        assert_eq!(
            drain(&mut m, &mut sink, &mut db, false)[0]["data"]["body"]["items"]
                .as_array()
                .unwrap()
                .len(),
            9
        );
        enqueue(&mut m, &mut sink, "clear", json!([]));
        drain(&mut m, &mut sink, &mut db, false);
        enqueue(
            &mut m,
            &mut sink,
            "import",
            json!([{"type":"user","id":"old"}]),
        );
        assert_eq!(
            drain(&mut m, &mut sink, &mut db, false)[0]["data"]["body"]["items"],
            json!([])
        );
    }
    #[test]
    fn failed_write_keeps_old_state_and_identity_isolation() {
        let mut m = module();
        let mut sink = EffectSink::new();
        let mut db = HashMap::new();
        enqueue(
            &mut m,
            &mut sink,
            "record",
            json!([{"type":"user","id":"old"}]),
        );
        drain(&mut m, &mut sink, &mut db, false);
        enqueue(&mut m, &mut sink, "clear", json!([]));
        drain(&mut m, &mut sink, &mut db, true);
        enqueue(&mut m, &mut sink, "read", json!([]));
        assert_eq!(
            drain(&mut m, &mut sink, &mut db, false)[0]["data"]["body"]["items"][0]["id"],
            "old"
        );
        let old_scope = scope(&m).unwrap();
        m.config.auth_user_id = "other".into();
        let payload = serde_json::to_vec(
            &json!({"kind":"search","action":"clear","scope":old_scope,"req_id":"bad"}),
        )
        .unwrap();
        assert!(handle(&mut m, &payload, &mut sink).is_err());
        enqueue(&mut m, &mut sink, "read", json!([]));
        assert_eq!(
            drain(&mut m, &mut sink, &mut db, false)[0]["data"]["body"]["items"],
            json!([])
        );
        let payload = br#"{"kind":"search","action":"read","req_id":"x","account_id":"actor"}"#;
        assert!(handle(&mut m, payload, &mut sink).is_err());
    }
}