-
Notifications
You must be signed in to change notification settings - Fork 37
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(billing): billing service (#325)
* feat(billing): billing service * better destroy * fix * better billing
- Loading branch information
1 parent
84a4baa
commit 6882299
Showing
3 changed files
with
104 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import { Logger, LoggerService, Service } from '@botpress/messaging-engine' | ||
import axios from 'axios' | ||
import clc from 'cli-color' | ||
import ms from 'ms' | ||
import { ConversationService } from '../conversations/service' | ||
import { MessageCreatedEvent, MessageEvents } from '../messages/events' | ||
import { MessageService } from '../messages/service' | ||
|
||
export class BillingService extends Service { | ||
private logger: Logger | ||
private timeout?: NodeJS.Timeout | ||
private stats: { [clientId: string]: { received: number; sent: number } } = {} | ||
|
||
constructor(loggers: LoggerService, private conversations: ConversationService, private messages: MessageService) { | ||
super() | ||
this.logger = loggers.root.sub('billing') | ||
} | ||
|
||
async setup() { | ||
if (process.env.BILLING_ENDPOINT?.length) { | ||
this.messages.events.on(MessageEvents.Created, this.handleMessageCreated.bind(this)) | ||
|
||
void this.tickBilling() | ||
} | ||
} | ||
|
||
async destroy() { | ||
try { | ||
if (this.timeout) { | ||
clearTimeout(this.timeout) | ||
} | ||
|
||
await this.flushBilling() | ||
} catch (e) { | ||
this.logger.error(e, 'Failed to destroy billing') | ||
} | ||
} | ||
|
||
private async tickBilling() { | ||
try { | ||
await this.flushBilling() | ||
} catch (e) { | ||
this.logger.error(e, 'Error occurred in billing') | ||
} finally { | ||
this.timeout = setTimeout(this.tickBilling.bind(this), ms('3s')) | ||
} | ||
} | ||
|
||
private async handleMessageCreated({ message }: MessageCreatedEvent) { | ||
const conversation = await this.conversations.get(message.conversationId) | ||
const stat = this.stats[conversation.clientId] || { sent: 0, received: 0 } | ||
|
||
if (message.authorId) { | ||
stat.received++ | ||
} else { | ||
stat.sent++ | ||
} | ||
|
||
this.stats[conversation.clientId] = stat | ||
} | ||
|
||
private async flushBilling() { | ||
const entries = [...Object.entries(this.stats)] | ||
|
||
for (const [clientId, stat] of entries) { | ||
const sentStats = { ...stat } | ||
const timestamp = new Date().toISOString() | ||
|
||
stat.sent = 0 | ||
stat.received = 0 | ||
|
||
await axios.post(process.env.BILLING_ENDPOINT!, { | ||
meta: { | ||
timestamp, | ||
sender: 'messaging', | ||
type: 'messages_processed', | ||
schema_version: '1.0.0' | ||
}, | ||
schema_version: '1.0.0', | ||
records: [ | ||
{ | ||
client_id: clientId, | ||
messages: sentStats, | ||
timestamp | ||
} | ||
] | ||
}) | ||
|
||
// it's possible that new stats have been entered while the post request | ||
// was waiting since it's async | ||
if (stat.received === 0 && stat.sent === 0) { | ||
delete this.stats[clientId] | ||
} | ||
|
||
this.logger.info(`${clc.blackBright(`[${clientId}]`)} ${clc.cyan('stats')}`, sentStats) | ||
} | ||
} | ||
} |
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