Skip to content

Commit

Permalink
Make keepalive configurable and default to false (#788)
Browse files Browse the repository at this point in the history
  • Loading branch information
silesky authored Feb 10, 2023
1 parent 9ec9cb1 commit 6fbae8d
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 16 deletions.
5 changes: 5 additions & 0 deletions .changeset/tasty-badgers-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@segment/analytics-next': minor
---

Make keep-alive configurable and default to false
34 changes: 34 additions & 0 deletions packages/browser/src/plugins/segmentio/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,40 @@ describe('Segment.io', () => {
})
})

describe('configuring a keep alive', () => {
it('should accept keepalive configuration', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

await analytics.register(
segmentio(analytics, {
apiKey: '',
deliveryStrategy: {
config: {
keepalive: true,
},
},
})
)

await analytics.track('foo')
const [_, params] = spyMock.mock.lastCall
expect(params.keepalive).toBe(true)
})

it('should default to no keepalive', async () => {
const analytics = new Analytics({ writeKey: 'foo' })

const segment = segmentio(analytics, {
apiKey: '',
})
await analytics.register(segment)
await analytics.track('foo')

const [_, params] = spyMock.mock.lastCall
expect(params.keepalive).toBeUndefined()
})
})

describe('#page', () => {
it('should enqueue section, name and properties', async () => {
await analytics.page('section', 'name', { property: true }, { opt: true })
Expand Down
7 changes: 5 additions & 2 deletions packages/browser/src/plugins/segmentio/batched-dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { SegmentEvent } from '../../core/events'
import { fetch } from '../../lib/fetch'
import { onPageLeave } from '../../lib/on-page-leave'

type BatchingConfig = {
export type BatchingDispatchConfig = {
size?: number
timeout?: number
}
Expand Down Expand Up @@ -43,7 +43,10 @@ function chunks(batch: object[]): Array<object[]> {
return result
}

export default function batch(apiHost: string, config?: BatchingConfig) {
export default function batch(
apiHost: string,
config?: BatchingDispatchConfig
) {
let buffer: object[] = []
let pageUnloaded = false

Expand Down
10 changes: 8 additions & 2 deletions packages/browser/src/plugins/segmentio/fetch-dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@ import { fetch } from '../../lib/fetch'

export type Dispatcher = (url: string, body: object) => Promise<unknown>

export default function (): { dispatch: Dispatcher } {
export type StandardDispatcherConfig = {
keepalive?: boolean
}

export default function (config?: StandardDispatcherConfig): {
dispatch: Dispatcher
} {
function dispatch(url: string, body: object): Promise<unknown> {
return fetch(url, {
keepalive: true,
keepalive: config?.keepalive,
headers: { 'Content-Type': 'text/plain' },
method: 'post',
body: JSON.stringify(body),
Expand Down
29 changes: 17 additions & 12 deletions packages/browser/src/plugins/segmentio/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,21 @@ import { Plugin } from '../../core/plugin'
import { PriorityQueue } from '../../lib/priority-queue'
import { PersistedPriorityQueue } from '../../lib/priority-queue/persisted'
import { toFacade } from '../../lib/to-facade'
import batch from './batched-dispatcher'
import standard from './fetch-dispatcher'
import batch, { BatchingDispatchConfig } from './batched-dispatcher'
import standard, { StandardDispatcherConfig } from './fetch-dispatcher'
import { normalize } from './normalize'
import { scheduleFlush } from './schedule-flush'

type DeliveryStrategy =
| {
strategy?: 'standard'
config?: StandardDispatcherConfig
}
| {
strategy?: 'batching'
config?: BatchingDispatchConfig
}

export type SegmentioSettings = {
apiKey: string
apiHost?: string
Expand All @@ -24,13 +34,7 @@ export type SegmentioSettings = {

maybeBundledConfigIds?: Record<string, string[]>

deliveryStrategy?: {
strategy?: 'standard' | 'batching'
config?: {
size?: number
timeout?: number
}
}
deliveryStrategy?: DeliveryStrategy
}

type JSON = ReturnType<Facade['json']>
Expand Down Expand Up @@ -71,10 +75,11 @@ export function segmentio(
const protocol = settings?.protocol ?? 'https'
const remote = `${protocol}://${apiHost}`

const deliveryStrategy = settings?.deliveryStrategy
const client =
settings?.deliveryStrategy?.strategy === 'batching'
? batch(apiHost, settings?.deliveryStrategy?.config)
: standard()
deliveryStrategy?.strategy === 'batching'
? batch(apiHost, deliveryStrategy.config)
: standard(deliveryStrategy?.config as StandardDispatcherConfig)

async function send(ctx: Context): Promise<Context> {
if (isOffline()) {
Expand Down

0 comments on commit 6fbae8d

Please sign in to comment.