samanbayaka 0.0.12 → 0.0.14

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/README.md CHANGED
@@ -30,6 +30,10 @@ This project is a modular, production-ready microservices framework built with M
30
30
  ```bash
31
31
  pnpm install samanbayaka
32
32
  ```
33
+ Once the package is installed, you can import the library using import or require approach:
34
+ ```bash
35
+ import sbk from "samanbayaka"
36
+ ```
33
37
  # Prerequisites
34
38
  It is assumed that NATS, Redpanda, and Redis are installed and properly configured. All services should be discoverable through the /etc/hosts file.
35
39
  #### Minimum required Node.js version: >= 22.x.x
@@ -37,12 +41,35 @@ It is assumed that NATS, Redpanda, and Redis are installed and properly configur
37
41
  node -v
38
42
  nvm use 22
39
43
  ```
44
+ Additionally, OpenObserve is used to view logs and telemetry.
40
45
 
41
46
  #### Environment variables
42
- To configure all required environment variables, copy the <your_project_name>/bash/sbk.sh file into the /etc/profile.d/ directory and update the environment variable values as needed. Before copying, ensure that your current working directory is the project directory.
47
+ To configure all required environment variables, create a Bash file:
48
+ ```bash
49
+ sudo nano /etc/logrotate.d/sbk.sh
50
+ ```
51
+ Paste this:
52
+ ```bash
53
+ ## Configurations files path
54
+ export SBK_CONFIG_PATH=/usr/local/etc/<your_folder>
55
+
56
+ ## Web server port 8760-8769
57
+ export SBK_PORT=8765
58
+
59
+ ## Log level allowed values are fatal | error | warn | info | debug | trace
60
+ export SBK_LOG_LEVEL=info
61
+
62
+ ## Maximum allowed TTL for the memoryLRU (L1) cache; the value is capped at 600 seconds.
63
+ export MAX_L1_TTL=120
64
+
65
+ ## Maximum allowed TTL for the redis (L2) cache; the value is capped at 86400 seconds.
66
+ export MAX_L2_TTL=600
67
+
68
+ ## Enabling telemetry middleware – Set the value to true; the default is false.
69
+ export SBK_TELEMETRY_ENABLE=false
70
+ ```
71
+ Set environment variables in the current Bash session.
43
72
  ```bash
44
- pwd
45
- sudo cp bash/sbk.sh /etc/profile.d/
46
73
  source /etc/profile.d/sbk.sh
47
74
  ```
48
75
  Optionally, you may verify the set environment variables.
@@ -53,14 +80,173 @@ echo $SBK_PORT
53
80
  Create a directory to store the configuration files, then copy all configuration files from the current project path into this directory and update them as needed. Before copying, ensure that your current working directory is the project directory.
54
81
  ```bash
55
82
  pwd
