-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
260 lines (236 loc) Β· 9.62 KB
/
Copy pathindex.js
File metadata and controls
260 lines (236 loc) Β· 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/**
* BunStash, a bun-powered logstash-like agent to transform and handle data
* Using Inputs, Filters and Outputs, handle many types of data and transform it
* to new consumers
* (C) 2024 - QXIP BV
*/
/**
* Imports
*/
/**
* Globals
*/
const Globals = {
debug: true, // Set to true to enable debug mode
}
/**
* Type Definitions
*/
/** @typedef {{input:[{module:string}], filter?: [{module:string}], output: [{module:string}]}} ParsedConfig */
/**
* Function to get the configuration file and parse it
* @param {string} configFile Path to the configuration file
* @returns {Promise<ParsedConfig>} Parsed configuration object
* @throws If the configuration file cannot be read or parsed exit with error code 3
*/
async function processConfigFile (configFile) {
try {
let config = Bun.file(configFile, 'utf-8');
/** @type {ParsedConfig} */
let parsedConfig = await config.json();
console.log('π-- Config file found:', parsedConfig);
return parsedConfig;
} catch (error) {
console.error('π«-- Error reading config file:', error);
process.exit(3);
}
}
/**
* Function to check flags and get/create config file
* @returns {Promise<ParsedConfig>} JSON configuration file
*/
async function checkFlags () {
let args = process.argv;
if (args.includes('-h')) {
console.log('π');
console.log('Provide a configuration file via -c or use the -cli option to create it interactively');
console.log('Use the cli if you are new to Bunstash to see what it can do.');
process.exit(0);
}
if (args.includes('-cli')) {
console.log('π§ -- CLI option not yet implemented');
/* Call CLI which interactively creates a config file */
process.exit(0);
}
if (args.includes('-c')) {
let configFile = args[args.indexOf('-c') + 1];
return processConfigFile(configFile);
} else {
console.log('β οΈ -- Provide a config file via -c or use the -cli option to create it interactively');
process.exit(1);
}
}
/**
* Observation Module
*/
const observationModule = {
/**
* Observable Groups
* @type {{input: object[], filter: object[], output: object[]}}}
*/
observableGroups: {
input: [],
filter: [],
output: []
},
/**
* Register modules from the config file
* @param {string} groupName
* @param {object[]} modules
* @returns {boolean} True if modules were registered successfully, false otherwise
* @throws If the group is not valid
*/
registerModules: function (groupName, modules) {
if (Globals.debug) console.log(`Observation Module: π¦ -- Registering modules for group ${groupName}`);
if (!this.observableGroups[groupName]) {
console.error(`π« -- No observable group found with name ${groupName}`);
return false;
}
this.observableGroups[groupName] = this.observableGroups[groupName].concat(modules);
if (Globals.debug) console.log(`Observation Module: π¦ -- Registered ${modules.length} modules for group ${groupName}`);
},
/**
* Array to store subscribed modules
* @type {{input: object[], filter: object[], output: object[]}}
*/
subscribedModules: {
input: [],
filter: [],
output: []
},
/**
*
* @param {string} observerGroup
* @param {object} observer
*/
subscribe: function (observerGroup, observer) {
if (Globals.debug) console.log(`Observation Module: π -- Subscribing ${observer} to ${observerGroup}`);
if (!this.observableGroups[observerGroup]) {
console.error(`π« -- No observable group found with name ${observerGroup}`);
return false;
}
if (!this.subscribedModules[observerGroup]) {
this.subscribedModules[observerGroup] = [];
}
this.subscribedModules[observerGroup].push(observer);
if (Globals.debug) console.log(`Observation Module: π -- Subscribed ${observer} to ${observerGroup}`);
},
/**
* Sending data to all observers in a subscription group
* @param {string} observerGroup
* @param {object} data
*/
emit: function (observerGroup, data) {
this.subscribedModules[observerGroup].forEach(observer => {
if (Globals.debug) console.log(`Observation Module: π€ -- Emitting data to ${observer.module} in group ${observerGroup}`);
observer(data);
})
}
};
const modulesManager = {
/**
* Initialize a module by its name
* @param {string} observerGroup
* @param {object} moduleConfig
* @returns {object} Initialized module
*/
initializeModule: function (observerGroup, moduleConfig) {
if (Globals.debug) console.log(`Modules Manager: π§ -- Initializing module ${moduleConfig.module}`);
try {
const module = require(`./lib/${observerGroup}/${moduleConfig.module}`);
const moduleInstance = new module(moduleConfig);
if (Globals.debug) console.log(`Modules Manager: π§ -- Initialized module ${moduleConfig.module}`);
return moduleInstance;
} catch (error) {
console.error(`π« -- Error initializing module ${moduleConfig.module}:`, error);
throw error;
}
}
}
/**
* Sets up Observable Groups from the config and
* subscribes each item to the appropriate group.
* @param {ParsedConfig} config
* @returns
*/
async function setupObservableGroups (config) {
console.log('π¬-- Setting up Observables');
if (config.input) {
console.log('β‘οΈ -- Input:', config.input);
observationModule.registerModules('input', config.input);
} else {
console.error('π« -- No input observer found. Need at least one.');
process.exit(1);
}
if (config.filter) {
console.log('πͺ€ -- Filter:', config.filter);
observationModule.registerModules('filter', config.filter);
}
if (config.output) {
console.log('β‘οΈ -- Output:', config.output);
observationModule.registerModules('output', config.output);
} else {
console.error('π« -- No output observer found. Need at least one. Try adding "\"stdout\":{}" if you are still testing.');
process.exit(1);
}
console.log('π-- Setting up filter and output observers.');
// Set up filter modules if they exist
if (observationModule.observableGroups.filter && observationModule.observableGroups.filter.length > 0) {
console.log('π -- Connecting filters to input modules');
// Subscribe each filter module to input modules' data events
for (let filterModule of observationModule.observableGroups.filter) {
filterModule = modulesManager.initializeModule('filter', filterModule);
if (filterModule.data) {
observationModule.subscribe('input', filterModule.data);
} else {
console.warn(`β οΈ -- Filter module ${filterModule.module} does not have a data event to process data.`);
console.warn('β οΈ -- Filter modules should implement a data event to process data, otherwise they will not receive data from input modules.');
}
}
// Subscribe output modules to filter modules
console.log('π -- Connecting outputs to filter modules');
for (let outputModule of observationModule.observableGroups.output) {
outputModule = modulesManager.initializeModule('output', outputModule);
if (outputModule.data) {
observationModule.subscribe('filter', outputModule.data);
} else {
console.warn(`β οΈ -- Output module ${outputModule.module} does not have a data event to process data.`);
console.warn('β οΈ -- Output modules should implement a data event to process data, otherwise they will not receive data from filter modules.');
}
}
} else {
// No filters, connect outputs directly to inputs
console.log('π -- No filters, connecting outputs directly to input modules');
for (let outputModule of observationModule.observableGroups.output) {
outputModule = modulesManager.initializeModule('output', outputModule);
if (outputModule.data) {
observationModule.subscribe('input', outputModule.data);
} else {
console.warn(`β οΈ -- Output module ${outputModule.module} does not have a data event to process data.`);
console.warn('β οΈ -- Output modules should implement a data event to process data, otherwise they will not receive data from filter modules.');
}
}
}
console.log('π-- Starting Input Observers');
for (let inputModule of observationModule.observableGroups.input) {
inputModule = modulesManager.initializeModule('input', inputModule);
}
return true;
}
async function main () {
console.log('π Bunstash is a data ingestion, transformation pipeline tool. Come visit us at https://github.com/sipcapture/bunstash \n');
console.log('------------------------------------------------------------------------------------------------------------------------');
let config = await checkFlags();
await setupObservableGroups(config);
}
main();
/**
* Handle interrupt signals (CTRL-C / CMD-C)
* for graceful shutdown
*/
process.on('SIGINT', () => {
console.log('\nπ Interrupt received, shutting down gracefully...');
// Perform any cleanup operations here
console.log('π Goodbye!');
process.exit(0);
});