Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CLOSE THIS][WIP] Completely and permanently replace continuation-local-storage with cls-hooked #10

Closed
wants to merge 14 commits into from
Closed
7 changes: 7 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
sudo: false
language: node_js
node_js:
- "0.10"
- "0.12"
- "4"
- "6"
9 changes: 9 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
2016-08-10, Version 1.0.0
=========================

* First release!

2016-08-10, Version 2.0.0-alpha.1
=========================

* Edited README.md and package.json in order to address both issues loopback-context#9 and async-listener#57 by permanently replacing continuation-local-storage with cls-hooked
86 changes: 84 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,86 @@
# loopback-context-cls
# loopback-context

Current context for LoopBack applications, based on
node-continuation-local-storage.
cls-hooked.

## USAGE WARNING

**Only if you use this package, do NOT run your app using `slc run` or `node .`**

Run using:

`node -r cls-hooked .`

This uses the `-r` option in order to require `cls-hooked` before your app (see warnings below for more info).

If you wish to use `strong-supervisor`, you would need to pass node options to `slc run`, which currently has issues, according to [strong-supervisor#56](https://github.com/strongloop/strong-supervisor/issues/56).

## INSTALL WARNING

**Only if you use this package, do NOT install your app using `npm install`.**

Install using:

```
npm config set engine-strict true
npm install
```

This keeps you from using Node < v0.4.5.

## TEST WARNING

**Do NOT test this package using `mocha .`.**

Test using:

```
npm test
```

This adds the `-r` option to `mocha` command, needed in order to pass tests.

## WARNING

**We recommend AGAINST using the loopback-context module until there is a stable solution to the issue below!**

The module node-continuation-local-storage is known to have many problems,
see e.g. [issue #59](https://github.com/othiym23/node-continuation-local-storage/issues/59).
As a result, loopback-context does not work in many situations, as can be
seen from issues reported in LoopBack's
[issue tracker](https://github.com/strongloop/loopback/issues?utf8=%E2%9C%93&q=is%3Aissue%20getCurrentcontext).

The new alternative
[cls-hooked](https://github.com/Jeff-Lewis/cls-hooked) is known to possibly inherit these problems if it's not imported before everything else, that's why you are required to follow the advice above if using this.

## Usage

1) Add `per-request` middleware to your
`server/middleware-config.json`:

```json
{
"initial": {
"loopback-context#per-request": {
}
}
}
```

2) Then you can access the context from your code:

```js
var LoopBackContext = require('loopback-context');

// ...

MyModel.myMethod = function(cb) {
var ctx = LoopBackContext.getCurrentContext();
ctx.get('key');
ctx.set('key', { foo: 'bar' });
});
```

See the official LoopBack
[documentation](https://docs.strongloop.com/display/APIC/Using+current+context)
for more details.
17 changes: 17 additions & 0 deletions browser/current-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright IBM Corp. 2015. All Rights Reserved.
// Node module: loopback-context-cls
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict';

var LoopBackContext = module.exports;

LoopBackContext.getCurrentContext = function() {
return null;
};

LoopBackContext.runInContext =
LoopBackContext.createContext = function() {
throw new Error('Current context is not supported in the browser.');
};
18 changes: 12 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "loopback-context",
"version": "1.0.0",
"description": "Current context for LoopBack applications, based on node-continuation-local-storage",
"description": "Current context for LoopBack applications, based on cls-hooked",
"keywords": [
"StrongLoop",
"LoopBack",
Expand All @@ -11,19 +11,25 @@
"type": "git",
"url": "https://github.com/strongloop/loopback-context"
},
"main": "index.js",
"browser": "browser.js",
"main": "server/current-context.js",
"browser": "browser/current-context.js",
"scripts": {
"test": "mocha",
"test": "mocha -r cls-hooked",
"posttest": "npm run lint",
"lint": "eslint ."
},
"license": "MIT",
"dependencies": {},
"dependencies": {
"cls-hooked": "^4.0.1"
},
"devDependencies": {
"async": "1.5.2",
"chai": "^3.5.0",
"dirty-chai": "^1.2.2",
"eslint": "^2.13.1",
"eslint-config-loopback": "^4.0.0",
"loopback": "^3.0.0-alpha.1",
"mocha": "^2.5.3"
"mocha": "^2.5.3",
"supertest": "^1.2.0"
}
}
92 changes: 92 additions & 0 deletions server/current-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright IBM Corp. 2015,2016. All Rights Reserved.
// Node module: loopback-context-cls
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict';

var cls = require('cls-hooked');
var domain = require('domain');

var LoopBackContext = module.exports;

/**
* Get the current context object. The context is preserved
* across async calls, it behaves like a thread-local storage.
*
* @returns {Namespace} The context object or null.
*/
LoopBackContext.getCurrentContext = function() {
// A placeholder method, see LoopBackContext.createContext() for the real version
return null;
};

/**
* Run the given function in such way that
* `LoopBackContext.getCurrentContext` returns the
* provided context object.
*
* **NOTE**
*
* The method is supported on the server only, it does not work
* in the browser at the moment.
*
* @param {Function} fn The function to run, it will receive arguments
* (currentContext, currentDomain).
* @param {Namespace} context An optional context object.
* When no value is provided, then the default global context is used.
*/
LoopBackContext.runInContext = function(fn, context) {
var currentDomain = domain.create();
currentDomain.oldBind = currentDomain.bind;
currentDomain.bind = function(callback, context) {
return currentDomain.oldBind(ns.bind(callback, context), context);
};

var ns = context || LoopBackContext.createContext('loopback');

currentDomain.run(function() {
ns.run(function executeInContext(context) {
fn(ns, currentDomain);
});
});
};

/**
* Create a new LoopBackContext instance that can be used
* for `LoopBackContext.runInContext`.
*
* **NOTES**
*
* At the moment, `LoopBackContext.getCurrentContext` supports
* a single global context instance only. If you call `createContext()`
* multiple times, `getCurrentContext` will return the last context
* created.
*
* The method is supported on the server only, it does not work
* in the browser at the moment.
*
* @param {String} scopeName An optional scope name.
* @return {Namespace} The new context object.
*/
LoopBackContext.createContext = function(scopeName) {
// Make the namespace globally visible via the process.context property
process.context = process.context || {};
var ns = process.context[scopeName];
if (!ns) {
ns = cls.createNamespace(scopeName);
process.context[scopeName] = ns;
// Set up LoopBackContext.getCurrentContext()
LoopBackContext.getCurrentContext = function() {
return ns && ns.active ? ns : null;
};
}
return ns;
};

/**
* Create middleware that sets up a new context for each incoming HTTP request.
*
* See perRequestContextFactory for more details.
*/
LoopBackContext.perRequest = require('./middleware/per-request');
60 changes: 60 additions & 0 deletions server/middleware/per-request.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright IBM Corp. 2014,2016. All Rights Reserved.
// Node module: loopback-context-cls
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

'use strict';

var LoopBackContext = require('../current-context');

module.exports = perRequestContextFactory;

var name = 'loopback';

/**
* Context middleware.
* ```js
* var perRequestContext = require(
* 'loopback-context/server/middleware/per-request-context.js');
* var app = loopback();
* app.use(perRequestContext(options);
* app.use(loopback.rest());
* app.listen();
* ```
* @options {Object} [options] Options for context
* @property {String} name Context scope name.
* @property {Boolean} enableHttpContext Whether HTTP context is enabled. Default is false.
*/

function perRequestContextFactory(options) {
options = options || {};
var scope = options.name || name;
var enableHttpContext = options.enableHttpContext || false;
var ns = LoopBackContext.createContext(scope);

// Return the middleware
return function perRequestContext(req, res, next) {
if (req.loopbackContext) {
return next();
}

LoopBackContext.runInContext(function processRequestInContext(ns, domain) {
req.loopbackContext = ns;

// Bind req/res event emitters to the given namespace
ns.bindEmitter(req);
ns.bindEmitter(res);

// Add req/res event emitters to the current domain
domain.add(req);
domain.add(res);

// Run the code in the context of the namespace
if (enableHttpContext) {
// Set up the transport context
ns.set('http', {req: req, res: res});
}
next();
});
};
}
6 changes: 6 additions & 0 deletions test/helpers/expect.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

var chai = require('chai');
chai.use(require('dirty-chai'));

module.exports = chai.expect;
Loading