• Stars
    star
    343
  • Rank 119,760 (Top 3 %)
  • Language
    Nim
  • License
    Apache License 2.0
  • Created about 6 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Chronos - An efficient library for asynchronous programming

Chronos - An efficient library for asynchronous programming

Github action License: Apache License: MIT Stability: experimental

Introduction

Chronos is an efficient async/await framework for Nim. Features include:

  • Efficient dispatch pipeline for asynchronous execution
  • HTTP server with SSL/TLS support out of the box (no OpenSSL needed)
  • Cancellation support
  • Synchronization primitivies like queues, events and locks
  • FIFO processing order of dispatch queue
  • Minimal exception effect support (see exception effects)

Installation

You can use Nim's official package manager Nimble to install Chronos:

nimble install chronos

or add a dependency to your .nimble file:

requires "chronos"

Projects using chronos

  • libp2p - Peer-to-Peer networking stack implemented in many languages
  • presto - REST API framework
  • Scorper - Web framework
  • 2DeFi - Decentralised file system
  • websock - WebSocket library with lots of features

chronos is available in the Nim Playground

Submit a PR to add yours!

Documentation

Concepts

Chronos implements the async/await paradigm in a self-contained library, using macros, with no specific helpers from the compiler.

Our event loop is called a "dispatcher" and a single instance per thread is created, as soon as one is needed.

To trigger a dispatcher's processing step, we need to call poll() - either directly or through a wrapper like runForever() or waitFor(). This step handles any file descriptors, timers and callbacks that are ready to be processed.

Future objects encapsulate the result of an async procedure, upon successful completion, and a list of callbacks to be scheduled after any type of completion - be that success, failure or cancellation.

(These explicit callbacks are rarely used outside Chronos, being replaced by implicit ones generated by async procedure execution and await chaining.)

Async procedures (those using the {.async.} pragma) return Future objects.

Inside an async procedure, you can await the future returned by another async procedure. At this point, control will be handled to the event loop until that future is completed.

Future completion is tested with Future.finished() and is defined as success, failure or cancellation. This means that a future is either pending or completed.

To differentiate between completion states, we have Future.failed() and Future.cancelled().

Dispatcher

You can run the "dispatcher" event loop forever, with runForever() which is defined as:

proc runForever*() =
  while true:
    poll()

You can also run it until a certain future is completed, with waitFor() which will also call Future.read() on it:

proc p(): Future[int] {.async.} =
  await sleepAsync(100.milliseconds)
  return 1

echo waitFor p() # prints "1"

waitFor() is defined like this:

proc waitFor*[T](fut: Future[T]): T =
  while not(fut.finished()):
    poll()
  return fut.read()

Async procedures and methods

The {.async.} pragma will transform a procedure (or a method) returning a specialised Future type into a closure iterator. If there is no return type specified, a Future[void] is returned.

proc p() {.async.} =
  await sleepAsync(100.milliseconds)

echo p().type # prints "Future[system.void]"

Whenever await is encountered inside an async procedure, control is passed back to the dispatcher for as many steps as it's necessary for the awaited future to complete successfully, fail or be cancelled. await calls the equivalent of Future.read() on the completed future and returns the encapsulated value.

proc p1() {.async.} =
  await sleepAsync(1.seconds)

proc p2() {.async.} =
  await sleepAsync(1.seconds)

proc p3() {.async.} =
  let
    fut1 = p1()
    fut2 = p2()
  # Just by executing the async procs, both resulting futures entered the
  # dispatcher's queue and their "clocks" started ticking.
  await fut1
  await fut2
  # Only one second passed while awaiting them both, not two.

waitFor p3()

Don't let await's behaviour of giving back control to the dispatcher surprise you. If an async procedure modifies global state, and you can't predict when it will start executing, the only way to avoid that state changing underneath your feet, in a certain section, is to not use await in it.

Error handling

Exceptions inheriting from CatchableError are caught by hidden try blocks and placed in the Future.error field, changing the future's status to Failed.

When a future is awaited, that exception is re-raised, only to be caught again by a hidden try block in the calling async procedure. That's how these exceptions move up the async chain.

A failed future's callbacks will still be scheduled, but it's not possible to resume execution from the point an exception was raised.

proc p1() {.async.} =
  await sleepAsync(1.seconds)
  raise newException(ValueError, "ValueError inherits from CatchableError")

proc p2() {.async.} =
  await sleepAsync(1.seconds)

proc p3() {.async.} =
  let
    fut1 = p1()
    fut2 = p2()
  await fut1
  echo "unreachable code here"
  await fut2

# `waitFor()` would call `Future.read()` unconditionally, which would raise the
# exception in `Future.error`.
let fut3 = p3()
while not(fut3.finished()):
  poll()

