// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One record from the mailbox history: everything that happened to one //! message at one point in the sequence. //! //! The history is how an already-synchronised mailbox is caught up without //! listing it again. Two things about it decide the shape of any program //! using it, and both are Gmail's rules rather than this library's: //! //! **A history id expires.** Gmail keeps roughly a week of history, and //! `startHistoryId` older than that is answered with 404. That is not an //! error to retry -- it means the incremental path is gone and the mailbox has //! to be walked in full -- so `history.list` reports it as //! `error.HistoryTooOld` rather than folding it in with every other 404. //! //! **A record is not a diff.** The same message appears in several records, //! records repeat across pages, and a message that was added and then deleted //! appears as both. What a caller wants is almost always the *set* of message //! ids that were touched, refetched afterwards; `Page.collectMessageIds` does //! that, and `Change` is there for the cases that genuinely need to know which //! label was added to what. const History = @This(); const std = @import("std"); const Message = @import("Message.zig"); const json = @import("json.zig"); /// Where in the sequence this record sits. The largest one on the last page /// is what to store as the starting point for next time. id: u64, /// Messages that exist at this point. Gmail sends this on every record, so it /// is the union of the four lists below and not a change of its own. messages: []const Message = &.{}, messages_added: []const Message = &.{}, messages_deleted: []const Message = &.{}, labels_added: []const LabelChange = &.{}, labels_removed: []const LabelChange = &.{}, pub const LabelChange = struct { message: Message, label_ids: []const []const u8, }; /// One thing that happened, flattened out of the four lists. pub const Change = union(enum) { added: Message, deleted: Message, labels_added: LabelChange, labels_removed: LabelChange, pub fn messageId(c: Change) []const u8 { return switch (c) { .added, .deleted => |m| m.id, .labels_added, .labels_removed => |l| l.message.id, }; } }; pub const ParseError = error{Malformed} || std.mem.Allocator.Error; /// Reads one history record. `alloc` should be an arena; see /// `Message.fromJson`. pub fn fromJson(alloc: std.mem.Allocator, value: std.json.Value) ParseError!History { if (value != .object) return error.Malformed; return .{ .id = json.unsigned64(value, "id") orelse return error.Malformed, .messages = try messageList(alloc, value, "messages"), .messages_added = try wrappedMessageList(alloc, value, "messagesAdded"), .messages_deleted = try wrappedMessageList(alloc, value, "messagesDeleted"), .labels_added = try labelChangeList(alloc, value, "labelsAdded"), .labels_removed = try labelChangeList(alloc, value, "labelsRemoved"), }; } /// Walks the four change lists in a fixed order: additions, deletions, label /// additions, label removals. pub fn changes(h: *const History) ChangeIterator { return .{ .history = h }; } pub const ChangeIterator = struct { history: *const History, which: usize = 0, index: usize = 0, pub fn next(it: *ChangeIterator) ?Change { while (it.which < 4) { const change: ?Change = switch (it.which) { 0 => if (it.index < it.history.messages_added.len) .{ .added = it.history.messages_added[it.index] } else null, 1 => if (it.index < it.history.messages_deleted.len) .{ .deleted = it.history.messages_deleted[it.index] } else null, 2 => if (it.index < it.history.labels_added.len) .{ .labels_added = it.history.labels_added[it.index] } else null, 3 => if (it.index < it.history.labels_removed.len) .{ .labels_removed = it.history.labels_removed[it.index] } else null, else => unreachable, }; if (change) |c| { it.index += 1; return c; } it.which += 1; it.index = 0; } return null; } }; fn messageList( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8, ) ParseError![]const Message { const items = json.array(value, name) orelse return &.{}; var list: std.ArrayList(Message) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { // A stub with no id is not a message; skipping it keeps one odd entry // from discarding a whole page of history. const m = Message.fromJson(alloc, item) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(m); } return list.toOwnedSlice(alloc); } fn wrappedMessageList( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8, ) ParseError![]const Message { const items = json.array(value, name) orelse return &.{}; var list: std.ArrayList(Message) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { const inner = json.object(item, "message") orelse continue; const m = Message.fromJson(alloc, inner) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(m); } return list.toOwnedSlice(alloc); } fn labelChangeList( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8, ) ParseError![]const LabelChange { const items = json.array(value, name) orelse return &.{}; var list: std.ArrayList(LabelChange) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { const inner = json.object(item, "message") orelse continue; const m = Message.fromJson(alloc, inner) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; var ids: std.ArrayList([]const u8) = .empty; if (json.array(item, "labelIds")) |label_ids| { try ids.ensureTotalCapacityPrecise(alloc, label_ids.len); for (label_ids) |l| switch (l) { .string => |s| ids.appendAssumeCapacity(s), else => {}, }; } list.appendAssumeCapacity(.{ .message = m, .label_ids = try ids.toOwnedSlice(alloc), }); } return list.toOwnedSlice(alloc); } const testing = std.testing; const TestHistory = struct { parsed: std.json.Parsed(std.json.Value), arena: std.heap.ArenaAllocator, history: History, fn init(text: []const u8) !TestHistory { var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, text, .{}); errdefer parsed.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); errdefer arena.deinit(); const history: History = try .fromJson(arena.allocator(), parsed.value); return .{ .parsed = parsed, .arena = arena, .history = history }; } fn deinit(t: *TestHistory) void { t.arena.deinit(); t.parsed.deinit(); } }; test "a record with every kind of change" { var t = try TestHistory.init( \\{"id":"1234567890", \\ "messages":[{"id":"m1","threadId":"t1"},{"id":"m2","threadId":"t2"}], \\ "messagesAdded":[{"message":{"id":"m1","threadId":"t1"}}], \\ "messagesDeleted":[{"message":{"id":"m9","threadId":"t9"}}], \\ "labelsAdded":[{"message":{"id":"m2","threadId":"t2"}, \\ "labelIds":["STARRED","IMPORTANT"]}], \\ "labelsRemoved":[{"message":{"id":"m2","threadId":"t2"}, \\ "labelIds":["UNREAD"]}]} ); defer t.deinit(); const h = t.history; try testing.expectEqual(@as(u64, 1234567890), h.id); try testing.expectEqual(@as(usize, 2), h.messages.len); try testing.expectEqual(@as(usize, 1), h.messages_added.len); try testing.expectEqualStrings("m9", h.messages_deleted[0].id); try testing.expectEqual(@as(usize, 2), h.labels_added[0].label_ids.len); try testing.expectEqualStrings("STARRED", h.labels_added[0].label_ids[0]); try testing.expectEqualStrings("UNREAD", h.labels_removed[0].label_ids[0]); var it = h.changes(); const first = it.next().?; try testing.expect(first == .added); try testing.expectEqualStrings("m1", first.messageId()); const second = it.next().?; try testing.expect(second == .deleted); try testing.expectEqualStrings("m9", second.messageId()); const third = it.next().?; try testing.expect(third == .labels_added); try testing.expectEqualStrings("m2", third.messageId()); const fourth = it.next().?; try testing.expect(fourth == .labels_removed); try testing.expectEqual(@as(?History.Change, null), it.next()); } test "every change list may be absent" { var t = try TestHistory.init("{\"id\":\"7\"}"); defer t.deinit(); try testing.expectEqual(@as(u64, 7), t.history.id); try testing.expectEqual(@as(usize, 0), t.history.messages.len); try testing.expectEqual(@as(usize, 0), t.history.labels_added.len); var it = t.history.changes(); try testing.expectEqual(@as(?History.Change, null), it.next()); } test "a record with no id is malformed" { var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, "{\"messages\":[]}", .{}); defer parsed.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); try testing.expectError(error.Malformed, History.fromJson(arena.allocator(), parsed.value)); } test "junk in a change list is skipped" { var t = try TestHistory.init( \\{"id":"7","messagesAdded":[{"message":{"id":"m1"}},{"nope":1}, \\ {"message":{"no":"id"}},42], \\ "labelsAdded":[{"message":{"id":"m2"}}]} ); defer t.deinit(); try testing.expectEqual(@as(usize, 1), t.history.messages_added.len); // No labelIds member at all: an empty list, not a crash. try testing.expectEqual(@as(usize, 1), t.history.labels_added.len); try testing.expectEqual(@as(usize, 0), t.history.labels_added[0].label_ids.len); }