56
- sudo mkdir -p /usr/local/etc/<your_project_name>
57
- sudo cp config/*.*  /usr/local/etc/<your_project_name>
83
+ sudo mkdir -p /usr/local/etc/<your_folder>
84
+ sudo cp config/*.*  /usr/local/etc/<your_folder>
85
+ ```
86
+ #### Log files
87
+ For production, it is recommended to create a new directory named "samanbayaka" under /var/log to store logs.
88
+ ```bash
89
+ sudo mkdir -p /var/log/samanbayaka
90
+ sudo chown -R $USER:$(id -gn) /var/log/samanbayaka
91
+ sudo chmod 755 /var/log/samanbayaka
92
+ ```
93
+ Empty your log files if they become very large, as follows:
94
+ ```bash
95
+ truncate -s 0 /var/log/samanbayaka/sbk-*.log
96
+ ```
97
+ #### Setup logrotate (optional)
98
+ Create config file:
99
+ ```bash
100
+ sudo nano /etc/logrotate.d/sbk
101
+ ```
102
+ Paste this:
103
+ ```bash
104
+ /var/log/samanbayaka/sbk-*.log {
105
+ daily
106
+ rotate 14
107
+ compress
108
+ delaycompress
109
+ missingok
110
+ notifempty
111
+ copytruncate
112
+ create 0640 node node
113
+ }
114
+ ```
115
+
116
+ ## API Docs
117
+
118
+ ### sbk.Errors
119
+
120
+ `sbk.Errors` exposes the Moleculer `Errors` object.
121
+
122
+ ### sbk.getConfig
123
+
124
+ `sbk.getConfig` is a function that returns a configuration object from a specified file name.
125
+
126
+ The file is loaded from the configuration directory defined by the environment variable.
127
+
128
+ ### sbk.loadDemo
129
+
130
+ `sbk.loadDemo` is an asynchronous function that creates a demo service to help understand the project.
131
+
132
+ ### sbk.loadGatewayService
133
+
134
+ `sbk.loadGatewayService` is an asynchronous function that creates a gateway service to expose REST APIs.
135
+
136
+ ### sbk.loadFeatureService
137
+
138
+ `sbk.loadFeatureService` is an asynchronous function that creates a feature service.
139
+
140
+ ##### Function Signature
141
+
142
+ ```js
143
+ sbk.loadFeatureService(schema)
144
+ ```
145
+
146
+ ##### Parameter
147
+
148
+ * `schema` - An object that follows the Moleculer service schema structure.
149
+
150
+ Example:
151
+
152
+ ```js
153
+ {
154
+ name: "math",
155
+ actions: {
156
+ add(ctx) {
157
+ return Number(ctx.params.a) + Number(ctx.params.b);
158
+ },
159
+
160
+ sub(ctx) {
161
+ return Number(ctx.params.a) - Number(ctx.params.b);
162
+ }
163
+ }
164
+ }
165
+ ```
166
+
167
+
168
+ ### sbk.auxBrokerService
169
+
170
+ `sbk.auxBrokerService` is a function used to initialize and manage message brokers such as Kafka, MQTT, and RabbitMQ.
171
+
172
+ ##### Function Signature
173
+
174
+ ```js
175
+ sbk.auxBrokerService(
176
+ type,
177
+ brokerOpts = {},
178
+ callback = () => {}
179
+ )
180
+ ```
181
+ ##### Parameters
182
+
183
+ * `type` *(string)* - Specifies the broker type to initialize. Supported values:
184
+
185
+ * `"kafka"`
186
+ * `"mqtt"`
187
+ * `"amqp"`
188
+
189
+ Example:
190
+
191
+ ```js
192
+ "kafka"
193
+ ```
194
+
195
+
196
+ * `brokerOpts` *(object)* - Configuration object used to initialize the broker client, producer, and consumer. Example structure:
197
+
198
+ ```js
199
+ {
200
+ name: <your_service_name>
201
+ client: {},
202
+ producer: {},
203
+ consumer: {
204
+ groupId: "all",
205
+ interMessageDelayMs: 10,
206
+ },
207
+ logLevel: "INFO",
208
+ gzip: true,
209
+ msgPack: true,
210
+ rest: false,
211
+ }
58
212
  ```
59
213
 
214
+ Configuration Options
215
+
216
+ | Property | Type | Description |
217
+ |---|---|---|
218
+ | `name` | `string` | Only lowercase letters (a–z), digits (0–9), and hyphens (-) are allowed. |
219
+ | `client` | `object` | Broker client configuration |
220
+ | `producer` | `object` | Producer configuration |
221
+ | `consumer` | `object` | Consumer configuration |
222
+ | `consumer.groupId` | `string` | Consumer group identifier is mandatory for the consumer |
223
+ | `consumer.interMessageDelayMs` | `number` | Optional delay between messages in milliseconds |
224
+ | `logLevel` | `string` | Logging level (`NOTHING`, `ERROR`, `WARN`, `INFO`, `DEBUG`), default `NOTHING` |
225
+ | `gzip` | `boolean` | Enables message compression; only GZIP is supported, default `true` |
226
+ | `msgPack` | `boolean` | Enables MessagePack serialization, default `true` |
227
+ | `rest` | `boolean` | Enables REST end point, default `false` |
228
+
229
+
230
+ * `callback` *(function)* - Callback function executed when a message/event is received.
231
+
232
+ Arguments
233
+
234
+ | Argument | Description |
235
+ |---|---|
236
+ | `ctx` | Broker context |
237
+ | `payload` | Incoming message payload |
238
+
239
+ Example:
240
+
241
+ ```js
242
+ (ctx, payload) => {
243
+ ctx.broker.logger.debug(payload)
244
+ }
245
+ ```
60
246
 
61
247
  # Usage
62
- #### Create a service, gateway
63
- The gateway is an important service that exposes all endpoints as REST APIs. At least one Gateway service is mandatory in the project.
248
+ #### Create gateway service
249
+ The Gateway is a critical service that exposes all endpoints as REST APIs. At least one Gateway service must be running to make the REST APIs accessible.
64
250
  ```bash
65
251
  mkdir gateway
66
252
  cd gateway
@@ -69,18 +255,22 @@ pnpm install samanbayaka
69
255
  touch index.mjs
70
256
  ```
71
257
 
72
- Open and edit the index.mjs file as follows
258
+ Open index.mjs and paste the following:
73
259
  ```bash
74
260
  import sbk from "samanbayaka"
75
261
  await sbk.loadGatewayService()
76
262
  ```
77
- Run the service, gateway
263
+ ---
264
+ #### Create feature services
78
265
  ```bash
79
- node index.mjs
266
+ mkdir <your_service_name>
267
+ cd <your_service_name>
268
+ npm init -y
269
+ pnpm install samanbayaka
270
+ touch index.mjs
80
271
  ```
81
272
 
82
-
83
- #### Create your endpoints as a feature service, such as hello
273
+ A feature service, such as `hello`, can be created as follows:
84
274
  ```bash
85
275
  mkdir hello
86
276
  cd hello
@@ -89,10 +279,10 @@ pnpm install samanbayaka
89
279
  touch index.mjs
90
280
  ```
91
281
 
92
- Open and edit the index.mjs file as follows
282
+ Open index.mjs and paste the following:
93
283
  ```bash
94
284
  import sbk from "samanbayaka"
95
- await sbk.loadFeatureService.mainBus({
285
+ await sbk.loadFeatureService({
96
286
  name: "hello",
97
287
  version: "v1",
98
288
 
@@ -109,9 +299,11 @@ await sbk.loadFeatureService.mainBus({
109
299
  cache: {
110
300
 
111
301
  /**
112
- * These cache entries will be expired after 5 seconds instead of 30.
302
+ * Cache entries expire after 30 seconds.
303
+ * For L1 caching, TTL should be defined as [L2_TTL, L1_TTL].
304
+ * Example: ttl: [60, 10] → L2 TTL is 60 seconds and L1 TTL is 10 seconds.
113
305
  */
