clang format, based on cpprest

This commit is contained in:
Benjamin Sergeant 2019-05-30 08:46:50 -07:00
parent 879a4b38aa
commit c65fec7271
47 changed files with 426 additions and 414 deletions

46
.clang-format Normal file
View File

@ -0,0 +1,46 @@
# https://releases.llvm.org/7.0.0/tools/clang/docs/ClangFormatStyleOptions.html
---
Language: Cpp
BasedOnStyle: WebKit
AlignAfterOpenBracket: Align
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: true
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Allman
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 100
ConstructorInitializerAllOnOneLineOrOnePerLine: false
Cpp11BracedListStyle: true
FixNamespaceComments: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^["<](stdafx|pch)\.h[">]$'
Priority: -1
- Regex: '^<Windows\.h>$'
Priority: 3
- Regex: '^<(WinIoCtl|winhttp|Shellapi)\.h>$'
Priority: 4
- Regex: '.*'
Priority: 2
IndentCaseLabels: true
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
PenaltyReturnTypeOnItsOwnLine: 1000
PointerAlignment: Left
SpaceAfterTemplateKeyword: false
Standard: Cpp11
UseTab: Never

View File

@ -6,14 +6,13 @@
#pragma once
#include <functional>
#include <atomic>
#include <functional>
namespace ix
{
using CancellationRequest = std::function<bool()>;
CancellationRequest makeCancellationRequestWithTimeout(int seconds,
std::atomic<bool>& requestInitCancellation);
}
CancellationRequest makeCancellationRequestWithTimeout(
int seconds, std::atomic<bool>& requestInitCancellation);
} // namespace ix

View File

@ -6,14 +6,15 @@
#pragma once
#include <stdint.h>
#include <string>
#include <atomic>
#include <memory>
#include <stdint.h>
#include <string>
namespace ix
{
class ConnectionState {
class ConnectionState
{
public:
ConnectionState();
virtual ~ConnectionState() = default;
@ -32,6 +33,4 @@ namespace ix
static std::atomic<uint64_t> _globalId;
};
}
} // namespace ix

View File

@ -11,22 +11,20 @@
#pragma once
#include "IXCancellationRequest.h"
#include <string>
#include <thread>
#include <atomic>
#include <condition_variable>
#include <set>
#include <string>
#include <thread>
struct addrinfo;
namespace ix
{
class DNSLookup {
class DNSLookup
{
public:
DNSLookup(const std::string& hostname,
int port,
int64_t wait = DNSLookup::kDefaultWait);
DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait);
~DNSLookup();
struct addrinfo* resolve(std::string& errMsg,
@ -78,4 +76,4 @@ namespace ix
const static int64_t kDefaultWait;
};
}
} // namespace ix

View File

@ -6,16 +6,15 @@
#pragma once
#include <algorithm>
#include <functional>
#include <mutex>
#include <atomic>
#include <tuple>
#include <memory>
#include <map>
#include "IXSocket.h"
#include "IXWebSocketHttpHeaders.h"
#include <algorithm>
#include <atomic>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <tuple>
namespace ix
{
@ -64,15 +63,14 @@ namespace ix
OnProgressCallback onProgressCallback;
};
class HttpClient {
class HttpClient
{
public:
HttpClient();
~HttpClient();
HttpResponse get(const std::string& url,
const HttpRequestArgs& args);
HttpResponse head(const std::string& url,
const HttpRequestArgs& args);
HttpResponse get(const std::string& url, const HttpRequestArgs& args);
HttpResponse head(const std::string& url, const HttpRequestArgs& args);
HttpResponse post(const std::string& url,
const HttpParameters& httpParameters,
@ -94,9 +92,7 @@ namespace ix
void log(const std::string& msg, const HttpRequestArgs& args);
bool gzipInflate(
const std::string& in,
std::string& out);
bool gzipInflate(const std::string& in, std::string& out);
std::shared_ptr<Socket> _socket;
@ -104,4 +100,4 @@ namespace ix
const static std::string kGet;
const static std::string kHead;
};
}
} // namespace ix

View File

@ -7,25 +7,25 @@
#pragma once
#ifdef _WIN32
# include <WS2tcpip.h>
# include <WinSock2.h>
# include <basetsd.h>
# include <io.h>
# include <ws2def.h>
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <basetsd.h>
#include <io.h>
#include <ws2def.h>
#else
# include <arpa/inet.h>
# include <errno.h>
# include <netdb.h>
# include <netinet/tcp.h>
# include <sys/select.h>
# include <sys/socket.h>
# include <sys/stat.h>
# include <sys/time.h>
# include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#endif
namespace ix
{
bool initNetSystem();
bool uninitNetSystem();
}
} // namespace ix

