Data Model Session Cache
Overview
Telegram/SourceFiles/data/ is Telegram Desktop's per-account in-memory domain model. The central owner is Data::Session in Telegram/…/data_session.h and Telegram/…/data_session.cpp: it is constructed from Main::Session, opens the account cache and big-file cache through Storage::DatabasePointer, then creates managers for histories, stickers, reactions, notifications, stories, saved messages/music, chat filters, streaming, and business/chatbot state. Most UI, API, storage, and update code does not allocate model objects directly; it asks this session for canonical objects by Telegram IDs, applies TL payloads into those objects, and listens to rpl::event_stream producers fired by the session or its sub-managers.
Peers are canonicalized through Data::Session::_peers and the typed ID helpers in Telegram/…/data_peer_id.h. Data::Session::peer(), user(), chat(), and channel() in data_session.cpp lazily create exactly one PeerData, UserData, ChatData, or ChannelData instance for a PeerId; peerLoaded() and typed *Loaded() variants only return objects that have been populated. PeerData in Telegram/…/data_peer.h carries shared peer state such as names, usernames, userpics, colors, emoji status, notification settings, forum/monoforum accessors, migration helpers, restriction checks, and display/update signals. UserData in Telegram/…/data_user.h adds user-specific flags, bot info, phone/contact state, last-seen, birthday, business details, story flags, premium/write restrictions, and input-user conversion. ChatData in Telegram/…/data_chat.h stores legacy group title/photo/version, participant counters, rights/restrictions, migration target, group-call info, bot commands, invite link, pending join requests, and allowed reactions. ChannelData in Telegram/…/data_channel.h models channels, megagroups, forums, monoforums, communities, locations, discussion links, membership/admin/restriction counters, PtsWaiter sequencing, revenue/paid-message hints, story permissions, and forum/community capabilities.
Raw MTProto objects are adapted into these canonical objects by Data::Session::processUser() and processChat() in data_session.cpp. These functions decode MTPUser, MTPChat, MTPDchannel, community, forbidden, empty, and minimal variants, preserve existing fields that a minimal update should not overwrite, update typed flag sets, normalize usernames, wire chat-to-channel migrations, compute story source state through Data::Stories, and emit peer update flags through the owning Main::Session changes pipeline. Bulk helpers processUsers() and processChats() first populate peers before message/dialog processing uses them.
Histories and messages are split between the data session's fast indexes and the History subsystem. Data::Histories in Telegram/…/data_histories.h owns the PeerId -> History map, coordinates API requests for dialog entries, read-inbox, delete, send, and topic creation, and postpones conflicting requests per history. Data::Session::_messages and _nonChannelMessages in data_session.h index loaded HistoryItem pointers by peer/message ID; registerMessage() in data_session.cpp maintains those maps and rejects duplicate registration by destroying the old item. processMessages() orders incoming MTPMessage values by server ID before calling addNewMessage(), which resolves the message peer with helpers from Telegram/…/data_types.h, creates/loads the peer history, and delegates actual item construction to History::addNewMessage. Data::HistoryMessages and MessagesList in Telegram/…/data_history_messages.h and Telegram/…/data_messages.h maintain sparse, queryable message ID slices for history viewers; their rpl update streams let UI slices stay live as ranges are added, removed, invalidated, or partially unknown.
Message IDs and special synthetic ranges are defined in Telegram/…/data_msg_id.h. Positive IDs below ServerMaxMsgId are server messages, very negative ranges are local client messages, story-backed message IDs, and UI sentinel positions such as ShowAtUnreadMsgId. FullMsgId pairs a PeerId with a MsgId; FullReplyTo adds quote, story, topic, monoforum, todo, and poll-option context for reply APIs and highlight navigation.
Media objects are canonicalized similarly. Data::Session owns _photos, _documents, _webpages, _polls, _todoLists, _games, _botApps, and _locations maps and exposes photo(), document(), webpage(), poll(), todoList(), etc. from data_session.h. processPhoto() / photoApplyFields() and processDocument() / documentApplyFields() in data_session.cpp translate TL media into PhotoData and DocumentData. PhotoData in Telegram/…/data_photo.h stores access hashes, file references, DC, inline thumbnails, multiple image/video CloudFile sizes, local file location, upload state, reply-preview cache, and active PhotoMedia views. DocumentData in Telegram/…/data_document.h stores remote or web location, mime/name/type, size/dimensions/date, thumbnail/video-thumbnail CloudFiles, streaming support flags, good-thumbnail state, sticker/song/voice/video additional data, cache keys, and active DocumentMedia views. Data::Session also tracks which HistoryItem or HistoryView::Element references each photo, document, webpage, game, poll, todo list, contact, call, or story so layout, repaint, load-progress, and destruction notifications can be routed to visible UI.
Web pages and rich previews are represented by WebPageData in Telegram/…/data_web_page.h. A page can point to a PhotoData, DocumentData, collage media, instant-view data, sticker-set previews, gifts, auctions, stories, and compose-tone emoji documents. WebPageData::ApplyChanges() consumes API result pages and Data::Session::notifyWebPageUpdateDelayed() batches UI notifications with game, poll, and todo-list update notifications.
Stories are managed by Data::Stories in Telegram/…/data_stories.h with individual Story instances from Telegram/…/data_story.h. Stories keep per-peer source lists, hidden/not-hidden lists, album IDs, stealth mode, read markers, lookup/resolve state, dependent messages, and viewers/reactions pagination. A Story stores owner peer, media (PhotoData, DocumentData, or group call), captions, privacy, pinned/profile flags, interaction counts, recent viewers, suggested reaction areas, URL/location/weather/channel-post overlays, repost metadata, and album membership. Data::Session links story IDs back to message items through _storyItems, and calls stories()->clear() during Data::Session::clear() after histories and message views are gone to avoid dangling story pointers in reply components.
Reactions, tags, effects, and paid reaction state live in Data::Reactions in Telegram/…/data_message_reactions.h. It requests top/recent/default/tag/effect lists from the API, resolves reaction animations and custom emoji through CustomEmojiManager, exposes update streams for reaction pickers and tag lists, schedules delayed paid reactions for messages and calls, and provides lookup helpers used by message items. Data::Session subscribes to Reactions::myTagRenamed() in its constructor and refreshes affected item views through _viewsByTag.
Chat filters and filtered dialog lists live in Data::ChatFilters in Telegram/…/data_chat_filters.h. A ChatFilter owns inclusion/exclusion rules over History* objects, pinned histories, title/icon/color, chatlist flags, and TL serialization/deserialization. The manager loads/reloads filters, applies update order and insert/remove changes, owns per-filter Dialogs::MainList instances, tracks suggested filters, chatlist invite links, "more chats" data, and whether message tags are enabled. Data::Session listens to ChatFilters::changed() and mirrors whether filters are enabled into Main::Session settings.
Notification state is split between each peer/thread and the session-level Data::NotifySettings manager in Telegram/…/data_notify_settings.h. The manager applies TL settings for notify peers, input notify peers, default categories, peers, topics, and threads; sends update/reset API calls; computes mute/sound/silent-post defaults; caches ringtone documents as DocumentMedia; tracks exception sets per default notify type; and runs a timer to unmute peers/topics when mute periods expire. Each PeerData carries its local PeerNotifySettings, while NotifySettings owns default values and exception lookup/update streams.
Storage interaction in this module is mostly cache-facing rather than persistence ownership. Data::Session::cache() and cacheBigFile() return opened cache databases initialized from Main::Session::local() paths and keys in data_session.cpp. Data::DocumentData and PhotoData expose cache keys, media keys, local file locations, and load/save operations; Data::Session::clearLocalStorage() clears local storage owned by the data layer, while Data::Session::clear() tears down in-memory objects and chat lists. Low-level cache tag constants and document/web/URL/geopoint cache-key helpers live in Telegram/…/data_types.h.
The raw/ subdirectory contains static adaptation data that is not session-owned. For example Telegram/…/raw_countries_bounds.h exposes Raw::CountryBounds() as a flat map from country code to GeoBounds, used by location-related features as immutable reference data rather than mutable account state.
Coupling
- If peer ID or message ID ranges change in Telegram/…/data_peer_id.h or Telegram/…/data_msg_id.h, verify all
Data::Sessionmaps in Telegram/…/data_session.h and message/history lookup paths in Telegram/…/data_session.cpp; the cache keys are typed only by these encoded IDs, and accidental overlap between user/chat/channel or server/local/story message ranges will route updates to the wrong object family. - If
Data::Session::processUser()orprocessChat()in Telegram/…/data_session.cpp starts applying new TL fields, also verifyPeerData,UserData,ChatData, andChannelDataflag masks in Telegram/…/data_peer.h, data_user.h, data_chat.h, and data_channel.h; these functions intentionally mask only fields present in the incoming variant, especially for minimal users/channels, so a new field can silently be lost or can incorrectly clear existing state. - If message construction, destruction, or ID changes are modified in Telegram/…/data_session.cpp, verify the
_messages,_nonChannelMessages,_dependentMessages, TTL/media-destroy maps, and view/reference registration maps declared in Telegram/…/data_session.h; UI repaint, notification, poll/story refresh, and cache cleanup depend on those indexes staying in sync withHistoryItemlifetime. - If media file-reference, thumbnail, or cache-key handling changes in Telegram/…/data_photo.h, Telegram/…/data_document.h, or Telegram/…/data_types.h, verify the corresponding
processPhoto()/processDocument()apply paths in Telegram/…/data_session.cpp; stale file references or wrong cache tags can make UI loads fail even though the in-memoryPhotoData/DocumentDataobject still exists. - If story media or story-message resolution changes in Telegram/…/data_stories.h or Telegram/…/data_story.h, verify
Data::Session::_storyItems,registerStoryItem(),refreshStoryItemViews(), and theclear()teardown order in Telegram/…/data_session.cpp; stories are referenced both as standalone sources and as resolved message/reply media. - If chat filter membership rules change in Telegram/…/data_chat_filters.h, verify
Data::Session::chatsListFor(), per-filterDialogs::MainListownership, pinned-chat order methods, and settings mirroring in Telegram/…/data_session.cpp; filter contents are stored asHistory*, not raw peer IDs, so history lifetime and filter refreshes must remain aligned. - If notification defaults or topic notification semantics change in Telegram/…/data_notify_settings.h, verify
PeerData::notify()in Telegram/…/data_peer.h and forum/topic paths inData::NotifySettings; mute state is derived from both per-peer settings and default exception sets, and topic/community parent mute propagation is handled by the manager rather than by peers alone.
Risks
- Telegram/…/data_session.cpp has order-sensitive teardown in
Data::Session::clear(): comments require forums to be cleared beforeCustomEmojiManagerand stories to be cleared after history items/views are gone. If that order is changed, forum topic cached custom emoji or story reply pointers can outlive the session data they reference and crash during destruction. - Telegram/…/data_session.cpp deliberately caps TTL timer scheduling to 24 hours in
scheduleNextTTLs()because badly wrong system clocks can makeunixtime::now()wrap into a negative timer interval. If TTL scheduling is simplified, expiring messages can assert inbase::Timeror stop being checked after a clock correction. - Telegram/…/data_session.cpp logs and destroys the old item on duplicate
registerMessage(). If callers create duplicateHistoryItemobjects for the samePeerId/MsgId, the old object is destroyed while views, reactions, media-reference maps, or dependent-message maps may still hold pointers unless unregister paths ran first.