-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathABBootstrap.js
More file actions
257 lines (220 loc) · 7.48 KB
/
ABBootstrap.js
File metadata and controls
257 lines (220 loc) · 7.48 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
/*
* ABBootstrap
* This object manages preparing an ABFactory for a Specific Tenant.
*/
const queryAllDefinitions = require("./queries/allDefinitions");
// {sql} queryAllDefinitions
// the sql query to load all the Definitions from a specific tenant.
const queryPluginLinks = require("./queries/allPluginLinks");
const Create = require("./queries/definitionCreate");
const Destroy = require("./queries/definitionDestroy");
const Find = require("./queries/definitionFind");
const Update = require("./queries/definitionUpdate");
const ABFactory = require("./ABFactory");
var Factories = {
/* tenantID : { ABFactory }} */
};
// {hash}
// Sort out all known tenant aware factories by tenantID.
var DefinitionManager = {
Create,
Destroy,
Find,
Update,
};
var Listener = null;
// {abServiceSubscriber}
// A Subscriber for the definition.* published messages.
/**
* @function staleHandler()
* handles resetting the ABFactory for the Tenant that just had their
* definitions updated.
* Definitions will be reloaded the next time a relevant request needs
* that tenant's data.
*/
function staleHandler(req) {
var tenantID = req.tenantID();
Factories[tenantID]?.emit("bootstrap.stale.reset");
const knexConn = Factories[tenantID]?.Knex.connection();
if (knexConn) KnexPool[tenantID] = knexConn;
delete Factories[tenantID];
req.log(`:: Definitions reset for tenant[${tenantID}]`);
}
var PendingFactory = {
/* tenantID : Promise */
};
// {hash}
// A lookup of Pending Factory builds. This prevents the SAME factory from
// being built at the same time.
var KnexPool = {
/* tenantID : AB.Knex.connection() */
};
// {hash}
// When definitions are updated, we destroy the existing ABFactory and create
// a new one. However each new ABFactory will create a NEW KNEX DB POOL and
// eventually we use up all our DB Connections ( error: ER_CON_COUNT_ERROR).
// The Knex connection won't change due to the Definition updates, so let's
// cache the KnexPools here and reuse them.
const https = require("http");
const vm = require("vm");
//http://192.168.1.56:8080/assets/ab_plugins/ab-object-netsuite-api/ABObjectNetsuiteAPI.js
//http://web/assets/ab_plugins/ab-object-netsuite-api/ABObjectNetsuiteAPI.js
function requireFromURL(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = "";
res.on("data", (chunk) => {
data += chunk;
});
res.on("end", () => {
try {
const script = new vm.Script(data);
const exports = {};
const module = { exports };
// const context = vm.createContext({ module, exports, require });
const context = vm.createContext({
// Node.js globals
Buffer,
console,
exports,
global: {},
module,
process,
require,
setTimeout,
clearTimeout,
setInterval,
clearInterval,
// Browser globals
fetch,
https,
URL,
// NOTE: when adding these, I start getting errors about not
// being able to find the stream module ...
// so we'll leave them out for now and include them as fallback
// in webpack.common.js config.
// vm,
// crypto,
// stream,
});
/*const exported = */ script.runInContext(context);
// resolve(exported.Plugin || exported.default || exported);
resolve(
module.exports.Plugin ||
module.exports.default ||
module.exports
);
} catch (error) {
console.error(data);
reject(error);
}
});
res.on("error", (error) => {
reject(error);
});
});
});
}
async function loadPlugin(p, newFactory) {
try {
let plgn = await requireFromURL(p.url);
newFactory.pluginRegister(plgn);
} catch (e) {
console.error(`Error loading plugin from ${p.url}:`, e);
}
}
async function setupFactory(req, tenantID) {
let defs = await queryAllDefinitions(req);
if (defs && Array.isArray(defs) && defs.length) {
var hashDefs = {};
defs.forEach((d) => {
hashDefs[d.id] = d;
});
req.log(`Tenant[${tenantID}] Knex pool exists: ${!!KnexPool[tenantID]}`);
var newFactory = new ABFactory(
hashDefs,
DefinitionManager,
req.toABFactoryReq(),
KnexPool[tenantID]
);
newFactory.id = tenantID;
// Reload our ABFactory whenever we detect any changes in
// our definitions. This should result in correct operation
// even though changing definitions become an "expensive"
// operation. (but only for designers)
var resetOnEvents = [
"definition.created",
"definition.destroyed",
"definition.updated",
];
resetOnEvents.forEach((event) => {
newFactory.on(event, () => {
Factories[tenantID]?.emit("bootstrap.stale.reset");
const knexConn = Factories[tenantID]?.Knex.connection();
if (knexConn) KnexPool[tenantID] = knexConn;
delete Factories[tenantID];
});
});
let pluginLinks = await queryPluginLinks(req, {
platform: newFactory.platform,
});
// console.log("::::::::::::::::::::::::");
// console.log(pluginLinks);
let allPluginLoads = [];
pluginLinks.forEach((p) => {
allPluginLoads.push(loadPlugin(p, newFactory));
});
await Promise.all(allPluginLoads);
await newFactory.init();
Factories[tenantID] = newFactory;
delete PendingFactory[tenantID];
return;
}
// if we get here, we had no definitions for this tenant
let errorNoDefinitions = new Error(
`No Definitions returned for tenant[${tenantID}]`
);
req.notify.developer(errorNoDefinitions, {
context: "ABBootstrap.queryAllDefinitions()",
tenantID,
});
throw errorNoDefinitions;
}
module.exports = {
init: async (req) => {
var tenantID = req.tenantID();
if (!tenantID) {
var errorNoTenantID = new Error(
"ABBootstrap.init(): could not resolve tenantID for request"
);
throw errorNoTenantID;
}
if (typeof Factories[tenantID] == "undefined") {
req.log(`:: Loading Definitions for tenant[${tenantID}]`);
if (!PendingFactory[tenantID]) {
PendingFactory[tenantID] = new Promise((resolve, reject) => {
setupFactory(req, tenantID).then(resolve).catch(reject);
});
}
await PendingFactory[tenantID];
}
// initialize Listener if not initialized
if (!Listener) {
// record our stale handler
Listener = req.serviceSubscribe("definition.stale", staleHandler);
// attach staleHandler() to our other Events:
[
"definition.created",
"definition.destroyed",
"definition.updated",
].forEach((e) => {
req.serviceSubscribe(e, staleHandler);
});
}
// return the ABFactory for this tenantID
return Factories[tenantID];
},
resetDefinitions: (req) => {
staleHandler(req);
},
};