View File

@ -11,7 +11,8 @@
namespace ix
{
class SelectInterrupt {
class SelectInterrupt
{
public:
SelectInterrupt();
virtual ~SelectInterrupt();
@ -23,6 +24,4 @@ namespace ix
virtual uint64_t read();
virtual int getFd() const;
};
}
} // namespace ix

View File

@ -7,13 +7,13 @@
#pragma once
#include "IXSelectInterrupt.h"
#include <stdint.h>
#include <string>
namespace ix
{
class SelectInterruptEventFd final : public SelectInterrupt {
class SelectInterruptEventFd final : public SelectInterrupt
{
public:
SelectInterruptEventFd();
virtual ~SelectInterruptEventFd();
@ -28,5 +28,4 @@ namespace ix
private:
int _eventfd;
};
}
} // namespace ix

View File

@ -12,4 +12,4 @@ namespace ix
{
class SelectInterrupt;
std::shared_ptr<SelectInterrupt> createSelectInterrupt();
}
} // namespace ix

View File

@ -7,14 +7,14 @@
#pragma once
#include "IXSelectInterrupt.h"
#include <mutex>
#include <stdint.h>
#include <string>
#include <mutex>
namespace ix
{
class SelectInterruptPipe final : public SelectInterrupt {
class SelectInterruptPipe final : public SelectInterrupt
{
public:
SelectInterruptPipe();
virtual ~SelectInterruptPipe();
@ -37,5 +37,4 @@ namespace ix
static const int kPipeReadIndex;
static const int kPipeWriteIndex;
};
}
} // namespace ix

View File

@ -10,4 +10,3 @@ namespace ix
{
void setThreadName(const std::string& name);
}

View File

@ -6,12 +6,12 @@
#pragma once
#include <string>
#include <functional>
#include <mutex>
#include <atomic>
#include <vector>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#ifdef _WIN32
#include <BaseTsd.h>
@ -49,7 +49,8 @@ namespace ix
CloseRequest = 5
};
class Socket {
class Socket
{
public:
Socket(int fd = -1);
virtual ~Socket();
@ -75,15 +76,11 @@ namespace ix
// Blocking and cancellable versions, working with socket that can be set
// to non blocking mode. Used during HTTP upgrade.
bool readByte(void* buffer,
const CancellationRequest& isCancellationRequested);
bool writeBytes(const std::string& str,
const CancellationRequest& isCancellationRequested);
bool readByte(void* buffer, const CancellationRequest& isCancellationRequested);
bool writeBytes(const std::string& str, const CancellationRequest& isCancellationRequested);
std::pair<bool, std::string> readLine(
const CancellationRequest& isCancellationRequested);
std::pair<bool, std::string> readBytes(
size_t length,
std::pair<bool, std::string> readLine(const CancellationRequest& isCancellationRequested);
std::pair<bool, std::string> readBytes(size_t length,
const OnProgressCallback& onProgressCallback,
const CancellationRequest& isCancellationRequested);
@ -111,4 +108,4 @@ namespace ix
std::shared_ptr<SelectInterrupt> _selectInterrupt;
};
}
} // namespace ix

View File

@ -6,12 +6,10 @@
#pragma once
#include "IXSocket.h"
#include "IXCancellationRequest.h"
#include <Security/Security.h>
#include "IXSocket.h"
#include <Security/SecureTransport.h>
#include <Security/Security.h>
#include <mutex>
namespace ix
@ -37,4 +35,4 @@ namespace ix
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe
};
}
} // namespace ix

View File

