-
Notifications
You must be signed in to change notification settings - Fork 26
/
Async2SyncModel.js
287 lines (248 loc) · 10.6 KB
/
Async2SyncModel.js
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**************************************************************************
* (C) Copyright ModusBox Inc. 2021 - All rights reserved. *
* *
* This file is made available under the terms of the license agreement *
* specified in the corresponding source code repository. *
* *
* ORIGINAL AUTHOR: *
* Paweł Marzec - pawel.marzec@modusbox.com *
**************************************************************************/
'use strict';
const util = require('util');
const PSM = require('./common').PersistentStateMachine;
const { SDKStateEnum } = require('./common');
const MojaloopRequests = require('@mojaloop/sdk-standard-components').MojaloopRequests;
const deferredJob = require('./lib').deferredJob;
function generate({
/**
* @name channelNameMethod
* @description generates the pub/sub channel name
* @param {object} args - the arguments passed as object, same as passed to `run, triggerDeferredJob, generateKey` method
* @returns {string} - the pub/sub channel name
*/
channelNameMethod,
/**
* @name requestActionMethod
* @description invokes the call to switch
* @param {object} requests - MojaloopRequests instance
* @param {array} args - the arguments passed as object to `run` method
*/
requestActionMethod,
/**
* @name argsValidationMethod
* @description makes validation of args object, invoked in `run, triggerDeferredJob, generateKey` methods to ensure everything is going well
* @param {object} requests - MojaloopRequests instance
* @param {array} args - the arguments passed as object to `run` method
*/
argsValidationMethod,
/**
* @name reformatMessageMethod
* @description reformats message received from PUB/SUB channel, it is optional method, if not specified identify function is used by default
* @param {object} message - message received
* @returns {object} - reformatted message
*/
reformatMessageMethod,
// the name of the model, used for logging
modelName
}) {
// don't reformat message if method not specified
const reformatMessage = reformatMessageMethod || ((m) => m);
const specStateMachine = {
init: 'start',
transitions: [
{ name: 'init', from: 'none', to: 'start' },
{ name: 'requestAction', from: 'start', to: 'succeeded' },
{ name: 'error', from: '*', to: 'errored' },
],
methods: {
// workflow methods
run,
getResponse,
// specific transitions handlers methods
onRequestAction
}
};
/**
* @name run
* @description run the workflow logic
* @param {arguments} args - arguments
* @returns {Object} - the http response payload
*/
async function run(args) {
// input validation, it should throws if any of args is invalid
argsValidationMethod(args);
const { data, logger } = this.context;
try {
// run transitions based on incoming state
switch (data.currentState) {
case 'start':
// the first transition is requestAction
await this.requestAction(args);
// don't await to finish the save
this.saveToCache();
// eslint-disable-next-line no-fallthrough
case 'succeeded':
// all steps complete so return
logger.log('Action called successfully');
return this.getResponse();
case 'errored':
// stopped in errored state
logger.log('State machine in errored state');
return;
}
} catch (err) {
logger.log(`Error running ${modelName} model: ${util.inspect(err)}`);
// as this function is recursive, we don't want to error the state machine multiple times
if (data.currentState !== 'errored') {
// err should not have a requestActionState property here!
if (err.requestActionState) {
logger.log('State machine is broken');
}
// transition to errored state
await this.error(err);
// avoid circular ref between requestActionState.lastError and err
err.requestActionState = structuredClone(this.getResponse());
}
throw err;
}
}
const mapCurrentState = {
start: SDKStateEnum.WAITING_FOR_ACTION,
succeeded: SDKStateEnum.COMPLETED,
errored: SDKStateEnum.ERROR_OCCURRED
};
/**
* @name getResponse
* @description returns the http response payload depending on which state machine is
* @returns {Object} - the http response payload
*/
function getResponse() {
const { data, logger } = this.context;
let resp = { ...data };
// project some of our internal state into a more useful
// representation to return to the SDK API consumer
resp.currentState = mapCurrentState[data.currentState];
// handle unexpected state
if (!resp.currentState) {
logger.error(`${modelName} model response being returned from an unexpected state: ${data.currentState}. Returning ERROR_OCCURRED state`);
resp.currentState = mapCurrentState.errored;
}
return resp;
}
/**
* @name onRequestAction
* @description generates the pub/sub channel name
* @param {object} args - the arguments passed as object
* @returns {string} - the pub/sub channel name
*/
async function onRequestAction(fsm, args) {
const { cache, logger } = this.context;
const { requests, config } = this.handlersContext;
logger.push({ args }).log('onRequestAction - arguments');
return deferredJob(cache, channelNameMethod(args))
.init(async (channel) => {
const res = await requestActionMethod(requests, args);
logger.push({ res, channel, args }).log('RequestAction call sent to peer, listening on response');
return res;
})
.job((message) => {
this.context.data = {
...reformatMessage(message),
currentState: this.state
};
logger.push({ message }).log('requestActionMethod message received');
})
.wait(config.requestProcessingTimeoutSeconds * 1000);
}
/**
*
* @param {object} cache - the cache instance used to publish message
* @param {object} message - the message used to trigger deferred job
* @param {object} args - args passed to channelNameMethod
* @returns {Promise} - the promise which resolves when deferred job is invoked
*/
async function triggerDeferredJob({ cache, message, args }) {
// input validation, it should throws if any of args is invalid
argsValidationMethod(args);
const cn = channelNameMethod(args);
return deferredJob(cache, cn).trigger(message);
}
/**
* @name generateKey
* @description generates the cache key used to store state machine
* @param {object} args - args passed to channelNameMethod
* @returns {string} - the cache key
*/
function generateKey(args) {
// input validation, it should throws if any of args is invalid
argsValidationMethod(args);
return `key-${channelNameMethod(args)}`;
}
/**
* @name injectHandlersContext
* @description injects the config into state machine data, so it will be accessible to on transition notification handlers via `this.handlersContext`
* @param {Object} config - config to be injected into state machine data
* @returns {Object} - the altered specStateMachine
*/
function injectHandlersContext(config) {
return {
...specStateMachine,
data: {
handlersContext: {
modelName,
config: { ...config }, // injects config property
requests: new MojaloopRequests({
logger: config.logger,
peerEndpoint: config.peerEndpoint,
alsEndpoint: config.alsEndpoint,
quotesEndpoint: config.quotesEndpoint,
transfersEndpoint: config.transfersEndpoint,
transactionRequestsEndpoint: config.transactionRequestsEndpoint,
dfspId: config.dfspId,
tls: {
enabled: config.outbound.tls.mutualTLS.enabled,
creds: config.outbound.tls.creds,
},
jwsSign: config.jwsSign,
jwsSignPutParties: config.jwsSignPutParties,
jwsSigningKey: config.jwsSigningKey,
wso2: config.wso2
})
}
}
};
}
/**
* @name create
* @description creates a new instance of state machine specified in specStateMachine ^
* @param {Object} data - payload data
* @param {String} key - the cache key where state machine will store the payload data after each transition
* @param {Object} config - the additional configuration for transition handlers
*/
async function create(data, key, config) {
const spec = injectHandlersContext(config, specStateMachine);
return PSM.create(data, config.cache, key, config.logger, spec);
}
/**
* @name loadFromCache
* @description loads state machine from cache by given key and specify the additional config for transition handlers
* @param {String} key - the cache key used to retrieve the state machine from cache
* @param {Object} config - the additional configuration for transition handlers
*/
async function loadFromCache(key, config) {
const customCreate = async (data, _cache, key) => create(data, key, config);
return PSM.loadFromCache(config.cache, key, config.logger, specStateMachine, customCreate);
}
return {
channelName: channelNameMethod,
triggerDeferredJob,
create,
generateKey,
loadFromCache,
// exports for testing purposes
mapCurrentState
};
}
module.exports = {
generate
};