Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 135 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
[workspace]
members = [
"examples/async-sqlite",
"examples/hello-world",
"examples/cpu-count",
]
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ All examples are for [`napi-backend`][napi-migration]. For examples using `legac

## Table of Contents

| Example | Description |
| ---------------------------- | ------------------------------------------ |
| [`cpu-count`][cpu-count] | Return the number of CPUs |
| [`hello-world`][hello-world] | Return a JS String with a greeting message |

| Example | Description |
| ------------------------------ | ------------------------------------------ |
| [`async-sqlite`][async-sqlite] | Async interface to a SQLite database |
| [`cpu-count`][cpu-count] | Return the number of CPUs |
| [`hello-world`][hello-world] | Return a JS String with a greeting message |

[async-sqlite]: examples/async-sqlite
[cpu-count]: examples/cpu-count
[hello-world]: examples/hello-world

Expand Down
18 changes: 18 additions & 0 deletions examples/async-sqlite/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "async-sqlite"
version = "0.1.0"
description = "Neon Async SQLite"
license = "MIT"
edition = "2018"
exclude = ["index.node"]

[lib]
crate-type = ["cdylib"]

[dependencies]
rusqlite = "0.25"

[dependencies.neon]
version = "0.8"
default-features = false
features = ["napi-6", "event-queue-api", "try-catch-api"]
55 changes: 55 additions & 0 deletions examples/async-sqlite/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Async SQLite

The Async SQLite example implements a simple database in Rust with a JavaScript API.

## Usage

```js
const Database = require(".");

(async () => {
const db = new Database();

const id = await db.insert("Marty McFly");
const name = await db.byId(id);

console.log(name);
})();
```

## Design

### Rust

SQLite provides a _synchronous_ interface. This means that the current thread is blocked while a query is executing. Ideally, JavaScript would be able to continue executing concurrently with query execution.

The Async SQLite example demonstrates one pattern for moving database operations to a separate thread and asynchronously calling back to JavaScript when the operation has completed.

#### Threads and Channels

Since SQLite is naturally single threaded, our application does not benefit from a thread pool or connection pool when querying the database. Instead, a _single_ rust [thread][thread] is spawned for performing database operations.

Once the database thread is spawned, the JavaScript main thread needs a way to communicate with it. A [multi-producer, single-consumer (mpsc)][mpsc] channel is created. The receiving end is owned by the database thread and the sender is held by JavaScript.

#### `JsBox`

Rust data cannot be directly held by JavaScript. The [`JsBox`][jsbox] provides a mechanism for allowing JavaScript to hold a reference to Rust data and later access it again from Rust.

#### Channels and `EventQueue`

The mpsc channel provides a way for the JavaScript main thread to communicate with the database thread, but it is one-way. In order to complete the callback, the database thread must be able to communicate with the JavaScript main thread. [`EventQueue`][eventqueue] provides a channel for sending these events back.

#### `Root`

The last issue to solve is sending a reference to the JavaScript callback to the database thread and back again before finally calling it. [Handles][handle] to JavaScript values are not `Send`; they cannot escape the scope that created them. The reason they cannot be passed to other threads is because when control is returned back to the JavaScript engine, the garbage collector may determine they are no longer used and free the value.

A [`Root`][root] is a special handle to a JavaScript value that prevents the value from being freed as long as the `Root` has not been dropped. By placing the callback in a `Root`, it can be safely sent across threads and finally accessed and called when back on the JavaScript main thread.

### JavaScript

[thread]: https://doc.rust-lang.org/std/thread/
[mpsc]: https://doc.rust-lang.org/std/sync/mpsc/index.html
[jsbox]: https://docs.rs/neon/0.8.1-napi/neon/types/struct.JsBox.html
[eventqueue]: https://docs.rs/neon/0.8.1-napi/neon/event/struct.EventQueue.html
[handle]: https://docs.rs/neon/0.8.1-napi/neon/handle/struct.Handle.html
[root]: https://docs.rs/neon/0.8.1-napi/neon/handle/struct.Root.html
33 changes: 33 additions & 0 deletions examples/async-sqlite/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use strict";

const { promisify } = require("util");

const { databaseNew, databaseClose, databaseInsert, databaseGetById } = require("./index.node");

// Convert the DB methods from using callbacks to returning promises
const databaseInsertAsync = promisify(databaseInsert);
const databaseGetByIdAsync = promisify(databaseGetById);

// Wrapper class for the boxed `Database` for idiomatic JavaScript usage
class Database {
constructor() {
this.db = databaseNew();
}

// Wrap each method with a delegate to `this.db`
// This could be node in several other ways, for example binding assignment
// in the constructor
insert(name) {
return databaseInsertAsync.call(this.db, name);
}

byId(id) {
return databaseGetByIdAsync.call(this.db, id);
}

close() {
databaseClose.call(this.db);
}
}

module.exports = Database;
28 changes: 28 additions & 0 deletions examples/async-sqlite/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "async-sqlite",
"version": "0.1.0",
"description": "Neon Async SQLite",
"main": "index.js",
"scripts": {
"build": "cargo-cp-artifact -nc index.node -- cargo build --message-format=json-render-diagnostics",
"install": "npm run build",
"test": "mocha"
},
"license": "MIT",
"devDependencies": {
"cargo-cp-artifact": "^0.1",
"mocha": "^8.4.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/neon-bindings/examples.git"
},
"keywords": [
"Neon",
"Examples"
],
"bugs": {
"url": "https://github.com/neon-bindings/examples/issues"
},
"homepage": "https://github.com/neon-bindings/examples#readme"
}
Loading