@pbvision/cloud-run-service 0.0.30 → 0.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pbvision/cloud-run-service",
3
- "version": "0.0.30",
3
+ "version": "0.0.32",
4
4
  "description": "fastify-firestore-service Web Framework on Cloud Run",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/src/analytics.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import assert from 'node:assert'
2
- import { randomUUID } from 'node:crypto'
2
+ import crypto, { randomUUID } from 'node:crypto'
3
3
 
4
4
  import { DatabaseAPI, EXCEPTIONS } from '@pbvision/fastify-firestore-service'
5
5
  import UAParser from 'ua-parser-js'
@@ -21,7 +21,6 @@ export class DatabaseAPIWithAnalytics extends DatabaseAPI {
21
21
  super(fastify, req, reply)
22
22
  this.__analyticsEvents = []
23
23
  this.__analyticsUserProfileUpdates = {} // uid to $set/$set_once to changes
24
- this.__analyticsSent = false
25
24
  }
26
25
 
27
26
  async postCommit (respData) {
@@ -30,15 +29,21 @@ export class DatabaseAPIWithAnalytics extends DatabaseAPI {
30
29
  return super.postCommit(respData)
31
30
  }
32
31
 
33
- logAnalyticsEvent (mixpanelUserId, eventName, inputProperties, deviceId = null) {
34
- assert(this.__analyticsSent === false)
32
+ logAnalyticsEvent (mixpanelUserId, eventName, inputProperties = {}, deviceId = null, insertId = null) {
33
+ if (insertId) {
34
+ // insert id must be <= 36 chars & only have alphanumeric & hyphen chars
35
+ insertId = crypto.createHash('md5').update(insertId).digest('hex')
36
+ } else {
37
+ insertId = randomUUID()
38
+ }
39
+
35
40
  this.__analyticsEvents.push({
36
41
  event: eventName,
37
42
  properties: addSenderId(mixpanelUserId, {
38
43
  ...inputProperties,
39
44
  token: mixpanelToken,
40
45
  time: new Date().getTime(),
41
- $insert_id: randomUUID(),
46
+ $insert_id: insertId,
42
47
  ip: this.req.ip
43
48
  }, deviceId)
44
49
  })
@@ -60,14 +65,13 @@ export class DatabaseAPIWithAnalytics extends DatabaseAPI {
60
65
  }
61
66
 
62
67
  async sendAnalyticsEvents () {
63
- // istanbul ignore if
64
- if (this.__analyticsSent) {
65
- return
66
- }
67
- this.__analyticsSent = true
68
+ const events = this.__analyticsEvents
69
+ this.__analyticsEvents = []
70
+ const userProfileUpdates = this.__analyticsUserProfileUpdates
71
+ this.__analyticsUserProfileUpdates = {}
68
72
 
69
73
  const promises = []
70
- if (this.__analyticsEvents.length) {
74
+ if (events.length) {
71
75
  const uaData = {}
72
76
  const parser = new UAParser(this.req.headers['user-agent'])
73
77
  const browser = parser.getBrowser()
@@ -92,7 +96,7 @@ export class DatabaseAPIWithAnalytics extends DatabaseAPI {
92
96
  }
93
97
  }
94
98
 
95
- for (const x of this.__analyticsEvents) {
99
+ for (const x of events) {
96
100
  Object.assign(x.properties, uaData)
97
101
  }
98
102
  // send all the events in one Mixpanel API call
@@ -100,12 +104,12 @@ export class DatabaseAPIWithAnalytics extends DatabaseAPI {
100
104
  method: 'POST',
101
105
  url: 'https://api.mixpanel.com/track',
102
106
  headers: { accept: 'text/plain' },
103
- body: this.__analyticsEvents
107
+ body: events
104
108
  }))
105
109
  }
106
110
  const sent = []
107
- for (const type of Object.keys(this.__analyticsUserProfileUpdates)) {
108
- const updatesByUser = this.__analyticsUserProfileUpdates[type]
111
+ for (const type of Object.keys(userProfileUpdates)) {
112
+ const updatesByUser = userProfileUpdates[type]
109
113
  const body = []
110
114
  for (const uid of Object.keys(updatesByUser)) {
111
115
  const updates = updatesByUser[uid]
@@ -54,12 +54,18 @@ export class TestAnalyticsAPI extends DatabaseAPIWithAnalytics {
54
54
  async computeResponse () {
55
55
  // istanbul ignore next
56
56
  assert(isUnitTesting || isLocalhost)
57
- const { eventCalls, profileUpdates } = this.req.body
57
+ const { eventCalls, profileUpdates, moreEventCalls } = this.req.body
58
58
  for (const x of (eventCalls ?? [])) {
59
59
  this.logAnalyticsEvent(...x)
60
60
  }
61
61
  for (const x of (profileUpdates ?? [])) {
62
62
  this.updateAnalyticsUserProfile(...x)
63
63
  }
64
+ if (moreEventCalls) {
65
+ await this.sendAnalyticsEvents()
66
+ for (const x of moreEventCalls) {
67
+ this.logAnalyticsEvent(...x)
68
+ }
69
+ }
64
70
  }
65
71
  }
@@ -1,3 +1,5 @@
1
+ import crypto from 'node:crypto'
2
+
1
3
  import { mixpanelToken } from '../src/analytics.js'
2
4
 
3
5
  import { AppTest, runTests } from './base-test.js'
@@ -63,6 +65,39 @@ class AnalyticsTest extends AppTest {
63
65
  }).expect(expRespCode)
64
66
  }
65
67
 
68
+ async testSendInBatches () {
69
+ await this.app.post('/analytics')
70
+ .send({
71
+ eventCalls: [
72
+ ['xyz', 'some event', { cool: 1, hi: 'world' }]
73
+ ],
74
+ moreEventCalls: [
75
+ ['xyz', 'another event', { x: 2 }]
76
+ ]
77
+ }).expect(200)
78
+ const calls = this.fetchMock.mock.calls
79
+ expect(calls.length).toBe(2)
80
+ const actualBody = JSON.parse(calls[0][1].body)
81
+ expect(actualBody).toEqual([{
82
+ event: 'some event',
83
+ properties: expect.objectContaining({
84
+ cool: 1,
85
+ hi: 'world',
86
+ $user_id: 'xyz',
87
+ token: mixpanelToken
88
+ })
89
+ }])
90
+ const actualBody2 = JSON.parse(calls[1][1].body)
91
+ expect(actualBody2).toEqual([{
92
+ event: 'another event',
93
+ properties: expect.objectContaining({
94
+ x: 2,
95
+ $user_id: 'xyz',
96
+ token: mixpanelToken
97
+ })
98
+ }])
99
+ }
100
+
66
101
  async testDeviceId () {
67
102
  await this.app.post('/analytics')
68
103
  .send({
@@ -106,6 +141,47 @@ class AnalyticsTest extends AppTest {
106
141
  }])
107
142
  }
108
143
 
144
+ async testCustomInsertionId () {
145
+ await this.app.post('/analytics')
146
+ .send({
147
+ eventCalls: [
148
+ ['some uid', 'some event', { cool: 1, hi: 'world' }, null, 'xx']
149
+ ]
150
+ }).expect(200)
151
+ const calls = this.fetchMock.mock.calls
152
+ expect(calls.length).toBe(1)
153
+ const actualBody = JSON.parse(calls[0][1].body)
154
+ expect(actualBody).toEqual([{
155
+ event: 'some event',
156
+ properties: expect.objectContaining({
157
+ cool: 1,
158
+ hi: 'world',
159
+ $user_id: 'some uid',
160
+ token: mixpanelToken,
161
+ $insert_id: crypto.createHash('md5').update('xx').digest('hex')
162
+ })
163
+ }])
164
+ }
165
+
166
+ async testOmittingEventProperties () {
167
+ await this.app.post('/analytics')
168
+ .send({
169
+ eventCalls: [
170
+ ['some uid', 'some event']
171
+ ]
172
+ }).expect(200)
173
+ const calls = this.fetchMock.mock.calls
174
+ expect(calls.length).toBe(1)
175
+ const actualBody = JSON.parse(calls[0][1].body)
176
+ expect(actualBody).toEqual([{
177
+ event: 'some event',
178
+ properties: expect.objectContaining({
179
+ $user_id: 'some uid',
180
+ token: mixpanelToken
181
+ })
182
+ }])
183
+ }
184
+
109
185
  async testUserAgent () {
110
186
  await this.sendBasicEvent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36')
111
187
  const calls = this.fetchMock.mock.calls