114
- ttl: 2*60
306
+ ttl: 30
115
307
  },
116
308
  handler(ctx){
117
309
  return "Hello Samanbayaka"
@@ -123,17 +315,109 @@ await sbk.loadFeatureService.mainBus({
123
315
  return `Welcome, ${ctx.params.query?.name || "Guest"} - ${ctx.broker.nodeID}`
124
316
  }
125
317
  },
126
- createUser
127
318
  },
128
319
  })
129
320
 
130
321
  ```
131
- Run the service, hello
322
+ ---
323
+ #### Create auxaliary broker services
324
+ ##### for producer
325
+ ```bash
326
+ mkdir <your_service_name>-<type>-<topic>
327
+ cd <your_service_name>-<type>-<topic>
328
+ npm init -y
329
+ pnpm install samanbayaka
330
+ touch index.mjs
331
+ ```
332
+ An auxiliary service, such as a `producer` that publishes messages to the `STUDENT` topic, can be created as follows:
333
+ ```js
334
+ mkdir producer-kafka-student
335
+ cd producer-kafka-student
336
+ npm init -y
337
+ pnpm install samanbayaka
338
+ touch index.mjs
339
+ ```
340
+
341
+ Open index.mjs and paste the following:
342
+ ```bash
343
+ import sbk from "samanbayaka"
344
+ await sbk.auxBrokerService(
345
+ "kafka",
346
+ {
347
+ name: "producer-kafka-student",
348
+ rest: true,
349
+ ...
350
+ },
351
+ () => {}
352
+ )
353
+ ```
354
+ In the service configuration `name` end with "`*`" i.e. `producer-kafka-student*` can capable to publish to the all topics start with `STUDENT` like `STUDENT.SCIENCE`, `STUDENT.ARTS` etc.
355
+ ```js
356
+ name: "producer-kafka-student*"
357
+ ```
358
+
359
+ If you do not expose the service as a REST API and run it as a private/internal service, either remove the `rest` property or set it to `false`.
360
+ ```js
361
+ rest: false
362
+ ```
363
+
364
+ ##### for consumer
365
+ ```bash
366
+ mkdir <your_service_name>-<type>-<topic>-<group>
367
+ cd <your_service_name>-<type>-<topic>-<group>
368
+ npm init -y
369
+ pnpm install samanbayaka
370
+ touch index.mjs
371
+ ```
372
+ An auxiliary service, such as a `consumer` that subscribe messages from the `STUDENT` topic having group name `junior`, can be created as follows:
373
+ ```js
374
+ mkdir producer-kafka-student-junior
375
+ cd producer-kafka-student-junior
376
+ npm init -y
377
+ pnpm install samanbayaka
378
+ touch index.mjs
379
+ ```
380
+ Open index.mjs and paste the following:
381
+ ```bash
382
+ import sbk from "samanbayaka"
383
+ await sbk.auxBrokerService(
384
+ "kafka",
385
+ {
386
+ name: "consumer-kafka-student",
387
+ consumer: {
388
+ groupId: "junior",
389
+ interMessageDelayMs: 10,
390
+ ...
391
+ },
392
+ ...
393
+ },
394
+ () => {}
395
+ )
396
+ ```
397
+ The `interMessageDelayMs` option introduces a delay between two consecutive message/event consumptions, measured in milliseconds. If you do not need any delay between message consumption, simply remove the `interMessageDelayMs` property from the consumer options.
398
+
399
+
400
+ ---
401
+
402
+ #### Run the services
403
+
404
+ * development/testing
132
405
  ```bash