echo "fut3.state = ", fut3.state # "Failed"
if fut3.failed():
  echo "p3() failed: ", fut3.error.name, ": ", fut3.error.msg
  # prints "p3() failed: ValueError: ValueError inherits from CatchableError"

You can put the await in a try block, to deal with that exception sooner:

proc p3() {.async.} =
  let
    fut1 = p1()
    fut2 = p2()
  try:
    await fut1
  except CachableError:
    echo "p1() failed: ", fut1.error.name, ": ", fut1.error.msg
  echo "reachable code here"
  await fut2

Chronos does not allow that future continuations and other callbacks raise CatchableError - as such, calls to poll will never raise exceptions caused originating from tasks on the dispatcher queue. It is however possible that Defect that happen in tasks bubble up through poll as these are not caught by the transformation.

Platform independence

Several functions in chronos are backed by the operating system, such as waiting for network events, creating files and sockets etc. The specific exceptions that are raised by the OS is platform-dependent, thus such functions are declared as raising CatchableError but will in general raise something more specific. In particular, it's possible that some functions that are annotated as raising CatchableError only raise on some platforms - in order to work on all platforms, calling code must assume that they will raise even when they don't seem to do so on one platform.

Exception effects

chronos currently offers minimal support for exception effects and raises annotations. In general, during the async transformation, a generic except CatchableError handler is added around the entire function being transformed, in order to catch any exceptions and transfer them to the Future. Because of this, the effect system thinks no exceptions are "leaking" because in fact, exception handling is deferred to when the future is being read.

Effectively, this means that while code can be compiled with {.push raises: [Defect]}, the intended effect propagation and checking is disabled for async functions.

To enable checking exception effects in async code, enable strict mode with -d:chronosStrictException.

In the strict mode, async functions are checked such that they only raise CatchableError and thus must make sure to explicitly specify exception effects on forward declarations, callbacks and methods using {.raises: [CatchableError].} (or more strict) annotations.

Cancellation support

Any running Future can be cancelled. This can be used to launch multiple futures, and wait for one of them to finish, and cancel the rest of them, to add timeout, or to let the user cancel a running task.

# Simple cancellation
let future = sleepAsync(10.minutes)
future.cancel()

# Wait for cancellation
let future2 = sleepAsync(10.minutes)
await future2.cancelAndWait()

# Race between futures
proc retrievePage(uri: string): Future[string] {.async.} =
  # requires to import uri, chronos/apps/http/httpclient, stew/byteutils
  let httpSession = HttpSessionRef.new()
  try:
    resp = await httpSession.fetch(parseUri(uri))
    result = string.fromBytes(resp.data)
  finally:
    # be sure to always close the session
    await httpSession.closeWait()

let
  futs =
    @[
      retrievePage("https://duckduckgo.com/?q=chronos"),
      retrievePage("https://www.google.fr/search?q=chronos")
    ]

let finishedFut = await one(futs)
for fut in futs:
  if not fut.finished:
    fut.cancel()
echo "Result: ", await finishedFut

When an await is cancelled, it will raise a CancelledError:

proc c1 {.async.} =
  echo "Before sleep"
  try:
    await sleepAsync(10.minutes)
    echo "After sleep" # not reach due to cancellation
  except CancelledError as exc:
    echo "We got cancelled!"
    raise exc

proc c2 {.async.} =
  await c1()
  echo "Never reached, since the CancelledError got re-raised"

let work = c2()
waitFor(work.cancelAndWait())

The CancelledError will now travel up the stack like any other exception. It can be caught and handled (for instance, freeing some resources)

Multiple async backend support

Thanks to its powerful macro support, Nim allows async/await to be implemented in libraries with only minimal support from the language - as such, multiple async libraries exist, including chronos and asyncdispatch, and more may come to be developed in the futures.

Libraries built on top of async/await may wish to support multiple async backends - the best way to do so is to create separate modules for each backend that may be imported side-by-side - see nim-metrics for an example.

An alternative way is to select backend using a global compile flag - this method makes it diffucult to compose applications that use both backends as may happen with transitive dependencies, but may be appropriate in some cases - libraries choosing this path should call the flag asyncBackend, allowing applications to choose the backend with -d:asyncBackend=<backend_name>.

Known async backends include:

  • chronos - this library (-d:asyncBackend=chronos)
  • asyncdispatch the standard library asyncdispatch module (-d:asyncBackend=asyncdispatch)
  • none - -d:asyncBackend=none - disable async support completely

none can be used when a library supports both a synchronous and asynchronous API, to disable the latter.

Compile-time configuration

chronos contains several compile-time configuration options enabling stricter compile-time checks and debugging helpers whose runtime cost may be significant.

