Skip to content

Commit

Permalink
fix: add retry to sendMetric to avoid connection errors
Browse files Browse the repository at this point in the history
  • Loading branch information
enzomerca committed Feb 7, 2024
1 parent 2de04c4 commit 17f71e5
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

### Fixed
- Add retries to `sendMetric` to avoid connection errors

## [0.48.0] - 2024-01-19

### Added
Expand Down
61 changes: 61 additions & 0 deletions node/utils/metrics/metrics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import axios from 'axios'

import { sendMetric } from './metrics'

jest.mock('axios')
afterEach(() => {
jest.resetAllMocks()
})

describe('when calling sendMetrics', () => {
it('should call axios.post', async () => {
const metric = {
account: 'account',
description: 'description',
kind: 'kind',
name: 'b2b-suite-buyerorg-data' as const,
}

await sendMetric(metric)

expect(axios.post).toBeCalledTimes(1)
})

it('should retry on failure', async () => {
const metric = {
account: 'account',
description: 'description',
kind: 'kind',
name: 'b2b-suite-buyerorg-data' as const,
}

jest
.spyOn(axios, 'post')
.mockImplementation()
.mockRejectedValueOnce(new Error('error'))

await sendMetric(metric)

expect(axios.post).toBeCalledTimes(2)
})

it('should fail after max retries', async () => {
const metric = {
account: 'account',
description: 'description',
kind: 'kind',
name: 'b2b-suite-buyerorg-data' as const,
}

jest
.spyOn(axios, 'post')
.mockImplementation()
.mockRejectedValue(new Error('Error'))

await expect(async () => {
await sendMetric(metric)
}).rejects.toThrowError('Error - after 2 retries.')

expect(axios.post).toBeCalledTimes(3)
})
})
15 changes: 13 additions & 2 deletions node/utils/metrics/metrics.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import axios from 'axios'

const ANALYTICS_URL = 'https://rc.vtex.com/api/analytics/schemaless-events'
const MAX_RETRIES = 2
const RETRY_INTERVAL = 1000 // 1 second

export const B2B_METRIC_NAME = 'b2b-suite-buyerorg-data'

Expand All @@ -11,6 +13,15 @@ export interface Metric {
readonly name: typeof B2B_METRIC_NAME
}

export const sendMetric = async (metric: Metric) => {
await axios.post(ANALYTICS_URL, metric)
export const sendMetric = async (metric: Metric, retries = 0) => {
try {
await axios.post(ANALYTICS_URL, metric)
} catch (error) {
if (retries < MAX_RETRIES) {
await new Promise((resolve) => setTimeout(resolve, RETRY_INTERVAL))
await sendMetric(metric, retries + 1)
} else {
throw new Error(`${error.message} - after ${MAX_RETRIES} retries.`)
}
}
}

0 comments on commit 17f71e5

Please sign in to comment.