All files / lib/backend-operations cloud-api-lambda-builder.js

82.72% Statements 134/162
46.99% Branches 39/83
93.33% Functions 14/15
82.72% Lines 134/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                          11x 11x 11x 11x 11x   11x 11x 11x 11x                               1x 1x   1x 1x 1x 1x 1x 1x   1x 1x                 1x   1x 1x   1x 1x 1x   1x 1x   1x 4x 4x         4x         1x       1x 1x 1x 1x   1x 2x 2x 2x 2x 4x 4x 4x 4x 2x               1x 1x 1x 1x 2x 2x 2x 2x             1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x                         1x 1x 1x 1x 1x 1x 2x 2x   2x 2x 1x 1x     2x 2x 2x   2x 2x 2x   2x   2x 2x 2x 1x 1x   1x 1x                                               1x 1x 1x 2x 2x   2x 2x 8x 8x 8x 4x 4x       1x       2x 2x 2x   2x 2x 2x 2x     2x 2x 2x 2x       2x 2x 2x 2x     2x       2x 2x   2x 2x 2x       2x                                     2x 2x 2x   2x 2x               2x               2x     11x    
/* 
 * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
 * the License. A copy of the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
 * and limitations under the License.
*/
"use strict";
const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const archiver = require('archiver')
const moment = require('moment')
 
const backendSpecManager = require('./backend-spec-manager.js')
const dfops = require('../utils/directory-file-ops.js')
const pathManager = require('../utils/awsmobilejs-path-manager.js')
const awsmobilejsConstant = require('../utils/awsmobilejs-constant.js')
 
let _projectInfo
let _backendProject
let _featureName //cloud-api feature name
let _callback
 
let _srcDirPath //contains all the lambda function
let _buildDirPath 
 
let _cloudApiPaths
let _lambdaFuncNames
let _lambdaFuncSrcDirs
let _lambdaFuncZipFiles
 
function build(projectInfo, backendProject, featureName, callback){
    _projectInfo = projectInfo
    _backendProject = backendProject
    
    _featureName = featureName
    _callback = callback
    Eif(validateCodebase()){
        buildLambdaFunctions(function(isNewBuildExecuted){
            Eif(updateLambdaFuncCodeName()){
                backendSpecManager.setBackendProjectObject(_backendProject, _projectInfo)
            }
            Eif(_callback){
                _callback(isNewBuildExecuted)
            }
        })
    }else{
        console.log(chalk.red('validation failed'))
    }
}
 
function validateCodebase(){
    let isCodebaseValid = true
 
    _srcDirPath = pathManager.getBackendFeatureDirPath(_projectInfo.ProjectPath, _featureName)
    _buildDirPath = pathManager.getBackendBuildFeatureDirPath(_projectInfo.ProjectPath, _featureName)
    
    getCloudApiPaths()
    getLambdaFunDirs()
    getExistingZipFiles()
 
    let paths = Object.keys(_cloudApiPaths)
    let srcDirs = Object.keys(_lambdaFuncSrcDirs)
 
    for(let i = 0; i<paths.length; i++){
        let lambdaFunc = _cloudApiPaths[paths[i]]
        Iif( /[^a-zA-Z0-9]/.test(lambdaFunc.name)){
            console.log(chalk.red('invalid lambda function name: ' + paths[i] + ': ' + lambdaFunc.name))
            console.log('lambda function name can only contain alphanumeric characters:  a-z A-Z 0-9')
            isCodebaseValid = false
        }
        Iif(lambdaFunc.name && !srcDirs.includes(lambdaFunc.name)){
            console.log(chalk.bgYellow.bold('Warning:') + ' no codebase found for lambda function: ' + paths[i] + ': ' + lambdaFunc.name)
        }
    }
 
    return isCodebaseValid
}
 