@ -7,14 +7,14 @@
#pragma once
#include "IXCancellationRequest.h"
#include <string>
struct addrinfo;
namespace ix
{
class SocketConnect {
class SocketConnect
{
public:
static int connect(const std::string& hostname,
int port,
@ -24,9 +24,8 @@ namespace ix
static void configure(int sockfd);
private:
static int connectToAddress(const struct addrinfo *address,
static int connectToAddress(const struct addrinfo* address,
std::string& errMsg,
const CancellationRequest& isCancellationRequested);
};
}
} // namespace ix

View File

@ -13,9 +13,7 @@
namespace ix
{
class Socket;
std::shared_ptr<Socket> createSocket(bool tls,
std::string& errorMsg);
std::shared_ptr<Socket> createSocket(bool tls, std::string& errorMsg);
std::shared_ptr<Socket> createSocket(int fd,
std::string& errorMsg);
}
std::shared_ptr<Socket> createSocket(int fd, std::string& errorMsg);
} // namespace ix

View File

@ -6,17 +6,15 @@
#pragma once
#include "IXSocket.h"
#include "IXCancellationRequest.h"
#include "IXSocket.h"
#include <mutex>
#include <openssl/bio.h>
#include <openssl/hmac.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/hmac.h>
#include <openssl/ssl.h>
#include <mutex>
namespace ix
{
class SocketOpenSSL final : public Socket
@ -40,10 +38,8 @@ namespace ix
std::string getSSLError(int ret);
SSL_CTX* openSSLCreateContext(std::string& errMsg);
bool openSSLHandshake(const std::string& hostname, std::string& errMsg);
bool openSSLCheckServerCert(SSL *ssl,
const std::string& hostname,
std::string& errMsg);
bool checkHost(const std::string& host, const char *pattern);
bool openSSLCheckServerCert(SSL* ssl, const std::string& hostname, std::string& errMsg);
bool checkHost(const std::string& host, const char* pattern);
SSL* _ssl_connection;
SSL_CTX* _ssl_context;
@ -54,4 +50,4 @@ namespace ix
static std::atomic<bool> _openSSLInitializationSuccessful;
};
}
} // namespace ix

View File

@ -16,9 +16,7 @@ namespace ix
SocketSChannel();
~SocketSChannel();
virtual bool connect(const std::string& host,
int port,
std::string& errMsg) final;
virtual bool connect(const std::string& host, int port, std::string& errMsg) final;
virtual void close() final;
// The important override
@ -31,4 +29,4 @@ namespace ix
private:
};
}
} // namespace ix

View File

@ -7,28 +7,28 @@
#pragma once
#include "IXConnectionState.h"
#include <utility> // pair
#include <string>
#include <set>
#include <thread>
#include <list>
#include <mutex>
#include <functional>
#include <memory>
#include <atomic>
#include <condition_variable>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <utility> // pair
namespace ix
{
class SocketServer {
class SocketServer
{
public:
using ConnectionStateFactory = std::function<std::shared_ptr<ConnectionState>()>;
// Each connection is handled by its own worker thread.
// We use a list as we only care about remove and append operations.
using ConnectionThreads = std::list<std::pair<std::shared_ptr<ConnectionState>,
std::thread>>;
using ConnectionThreads =
std::list<std::pair<std::shared_ptr<ConnectionState>, std::thread>>;
SocketServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost,
@ -52,7 +52,6 @@ namespace ix
void wait();
protected:
// Logging
void logError(const std::string& str);
void logInfo(const std::string& str);
@ -93,12 +92,11 @@ namespace ix
// the factory to create ConnectionState objects
ConnectionStateFactory _connectionStateFactory;
virtual void handleConnection(int fd,
std::shared_ptr<ConnectionState> connectionState) = 0;
virtual void handleConnection(int fd, std::shared_ptr<ConnectionState> connectionState) = 0;
virtual size_t getConnectedClientsCount() = 0;
// Returns true if all connection threads are joined
void closeTerminatedThreads();
size_t getConnectionsThreadsCount();
};
}
} // namespace ix

View File

@ -20,4 +20,4 @@ namespace ix
std::string& query,
int& port);
};
}
} // namespace ix

View File

