Skip to content

Instantly share code, notes, and snippets.

@ryanseys
Last active August 29, 2015 14:20
Show Gist options
  • Save ryanseys/0e2c3244175db6525d7a to your computer and use it in GitHub Desktop.
Save ryanseys/0e2c3244175db6525d7a to your computer and use it in GitHub Desktop.
Testing socket stuff
// before running, set pool: { maxSockets: 2 } in request defaults.
var projectId = process.env.PROJECT_ID;
var keyFile = process.env.GCLOUD_KEYFILE;
var fs = require('fs');
var gcloud = require('gcloud')({
projectId: projectId,
credentials: require(keyFile)
});
var storage = gcloud.storage();
var bucket = storage.bucket('ryanseys-files');
var localFileStream;
var localStreams = [];
var requestStreams = [];
for(var i = 0; i < 3; i++) {
localFileStream = fs.createWriteStream('./cover' + i + '.jpg');
var file = bucket.file('cover.jpg');
var stream = file.createReadStream();
stream.on('error', function(err){ console.log('Error happened: ', err); });
stream.on('complete', function(metadata){ console.log('Complete', metadata); });
stream.pipe(localFileStream);
localStreams.push(localFileStream);
requestStreams.push(stream);
}
// end the 3 requests prematurely
for (i in requestStreams) {
requestStreams[i].end();
}
// create a 4th request that should succeed!
localFileStream = fs.createWriteStream('./cover4.jpg');
var file = bucket.file('cover.jpg');
var stream = file.createReadStream();
stream.on('error', function(err){ console.log('Error on file 4: ', err); });
stream.on('complete', function(metadata){ console.log('Complete file 4'); });
stream.pipe(localFileStream);
setTimeout(function() {
console.log('Time out');
}, 1000 * 60 * 60);
// keep this process around for 1 hour
// use this time to check the open sockets using the following command:
// $ lsof -i tcp:443 -n -P | grep node
// before the fix, you should see maxSockets = 2 = # of sockets hanging around open and the 4th file download will not be complete.
// after the fix, you should see 0 sockets hanging around and the 4th file download will complete.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment