Skip to content
This repository has been archived by the owner on Sep 6, 2021. It is now read-only.

Receive binary Brackets-Node command responses #6339

Merged
merged 2 commits into from
Jan 9, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 55 additions & 7 deletions src/utils/NodeConnection.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, browser: true */
/*global $, define, brackets, WebSocket */
/*global $, define, brackets, WebSocket, ArrayBuffer, Uint32Array */

define(function (require, exports, module) {
"use strict";
Expand All @@ -46,6 +46,9 @@ define(function (require, exports, module) {
/** @define{number} Milliseconds to wait before retrying connecting */
var RETRY_DELAY = 500; // 1/2 second

/** @define {number} Maximum value of the command ID counter */
var MAX_COUNTER_VALUE = 4294967295; // 2^32 - 1

/**
* @private
* Helper function to auto-reject a deferred after a given amount of time.
Expand Down Expand Up @@ -74,6 +77,10 @@ define(function (require, exports, module) {
port = nodePort;
ws = new WebSocket("ws://localhost:" + port);

// Expect ArrayBuffer objects from Node when receiving binary
// data instead of DOM Blobs, which are the default.
ws.binaryType = "arraybuffer";

// If the server port isn't open, we get a close event
// at some point in the future (and will not get an onopen
// event)
Expand Down Expand Up @@ -174,6 +181,23 @@ define(function (require, exports, module) {
*/
NodeConnection.prototype._pendingCommandDeferreds = null;

/**
* @private
* @return {number} The next command ID to use. Always representable as an
* unsigned 32-bit integer.
*/
NodeConnection.prototype._getNextCommandID = function () {
var nextID;

if (this._commandCount > MAX_COUNTER_VALUE) {
nextID = this._commandCount = 0;
} else {
nextID = this._commandCount++;
}

return nextID;
};

/**
* @private
* Helper function to do cleanup work when a connection fails
Expand Down Expand Up @@ -402,12 +426,36 @@ define(function (require, exports, module) {
*/
NodeConnection.prototype._receive = function (message) {
var responseDeferred = null;
var data = message.data;
var m;
try {
m = JSON.parse(message.data);
} catch (e) {
console.error("[NodeConnection] received malformed message", message, e.message);
return;

if (message.data instanceof ArrayBuffer) {
// The first four bytes encode the command ID as an unsigned 32-bit integer
if (data.byteLength < 4) {
console.error("[NodeConnection] received malformed binary message");
return;
}

var header = data.slice(0, 4),
body = data.slice(4),
headerView = new Uint32Array(header),
id = headerView[0];

// Unpack the binary message into a commandResponse
m = {
type: "commandResponse",
message: {
id: id,
response: body
}
};
} else {
try {
m = JSON.parse(data);
} catch (e) {
console.error("[NodeConnection] received malformed message", message, e.message);
return;
}
}

switch (m.type) {
Expand Down Expand Up @@ -467,7 +515,7 @@ define(function (require, exports, module) {
return function () {
var deferred = $.Deferred();
var parameters = Array.prototype.slice.call(arguments, 0);
var id = self._commandCount++;
var id = self._getNextCommandID();
self._pendingCommandDeferreds[id] = deferred;
self._send({id: id,
domain: domainName,
Expand Down
99 changes: 99 additions & 0 deletions test/spec/NodeConnection-test-files/BinaryTestCommands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, node: true */
/*global */

(function () {
"use strict";

/**
* @private
* @type {DomainManager}
* The DomainManager passed in at init.
*/
var _domainManager = null;


/**
* @private
* @type {Buffer}
*/
var _buffer = new Buffer(18);

// write some bytes into the buffer with varied alignments
_buffer.writeUInt8(1, 0);
_buffer.writeUInt32LE(Math.pow(2, 32) - 1, 1);
_buffer.writeFloatBE(3.141592, 5);
_buffer.writeDoubleLE(Number.MAX_VALUE, 9);
_buffer.writeInt8(-128, 17);

/**
* @private
* @return {Buffer}
*/
function _getBufferSync() {
return _buffer;
}

/**
* @private
* @param {function(?string, Buffer=)} callback
*/
function _getBufferAsync(callback) {
process.nextTick(function () {
callback(null, _buffer);
});
}

/**
* @param {DomainManager} DomainManager The DomainManager for the server
*/
function init(DomainManager) {
_domainManager = DomainManager;
if (!_domainManager.hasDomain("test")) {
_domainManager.registerDomain("test", {major: 0, minor: 1});
}
_domainManager.registerCommand(
"binaryTest",
"getBufferSync",
_getBufferSync,
false,
"Get a byte array synchronously",
[],
{name: "bytes", type: "Buffer"}
);
_domainManager.registerCommand(
"binaryTest",
"getBufferAsync",
_getBufferAsync,
true,
"Get a byte array asynchronously",
[],
{name: "bytes", type: "Buffer"}
);
}

exports.init = init;

}());
70 changes: 68 additions & 2 deletions test/spec/NodeConnection-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
/*jslint vars: true, plusplus: true, devel: true, browser: true, nomen: true,
indent: 4, maxerr: 50 */
/*global define, describe, it, xit, expect, beforeEach, afterEach, waits,
waitsFor, runs, $, brackets, waitsForDone */
waitsFor, runs, $, brackets, waitsForDone, ArrayBuffer, DataView */

define(function (require, exports, module) {
"use strict";
Expand Down Expand Up @@ -399,5 +399,71 @@ define(function (require, exports, module) {
});

});

it("should receive synchronous binary command responses", function () {
var connection = createConnection();
var commandDeferred = null;
var result = null;
runConnectAndWait(connection, false);
runLoadDomainsAndWait(connection, ["BinaryTestCommands"], false);
runs(function () {
commandDeferred = connection.domains.binaryTest.getBufferSync();
commandDeferred.done(function (response) {
result = response;
});
});
waitsFor(
function () {
return commandDeferred &&
commandDeferred.state() === "resolved" &&
result;
},
CONNECTION_TIMEOUT
);
runs(function () {
var view = new DataView(result);

expect(result instanceof ArrayBuffer).toBe(true);
expect(result.byteLength).toBe(18);
expect(view.getUint8(0)).toBe(1);
expect(view.getUint32(1)).toBe(4294967295);
expect(view.getFloat32(5, false)).toBe(3.141592025756836);
expect(view.getFloat64(9, true)).toBe(1.7976931348623157e+308);
expect(view.getInt8(17)).toBe(-128);
});
});

it("should receive asynchronous binary command response", function () {
var connection = createConnection();
var commandDeferred = null;
var result = null;
runConnectAndWait(connection, false);
runLoadDomainsAndWait(connection, ["BinaryTestCommands"], false);
runs(function () {
commandDeferred = connection.domains.binaryTest.getBufferAsync();
commandDeferred.done(function (response) {
result = response;
});
});
waitsFor(
function () {
return commandDeferred &&
commandDeferred.state() === "resolved" &&
result;
},
CONNECTION_TIMEOUT
);
runs(function () {
var view = new DataView(result);

expect(result instanceof ArrayBuffer).toBe(true);
expect(result.byteLength).toBe(18);
expect(view.getUint8(0)).toBe(1);
expect(view.getUint32(1)).toBe(4294967295);
expect(view.getFloat32(5, false)).toBe(3.141592025756836);
expect(view.getFloat64(9, true)).toBe(1.7976931348623157e+308);
expect(view.getInt8(17)).toBe(-128);
});
});
});
});
});