NodeJS, MemoryStore Session, not persisting between requests with cluster

I have a NodeJS application. I am scaling it to run on multiple cores with express-cluster. I am using express-session and cookie-parser. When storing values on the session I noticed that the values were not persisting between requests.

Here is my configuration module configuring express: (shortened to contain only relevant details)

var express = require('express'),
    config = require('./config'),
    cookieParser = require('cookie-parser'),
    session = require('express-session'),
    bodyParser = require('body-parser');

module.exports = function() {
    var app = express();
    app.use(cookieParser());
    app.use(session({
        secret: 'asdf',
        resave: true,
        saveUninitialized: true
    }));
    return app;
};

This works! (there is only one client listening for connections and one master node)
Here is my server.js:

var config = require('./config/config'),
    app = require('./config/express')(),
    modules = require('./app/modules')(app),
    cluster = require('cluster');

if(cluster.isMaster) {
    cluster.fork();
} else {
    app.listen(config.port);
}
exports = module.exports = app;

If however you begin to scale this up, it breaks. Express cluster uses round robin scheduling to handle incoming requests. I can only assume each request stomps on the previous session, clearing out the session variable set by a previous request.

var config = require('./config/config'),
    app = require('./config/express')(),
    modules = require('./app/modules')(app),
    cluster = require('cluster');

if(cluster.isMaster) {
    cluster.fork();
    cluster.fork();
} else {
    app.listen(config.port);
}
exports = module.exports = app;

Extract CSS for particular HTML Element

I was doing some quick and dirty page building/html hacking and needed just the CSS relevant to a single element in CSS.

I wrote a script that recursively scans for all CSS on the page and pretty print the CSS to the console. Or I suppose you could put it in a webpage, but I have no idea why you would want to.

Copy the JS into your console then you can use it like so:

CSSLIB.test(); // Should output ‘hi’
CSSLIB.printCssForElement(‘xpath expression here’) // Blob of css
CSSLIB.prettyPrintCssForElement(‘xpath expression here’) // Pretty blob of css

You can get the source here:
https://github.com/NeverOddOrEven/CodeBits/blob/master/js/ExtractNodeCSS.js

A fiddlejs to showcase $scope in Angular Directives

I have been working a lot in Angular lately.  I wanted to ensure I had a solid understanding of $scope because it is probably one of the more confusing aspects of Angular short of when to use “$scope.$apply(function() { … }).”

I set about condensing and distilling various articles on the  subject into a single code example. I wound up with a fiddle that demonstrates everything except expression binding with the ‘&’ operator.

Click to go to jsfiddle.

Have a look!

 

Spelling out numbers: JavaScript

I wrote up some JavaScript code to convert “34.27” to “thirty-four point twenty-seven.” This could be useful for the print checks line when generating checks procedurally, or maybe filling out contracts. It works up to the trillions order-of-magnitude. Supporting higher orders is as simple as adding the name of the desired order(s) to the relevant array.

Check it out in action here, or just check out the source at GitHub.

 

MongoDB, ExpressJS, AngularJS, NodeJS – MEANJS.org

I have been working extensively over the last three weeks with that MEAN.JS stack over at MEAN.JS org. It is a pretty impressive stack. In my experience its vertically organized modules are arranged much the same way as projects I have been a part of in enterprise MVC environments. I prefer standard approaches; they translate well when speaking with other engineers. Couple the enterprise grade framework with the declarative nature of angular, and you have an incredibly simple to use framework that separates the UI from the business logic.

Well, mostly. There are a couple shortcomings to MEAN.JS in my experience. AngularJS is intended to separate the concerns of the UI from the business logic; and that is true! On its own angularjs does just that. However, with MEAN.JS there is no discussion of mapping from the business data models (which exist in the core area), to presentation models (lacking on the UI side). Without this bridge, you cannot truthfully say they are separate. Your UI will be bound to the structure of the data as it exists coming out of core. It is something I feel that should be integrated into the framework and examples, or at least briefly discussed in the documentation.

And the second shortcoming: The framework automatically includes javascript files. The framework recursively scans your module directories to add any javascript files that it finds. You can exclude your unit tests by following the naming convention *.spec.js. To ignore other javascript files, such as javascript workers, you will need to modify the regular expression in config/express.js.

