corebasic 1.0.66 → 1.0.68

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/libs/dip.js CHANGED
@@ -12,6 +12,8 @@ export const transactionAbort = Elabase.transactionAbort
12
12
  export const transactionReset = Elabase.transactionReset
13
13
  export const transactionCommit = Elabase.transactionCommit
14
14
 
15
+ export const shard_stats = Elabase.shard_stats
16
+ export let config = Elabase.config
15
17
 
16
18
  export const IdempotentDip = () => {
17
19
  return {
package/libs/dipper.js ADDED
@@ -0,0 +1,91 @@
1
+ import axios from 'axios'
2
+ // import {curly} from 'node-libcurl'
3
+
4
+ function hashStr(str) {
5
+ let hash = 0;
6
+ for (let i = 0; i < str.length; i++) {
7
+ let charCode = str.charCodeAt(i);
8
+ hash += charCode;
9
+ }
10
+ return hash;
11
+ }
12
+
13
+ function hash(string, digits) {
14
+ digits = digits || 6;
15
+ var m = Math.pow(10, digits+1) - 1;
16
+ var phi = Math.pow(10, digits) / 2 - 1;
17
+ var n = 0;
18
+ for (var i = 0; i < string.length; i++) {
19
+ n = (n + phi * string.charCodeAt(i)) % m;
20
+ }
21
+ return n.toString();
22
+ }
23
+ let shards = []
24
+ let shardCount = 20
25
+
26
+ for (let i = 1; i <= shardCount; i++)
27
+ shards.push(`127.0.0.1:${9500 + i}`)
28
+
29
+
30
+ // function shard(key) {
31
+ // return hash(key,1) % shardCount
32
+ // }
33
+ function shard(key) {
34
+ return hashStr(key) % shardCount
35
+ }
36
+
37
+ export let shard_hits = {}
38
+
39
+ async function postDip(url, arg) {
40
+ return (await axios.post(url, arg)).data
41
+ // curl
42
+ // -----
43
+ // const { data } = await curly.post(url, {
44
+ // postFields: JSON.stringify(arg),
45
+ // httpHeader: [
46
+ // 'Content-Type: application/json',
47
+ // 'Accept: application/json'
48
+ // ],
49
+ // })
50
+ // return data
51
+ }
52
+
53
+ export default async function dipper(arg) {
54
+
55
+ let result = []
56
+
57
+ let _id = arg.query?._id ?? arg.insert?._id ?? undefined
58
+
59
+ if (!_id) {
60
+ let result = []
61
+ for (let url of shards) {
62
+ shard_hits[url] = (shard_hits[url] ?? 0) + 1
63
+ result.push(await postDip(`http://${url}/execute`, arg))
64
+ }
65
+
66
+ } else {
67
+
68
+ let ids = typeof _id == "object" ? _id.$in : [_id]
69
+ for (let id of ids) {
70
+ let key = shard(id)
71
+ let url = shards[key]
72
+ shard_hits[url] = (shard_hits[url] ?? 0) + 1
73
+ result.push(await postDip(`http://${url}/execute`, arg))
74
+ }
75
+ }
76
+
77
+ if (arg.mode === "query")
78
+ result = result.reduce( (partial, item) => partial.concat(item), [])
79
+
80
+
81
+
82
+ return arg.mode === "query" ? result : result[0]
83
+ }
84
+
85
+
86
+ export const shard_stats = () => {
87
+ let total = Object.values(shard_hits).reduce( (partial, value) => partial + value, 0)
88
+ let result = {}
89
+ Object.entries(shard_hits).forEach( ([key,value]) => result[key] = parseFloat(value * 100 / total).toFixed(2) )
90
+ return result
91
+ }
package/libs/elabase.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import axios from 'axios'
2
+ import {default as dipper, shard_stats as ShardStats} from './dipper.js'
2
3
 
3
4
 
4
5
 
5
6
 
6
7
 
7
-
8
-
8
+ export const shard_stats = ShardStats
9
9
 
10
10
 
11
11
 
@@ -176,6 +176,10 @@ export const remove = async (collection, query) => {
176
176
  })
177
177
  }
