# Data layer interface (for UI code) Namespace `dp`, includes relative to `src/`. Threading: every callback and every state mutation runs on the SDL main thread (`UiQueue::drain()` in the main loop). A cancelled call (`token->cancel()`) never calls back. Calls that fail before any network (no token) call back asynchronously via `UiQueue`. ```cpp template using Done = std::function)>; // api/ApiTypes.hpp // Result: ok(), value(), error(). Result = "void" result. CancelPtr = shared_ptr struct Error { enum class Kind { Offline, Timeout, Http, Api, Decode, Cancelled, Unauthorized, Local } kind; int status; std::string message; bool isSpecific; }; ``` Show an error: `AlertMessage a = AlertMessage::presentedError(error);` (core/AlertMessage.hpp: fields `isPresented, title, message, buttonText`; `none()`, `presentedError(const std::string&)`, `presentedError(const Error&)`, `presentedMessage(const std::string&)`). Cancelled gives no alert; API-class errors with status and a non-specific message show "(status) message". ## Picking the implementation ```cpp DevPlaceApi& api = useMock ? static_cast(MockDevPlaceApi::shared()) // api/mock/MockDevPlaceApi.hpp : static_cast(ProdDevPlaceApi::shared()); // api/ProdDevPlaceApi.hpp ``` `NetworkService::instance().start()` must have run for the prod API. `MockDevPlaceApi::setDelayScale(double)` (0 = fast). ## api/DevPlaceApi.hpp (abstract, every method returns CancelPtr) `using Str = std::optional;` ``` logIn(email, password, Done) // sets AppState token and currentUser signUp(username, email, password, confirmPassword, const BirthDate&, bool acceptTerms, Done) deleteAccount(password, Done) feed(const std::optional& before, Done) feed(Done) // first page postDetail(slug, Done) createPost(Str title, optional, content, vector attachments, Str pollQuestion, vector pollOptions, Str projectLink, Done) editPost(slug, title, PostTopic, content, projectLink, Done) deletePost(slug, Done) createComment(TargetType, targetId, content, Str parentId, vector, Done) editComment(uid, content, Done) deleteComment(uid, Done) profile(Str username, Done) // nullopt = own profile (needs token) followUser / unfollowUser / blockUser / unblockUser / muteUser / unmuteUser (username, Done) messages(Str withUid, Done) messages(Done) sendMessage(receiverId, content, vector, Done) unique_ptr makeMessagesSocket(otherUserId) usersForMentioning(query, Done) notifications(const optional& before, Done) notifications(Done) openNotification(uid, Done) notificationCounts(Done) markNotificationRead(uid, Done) markAllNotificationsRead(Done) registerPushDevice(deviceToken, Done) unregisterPushDevice(deviceToken, Done) vote(TargetType, targetId, Vote, Done) // backend toggles: always send Vote::Up to add/remove an upvote submitPollChoice(pollId, optionId, Done) react(TargetType, targetId, emoji, Done) reportReasons(Done>) report(TargetType, targetId, reason, Str detail, Done) uploadFile(const std::string& bytes, filename, mimeType, Done) uploadFromUrl(url, Str filename, Done) deleteAttachment(uid, Done) refreshTokenIfNeeded(Done) // called internally before every authenticated request ``` Derived classes hide the convenience overloads: call them through a `DevPlaceApi&`, or add `using DevPlaceApi::feed;`. Limits to enforce in forms: `spec/ModelLimits.hpp` (`kMaxPostTitleLength` 500, `kMinPostContentLength` 10, `kMaxPostContentLength` 125000, `kMinCommentContentLength` 3, `kMaxDirectMessageLength` 2000, `kMaxAttachmentsCount` 10, `kMaxPollOptionsCount` 6, `kMaxReportDetailLength` 2000). ## api/MessagesSocket.hpp ``` using EventHandler = std::function; // UI thread setEventHandler(EventHandler) connect() disconnect() send(content, vector attachmentUids, clientId) sendTyping() sendRead(withUid) ``` `LiveMessagesSocket(receiverUid, UrlProvider)` (api/LiveMessagesSocket.hpp), `MockMessagesSocket` (api/mock). Events: `ChatSocketEvent{type: Ready|Message|Typing|Read|Failed|Disconnected, userUid, message (optional ChatSocketIncomingMessage), fromUid, byUid, clientId, text}` (model/ChatSocketEvent.hpp). Codec: `ChatSocketCodec::decode/encodeSend/encodeTyping/encodeRead`. Reconnect: emits Disconnected, waits 200 ms doubling to 5000 ms, a fresh ticket per connect. ## api/DevPlaceRequest.hpp (SDK port, one method per endpoint, explicit token) Constructed with `NetworkService&` (default instance). Same `Done` shape. `Token = optional`. Auth: getAuthToken, signUp, forgotPassword, resetPassword. Feed: getFeed(tab, topic, search, before, token), getPost, createPost, editPost, deletePost. Comments: createComment, editComment, deleteComment. getProjects, getProject, getGists, getGist, getNews, getArticle, getProfile(username, tab, token), searchProfiles, deleteAccount, getFollowers, getFollowing, followUser, unfollowUser, blockUser, unblockUser, muteUser, unmuteUser, getLeaderboard, vote, submitPollChoice, react, toggleBookmark, getBookmarks, getReportReasons, report, getMessages, sendMessage, searchMessageRecipients, getMessagesWebSocketTicket, `std::string messagesWebSocketUrl(ticket) const`, getNotifications, openNotification, getNotificationCounts, markNotificationRead, markAllNotificationsRead, registerPushDevice, uploadFile (multipart), uploadFromUrl, deleteAttachment. `ApiErrorDecoder::decodeBody(body)` / `fromResponse(status, body)` (api/ApiErrorDecoder.hpp). `DevPlaceError::notLoggedIn()`, `invalidUrl(s)`, `postNotEditable()` (api/DevPlaceError.hpp). ## store/AppState.hpp (singleton `AppState::instance()`, extends `Observable`) ``` version() -> uint64 (grows on every mutation) subscribe(std::function) -> id (0 = refused) unsubscribe(id) token() currentUser() feed() unreadNotificationCount() unreadMessageCount() pendingConversationUid() (const optional<>& / int64) isLoggedIn() isCurrentUser(id) setToken setCurrentUser setFeed setUnreadCounts(notifications, messages) setPendingConversationUid clear() loadFeed(DevPlaceApi&, Done) loadUnreadCounts(DevPlaceApi&, std::function done = {}) loadMoreFeed(DevPlaceApi&, Done) conversationUser(uid, DevPlaceApi&, function)>) updatePostVoteInFeed(postId, Vote, count) updateCommentVoteInFeed(commentId, Vote) updatePostReactionInFeed(postId, emoji) updateCommentReactionInFeed(commentId, emoji) performVoteToggle(TargetType, targetId, Vote currentVote, DevPlaceApi&, function apply, function done = {}) performReactionToggle(TargetType, targetId, emoji, DevPlaceApi&, function apply, function done = {}) ``` UI redraw rule: remember `version()` per frame, redraw when it changed (or subscribe). ## store/SettingsStore.hpp (`SettingsStore::instance()`, extends `Observable`, file settings.json) Getters: `appearance()` (AppearanceMode: System, Light, Dark; `raw()`, `title()`, default Dark), `showFeedAttachments()`, `showFeedComments()`, `showReportButtons()` (default true), `recentEmojis()` (max 30), `draftPostTitle()`, `draftPostMessage()`, `draftReplyMessage()`. Setters: `setAppearance`, `setShowFeedAttachments`, `setShowFeedComments`, `setShowReportButtons`, `setDraftPostTitle`, `setDraftPostMessage`, `setDraftReplyMessage`, `recordEmojiPick(emoji)`. `rebind(dir)`, `reload()`. ## store/SessionStore.hpp (`SessionStore::instance()`, extends `Observable`, file session.json, mode 0600) `email()`, `password()` (`optional`), `setEmail(optional)`, `setPassword(optional)` (false when not persisted). Store the credentials after a successful login so `refreshTokenIfNeeded` can re-login; clear both on logout. ## model/ (all `static T fromJson(const Json&)`, throws `DecodeError` when a required key is missing/null/mistyped) User, Attachment, UploadResponse, Media, Badge, Reactions (`toggling`), Comment (`id()`, `voteCount()`, `replacingReactions`, `replacingChildren`, `applyingVote`), CommentTree (`updatingVote`, `updatingReaction`), Poll, PollOption, Post (`id()`, `replacingReactions`, `replacingRecentComments`), PostDetail (`with(...)`), Feed (`replacingPosts`), Article, ArticleDetail, News, Gist, GistDetail, Gists, Project, ProjectDetail, Projects, Profile, Followers, Following, FollowUser, Leaderboard, LeaderboardEntry, Bookmarks, BookmarkItem, Conversation, Message, MessagesInbox, MessagesWebSocketTicket, UserSearch, Notifications, NotificationGroup, Notification, NotificationCounts, NotificationOpen, ReportReason, ActionResponse, AuthToken (`isExpired()`, `willExpireSoon()`), BirthDate (`fromDate(Date)`, `toString()`), Vote (Up, Down, None; `value()`), PostTopic (`all()`, `raw()`, `name()`, `fromRaw`), TargetType, Role, NotificationType, PushProvider, AppearanceMode. Models are plain aggregates; `Post::id()` style helpers return the prefixed identity ("post:" + uid). ## Core helpers `Timer::after(ms, fn)` (core/Timer.hpp, UI thread, cancellable), `Observable`, `Uuid::random()`, `AppPaths::prefDirectory()`.