@ -9,18 +9,17 @@
#pragma once
#include "IXProgressCallback.h"
#include "IXWebSocketCloseConstants.h"
#include "IXWebSocketErrorInfo.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketTransport.h"
#include <atomic>
#include <mutex>
#include <string>
#include <thread>
#include <mutex>
#include <atomic>
#include "IXWebSocketTransport.h"
#include "IXWebSocketErrorInfo.h"
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketCloseConstants.h"
#include "IXProgressCallback.h"
namespace ix
{
@ -64,9 +63,7 @@ namespace ix
std::string reason;
bool remote;
WebSocketCloseInfo(uint16_t c = 0,
const std::string& r = std::string(),
bool rem = false)
WebSocketCloseInfo(uint16_t c = 0, const std::string& r = std::string(), bool rem = false)
: code(c)
, reason(r)
, remote(rem)
@ -91,7 +88,8 @@ namespace ix
~WebSocket();
void setUrl(const std::string& url);
void setPerMessageDeflateOptions(const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions);
void setPerMessageDeflateOptions(
const WebSocketPerMessageDeflateOptions& perMessageDeflateOptions);
void setHeartBeatPeriod(int heartBeatPeriodSecs);
void setPingInterval(int pingIntervalSecs); // alias of setHeartBeatPeriod
void setPingTimeout(int pingTimeoutSecs);
@ -116,8 +114,7 @@ namespace ix
const OnProgressCallback& onProgressCallback = nullptr);
WebSocketSendInfo ping(const std::string& text);
void close(uint16_t code = 1000,
const std::string& reason = "Normal closure");
void close(uint16_t code = 1000, const std::string& reason = "Normal closure");
void setOnMessageCallback(const OnMessageCallback& callback);
static void setTrafficTrackerCallback(const OnTrafficTrackerCallback& callback);
@ -138,7 +135,6 @@ namespace ix
bool isAutomaticReconnectionEnabled() const;
private:
WebSocketSendInfo sendMessage(const std::string& text,
SendMessageKind sendMessageKind,
const OnProgressCallback& callback = nullptr);
@ -180,4 +176,4 @@ namespace ix
friend class WebSocketServer;
};
}
} // namespace ix

View File

@ -26,4 +26,4 @@ namespace ix
static const std::string kProtocolErrorMessage;
static const std::string kNoStatusCodeErrorMessage;
};
}
} // namespace ix

View File

@ -18,4 +18,4 @@ namespace ix
std::string reason;
bool decompressionError = false;
};
}
} // namespace ix

View File

@ -7,15 +7,14 @@
#pragma once
#include "IXCancellationRequest.h"
#include "IXSocket.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXSocket.h"
#include <string>
#include <atomic>
#include <chrono>
#include <memory>
#include <string>
#include <tuple>
namespace ix
@ -42,7 +41,8 @@ namespace ix
}
};
class WebSocketHandshake {
class WebSocketHandshake
{
public:
WebSocketHandshake(std::atomic<bool>& requestInitCancellation,
std::shared_ptr<Socket> _socket,
@ -56,8 +56,7 @@ namespace ix
int port,
int timeoutSecs);
WebSocketInitResult serverHandshake(int fd,
int timeoutSecs);
WebSocketInitResult serverHandshake(int fd, int timeoutSecs);
private:
std::string genRandomString(const int len);
@ -75,4 +74,4 @@ namespace ix
WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions;
std::atomic<bool>& _enablePerMessageDeflate;
};
}
} // namespace ix

View File

@ -7,10 +7,9 @@
#pragma once
#include "IXCancellationRequest.h"
#include <string>
#include <map>
#include <memory>
#include <string>
namespace ix
{
@ -21,15 +20,14 @@ namespace ix
// Case Insensitive compare_less binary function
struct NocaseCompare
{
bool operator() (const unsigned char& c1, const unsigned char& c2) const;
bool operator()(const unsigned char& c1, const unsigned char& c2) const;
};
bool operator() (const std::string & s1, const std::string & s2) const;
bool operator()(const std::string& s1, const std::string& s2) const;
};
using WebSocketHttpHeaders = std::map<std::string, std::string, CaseInsensitiveLess>;
std::pair<bool, WebSocketHttpHeaders> parseHttpHeaders(
std::shared_ptr<Socket> socket,
const CancellationRequest& isCancellationRequested);
}
std::shared_ptr<Socket> socket, const CancellationRequest& isCancellationRequested);
} // namespace ix

View File

@ -7,9 +7,9 @@
#pragma once
#include "IXWebSocket.h"
#include <thread>
#include <list>
#include <memory>
#include <thread>
namespace ix
{
@ -50,4 +50,4 @@ namespace ix
std::mutex _messagesMutex;
std::list<MessagePtr> _messages;
};
}
} // namespace ix

View File

@ -34,8 +34,8 @@
#pragma once
#include <string>
#include <memory>
#include <string>
namespace ix
{
@ -57,4 +57,4 @@ namespace ix
std::unique_ptr<WebSocketPerMessageDeflateCompressor> _compressor;
std::unique_ptr<WebSocketPerMessageDeflateDecompressor> _decompressor;
};
}
} // namespace ix

View File

@ -7,8 +7,8 @@
#pragma once
#include "zlib.h"
#include <string>
#include <memory>
#include <string>
namespace ix
{
@ -46,5 +46,4 @@ namespace ix
z_stream _inflateState;
};
}
} // namespace ix

View File

@ -42,4 +42,4 @@ namespace ix
int _clientMaxWindowBits;
int _serverMaxWindowBits;
};
}
} // namespace ix

