提交 58ce3866 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

Channel: start the party

上级 ca8f4364
...@@ -18,7 +18,7 @@ class Request ...@@ -18,7 +18,7 @@ class Request
{ {
return JSON.stringify( return JSON.stringify(
{ {
method : this._method, request : this._method,
id : this._id, id : this._id,
data : this._data data : this._data
}); });
......
...@@ -6,7 +6,8 @@ const logger = require('../logger')('Channel'); ...@@ -6,7 +6,8 @@ const logger = require('../logger')('Channel');
const Request = require('./Request'); const Request = require('./Request');
// Max time waiting for a response from the worker subprocess // Max time waiting for a response from the worker subprocess
const REQUEST_TIMEOUT = 4000; // TODO: set it properly const MESSAGE_MAX_SIZE = 65536;
const REQUEST_TIMEOUT = 5000;
class Channel extends EventEmitter class Channel extends EventEmitter
{ {
...@@ -21,11 +22,91 @@ class Channel extends EventEmitter ...@@ -21,11 +22,91 @@ class Channel extends EventEmitter
this._pendingSent = new Map(); this._pendingSent = new Map();
// TODO: read Channel responses/notifications from the worker // Buffer for incomplete data received from the Channel's socket
this._recvBuffer = null;
// Read Channel responses/notifications from the worker
this._socket.on('data', (buffer) => this._socket.on('data', (buffer) =>
{ {
logger.debug('data received from the socket: %s', buffer.toString('utf8')); // No recvBuffer
if (!this._recvBuffer)
{
// TODO: remove
// logger.debug('recvBuffer was empty');
this._recvBuffer = buffer;
}
else
{
// TODO: remove
// logger.debug('recvBuffer was not empty [length:%s]', this._recvBuffer.length);
this._recvBuffer = Buffer.concat([ this._recvBuffer, buffer ], this._recvBuffer.length + buffer.length);
if (this._recvBuffer.length > MESSAGE_MAX_SIZE)
{
logger.error('recvBuffer full, discarding all the data in it');
// Reset the recvBuffer and exit
this._recvBuffer = null;
return;
}
}
while (true)
{
let nsPayload;
let json;
try
{
nsPayload = netstring.nsPayload(this._recvBuffer);
}
catch (error)
{
logger.error('invalid data received: %s', error.message);
// Reset the recvBuffer and exit
this._recvBuffer = null;
return;
}
// Incomplete netstring
if (nsPayload === -1)
{
logger.debug('not enought data, waiting for more data');
return;
}
// Check whether it is valid JSON
try
{
// NOTE: cool, JSON.parse() allows a Buffer
json = JSON.parse(nsPayload);
}
catch (error)
{
logger.error('invalid JSON received: %s', error.message);
return;
}
// Process JSON
this._processMessage(json);
// Remove the read payload from the recvBuffer
this._recvBuffer = this._recvBuffer.slice(netstring.nsLength(this._recvBuffer));
if (!this._recvBuffer.length)
{
// TODO: remove
// logger.debug('no more data in the buffer');
this._recvBuffer = null;
return;
}
}
}); });
} }
...@@ -34,7 +115,7 @@ class Channel extends EventEmitter ...@@ -34,7 +115,7 @@ class Channel extends EventEmitter
logger.debug('close()'); logger.debug('close()');
// Close every pending sent // Close every pending sent
this._pendingSent.forEach(sent => sent.close()); this._pendingSent.forEach((sent) => sent.close());
// Close the UnixStream socket // Close the UnixStream socket
this._socket.destroy(); this._socket.destroy();
...@@ -113,6 +194,36 @@ class Channel extends EventEmitter ...@@ -113,6 +194,36 @@ class Channel extends EventEmitter
return promise; return promise;
} }
_processMessage(json)
{
logger.debug('_processMessage()');
// TODO: remove
logger.debug('received json: %o', json);
// If a Response retrieve its associated Request
if (json.id)
{
let sent = this._pendingSent.get(json.id);
if (!sent)
{
logger.error('received Response does not match any sent Request');
return;
}
if (json.status === 200)
{
sent.resolve(json.data);
}
else
{
sent.reject(json.data);
}
}
}
} }
module.exports = Channel; module.exports = Channel;
...@@ -28,21 +28,19 @@ class Room extends EventEmitter ...@@ -28,21 +28,19 @@ class Room extends EventEmitter
bar : 'œæ€😤😮😱Ω∑©' bar : 'œæ€😤😮😱Ω∑©'
}; };
// setInterval(() => {
this._channel.sendRequest('createRoom', data) this._channel.sendRequest('createRoom', data)
.then(data => .then(() =>
{ {
logger.debug('"createRoom" command succeeded: %s', data); // TODO: TMP logger.debug('"createRoom" command succeeded');
this._status = STATUS.OPEN; this._status = STATUS.OPEN;
}) })
.catch(error => .catch((error) =>
{ {
logger.error('"createRoom" command failed: %s', error); logger.error('"createRoom" command failed: %s', error);
// TODO: enable this.close(error);
// this.close(error);
}); });
// }, 50);
} }
close(error) close(error)
......
...@@ -77,6 +77,18 @@ class Worker extends EventEmitter ...@@ -77,6 +77,18 @@ class Worker extends EventEmitter
}); });
}); });
// Be also ready for 3rd party worker libraries logging to stdout/stderr
this._child.stdout.on('data', (buffer) =>
{
logger.debug(buffer.toString('utf8'));
});
this._child.stderr.on('data', (buffer) =>
{
logger.error(buffer.toString('utf8'));
});
// Set child process events // Set child process events
this._child.on('exit', (code, signal) => this._child.on('exit', (code, signal) =>
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#include "common.h" #include "common.h"
#include "handles/UnixStreamSocket.h" #include "handles/UnixStreamSocket.h"
#include <json/json.h>
namespace Channel namespace Channel
{ {
...@@ -16,10 +17,15 @@ namespace Channel ...@@ -16,10 +17,15 @@ namespace Channel
// virtual void onControlUnixStreamSocketClosed(Channel::UnixStreamSocket* unixSocket, bool is_closed_by_peer) = 0; // virtual void onControlUnixStreamSocketClosed(Channel::UnixStreamSocket* unixSocket, bool is_closed_by_peer) = 0;
}; };
private:
static MS_BYTE writeBuffer[];
public: public:
UnixStreamSocket(Listener* listener, int fd); UnixStreamSocket(Listener* listener, int fd);
virtual ~UnixStreamSocket(); virtual ~UnixStreamSocket();
void Send(Json::Value &json);
/* Pure virtual methods inherited from ::UnixStreamSocket. */ /* Pure virtual methods inherited from ::UnixStreamSocket. */
public: public:
virtual void userOnUnixStreamRead() override; virtual void userOnUnixStreamRead() override;
......
...@@ -2,14 +2,19 @@ ...@@ -2,14 +2,19 @@
#include "Channel/UnixStreamSocket.h" #include "Channel/UnixStreamSocket.h"
#include "Logger.h" #include "Logger.h"
#include <json/json.h>
#include <netstring.h> #include <netstring.h>
#include <cstring> // std::memmove() #include <cstring> // std::memmove()
# #include <cmath> // std::ceil()
#define MESSAGE_MAX_SIZE 65536 // TODO: set proper buffer size #include <cstdio> // sprintf()
#define MESSAGE_MAX_SIZE 65536
namespace Channel namespace Channel
{ {
/* Static variables. */
MS_BYTE UnixStreamSocket::writeBuffer[MESSAGE_MAX_SIZE];
/* Instance methods. */ /* Instance methods. */
UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) : UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) :
...@@ -24,6 +29,43 @@ namespace Channel ...@@ -24,6 +29,43 @@ namespace Channel
MS_TRACE(); MS_TRACE();
} }
void UnixStreamSocket::Send(Json::Value &json)
{
MS_TRACE();
Json::FastWriter fastWriter;
fastWriter.dropNullPlaceholders();
fastWriter.omitEndingLineFeed();
// Write("VALID JSON MAN !!!!:");
// Write(std::string("---BEGIN---").append(fastWriter.write(json)).append("---JEJE---"));
size_t ns_num_len;
std::string ns_payload = fastWriter.write(json);
size_t ns_payload_len = ns_payload.length();
size_t ns_len;
if (ns_payload_len == 0)
{
ns_num_len = 1;
UnixStreamSocket::writeBuffer[0] = '0';
UnixStreamSocket::writeBuffer[1] = ':';
UnixStreamSocket::writeBuffer[2] = ',';
}
else
{
ns_num_len = (size_t)std::ceil(std::log10((double)ns_payload_len + 1));
std::sprintf((char*)UnixStreamSocket::writeBuffer, "%lu:", (unsigned long)ns_payload_len);
std::memcpy(UnixStreamSocket::writeBuffer + ns_num_len + 1, ns_payload.c_str(), ns_payload_len);
UnixStreamSocket::writeBuffer[ns_num_len + ns_payload_len + 1] = ',';
}
ns_len = ns_num_len + ns_payload_len + 2;
Write(UnixStreamSocket::writeBuffer, ns_len);
}
void UnixStreamSocket::userOnUnixStreamRead() void UnixStreamSocket::userOnUnixStreamRead()
{ {
MS_TRACE(); MS_TRACE();
...@@ -50,8 +92,8 @@ namespace Channel ...@@ -50,8 +92,8 @@ namespace Channel
// Check if the buffer is full. // Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) if (this->bufferDataLen == this->bufferSize)
{ {
// First case: the uncomplete message does not begin at position 0 of // First case: the incomplete message does not begin at position 0 of
// the buffer, so move the uncomplete message to the position 0. // the buffer, so move the incomplete message to the position 0.
if (this->msgStart != 0) if (this->msgStart != 0)
{ {
MS_ERROR("no more space in the buffer, moving parsed bytes to the beginning of the buffer and waiting for more data"); MS_ERROR("no more space in the buffer, moving parsed bytes to the beginning of the buffer and waiting for more data");
...@@ -60,7 +102,7 @@ namespace Channel ...@@ -60,7 +102,7 @@ namespace Channel
this->msgStart = 0; this->msgStart = 0;
this->bufferDataLen = read_len; this->bufferDataLen = read_len;
} }
// Second case: the uncomplete message begins at position 0 of the buffer. // Second case: the incomplete message begins at position 0 of the buffer.
// The message is too big, so discard it. // The message is too big, so discard it.
else else
{ {
...@@ -114,9 +156,26 @@ namespace Channel ...@@ -114,9 +156,26 @@ namespace Channel
{ {
MS_DEBUG("jsoncpp: IT IS VALID JSON:\n%s", json.toStyledString().c_str()); MS_DEBUG("jsoncpp: IT IS VALID JSON:\n%s", json.toStyledString().c_str());
Write("VALID JSON MAN !!!!:"); Json::Value jsonResponse;
Write(json.toStyledString());
jsonResponse["id"] = json["id"];
char ch = json["id"].asString().back();
if (ch > 'm')
{
jsonResponse["status"] = 200;
jsonResponse["reason"] = "OK";
jsonResponse["data"] = "🐮🐷🐣😡";
}
else
{
jsonResponse["status"] = 500;
jsonResponse["reason"] = "ERROR";
jsonResponse["data"] = "ERROR JODER !!!!!!";
}
Send(jsonResponse);
// TODO: process it // TODO: process it
} }
......
...@@ -134,7 +134,7 @@ namespace RTC ...@@ -134,7 +134,7 @@ namespace RTC
// Check if the buffer is full. // Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize) if (this->bufferDataLen == this->bufferSize)
{ {
// First case: the uncomplete frame does not begin at position 0 of // First case: the incomplete frame does not begin at position 0 of
// the buffer, so move the frame to the position 0. // the buffer, so move the frame to the position 0.
if (this->frameStart != 0) if (this->frameStart != 0)
{ {
...@@ -144,7 +144,7 @@ namespace RTC ...@@ -144,7 +144,7 @@ namespace RTC
this->bufferDataLen = this->bufferSize - this->frameStart; this->bufferDataLen = this->bufferSize - this->frameStart;
this->frameStart = 0; this->frameStart = 0;
} }
// Second case: the uncomplete frame begins at position 0 of the buffer. // Second case: the incomplete frame begins at position 0 of the buffer.
// The frame is too big, so close the connection. // The frame is too big, so close the connection.
else else
{ {
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论