Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: replace binarySearchByDateEqualOrNearestGreater with findIndexInSortedArray \w midpoint match #1370

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 7 additions & 32 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ export const findIndexInSortedArray = <T, L>({

const comparableMiddle = selectValueToCompare(sortedArray[middle]);

// if (comparableNeedle === comparableMiddle) return middle;
if (comparableNeedle === comparableMiddle) return middle;

if (
(sortDirection === 'ascending' && comparableNeedle < comparableMiddle) ||
Expand Down Expand Up @@ -499,36 +499,6 @@ type MessagePaginationUpdatedParams<StreamChatGenerics extends ExtendableGeneric
messagePaginationOptions?: MessagePaginationOptions;
};

export function binarySearchByDateEqualOrNearestGreater(
array: {
created_at?: string;
}[],
targetDate: Date,
): number {
let left = 0;
let right = array.length - 1;

while (left <= right) {
const mid = Math.floor((left + right) / 2);
const midCreatedAt = array[mid].created_at;
if (!midCreatedAt) {
left += 1;
continue;
}
const midDate = new Date(midCreatedAt);

if (midDate.getTime() === targetDate.getTime()) {
return mid;
} else if (midDate.getTime() < targetDate.getTime()) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return left;
}

const messagePaginationCreatedAtAround = <StreamChatGenerics extends ExtendableGenerics = DefaultGenerics>({
parentSet,
requestedPageSize,
Expand Down Expand Up @@ -580,7 +550,12 @@ const messagePaginationCreatedAtAround = <StreamChatGenerics extends ExtendableG
updateHasPrev = firstPageMsgIsFirstInSet;
updateHasNext = lastPageMsgIsLastInSet;
const midPointByCount = Math.floor(returnedPage.length / 2);
const midPointByCreationDate = binarySearchByDateEqualOrNearestGreater(returnedPage, createdAtAroundDate);
const midPointByCreationDate = findIndexInSortedArray<{ created_at: Date }, number>({
needle: { created_at: createdAtAroundDate },
sortedArray: returnedPage.map(formatMessage),
sortDirection: 'ascending',
selectValueToCompare: (message) => message.created_at.getTime(),
});

if (midPointByCreationDate !== -1) {
hasPrev = midPointByCount <= midPointByCreationDate;
Expand Down
6 changes: 5 additions & 1 deletion test/unit/channel.js
Original file line number Diff line number Diff line change
Expand Up @@ -1275,9 +1275,13 @@ describe('Channel.query', async () => {
it('should update pagination for queried message set to prevent more pagination', async () => {
const client = await getClientWithUser();
const channel = client.channel('messaging', uuidv4());
const timestamp = new Date('2024-01-01T00:00:00.000Z').getTime();

const mockedChannelQueryResponse = {
...mockChannelQueryResponse,
messages: Array.from({ length: DEFAULT_QUERY_CHANNEL_MESSAGE_LIST_PAGE_SIZE - 1 }, generateMsg),
messages: Array.from({ length: DEFAULT_QUERY_CHANNEL_MESSAGE_LIST_PAGE_SIZE - 1 }, (_, index) =>
generateMsg({ created_at: new Date(timestamp + index * 1000).toISOString() }),
),
};
const mock = sinon.mock(client);
mock.expects('post').returns(Promise.resolve(mockedChannelQueryResponse));
Expand Down
102 changes: 78 additions & 24 deletions test/unit/channel_state.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ describe('ChannelState addMessagesSorted', function () {
expect(state.messages).to.have.length(10);
state.addMessagesSorted([generateMsg({ id: 'id', date: `2020-01-01T00:00:00.007Z` })]);
expect(state.messages).to.have.length(11);
expect(state.messages[7].id).to.be.equal('7');
expect(state.messages[8].id).to.be.equal('id');
expect(state.messages[7].id).to.be.equal('id');
expect(state.messages[8].id).to.be.equal('7');
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One hurdle of the midpoint check addition is that message with the same created_at will be added before existing one but since the existence of the messages with the same created_at in real-world applications is almost impossible - I adjusted the test.

Even without midpoint check, the previous solution - in case of multiple messages with the same created_at - the new message would be placed at most one index after the already existing one which is still incorrect.

});

it('add lots of messages in order', async function () {
Expand Down Expand Up @@ -208,8 +208,22 @@ describe('ChannelState addMessagesSorted', function () {

it('should add messages to new message set', () => {
const state = new ChannelState();
state.addMessagesSorted([generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })]);
state.addMessagesSorted([generateMsg({ id: '0' }), generateMsg({ id: '1' })], false, false, true, 'new');

state.addMessagesSorted([
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
]);
state.addMessagesSorted(
[
generateMsg({ id: '0', created_at: '2020-01-01T00:00:00.004Z' }),
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.005Z' }),
],
false,
false,
true,
'new',
);

expect(state.messages.length).to.be.equal(3);
expect(state.messages[0].id).to.be.equal('12');
Expand All @@ -223,7 +237,11 @@ describe('ChannelState addMessagesSorted', function () {
it('should add messages to current message set', () => {
const state = new ChannelState();
state.addMessagesSorted(
[generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })],
[
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
],
false,
false,
true,
Expand All @@ -239,7 +257,11 @@ describe('ChannelState addMessagesSorted', function () {
it('should add messages to latest message set', () => {
const state = new ChannelState();
state.addMessagesSorted(
[generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })],
[
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
],
false,
false,
true,
Expand All @@ -258,17 +280,37 @@ describe('ChannelState addMessagesSorted', function () {

it(`should add messages to latest message set when it's not currently active`, () => {
const state = new ChannelState();

state.addMessagesSorted(
[generateMsg({ id: '12' }), generateMsg({ id: '13' }), generateMsg({ id: '14' })],
[
generateMsg({ id: '12', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '13', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '14', created_at: '2020-01-01T00:00:00.003Z' }),
],
false,
false,
true,
'latest',
);
state.addMessagesSorted([generateMsg({ id: '0' }), generateMsg({ id: '1' })], false, false, true, 'new');
state.addMessagesSorted(
[
generateMsg({ id: '0', created_at: '2020-01-01T00:00:00.004Z' }),
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.005Z' }),
],
false,
false,
true,
'new',
);
state.messageSets[0].isCurrent = false;
state.messageSets[1].isCurrent = true;
state.addMessagesSorted([generateMsg({ id: '15' })], false, false, true, 'latest');
state.addMessagesSorted(
[generateMsg({ id: '15', created_at: '2020-01-01T00:00:00.006Z' })],
false,
false,
true,
'latest',
);

expect(state.latestMessages.length).to.be.equal(4);
expect(state.latestMessages[3].id).to.be.equal('15');
Expand Down Expand Up @@ -684,10 +726,10 @@ describe('deleteUserMessages', () => {
const user1 = generateUser();
const user2 = generateUser();

const m1u1 = generateMsg({ user: user1 });
const m2u1 = generateMsg({ user: user1 });
const m1u2 = generateMsg({ user: user2 });
const m2u2 = generateMsg({ user: user2 });
const m1u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.001Z' });
const m2u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.002Z' });
const m1u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.003Z' });
const m2u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.004Z' });

state.addMessagesSorted([m1u1, m2u1, m1u2, m2u2]);

Expand Down Expand Up @@ -719,10 +761,10 @@ describe('deleteUserMessages', () => {
const user1 = generateUser();
const user2 = generateUser();

const m1u1 = generateMsg({ user: user1 });
const m2u1 = generateMsg({ user: user1 });
const m1u2 = generateMsg({ user: user2 });
const m2u2 = generateMsg({ user: user2 });
const m1u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.001Z' });
const m2u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.002Z' });
const m1u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.003Z' });
const m2u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.004Z' });

state.addMessagesSorted([m1u1, m2u1, m1u2, m2u2]);
expect(state.messages).to.have.length(4);
Expand Down Expand Up @@ -755,10 +797,10 @@ describe('updateUserMessages', () => {
let user1 = generateUser();
const user2 = generateUser();

const m1u1 = generateMsg({ user: user1 });
const m2u1 = generateMsg({ user: user1 });
const m1u2 = generateMsg({ user: user2 });
const m2u2 = generateMsg({ user: user2 });
const m1u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.001Z' });
const m2u1 = generateMsg({ user: user1, created_at: '2020-01-01T00:00:00.002Z' });
const m1u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.003Z' });
const m2u2 = generateMsg({ user: user2, created_at: '2020-01-01T00:00:00.004Z' });

state.addMessagesSorted([m1u1, m2u1, m1u2, m2u2]);

Expand All @@ -785,7 +827,11 @@ describe('updateUserMessages', () => {
describe('latestMessages', () => {
it('should return latest messages - if they are the current message set', () => {
const state = new ChannelState();
const messages = [generateMsg({ id: '1' }), generateMsg({ id: '2' }), generateMsg({ id: '3' })];
const messages = [
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '2', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '3', created_at: '2020-01-01T00:00:00.003Z' }),
];
state.addMessagesSorted(messages);

expect(state.latestMessages.length).to.be.equal(messages.length);
Expand All @@ -796,7 +842,11 @@ describe('latestMessages', () => {

it('should return latest messages - if they are not the current message set', () => {
const state = new ChannelState();
const latestMessages = [generateMsg({ id: '1' }), generateMsg({ id: '2' }), generateMsg({ id: '3' })];
const latestMessages = [
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '2', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '3', created_at: '2020-01-01T00:00:00.003Z' }),
];
state.addMessagesSorted(latestMessages);
const newMessages = [generateMsg({ id: '0' })];
state.addMessagesSorted(newMessages, false, true, true, 'new');
Expand All @@ -811,7 +861,11 @@ describe('latestMessages', () => {

it('should return latest messages - if they are not the current message set and new messages received', () => {
const state = new ChannelState();
const latestMessages = [generateMsg({ id: '1' }), generateMsg({ id: '2' }), generateMsg({ id: '3' })];
const latestMessages = [
generateMsg({ id: '1', created_at: '2020-01-01T00:00:00.001Z' }),
generateMsg({ id: '2', created_at: '2020-01-01T00:00:00.002Z' }),
generateMsg({ id: '3', created_at: '2020-01-01T00:00:00.003Z' }),
];
state.addMessagesSorted(latestMessages);
const newMessages = [generateMsg({ id: '0' })];
state.addMessagesSorted(newMessages, false, true, true, 'new');
Expand Down
20 changes: 0 additions & 20 deletions test/unit/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2690,23 +2690,3 @@ describe('messageSetPagination', () => {
});
});
});

describe('', () => {
const messages = [
{ created_at: '2024-08-05T08:55:00.199808Z', id: '0' },
{ created_at: '2024-08-05T08:55:01.199808Z', id: '1' },
{ created_at: '2024-08-05T08:55:02.199808Z', id: '2' },
{ created_at: '2024-08-05T08:55:03.199808Z', id: '3' },
{ created_at: '2024-08-05T08:55:04.199808Z', id: '4' },
{ created_at: '2024-08-05T08:55:05.199808Z', id: '5' },
{ created_at: '2024-08-05T08:55:06.199808Z', id: '6' },
{ created_at: '2024-08-05T08:55:07.199808Z', id: '7' },
{ created_at: '2024-08-05T08:55:08.199808Z', id: '8' },
];
it('finds the nearest newer item', () => {
expect(binarySearchByDateEqualOrNearestGreater(messages, new Date('2024-08-05T08:55:02.299808Z'))).to.eql(3);
});
it('finds the nearest matching item', () => {
expect(binarySearchByDateEqualOrNearestGreater(messages, new Date('2024-08-05T08:55:07.199808Z'))).to.eql(7);
});
});
Comment on lines -2694 to -2712
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to utils.test.ts with additions.

92 changes: 84 additions & 8 deletions test/unit/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { v4 as uuidv4 } from 'uuid';

import { generateMsg } from './test-utils/generateMessage';

import { addToMessageList, formatMessage } from '../../src/utils';
import { addToMessageList, findIndexInSortedArray, formatMessage } from '../../src/utils';

import type { FormatMessageResponse, MessageResponse } from '../../src';

describe('addToMessageList', () => {
const timestamp = new Date('2024-09-18T15:30:00.000Z').getTime();
const timestamp = new Date('2024-01-01T00:00:00.000Z').getTime();
// messages with each created_at 10 seconds apart
let messagesBefore: FormatMessageResponse[];

Expand Down Expand Up @@ -93,15 +93,91 @@ describe('addToMessageList', () => {
});

it("updates an existing message that wasn't filtered due to changed timestamp (timestampChanged)", () => {
const newMessage = getNewFormattedMessage({ timeOffset: 30 * 1000, id: messagesBefore[4].id });
const newMessage = getNewFormattedMessage({ timeOffset: 30 * 1000, id: messagesBefore[3].id });

expect(messagesBefore[4].id).to.equal(newMessage.id);
expect(messagesBefore[4].text).to.not.equal(newMessage.text);
expect(messagesBefore[4]).to.not.equal(newMessage);
expect(messagesBefore[3].id).to.equal(newMessage.id);
expect(messagesBefore[3].text).to.not.equal(newMessage.text);
expect(messagesBefore[3]).to.not.equal(newMessage);

const messagesAfter = addToMessageList(messagesBefore, newMessage, false, 'created_at', false);
const messagesAfter = addToMessageList(messagesBefore, newMessage, false);

expect(messagesAfter).to.have.length(5);
expect(messagesAfter[4]).to.equal(newMessage);
expect(messagesAfter[3]).to.equal(newMessage);
});
Comment on lines 95 to +106
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I messed up here previously.

});

describe('findIndexInSortedArray', () => {
const timestamp = new Date('2024-01-01T00:00:00.000Z').getTime();

const generateMessages = ({ count = 10, sort = 'desc' }: { count?: number; sort?: 'asc' | 'desc' } = {}) => {
const messages = Array.from({ length: count }, (_, index) =>
generateMsg({ created_at: new Date(timestamp + index * 10 * 1000).toISOString() }),
);

if (sort === 'desc') {
messages.reverse();
}

return messages as MessageResponse[];
};

describe('ascending order', () => {
const messages = generateMessages({ sort: 'asc' }).map(formatMessage);

it('finds index of the message with closest matching created_at', () => {
const newMessage = formatMessage(generateMsg({ created_at: new Date(timestamp + 22 * 1000) }) as MessageResponse);

const index = findIndexInSortedArray({
needle: newMessage,
sortedArray: messages,
sortDirection: 'ascending',
selectValueToCompare: (v) => v.created_at.getTime(),
});

expect(index).to.equal(3);
});

it('finds exact index', () => {
const newMessage = formatMessage(generateMsg({ created_at: new Date(timestamp + 20 * 1000) }) as MessageResponse);

const index = findIndexInSortedArray({
needle: newMessage,
sortedArray: messages,
sortDirection: 'ascending',
selectValueToCompare: (v) => v.created_at.getTime(),
});

expect(index).to.equal(2);
});
});

describe('descending order', () => {
const messages = generateMessages({ sort: 'desc' }).map(formatMessage);

it('finds index of the message with closest matching created_at', () => {
const newMessage = formatMessage(generateMsg({ created_at: new Date(timestamp + 22 * 1000) }) as MessageResponse);

const index = findIndexInSortedArray({
needle: newMessage,
sortedArray: messages,
sortDirection: 'descending',
selectValueToCompare: (v) => v.created_at.getTime(),
});

expect(index).to.equal(7);
});

it('finds exact index', () => {
const newMessage = formatMessage(generateMsg({ created_at: new Date(timestamp + 10 * 1000) }) as MessageResponse);

const index = findIndexInSortedArray({
needle: newMessage,
sortedArray: messages,
sortDirection: 'descending',
selectValueToCompare: (v) => v.created_at.getTime(),
});

expect(index).to.equal(8);
});
});
});
Loading