View File

@ -15,8 +15,7 @@ namespace ix
size_t payloadSize;
size_t wireSize;
WebSocketSendInfo(bool s = false, bool c = false,
size_t p = 0, size_t w = 0)
WebSocketSendInfo(bool s = false, bool c = false, size_t p = 0, size_t w = 0)
: success(s)
, compressionError(c)
, payloadSize(p)
@ -25,4 +24,4 @@ namespace ix
;
}
};
}
} // namespace ix

View File

@ -6,24 +6,24 @@
#pragma once
#include <utility> // pair
#include <string>
#include <set>
#include <thread>
#include <mutex>
#include "IXSocketServer.h"
#include "IXWebSocket.h"
#include <condition_variable>
#include <functional>
#include <memory>
#include <condition_variable>
#include "IXWebSocket.h"
#include "IXSocketServer.h"
#include <mutex>
#include <set>
#include <string>
#include <thread>
#include <utility> // pair
namespace ix
{
using OnConnectionCallback = std::function<void(std::shared_ptr<WebSocket>,
std::shared_ptr<ConnectionState>)>;
using OnConnectionCallback =
std::function<void(std::shared_ptr<WebSocket>, std::shared_ptr<ConnectionState>)>;
class WebSocketServer final : public SocketServer {
class WebSocketServer final : public SocketServer
{
public:
WebSocketServer(int port = SocketServer::kDefaultPort,
const std::string& host = SocketServer::kDefaultHost,
@ -59,4 +59,4 @@ namespace ix
std::shared_ptr<ConnectionState> connectionState) final;
virtual size_t getConnectedClientsCount() final;
};
}
} // namespace ix

View File

@ -10,22 +10,21 @@
// Adapted from https://github.com/dhbaird/easywsclient
//
#include <string>
#include <vector>
#include <functional>
#include <memory>
#include <mutex>
#include <atomic>
#include <list>
#include "IXWebSocketSendInfo.h"
#include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXCancellationRequest.h"
#include "IXWebSocketHandshake.h"
#include "IXProgressCallback.h"
#include "IXWebSocketCloseConstants.h"
#include "IXWebSocketHandshake.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include "IXWebSocketSendInfo.h"
#include <atomic>
#include <functional>
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
namespace ix
{
@ -63,14 +62,9 @@ namespace ix
AbnormalClose
};
using OnMessageCallback = std::function<void(const std::string&,
size_t,
bool,
MessageKind)>;
using OnCloseCallback = std::function<void(uint16_t,
const std::string&,
size_t,
bool)>;
using OnMessageCallback =
std::function<void(const std::string&, size_t, bool, MessageKind)>;
using OnCloseCallback = std::function<void(uint16_t, const std::string&, size_t, bool)>;
WebSocketTransport();
~WebSocketTransport();
@ -103,19 +97,20 @@ namespace ix
ReadyState getReadyState() const;
void setReadyState(ReadyState readyState);
void setOnCloseCallback(const OnCloseCallback& onCloseCallback);
void dispatch(PollResult pollResult,
const OnMessageCallback& onMessageCallback);
void dispatch(PollResult pollResult, const OnMessageCallback& onMessageCallback);
size_t bufferedAmount() const;
private:
std::string _url;
struct wsheader_type {
struct wsheader_type
{
unsigned header_size;
bool fin;
bool rsv1;
bool mask;
enum opcode_type {
enum opcode_type
{
CONTINUATION = 0x0,
TEXT_FRAME = 0x1,
BINARY_FRAME = 0x2,
@ -176,7 +171,7 @@ namespace ix
std::atomic<bool> _requestInitCancellation;
mutable std::mutex _closingTimePointMutex;
std::chrono::time_point<std::chrono::steady_clock>_closingTimePoint;
std::chrono::time_point<std::chrono::steady_clock> _closingTimePoint;
static const int kClosingMaximumWaitingDelayInMs;
// enable auto response to ping
@ -211,7 +206,8 @@ namespace ix
// No PONG data was received through the socket for longer than ping timeout delay
bool pingTimeoutExceeded();
// after calling close(), if no CLOSE frame answer is received back from the remote, we should close the connexion
// after calling close(), if no CLOSE frame answer is received back from the remote, we
// should close the connexion
bool closingDelayExceeded();
void initTimePointsAndGCDAfterConnect();
@ -252,4 +248,4 @@ namespace ix
std::string getMergedChunks() const;
};
}
} // namespace ix

View File

@ -57,22 +57,28 @@ namespace LUrlParser
std::string m_Password;
clParseURL()
: m_ErrorCode( LUrlParserError_Uninitialized )
{}
: m_ErrorCode(LUrlParserError_Uninitialized)
{
}
/// return 'true' if the parsing was successful
bool IsValid() const { return m_ErrorCode == LUrlParserError_Ok; }
bool IsValid() const
{
return m_ErrorCode == LUrlParserError_Ok;
}
/// helper to convert the port number to int, return 'true' if the port is valid (within the 0..65535 range)
bool GetPort( int* OutPort ) const;
/// helper to convert the port number to int, return 'true' if the port is valid (within the
/// 0..65535 range)
bool GetPort(int* OutPort) const;
/// parse the URL
static clParseURL ParseURL( const std::string& URL );
static clParseURL ParseURL(const std::string& URL);
private:
explicit clParseURL( LUrlParserError ErrorCode )
: m_ErrorCode( ErrorCode )
{}
explicit clParseURL(LUrlParserError ErrorCode)
: m_ErrorCode(ErrorCode)
{
}
};
} // namespace LUrlParser

