Tag Archive for MongoDB Mobile

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.





Stitch & Mobile Webinar Questions & Replay

How do you test MongoDB Stitch functions, how do you store Stitch triggers, and what services can you integrate Stitch with? These were some of the great questions that were asked and answered in my recent webinar. You can watch the replay of “MongoDB Mobile and MongoDB Stitch – Introduction and Latest Developments” here, or read on as I share the answers to those questions here.

For those new to MongoDB Stitch, it’s the serverless platform from MongoDB that isolates complexity and ‘plumbing’ so you can build applications faster. Stitch went GA in June 2018, and we recently added a set of new capabilities, including global Stitch apps, more AWS services, a React Native SDK, and the beta for Stitch Mobile Sync. MongoDB Mobile is an embedded version of the MongoDB database that you can embed in your mobile or IoT apps.

Building mobile apps with MongoDB Mobile, MongoDB Stitch, and MongoDB Atlas

These are some of the questions I thought might be of interest:

How do you test Stitch functions?

The Stitch UI includes a console which can be used to test your Stitch functions; you can include console.log statements to add extra debug output to the console (they also get added to the log files for every function invoked from an incoming webhook, trigger, or the Stitch SDK).

You can also invoke your Stitch functions through the mongo shell. To do that, you’ll need to enable the MongoDB wire protocol so that the shell can talk to your Stitch app, then use the Stitch connection string provided. Once connected, you can call Stitch functions explicitly like this:

mongo> db.runCommand({callFunction: "morning", arguments: ["Billy"]})

{"ok" : 1,
 "response" : {"message" : "Good Morning Billy from andrew.morgan@mongodb.com"}
}

You can read more about this in this post which takes you through the process.

How do you store stitch triggers in your Git repo?

You can export your Stitch application from the Stitch UI or the Stitch CLI; the exported app is represented by a directory structure containing JSON and JavaScript files:

yourStitchApp/
├── stitch.json
├── secrets.json
├── variables.json
├── auth_providers/
│   └── <provider name>.json
├── functions/
│   └── <function name>/
│       ├── config.json
│       └── source.js
├── services/
│   └── <service name>/
│       ├── config.json
│       ├── incoming_webhooks/
│       │   ├── config.json
│       │   └── source.js
│       └── rules/
│           └── <rule name>.json
├── triggers/
│   └── <trigger name>/
│       ├── config.json
│       └── source.js
└── values/
    └── <value name>.json

You can then work on the trigger configuration and the associated function locally, source control the app using Git, or import it into a new App.

We saw a few integration provider logos in the presentation. Is there a page on the MongoDB site with the comprehensive list?

You can find the list of Stitch’s built-in service integrations in the Stitch documentation.

Note that if we don’t have a built-in integration for a particular service, then you can easily integrate it yourself, using the Stitch HTTP service and incoming webhooks. You can even export your new service integration to share with others.

Is MongoDB Mobile + Stitch Mobile Sync the same as a cache in a progressive app?

It certainly removes the need to have a separate cache, but it does much more. With MongoDB Mobile, the data is persistently stored on your device. You also have the full power of the MongoDB Query Language to perform sophisticated queries and aggregations on that local data. Changes made to the local database are pushed back to MongoDB Atlas, and from there to any other mobile devices configured to sync the same documents (e.g., for the same user running the app on another device).

How do I download & embed MongoDB Mobile?

You simply need to add 1 line to your Android or Xcode project to have access to the entire Stitch SDK, including the Stitch Local Database service (i.e.,the MongoDB Mobile database). The Stitch SDK includes the entire mobile and makes it very easy to use and consume, even if you’re just using the local MongoDB Mobile database and not Stitch.


Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.