agora-foundation 3.8.1 → 3.9.0-alpha

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 (91) hide show
  1. package/lib/decorator/log/handler.d.ts +1 -1
  2. package/lib/decorator/log/handler.js +57 -64
  3. package/lib/decorator/log/index.d.ts +26 -1
  4. package/lib/decorator/log/index.js +50 -5
  5. package/lib/decorator/log/log-serializer.d.ts +1 -1
  6. package/lib/decorator/log/log-serializer.js +15 -2
  7. package/lib/decorator/proxy.d.ts +1 -1
  8. package/lib/decorator/proxy.js +16 -16
  9. package/lib/decorator/type.d.ts +3 -2
  10. package/lib/decorator/type.js +2 -2
  11. package/lib/utilities/desc-type.d.ts +1 -0
  12. package/lib/utilities/desc-type.js +1 -1
  13. package/lib/utilities/env.d.ts +2 -1
  14. package/lib/utilities/env.js +1 -0
  15. package/lib/utilities/{agora-error.d.ts → error/agora-error.d.ts} +5 -11
  16. package/lib/utilities/error/agora-error.js +148 -0
  17. package/lib/utilities/error/error-code.d.ts +69 -0
  18. package/lib/utilities/error/error-code.js +81 -0
  19. package/lib/utilities/logger.d.ts +13 -1
  20. package/lib/utilities/logger.js +103 -13
  21. package/lib/utilities/observable.js +1 -0
  22. package/lib/utilities/package-info.d.ts +8 -0
  23. package/lib/utilities/package-info.js +85 -0
  24. package/lib/utilities/regex.d.ts +1 -0
  25. package/lib/utilities/regex.js +14 -0
  26. package/lib/utilities/tools.d.ts +28 -0
  27. package/lib/utilities/tools.js +154 -0
  28. package/lib/worker/worker-factory.js +22 -1
  29. package/lib-es/decorator/bound/index.js +12 -0
  30. package/lib-es/decorator/index.js +4 -0
  31. package/lib-es/decorator/lodash/index.js +34 -0
  32. package/lib-es/decorator/log/handler.js +71 -0
  33. package/lib-es/decorator/log/index.js +73 -0
  34. package/lib-es/decorator/log/log-serializer.js +28 -0
  35. package/lib-es/decorator/proxy.js +149 -0
  36. package/lib-es/decorator/type.js +7 -0
  37. package/lib-es/decorator/validate/index.js +32 -0
  38. package/lib-es/logger/common.js +45 -0
  39. package/lib-es/logger/constants.js +3 -0
  40. package/lib-es/logger/hijack.js +61 -0
  41. package/lib-es/logger/index.js +52 -0
  42. package/lib-es/logger/logger-impl.js +122 -0
  43. package/lib-es/logger/manager-impl.js +63 -0
  44. package/lib-es/logger/type.js +7 -0
  45. package/lib-es/restful-scheduler/scheduler.js +224 -0
  46. package/lib-es/schedule/index.js +3 -0
  47. package/lib-es/schedule/scheduler.js +102 -0
  48. package/lib-es/schedule/task.js +159 -0
  49. package/lib-es/upload/index.js +1 -0
  50. package/lib-es/upload/scheduler.js +145 -0
  51. package/lib-es/upload/type.js +1 -0
  52. package/lib-es/utilities/async-retry.js +177 -0
  53. package/lib-es/utilities/browser.js +20 -0
  54. package/lib-es/utilities/desc-type.js +3 -0
  55. package/lib-es/utilities/env.js +55 -0
  56. package/lib-es/utilities/error/agora-error.js +140 -0
  57. package/lib-es/utilities/error/error-code.js +74 -0
  58. package/lib-es/utilities/events.js +125 -0
  59. package/lib-es/utilities/file-reader.js +15 -0
  60. package/lib-es/utilities/interceptor.js +23 -0
  61. package/lib-es/utilities/logger.js +109 -0
  62. package/lib-es/utilities/misc.js +74 -0
  63. package/lib-es/utilities/observable.js +97 -0
  64. package/lib-es/utilities/package-info.js +78 -0
  65. package/lib-es/utilities/race-condition.js +17 -0
  66. package/lib-es/utilities/regex.js +7 -0
  67. package/lib-es/utilities/safely-remove-child.js +29 -0
  68. package/lib-es/utilities/schema.js +36 -0
  69. package/lib-es/utilities/tools.js +144 -0
  70. package/lib-es/utilities/value-check.js +3 -0
  71. package/lib-es/utilities/zip.js +200 -0
  72. package/lib-es/worker/constants.js +13 -0
  73. package/lib-es/worker/handler/binary.js +157 -0
  74. package/lib-es/worker/handler/db.js +34 -0
  75. package/lib-es/worker/handler/fs-log.js +149 -0
  76. package/lib-es/worker/handler/log-rotate-new.js +230 -0
  77. package/lib-es/worker/handler/log-rotate.js +80 -0
  78. package/lib-es/worker/handler/log.js +291 -0
  79. package/lib-es/worker/handler/reply.js +15 -0
  80. package/lib-es/worker/index.js +8 -0
  81. package/lib-es/worker/interactor.js +435 -0
  82. package/lib-es/worker/mutex.js +57 -0
  83. package/lib-es/worker/type.js +1 -0
  84. package/lib-es/worker/worker-entry.js +3 -0
  85. package/lib-es/worker/worker-factory.js +15 -0
  86. package/lib-es/worker/worker-installer.js +71 -0
  87. package/package.json +8 -4
  88. package/lib/utilities/agora-error.js +0 -128
  89. package/lib/worker/545.worker-factory.js +0 -1
  90. package/lib/worker/847.worker-factory.js +0 -2
  91. package/lib/worker/847.worker-factory.js.LICENSE.txt +0 -24