View File

@ -40,6 +40,9 @@ run:
trail:
sh third_party/remote_trailing_whitespaces.sh
format:
sh third_party/indent.sh
# That target is used to start a node server, but isn't required as we have
# a builtin C++ server started in the unittest now
test_server:

View File

@ -6,14 +6,15 @@
#pragma once
#include <memory>
#include <functional>
#include <memory>
namespace ix
{
class Socket;
class RedisClient {
class RedisClient
{
public:
using OnRedisSubscribeResponseCallback = std::function<void(const std::string&)>;
using OnRedisSubscribeCallback = std::function<void(const std::string&)>;
@ -21,15 +22,11 @@ namespace ix
RedisClient() = default;
~RedisClient() = default;
bool connect(const std::string& hostname,
int port);
bool connect(const std::string& hostname, int port);
bool auth(const std::string& password,
std::string& response);
bool auth(const std::string& password, std::string& response);
bool publish(const std::string& channel,
const std::string& message,
std::string& errMsg);
bool publish(const std::string& channel, const std::string& message, std::string& errMsg);
bool subscribe(const std::string& channel,
const OnRedisSubscribeResponseCallback& responseCallback,
@ -40,5 +37,4 @@ namespace ix
std::shared_ptr<Socket> _socket;
};
}
} // namespace ix

View File

@ -6,11 +6,10 @@
#pragma once
#include <ixwebsocket/IXHttpClient.h>
#include <jsoncpp/json/json.h>
#include <regex>
#include <ixwebsocket/IXHttpClient.h>
namespace ix
{
class SentryClient

View File

@ -6,16 +6,15 @@
#pragma once
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
#include <jsoncpp/json/json.h>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <unordered_map>
#include <memory>
#include <jsoncpp/json/json.h>
#include <ixwebsocket/IXWebSocketHttpHeaders.h>
#include <ixwebsocket/IXWebSocketPerMessageDeflateOptions.h>
namespace ix
{
@ -72,8 +71,7 @@ namespace ix
/// Publish a message to a channel
///
/// No-op if the connection is not established
bool publish(const Json::Value& channels,
const Json::Value& msg);
bool publish(const Json::Value& channels, const Json::Value& msg);
// Subscribe to a channel, and execute a callback when an incoming
// message arrives.
@ -126,8 +124,7 @@ namespace ix
const std::string& errorMsg = std::string(),
const WebSocketHttpHeaders& headers = WebSocketHttpHeaders(),
const std::string& subscriptionId = std::string());
void invokeErrorCallback(const std::string& errorMsg,
const std::string& serializedPdu);
void invokeErrorCallback(const std::string& errorMsg, const std::string& serializedPdu);
///
/// Member variables

View File

@ -7,12 +7,10 @@
#pragma once
#include "IXCobraMetricsThreadedPublisher.h"
#include <chrono>
#include <jsoncpp/json/json.h>
#include <string>
#include <unordered_map>
#include <chrono>
namespace ix
{
@ -28,10 +26,11 @@ namespace ix
/// to make shouldPush as fast as possible. _enabled default to false.
///
/// The code that set those is ran only once at init, and
/// the last value to be set is _enabled, which is also the first value checked in shouldPush,
/// so there shouldn't be any race condition.
/// the last value to be set is _enabled, which is also the first value checked in
/// shouldPush, so there shouldn't be any race condition.
///
/// 2. The queue of messages is thread safe, so multiple metrics can be safely pushed on multiple threads
/// 2. The queue of messages is thread safe, so multiple metrics can be safely pushed on
/// multiple threads
///
/// 3. Access to _last_update is protected as it needs to be read/write.
///
@ -62,40 +61,44 @@ namespace ix
void push(const std::string& id,
const CobraMetricsPublisher::Message& data = CobraMetricsPublisher::Message());
/// Richer interface using json, which supports types (bool, int, float) and hierarchies of elements
/// Richer interface using json, which supports types (bool, int, float) and hierarchies of
/// elements
///
/// The shouldPushTest argument should be set to false, and used in combination with the shouldPush method
/// for places where we want to be as lightweight as possible when collecting metrics. When set to false,
/// it is used so that we don't do double work when computing whether a metrics should be sent or not.
void push(const std::string& id,
const Json::Value& data,
bool shouldPushTest = true);
/// The shouldPushTest argument should be set to false, and used in combination with the
/// shouldPush method for places where we want to be as lightweight as possible when
/// collecting metrics. When set to false, it is used so that we don't do double work when
/// computing whether a metrics should be sent or not.
void push(const std::string& id, const Json::Value& data, bool shouldPushTest = true);
/// Interface used by lua. msg is a json encoded string.
void push(const std::string& id,
const std::string& data,
bool shouldPushTest = true);
void push(const std::string& id, const std::string& data, bool shouldPushTest = true);
/// Tells whether a metric can be pushed.
/// A metric can be pushed if it satisfies those conditions:
///
/// 1. the metrics system should be enabled
/// 2. the metrics shouldn't be black-listed
/// 3. the metrics shouldn't have reached its rate control limit at this "sampling"/"calling" time
/// 3. the metrics shouldn't have reached its rate control limit at this
/// "sampling"/"calling" time
bool shouldPush(const std::string& id) const;
/// Get generic information json object
Json::Value& getGenericAttributes();
/// Set generic information values
void setGenericAttributes(const std::string& attrName,
const Json::Value& value);
void setGenericAttributes(const std::string& attrName, const Json::Value& value);
/// Set a unique id for the session. A uuid can be used.
void setSession(const std::string& session) { _session = session; }
void setSession(const std::string& session)
{
_session = session;
}
/// Get the unique id used to identify the current session
const std::string& getSession() const { return _session; }
const std::string& getSession() const
{
return _session;
}
/// Return the number of milliseconds since the epoch (~1970)
uint64_t getMillisecondsSinceEpoch() const;
@ -117,7 +120,6 @@ namespace ix
bool isAuthenticated() const;
private:
/// Lookup an id in our metrics to see whether it is blacklisted
/// Complexity is logarithmic
bool isMetricBlacklisted(const std::string& id) const;
@ -150,15 +152,16 @@ namespace ix
/// Metrics control (black list + rate control)
std::vector<std::string> _blacklist;
std::unordered_map<std::string, int> _rate_control;
std::unordered_map<std::string, std::chrono::time_point<std::chrono::steady_clock>> _last_update;
std::unordered_map<std::string, std::chrono::time_point<std::chrono::steady_clock>>
_last_update;
mutable std::mutex _last_update_mutex; // protect access to _last_update
// const strings for internal ids
static const std::string kSetRateControlId;
static const std::string kSetBlacklistId;
/// Our protocol version. Can be used by subscribers who would want to be backward compatible
/// if we change the way we arrange data
/// Our protocol version. Can be used by subscribers who would want to be backward
/// compatible if we change the way we arrange data
static const int kVersion;
};

View File

@ -7,16 +7,14 @@
#pragma once
#include "IXCobraConnection.h"
#include <jsoncpp/json/json.h>
#include <string>
#include <queue>
#include <mutex>
#include <thread>
#include <map>
#include <atomic>
#include <condition_variable>
#include <jsoncpp/json/json.h>
#include <map>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
namespace ix
{
@ -67,8 +65,7 @@ namespace ix
};
/// Push a message to be processed by the background thread
void pushMessage(MessageKind messageKind,
const Json::Value& msg);
void pushMessage(MessageKind messageKind, const Json::Value& msg);
/// Get a wait time which is increasing exponentially based on the number of retries
uint64_t getWaitTimeExp(int retry_count);

View File

@ -3,20 +3,19 @@
namespace ix
{
class IXCoreLogger
{
public:
class IXCoreLogger
{
public:
using LogFunc = std::function<void(const char*)>;
static void Log(const char* msg);
static void setLogFunction(LogFunc& func) {
static void setLogFunction(LogFunc& func)
{
_currentLogger = func;
}
private:
private:
static LogFunc _currentLogger;
};
};
} // ix
} // namespace ix

View File

@ -12,4 +12,4 @@ namespace ix
{
std::string base64_encode(const std::string& data, size_t len);
std::string base64_decode(const std::string& encoded_string);
}
} // namespace ix

View File

@ -13,4 +13,3 @@ namespace ix
{
uint64_t djb2Hash(const std::vector<uint8_t>& data);
}

View File

@ -14,4 +14,4 @@ namespace ix
*/
std::string uuid4();
}
} // namespace ix

