Unverified 提交 ed15a863 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo 提交者: GitHub

Channel and PayloadChannel: Optimize message format and JSON generation (#893)

Replaces PR #870.
上级 7fa40fab
......@@ -5,6 +5,7 @@
* Node: Define TypeScript types for `internal` and `data` objects (PR #891).
* `Channel` and `PayloadChannel`: Refactor `internal` with a single `handlerId` (PR #889).
* `Channel` and `PayloadChannel`: Optimize message format and JSON generation (PR #893).
* Update NPM deps.
......
{"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,OAAQ,SAAQ,oBAAoB;;IAoBhD;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,GAAG,EACH,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;QACpB,GAAG,EAAE,MAAM,CAAC;KACZ;IAiIF;;OAEG;IACH,KAAK,IAAI,IAAI;IAmCb;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAqD3E,OAAO,CAAC,cAAc;CA+DtB"}
\ No newline at end of file
{"version":3,"file":"Channel.d.ts","sourceRoot":"","sources":["../src/Channel.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,OAAQ,SAAQ,oBAAoB;;IAoBhD;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,GAAG,EACH,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;QACpB,GAAG,EAAE,MAAM,CAAC;KACZ;IAiIF;;OAEG;IACH,KAAK,IAAI,IAAI;IAmCb;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAoD3E,OAAO,CAAC,cAAc;CA+DtB"}
\ No newline at end of file
......@@ -144,13 +144,12 @@ class Channel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('request() [method:%s, id:%s]', method, id);
if (this.#closed)
throw new errors_1.InvalidStateError('Channel closed');
const request = { id, method, handlerId, data };
const payload = JSON.stringify(request);
if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
const request = `${id}:${method}:${handlerId}:${JSON.stringify(data)}`;
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
// This may throw if closed or remote side ended.
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this.#producerSocket.write(payload);
this.#producerSocket.write(Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this.#producerSocket.write(request);
return new Promise((pResolve, pReject) => {
const sent = {
id: id,
......
......@@ -181,7 +181,7 @@ class DataConsumer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
message = ' ';
else if (ppid === 57)
message = Buffer.alloc(1);
const requestData = { ppid };
const requestData = String(ppid);
await this.#payloadChannel.request('dataConsumer.send', this.#internal.dataConsumerId, requestData, message);
}
/**
......
......@@ -167,7 +167,7 @@ class DataProducer extends EnhancedEventEmitter_1.EnhancedEventEmitter {
message = ' ';
else if (ppid === 57)
message = Buffer.alloc(1);
const notifData = { ppid };
const notifData = String(ppid);
this.#payloadChannel.notify('dataProducer.send', this.#internal.dataProducerId, notifData, message);
}
handleWorkerNotifications() {
......
......@@ -16,11 +16,11 @@ export declare class PayloadChannel extends EnhancedEventEmitter {
/**
* @private
*/
notify(event: string, handlerId: string, data: any | undefined, payload: string | Buffer): void;
notify(event: string, handlerId: string, data: string | undefined, payload: string | Buffer): void;
/**
* @private
*/
request(method: string, handlerId: string, data: any, payload: string | Buffer): Promise<any>;
request(method: string, handlerId: string, data: string, payload: string | Buffer): Promise<any>;
private processData;
}
//# sourceMappingURL=PayloadChannel.d.ts.map
\ No newline at end of file
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,cAAe,SAAQ,oBAAoB;;IAuBvD;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;KACpB;IAsFF;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Bb;;OAEG;IACH,MAAM,CACL,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,GAAG,GAAG,SAAS,EACrB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IA2CP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,GAAG,EACT,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAyDxC,OAAO,CAAC,WAAW;CA8FnB"}
\ No newline at end of file
{"version":3,"file":"PayloadChannel.d.ts","sourceRoot":"","sources":["../src/PayloadChannel.ts"],"names":[],"mappings":";AAGA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAmB9D,qBAAa,cAAe,SAAQ,oBAAoB;;IAuBvD;;OAEG;gBAEF,EACC,cAAc,EACd,cAAc,EACd,EACD;QACC,cAAc,EAAE,GAAG,CAAC;QACpB,cAAc,EAAE,GAAG,CAAC;KACpB;IAsFF;;OAEG;IACH,KAAK,IAAI,IAAI;IA6Bb;;OAEG;IACH,MAAM,CACL,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxB,OAAO,EAAE,MAAM,GAAG,MAAM,GACtB,IAAI;IA2CP;;OAEG;IACG,OAAO,CACZ,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC;IAyDxC,OAAO,CAAC,WAAW;CA8FnB"}
\ No newline at end of file
......@@ -109,7 +109,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
logger.debug('notify() [event:%s]', event);
if (this.#closed)
throw new errors_1.InvalidStateError('PayloadChannel closed');
const notification = JSON.stringify({ event, handlerId, data });
const notification = `n:${event}:${handlerId}:${data}`;
if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big');
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
......@@ -141,10 +141,10 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
const id = this.#nextId;
logger.debug('request() [method:%s, id:%s]', method, id);
if (this.#closed)
throw new errors_1.InvalidStateError('Channel closed');
const request = JSON.stringify({ id, method, handlerId, data });
throw new errors_1.InvalidStateError('PayloadChannel closed');
const request = `r:${id}:${method}:${handlerId}:${data}`;
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
throw new Error('PayloadChannel request too big');
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
// This may throw if closed or remote side ended.
......@@ -167,7 +167,7 @@ class PayloadChannel extends EnhancedEventEmitter_1.EnhancedEventEmitter {
pReject(error);
},
close: () => {
pReject(new errors_1.InvalidStateError('Channel closed'));
pReject(new errors_1.InvalidStateError('PayloadChannel closed'));
}
};
// Add sent stuff to the map.
......
......@@ -234,16 +234,15 @@ export class Channel extends EnhancedEventEmitter
if (this.#closed)
throw new InvalidStateError('Channel closed');
const request = { id, method, handlerId, data };
const payload = JSON.stringify(request);
const request = `${id}:${method}:${handlerId}:${JSON.stringify(data)}`;
if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
// This may throw if closed or remote side ended.
this.#producerSocket.write(
Buffer.from(Uint32Array.of(Buffer.byteLength(payload)).buffer));
this.#producerSocket.write(payload);
Buffer.from(Uint32Array.of(Buffer.byteLength(request)).buffer));
this.#producerSocket.write(request);
return new Promise((pResolve, pReject) =>
{
......
......@@ -350,7 +350,7 @@ export class DataConsumer extends EnhancedEventEmitter<DataConsumerEvents>
else if (ppid === 57)
message = Buffer.alloc(1);
const requestData = { ppid };
const requestData = String(ppid);
await this.#payloadChannel.request(
'dataConsumer.send', this.#internal.dataConsumerId, requestData, message);
......
......@@ -314,7 +314,7 @@ export class DataProducer extends EnhancedEventEmitter<DataProducerEvents>
else if (ppid === 57)
message = Buffer.alloc(1);
const notifData = { ppid };
const notifData = String(ppid);
this.#payloadChannel.notify(
'dataProducer.send', this.#internal.dataProducerId, notifData, message);
......
......@@ -178,7 +178,7 @@ export class PayloadChannel extends EnhancedEventEmitter
notify(
event: string,
handlerId: string,
data: any | undefined,
data: string | undefined,
payload: string | Buffer
): void
{
......@@ -187,7 +187,7 @@ export class PayloadChannel extends EnhancedEventEmitter
if (this.#closed)
throw new InvalidStateError('PayloadChannel closed');
const notification = JSON.stringify({ event, handlerId, data });
const notification = `n:${event}:${handlerId}:${data}`;
if (Buffer.byteLength(notification) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel notification too big');
......@@ -229,7 +229,7 @@ export class PayloadChannel extends EnhancedEventEmitter
async request(
method: string,
handlerId: string,
data: any,
data: string,
payload: string | Buffer): Promise<any>
{
this.#nextId < 4294967295 ? ++this.#nextId : (this.#nextId = 1);
......@@ -239,12 +239,12 @@ export class PayloadChannel extends EnhancedEventEmitter
logger.debug('request() [method:%s, id:%s]', method, id);
if (this.#closed)
throw new InvalidStateError('Channel closed');
throw new InvalidStateError('PayloadChannel closed');
const request = JSON.stringify({ id, method, handlerId, data });
const request = `r:${id}:${method}:${handlerId}:${data}`;
if (Buffer.byteLength(request) > MESSAGE_MAX_LEN)
throw new Error('Channel request too big');
throw new Error('PayloadChannel request too big');
else if (Buffer.byteLength(payload) > MESSAGE_MAX_LEN)
throw new Error('PayloadChannel payload too big');
......@@ -278,7 +278,7 @@ export class PayloadChannel extends EnhancedEventEmitter
},
close : () =>
{
pReject(new InvalidStateError('Channel closed'));
pReject(new InvalidStateError('PayloadChannel closed'));
}
};
......
......@@ -6,6 +6,8 @@
#include <nlohmann/json.hpp>
#include <string>
using json = nlohmann::json;
namespace Channel
{
class ChannelNotifier
......@@ -15,6 +17,7 @@ namespace Channel
static void Emit(uint64_t targetId, const char* event);
static void Emit(const std::string& targetId, const char* event);
static void Emit(const std::string& targetId, const char* event, json& data);
static void Emit(const std::string& targetId, const char* event, const std::string& data);
public:
// Passed by argument.
......
......@@ -82,7 +82,7 @@ namespace Channel
static absl::flat_hash_map<std::string, MethodId> string2MethodId;
public:
ChannelRequest(Channel::ChannelSocket* channel, json& jsonRequest);
ChannelRequest(Channel::ChannelSocket* channel, const char* msg, size_t msgLen);
virtual ~ChannelRequest();
void Accept();
......
......@@ -5,6 +5,9 @@
#include "Channel/ChannelRequest.hpp"
#include "handles/UnixStreamSocket.hpp"
#include <nlohmann/json.hpp>
#include <string>
using json = nlohmann::json;
namespace Channel
{
......@@ -83,6 +86,7 @@ namespace Channel
void SetListener(Listener* listener);
bool CallbackRead();
void Send(json& jsonMessage);
void Send(const std::string& message);
void SendLog(const char* message, uint32_t messageLen);
private:
......
......@@ -3,14 +3,11 @@
#include "common.hpp"
#include <absl/container/flat_hash_map.h>
#include <nlohmann/json.hpp>
#include <string>
using json = nlohmann::json;
namespace PayloadChannel
{
class Notification
class PayloadChannelNotification
{
public:
enum class EventId
......@@ -21,14 +18,14 @@ namespace PayloadChannel
};
public:
static bool IsNotification(json& jsonNotification);
static bool IsNotification(const char* msg, size_t msgLen);
private:
static absl::flat_hash_map<std::string, EventId> string2EventId;
public:
explicit Notification(json& jsonNotification);
virtual ~Notification();
PayloadChannelNotification(const char* msg, size_t msgLen);
virtual ~PayloadChannelNotification();
public:
void SetPayload(const uint8_t* payload, size_t payloadLen);
......@@ -38,7 +35,7 @@ namespace PayloadChannel
std::string event;
EventId eventId;
std::string handlerId;
json data;
std::string data;
const uint8_t* payload{ nullptr };
size_t payloadLen{ 0u };
};
......
......@@ -6,6 +6,8 @@
#include <nlohmann/json.hpp>
#include <string>
using json = nlohmann::json;
namespace PayloadChannel
{
class PayloadChannelNotifier
......@@ -20,6 +22,12 @@ namespace PayloadChannel
json& data,
const uint8_t* payload,
size_t payloadLen);
static void Emit(
const std::string& targetId,
const char* event,
const std::string& data,
const uint8_t* payload,
size_t payloadLen);
public:
// Passed by argument.
......
......@@ -23,13 +23,13 @@ namespace PayloadChannel
};
public:
static bool IsRequest(json& jsonRequest);
static bool IsRequest(const char* msg, size_t msgLen);
private:
static absl::flat_hash_map<std::string, MethodId> string2MethodId;
public:
PayloadChannelRequest(PayloadChannel::PayloadChannelSocket* channel, json& jsonRequest);
PayloadChannelRequest(PayloadChannel::PayloadChannelSocket* channel, char* msg, size_t msgLen);
virtual ~PayloadChannelRequest();
public:
......@@ -46,7 +46,7 @@ namespace PayloadChannel
std::string method;
MethodId methodId;
std::string handlerId;
json data;
std::string data;
const uint8_t* payload{ nullptr };
size_t payloadLen{ 0u };
// Others.
......
......@@ -2,10 +2,13 @@
#define MS_PAYLOAD_CHANNEL_UNIX_STREAM_SOCKET_HPP
#include "common.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/PayloadChannelNotification.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
#include "handles/UnixStreamSocket.hpp"
#include <nlohmann/json.hpp>
#include <string>
using json = nlohmann::json;
namespace PayloadChannel
{
......@@ -69,7 +72,7 @@ namespace PayloadChannel
virtual ~NotificationHandler() = default;
public:
virtual void HandleNotification(PayloadChannel::Notification* notification) = 0;
virtual void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) = 0;
};
class Listener : public RequestHandler, public NotificationHandler
......@@ -95,7 +98,9 @@ namespace PayloadChannel
void SetListener(Listener* listener);
bool CallbackRead();
void Send(json& jsonMessage, const uint8_t* payload, size_t payloadLen);
void Send(const std::string& message, const uint8_t* payload, size_t payloadLen);
void Send(json& jsonMessage);
void Send(const std::string& message);
private:
void SendImpl(const uint8_t* message, uint32_t messageLen);
......@@ -118,7 +123,7 @@ namespace PayloadChannel
PayloadChannelReadCtx payloadChannelReadCtx{ nullptr };
PayloadChannelWriteFn payloadChannelWriteFn{ nullptr };
PayloadChannelWriteCtx payloadChannelWriteCtx{ nullptr };
PayloadChannel::Notification* ongoingNotification{ nullptr };
PayloadChannel::PayloadChannelNotification* ongoingNotification{ nullptr };
PayloadChannel::PayloadChannelRequest* ongoingRequest{ nullptr };
uv_async_t* uvReadHandle{ nullptr };
uint8_t* writeBuffer{ nullptr };
......
......@@ -58,7 +58,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
public:
// Passed by argument.
......
......@@ -39,7 +39,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
};
} // namespace RTC
......
......@@ -36,7 +36,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
private:
bool IsConnected() const override;
......
......@@ -36,7 +36,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
private:
bool IsConnected() const override;
......
......@@ -138,7 +138,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
private:
RTC::RtpStreamRecv* GetRtpStream(RTC::RtpPacket* packet);
......
......@@ -3,7 +3,7 @@
#include "common.hpp"
#include "Channel/ChannelRequest.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/PayloadChannelNotification.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
#include "RTC/Consumer.hpp"
#include "RTC/DataConsumer.hpp"
......
......@@ -6,7 +6,7 @@
#include "DepLibUV.hpp"
#include "Channel/ChannelRequest.hpp"
#include "Channel/ChannelSocket.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/PayloadChannelNotification.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
#include "RTC/Consumer.hpp"
#include "RTC/DataConsumer.hpp"
......@@ -139,7 +139,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
protected:
// Must be called from the subclass.
......
......@@ -72,7 +72,7 @@ namespace RTC
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
private:
bool IsConnected() const override;
......
......@@ -7,6 +7,7 @@
#include <cstring> // std::memcmp(), std::memcpy()
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
#ifdef _WIN32
#include <ws2ipdef.h>
// https://stackoverflow.com/a/24550632/2085408
......@@ -276,6 +277,8 @@ namespace Utils
static uint8_t* Base64Decode(const uint8_t* data, size_t len, size_t& outLen);
static uint8_t* Base64Decode(const std::string& str, size_t& outLen);
static std::vector<std::string> Split(const std::string& str, char separator, size_t limit = 0);
};
class Time
......
......@@ -4,7 +4,7 @@
#include "common.hpp"
#include "Channel/ChannelRequest.hpp"
#include "Channel/ChannelSocket.hpp"
#include "PayloadChannel/Notification.hpp"
#include "PayloadChannel/PayloadChannelNotification.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
#include "PayloadChannel/PayloadChannelSocket.hpp"
#include "RTC/Router.hpp"
......@@ -48,7 +48,7 @@ public:
/* Methods inherited from PayloadChannel::PayloadChannelSocket::NotificationHandler. */
public:
void HandleNotification(PayloadChannel::Notification* notification) override;
void HandleNotification(PayloadChannel::PayloadChannelNotification* notification) override;
/* Methods inherited from PayloadChannel::PayloadChannelSocket::Listener. */
public:
......
......@@ -62,7 +62,7 @@ common_sources = [
'src/Channel/ChannelNotifier.cpp',
'src/Channel/ChannelRequest.cpp',
'src/Channel/ChannelSocket.cpp',
'src/PayloadChannel/Notification.cpp',
'src/PayloadChannel/PayloadChannelNotification.cpp',
'src/PayloadChannel/PayloadChannelNotifier.cpp',
'src/PayloadChannel/PayloadChannelRequest.cpp',
'src/PayloadChannel/PayloadChannelSocket.cpp',
......@@ -280,6 +280,8 @@ mediasoup_worker_test = executable(
],
sources: common_sources + [
'test/src/tests.cpp',
'test/src/PayloadChannel/TestPayloadChannelNotification.cpp',
'test/src/PayloadChannel/TestPayloadChannelRequest.cpp',
'test/src/RTC/TestKeyFrameRequestManager.cpp',
'test/src/RTC/TestNackGenerator.cpp',
'test/src/RTC/TestRateCalculator.cpp',
......
......@@ -61,4 +61,22 @@ namespace Channel
ChannelNotifier::channel->Send(jsonNotification);
}
void ChannelNotifier::Emit(const std::string& targetId, const char* event, const std::string& data)
{
MS_TRACE();
MS_ASSERT(ChannelNotifier::channel, "channel unset");
std::string notification("{\"targetId\":\"");
notification.append(targetId);
notification.append("\",\"event\":\"");
notification.append(event);
notification.append("\",\"data\":");
notification.append(data);
notification.append("}");
ChannelNotifier::channel->Send(notification);
}
} // namespace Channel
......@@ -75,24 +75,24 @@ namespace Channel
/* Instance methods. */
ChannelRequest::ChannelRequest(Channel::ChannelSocket* channel, json& jsonRequest)
/**
* msg contains "id:method:handlerId:data" where:
* - id: The ID of the request.
* - handlerId: The ID of the target entity
* - data: JSON object.
*/
ChannelRequest::ChannelRequest(Channel::ChannelSocket* channel, const char* msg, size_t msgLen)
: channel(channel)
{
MS_TRACE();
auto jsonIdIt = jsonRequest.find("id");
auto info = Utils::String::Split(std::string(msg, msgLen), ':', 3);
if (jsonIdIt == jsonRequest.end() || !Utils::Json::IsPositiveInteger(*jsonIdIt))
MS_THROW_ERROR("missing id");
if (info.size() < 2)
MS_THROW_ERROR("too few arguments");
this->id = jsonIdIt->get<uint32_t>();
auto jsonMethodIt = jsonRequest.find("method");
if (jsonMethodIt == jsonRequest.end() || !jsonMethodIt->is_string())
MS_THROW_ERROR("missing method");
this->method = jsonMethodIt->get<std::string>();
this->id = std::stoul(info[0]);
this->method = info[1];
auto methodIdIt = ChannelRequest::string2MethodId.find(this->method);
......@@ -105,17 +105,33 @@ namespace Channel
this->methodId = methodIdIt->second;
auto jsonHandlerIdIt = jsonRequest.find("handlerId");
if (jsonHandlerIdIt != jsonRequest.end() && jsonHandlerIdIt->is_string())
this->handlerId = *jsonHandlerIdIt;
if (info.size() > 2)
{
auto& handlerId = info[2];
auto jsonDataIt = jsonRequest.find("data");
if (handlerId != "undefined")
this->handlerId = handlerId;
}
if (jsonDataIt != jsonRequest.end() && jsonDataIt->is_object())
this->data = *jsonDataIt;
else
this->data = json::object();
if (info.size() > 3)
{
auto& data = info[3];
if (data != "undefined")
{
try
{
this->data = json::parse(data);
if (!this->data.is_object())
this->data = json::object();
}
catch (const json::parse_error& error)
{
MS_THROW_TYPE_ERROR("JSON parsing error: %s", error.what());
}
}
}
}
ChannelRequest::~ChannelRequest()
......@@ -131,12 +147,12 @@ namespace Channel
this->replied = true;
json jsonResponse = json::object();
std::string response("{\"id\":");
jsonResponse["id"] = this->id;
jsonResponse["accepted"] = true;
response.append(std::to_string(this->id));
response.append(",\"accepted\":true}");
this->channel->Send(jsonResponse);
this->channel->Send(response);
}
void ChannelRequest::Accept(json& data)
......
......@@ -140,6 +140,24 @@ namespace Channel
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
void ChannelSocket::Send(const std::string& message)
{
MS_TRACE_STD();
if (this->closed)
return;
if (message.length() > PayloadMaxLen)
{
MS_ERROR_STD("message too big");
return;
}
SendImpl(
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
void ChannelSocket::SendLog(const char* message, uint32_t messageLen)
{
MS_TRACE_STD();
......@@ -171,42 +189,6 @@ namespace Channel
auto free = this->channelReadFn(
&message, &messageLen, &messageCtx, this->uvReadHandle, this->channelReadCtx);
if (free)
{
try
{
json jsonMessage = json::parse(message, message + static_cast<size_t>(messageLen));
auto* request = new Channel::ChannelRequest(this, jsonMessage);
// Notify the listener.
try
{
this->listener->HandleRequest(request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR_STD("discarding wrong Channel request: %s", error.what());
}
free(message, messageLen, messageCtx);
}
return free != nullptr;
}
......@@ -240,8 +222,7 @@ namespace Channel
try
{
json jsonMessage = json::parse(msg, msg + msgLen);
auto* request = new Channel::ChannelRequest(this, jsonMessage);
auto* request = new Channel::ChannelRequest(this, msg, msgLen);
// Notify the listener.
try
......
#define MS_CLASS "PayloadChannel::Notification"
// #define MS_LOG_DEV_LEVEL 3
#include "PayloadChannel/Notification.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
namespace PayloadChannel
{
/* Class variables. */
// clang-format off
absl::flat_hash_map<std::string, Notification::EventId> Notification::string2EventId =
{
{ "transport.sendRtcp", Notification::EventId::TRANSPORT_SEND_RTCP },
{ "producer.send", Notification::EventId::PRODUCER_SEND },
{ "dataProducer.send", Notification::EventId::DATA_PRODUCER_SEND }
};
// clang-format on
/* Class methods. */
bool Notification::IsNotification(json& jsonNotification)
{
MS_TRACE();
auto jsonEventIdIt = jsonNotification.find("event");
if (jsonEventIdIt == jsonNotification.end() || !jsonEventIdIt->is_string())
return false;
auto event = jsonEventIdIt->get<std::string>();
auto eventIdIt = Notification::string2EventId.find(event);
if (eventIdIt == Notification::string2EventId.end())
return false;
return true;
}
/* Instance methods. */
Notification::Notification(json& jsonNotification)
{
MS_TRACE();
auto jsonEventIdIt = jsonNotification.find("event");
if (jsonEventIdIt == jsonNotification.end() || !jsonEventIdIt->is_string())
MS_THROW_ERROR("missing event");
this->event = jsonEventIdIt->get<std::string>();
auto eventIdIt = Notification::string2EventId.find(this->event);
if (eventIdIt == Notification::string2EventId.end())
MS_THROW_ERROR("unknown event '%s'", this->event.c_str());
this->eventId = eventIdIt->second;
auto jsonHandlerIdIt = jsonNotification.find("handlerId");
if (jsonHandlerIdIt != jsonNotification.end() && jsonHandlerIdIt->is_string())
this->handlerId = *jsonHandlerIdIt;
auto jsonDataIt = jsonNotification.find("data");
if (jsonDataIt != jsonNotification.end() && jsonDataIt->is_object())
this->data = *jsonDataIt;
else
this->data = json::object();
}
Notification::~Notification()
{
MS_TRACE();
}
void Notification::SetPayload(const uint8_t* payload, size_t payloadLen)
{
MS_TRACE();
this->payload = payload;
this->payloadLen = payloadLen;
}
} // namespace PayloadChannel
#define MS_CLASS "PayloadChannel::PayloadChannelNotification"
// #define MS_LOG_DEV_LEVEL 3
#include "PayloadChannel/PayloadChannelNotification.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
namespace PayloadChannel
{
/* Class variables. */
// clang-format off
absl::flat_hash_map<std::string, PayloadChannelNotification::EventId> PayloadChannelNotification::string2EventId =
{
{ "transport.sendRtcp", PayloadChannelNotification::EventId::TRANSPORT_SEND_RTCP },
{ "producer.send", PayloadChannelNotification::EventId::PRODUCER_SEND },
{ "dataProducer.send", PayloadChannelNotification::EventId::DATA_PRODUCER_SEND }
};
// clang-format on
/* Class methods. */
bool PayloadChannelNotification::IsNotification(const char* msg, size_t msgLen)
{
MS_TRACE();
return (msgLen > 2 && msg[0] == 'n' && msg[1] == ':');
}
/* Instance methods. */
PayloadChannelNotification::PayloadChannelNotification(const char* msg, size_t msgLen)
{
MS_TRACE();
auto info = Utils::String::Split(std::string(msg, msgLen), ':');
if (info.size() < 1)
MS_THROW_ERROR("too few arguments");
this->event = info[0];
auto eventIdIt = PayloadChannelNotification::string2EventId.find(this->event);
if (eventIdIt == PayloadChannelNotification::string2EventId.end())
MS_THROW_ERROR("unknown event '%s'", this->event.c_str());
this->eventId = eventIdIt->second;
if (info.size() > 1)
{
auto& handlerId = info[1];
if (handlerId != "undefined")
this->handlerId = handlerId;
}
if (info.size() > 2)
{
auto& data = info[2];
if (data != "undefined")
this->data = data;
}
}
PayloadChannelNotification::~PayloadChannelNotification()
{
MS_TRACE();
}
void PayloadChannelNotification::SetPayload(const uint8_t* payload, size_t payloadLen)
{
MS_TRACE();
this->payload = payload;
this->payloadLen = payloadLen;
}
} // namespace PayloadChannel
......@@ -26,12 +26,14 @@ namespace PayloadChannel
MS_ASSERT(PayloadChannelNotifier::payloadChannel, "payloadChannel unset");
json jsonNotification = json::object();
std::string notification("{\"targetId\":\"");
jsonNotification["targetId"] = targetId;
jsonNotification["event"] = event;
notification.append(targetId);
notification.append("\",\"event\":\"");
notification.append(event);
notification.append("}");
PayloadChannelNotifier::payloadChannel->Send(jsonNotification, payload, payloadLen);
PayloadChannelNotifier::payloadChannel->Send(notification, payload, payloadLen);
}
void PayloadChannelNotifier::Emit(
......
......@@ -19,44 +19,35 @@ namespace PayloadChannel
// clang-format on
/* Class methods. */
bool PayloadChannelRequest::IsRequest(json& jsonRequest)
bool PayloadChannelRequest::IsRequest(const char* msg, size_t msgLen)
{
MS_TRACE();
auto jsonIdIt = jsonRequest.find("id");
if (jsonIdIt == jsonRequest.end() || !Utils::Json::IsPositiveInteger(*jsonIdIt))
return false;
auto jsonMethodIt = jsonRequest.find("method");
if (jsonMethodIt == jsonRequest.end() || !jsonMethodIt->is_string())
return false;
return true;
return (msgLen > 2 && msg[0] == 'r' && msg[1] == ':');
}
/* Instance methods. */
/**
* msg contains "id:method:handlerId:data" where:
* - id: The ID of the request.
* - handlerId: The ID of the target entity
* - data: JSON object.
*/
PayloadChannelRequest::PayloadChannelRequest(
PayloadChannel::PayloadChannelSocket* channel, json& jsonRequest)
PayloadChannel::PayloadChannelSocket* channel, char* msg, size_t msgLen)
: channel(channel)
{
MS_TRACE();
auto jsonIdIt = jsonRequest.find("id");
if (jsonIdIt == jsonRequest.end() || !Utils::Json::IsPositiveInteger(*jsonIdIt))
MS_THROW_ERROR("missing id");
this->id = jsonIdIt->get<uint32_t>();
auto jsonMethodIt = jsonRequest.find("method");
auto info = Utils::String::Split(std::string(msg, msgLen), ':', 3);
if (jsonMethodIt == jsonRequest.end() || !jsonMethodIt->is_string())
MS_THROW_ERROR("missing method");
if (info.size() < 2)
MS_THROW_ERROR("too few arguments");
this->method = jsonMethodIt->get<std::string>();
this->id = std::stoul(info[0]);
this->method = info[1];
auto methodIdIt = PayloadChannelRequest::string2MethodId.find(this->method);
......@@ -69,17 +60,21 @@ namespace PayloadChannel
this->methodId = methodIdIt->second;
auto jsonHandlerIdIt = jsonRequest.find("handlerId");
if (info.size() > 2)
{
auto& handlerId = info[2];
if (jsonHandlerIdIt != jsonRequest.end() && jsonHandlerIdIt->is_object())
this->handlerId = *jsonHandlerIdIt;
if (handlerId != "undefined")
this->handlerId = handlerId;
}
auto jsonDataIt = jsonRequest.find("data");
if (info.size() > 3)
{
auto& data = info[3];
if (jsonDataIt != jsonRequest.end() && jsonDataIt->is_object())
this->data = *jsonDataIt;
else
this->data = json::object();
if (data != "undefined")
this->data = data;
}
}
PayloadChannelRequest::~PayloadChannelRequest()
......@@ -95,12 +90,12 @@ namespace PayloadChannel
this->replied = true;
json jsonResponse = json::object();
std::string response("{\"id\":");
jsonResponse["id"] = this->id;
jsonResponse["accepted"] = true;
response.append(std::to_string(this->id));
response.append(",\"accepted\":true}");
this->channel->Send(jsonResponse);
this->channel->Send(response);
}
void PayloadChannelRequest::Accept(json& data)
......
......@@ -131,6 +131,16 @@ namespace PayloadChannel
std::string message = jsonMessage.dump();
this->Send(message, payload, payloadLen);
}
void PayloadChannelSocket::Send(const std::string& message, const uint8_t* payload, size_t payloadLen)
{
MS_TRACE();
if (this->closed)
return;
if (message.length() > PayloadMaxLen)
{
MS_ERROR("message too big");
......@@ -171,6 +181,24 @@ namespace PayloadChannel
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
void PayloadChannelSocket::Send(const std::string& message)
{
MS_TRACE();
if (this->closed)
return;
if (message.length() > PayloadMaxLen)
{
MS_ERROR("message too big");
return;
}
SendImpl(
reinterpret_cast<const uint8_t*>(message.c_str()), static_cast<uint32_t>(message.length()));
}
bool PayloadChannelSocket::CallbackRead()
{
MS_TRACE();
......@@ -196,94 +224,6 @@ namespace PayloadChannel
this->uvReadHandle,
this->payloadChannelReadCtx);
if (free)
{
try
{
json jsonData = json::parse(message, message + static_cast<size_t>(messageLen));
if (PayloadChannelRequest::IsRequest(jsonData))
{
try
{
auto* request = new PayloadChannel::PayloadChannelRequest(this, jsonData);
request->SetPayload(payload, payloadLen);
// Notify the listener.
try
{
this->listener->HandleRequest(request);
}
catch (const MediaSoupTypeError& error)
{
request->TypeError(error.what());
}
catch (const MediaSoupError& error)
{
request->Error(error.what());
}
// Delete the Request.
delete request;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification: %s", error.what());
}
}
else if (Notification::IsNotification(jsonData))
{
try
{
auto* notification = new PayloadChannel::Notification(jsonData);
notification->SetPayload(payload, payloadLen);
// Notify the listener.
try
{
this->listener->HandleNotification(notification);
}
catch (const MediaSoupError& error)
{
MS_ERROR("notification failed: %s", error.what());
}
// Delete the Notification.
delete notification;
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification: %s", error.what());
}
}
else
{
MS_ERROR("discarding wrong Payload Channel data");
}
}
catch (const json::parse_error& error)
{
MS_ERROR("JSON parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Channel request: %s", error.what());
}
free(message, messageLen, messageCtx);
free(payload, payloadLen, payloadCapacity);
}
return free != nullptr;
}
......@@ -336,42 +276,40 @@ namespace PayloadChannel
if (!this->ongoingNotification && !this->ongoingRequest)
{
json jsonData = json::parse(msg, msg + msgLen);
if (PayloadChannelRequest::IsRequest(jsonData))
if (PayloadChannelRequest::IsRequest(msg, msgLen))
{
try
{
this->ongoingRequest = new PayloadChannel::PayloadChannelRequest(this, jsonData);
this->ongoingRequest = new PayloadChannel::PayloadChannelRequest(this, msg + 2, msgLen - 2);
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
MS_ERROR_STD("msg parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification: %s", error.what());
MS_ERROR("discarding wrong PayloadChannel request: %s", error.what());
}
}
else if (Notification::IsNotification(jsonData))
else if (PayloadChannelNotification::IsNotification(msg, msgLen))
{
try
{
this->ongoingNotification = new PayloadChannel::Notification(jsonData);
this->ongoingNotification =
new PayloadChannel::PayloadChannelNotification(msg + 2, msgLen - 2);
}
catch (const json::parse_error& error)
{
MS_ERROR_STD("JSON parsing error: %s", error.what());
MS_ERROR_STD("msg parsing error: %s", error.what());
}
catch (const MediaSoupError& error)
{
MS_ERROR("discarding wrong Payload Channel notification: %s", error.what());
MS_ERROR("discarding wrong PayloadChannel notification: %s", error.what());
}
}
else
{
MS_ERROR("discarding wrong Payload Channel data");
MS_ERROR("discarding wrong PayloadChannel data");
}
}
else if (this->ongoingNotification)
......
......@@ -8,6 +8,7 @@
#include "Utils.hpp"
#include "Channel/ChannelNotifier.hpp"
#include "RTC/SctpAssociation.hpp"
#include <stdexcept>
namespace RTC
{
......@@ -198,12 +199,10 @@ namespace RTC
// Trigger 'bufferedamountlow' now.
if (this->bufferedAmount <= this->bufferedAmountLowThreshold)
{
// Notify the Node DataConsumer.
json data = json::object();
std::string data("{\"bufferedAmount\":\"");
data["bufferedAmount"] = this->bufferedAmount;
Channel::ChannelNotifier::Emit(this->id, "bufferedamountlow", data);
data.append(std::to_string(this->bufferedAmount));
data.append("\"}");
}
// Force the trigger of 'bufferedamountlow' once there is less or same
// buffered data than the given threshold.
......@@ -240,26 +239,29 @@ namespace RTC
MS_THROW_ERROR("no SCTP association present");
}
auto jsonPpidIt = request->data.find("ppid");
int ppid;
if (jsonPpidIt == request->data.end() || !Utils::Json::IsPositiveInteger(*jsonPpidIt))
// This may throw.
// NOTE: If this throws we have to catch the error and throw a MediaSoupError
// intead, otherwise the process would crash.
try
{
ppid = std::stoi(request->data);
}
catch (const std::exception& error)
{
MS_THROW_TYPE_ERROR("invalid ppid");
MS_THROW_TYPE_ERROR("invalid PPID value: %s", error.what());
}
auto ppid = jsonPpidIt->get<uint32_t>();
const auto* msg = request->payload;
auto len = request->payloadLen;
if (len > this->maxMessageSize)
{
MS_WARN_TAG(
message,
MS_THROW_TYPE_ERROR(
"given message exceeds maxMessageSize value [maxMessageSize:%zu, len:%zu]",
len,
this->maxMessageSize);
return;
}
const auto* cb = new onQueuedCallback(
......@@ -338,9 +340,10 @@ namespace RTC
this->forceTriggerBufferedAmountLow = false;
// Notify the Node DataConsumer.
json data = json::object();
std::string data("{\"bufferedAmount\":\"");
data["bufferedAmount"] = this->bufferedAmount;
data.append(std::to_string(this->bufferedAmount));
data.append("\"}");
Channel::ChannelNotifier::Emit(this->id, "bufferedamountlow", data);
}
......
......@@ -6,6 +6,7 @@
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
#include <stdexcept>
namespace RTC
{
......@@ -146,34 +147,37 @@ namespace RTC
}
}
void DataProducer::HandleNotification(PayloadChannel::Notification* notification)
void DataProducer::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
switch (notification->eventId)
{
case PayloadChannel::Notification::EventId::DATA_PRODUCER_SEND:
case PayloadChannel::PayloadChannelNotification::EventId::DATA_PRODUCER_SEND:
{
auto jsonPpidIt = notification->data.find("ppid");
int ppid;
if (jsonPpidIt == notification->data.end() || !Utils::Json::IsPositiveInteger(*jsonPpidIt))
// This may throw.
// NOTE: If this throws we have to catch the error and throw a MediaSoupError
// intead, otherwise the process would crash.
try
{
MS_THROW_TYPE_ERROR("invalid ppid");
ppid = std::stoi(notification->data);
}
catch (const std::exception& error)
{
MS_THROW_TYPE_ERROR("invalid PPID value: %s", error.what());
}
auto ppid = jsonPpidIt->get<uint32_t>();
const auto* msg = notification->payload;
auto len = notification->payloadLen;
if (len > this->maxMessageSize)
{
MS_WARN_TAG(
message,
MS_THROW_TYPE_ERROR(
"given message exceeds maxMessageSize value [maxMessageSize:%zu, len:%zu]",
len,
this->maxMessageSize);
break;
}
this->ReceiveMessage(ppid, msg, len);
......
......@@ -51,13 +51,13 @@ namespace RTC
RTC::Transport::HandleRequest(request);
}
void DirectTransport::HandleNotification(PayloadChannel::Notification* notification)
void DirectTransport::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
switch (notification->eventId)
{
case PayloadChannel::Notification::EventId::TRANSPORT_SEND_RTCP:
case PayloadChannel::PayloadChannelNotification::EventId::TRANSPORT_SEND_RTCP:
{
const auto* data = notification->payload;
auto len = notification->payloadLen;
......
......@@ -415,7 +415,7 @@ namespace RTC
}
}
void PipeTransport::HandleNotification(PayloadChannel::Notification* notification)
void PipeTransport::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
......
......@@ -679,7 +679,7 @@ namespace RTC
}
}
void PlainTransport::HandleNotification(PayloadChannel::Notification* notification)
void PlainTransport::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
......
......@@ -609,13 +609,13 @@ namespace RTC
}
}
void Producer::HandleNotification(PayloadChannel::Notification* notification)
void Producer::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
switch (notification->eventId)
{
case PayloadChannel::Notification::EventId::PRODUCER_SEND:
case PayloadChannel::PayloadChannelNotification::EventId::PRODUCER_SEND:
{
const auto* data = notification->payload;
auto len = notification->payloadLen;
......
......@@ -1463,7 +1463,7 @@ namespace RTC
}
}
void Transport::HandleNotification(PayloadChannel::Notification* notification)
void Transport::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
......
......@@ -662,7 +662,7 @@ namespace RTC
}
}
void WebRtcTransport::HandleNotification(PayloadChannel::Notification* notification)
void WebRtcTransport::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
......
......@@ -10,6 +10,7 @@
#include <mutex>
#include <nlohmann/json.hpp>
#include <sstream> // std::ostringstream
#include <stdexcept>
extern "C"
{
#include <getopt.h>
......
......@@ -170,4 +170,43 @@ namespace Utils
return Base64Decode(data, str.size(), outLen);
}
std::vector<std::string> Utils::String::Split(const std::string& str, char separator, size_t limit)
{
std::vector<std::string> items;
size_t pos = 0;
while (pos < str.length())
{
auto found = str.find(separator, pos);
std::string item;
if (found != std::string::npos)
{
item = str.substr(pos, found - pos);
items.push_back(item);
}
else
{
item = str.substr(pos, str.size());
items.push_back(item);
break;
}
// Escape the separator character.
pos += item.length() + 1;
// Limit reached, add the remaining buffer to the last item.
if (limit != 0 && items.size() >= limit)
{
item = str.substr(pos, str.size());
items.push_back(item);
break;
}
}
return items;
}
} // namespace Utils
......@@ -452,7 +452,7 @@ inline void Worker::OnChannelClosed(Channel::ChannelSocket* /*socket*/)
Close();
}
inline void Worker::HandleNotification(PayloadChannel::Notification* notification)
inline void Worker::HandleNotification(PayloadChannel::PayloadChannelNotification* notification)
{
MS_TRACE();
......@@ -562,39 +562,62 @@ inline void Worker::OnSignal(SignalsHandler* /*signalsHandler*/, int signum)
inline void Worker::OnChannelRequestHandlerAdded(
const std::string& id, Channel::ChannelSocket::RequestHandler* handler)
{
MS_TRACE();
if (this->mapChannelRequestHandlers.find(id) != this->mapChannelRequestHandlers.end())
{
MS_THROW_ERROR("Channel request handler with ID %s already exists", id.c_str());
}
this->mapChannelRequestHandlers[id] = handler;
}
inline void Worker::OnChannelRequestHandlerRemoved(const std::string& id)
{
MS_TRACE();
this->mapChannelRequestHandlers.erase(id);
}
inline void Worker::OnPayloadChannelRequestHandlerAdded(
const std::string& id, PayloadChannel::PayloadChannelSocket::RequestHandler* handler)
{
MS_TRACE();
if (this->mapPayloadChannelRequestHandlers.find(id) != this->mapPayloadChannelRequestHandlers.end())
MS_THROW_ERROR("Payload channel request handler with ID %s already exists", id.c_str());
{
MS_THROW_ERROR("PayloadChannel request handler with ID %s already exists", id.c_str());
}
this->mapPayloadChannelRequestHandlers[id] = handler;
}
inline void Worker::OnPayloadChannelRequestHandlerRemoved(const std::string& id)
{
MS_TRACE();
this->mapPayloadChannelRequestHandlers.erase(id);
}
inline void Worker::OnPayloadChannelNotificationHandlerAdded(
const std::string& id, PayloadChannel::PayloadChannelSocket::NotificationHandler* handler)
{
MS_TRACE();
if (
this->mapPayloadChannelNotificationHandlers.find(id) !=
this->mapPayloadChannelNotificationHandlers.end())
MS_THROW_ERROR("Payload channel notification handler with ID %s already exists", id.c_str());
{
MS_THROW_ERROR("PayloadChannel notification handler with ID %s already exists", id.c_str());
}
this->mapPayloadChannelNotificationHandlers[id] = handler;
}
inline void Worker::OnPayloadChannelNotificationHandlerRemoved(const std::string& id)
{
MS_TRACE();
this->mapPayloadChannelNotificationHandlers.erase(id);
}
......
#include "common.hpp"
#include "PayloadChannel/PayloadChannelNotification.hpp"
#include <catch2/catch.hpp>
SCENARIO("PayloadChannelNotification", "[channel][notification]")
{
SECTION("notification")
{
char foo[]{ "n:abcd" };
REQUIRE(PayloadChannel::PayloadChannelNotification::IsNotification(foo, sizeof(foo)) == true);
}
SECTION("request")
{
char foo[]{ "r:abcd" };
REQUIRE(PayloadChannel::PayloadChannelNotification::IsNotification(foo, sizeof(foo)) == false);
}
SECTION("non notification")
{
char foo[]{ "abcd" };
REQUIRE(PayloadChannel::PayloadChannelNotification::IsNotification(foo, sizeof(foo)) == false);
}
SECTION("empty string")
{
char foo[]{};
REQUIRE(PayloadChannel::PayloadChannelNotification::IsNotification(foo, sizeof(foo)) == false);
}
}
#include "common.hpp"
#include "PayloadChannel/PayloadChannelRequest.hpp"
#include <catch2/catch.hpp>
SCENARIO("PayloadChannelRequest", "[channel][request]")
{
SECTION("notification")
{
char foo[]{ "n:abcd" };
REQUIRE(PayloadChannel::PayloadChannelRequest::IsRequest(foo, sizeof(foo)) == false);
}
SECTION("request")
{
char foo[]{ "r:abcd" };
REQUIRE(PayloadChannel::PayloadChannelRequest::IsRequest(foo, sizeof(foo)) == true);
}
SECTION("non request")
{
char foo[]{ "abcd" };
REQUIRE(PayloadChannel::PayloadChannelRequest::IsRequest(foo, sizeof(foo)) == false);
}
SECTION("empty string")
{
char foo[]{};
REQUIRE(PayloadChannel::PayloadChannelRequest::IsRequest(foo, sizeof(foo)) == false);
}
}
......@@ -76,3 +76,40 @@ SCENARIO("String::Base64Encode() and String::Base64Decode()")
REQUIRE(outLen == sizeof(rtpPacket));
REQUIRE(std::memcmp(decodedPtr, rtpPacket, outLen) == 0);
}
SCENARIO("String::Split()", "[utils][string]")
{
SECTION("empty string")
{
std::string foo{};
auto v = String::Split(foo, ',');
REQUIRE(v.size() == 0);
}
SECTION("character separated string with no limit")
{
std::string foo{ "a,b,c,d" };
auto v = String::Split(foo, ',');
REQUIRE(v.size() == 4);
REQUIRE(v[0] == "a");
REQUIRE(v[1] == "b");
REQUIRE(v[2] == "c");
REQUIRE(v[3] == "d");
}
SECTION("character separated string with limit")
{
std::string foo{ "a,b,c,d" };
auto v = String::Split(foo, ',', 2);
REQUIRE(v.size() == 3);
REQUIRE(v[0] == "a");
REQUIRE(v[1] == "b");
REQUIRE(v[2] == "c,d");
}
}
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论