ws-process 0.3.38 → 0.3.40

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/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /* eslint-disable import/no-unresolved */
2
2
  // ws-process.js
3
3
  import axios from 'axios';
4
+ import * as Sentry from '@sentry/react';
4
5
  import {
5
6
  defined, clone, makeid, tryit,
6
7
  } from '@bsgp/lib-core';
@@ -257,6 +258,36 @@ async function decompress(decodedRes) {
257
258
  return JSON.parse(uncompressedStrRes);
258
259
  }
259
260
 
261
+ async function compress(jsonString) {
262
+ // Convert JSON to Stream
263
+ const stream = new Blob([jsonString], {
264
+ type: 'application/json',
265
+ }).stream();
266
+
267
+ // gzip stream
268
+ const compressedReadableStream = stream.pipeThrough(
269
+ // eslint-disable-next-line no-undef
270
+ new CompressionStream('gzip'),
271
+ );
272
+
273
+ // create Response
274
+ const compressedResponse = await new Response(compressedReadableStream);
275
+
276
+ // Get response Blob
277
+ const blob = await compressedResponse.blob();
278
+ // Get the ArrayBuffer
279
+ const buffer = await blob.arrayBuffer();
280
+
281
+ // convert ArrayBuffer to base64 encoded string
282
+ const compressedBase64 = btoa(
283
+ String.fromCharCode(
284
+ ...new Uint8Array(buffer),
285
+ ),
286
+ );
287
+
288
+ return compressedBase64;
289
+ }
290
+
260
291
  async function convertResponseData(inData) {
261
292
  let jsonData;
262
293
 
@@ -308,7 +339,7 @@ async function convertResponseData(inData) {
308
339
  } catch (ex) {
309
340
  jsonData = b64decode(itemLocal.dataSplitted.join(''));
310
341
  jsonData = await decompress(jsonData);
311
- console.log('compression ratio:', inData.splitted.compressionRatio, '=', inData.splitted.compressedSize, '/', inData.splitted.uncompressedSize);
342
+ console.log('res compression ratio:', inData.splitted.compressionRatio, '=', inData.splitted.compressedSize, '/', inData.splitted.uncompressedSize);
312
343
  }
313
344
  } else {
314
345
  jsonData = itemLocal.dataSplitted.join('');
@@ -324,7 +355,7 @@ async function convertResponseData(inData) {
324
355
  } catch (ex) {
325
356
  jsonData = b64decode(inData.response);
326
357
  jsonData = await decompress(jsonData);
327
- console.log('compression ratio:', inData.compressionRatio, '=', inData.compressedSize, '/', inData.uncompressedSize);
358
+ console.log('res compression ratio:', inData.compressionRatio, '=', inData.compressedSize, '/', inData.uncompressedSize);
328
359
  }
329
360
  } else {
330
361
  jsonData = inData;
@@ -653,7 +684,7 @@ function asyncSend(msg) {
653
684
  )
654
685
  : false;
655
686
  if (hasError) {
656
- // reject the promise from reqHandler in runProcess
687
+ // reject the promise from reqHandler in runProcess
657
688
 
658
689
  const { callback } = cProcessItem;
659
690
  if (callback) {
@@ -688,7 +719,7 @@ function asyncSend(msg) {
688
719
  }
689
720
 
690
721
  local.store.dispatch(getWebSocket()).then(
691
- () => {
722
+ async () => {
692
723
  const jsonMSG = tryit(
693
724
  () => (typeof msg === 'string' ? JSON.parse(msg) : msg),
694
725
  msg,
@@ -730,13 +761,35 @@ function asyncSend(msg) {
730
761
  }
731
762
 
732
763
  console.log('%csending message:', 'color:green', jsonMSG);
764
+
733
765
  const wsMSG = JSON.stringify(jsonMSG);
766
+ const encodedMsg = b64EncodeUnicode(wsMSG);
767
+ const compressedMsg = await compress(wsMSG);
768
+ console.log('req compression ratio: ', (compressedMsg.length / encodedMsg.length).toFixed(2), '=', compressedMsg.length, '/', encodedMsg.length);
734
769
 
735
770
  const frameSize = Math.floor(1024 * 32 * 0.9);
736
- const refinedMSG = cutStringByLength(wsMSG, frameSize);
771
+ const refinedMSG = cutStringByLength(compressedMsg, frameSize);
772
+
737
773
  if (refinedMSG.length === 1) {
738
- local.wsProcess.wSocket.send(wsMSG);
774
+ local.wsProcess.wSocket.send(JSON.stringify({
775
+ action: jsonMSG.action,
776
+ body: compressedMsg,
777
+ }));
739
778
  } else {
779
+ try {
780
+ const transaction = Sentry.startInactiveSpan({
781
+ name: 'Split Request Payload',
782
+ op: 'onSplitReqPayload',
783
+ data: {
784
+ payload: jsonMSG,
785
+ },
786
+ });
787
+ transaction.finish();
788
+ // Finishing the transaction will send it to Sentry
789
+ } catch (ex) {
790
+ console.log('sentry ex:', ex);
791
+ }
792
+
740
793
  const srcIndicator = getRandomID();
741
794
  const payloadArr = createSplitPayload(refinedMSG, srcIndicator, jsonMSG);
742
795
  payloadArr.forEach((eachMSG) => {
@@ -770,10 +823,10 @@ function asyncSend(msg) {
770
823
 
771
824
  const started = tryit(() => jsonData.started);
772
825
  if (started) {
773
- /*
774
- The web socket has run the target lambda function asynchronously,
775
- so we just wait for next message from lambda function
776
- */
826
+ /*
827
+ The web socket has run the target lambda function asynchronously,
828
+ so we just wait for next message from lambda function
829
+ */
777
830
 
778
831
  const cProcess = getCurrentProcess(getState, started.processID);
779
832
  if (cProcess) {
@@ -792,7 +845,7 @@ function asyncSend(msg) {
792
845
  console.log('%conmessage(converted):', 'color:red', jsonResponse);
793
846
 
794
847
  if (!jsonResponse) {
795
- // It might be splitted
848
+ // It might be splitted
796
849
 
797
850
  return;
798
851
  }
@@ -817,11 +870,11 @@ function asyncSend(msg) {
817
870
  if (
818
871
  hasKeys(jsonResponse, ['message', 'connectionId', 'requestId'])
819
872
  ) {
820
- /*
821
- It's an error when lambda failed by
822
- uncaught exceptions,
823
- like "forbidden", "internal server error".
824
- */
873
+ /*
874
+ It's an error when lambda failed by
875
+ uncaught exceptions,
876
+ like "forbidden", "internal server error".
877
+ */
825
878
 
826
879
  if (local.validateResponse) {
827
880
  local.store.dispatch(local.validateResponse(jsonResponse));
@@ -838,7 +891,7 @@ function asyncSend(msg) {
838
891
  jsonResponse.processID,
839
892
  );
840
893
  if (!getNextProcessItem(getState, jsonResponse.processID)) {
841
- // It is last, then append
894
+ // It is last, then append
842
895
 
843
896
  local.dispatch(
844
897
  addWSRequest({
@@ -1095,9 +1148,7 @@ function runProcess(processID, data) {
1095
1148
  if (reqParameters && prcItem.reqParameters) {
1096
1149
  // If this process item is re-added by ws-process
1097
1150
 
1098
- reqParameters.subAction = `${
1099
- reqParameters.subAction
1100
- }_${getRandomID()}`;
1151
+ reqParameters.subAction = `${reqParameters.subAction}_${getRandomID()}`;
1101
1152
  }
1102
1153
 
1103
1154
  if (reqParameters && reqParameters.url) {
@@ -1336,10 +1387,10 @@ function init({
1336
1387
  local.stage = stage;
1337
1388
  local.wsURL = wsURL;
1338
1389
 
1339
- local.beforeEachProcess = beforeEachProcess || (() => {});
1340
- local.afterEachProcess = afterEachProcess || (() => {});
1341
- local.beforeAllProcesses = beforeAllProcesses || (() => {});
1342
- local.afterAllProcesses = afterAllProcesses || (() => {});
1390
+ local.beforeEachProcess = beforeEachProcess || (() => { });
1391
+ local.afterEachProcess = afterEachProcess || (() => { });
1392
+ local.beforeAllProcesses = beforeAllProcesses || (() => { });
1393
+ local.afterAllProcesses = afterAllProcesses || (() => { });
1343
1394
  local.validateResponse = validateResponse;
1344
1395
  }
1345
1396
 
@@ -1,4 +1,5 @@
1
- import { isArray, isNumber, isString } from '@bsgp/lib-core/types';
1
+ // eslint-disable-next-line import/no-unresolved
2
+ import { isArray, isNumber, isString } from '@bsgp/lib-core';
2
3
 
3
4
  /**
4
5
  * This function checks string byte size.
@@ -7,8 +8,8 @@ import { isArray, isNumber, isString } from '@bsgp/lib-core/types';
7
8
  * @param {string} string string payload which will be cut into pieces
8
9
  * @param {number} size length of each cut pieces
9
10
  */
10
- function cutStringByLength(string, size = 30000) {
11
- if (!isString(string)) {
11
+ function cutStringByLength(encodedString, size = 30000) {
12
+ if (!isString(encodedString)) {
12
13
  throw new Error('first parameter should be string on function cutStringByLength');
13
14
  }
14
15
 
@@ -16,10 +17,6 @@ function cutStringByLength(string, size = 30000) {
16
17
  throw new Error('second parameter should be number on function cutStringByLength');
17
18
  }
18
19
 
19
- const encodedString = btoa(
20
- encodeURIComponent(string).replace(/%([0-9A-F]{2})/g, (match, p1) => String.fromCharCode(`0x${p1}`)),
21
- );
22
-
23
20
  const payloadPieces = [];
24
21
  const payloadLength = encodedString.length;
25
22
  for (let idx = 0; idx < payloadLength; idx += size) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ws-process",
3
- "version": "0.3.38",
3
+ "version": "0.3.40",
4
4
  "description": "Process Management for Web Socket Client",
5
5
  "main": "index.js",
6
6
  "scripts": {