For me, it is line 30 (change is in red text):
modulesJSFiles: utilities.walk(‘./public/modules’, /(.).(js)/, /(.).(spec|worker.js)/, ‘./public’)

That’s all for now. Just a long winded update!

Heartbleed OpenSSL Vulnerability

Check the security of your site certificate and web host here. Qualys warns the feature is experimental, but the security test itself is a good thing to have when setting up your site’s security.

http://heartbleed.com/ has a wealth of information to answer any questions you may have.

OpenSSL released a technical statement related to the Heartbleed vulnerability here.

 

Ohio Startup Scene

CLEVELAND, Ohio — A California outlook forced Mark Kvamme to adjust his sense of the spectacular as he immersed himself in Ohio’s startup scene.

Read the original article here.

The entire Midwest attracts about $1 billion in venture capital each year, he notes. Meanwhile, $12 billion pours into the three Zip Codes of Silicon Valley, where he once made investments for Sequoia Capital.

It’s no wonder, he said, that entrepreneurs struggle to launch and succeed in the Buckeye State.

“Capital is their lifeblood. It’s what they need,” Kvamme declared.

He said he thinks the state and region need to do more to find that capital for their entrepreneurs, who in turn need to take bigger risks and fail more often.

Ponder that, Ohio.

Kvamme — pronounced KAWH-mee — came to Ohio to launch and briefly lead JobsOhio for Gov. John Kasich. Kvamme now runs a Columbus venture capital firm. Monday, he’ll share his insight into the Ohio and California startup ecosystems during the Northeast Ohio Entrepreneurship Expo at the Cleveland Museum of Art.

He’s joining an investor panel that will take on the Midwest challenge, “Attracting Capital Between the Coasts.”

Kvamme sees a battle of perceptions. The Midwest produces great talent and innovations, he said. He points to the concentration of Fortune 500 companies and the millions in federal research dollars attracted by universities such as Case Western Reserve.

There are startups that do soar, like TOA Technologies, which grew from a Beachwood business incubator into a global provider of work management software.

“The quality of entrepreneurship here, the quality of the engineering, it’s as high as anything in California,” he said.

But Ohio has little experience with venture capital investment and has few venture capital firms and that hurts, Kvamme said. Even in a global economy, rich people want to invest near home.

Thus, many promising Ohio companies either starve for capital or get stolen away, to the coast where the venture capital lives.

Ohio needs more local venture capital, Kvamme said, and it needs more faith in its ability to create great companies.

He thinks he’s doing his part. With former Sequoia partner Chris Olsen, he co-founded Drive Capital, a nearly $250-million fund that will invest primarily in Midwest startups.

“One, we’re telling the world you can do this in Ohio,” he said, adding that the partners hope others follow. “We do want to see hundreds of millions of dollars of funding throughout Ohio. Because we need trading partners. And money follows success.”

Of course, Drive enjoyed a startup boost, a quiet $50 million the partners secured from Ohio State University and then-President E. Gordon Gee, which created uproar when the news leaked.

Kvamme said the controversy was overblown. A large percentage of venture capital comes from university and foundation endowments, he said. More significant, he argues, is the fact Drive attracted 60 percent of its funds from outside of Ohio.

“We brought $150 million to this state,” he said. “If we make Ohio State three, four, five times their investment, I hope you’ll report that, too.”

Ohio needs more venture capital firms and until it gets them, Kvamme argued, it needs to help job creators find capital.

Recently, JumpStart, the sponsor of Monday’s expo, floated the idea of a state government venture fund, perhaps stemming from the Third Frontier initiative.

Kvamme thinks universities need to be more aggressive pushing their professors to commercialize research and help them find capital, and that Ohio needs to become more enamored with consumer products, which can bloom into billion dollar companies in the new economy.

Mostly, the state needs a bit more of a California attitude, he said. It needs to support entrepreneurs willing to take risks and fail, so that they try, try again.

Mahoning Valley picks up a new, advanced manufacturer

Laird Technology is moving its Wireless Automation and Controls division from Sharpsville, Penn., across the Ohio border to Warren, which will pick up 150 jobs and soon add more.

