@aochuang/client-sdk 1.0.400 → 1.0.401

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.
@@ -1,5 +1,48 @@
1
1
  import Socket from '../../socket'
2
2
 
3
+ const LOG_CONTENT_MAX_LENGTH = 100
4
+
5
+ function cloneLogData (data) {
6
+ const cloneData = Object.assign({}, data)
7
+ ;['content', 'contBody'].forEach(field => {
8
+ if (typeof cloneData[field] === 'string') {
9
+ const contentLength = cloneData[field].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
+ } else if (cloneData[field] !== undefined) {
14
+ cloneData[`${field}Type`] = typeof cloneData[field]
15
+ delete cloneData[field]
16
+ }
17
+ })
18
+ delete cloneData.accessToken
19
+ delete cloneData.token
20
+ return cloneData
21
+ }
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
+
3
46
  export default class Websocket {
4
47
  get connectStatus () {
5
48
  return this.socket.connectStatus
@@ -12,6 +55,7 @@ export default class Websocket {
12
55
  constructor (options) {
13
56
  options = Object.assign({
14
57
  socket: null,
58
+ log: null,
15
59
  // 检查socket事件通知方法,有些场景不需要后端推送的命令执行,比如管理后台
16
60
  checkSocketEventNotifyMethod: null,
17
61
  // 执行回调事件前的方法
@@ -40,7 +84,8 @@ export default class Websocket {
40
84
  throw new Error('socket实例不能为空')
41
85
  }
42
86
  this.socket = options.socket
43
- this.socket.log.onBeforeAdd(({ data }) => {
87
+ this.log = options.log || this.socket.log || null
88
+ this.log && this.log.onBeforeAdd && this.log.onBeforeAdd(({ data }) => {
44
89
  // 收消息需要拦截一些,因为下面有了
45
90
  if (data && ['socket:sendMessage'].includes(data.group)) {
46
91
  return false
@@ -55,23 +100,35 @@ export default class Websocket {
55
100
  }
56
101
  })
57
102
  this.socket.event.on('onCmdNewMessage', (evt) => {
58
- if (!options.checkSocketEventNotifyMethod || options.checkSocketEventNotifyMethod(evt) !== false) {
59
- const cloneMsg = Object.assign({}, evt.data)
60
- const newMsg = Object.assign({}, cloneMsg.chatroomMessage || cloneMsg.friendMessage)
61
- if (typeof newMsg.content === 'string') {
62
- newMsg.content = newMsg.content.substr(0, 100) // 只保留前100个字符,怕数据太多了
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 {
114
+ let processingError
115
+ try {
116
+ options.onCmdNewMessage(evt)
117
+ } catch (error) {
118
+ processingError = error
63
119
  }
64
- delete cloneMsg.chatroomMessage
65
- delete cloneMsg.friendMessage
66
- cloneMsg.message = newMsg
67
- this.socket.logEnable && this.socket.log.addLog({
68
- group: 'client-chat-socket:receiveMessage',
69
- content: {
70
- title: 'socket收到消息',
71
- data: cloneMsg
72
- }
120
+ this.addLog({
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))
73
128
  })
74
- options.onCmdNewMessage(evt)
129
+ if (processingError) {
130
+ throw processingError
131
+ }
75
132
  }
76
133
  })
77
134
  this.socket.event.on('onCmdSendMessageResult', (evt) => {
@@ -134,14 +191,11 @@ export default class Websocket {
134
191
  options.onHeartbeatSuccess && options.onHeartbeatSuccess(evt)
135
192
  })
136
193
  this.socket.event.on('onSendMessage', (evt) => {
137
- const cloneData = Object.assign({}, evt.data)
138
- if (cloneData && typeof cloneData.content === 'string') {
139
- cloneData.content = cloneData.content.substr(0, 100)
140
- }
194
+ const cloneData = cloneLogData(evt.data)
141
195
  if (evt.data.cmdType === 'CmdRequestWechatAccountsAliveStatus') {
142
196
  delete cloneData.wechatAccountIds
143
197
  }
144
- this.socket.logEnable && this.socket.log.addLog({
198
+ this.addLog({
145
199
  group: 'client-chat-socket:sendMessage',
146
200
  content: {
147
201
  title: '发送消息',
@@ -222,13 +276,17 @@ export default class Websocket {
222
276
  }
223
277
 
224
278
  addLog (data) {
225
- this.socket.logEnable && this.socket.log.addLog(data)
279
+ this.socket.logEnable && this.log && this.log.addLog(data)
226
280
  }
227
281
 
228
282
  exportLogData () {
229
283
  return this.socket.exportLogData()
230
284
  }
231
285
 
286
+ exportLogFiles () {
287
+ return this.socket.exportLogFiles()
288
+ }
289
+
232
290
  checkAndSync () {
233
291
  return this.socket.checkAndSync()
234
292
  }
@@ -55,6 +55,7 @@ class ClientChat {
55
55
  constructor (options) {
56
56
  options = Object.assign({
57
57
  socket: null,
58
+ log: null,
58
59
  checkSocketEventNotifyMethod: null,
59
60
  getLoginUserIdMethod: null,
60
61
  getLoginUserTokenMethod: null,
@@ -101,6 +102,7 @@ class ClientChat {
101
102
  if (!options.loadRoomMessageDataMethod) {
102
103
  throw new Error('loadRoomMessageDataMethod不能为空')
103
104
  }
105
+ this.log = options.log || (options.socket && options.socket.log) || null
104
106
  this.onOverwriteFriendInfoChange = options.onOverwriteFriendInfoChange
105
107
  this.shouldMarkCurrentSessionReadMethod = options.shouldMarkCurrentSessionReadMethod
106
108
  this.event = new Event({
@@ -416,6 +418,7 @@ class ClientChat {
416
418
  groupField: 'wechatFriendId',
417
419
  sortField: 'wechatTime',
418
420
  clientChat: this,
421
+ getSessionIdMethod: data => createSessionId(options.getLoginAccountIdMethod ? options.getLoginAccountIdMethod() : data && data.accountId, data && data.wechatFriendId),
419
422
  checkMessageSendResultMethod: options.checkMessageSendResultMethod,
420
423
  loadLossMessageDataMethod: options.loadLossFriendMessageDataMethod,
421
424
  onAddMessageSuccess: ({ data, isBeforeLastMessage }) => {
@@ -539,6 +542,7 @@ class ClientChat {
539
542
  groupField: 'wechatChatroomId',
540
543
  sortField: 'wechatTime',
541
544
  clientChat: this,
545
+ getSessionIdMethod: data => createSessionId(options.getLoginAccountIdMethod ? options.getLoginAccountIdMethod() : data && data.accountId, data && data.wechatChatroomId),
542
546
  checkMessageSendResultMethod: options.checkMessageSendResultMethod,
543
547
  loadLossMessageDataMethod: options.loadLossRoomMessageDataMethod,
544
548
  onAddMessageSuccess: ({ data, isBeforeLastMessage }) => {
@@ -803,6 +807,7 @@ class ClientChat {
803
807
  })
804
808
  this.socket = new ClientChatSocket({
805
809
  socket: options.socket,
810
+ log: this.log,
806
811
  getLoginUserIdMethod: options.getLoginUserIdMethod,
807
812
  getLoginUserTokenMethod: options.getLoginUserTokenMethod,
808
813
  checkSocketEventNotifyMethod: options.checkSocketEventNotifyMethod,
@@ -1134,22 +1139,65 @@ class ClientChat {
1134
1139
 
1135
1140
  },
1136
1141
  onSocketOpen: () => {
1137
- const ps = []
1138
- if (this.friendMessage.lastReceiveMessageTime) {
1139
- ps.push(this.friendMessage.loadLossMessageData())
1140
- }
1141
- if (this.roomMessage.lastReceiveMessageTime) {
1142
- ps.push(this.roomMessage.loadLossMessageData())
1142
+ const reconnectTime = Date.now()
1143
+ const syncTasks = []
1144
+ const syncLossMessages = (type, messageInstance) => {
1145
+ const watermarkBefore = messageInstance.lastReceiveMessageTime
1146
+ if (!watermarkBefore) {
1147
+ messageInstance.setLastReceiveMessageTime(reconnectTime)
1148
+ this.socket.addLog({
1149
+ group: 'diagnostic:loss_sync_result',
1150
+ content: {
1151
+ event: 'loss_sync_result',
1152
+ type,
1153
+ result: 'initialized',
1154
+ watermarkBefore,
1155
+ watermarkAfter: messageInstance.lastReceiveMessageTime
1156
+ }
1157
+ })
1158
+ return
1159
+ }
1160
+ const startedAt = Date.now()
1161
+ const task = messageInstance.loadLossMessageData().then(result => {
1162
+ messageInstance.setLastReceiveMessageTime(reconnectTime)
1163
+ this.socket.addLog({
1164
+ group: 'diagnostic:loss_sync_result',
1165
+ content: Object.assign({
1166
+ event: 'loss_sync_result',
1167
+ type,
1168
+ result: 'success',
1169
+ watermarkBefore,
1170
+ watermarkAfter: messageInstance.lastReceiveMessageTime,
1171
+ durationMs: Date.now() - startedAt
1172
+ }, result)
1173
+ })
1174
+ return true
1175
+ }, error => {
1176
+ this.socket.addLog({
1177
+ group: 'diagnostic:loss_sync_result',
1178
+ content: {
1179
+ event: 'loss_sync_result',
1180
+ type,
1181
+ result: 'failed',
1182
+ watermarkBefore,
1183
+ watermarkAfter: messageInstance.lastReceiveMessageTime,
1184
+ durationMs: Date.now() - startedAt,
1185
+ errorType: error && (error.name || error.code) || typeof error
1186
+ }
1187
+ })
1188
+ return false
1189
+ })
1190
+ syncTasks.push(task)
1143
1191
  }
1144
- Promise.all(ps).finally(() => {
1145
- this.friendMessage.setLastReceiveMessageTime(Date.now())
1146
- this.roomMessage.setLastReceiveMessageTime(Date.now())
1192
+ syncLossMessages('friend', this.friendMessage)
1193
+ syncLossMessages('room', this.roomMessage)
1194
+ Promise.all(syncTasks).then(() => {
1147
1195
  // 断线期间本地增量可能和服务端产生偏差(其他端已读、消息延迟等),重连后以服务端为准全量校准一次
1148
- if (ps.length) {
1196
+ if (syncTasks.length) {
1149
1197
  this.account.refreshAllAccountUnreadMesageNum()
1150
1198
  }
1151
1199
  })
1152
- },
1200
+ },
1153
1201
  onSocketClose: (evt) => {
1154
1202
  },
1155
1203
  onSocketKickOut: () => {
@@ -25,6 +25,8 @@ export default class Socket {
25
25
 
26
26
  maxReconnectInterval = 60000
27
27
 
28
+ connectionGeneration = 0
29
+
28
30
  data = Vue.observable({
29
31
  connectIpChange: false, // 连接设备是否变化,如果变化需要提示用户退出重新登录
30
32
  connectMessage: null,
@@ -47,6 +49,7 @@ export default class Socket {
47
49
  url: null,
48
50
  client: null,
49
51
  logEnable: false,
52
+ log: null,
50
53
  logName: 'socket',
51
54
  logMaxSize: 3 * 1024 * 1024, // 非网页版本最多记3M日志
52
55
  socketAdapter: null, // 支持从外面传一个socket构造函数,但是要实现socket标准的使用方式
@@ -73,7 +76,7 @@ export default class Socket {
73
76
  this.logEnable = !!options.logEnable
74
77
  this.url = options.url
75
78
  this.event = new Event()
76
- this.log = new Log({
79
+ this.log = options.log || new Log({
77
80
  maxSize: options.logMaxSize, // 非网页版本日志大小限制
78
81
  name: options.logName || 'socket'
79
82
  })
@@ -105,6 +108,17 @@ export default class Socket {
105
108
  return !!socket && socket === this._ws
106
109
  }
107
110
 
111
+ _addSocketStateLog (event, data = {}) {
112
+ this.logEnable && this.log.addLog({
113
+ group: 'diagnostic:socket_state',
114
+ content: Object.assign({
115
+ event,
116
+ connectionGeneration: this.connectionGeneration,
117
+ connectStatus: this.connectStatus
118
+ }, data)
119
+ })
120
+ }
121
+
108
122
  _handleReconnectLimitExceeded () {
109
123
  const err = new Error('socket重连次数已超过上限')
110
124
  clearTimeout(this._reconnectTimer)
@@ -141,14 +155,20 @@ export default class Socket {
141
155
  this.readyPromise = createPromise()
142
156
  this.data.connectUrl = this.url + `?client=${this.client}&accountId=${this.accountId}&accessToken=${this.token}`
143
157
  let socket = null
158
+ this.connectionGeneration++
144
159
  this.data.connectStatus = CONNECT_STATUS.Connecting
145
160
  this.logEnable && this.log.addLog({
146
161
  group: 'socket:connect',
147
162
  content: {
148
163
  title: '开始连接',
149
- socketUrl: this.data.connectUrl
164
+ client: this.client,
165
+ accountId: this.accountId,
166
+ connectionGeneration: this.connectionGeneration
150
167
  }
151
168
  })
169
+ this._addSocketStateLog('connect_start', {
170
+ to: CONNECT_STATUS.Connecting
171
+ })
152
172
  this._ws = null
153
173
  if (this.socketAdapter) {
154
174
  socket = new this.socketAdapter(this.data.connectUrl)
@@ -275,6 +295,9 @@ export default class Socket {
275
295
  title: 'socket连接中'
276
296
  }
277
297
  })
298
+ this._addSocketStateLog('native_open', {
299
+ to: CONNECT_STATUS.Success
300
+ })
278
301
  this.sendMessage(params).then(() => {
279
302
  if (socket && !this._isCurrentSocket(socket)) {
280
303
  return
@@ -286,6 +309,9 @@ export default class Socket {
286
309
  }
287
310
  })
288
311
  this._startHeartbeat() // 注释掉,因为现在心跳的命令改了,用账号在线状态控制,减少命令发送频率
312
+ this._addSocketStateLog('signin_success', {
313
+ result: 'success'
314
+ })
289
315
  successFn && successFn()
290
316
  this.event.emit('onOpen')
291
317
  }, (err) => {
@@ -293,6 +319,13 @@ export default class Socket {
293
319
  return
294
320
  }
295
321
  errorFn && errorFn(err)
322
+ this.data.connectStatus = CONNECT_STATUS.Error
323
+ this._addSocketStateLog('signin_failed', {
324
+ result: 'failed',
325
+ errorType: err && (err.name || err.code) || typeof err,
326
+ willReconnect: true
327
+ })
328
+ this.reconnect().catch(() => {})
296
329
  })
297
330
  }
298
331
 
@@ -324,11 +357,15 @@ export default class Socket {
324
357
  reason: evt.reason,
325
358
  }
326
359
  })
360
+ this._addSocketStateLog('socket_close', {
361
+ from: prevConnectStatus,
362
+ to: CONNECT_STATUS.Close,
363
+ closeCode: evt.code,
364
+ reason: evt.reason,
365
+ willReconnect: !evt.reason || evt.reason.indexOf('(手动关闭)') < 0
366
+ })
327
367
  if (!evt.reason || evt.reason.indexOf('(手动关闭)') < 0) {
328
- if (prevConnectStatus === CONNECT_STATUS.Connecting) {
329
- return
330
- }
331
- this.reconnect()
368
+ this.reconnect().catch(() => {})
332
369
  }
333
370
  this.event.emit('onClose', {
334
371
  code: evt.code,
@@ -355,7 +392,11 @@ export default class Socket {
355
392
  if (this.readyPromise && typeof this.readyPromise.reject === 'function') {
356
393
  this.readyPromise.reject(new Error('socket连接错误'))
357
394
  }
358
- this.reconnect()
395
+ this._addSocketStateLog('socket_error', {
396
+ to: CONNECT_STATUS.Error,
397
+ willReconnect: true
398
+ })
399
+ this.reconnect().catch(() => {})
359
400
  }
360
401
 
361
402
  mockSocketMessage (evt) {
@@ -445,6 +486,10 @@ export default class Socket {
445
486
  // 指数退避 + 随机抖动
446
487
  const jitter = Math.random() * 500 * 2 - 500
447
488
  const actualInterval = Math.min(this.reconnectInterval + jitter, this.maxReconnectInterval)
489
+ this._addSocketStateLog('reconnect_scheduled', {
490
+ retryCount: this.reconnectCount,
491
+ delayMs: Math.max(0, Math.round(actualInterval))
492
+ })
448
493
  // 先翻倍再等待,避免定时器被取消导致倍数丢失
449
494
  this.reconnectInterval = Math.min(this.reconnectInterval * 2, this.maxReconnectInterval)
450
495
  clearTimeout(this._reconnectTimer)
@@ -801,6 +846,10 @@ export default class Socket {
801
846
  return this.log.exportLogData()
802
847
  }
803
848
 
849
+ exportLogFiles () {
850
+ return this.log.exportLogFiles()
851
+ }
852
+
804
853
  checkAndSync () {
805
854
  return this.log.checkAndSync()
806
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
+ }