Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions yerpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ tokio-tungstenite = { version = "0.26.1" }
tokio = { version = "1.43.0", features = ["rt", "macros"] }
url = "2.5.4"
insta = "1.47.2"
tempfile = "3.27.0"
97 changes: 0 additions & 97 deletions yerpc/qt/generated/client.hpp

This file was deleted.

36 changes: 36 additions & 0 deletions yerpc/tests/axum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod tests {
use axum::{extract::ws::WebSocketUpgrade, response::Response, routing::get, Router};
use futures_util::{SinkExt, StreamExt};
use std::net::SocketAddr;
use std::path::Path;
use tokio::net::TcpStream;
use tokio_tungstenite::client_async;
use tokio_tungstenite::tungstenite::http::StatusCode;
Expand Down Expand Up @@ -76,4 +77,39 @@ mod tests {
assert_eq!(res.as_str(), "FOO");
Ok(())
}

pub fn assert_dir_snapshot(prefix: &str, f: impl FnOnce(&Path)) {
let dir = tempfile::tempdir().unwrap();
f(dir.path());
assert_dir_snapshot_inner(prefix, dir.path());
}

fn assert_dir_snapshot_inner(prefix: &str, dir: &Path) {
let mut entries: Vec<_> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().path())
.collect();
entries.sort();

for file_path in entries {
let relative = file_path
.strip_prefix(dir)
.unwrap()
.to_string_lossy()
.replace('.', "_");
let contents = std::fs::read_to_string(&file_path).unwrap();
let snapshot_name = format!("{prefix}__{relative}");
insta::assert_snapshot!(snapshot_name, contents);
}
}

#[test]
fn ts_bindings() {
assert_dir_snapshot("typescript", |p| write_ts_bindings(p))
}

#[test]
fn qt_bindings() {
assert_dir_snapshot("qt", |p| write_qt_bindings(p, "my_namespace"))
}
}
182 changes: 182 additions & 0 deletions yerpc/tests/snapshots/axum__tests__qt__client_hpp.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
---
source: yerpc/tests/axum.rs
expression: contents
---
#pragma once

#include "types.hpp"

#include <QFuture>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QString>

#include <cstdint>
#include <utility>

