@arms/rum-core 0.1.6 → 0.1.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.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * 资源清理组:统一管理多个清理函数的生命周期
3
+ *
4
+ * 用于收敛采集器中常见的 cleanup 数组模式,
5
+ * 避免每个采集器重复实现 push + forEach 逻辑
6
+ */
7
+ export function createDisposableGroup() {
8
+ var cleanups = [];
9
+ return {
10
+ /** 注册一个或多个清理函数 */add: function add() {
11
+ cleanups.push.apply(cleanups, arguments);
12
+ },
13
+ /** 执行所有清理函数并重置 */dispose: function dispose() {
14
+ cleanups.forEach(function (fn) {
15
+ return fn();
16
+ });
17
+ cleanups.length = 0;
18
+ }
19
+ };
20
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * 带 cancel 的 leading + trailing 节流函数
3
+ *
4
+ * - leading:连续调用时立即触发首次
5
+ * - trailing:保证最后一次在 wait 内补发
6
+ * - cancel:丢弃尾调用并重置节流窗口,防止跨 view 串数据
7
+ *
8
+ * @param fn 需要节流的函数
9
+ * @param wait 节流间隔(毫秒)
10
+ */
11
+ export declare function throttle(fn: () => void, wait: number): {
12
+ (): void;
13
+ cancel: () => void;
14
+ };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * 带 cancel 的 leading + trailing 节流函数
3
+ *
4
+ * - leading:连续调用时立即触发首次
5
+ * - trailing:保证最后一次在 wait 内补发
6
+ * - cancel:丢弃尾调用并重置节流窗口,防止跨 view 串数据
7
+ *
8
+ * @param fn 需要节流的函数
9
+ * @param wait 节流间隔(毫秒)
10
+ */
11
+ export function throttle(fn, wait) {
12
+ var lastInvoke = 0;
13
+ var timer = null;
14
+ var invoke = function invoke() {
15
+ lastInvoke = Date.now();
16
+ timer = null;
17
+ fn();
18
+ };
19
+ var wrapped = function wrapped() {
20
+ var remaining = wait - (Date.now() - lastInvoke);
21
+ if (remaining <= 0) {
22
+ if (timer) {
23
+ clearTimeout(timer);
24
+ timer = null;
25
+ }
26
+ invoke();
27
+ } else if (!timer) {
28
+ timer = setTimeout(invoke, remaining);
29
+ }
30
+ };
31
+ wrapped.cancel = function () {
32
+ if (timer) {
33
+ clearTimeout(timer);
34
+ timer = null;
35
+ }
36
+ // 重置 leading 窗口,让下次调用立刻触发,避免跨 view 共享上次的节流窗口
37
+ lastInvoke = 0;
38
+ };
39
+ return wrapped;
40
+ }
package/lib/index.d.ts CHANGED
@@ -19,5 +19,7 @@ export * from './utils/trace';
19
19
  export * from './utils/verify';
20
20
  export * from './utils/url';
21
21
  export * from './utils/events';
22
+ export * from './utils/throttle';
23
+ export * from './utils/disposable';
22
24
  export * from './monitor';
23
25
  export { Client, Context, Reporter, Shell };
package/lib/index.js CHANGED
@@ -135,6 +135,20 @@ Object.keys(_events).forEach(function (key) {
135
135
  if (key in exports && exports[key] === _events[key]) return;
136
136
  exports[key] = _events[key];
137
137
  });
138
+ var _throttle = require("./utils/throttle");
139
+ Object.keys(_throttle).forEach(function (key) {
140
+ if (key === "default" || key === "__esModule") return;
141
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
142
+ if (key in exports && exports[key] === _throttle[key]) return;
143
+ exports[key] = _throttle[key];
144
+ });
145
+ var _disposable = require("./utils/disposable");
146
+ Object.keys(_disposable).forEach(function (key) {
147
+ if (key === "default" || key === "__esModule") return;
148
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
149
+ if (key in exports && exports[key] === _disposable[key]) return;
150
+ exports[key] = _disposable[key];
151
+ });
138
152
  var _monitor = require("./monitor");
139
153
  Object.keys(_monitor).forEach(function (key) {
140
154
  if (key === "default" || key === "__esModule") return;
@@ -1,6 +1,6 @@
1
1
  import { IClient, IConfiguration, IContext, IRumSession } from '../types/client';
2
- import { IConfigManager } from "../types/config";
3
- import { RumEvent } from '../types/rum-event';
2
+ import { IConfigManager } from '../types/config';
3
+ import { RumEvent, SendEventOptions } from '../types/rum-event';
4
4
  import { IProcessor } from '../types/processor';
5
5
  import { ICollector } from '../types/collector';
6
6
  import { IReporter } from '../types/reporter';
@@ -12,7 +12,7 @@ declare class Client implements IClient {
12
12
  private reporter;
13
13
  private ctx;
14
14
  init(config: IConfiguration, rumSession?: IRumSession, configManager?: IConfigManager, monitorReporter?: IMonitorReporter): void;
15
- sendEvent: (payload: RumEvent) => void;
15
+ sendEvent: (payload: RumEvent, options?: SendEventOptions) => void;
16
16
  setContext(ctx: IContext): void;
17
17
  getContext(): IContext;
18
18
  useCollectors(collectors: ICollector[]): void;
@@ -19,8 +19,8 @@ var Client = /*#__PURE__*/function () {
19
19
  this.processors = void 0;
20
20
  this.reporter = void 0;
21
21
  this.ctx = void 0;
22
- this.sendEvent = function (payload) {
23
- _this.emitter.emit(_client.EventType.collect, payload);
22
+ this.sendEvent = function (payload, options) {
23
+ _this.emitter.emit(_client.EventType.collect, payload, options);
24
24
  };
25
25
  }
26
26
  var _proto = Client.prototype;
@@ -61,7 +61,7 @@ var Client = /*#__PURE__*/function () {
61
61
  });
62
62
 
63
63
  // collector 收集数据统一 push 到各匹配 processor
64
- this.emitter.on(_client.EventType.collect, function (payload) {
64
+ this.emitter.on(_client.EventType.collect, function (payload, options) {
65
65
  ctx.setRumEvent(payload);
66
66
  for (var _iterator = _createForOfIteratorHelperLoose(processors), _step; !(_step = _iterator()).done;) {
67
67
  var processor = _step.value;
@@ -73,12 +73,12 @@ var Client = /*#__PURE__*/function () {
73
73
  }
74
74
  if (processor.match(ctx)) {
75
75
  var res = processor.process(ctx);
76
- if (res) {
77
- ctx.setRumEvent(res);
78
- }
76
+ // 无论返回值是否为 falsy 都写回 context,
77
+ // 确保 processor 返回 null/undefined(丢弃事件)时能正确生效
78
+ ctx.setRumEvent(res);
79
79
  }
80
80
  }
81
- reporter.report(ctx);
81
+ reporter.report(ctx, options);
82
82
  });
83
83
  collectors.forEach(function (collector) {
84
84
  collector.setup(ctx, _this2.sendEvent);
@@ -1,23 +1,46 @@
1
1
  import { IContext } from '../types/client';
2
- import { RumEvent, IViewData, RumEventBundle } from '../types/rum-event';
2
+ import { RumEvent, IViewData, RumEventBundle, SendEventOptions } from '../types/rum-event';
3
+ /**
4
+ * 抽象上报器,负责事件排队、批量打包与发送。
5
+ *
6
+ * 上报模式(通过 SendEventOptions 控制):
7
+ * - 默认:事件进入队列,等待定时器或队列满后批量 flush
8
+ * - immediate:事件进入队列后立即 flush 整个队列
9
+ * - single:事件不进队列,独立打包立即上报
10
+ */
3
11
  export default abstract class Reporter {
4
12
  name: string;
5
- /**
6
- * 新上报事件优先检测队列是否超过 50 条,如果超过立即 report。
7
- * 如果没超过则检测 FlushTime 内有无新上报事件,如果有新事件,重置 timer,无则 report
8
- */
9
13
  protected eventQueue: RumEvent[];
10
14
  protected ctx: IContext;
11
15
  private timer;
12
16
  private _init;
13
17
  getReportCfg(): import("../types/client").IReportConfig;
14
- report(ctx: IContext): void;
18
+ /**
19
+ * 上报入口,根据 options 决定上报策略:
20
+ * - single: 当前事件独立打包立即发送,不影响队列
21
+ * - immediate: 当前事件入队后立即 flush 整个队列
22
+ * - 默认: 当前事件入队,等待定时器或队列满后批量 flush
23
+ */
24
+ report(ctx: IContext, options?: SendEventOptions): void;
25
+ /**
26
+ * 当前事件独立打包上报,不进入批量队列,不重置队列定时器
27
+ */
28
+ private flushSingleEvent;
15
29
  private pushToQueue;
16
30
  /**
17
31
  * eventQueue 提取最新 View 作为公共 View,event 中不同 View Event 保留 View id
18
32
  */
19
33
  protected flushEventQueue(): void;
20
- mergeEvent(ctx: IContext, events: RumEvent[], view: IViewData): void;
34
+ /**
35
+ * 按 session_id 分组事件并分别打包上报:
36
+ * - 当前 session 的事件统一打包
37
+ * - 非当前 session 的事件按各自 session_id 单独打包
38
+ */
39
+ protected dispatchEvents(ctx: IContext, events: RumEvent[], view: IViewData): void;
40
+ /**
41
+ * 构建 bundle 并发送请求
42
+ */
43
+ private buildAndSend;
21
44
  private tryRequest;
22
45
  /**
23
46
  * 接口请求由各平台 sdk reporter 实现
@@ -15,13 +15,18 @@ var _url = require("../utils/url");
15
15
  var FLUSH_TIME = 3000;
16
16
  var MAX_EVENT_COUNT = 20;
17
17
  var attrs = ['app', 'user', 'device', 'os', 'geo', 'isp', 'net', 'properties'];
18
+
19
+ /**
20
+ * 抽象上报器,负责事件排队、批量打包与发送。
21
+ *
22
+ * 上报模式(通过 SendEventOptions 控制):
23
+ * - 默认:事件进入队列,等待定时器或队列满后批量 flush
24
+ * - immediate:事件进入队列后立即 flush 整个队列
25
+ * - single:事件不进队列,独立打包立即上报
26
+ */
18
27
  var Reporter = exports["default"] = /*#__PURE__*/function () {
19
28
  function Reporter() {
20
29
  this.name = 'reporter';
21
- /**
22
- * 新上报事件优先检测队列是否超过 50 条,如果超过立即 report。
23
- * 如果没超过则检测 FlushTime 内有无新上报事件,如果有新事件,重置 timer,无则 report
24
- */
25
30
  this.eventQueue = [];
26
31
  this.ctx = void 0;
27
32
  this.timer = void 0;
@@ -40,30 +45,62 @@ var Reporter = exports["default"] = /*#__PURE__*/function () {
40
45
  cfg.maxEventCount = MAX_EVENT_COUNT;
41
46
  }
42
47
  return cfg;
43
- };
44
- _proto.report = function report(ctx) {
48
+ }
49
+
50
+ /**
51
+ * 上报入口,根据 options 决定上报策略:
52
+ * - single: 当前事件独立打包立即发送,不影响队列
53
+ * - immediate: 当前事件入队后立即 flush 整个队列
54
+ * - 默认: 当前事件入队,等待定时器或队列满后批量 flush
55
+ */;
56
+ _proto.report = function report(ctx, options) {
45
57
  var _this = this;
46
58
  this.ctx = ctx;
47
59
  if (!this._init) {
48
60
  this.init(ctx);
49
61
  this._init = true;
50
62
  }
63
+
64
+ // single 优先级最高:当前事件单独上报,不影响队列
65
+ if (options && options.single) {
66
+ this.flushSingleEvent(ctx);
67
+ return;
68
+ }
51
69
  clearTimeout(this.timer);
52
70
  this.pushToQueue();
53
71
  var reportConfig = this.getReportCfg();
54
- // 超过 MaxCount 直接 flush,否则延迟发送
55
- if (this.eventQueue.length >= reportConfig.maxEventCount) {
72
+ if (options && options.immediate || this.eventQueue.length >= reportConfig.maxEventCount) {
56
73
  this.flushEventQueue();
57
74
  } else {
58
75
  this.timer = setTimeout(function () {
59
76
  _this.flushEventQueue();
60
77
  }, reportConfig.flushTime);
61
78
  }
79
+ }
80
+
81
+ /**
82
+ * 当前事件独立打包上报,不进入批量队列,不重置队列定时器
83
+ */;
84
+ _proto.flushSingleEvent = function flushSingleEvent(ctx) {
85
+ var _event$view;
86
+ var session = ctx.session;
87
+ var sampled = session ? session.getSampled() : true;
88
+ if (!sampled) return;
89
+ var event = ctx.getRumEvent();
90
+ if (!event) return;
91
+ var views = ctx.getViews();
92
+ var curView = views[views.length - 1];
93
+ if (((_event$view = event.view) === null || _event$view === void 0 ? void 0 : _event$view.id) === curView.id) {
94
+ delete event.view;
95
+ }
96
+ this.dispatchEvents(ctx, [event], curView);
62
97
  };
63
98
  _proto.pushToQueue = function pushToQueue() {
64
99
  var ctx = this.ctx,
65
100
  eventQueue = this.eventQueue;
66
101
  var event = ctx.getRumEvent();
102
+ // processor 返回 null/undefined 表示丢弃事件,直接跳过
103
+ if (!event) return;
67
104
 
68
105
  // 针对相同 event,做 times 合并
69
106
  // todo,支持其他类型 event 合并
@@ -121,8 +158,8 @@ var Reporter = exports["default"] = /*#__PURE__*/function () {
121
158
  views.forEach(function (view) {
122
159
  if (view.id === curView.id) {
123
160
  var events = eventQueue.filter(function (event) {
124
- var _event$view;
125
- return ((_event$view = event.view) === null || _event$view === void 0 ? void 0 : _event$view.id) === view.id;
161
+ var _event$view2;
162
+ return ((_event$view2 = event.view) === null || _event$view2 === void 0 ? void 0 : _event$view2.id) === view.id;
126
163
  });
127
164
  events.forEach(function (event) {
128
165
  delete event.view;
@@ -131,28 +168,49 @@ var Reporter = exports["default"] = /*#__PURE__*/function () {
131
168
  });
132
169
  var session = ctx.session;
133
170
  var sampled = session ? session.getSampled() : true;
134
- sampled && this.mergeEvent(ctx, eventQueue, curView);
171
+ sampled && this.dispatchEvents(ctx, eventQueue, curView);
135
172
  this.eventQueue = [];
136
- };
137
- _proto.mergeEvent = function mergeEvent(ctx, events, view) {
173
+ }
174
+
175
+ /**
176
+ * 按 session_id 分组事件并分别打包上报:
177
+ * - 当前 session 的事件统一打包
178
+ * - 非当前 session 的事件按各自 session_id 单独打包
179
+ */;
180
+ _proto.dispatchEvents = function dispatchEvents(ctx, events, view) {
138
181
  var config = ctx.getConfig();
139
182
  var session = ctx.session;
140
183
  var sessionId = session.getSessionId();
141
- // events.forEach(event => {
142
- // if (event.session_id === sessionId) {
143
- // delete event.session_id;
144
- // }
145
- // });
184
+ var currentSessionEvents = [];
185
+ var otherSessionEventsMap = {};
146
186
  for (var i = 0; i < events.length; i++) {
147
187
  var e = events[i];
148
- if (e.session_id === sessionId) {
188
+ if (!e.session_id || e.session_id === sessionId) {
149
189
  delete e.session_id;
190
+ currentSessionEvents.push(e);
150
191
  } else {
151
- events.splice(i, 1);
152
- i--;
192
+ var sid = e.session_id;
193
+ if (!otherSessionEventsMap[sid]) {
194
+ otherSessionEventsMap[sid] = [];
195
+ }
196
+ delete e.session_id;
197
+ otherSessionEventsMap[sid].push(e);
153
198
  }
154
199
  }
155
- if (events.length === 0) return;
200
+ if (currentSessionEvents.length > 0) {
201
+ this.buildAndSend(ctx, config, session, sessionId, currentSessionEvents, view);
202
+ }
203
+ var otherSessionIds = Object.keys(otherSessionEventsMap);
204
+ for (var _i = 0; _i < otherSessionIds.length; _i++) {
205
+ var _sid = otherSessionIds[_i];
206
+ this.buildAndSend(ctx, config, session, _sid, otherSessionEventsMap[_sid], view);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * 构建 bundle 并发送请求
212
+ */;
213
+ _proto.buildAndSend = function buildAndSend(ctx, config, session, sessionId, events, view) {
156
214
  var extend = (0, _url.getUrlParams)(config.endpoint);
157
215
  var bundle = (0, _extends2["default"])({
158
216
  app: {
@@ -1,6 +1,6 @@
1
- import { IClient, IConfiguration } from "../types/client";
2
- import { RumCustomEvent, RumEvent, RumExceptionEvent, RumResourceEvent, RumViewEvent } from "../types/rum-event";
3
- import { IShell } from "../types/shell";
1
+ import { IClient, IConfiguration } from '../types/client';
2
+ import { RumCustomEvent, RumEvent, RumExceptionEvent, RumResourceEvent, RumViewEvent, SendEventOptions } from '../types/rum-event';
3
+ import { IShell } from '../types/shell';
4
4
  export default abstract class Shell implements IShell {
5
5
  client: IClient;
6
6
  constructor(config?: IConfiguration);
@@ -8,7 +8,7 @@ export default abstract class Shell implements IShell {
8
8
  * 初始化
9
9
  */
10
10
  abstract init(configuration: IConfiguration): Promise<Shell> | Shell;
11
- sendEvent(payload: RumEvent): void;
11
+ sendEvent(payload: RumEvent, options?: SendEventOptions): void;
12
12
  /**
13
13
  * get config
14
14
  */
@@ -40,9 +40,9 @@ var Shell = exports["default"] = /*#__PURE__*/function () {
40
40
  * 初始化
41
41
  */
42
42
  var _proto = Shell.prototype;
43
- _proto.sendEvent = function sendEvent(payload) {
43
+ _proto.sendEvent = function sendEvent(payload, options) {
44
44
  if (this.client) {
45
- this.client.sendEvent(payload);
45
+ this.client.sendEvent(payload, options);
46
46
  }
47
47
  }
48
48
 
@@ -69,10 +69,11 @@ var Shell = exports["default"] = /*#__PURE__*/function () {
69
69
  event_type: _rumEvent.RumEventType.CUSTOM
70
70
  });
71
71
  this.sendEvent(data);
72
- };
72
+ }
73
+
73
74
  /**
74
75
  * 自定义视图上报
75
- */
76
+ */;
76
77
  _proto.sendView = function sendView(payload) {
77
78
  if (!(0, _is.isObject)(payload)) {
78
79
  return;
@@ -94,10 +95,11 @@ var Shell = exports["default"] = /*#__PURE__*/function () {
94
95
  event_type: _rumEvent.RumEventType.VIEW
95
96
  });
96
97
  this.sendEvent(data);
97
- };
98
+ }
99
+
98
100
  /**
99
101
  * 自定义异常上报
100
- */
102
+ */;
101
103
  _proto.sendException = function sendException(payload) {
102
104
  if (!payload.name || !payload.message) {
103
105
  return;
@@ -116,10 +118,11 @@ var Shell = exports["default"] = /*#__PURE__*/function () {
116
118
  source: 'custom'
117
119
  });
118
120
  this.sendEvent(data);
119
- };
121
+ }
122
+
120
123
  /**
121
124
  * 自定义资源上报
122
- */
125
+ */;
123
126
  _proto.sendResource = function sendResource(payload) {
124
127
  if (!payload.name || !payload.type || !(0, _is.isNumber)(payload.duration)) {
125
128
  return;
@@ -1,7 +1,7 @@
1
1
  import { ICollector } from './collector';
2
2
  import { IProcessor } from './processor';
3
3
  import { IReporter } from './reporter';
4
- import { RumEvent, RumEventBundle, IViewData } from './rum-event';
4
+ import { RumEvent, RumEventBundle, IViewData, SendEventOptions } from './rum-event';
5
5
  import { MatchOption } from '../utils/match';
6
6
  import { IConfigManager } from './config';
7
7
  import { EventEmitter } from '../utils/events';
@@ -119,7 +119,7 @@ export interface IClient {
119
119
  /**
120
120
  * 业务自定义上传数据
121
121
  */
122
- sendEvent(payload: RumEvent): void;
122
+ sendEvent(payload: RumEvent, options?: SendEventOptions): void;
123
123
  /**
124
124
  * 修改运行时上下文
125
125
  */
@@ -1,7 +1,7 @@
1
1
  import { IContext } from './client';
2
- import { RumEvent } from './rum-event';
2
+ import { SendEventFn } from './rum-event';
3
3
  export interface ICollector {
4
4
  name: string;
5
- setup(ctx: IContext, sendEvent: (payload: RumEvent) => void): void;
5
+ setup(ctx: IContext, sendEvent: SendEventFn): void;
6
6
  destroy?(): void;
7
7
  }
@@ -1,8 +1,8 @@
1
1
  import { IContext } from './client';
2
- import { RumEventBundle } from './rum-event';
2
+ import { RumEventBundle, SendEventOptions } from './rum-event';
3
3
  export interface IReporter {
4
4
  name: string;
5
5
  init(ctx: IContext): void;
6
6
  request(ctx: IContext, bundle: RumEventBundle): void;
7
- report(ctx: IContext): void;
7
+ report(ctx: IContext, options?: SendEventOptions): void;
8
8
  }
@@ -7,6 +7,15 @@ export declare enum RumEventType {
7
7
  CUSTOM = "custom",
8
8
  APPLICATION = "application"
9
9
  }
10
+ /** sendEvent 方法的可选配置 */
11
+ export interface SendEventOptions {
12
+ /** 是否立即上报,将当前事件加入队列后立即 flush 整个队列 */
13
+ immediate?: boolean;
14
+ /** 是否单独上报,当前事件不入队列,独立打包发送 */
15
+ single?: boolean;
16
+ }
17
+ /** 采集器向上层发送事件的统一回调签名 */
18
+ export type SendEventFn = (payload: RumEvent, options?: SendEventOptions) => void;
10
19
  export interface BaseObject {
11
20
  [key: string]: BaseObjectValue;
12
21
  }
@@ -12,6 +12,8 @@ var RumEventType = exports.RumEventType = /*#__PURE__*/function (RumEventType) {
12
12
  RumEventType["APPLICATION"] = "application";
13
13
  return RumEventType;
14
14
  }({});
15
+ /** sendEvent 方法的可选配置 */
16
+ /** 采集器向上层发送事件的统一回调签名 */
15
17
  /** 电池信息 */
16
18
  /** 设备信息 */
17
19
  /** 内存信息 */
@@ -1,5 +1,5 @@
1
- import { IConfiguration } from "./client";
2
- import { RumEvent } from "./rum-event";
1
+ import { IConfiguration } from './client';
2
+ import { RumEvent, SendEventOptions } from './rum-event';
3
3
  /**
4
4
  * 每个 sdk shell 导出固定需要实现的基础 api
5
5
  * 对外导出 shell 层, 所有 shell 层模型的 API 设计约定:
@@ -15,7 +15,7 @@ export interface IShell {
15
15
  /**
16
16
  * 自定义上传数据
17
17
  */
18
- sendEvent(payload: RumEvent): void;
18
+ sendEvent(payload: RumEvent, options?: SendEventOptions): void;
19
19
  /**
20
20
  * get config
21
21
  */