Strictness options generally will become default in future chronos releases and allow adapting existing code without changing the new version - see the config.nim module for more information.

TODO

  • Pipe/Subprocess Transports.
  • Multithreading Stream/Datagram servers

Contributing

When submitting pull requests, please add test cases for any new features or fixes and make sure nimble test is still able to execute the entire test suite successfully.

chronos follows the Status Nim Style Guide.

Other resources

License

Licensed and distributed under either of

or

at your option. These files may not be copied, modified, or distributed except according to those terms.

More Repositories

1

status-mobile

a free (libre) open source, mobile OS for Ethereum
Clojure
3,831
star
2

react-native-desktop-qt

A Desktop port of React Native, driven by Qt, forked from Canonical
JavaScript
1,194
star
3

status-go

The Status module that consumes go-ethereum
Go
715
star
4

nimbus-eth1

Nimbus: an Ethereum Execution Client for Resource-Restricted Devices
Nim
552
star
5

nimbus-eth2

Nim implementation of the Ethereum Beacon Chain
Nim
489
star
6

status-desktop

Status Desktop client made in Nim & QML
QML
259
star
7

status-keycard

Our Javacard Implementation for making secure transactions within Status and Ethereum
Java
195
star
8

status-network-token

Smart Contracts for the Status Contribution Period, along with Genesis and Network Tokens
JavaScript
148
star
9

nim-chronicles

A crafty implementation of structured logging for Nim.
Nim
138
star
10

open-bounty

Enable communities to distribute funds to push their cause forward.
JavaScript
119
star
11

nim-stew

stew is collection of utilities, std library extensions and budding libraries that are frequently used at Status, but are too small to deserve their own git repository.
Nim
119
star
12

doubleratchet

The Double Ratchet Algorithm implementation in Go
Go
108
star
13

nim-faststreams

Nearly zero-overhead input/output streams for Nim
Nim
107
star
14

nim-taskpools

Lightweight, energy-efficient, easily auditable threadpool
Nim
98
star
15

swarms

Swarm Home. New, completed and in-progress features for Status
HTML
92
star
16

contracts

Python
87
star
17

nim-json-rpc

Nim library for implementing JSON-RPC clients and servers
Nim
84
star
18

status-web

TypeScript
77
star
19

nim-websock

Websocket for Nim
Nim
74
star
20

questionable

Elegant optional types for Nim
Nim
73
star
21

nim-stint

Stack-based arbitrary-precision integers - Fast and portable with natural syntax for resource-restricted devices.
Nim
73
star
22

nim-eth

Common utilities for Ethereum
Nim
69
star
23

nim-graphql

Nim implementation of GraphQL with sugar and steroids
Nim
64
star
24

nim-drchaos

A powerful and easy-to-use fuzzing framework in Nim for C/C++/Obj-C targets
Nim
63
star
25

clj-rn

A utility for building ClojureScript-based React Native apps
Clojure
56
star
26

nim-confutils

Simplified handling of command line options and config files
Nim
56
star
27

nim-serialization

A modern and extensible serialization framework for Nim
Nim
54
star
28

nim-presto

REST API framework for Nim language
Nim
47
star
29

keycard-cli

A command line tool and shell to manage keycards
Go
45
star
30

nim-json-serialization

Flexible JSON serialization not relying on run-time type information
Nim
39
star
31

nim-quic

QUIC for Nim
Nim
39
star
32

keycard-go

Go pkg to interact with the Status Keycard
Go
39
star
33

nim-metrics

Nim metrics client library supporting the Prometheus monitoring toolkit, StatsD and Carbon
Nim
38
star
34

nim-web3

Nim
37
star
35

nim-bearssl

BearSSL wrapper in Nim
C
37
star
36

ETHPrize-interviews

A repository for the ETHPrize website.
HTML
36
star
37

nim-codex

Decentralized Durability Engine
Nim
36
star
38

nim-toml-serialization

Flexible TOML serialization [not] relying on run-time type information.
Nim
34
star
39

hackathon

Status API Hackathon
JavaScript
32
star
40

nim-rocksdb

Nim wrapper for RocksDB, a persistent key-value store for Flash and RAM Storage.
Nim
29
star
41

nim-daemon

Cross-platform process daemonization library for Nim language
Nim
28
star
42

status-electron

[OUTDATED NOT SUPPORTED] Status Electron (React Native Web and Electron)
Clojure
27
star
43

nim-style-guide

Status style guid for the Nim language
Nim
26
star
44

StatusQ

Reusable Status QML components
QML
26
star
45

status-teller-network

DApp which provides a platform for borderless, peer-to-peer, fiat-to-crypto echanges that allows Stakeholders to find nearby users to exchange their cash for digital assets and currency.
JavaScript
26
star
46

nim-decimal