function getCloudApiPaths(){
    _cloudApiPaths = {}
    _lambdaFuncNames = []
    let components = _backendProject.features.cloudlogic.components
    let apiNames = Object.keys(components)
 
    for(let i = 0; i<apiNames.length; i++){
        let api = components[apiNames[i]]
        Eif(api.paths){
            let pathNames = Object.keys(api.paths)
            for(let j = 0; j < pathNames.length; j++){
                let key  = api.attributes.name + pathNames[j]
                let lambdaFunc = api.paths[pathNames[j]]
                _cloudApiPaths[key] = lambdaFunc
                if(!_lambdaFuncNames.includes(lambdaFunc.name)){
                    _lambdaFuncNames.push(lambdaFunc.name)
                }
            }
        }
    }
}
 
function getLambdaFunDirs(){
    _lambdaFuncSrcDirs = {}
    Eif(fs.existsSync(_srcDirPath)){
        let lambdaFunctionDirNames = fs.readdirSync(_srcDirPath)
        for(let i = 0; i < lambdaFunctionDirNames.length; i++) {
            let funcDirPath = path.join(_srcDirPath, lambdaFunctionDirNames[i])
            let stat = fs.lstatSync(funcDirPath)
            Eif(stat.isDirectory() && _lambdaFuncNames.includes(lambdaFunctionDirNames[i])) {
                _lambdaFuncSrcDirs[lambdaFunctionDirNames[i]] = funcDirPath
            }
        }
    }
}
 
function getExistingZipFiles(){
    _lambdaFuncZipFiles = {}
    Eif(fs.existsSync(_buildDirPath)){
        let zipFiles = fs.readdirSync(_buildDirPath)
        for(let i = 0; i < zipFiles.length; i++) {
            let zipFileName = zipFiles[i]
            let funcZipFilePath = path.join(_buildDirPath, zipFileName)
            let stat = fs.lstatSync(funcZipFilePath)
            Eif(stat.isFile()) {
                let strippedZipFileName = path.basename(zipFileName, '.zip').split('-')[0]
                Eif(_lambdaFuncNames.includes(strippedZipFileName)){
                    _lambdaFuncZipFiles[strippedZipFileName] = funcZipFilePath
                }else{
                    fs.removeSync(funcZipFilePath)
                }
            }else{
                fs.removeSync(funcZipFilePath)
            }
        }
    }
}
 
 
function buildLambdaFunctions(callback){
    let isNewBuildExecuted = false
    let zipFileNameSuffix = '-' + moment().format(awsmobilejsConstant.DateTimeFormatStringCompact)
    let srcFuncNames = Object.keys(_lambdaFuncSrcDirs)
    Eif(srcFuncNames.length > 0){
        let count = 0
        for(let i = 0; i<srcFuncNames.length; i++){
            let lambdaFuncName = srcFuncNames[i]
            Eif(isNewBuildNeeded(lambdaFuncName)){
 
                fs.ensureDirSync(_buildDirPath)
                if(!isNewBuildExecuted){
                    isNewBuildExecuted = true
                    console.log('   building ' + _featureName)
                }
 
                let srcCodeDir = _lambdaFuncSrcDirs[lambdaFuncName]
                let zipFileName = lambdaFuncName  + zipFileNameSuffix + '.zip'
                let zipFilePath = path.join(_buildDirPath, zipFileName)
 
                let existingZipFilePath = _lambdaFuncZipFiles[lambdaFuncName]
                Eif(fs.existsSync(existingZipFilePath)){
                    fs.removeSync(existingZipFilePath)
                }
                _lambdaFuncZipFiles[lambdaFuncName] = zipFilePath
 
                buildAWSLambda(srcCodeDir, zipFilePath, function(){  
                    count ++ 
                    if(count == srcFuncNames.length){
                        Eif(isNewBuildExecuted){
                            console.log('   done')
                        }
                        Eif(callback){
                            callback(isNewBuildExecuted)
                        }
                    }
                })
            }else{
                count ++ 
                if(count == srcFuncNames.length){
                    if(isNewBuildExecuted){
                        console.log('   done')
                    }
                    if(callback){
                        callback(isNewBuildExecuted)
                    }
                }
            }
        }
    }else{
        if(callback){
            callback(isNewBuildExecuted)
        }
    }
}
 