View File

@ -6,11 +6,10 @@
#pragma once
#include "nlohmann/json.hpp"
#include <string>
#include <vector>
#include "nlohmann/json.hpp"
namespace snake
{
struct AppConfig
@ -31,16 +30,11 @@ namespace snake
bool verbose;
};
bool isAppKeyValid(
const AppConfig& appConfig,
std::string appkey);
bool isAppKeyValid(const AppConfig& appConfig, std::string appkey);
std::string getRoleSecret(
const AppConfig& appConfig,
std::string appkey,
std::string role);
std::string getRoleSecret(const AppConfig& appConfig, std::string appkey, std::string role);
std::string generateNonce();
void dumpConfig(const AppConfig& appConfig);
}
} // namespace snake

View File

@ -6,27 +6,47 @@
#pragma once
#include <string>
#include <future>
#include <ixwebsocket/IXConnectionState.h>
#include "IXRedisClient.h"
#include <future>
#include <ixwebsocket/IXConnectionState.h>
#include <string>
namespace snake
{
class SnakeConnectionState : public ix::ConnectionState
{
public:
std::string getNonce() { return _nonce; }
void setNonce(const std::string& nonce) { _nonce = nonce; }
std::string getNonce()
{
return _nonce;
}
void setNonce(const std::string& nonce)
{
_nonce = nonce;
}
std::string appkey() { return _appkey; }
void setAppkey(const std::string& appkey) { _appkey = appkey; }
std::string appkey()
{
return _appkey;
}
void setAppkey(const std::string& appkey)
{
_appkey = appkey;
}
std::string role() { return _role; }
void setRole(const std::string& role) { _role = role; }
std::string role()
{
return _role;
}
void setRole(const std::string& role)
{
_role = role;
}
ix::RedisClient& redisClient() { return _redisClient; }
ix::RedisClient& redisClient()
{
return _redisClient;
}
std::future<void> fut;
@ -37,4 +57,4 @@ namespace snake
ix::RedisClient _redisClient;
};
}
} // namespace snake

