Skip to content

Commit

Permalink
Merge pull request #1304 from bugsnag/in-flight-package
Browse files Browse the repository at this point in the history
Create @bugsnag/in-flight internal package
  • Loading branch information
imjoehaines authored Feb 25, 2021
2 parents 832c842 + 99d3e00 commit 1eca4ce
Show file tree
Hide file tree
Showing 10 changed files with 371 additions and 0 deletions.
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ module.exports = {
]),
project('node plugins', [
'delivery-node',
'in-flight',
'plugin-express',
'plugin-koa',
'plugin-restify',
Expand Down
1 change: 1 addition & 0 deletions packages/core/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ interface Delivery {
export default class ClientWithInternals<T extends Config = Config> extends Client {
public constructor(opts: T, schema?: {[key: string]: any}, internalPlugins?: Plugin[], notifier?: Notifier)
_config: T
_depth: number
_logger: LoggerConfig
_breadcrumbs: Breadcrumb[];
_delivery: Delivery
Expand Down
19 changes: 19 additions & 0 deletions packages/in-flight/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) Bugsnag, https://www.bugsnag.com/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
7 changes: 7 additions & 0 deletions packages/in-flight/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# @bugsnag/in-flight

Internal [@bugsnag/js](https://github.com/bugsnag/bugsnag-js) package to keep track of in-flight requests

## License

This package is free software released under the MIT License. See [LICENSE.txt](./LICENSE.txt) for details.
13 changes: 13 additions & 0 deletions packages/in-flight/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 30 additions & 0 deletions packages/in-flight/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@bugsnag/in-flight",
"version": "7.7.0",
"main": "src/in-flight.js",
"types": "types/bugsnag-in-flight.d.ts",
"description": "Internal package to keep track of in-flight requests to Bugsnag",
"homepage": "https://www.bugsnag.com/",
"repository": {
"type": "git",
"url": "[email protected]:bugsnag/bugsnag-js.git"
},
"publishConfig": {
"access": "public"
},
"files": [
"src",
"types"
],
"author": "Bugsnag",
"license": "MIT",
"dependencies": {
"@bugsnag/cuid": "^3.0.0"
},
"devDependencies": {
"@bugsnag/core": "^7.7.0"
},
"peerDependencies": {
"@bugsnag/core": "^7.0.0"
}
}
72 changes: 72 additions & 0 deletions packages/in-flight/src/in-flight.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const cuid = require('@bugsnag/cuid')

const FLUSH_POLL_INTERVAL_MS = 50
const inFlightRequests = new Map()

const noop = () => {}

module.exports = {
trackInFlight (client) {
const originalNotify = client._notify

client._notify = function (event, onError, callback = noop) {
const id = cuid()
inFlightRequests.set(id, true)

const _callback = function () {
inFlightRequests.delete(id)
callback.apply(null, arguments)
}

client._depth += 1

try {
originalNotify.call(client, event, onError, _callback)
} finally {
client._depth -= 1
}
}

const delivery = client._delivery
const originalSendSession = delivery.sendSession

delivery.sendSession = function (session, callback = noop) {
const id = cuid()
inFlightRequests.set(id, true)

const _callback = function () {
inFlightRequests.delete(id)
callback.apply(null, arguments)
}

originalSendSession.call(delivery, session, _callback)
}
},

flush (timeoutMs) {
return new Promise(function (resolve, reject) {
let resolveTimeout
const rejectTimeout = setTimeout(
() => {
if (resolveTimeout) clearTimeout(resolveTimeout)

reject(new Error(`flush timed out after ${timeoutMs}ms`))
},
timeoutMs
)

const resolveIfNoRequests = function () {
if (inFlightRequests.size === 0) {
clearTimeout(rejectTimeout)
resolve()

return
}

resolveTimeout = setTimeout(resolveIfNoRequests, FLUSH_POLL_INTERVAL_MS)
}

resolveIfNoRequests()
})
}
}
219 changes: 219 additions & 0 deletions packages/in-flight/test/in-flight.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,219 @@
import Client, { EventDeliveryPayload, SessionDeliveryPayload } from '@bugsnag/core/client'

// The in-flight package has module level state which can leak between tests
// We can avoid this using jest's 'isolateModules' but need to type the
// 'bugsnagInFlight' variable for this test to compile
import BugsnagInFlightJustForTypescript from '../types/bugsnag-in-flight'

let bugsnagInFlight: BugsnagInFlightJustForTypescript
jest.isolateModules(() => { bugsnagInFlight = require('../src/in-flight') })

describe('@bugsnag/in-flight', () => {
it('tracks in-flight events', () => {
const client = new Client({ apiKey: 'AN_API_KEY' })
const payloads: EventDeliveryPayload[] = []
const sendSession = jest.fn()

client._setDelivery(() => ({
sendEvent: (payload, cb) => {
expect(client._depth).toBe(2)
payloads.push(payload)
cb()
},
sendSession
}))

bugsnagInFlight.trackInFlight(client)

expect(payloads.length).toBe(0)

const onError = jest.fn()
const callback = jest.fn()

expect(client._depth).toBe(1)

client.notify(new Error('xyz'), onError, callback)

expect(client._depth).toBe(1)
expect(onError).toHaveBeenCalledTimes(1)
expect(callback).toHaveBeenCalledTimes(1)
expect(payloads.length).toBe(1)
expect(sendSession).not.toHaveBeenCalled()
})

it('tracks in-flight sessions', () => {
const client = new Client({ apiKey: 'AN_API_KEY' })
const payloads: SessionDeliveryPayload[] = []
const sendEvent = jest.fn()
const callback = jest.fn()

client._sessionDelegate = {
startSession: jest.fn(function (client, session) {
client._delivery.sendSession(session, callback)
}),
pauseSession: jest.fn(),
resumeSession: jest.fn()
}

client._setDelivery(() => ({
sendEvent,
sendSession: (payload, cb) => {
payloads.push(payload)
cb()
}
}))

bugsnagInFlight.trackInFlight(client)

expect(payloads.length).toBe(0)
expect(callback).not.toHaveBeenCalled()
expect(client._sessionDelegate.startSession).not.toHaveBeenCalled()
expect(client._sessionDelegate.pauseSession).not.toHaveBeenCalled()
expect(client._sessionDelegate.resumeSession).not.toHaveBeenCalled()

client.startSession()

expect(payloads.length).toBe(1)
expect(callback).toHaveBeenCalledTimes(1)
expect(client._sessionDelegate.startSession).toHaveBeenCalledTimes(1)
expect(client._sessionDelegate.pauseSession).not.toHaveBeenCalled()
expect(client._sessionDelegate.resumeSession).not.toHaveBeenCalled()
})

it('tracks all in-flight requests', () => {
const client = new Client({ apiKey: 'AN_API_KEY' })
const eventPayloads: EventDeliveryPayload[] = []
const sessionPayloads: SessionDeliveryPayload[] = []
const sessionCallback = jest.fn()

client._sessionDelegate = {
startSession: jest.fn(function (client, session) {
client._delivery.sendSession(session, sessionCallback)
}),
pauseSession: jest.fn(),
resumeSession: jest.fn()
}

client._setDelivery(() => ({
sendEvent: (payload, cb) => {
expect(client._depth).toBe(2)
eventPayloads.push(payload)
cb()
},
sendSession: (payload, cb) => {
sessionPayloads.push(payload)
cb()
}
}))

bugsnagInFlight.trackInFlight(client)

expect(eventPayloads.length).toBe(0)
expect(sessionPayloads.length).toBe(0)

const onError = jest.fn()
const notifyCallback = jest.fn()

expect(client._depth).toBe(1)

client.notify(new Error('xyz'), onError, notifyCallback)
client.startSession()

expect(client._depth).toBe(1)
expect(onError).toHaveBeenCalledTimes(1)
expect(notifyCallback).toHaveBeenCalledTimes(1)
expect(sessionCallback).toHaveBeenCalledTimes(1)
expect(eventPayloads.length).toBe(1)
expect(sessionPayloads.length).toBe(1)
})

it('can flush successfully', async () => {
const client = new Client({ apiKey: 'AN_API_KEY' })
const eventPayloads: EventDeliveryPayload[] = []
const sessionPayloads: SessionDeliveryPayload[] = []

client._sessionDelegate = {
startSession (client, session) {
client._delivery.sendSession(session, () => {})
},
pauseSession: () => {},
resumeSession: () => {}
}

client._setDelivery(() => ({
sendEvent (payload, cb) {
setTimeout(function () {
eventPayloads.push(payload)
cb()
}, 100)
},
sendSession (payload, cb) {
setTimeout(function () {
sessionPayloads.push(payload)
cb()
}, 100)
}
}))

bugsnagInFlight.trackInFlight(client)

client.notify(new Error('xyz'))
client.startSession()

expect(eventPayloads.length).toBe(0)
expect(sessionPayloads.length).toBe(0)

await bugsnagInFlight.flush(1000)

expect(eventPayloads.length).toBe(1)
expect(sessionPayloads.length).toBe(1)
})

it('will timeout if flush takes too long', async () => {
const client = new Client({ apiKey: 'AN_API_KEY' })
const eventPayloads: EventDeliveryPayload[] = []
const sessionPayloads: SessionDeliveryPayload[] = []

client._sessionDelegate = {
startSession: (client, session) => {
client._delivery.sendSession(session, () => {})
},
pauseSession: () => {},
resumeSession: () => {}
}

client._setDelivery(() => ({
sendEvent (payload, cb) {
setTimeout(() => {
eventPayloads.push(payload)
cb()
}, 250)
},
sendSession (payload, cb) {
setTimeout(() => {
sessionPayloads.push(payload)
cb()
}, 250)
}
}))

bugsnagInFlight.trackInFlight(client)

client.notify(new Error('xyz'))
client.startSession()

expect(eventPayloads.length).toBe(0)
expect(sessionPayloads.length).toBe(0)

const expected = new Error('flush timed out after 10ms')
await expect(() => bugsnagInFlight.flush(10)).rejects.toThrow(expected)

expect(eventPayloads.length).toBe(0)
expect(sessionPayloads.length).toBe(0)

await bugsnagInFlight.flush(1000)

expect(eventPayloads.length).toBe(1)
expect(sessionPayloads.length).toBe(1)
})
})
8 changes: 8 additions & 0 deletions packages/in-flight/types/bugsnag-in-flight.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Client } from '@bugsnag/core'

interface BugsnagInFlight {
trackInFlight (client: Client): void
flush (timeoutMs: number): Promise<void>
}

export default BugsnagInFlight
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"packages/delivery-react-native",
"packages/delivery-x-domain-request",
"packages/delivery-xml-http-request",
"packages/in-flight",
"packages/plugin-app-duration",
"packages/plugin-browser-context",
"packages/plugin-browser-device",
Expand Down

0 comments on commit 1eca4ce

Please sign in to comment.