Archive for December 18, 2018

MongoDB Stitch Triggers & Amazon Kinesis – The AWS re:Invent Stitch Rover Demo

This post delves into using MongoDB Stitch Triggers and the Stitch AWS service to push MongoDB database changes to Amazon Kinesis. This is the fifth and final article in a series of blog posts examining how the MongoDB Mobile/Stitch-controlled rover was put together for our AWS re:Invent demo.

Sensor data from MongoDB Stitch Rover is pushed to Amazon Kinesis

Stitch has simple, built-in integration with AWS services, letting you call services like Kinesis from Stitch Functions using syntax similar to the AWS SDK. To start, we configure a new AWS service in Stitch using an IAM role from AWS and then create a new Stitch Service rule to enable Kinesis:

Configure the Amazon Kinesis through the MongoDB Stitch AWS Service

We then need a Stitch Function (kinesisTrigger) to put our rover’s sensor data onto a Kinesis stream. Note that the sensor data is taken from the event function argument (we’ll get to that in a second):

exports = function(event){
  const awsService = context.services.get('aws');
  const roverId = event.fullDocument.roverId;
  try{
    awsService.kinesis("us-west-2").PutRecord({
      Data: JSON.stringify(event.fullDocument), 
      StreamName: context.values.get("Stream"),
      PartitionKey: context.values.get("Partitions")[roverId]
    }).then(function(response) {
      return response;
    });

    console.log("Successfully put the following document into the " +
      context.values.get("Stream") + " Kinesis stream: " + 
             EJSON.stringify(event.fullDocument));
  }catch(error){
    console.log(error);
  }
};

As the rover will sometimes be disconnected from the network, it stores the readings locally in the MongoDB Mobile database. Stitch Mobile Sync will then sync these same documents to Atlas whenever it’s online.

Propagating sensor data to Amazon Kinesis using MongoDB Stitch Mobile Sync, Stitch Triggers, and a Stitch Function

We’ve configured the kinesisTrigger trigger to fire whenever a new document is added to the rover.sensors collection. The trigger calls the linked function KinesisTrigger (the trigger and function names don’t need to match), passing the inserted document as a function argument. From the time that the Stitch Trigger is hit, it typically takes just 20ms to get the data into Kinesis.

Creating a MongoDB Database Trigger using Stitch Triggers

This completes the blog series. As a reminder, this is what we’ve covered in the five posts:
MongoDB Stitch/Mobile Mars Rover Lands at AWS re:Invent describes how MongoDB Stitch, MongoDB Mobile, Atlas, Android Things, a Raspberry Pi, and Amazon Kinesis are used to reliably control our Mars rover.
MongoDB Stitch QueryAnywhere focuses on how the Mission Control app records the user commands in MongoDB Atlas by calling the Stitch SDK directly from the frontend code.
MongoDB Stitch Mobile Sync shows how Stitch Mobile Sync synchronizes the user commands written to MongoDB Atlas by the Mission Control app with the MongoDB Mobile database embedded in the rover (and how it syncs the data back to Atlas when it’s updated in MongoDB Mobile).
MongoDB Stitch Functions focuses on how a Stitch Function is used to provide aggregated sensor data such as the average temperature for the last 5 minutes.
MongoDB Stitch Triggers & Amazon Kinesis shows how we use MongoDB Stitch Triggers and the Stitch AWS service to push MongoDB database changes to Amazon Kinesis.

You can find all of the code in the Stitch Rover GitHub repo.

Why not try Stitch out for yourself.





MongoDB Stitch Functions – The AWS re:Invent Stitch Rover Demo

This is the fourth in a series of blog posts examining how the MongoDB Mobile/Stitch-controlled rover was put together for our re:Invent demo. This post focuses on how a Stitch Function is used to provide aggregated sensor data such as the average temperature for the last 5 minutes.

