📜 ⬆️ ⬇️

Using Chakra and JavaScript in Azure DocumentDB

We offer you a translation of the article " Running JavaScript in Azure DocumentDB with Chakra " by Andrew Liu (Program Manager, Azure DocumentDB) and Limin Zhu (Program Manager, Chakra).

Chakra is a JavaScript engine used in Microsoft Edge and universal Windows applications. Beginning with Windows 8.1 and Windows Server 2012 R2, Chakra has a new set of embedding APIs ( JavaScript Runtime , or JSRT API), which allows Chakra to be used outside of the mentioned client scripts.



Azure DocumentDB was one of the first services with built-in Chakra, used for the native implementation of scripting capabilities in the database engine. With the recent announcement of the opening of the key components of Chakra ( ChakraCore ) on GitHub, we are also pleased to share our experience and future plans for the use of Chakra.

Using JavaScript in a NoSQL database


Azure DocumentDB is a NoSQL database service optimized for writing and focused on working with documents. The service is initially designed to support natively work with JSON and JavaScript. Originating from JavaScript object expressions, JSON is often used when transmitting structured and partially structured data.
')
DocumentDB uses Chakra to implement programmable features in the server part, including transactional execution of logic in JavScript natively within the database engine. It seems to us that the approach using JavaScript as a modern alternative to T-SQL provides developers with a natural interface for implementing business logic expressed in the form of server scripts ( stored procedures, triggers and user-defined functions ) in DocumentDB.

As an example, let's take a look at stored procedures in order to understand how Chakra is used in DocumentDB. As developers, you can register and run stored procedures written in JavaScript to perform a batch or sequential set of operations on many documents using a single ACID transaction. When a tenant registers a stored procedure, Chakra pre-compiles it into bytecode.

Further, when the tenant launches the procedure, the Chakra runtime executes the corresponding script in its sandbox, taking into account the existing resource constraints. The runtime implements tight integration between the JavaScript program model and the isolated database state snapshot. Until the stored procedure is successful, all operations in the database are implemented as part of a single transaction. In the event of an exception in the DocumentDB script, the entire transaction is automatically rolled back.



Let's take a closer look at some of the features of Chakra and their use in DocumentDB.

Rental streams


Chakra implements the rental flow model, in which the JavaScript runtime always runs in one flow, but is not tied tightly to a specific flow. In other words, the runtime environment runs at the same time in one thread, but the binding to a particular thread may change over time.

The lease of threads is well suited for DocumentDB, as it manages a set of execution environments and can assign an environment for each tenant to perform JavaScript. This avoids the cost of unnecessary initialization of new execution environments for each tenant, while DocumentDB can maintain the security and isolation of each tenant.

Bytecode serialization


After registering the server-side script, DocumentDB uses Chakra to precompile and serialize the script into bytecode. In the normal execution chain of the JavaScript engine, it is necessary to parse the code, create a syntax tree and generate bytecode before execution. Bytecode serialization in Chakra allows DocumentDB to process the script in advance, up to the generation of bytecode and save the cached copy for later reuse. This allows you to save on re-analysis of the code before each execution, which gives a significant gain in speed of execution.

Resource Management API


DocumentDB is designed as a multi-tenant service, in which strict resource management and tenant isolation are critical to prevent "annoying neighborhood problems." Any integrated components must implement their activities within extremely limited system resources and integrate them into a common resource management and tenant isolation system in DocumentDB.

If we allow one of the scripts in the tenant to consume additional resources, this may affect the performance of all tenants or even disrupt the entire service. Chakra exposes the APIs that DocumentDB uses to solve this problem, allowing the database to interrupt script execution in the event that the consumption of CPU or memory resources is out of range.

Switch to ChakraCore


As you know, the Chakra team recently opened up key engine components as part of the ChakraCore project. ChakraCore implements almost the same features as Chakra, and is designed as a self-contained JavaScript engine, which will be further developed in the open form. We from DocumentDB have already included in our migration plans from Chakra to ChakraCore in the near future. This step will allow us to provide users with additional benefits, while retaining the possibilities voiced above. We also plan to contribute to the development of the engine.

ECMAScript 6 Features


The past year has been particularly remarkable for the JavaScript community, given the final adoption of the ECMAScript 6 standard (ES6, or officially ES2015) - perhaps the most significant JavaScript update ever. A variety of new features and syntax buns implemented in ES6 received a lot of recognition from the community.

ChakraCore already implements many of the features of ES6. Migrating DocumentDB to a new engine will allow developers to use even more convenient JavaScript code to work with databases, for example, to simplify data processing using ES6 promises. The following is an example of a stored procedure using promises and switch functions from ES6:

function swapPlayerInventories(playerId1, playerId2) { __.filter(document => {return document.id == playerId1 || document.id == playerId2;}) .then(playersToSwap => { var player1 = playersToSwap[0], player2 = playersToSwap[1]; var player1ItemTemp = player1.item; player1.item = player2.item; player2.item = player1ItemTemp; return __.replaceDocument(player1); }) .then(() => __.replaceDocument(player2)) .catch(error => { throw 'Unable to update players, rollback transaction.';} ); } 


And a few more words


Using Chakra was a great success for us, we look forward to further developing the service with migration to ChakraCore. A wiki with embedding instructions is a good starting point for exploring how to integrate ChakraCore into your applications.

If you have feedback for the Chakra team, you can open a request for GitHub or contact them on twitter @ChakraCore .

You can learn more about the DocumentDB software model from the server side in the documentation pages . If you have any questions about DocumentDB, contact us on the StackOverflow forums or schedule a 1: 1 chat with DocumentDB engineering team. You can follow the latest news and announcements of new features in our twitter @DocumentDB .

Source: https://habr.com/ru/post/275463/


All Articles