-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp-code-versions.js
More file actions
318 lines (294 loc) · 11.8 KB
/
app-code-versions.js
File metadata and controls
318 lines (294 loc) · 11.8 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
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
'use strict'
/**
* App Code Version API
* @module rest/contexts/versions/app-code-versions
*/
var express = require('express')
var app = module.exports = express()
var mw = require('dat-middleware')
var flow = require('middleware-flow')
var find = require('101/find')
var hasProps = require('101/has-properties')
var hasKeypaths = require('101/has-keypaths')
var isString = require('101/is-string')
var keypather = require('keypather')()
var last = require('101/last')
var Boom = mw.Boom
var ContextService = require('models/services/context-service')
var ContextVersionService = require('models/services/context-version-service')
var InfraCodeVersionService = require('models/services/infracode-version-service')
var validations = require('middlewares/validations')
var isObjectId = validations.isObjectId
var optimus = require('@runnable/optimus/client')
var ContextVersion = require('models/mongo/context-version')
const errorMessages = require('errors/frontend-error-messages')
var findContext = function (req, res, next) {
ContextService.findContextAndAssertAccess(req.params.contextId, req.sessionUser)
.tap(function (context) {
req.context = context
})
.asCallback(function (err) {
next(err)
})
}
var findContextVersion = flow.series(
function (req, res, next) {
ContextVersionService.findContextVersion(keypather.get(req, 'params.versionId'))
.tap(function (contextVersion) {
req.contextVersion = contextVersion
})
.asCallback(function (err) {
next(err)
})
},
mw('contextVersion')('build.completed').require()
.then(mw.next(Boom.badRequest('Cannot modify a built version.'))),
mw('contextVersion')('build.started').require()
.then(mw.next(Boom.badRequest('Cannot modify an in progress version.'))))
var findInfraCodeVersion = function (req, res, next) {
var id = keypather.get(req, 'contextVersion.infraCodeVersion')
InfraCodeVersionService.findInfraCodeVersion(id, { files: 0 })
.tap(function (infraCodeVersion) {
req.infraCodeVersion = infraCodeVersion
})
.asCallback(function (err) {
next(err)
})
}
/** Push a gitRepo to a {@link module:models/version Version}
* @param {ObjectId} contextId ID of the {@link module:models/context Context}
* @param {ObjectId} id ID of the {@link module:models/version Version}
* @param {body.repo}
* @param {body.branch}
* @param {body.commit}
* @returns {object} The Context along with containers that it built
* @event POST rest/contexts/:contextId/versions/:id/appCodeVersions
* @memberof module:rest/contexts/versions/app-code-versions */
app.post('/contexts/:contextId/versions/:versionId/appCodeVersions',
findContext,
findContextVersion,
mw.body('repo').require().string(),
mw.body('branch').require().string(),
mw.body('commit').require().then(mw.body('commit').string()),
mw.body('useLatest').require().then(mw.body('useLatest').boolean()),
function (req, res, next) {
ContextVersion.addGithubRepoToVersion(
req.sessionUser,
req.params.versionId,
req.body
)
.then(function () {
return ContextVersion.findByIdAsync(req.params.versionId)
})
.then(function (contextVersion) {
var acvs = contextVersion ? contextVersion.appCodeVersions : []
var acv = find(acvs, hasProps({
lowerRepo: keypather.get(req, 'body.repo.toLowerCase()')
}))
res.status(201).json(acv)
})
.catch(ContextVersion.DeployKeyError, err => {
throw Boom.badImplementation(errorMessages.contextVersions.create.deployKey, { err })
})
.catch(function (err) {
next(err)
})
})
/** Update an appCodeVersion (gitRepo) for a {@link module:models/version Version}
* @param {ObjectId} contextId ID of the {@link module:models/context Context}
* @param {ObjectId} versionId ID of the {@link module:models/version Version}
* @param {ObjectId} id ID of the appCodeVersion
* @param {body.repo} [branch] update the branch of an existing repo
* @param {body.commit} [commit] update the commit of an existing repo
* @event POST rest/contexts/:contextId/versions/:id/appCodeVersions
* @memberof module:rest/contexts/versions/app-code-versions */
app.patch('/contexts/:contextId/versions/:versionId/appCodeVersions/:appCodeVersionId',
findContext,
findContextVersion,
mw.params('contextId', 'versionId', 'appCodeVersionId').validate(isObjectId),
mw.body('branch').require().then(mw.body('branch').string()),
mw.body('commit').require().then(mw.body('commit').string()),
mw.body({ or: [ 'branch', 'commit', 'transformRules', 'useLatest' ] }).require().pick(),
function (req, res, next) {
req.contextVersion.modifyAppCodeVersionAsync(keypather.get(req, 'params.appCodeVersionId'), req.body)
.then(function (contextVersion) {
var acvs = contextVersion ? contextVersion.appCodeVersions : []
var acv = find(acvs, hasKeypaths({
'_id.toString()': keypather.get(req, 'params.appCodeVersionId.toString()')
}))
res.status(200).json(acv)
})
.catch(function (err) {
next(err)
})
})
/** Delete an appCodeVersion (gitRepo) for a {@link module:models/version Version}
* @param {ObjectId} contextId ID of the {@link module:models/context Context}
* @param {ObjectId} versionId ID of the {@link module:models/version Version}
* @param {ObjectId} id ID of the appCodeVersion
* @event POST rest/contexts/:contextId/versions/:id/appCodeVersions
* @memberof module:rest/contexts/versions/app-code-versions */
app.delete('/contexts/:contextId/versions/:versionId/appCodeVersions/:appCodeVersionId',
findContext,
findContextVersion,
mw.params('contextId', 'versionId', 'appCodeVersionId').validate(isObjectId),
function (req, res, next) {
req.contextVersion.pullAppCodeVersionAsync(keypather.get(req, 'params.appCodeVersionId'))
.asCallback(function (err) {
next(err)
})
},
mw.res.send(204))
/* jshint maxlen: false */
/**
* Use Optimus to get the results of the transformation rules for an
* appCodeVersion.
* @param {ObjectId} contextId ID of the {@link module:models/context Context}
* @param {ObjectId} versionId ID of the {@link module:models/version Version}
* @param {ObjectId} id ID of the appCodeVersion
* @event POST rest/contexts/:contextId/versions/:id/appCodeVersions/:appcodeVersionId/actions/applyTransformRules
* @memberof module:rest/contexts/versions/app-code-versions
*/
app.post('/contexts/:contextId/versions/:versionId/appCodeVersions/:appCodeVersionId/actions/applyTransformRules',
findContext,
findContextVersion,
findInfraCodeVersion,
function applyTransformRules (req, res, next) {
var contextVersion = req.contextVersion
// TODO This may change in the future, assuming only one for now.
var appCodeVersion = ContextVersion
.getMainAppCodeVersion(contextVersion.appCodeVersions)
var infraCodeVersion = req.infraCodeVersion
// Construct the fs-transform rule set
var exclude = appCodeVersion.transformRules.exclude
var replace = appCodeVersion.transformRules.replace
var rename = appCodeVersion.transformRules.rename
var rules = []
if (exclude.length > 0) {
rules.push({ action: 'exclude', files: exclude })
}
rules = rules.concat(replace, rename)
// Ask mighty optimus for the results...
optimus.transform(
{
// optimus does not assume that it is coming from github should it?
repo: `git@${process.env.GITHUB_HOST}:${appCodeVersion.repo}`,
commitish: appCodeVersion.commit,
rules: rules,
deployKey: appCodeVersion.privateKey
},
handleOptimusError(next, function (response) {
var fullpath = '/translation_rules.sh'
infraCodeVersion.upsertFs(fullpath, response.body.script, function (err) {
if (err) {
return next(Boom.create(504, err.message, err))
}
res.json(response.body)
})
})
)
})
/**
* Tests a single transform rule and responds with what it changes.
* @param {ObjectId} contextId ID of the {@link module:models/context Context}
* @param {ObjectId} versionId ID of the {@link module:models/version Version}
* @param {ObjectId} id ID of the appCodeVersion
* @event POST rest/contexts/:contextId/versions/:id/appCodeVersions/:appcodeVersionId/actions/applyTransformRules
* @memberof module:rest/contexts/versions/app-code-versions
*/
app.post('/contexts/:contextId/versions/:versionId/appCodeVersions/:appCodeVersionId/actions/testTransformRule',
findContext,
findContextVersion,
/* jshint maxcomplexity:7 */
function testTransformRule (req, res, next) {
// Validate that the given rule conforms to our expectations
var testRule = req.body
if (!isString(testRule.action)) {
return next(Boom.badRequest(
'Supplied transformation rule requires an action attribute.'
))
}
if (testRule.action !== 'rename' && testRule.action !== 'replace') {
return next(Boom.badRequest(
'Invalid action "' + testRule.action + '" given' +
' for test rule. Expected "rename" or "replace".'
))
}
// Get required information to build a partial rule set
var contextVersion = req.contextVersion.toJSON()
var appCodeVersion = ContextVersion
.getMainAppCodeVersion(contextVersion.appCodeVersions)
var transformRules = appCodeVersion.transformRules
var exclude = transformRules.exclude
var replace = transformRules.replace
var rename = transformRules.rename
var rules = []
if (exclude.length > 0) {
rules.push({ action: 'exclude', files: exclude })
}
// Build the partial rule set.
// Note: since replace and rename rules are pretty much independent we will
// only be testing the rules from the set that the test rule belongs.
var ruleCollection = (testRule.action === 'replace') ? replace : rename
// If the supplied rule was given with a mongo id, cut off the rule set at
// that point.
if (testRule._id) {
var oldRule = ruleCollection.filter(function (rule) {
return rule._id.toString() === testRule._id.toString()
}).pop()
if (!oldRule) {
return next(Boom.badRequest(
'Rule with given _id: "' + testRule._id + '" was not found.'
))
}
ruleCollection = ruleCollection.slice(0, ruleCollection.indexOf(oldRule))
}
// Add the rule to the end of the collection and push the rules into the
// final rule list
rules = rules.concat(ruleCollection, testRule)
// Ask optimus for the results...
optimus.transform(
{
repo: `git@${process.env.GITHUB_HOST}:${appCodeVersion.repo}`,
commitish: appCodeVersion.commit,
rules: rules,
deployKey: appCodeVersion.privateKey
},
handleOptimusError(next, function (response) {
res.json(last(response.body.results))
})
)
})
/**
* Handles error responses from optimus.
* @param {function} next Next method for the containing route, this is used
* to bypass the route and pass errors to default handlers.
* @param {function} cb Callback to execute if an error _DID NOT_ occur.
* @return {function} A function that wraps the callback and handles errors
* from optimus.
*/
function handleOptimusError (next, cb) {
return function (err, response) {
// Errors from simple-api-client (via request) are most likely timeouts
if (err) {
return next(Boom.create(504, err.message, {
err: err,
report: false
}))
}
// 500 and greater should come back as a 502 Gateway Error
if (response.statusCode >= 500) {
return next(Boom.create(502, response.body.message, {
report: false
}))
}
// 400 and greater should be passed directly
if (response.statusCode >= 400) {
return next(Boom.create(response.statusCode, response.body.message, {
report: false
}))
}
var args = Array.prototype.slice.call(arguments, 1) // do not include err
cb.apply(cb, args)
}
}