UNPKG

@teamsparta/cross-platform-logger

Version:

```typescript import * as CPL from "@teamsparta/cross-platform-logger";

234 lines 12.4 kB
"use strict"; // https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-kinesis/index.html // https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html // https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html // https://docs.aws.amazon.com/streams/latest/dev/developing-producers-with-sdk.html#kinesis-using-sdk-java-add-data-to-stream var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.FlounderLog = void 0; // javascript v3 AWS SDK var client_kinesis_1 = require("@aws-sdk/client-kinesis"); var credential_providers_1 = require("@aws-sdk/credential-providers"); var buffer_1 = require("buffer"); var FlounderLog = /** @class */ (function () { // private _recordData: { Data: Uint8Array | undefined, PartitionKey: string }[]; function FlounderLog(flounder_key, is_dev) { if (is_dev === void 0) { is_dev = true; } var _this = this; this.initKinesis = function (flounder_key) { _this._client = new client_kinesis_1.KinesisClient({ region: _this._region, credentials: (0, credential_providers_1.fromCognitoIdentityPool)({ identityPoolId: flounder_key, clientConfig: { region: _this._region } }) }); }; this._getStream = function () { return _this._is_dev ? "TEST.online_lead_kinesis" : "PROD.sparta_online"; }; this._debug = function (title, data) { if (!_this._is_dev) return; var space = 0; if (title === 'data') { space = 2; console.log("%c".concat(data === null || data === void 0 ? void 0 : data.key), 'color: #87CEEB; font-size:15px '); } var text_to_output = typeof (data) === 'object' ? JSON.stringify(__assign({}, data), undefined, space) : data; console.log("CPlog ".concat(title, ": ").concat(text_to_output)); }; this.push_events = function (key, data) { if (data === void 0) { data = {}; } _this._debug("data", __assign({ key: key }, data)); var record = { // Data: Uint8Array | undefined; The data blob to put into the record, which is base64-encoded when the blob is serialized. Data: buffer_1.Buffer.from(JSON.stringify(__assign({ key: key }, data))), // Kinesis Data Streams segregates the data records that belong to a stream into multiple shards, using the partition key associated with each data record to determine the shard to which a given data record belongs. // Requests made with many different partition keys to streams with many different shards are generally faster than requests with a small number of partition keys to a small number of shards. PartitionKey: String(Math.floor(Math.random() * 10) + 1) }; _this._recordData.push(record); }; this.get_failed_events = function (result) { var _a, _b; // this._debug("response", result); var failedCounts = (_a = result.FailedRecordCount) !== null && _a !== void 0 ? _a : 0; var recordsList = (_b = result.Records) !== null && _b !== void 0 ? _b : []; var failed_array = []; if (recordsList && failedCounts > 0) { failed_array = recordsList.reduce(function (array, record, idx) { if (!!record.ErrorCode) array.push(_this._recordData[idx]); return array; }, []); } return failed_array; }; this.send = function () { return __awaiter(_this, void 0, void 0, function () { var command, e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: command = new client_kinesis_1.PutRecordsCommand({ Records: this._recordData, StreamName: this._getStream() }); // clear record data this._recordData = []; _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, this._client.send(command)]; case 2: return [2 /*return*/, _a.sent()]; case 3: e_1 = _a.sent(); console.log(e_1); return [2 /*return*/]; case 4: return [2 /*return*/]; } }); }); }; this.sendInterval = function () { if (typeof window !== "undefined") { window.setInterval(function () { return __awaiter(_this, void 0, void 0, function () { var result, failed_events; return __generator(this, function (_a) { switch (_a.label) { case 0: if (!this._recordData.length) return [2 /*return*/]; return [4 /*yield*/, this.send()]; case 1: result = _a.sent(); if (result) { failed_events = this.get_failed_events(result); this._recordData.concat(failed_events); } return [2 /*return*/]; } }); }); }, 1000); } }; this.send_events_keep_alive = function (key_1) { var args_1 = []; for (var _i = 1; _i < arguments.length; _i++) { args_1[_i - 1] = arguments[_i]; } return __awaiter(_this, __spreadArray([key_1], args_1, true), void 0, function (key, data) { var stream_name, kinesis_api_gateway_url, headers, mergedData, payload, payload_blob, response, responseData, error_1; if (data === void 0) { data = {}; } return __generator(this, function (_a) { switch (_a.label) { case 0: stream_name = this._getStream(); kinesis_api_gateway_url = "https://a6wkbhd6x8.execute-api.ap-northeast-2.amazonaws.com/main/streams/".concat(stream_name); headers = { 'Content-Type': 'application/json' }; mergedData = __assign(__assign({}, data), { key: key }); payload = { PartitionKey: '3', Data: mergedData }; payload_blob = new Blob([JSON.stringify(payload)]); this._debug('unload sent', mergedData); _a.label = 1; case 1: _a.trys.push([1, 6, , 7]); return [4 /*yield*/, fetch(kinesis_api_gateway_url, { method: 'PUT', headers: headers, body: payload_blob, keepalive: true })]; case 2: response = _a.sent(); if (!!response.ok) return [3 /*break*/, 3]; this._debug('HTTP error! Status:', response.status); return [3 /*break*/, 5]; case 3: return [4 /*yield*/, response.json()]; case 4: responseData = _a.sent(); this._debug('Data sent successfully!', responseData); _a.label = 5; case 5: return [3 /*break*/, 7]; case 6: error_1 = _a.sent(); this._debug('There was a problem with the fetch operation:', error_1.message); return [3 /*break*/, 7]; case 7: return [2 /*return*/]; } }); }); }; this._is_dev = is_dev; this._region = 'ap-northeast-2'; this.initKinesis(flounder_key); this._recordData = []; this.sendInterval(); } return FlounderLog; }()); exports.FlounderLog = FlounderLog; //# sourceMappingURL=flounder.js.map