git » sdk » commit 65784dd

Keep sortId shorter with a large MessageSync

author Stephen Paul Weber
2026-11-10 03:03:36 UTC
committer Stephen Paul Weber
2026-11-10 20:29:18 UTC
parent 309d938cc1e9b0f4c70a36aaf08c0bd28e43acf3

Keep sortId shorter with a large MessageSync

Doing between over and over again in a small window is worst case for
the algorithm, so use nBetween on a whole page at a time to improve the
size of the sortIds.

borogove/MessageSync.hx +40 -31
test/TestSortId.hx +68 -0

diff --git a/borogove/MessageSync.hx b/borogove/MessageSync.hx
index eac1bc7..0c92fd4 100644
--- a/borogove/MessageSync.hx
+++ b/borogove/MessageSync.hx
@@ -10,6 +10,7 @@ import borogove.queries.MAMQuery;
 import thenshim.Promise;
 import thenshim.PromiseTools;
 using StringTools;
+using Lambda;
 
 #if !NO_OMEMO
 import borogove.OMEMO;
@@ -59,7 +60,8 @@ class MessageSync {
 		if (complete) {
 			throw new Exception("Attempt to fetch messages, but already complete");
 		}
-		final promisedMessages:Array<Promise<Message>> = [];
+		final promisedMessages:Array<Promise<(String) -> Message>> = [];
+		final pageStartSortA = sortA;
 		if (lastPage != null) {
 			if (filter.page == null) filter.page = {};
 			if (filter.page.before == null) {
@@ -86,8 +88,6 @@ class MessageSync {
 			if (originalMessage == null) { // No message, nothing for us to do
 				return EventHandled;
 			}
-			final sortLower = sortA;
-			sortA = FractionalIndexing.between(sortLower, sortB, FractionalIndexing.BASE_95_DIGITS);
 			final serverReceivedAt = result.findText("{urn:xmpp:forward:0}forwarded/{urn:xmpp:delay}delay@stamp");
 			var timeReceived = serverReceivedAt;
 			if (timeReceived == null) {
@@ -115,7 +115,6 @@ class MessageSync {
 				jmi.set(jmiChildren[0].attr.get("id"), originalMessage);
 			}
 
-			final sortId = sortA;
 #if !NO_OMEMO
 			if (originalMessage.hasChild("encrypted", NS.OMEMO)) {
 				trace("MAM: Processing OMEMO message from " + originalMessage.attr.get("from"));
@@ -123,7 +122,7 @@ class MessageSync {
 					final decryptedStanza = decryptionResult.stanza;
 					trace("MAM: Decrypted stanza: "+decryptedStanza);
 
-					return Message.fromStanza(decryptedStanza, client.jid, (builder, stanza) -> {
+					return (sortId) -> Message.fromStanza(decryptedStanza, client.jid, (builder, stanza) -> {
 						builder.sortId = sortId;
 						builder.debug = {
 							source: "mam",
@@ -133,7 +132,7 @@ class MessageSync {
 							startFiler: startFilter,
 							now: Date.format(std.Date.now()),
 							path: "decrypted",
-							sortId: { method: "between", startSortA: startSortA, lower: sortLower, upper: sortB },
+							sortId: { method: "between", startSortA: startSortA, lower: pageStartSortA, upper: sortB },
 						};
 						builder.serverId = result.attr.get("id");
 						builder.serverIdBy = serviceJID;
@@ -143,25 +142,23 @@ class MessageSync {
 					});
 				}, (err) -> {
 					trace("MAM: Decryption failed: "+err);
-					return Message.fromStanza(originalMessage, client.jid, (builder, stanza) -> {
-							builder.sortId = sortA;
-							builder.debug = {
-								source: "mam",
-								serverReceivedAt: serverReceivedAt,
-								serviceJID: serviceJID,
-								filter: filter,
-								startFiler: startFilter,
-								now: Date.format(std.Date.now()),
-								path: "decryption failed",
-								sortId: { method: "between", startSortA: startSortA, lower: sortLower, upper: sortB },
-							};
-							builder.serverId = result.attr.get("id");
-							builder.serverIdBy = serviceJID;
-							if (timeReceived != null && builder.timeReceived == null) builder.timeReceived = timeReceived;
-							return contextHandler(builder, stanza);
-						},
-						new EncryptionInfo(DecryptionFailure, NS.OMEMO, "OMEMO", "internal-error", Std.string(err))
-					);
+					return (sortId) -> Message.fromStanza(originalMessage, client.jid, (builder, stanza) -> {
+						builder.sortId = sortId;
+						builder.debug = {
+							source: "mam",
+							serverReceivedAt: serverReceivedAt,
+							serviceJID: serviceJID,
+							filter: filter,
+							startFiler: startFilter,
+							now: Date.format(std.Date.now()),
+							path: "decryption failed",
+							sortId: { method: "between", startSortA: startSortA, lower: pageStartSortA, upper: sortB },
+						};
+						builder.serverId = result.attr.get("id");
+						builder.serverIdBy = serviceJID;
+						if (timeReceived != null && builder.timeReceived == null) builder.timeReceived = timeReceived;
+						return contextHandler(builder, stanza);
+					}, new EncryptionInfo(DecryptionFailure, NS.OMEMO, "OMEMO", "internal-error", Std.string(err)));
 				}));
 				return EventHandled;
 			}
@@ -169,7 +166,7 @@ class MessageSync {
 
 			trace("MAM: Processing non-OMEMO message from " + originalMessage.attr.get("from"));
 
-			final msg = Message.fromStanza(originalMessage, client.jid, (builder, stanza) -> {
+			promisedMessages.push(Promise.resolve((sortId) -> Message.fromStanza(originalMessage, client.jid, (builder, stanza) -> {
 				builder.sortId = sortId;
 				builder.debug = {
 					source: "mam",
@@ -179,15 +176,13 @@ class MessageSync {
 					startFiler: startFilter,
 					now: Date.format(std.Date.now()),
 					path: "unencrypted",
-					sortId: { method: "between", startSortA: startSortA, lower: sortLower, upper: sortB },
+					sortId: { method: "between", startSortA: startSortA, lower: pageStartSortA, upper: sortB },
 				};
 				builder.serverId = result.attr.get("id");
 				builder.serverIdBy = serviceJID;
 				if (timeReceived != null && builder.timeReceived == null) builder.timeReceived = timeReceived;
 				return contextHandler(builder, stanza);
-			});
-
-			promisedMessages.push(Promise.resolve(msg));
+			})));
 
 			return EventHandled;
 		});
@@ -205,9 +200,11 @@ class MessageSync {
 			}
 			if (result != null || errorHandler == null) {
 				PromiseTools.all(promisedMessages).then((messages) -> {
+					final sortIds = sortIdsForPage(pageStartSortA, sortB, messages.length);
+					if (sortIds.length > 0) sortA = sortIds[sortIds.length - 1];
 					handler({
 						sync: this,
-						messages: messages,
+						messages: messages.mapi((i, m) -> m(sortIds[i])),
 					});
 				});
 			}
@@ -219,6 +216,18 @@ class MessageSync {
 		return !complete;
 	}
 
+	private static function sortIdsForPage(start:Null<String>, end:Null<String>, count:Int):Array<String> {
+		if (count <= 0) return [];
+		if (start == null && end != null) {
+			final first = FractionalIndexing.between(null, end, FractionalIndexing.BASE_95_DIGITS);
+			if (count == 1) return [first];
+			final rest = FractionalIndexing.nBetween(first, end, count - 1, FractionalIndexing.BASE_95_DIGITS);
+			rest.unshift(first);
+			return rest;
+		}
+		return FractionalIndexing.nBetween(start, end, count, FractionalIndexing.BASE_95_DIGITS);
+	}
+
 	public function addContext(handler: (ChatMessageBuilder, Stanza)->ChatMessageBuilder) {
 		this.contextHandler = handler;
 	}
diff --git a/test/TestSortId.hx b/test/TestSortId.hx
index 5dcc47f..d64bdcf 100644
--- a/test/TestSortId.hx
+++ b/test/TestSortId.hx
@@ -465,4 +465,72 @@ class TestSortId extends utest.Test {
 
 		startBatch();
 	}
+
+	public function testLongChannelSyncSortIdStaysShort(async: Async) {
+		final persistence = new Dummy();
+		final client = new Client("test@example.com", persistence);
+		final disco = new Caps("", [], ["http://jabber.org/protocol/muc", "urn:xmpp:mam:2"], []);
+		final channel = new Channel(client, client.stream, persistence, "longsync@example.com", Open, false, false, null, null, null, disco);
+		client.chats.push(channel);
+
+		final messageCount = 700;
+		final maxAllowedLength = 100;
+		var maxSortIdLength = 0;
+		var finished = false;
+
+		client.addSyncMessageListener((message) -> {
+			final sortId = message.sortId;
+			if (sortId == null) return;
+			if (sortId.length > maxSortIdLength) maxSortIdLength = sortId.length;
+		});
+
+		client.on("chats/update", (chats) -> {
+			if (finished || channel.sync != null) return EventHandled;
+			finished = true;
+			Assert.isTrue(maxSortIdLength < maxAllowedLength, 'max sortId length $maxSortIdLength should be < $maxAllowedLength for a single $messageCount-message sync');
+			async.done();
+			return EventHandled;
+		});
+
+		client.stream.on("sendStanza", (stanza: Stanza) -> {
+			if (stanza.name != "iq") return EventUnhandled;
+			final query = stanza.findChild("{urn:xmpp:mam:2}query");
+			if (query == null) return EventUnhandled;
+
+			final iqId = stanza.attr.get("id");
+			final queryId = query.attr.get("queryid");
+			if (iqId == null || queryId == null) {
+				Assert.fail("MAM query was not sent");
+				return EventHandled;
+			}
+
+			haxe.Timer.delay(() -> {
+				for (i in 0...messageCount) {
+					final serverId = 'long-$i';
+					client.stream.onStanza(new Stanza("message", { from: channel.chatId, xmlns: "jabber:client" })
+						.tag("result", { xmlns: "urn:xmpp:mam:2", queryid: queryId, id: serverId })
+							.tag("forwarded", { xmlns: "urn:xmpp:forward:0" })
+								.tag("delay", { xmlns: "urn:xmpp:delay", stamp: "2023-01-01T00:00:00Z" }).up()
+								.tag("message", { from: channel.chatId + "/user", to: "test@example.com", id: serverId, xmlns: "jabber:client" })
+									.textTag("body", 'message $serverId')
+								.up()
+							.up()
+						.up()
+					);
+				}
+
+				client.stream.onStanza(new Stanza("iq", { type: "result", id: iqId, from: channel.chatId, xmlns: "jabber:client" })
+					.tag("fin", { xmlns: "urn:xmpp:mam:2", complete: "true" })
+						.tag("set", { xmlns: "http://jabber.org/protocol/rsm" })
+							.textTag("first", "long-0")
+							.textTag("last", 'long-${messageCount - 1}')
+						.up()
+					.up()
+				);
+			}, 0);
+			return EventHandled;
+		});
+
+		channel.doSync(null);
+	}
 }