namespace my_namespace {

struct ResultError {
/** Error code of the result. Equals `0` if there is no error. */
int32_t error_code = 0;

/** Error message of the result. Equals an empty string if there is no error.
*/
QString error_message{};

/** Returns `true` if the result represents an error. */
bool isError() const { return error_code != 0; }

/**
* Explicitly discards the result. Used to silence `[[nodiscard]]` warnings
*/
void ignore() const {}
};

template <typename T> struct [[nodiscard]] Result : ResultError {
/* Constructs a successful result containing the given value */
static Result<T> ok(T value) { return {{0, {}}, std::move(value)}; }

/* Constructs an error result with the given error code and message */
static Result<T> error(int32_t error_code, QString error_message) {
return {{error_code, std::move(error_message)}, {}};
}

/** Value of the result. Is a default constructed value if the result
* represents an error. */
T value{};

/**
* If the result represents an error, logs a warning with the error details
* and the caller's source location. Returns a copy of this result for
* chaining.
*/
Result<T> logError(const char *file = __builtin_FILE(),
int line = __builtin_LINE()) const {
if (error_code) {
qWarning().noquote()
<< QStringLiteral("Result::logError() from %1:%2 | Error %3: %4")
.arg(QLatin1String(file))
.arg(line)
.arg(error_code)
.arg(error_message);
}
return *this;
}

/** Return the `value` converted to json */
QJsonValue valueToJson() const { return toJson(value); }
};

template <> struct [[nodiscard]] Result<void> : ResultError {
/* Constructs a successful result */
static Result<void> ok() { return {{0, {}}}; }

/* Constructs an error result with the given error code and message */
static Result<void> error(int32_t error_code, QString error_message) {
return {{error_code, std::move(error_message)}};
}

/**
* If the result represents an error, logs a warning with the error details
* and the caller's source location. Returns a copy of this result for
* chaining.
*/
Result<void> logError(const char *file = __builtin_FILE(),
int line = __builtin_LINE()) const {
if (error_code) {
qWarning().noquote()
<< QStringLiteral("Result::logError() from %1:%2 | Error %3: %4")
.arg(QLatin1String(file))
.arg(line)
.arg(error_code)
.arg(error_message);
}
return *this;
}
};

static Result<QJsonValue> parseResult(const QJsonObject &val) {
if (val.contains("error")) {
QJsonObject err = val["error"].toObject();
QJsonValue error_message = err["message"];
int error_code = err["code"].toInt();
if (!error_message.isString() || error_code == 0)
return Result<QJsonValue>::error(
-32700, "Invalid error in response: " +
QJsonDocument(val).toJson(QJsonDocument::Compact));
return Result<QJsonValue>::error(error_code, error_message.toString());
}
if (!val.contains("result"))
return Result<QJsonValue>::error(
-32700, "Neither error nor result in response: " +
QJsonDocument(val).toJson(QJsonDocument::Compact));
return Result<QJsonValue>::ok(val["result"]);
}

class Transport {
public:
using CompletionHandler = std::function<void(const Result<QJsonValue>)>;
virtual void send(const QString method, const QJsonValue request,
CompletionHandler onCompleted) = 0;
virtual ~Transport() = default;
};

class RawClient {
template <typename T>
QFuture<Result<T>> request(const QString method, const QJsonArray params) {
QFutureInterface<Result<T>> interface;
interface.reportStarted();
transport_->send(method, params,
[method, interface](const Result<QJsonValue> val) mutable {
interface.reportResult(
mapToConcreteType<T>(val, method));
interface.reportFinished();
});
return interface.future();
}

template <typename T>
static Result<T> mapToConcreteType(const Result<QJsonValue> val,
const QString method) {
if constexpr (std::is_void_v<T>) {
if (val.error_code)
return Result<void>::error(val.error_code,
method + ": " + val.error_message);
return Result<void>::ok();
} else {
if (val.error_code)
return Result<T>::error(val.error_code,
method + ": " + val.error_message);
T out;
if (!tryFromJson(val.value, out)) {
return Result<T>::error(-32700,
method + ": Could not parse result " +
QJsonDocument(QJsonArray{val.value})
.toJson(QJsonDocument::Compact));
}
return Result<T>::ok(out);
}
}

public:
RawClient(std::unique_ptr<Transport> t) : transport_{std::move(t)} {}

std::unique_ptr<Transport> transport_;


[[nodiscard]] QFuture<Result<QString>> shout(QString msg) {
return request<QString>("shout", QJsonArray{toJson(msg)});
}


[[nodiscard]] QFuture<Result<float>> add(float a, float b) {
return request<float>("add", QJsonArray{toJson(a), toJson(b)});
}


};

}
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
---
source: yerpc/tests/axum.rs
expression: contents
---
// AUTO-GENERATED by yerpc-derive

#pragma once

#include <optional>
#include <cstdint>
#include <type_traits>

#include <QString>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>

namespace my_namespace {

namespace Hidden {
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
Expand All @@ -29,3 +34,5 @@ inline bool tryFromJson(const QJsonValue &v, float &out) {
out = static_cast<float>(v.toDouble());
return true;
}

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
source: yerpc/tests/axum.rs
expression: contents
---
// AUTO-GENERATED by yerpc-derive

import * as T from "./types.js"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
source: yerpc/tests/axum.rs
expression: contents
---
// AUTO-GENERATED by typescript-type-def

export type JSONValue = (null | boolean | number | string | (JSONValue)[] | {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
---
source: yerpc/tests/axum.rs
expression: contents
---
// AUTO-GENERATED by typescript-type-def

export type F32 = number;
Loading