|
| 1 | +/* |
| 2 | +Copyright 2022 The Matrix.org Foundation C.I.C. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +import MockHttpBackend from 'matrix-mock-request'; |
| 18 | +import { indexedDB as fakeIndexedDB } from 'fake-indexeddb'; |
| 19 | + |
| 20 | +import { IHttpOpts, IndexedDBStore, MatrixEvent, MemoryStore, Room } from "../../src"; |
| 21 | +import { MatrixClient } from "../../src/client"; |
| 22 | +import { ToDeviceBatch } from '../../src/models/ToDeviceMessage'; |
| 23 | +import { logger } from '../../src/logger'; |
| 24 | + |
| 25 | +const FAKE_USER = "@alice:example.org"; |
| 26 | +const FAKE_DEVICE_ID = "AAAAAAAA"; |
| 27 | +const FAKE_PAYLOAD = { |
| 28 | + "foo": 42, |
| 29 | +}; |
| 30 | +const EXPECTED_BODY = { |
| 31 | + messages: { |
| 32 | + [FAKE_USER]: { |
| 33 | + [FAKE_DEVICE_ID]: FAKE_PAYLOAD, |
| 34 | + }, |
| 35 | + }, |
| 36 | +}; |
| 37 | + |
| 38 | +const FAKE_MSG = { |
| 39 | + userId: FAKE_USER, |
| 40 | + deviceId: FAKE_DEVICE_ID, |
| 41 | + payload: FAKE_PAYLOAD, |
| 42 | +}; |
| 43 | + |
| 44 | +enum StoreType { |
| 45 | + Memory = 'Memory', |
| 46 | + IndexedDB = 'IndexedDB', |
| 47 | +} |
| 48 | + |
| 49 | +// Jest now uses @sinonjs/fake-timers which exposes tickAsync() and a number of |
| 50 | +// other async methods which break the event loop, letting scheduled promise |
| 51 | +// callbacks run. Unfortunately, Jest doesn't expose these, so we have to do |
| 52 | +// it manually (this is what sinon does under the hood). We do both in a loop |
| 53 | +// until the thing we expect happens: hopefully this is the least flakey way |
| 54 | +// and avoids assuming anything about the app's behaviour. |
| 55 | +const realSetTimeout = setTimeout; |
| 56 | +function flushPromises() { |
| 57 | + return new Promise(r => { |
| 58 | + realSetTimeout(r, 1); |
| 59 | + }); |
| 60 | +} |
| 61 | + |
| 62 | +async function flushAndRunTimersUntil(cond: () => boolean) { |
| 63 | + while (!cond()) { |
| 64 | + await flushPromises(); |
| 65 | + if (cond()) break; |
| 66 | + jest.advanceTimersToNextTimer(); |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +describe.each([ |
| 71 | + [StoreType.Memory], [StoreType.IndexedDB], |
| 72 | +])("queueToDevice (%s store)", function(storeType) { |
| 73 | + let httpBackend: MockHttpBackend; |
| 74 | + let client: MatrixClient; |
| 75 | + |
| 76 | + beforeEach(function() { |
| 77 | + httpBackend = new MockHttpBackend(); |
| 78 | + |
| 79 | + const store = storeType === StoreType.IndexedDB ? |
| 80 | + new IndexedDBStore({ indexedDB: fakeIndexedDB }) : new MemoryStore(); |
| 81 | + |
| 82 | + client = new MatrixClient({ |
| 83 | + baseUrl: "https://my.home.server", |
| 84 | + accessToken: "my.access.token", |
| 85 | + request: httpBackend.requestFn as IHttpOpts["request"], |
| 86 | + store, |
| 87 | + }); |
| 88 | + }); |
| 89 | + |
| 90 | + afterEach(function() { |
| 91 | + jest.useRealTimers(); |
| 92 | + }); |
| 93 | + |
| 94 | + it("sends a to-device message", async function() { |
| 95 | + httpBackend.when( |
| 96 | + "PUT", "/sendToDevice/org.example.foo/", |
| 97 | + ).check((request) => { |
| 98 | + expect(request.data).toEqual(EXPECTED_BODY); |
| 99 | + }).respond(200, {}); |
| 100 | + |
| 101 | + await client.queueToDevice({ |
| 102 | + eventType: "org.example.foo", |
| 103 | + batch: [ |
| 104 | + FAKE_MSG, |
| 105 | + ], |
| 106 | + }); |
| 107 | + |
| 108 | + await httpBackend.flushAllExpected(); |
| 109 | + }); |
| 110 | + |
| 111 | + it("retries on error", async function() { |
| 112 | + jest.useFakeTimers(); |
| 113 | + |
| 114 | + httpBackend.when( |
| 115 | + "PUT", "/sendToDevice/org.example.foo/", |
| 116 | + ).respond(500); |
| 117 | + |
| 118 | + httpBackend.when( |
| 119 | + "PUT", "/sendToDevice/org.example.foo/", |
| 120 | + ).check((request) => { |
| 121 | + expect(request.data).toEqual(EXPECTED_BODY); |
| 122 | + }).respond(200, {}); |
| 123 | + |
| 124 | + await client.queueToDevice({ |
| 125 | + eventType: "org.example.foo", |
| 126 | + batch: [ |
| 127 | + FAKE_MSG, |
| 128 | + ], |
| 129 | + }); |
| 130 | + expect(httpBackend.flushSync(null, 1)).toEqual(1); |
| 131 | + |
| 132 | + await flushAndRunTimersUntil(() => httpBackend.requests.length > 0); |
| 133 | + |
| 134 | + expect(httpBackend.flushSync(null, 1)).toEqual(1); |
| 135 | + }); |
| 136 | + |
| 137 | + it("stops retrying on 4xx errors", async function() { |
| 138 | + jest.useFakeTimers(); |
| 139 | + |
| 140 | + httpBackend.when( |
| 141 | + "PUT", "/sendToDevice/org.example.foo/", |
| 142 | + ).respond(400); |
| 143 | + |
| 144 | + await client.queueToDevice({ |
| 145 | + eventType: "org.example.foo", |
| 146 | + batch: [ |
| 147 | + FAKE_MSG, |
| 148 | + ], |
| 149 | + }); |
| 150 | + expect(httpBackend.flushSync(null, 1)).toEqual(1); |
| 151 | + |
| 152 | + // Asserting that another request is never made is obviously |
| 153 | + // a bit tricky - we just flush the queue what should hopefully |
| 154 | + // be plenty of times and assert that nothing comes through. |
| 155 | + let tries = 0; |
| 156 | + await flushAndRunTimersUntil(() => ++tries === 10); |
| 157 | + |
| 158 | + expect(httpBackend.requests.length).toEqual(0); |
| 159 | + }); |
| 160 | + |
| 161 | + it("honours ratelimiting", async function() { |
| 162 | + jest.useFakeTimers(); |
| 163 | + |
| 164 | + // pick something obscure enough it's unlikley to clash with a |
| 165 | + // retry delay the algorithm uses anyway |
| 166 | + const retryDelay = 279 * 1000; |
| 167 | + |
| 168 | + httpBackend.when( |
| 169 | + "PUT", "/sendToDevice/org.example.foo/", |
| 170 | + ).respond(429, { |
| 171 | + errcode: "M_LIMIT_EXCEEDED", |
| 172 | + retry_after_ms: retryDelay, |
| 173 | + }); |
| 174 | + |
| 175 | + httpBackend.when( |
| 176 | + "PUT", "/sendToDevice/org.example.foo/", |
| 177 | + ).respond(200, {}); |
| 178 | + |
| 179 | + await client.queueToDevice({ |
| 180 | + eventType: "org.example.foo", |
| 181 | + batch: [ |
| 182 | + FAKE_MSG, |
| 183 | + ], |
| 184 | + }); |
| 185 | + expect(httpBackend.flushSync(null, 1)).toEqual(1); |
| 186 | + await flushPromises(); |
| 187 | + |
| 188 | + logger.info("Advancing clock to just before expected retry time..."); |
| 189 | + |
| 190 | + jest.advanceTimersByTime(retryDelay - 1000); |
| 191 | + await flushPromises(); |
| 192 | + |
| 193 | + expect(httpBackend.requests.length).toEqual(0); |
| 194 | + |
| 195 | + logger.info("Advancing clock past expected retry time..."); |
| 196 | + |
| 197 | + jest.advanceTimersByTime(2000); |
| 198 | + await flushPromises(); |
| 199 | + |
| 200 | + expect(httpBackend.flushSync(null, 1)).toEqual(1); |
| 201 | + }); |
| 202 | + |
| 203 | + it("retries on retryImmediately()", async function() { |
| 204 | + httpBackend.when("GET", "/_matrix/client/versions").respond(200, { |
| 205 | + versions: ["r0.0.1"], |
| 206 | + }); |
| 207 | + |
| 208 | + await Promise.all([client.startClient(), httpBackend.flush(null, 1, 20)]); |
| 209 | + |
| 210 | + try { |
| 211 | + httpBackend.when( |
| 212 | + "PUT", "/sendToDevice/org.example.foo/", |
| 213 | + ).respond(500); |
| 214 | + |
| 215 | + httpBackend.when( |
| 216 | + "PUT", "/sendToDevice/org.example.foo/", |
| 217 | + ).respond(200, {}); |
| 218 | + |
| 219 | + await client.queueToDevice({ |
| 220 | + eventType: "org.example.foo", |
| 221 | + batch: [ |
| 222 | + FAKE_MSG, |
| 223 | + ], |
| 224 | + }); |
| 225 | + expect(await httpBackend.flush(null, 1, 1)).toEqual(1); |
| 226 | + await flushPromises(); |
| 227 | + |
| 228 | + client.retryImmediately(); |
| 229 | + |
| 230 | + expect(await httpBackend.flush(null, 1, 20)).toEqual(1); |
| 231 | + } finally { |
| 232 | + client.stopClient(); |
| 233 | + } |
| 234 | + }); |
| 235 | + |
| 236 | + it("retries on when client is started", async function() { |
| 237 | + httpBackend.when("GET", "/_matrix/client/versions").respond(200, { |
| 238 | + versions: ["r0.0.1"], |
| 239 | + }); |
| 240 | + |
| 241 | + await Promise.all([client.startClient(), httpBackend.flush("/_matrix/client/versions", 1, 20)]); |
| 242 | + |
| 243 | + try { |
| 244 | + httpBackend.when( |
| 245 | + "PUT", "/sendToDevice/org.example.foo/", |
| 246 | + ).respond(500); |
| 247 | + |
| 248 | + httpBackend.when( |
| 249 | + "PUT", "/sendToDevice/org.example.foo/", |
| 250 | + ).respond(200, {}); |
| 251 | + |
| 252 | + await client.queueToDevice({ |
| 253 | + eventType: "org.example.foo", |
| 254 | + batch: [ |
| 255 | + FAKE_MSG, |
| 256 | + ], |
| 257 | + }); |
| 258 | + expect(await httpBackend.flush(null, 1, 1)).toEqual(1); |
| 259 | + await flushPromises(); |
| 260 | + |
| 261 | + client.stopClient(); |
| 262 | + await Promise.all([client.startClient(), httpBackend.flush("/_matrix/client/versions", 1, 20)]); |
| 263 | + |
| 264 | + expect(await httpBackend.flush(null, 1, 20)).toEqual(1); |
| 265 | + } finally { |
| 266 | + client.stopClient(); |
| 267 | + } |
| 268 | + }); |
| 269 | + |
| 270 | + it("retries when a message is retried", async function() { |
| 271 | + httpBackend.when("GET", "/_matrix/client/versions").respond(200, { |
| 272 | + versions: ["r0.0.1"], |
| 273 | + }); |
| 274 | + |
| 275 | + await Promise.all([client.startClient(), httpBackend.flush(null, 1, 20)]); |
| 276 | + |
| 277 | + try { |
| 278 | + httpBackend.when( |
| 279 | + "PUT", "/sendToDevice/org.example.foo/", |
| 280 | + ).respond(500); |
| 281 | + |
| 282 | + httpBackend.when( |
| 283 | + "PUT", "/sendToDevice/org.example.foo/", |
| 284 | + ).respond(200, {}); |
| 285 | + |
| 286 | + await client.queueToDevice({ |
| 287 | + eventType: "org.example.foo", |
| 288 | + batch: [ |
| 289 | + FAKE_MSG, |
| 290 | + ], |
| 291 | + }); |
| 292 | + |
| 293 | + expect(await httpBackend.flush(null, 1, 1)).toEqual(1); |
| 294 | + await flushPromises(); |
| 295 | + |
| 296 | + const dummyEvent = new MatrixEvent({ |
| 297 | + event_id: "!fake:example.org", |
| 298 | + }); |
| 299 | + const mockRoom = { |
| 300 | + updatePendingEvent: jest.fn(), |
| 301 | + } as unknown as Room; |
| 302 | + client.resendEvent(dummyEvent, mockRoom); |
| 303 | + |
| 304 | + expect(await httpBackend.flush(null, 1, 20)).toEqual(1); |
| 305 | + } finally { |
| 306 | + client.stopClient(); |
| 307 | + } |
| 308 | + }); |
| 309 | + |
| 310 | + it("splits many messages into multiple HTTP requests", async function() { |
| 311 | + const batch: ToDeviceBatch = { |
| 312 | + eventType: "org.example.foo", |
| 313 | + batch: [], |
| 314 | + }; |
| 315 | + |
| 316 | + for (let i = 0; i <= 20; ++i) { |
| 317 | + batch.batch.push({ |
| 318 | + userId: `@user${i}:example.org`, |
| 319 | + deviceId: FAKE_DEVICE_ID, |
| 320 | + payload: FAKE_PAYLOAD, |
| 321 | + }); |
| 322 | + } |
| 323 | + |
| 324 | + httpBackend.when( |
| 325 | + "PUT", "/sendToDevice/org.example.foo/", |
| 326 | + ).check((request) => { |
| 327 | + expect(Object.keys(request.data.messages).length).toEqual(20); |
| 328 | + }).respond(200, {}); |
| 329 | + |
| 330 | + httpBackend.when( |
| 331 | + "PUT", "/sendToDevice/org.example.foo/", |
| 332 | + ).check((request) => { |
| 333 | + expect(Object.keys(request.data.messages).length).toEqual(1); |
| 334 | + }).respond(200, {}); |
| 335 | + |
| 336 | + await client.queueToDevice(batch); |
| 337 | + await httpBackend.flushAllExpected(); |
| 338 | + }); |
| 339 | +}); |
0 commit comments