Skip to content

Commit b4672e2

Browse files
authored
Use client logger in more places (core code) (#4899)
* Use client logger for sync Use the logger attached to the MatrixClient when writing log messages out of the sync api. This helps figure out what's going on when multiple clients are running in the same JS environment. * Use client logger for to-device message queue * Use client logger in `PushProcessor.rewriteDefaultRules` * use client logger in `ServerCapabilities` * Mark global `logger` as deprecated
1 parent 940d358 commit b4672e2

10 files changed

+109
-86
lines changed

spec/integ/sliding-sync-sdk.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ describe("SlidingSyncSdk", () => {
126126
// assign client/httpBackend globals
127127
const setupClient = async (testOpts?: Partial<IStoredClientOpts & { withCrypto: boolean }>) => {
128128
testOpts = testOpts || {};
129-
const syncOpts: SyncApiOptions = {};
129+
const syncOpts: SyncApiOptions = { logger };
130130
const testClient = new TestClient(selfUserId, "DEVICE", selfAccessToken);
131131
httpBackend = testClient.httpBackend;
132132
client = testClient.client;

spec/unit/ToDeviceMessageQueue.spec.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { getMockClientWithEventEmitter } from "../test-utils/client";
55
import { StubStore } from "../../src/store/stub";
66
import { type IndexedToDeviceBatch } from "../../src/models/ToDeviceMessage";
77
import { SyncState } from "../../src/sync";
8+
import { logger } from "../../src/logger.ts";
89

910
describe("onResumedSync", () => {
1011
let batch: IndexedToDeviceBatch | null;
@@ -55,7 +56,7 @@ describe("onResumedSync", () => {
5556
}
5657
});
5758

58-
queue = new ToDeviceMessageQueue(mockClient);
59+
queue = new ToDeviceMessageQueue(mockClient, logger);
5960
});
6061

6162
it("resends queue after connectivity restored", async () => {

spec/unit/pushprocessor.spec.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
TweakName,
2929
} from "../../src";
3030
import { mockClientMethodsUser } from "../test-utils/client";
31+
import { logger } from "../../src/logger.ts";
3132

3233
const msc3914RoomCallRule: IPushRule = {
3334
rule_id: ".org.matrix.msc3914.rule.room.call",
@@ -209,7 +210,7 @@ describe("NotificationService", function () {
209210
msgtype: "m.text",
210211
},
211212
});
212-
matrixClient.pushRules = PushProcessor.rewriteDefaultRules(matrixClient.pushRules!);
213+
matrixClient.pushRules = PushProcessor.rewriteDefaultRules(logger, matrixClient.pushRules!);
213214
pushProcessor = new PushProcessor(matrixClient);
214215
});
215216

@@ -731,7 +732,7 @@ describe("Test PushProcessor.partsForDottedKey", function () {
731732

732733
describe("rewriteDefaultRules", () => {
733734
it("should add default rules in the correct order", () => {
734-
const pushRules = PushProcessor.rewriteDefaultRules({
735+
const pushRules = PushProcessor.rewriteDefaultRules(logger, {
735736
device: {},
736737
global: {
737738
content: [],
@@ -867,7 +868,7 @@ describe("rewriteDefaultRules", () => {
867868
});
868869

869870
it("should add missing msc3914 rule in correct place", () => {
870-
const pushRules = PushProcessor.rewriteDefaultRules({
871+
const pushRules = PushProcessor.rewriteDefaultRules(logger, {
871872
device: {},
872873
global: {
873874
// Sample push rules from a Synapse user.

src/ToDeviceMessageQueue.ts

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ limitations under the License.
1515
*/
1616

1717
import { ToDeviceMessageId } from "./@types/event.ts";
18-
import { logger } from "./logger.ts";
18+
import { type Logger } from "./logger.ts";
1919
import { type MatrixClient, ClientEvent } from "./client.ts";
2020
import { type MatrixError } from "./http-api/index.ts";
2121
import {
@@ -40,7 +40,10 @@ export class ToDeviceMessageQueue {
4040
private retryTimeout: ReturnType<typeof setTimeout> | null = null;
4141
private retryAttempts = 0;
4242

43-
public constructor(private client: MatrixClient) {}
43+
public constructor(
44+
private client: MatrixClient,
45+
private readonly logger: Logger,
46+
) {}
4447

4548
public start(): void {
4649
this.running = true;
@@ -67,7 +70,7 @@ export class ToDeviceMessageQueue {
6770
const msgmap = batchWithTxnId.batch.map(
6871
(msg) => `${msg.userId}/${msg.deviceId} (msgid ${msg.payload[ToDeviceMessageId]})`,
6972
);
70-
logger.info(
73+
this.logger.info(
7174
`Enqueuing batch of to-device messages. type=${batch.eventType} txnid=${batchWithTxnId.txnId}`,
7275
msgmap,
7376
);
@@ -83,7 +86,7 @@ export class ToDeviceMessageQueue {
8386

8487
if (this.sending || !this.running) return;
8588

86-
logger.debug("Attempting to send queued to-device messages");
89+
this.logger.debug("Attempting to send queued to-device messages");
8790

8891
this.sending = true;
8992
let headBatch: IndexedToDeviceBatch | null;
@@ -99,7 +102,7 @@ export class ToDeviceMessageQueue {
99102
// Make sure we're still running after the async tasks: if not, stop.
100103
if (!this.running) return;
101104

102-
logger.debug("All queued to-device messages sent");
105+
this.logger.debug("All queued to-device messages sent");
103106
} catch (e) {
104107
++this.retryAttempts;
105108
// eslint-disable-next-line @typescript-eslint/naming-convention
@@ -109,15 +112,15 @@ export class ToDeviceMessageQueue {
109112
// the scheduler function doesn't differentiate between fatal errors and just getting
110113
// bored and giving up for now
111114
if (Math.floor((<MatrixError>e).httpStatus! / 100) === 4) {
112-
logger.error("Fatal error when sending to-device message - dropping to-device batch!", e);
115+
this.logger.error("Fatal error when sending to-device message - dropping to-device batch!", e);
113116
await this.client.store.removeToDeviceBatch(headBatch!.id);
114117
} else {
115-
logger.info("Automatic retry limit reached for to-device messages.");
118+
this.logger.info("Automatic retry limit reached for to-device messages.");
116119
}
117120
return;
118121
}
119122

120-
logger.info(`Failed to send batch of to-device messages. Will retry in ${retryDelay}ms`, e);
123+
this.logger.info(`Failed to send batch of to-device messages. Will retry in ${retryDelay}ms`, e);
121124
this.retryTimeout = setTimeout(this.sendQueue, retryDelay);
122125
} finally {
123126
this.sending = false;
@@ -133,7 +136,7 @@ export class ToDeviceMessageQueue {
133136
contentMap.getOrCreate(item.userId).set(item.deviceId, item.payload);
134137
}
135138

136-
logger.info(
139+
this.logger.info(
137140
`Sending batch of ${batch.batch.length} to-device messages with ID ${batch.id} and txnId ${batch.txnId}`,
138141
);
139142

@@ -146,7 +149,7 @@ export class ToDeviceMessageQueue {
146149
*/
147150
private onResumedSync = (state: SyncState | null, oldState: SyncState | null): void => {
148151
if (state === SyncState.Syncing && oldState !== SyncState.Syncing) {
149-
logger.info(`Resuming queue after resumed sync`);
152+
this.logger.info(`Resuming queue after resumed sync`);
150153
this.sendQueue();
151154
}
152155
};

src/client.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1364,7 +1364,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
13641364
// the underlying session management and doesn't use any actual media capabilities
13651365
this.matrixRTC = new MatrixRTCSessionManager(this);
13661366

1367-
this.serverCapabilitiesService = new ServerCapabilities(this.http);
1367+
this.serverCapabilitiesService = new ServerCapabilities(this.logger, this.http);
13681368

13691369
this.on(ClientEvent.Sync, this.fixupRoomNotifications);
13701370

@@ -1386,7 +1386,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
13861386

13871387
this.roomNameGenerator = opts.roomNameGenerator;
13881388

1389-
this.toDeviceMessageQueue = new ToDeviceMessageQueue(this);
1389+
this.toDeviceMessageQueue = new ToDeviceMessageQueue(this, this.logger);
13901390

13911391
// The SDK doesn't really provide a clean way for events to recalculate the push
13921392
// actions for themselves, so we have to kinda help them out when they are encrypted.
@@ -1503,6 +1503,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
15031503
}
15041504
return this.canResetTimelineCallback(roomId);
15051505
},
1506+
logger: this.logger.getChild("sync"),
15061507
};
15071508
}
15081509

@@ -7324,7 +7325,7 @@ export class MatrixClient extends TypedEventEmitter<EmittedEvents, ClientEventHa
73247325
*/
73257326
public setPushRules(rules: IPushRules): void {
73267327
// Fix-up defaults, if applicable.
7327-
this.pushRules = PushProcessor.rewriteDefaultRules(rules, this.getUserId()!);
7328+
this.pushRules = PushProcessor.rewriteDefaultRules(this.logger, rules, this.getUserId()!);
73287329
// Pre-calculate any necessary caches.
73297330
this.pushProcessor.updateCachedPushRuleKeys(this.pushRules);
73307331
}

src/logger.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,9 @@ function getPrefixedLogger(prefix?: string): PrefixedLogger {
160160
/**
161161
* Drop-in replacement for `console` using {@link https://www.npmjs.com/package/loglevel|loglevel}.
162162
* Can be tailored down to specific use cases if needed.
163+
*
164+
* @deprecated avoid the use of this unless you are the constructor of `MatrixClient`: you should be using the logger
165+
* associated with `MatrixClient`.
163166
*/
164167
export const logger = getPrefixedLogger() as LoggerWithLogMethod;
165168

src/pushprocessor.ts

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ limitations under the License.
1515
*/
1616

1717
import { deepCompare, escapeRegExp, globToRegexp, isNullOrUndefined } from "./utils.ts";
18-
import { logger } from "./logger.ts";
18+
import { type Logger } from "./logger.ts";
1919
import { type MatrixClient } from "./client.ts";
2020
import { type MatrixEvent } from "./models/event.ts";
2121
import {
@@ -170,6 +170,7 @@ const EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS: OrderedRules = [
170170
/**
171171
* Make sure that each of the rules listed in `defaultRuleIds` is listed in the given set of push rules.
172172
*
173+
* @param logger - A `Logger` to write log messages to.
173174
* @param kind - the kind of push rule set being merged.
174175
* @param incomingRules - the existing set of known push rules for the user.
175176
* @param defaultRules - a lookup table for the default definitions of push rules.
@@ -178,6 +179,7 @@ const EXPECTED_DEFAULT_UNDERRIDE_RULE_IDS: OrderedRules = [
178179
* @returns A copy of `incomingRules`, with any missing default rules inserted in the right place.
179180
*/
180181
function mergeRulesWithDefaults(
182+
logger: Logger,
181183
kind: PushRuleKind,
182184
incomingRules: IPushRule[],
183185
defaultRules: Record<string, IPushRule>,
@@ -276,11 +278,17 @@ export class PushProcessor {
276278
* Rewrites conditions on a client's push rules to match the defaults
277279
* where applicable. Useful for upgrading push rules to more strict
278280
* conditions when the server is falling behind on defaults.
281+
*
282+
* @param logger - A `Logger` to write log messages to.
279283
* @param incomingRules - The client's existing push rules
280284
* @param userId - The Matrix ID of the client.
281285
* @returns The rewritten rules
282286
*/
283-
public static rewriteDefaultRules(incomingRules: IPushRules, userId: string | undefined = undefined): IPushRules {
287+
public static rewriteDefaultRules(
288+
logger: Logger,
289+
incomingRules: IPushRules,
290+
userId: string | undefined = undefined,
291+
): IPushRules {
284292
let newRules: IPushRules = JSON.parse(JSON.stringify(incomingRules)); // deep clone
285293

286294
// These lines are mostly to make the tests happy. We shouldn't run into these
@@ -292,13 +300,15 @@ export class PushProcessor {
292300

293301
// Merge the client-level defaults with the ones from the server
294302
newRules.global.override = mergeRulesWithDefaults(
303+
logger,
295304
PushRuleKind.Override,
296305
newRules.global.override,
297306
DEFAULT_OVERRIDE_RULES,
298307
EXPECTED_DEFAULT_OVERRIDE_RULE_IDS,
299308
);
300309

301310
newRules.global.underride = mergeRulesWithDefaults(
311+
logger,
302312
PushRuleKind.Underride,
303313
newRules.global.underride,
304314
DEFAULT_UNDERRIDE_RULES,

src/serverCapabilities.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ limitations under the License.
1515
*/
1616

1717
import { type IHttpOpts, type MatrixHttpApi, Method } from "./http-api/index.ts";
18-
import { logger } from "./logger.ts";
18+
import { type Logger } from "./logger.ts";
1919

2020
// How often we update the server capabilities.
2121
// 6 hours - an arbitrary value, but they should change very infrequently.
@@ -78,7 +78,10 @@ export class ServerCapabilities {
7878
private retryTimeout?: ReturnType<typeof setTimeout>;
7979
private refreshTimeout?: ReturnType<typeof setInterval>;
8080

81-
public constructor(private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>) {}
81+
public constructor(
82+
private readonly logger: Logger,
83+
private readonly http: MatrixHttpApi<IHttpOpts & { onlyData: true }>,
84+
) {}
8285

8386
/**
8487
* Starts periodically fetching the server capabilities.
@@ -117,12 +120,12 @@ export class ServerCapabilities {
117120
await this.fetchCapabilities();
118121
this.clearTimeouts();
119122
this.refreshTimeout = setTimeout(this.poll, CAPABILITIES_CACHE_MS);
120-
logger.debug("Fetched new server capabilities");
123+
this.logger.debug("Fetched new server capabilities");
121124
} catch (e) {
122125
this.clearTimeouts();
123126
const howLong = Math.floor(CAPABILITIES_RETRY_MS + Math.random() * 5000);
124127
this.retryTimeout = setTimeout(this.poll, howLong);
125-
logger.warn(`Failed to refresh capabilities: retrying in ${howLong}ms`, e);
128+
this.logger.warn(`Failed to refresh capabilities: retrying in ${howLong}ms`, e);
126129
}
127130
};
128131

src/sliding-sync-sdk.ts

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,8 @@ export class SlidingSyncSdk {
326326
public constructor(
327327
private readonly slidingSync: SlidingSync,
328328
private readonly client: MatrixClient,
329-
opts?: IStoredClientOpts,
330-
syncOpts?: SyncApiOptions,
329+
opts: IStoredClientOpts | undefined,
330+
syncOpts: SyncApiOptions,
331331
) {
332332
this.opts = defaultClientOpts(opts);
333333
this.syncOpts = defaultSyncApiOpts(syncOpts);
@@ -356,7 +356,11 @@ export class SlidingSyncSdk {
356356
let room = this.client.store.getRoom(roomId);
357357
if (!room) {
358358
if (!roomData.initial) {
359-
logger.debug("initial flag not set but no stored room exists for room ", roomId, roomData);
359+
this.syncOpts.logger.debug(
360+
"initial flag not set but no stored room exists for room ",
361+
roomId,
362+
roomData,
363+
);
360364
return;
361365
}
362366
room = _createAndReEmitRoom(this.client, roomId, this.opts);
@@ -366,7 +370,7 @@ export class SlidingSyncSdk {
366370

367371
private onLifecycle(state: SlidingSyncState, resp: MSC3575SlidingSyncResponse | null, err?: Error): void {
368372
if (err) {
369-
logger.debug("onLifecycle", state, err);
373+
this.syncOpts.logger.debug("onLifecycle", state, err);
370374
}
371375
switch (state) {
372376
case SlidingSyncState.Complete:
@@ -407,7 +411,9 @@ export class SlidingSyncSdk {
407411
}
408412
} else {
409413
this.failCount = 0;
410-
logger.log(`SlidingSyncState.RequestFinished with ${Object.keys(resp?.rooms || []).length} rooms`);
414+
this.syncOpts.logger.debug(
415+
`SlidingSyncState.RequestFinished with ${Object.keys(resp?.rooms || []).length} rooms`,
416+
);
411417
}
412418
break;
413419
}
@@ -526,7 +532,7 @@ export class SlidingSyncSdk {
526532
private shouldAbortSync(error: MatrixError): boolean {
527533
if (error.errcode === "M_UNKNOWN_TOKEN") {
528534
// The logout already happened, we just need to stop.
529-
logger.warn("Token no longer valid - assuming logout");
535+
this.syncOpts.logger.warn("Token no longer valid - assuming logout");
530536
this.stop();
531537
this.updateSyncState(SyncState.Error, { error });
532538
return true;
@@ -654,7 +660,7 @@ export class SlidingSyncSdk {
654660
for (let i = timelineEvents.length - 1; i >= 0; i--) {
655661
const eventId = timelineEvents[i].getId();
656662
if (room.getTimelineForEvent(eventId)) {
657-
logger.debug("Already have event " + eventId + " in limited " +
663+
this.syncOpts.logger.debug("Already have event " + eventId + " in limited " +
658664
"sync - not resetting");
659665
limited = false;
660666
@@ -863,19 +869,19 @@ export class SlidingSyncSdk {
863869
* Main entry point. Blocks until stop() is called.
864870
*/
865871
public async sync(): Promise<void> {
866-
logger.debug("Sliding sync init loop");
872+
this.syncOpts.logger.debug("Sliding sync init loop");
867873

868874
// 1) We need to get push rules so we can check if events should bing as we get
869875
// them from /sync.
870876
while (!this.client.isGuest()) {
871877
try {
872-
logger.debug("Getting push rules...");
878+
this.syncOpts.logger.debug("Getting push rules...");
873879
const result = await this.client.getPushRules();
874-
logger.debug("Got push rules");
880+
this.syncOpts.logger.debug("Got push rules");
875881
this.client.pushRules = result;
876882
break;
877883
} catch (err) {
878-
logger.error("Getting push rules failed", err);
884+
this.syncOpts.logger.error("Getting push rules failed", err);
879885
if (this.shouldAbortSync(<MatrixError>err)) {
880886
return;
881887
}
@@ -890,7 +896,7 @@ export class SlidingSyncSdk {
890896
* Stops the sync object from syncing.
891897
*/
892898
public stop(): void {
893-
logger.debug("SyncApi.stop");
899+
this.syncOpts.logger.debug("SyncApi.stop");
894900
this.slidingSync.stop();
895901
}
896902

0 commit comments

Comments
 (0)