A common question we were asked at re:Invent is how Stitch’s serverless Functions compare with AWS Lambda functions. Stitch functions are designed to be very light-weight (run as Goroutines and deliver low latency – ideal, for example, when working with a database (especially as your function has a persistent MongoDB connection). In contrast, Lambda functions are more heavy-weight (Lambda spins up containers to run your functions in) – better suited to compute-heavy operations.

You write your functions in JavaScript (ES6) through the Stitch UI or the command line. We created this function (getReadings) to fetch a rover’s sensor data for the specified interval and then return the computed average, minimum, and maximum values:

exports = function(roverId, start, end){
  const mdb = context.services.get('mongodb-atlas');
  const sensors = mdb.db("Rovers").collection("Sensors");

  return sensors.find({"id": roverId, "time":{"$gt":start,"$lt":end}})
    .toArray()
    .then(readings => {
     let data = objArray.map(readings => readings.reading);
     return {"Average": data.reduce((a,b) => a + b, 0) / data.length,
        "Min": Math.min(...readings),
        "Max": Math.max(...readings)};
  });
};

This function can then be called from your app frontend code:

Calling a MongoDB Stitch Function from a client frontend

The frontend code to run this function is as simple as this:

context.functions.execute("getReadings", myId, samplePeriod.start, 
    samplePeriod.end);

There’s a lot more that you can do in functions, such as sending data to another cloud service. You’ll see an example of this in the next post which shows how a Stitch Trigger calls a Stitch function to send MongoDB Atlas data to AWS Kinesis.

If you can’t wait then you can find all of the code in the Stitch Rover GitHub repo.





MongoDB Stitch Mobile Sync – The AWS re:Invent Stitch Rover Demo

At AWS re:Invent, we demonstrated how MongoDB Mobile, MongoDB Stitch, and AWS services could be used to build a cloud-controlled Mars rover – read the overview post for the setup. This post focuses on how Stitch Mobile Sync synchronizes the user commands written to MongoDB Atlas by the Mission Control app with the MongoDB Mobile database embedded in the rover (and how it syncs the data back to Atlas when it’s updated in MongoDB Mobile).

MongoDB Stitch Rover - Stitch Mobile Sync

Many people who took part in the demo at re:Invent asked why Mission Control wrote the commands to Atlas rather than sending them directly to the rover. The reason is that you can’t guarantee that the rover will always have network access (and when thousands descended on the expo hall for the Monday evening social, we learned that maintaining a connection over conference WiFi can be just as tricky as maintaining one to Mars). The commands are stored in Atlas and then synchronized to the rover whenever it’s online.

Stitch Mobile Sync architecture

Each rover has a single document in the rover.rovers collection, and each command is stored as an element in the moves array:

{
  "_id" : "5bee1053fdc728f2623e20eb",
  "moves" : [
    {
      "_id" : "5c0e4db5119f6e36c7d06f55",
      "angle" : 90,
      "speed" : 2
    },
    {
      "_id" : "5c0e4dbc119f6e36c7d06f56",
      "angle" : 118,
      "speed" : 3
    },
    {
      "_id" : "5c0e4dc3119f6e36c7d06f57",
      "angle" : 45,
      "speed" : -1
    }
  ],
  "__stitch_sync_version" : {
    "spv" : 1,
    "id" : "2f704b04-2338-4c75-a7cf-d555c94cb556",
    "v" : NumberLong(10313)
  }
}

Stitch Mobile sync automatically pushes the document to the rover’s MongoDB Mobile database, and the rover’s Android app moves the rover in response. Once a move command has been acted on, the app removes it from the array and updates the document in MongoDB Mobile. Stitch Mobile Sync then automatically pushes the change back to Atlas:

doMove(move);
final Document update = new Document("$pull", new Document("moves",
                new Document("_id", move.getId())));
rovers.sync().updateOne(getRoverFilter(), update).addOnCompleteListener(task -> {
  if (!task.isSuccessful()) {
    Log.d(TAG, "failed to update rover document", task.getException());
  }
  try {
    Thread.sleep(MOVE_LOOP_WAIT_TIME_MS);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
  moveLoop();
}

You may have noticed that the same document is being updated in both Atlas and MongoDB Mobile, raising the possibility of conflicts. A conflict occurs when the document is updated in one database and, before that change has been synced, the same document is updated in the second. Sketchy network connectivity increases the size of the window where this can happen and that makes conflicts more likely.

Fortunately, Stitch Mobile Sync allows the client application to register a conflict handler function. The function is passed both versions of the document and can decide what the ‘winning’ document should look like. The conflict handling could be as simple as “local wins”, but in this case, we take the remote document (which contains at least one command not yet added to the local database) and remove any commands that have already been acted on:

public class RoverActivity extends Activity 
  implements ConflictHandler<Rover> {

  @Override
  public Rover resolveConflict(
    final BsonValue documentId,
    final ChangeEvent<Rover> localEvent,
    final ChangeEvent<Rover> remoteEvent
    ) {
    if (localEvent.getFullDocument().getLastMoveCompleted() == null) {
      return remoteEvent.getFullDocument();
    }
    // Given this sync model consists of a single producer and a
    // single consumer, a conflict can only occur when a production
    // and consumption happens at the same "time". That means
    // that there should always be an overlap of moves during a 
    // conflict and that the last move completed is always present
    // in the remote. Therefore we should trim all moves up to
    // and including the last completed move.
    final Rover localRover = localEvent.getFullDocument();
    final String lastMoveCompleted = localRover.getLastMoveCompleted();
    final Rover remoteRover = remoteEvent.getFullDocument();
    final List<Move> nextMoves = new ArrayList<>(remoteRover
      .getMoves().size());
    boolean caughtUp = false;
    for (final Move move : remoteRover.getMoves()) {
      if (move.getId().equals(lastMoveCompleted)) {
        caughtUp = true;
      } else 
      {
        if (caughtUp) {
          nextMoves.add(move);
        }
      }
    }
    return new Rover(localRover, nextMoves);
  }
}

The next post in this series looks at how Stitch Functions can be used to provide an aggregated view of the rover’s sensor data.

If you can’t wait then you can find all of the code in the Stitch Rover GitHub repo.





MongoDB Stitch Mobile Sync – The AWS re:Invent Stitch Rover Demo

At AWS re:Invent, we demonstrated how MongoDB Mobile, MongoDB Stitch, and AWS services could be used to build a cloud-controlled Mars rover – read the overview post for the setup. This post focuses on how the mission control app records the user commands in MongoDB Atlas.

Mission Control is a simple web application that we ran on an iPad. The web app takes commands from the user through its UI which displays directions for the rover to travel in. Each command sets the rover off in that direction for a short fixed amount of time.

MongoDB Stitch QueryAnywhere rover Mission Control web app

Rather than sending the command directly to the rover, and as Mars is a long way away and network connections are not always reliable, the app stores the commands in an array within the rover’s document in Atlas – in that way, commands can be queued up and sent to the rover as soon as it’s back online.

MongoDB Stitch QueryAnywhere

This is what the document looks like after a few commands have been submitted (but not yet acted on by the rover):

{
    "_id" : "5bee1053fdc728f2623e20eb",
    "moves" : [
        {
            "_id" : "5c0e4db5119f6e36c7d06f55",
            "angle" : 90,
            "speed" : 2
        },
        {
            "_id" : "5c0e4dbc119f6e36c7d06f56",
            "angle" : 118,
            "speed" : 3
        },
        {
            "_id" : "5c0e4dc3119f6e36c7d06f57",
            "angle" : 45,
            "speed" : -1
        }
    ],
    "__stitch_sync_version" : {
        "spv" : 1,
        "id" : "2f704b04-2338-4c75-a7cf-d555c94cb556",
        "v" : NumberLong(10313)
    }
}

A traditional way of access the database from the frontend app would be to stand up an app server, implement a custom REST API and data access control layer, and then send the commands to it from the frontend app. MongoDB Stitch massively simplifies that workflow by letting a web (or mobile) app execute MongoDB Query Language operations directly – removing the need for thousands of lines of boilerplate code.

When we explained this access model to demo visitors, some were nervous about this approach as we’ve been taught that the schema and database access should be hidden from the frontend (remember SQL injection attacks?). Fortunately, Stitch QueryAnywhere is made up of two components – the first is the Stitch SDK that enables direct access to the database, the second is the sophisticated, fine-grained user access controls provided by the Stitch service. If that doesn’t allay your fears then you have the option to obfuscate the schema by accessing the database through Stitch Functions.

Updating the document from the web app is a cinch with Stitch. The first step is to import the Stitch SDK:

<head>
  <script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.0.15-0/stitch.js"></script>
  <script src="https://s3.amazonaws.com/stitch-sdks/bson/bson.bundle.js"></script>
</head>

The second step is to create the object/document for the command and push it onto the moves array within this rover’s document in the rover.rovers collection:

function pushMoveToRover(roverId) {
    const client = stitch.Stitch.defaultAppClient;
    const coll = client.getServiceClient(stitch.RemoteMongoClient.factory,
        'mongodb-atlas').db('rover').collection('rovers');
    const angle = parseInt($("#angle").val());
    const speed = parseInt($("#speed").val());
    if (isNaN(angle) || isNaN(speed)) {
        return;
    }
    const move = {"_id": new BSON.ObjectID().toHexString(), angle, speed};
    coll.updateOne({"_id": roverId}, {"$push": { "moves": move }, 
        "$inc": {"__stitch_sync_version.v": 1}});
}

If you are used to working with the MongoDB Query Language from an app server, that should seem very familiar. The only thing that might catch your eye is that __stitch_sync_version.v. That’s part of how this update will get to the MongoDB Mobile database embedded in the rover. We’ll explain that in the next part.

If you can’t wait then you can find all of the code in the Stitch Rover GitHub repo.





MongoDB Stitch/Mobile Mars Rover Lands at AWS re:Invent

Powered by MongoDB Mobile, MongoDB Stitch, and AWS Kinesis, the MongoDB rover debuted at AWS re:Invent. More than a thousand people stopped by our demo to see if they could navigate the rover around a treacherous alien landscape.

MongoDB Stitch & Rover at AWS re:Invent

One of the challenges in controlling a rover on the other side of the Solar System is that there will frequently be times when you lose connectivity. To solve that, we store all of the commands in MongoDB Atlas and sync them to the rover (in its local MongoDB Mobile database) whenever it’s contactable.

MongoDB Stitch Rover Application Architecture

Visitors controlled the rover via a JavaScript web app, which uses Stitch QueryAnywhere to write commands for the rover directly to a collection in MongoDB Atlas (the fully managed hosted MongoDB database, in this case, running in the AWS cloud).

After the commands are sent to the cloud, Stitch Mobile Sync takes over, ensuring all commands are automatically written to the MongoDB Mobile database embedded on the rover (running Android Things on a Raspberry Pi 3b) by Stitch Mobile Sync. The Java app on the rover then acts on the synced commands (moving the Rover), before removing them from the mobile database to reflect that it’s completed with that set of commands – with the updated status then finally synced back to Atlas by Stitch Mobile Sync.

The rover can also record environmental sensor data in MongoDB Mobile, which Stitch Mobile Sync syncs to the sensors collection in Atlas. A Stitch Trigger on the sensors collection then runs a Stitch Function to push those sensor readings to AWS Kinesis for further analysis, such as anomaly detection.

The first appearance of the MongoDB rover coincided with the Mars landing of InSight. We even had our own 7 minutes of terror when the event WiFi buckled under the pressure of thousands of delegates descending on the expo hall during Monday’s evening social – but it did at least demonstrate that Stitch Mobile Sync quickly catches up once connectivity is restored.

This post is the first in a series delving into the components of this interactive demo, and if you can’t wait for more details, then you can find all of the code in GitHub.