@@ -0,0 +1,157 @@
1
+ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
2
+ import _regeneratorRuntime from "@babel/runtime/regenerator";
3
+ import { readAsArrayBuffer } from '../../utilities/file-reader';
4
+ import { WorkerDirectives } from '../constants';
5
+ import { db } from './db';
6
+ import { reply } from './reply';
7
+ export var persistBinary = /*#__PURE__*/function () {
8
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(self, callId, id, data) {
9
+ var _t;
10
+ return _regeneratorRuntime.wrap(function (_context) {
11
+ while (1) switch (_context.prev = _context.next) {
12
+ case 0:
13
+ _context.prev = 0;
14
+ _context.next = 1;
15
+ return db.tempLogs.put({
16
+ id: id,
17
+ data: data
18
+ });
19
+ case 1:
20
+ reply(self, callId, WorkerDirectives.PERSIST_BUFFER, {
21
+ isSuccess: true
22
+ });
23
+ _context.next = 3;
24
+ break;
25
+ case 2:
26
+ _context.prev = 2;
27
+ _t = _context["catch"](0);
28
+ console.error("[logger] failed to persist buffer.", _t);
29
+ reply(self, callId, WorkerDirectives.PERSIST_BUFFER, {
30
+ isSuccess: false
31
+ });
32
+ case 3:
33
+ case "end":
34
+ return _context.stop();
35
+ }
36
+ }, _callee, null, [[0, 2]]);
37
+ }));
38
+ return function persistBinary(_x, _x2, _x3, _x4) {
39
+ return _ref.apply(this, arguments);
40
+ };
41
+ }();
42
+ export var unpersistBinary = /*#__PURE__*/function () {
43
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(self, callId, id) {
44
+ var _t2;
45
+ return _regeneratorRuntime.wrap(function (_context2) {
46
+ while (1) switch (_context2.prev = _context2.next) {
47
+ case 0:
48
+ _context2.prev = 0;
49
+ _context2.next = 1;
50
+ return db.tempLogs["delete"](id);
51
+ case 1:
52
+ reply(self, callId, WorkerDirectives.UNPERSIST_BUFFER, {
53
+ isSuccess: true
54
+ });
55
+ _context2.next = 3;
56
+ break;
57
+ case 2:
58
+ _context2.prev = 2;
59
+ _t2 = _context2["catch"](0);
60
+ console.error("[logger] failed to unpersist buffer.", _t2);
61
+ reply(self, callId, WorkerDirectives.UNPERSIST_BUFFER, {
62
+ isSuccess: false
63
+ });
64
+ case 3:
65
+ case "end":
66
+ return _context2.stop();
67
+ }
68
+ }, _callee2, null, [[0, 2]]);
69
+ }));
70
+ return function unpersistBinary(_x5, _x6, _x7) {
71
+ return _ref2.apply(this, arguments);
72
+ };
73
+ }();
74
+ export var getBuffer = /*#__PURE__*/function () {
75
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(self, callId, id) {
76
+ var tempLogs, buffer, data, _t3;
77
+ return _regeneratorRuntime.wrap(function (_context3) {
78
+ while (1) switch (_context3.prev = _context3.next) {
79
+ case 0:
80
+ _context3.prev = 0;
81
+ _context3.next = 1;
82
+ return db.tempLogs.where('id').equals(id).first();
83
+ case 1:
84
+ tempLogs = _context3.sent;
85
+ buffer = null;
86
+ if (!(tempLogs !== null && tempLogs !== void 0 && tempLogs.data)) {
87
+ _context3.next = 3;
88
+ break;
89
+ }
90
+ _context3.next = 2;
91
+ return readAsArrayBuffer(tempLogs.data);
92
+ case 2:
93
+ data = _context3.sent;
94
+ buffer = data;
95
+ case 3:
96
+ if (buffer) {
97
+ reply(self, callId, WorkerDirectives.GET_BUFFER, {
98
+ isSuccess: true,
99
+ buffer: buffer
100
+ }, [buffer]);
101
+ } else {
102
+ reply(self, callId, WorkerDirectives.GET_BUFFER, {
103
+ isSuccess: true,
104
+ buffer: null
105
+ });
106
+ }
107
+ _context3.next = 5;
108
+ break;
109
+ case 4:
110
+ _context3.prev = 4;
111
+ _t3 = _context3["catch"](0);
112
+ console.error("[logger] failed to get buffer.", _t3);
113
+ reply(self, callId, WorkerDirectives.GET_BUFFER, {
114
+ isSuccess: false
115
+ });
116
+ case 5:
117
+ case "end":
118
+ return _context3.stop();
119
+ }
120
+ }, _callee3, null, [[0, 4]]);
121
+ }));
122
+ return function getBuffer(_x8, _x9, _x0) {
123
+ return _ref3.apply(this, arguments);
124
+ };
125
+ }();
126
+ export var clearTempLogs = /*#__PURE__*/function () {
127
+ var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(self, callId) {
128
+ var _t4;
129
+ return _regeneratorRuntime.wrap(function (_context4) {
130
+ while (1) switch (_context4.prev = _context4.next) {
131
+ case 0:
132
+ _context4.prev = 0;
133
+ _context4.next = 1;
134
+ return db.tempLogs.clear();
135
+ case 1:
136
+ reply(self, callId, WorkerDirectives.CLEAR_TEMP_LOGS, {
137
+ isSuccess: true
138
+ });
139
+ _context4.next = 3;
140
+ break;
141
+ case 2:
142
+ _context4.prev = 2;
143
+ _t4 = _context4["catch"](0);
144
+ console.error("[logger] failed to clear temp logs.", _t4);
145
+ reply(self, callId, WorkerDirectives.CLEAR_TEMP_LOGS, {
146
+ isSuccess: false
147
+ });
148
+ case 3:
149
+ case "end":
150
+ return _context4.stop();
151
+ }
152
+ }, _callee4, null, [[0, 2]]);
153
+ }));
154
+ return function clearTempLogs(_x1, _x10) {
155
+ return _ref4.apply(this, arguments);
156
+ };
157
+ }();
@@ -0,0 +1,34 @@
1
+ import "core-js/modules/es.reflect.construct.js";
2
+ import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
3
+ import _createClass from "@babel/runtime/helpers/createClass";
4
+ import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
5
+ import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
6
+ import _inherits from "@babel/runtime/helpers/inherits";
7
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
8
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
9
+ import Dexie from 'dexie';
10
+ var DATABASE_NAME = "AgoraLogger";
11
+ var TABLE_NAME_LOGS = "logs";
12
+ var TABLE_NAME_LOGS_TEMP_BUFFERS = "tempLogs";
13
+ export var LoggerDB = /*#__PURE__*/function (_Dexie) {
14
+ function LoggerDB() {
15
+ var _this;
16
+ _classCallCheck(this, LoggerDB);
17
+ _this = _callSuper(this, LoggerDB, [DATABASE_NAME]);
18
+ _this.openDatabase();
19
+ _this.logs = _this.table(TABLE_NAME_LOGS);
20
+ _this.tempLogs = _this.table(TABLE_NAME_LOGS_TEMP_BUFFERS);
21
+ return _this;
22
+ }
23
+ _inherits(LoggerDB, _Dexie);
24
+ return _createClass(LoggerDB, [{
25
+ key: "openDatabase",
26
+ value: function openDatabase() {
27
+ this.version(2).stores({
28
+ logs: '++id, content, label, created_at',
29
+ tempLogs: '++id, data'
30
+ });
31
+ }
32
+ }]);
33
+ }(Dexie);
34
+ export var db = new LoggerDB();
@@ -0,0 +1,149 @@
1
+ import "core-js/modules/es.symbol.js";
2
+ import "core-js/modules/es.symbol.description.js";
3
+ import "core-js/modules/es.symbol.iterator.js";
4
+ import "core-js/modules/es.error.cause.js";
5
+ import "core-js/modules/es.error.to-string.js";
6
+ import "core-js/modules/es.array.from.js";
7
+ import "core-js/modules/es.array.is-array.js";
8
+ import "core-js/modules/es.array.iterator.js";
9
+ import "core-js/modules/es.array.slice.js";
10
+ import "core-js/modules/es.date.to-string.js";
11
+ import "core-js/modules/es.function.name.js";
12
+ import "core-js/modules/es.object.to-string.js";
13
+ import "core-js/modules/es.regexp.exec.js";
14
+ import "core-js/modules/es.regexp.test.js";
15
+ import "core-js/modules/es.regexp.to-string.js";
16
+ import "core-js/modules/es.string.iterator.js";
17
+ import "core-js/modules/web.dom-collections.iterator.js";
18
+ import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
19
+ import _regeneratorRuntime from "@babel/runtime/regenerator";
20
+ import "core-js/modules/es.array.concat.js";
21
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
22
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
23
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
24
+ import JSZip from 'jszip';
25
+ import { WorkerDirectives } from '../constants';
26
+ import { db } from './db';
27
+ import { reply } from './reply';
28
+ export var collectLogsOnFs = /*#__PURE__*/function () {
29
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(self, callId, logDirPath) {
30
+ var fs;
31
+ return _regeneratorRuntime.wrap(function (_context2) {
32
+ while (1) switch (_context2.prev = _context2.next) {
33
+ case 0:
34
+ try {
35
+ fs = window.require('fs');
36
+ fs.readdir(logDirPath, /*#__PURE__*/function () {
37
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(err, files) {
38
+ var zip, _iterator, _step, file, filePath, logFileData, blob, buffer;
39
+ return _regeneratorRuntime.wrap(function (_context) {
40
+ while (1) switch (_context.prev = _context.next) {
41
+ case 0:
42
+ if (!err) {
43
+ _context.next = 1;
44
+ break;
45
+ }
46
+ console.error("[logger] failed to read log dir.", err);
47
+ reply(self, callId, WorkerDirectives.COLLECT_LOGS_ON_FS, {
48
+ isSuccess: false
49
+ });
50
+ _context.next = 5;
51
+ break;
52
+ case 1:
53
+ if (!(files.length === 0)) {
54
+ _context.next = 2;
55
+ break;
56
+ }
57
+ reply(self, callId, WorkerDirectives.COLLECT_LOGS_ON_FS, {
58
+ isSuccess: true,
59
+ buffer: null
60
+ });
61
+ _context.next = 5;
62
+ break;
63
+ case 2:
64
+ zip = new JSZip();
65
+ _iterator = _createForOfIteratorHelper(files);
66
+ try {
67
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
68
+ file = _step.value;
69
+ filePath = "".concat(logDirPath, "/").concat(file);
70
+ logFileData = fs.readFileSync(filePath);
71
+ zip.file(file, logFileData);
72
+ }
73
+ } catch (err) {
74
+ _iterator.e(err);
75
+ } finally {
76
+ _iterator.f();
77
+ }
78
+ _context.next = 3;
79
+ return zip.generateAsync({
80
+ type: 'blob'
81
+ });
82
+ case 3:
83
+ blob = _context.sent;
84
+ _context.next = 4;
85
+ return blob.arrayBuffer();
86
+ case 4:
87
+ buffer = _context.sent;
88
+ reply(self, callId, WorkerDirectives.COLLECT_LOGS_ON_FS, {
89
+ isSuccess: true,
90
+ buffer: buffer
91
+ });
92
+ case 5:
93
+ case "end":
94
+ return _context.stop();
95
+ }
96
+ }, _callee);
97
+ }));
98
+ return function (_x4, _x5) {
99
+ return _ref2.apply(this, arguments);
100
+ };
101
+ }());
102
+ } catch (e) {
103
+ console.error("[logger] failed to get buffer.", e);
104
+ reply(self, callId, WorkerDirectives.GET_BUFFER, {
105
+ isSuccess: false
106
+ });
107
+ }
108
+ case 1:
109
+ case "end":
110
+ return _context2.stop();
111
+ }
112
+ }, _callee2);
113
+ }));
114
+ return function collectLogsOnFs(_x, _x2, _x3) {
115
+ return _ref.apply(this, arguments);
116
+ };
117
+ }();
118
+ export var clearTempLogs = /*#__PURE__*/function () {
119
+ var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(self, callId) {
120
+ var _t;
121
+ return _regeneratorRuntime.wrap(function (_context3) {
122
+ while (1) switch (_context3.prev = _context3.next) {
123
+ case 0:
124
+ _context3.prev = 0;
125
+ _context3.next = 1;
126
+ return db.tempLogs.clear();
127
+ case 1:
128
+ reply(self, callId, WorkerDirectives.CLEAR_TEMP_LOGS, {
129
+ isSuccess: true
130
+ });
131
+ _context3.next = 3;
132
+ break;
133
+ case 2:
134
+ _context3.prev = 2;
135
+ _t = _context3["catch"](0);
136
+ console.error("[logger] failed to clear temp logs.", _t);
137
+ reply(self, callId, WorkerDirectives.CLEAR_TEMP_LOGS, {
138
+ isSuccess: false
139
+ });
140
+ case 3:
141
+ case "end":
142
+ return _context3.stop();
143
+ }
144
+ }, _callee3, null, [[0, 2]]);
145
+ }));
146
+ return function clearTempLogs(_x6, _x7) {
147
+ return _ref3.apply(this, arguments);
148
+ };
149
+ }();
@@ -0,0 +1,230 @@
1
+ import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
2
+ import _createClass from "@babel/runtime/helpers/createClass";
3
+ import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
4
+ import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
5
+ import _inherits from "@babel/runtime/helpers/inherits";
6
+ import _defineProperty from "@babel/runtime/helpers/defineProperty";
7
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
8
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
9
+ import "core-js/modules/es.array.concat.js";
10
+ import "core-js/modules/es.array.filter.js";
11
+ import "core-js/modules/es.array.for-each.js";
12
+ import "core-js/modules/es.array.join.js";
13
+ import "core-js/modules/es.array.map.js";
14
+ import "core-js/modules/es.array.push.js";
15
+ import "core-js/modules/es.array.slice.js";
16
+ import "core-js/modules/es.array.sort.js";
17
+ import "core-js/modules/es.date.to-string.js";
18
+ import "core-js/modules/es.object.to-string.js";
19
+ import "core-js/modules/es.string.ends-with.js";
20
+ import "core-js/modules/es.reflect.construct.js";
21
+ import "core-js/modules/es.string.pad-start.js";
22
+ import "core-js/modules/es.string.starts-with.js";
23
+ import "core-js/modules/esnext.iterator.constructor.js";
24
+ import "core-js/modules/esnext.iterator.filter.js";
25
+ import "core-js/modules/esnext.iterator.for-each.js";
26
+ import "core-js/modules/esnext.iterator.map.js";
27
+ import "core-js/modules/web.dom-collections.for-each.js";
28
+ import "core-js/modules/web.immediate.js";
29
+ var formatTimestamp = function formatTimestamp() {
30
+ var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
31
+ var year = date.getFullYear();
32
+ var month = String(date.getMonth() + 1).padStart(2, '0');
33
+ var day = String(date.getDate()).padStart(2, '0');
34
+ var hours = String(date.getHours()).padStart(2, '0');
35
+ var minutes = String(date.getMinutes()).padStart(2, '0');
36
+ var seconds = String(date.getSeconds()).padStart(2, '0');
37
+ return "".concat(year).concat(month).concat(day).concat(hours).concat(minutes).concat(seconds);
38
+ };
39
+ export var createRotateTransport = function createRotateTransport(filenamePrefix, logFolderPath) {
40
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
41
+ var WinstonTransport = require('winston-transport');
42
+ var CustomRotateTransport = /*#__PURE__*/function (_WinstonTransport) {
43
+ function CustomRotateTransport(opts) {
44
+ var _this;
45
+ _classCallCheck(this, CustomRotateTransport);
46
+ _this = _callSuper(this, CustomRotateTransport, [{
47
+ level: opts.level || 'info'
48
+ }]);
49
+ _defineProperty(_this, "currentFile", '');
50
+ _defineProperty(_this, "currentStream", null);
51
+ _defineProperty(_this, "currentSize", 0);
52
+ _defineProperty(_this, "writeQueue", []);
53
+ _defineProperty(_this, "writing", false);
54
+ _defineProperty(_this, "lastTimestamp", '');
55
+ _defineProperty(_this, "rotateIndex", 0);
56
+ _this.filenamePrefix = opts.filenamePrefix;
57
+ _this.logFolderPath = opts.logFolderPath;
58
+ _this.maxSize = opts.maxSize || 1024 * 1024;
59
+ _this.maxFiles = opts.maxFiles || 5;
60
+ _this.level = opts.level || 'info';
61
+ _this.fs = require('fs');
62
+ _this.path = require('path');
63
+ return _this;
64
+ }
65
+
66
+ /**
67
+ * 生成唯一的日志文件名,避免同一秒多次轮转导致的覆盖
68
+ */
69
+ _inherits(CustomRotateTransport, _WinstonTransport);
70
+ return _createClass(CustomRotateTransport, [{
71
+ key: "generateLogFilename",
72
+ value: function generateLogFilename() {
73
+ var timestamp = formatTimestamp();
74
+ if (timestamp === this.lastTimestamp) {
75
+ this.rotateIndex += 1;
76
+ } else {
77
+ this.rotateIndex = 0;
78
+ this.lastTimestamp = timestamp;
79
+ }
80
+ return this.rotateIndex === 0 ? "".concat(this.filenamePrefix, "-").concat(timestamp, ".log") : "".concat(this.filenamePrefix, "-").concat(timestamp, "-").concat(this.rotateIndex, ".log");
81
+ }
82
+
83
+ /**
84
+ * 创建新日志文件,并清理旧文件
85
+ */
86
+ }, {
87
+ key: "createNewLogFile",
88
+ value: function createNewLogFile() {
89
+ if (this.currentStream) {
90
+ this.currentStream.end();
91
+ }
92
+ var filename = this.generateLogFilename();
93
+ this.currentFile = this.path.join(this.logFolderPath, filename);
94
+ console.log("[CustomRotateTransport] Creating new log file: ".concat(this.currentFile));
95
+ this.currentStream = this.fs.createWriteStream(this.currentFile, {
96
+ flags: 'a'
97
+ });
98
+ this.currentSize = this.fs.existsSync(this.currentFile) ? this.fs.statSync(this.currentFile).size : 0;
99
+ this.cleanupOldFiles();
100
+ }
101
+
102
+ /**
103
+ * 只允许每个 buffer 触发一次轮转,避免多余文件
104
+ */
105
+ }, {
106
+ key: "processQueue",
107
+ value: function processQueue() {
108
+ var _this2 = this;
109
+ if (this.writing || this.writeQueue.length === 0) return;
110
+ this.writing = true;
111
+ var _ref = this.writeQueue.shift(),
112
+ buffer = _ref.buffer,
113
+ callback = _ref.callback;
114
+
115
+ // 1. 单条日志大于 maxSize,直接新建新文件并写入,不要理会 currentStream
116
+ if (buffer.length > this.maxSize) {
117
+ this.createNewLogFile();
118
+ console.log("[CustomRotateTransport] buffer.length (".concat(buffer.length, ") > maxSize (").concat(this.maxSize, "), force rotate."));
119
+ this.currentStream.write(buffer, function () {
120
+ try {
121
+ _this2.currentSize = _this2.fs.statSync(_this2.currentFile).size;
122
+ } catch (_unused) {
123
+ _this2.currentSize += buffer.length;
124
+ }
125
+ callback();
126
+ _this2.writing = false;
127
+ _this2.processQueue();
128
+ });
129
+ return;
130
+ }
131
+
132
+ // 2. buffer.length <= maxSize,才需要判断 currentStream 是否为空
133
+ if (!this.currentStream) {
134
+ this.createNewLogFile();
135
+ }
136
+ var actualSize = 0;
137
+ try {
138
+ actualSize = this.fs.existsSync(this.currentFile) ? this.fs.statSync(this.currentFile).size : 0;
139
+ } catch (_unused2) {
140
+ actualSize = this.currentSize;
141
+ }
142
+ if (actualSize + buffer.length > this.maxSize) {
143
+ console.log("[CustomRotateTransport] actualSize (".concat(actualSize, ") + buffer.length (").concat(buffer.length, ") > maxSize (").concat(this.maxSize, "), rotate."));
144
+ this.createNewLogFile();
145
+ // 强制清理,确保文件数量不超过限制
146
+ setImmediate(function () {
147
+ return _this2.cleanupOldFiles();
148
+ });
149
+ }
150
+ this.currentStream.write(buffer, function () {
151
+ try {
152
+ _this2.currentSize = _this2.fs.statSync(_this2.currentFile).size;
153
+ } catch (_unused3) {
154
+ _this2.currentSize += buffer.length;
155
+ }
156
+ callback();
157
+ _this2.writing = false;
158
+ _this2.processQueue();
159
+ });
160
+ }
161
+
162
+ /**
163
+ * 清理旧日志文件,只保留 maxFiles 个
164
+ */
165
+ }, {
166
+ key: "cleanupOldFiles",
167
+ value: function cleanupOldFiles() {
168
+ var _this3 = this;
169
+ try {
170
+ var files = this.fs.readdirSync(this.logFolderPath).filter(function (file) {
171
+ return file.startsWith(_this3.filenamePrefix) && file.endsWith('.log');
172
+ }).map(function (file) {
173
+ return {
174
+ name: file,
175
+ path: _this3.path.join(_this3.logFolderPath, file),
176
+ stat: _this3.fs.statSync(_this3.path.join(_this3.logFolderPath, file))
177
+ };
178
+ }).sort(function (a, b) {
179
+ return b.stat.mtime.getTime() - a.stat.mtime.getTime();
180
+ });
181
+ console.log("[CustomRotateTransport] Found ".concat(files.length, " log files, maxFiles: ").concat(this.maxFiles));
182
+ if (files.length > this.maxFiles) {
183
+ var filesToDelete = files.slice(this.maxFiles);
184
+ console.log("[CustomRotateTransport] Will delete ".concat(filesToDelete.length, " old files"));
185
+ filesToDelete.forEach(function (file) {
186
+ try {
187
+ _this3.fs.unlinkSync(file.path);
188
+ console.log("[CustomRotateTransport] Deleted old log file: ".concat(file.path));
189
+ } catch (err) {
190
+ console.warn("[CustomRotateTransport] Failed to delete log file: ".concat(file.path), err);
191
+ }
192
+ });
193
+ }
194
+ } catch (err) {
195
+ console.warn('[CustomRotateTransport] Error cleaning up old log files:', err);
196
+ }
197
+ }
198
+ }, {
199
+ key: "log",
200
+ value: function log(info, callback) {
201
+ var _this4 = this;
202
+ setImmediate(function () {
203
+ return _this4.emit('logged', info);
204
+ });
205
+ var message = info[Symbol["for"]('message')] || info.message || '';
206
+ var buffer = Buffer.from(message + '\n', 'utf8');
207
+ this.writeQueue.push({
208
+ buffer: buffer,
209
+ callback: callback
210
+ });
211
+ this.processQueue();
212
+ }
213
+ }, {
214
+ key: "close",
215
+ value: function close() {
216
+ if (this.currentStream) {
217
+ this.currentStream.end();
218
+ this.currentStream = null;
219
+ }
220
+ }
221
+ }]);
222
+ }(WinstonTransport);
223
+ return new CustomRotateTransport({
224
+ filenamePrefix: filenamePrefix,
225
+ logFolderPath: logFolderPath,
226
+ maxSize: options.maxSize,
227
+ maxFiles: options.maxFiles,
228
+ level: options.level
229
+ });
230
+ };
@@ -0,0 +1,80 @@
1
+ import "core-js/modules/es.array.concat.js";
2
+ import "core-js/modules/es.array.filter.js";
3
+ import "core-js/modules/es.array.for-each.js";
4
+ import "core-js/modules/es.array.join.js";
5
+ import "core-js/modules/es.array.slice.js";
6
+ import "core-js/modules/es.array.sort.js";
7
+ import "core-js/modules/es.object.to-string.js";
8
+ import "core-js/modules/es.regexp.constructor.js";
9
+ import "core-js/modules/es.regexp.dot-all.js";
10
+ import "core-js/modules/es.regexp.exec.js";
11
+ import "core-js/modules/es.regexp.sticky.js";
12
+ import "core-js/modules/es.regexp.test.js";
13
+ import "core-js/modules/es.regexp.to-string.js";
14
+ import "core-js/modules/esnext.iterator.constructor.js";
15
+ import "core-js/modules/esnext.iterator.filter.js";
16
+ import "core-js/modules/esnext.iterator.for-each.js";
17
+ import "core-js/modules/web.dom-collections.for-each.js";
18
+ import "core-js/modules/web.timers.js";
19
+ export var createRotateTransport = function createRotateTransport(filenamePrefix, logFolderPath) {
20
+ require('winston-daily-rotate-file');
21
+ var winston = require('winston');
22
+ console.log('[worker] log rotate transport created:', filenamePrefix, logFolderPath);
23
+ var transport = new winston.transports.DailyRotateFile({
24
+ level: 'info',
25
+ frequency: '9999d',
26
+ dirname: logFolderPath,
27
+ filename: "".concat(filenamePrefix, "-%DATE%.log"),
28
+ datePattern: 'YYYYMMDDhhmmss',
29
+ maxSize: 1024 * 1024
30
+ });
31
+ transport.on('error', function (error) {
32
+ // log or handle errors here
33
+ console.error('[worker] winston transport error:', error);
34
+ });
35
+ transport.on('new', function (filename) {
36
+ console.log("[worker] winston transport new file created: ".concat(filename));
37
+ });
38
+ transport.on('rotate', function (oldFilename, newFilename) {
39
+ console.log("[worker] winston transport rotated: ".concat(oldFilename, " -> ").concat(newFilename));
40
+ clearLogFolder(logFolderPath, filenamePrefix);
41
+ });
42
+
43
+ // only keep the latest 5 log files
44
+ clearLogFolder(logFolderPath, filenamePrefix);
45
+ return transport;
46
+ };
47
+ var clearLogFolder = function clearLogFolder(logFolderPath, filenamePrefix) {
48
+ var fs = require('node:fs');
49
+ setTimeout(function () {
50
+ fs.readdir(logFolderPath, function (err, files) {
51
+ if (err) {
52
+ console.error("[worker] failed to read log folder: ".concat(logFolderPath), err);
53
+ return;
54
+ }
55
+ var sortedLogFileList = files.filter(function (file) {
56
+ return new RegExp("^".concat(filenamePrefix, "-\\d{14}\\.log")).test(file);
57
+ }).sort(function (a, b) {
58
+ return fs.statSync("".concat(logFolderPath, "/").concat(a)).mtime.getTime() - fs.statSync("".concat(logFolderPath, "/").concat(b)).mtime.getTime();
59
+ });
60
+ console.log("[worker] sorted log files: ".concat(sortedLogFileList.join(', '), ", count: ").concat(sortedLogFileList.length));
61
+ if (sortedLogFileList.length <= 5) {
62
+ return; // 不需要删除文件
63
+ }
64
+ var listToDelete = sortedLogFileList.slice(0, sortedLogFileList.length - 5);
65
+
66
+ // 判断如果超过5个文件,则删除最旧的文件
67
+ console.log("[worker] log files to delete: ".concat(listToDelete.join(', ')));
68
+ listToDelete.forEach(function (file) {
69
+ var oldFilename = "".concat(logFolderPath, "/").concat(file);
70
+ fs.unlink(oldFilename, function (err) {
71
+ if (err) {
72
+ console.error("[worker] failed to delete log file: ".concat(oldFilename), err);
73
+ } else {
74
+ console.log("[worker] successfully deleted log file: ".concat(oldFilename));
75
+ }
76
+ });
77
+ });
78
+ });
79
+ });
80
+ };