A correctly-rounded arbitrary precision decimal floating point arithmetic library
C
26
star
47

codex-research

Codex durability engine research
Jupyter Notebook
25
star
48

nim-http-utils

Nim language HTTP helper procedures
Nim
25
star
49

vyper-debug

Easy to use Vyper debugger | vdb (https://github.com/ethereum/vyper)
Python
24
star
50

react-native-status-keycard

React Native library to interact with Status Keycard using NFC connection
Java
24
star
51

nim-unittest2

Beautiful and efficient unit testing for Nim evolved from the standard library `unittest` module
Nim
24
star
52

mingw-windows10-uwp

Minimal Windows 10 Store ready sample of MinGW dll PInvoked from Windows 10 UWP application
C#
24
star
53

wiki.status.im

It's the wiki... for Status
HTML
24
star
54

nim-snappy

Nim implementation of Snappy compression algorithm
Nim
24
star
55

CryptoLife

A repo for all the #CryptoLife Hackathon submissions, The National House Smichov, Prague, 26-28th October 2018.
23
star
56

status-chat-widget

Easily embed a status chatroom in your website - outdated, please use https://github.com/status-im/js-waku
JavaScript
22
star
57

nim-blscurve

Nim implementation of BLS signature scheme (Boneh-Lynn-Shacham) over Barreto-Lynn-Scott (BLS) curve BLS12-381
C
22
star
58

keycard-connect

Keycard + WalletConnect
Kotlin
21
star
59

nimplay

Nim Ethereum Contract DSL. Targeting eWASM.
Nim
20
star
60

whisper-tutorial

Whisper Tutorial using web3js
JavaScript
20
star
61

nim-cookbook

Nim
20
star
62

ens-usernames

DApp to register usernames for Status Network
JavaScript
19
star
63

status-keycard-java

Java SDK for the Status Keycard
Java
19
star
64

Keycard.swift

Swift
19
star
65

account-contracts

Key managers, recovery, gas abstraction and self-sovereign identity for web3 universal login.
Solidity
19
star
66

ethereumj-personal

EthereumJ for Personal Devices DEPRECATED
Java
19
star
67

liquid-funding

Dapp for delegating donations to projects
JavaScript
19
star
68

nim-protobuf-serialization

Nim
17
star
69

nim-testutils

testrunner et al
Nim
17
star
70

general-market-framework

A Generalised Market Framework for Ethereum
Python
16
star
71

nim-libbacktrace

Nim wrapper for libbacktrace
C
16
star
72

wallet

CSS
16
star
73

react-native-transparent-video

React Native video player with alpha channel (alpha-packing) support.
Java
16
star
74

go-maven-resolver

Tool for resolving Java Maven dependencies
Go
15
star
75

murmur

WIP - Whisper node / client implementation built in javascript
JavaScript
15
star
76

bigbrother-specs

Research and specification for Big Brother protocol
14
star
77

status-dev-cli

Status command-line tools
JavaScript
14
star
78

nim-evmc

Nim EVMC - Ethereum VM binary compatible interface
Nim
14
star
79

keycard-installer-android

discontinued, use https://github.com/status-im/keycard-cli - Keycard applet installer over NFC
Java
14
star
80

specs

Specifications for Status clients.
HTML
14
star
81

nescience

A Zero-Knowledge Toolkit
Nim
13
star
82

move

MOVΞ - A Decentralised Ride Sharing DApp
JavaScript
13
star
83

geth_exporter

geth metrics exporter for Prometheus
Go
13
star
84

autobounty

Github bot that automatically funds https://openbounty.status.im bounties
JavaScript
13
star
85

status-security

Repository for all Status Network related security information
JavaScript
13
star
86

snt-gas-relay

SNT Gas Relay
JavaScript
13
star
87

nim-ttmath

C++
12
star
88

nim-eth-p2p

Nim Ethereum P2P protocol implementation
Nim
11
star
89

keycard-redeem

TypeScript
11
star
90

status-github-bot

A bot for github
JavaScript
11
star
91

syng-client

The Mobile Client for the Ethereum Network DEPRECATED
Java
11
star
92

dreddit-devcon

JavaScript
11
star
93

keycard-pro

WIP
C
11
star
94

embark-status

Provides an ability to debug Embark DApps in Status
JavaScript
11
star
95

pluto

Clojure
11
star
96

snt-voting

JavaScript
11
star
97

nimbus-launch

Jumpstart your Nim project at Status
Nim
11
star
98

nim-eth-contracts

Ethereum smart contracts in Nim
Nim
10
star
99

translate.status.im

Help translate Status into your language!
JavaScript
10
star
100

nim-ssz-serialization

Nim implementation of Simple Serialize (SSZ) serialization and merkleization
Nim
10
star