178
178
 
179
+ export let config = {
180
+ useDipper: false
181
+ }
182
+
179
183
  function execute(arg) {
180
184
  // arg example
181
185
  // {
@@ -194,7 +198,8 @@ function execute(arg) {
194
198
  if (stats)
195
199
  arg.stats = true
196
200
 
197
- return axios
201
+ return config.useDipper ? dipper(arg)
202
+ : axios
198
203
  .post(fullurl, arg)
199
204
  // .timeout(5000)
200
205
  .then(result => {
package/libs/features.js CHANGED
@@ -8,14 +8,14 @@ let apis = {}
8
8
 
9
9
  export const start = async (app, url, file) => {
10
10
  features = await Utils.fileToJson(url, file)
11
-
11
+
12
12
 
13
13
  // Registering handlers
14
14
  for (let name in features) {
15
15
  let feature = features[name]
16
16
  apis[feature.api] = apis[feature.api] ?? {}
17
17
  apis[feature.api][name] = feature
18
-
18
+
19
19
  name = name.split('.')
20
20
  let handler = name.pop()
21
21
  name = `src/${name.join('/')}`
@@ -75,7 +75,7 @@ export const start = async (app, url, file) => {
75
75
  } catch {
76
76
  console.warn(`Feature: ${message.feature}, error in executing handler during Kafka.receive(topic: ${topic})`)
77
77
  }
78
- await timer(10000);
78
+ await timer(10000);
79
79
  }
80
80
  })
81
81
  }
@@ -93,7 +93,7 @@ export const start = async (app, url, file) => {
93
93
  }
94
94
  })
95
95
  }
96
-
96
+
97
97
  const commandAction = async (req, res, topic) => {
98
98
  let txn = req.body.txn ?? Util.uid()
99
99
  let _id = req.body.data._id ?? txn
@@ -0,0 +1,46 @@
1
+
2
+ import axios from 'axios'
3
+ import { createClient } from 'redis';
4
+
5
+ // url: 'redis://alice:foobared@localhost:6380'
6
+ const consumer = createClient({ url: 'redis://localhost:6380' });
7
+ await consumer.connect();
8
+ const publisher = createClient({ url: 'redis://localhost:6380' });
9
+ await publisher.connect();
10
+
11
+ consumer.on('error', err => console.log('Redis Client Error', err));
12
+
13
+
14
+ let users_pool = {
15
+
16
+ }
17
+
18
+ async function disconnect(user) {
19
+ delete users_pool[user]
20
+ await consumer.unsubscribe(user);
21
+ }
22
+ async function connect({user,req,res}) {
23
+ users_pool[user] = {req,res}
24
+ await consumer.subscribe(user, (message, channel) => {
25
+ if (users_pool[user])
26
+ users_pool[user].res.write(JSON.stringify({message, channel}) + "\n")
27
+ });
28
+ }
29
+
30
+ export function start(app) {
31
+ app.get('/messages/:user', async (req, res) => {
32
+ await connect({user: req.params.user, req, res})
33
+ req.on("close", async () => await disconnect(req.params.user)) // request closed unexpectedly
34
+ req.on("end", async () => await disconnect(req.params.user)) // request ended normally
35
+ })
36
+ }
37
+
38
+
39
+ export async function publish(channel, message) {
40
+ await publisher.publish(channel, typeof message === "object" ? JSON.stringify(message) : message);
41
+ }
42
+
43
+
44
+
45
+
46
+
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "corebasic",
3
3
  "type": "module",
4
- "version": "1.0.66",
4
+ "version": "1.0.68",
5
5
  "description": "",
6
6
  "main": "index.js",
7
7
  "scripts": {
@@ -15,6 +15,7 @@
15
15
  "axios": "^1.4.0",
16
16
  "jsonminify": "^0.4.2",
17
17
  "jsonwebtoken": "^9.0.1",
18
- "otp-generator": "^4.0.1"
18
+ "otp-generator": "^4.0.1",
19
+ "redis": "^4.6.8"
19
20
  }
20
21
  }