Skip to content

Commit

Permalink
refactor(core/json,serviceworker,ipc,window): lock down conduit, remo…
Browse files Browse the repository at this point in the history
…ve realloc, speed up JSON impl
  • Loading branch information
jwerle committed Nov 25, 2024
1 parent 32f2a8f commit c11eda9
Show file tree
Hide file tree
Showing 31 changed files with 1,518 additions and 798 deletions.
2 changes: 1 addition & 1 deletion api/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ export const debug = !!globalThis.__args?.debug

/**
* Application configuration.
* @type {object}
* @type {Record<string, string|number|boolean|(string|number|boolean)[]>}
*/
export const config = globalThis.__args?.config ?? {}

Expand Down
28 changes: 16 additions & 12 deletions api/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8082,9 +8082,9 @@ declare module "socket:application" {
export const debug: boolean;
/**
* Application configuration.
* @type {object}
* @type {Record<string, string|number|boolean|(string|number|boolean)[]>}
*/
export const config: object;
export const config: Record<string, string | number | boolean | (string | number | boolean)[]>;
export namespace backend {
/**
* @param {object} opts - an options object
Expand Down Expand Up @@ -9433,9 +9433,12 @@ declare module "socket:internal/conduit" {
/**
* @typedef {{ options: object, payload: Uint8Array }} ReceiveMessage
* @typedef {function(Error?, ReceiveCallback | undefined)} ReceiveCallback
* @typedef {{ id?: string|BigInt|number, reconnect?: {} }} ConduitOptions
* @typedef {{ isActive: boolean, handles: { ids: string[], count: number }}} ConduitDiagnostics
* @typedef {{ isActive: boolean, port: number }} ConduitStatus
* @typedef {{
* id?: string|BigInt|number,
* sharedKey?: string
*}} ConduitOptions
*/
export const DEFALUT_MAX_RECONNECT_RETRIES: 32;
export const DEFAULT_MAX_RECONNECT_TIMEOUT: 256;
Expand Down Expand Up @@ -9476,12 +9479,9 @@ declare module "socket:internal/conduit" {
/**
* Creates an instance of Conduit.
*
* @param {object} params - The parameters for the Conduit.
* @param {string} params.id - The ID for the connection.
* @param {ConduitOptions} options
*/
constructor({ id }: {
id: string;
});
constructor(options: ConduitOptions);
/**
* @type {boolean}
*/
Expand All @@ -9506,6 +9506,10 @@ declare module "socket:internal/conduit" {
* @type {number?}
*/
id: number | null;
/**
* @type {string}
*/
sharedKey: string;
/**
* The URL string for the WebSocket server.
* @type {string}
Expand Down Expand Up @@ -9597,10 +9601,6 @@ declare module "socket:internal/conduit" {
payload: Uint8Array;
};
export type ReceiveCallback = (arg0: Error | null, arg1: ReceiveCallback | undefined) => any;
export type ConduitOptions = {
id?: string | BigInt | number;
reconnect?: {};
};
export type ConduitDiagnostics = {
isActive: boolean;
handles: {
Expand All @@ -9612,6 +9612,10 @@ declare module "socket:internal/conduit" {
isActive: boolean;
port: number;
};
export type ConduitOptions = {
id?: string | BigInt | number;
sharedKey?: string;
};
}

declare module "socket:ip" {
Expand Down
22 changes: 15 additions & 7 deletions api/internal/conduit.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,17 @@ let isApplicationPaused = false
* The default Conduit port
* @type {number}
*/
let defaultConduitPort = globalThis.__args.conduit || 0
let defaultConduitPort = globalThis.__args.conduit?.port || 0

/**
* @typedef {{ options: object, payload: Uint8Array }} ReceiveMessage
* @typedef {function(Error?, ReceiveCallback | undefined)} ReceiveCallback
* @typedef {{ id?: string|BigInt|number, reconnect?: {} }} ConduitOptions
* @typedef {{ isActive: boolean, handles: { ids: string[], count: number }}} ConduitDiagnostics
* @typedef {{ isActive: boolean, port: number }} ConduitStatus
* @typedef {{
* id?: string|BigInt|number,
* sharedKey?: string
*}} ConduitOptions
*/
export const DEFALUT_MAX_RECONNECT_RETRIES = 32
export const DEFAULT_MAX_RECONNECT_TIMEOUT = 256
Expand Down Expand Up @@ -160,6 +163,11 @@ export class Conduit extends EventTarget {
*/
id = null

/**
* @type {string}
*/
sharedKey = globalThis.__args?.conduit?.sharedKey ?? ''

/**
* @private
* @type {function(MessageEvent)}
Expand All @@ -186,13 +194,13 @@ export class Conduit extends EventTarget {
/**
* Creates an instance of Conduit.
*
* @param {object} params - The parameters for the Conduit.
* @param {string} params.id - The ID for the connection.
* @param {ConduitOptions} options
*/
constructor ({ id }) {
constructor (options) {
super()

this.id = id
this.id = options.id
this.sharedKey = options.sharedKey || this.sharedKey
// @ts-ignore
this.port = this.constructor.port
this.connect()
Expand All @@ -206,7 +214,7 @@ export class Conduit extends EventTarget {
* @type {string}
*/
get url () {
return `ws://localhost:${this.port}/${this.id}/${client.top.id}`
return `ws://localhost:${this.port}/${this.id}/${client.top.id}?key=${this.sharedKey || ''}`
}

/**
Expand Down
1 change: 1 addition & 0 deletions bin/build-runtime-library.sh
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ declare sources=(
$(find "$root"/src/app/*.cc)
$(find "$root"/src/core/*.cc)
$(find "$root"/src/core/modules/*.cc)
$(find "$root"/src/core/json/*.cc)
$(find "$root"/src/extension/*.cc)
$(find "$root"/src/ipc/*.cc)
$(find "$root"/src/platform/*.cc)
Expand Down
75 changes: 58 additions & 17 deletions src/core/codec.cc
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ static const char SAFE[256] = {
/* F */ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
};

// encoding table for base64 encoding
static const char BASE64_ENCODING_TABLE[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// modulus table for base64 encoding
static const int BASE64_MOD_TABLE[] = {0, 2, 1};

namespace SSC {
const Array<uint8_t, 8> toBytes (const uint64_t input) {
Array<uint8_t, 8> bytes;
Expand Down Expand Up @@ -174,31 +180,66 @@ namespace SSC {
memcpy(dest, hash, 20);
}

unsigned char* base64Encode(const unsigned char *data, size_t input_length, size_t *output_length) {
*output_length = (size_t) (4.0 * ceil((double) input_length / 3.0));
unsigned char *encoded_data = (unsigned char *) malloc(*output_length + 1);
if (!encoded_data) return 0;
const String shacalc (const String& input, size_t size) {
char output[size];
shacalc(input.data(), output);
return String(output, size);
}

size_t encodeBase64Length (size_t inputLength) {
return (size_t) (4.0 * ceil((double) inputLength / 3.0));
}

unsigned char* encodeBase64 (
const unsigned char* input,
unsigned char* output,
size_t inputLength,
size_t* outputLength
) {
int i = 0;
int j = 0;

for (i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? data[i++] : 0;
uint32_t octet_b = i < input_length ? data[i++] : 0;
uint32_t octet_c = i < input_length ? data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
if (!output) {
return nullptr;
}

const auto length = encodeBase64Length(inputLength);

for (i = 0, j = 0; i < inputLength;) {
uint32_t octetA = i < inputLength ? input[i++] : 0;
uint32_t octetB = i < inputLength ? input[i++] : 0;
uint32_t octetC = i < inputLength ? input[i++] : 0;
uint32_t triple = (octetA << 0x10) + (octetB << 0x08) + octetC;
output[j++] = BASE64_ENCODING_TABLE[(triple >> 3 * 6) & 0x3F];
output[j++] = BASE64_ENCODING_TABLE[(triple >> 2 * 6) & 0x3F];
output[j++] = BASE64_ENCODING_TABLE[(triple >> 1 * 6) & 0x3F];
output[j++] = BASE64_ENCODING_TABLE[(triple >> 0 * 6) & 0x3F];
}

for (i = 0; i < mod_table[input_length % 3]; i++) {
encoded_data[*output_length - 1 - i] = '=';
for (i = 0; i < BASE64_MOD_TABLE[inputLength % 3]; i++) {
output[length - 1 - i] = '=';
}

encoded_data[*output_length] = '\0'; // Null-terminate the string
return encoded_data;
output[length] = 0;

if (outputLength != nullptr) {
*outputLength = length;
}

return output;
}

const Vector<unsigned char> encodeBase64 (const String& input) {
size_t size;
unsigned char output[encodeBase64Length(input.size())];
encodeBase64(
reinterpret_cast<const unsigned char*>(input.data()),
output,
input.size(),
&size
);

return Vector<unsigned char>(output, output + size + 1);
}

String encodeURIComponent (const String& input) {
Expand Down
23 changes: 15 additions & 8 deletions src/core/codec.hh
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

#include "../platform/types.hh"

#define SHA_DIGEST_LENGTH 20

namespace SSC {
/**
* Encodes input by replacing certain characters by
Expand Down Expand Up @@ -85,21 +87,26 @@ namespace SSC {
* @param dest Pointer to the destination buffer to store the hash
*/
void shacalc (const char* src, char* dest);
const String shacalc (const String&, size_t size = SHA_DIGEST_LENGTH);

/**
* Encodes a given input data to a Base64 encoded string.
* @param data Pointer to the input data
* @param input_length Length of the input data
* @param output_length Pointer to store the length of the encoded output
* @param input Pointer to the input data
* @param output Pointer to the output data
* @param inputLength Length of the input data
* @param outputLength Pointer to store the length of the encoded output
* @return Pointer to the Base64 encoded string
*/
unsigned char* base64Encode(const unsigned char *data, size_t input_length, size_t *output_length);
unsigned char* encodeBase64 (
const unsigned char* input,
unsigned char* output,
size_t inputLength,
size_t* outputLength
);

// Encoding table for base64 encoding
const char encoding_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t encodeBase64Length (size_t inputLength);

// Modulus table for base64 encoding
const int mod_table[] = {0, 2, 1};
const Vector<unsigned char> encodeBase64 (const String&);
}

#endif
28 changes: 28 additions & 0 deletions src/core/headers.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ namespace SSC {
return this->value.string != string;
}

const String Headers::Header::operator + (const String& string) const {
return this->value + string;
}

bool Headers::Header::empty () const {
return this->value.empty();
}

size_t Headers::Header::size() const {
return this->value.size();
}

Headers::Headers (const String& source) {
for (const auto& entry : split(source, '\n')) {
const auto tuple = split(entry, ':');
Expand Down Expand Up @@ -106,6 +118,10 @@ namespace SSC {
return this->entries.size();
}

bool Headers::empty () const {
return this->entries.empty();
}

String Headers::str () const {
StringStream headers;
auto remaining = this->size();
Expand Down Expand Up @@ -235,6 +251,10 @@ namespace SSC {
return this->string != string;
}

const String Headers::Value::operator + (const String& string) const {
return this->string + string;
}

const String& Headers::Value::str () const {
return this->string;
}
Expand All @@ -243,6 +263,14 @@ namespace SSC {
return this->str().c_str();
}

size_t Headers::Value::size() const {
return this->string.size();
}

bool Headers::Value::empty () const {
return this->string.empty();
}

const String toHeaderCase (const String& source) {
Vector<String> parts;
for (const auto& entry : split(trim(source), '-')) {
Expand Down
7 changes: 7 additions & 0 deletions src/core/headers.hh
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@ namespace SSC {
bool operator != (const Value&) const;
bool operator == (const String&) const;
bool operator != (const String&) const;
const String operator + (const String&) const;

const String& str () const;
const char * c_str() const;
bool empty () const;
size_t size () const;

template <typename T> void set (T value) {
auto v = Value(value);
Expand All @@ -47,6 +50,9 @@ namespace SSC {
bool operator != (const Header&) const;
bool operator == (const String&) const;
bool operator != (const String&) const;
const String operator + (const String&) const;
size_t size () const;
bool empty () const;
};

using Entries = Vector<Header>;
Expand All @@ -60,6 +66,7 @@ namespace SSC {
Headers (const Entries& entries);
size_t size () const;
String str () const;
bool empty () const;

void set (const String& name, const String& value) noexcept;
void set (const Header& header) noexcept;
Expand Down
Loading

0 comments on commit c11eda9

Please sign in to comment.