Microsoft Azure SDK for Rust

Introduction

Microsoft Azure exposes its technologies via REST API. These APIs are easily consumable from any language (good) but are weakly typed. With this library and its related crate you can exploit the power of Microsoft Azure from Rust in a idiomatic way.

This crate relies heavily on the excellent crate called Hyper. As of this library version 0.4.0 all the methods are future-aware.

From version 0.8.0 for Cosmos and 0.9.0 for Storage the repo is embracing the builder pattern. As of 0.10.0, most of storage APIs have been migrated to the builder pattern but there are methods still missing. Please chech the relevant issues to follow the update process. This is still an in-progress transition but the resulting API is much more easy to use. Also most checks have been moved to compile-time. Unfortunately the changes are not backward-compatibile. I have blogged about my appoach here: https://dev.to/mindflavor/rust-builder-pattern-with-types-3chf.

NOTE: This repository is under heavy development and is likely to break over time. The current releases will probabily contain bugs. As usual open issues if you find any.

Disclaimer

Although I am a Microsoft employee, this is not a Microsoft endorsed project. It's simply a pet project of mine: I love Rust (who doesn't? 😏) and Microsoft Azure technologies so I thought to close the gap between them. It's also a good project for learning Rust. This library relies heavily on Hyper. We use the latest Hyper code so this library is fully async with Futures and Tokio.

Example

main.rs

externcrate azure_sdk_for_rust;externcrate chrono;externcrate futures;externcrate hyper;externcrate hyper_tls;externcrate tokio;externcrate tokio_core;usestd::error::Error;usefutures::future::*;usetokio_core::reactor::Core;useazure_sdk_for_rust::cosmos::{AuthorizationToken, Client, TokenType};#[macro_use]externcrate serde_derive;useazure_sdk_for_rust::cosmos;#[derive(Serialize, Deserialize, Debug)]structMySampleStruct<'a>{id:&'astr,
a_string:&'astr,
a_number:u64,
a_timestamp:i64,
}// Following the official azure cosmos db tutorial: https://docs.microsoft.com/pt-br/azure/cosmos-db/sql-api-dotnetcore-get-started// Master key is the Primary Key from Keys section in your CosmosDB screen// Account is the first part of URI from Keys section, if your URI is https://test.documents.azure.com:443/ the account is test// DATABASES are the base objects in your Data Explorer section// COLLECTIONS are the objects inside the DATABASESconstDATABASE:&'staticstr="azuresdktestdb";constCOLLECTION:&'staticstr="azuresdktc";fnmain(){code().unwrap();}// This code will perform these tasks:// 1. Find an Azure Cosmos DB called *DATABASE*. If it does not exist, create it.// 2. Find an Azure Cosmos collection called *COLLECTION* in *DATABASE*.// If it does not exist, create it.// 3. Store an entry in collection *COLLECTION* of database *DATABASE*.// 4. Delete everything.//// We will use multiple futures for this hoping to make the code clearer.// There is no need to proceed this way in your code.// You can go crazy with future combinators if you want to :)fncode()->Result<(), Box<Error>>{// Let's get Cosmos account and master key from env variables.// This helps automated testing.let master_key =std::env::var("COSMOSDB_MASTER_KEY").expect("Set env variable COSMOS_MASTER_KEY first!");let account =std::env::var("COSMOSDB_ACCOUNT").expect("Set env variable COSMOS_ACCOUNT first!");// First, we create an authorization token. There are two types of tokens, master and resource// constrained. Please check the Azure documentation for details. You can change tokens// at will and it's a good practice to raise your privileges only when needed.let authorization_token =AuthorizationToken::new(account,TokenType::Master,&master_key)?;// We will create a tokio-core reactor which will drive our futures.letmut core =Core::new()?;// Next we will create a Cosmos client. You need an authorization_token but you can later// change it if needed. Notice the client will be tied to your reactor.let client =Client::new(authorization_token)?;// list_databases will give us the databases available in our account. If there is// an error (for example, the given key is not valid) you will receive a// specific AzureError. In this example we will look for a specific database// so we chain a filter operation.let future = client
.list_databases().and_then(|databases|ok(databases.into_iter().find(|db| db.id ==DATABASE)));// Now we run the future and check the answer. If the requested database// is not found we create it.let database =match core.run(future)?{Some(db)=> db,None=> core.run(client.create_database(DATABASE))?,};println!("database == {:?}", database);// Now we look for a specific collection. If is not already present// we will create it. The collection creation is more complex and// has many options (such as indexing and so on).let collection ={let collections = core.run(client.list_collections(&DATABASE))?;ifletSome(collection)= collections.into_iter().find(|coll|coll.id ==COLLECTION){
collection
}else{let indexes =cosmos::collection::IncludedPathIndex {
kind:cosmos::collection::KeyKind::Hash,
data_type:cosmos::collection::DataType::String,
precision:Some(3),};let ip =cosmos::collection::IncludedPath {
path:"/*".to_owned(),
indexes:vec![indexes],};let ip =cosmos::collection::IndexingPolicy {
automatic:true,
indexing_mode:cosmos::collection::IndexingMode::Consistent,
included_paths:vec![ip],
excluded_paths:vec![],};let coll =cosmos::collection::Collection::new(COLLECTION, ip);// Notice here we specify the expected performance level.// Performance levels have price impact. Also, higher// performance levels force you to specify an indexing// strategy. Consult the documentation for more details.
core.run(client.create_collection(&DATABASE,400,&coll))?}};println!("collection = {:?}", collection);// Now that we have a database and a collection we can insert// data in them. Let's create a struct. The only constraint// is that the struct should be Serializable.let doc = MySampleStruct {
id:"unique_id1",
a_string:"Something here",
a_number:100,
a_timestamp:chrono::Utc::now().timestamp(),};// Now we store the struct in Azure Cosmos DB.// Notice how easy it is! :)// The method create_document will return, upon success,// the document attributes.let document_attributes = core.run(
client
.create_document(&DATABASE,&COLLECTION,&doc).execute(),)?;println!("document_attributes == {:?}", document_attributes);// We will perform some cleanup. First we delete the collection...
core.run(client.delete_collection(DATABASE,&COLLECTION))?;println!("collection deleted");// And then we delete the database.
core.run(client.delete_database(DATABASE))?;println!("database deleted");Ok(())}

State of the art

Right now the key framework is in place (authentication, enumerations, parsing and so on). If you want to contribute please do!
Methods are added daily so please check the release page for updates on the progress.
Also note that the project is in early stages so the APIs are bound to change at any moment. I will strive to keep things steady but since I'm new to Rust I'm sure I'll have to correct some serious mistake before too long 😄.
I generally build for the latest nightly and leave to Travis to check the retrocompatibility.

Contributing

If you want to contribute please do! No formality required! 😉. Please note that asking for a pull request you accept to yield your code as per Apache license, version 2.0.