@planningcenter/chat-react-native 4.7.1-qa-staging.7 → 4.7.1-qa-staging.8
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/build/contexts/chat_context.d.ts +0 -2
- package/build/contexts/chat_context.d.ts.map +1 -1
- package/build/contexts/chat_context.js +16 -93
- package/build/contexts/chat_context.js.map +1 -1
- package/build/hooks/use_product_analytics.d.ts.map +1 -1
- package/build/hooks/use_product_analytics.js +93 -75
- package/build/hooks/use_product_analytics.js.map +1 -1
- package/build/utils/product_analytics_token.d.ts +12 -0
- package/build/utils/product_analytics_token.d.ts.map +1 -0
- package/build/utils/product_analytics_token.js +84 -0
- package/build/utils/product_analytics_token.js.map +1 -0
- package/package.json +3 -3
- package/src/contexts/chat_context.tsx +2 -58
- package/src/hooks/__tests__/use_product_analytics.test.tsx +304 -0
- package/src/hooks/use_product_analytics.ts +74 -41
- package/src/utils/product_analytics_token.ts +120 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@planningcenter/chat-react-native",
|
|
3
|
-
"version": "4.7.1-qa-staging.
|
|
3
|
+
"version": "4.7.1-qa-staging.8",
|
|
4
4
|
"description": "",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"@fortawesome/fontawesome-svg-core": "^7.2.0",
|
|
35
35
|
"@fortawesome/react-native-fontawesome": "^0.3.2",
|
|
36
|
-
"@planningcenter/emoji-keyboard": "4.7.1-qa-staging.
|
|
36
|
+
"@planningcenter/emoji-keyboard": "4.7.1-qa-staging.8",
|
|
37
37
|
"lodash-inflection": "^1.5.0"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
@@ -84,5 +84,5 @@
|
|
|
84
84
|
"sf-symbols-typescript": "^2.2.0",
|
|
85
85
|
"typescript": "~6.0.3"
|
|
86
86
|
},
|
|
87
|
-
"gitHead": "
|
|
87
|
+
"gitHead": "943fb630f81d1960d40c333a9933e25f9fea7535"
|
|
88
88
|
}
|
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
import { useQuery } from '@tanstack/react-query'
|
|
2
1
|
import { merge } from 'lodash'
|
|
3
2
|
import React, { createContext, useMemo } from 'react'
|
|
4
3
|
import { ColorSchemeName, useColorScheme } from 'react-native'
|
|
5
4
|
import { AgeCheckContactInfo } from '../screens/age_check/screen_props'
|
|
6
|
-
import {
|
|
5
|
+
import { DeepPartial } from '../types'
|
|
7
6
|
import { FailedResponse } from '../types'
|
|
8
|
-
import {
|
|
9
|
-
import { Client, ENV, OauthType, PartialToken, Session, Uri } from '../utils'
|
|
7
|
+
import { ENV, OauthType, PartialToken, Session } from '../utils'
|
|
10
8
|
import { setLiquidGlassCapability } from '../utils/liquid_glass'
|
|
11
9
|
import { ChatTheme, defaultTheme, DefaultTheme } from '../utils/theme'
|
|
12
10
|
|
|
@@ -27,7 +25,6 @@ export interface ChatContextValue extends Omit<ChatProviderProps, 'theme'> {
|
|
|
27
25
|
session: Session
|
|
28
26
|
theme: ChatTheme
|
|
29
27
|
onAgeDisqualification: (params: AgeCheckContactInfo) => void
|
|
30
|
-
productAnalyticsConfig: ProductAnalyticsConfig | undefined
|
|
31
28
|
}
|
|
32
29
|
|
|
33
30
|
export const ChatContext = createContext<ChatContextValue>({
|
|
@@ -40,7 +37,6 @@ export const ChatContext = createContext<ChatContextValue>({
|
|
|
40
37
|
token: undefined,
|
|
41
38
|
edgeToEdge: true,
|
|
42
39
|
liquidGlassEnabled: false,
|
|
43
|
-
productAnalyticsConfig: undefined,
|
|
44
40
|
})
|
|
45
41
|
|
|
46
42
|
export function ChatProvider({ children, value }: { children: any; value: ChatProviderProps }) {
|
|
@@ -64,7 +60,6 @@ export function ChatProvider({ children, value }: { children: any; value: ChatPr
|
|
|
64
60
|
[env, prototypeName, token, tokenType]
|
|
65
61
|
)
|
|
66
62
|
|
|
67
|
-
const productAnalyticsConfig = useProductAnalyticsConfig(session)
|
|
68
63
|
const contextValue: ChatContextValue = {
|
|
69
64
|
...value,
|
|
70
65
|
edgeToEdge,
|
|
@@ -76,7 +71,6 @@ export function ChatProvider({ children, value }: { children: any; value: ChatPr
|
|
|
76
71
|
session,
|
|
77
72
|
theme,
|
|
78
73
|
token,
|
|
79
|
-
productAnalyticsConfig,
|
|
80
74
|
}
|
|
81
75
|
|
|
82
76
|
return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>
|
|
@@ -107,53 +101,3 @@ export const useCreateChatTheme = ({
|
|
|
107
101
|
|
|
108
102
|
return theme
|
|
109
103
|
}
|
|
110
|
-
|
|
111
|
-
interface ProductAnalyticsTokenResponse {
|
|
112
|
-
type: 'ProductAnalyticsToken'
|
|
113
|
-
id: string
|
|
114
|
-
url: string
|
|
115
|
-
metadata: Record<string, unknown>
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// expiry time comes from here:
|
|
119
|
-
// https://github.com/planningcenter/pco-product-analytics/blob/e5bbc4c31b715b3c329c06a162829ee6967d3094/lib/pco/product/analytics/client_token_provider.rb#L24
|
|
120
|
-
const TOKEN_EXPIRY_TIME = 604800 * 1000 // 7 days in milliseconds
|
|
121
|
-
|
|
122
|
-
const useProductAnalyticsConfig = (session: Session): ProductAnalyticsConfig | undefined => {
|
|
123
|
-
const uri = useMemo(() => new Uri({ session }), [session])
|
|
124
|
-
const apiClient = useMemo(
|
|
125
|
-
() =>
|
|
126
|
-
new Client({
|
|
127
|
-
root: uri.api(`/chat/v2`),
|
|
128
|
-
defaultHeaders: uri.headers,
|
|
129
|
-
version: '2018-11-01',
|
|
130
|
-
}),
|
|
131
|
-
[uri]
|
|
132
|
-
)
|
|
133
|
-
|
|
134
|
-
const { data: config } = useQuery<ProductAnalyticsConfig>({
|
|
135
|
-
queryKey: ['product-analytics-token'],
|
|
136
|
-
queryFn: () =>
|
|
137
|
-
apiClient
|
|
138
|
-
.post<ApiResource<ProductAnalyticsTokenResponse>>({
|
|
139
|
-
url: '/me/product_analytics_authorize',
|
|
140
|
-
data: {
|
|
141
|
-
data: {
|
|
142
|
-
type: 'ProductAnalyticsToken',
|
|
143
|
-
attributes: {},
|
|
144
|
-
},
|
|
145
|
-
},
|
|
146
|
-
})
|
|
147
|
-
.then(res => ({
|
|
148
|
-
token: res.data.id,
|
|
149
|
-
endpoint: res.data.url,
|
|
150
|
-
metadata: res.data.metadata,
|
|
151
|
-
})),
|
|
152
|
-
staleTime: TOKEN_EXPIRY_TIME,
|
|
153
|
-
gcTime: TOKEN_EXPIRY_TIME,
|
|
154
|
-
refetchInterval: TOKEN_EXPIRY_TIME,
|
|
155
|
-
enabled: process.env.NODE_ENV !== 'test',
|
|
156
|
-
})
|
|
157
|
-
|
|
158
|
-
return config
|
|
159
|
-
}
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
2
|
+
import { act, render, renderHook, waitFor } from '@testing-library/react-native'
|
|
3
|
+
import React from 'react'
|
|
4
|
+
import { Text } from 'react-native'
|
|
5
|
+
import { buildTestQueryClient } from '../../__utils__/query_client'
|
|
6
|
+
import { ChatProvider } from '../../contexts/chat_context'
|
|
7
|
+
import { Log } from '../../utils/native_adapters/configuration'
|
|
8
|
+
import {
|
|
9
|
+
productAnalyticsStorageKey,
|
|
10
|
+
StoredProductAnalyticsConfig,
|
|
11
|
+
TOKEN_EXPIRY_TIME,
|
|
12
|
+
} from '../../utils/product_analytics_token'
|
|
13
|
+
import { Session } from '../../utils/session'
|
|
14
|
+
import { ONE_HOUR } from '../../utils/time'
|
|
15
|
+
import { currentPersonQueryKey } from '../use_current_person'
|
|
16
|
+
import { analyticsEvents, useProductAnalytics } from '../use_product_analytics'
|
|
17
|
+
|
|
18
|
+
const mockStoredItems = new Map<string, string>()
|
|
19
|
+
jest.mock('../../utils/native_adapters', () => ({
|
|
20
|
+
...jest.requireActual('../../utils/native_adapters'),
|
|
21
|
+
Storage: {
|
|
22
|
+
getItem: async (key: string) => mockStoredItems.get(key) ?? null,
|
|
23
|
+
setItem: async (key: string, value: string) => {
|
|
24
|
+
mockStoredItems.set(key, value)
|
|
25
|
+
},
|
|
26
|
+
removeItem: async (key: string) => {
|
|
27
|
+
mockStoredItems.delete(key)
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
}))
|
|
31
|
+
|
|
32
|
+
const AUTHORIZE_PATH = '/me/product_analytics_authorize'
|
|
33
|
+
const ANALYTICS_ENDPOINT = 'https://analytics.pco.test/events'
|
|
34
|
+
const accessToken = 'access-token-12345678'
|
|
35
|
+
const otherAccessToken = 'access-token-87654321'
|
|
36
|
+
const session = new Session({ token: { access_token: accessToken } })
|
|
37
|
+
|
|
38
|
+
const jsonResponse = (body: unknown, status = 200) => {
|
|
39
|
+
const response = {
|
|
40
|
+
ok: status >= 200 && status < 300,
|
|
41
|
+
status,
|
|
42
|
+
statusText: '',
|
|
43
|
+
url: '',
|
|
44
|
+
headers: {},
|
|
45
|
+
text: async () => JSON.stringify(body),
|
|
46
|
+
json: async () => body,
|
|
47
|
+
arrayBuffer: async () => new ArrayBuffer(0),
|
|
48
|
+
clone: () => response,
|
|
49
|
+
}
|
|
50
|
+
return response as unknown as Response
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const authorizeResponse = (token: string) =>
|
|
54
|
+
jsonResponse({
|
|
55
|
+
data: {
|
|
56
|
+
type: 'ProductAnalyticsToken',
|
|
57
|
+
id: token,
|
|
58
|
+
attributes: { url: ANALYTICS_ENDPOINT, metadata: { person_id: '42' } },
|
|
59
|
+
},
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
const fetchMock = jest.fn<Promise<Response>, [string, RequestInit]>()
|
|
63
|
+
const authorizeCalls = () => fetchMock.mock.calls.filter(([url]) => url.includes(AUTHORIZE_PATH))
|
|
64
|
+
const analyticsCalls = () => fetchMock.mock.calls.filter(([url]) => url === ANALYTICS_ENDPOINT)
|
|
65
|
+
const sentEvents = () =>
|
|
66
|
+
analyticsCalls().flatMap(([, init]) => JSON.parse(init.body as string).events)
|
|
67
|
+
|
|
68
|
+
const respondWithToken = (token: string, status = 200, eventsStatus = 200) => {
|
|
69
|
+
fetchMock.mockImplementation(async url => {
|
|
70
|
+
if (url.includes(AUTHORIZE_PATH)) {
|
|
71
|
+
return status === 200 ? authorizeResponse(token) : jsonResponse({ errors: [] }, status)
|
|
72
|
+
}
|
|
73
|
+
return jsonResponse({}, eventsStatus)
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const PERSON_ID = '42'
|
|
78
|
+
|
|
79
|
+
const storeConfig = (overrides: Partial<StoredProductAnalyticsConfig> = {}) => {
|
|
80
|
+
const config: StoredProductAnalyticsConfig = {
|
|
81
|
+
token: 'stored-token',
|
|
82
|
+
endpoint: ANALYTICS_ENDPOINT,
|
|
83
|
+
metadata: { person_id: PERSON_ID },
|
|
84
|
+
expiresAt: Date.now() + TOKEN_EXPIRY_TIME,
|
|
85
|
+
personId: PERSON_ID,
|
|
86
|
+
...overrides,
|
|
87
|
+
}
|
|
88
|
+
mockStoredItems.set(productAnalyticsStorageKey(session), JSON.stringify(config))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let queryClient: QueryClient
|
|
92
|
+
let reportError: jest.SpyInstance
|
|
93
|
+
|
|
94
|
+
const buildWrapper =
|
|
95
|
+
(accessTokenForSession: string) =>
|
|
96
|
+
({ children }: { children: React.ReactNode }) => (
|
|
97
|
+
<QueryClientProvider client={queryClient}>
|
|
98
|
+
<ChatProvider
|
|
99
|
+
value={{
|
|
100
|
+
token: { access_token: accessTokenForSession },
|
|
101
|
+
onUnauthorizedResponse: () => {},
|
|
102
|
+
theme: { theme: { colors: {} }, colorScheme: 'light' },
|
|
103
|
+
}}
|
|
104
|
+
>
|
|
105
|
+
{children}
|
|
106
|
+
</ChatProvider>
|
|
107
|
+
</QueryClientProvider>
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
const renderAnalytics = (accessTokenForSession = accessToken) =>
|
|
111
|
+
renderHook(() => useProductAnalytics(), { wrapper: buildWrapper(accessTokenForSession) })
|
|
112
|
+
|
|
113
|
+
beforeEach(() => {
|
|
114
|
+
queryClient = buildTestQueryClient()
|
|
115
|
+
queryClient.setQueryData(currentPersonQueryKey, { data: { type: 'Person', id: PERSON_ID } })
|
|
116
|
+
mockStoredItems.clear()
|
|
117
|
+
fetchMock.mockReset()
|
|
118
|
+
reportError = jest.spyOn(Log, 'reportError').mockImplementation(() => {})
|
|
119
|
+
global.fetch = fetchMock as unknown as typeof fetch
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
afterEach(() => {
|
|
123
|
+
queryClient.clear()
|
|
124
|
+
jest.restoreAllMocks()
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
describe('ChatProvider', () => {
|
|
128
|
+
const originalNodeEnv = process.env.NODE_ENV
|
|
129
|
+
|
|
130
|
+
beforeAll(() => {
|
|
131
|
+
process.env.NODE_ENV = 'development'
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
afterAll(() => {
|
|
135
|
+
process.env.NODE_ENV = originalNodeEnv
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it('does not request a product analytics token when nothing publishes an event', async () => {
|
|
139
|
+
respondWithToken('unused-token')
|
|
140
|
+
const Wrapper = buildWrapper(accessToken)
|
|
141
|
+
|
|
142
|
+
render(<Text>A screen without analytics</Text>, { wrapper: Wrapper })
|
|
143
|
+
await act(async () => {})
|
|
144
|
+
|
|
145
|
+
expect(authorizeCalls()).toHaveLength(0)
|
|
146
|
+
})
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
describe('useProductAnalytics', () => {
|
|
150
|
+
it('requests the token once for concurrent events and sends both with it', async () => {
|
|
151
|
+
respondWithToken('fresh-token')
|
|
152
|
+
const { result } = renderAnalytics()
|
|
153
|
+
|
|
154
|
+
await act(() =>
|
|
155
|
+
Promise.all([
|
|
156
|
+
result.current.publishEvent(analyticsEvents.conversation_index_opened),
|
|
157
|
+
result.current.publishEvent(analyticsEvents.search_performed, { term_length: 3 }),
|
|
158
|
+
])
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
162
|
+
expect(analyticsCalls()).toHaveLength(2)
|
|
163
|
+
analyticsCalls().forEach(([, init]) => {
|
|
164
|
+
expect(init.headers).toMatchObject({ 'X-Authorization': 'Bearer fresh-token' })
|
|
165
|
+
})
|
|
166
|
+
expect(sentEvents()).toEqual([
|
|
167
|
+
{ name: analyticsEvents.conversation_index_opened, meta: { person_id: '42' } },
|
|
168
|
+
{ name: analyticsEvents.search_performed, meta: { person_id: '42', term_length: 3 } },
|
|
169
|
+
])
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
it('stores a fetched token with its expiry for this person', async () => {
|
|
173
|
+
respondWithToken('fresh-token')
|
|
174
|
+
const { result } = renderAnalytics()
|
|
175
|
+
const before = Date.now()
|
|
176
|
+
|
|
177
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_show_opened))
|
|
178
|
+
|
|
179
|
+
const stored = JSON.parse(mockStoredItems.get(productAnalyticsStorageKey(session)) ?? 'null')
|
|
180
|
+
expect(stored).toMatchObject({
|
|
181
|
+
token: 'fresh-token',
|
|
182
|
+
endpoint: ANALYTICS_ENDPOINT,
|
|
183
|
+
personId: PERSON_ID,
|
|
184
|
+
})
|
|
185
|
+
expect(stored.expiresAt).toBeGreaterThanOrEqual(before + TOKEN_EXPIRY_TIME)
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
it('reuses a stored unexpired token for the same person without an authorize request', async () => {
|
|
189
|
+
respondWithToken('fresh-token')
|
|
190
|
+
storeConfig()
|
|
191
|
+
const { result } = renderAnalytics()
|
|
192
|
+
|
|
193
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
194
|
+
|
|
195
|
+
expect(authorizeCalls()).toHaveLength(0)
|
|
196
|
+
expect(analyticsCalls()).toHaveLength(1)
|
|
197
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
198
|
+
'X-Authorization': 'Bearer stored-token',
|
|
199
|
+
})
|
|
200
|
+
})
|
|
201
|
+
|
|
202
|
+
it('replaces a stored token that is within an hour of expiring', async () => {
|
|
203
|
+
respondWithToken('fresh-token')
|
|
204
|
+
storeConfig({ expiresAt: Date.now() + ONE_HOUR / 2 })
|
|
205
|
+
const { result } = renderAnalytics()
|
|
206
|
+
|
|
207
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
208
|
+
|
|
209
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
210
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
211
|
+
'X-Authorization': 'Bearer fresh-token',
|
|
212
|
+
})
|
|
213
|
+
expect(mockStoredItems.get(productAnalyticsStorageKey(session))).toContain('fresh-token')
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
it('reuses the stored token after the access token is refreshed', async () => {
|
|
217
|
+
respondWithToken('fresh-token')
|
|
218
|
+
storeConfig()
|
|
219
|
+
const { result } = renderAnalytics(otherAccessToken)
|
|
220
|
+
|
|
221
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
222
|
+
|
|
223
|
+
expect(authorizeCalls()).toHaveLength(0)
|
|
224
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
225
|
+
'X-Authorization': 'Bearer stored-token',
|
|
226
|
+
})
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
it('replaces a token stored for another person', async () => {
|
|
230
|
+
respondWithToken('fresh-token')
|
|
231
|
+
storeConfig({ personId: '99' })
|
|
232
|
+
const { result } = renderAnalytics()
|
|
233
|
+
|
|
234
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
235
|
+
|
|
236
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
237
|
+
expect(analyticsCalls()[0][1].headers).toMatchObject({
|
|
238
|
+
'X-Authorization': 'Bearer fresh-token',
|
|
239
|
+
})
|
|
240
|
+
expect(mockStoredItems.get(productAnalyticsStorageKey(session))).toContain('fresh-token')
|
|
241
|
+
})
|
|
242
|
+
|
|
243
|
+
it('drops the event without retrying when the authorize request is rejected', async () => {
|
|
244
|
+
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
|
245
|
+
jest.spyOn(console, 'error').mockImplementation(() => {})
|
|
246
|
+
respondWithToken('fresh-token', 429)
|
|
247
|
+
const { result } = renderAnalytics()
|
|
248
|
+
|
|
249
|
+
const responses = await act(() =>
|
|
250
|
+
result.current.publishEvent(analyticsEvents.conversation_index_opened)
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
expect(responses).toEqual([])
|
|
254
|
+
expect(authorizeCalls()).toHaveLength(1)
|
|
255
|
+
expect(analyticsCalls()).toHaveLength(0)
|
|
256
|
+
await waitFor(() => expect(mockStoredItems.size).toBe(0))
|
|
257
|
+
// Reported once, by the API client's HTTP instrumentation, not again here
|
|
258
|
+
expect(reportError).toHaveBeenCalledTimes(1)
|
|
259
|
+
expect(reportError.mock.calls[0][1]).toMatchObject({ scope: 'http' })
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
it('reports an unexpected token failure to Sentry and drops the event', async () => {
|
|
263
|
+
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
|
264
|
+
// An authorize response without the expected body
|
|
265
|
+
fetchMock.mockImplementation(async () => jsonResponse({}))
|
|
266
|
+
const { result } = renderAnalytics()
|
|
267
|
+
|
|
268
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
269
|
+
|
|
270
|
+
expect(analyticsCalls()).toHaveLength(0)
|
|
271
|
+
expect(reportError).toHaveBeenCalledTimes(1)
|
|
272
|
+
expect(reportError.mock.calls[0][1]).toMatchObject({
|
|
273
|
+
tags: { feature: 'product-analytics', 'analytics.stage': 'prepare' },
|
|
274
|
+
})
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
it('reports events the analytics endpoint rejects', async () => {
|
|
278
|
+
respondWithToken('fresh-token', 200, 401)
|
|
279
|
+
const { result } = renderAnalytics()
|
|
280
|
+
|
|
281
|
+
await act(() => result.current.publishEvent(analyticsEvents.conversation_index_opened))
|
|
282
|
+
|
|
283
|
+
expect(reportError).toHaveBeenCalledTimes(1)
|
|
284
|
+
const [error, context] = reportError.mock.calls[0]
|
|
285
|
+
expect(error.name).toBe('HTTPError401')
|
|
286
|
+
expect(context).toMatchObject({ tags: { 'analytics.stage': 'send', 'http.status': '401' } })
|
|
287
|
+
})
|
|
288
|
+
|
|
289
|
+
it('does not report a network failure while sending events', async () => {
|
|
290
|
+
jest.spyOn(console, 'warn').mockImplementation(() => {})
|
|
291
|
+
fetchMock.mockImplementation(async url => {
|
|
292
|
+
if (url.includes(AUTHORIZE_PATH)) return authorizeResponse('fresh-token')
|
|
293
|
+
throw new TypeError('Network request failed')
|
|
294
|
+
})
|
|
295
|
+
const { result } = renderAnalytics()
|
|
296
|
+
|
|
297
|
+
const responses = await act(() =>
|
|
298
|
+
result.current.publishEvent(analyticsEvents.conversation_index_opened)
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
expect(responses).toEqual([])
|
|
302
|
+
expect(reportError).not.toHaveBeenCalled()
|
|
303
|
+
})
|
|
304
|
+
})
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isCancelledError, useQueryClient } from '@tanstack/react-query'
|
|
2
|
+
import { useCallback, useEffect, useRef } from 'react'
|
|
2
3
|
import { useChatContext } from '../contexts/chat_context'
|
|
3
4
|
import { ProductAnalyticsConfig } from '../types/product_analytics'
|
|
4
5
|
import { AnalyticsMetadataResource } from '../types/resources/analytics_metadata'
|
|
5
6
|
import { keysToSnakeCase } from '../utils/client/utils'
|
|
7
|
+
import { Log } from '../utils/native_adapters/configuration'
|
|
8
|
+
import { fetchProductAnalyticsConfig } from '../utils/product_analytics_token'
|
|
9
|
+
import { isResponseLike, ResponseError } from '../utils/response_error'
|
|
6
10
|
import { SHA256, enc } from '../utils/sha_256'
|
|
7
11
|
|
|
8
12
|
export interface EventMetadata {
|
|
@@ -27,6 +31,46 @@ function contentSha256(payload: string): string {
|
|
|
27
31
|
return SHA256(payload).toString(enc.Hex)
|
|
28
32
|
}
|
|
29
33
|
|
|
34
|
+
type AnalyticsStage = 'prepare' | 'send'
|
|
35
|
+
|
|
36
|
+
const REPORT_TAGS = {
|
|
37
|
+
team: 'chat',
|
|
38
|
+
package: 'chat-react-native',
|
|
39
|
+
feature: 'product-analytics',
|
|
40
|
+
} as const
|
|
41
|
+
|
|
42
|
+
const isNetworkFailure = (error: unknown) =>
|
|
43
|
+
error instanceof TypeError && /network/i.test(error.message)
|
|
44
|
+
|
|
45
|
+
// HTTP failures from the API client are already reported by instrumentedFetch,
|
|
46
|
+
// network failures are expected on flaky connections, and queries are cancelled
|
|
47
|
+
// whenever the session changes. Anything else is a bug worth seeing in Sentry.
|
|
48
|
+
const isExpectedFailure = (error: unknown) =>
|
|
49
|
+
isResponseLike(error) ||
|
|
50
|
+
error instanceof ResponseError ||
|
|
51
|
+
isCancelledError(error) ||
|
|
52
|
+
isNetworkFailure(error)
|
|
53
|
+
|
|
54
|
+
function reportAnalyticsError(error: unknown, stage: AnalyticsStage) {
|
|
55
|
+
if (__DEV__) {
|
|
56
|
+
console.warn(`Product Analytics ${stage} failed:`, error)
|
|
57
|
+
}
|
|
58
|
+
if (isExpectedFailure(error)) return
|
|
59
|
+
|
|
60
|
+
const reported = error instanceof Error ? error : new Error(String(error))
|
|
61
|
+
Log.reportError(reported, { tags: { ...REPORT_TAGS, 'analytics.stage': stage } })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The events endpoint is outside the chat API, so it isn't instrumented.
|
|
65
|
+
// A rejected batch here usually means the stored token is no longer accepted.
|
|
66
|
+
function reportRejectedEvents(response: Response) {
|
|
67
|
+
const error = new Error(`HTTP ${response.status} POST product analytics events`)
|
|
68
|
+
error.name = `HTTPError${response.status}`
|
|
69
|
+
Log.reportError(error, {
|
|
70
|
+
tags: { ...REPORT_TAGS, 'analytics.stage': 'send', 'http.status': String(response.status) },
|
|
71
|
+
})
|
|
72
|
+
}
|
|
73
|
+
|
|
30
74
|
function sendEvents(events: AnalyticsEvent[], config: ProductAnalyticsConfig): Promise<Response[]> {
|
|
31
75
|
// Split into chunks of 10 and make parallel requests
|
|
32
76
|
const chunks: AnalyticsEvent[][] = []
|
|
@@ -37,7 +81,7 @@ function sendEvents(events: AnalyticsEvent[], config: ProductAnalyticsConfig): P
|
|
|
37
81
|
return Promise.all(
|
|
38
82
|
chunks.map(async chunk => {
|
|
39
83
|
const payload = JSON.stringify({ events: chunk })
|
|
40
|
-
|
|
84
|
+
const response = await fetch(config.endpoint, {
|
|
41
85
|
method: 'POST',
|
|
42
86
|
headers: {
|
|
43
87
|
'Content-Type': 'application/json; charset=utf-8',
|
|
@@ -46,56 +90,45 @@ function sendEvents(events: AnalyticsEvent[], config: ProductAnalyticsConfig): P
|
|
|
46
90
|
},
|
|
47
91
|
body: payload,
|
|
48
92
|
})
|
|
93
|
+
if (!response.ok) reportRejectedEvents(response)
|
|
94
|
+
return response
|
|
49
95
|
})
|
|
50
96
|
).catch(error => {
|
|
51
|
-
|
|
52
|
-
console.warn('Product Analytics request failed:', error)
|
|
53
|
-
}
|
|
97
|
+
reportAnalyticsError(error, 'send')
|
|
54
98
|
return [] as Response[]
|
|
55
99
|
})
|
|
56
100
|
}
|
|
57
101
|
|
|
58
102
|
export const useProductAnalytics = () => {
|
|
59
|
-
const {
|
|
60
|
-
|
|
61
|
-
const snakeCasedBaseMeta = useMemo(
|
|
62
|
-
() => keysToSnakeCase(productAnalyticsConfig?.metadata || {}),
|
|
63
|
-
[productAnalyticsConfig?.metadata]
|
|
64
|
-
)
|
|
65
|
-
|
|
66
|
-
const publishEvent = useCallback(
|
|
67
|
-
(name: AnalyticsEventName, meta: EventMetadata = {}): Promise<Response[]> => {
|
|
68
|
-
if (!productAnalyticsConfig) {
|
|
69
|
-
if (__DEV__) {
|
|
70
|
-
console.warn('Product Analytics not available')
|
|
71
|
-
}
|
|
72
|
-
return Promise.resolve([])
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
const mergedMeta = { ...snakeCasedBaseMeta, ...meta } as EventMetadata
|
|
76
|
-
|
|
77
|
-
return sendEvents([{ name, meta: mergedMeta }], productAnalyticsConfig)
|
|
78
|
-
},
|
|
79
|
-
[productAnalyticsConfig, snakeCasedBaseMeta]
|
|
80
|
-
)
|
|
103
|
+
const { session } = useChatContext()
|
|
104
|
+
const queryClient = useQueryClient()
|
|
81
105
|
|
|
82
106
|
const publishEvents = useCallback(
|
|
83
107
|
(events: Array<{ name: AnalyticsEventName; meta?: EventMetadata }>): Promise<Response[]> => {
|
|
84
|
-
if (!
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
108
|
+
if (!session.isAuthenticated) return Promise.resolve([])
|
|
109
|
+
|
|
110
|
+
return fetchProductAnalyticsConfig(queryClient, session)
|
|
111
|
+
.then(config => {
|
|
112
|
+
const baseMeta = keysToSnakeCase(config.metadata || {})
|
|
113
|
+
const eventsWithMeta = events.map(event => ({
|
|
114
|
+
name: event.name,
|
|
115
|
+
meta: { ...baseMeta, ...event.meta } as EventMetadata,
|
|
116
|
+
}))
|
|
117
|
+
|
|
118
|
+
return sendEvents(eventsWithMeta, config)
|
|
119
|
+
})
|
|
120
|
+
.catch(error => {
|
|
121
|
+
reportAnalyticsError(error, 'prepare')
|
|
122
|
+
return [] as Response[]
|
|
123
|
+
})
|
|
97
124
|
},
|
|
98
|
-
[
|
|
125
|
+
[queryClient, session]
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
const publishEvent = useCallback(
|
|
129
|
+
(name: AnalyticsEventName, meta: EventMetadata = {}): Promise<Response[]> =>
|
|
130
|
+
publishEvents([{ name, meta }]),
|
|
131
|
+
[publishEvents]
|
|
99
132
|
)
|
|
100
133
|
|
|
101
134
|
return { publishEvent, publishEvents }
|