@planningcenter/chat-react-native 4.7.1-qa-staging.7 → 4.7.1-qa-staging.9

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.
Files changed (71) hide show
  1. package/build/contexts/api_provider.d.ts.map +1 -1
  2. package/build/contexts/api_provider.js +2 -0
  3. package/build/contexts/api_provider.js.map +1 -1
  4. package/build/contexts/chat_context.d.ts +0 -2
  5. package/build/contexts/chat_context.d.ts.map +1 -1
  6. package/build/contexts/chat_context.js +16 -93
  7. package/build/contexts/chat_context.js.map +1 -1
  8. package/build/contexts/session_context.d.ts.map +1 -1
  9. package/build/contexts/session_context.js +3 -0
  10. package/build/contexts/session_context.js.map +1 -1
  11. package/build/hooks/use_conversation_jolt_events.d.ts.map +1 -1
  12. package/build/hooks/use_conversation_jolt_events.js +3 -2
  13. package/build/hooks/use_conversation_jolt_events.js.map +1 -1
  14. package/build/hooks/use_conversations_actions.d.ts +9 -9
  15. package/build/hooks/use_conversations_actions.d.ts.map +1 -1
  16. package/build/hooks/use_conversations_actions.js +12 -7
  17. package/build/hooks/use_conversations_actions.js.map +1 -1
  18. package/build/hooks/use_conversations_cache.d.ts +1 -3
  19. package/build/hooks/use_conversations_cache.d.ts.map +1 -1
  20. package/build/hooks/use_conversations_cache.js +79 -124
  21. package/build/hooks/use_conversations_cache.js.map +1 -1
  22. package/build/hooks/use_conversations_jolt_events.d.ts.map +1 -1
  23. package/build/hooks/use_conversations_jolt_events.js +47 -20
  24. package/build/hooks/use_conversations_jolt_events.js.map +1 -1
  25. package/build/hooks/use_mark_latest_message_read.d.ts.map +1 -1
  26. package/build/hooks/use_mark_latest_message_read.js +5 -4
  27. package/build/hooks/use_mark_latest_message_read.js.map +1 -1
  28. package/build/hooks/use_product_analytics.d.ts.map +1 -1
  29. package/build/hooks/use_product_analytics.js +93 -75
  30. package/build/hooks/use_product_analytics.js.map +1 -1
  31. package/build/types/jolt_events/index.d.ts +2 -0
  32. package/build/types/jolt_events/index.d.ts.map +1 -1
  33. package/build/types/jolt_events/index.js.map +1 -1
  34. package/build/types/jolt_events/person_events.d.ts +9 -0
  35. package/build/types/jolt_events/person_events.d.ts.map +1 -0
  36. package/build/types/jolt_events/person_events.js +2 -0
  37. package/build/types/jolt_events/person_events.js.map +1 -0
  38. package/build/utils/jolt/parse_stream_user_event_type.d.ts +3 -0
  39. package/build/utils/jolt/parse_stream_user_event_type.d.ts.map +1 -0
  40. package/build/utils/jolt/parse_stream_user_event_type.js +9 -0
  41. package/build/utils/jolt/parse_stream_user_event_type.js.map +1 -0
  42. package/build/utils/product_analytics_token.d.ts +12 -0
  43. package/build/utils/product_analytics_token.d.ts.map +1 -0
  44. package/build/utils/product_analytics_token.js +84 -0
  45. package/build/utils/product_analytics_token.js.map +1 -0
  46. package/build/utils/throttled_refresh.d.ts +7 -0
  47. package/build/utils/throttled_refresh.d.ts.map +1 -0
  48. package/build/utils/throttled_refresh.js +42 -0
  49. package/build/utils/throttled_refresh.js.map +1 -0
  50. package/package.json +3 -3
  51. package/src/contexts/api_provider.tsx +2 -0
  52. package/src/contexts/chat_context.tsx +2 -58
  53. package/src/contexts/session_context.tsx +3 -0
  54. package/src/hooks/__tests__/jolt_refresh_throttling.test.tsx +229 -0
  55. package/src/hooks/__tests__/use_conversations_jolt_events.test.tsx +1 -0
  56. package/src/hooks/__tests__/use_conversations_mark_read.test.tsx +38 -12
  57. package/src/hooks/__tests__/use_mark_latest_message_read.test.tsx +23 -2
  58. package/src/hooks/__tests__/use_product_analytics.test.tsx +304 -0
  59. package/src/hooks/use_conversation_jolt_events.ts +2 -1
  60. package/src/hooks/use_conversations_actions.ts +7 -4
  61. package/src/hooks/use_conversations_cache.ts +1 -23
  62. package/src/hooks/use_conversations_jolt_events.ts +24 -10
  63. package/src/hooks/use_mark_latest_message_read.ts +6 -5
  64. package/src/hooks/use_product_analytics.ts +74 -41
  65. package/src/types/jolt_events/index.ts +2 -0
  66. package/src/types/jolt_events/person_events.ts +16 -0
  67. package/src/utils/__tests__/throttled_refresh.test.ts +101 -0
  68. package/src/utils/jolt/__tests__/parse_stream_user_event_type.test.ts +27 -0
  69. package/src/utils/jolt/parse_stream_user_event_type.ts +16 -0
  70. package/src/utils/product_analytics_token.ts +120 -0
  71. package/src/utils/throttled_refresh.ts +62 -0