View File

@ -18,9 +18,8 @@ namespace snake
class SnakeConnectionState;
struct AppConfig;
void processCobraMessage(
std::shared_ptr<SnakeConnectionState> state,
void processCobraMessage(std::shared_ptr<SnakeConnectionState> state,
std::shared_ptr<ix::WebSocket> ws,
const AppConfig& appConfig,
const std::string& str);
}
} // namespace snake

View File

@ -6,10 +6,9 @@
#pragma once
#include <string>
#include <ixwebsocket/IXWebSocketServer.h>
#include "IXAppConfig.h"
#include <ixwebsocket/IXWebSocketServer.h>
#include <string>
namespace snake
{
@ -27,4 +26,4 @@ namespace snake
AppConfig _appConfig;
ix::WebSocketServer _server;
};
}
} // namespace snake

12
ws/ws.h
View File

@ -28,17 +28,13 @@ namespace ix
int ws_broadcast_server_main(int port, const std::string& hostname);
int ws_transfer_main(int port, const std::string& hostname);
int ws_chat_main(const std::string& url,
const std::string& user);
int ws_chat_main(const std::string& url, const std::string& user);
int ws_connect_main(const std::string& url, bool disableAutomaticReconnection);
int ws_receive_main(const std::string& url,
bool enablePerMessageDeflate,
int delayMs);
int ws_receive_main(const std::string& url, bool enablePerMessageDeflate, int delayMs);
int ws_send_main(const std::string& url,
const std::string& path);
int ws_send_main(const std::string& url, const std::string& path);
int ws_redis_publish_main(const std::string& hostname,
int port,
@ -95,4 +91,4 @@ namespace ix
const std::string& redisPassword,
bool verbose,
const std::string& appsConfigPath);
}
} // namespace ix