406
+ cd <your_path>/gateway
133
407
  node index.mjs
408
+ cd <your_path>/hello
409
+ node index.mjs
410
+ ```
411
+ * production
412
+ ```bash
413
+ cd <your_path>/gateway
414
+ node index.mjs >> /var/log/samanbayaka/sbk-${HOSTNAME}-$$.log 2>&1
415
+ cd <your_path>/hello
416
+ node index.mjs >> /var/log/samanbayaka/sbk-${HOSTNAME}-$$.log 2>&1
134
417
  ```
418
+
135
419
  # Demo
136
- You can also run the demo service to better understand how the system works.
420
+ You can also run the demo service to better understand how microservices work in the Moleculer ecosystem and how REST APIs are exposed.
137
421
  ```bash
138
422
  mkdir demo
139
423
  cd demo
@@ -151,9 +435,6 @@ Run the service, demo
151
435
  node demo.mjs
152
436
  ```
153
437
 
154
-
155
-
156
-
157
438
  <p align="center" style="margin-top: 100px;">
158
439
  <img src="https://moleculer.services/images/banner.png" alt="Moleculer Logo" width="600">
159
440
  </p>
package/commit-hash.mjs CHANGED
@@ -1 +1 @@
1
- export const COMMIT_HASH = '3290420';
1
+ export const COMMIT_HASH = '782e7c8';
@@ -0,0 +1,27 @@
1
+ /*catcher.mjs*/
2
+ export default {
3
+ /**
4
+ * Maximum items
5
+ */
6
+ max: 200,
7
+
8
+ /**
9
+ * Time-to-Live in seconds
10
+ */
11
+ ttl: [600, 120],
12
+
13
+ redis: {
14
+ /**
15
+ * Turns Redis client monitoring on.
16
+ */
17
+ monitor: false,
18
+
19
+ /**
20
+ * Redis settings like hostname, port, password
21
+ */
22
+ host: "redis",
23
+ port: 6379,
24
+ // password: "1234",
25
+ // db: 0,
26
+ }
27
+ }
@@ -1,54 +1,66 @@
1
- /*kafkajs.mjs*/
2
- // export default Object.freeze({
3
- // prefix: "SBK",
4
- // client: {
5
- // clientId: "moleculer-kafkajs",
6
- // brokers: ["redpanda:9092"],
7
- // connectionTimeout: 3000,
8
- // requestTimeout: 25000,
9
- // enforceRequestTimeout: false,
10
- // retry: {
11
- // maxRetryTime: 30000,
12
- // initialRetryTime: 300,
13
- // factor: 0.2,
14
- // multiplier: 2,
15
- // retries: 5
16
- // },
17
- // producer: {
18
- // idempotent: true,
19
- // maxInFlightRequests: 1,
20
- // },
21
- // logLevel: "INFO",
22
- // }
23
- // })
24
-
25
-
26
- export default Object.freeze({
27
- type: "Kafka",
28
- options: {
29
- // host: "localhost:9092", // Your Kafka broker address
30
- client: {
31
- clientId: "moleculer-cluster",
32
- brokers: ["redpanda:9092"],
33
- connectionTimeout: 3000,
34
- requestTimeout: 25000,
35
- enforceRequestTimeout: false,
36
- retry: {
37
- maxRetryTime: 30000,
38
- initialRetryTime: 300,
39
- factor: 0.2,
40
- multiplier: 2,
41
- retries: 5
42
- }
1
+ export default {
2
+ client: {
3
+ clientId: "node-client123",
4
+ brokers: ["pnsntst.wbsedcl.in:9092"],
5
+ connectionTimeout: 20000,
6
+ requestTimeout: 20000,
7
+ enforceRequestTimeout: true,
8
+ retry: {
9
+ maxRetryTime: 60000,
10
+ initialRetryTime: 300,
11
+ factor: 0.2,
12
+ multiplier: 2,
13
+ retries: 5
43
14
  },
44
- producer: {
45
- idempotent: true,
46
- maxInFlightRequests: 1,
15
+ ssl: {
16
+ rejectUnauthorized: true,
47
17
  },
48
- consumer: {
49
- groupId: "moleculer-group"
18
+ sasl: {
19
+ mechanism: "scram-sha-256",
20
+ username: "bob",
21
+ password: "SUhcznwt0xopsTfDXKIPzgw66dzJpZ",
22
+ },
23
+ },
24
+ producer: {
25
+ retry: {
26
+ initialRetryTime: 300,
27
+ // retries: Number.MAX_SAFE_INTEGER
28
+ retries: 8,
29
+ maxRetryTime: 30000,
30
+ factor: 0.2,
31
+ multiplier: 2
50
32
  },
51
- logLevel: "INFO",
52
- }
53
- // Ensure protocol v5 is active (default in 0.15.0-beta1)
54
- })
33
+ metadataMaxAge: 300000,
34
+ allowAutoTopicCreation: false,
35
+ transactionTimeout: 30000,
36
+ idempotent: true,
37
+ maxInFlightRequests: 1,
38
+ },
39
+ consumer: {
40
+ groupId: "default",
41
+ // partitionAssigners: <Array>,
42
+ sessionTimeout: 30000,
43
+ rebalanceTimeout: 60000,
44
+ heartbeatInterval: 5000,
45
+ metadataMaxAge: 300000,
46
+ allowAutoTopicCreation: false,
47
+ maxBytesPerPartition: 1048576, // 1 MB
48
+ minBytes: 1,
49
+ maxBytes: 10485760, // 10 MB
50
+ maxWaitTimeInMs: 5000,
51
+ retry: {
52
+ initialRetryTime: 300,
53
+ retries: 8,
54
+ maxRetryTime: 30000,
55
+ factor: 0.2,
56
+ multiplier: 2
57
+ },
58
+ maxInFlightRequests: 1,
59
+ // rackId: <String>,
60
+ // interMessageDelayMs: 10,
61
+ },
62
+ logLevel: "INFO",
63
+ gzip: true,
64
+ msgPack: true,
65
+ rest: false,
66
+ }