Skip to content

Commit c00b5f4

Browse files
authored
perf(sessions): reuse opaque-key matchers and pruning cursors (#133691)
1 parent 6107afa commit c00b5f4

2 files changed

Lines changed: 52 additions & 62 deletions

File tree

‎src/infra/map-size.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,13 @@ export function pruneMapToMaxSize<K, V>(map: Map<K, V>, maxSize: number): void {
1010
return;
1111
}
1212

13+
if (map.size <= limit) {
14+
return;
15+
}
16+
// Reuse the insertion-order cursor so bulk pruning does not restart at deleted entries.
17+
const keys = map.keys();
1318
while (map.size > limit) {
14-
// Map iteration is insertion ordered; deleting the first key preserves the newest tracked
15-
// entries for request/memory guard caches.
16-
const oldest = map.keys().next();
19+
const oldest = keys.next();
1720
if (oldest.done) {
1821
break;
1922
}

‎src/sessions/session-key-utils.ts‎

Lines changed: 46 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,22 @@ const CASE_PRESERVING_PEERS: readonly CasePreservingPeerDescriptor[] = [
6666
{ channel: "matrix", peerKinds: new Set(["channel", "group"]), span: "tail", unscoped: true },
6767
];
6868

69-
/** True when (channel, peerKind) owns a case-sensitive opaque peer ID. */
70-
function isCasePreservingPeer(
71-
channel: string | undefined | null,
72-
peerKind: string | undefined | null,
73-
): boolean {
74-
const c = normalizeLowercaseStringOrEmpty(channel);
75-
const k = normalizeLowercaseStringOrEmpty(peerKind);
76-
return findCasePreservingPeerDescriptor(c, k) !== undefined;
77-
}
69+
const CASE_PRESERVING_PEER_PATTERNS = CASE_PRESERVING_PEERS.flatMap((descriptor) =>
70+
[...descriptor.peerKinds].map((peerKind) => {
71+
const prefix = `${escapeRegExp(descriptor.channel)}:${escapeRegExp(peerKind)}:`;
72+
return {
73+
span: descriptor.span,
74+
pattern: new RegExp(
75+
descriptor.span === "segment" ? `(^|:)${prefix}([^:]+)` : `^(?:agent:[^:]*:)+:*${prefix}`,
76+
descriptor.span === "segment" ? "gi" : "i",
77+
),
78+
unscopedPattern:
79+
descriptor.span === "tail" && descriptor.unscoped
80+
? new RegExp(`^${prefix}`, "i")
81+
: undefined,
82+
};
83+
}),
84+
);
7885

7986
function findCasePreservingPeerDescriptor(
8087
channel: string | undefined | null,
@@ -121,7 +128,7 @@ export function normalizeSessionPeerId(params: {
121128
if (!peerId) {
122129
return "";
123130
}
124-
return isCasePreservingPeer(params.channel, params.peerKind)
131+
return findCasePreservingPeerDescriptor(params.channel, params.peerKind) !== undefined
125132
? peerId
126133
: normalizeLowercaseStringOrEmpty(peerId);
127134
}
@@ -159,56 +166,36 @@ function mayContainCasePreservingPeer(raw: string): boolean {
159166
*/
160167
function collectCasePreservedSpans(raw: string): PreservedSpan[] {
161168
const spans: PreservedSpan[] = [];
162-
for (const descriptor of CASE_PRESERVING_PEERS) {
163-
const channel = escapeRegExp(descriptor.channel);
164-
for (const peerKind of descriptor.peerKinds) {
165-
const kind = escapeRegExp(peerKind);
166-
if (descriptor.span === "segment") {
167-
// Unscoped: `<channel>:<peerKind>:<segment>` at start or after any colon.
168-
const re = new RegExp(`(^|:)${channel}:${kind}:([^:]+)`, "gi");
169-
for (const match of raw.matchAll(re)) {
170-
const matched = match[0] ?? "";
171-
const segment = match[2] ?? "";
172-
const segStart = (match.index ?? 0) + matched.length - segment.length;
173-
// Segment spans match the legacy `peerId.trim()` behavior exactly.
174-
spans.push({ start: segStart, end: segStart + segment.length, trim: true });
175-
}
176-
} else {
177-
const collectTailSpan = (tailStart: number): void => {
178-
if (tailStart >= raw.length) {
179-
return;
180-
}
181-
// Preserve Matrix room/event IDs, but keep structural thread marker
182-
// casing canonical so `:Thread:` cannot fork a session key.
183-
const tail = raw.slice(tailStart);
184-
const threadMarker = ":thread:";
185-
const markerIndex = normalizeLowercaseStringOrEmpty(tail).lastIndexOf(threadMarker);
186-
if (markerIndex === -1) {
187-
spans.push({ start: tailStart, end: raw.length, trim: false });
188-
return;
189-
}
190-
spans.push({ start: tailStart, end: tailStart + markerIndex, trim: false });
191-
const threadIdStart = tailStart + markerIndex + threadMarker.length;
192-
if (threadIdStart < raw.length) {
193-
spans.push({ start: threadIdStart, end: raw.length, trim: false });
194-
}
195-
};
196-
// Preserve tails behind nested or malformed ownership wrappers without
197-
// treating an inner channel-shaped identity as a runtime route.
198-
const scopedRe = new RegExp(`^(?:agent:[^:]*:)+:*${channel}:${kind}:`, "i");
199-
const scopedMatch = scopedRe.exec(raw);
200-
if (scopedMatch) {
201-
collectTailSpan(scopedMatch[0].length);
202-
continue;
203-
}
204-
if (descriptor.unscoped) {
205-
const unscopedRe = new RegExp(`^${channel}:${kind}:`, "i");
206-
const unscopedMatch = unscopedRe.exec(raw);
207-
if (unscopedMatch) {
208-
collectTailSpan(unscopedMatch[0].length);
209-
}
210-
}
169+
for (const descriptor of CASE_PRESERVING_PEER_PATTERNS) {
170+
if (descriptor.span === "segment") {
171+
// matchAll clones the global matcher, so separate keys never share a cursor.
172+
for (const match of raw.matchAll(descriptor.pattern)) {
173+
const matched = match[0] ?? "";
174+
const segment = match[2] ?? "";
175+
const segStart = (match.index ?? 0) + matched.length - segment.length;
176+
// Segment spans match the legacy peerId.trim() behavior exactly.
177+
spans.push({ start: segStart, end: segStart + segment.length, trim: true });
211178
}
179+
continue;
180+
}
181+
// Nested/malformed ownership wrappers remain opaque; only the matcher owns their shape.
182+
const match = descriptor.pattern.exec(raw) ?? descriptor.unscopedPattern?.exec(raw);
183+
if (!match || match[0].length >= raw.length) {
184+
continue;
185+
}
186+
const tailStart = match[0].length;
187+
const tail = raw.slice(tailStart);
188+
const threadMarker = ":thread:";
189+
const markerIndex = normalizeLowercaseStringOrEmpty(tail).lastIndexOf(threadMarker);
190+
if (markerIndex === -1) {
191+
spans.push({ start: tailStart, end: raw.length, trim: false });
192+
continue;
193+
}
194+
// Room/event bytes stay opaque; only the structural thread marker is folded.
195+
spans.push({ start: tailStart, end: tailStart + markerIndex, trim: false });
196+
const threadIdStart = tailStart + markerIndex + threadMarker.length;
197+
if (threadIdStart < raw.length) {
198+
spans.push({ start: threadIdStart, end: raw.length, trim: false });
212199
}
213200
}
214201
return spans;

0 commit comments

Comments
 (0)