@aochuang/client-sdk 1.0.381-dev-2 → 1.0.381-dev-3

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": "@aochuang/client-sdk",
3
- "version": "1.0.381-dev-2",
3
+ "version": "1.0.381-dev-3",
4
4
  "description": "",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -56,15 +56,30 @@ export default class ClientChatAccount {
56
56
  }
57
57
 
58
58
  _addUnreadMessageNumLog (title, data) {
59
- if (this.onUnreadMessageNumLog) {
59
+ try {
60
+ if (!this.onUnreadMessageNumLog) {
61
+ return
62
+ }
60
63
  this.onUnreadMessageNumLog({
61
- group: 'client-chat-account:unreadMessageNum',
62
- content: {
63
- title,
64
- data
65
- }
64
+ group: 'diagnostic:account_unread_changed',
65
+ content: Object.assign({
66
+ event: 'account_unread_changed',
67
+ title
68
+ }, data)
66
69
  })
67
- }
70
+ } catch (error) {}
71
+ }
72
+
73
+ _addDiagnosticLog (event, data) {
74
+ try {
75
+ if (!this.onUnreadMessageNumLog) {
76
+ return
77
+ }
78
+ this.onUnreadMessageNumLog({
79
+ group: `diagnostic:${event}`,
80
+ content: Object.assign({ event }, data)
81
+ })
82
+ } catch (error) {}
68
83
  }
69
84
 
70
85
  get accountData () {
@@ -198,6 +213,7 @@ export default class ClientChatAccount {
198
213
  }
199
214
 
200
215
  refreshAllAccountUnreadMesageNum () {
216
+ const startedAt = Date.now()
201
217
  this.getAccountUnreadMessageNumMethod({
202
218
  wechatAccountIds: Object.keys(this.accountMap)
203
219
  }).then(rs => {
@@ -216,10 +232,17 @@ export default class ClientChatAccount {
216
232
  source: 'refreshAll',
217
233
  accounts: nextData
218
234
  })
235
+ }).catch(error => {
236
+ this._addDiagnosticLog('account_unread_refresh_failed', {
237
+ scope: 'all',
238
+ durationMs: Date.now() - startedAt,
239
+ errorType: error && (error.name || error.code) || typeof error
240
+ })
219
241
  })
220
242
  }
221
243
 
222
244
  refreshAccountUnreadMessageNum (params) {
245
+ const startedAt = Date.now()
223
246
  const { wechatAccountId, ...nextParams } = params
224
247
  this.getAccountUnreadMessageNumMethod(Object.assign({
225
248
  wechatAccountIds: [wechatAccountId]
@@ -251,6 +274,13 @@ export default class ClientChatAccount {
251
274
  before: before ? { num: before.num, muteNum: before.muteNum } : null,
252
275
  after: { num: after.num, muteNum: after.muteNum }
253
276
  })
277
+ }).catch(error => {
278
+ this._addDiagnosticLog('account_unread_refresh_failed', {
279
+ scope: 'single',
280
+ wechatAccountId,
281
+ durationMs: Date.now() - startedAt,
282
+ errorType: error && (error.name || error.code) || typeof error
283
+ })
254
284
  })
255
285
  }
256
286
 
@@ -54,6 +54,7 @@ export default class ClientChatMessage {
54
54
  groupField: null, // 分组的字段
55
55
  checkMessageSendResultMethod: null, // 检查消息发送结果
56
56
  loadLossMessageDataMethod: null, // 加载丢失的消息数据,例如socket断开期间没有收到的数据
57
+ getSessionIdMethod: null,
57
58
  onAddMessageSuccess: null // 新增消息成功回调事件
58
59
  }, options)
59
60
  if (!options.clientChat) {
@@ -68,6 +69,7 @@ export default class ClientChatMessage {
68
69
  this.sortField = options.sortField
69
70
  this.checkMessageSendResultMethod = options.checkMessageSendResultMethod
70
71
  this.loadLossMessageDataMethod = options.loadLossMessageDataMethod
72
+ this.getSessionIdMethod = options.getSessionIdMethod
71
73
  this.onAddMessageSuccess = options.onAddMessageSuccess
72
74
  this.event = new Event()
73
75
  }
@@ -83,9 +85,31 @@ export default class ClientChatMessage {
83
85
  event
84
86
  }, data)
