• Stars
    star
    279
  • Rank 147,967 (Top 3 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 11 years ago
  • Updated 8 months ago

Reviews

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

Repository Details

Flow control and error handling for Node.js

NOTE: This project is deprecated and no longer being actively developed or maintained. See Issue #50 for details.

StrongLoop zone library

Overview

The Zone library provides a way to represent the dynamic extent of asynchronous calls in Node. Just like the scope of a function defines where it may be used, the extent of a call represents the lifetime that is it active.

A Zone also provides execution context that can persist across the lifecycle of one or more asynchronous calls. This is similar to the concept of thread-local data in Java.

Zones provide a way to group and track resources and errors across asynchronous operations. In addition zones:

  • Enables more effective debugging by providing better stack traces for asynchronous functions
  • Makes it easier to write and understand asynchronous functions for Node applications
  • Makes it easier to handle errors raised asynchronously and avoid resulting resource leaks
  • Enables you to associate user data with asynchronous control flow

Dart's async library and Brian Ford's zone.js library provide similar functionality.

Implementation status

  • The zone library dynamically modifies Node's asynchronous APIs at runtime. As detailed below, some of the modules have not yet been completed, and thus you cannot use them with zones.

    The following modules have not been zone enabled:

    • cluster
    • crypto: pbkdf2, randomBytes, pseudoRandomBytes
    • fs: fs.watch, fs.watchFile, fs.FSWatcher
    • process object: process.on('SIGHUP') and other signals.
    • tls / https
    • udp
    • zlib

Using zones

To use zones, add the following as the very first line of your program:

require('zone').enable();

The zone library exports a global variable, zone. The zone global variable always refers to the currently active zone. Some methods that can always be found on the 'zone' object are actually static methods of the Zone class, so they don't do anything with the currently active zone.

After loading the zone library the program has entered the 'root' zone.

Creating a zone

There are a few different ways to create a zone. The canonical way to create a one-off zone is:

// Load the library
require('zone').enable();

// MyZone is the name of this zone which shows up in stack traces.
zone.create(function MyZone() {
  // At this point the 'zone' global points at the zone instance ("MyZone")
  // that we just created.
});

The zone constructor function is called synchronously.

Defining zone functions

Under some circumstances it may be desirable to create a function that is always wrapped within a zone. The obvious way to do this:

function renderTemplate(fileName, cb) {
  zone.create(function() {
    // Actual work here
    ...
  }).setCallback(cb);
}

To make this a little less verbose there is the 'zone.define()' API. With it you can wrap a function such that when it's called a zone is created. Example:

var renderTemplate = zone.define(function(fileName, cb) {
  zone.setCallback(cb);
  // Actual work here
  ...
});

Now you can use this zone template as follows:

renderTemplate('bar', function(err, result) {
  if (err)
    throw err;
  // Do something with the result
  ...
});

Obtaining the result of a zone

Zones are like asynchronous functions. From the outside perspective, they can return a single value or "throw" a single error. There are a couple of ways the outside zone may obtain the result of a zone. When a zone reports its outcome:

  • No more callbacks will run inside the zone.
  • All non-garbage-collectable resources have been cleaned up.

Zones also automatically exit when no explicit value is returned.

A way to obtain the outcome of a zone is:

require('zone').enable();
var net = require('net');

zone.create(function MyZone() {
  // This runs in the context of MyZone
  net.createConnection(...);
  fs.stat(...)

  if (Math.random() < 0.5)
    throw new Error('Chaos monkey!');
  else if (Math.random() < 0.5)
    zone.return('Chaos monkey in disguise!');
  else
    ; // Wait for the zone to auto-exit.

}).setCallback(function(err, result) {
  // Here we're back in the root zone.
  // Asynchronicity is guaranteed, even if the zone returns or throws immediately.
  // By the time we get here we are sure:
  //   * the connection has been closed one way or another
  //   * fs.stat has completed
});

You can also use the then and catch methods, as if it were a promise. Note that unlike promises you can't currently chain calls callbacks.

zone.create(function MyZone() {
  // Do whatever
}).then(function(result) {
  // Runs when succesful
}).catch(function(err) {
  // Handle error
});

Sharing resources between zones

Within a zone you may use resources that are "owned" by ancestor zones. So this is okay:

var server = http.createServer().listen(1234);
server.listen(1234);

zone.create(function ServerZone() {
  // Yes, allowed.
  server.on('connection', function(req, res) { ... });

  // Totally okay
  process.stdout.write('hello!');
});

However, using resources owned by child zones is not allowed:

var server;

zone.create(function SomeZone() {
 server = http.createServer().listen(1234);
});

// NOT OKAY!
server.on('connection', function() { ... });

NOTE: Currently zones don't always enforce these rules, but you're not supposed to do this. It would also be dumb, since the server will disappear when SomeZone() exits itself!

The rules of engagement

It is okay for a zone to temporarily enter an ancestor zone. It is not allowed to enter child zones, siblings, etc. The rationale behind this is that when a zone is alive its parent must also be alive. Other zones may exit unless they are aware that code will run inside them.

zone.create(function OuterZone() {
  var childZone = zone.create(function ChildZone() {
    ...
  });

  // Fine.
  zone.parent.run(function() {
    console.log('Hello from the root zone!');
  });

  // NOT ALLOWED
  childZone.run(function() {
    console.log('Weird. This isn't supposed to work!');
  });
});

Exiting a zone

There are a few ways to explicitly exit a zone:

  • zone.return(value) sets the return value of the zone and starts cleanup.
  • zone.throw(error) sets the zone to failed state and starts cleanup. zone.throw itself does not throw, so statements after it will run.
  • throw error uses normal exception handling. If the exception is not caught before it reaches the binding layer, the active zone is set to failed state and starts cleanup.
  • zone.complete(err, value) is a zone-bound function that may be passed to subordinates to let them exit the zone.

A rather pointless example:

zone.create(function StatZone() {
  fs.stat('/some/file', function(err, result) {
    if (err)
      throw err;
    else
      zone.return(result);
  });
});

This is equivalent to:

zone.create(function StatZone() {
  fs.stat('/some/file', zone.complete);
});

To run code in a child zone, you can use zone.bindCallback and zone.bindAsyncCallback to create a callback object which can be invoked from a parent zone.

Sharing resources between zones

Within a zone you may use resources that are "owned" by ancestor zones. So this is okay:

var server = http.createServer().listen(1234);
server.listen(1234);

zone.create(function ServerZone() {
  // Yes, allowed.
  server.on('connection', function(req, res) { ... });

  // Totally okay
  process.stdout.write('hello!');
});

However, using resources owned by child zones is not allowed:

var server;

zone.create(function SomeZone() {
 server = http.createServer().listen(1234);
});

// NOT OKAY!
server.on('connection', function() { ... });

NOTE: Currently zones don't always enforce these rules, but you're not supposed to do this. It would also be dumb, since the server will disappear when SomeZone() exits itself!

Zone.data

zone.data is a magical property that that associates arbitrary data with a zone. In a way you can think of it as the 'scope' of a zone. Properties that are not explicitly defined within the scope of a zone are inherited from the parent zone.

  • In the root zone, zone.data equals the global object.
  • In any other zone, zone.data starts off as an empty object with the parent zone's data property as it's prototype.
  • In other words, zone.data.__proto__ === zone.parent.data.

More Repositories

1

loopback

LoopBack makes it easy to build modern applications that require complex integrations.
JavaScript
13,228
star
2

node-foreman

A Node.js Version of Foreman
JavaScript
1,257
star
3

microgateway

IBM API Connect Microgateway framework, built on Node.js & Nginx
JavaScript
1,193
star
4

strong-pm

deployer for node applications
JavaScript
998
star
5

loopback-example-access-control

An example demonstrating LoopBack access control mechanisms.
JavaScript
370
star
6

strongloop

StrongLoop: Enterprise Node to Power the API Economy
JavaScript
332
star
7

loopback-example-offline-sync

Offline sync, change tracking, and replication.
JavaScript
286
star
8

loopback-example-user-management

LoopBack user management example
JavaScript
189
star
9

loopback-example-passport

LoopBack example for facebook login
HTML
186
star
10

generator-loopback

Yeoman generator that scaffolds out a LoopBack application
JavaScript
158
star
11

loopback-sdk-angular

Service for auto-generating Angular $resource services for LoopBack
JavaScript
155
star
12

loopback-component-passport

LoopBack passport integration to support third party logins and account linking
JavaScript
139
star
13

loopback-component-storage

Storage component for LoopBack.
JavaScript
130
star
14

strong-pubsub

PubSub for Node.js, Browser, Mobile and IoT
JavaScript
129
star
15

loopback-example-database

A tutorial for basic database related features.
JavaScript
120
star
16

strong-arc

StrongLoop Arc has been replaced by API Connect. We recommend Arc users move to the Essentials edition of API Connect. If you have questions, please email [email protected].
JavaScript
114
star
17

loopback-cli

LoopBack CLI tool for creating projects, models and more.
JavaScript
105
star
18

strong-remoting

Communicate between objects in servers, mobile apps, and other servers.
JavaScript
104
star
19

angular-live-set

Build realtime angular apps with html5's Server Sent Events
JavaScript
101
star
20

strong-cluster-control

cluster control module, allowing run-time control and monitoring of cluster
JavaScript
100
star
21

loopback-example-angular

A simple todo list using AngularJS on the client-side and LoopBack on the server-side.
JavaScript
97
star
22

loopback-component-push

Push notification component for LoopBack.
JavaScript
96
star
23

loopback4-example-microservices

Deprecated - please use https://github.com/strongloop/loopback4-example-shopping/tree/master/kubernetes
TypeScript
88
star
24

loopback-getting-started

Getting started example for LoopBack
TSQL
87
star
25

loopback-example-relations

Basic model relations concepts.
JavaScript
80
star
26

loopback-component-explorer

Browse and test your LoopBack app's APIs
JavaScript
71
star
27

loopback-example-ssl

An example to demonstrate how to set up SSL for LoopBack applications
JavaScript
69
star
28

loopback-getting-started-intermediate

JavaScript
68
star
29

loopback-example-facade

Best practices for building scalable Microservices.
JavaScript
67
star
30

strong-supervisor

Application supervisor that automatically adds cluster control and performance monitoring with StrongOps
JavaScript
66
star
31

loopback-boot

Convention-based bootstrapper for LoopBack applications
JavaScript
62
star
32

loopback-component-oauth2

oAuth 2.0 server for LoopBack
JavaScript
62
star
33

strong-agent

Profile, control, and monitor Node.js processes and clusters
JavaScript
61
star
34

strong-mq

MQ API with cluster integration, implemented over various message queues.
JavaScript
56
star
35

loopback-filters

implements LoopBack-style filtering.
JavaScript
55
star
36

modern-syslog

modern-syslog
JavaScript
49
star
37

loopback-example-app-logic

How to add your own business logic in a LoopBack app.
JavaScript
49
star
38

loopback-workspace

Manage a directory of LoopBack projects for a user, team, or organization
JavaScript
49
star
39

loopback-example-angular-live-set

Example of realtime angular app using html5 Server-sent events
JavaScript
48
star
40

strong-build

Build node packages into deployable applications
JavaScript
47
star
41

strong-oracle

Deprecated: Node.js Driver for Oracle databases (Use https://github.com/oracle/node-oracledb instead)
C++
45
star
42

loopback-swagger

LoopBack Swagger Spec Integration
JavaScript
44
star
43

loopback-example-storage

Example for loopback-component-storage.
HTML
43
star
44

supercluster

A module to make it easy to distribute work across multiple network-connected hosts.
JavaScript
30
star
45

loopback-sdk-angular-cli

CLI tools for auto-generating Angular $resource services for LoopBack
JavaScript
29
star
46

gulp-loopback-sdk-angular

gulp plugin for auto-generating Angular $resource services for LoopBack
JavaScript
27
star
47

apiconnect-docker

IBM API Connect on Docker
Shell
26
star
48

strong-globalize

strong-globalize is built on Unicode CLDR and jquery/globalize and implements automatic extraction of strings from JS source code and HTML templates, lint the string resource, machine-translate them in seconds. In runtime, it loads locale and string resource into memory and provides a hook to persistent logging.
JavaScript
25
star
49

loopback-context

Current context for LoopBack applications, based on node-continuation-local-storage
JavaScript
25
star
50

grunt-loopback-sdk-angular

Grunt plugin for auto-generating Angular $resource services for LoopBack
JavaScript
23
star
51

strong-cluster-socket.io-store

Implementation of socket.io store using node's native cluster messaging
JavaScript
23
star
52

loopback-connector-remote

LoopBack remote REST API connector
JavaScript
22
star
53

eslint-config-loopback

LoopBack's ESLint shareable configs.
20
star
54

strongloop-buildpacks

Shell
19
star
55

loopback-connector-swagger

Connect Loopback to a Swagger-compliant API
JavaScript
19
star
56

loopback-multitenant-poc

LoopBack Multitenancy PoC
JavaScript
19
star
57

flow-engine

JavaScript
18
star
58

loopback-example-mixins

Example app demonstrating mixins
JavaScript
17
star
59

eslint-config-strongloop

Baseline eslint configuration for StrongLoop modules
JavaScript
17
star
60

async-tracker

The AsyncTracker API is the JavaScript interface which allows developers to be notified about key events in the lifetime of observed objects and scheduled asynchronous events.
JavaScript
16
star
61

strong-express-metrics

An Express middleware for collecting HTTP statistics.
JavaScript
15
star
62

strong-store-cluster

JavaScript
14
star
63

strong-pubsub-example

Simple example app using strong-pubsub
JavaScript
14
star
64

strong-docs

build documentation sites for your node modules
TypeScript
14
star
65

loopback-connector-jsonrpc

Loopback Connector for JSONRPC
JavaScript
13
star
66

strong-deploy

Deploy nodejs applications
JavaScript
13
star
67

strong-data-uri

Parser and encoder for `data:` URIs
JavaScript
13
star
68

loopback-example-polyglot

Example LoopBack application with polyglot runtimes
JavaScript
13
star
69

loopback-example-push

Push notifications with LoopBack.
JavaScript
12
star
70

strong-task-emitter

JavaScript
11
star
71

strong-pubsub-redis

Redis adapter for strong-pubsub
JavaScript
11
star
72

strong-service-systemd

Generate an systemd service based on provided parameters
JavaScript
11
star
73

strong-cluster-connect-store

Implementation of connect store using node's native cluster messaging
JavaScript
11
star
74

strong-nginx-controller

Nginx controller for Arc
JavaScript
10
star
75

loopback-sandbox

A repository for reproducing LoopBack community issues.
JavaScript
10
star
76

loopback4-example-family-tree

An example LoopBack application to demonstrate OASGraph
TypeScript
10
star
77

strong-log-transformer

A stream filter for performing common log stream transformations like timestamping and joining multi-line messages.
JavaScript
10
star
78

strong-agent-statsd

publish strong-agent metrics to statsd
JavaScript
9
star
79

loopback-connector-db2iseries

Loopback connector for DB2 on iSeries
PLSQL
9
star
80

loopback-multitenancy

WORK IN PROGRESS: Multitenancy component for LoopBack.
JavaScript
9
star
81

strong-pubsub-mqtt

JavaScript
9
star
82

express-example-app

express example app for strong-pm
JavaScript
8
star
83

strong-config-loader

JavaScript
8
star
84

poc-loopback-multitenancy

Proof of concept for multitenancy in LoopBack.
JavaScript
8
star
85

strong-tools

Tools for packaging, releasing, and preparing npm modules
JavaScript
8
star
86

ephemeral-npm

Disposable npm server for testing packages
Shell
8
star
87

dist-paas-buildpack

StrongLoop distributions for PAAS
Shell
7
star
88

strong-service-install

Create/install system service for a given app
JavaScript
7
star
89

strong-service-upstart

Generate an upstart job based on provided parameters
JavaScript
7
star
90

strong-cluster-tls-store

Implementation of TLS session store using node's native cluster messaging
JavaScript
7
star
91

loopback-phase

Phase management for LoopBack applications.
JavaScript
7
star
92

loopback-oracle-installer

Loopback Oracle Installer
JavaScript
7
star
93

strong-module-loader

JavaScript
7
star
94

strong-pubsub-bridge

JavaScript
6
star
95

v4.loopback.io

LoopBack 4 Web Site
HTML
6
star
96

strong-tunnel

Disposable ssh proxy for TCP connections via URL
JavaScript
6
star
97

strong-pubsub-primus

Primus compatibility layer for strong-pubsub.
JavaScript
6
star
98

loopback-example-kv-connectors

LoopBack KeyValue connector examples.
JavaScript
6
star
99

strong-docker-build

Build a Docker image of an app run under strong-supervisor
JavaScript
6
star
100

loopback-oracle-builder

Loopback Oracle Builder
Shell
5
star