30 Aug 2017

A Forge Viewer with Faster Serverless deployment using Claudia.js

Forge Viewer

Introduction

I'm going to present a minimal setup, a 'hello Forge Viewer' if you will.  It will connect a Forge viewer to your live data using a cheap AWS-Lambda serverless function and make it easy to deploy, update and test locally, using ClaudiaJs.

This is a follow up to Philippe's great blog post 'Running Forge on Lambda' - It showed you the basics of hosting a Forge Viewer with Serverless technology based on AWS-Lambda.  It used a ‘manual’ deploy through the AWS console, which involves a lot of tricky steps every time we make a code change - zip up files, upload it via the browser, configure any new endpoints in API-gateway, etc.  If we are going to be making many code changes, then it will slow down development cycles.  So is there a better way ?   yes - ClaudiaJS !

What is ClaudiaJS?  It's a command line tool that deploys your localhost nodejs app to AWS Lambda with a simple ‘create’ command.  Any subsequent code changes, use the ‘update’ command - simple !

To get started, use my GitHub 'hello Forge' minimal template: (https://github.com/wallabyway/viewer-serverless)

Here’s the live demo:   https://adc6qwtnce.execute-api.us-east-1.amazonaws.com/tutorial/

Debugging locally and updating can be a little tricky, here's a youtube video walkthrough: https://www.youtube.com/watch?v=aK-nIFZqslI

Setup

Prerequisites

  1. An Amazon Web Services account that has IAM full access and full Lambda access. Check out this for how to create an account.
  2. Node.js (version 4.3.2 and up) and NPM installed on your machine. If you need these, check out this link.

Steps

1. Clone the repo and install, like this:

> git clone https://github.com/wallabyway/viewer-serverless
> cd viewer-serverless
> npm install

2. Set up your AWS Credentials

Create a folder called .aws and a file called ‘credentials’

> mkdir ~/.aws && cd .aws && nano credentials

Copy the text below and save - don't forget to replace the key and secret with your Amazon IAM credentials

[claudia]
aws_access_key_id = ACCESS_KEY_ID_FROM_AWS_PAGE
aws_secret_access_key = SECRET_KEY_FROM_AWS_PAGE

This is the same file used by all aws command line programs like 's3cmd' and 'claudiaJs' to connect to AWS services.

Now... with your environment set up, let’s start coding!

Code

There are two files we are interested in - The server code is found in file ‘app.js’ and the viewer code is found in file 'www / index.html'

Server code

The nodejs app, running on Lambda, will contact the Forge API’s to retrieve an Access Token, and then host a public endpoint for the browser to pull the access token and our web page.

In the app.js code, we create two endpoints, the first endpoint serves the accessToken via an init.js file and an options variable.  (We will see that options variable and the accessToken passed to the browser later)…

    app.get('/js/init.js', (req, res) => {
        oAuth2TwoLegged.authenticate().then( function(restoken) {
            res.send(` 
                options = {
                    accessToken: "${restoken.access_token}",
                    env: "AutodeskProduction",
                    urn: "${URN}"
                };
            `);
            console.log(`Sent ForgeToken: ${restoken.access_token}`);
        });

    })

 

The second endpoint is just standard node/express serving static files:

app.use(express.static(__dirname + '/www'));

That’s it for the server.  Now let’s look at the viewer.

Client Code

Here is the ‘hello world’ equivalent of the Forge viewer.  Initialize the viewer with the options variable containing our AccessToken from the server, then load our URN with loadDocument. Once it’s loaded, switch our camera to the first ‘viewable’.

function initializeViewer() {

            function onLoadSuccess() {
              var viewables = viewerApp.bubble.search({ 'type': 'geometry' });
              if (viewables.length > 0)
                  viewerApp.selectItem(viewables[0].data);
            };

            function onInitialized() {
                viewerApp = new Autodesk.Viewing.ViewingApplication('forgeViewer');
                viewerApp.registerViewer( viewerApp.k3D, Autodesk.Viewing.Private.GuiViewer3D );    
                viewerApp.loadDocument( options.urn, onLoadSuccess);
            };
            Autodesk.Viewing.Initializer( options, onInitialized);
        }

Deploying with Claudia

Now it’s time to deploy our code to AWS-Lambda using ClaudiaJS.

In the package.json file, I've added four convenient ‘run scripts’ to create, update and destroy our deployment(s).

{"create": "claudia create --handler lambda.handler --deploy-proxy-api --region us-east-1 --version tutorial",
"setvars": "claudia set-version --version tutorial --set-env FORGE_CLIENT_ID=xxx,FORGE_CLIENT_SECRET=xxx,FORGE_URN=xxx",
"update": "claudia update --version tutorial",
"destroy": "claudia destroy"}

Create

Let's start with the first one ”create”... Simply type:

> npm run create

This will zip, upload and configure our node.js app to a new AWS Lambda endpoint. Once it's finished you will see a 'new URL' endpoint in the console output.  But before we can run it, we need to setup the Environment variables on AWS-Lambda.  

Set Environment Variables

To setup environment variables on Lambda, type the following:

> claudia set-version --version tutorial --set-env FORGE_CLIENT_ID=xxx,FORGE_CLIENT_SECRET=xxx,FORGE_URN=xxx

change the 'xxx' values with your forge credentials and the URN of the design file you want to view.

Note: You can also run 'setvars' npm script (above) to do the same thing.

> npm run setvars

All done ! 

Claudia has pushed our code and our environment variables to AWS-Lambda and we can now try our URL.

If all goes well, it should look something like this:  https://adc6qwtnce.execute-api.us-east-1.amazonaws.com/tutorial/

Note: Add a '/' or a '/index.html' to the URL.

'Updating' the app

Let's make a code change and deploy it.

<h2>My Tutorial </h2>
<style> h2 {font-family:arial; position:absolute; margin:20px; color:darkblue; z-index:1;}</style>
  1. add the text 'My Tutorial' to the 'www/index.html' file. (see the code below and on GitHub)
  2. Type:  > npm run update 
  3. Refresh the browser

You should see 'My Tutorial' appear as an overlay to the viewer.  See the gif animation (or YouTube video)

Make sure LINE#38 in app.js is commented out

Debugging Locally

Debugging locally

With a single line change, you can also debug the same code on a local version of node.js.  This is one of the key benefits of using ClaudiaJs.

 1. Uncomment line 38, in app.js
 2. Start the server:

> node app.js

 3. Open localhost:3000/ in a browser
 4. Make some code changes and hit refresh

Note: Add your Forge Environment variables like this:

export FORGE_CLIENT_ID=lDB........0Ol
export FORGE_CLIENT_SECRET=f...H
export FORGE_URN= dXJu........QucnZ0

 

Conclusion

Congrats, you are all done! You have setup Claudia and now can use this as a building block for your real applications.

Overall, using Claudia.js makes it easier and faster to get started with Lambda functions.  I hope this minimal example helps you get started with the Autodesk Forge platform with low cost cloud solutions that scale well...  like AWS-Lambda !

Reach out and follow me on twitter! Check out my GitHub for my open source projects!

For further information on Clauda.js, check out their main page.

Related Article