85
87
  })
86
- } catch (error) {
87
- // 诊断日志失败不能影响消息处理。
88
- }
88
+ } catch (error) {}
89
+ }
90
+
91
+ getMessageDiagnosticData (data, extra = {}) {
92
+ let sessionId
93
+ try {
94
+ sessionId = this.getSessionIdMethod && this.getSessionIdMethod(data)
95
+ } catch (error) {}
96
+ return Object.assign({
97
+ messageId: data && data.id,
98
+ msgSvrId: data && data.msgSvrId,
99
+ sessionId
100
+ }, extra)
101
+ }
102
+
103
+ handleSessionUpdateError (data, error) {
104
+ this.addDiagnosticLog('message_session_update_failed', this.getMessageDiagnosticData(data, {
105
+ errorType: error && (error.name || error.code) || typeof error
106
+ }))
107
+ try {
108
+ console.error('[client-chat-message] onAddMessageSuccess error', {
109
+ messageId: data && data.id,
110
+ error
111
+ })
112
+ } catch (consoleError) {}
89
113
  }
90
114
 
91
115
  getGroupMessageSummary (groupId) {
@@ -149,9 +173,15 @@ export default class ClientChatMessage {
149
173
  */
150
174
  addMessage (data, fireEvent) {
151
175
  if (!data || !data.id || !data[this.groupField] || !data[this.sortField]) {
176
+ this.addDiagnosticLog('message_rejected', this.getMessageDiagnosticData(data, {
177
+ reason: 'missing_required_field'
178
+ }))
152
179
  throw new Error('缺少必须参数')
153
180
  }
154
181
  if (this.messageMap[data.id]) {
182
+ this.addDiagnosticLog('message_rejected', this.getMessageDiagnosticData(data, {
183
+ reason: 'duplicate_message_id'
184
+ }))
155
185
  return
156
186
  }
157
187
  if (this.tempMessageMap[data.id]) {
@@ -172,11 +202,22 @@ export default class ClientChatMessage {
172
202
  Vue.set(this.data.messageData[groupField][sortFields.day], sortFields.milliseconds, [])
173
203
  }
174
204
  if (this.data.messageData[groupField][sortFields.day][sortFields.milliseconds].some(v => v.id === data.id)) {
205
+ this.addDiagnosticLog('message_rejected', this.getMessageDiagnosticData(data, {
206
+ reason: 'duplicate_time_bucket'
207
+ }))
175
208
  return
176
209
  }
177
210
  this.data.messageData[groupField][sortFields.day][sortFields.milliseconds].push(data)
178
211
  this.messageMap[data.id] = data
179
212
  this.setLastMessageTime(groupField, data[this.sortField], data)
213
+ const storedDiagnostic = {}
214
+ if (isBeforeLastMessage) {
215
+ storedDiagnostic.outOfOrder = true
216
+ }
217
+ if (fireEvent === false) {
218
+ storedDiagnostic.eventDispatch = 'disabled'
219
+ }
220
+ this.addDiagnosticLog('message_stored', this.getMessageDiagnosticData(data, storedDiagnostic))
180
221
  // 发送中的消息并且不是临时占位消息,需要增加轮询结果逻辑
181
222
  if (data.isSend && data.sendStatus === 1 && !data._temp) {
182
223
  // 排除一下系统消息,因为后端系统消息的sendStatus永远为1,这会导致前端总是轮训去调用接口检查消息状态
@@ -188,16 +229,19 @@ export default class ClientChatMessage {
188
229
  // 先执行onAddMessageSuccess再发add-message事件,保证会话的getSession轮询先由这里发起、更新会话的回调排在最前面,
189
230
  // 外部监听add-message后再调getSession只是复用同一个轮询
190
231
  // try/catch是为了避免回调里的异常把add-message事件吞掉(外部的新消息提醒、本地消息缓存都依赖这个事件)
232
+ let sessionUpdateResult
191
233
  try {
192
- this.onAddMessageSuccess && this.onAddMessageSuccess({
234
+ sessionUpdateResult = this.onAddMessageSuccess && this.onAddMessageSuccess({
193
235
  data,
194
236
  lastMessageTime,
195
237
  isBeforeLastMessage
196
238
  })
197
239
  } catch (error) {
198
- console.error('[client-chat-message] onAddMessageSuccess error', {
199
- messageId: data.id,
200
- error
240
+ this.handleSessionUpdateError(data, error)
241
+ }
242
+ if (sessionUpdateResult && typeof sessionUpdateResult.catch === 'function') {
243
+ sessionUpdateResult.catch(error => {
244
+ this.handleSessionUpdateError(data, error)
201
245
  })
202
246
  }
203
247
  // 如果消息包含这种情况,就不能往外发送add-message事件
@@ -218,19 +262,14 @@ export default class ClientChatMessage {
218
262
  this.event && this.event.emit('add-message', {
219
263
  data
220
264
  })
265
+ this.addDiagnosticLog('message_event_emitted', this.getMessageDiagnosticData(data))
221
266
  } else {
222
- this.addDiagnosticLog('message_event_suppressed', {
223
- reason: suppressedReason,
224
- messageId: data.id,
225
- msgSvrId: data.msgSvrId,
226
- wechatAccountId: data.wechatAccountId,
227
- targetField: this.groupField,
228
- targetId: groupField,
229
- messageTime: data[this.sortField],
230
- lastMessageTime,
231
- memoryInserted: true,
232
- addMessageEventEmitted: false
233
- })
267
+ const suppressedDiagnostic = { reason: suppressedReason }
268
+ if (suppressedReason === 'out_of_order') {
269
+ suppressedDiagnostic.messageTime = data[this.sortField]
270
+ suppressedDiagnostic.lastMessageTime = lastMessageTime
271
+ }
272
+ this.addDiagnosticLog('message_event_suppressed', this.getMessageDiagnosticData(data, suppressedDiagnostic))
234
273
  }
235
274
  }
236
275
  }
@@ -232,20 +232,21 @@ export default class ClientChatSession {
232
232
  })
233
233
  }
234
234
 
235
- _addGetSessionLog (title, data) {
235
+ _addGetSessionLog (event, data) {
236
236
  if (this.onGetSessionLog) {
237
237
  this.onGetSessionLog({
238
- group: 'client-chat-session:getSession',
239
- content: {
240
- title,
241
- data
242
- }
238
+ group: `diagnostic:${event}`,
239
+ content: Object.assign({ event }, data)
243
240
  })
244
241
  }
245
242
  }
246
243
 
247
244
  getSession (sessionId, serializeMethod) {
248
245
  if (this.sessionMap[sessionId]) {
246
+ this._addGetSessionLog('session_resolved', {
247
+ sessionId,
248
+ source: 'memory'
249
+ })
249
250
  return Promise.resolve({
250
251
  data: this.sessionMap[sessionId]
251
252
  })
@@ -257,6 +258,10 @@ export default class ClientChatSession {
257
258
  if (serializeMethod) {
258
259
  pollRequest.serializeMethods.push(serializeMethod)
259
260
  }
261
+ this._addGetSessionLog('session_poll_joined', {
262
+ sessionId,
263
+ mergedCount: pollRequest.serializeMethods.length
264
+ })
260
265
  return pollRequest.ps
261
266
  }
262
267
 
@@ -283,7 +288,7 @@ export default class ClientChatSession {
283
288
  pollRequest.lastRequestError = null
284
289
  pollRequest.startedAt = Date.now()
285
290
  this.pollRequestMap[sessionId] = pollRequest
286
- this._addGetSessionLog('创建会话轮询', {
291
+ this._addGetSessionLog('session_poll_started', {
287
292
  sessionId,
288
293
  spanTime: GET_SESSION_POLL_SPAN_TIME,
289
294
  timeout: GET_SESSION_POLL_TIMEOUT
@@ -312,7 +317,7 @@ export default class ClientChatSession {
312
317
  unreadDelta: context.accountUnreadDelta
313
318
  })
314
319
  const wechatAccountId = rs.data.wechatAccountId
315
- this._addGetSessionLog('会话轮询合并完成', {
320
+ this._addGetSessionLog('session_poll_completed', {
316
321
  sessionId,
317
322
  requestCount: pollRequest.requestCount,
318
323
  emptyResponseCount: pollRequest.emptyResponseCount,
@@ -330,7 +335,7 @@ export default class ClientChatSession {
330
335
  })
331
336
  return rs
332
337
  }).catch((error) => {
333
- this._addGetSessionLog('会话轮询失败', {
338
+ this._addGetSessionLog('session_poll_failed', {
334
339
  sessionId,
335
340
  isTimeout: error === 'timeout',
336
341
  timeout: GET_SESSION_POLL_TIMEOUT,
@@ -930,6 +935,16 @@ export default class ClientChatSession {
930
935
  }
931
936
  }
932
937
  if (changeProps && Object.keys(changeProps).length) {
938
+ if (changeProps.unreadMsgCount) {
939
+ this._addGetSessionLog('session_unread_changed', {
940
+ sessionId,
941
+ wechatAccountId: session.wechatAccountId,
942
+ source: 'updateSession',
943
+ before: changeProps.unreadMsgCount.before,
944
+ after: changeProps.unreadMsgCount.after,
945
+ delta: (changeProps.unreadMsgCount.after || 0) - (changeProps.unreadMsgCount.before || 0)
946
+ })
947
+ }
933
948
  this.onUpdateSession && this.onUpdateSession({
934
949
  session,
935
950
  changeProps,
@@ -949,10 +964,30 @@ export default class ClientChatSession {
949
964
  if (!session) {
950
965
  return
951
966
  }
967
+ const oldUnreadMsgCount = session.unreadMsgCount || 0
968
+ this._addGetSessionLog('session_read_requested', {
969
+ sessionId,
970
+ wechatAccountId: session.wechatAccountId,
971
+ oldUnreadMsgCount
972
+ })
952
973
  return this.updateSessionRead({
953
974
  conversationId: sessionId
954
975
  }).then(() => {
955
976
  this.markSessionRead(sessionId)
977
+ this._addGetSessionLog('session_read_applied', {
978
+ sessionId,
979
+ wechatAccountId: session.wechatAccountId,
980
+ oldUnreadMsgCount,
981
+ unreadMsgCount: 0
982
+ })
983
+ }).catch(error => {
984
+ this._addGetSessionLog('session_read_failed', {
985
+ sessionId,
986
+ wechatAccountId: session.wechatAccountId,
987
+ oldUnreadMsgCount,
988
+ error: error && (error.message || error.errMsg || error.toString && error.toString()) || error
989
+ })
990
+ return Promise.reject(error)
956
991
  })
957
992
  }
958
993
 
@@ -1143,6 +1178,13 @@ export default class ClientChatSession {
1143
1178
  lastUpdateTime: null // 最后更新时间
1144
1179
  })
1145
1180
  this.data.loading = true
1181
+ const startedAt = Date.now()
1182
+ this._addGetSessionLog('session_list_requested', {
1183
+ mode: 'reload',
1184
+ wechatAccountId: params.wechatAccountId,
1185
+ lastUpdateTime: params.lastUpdateTime,
1186
+ size: params.size
1187
+ })
1146
1188
  const ps1 = this.loadSessionData(params, {
1147
1189
  lastSession: null,
1148
1190
  lastUpdateSession: null,
@@ -1150,7 +1192,7 @@ export default class ClientChatSession {
1150
1192
  })
1151
1193
  ps1.then((rs) => {
1152
1194
  this.setSessionData(rs.data, params.wechatAccountId || ALL_WECHAT_ACCOUNT_ID)
1153
- })
1195
+ }, () => {})
1154
1196
  if (this.cancelLoadDataRequest) {
1155
1197
  this.cancelLoadDataRequest()
1156
1198
  }
@@ -1159,9 +1201,21 @@ export default class ClientChatSession {
1159
1201
  }
1160
1202
  return Promise.all([ps1]).then((rs) => {
1161
1203
  this.data.loading = false
1204
+ this._addGetSessionLog('session_list_applied', {
1205
+ mode: 'reload',
1206
+ wechatAccountId: params.wechatAccountId,
1207
+ count: rs[0] && rs[0].data && rs[0].data.length || 0,
1208
+ duration: Date.now() - startedAt
1209
+ })
1162
1210
  return rs[0]
1163
1211
  }, err => {
1164
1212
  this.data.loading = false
1213
+ this._addGetSessionLog('session_list_failed', {
1214
+ mode: 'reload',
1215
+ wechatAccountId: params.wechatAccountId,
1216
+ duration: Date.now() - startedAt,
1217
+ error: err && (err.message || err.errMsg || err.toString && err.toString()) || err
1218
+ })
1165
1219
  return Promise.reject(err)
1166
1220
  })
1167
1221
  }
@@ -1173,6 +1227,13 @@ export default class ClientChatSession {
1173
1227
  size: 20 // 本次要获取的会话条数
1174
1228
  }, params)
1175
1229
  this.data.loading = true
1230
+ const startedAt = Date.now()
1231
+ this._addGetSessionLog('session_list_requested', {
1232
+ mode: 'load_more',
1233
+ wechatAccountId: params.wechatAccountId,
1234
+ lastUpdateTime: params.lastUpdateTime,
1235
+ size: params.size
1236
+ })
1176
1237
  let lastSession = this._getLastSessionBySessionGroup(params.wechatAccountId || ALL_WECHAT_ACCOUNT_ID)
1177
1238
  const ps1 = this.loadSessionData(params, {
1178
1239
  lastSession,
@@ -1190,9 +1251,21 @@ export default class ClientChatSession {
1190
1251
  }
1191
1252
  return Promise.all([ps1]).then((rs) => {
1192
1253
  this.data.loading = false
1254
+ this._addGetSessionLog('session_list_applied', {
1255
+ mode: 'load_more',
1256
+ wechatAccountId: params.wechatAccountId,
1257
+ count: rs[0] && rs[0].data && rs[0].data.length || 0,
1258
+ duration: Date.now() - startedAt
1259
+ })
1193
1260
  return rs[0]
1194
1261
  }, err => {
1195
1262
  this.data.loading = false
1263
+ this._addGetSessionLog('session_list_failed', {
1264
+ mode: 'load_more',
1265
+ wechatAccountId: params.wechatAccountId,
1266
+ duration: Date.now() - startedAt,
1267
+ error: err && (err.message || err.errMsg || err.toString && err.toString()) || err
1268
+ })
1196
1269
  return Promise.reject(err)
1197
1270
  })
1198
1271
  }
@@ -7,9 +7,9 @@ function cloneLogData (data) {
7
7
  ;['content', 'contBody'].forEach(field => {
8
8
  if (typeof cloneData[field] === 'string') {
9
9
  const contentLength = cloneData[field].length
10
- cloneData[field] = cloneData[field].substr(0, LOG_CONTENT_MAX_LENGTH)
11
- cloneData[`${field}Length`] = contentLength
12
- cloneData[`${field}Truncated`] = contentLength > LOG_CONTENT_MAX_LENGTH
10
+ if (contentLength > LOG_CONTENT_MAX_LENGTH) {
11
+ cloneData[field] = `${cloneData[field].substr(0, LOG_CONTENT_MAX_LENGTH)}...+${contentLength - LOG_CONTENT_MAX_LENGTH}`
12
+ }
13
13
  } else if (cloneData[field] !== undefined) {
14
14
  cloneData[`${field}Type`] = typeof cloneData[field]
15
15
  delete cloneData[field]
@@ -20,6 +20,29 @@ function cloneLogData (data) {
20
20
  return cloneData
21
21
  }
22
22
 
23
+ function getMessageDiagnosticData (data) {
24
+ const message = data && (data.friendMessage || data.chatroomMessage) || {}
25
+ return {
26
+ messageId: message.id || data && data.id,
27
+ msgSvrId: message.msgSvrId || data && data.msgSvrId
28
+ }
29
+ }
30
+
31
+ export function getSocketMessageLogData (data) {
32
+ const cloneData = Object.assign({}, data)
33
+ ;['friendMessage', 'chatroomMessage'].forEach(field => {
34
+ if (!cloneData[field] || typeof cloneData[field] !== 'object') {
35
+ return
36
+ }
37
+ cloneData[field] = Object.assign({}, cloneData[field])
38
+ delete cloneData[field].accessToken
39
+ delete cloneData[field].token
40
+ })
41
+ delete cloneData.accessToken
42
+ delete cloneData.token
43
+ return cloneData
44
+ }
45
+
23
46
  export default class Websocket {
24
47
  get connectStatus () {
25
48
  return this.socket.connectStatus
@@ -77,32 +100,31 @@ export default class Websocket {
77
100
  }
78
101
  })
79
102
  this.socket.event.on('onCmdNewMessage', (evt) => {
80
- if (!options.checkSocketEventNotifyMethod || options.checkSocketEventNotifyMethod(evt) !== false) {
103
+ const messageLogData = getSocketMessageLogData(evt && evt.data)
104
+ if (options.checkSocketEventNotifyMethod && options.checkSocketEventNotifyMethod(evt) === false) {
105
+ this.addLog({
106
+ group: 'diagnostic:message_received_suppressed',
107
+ content: Object.assign({
108
+ event: 'message_received_suppressed',
109
+ reason: 'notify_filter',
110
+ data: messageLogData
111
+ }, getMessageDiagnosticData(evt && evt.data))
112
+ })
113
+ } else {
81
114
  let processingError
82
115
  try {
83
116
  options.onCmdNewMessage(evt)
84
117
  } catch (error) {
85
118
  processingError = error
86
119
  }
87
- const cloneData = cloneLogData(evt.data)
88
- if (evt.data.friendMessage) {
89
- cloneData.friendMessage = cloneLogData(evt.data.friendMessage)
90
- }
91
- if (evt.data.chatroomMessage) {
92
- cloneData.chatroomMessage = cloneLogData(evt.data.chatroomMessage)
93
- }
94
120
  this.addLog({
95
- group: 'client-chat-socket:receiveMessage',
96
- content: {
97
- title: 'socket收到消息',
98
- data: cloneData,
99
- processing: processingError ? {
100
- result: 'failed',
101
- errorType: processingError && (processingError.name || processingError.code) || typeof processingError
102
- } : {
103
- result: 'success'
104
- }
105
- }
121
+ group: 'diagnostic:message_received',
122
+ content: Object.assign({
123
+ event: 'message_received',
124
+ result: processingError ? 'failed' : 'success',
125
+ errorType: processingError && (processingError.name || processingError.code) || undefined,
126
+ data: messageLogData
127
+ }, getMessageDiagnosticData(evt && evt.data))
106
128
  })
107
129
  if (processingError) {
108
130
  throw processingError
@@ -261,6 +283,10 @@ export default class Websocket {
261
283
  return this.socket.exportLogData()
262
284
  }
263
285
 
286
+ exportLogFiles () {
287
+ return this.socket.exportLogFiles()
288
+ }
289
+
264
290
  checkAndSync () {
265
291
  return this.socket.checkAndSync()
266
292
  }
@@ -418,6 +418,7 @@ class ClientChat {
418
418
  groupField: 'wechatFriendId',
419
419
  sortField: 'wechatTime',
420
420
  clientChat: this,
421
+ getSessionIdMethod: data => createSessionId(options.getLoginAccountIdMethod ? options.getLoginAccountIdMethod() : data && data.accountId, data && data.wechatFriendId),
421
422
  checkMessageSendResultMethod: options.checkMessageSendResultMethod,
422
423
  loadLossMessageDataMethod: options.loadLossFriendMessageDataMethod,
423
424
  onAddMessageSuccess: ({ data, isBeforeLastMessage }) => {
@@ -541,6 +542,7 @@ class ClientChat {
541
542
  groupField: 'wechatChatroomId',
542
543
  sortField: 'wechatTime',
543
544
  clientChat: this,
545
+ getSessionIdMethod: data => createSessionId(options.getLoginAccountIdMethod ? options.getLoginAccountIdMethod() : data && data.accountId, data && data.wechatChatroomId),
544
546
  checkMessageSendResultMethod: options.checkMessageSendResultMethod,
545
547
  loadLossMessageDataMethod: options.loadLossRoomMessageDataMethod,
546
548
  onAddMessageSuccess: ({ data, isBeforeLastMessage }) => {
@@ -846,6 +846,10 @@ export default class Socket {
846
846
  return this.log.exportLogData()
847
847
  }
848
848
 
849
+ exportLogFiles () {
850
+ return this.log.exportLogFiles()
851
+ }
852
+
849
853
  checkAndSync () {
850
854
  return this.log.checkAndSync()
851
855
  }
@@ -0,0 +1,13 @@
1
+ export const INDEXED_DB_VERSION = 2
2
+ export const INDEXED_DB_STORE_NAME = 'logs'
3
+ export const INDEXED_DB_META_STORE_NAME = 'meta'
4
+ export const INDEXED_DB_ORDER_INDEX_NAME = 'order'
5
+ export const INDEXED_DB_STATS_KEY = 'stats'
6
+
7
+ export const DEFAULT_INDEXED_DB_MAX_SIZE = 200 * 1024 * 1024
8
+ export const DEFAULT_FLUSH_INTERVAL = 300
9
+ export const DEFAULT_FLUSH_THRESHOLD = 50
10
+ export const DEFAULT_FLUSH_BATCH_SIZE = 500
11
+ export const DEFAULT_MAX_PENDING_COUNT = 2000
12
+ export const DEFAULT_MAX_PENDING_BYTES = 2 * 1024 * 1024
13
+
@@ -0,0 +1,88 @@
1
+ import { safeStringify, getByteSize } from './serialize'
2
+
3
+ export const ERROR_LOG_GROUPS = [
4
+ 'diagnostic:runtime_error',
5
+ 'diagnostic:runtime_error_suppressed'
6
+ ]
7
+
8
+ export function recordPayload (record) {
9
+ if (record && typeof record.payload === 'string') {
10
+ return record.payload
11
+ }
12
+ return safeStringify(record && record.log) || '{}'
13
+ }
14
+
15
+ export function recordDay (record, payload) {
16
+ if (record && record.day) {
17
+ return record.day
18
+ }
19
+ try {
20
+ const log = record && record.log ? record.log : JSON.parse(payload)
21
+ const value = log && (log.timestamp || log.createTime)
22
+ if (typeof value === 'number') {
23
+ const date = new Date(value)
24
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
25
+ }
26
+ if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}/.test(value)) {
27
+ return value.slice(0, 10)
28
+ }
29
+ } catch (error) {}
30
+ return 'unknown-date'
31
+ }
32
+
33
+ function isErrorLogRecord (record, payload) {
34
+ const group = record && (
35
+ record.group ||
36
+ (record.log && record.log.group)
37
+ )
38
+ if (ERROR_LOG_GROUPS.indexOf(group) >= 0) {
39
+ return true
40
+ }
41
+ if (typeof payload !== 'string') {
42
+ return false
43
+ }
44
+ return ERROR_LOG_GROUPS.some(errorGroup => (
45
+ payload.indexOf(`"group":"${errorGroup}"`) >= 0
46
+ ))
47
+ }
48
+
49
+ export function createExportFiles (records, options = {}) {
50
+ const separateErrorLogs = !!options.separateErrorLogs
51
+ const groups = Object.create(null)
52
+ ;(records || []).forEach(record => {
53
+ const payload = recordPayload(record)
54
+ const day = recordDay(record, payload)
55
+ const type = separateErrorLogs && isErrorLogRecord(record, payload) ? 'error' : 'operation'
56
+ const key = `${type}:${day}`
57
+ if (!groups[key]) {
58
+ groups[key] = { day, type, payloads: [] }
59
+ }
60
+ groups[key].payloads.push(payload)
61
+ })
62
+ return Object.keys(groups).sort((left, right) => {
63
+ const leftGroup = groups[left]
64
+ const rightGroup = groups[right]
65
+ return leftGroup.day.localeCompare(rightGroup.day) || leftGroup.type.localeCompare(rightGroup.type)
66
+ }).map(key => {
67
+ const group = groups[key]
68
+ const payloads = group.payloads
69
+ const parts = ['[']
70
+ payloads.forEach((payload, index) => {
71
+ if (index) {
72
+ parts.push(',')
73
+ }
74
+ parts.push(payload)
75
+ })
76
+ parts.push(']')
77
+ const content = typeof Blob !== 'undefined'
78
+ ? new Blob(parts, { type: 'application/json' })
79
+ : parts.join('')
80
+ return {
81
+ day: group.day,
82
+ type: group.type,
83
+ count: payloads.length,
84
+ size: typeof content === 'string' ? getByteSize(content) : content.size,
85
+ content
86
+ }
87
+ })
88
+ }