fix(persona): serialize per-message-profile account data writes

This commit is contained in:
Erwan Leboucher authored and 7w1 committed 2026-08-05 21:13:35 -05:00
1 parent 53226ab1d9
commit a466ba15a0
3 files changed
+124 -36

No files matched your search

@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
import type { MatrixClient } from '$types/matrix-sdk';
import { describe, expect, it, vi } from 'vitest';
import {
extractCircumfixProxyTagsFromKey,
@@ -8,6 +9,8 @@ import {
type PerMessageProfileProxyAssociationV1,
proxyNeedsMigration,
createProxyKey,
setCurrentlyUsedPerMessageProfileIdForAccount,
setCurrentlyUsedPerMessageProfileIdForRoom,
} from './usePerMessageProfile';
describe('migratePerMessageProfileProxyAssociation', () => {
@@ -132,3 +135,60 @@ describe('parsePerMessageProfileProxyAssociation', () => {
expect(parsed.regex.test('[no] trailing')).toBe(false);
});
});
describe('per-message profile persistence', () => {
it('serializes room writes and reads the latest account data snapshot', async () => {
const associations: Record<string, { profileId: string }> = {};
const writes: unknown[] = [];
let releaseFirstWrite!: () => void;
const firstWrite = new Promise<void>((resolve) => {
releaseFirstWrite = resolve;
});
const mx = {
getAccountData: vi.fn<() => { getContent: () => { associations: typeof associations } }>(
() => ({ getContent: () => ({ associations }) })
),
setAccountData: vi.fn<
(_event: unknown, content: { associations: typeof associations }) => Promise<void>
>(async (_event, content) => {
writes.push(content);
if (writes.length === 1) await firstWrite;
Object.assign(associations, content.associations);
}),
} as unknown as MatrixClient;
const first = setCurrentlyUsedPerMessageProfileIdForRoom(mx, '!room:example.org', 'first');
const second = setCurrentlyUsedPerMessageProfileIdForRoom(mx, '!room:example.org', 'second');
await vi.waitFor(() => expect(writes).toHaveLength(1));
releaseFirstWrite();
await Promise.all([first, second]);
expect(writes).toHaveLength(2);
expect((writes[1] as { associations: typeof associations }).associations).toEqual({
'!room:example.org': { profileId: 'second' },
});
});
it('continues queued account writes after a rejected write', async () => {
const writes: string[] = [];
const mx = {
setAccountData: vi.fn<
(_event: unknown, content: { association: { profileId: string } }) => Promise<void>
>(async (_event, content) => {
writes.push(content.association.profileId);
if (writes.length === 1) throw new Error('write failed');
}),
deleteAccountData: vi.fn<(...args: unknown[]) => void>(),
} as unknown as MatrixClient;
const first = setCurrentlyUsedPerMessageProfileIdForAccount(mx, 'first');
const second = setCurrentlyUsedPerMessageProfileIdForAccount(mx, 'second');
await expect(first).rejects.toThrow('write failed');
await expect(second).resolves.toBeUndefined();
expect(writes).toEqual(['first', 'second']);
});
});
+43 -35
View File
@@ -4,16 +4,20 @@ import type { PronounSet } from '$utils/pronouns';
import type { MatrixClient } from '$types/matrix-sdk';
import { CustomAccountDataEvent } from '$types/matrix/accountData';
import type { ColorSet } from './useUserProfile';
import { MATRIX_UNSTABLE_COLORS } from '$unstable/prefixes';
import {
MATRIX_UNSTABLE_COLORS,
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_CIRCUMFIX_PROPERTY_NAME,
MATRIX_SABLE_UNSTABLE_MSC4461_TRIGGER_SUFFIX_PROPERTY_NAME,
MATRIX_UNSTABLE_MSC4461_ACCOUNT_PER_MESSAGE_PROFILES_PROPERTY_NAME,
MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME,
} from '$unstable/prefixes';
import { createKeyedQueue } from '$utils/keyedQueue';
const ACCOUNT_DATA_PREFIX = CustomAccountDataEvent.SablePerProfileMessageProfiles;
/** Account data is read-modify-written, so writes to the same key must not interleave. */
const enqueueProfilePersistence = createKeyedQueue();
/**
* @deprecated in favour if {@link PerMessageProfileMsc4461}
* a per message profile
@@ -622,32 +626,34 @@ export async function setCurrentlyUsedPerMessageProfileIdForRoom(
validUntil?: number,
reset?: boolean
) {
const accountData = mx.getAccountData(
`${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters<typeof mx.getAccountData>[0]
);
const content: PerMessageProfileRoomAssociationWrapper | undefined = accountData?.getContent();
const associations = getAssociationsMap(content);
return enqueueProfilePersistence('roomassociation', async () => {
const accountData = mx.getAccountData(
`${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters<typeof mx.getAccountData>[0]
);
const content: PerMessageProfileRoomAssociationWrapper | undefined = accountData?.getContent();
const associations = getAssociationsMap(content);
if (reset) {
associations.delete(roomId);
if (reset) {
associations.delete(roomId);
await mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters<typeof mx.setAccountData>[0],
{ associations: associationsMapToObject(associations) } as Parameters<
typeof mx.setAccountData
>[1]
);
return;
}
if (!profileId) {
throw new Error("profile Id is empty, yet it isn't a reset");
}
associations.set(roomId, { profileId, validUntil });
await mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters<typeof mx.setAccountData>[0],
{ associations: associationsMapToObject(associations) } as Parameters<
typeof mx.setAccountData
>[1]
);
return;
}
if (!profileId) {
throw new Error("profile Id is empty, yet it isn't a reset");
}
associations.set(roomId, { profileId, validUntil });
await mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.roomassociation` as Parameters<typeof mx.setAccountData>[0],
{ associations: associationsMapToObject(associations) } as Parameters<
typeof mx.setAccountData
>[1]
);
});
}
/**
@@ -659,22 +665,24 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount(
validUntil?: number,
reset?: boolean
) {
if (reset) {
await mx.deleteAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.setAccountData>[0]
return enqueueProfilePersistence('globalassociation', async () => {
if (reset) {
await mx.deleteAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.setAccountData>[0]
);
return;
}
if (!profileId) {
throw new Error("profile Id is empty, yet it isn't a reset");
}
const association: PerMessageProfileRoomAssociation = { profileId, validUntil };
await mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.setAccountData>[0],
{ association: association } as Parameters<typeof mx.setAccountData>[1]
);
return;
}
if (!profileId) {
throw new Error("profile Id is empty, yet it isn't a reset");
}
const association: PerMessageProfileRoomAssociation = { profileId, validUntil };
await mx.setAccountData(
`${ACCOUNT_DATA_PREFIX}.globalassociation` as Parameters<typeof mx.setAccountData>[0],
{ association: association } as Parameters<typeof mx.setAccountData>[1]
);
});
}
/*
+20
View File
@@ -0,0 +1,20 @@
/** Serializes operations per key so read-modify-write sequences cannot interleave. */
export function createKeyedQueue() {
const tails = new Map<string, Promise<void>>();
return function run<T>(key: string, operation: () => T | PromiseLike<T>): Promise<T> {
const previous = tails.get(key) ?? Promise.resolve();
const current = previous.catch(() => undefined).then(operation);
const tail = current.then(
() => undefined,
() => undefined
);
tails.set(key, tail);
void tail.then(() => {
if (tails.get(key) === tail) tails.delete(key);
});
return current;
};
}