@@ -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
+ })
@@ -3,6 +3,7 @@ import { useCallback, useMemo } from 'react'
3
3
  import { ApiResource, ConversationResource } from '../types'
4
4
  import { JoltConversationEvent, JoltReactionEvent } from '../types/jolt_events'
5
5
  import { completeMessageCreationConversationTracking } from '../utils/performance_tracking'
6
+ import { throttledRefresh } from '../utils/throttled_refresh'
6
7
  import { useApiClient } from './use_api_client'
7
8
  import { getConversationRequestArgs } from './use_conversation'
8
9
  import { useCurrentPerson } from './use_current_person'
@@ -54,7 +55,7 @@ export function useConversationJoltEvents({ conversationId }: Props) {
54
55
  }
55
56
  })
56
57
 
57
- queryClient.invalidateQueries({ queryKey })
58
+ throttledRefresh(queryClient, queryKey, e, () => queryClient.invalidateQueries({ queryKey }))
58
59
  },
59
60
  [queryClient, queryKey, currentPersonId, apiClient]
60
61
  )
@@ -17,7 +17,7 @@ export const useConversationsMarkRead = ({
17
17
  const queryClient = useQueryClient()
18
18
  const { args } = useConversationsContext()
19
19
  const currentPersonCache = useCurrentPersonCache()
20
- const { updateInAllLists, invalidateAllLists, fetchUpdate } = useConversationsCache(args)
20
+ const { updateInAllLists, invalidateAllLists } = useConversationsCache(args)
21
21
  const conversationQueryKey = getRequestQueryKey(
22
22
  getConversationRequestArgs({ conversation_id: conversation.id })
23
23
  )
@@ -48,13 +48,16 @@ export const useConversationsMarkRead = ({
48
48
  mutationFn: async (read: boolean) => {
49
49
  const action = read ? 'mark_read' : 'mark_unread'
50
50
 
51
- return apiClient.chat.post({
51
+ return apiClient.chat.post<ApiResource<ConversationResource>>({
52
52
  url: `/me/conversations/${conversation.id}/${action}`,
53
53
  data: { data: { type: '', attributes: {} }, fields: { Conversation: 'unread_count,id' } },
54
54
  })
55
55
  },
56
- onSuccess: () => {
57
- fetchUpdate(conversation)
56
+ onSuccess: response => {
57
+ const unreadCount = response.data?.unreadCount
58
+ if (unreadCount === undefined) return
59
+
60
+ updateInAllLists(conversation.id, { unreadCount })
58
61
  },
59
62
  onError: () => {
60
63
  Alert.alert('Oops', 'Something went wrong updating this conversation, please try again')
@@ -2,7 +2,6 @@ import { InfiniteData, useQueryClient } from '@tanstack/react-query'
2
2
  import { ApiCollection, ConversationResource } from '../types'
3
3
  import {
4
4
  deleteRecordInPagesData,
5
- updateRecordInPagesData,
6
5
  updateAllRecordsInPagesData,
7
6
  updateOrCreateRecordInPagesData,
8
7
  } from '../utils'
@@ -44,20 +43,6 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
44
43
  )
45
44
  }
46
45
 
47
- const updateOnly = async (conversation: ConversationResource) => {
48
- if (!conversation.id) return
49
-
50
- queryClient.setQueryData<QueryData>(conversationQueryKey, prev =>
51
- updateRecordInPagesData({
52
- data: prev,
53
- record: conversation,
54
- processRecord: (record, current) => {
55
- return { ...current, ...record }
56
- },
57
- })
58
- )
59
- }
60
-
61
46
  const updateAll = async (update: Partial<ConversationResource>) => {
62
47
  queryClient.setQueryData<QueryData>(conversationQueryKey, prev =>
63
48
  updateAllRecordsInPagesData({
@@ -92,13 +77,6 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
92
77
  )
93
78
  }
94
79
 
95
- const fetchAndUpdate = async ({ id }: { id: number }) => {
96
- const conversation = await fetchConversation(id).catch(() => undefined)
97
- if (!conversation) return
98
-
99
- updateOnly(conversation)
100
- }
101
-
102
80
  const fetchAndSync = async ({ id }: { id: number }) => {
103
81
  let conversation: ConversationResource | undefined
104
82
  try {
@@ -115,10 +93,10 @@ export function useConversationsCache(args?: Partial<ConversationRequestArgs>) {
115
93
  }
116
94
 
117
95
  return {
96
+ queryKey: conversationQueryKey,
118
97
  create: updateOrCreate,
119
98
  destroy: handleConversationDestroy,
120
99
  fetchSync: fetchAndSync,
121
- fetchUpdate: fetchAndUpdate,
122
100
  invalidate: () => queryClient.invalidateQueries({ queryKey: conversationQueryKey }),
123
101
  invalidateAllLists,
124
102
  update: updateOrCreate,
@@ -1,37 +1,48 @@
1
+ import { useQueryClient } from '@tanstack/react-query'
1
2
  import { useConversationsContext } from '../contexts/conversations_context'
2
3
  import { CurrentPersonResource } from '../types'
3
- import { JoltConversationEvent } from '../types/jolt_events'
4
+ import { JoltConversationEvent, StreamUserUpdatedEvent } from '../types/jolt_events'
5
+ import { parseStreamUserEventType } from '../utils/jolt/parse_stream_user_event_type'
4
6
  import { completeMessageCreationConversationTracking } from '../utils/performance_tracking'
7
+ import { throttledRefresh } from '../utils/throttled_refresh'
5
8
  import { useApiGet } from './use_api'
6
9
  import { useApiClient } from './use_api_client'
7
10
  import { useConversationsCache } from './use_conversations_cache'
8
- import { currentPersonRequestArgs, useCurrentPersonCache } from './use_current_person'
11
+ import {
12
+ currentPersonQueryKey,
13
+ currentPersonRequestArgs,
14
+ useCurrentPersonCache,
15
+ } from './use_current_person'
9
16
  import { useJoltChannel, useJoltEvent } from './use_jolt'
10
17
 
11
18
  const useCurrentPerson = () => {
12
19
  return useApiGet<CurrentPersonResource>(currentPersonRequestArgs)
13
20
  }
14
21
 
22
+ const refreshesCurrentPerson = (event: StreamUserUpdatedEvent) => {
23
+ const eventType = parseStreamUserEventType(event)
24
+ return eventType === undefined || eventType === 'app_grant.synced'
25
+ }
26
+
15
27
  export function useConversationsJoltEvents() {
16
28
  const { data: currentPerson } = useCurrentPerson()
17
29
  const { args } = useConversationsContext()
18
30
  const cache = useConversationsCache(args)
19
31
  const currentPersonCache = useCurrentPersonCache()
20
32
  const apiClient = useApiClient()
33
+ const queryClient = useQueryClient()
21
34
  const enabled = currentPerson?.id ? true : false
22
35
  const joltChannel = useJoltChannel(`chat.people.${currentPerson?.id}`, enabled)
23
36
 
24
37
  useJoltEvent(joltChannel, 'conversation.updated', (e: JoltConversationEvent) => {
25
- if (
26
- e.data.data.last_message_idempotent_key &&
27
- e.data.data.last_message_author_id === currentPerson?.id
28
- ) {
38
+ const { id, last_message_idempotent_key, last_message_author_id } = e.data.data
39
+ if (last_message_idempotent_key && last_message_author_id === currentPerson?.id) {
29
40
  completeMessageCreationConversationTracking({
30
41
  apiClient,
31
- idempotentKey: e.data.data.last_message_idempotent_key,
42
+ idempotentKey: last_message_idempotent_key,
32
43
  })
33
44
  }
34
- cache.fetchSync({ id: e.data.data.id })
45
+ throttledRefresh(queryClient, [...cache.queryKey, id], e, () => cache.fetchSync({ id }))
35
46
  })
36
47
  useJoltEvent(joltChannel, 'conversation.created', (e: JoltConversationEvent) =>
37
48
  cache.fetchSync({ id: e.data.data.id })
@@ -40,6 +51,9 @@ export function useConversationsJoltEvents() {
40
51
  cache.destroy({ id: e.data.data.id })
41
52
  )
42
53
 
43
- useJoltEvent(joltChannel, 'STREAM_USER_UPDATED', currentPersonCache.invalidate) // Would be nice to have a non-stream chat event
44
- useJoltEvent(joltChannel, 'conversation.read', currentPersonCache.invalidate)
54
+ useJoltEvent(joltChannel, 'STREAM_USER_UPDATED', (e: StreamUserUpdatedEvent) => {
55
+ if (!refreshesCurrentPerson(e)) return
56
+
57
+ throttledRefresh(queryClient, currentPersonQueryKey, e, currentPersonCache.invalidate)
58
+ })
45
59
  }
@@ -1,6 +1,7 @@
1
- import { debounce } from 'lodash'
1
+ import { throttle } from 'lodash'
2
2
  import { useEffect, useMemo, useRef } from 'react'
3
3
  import { ConversationResource, MessageResource } from '../types'
4
+ import { REFRESH_THROTTLE_MS } from '../utils/throttled_refresh'
4
5
  import { useAppState } from './use_app_state'
5
6
  import { useConversationsMarkRead } from './use_conversations_actions'
6
7
 
@@ -13,8 +14,8 @@ interface Props {
13
14
  export function useMarkLatestMessageRead({ conversation, enabled = true }: Props) {
14
15
  const firedOnce = useRef<boolean>(false)
15
16
  const { markRead } = useConversationsMarkRead({ conversation })
16
- const debouncedMarkRead = useMemo(
17
- () => debounce(markRead, 1000, { leading: true, trailing: true }),
17
+ const throttledMarkRead = useMemo(
18
+ () => throttle(markRead, REFRESH_THROTTLE_MS, { leading: true, trailing: true }),
18
19
  [markRead]
19
20
  )
20
21
  const unreadCount = conversation.unreadCount
@@ -30,6 +31,6 @@ export function useMarkLatestMessageRead({ conversation, enabled = true }: Props
30
31
 
31
32
  firedOnce.current = true
32
33
 
33
- debouncedMarkRead(true)
34
- }, [debouncedMarkRead, isActive, shouldMarkRead, unreadReaction])
34
+ throttledMarkRead(true)
35
+ }, [throttledMarkRead, isActive, shouldMarkRead, unreadReaction])
35
36
  }
@@ -1,8 +1,12 @@
1
- import { useCallback, useEffect, useMemo, useRef } from 'react'
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
- return fetch(config.endpoint, {
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
- if (__DEV__) {
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 { productAnalyticsConfig } = useChatContext()
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 (!productAnalyticsConfig) {
85
- if (__DEV__) {
86
- console.warn('Product Analytics not available')
87
- }
88
- return Promise.resolve([])
89
- }
90
-
91
- const eventsWithMeta = events.map(event => ({
92
- name: event.name,
93
- meta: { ...snakeCasedBaseMeta, ...event.meta } as EventMetadata,
94
- }))
95
-
96
- return sendEvents(eventsWithMeta, productAnalyticsConfig)
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
- [productAnalyticsConfig, snakeCasedBaseMeta]
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 }
@@ -10,6 +10,7 @@ import type {
10
10
  MessageDeletedEvent,
11
11
  MessageUpdatedEvent,
12
12
  } from './message_events'
13
+ import type { StreamUserEventType, StreamUserUpdatedEvent } from './person_events'
13
14
  import type { ReactionCreatedEvent, ReactionDeletedEvent } from './reaction_events'
14
15
  import type { TypingBroadcastEvent } from './typing_events'
15
16
 
@@ -22,6 +23,7 @@ export type JoltMessageEvent = MessageCreatedEvent | MessageUpdatedEvent | Messa
22
23
  export type JoltReactionEvent = ReactionCreatedEvent | ReactionDeletedEvent
23
24
  export type JoltTypingEvent = TypingBroadcastEvent
24
25
  export type JoltAttachmentEvent = AttachmentFlaggedEvent
26
+ export type { StreamUserEventType, StreamUserUpdatedEvent }
25
27
 
26
28
  export type CustomJoltEvent =
27
29
  | JoltConversationEvent