The maker of remote control systems for mines and railroads plans to add about 50 people to the expanding division, boosting employment to more than 200 at a former Delphi complex on North River Road.

“It’s a really nice, high-tech company for us here,” said Sarah Boyarko, the vice president of economic development for the Youngstown/Warren Regional Chamber, which helped the company find its new home. “They are not only going to relocate 150-plus employees, they are hiring. These are good paying jobs.”

Laird said it outgrew its space in Sharpsville, just over the border from Youngstown, and was looking for room to grow and innovate.

It expects to complete the move this summer.

Northeast Ohio’s largest software company had a problem. Locally, it’s known as Hyland Software. But outside of Northeast Ohio, the Westlake company is best known for its flagship product, OnBase.

With international sales growing, world opinion–and brand awareness–grows ever more important.

“There was a lot of confusion in the marketplace,” said Drew Chapin, Hyland’s vice president of marketing. “People in Northeast Ohio didn’t know what OnBase was. Globally, it’s all about OnBase.”

The solution: “OnBase by Hyland.” That’s the new logo and marketing theme for a company with a single-minded pursuit.

OnBase is Hyland’s first and only product. Its actually a suite of tools for ECM–enterprise content management–which companies use to store and retrieve data, capture images and manage their workflow.

Hyland engineers customize OnBase annually. The 14th edition comes out this summer.

Chapin said the new brand connects the product to its builders while putting Hyland’s best foot forward.

OnBase by Hyland is being promoted in a marketing campaign reflected on business cards, in trade show booths and on the Internet. Hyland.com now directs visitors to Onbase.com.

Robert L. Smith covers economic development and the innovation economy for The Plain Dealer. Contact him at rsmith@plaind.com, 216-999-4024.

WordPress, SSL, and broken CSS

It is nice to have a platform from which to share a little knowledge I have uncovered. Sometimes the WordPress function is_ssl() will return false even though you are running your site over an SSL connection. Apparently, if your site is running behind a load balancer the $_SERVER[‘HTTPS’] may not be set causing the is_ssl() function to fail.

In your wp-includes/functions.php file, you will find this code:

/**
* Determine if SSL is used.
* @since 2.6.0
* @return bool True if SSL, false if not used.
*/
function is_ssl() {
if ( isset($_SERVER['HTTPS']) ) {
if ( 'on' == strtolower($_SERVER['HTTPS']) )
return true;
if ( '1' == $_SERVER['HTTPS'] )
return true;
} elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
return true;
}

// hacked by me
return true;
}

I know my change is not elegant, nor is it robust, but it is effective. I told my host to run all traffic over SSL so this is a safe bet for my personal website. This may not be the case for you, but it is nice to know the cause of the problem.

There is allegedly a better fix if you follow this link but I was unable to get it to work on my installation for some reason. I have already spent far too long on this issue; hopefully I have saved you some time.

Embedding ads, and their effect on your site

Are ad servers to blame for slow page loads? You could be losing viewers and money!

It was in 2006 that the first study concluded that slow response times from your website results in lower conversion rates. “Patient” web users will abandon your page after only a two second delay. It has also been shown that reducing load times below the two second threshold will increase conversion rates. Check it out for yourself here.

Steps you can take to decrease your page load times:

  1. Use a reputable hosting platform with high availability and high connectivity
  2. Use the latest technology available that supports high throughput processing
  3. Make your pages smaller
  4. Use HTML5 instead of Flash
  5. Minify javascript
  6. Lower the number of HTTP requests (this is extremely crucial for 3G mobile devices
    1. Use compressed image formats / Embed images in the page if you can
    2. Reduce the number of external loads such as multiple javascript scripts

 

Defining RESTful Web Services

This is one of the best articles I have come across to describe a RESTful API.

Representational State Transfer (REST) has gained widespread acceptance across the Web as a simpler alternative to SOAP- and Web Services Description Language (WSDL)-based Web services. Key evidence of this shift in interface design is the adoption of REST by mainstream Web 2.0 service providers—including Yahoo, Google, and Facebook—who have deprecated or passed on SOAP and WSDL-based interfaces in favor of an easier-to-use, resource-oriented model to expose their services. In this article, Alex Rodriguez introduces you to the basic principles of REST.

Click here to read the full article