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

Channel: more API

上级 dc129757
'use strict'; 'use strict';
const randomString = require('random-string'); const randomNumber = require('random-number');
const logger = require('../logger')('Channel:Request'); const logger = require('../logger')('Channel:Request');
const randomNumberGenerator = randomNumber.generator(
{
min : 10000,
max : 99999,
integer : true
});
class Request class Request
{ {
constructor(method, data) constructor(method, data)
{ {
logger.debug('constructor() [method:%s]', method); logger.debug('constructor() [method:%s]', method);
this._id = randomString({ length: 8 }).toLowerCase(); this._id = randomNumberGenerator();
this._method = method; this._method = method;
this._data = data || {}; this._data = data || {};
} }
...@@ -18,20 +25,20 @@ class Request ...@@ -18,20 +25,20 @@ class Request
{ {
return JSON.stringify( return JSON.stringify(
{ {
request : this._method, id : this._id,
id : this._id, method : this._method,
data : this._data data : this._data
}); });
} }
get method() get id()
{ {
return this._method; return this._id;
} }
get id() get method()
{ {
return this._id; return this._method;
} }
get data() get data()
......
...@@ -31,21 +31,15 @@ class Channel extends EventEmitter ...@@ -31,21 +31,15 @@ class Channel extends EventEmitter
// No recvBuffer // No recvBuffer
if (!this._recvBuffer) if (!this._recvBuffer)
{ {
// TODO: remove
// logger.debug('recvBuffer was empty');
this._recvBuffer = buffer; this._recvBuffer = buffer;
} }
else 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); this._recvBuffer = Buffer.concat([ this._recvBuffer, buffer ], this._recvBuffer.length + buffer.length);
if (this._recvBuffer.length > MESSAGE_MAX_SIZE) if (this._recvBuffer.length > MESSAGE_MAX_SIZE)
{ {
logger.error('recvBuffer full, discarding all the data in it'); logger.error('recvBuffer is full, discarding all the data in it');
// Reset the recvBuffer and exit // Reset the recvBuffer and exit
this._recvBuffer = null; this._recvBuffer = null;
...@@ -100,9 +94,6 @@ class Channel extends EventEmitter ...@@ -100,9 +94,6 @@ class Channel extends EventEmitter
if (!this._recvBuffer.length) if (!this._recvBuffer.length)
{ {
// TODO: remove
// logger.debug('no more data in the buffer');
this._recvBuffer = null; this._recvBuffer = null;
return; return;
} }
...@@ -197,12 +188,10 @@ class Channel extends EventEmitter ...@@ -197,12 +188,10 @@ class Channel extends EventEmitter
_processMessage(json) _processMessage(json)
{ {
logger.debug('_processMessage()');
// TODO: remove // TODO: remove
logger.debug('received json: %o', json); logger.debug('received json: %o', json);
// If a Response retrieve its associated Request // If a Response, retrieve its associated Request
if (json.id) if (json.id)
{ {
let sent = this._pendingSent.get(json.id); let sent = this._pendingSent.get(json.id);
...@@ -220,7 +209,11 @@ class Channel extends EventEmitter ...@@ -220,7 +209,11 @@ class Channel extends EventEmitter
} }
else else
{ {
sent.reject(json.data); let error = new Error(json.reason);
// Add .status to the Error instance
error.status = json.status;
sent.reject(error);
} }
} }
} }
......
...@@ -28,7 +28,6 @@ class Room extends EventEmitter ...@@ -28,7 +28,6 @@ class Room extends EventEmitter
bar : 'œæ€😤😮😱Ω∑©' bar : 'œæ€😤😮😱Ω∑©'
}; };
// setInterval(() => {
this._channel.request('createRoom', data) this._channel.request('createRoom', data)
.then(() => .then(() =>
{ {
...@@ -36,15 +35,14 @@ class Room extends EventEmitter ...@@ -36,15 +35,14 @@ class Room extends EventEmitter
this._status = STATUS.OPEN; this._status = STATUS.OPEN;
this.emit('open'); this.emit('open', data);
}) })
.catch((error) => .catch((error) =>
{ {
logger.error('"createRoom" command failed [error:%s]', error); logger.error('"createRoom" command failed [status:%s, error:"%s"]', error.status, error.message);
this.close(error); this.close(error);
}); });
// }, 20);
} }
close(error) close(error)
......
...@@ -13,18 +13,22 @@ namespace Channel ...@@ -13,18 +13,22 @@ namespace Channel
class Request class Request
{ {
public: public:
static Channel::Request* Factory(Channel::UnixStreamSocket* channel, Json::Value& msg); static Channel::Request* Factory(Channel::UnixStreamSocket* channel, Json::Value& json);
public: public:
Request(Channel::UnixStreamSocket* channel, std::string& id, std::string& method, Json::Value& data); Request(Channel::UnixStreamSocket* channel, unsigned int id, std::string& method, Json::Value& data);
virtual ~Request(); virtual ~Request();
void Reply(int status); // void Accept(Json::Value data = Json::Value(Json::nullValue));
void Accept();
void Accept(Json::Value &data);
void Reject(unsigned int status, std::string& reason);
void Reject(unsigned int status, const char* reason = nullptr);
public: public:
// Passed by argument: // Passed by argument:
Channel::UnixStreamSocket* channel = nullptr; Channel::UnixStreamSocket* channel = nullptr;
std::string id; unsigned int id;
std::string method; std::string method;
Json::Value data; Json::Value data;
// Others: // Others:
......
...@@ -7,27 +7,55 @@ namespace Channel ...@@ -7,27 +7,55 @@ namespace Channel
{ {
/* Static methods. */ /* Static methods. */
Channel::Request* Request::Factory(Channel::UnixStreamSocket* channel, Json::Value& msg) Channel::Request* Request::Factory(Channel::UnixStreamSocket* channel, Json::Value& json)
{ {
MS_TRACE(); MS_TRACE();
unsigned int id;
std::string method;
Json::Value data;
// TODO: TMP // TODO: TMP
Json::FastWriter fastWriter; Json::FastWriter fastWriter;
fastWriter.dropNullPlaceholders(); fastWriter.dropNullPlaceholders();
fastWriter.omitEndingLineFeed(); fastWriter.omitEndingLineFeed();
MS_DEBUG("JSON msg: %s", fastWriter.write(msg).c_str()); MS_DEBUG("JSON msg: %s", fastWriter.write(json).c_str());
// Check fields.
if (json["id"].isUInt())
{
id = json["id"].asUInt();
}
else
{
MS_ERROR("json has no numeric .id field");
return nullptr;
}
if (json["method"].isString())
{
method = json["method"].asString();
}
else
{
MS_ERROR("json has no string .method field");
// TODO: Check keys. return nullptr;
}
std::string id = msg["id"].asString(); if (json["data"].isObject())
std::string method = msg["method"].asString(); data = json["data"];
else
data = Json::Value(Json::objectValue);
return new Request(channel, id, method, msg["data"]); return new Request(channel, id, method, data);
} }
/* Instance methods. */ /* Instance methods. */
Request::Request(Channel::UnixStreamSocket* channel, std::string& id, std::string& method, Json::Value& data) : Request::Request(Channel::UnixStreamSocket* channel, unsigned int id, std::string& method, Json::Value& data) :
channel(channel), channel(channel),
id(id), id(id),
method(method), method(method),
...@@ -41,7 +69,46 @@ namespace Channel ...@@ -41,7 +69,46 @@ namespace Channel
MS_TRACE(); MS_TRACE();
} }
void Request::Reply(int status) void Request::Accept()
{
MS_TRACE();
static Json::Value no_data(Json::nullValue);
Accept(no_data);
}
void Request::Accept(Json::Value &data)
{
MS_TRACE();
if (this->replied)
{
MS_ERROR("already replied");
return;
}
this->replied = true;
Json::Value json;
json["id"] = this->id;
json["status"] = 200;
if (data.isObject())
json["data"] = data;
this->channel->Send(json);
}
void Request::Reject(unsigned int status, std::string& reason)
{
MS_TRACE();
Reject(status, reason.c_str());
}
void Request::Reject(unsigned int status, const char* reason)
{ {
MS_TRACE(); MS_TRACE();
...@@ -58,6 +125,9 @@ namespace Channel ...@@ -58,6 +125,9 @@ namespace Channel
json["id"] = this->id; json["id"] = this->id;
json["status"] = status; json["status"] = status;
if (reason)
json["reason"] = reason;
this->channel->Send(json); this->channel->Send(json);
} }
} }
...@@ -94,16 +94,26 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request ...@@ -94,16 +94,26 @@ void Loop::onChannelRequest(Channel::UnixStreamSocket* channel, Channel::Request
{ {
MS_TRACE(); MS_TRACE();
char ch = request->id.back(); if (request->id < 25000)
{
request->Accept();
}
else if (request->id < 50000)
{
Json::Value data;
if (ch > 'm') data["jojojo"] = "🐮🐷🐣😡";
request->Accept(data);
}
else if (request->id < 75000)
{ {
// jsonResponse["data"] = "🐮🐷🐣😡"; std::string reason = "this is a std::string reason";
request->Reply(200);
request->Reject(400, reason);
} }
else else
{ {
request->Reply(500); request->Reject(500, "this is a char* reason");
} }
} }
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论