This is an automated email from the ASF dual-hosted git repository.

mrutkowski pushed a commit to branch master
in repository 
https://gitbox.apache.org/repos/asf/incubator-openwhisk-runtime-nodejs.git


The following commit(s) were added to refs/heads/master by this push:
     new bd9385c  Follow up on Knative PR - 119 (#122)
bd9385c is described below

commit bd9385cdf961d102002862c264bc7a5afccda582
Author: Priti Desai <[email protected]>
AuthorDate: Wed Apr 24 10:48:26 2019 -0700

    Follow up on Knative PR - 119 (#122)
    
    * changes to app.js
    
    * changes to knative.js
    
    * changes to service.js
    
    * not used anywhere
    
    * changing const to var
---
 core/nodejsActionBase/app.js              | 55 +++++++++----------
 core/nodejsActionBase/platform/knative.js | 90 ++++++++++++++++---------------
 core/nodejsActionBase/src/service.js      | 54 +++++++++----------
 3 files changed, 103 insertions(+), 96 deletions(-)

diff --git a/core/nodejsActionBase/app.js b/core/nodejsActionBase/app.js
index f45ee4b..d825dc3 100644
--- a/core/nodejsActionBase/app.js
+++ b/core/nodejsActionBase/app.js
@@ -17,10 +17,10 @@
 
 // __OW_ALLOW_CONCURRENT: see docs/concurrency.md
 var config = {
-    'port': 8080,
-    'apiHost': process.env.__OW_API_HOST,
-    'allowConcurrent': process.env.__OW_ALLOW_CONCURRENT,
-    'requestBodyLimit': "48mb"
+        'port': 8080,
+        'apiHost': process.env.__OW_API_HOST,
+        'allowConcurrent': process.env.__OW_ALLOW_CONCURRENT,
+        'requestBodyLimit': "48mb"
 };
 
 var bodyParser = require('body-parser');
@@ -50,12 +50,12 @@ var targetPlatform = process.env.__OW_RUNTIME_PLATFORM;
 
 // default to "openwhisk" platform initialization if not defined
 // TODO export isvalid() from platform, if undefined this is OK to default, 
but if not valid value then error out
-if(typeof targetPlatform === "undefined") {
+if (typeof targetPlatform === "undefined") {
     targetPlatform = platformFactory.PLATFORM_OPENWHISK;
     // console.log("__OW_RUNTIME_PLATFORM is undefined; defaulting to 
'openwhisk' ...");
 }
 
-if(!platformFactory.isSupportedPlatform(targetPlatform)){
+if (!platformFactory.isSupportedPlatform(targetPlatform)) {
     console.error("__OW_RUNTIME_PLATFORM ("+targetPlatform+") is not supported 
by the runtime.");
     process.exit(9);
 }
@@ -66,29 +66,30 @@ if(!platformFactory.isSupportedPlatform(targetPlatform)){
  * to move data where the platform and function author expects it to be.
  */
 
-var platformImpl = factory.createPlatformImpl(targetPlatform);
+const platformImpl = factory.createPlatformImpl(targetPlatform);
 
-if(typeof platformImpl == "undefined") {
-    console.error("Failed to initialize __OW_RUNTIME_PLATFORM 
("+targetPlatform+").");
-    process.exit(10);
-}
+if (typeof platformImpl !== "undefined") {
 
-// Call platform impl. to register platform-specific endpoints (routes)
-platformImpl.registerHandlers(app, platformImpl);
+    platformImpl.registerHandlers(app, platformImpl);
 
-// short-circuit any requests to invalid routes (endpoints) that we have no 
handlers for.
-app.use(function (req, res, next) {
-    res.status(500).json({error: "Bad request."});
-});
+    // short-circuit any requests to invalid routes (endpoints) that we have 
no handlers for.
+    app.use(function (req, res, next) {
+        res.status(500).json({error: "Bad request."});
+    });
 
-/**
- * Register a default error handler. This effectively only gets called when 
invalid JSON is received
- * (JSON Parser) and we do not wish the default handler to error with a 400 
and send back HTML in the
- * body of the response.
- */
-app.use(function (err, req, res, next) {
-    console.log(err.stackTrace);
-    res.status(500).json({error: "Bad request."});
-});
+    /**
+     * Register a default error handler. This effectively only gets called 
when invalid JSON is received
+     * (JSON Parser) and we do not wish the default handler to error with a 
400 and send back HTML in the
+     * body of the response.
+     */
+    app.use(function (err, req, res, next) {
+        console.log(err.stackTrace);
+        res.status(500).json({error: "Bad request."});
+    });
 
-service.start(app);
+    service.start(app);
+
+} else {
+    console.error("Failed to initialize __OW_RUNTIME_PLATFORM 
("+targetPlatform+").");
+    process.exit(10);
+}
diff --git a/core/nodejsActionBase/platform/knative.js 
b/core/nodejsActionBase/platform/knative.js
index cbc9b8c..1fc68a8 100644
--- a/core/nodejsActionBase/platform/knative.js
+++ b/core/nodejsActionBase/platform/knative.js
@@ -129,38 +129,16 @@ function preProcessInitData(env, initdata, valuedata, 
activationdata) {
         // param. data (as they both appear within "body.value") so we must 
save it to its final location
         // as the default Action name as part of the activation data
         // NOTE: if action name is not present in the action data, we will set 
it regardless even if an empty string
-        if( typeof(activationdata) !== "undefined" ) {
-            if ( typeof(activationdata.action_name) === "undefined" ||
-                (typeof(activationdata.action_name) === "string" && 
activationdata.action_name.length == 0 )){
+        if (typeof(activationdata) !== "undefined" ) {
+            if (typeof(activationdata.action_name) === "undefined" ||
+                (typeof(activationdata.action_name) === "string" && 
activationdata.action_name.length == 0)){
                 activationdata.action_name = actionName;
             }
         }
 
     } catch(e){
         console.error(e);
-        throw("Unable to initialize the runtime: " + e.message);
-    }
-}
-
-/**
- * Pre-process the incoming http request data, moving it to where the
- * route handlers expect it to be for an openwhisk runtime.
- */
-function preProcessActivationData(env, activationdata) {
-    try {
-        // Note: we move the values here so that the "run()" handler does not 
have
-        // to move them again.
-        Object.keys(activationdata).forEach(
-            function (k) {
-                if (typeof activationdata[k] === 'string') {
-                    var envVariable = OW_ENV_PREFIX + k.toUpperCase();
-                    process.env[envVariable] = activationdata[k];
-                }
-            }
-        );
-    } catch(e){
-        console.error(e);
-        throw("Unable to initialize the runtime: " + e.message);
+        throw("Unable to process Initialization data: " + e.message);
     }
 }
 
@@ -198,6 +176,7 @@ function preProcessHTTPContext(req, valueData) {
                 // make value data available as __ow_body
                 const tmpBody = Object.assign({}, req.body.value);
                 // delete main, binary, raw, and code from the body before 
sending it as an action argument
+                removeInitData(tmpBody);
                 delete tmpBody.main;
                 delete tmpBody.code;
                 delete tmpBody.binary;
@@ -219,10 +198,31 @@ function preProcessHTTPContext(req, valueData) {
         valueData.__ow_path = "";
     } catch (e) {
         console.error(e);
-        throw ("Unable to initialize the runtime: " + e.message)
+        throw ("Unable to process HTTP Context: " + e.message)
     }
 }
 
+/**
+ * Pre-process the incoming http request data, moving it to where the
+ * route handlers expect it to be for an openwhisk runtime.
+ */
+function preProcessActivationData(env, activationdata) {
+    try {
+        // Note: we move the values here so that the "run()" handler does not 
have
+        // to move them again.
+        Object.keys(activationdata).forEach(
+            function (k) {
+                if (typeof activationdata[k] === 'string') {
+                    var envVariable = OW_ENV_PREFIX + k.toUpperCase();
+                    process.env[envVariable] = activationdata[k];
+                }
+            }
+        );
+    } catch(e){
+        console.error(e);
+        throw("Unable to process Activation data: " + e.message);
+    }
+}
 
 /**
  * Pre-process the incoming http request data, moving it to where the
@@ -230,13 +230,27 @@ function preProcessHTTPContext(req, valueData) {
  */
 function preProcessRequest(req){
     try {
+        let env = process.env || {};
+
         // Get or create valid references to the various data we might 
encounter
         // in a request such as Init., Activation and function parameter data.
         let body = req.body || {};
         let valueData = body.value || {};
         let initData = body.init || {};
         let activationData = body.activation || {};
-        let env = process.env || {};
+
+        // process initialization (i.e., "init") data
+        if (hasInitData(req)) {
+            preProcessInitData(env, initData, valueData, activationData);
+        }
+
+        if( hasActivationData(req)) {
+            // process HTTP request header and body to make it available to 
function as parameter data
+            preProcessHTTPContext(req, valueData);
+
+            // process per-activation (i.e, "run") data
+            preProcessActivationData(env, activationData);
+        }
 
         // Fix up pointers in case we had to allocate new maps
         req.body = body;
@@ -244,19 +258,10 @@ function preProcessRequest(req){
         req.body.init = initData;
         req.body.activation = activationData;
 
-        // process initialization (i.e., "init") data
-        preProcessInitData(env, initData, valueData, activationData);
-
-        // process HTTP request header and body to make it available to 
function as parameter data
-        preProcessHTTPContext(req, valueData);
-
-        // process per-activation (i.e, "run") data
-        preProcessActivationData(env, activationData);
-
     } catch(e){
         console.error(e);
         // TODO: test this error is handled properly and results in an HTTP 
error response
-        throw("Unable to initialize the runtime: " + e.message);
+        throw("Unable to process request data: " + e.message);
     }
 }
 
@@ -384,10 +389,11 @@ function PlatformKnativeImpl(platformFactory) {
                 // Process request and process env. variables to provide them 
in the manner
                 // an OpenWhisk Action expects them, as well as enable 
additional Http features.
                 preProcessRequest(req);
-
+                // Invoke the OW "init" entrypoint
                 service.initCode(req).then(function () {
                     // delete any INIT data (e.g., code, raw, etc.) from the 
'value' data before calling run().
                     removeInitData(req.body);
+                    // Invoke the OW "run" entrypoint
                     service.runCode(req).then(function (result) {
                         postProcessResponse(req, result, res)
                     });
@@ -405,7 +411,7 @@ function PlatformKnativeImpl(platformFactory) {
                 // Process request and process env. variables to provide them 
in the manner
                 // an OpenWhisk Action expects them, as well as enable 
additional Http features.
                 preProcessRequest(req);
-
+                // Invoke the OW "init" entrypoint
                 service.initCode(req).then(function (result) {
                     res.status(result.code).send(result.response);
                 }).catch(function (error) {
@@ -421,7 +427,7 @@ function PlatformKnativeImpl(platformFactory) {
                 // Process request and process env. variables to provide them 
in the manner
                 // an OpenWhisk Action expects them, as well as enable 
additional Http features.
                 preProcessRequest(req);
-
+                // Invoke the OW "run" entrypoint
                 service.runCode(req).then(function (result) {
                     postProcessResponse(req, result, res)
                 }).catch(function (error) {
@@ -436,7 +442,7 @@ function PlatformKnativeImpl(platformFactory) {
             }
 
         } catch (e) {
-            res.status(500).json({error: "internal error during function 
initialization."})
+            res.status(500).json({error: "internal error during request 
processing."})
         }
     };
 
diff --git a/core/nodejsActionBase/src/service.js 
b/core/nodejsActionBase/src/service.js
index eca3102..f84caec 100644
--- a/core/nodejsActionBase/src/service.js
+++ b/core/nodejsActionBase/src/service.js
@@ -24,12 +24,12 @@ function NodeActionService(config) {
         ready: 'ready',
         starting: 'starting',
         running: 'running',
-        stopped: 'stopped'
+        stopped: 'stopped',
     };
 
     // TODO: save the entire configuration for use by any of the route handlers
     var status = Status.ready;
-    var ignoreRunStatus = config.allowConcurrent === undefined ? false : 
config.allowConcurrent.toLowerCase() === "true";
+    var ignoreRunStatus = config.allowConcurrent === undefined ? false : 
config.allowConcurrent.toLowerCase() === 'true';
     var server = undefined;
     var userCodeRunner = undefined;
 
@@ -47,11 +47,11 @@ function NodeActionService(config) {
      * { code: int, response: object }
      *
      */
-    function responseMessage (code, response) {
+    function responseMessage(code, response) {
         return { code: code, response: response };
     }
 
-    function errorMessage (code, errorMsg) {
+    function errorMessage(code, errorMsg) {
         return responseMessage(code, { error: errorMsg });
     }
 
@@ -84,26 +84,26 @@ function NodeActionService(config) {
             var message = body.value || {};
 
             if (message.main && message.code && typeof message.main === 
'string' && typeof message.code === 'string') {
-                return doInit(message).then(function (result) {
+                return doInit(message).then(function(result) {
                     setStatus(Status.ready);
                     return responseMessage(200, { OK: true });
-                }).catch(function (error) {
+                }).catch(function(error) {
                     setStatus(Status.stopped);
-                    var errStr = "Initialization has failed due to: " + 
error.stack ? String(error.stack) : error;
+                    var errStr = 'Initialization has failed due to: ' + 
error.stack ? String(error.stack) : error;
                     return Promise.reject(errorMessage(502, errStr));
                 });
             } else {
                 setStatus(Status.ready);
-                var msg = "Missing main/no code to execute.";
+                var msg = 'Missing main/no code to execute.';
                 return Promise.reject(errorMessage(403, msg));
             }
         } else if (userCodeRunner !== undefined) {
-            var msg = "Cannot initialize the action more than once.";
-            console.error("Internal system error:", msg);
+            var msg = 'Cannot initialize the action more than once.';
+            console.error('Internal system error:', msg);
             return Promise.reject(errorMessage(403, msg));
         } else {
-            var msg = "System not ready, status is " + status + ".";
-            console.error("Internal system error:", msg);
+            var msg = 'System not ready, status is ' + status + '.';
+            console.error('Internal system error:', msg);
             return Promise.reject(errorMessage(403, msg));
         }
     };
@@ -122,23 +122,23 @@ function NodeActionService(config) {
                 setStatus(Status.running);
             }
 
-            return doRun(req).then(function (result) {
+            return doRun(req).then(function(result) {
                 if (!ignoreRunStatus) {
                     setStatus(Status.ready);
                 }
-                if (typeof result !== "object") {
-                    return errorMessage(502, "The action did not return a 
dictionary.");
+                if (typeof result !== 'object') {
+                    return errorMessage(502, 'The action did not return a 
dictionary.');
                 } else {
                     return responseMessage(200, result);
                 }
-            }).catch(function (error) {
-                var msg = "An error has occurred: " + error;
+            }).catch(function(error) {
+                var msg = 'An error has occurred: ' + error;
                 setStatus(Status.stopped);
                 return Promise.reject(errorMessage(502, msg));
             });
         } else {
-            var msg = "System not ready, status is " + status + ".";
-            console.error("Internal system error:", msg);
+            var msg = 'System not ready, status is ' + status + '.';
+            console.error('Internal system error:', msg);
             return Promise.reject(errorMessage(403, msg));
         }
     };
@@ -146,12 +146,12 @@ function NodeActionService(config) {
     function doInit(message) {
         userCodeRunner = new NodeActionRunner();
 
-        return userCodeRunner.init(message).then(function (result) {
+        return userCodeRunner.init(message).then(function(result) {
             // 'true' has no particular meaning here. The fact that the promise
             // is resolved successfully in itself carries the intended message
             // that initialization succeeded.
             return true;
-        }).catch(function (error) {
+        }).catch(function(error) {
             // emit error to activation log then flush the logs as this
             // is the end of the activation
             console.error('Error during initialization:', error);
@@ -162,23 +162,23 @@ function NodeActionService(config) {
 
     function doRun(req) {
         var msg = req && req.body || {};
-        // Move per-activation keys to process env. vars with __OW_ (reserved) 
prefix)
+        // Move per-activation keys to process env. vars with __OW_ (reserved) 
prefix
         Object.keys(msg).forEach(
-            function (k) {
-                if(typeof msg[k] === 'string' && k !== 'value'){
+            function(k) {
+                if (typeof msg[k] === 'string' && k !== 'value'){
                     var envVariable = '__OW_' + k.toUpperCase();
-                    process.env[envVariable] = msg[k];
+                    process.env['__OW_' + k.toUpperCase()] = msg[k];
                 }
             }
         );
 
         return userCodeRunner.run(msg.value).then(function(result) {
-            if (typeof result !== "object") {
+            if (typeof result !== 'object') {
                 console.error('Result must be of type object but has type "' + 
typeof result + '":', result);
             }
             writeMarkers();
             return result;
-        }).catch(function (error) {
+        }).catch(function(error) {
             console.error(error);
             writeMarkers();
             return Promise.reject(error);

Reply via email to