Skip to content

Commit

Permalink
Dependency Inversion for Logger (#1153)
Browse files Browse the repository at this point in the history
* feat: interface "ILogger" created
feat: interface "ILogger" used instead of pino logger
feat: "PinoLoggerAdapter" created to implement "ILogger" interface

* feat: PinoLoggerAdapter removed
feat: ILogger mapping the features we're using from pino

* fix: sort imports

---------

Co-authored-by: Mateus Franchini de Freitas <contato.mateusfr@outlook.com>
Co-authored-by: Mateus Franchini de Freitas <mfranchini@domtec.com.br>
Co-authored-by: Rajeh Taher <rajeh@reforward.dev>
  • Loading branch information
4 people authored Mar 1, 2025
1 parent 447e648 commit 21f8431
Show file tree
Hide file tree
Showing 15 changed files with 47 additions and 36 deletions.
6 changes: 3 additions & 3 deletions src/Socket/messages-recv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -866,7 +866,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
}

if(placeholderResendCache.get(messageKey?.id!)) {
logger.debug('already requested resend', { messageKey })
logger.debug({ messageKey }, 'already requested resend')
return
} else {
placeholderResendCache.set(messageKey?.id!, true)
Expand All @@ -875,7 +875,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {
await delay(5000)

if(!placeholderResendCache.get(messageKey?.id!)) {
logger.debug('message received while resend requested', { messageKey })
logger.debug({ messageKey }, 'message received while resend requested')
return 'RESOLVED'
}

Expand All @@ -888,7 +888,7 @@ export const makeMessagesRecvSocket = (config: SocketConfig) => {

setTimeout(() => {
if(placeholderResendCache.get(messageKey?.id!)) {
logger.debug('PDO message without response after 15 seconds. Phone possibly offline', { messageKey })
logger.debug({ messageKey }, 'PDO message without response after 15 seconds. Phone possibly offline')
placeholderResendCache.del(messageKey?.id!)
}
}, 15_000)
Expand Down
6 changes: 3 additions & 3 deletions src/Store/make-in-memory-store.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type KeyedDB from '@adiwajshing/keyed-db'
import type { Comparable } from '@adiwajshing/keyed-db/lib/Types'
import type { Logger } from 'pino'
import { proto } from '../../WAProto'
import { DEFAULT_CONNECTION_CONFIG } from '../Defaults'
import type makeMDSocket from '../Socket'
import type { BaileysEventEmitter, Chat, ConnectionState, Contact, GroupMetadata, PresenceData, WAMessage, WAMessageCursor, WAMessageKey } from '../Types'
import { Label } from '../Types/Label'
import { LabelAssociation, LabelAssociationType, MessageLabelAssociation } from '../Types/LabelAssociation'
import { md5, toNumber, updateMessageWithReaction, updateMessageWithReceipt } from '../Utils'
import { ILogger } from '../Utils/logger'
import { jidDecode, jidNormalizedUser } from '../WABinary'
import makeOrderedDictionary from './make-ordered-dictionary'
import { ObjectRepository } from './object-repository'
Expand All @@ -29,7 +29,7 @@ export const waLabelAssociationKey: Comparable<LabelAssociation, string> = {
export type BaileysInMemoryStoreConfig = {
chatKey?: Comparable<Chat, string>
labelAssociationKey?: Comparable<LabelAssociation, string>
logger?: Logger
logger?: ILogger
socket?: WASocket
}

Expand All @@ -39,7 +39,7 @@ export default (config: BaileysInMemoryStoreConfig) => {
const socket = config.socket
const chatKey = config.chatKey || waChatKey(true)
const labelAssociationKey = config.labelAssociationKey || waLabelAssociationKey
const logger: Logger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
const logger: ILogger = config.logger || DEFAULT_CONNECTION_CONFIG.logger.child({ stream: 'in-mem-store' })
const KeyedDB = require('@adiwajshing/keyed-db').default

const chats = new KeyedDB(chatKey, c => c.id) as KeyedDB<Chat, string>
Expand Down
4 changes: 2 additions & 2 deletions src/Types/Message.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { AxiosRequestConfig } from 'axios'
import type { Logger } from 'pino'
import type { Readable } from 'stream'
import type { URL } from 'url'
import { proto } from '../../WAProto'
Expand All @@ -23,6 +22,7 @@ export type WAGenericMediaMessage = proto.Message.IVideoMessage | proto.Message.
export import WAMessageStubType = proto.WebMessageInfo.StubType
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
export import WAMessageStatus = proto.WebMessageInfo.Status
import { ILogger } from '../Utils/logger'
export type WAMediaPayloadURL = { url: URL | string }
export type WAMediaPayloadStream = { stream: Readable }
export type WAMediaUpload = Buffer | WAMediaPayloadStream | WAMediaPayloadURL
Expand Down Expand Up @@ -241,7 +241,7 @@ export type MessageGenerationOptionsFromContent = MiscMessageGenerationOptions &
export type WAMediaUploadFunction = (readStream: Readable, opts: { fileEncSha256B64: string, mediaType: MediaType, timeoutMs?: number }) => Promise<{ mediaUrl: string, directPath: string }>

export type MediaGenerationOptions = {
logger?: Logger
logger?: ILogger
mediaTypeOverride?: MediaType
upload: WAMediaUploadFunction
/** cache media so it does not have to be uploaded again */
Expand Down
6 changes: 3 additions & 3 deletions src/Types/Socket.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

import { AxiosRequestConfig } from 'axios'
import type { Agent } from 'https'
import type { Logger } from 'pino'
import type { URL } from 'url'
import { proto } from '../../WAProto'
import { ILogger } from '../Utils/logger'
import { AuthenticationState, SignalAuthState, TransactionCapabilityOptions } from './Auth'
import { GroupMetadata } from './GroupMetadata'
import { MediaConnInfo } from './Message'
Expand Down Expand Up @@ -38,8 +38,8 @@ export type SocketConfig = {
mobile?: boolean
/** proxy agent */
agent?: Agent
/** pino logger */
logger: Logger
/** logger */
logger: ILogger
/** version to connect with */
version: WAVersion
/** override browser config */
Expand Down
5 changes: 3 additions & 2 deletions src/Utils/auth-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { DEFAULT_CACHE_TTLS } from '../Defaults'
import type { AuthenticationCreds, CacheStore, SignalDataSet, SignalDataTypeMap, SignalKeyStore, SignalKeyStoreWithTransaction, TransactionCapabilityOptions } from '../Types'
import { Curve, signedKeyPair } from './crypto'
import { delay, generateRegistrationId } from './generics'
import { ILogger } from './logger'

/**
* Adds caching capability to a SignalKeyStore
Expand All @@ -14,7 +15,7 @@ import { delay, generateRegistrationId } from './generics'
*/
export function makeCacheableSignalKeyStore(
store: SignalKeyStore,
logger: Logger,
logger: ILogger,
_cache?: CacheStore
): SignalKeyStore {
const cache = _cache || new NodeCache({
Expand Down Expand Up @@ -83,7 +84,7 @@ export function makeCacheableSignalKeyStore(
*/
export const addTransactionCapability = (
state: SignalKeyStore,
logger: Logger,
logger: ILogger,
{ maxCommitRetries, delayBetweenTriesMs }: TransactionCapabilityOptions
): SignalKeyStoreWithTransaction => {
// number of queries made to the DB during the transaction
Expand Down
6 changes: 3 additions & 3 deletions src/Utils/chat-utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Boom } from '@hapi/boom'
import { AxiosRequestConfig } from 'axios'
import type { Logger } from 'pino'
import { proto } from '../../WAProto'
import { BaileysEventEmitter, Chat, ChatModification, ChatMutation, ChatUpdate, Contact, InitialAppStateSyncOptions, LastMessageList, LTHashState, WAPatchCreate, WAPatchName } from '../Types'
import { ChatLabelAssociation, LabelAssociationType, MessageLabelAssociation } from '../Types/LabelAssociation'
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildren, isJidGroup, jidNormalizedUser } from '../WABinary'
import { aesDecrypt, aesEncrypt, hkdf, hmacSign } from './crypto'
import { toNumber } from './generics'
import { ILogger } from './logger'
import { LT_HASH_ANTI_TAMPERING } from './lt-hash'
import { downloadContentFromMessage, } from './messages-media'

Expand Down Expand Up @@ -410,7 +410,7 @@ export const decodePatches = async(
getAppStateSyncKey: FetchAppStateSyncKey,
options: AxiosRequestConfig<{}>,
minimumVersionNumber?: number,
logger?: Logger,
logger?: ILogger,
validateMacs = true
) => {
const newState: LTHashState = {
Expand Down Expand Up @@ -716,7 +716,7 @@ export const processSyncAction = (
ev: BaileysEventEmitter,
me: Contact,
initialSyncOpts?: InitialAppStateSyncOptions,
logger?: Logger,
logger?: ILogger,
) => {
const isInitialSync = !!initialSyncOpts
const accountSettings = initialSyncOpts?.accountSettings
Expand Down
4 changes: 2 additions & 2 deletions src/Utils/decode-wa-message.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Boom } from '@hapi/boom'
import { Logger } from 'pino'
import { proto } from '../../WAProto'
import { SignalRepository, WAMessageKey } from '../Types'
import { areJidsSameUser, BinaryNode, isJidBroadcast, isJidGroup, isJidNewsletter, isJidStatusBroadcast, isJidUser, isLidUser } from '../WABinary'
import { unpadRandomMax16 } from './generics'
import { ILogger } from './logger'

export const NO_MESSAGE_FOUND_ERROR_TEXT = 'Message absent from node'
export const MISSING_KEYS_ERROR_TEXT = 'Key used already or never filled'
Expand Down Expand Up @@ -136,7 +136,7 @@ export const decryptMessageNode = (
meId: string,
meLid: string,
repository: SignalRepository,
logger: Logger
logger: ILogger
) => {
const { fullMessage, author, sender } = decodeMessageNode(stanza, meId, meLid)
return {
Expand Down
6 changes: 3 additions & 3 deletions src/Utils/event-buffer.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import EventEmitter from 'events'
import { Logger } from 'pino'
import { proto } from '../../WAProto'
import { BaileysEvent, BaileysEventEmitter, BaileysEventMap, BufferedEventData, Chat, ChatUpdate, Contact, WAMessage, WAMessageStatus } from '../Types'
import { trimUndefined } from './generics'
import { ILogger } from './logger'
import { updateMessageWithReaction, updateMessageWithReceipt } from './messages'
import { isRealMessage, shouldIncrementChatUnread } from './process-message'

Expand Down Expand Up @@ -59,7 +59,7 @@ type BaileysBufferableEventEmitter = BaileysEventEmitter & {
* making the data processing more efficient.
* @param ev the baileys event emitter
*/
export const makeEventBuffer = (logger: Logger): BaileysBufferableEventEmitter => {
export const makeEventBuffer = (logger: ILogger): BaileysBufferableEventEmitter => {
const ev = new EventEmitter()
const historyCache = new Set<string>()

Expand Down Expand Up @@ -190,7 +190,7 @@ function append<E extends BufferableEvent>(
event: E,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
eventData: any,
logger: Logger
logger: ILogger
) {
switch (event) {
case 'messaging-history.set':
Expand Down
4 changes: 2 additions & 2 deletions src/Utils/generics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { Boom } from '@hapi/boom'
import axios, { AxiosRequestConfig } from 'axios'
import { createHash, randomBytes } from 'crypto'
import { platform, release } from 'os'
import { Logger } from 'pino'
import { proto } from '../../WAProto'
import { version as baileysVersion } from '../Defaults/baileys-version.json'
import { BaileysEventEmitter, BaileysEventMap, BrowsersMap, ConnectionState, DisconnectReason, WACallUpdateType, WAVersion } from '../Types'
import { BinaryNode, getAllBinaryNodeChildren, jidDecode } from '../WABinary'
import { ILogger } from './logger'

const PLATFORM_MAP = {
'aix': 'AIX',
Expand Down Expand Up @@ -242,7 +242,7 @@ export function bindWaitForEvent<T extends keyof BaileysEventMap>(ev: BaileysEve

export const bindWaitForConnectionUpdate = (ev: BaileysEventEmitter) => bindWaitForEvent(ev, 'connection.update')

export const printQRIfNecessaryListener = (ev: BaileysEventEmitter, logger: Logger) => {
export const printQRIfNecessaryListener = (ev: BaileysEventEmitter, logger: ILogger) => {
ev.on('connection.update', async({ qr }) => {
if(qr) {
const QR = await import('qrcode-terminal')
Expand Down
4 changes: 2 additions & 2 deletions src/Utils/link-preview.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { AxiosRequestConfig } from 'axios'
import { Logger } from 'pino'
import { WAMediaUploadFunction, WAUrlInfo } from '../Types'
import { ILogger } from './logger'
import { prepareWAMessageMedia } from './messages'
import { extractImageThumb, getHttpStream } from './messages-media'

Expand All @@ -25,7 +25,7 @@ export type URLGenerationOptions = {
headers?: AxiosRequestConfig<{}>['headers']
}
uploadImage?: WAMediaUploadFunction
logger?: Logger
logger?: ILogger
}

/**
Expand Down
12 changes: 11 additions & 1 deletion src/Utils/logger.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
import P from 'pino'

export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
export interface ILogger {
level: string
child(obj: Record<string, unknown>): ILogger
trace(obj: unknown, msg?: string)
debug(obj: unknown, msg?: string)
info(obj: unknown, msg?: string)
warn(obj: unknown, msg?: string)
error(obj: unknown, msg?: string)
}

export default P({ timestamp: () => `,"time":"${new Date().toJSON()}"` })
8 changes: 4 additions & 4 deletions src/Utils/messages-media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { createReadStream, createWriteStream, promises as fs, WriteStream } from
import type { IAudioMetadata } from 'music-metadata'
import { tmpdir } from 'os'
import { join } from 'path'
import type { Logger } from 'pino'
import { Readable, Transform } from 'stream'
import { URL } from 'url'
import { proto } from '../../WAProto'
Expand All @@ -16,6 +15,7 @@ import { BaileysEventMap, DownloadableMessage, MediaConnInfo, MediaDecryptionKey
import { BinaryNode, getBinaryNodeChild, getBinaryNodeChildBuffer, jidNormalizedUser } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, hkdf } from './crypto'
import { generateMessageID } from './generics'
import { ILogger } from './logger'

const getTmpFilesDirectory = () => tmpdir()

Expand Down Expand Up @@ -207,7 +207,7 @@ export async function getAudioDuration(buffer: Buffer | string | Readable) {
/**
referenced from and modifying https://github.com/wppconnect-team/wa-js/blob/main/src/chat/functions/prepareAudioWaveform.ts
*/
export async function getAudioWaveform(buffer: Buffer | string | Readable, logger?: Logger) {
export async function getAudioWaveform(buffer: Buffer | string | Readable, logger?: ILogger) {
try {
const { default: decoder } = await eval('import(\'audio-decode\')')
let audioData: Buffer
Expand Down Expand Up @@ -290,7 +290,7 @@ export async function generateThumbnail(
file: string,
mediaType: 'video' | 'image',
options: {
logger?: Logger
logger?: ILogger
}
) {
let thumbnail: string | undefined
Expand Down Expand Up @@ -330,7 +330,7 @@ export const getHttpStream = async(url: string | URL, options: AxiosRequestConfi

type EncryptedStreamOptions = {
saveOriginalFileIfRequired?: boolean
logger?: Logger
logger?: ILogger
opts?: AxiosRequestConfig
}

Expand Down
4 changes: 2 additions & 2 deletions src/Utils/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Boom } from '@hapi/boom'
import axios from 'axios'
import { randomBytes } from 'crypto'
import { promises as fs } from 'fs'
import { Logger } from 'pino'
import { type Transform } from 'stream'
import { proto } from '../../WAProto'
import { MEDIA_KEYS, URL_REGEX, WA_DEFAULT_EPHEMERAL } from '../Defaults'
Expand All @@ -27,6 +26,7 @@ import {
import { isJidGroup, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
import { sha256 } from './crypto'
import { generateMessageID, getKeyAuthor, unixTimestampSeconds } from './generics'
import { ILogger } from './logger'
import { downloadContentFromMessage, encryptedStream, generateThumbnail, getAudioDuration, getAudioWaveform, MediaDownloadOptions } from './messages-media'

type MediaUploadData = {
Expand Down Expand Up @@ -847,7 +847,7 @@ export const aggregateMessageKeysNotFromMe = (keys: proto.IMessageKey[]) => {

type DownloadMediaMessageContext = {
reuploadRequest: (msg: WAMessage) => Promise<WAMessage>
logger: Logger
logger: ILogger
}

const REUPLOAD_REQUIRED_STATUS = [410, 404]
Expand Down
4 changes: 2 additions & 2 deletions src/Utils/noise-handler.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Boom } from '@hapi/boom'
import { Logger } from 'pino'
import { proto } from '../../WAProto'
import { NOISE_MODE, WA_CERT_DETAILS } from '../Defaults'
import { KeyPair } from '../Types'
import { BinaryNode, decodeBinaryNode } from '../WABinary'
import { aesDecryptGCM, aesEncryptGCM, Curve, hkdf, sha256 } from './crypto'
import { ILogger } from './logger'

const generateIV = (counter: number) => {
const iv = new ArrayBuffer(12)
Expand All @@ -21,7 +21,7 @@ export const makeNoiseHandler = ({
}: {
keyPair: KeyPair
NOISE_HEADER: Uint8Array
logger: Logger
logger: ILogger
routingInfo?: Buffer | undefined
}) => {
logger = logger.child({ class: 'ns' })
Expand Down
4 changes: 2 additions & 2 deletions src/Utils/process-message.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { AxiosRequestConfig } from 'axios'
import type { Logger } from 'pino'
import { proto } from '../../WAProto'
import { AuthenticationCreds, BaileysEventEmitter, CacheStore, Chat, GroupMetadata, ParticipantAction, RequestJoinAction, RequestJoinMethod, SignalKeyStoreWithTransaction, SocketConfig, WAMessageStubType } from '../Types'
import { getContentType, normalizeMessageContent } from '../Utils/messages'
import { areJidsSameUser, isJidBroadcast, isJidStatusBroadcast, jidNormalizedUser } from '../WABinary'
import { aesDecryptGCM, hmacSign } from './crypto'
import { getKeyAuthor, toNumber } from './generics'
import { downloadAndProcessHistorySyncNotification } from './history'
import { ILogger } from './logger'

type ProcessMessageContext = {
shouldProcessHistoryMsg: boolean
Expand All @@ -15,7 +15,7 @@ type ProcessMessageContext = {
keyStore: SignalKeyStoreWithTransaction
ev: BaileysEventEmitter
getMessage: SocketConfig['getMessage']
logger?: Logger
logger?: ILogger
options: AxiosRequestConfig<{}>
}

Expand Down

0 comments on commit 21f8431

Please sign in to comment.