-
-
Notifications
You must be signed in to change notification settings - Fork 740
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
feat: unique connection counting #9074
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
176e8ad
feat: unique connection counting
kwasniew 7f897b1
feat: unique connection counting
kwasniew 87c1e09
feat: improve logic for syncing counts
kwasniew 486f009
feat: improve logic for syncing counts
kwasniew 289d51c
Merge branch 'main' of github.com:Unleash/unleash into unique-connect…
kwasniew 6c7a8c9
chore: sync with main
kwasniew f229fb8
Merge branch 'main' of github.com:Unleash/unleash into unique-connect…
kwasniew 60d9f01
Merge branch 'main' of github.com:Unleash/unleash into unique-connect…
kwasniew 0a61a5d
chore: remove comment
kwasniew 7ab988e
refactor: simplify senc algorithm
kwasniew 747a636
refactor: simplify senc algorithm
kwasniew de28f91
chore: explain n
kwasniew 8feee0d
refactor: remove extra factory fn for clock
kwasniew 9e26793
refactor: remove extra factory fn for clock
kwasniew File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
27 changes: 27 additions & 0 deletions
27
src/lib/features/unique-connection/fake-unique-connection-store.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import type { IUniqueConnectionStore } from '../../types'; | ||
import type { | ||
TimedUniqueConnections, | ||
UniqueConnections, | ||
} from './unique-connection-store-type'; | ||
|
||
export class FakeUniqueConnectionStore implements IUniqueConnectionStore { | ||
private uniqueConnectionsRecord: Record<string, TimedUniqueConnections> = | ||
{}; | ||
|
||
async insert(uniqueConnections: UniqueConnections): Promise<void> { | ||
this.uniqueConnectionsRecord[uniqueConnections.id] = { | ||
...uniqueConnections, | ||
updatedAt: new Date(), | ||
}; | ||
} | ||
|
||
async get( | ||
id: 'current' | 'previous', | ||
): Promise<(UniqueConnections & { updatedAt: Date }) | null> { | ||
return this.uniqueConnectionsRecord[id] || null; | ||
} | ||
|
||
async deleteAll(): Promise<void> { | ||
this.uniqueConnectionsRecord = {}; | ||
} | ||
} |
169 changes: 169 additions & 0 deletions
169
src/lib/features/unique-connection/unique-connection-service.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,169 @@ | ||
import { UniqueConnectionService } from './unique-connection-service'; | ||
import { FakeUniqueConnectionStore } from './fake-unique-connection-store'; | ||
import getLogger from '../../../test/fixtures/no-logger'; | ||
import type { IFlagResolver } from '../../types'; | ||
import { SDK_CONNECTION_ID_RECEIVED } from '../../metric-events'; | ||
import { addHours } from 'date-fns'; | ||
import EventEmitter from 'events'; | ||
|
||
const alwaysOnFlagResolver = { | ||
isEnabled() { | ||
return true; | ||
}, | ||
} as unknown as IFlagResolver; | ||
|
||
test('sync first current bucket', async () => { | ||
const eventBus = new EventEmitter(); | ||
const config = { flagResolver: alwaysOnFlagResolver, getLogger, eventBus }; | ||
const uniqueConnectionStore = new FakeUniqueConnectionStore(); | ||
const uniqueConnectionService = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
uniqueConnectionService.listen(); | ||
|
||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection1'); | ||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection1'); | ||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection2'); | ||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection2'); | ||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection2'); | ||
|
||
await uniqueConnectionService.sync(); | ||
|
||
const stats = await uniqueConnectionService.getStats(); | ||
expect(stats).toEqual({ previous: 0, current: 2 }); | ||
}); | ||
|
||
test('sync first previous bucket', async () => { | ||
const eventBus = new EventEmitter(); | ||
const config = { flagResolver: alwaysOnFlagResolver, getLogger, eventBus }; | ||
const uniqueConnectionStore = new FakeUniqueConnectionStore(); | ||
const uniqueConnectionService = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
uniqueConnectionService.listen(); | ||
|
||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection1'); | ||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection2'); | ||
|
||
await uniqueConnectionService.sync(); | ||
|
||
eventBus.emit(SDK_CONNECTION_ID_RECEIVED, 'connection3'); | ||
|
||
await uniqueConnectionService.sync(addHours(new Date(), 1)); | ||
|
||
const stats = await uniqueConnectionService.getStats(); | ||
expect(stats).toEqual({ previous: 3, current: 0 }); | ||
}); | ||
|
||
test('sync to existing current bucket from the same service', async () => { | ||
const eventBus = new EventEmitter(); | ||
const config = { flagResolver: alwaysOnFlagResolver, getLogger, eventBus }; | ||
const uniqueConnectionStore = new FakeUniqueConnectionStore(); | ||
const uniqueConnectionService = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
uniqueConnectionService.listen(); | ||
|
||
uniqueConnectionService.count('connection1'); | ||
uniqueConnectionService.count('connection2'); | ||
|
||
await uniqueConnectionService.sync(); | ||
|
||
uniqueConnectionService.count('connection1'); | ||
uniqueConnectionService.count('connection3'); | ||
|
||
const stats = await uniqueConnectionService.getStats(); | ||
expect(stats).toEqual({ previous: 0, current: 3 }); | ||
}); | ||
|
||
test('sync to existing current bucket from another service', async () => { | ||
const eventBus = new EventEmitter(); | ||
const config = { | ||
flagResolver: alwaysOnFlagResolver, | ||
getLogger, | ||
eventBus: eventBus, | ||
}; | ||
const uniqueConnectionStore = new FakeUniqueConnectionStore(); | ||
const uniqueConnectionService1 = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
const uniqueConnectionService2 = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
|
||
uniqueConnectionService1.count('connection1'); | ||
uniqueConnectionService1.count('connection2'); | ||
await uniqueConnectionService1.sync(); | ||
|
||
uniqueConnectionService2.count('connection1'); | ||
uniqueConnectionService2.count('connection3'); | ||
await uniqueConnectionService2.sync(); | ||
|
||
const stats1 = await uniqueConnectionService1.getStats(); | ||
kwasniew marked this conversation as resolved.
Show resolved
Hide resolved
|
||
expect(stats1).toEqual({ previous: 0, current: 3 }); | ||
const stats2 = await uniqueConnectionService2.getStats(); | ||
expect(stats2).toEqual({ previous: 0, current: 3 }); | ||
}); | ||
|
||
test('sync to existing previous bucket from another service', async () => { | ||
const eventBus = new EventEmitter(); | ||
const config = { | ||
flagResolver: alwaysOnFlagResolver, | ||
getLogger, | ||
eventBus: eventBus, | ||
}; | ||
const uniqueConnectionStore = new FakeUniqueConnectionStore(); | ||
const uniqueConnectionService1 = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
const uniqueConnectionService2 = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
|
||
uniqueConnectionService1.count('connection1'); | ||
uniqueConnectionService1.count('connection2'); | ||
await uniqueConnectionService1.sync(addHours(new Date(), 1)); | ||
|
||
uniqueConnectionService2.count('connection1'); | ||
uniqueConnectionService2.count('connection3'); | ||
await uniqueConnectionService2.sync(addHours(new Date(), 1)); | ||
|
||
const stats1 = await uniqueConnectionService1.getStats(); | ||
expect(stats1).toEqual({ previous: 3, current: 0 }); | ||
const stats2 = await uniqueConnectionService2.getStats(); | ||
expect(stats2).toEqual({ previous: 3, current: 0 }); | ||
}); | ||
|
||
test('populate previous and current', async () => { | ||
const eventBus = new EventEmitter(); | ||
const config = { flagResolver: alwaysOnFlagResolver, getLogger, eventBus }; | ||
const uniqueConnectionStore = new FakeUniqueConnectionStore(); | ||
const uniqueConnectionService = new UniqueConnectionService( | ||
{ uniqueConnectionStore }, | ||
config, | ||
); | ||
|
||
uniqueConnectionService.count('connection1'); | ||
uniqueConnectionService.count('connection2'); | ||
await uniqueConnectionService.sync(); | ||
await uniqueConnectionService.sync(); | ||
|
||
uniqueConnectionService.count('connection3'); | ||
await uniqueConnectionService.sync(addHours(new Date(), 1)); | ||
await uniqueConnectionService.sync(addHours(new Date(), 1)); // deliberate duplicate call | ||
|
||
uniqueConnectionService.count('connection3'); | ||
uniqueConnectionService.count('connection4'); | ||
await uniqueConnectionService.sync(addHours(new Date(), 1)); | ||
await uniqueConnectionService.sync(addHours(new Date(), 1)); // deliberate duplicate call | ||
|
||
const stats = await uniqueConnectionService.getStats(); | ||
expect(stats).toEqual({ previous: 3, current: 2 }); | ||
}); |
99 changes: 99 additions & 0 deletions
99
src/lib/features/unique-connection/unique-connection-service.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
import type { IUnleashConfig } from '../../types/option'; | ||
import type { IFlagResolver, IUnleashStores } from '../../types'; | ||
import type { Logger } from '../../logger'; | ||
import type { IUniqueConnectionStore } from './unique-connection-store-type'; | ||
import HyperLogLog from 'hyperloglog-lite'; | ||
import type EventEmitter from 'events'; | ||
import { SDK_CONNECTION_ID_RECEIVED } from '../../metric-events'; | ||
|
||
// HyperLogLog will create 2^n registers | ||
const n = 12; | ||
kwasniew marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
export class UniqueConnectionService { | ||
private logger: Logger; | ||
|
||
private uniqueConnectionStore: IUniqueConnectionStore; | ||
|
||
private flagResolver: IFlagResolver; | ||
|
||
private eventBus: EventEmitter; | ||
|
||
private activeHour: number; | ||
|
||
private hll = HyperLogLog(n); | ||
|
||
constructor( | ||
{ | ||
uniqueConnectionStore, | ||
}: Pick<IUnleashStores, 'uniqueConnectionStore'>, | ||
config: Pick<IUnleashConfig, 'getLogger' | 'flagResolver' | 'eventBus'>, | ||
) { | ||
this.uniqueConnectionStore = uniqueConnectionStore; | ||
this.logger = config.getLogger('services/unique-connection-service.ts'); | ||
this.flagResolver = config.flagResolver; | ||
this.eventBus = config.eventBus; | ||
this.activeHour = new Date().getHours(); | ||
} | ||
|
||
listen() { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this service is interested in new connection ids received |
||
this.eventBus.on(SDK_CONNECTION_ID_RECEIVED, this.count.bind(this)); | ||
} | ||
|
||
count(connectionId: string) { | ||
if (!this.flagResolver.isEnabled('uniqueSdkTracking')) return; | ||
this.hll.add(HyperLogLog.hash(connectionId)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this data structure tracks unique connections |
||
} | ||
|
||
async getStats() { | ||
kwasniew marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const [previous, current] = await Promise.all([ | ||
this.uniqueConnectionStore.get('previous'), | ||
this.uniqueConnectionStore.get('current'), | ||
]); | ||
const previousHll = HyperLogLog(n); | ||
if (previous) { | ||
previousHll.merge({ n, buckets: previous.hll }); | ||
} | ||
const currentHll = HyperLogLog(n); | ||
if (current) { | ||
currentHll.merge({ n, buckets: current.hll }); | ||
} | ||
return { previous: previousHll.count(), current: currentHll.count() }; | ||
} | ||
|
||
async sync(currentTime = new Date()): Promise<void> { | ||
if (!this.flagResolver.isEnabled('uniqueSdkTracking')) return; | ||
|
||
const currentHour = currentTime.getHours(); | ||
const currentBucket = await this.uniqueConnectionStore.get('current'); | ||
|
||
if (this.activeHour !== currentHour && currentBucket) { | ||
if (currentBucket.updatedAt.getHours() < currentHour) { | ||
this.hll.merge({ n, buckets: currentBucket.hll }); | ||
await this.uniqueConnectionStore.insert({ | ||
hll: this.hll.output().buckets, | ||
id: 'previous', | ||
}); | ||
} else { | ||
const previousBucket = | ||
await this.uniqueConnectionStore.get('previous'); | ||
if (previousBucket) { | ||
this.hll.merge({ n, buckets: previousBucket.hll }); | ||
} | ||
await this.uniqueConnectionStore.insert({ | ||
hll: this.hll.output().buckets, | ||
id: 'previous', | ||
}); | ||
} | ||
|
||
this.activeHour = currentHour; | ||
this.hll = HyperLogLog(n); | ||
} else if (currentBucket) { | ||
this.hll.merge({ n, buckets: currentBucket.hll }); | ||
} | ||
|
||
await this.uniqueConnectionStore.insert({ | ||
hll: this.hll.output().buckets, | ||
id: 'current', | ||
}); | ||
} | ||
} |
14 changes: 14 additions & 0 deletions
14
src/lib/features/unique-connection/unique-connection-store-type.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
export type UniqueConnections = { | ||
hll: Buffer; | ||
kwasniew marked this conversation as resolved.
Show resolved
Hide resolved
|
||
id: 'current' | 'previous'; | ||
}; | ||
|
||
export type TimedUniqueConnections = UniqueConnections & { | ||
updatedAt: Date; | ||
}; | ||
|
||
export interface IUniqueConnectionStore { | ||
insert(uniqueConnections: UniqueConnections): Promise<void>; | ||
get(id: 'current' | 'previous'): Promise<TimedUniqueConnections | null>; | ||
deleteAll(): Promise<void>; | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sync in-memory HyperLogLogs with DB