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

chore: Logs peer & graph API response times #362

Merged
merged 3 commits into from
Nov 23, 2021
Merged
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
33 changes: 13 additions & 20 deletions src/AssetPack/AssetPack.router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { ILoggerComponent } from '@well-known-components/interfaces'
import { Router } from '../common/Router'
import { HTTPError, STATUS_CODES } from '../common/HTTPError'
import { getValidator } from '../utils/validator'
import { logExecutionTime } from '../utils/logging'
import {
withModelExists,
withModelAuthorization,
Expand Down Expand Up @@ -120,8 +121,9 @@ export class AssetPackRouter extends Router {
if (owner === 'default') {
return this.sendDefaultAssetPacksRaw(res, tracer)
} else if (ethAddress && owner === ethAddress) {
const usersAssetPacks = await this.logExecutionTime(
const usersAssetPacks = await logExecutionTime(
() => AssetPack.findByEthAddressWithAssets(ethAddress),
this.logger,
`Get the user\'s (${ethAddress}) asset packs`,
tracer
)
Expand All @@ -138,8 +140,9 @@ export class AssetPackRouter extends Router {

// Get user asset packs
if (ethAddress) {
assetPacks = await this.logExecutionTime(
assetPacks = await logExecutionTime(
() => AssetPack.findByEthAddressWithAssets(ethAddress),
this.logger,
`Get the user\'s (${ethAddress}) asset packs`,
tracer
)
Expand All @@ -151,8 +154,9 @@ export class AssetPackRouter extends Router {

// Get default asset packs
if (ethAddress !== DEFAULT_ETH_ADDRESS) {
const [defaultAssetPacks] = await this.logExecutionTime(
const [defaultAssetPacks] = await logExecutionTime(
this.getDefaultAssetPacks,
this.logger,
'Get the default asset packs',
tracer
)
Expand All @@ -177,8 +181,9 @@ export class AssetPackRouter extends Router {
`Starting request to get the asset pack with id ${id} and the address ${eth_address} with tracer ${tracer}`
)

const isVisible = await this.logExecutionTime(
const isVisible = await logExecutionTime(
() => AssetPack.isVisible(id, [eth_address, DEFAULT_ETH_ADDRESS]),
this.logger,
'Get if asset pack is visible',
tracer
)
Expand All @@ -195,8 +200,9 @@ export class AssetPackRouter extends Router {
`[${tracer}] Assets pack with id ${id} is visible to ${eth_address}`
)

const assetPack = await this.logExecutionTime(
const assetPack = await logExecutionTime(
() => AssetPack.findOneWithAssets(id),
this.logger,
'Find one with assets',
tracer
)
Expand Down Expand Up @@ -308,8 +314,9 @@ export class AssetPackRouter extends Router {
res: express.Response,
tracer: string
) => {
const [, defaultAssetPacksRaw] = await this.logExecutionTime(
const [, defaultAssetPacksRaw] = await logExecutionTime(
this.getDefaultAssetPacks,
this.logger,
'Get default asset packs for default owner',
tracer
)
Expand Down Expand Up @@ -347,20 +354,6 @@ export class AssetPackRouter extends Router {
return [this.defaultAssetPacks, this.defaultAssetPacksCachedResponse]
}

private logExecutionTime = async <T>(
functionToMeasure: () => T | Promise<T>,
name: string,
tracer: string
): Promise<T> => {
const start = process.hrtime.bigint()
const result = await functionToMeasure()
const end = process.hrtime.bigint()
this.logger.info(
`[${tracer}] ${name} took ${(end - start) / BigInt(1000000)} ms to run`
)
return result
}

private sanitize(assetPacks: FullAssetPackAttributes[]) {
return utils.mapOmit<FullAssetPackAttributes>(
assetPacks,
Expand Down
74 changes: 52 additions & 22 deletions src/ethereum/api/collection.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import gql from 'graphql-tag'
import { env } from 'decentraland-commons'
import { createConsoleLogComponent } from '@well-known-components/logger'
import { ILoggerComponent } from '@well-known-components/interfaces'
import {
collectionFragment,
itemFragment,
Expand All @@ -16,6 +18,7 @@ import {
PAGINATION_VARIABLES,
PAGINATION_ARGUMENTS,
} from './BaseGraphAPI'
import { logExecutionTime } from '../../utils/logging'

const getCollectionByIdQuery = () => gql`
query getCollectionById($id: String) {
Expand Down Expand Up @@ -132,6 +135,13 @@ const getRaritiesQuery = () => gql`
export const COLLECTIONS_URL = env.get('COLLECTIONS_GRAPH_URL', '')

export class CollectionAPI extends BaseGraphAPI {
logger: ILoggerComponent.ILogger

constructor(url: string) {
super(url)
this.logger = createConsoleLogComponent().getLogger('GraphAPI')
Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe it's worth it to call it CollectionsGraphAPI ? or are we trying to group all graph api logs?

I say this because we also have third parties :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

You're right! Renamed.

}

fetchCollection = async (contractAddress: string) => {
const {
data: { collections = [] },
Expand All @@ -153,17 +163,26 @@ export class CollectionAPI extends BaseGraphAPI {
fetchCollectionsByAuthorizedUser = async (
userAddress: string
): Promise<CollectionFragment[]> => {
return this.paginate(['creator', 'manager', 'minter'], {
query: getCollectionsByAuthorizedUserQuery(),
variables: {
user: userAddress.toLowerCase(),
users: [userAddress.toLowerCase()],
},
})
return logExecutionTime(
() =>
this.paginate(['creator', 'manager', 'minter'], {
query: getCollectionsByAuthorizedUserQuery(),
variables: {
user: userAddress.toLowerCase(),
users: [userAddress.toLowerCase()],
},
}),
this.logger,
'Collections by authorized user'
)
}

fetchItems = async (): Promise<ItemFragment[]> => {
return this.paginate(['items'], { query: getItemsQuery() })
return logExecutionTime(
() => this.paginate(['items'], { query: getItemsQuery() }),
this.logger,
'Items fetch'
)
}

fetchItem = async (contractAddress: string, tokenId: string) => {
Expand All @@ -182,26 +201,33 @@ export class CollectionAPI extends BaseGraphAPI {
): Promise<ItemFragment[]> => {
const {
data: { items = [] },
} = await this.query<{ items: ItemFragment[] }>({
query: getItemsByCollectionIdQuery(),
variables: { collectionId: contractAddress.toLowerCase() },
})
} = await logExecutionTime(
() =>
this.query<{ items: ItemFragment[] }>({
query: getItemsByCollectionIdQuery(),
variables: { collectionId: contractAddress.toLowerCase() },
}),
this.logger,
'Items by contract fetch'
)

return items
}

fetchItemsByAuthorizedUser = async (
userAddress: string
): Promise<ItemFragment[]> => {
const result: { items: ItemFragment[] }[] = await this.paginate(
['creator', 'manager', 'minter'],
{
query: getItemsByAuthorizedUserQuery(),
variables: {
user: userAddress.toLowerCase(),
users: [userAddress.toLowerCase()],
},
}
const result: { items: ItemFragment[] }[] = await logExecutionTime(
() =>
this.paginate(['creator', 'manager', 'minter'], {
query: getItemsByAuthorizedUserQuery(),
variables: {
user: userAddress.toLowerCase(),
users: [userAddress.toLowerCase()],
},
}),
this.logger,
'Items by author fetch'
)

return result.reduce(
Expand Down Expand Up @@ -234,7 +260,11 @@ export class CollectionAPI extends BaseGraphAPI {
}

fetchCommittee = async (): Promise<AccountFragment[]> => {
return this.paginate(['accounts'], { query: getCommitteeQuery() })
return logExecutionTime(
() => this.paginate(['accounts'], { query: getCommitteeQuery() }),
this.logger,
'Committee fetch'
)
}

fetchRarities = async () => {
Expand Down
38 changes: 25 additions & 13 deletions src/ethereum/api/peer.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import fetch from 'isomorphic-fetch'
import { ILoggerComponent } from '@well-known-components/interfaces'
import { createConsoleLogComponent } from '@well-known-components/logger'
import { env } from 'decentraland-commons'
import { LambdasClient } from 'dcl-catalyst-client'
import { AuthLink } from 'dcl-crypto'
import { WearableData, WearableRepresentation } from '../../Item/wearable/types'
import { ItemRarity } from '../../Item'
import { MetricsAttributes } from '../../Metrics'
import { logExecutionTime } from '../../utils/logging'

export const THUMBNAIL_PATH = 'thumbnail.png'

Expand Down Expand Up @@ -48,36 +51,45 @@ export const PEER_URL = env.get('PEER_URL', '')

export class PeerAPI {
lambdasClient: LambdasClient
logger: ILoggerComponent.ILogger

constructor() {
this.lambdasClient = new LambdasClient(`${PEER_URL}/lambdas`)
this.logger = createConsoleLogComponent().getLogger('PeerAPI')
}

async validateSignature(
body: SignatureBody
): Promise<ValidateSignatureResponse> {
const response = await fetch(
`${PEER_URL}/lambdas/crypto/validate-signature`,
{
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body, null, 2),
}
const response = await logExecutionTime(
() =>
fetch(`${PEER_URL}/lambdas/crypto/validate-signature`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body, null, 2),
}),
this.logger,
'Validate Signature Fetch'
)
const result = (await response.json()) as ValidateSignatureResponse
if (!result.valid) {
this.logger.error('Logging request unsuccessful')
throw new Error(result.error)
}
return result
}

async fetchWearables(urns: string[]): Promise<Wearable[]> {
const wearables: PeerWearable[] =
urns.length > 0
? await this.lambdasClient.fetchWearables({ wearableIds: urns })
: []
const wearables: PeerWearable[] = await logExecutionTime(
() =>
urns.length > 0
? this.lambdasClient.fetchWearables({ wearableIds: urns })
: [],
this.logger,
'Wearables Fetch'
)
return wearables.map((wearable) => this.toWearable(wearable))
}

Expand Down
20 changes: 20 additions & 0 deletions src/utils/logging.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { ILoggerComponent } from '@well-known-components/interfaces'
import { v4 as uuidv4 } from 'uuid'

export const logExecutionTime = async <T>(
functionToMeasure: () => T | Promise<T>,
logger: ILoggerComponent.ILogger,
name: string,
tracer: string = uuidv4()
): Promise<T> => {
const start = process.hrtime.bigint()
logger.info(`[${tracer}] Performing ${name}`)
const result = await functionToMeasure()
const end = process.hrtime.bigint()
logger.info(
`[${tracer ?? 'no-tracer'}] ${name} took ${
(end - start) / BigInt(1000000)
} ms to run`
)
return result
}