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

Channel: start the party

上级 ca8f4364
......@@ -18,9 +18,9 @@ class Request
{
return JSON.stringify(
{
method : this._method,
id : this._id,
data : this._data
request : this._method,
id : this._id,
data : this._data
});
}
......
......@@ -6,7 +6,8 @@ const logger = require('../logger')('Channel');
const Request = require('./Request');
// 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
{
......@@ -21,11 +22,91 @@ class Channel extends EventEmitter
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) =>
{
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
logger.debug('close()');
// Close every pending sent
this._pendingSent.forEach(sent => sent.close());
this._pendingSent.forEach((sent) => sent.close());
// Close the UnixStream socket
this._socket.destroy();
......@@ -113,6 +194,36 @@ class Channel extends EventEmitter
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;
......@@ -28,21 +28,19 @@ class Room extends EventEmitter
bar : 'œæ€😤😮😱Ω∑©'
};
// setInterval(() => {
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;
})
.catch(error =>
.catch((error) =>
{
logger.error('"createRoom" command failed: %s', error);
// TODO: enable
// this.close(error);
this.close(error);
});
// }, 50);
}
close(error)
......
......@@ -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
this._child.on('exit', (code, signal) =>
......
......@@ -3,6 +3,7 @@
#include "common.h"
#include "handles/UnixStreamSocket.h"
#include <json/json.h>
namespace Channel
{
......@@ -16,10 +17,15 @@ namespace Channel
// virtual void onControlUnixStreamSocketClosed(Channel::UnixStreamSocket* unixSocket, bool is_closed_by_peer) = 0;
};
private:
static MS_BYTE writeBuffer[];
public:
UnixStreamSocket(Listener* listener, int fd);
virtual ~UnixStreamSocket();
void Send(Json::Value &json);
/* Pure virtual methods inherited from ::UnixStreamSocket. */
public:
virtual void userOnUnixStreamRead() override;
......
......@@ -2,14 +2,19 @@
#include "Channel/UnixStreamSocket.h"
#include "Logger.h"
#include <json/json.h>
#include <netstring.h>
#include <cstring> // std::memmove()
#
#define MESSAGE_MAX_SIZE 65536 // TODO: set proper buffer size
#include <cmath> // std::ceil()
#include <cstdio> // sprintf()
#define MESSAGE_MAX_SIZE 65536
namespace Channel
{
/* Static variables. */
MS_BYTE UnixStreamSocket::writeBuffer[MESSAGE_MAX_SIZE];
/* Instance methods. */
UnixStreamSocket::UnixStreamSocket(Listener* listener, int fd) :
......@@ -24,6 +29,43 @@ namespace Channel
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()
{
MS_TRACE();
......@@ -50,8 +92,8 @@ namespace Channel
// Check if the buffer is full.
if (this->bufferDataLen == this->bufferSize)
{
// First case: the uncomplete message does not begin at position 0 of
// the buffer, so move the uncomplete message to the position 0.
// First case: the incomplete message does not begin at position 0 of
// the buffer, so move the incomplete message to the position 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");
......@@ -60,7 +102,7 @@ namespace Channel
this->msgStart = 0;
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.
else
{
......@@ -114,9 +156,26 @@ namespace Channel
{
MS_DEBUG("jsoncpp: IT IS VALID JSON:\n%s", json.toStyledString().c_str());
Write("VALID JSON MAN !!!!:");
Write(json.toStyledString());
Json::Value jsonResponse;
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
}
......
......@@ -134,7 +134,7 @@ namespace RTC
// Check if the buffer is full.
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.
if (this->frameStart != 0)
{
......@@ -144,7 +144,7 @@ namespace RTC
this->bufferDataLen = this->bufferSize - this->frameStart;
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.
else
{
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论