This repository was archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.js
406 lines (333 loc) · 12.1 KB
/
utils.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
const { resolve, join } = require('path')
const { pick, isEmpty, path, uniq } = require('ramda')
const { Graph, alg } = require('graphlib')
const traverse = require('traverse')
const { utils } = require('@serverless/core')
const newMetric = require('@serverless/component-metrics')
const getComponentMetric = async (componentPath, componentMethod = 'default', instance) => {
const metric = newMetric()
metric.componentMethod(componentMethod)
metric.componentContext(instance.context.instance.name || 'cli_declarative')
metric.componentContextVersion(instance.context.instance.version || '1.0.0')
metric.componentError(null)
let componentName = componentPath
let componentVersion
const componentPackageJsonPath = join(componentPath, 'package.json')
// if package.json exists, read it to get name & version
if (await utils.fileExists(componentPackageJsonPath)) {
const componentPackageJson = await utils.readFile(componentPackageJsonPath)
componentName = componentPackageJson.name || componentPath
componentVersion = componentPackageJson.version
}
metric.componentName(componentName)
if (componentVersion) {
metric.componentVersion(componentVersion)
}
// we only publish after the method is run
// to check whether there was an error
return metric
}
const getOutputs = (allComponents) => {
const outputs = {}
for (const alias in allComponents) {
outputs[alias] = allComponents[alias].outputs
}
return outputs
}
const resolveObject = (object, context) => {
const regex = /\${(\w*:?[\w\d.-]+)}/g
const resolvedObject = traverse(object).forEach(function(value) {
const matches = typeof value === 'string' ? value.match(regex) : null
if (matches) {
let newValue = value
for (const match of matches) {
const referencedPropertyPath = match.substring(2, match.length - 1).split('.')
const referencedPropertyValue = path(referencedPropertyPath, context)
if (referencedPropertyValue === undefined) {
throw Error(`invalid reference ${match}`)
}
if (match === value) {
newValue = referencedPropertyValue
} else if (typeof referencedPropertyValue === 'string') {
newValue = newValue.replace(match, referencedPropertyValue)
} else {
throw Error(`the referenced substring is not a string`)
}
}
this.update(newValue)
}
})
return resolvedObject
}
const validateGraph = (graph) => {
const isAcyclic = alg.isAcyclic(graph)
if (!isAcyclic) {
const cycles = alg.findCycles(graph)
let msg = ['Your template has circular dependencies:']
cycles.forEach((cycle, index) => {
let fromAToB = cycle.join(' --> ')
fromAToB = `${(index += 1)}. ${fromAToB}`
const fromBToA = cycle.reverse().join(' <-- ')
const padLength = fromAToB.length + 4
msg.push(fromAToB.padStart(padLength))
msg.push(fromBToA.padStart(padLength))
}, cycles)
msg = msg.join('\n')
throw new Error(msg)
}
}
const getTemplate = async (inputs) => {
const template = inputs.template || {}
if (typeof template === 'string') {
if (
(!utils.isJsonPath(template) && !utils.isYamlPath(template)) ||
!(await utils.fileExists(template))
) {
throw Error('the referenced template path does not exist')
}
return utils.readFile(template)
} else if (typeof template !== 'object') {
throw Error('the template input could either be an object, or a string path to a template file')
}
return template
}
const resolveTemplate = (template) => {
const regex = /\${(\w*:?[\w\d.-]+)}/g
let variableResolved = false
const resolvedTemplate = traverse(template).forEach(function(value) {
const matches = typeof value === 'string' ? value.match(regex) : null
if (matches) {
let newValue = value
for (const match of matches) {
const referencedPropertyPath = match.substring(2, match.length - 1).split('.')
const referencedTopLevelProperty = referencedPropertyPath[0]
if (/\${env\.(\w*:?[\w\d.-]+)}/g.test(match)) {
newValue = process.env[referencedPropertyPath[1]]
variableResolved = true
} else {
if (!template[referencedTopLevelProperty]) {
throw Error(`invalid reference ${match}`)
}
if (!template[referencedTopLevelProperty].component) {
variableResolved = true
const referencedPropertyValue = path(referencedPropertyPath, template)
if (referencedPropertyValue === undefined) {
throw Error(`invalid reference ${match}`)
}
if (match === value) {
newValue = referencedPropertyValue
} else if (typeof referencedPropertyValue === 'string') {
newValue = newValue.replace(match, referencedPropertyValue)
} else {
throw Error(`the referenced substring is not a string`)
}
}
}
}
this.update(newValue)
}
})
if (variableResolved) {
return resolveTemplate(resolvedTemplate)
}
return resolvedTemplate
}
const getAllComponents = async (obj = {}) => {
const allComponents = {}
for (const key in obj) {
if (obj[key] && obj[key].component) {
// local components start with a .
if (obj[key].component[0] === '.') {
// todo should local component paths be relative to cwd?
const localComponentPath = resolve(process.cwd(), obj[key].component, 'serverless.js')
if (!(await utils.fileExists(localComponentPath))) {
throw Error(`No serverless.js file found in ${obj[key].component}`)
}
}
allComponents[key] = {
path: obj[key].component,
inputs: obj[key].inputs || {}
}
}
}
return allComponents
}
const downloadComponents = async (allComponents) => {
// npm components property does not start with a period.
// ie. local components component property is ./abc or ../abc
const aliasesToDownload = Object.keys(allComponents).filter(
(alias) => allComponents[alias].path[0] !== '.'
)
const componentsToDownload = pick(aliasesToDownload, allComponents)
// using uniq to remove any duplicates in case
// the user is using multiple instances of the same
// component, so that it would be downloaded only once
const componentsList = uniq(aliasesToDownload.map((alias) => componentsToDownload[alias].path))
const componentsPaths = await utils.download(componentsList)
const downloadedComponents = {}
for (const alias in componentsToDownload) {
const npmPackageName = componentsToDownload[alias].path
downloadedComponents[alias] = {
...componentsToDownload[alias],
path: componentsPaths[npmPackageName]
}
}
allComponents = { ...allComponents, ...downloadedComponents }
return allComponents
}
const setDependencies = (allComponents) => {
const regex = /\${(\w*:?[\w\d.-]+)}/g
for (const alias in allComponents) {
const dependencies = traverse(allComponents[alias].inputs).reduce(function(accum, value) {
const matches = typeof value === 'string' ? value.match(regex) : null
if (matches) {
for (const match of matches) {
const referencedComponent = match.substring(2, match.length - 1).split('.')[0]
if (!allComponents[referencedComponent]) {
throw Error(`the referenced component in expression ${match} does not exist`)
}
if (!accum.includes(referencedComponent)) {
accum.push(referencedComponent)
}
}
}
return accum
}, [])
allComponents[alias].dependencies = dependencies
}
return allComponents
}
const createGraph = (allComponents) => {
const graph = new Graph()
for (const alias in allComponents) {
graph.setNode(alias, allComponents[alias])
}
for (const alias in allComponents) {
const { dependencies } = allComponents[alias]
if (!isEmpty(dependencies)) {
for (const dependency of dependencies) {
graph.setEdge(alias, dependency)
}
}
}
validateGraph(graph)
return graph
}
const executeGraph = async (allComponents, graph, instance) => {
const leaves = graph.sinks()
if (isEmpty(leaves)) {
return allComponents
}
const promises = []
for (const alias of leaves) {
const componentData = graph.node(alias)
const fn = async () => {
const component = await instance.load(componentData.path, alias)
const availableOutputs = getOutputs(allComponents)
const inputs = resolveObject(allComponents[alias].inputs, availableOutputs)
instance.context.status('Deploying', alias)
const metric = await getComponentMetric(componentData.path, 'default', instance)
try {
allComponents[alias].outputs = (await component(inputs)) || {}
} catch (e) {
// on error, publish error metric
metric.componentError(e.message)
await metric.publish()
throw e
}
await metric.publish()
}
promises.push(fn())
}
await Promise.all(promises)
for (const alias of leaves) {
graph.removeNode(alias)
}
return executeGraph(allComponents, graph, instance)
}
const syncState = async (allComponents, instance) => {
const promises = []
for (const alias in instance.state.components || {}) {
if (!allComponents[alias]) {
const fn = async () => {
const component = await instance.load(instance.state.components[alias], alias)
instance.context.status('Removing', alias)
const metric = await getComponentMetric(
instance.state.components[alias],
'remove',
instance
)
try {
await component.remove()
} catch (e) {
// on error, publish error metric
metric.componentError(e.message)
await metric.publish()
throw e
}
await metric.publish()
}
promises.push(fn())
}
}
await Promise.all(promises)
instance.state.components = {}
for (const alias in allComponents) {
instance.state.components[alias] = allComponents[alias].path
}
await instance.save()
}
const createCustomMethodHandler = (instance, method) => {
return async ({ component, template, ...inputs }) => {
let components = Array.isArray(component) ? component : [component]
components = components.filter(Boolean)
if (!components.length) {
throw Error(`"component" input is required to run custom methods`)
}
instance.context.debug(
`Attempting to run method "${method}" on template aliases: ${components.join(', ')}`
)
// Make sure the template is an object
const templateObject = await getTemplate({ template })
// Load template components
const templateComponents = await getAllComponents(templateObject)
// Get only the requested components ("component" input)
const componentsToRun = Object.keys(templateComponents)
.filter((alias) => components.includes(alias))
.reduce((acc, item) => {
acc.push({ alias: item, path: templateComponents[item].path })
return acc
}, [])
// Verify all the components have the requested method implemented
instance.context.debug(`Verifying presence of method "${method}" in requested components...`)
for (let i = 0; i < componentsToRun.length; i++) {
const item = componentsToRun[i]
const cmp = await instance.load(item.path, item.alias)
if (typeof cmp[method] !== 'function') {
throw Error(`method "${method}" not found in "${item.path}"`)
}
// Store the loaded component so we don't have to load it again
componentsToRun[i].component = cmp
}
// Run custom method and return output
const outputs = {}
for (let i = 0; i < componentsToRun.length; i++) {
const cmp = componentsToRun[i]
instance.context.debug(`Running method "${method}" on "${cmp.path}"...`)
outputs[cmp.alias] = await cmp.component[method](inputs)
}
return outputs
}
}
module.exports = {
getTemplate,
resolveTemplate,
getAllComponents,
downloadComponents,
setDependencies,
createGraph,
executeGraph,
syncState,
getOutputs,
createCustomMethodHandler
}