git » sdk » commit 21c85a3

Batch chat updates properly

author Eric Roberts
2026-10-13 18:56:13 UTC
committer Eric Roberts
2026-10-14 15:50:13 UTC
parent f7e77eefbd8fa1acf038f6ac5d327c4fbc24e55a

Batch chat updates properly

Right now it's batched per listener. But cheogram unsubscribes and
resubscribes on updates, so it essentially always ends up delivering
immediately.

Instead the batching is at the client level now.

This should mean fewer updates to the UI, which should fix some
performance problems that I am seeing.

borogove/ChatUpdateBatcher.hx +49 -0
borogove/Client.hx +7 -34
test/TestAll.hx +1 -0
test/TestChatUpdateBatcher.hx +174 -0
test/TestClient.hx +77 -1

diff --git a/borogove/ChatUpdateBatcher.hx b/borogove/ChatUpdateBatcher.hx
new file mode 100644
index 0000000..2083062
--- /dev/null
+++ b/borogove/ChatUpdateBatcher.hx
@@ -0,0 +1,49 @@
+package borogove;
+
+class ChatUpdateBatcher {
+	private static inline final BATCH_INTERVAL_MS = 500;
+	private final deliver: Array<Chat>->Void;
+	private final now: ()->Float;
+	private final buffer: Map<String, Chat> = new Map();
+	private var lastDelivery = -1.0;
+	private var timer: Null<haxe.Timer> = null;
+
+	public function new(deliver: Array<Chat>->Void, ?now: ()->Float) {
+		this.deliver = deliver;
+		this.now = now ?? (() -> haxe.Timer.stamp() * 1000);
+	}
+
+	public function add(chats: Array<Chat>): Void {
+		if (chats.length == 0) return;
+
+		timer?.stop();
+
+		for (chat in chats) buffer[chat.chatId] = chat;
+
+		if (shouldSendNow()) {
+			flush();
+		} else {
+			timer = haxe.Timer.delay(flush, BATCH_INTERVAL_MS);
+		}
+	}
+
+	private function shouldSendNow(): Bool {
+		return neverSent() || dueForSend();
+	}
+
+	private function neverSent() {
+		return lastDelivery < 0;
+	}
+
+	private function dueForSend() {
+		return now() - lastDelivery >= BATCH_INTERVAL_MS;
+	}
+
+	private function flush(): Void {
+		lastDelivery = now();
+		final batch = Lambda.array(buffer);
+		buffer.clear();
+		deliver(batch);
+	}
+
+}
diff --git a/borogove/Client.hx b/borogove/Client.hx
index 4f980b9..670bf3c 100644
--- a/borogove/Client.hx
+++ b/borogove/Client.hx
@@ -82,6 +82,7 @@ class Client extends EventEmitter {
 	@:allow(borogove)
 	private var chats: Array<Chat> = [];
 	private final chatsIndex: Map<String, Chat> = new Map();
+	private final chatUpdateBatcher: ChatUpdateBatcher;
 	private final persistence: Persistence;
 	@:allow(borogove)
 	private final capsRepo: CapsRepo;
@@ -150,6 +151,9 @@ class Client extends EventEmitter {
 		promiseFactory.scheduler.addNext = mainLoop.run;
 		#end
 		super();
+		chatUpdateBatcher = new ChatUpdateBatcher(batch -> {
+			this.trigger("chats/update/batched", batch);
+		});
 		capsRepo = new CapsRepo(persistence);
 		this.jid = JID.parse(accountId);
 		this._displayName = this.jid.node ?? this.jid.asString();
@@ -172,6 +176,7 @@ class Client extends EventEmitter {
 		});
 
 		this.on("chats/update", (data: Array<Chat>) -> {
+			chatUpdateBatcher.add(data);
 			stream.emitSMupdates = !Util.existsFast(chats, chat -> chat.uiState != Closed && chat.syncing());
 			return EventHandled;
 		});
@@ -1781,43 +1786,11 @@ class Client extends EventEmitter {
 	**/
 	@:HaxeSwiftBridge.contextLifetime(handler, EventEmitter)
 	public function addChatsUpdatedListener(handler:Array<Chat>->Void) {
-		final updateChatBuffer: Map<String, Bool> = new Map();
-		var lastCall = -1.0;
-		var updateChatTimer = null;
-		return this.on("chats/update", (data: Array<Chat>) -> {
-			final now = haxe.Timer.stamp() * 1000;
-			if (updateChatTimer != null) {
-				updateChatTimer.stop();
-			}
-			for (chat in data) {
-				assert(getChat(chat.chatId) != null, "chats/update was triggered for a chat not in chats");
-				updateChatBuffer[chat.chatId] = true;
-			}
-			if (lastCall < 0 || now - lastCall >= 500) {
-				lastCall = now;
-				final toSend = [];
-				for (chatId => v in updateChatBuffer) {
-					toSend.push(getChat(chatId));
-				}
-				handler(toSend);
-				updateChatTimer = null;
-				updateChatBuffer.clear();
-			} else {
-				updateChatTimer = haxe.Timer.delay(() -> {
-					lastCall = haxe.Timer.stamp() * 1000;
-					final toSend = [];
-					for (chatId => v in updateChatBuffer) {
-						toSend.push(getChat(chatId));
-					}
-					handler(toSend);
-					updateChatTimer = null;
-					updateChatBuffer.clear();
-				}, 500);
-			}
+		return this.on("chats/update/batched", (data: Array<Chat>) -> {
+			handler(data);
 			return EventHandled;
 		});
 	}
-
 #if !NO_JINGLE
 	/**
 		Event fired when a new call comes in
diff --git a/test/TestAll.hx b/test/TestAll.hx
index df0c519..6b24d0f 100644
--- a/test/TestAll.hx
+++ b/test/TestAll.hx
@@ -19,6 +19,7 @@ class TestAll {
 			new TestChatMessage(),
 			new TestChatMessageCombiner(),
 			new TestChatMessageBuilder(),
+			new TestChatUpdateBatcher(),
 			new TestClient(),
 			new TestEmojiUtil(),
 			new TestHtml(),
diff --git a/test/TestChatUpdateBatcher.hx b/test/TestChatUpdateBatcher.hx
new file mode 100644
index 0000000..268c2c4
--- /dev/null
+++ b/test/TestChatUpdateBatcher.hx
@@ -0,0 +1,174 @@
+package test;
+
+import borogove.Chat;
+import borogove.ChatUpdateBatcher;
+import borogove.Client;
+import borogove.persistence.Dummy;
+import utest.Assert;
+
+@:access(borogove)
+class TestChatUpdateBatcher extends utest.Test {
+	private function chat(id: String): Chat {
+		final client = new Client("test@example.com", new Dummy());
+		return client.getDirectChat(id, false);
+	}
+
+	public function testEmptyUpdateDoesNotStartDeliveryWindow() {
+		final first = chat("first@example.com");
+		final batches: Array<Array<Chat>> = [];
+		final batcher = new ChatUpdateBatcher(batch -> batches.push(batch));
+
+		batcher.add([]);
+		Assert.equals(0, batches.length);
+		batcher.add([first]);
+		Assert.equals(1, batches.length);
+		if (batches.length == 1) Assert.equals(first, batches[0][0]);
+	}
+
+	public function testEmptyUpdateDoesNotPostponePendingDelivery() {
+		final first = chat("first@example.com");
+		final last = chat("last@example.com");
+		final batches: Array<Array<Chat>> = [];
+		final interval = ChatUpdateBatcher.BATCH_INTERVAL_MS;
+		final justBeforeDelivery = interval - 1;
+		final deliveryDue = interval;
+		final afterNextWindow = deliveryDue + interval + 1;
+		var now = 0.0;
+		final batcher = new ChatUpdateBatcher(batch -> batches.push(batch), () -> now);
+		batcher.add([first]);
+		batcher.add([last]);
+		final pending = batcher.timer;
+
+		now = justBeforeDelivery;
+		batcher.add([]);
+		Assert.equals(pending, batcher.timer);
+		Assert.equals(1, batches.length);
+		now = deliveryDue;
+		batcher.timer.run();
+		Assert.equals(2, batches.length);
+		if (batches.length == 2) {
+			Assert.equals(1, batches[1].length);
+			Assert.equals(last, batches[1][0]);
+		}
+		now = afterNextWindow;
+		batcher.add([]);
+		Assert.equals(2, batches.length);
+		Assert.equals(pending, batcher.timer);
+	}
+
+	public function testFirstBatchIsImmediateAndDeduplicated() {
+		final first = chat("first@example.com");
+		final latest = chat("first@example.com");
+		final second = chat("second@example.com");
+		final batches: Array<Array<Chat>> = [];
+		final batcher = new ChatUpdateBatcher(batch -> batches.push(batch));
+
+		batcher.add([first, second, latest]);
+
+		Assert.equals(1, batches.length);
+		Assert.equals(2, batches[0].length);
+		Assert.isTrue(batches[0].contains(latest));
+		Assert.isTrue(batches[0].contains(second));
+		Assert.isFalse(batches[0].contains(first));
+	}
+
+	public function testInstancesHaveIndependentWindows() {
+		final first = chat("first@example.com");
+		final second = chat("second@example.com");
+		final batches: Array<Array<Chat>> = [];
+		final otherBatches: Array<Array<Chat>> = [];
+		final batcher = new ChatUpdateBatcher(batch -> batches.push(batch));
+		final other = new ChatUpdateBatcher(batch -> otherBatches.push(batch));
+
+		batcher.add([first]);
+		batcher.add([second]);
+		other.add([second]);
+		Assert.equals(1, batches.length);
+		Assert.equals(1, otherBatches.length);
+		Assert.equals(second, otherBatches[0][0]);
+
+		batcher.timer.run();
+		Assert.equals(2, batches.length);
+		Assert.equals(1, otherBatches.length);
+		if (batches.length == 2) Assert.equals(second, batches[1][0]);
+	}
+
+	public function testTrailingTimerRestartsAndDeliversLatestChat() {
+		final first = chat("first@example.com");
+		final replacement = chat("first@example.com");
+		final last = chat("last@example.com");
+		final batches: Array<Array<Chat>> = [];
+		final interval = ChatUpdateBatcher.BATCH_INTERVAL_MS;
+		final anotherUpdateAt = interval / 2;
+		final trailingDeliveryAt = anotherUpdateAt + interval;
+		var now = 0.0;
+		final batcher = new ChatUpdateBatcher(batch -> batches.push(batch), () -> now);
+		batcher.add([first]);
+		batcher.add([first]);
+		final previous = batcher.timer;
+
+		now = anotherUpdateAt;
+		batcher.add([replacement, last]);
+		Assert.isFalse(previous == batcher.timer);
+		Assert.equals(1, batches.length);
+		now = trailingDeliveryAt;
+		batcher.timer.run();
+		Assert.equals(2, batches.length);
+		if (batches.length == 2) {
+			Assert.equals(2, batches[1].length);
+			Assert.isTrue(batches[1].contains(replacement));
+			Assert.isTrue(batches[1].contains(last));
+			Assert.isFalse(batches[1].contains(first));
+		}
+	}
+
+	public function testContinuousBurstFlushesBeforeItStops() {
+		final first = chat("first@example.com");
+		final last = chat("last@example.com");
+		final batches: Array<Array<Chat>> = [];
+		final interval = ChatUpdateBatcher.BATCH_INTERVAL_MS;
+		final halfwayToDelivery = interval / 2;
+		final justBeforeDelivery = interval - 1;
+		final deliveryDue = interval;
+		final lastUpdateAt = deliveryDue + halfwayToDelivery;
+		final trailingDeliveryAt = lastUpdateAt + interval;
+		var now = 0.0;
+		final batcher = new ChatUpdateBatcher(batch -> batches.push(batch), () -> now);
+		batcher.add([first]);
+		for (updateAt in [halfwayToDelivery, justBeforeDelivery]) {
+			now = updateAt;
+			batcher.add([first]);
+			Assert.equals(1, batches.length);
+		}
+		now = deliveryDue;
+		batcher.add([first]);
+		Assert.equals(2, batches.length);
+		now = lastUpdateAt;
+		batcher.add([last]);
+		Assert.equals(2, batches.length);
+		now = trailingDeliveryAt;
+		batcher.timer.run();
+		Assert.equals(3, batches.length);
+		if (batches.length == 3) Assert.equals(last, batches[2][0]);
+	}
+
+	public function testUpdateAddedDuringDeliveryIsEventuallyDelivered() {
+		final first = chat("first@example.com");
+		final last = chat("last@example.com");
+		final batches: Array<Array<Chat>> = [];
+		var batcher: ChatUpdateBatcher = null;
+		batcher = new ChatUpdateBatcher(batch -> {
+			batches.push(batch);
+			if (batches.length == 1) batcher.add([last]);
+		});
+		batcher.add([first]);
+		Assert.equals(1, batches.length);
+
+		batcher.timer.run();
+		Assert.equals(2, batches.length);
+		if (batches.length == 2) {
+			Assert.equals(1, batches[1].length);
+			Assert.equals(last, batches[1][0]);
+		}
+	}
+}
diff --git a/test/TestClient.hx b/test/TestClient.hx
index 31cd832..0bb6ea9 100644
--- a/test/TestClient.hx
+++ b/test/TestClient.hx
@@ -44,6 +44,78 @@ class TestClient extends utest.Test {
 		Assert.isTrue(channel.isJoined);
 	}
 
+	public function testChatsUpdateBatchSurvivesResubscription() {
+		final client = new Client("test@example.com", new Dummy());
+		final first = client.getDirectChat("first@example.com", false);
+		final last = client.getDirectChat("last@example.com", false);
+		final oldBatches: Array<Array<Chat>> = [];
+		final newBatches: Array<Array<Chat>> = [];
+
+		final token = client.addChatsUpdatedListener(batch -> oldBatches.push(batch));
+		client.trigger("chats/update", [first]);
+		Assert.equals(1, oldBatches.length);
+		client.trigger("chats/update", [first]);
+		client.removeEventListener(token);
+
+		client.addChatsUpdatedListener(batch -> newBatches.push(batch));
+		client.trigger("chats/update", [last]);
+		Assert.equals(0, newBatches.length);
+		client.chatUpdateBatcher.timer.run();
+
+		Assert.equals(1, oldBatches.length);
+		Assert.equals(1, newBatches.length);
+		Assert.equals(2, newBatches[0].length);
+		Assert.isTrue(newBatches[0].contains(first));
+		Assert.isTrue(newBatches[0].contains(last));
+	}
+
+	public function testChatsUpdateListenersShareBatch() {
+		final client = new Client("test@example.com", new Dummy());
+		final chat = client.getDirectChat("friend@example.com", false);
+		final batches: Array<Array<Chat>> = [];
+		final lateBatches: Array<Array<Chat>> = [];
+
+		client.addChatsUpdatedListener(batch -> batches.push(batch));
+		client.trigger("chats/update", [chat]);
+		client.addChatsUpdatedListener(batch -> lateBatches.push(batch));
+		client.trigger("chats/update", [chat, chat]);
+		Assert.equals(1, batches.length);
+		Assert.equals(0, lateBatches.length);
+		client.chatUpdateBatcher.timer.run();
+
+		Assert.equals(2, batches.length);
+		Assert.equals(1, lateBatches.length);
+		Assert.equals(batches[1], lateBatches[0]);
+		Assert.equals(1, batches[1].length);
+		Assert.equals(chat, batches[1][0]);
+	}
+
+	public function testClientsBatchChatsUpdatesIndependently() {
+		final client = new Client("test@example.com", new Dummy());
+		final other = new Client("other@example.com", new Dummy());
+		final chat = client.getDirectChat("friend@example.com", false);
+		final otherChat = other.getDirectChat("friend@example.com", false);
+		var calls = 0;
+		var otherCalls = 0;
+		client.addChatsUpdatedListener(_ -> calls++);
+		other.addChatsUpdatedListener(_ -> otherCalls++);
+
+		client.trigger("chats/update", [chat]);
+		client.trigger("chats/update", [chat]);
+		Assert.equals(1, calls);
+		Assert.equals(0, otherCalls);
+		other.trigger("chats/update", [otherChat]);
+		other.trigger("chats/update", [otherChat]);
+		Assert.equals(1, otherCalls);
+
+		client.chatUpdateBatcher.timer.run();
+		Assert.equals(2, calls);
+		Assert.equals(1, otherCalls);
+		other.chatUpdateBatcher.timer.run();
+		Assert.equals(2, calls);
+		Assert.equals(2, otherCalls);
+	}
+
 	public function testSetStatus(async: Async) {
 		final persistence = new Dummy();
 		final client = new Client("test@example.com", persistence);
@@ -106,6 +178,7 @@ class TestClient extends utest.Test {
 					.tag("undefined")
 						.textTag("emoji", "💻", { xmlns: "https://ns.borogove.dev/" })
 		);
+		client.chatUpdateBatcher.timer.run();
 	}
 
 	public function testPresenceIncludesStatus() {
@@ -775,10 +848,12 @@ class TestClient extends utest.Test {
 		client.stream.onStanza(originalStanza);
 
 		haxe.Timer.delay(() -> {
-			client.addChatsUpdatedListener(chats -> {
+			var token = null;
+			token = client.addChatsUpdatedListener(chats -> {
 				final c = chats.find(x -> x.chatId == "friend@example.com");
 				Assert.notNull(c?.lastMessage);
 				Assert.equals("corrected", c.lastMessage.text);
+				client.removeEventListener(token);
 				async.done();
 			});
 
@@ -786,6 +861,7 @@ class TestClient extends utest.Test {
 					.textTag("body", "corrected")
 					.tag("replace", { id: "msg1", xmlns: "urn:xmpp:message-correct:0" }).up();
 			client.stream.onStanza(correctionStanza);
+			client.chatUpdateBatcher.timer.run();
 		}, 1);
 	}