ADR-0002: Single-Responsibility Protocol & Storage Module Boundaries
- Status: Accepted
- Date: 2026-11-08
- Author: ngxc
- Deciders: Alolite Core Engineering
1. Context & Problem Statement
Before this refactoring, three monolithic files (src/protocol/chat.rs at 8,275 lines / 95 pub items, src/protocol/history_sync.rs at 2,281 lines, and src/protocol/session.rs at 2,191 lines) accumulated ~70% of the entire src/protocol/ directory. This created three structural defects:
- Broken Layering:
src/protocol/history_sync.rsopenedrusqlite::ConnectionandMessageStoredirectly, whilesrc/protocol/chat.rsread/wrotethreads_cache.json(load_threads_cache/save_threads_cache), violating the pure-protocol boundary inAGENTS.md. - Split Domain Ownership: Reaction sending (
send_reaction) and seen/mute REST calls (send_seen_v2,set_unread_mark,set_mute_conversation) lived inchat.rsalongside separatereactions.rsandunread.rsmodules. - Duplicated Wire Helpers: Identical JSON unwrapping (
unwrap_data,pick_str),group_prefix stripping, control-event flattening (controls/content/ stringifieddata), monotonicclientIdgeneration, and MD5/timestamp helpers were duplicated across multiple files.
2. Decision
Decompose the protocol and persistence layers into cohesive single-responsibility modules without maintaining legacy re-export shims:
-
Shared Foundation (
src/protocol/wire.rs+src/protocol/registry/):wire.rsis the single source of truth forrequire_login,obj,unwrap_data,pick_str,val_i64,val_u64,wire_identity,is_group_flag,strip_group_prefix,iter_control_items,parse_control_data,next_client_message_id, and host helpersdomain_or/chat_send_host.registry/splits intoregistry/mod.rs(ApiDomain,CommandSpec,lookup_command, domain command constants),registry/http_table.rs(437-entry sortedCOMMAND_REGISTRY), andregistry/ws.rs(complete WebSocketcmdand close-code catalog).
-
Session Transport (
src/protocol/session/):session/mod.rs:SessionHTTP transport (reqwest,ParamCipher, candidate failover,api_get/api_post).session/domains.rs:Domainsrouting table,heal_from_verified,apply_service_map, candidate ranking.session/persistence.rs:SavedSession,LoginInfo,DeviceIdentity,save_to_file/load_from_file,official_imei.session/privacy.rs: Privacy Guard toggles (block_typing/block_delivered/block_seen),redact_*,urlencode,truncate.session/status.rs:SessionError,SessionStatus,AUTH_ERROR_CODES.
-
Domain-Grouped Protocol Subdirectories (
src/protocol/{auth,social,messaging}/):auth/:login.rs(password & server/login info),qr.rs(QR1/QR2 flow),trust/*(Curve25519/XEdDSA Trusted Companion Device crypto).social/:friends.rs(get_friends,FriendshipStatus,PhoneLookupResult,find_user_by_phone, friend requests, online status),groups.rs(get_groups,fetch_group_profiles,get_mini_profiles,get_group_history*,resolve_thread_names).messaging/:model.rs(WireMessageRef,MessageKind,DeliveryState,UnreadPolicy),threads.rs(ChatMessage,Thread,SidebarPresentation,MessageIdentityIndex,merge_thread_into,deduplicate_threads, pin/hide/delete conversation ops),send.rs(outbound text/RTF/quote/forward/recall/delete/typing),polling.rs(PollState,QueueCursor,lp_chat,get_last_msgs,get_cloud_messages,merge_previews,merge_group_history,parse_chat_message),attachments.rs(chunked image/asyncfile uploads,FileDoneRegistry, CDN URL/filename helpers),links.rs(LinkMetadata,extract_first_url,/api/message/parselink, OpenGraph HTML fallback),stickers.rs(sticker store, category detail, Vietnamese keyword search,send_sticker*),reactions.rs(send_reaction,icon_to_emoji,reaction_code_and_type),unread.rs(send_seen_v2,set_unread_mark,set_mute_conversation,get_mute_conversations,MuteControlEvent,extract_mute_controls).
-
Pure Sync vs. SQLite Storage Boundary (
src/protocol/sync/vs.src/storage/):src/protocol/sync/contains zerorusqliteorMessageStoreimports:sync/mod.rs(sync key/status state & cursor helper),sync/controls.rs(pull_mobile_msg,cancel_phone_sync,clean_sync,/api/znoise,MobileSyncControlEvent),sync/zdb4.rs(RSA-2048 sync keys &ZDB4.0decryptor),sync/bin_net.rs(BinNetTLV decoder),sync/v2_proto.rs(proto.Sync2chunk parser),sync/history.rs(thread history cloud fetch loop),sync/phone.rs(pure phone message sync & polling queue drain),sync/container.rs(mobile backup container & Sync V2 chunk download/crypto).src/storage/sync_ingest.rsandsrc/storage/thread_cache.rsown all pure SQLite archive ingestion (extract_conv_archives_from_entries,commit_conv_archives_to_store,commit_mobile_backup_to_store,commit_sync_v2_messages_to_store,commit_phone_sync_to_store,persist_thread_snapshot) andthreads_cache.jsonpersistence (load_threads_cache,save_threads_cache), free ofSessionor HTTP transport.CoreEnginecomposes protocol fetch with storage persistence.
-
Typed Protocol Boundary & UI-Free
CoreEngine(src/core/):- Public endpoints in
src/protocol/return typed structs (SendMessageReceipt,ActionAck,PollBatch,CloudMessagesPage,LastMsgsBatch,MuteSnapshot,QrScannedProfile,QrConfirmResult) instead of rawserde_json::Value. src/core/(CoreEngine,CoreEvent,CoreImageData) contains zeroeguiimports and drives both the GUI worker adapter (src/gui/worker/) and MCP/REST (src/mcp/).
- Public endpoints in
3. Mandatory Module & Boundary Rules Going Forward
- No
rusqliteor local disk cache I/O insidesrc/protocol/(exception: explicit credential persistence insession/persistence.rsand read-only media cache lookup inmessaging/stickers.rs). All SQLite queries, migrations, andthreads_cache.jsonwrites belong insrc/storage/. - All service hosts live exclusively in
src/protocol/endpoints.rs; outbound HTTP endpoints should be declared insrc/protocol/registry/and dispatched viaSession::api_get/Session::api_post. - One cohesive responsibility per file under domain subdirectories: New protocol features must join
auth/,social/,messaging/,session/,registry/, orsync/rather than adding root-level files or expandingsend.rs/threads.rs. Internal helpers shared across siblings staypub(super). - No duplicate wire/JSON helpers: Reuse
crate::protocol::wire::*(includingstrip_vn_diacritics),crate::clock::now_ms, andcrate::crypto::md5_hex_bytesinstead of reimplementing ad-hoc parsers. - Clean cutover over shims: Do not re-add deprecated wildcard re-exports; update callers directly to canonical domain paths.
- Integration fixtures vs. unit tests: Keep focused unit tests inline under
#[cfg(test)] mod tests; place multi-module integration and large binary/JSON fixture tests undertests/protocol_*.rs.