Introducing a new way to review your PRs.

Read the announcement

ayugram / ayugramdesktop

Desktop Telegram client with good customization and Ghost mode.

View on GitHub

13 documents · Updated Nov 16, 2026

docs / data-model-session-cache

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

Risks

  • Telegram/…/data_session.cpp has order-sensitive teardown in Data::Session::clear(): comments require forums to be cleared before CustomEmojiManager and 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 make unixtime::now() wrap into a negative timer interval. If TTL scheduling is simplified, expiring messages can assert in base::Timer or stop being checked after a clock correction.
  • Telegram/…/data_session.cpp logs and destroys the old item on duplicate registerMessage(). If callers create duplicate HistoryItem objects for the same PeerId/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.