function updateLambdaFuncCodeName(){
    let codeFileNameUpdated = false
    let lambdaWithZipFiles = Object.keys(_lambdaFuncZipFiles)
    for(let i = 0; i<lambdaWithZipFiles.length; i++){
        let lambdaFuncName = lambdaWithZipFiles[i]
        let zipFileName = path.basename(_lambdaFuncZipFiles[lambdaFuncName])
 
        let apiPaths = Object.keys(_cloudApiPaths)
        for(let i = 0; i<apiPaths.length; i++){
            let lambdaFunc = _cloudApiPaths[apiPaths[i]]
            let codeFileName = 'uploads/' + zipFileName
            if(lambdaFunc.name == lambdaFuncName && lambdaFunc.codeFilename != codeFileName){
                lambdaFunc.codeFilename = codeFileName
                codeFileNameUpdated = true
            }
        }
    }
    return codeFileNameUpdated
}
 
function buildAWSLambda(srcCodeDir, zipFilePath, callback){
    let npm = /^win/.test(process.platform) ? 'npm.cmd' : 'npm'
    require('child_process').spawnSync(npm, [ 'install' ], { cwd : srcCodeDir })
    let output = fs.createWriteStream(zipFilePath)
    
    console.log('      zipping ' + path.basename(srcCodeDir))
    output.on('close', function() {
        Eif(callback){
            callback()
        }
    })
    let zip = archiver.create('zip', {})
    zip.pipe(output)
    zip.directory(srcCodeDir, false)
    zip.finalize()
}
 
function isNewBuildNeeded(lambdaFuncName){
    let result = false
    let srcCodeDir = _lambdaFuncSrcDirs[lambdaFuncName]
    Eif(srcCodeDir && fs.existsSync(srcCodeDir)){
        result = isCodebaseChanged(lambdaFuncName) || 
                isZipFileMissing(lambdaFuncName)
    }
    return result
}
 
function isCodebaseChanged(lambdaFuncName){
    let result = false
    let srcCodeDir = _lambdaFuncSrcDirs[lambdaFuncName]
 
    let timeStamp = getTimeStamp(_projectInfo)
    let lastSrcDirModificationTime = moment(dfops.getDirContentMTime(srcCodeDir, null, null))
    result =!timeStamp.isValid() ||
            !lastSrcDirModificationTime.isValid() ||
            timeStamp.isBefore(lastSrcDirModificationTime) 
 
    return result
}
 
function isZipFileMissing(lambdaFuncName){
    let result = false
 
    let srcCodeDir = _lambdaFuncSrcDirs[lambdaFuncName]
    let existingZipFilePath = _lambdaFuncZipFiles[lambdaFuncName]
 
    if(existingZipFilePath && fs.existsSync(existingZipFilePath)){ 
        result = false
    }else{
        result = true
    }
 
    return result
}
 
function getTimeStamp(projectInfo){
    let lastBackendBuildTime = moment(projectInfo.BackendLastBuildTime, awsmobilejsConstant.DateTimeFormatString)
    let lastBackendPushTime = moment(projectInfo.BackendLastPushTime, awsmobilejsConstant.DateTimeFormatString)
    let lastBackendSyncToDevTime = moment(projectInfo.BackendLastSyncToDevTime, awsmobilejsConstant.DateTimeFormatString)
 
    let result = lastBackendBuildTime
    Iif(lastBackendPushTime.isValid()){
        if(result.isValid()){
            result = lastBackendPushTime > result ? lastBackendPushTime : result
        }else{
            result = lastBackendPushTime
        }
    }
    
    Iif(lastBackendSyncToDevTime.isValid()){
        if(result.isValid()){
            result = lastBackendSyncToDevTime > result ? lastBackendSyncToDevTime : result
        }else{
            result = lastBackendSyncToDevTime
        }
    }
 
    return result
}
 
module.exports = {
    build
}