feat(clients): live: Gemini Live API over WebSocket, RFC 6455 client, session, relay, discovery check
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
// Route: GET /agent/live (mobile-first Live API page, no credential needed)
|
||||
#include "support/GoogleRig.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
|
||||
int main() {
|
||||
GoogleRig rig(false);
|
||||
Fixture f(rig.client);
|
||||
auto res = f.client->get("/agent/live");
|
||||
check(res.status == 200, "status 200 without a credential");
|
||||
check(contains(res.headers.get("Content-Type"), "text/html"), "html");
|
||||
check(contains(res.body, "Live API") && contains(res.body, "l-create"), "page body");
|
||||
check(contains(res.body, "/embedded/agent_live.js"), "script referenced");
|
||||
check(contains(res.body, "viewport"), "responsive meta from the base template");
|
||||
check(contains(f.client->get("/").body, "/agent/live"), "listed in the feature matrix");
|
||||
check(f.client->post("/agent/live").status == 405, "post is 405");
|
||||
check(rig.mock->send_count() == 0, "side effect: no upstream traffic");
|
||||
return finish("agent/live");
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// Routes: POST /agent/live/sessions, POST .../{id}/send, GET .../{id}/events,
|
||||
// POST .../{id}/close (HTTP relay over a loopback WebSocket server)
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <thread>
|
||||
|
||||
#include "../../../src/google/live/loopback.h"
|
||||
#include "support/GoogleRig.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
using live_test::LoopbackServer;
|
||||
using live_test::ServerConn;
|
||||
|
||||
namespace {
|
||||
std::string json_of(const std::string& body, const std::string& key) {
|
||||
std::size_t k = body.find("\"" + key + "\":\"");
|
||||
if (k == std::string::npos) return "";
|
||||
k += key.size() + 4;
|
||||
return body.substr(k, body.find('"', k) - k);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
unsetenv("GOOGLE_ACCESS_TOKEN");
|
||||
unsetenv("GOOGLE_CLOUD_PROJECT");
|
||||
setenv("GOOGLE_API_KEY", "test-key", 1);
|
||||
|
||||
// No credential: every Google-bound route answers 503, nothing connects.
|
||||
{
|
||||
GoogleRig rig(false);
|
||||
Fixture f(rig.client);
|
||||
auto res = f.client->post("/agent/live/sessions", "{}", "application/json");
|
||||
check(res.status == 503, "create without a credential is 503");
|
||||
check(contains(res.body, "google_not_configured"), "error code google_not_configured");
|
||||
check(f.client->post("/agent/live/sessions/s0123456789ab/send",
|
||||
"{\"kind\":\"text\",\"text\":\"x\"}", "application/json").status == 503,
|
||||
"send without a credential is 503");
|
||||
check(f.client->post("/agent/live/sessions/s0123456789ab/close", "{}", "application/json").status == 503,
|
||||
"close without a credential is 503");
|
||||
}
|
||||
|
||||
std::string text_seen, audio_seen;
|
||||
LoopbackServer server([&](ServerConn& c) {
|
||||
c.read_message(); // setup
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
text_seen = c.read_message().value_or("");
|
||||
c.send_text("{\"serverContent\":{\"modelTurn\":{\"parts\":[{\"text\":\"hello from loopback\"}]}}}");
|
||||
c.send_text("{\"serverContent\":{\"turnComplete\":true}}");
|
||||
audio_seen = c.read_message().value_or("");
|
||||
while (c.read_frame()) {
|
||||
}
|
||||
});
|
||||
setenv("GOOGLE_LIVE_URL", server.url().c_str(), 1);
|
||||
|
||||
GoogleRig rig;
|
||||
Fixture f(rig.client);
|
||||
|
||||
// Validation: rejected before any socket is opened.
|
||||
check(f.client->post("/agent/live/sessions", "{\"modality\":\"VIDEO\"}", "application/json").status == 422,
|
||||
"bad modality is 422");
|
||||
check(f.client->post("/agent/live/sessions", "{\"model\":\"../x\"}", "application/json").status == 422,
|
||||
"bad model is 422");
|
||||
check(f.client->post("/agent/live/sessions", "{\"voice\":\"a b;c\"}", "application/json").status == 422,
|
||||
"bad voice is 422");
|
||||
check(f.client->get("/agent/live/sessions").status == 405, "get on create is 405");
|
||||
|
||||
auto created = f.client->post("/agent/live/sessions", "{\"system\":\"be brief\",\"transcribe\":\"1\"}",
|
||||
"application/json");
|
||||
check(created.status == 201, "create answers 201");
|
||||
std::string id = json_of(created.body, "id");
|
||||
check(id.size() == 13 && id[0] == 's', "session id shape");
|
||||
check(!contains(created.body, "test-key"), "credential never returned");
|
||||
|
||||
std::string base = "/agent/live/sessions/" + id;
|
||||
check(f.client->post(base + "/send", "{\"kind\":\"smoke\"}", "application/json").status == 422,
|
||||
"unknown kind is 422");
|
||||
check(f.client->post(base + "/send", "{\"kind\":\"text\",\"text\":\"\"}", "application/json").status == 422,
|
||||
"empty text is 422");
|
||||
check(f.client->post(base + "/send", "{\"kind\":\"text\",\"text\":\"" + std::string(32001, 'a') + "\"}",
|
||||
"application/json").status == 422,
|
||||
"text over the cap is 422");
|
||||
check(f.client->post(base + "/send", "{\"kind\":\"audio\",\"data_b64\":\"!!\"}", "application/json").status == 422,
|
||||
"bad base64 is 422");
|
||||
check(f.client->post("/agent/live/sessions/s000000000000/send", "{\"kind\":\"text\",\"text\":\"x\"}",
|
||||
"application/json").status == 404,
|
||||
"unknown session is 404");
|
||||
check(f.client->get(base + "/send").status == 405, "get on send is 405");
|
||||
|
||||
auto sent = f.client->post(base + "/send", "{\"kind\":\"text\",\"text\":\"hi there\"}", "application/json");
|
||||
check(sent.status == 200 && contains(sent.body, "\"sent\":true"), "text sent");
|
||||
|
||||
// Poll by cursor until the model text arrives.
|
||||
std::string cursor = "0", all;
|
||||
for (int i = 0; i < 40 && !contains(all, "turn_complete"); ++i) {
|
||||
auto page = f.client->get(base + "/events?cursor=" + cursor);
|
||||
check(page.status == 200, "events answers 200");
|
||||
all += page.body;
|
||||
std::string next = json_of(page.body, "next_cursor");
|
||||
std::size_t k = page.body.find("\"next_cursor\":");
|
||||
if (k != std::string::npos) cursor = page.body.substr(k + 14, page.body.find_first_of(",}", k) - k - 14);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
check(contains(all, "hello from loopback"), "model text relayed");
|
||||
check(contains(all, "\"type\":\"turn_complete\""), "turn_complete relayed");
|
||||
check(contains(f.client->get(base + "/events?cursor=" + cursor).body, "\"events\":[]"),
|
||||
"cursor: nothing new after the last event");
|
||||
check(f.client->get(base + "/events?cursor=abc").status == 422, "bad cursor is 422");
|
||||
check(f.client->get("/agent/live/sessions/s000000000000/events").status == 404, "unknown session events is 404");
|
||||
|
||||
auto audio = f.client->post(base + "/send",
|
||||
"{\"kind\":\"audio\",\"data_b64\":\"AQID\",\"mime\":\"audio/pcm;rate=16000\"}",
|
||||
"application/json");
|
||||
check(audio.status == 200, "audio chunk sent");
|
||||
check(f.client->post(base + "/send", "{\"kind\":\"audio\",\"data_b64\":\"AQID\",\"mime\":\"image/png\"}",
|
||||
"application/json").status == 422,
|
||||
"audio with an image mime is 422");
|
||||
|
||||
auto closed = f.client->post(base + "/close", "{}", "application/json");
|
||||
check(closed.status == 200 && contains(closed.body, "\"closed\":true"), "close answers 200");
|
||||
check(f.client->post(base + "/close", "{}", "application/json").status == 404, "closing twice is 404");
|
||||
check(f.client->get(base + "/events").status == 404, "closed session events is 404");
|
||||
|
||||
check(contains(text_seen, "\"realtimeInput\"") && contains(text_seen, "hi there"),
|
||||
"side effect: the loopback server got the text turn");
|
||||
check(contains(audio_seen, "audio/pcm;rate=16000") && contains(audio_seen, "AQID"),
|
||||
"side effect: the loopback server got the audio chunk");
|
||||
check(contains(server.request(), "Sec-WebSocket-Key"), "side effect: a real WebSocket upgrade happened");
|
||||
check(rig.mock->send_count() == 0, "no HTTP traffic to Google");
|
||||
return finish("agent/live/sessions");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Route: GET /agent/live/status (credential form and static caps)
|
||||
#include <cstdlib>
|
||||
|
||||
#include "support/GoogleRig.hpp"
|
||||
|
||||
using namespace molo::example::test;
|
||||
|
||||
int main() {
|
||||
unsetenv("GOOGLE_ACCESS_TOKEN");
|
||||
setenv("GOOGLE_API_KEY", "AIzaTEST-LIVE-KEY", 1);
|
||||
unsetenv("GOOGLE_LIVE_URL");
|
||||
{
|
||||
GoogleRig rig;
|
||||
Fixture f(rig.client);
|
||||
auto res = f.client->get("/agent/live/status");
|
||||
check(res.status == 200, "status 200");
|
||||
check(contains(res.headers.get("Content-Type"), "application/json"), "json");
|
||||
check(contains(res.body, "\"configured\":true"), "configured with a key");
|
||||
check(contains(res.body, "\"auth_mode\":\"gemini_api_key\""), "plain key selects the Gemini API form");
|
||||
check(contains(res.body, "\"max_sessions\":8"), "caps shown");
|
||||
check(!contains(res.body, "AIzaTEST-LIVE-KEY"), "credential never shown");
|
||||
check(rig.mock->send_count() == 0, "side effect: no upstream traffic");
|
||||
}
|
||||
setenv("GOOGLE_API_KEY", "AQ.test-express", 1);
|
||||
setenv("GOOGLE_CLOUD_PROJECT", "test-project", 1);
|
||||
{
|
||||
GoogleRig rig;
|
||||
Fixture f(rig.client);
|
||||
check(contains(f.client->get("/agent/live/status").body, "\"auth_mode\":\"vertex_express\""),
|
||||
"AQ. key with a project selects Vertex express");
|
||||
}
|
||||
unsetenv("GOOGLE_API_KEY");
|
||||
{
|
||||
GoogleRig rig(false);
|
||||
Fixture f(rig.client);
|
||||
check(contains(f.client->get("/agent/live/status").body, "\"configured\":false"),
|
||||
"not configured without a credential");
|
||||
}
|
||||
Fixture f;
|
||||
check(f.client->post("/agent/live/status").status == 405, "post is 405");
|
||||
return finish("agent/live/status");
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
#pragma once
|
||||
|
||||
// Loopback WebSocket server for tests: raw sockets, plain ws://, one
|
||||
// accepted connection, a user script running on the server thread. It
|
||||
// speaks RFC 6455 from first principles (own accept computation through the
|
||||
// module's SHA-1 would be circular, so the accept key is also checked
|
||||
// against the RFC example in test_ws_frame).
|
||||
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
#include "google/live/ws_frame.h"
|
||||
#include "google/live/ws_handshake.h"
|
||||
|
||||
namespace live_test {
|
||||
|
||||
using namespace molo::google::live;
|
||||
|
||||
struct ServerConn {
|
||||
int fd = -1;
|
||||
FrameDecoder decoder{8u * 1024u * 1024u, true};
|
||||
std::string request; // handshake request text
|
||||
|
||||
void send_raw(const std::string& bytes) const {
|
||||
std::size_t sent = 0;
|
||||
while (sent < bytes.size()) {
|
||||
ssize_t n = ::send(fd, bytes.data() + sent, bytes.size() - sent, MSG_NOSIGNAL);
|
||||
if (n <= 0) return;
|
||||
sent += (std::size_t)n;
|
||||
}
|
||||
}
|
||||
void send_text(const std::string& s) const { send_raw(encode_frame(true, WsOpcode::Text, s, nullptr)); }
|
||||
void send_binary(const std::string& s) const { send_raw(encode_frame(true, WsOpcode::Binary, s, nullptr)); }
|
||||
void send_close(std::uint16_t code, const std::string& reason = "") const {
|
||||
std::string p;
|
||||
p.push_back((char)(code >> 8));
|
||||
p.push_back((char)(code & 0xFF));
|
||||
send_raw(encode_frame(true, WsOpcode::Close, p + reason, nullptr));
|
||||
}
|
||||
// Next client frame; nullopt on EOF or timeout (2 s).
|
||||
std::optional<WsFrame> read_frame() {
|
||||
for (;;) {
|
||||
auto f = decoder.next();
|
||||
if (f) return f;
|
||||
char buf[4096];
|
||||
ssize_t n = ::recv(fd, buf, sizeof buf, 0);
|
||||
if (n <= 0) return std::nullopt;
|
||||
decoder.feed(buf, (std::size_t)n);
|
||||
}
|
||||
}
|
||||
// Next text/binary client message payload (skips pings, answers none).
|
||||
std::optional<std::string> read_message() {
|
||||
std::string acc;
|
||||
for (;;) {
|
||||
auto f = read_frame();
|
||||
if (!f) return std::nullopt;
|
||||
if (f->opcode >= 8) {
|
||||
if (f->opcode == 8) return std::nullopt;
|
||||
continue;
|
||||
}
|
||||
acc += f->payload;
|
||||
if (f->fin) return acc;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
class LoopbackServer {
|
||||
public:
|
||||
using Script = std::function<void(ServerConn&)>;
|
||||
|
||||
enum class Handshake { Ok, BadAccept, Status403, CloseImmediately };
|
||||
|
||||
explicit LoopbackServer(Script script, Handshake mode = Handshake::Ok)
|
||||
: script_(std::move(script)), mode_(mode) {
|
||||
listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
int one = 1;
|
||||
::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
|
||||
sockaddr_in a{};
|
||||
a.sin_family = AF_INET;
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
a.sin_port = 0;
|
||||
::bind(listen_fd_, (sockaddr*)&a, sizeof a);
|
||||
::listen(listen_fd_, 1);
|
||||
socklen_t len = sizeof a;
|
||||
::getsockname(listen_fd_, (sockaddr*)&a, &len);
|
||||
port_ = ntohs(a.sin_port);
|
||||
thread_ = std::thread([this] { run(); });
|
||||
}
|
||||
~LoopbackServer() {
|
||||
if (listen_fd_ >= 0) ::shutdown(listen_fd_, SHUT_RDWR);
|
||||
if (thread_.joinable()) thread_.join();
|
||||
if (listen_fd_ >= 0) ::close(listen_fd_);
|
||||
}
|
||||
int port() const { return port_; }
|
||||
std::string url(const std::string& path = "/ws") const {
|
||||
return "ws://127.0.0.1:" + std::to_string(port_) + path;
|
||||
}
|
||||
std::string request() const { return request_; }
|
||||
|
||||
private:
|
||||
void run() {
|
||||
timeval tv{2, 0};
|
||||
int fd = ::accept(listen_fd_, nullptr, nullptr);
|
||||
if (fd < 0) return;
|
||||
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
|
||||
ServerConn conn;
|
||||
conn.fd = fd;
|
||||
std::string head;
|
||||
char buf[2048];
|
||||
while (head.find("\r\n\r\n") == std::string::npos) {
|
||||
ssize_t n = ::recv(fd, buf, sizeof buf, 0);
|
||||
if (n <= 0) {
|
||||
::close(fd);
|
||||
return;
|
||||
}
|
||||
head.append(buf, (std::size_t)n);
|
||||
}
|
||||
std::size_t end = head.find("\r\n\r\n") + 4;
|
||||
if (end < head.size()) conn.decoder.feed(head.data() + end, head.size() - end);
|
||||
head.resize(end);
|
||||
conn.request = head;
|
||||
request_ = head;
|
||||
std::size_t k = head.find("Sec-WebSocket-Key: ");
|
||||
std::string key = head.substr(k + 19, head.find("\r\n", k) - k - 19);
|
||||
if (mode_ == Handshake::CloseImmediately) {
|
||||
::close(fd);
|
||||
return;
|
||||
}
|
||||
if (mode_ == Handshake::Status403) {
|
||||
conn.send_raw("HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n");
|
||||
::close(fd);
|
||||
return;
|
||||
}
|
||||
std::string accept = WsHandshake::accept_for(key);
|
||||
if (mode_ == Handshake::BadAccept) accept = "AAAAAAAAAAAAAAAAAAAAAAAAAAA=";
|
||||
conn.send_raw("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\nSec-WebSocket-Accept: " + accept + "\r\n\r\n");
|
||||
if (mode_ == Handshake::Ok) {
|
||||
try {
|
||||
script_(conn);
|
||||
} catch (...) {
|
||||
}
|
||||
}
|
||||
::close(fd);
|
||||
}
|
||||
|
||||
Script script_;
|
||||
Handshake mode_;
|
||||
int listen_fd_ = -1;
|
||||
int port_ = 0;
|
||||
std::thread thread_;
|
||||
std::string request_;
|
||||
};
|
||||
|
||||
// Polls the session for an event of `kind`, up to timeout_ms, returning all
|
||||
// events seen (so tests can assert order).
|
||||
} // namespace live_test
|
||||
@@ -0,0 +1,571 @@
|
||||
// Live API: typed setup, client messages, server event decoding, session,
|
||||
// relay. The wire names are checked against live_spec.h (which the
|
||||
// tools/check_discovery.py script checks against Google's Discovery
|
||||
// documents). No Google traffic: the loopback server only carries bytes.
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <set>
|
||||
|
||||
#include "framework.h"
|
||||
#include "google/errors.h"
|
||||
#include "google/live/live_config.h"
|
||||
#include "google/live/live_relay.h"
|
||||
#include "google/live/live_session.h"
|
||||
#include "google/live/live_spec.h"
|
||||
#include "loopback.h"
|
||||
#include "security/crypto/Base64.h"
|
||||
|
||||
using namespace molo::google;
|
||||
using namespace molo::google::live;
|
||||
using molo::clients::body::Json;
|
||||
using molo::security::crypto::Base64;
|
||||
using live_test::LoopbackServer;
|
||||
using live_test::ServerConn;
|
||||
|
||||
namespace {
|
||||
|
||||
void collect_keys(const Json& j, std::set<std::string>& out) {
|
||||
if (j.is_object()) {
|
||||
for (const auto& [k, v] : j.as_object()) {
|
||||
out.insert(k);
|
||||
collect_keys(v, out);
|
||||
}
|
||||
} else if (j.is_array()) {
|
||||
for (const auto& v : j.as_array()) collect_keys(v, out);
|
||||
}
|
||||
}
|
||||
|
||||
std::set<std::string> spec_fields() {
|
||||
std::set<std::string> s;
|
||||
for (std::size_t i = 0; i < kLiveSpecRows; ++i) s.insert(kLiveSpec[i].field);
|
||||
return s;
|
||||
}
|
||||
|
||||
LiveEndpoint local_endpoint(const LoopbackServer& s, bool vertex = false) {
|
||||
LiveEndpoint e;
|
||||
if (vertex) {
|
||||
CloudContext ctx;
|
||||
ctx.project = "test-project";
|
||||
e = LiveEndpoint::vertex(ctx, "tok");
|
||||
} else {
|
||||
e = LiveEndpoint::api_key("test-key");
|
||||
}
|
||||
e.url_override = s.url();
|
||||
return e;
|
||||
}
|
||||
|
||||
// Reads events until `kind` (inclusive) or timeout; returns everything seen.
|
||||
std::vector<LiveEvent> until(LiveSession& s, LiveEventKind kind, int ms = 3000) {
|
||||
std::vector<LiveEvent> seen;
|
||||
auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
|
||||
while (std::chrono::steady_clock::now() < deadline) {
|
||||
auto e = s.next_event(100);
|
||||
if (!e) {
|
||||
if (!s.open() && s.pending() == 0) break;
|
||||
continue;
|
||||
}
|
||||
seen.push_back(*e);
|
||||
if (e->kind == kind) break;
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(live_endpoint, urls_headers_models) {
|
||||
CloudContext ctx;
|
||||
ctx.project = "p1";
|
||||
ctx.location = "europe-west4";
|
||||
auto v = LiveEndpoint::vertex(ctx, "tok");
|
||||
ASSERT_EQ(v.url(), "wss://europe-west4-aiplatform.googleapis.com/ws/"
|
||||
"google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent");
|
||||
ASSERT_EQ(v.headers().at(0).first, "Authorization");
|
||||
ASSERT_EQ(v.headers().at(0).second, "Bearer tok");
|
||||
ASSERT_EQ(v.model_name("m1"), "projects/p1/locations/europe-west4/publishers/google/models/m1");
|
||||
ctx.location = "global";
|
||||
ASSERT_TRUE(LiveEndpoint::vertex(ctx, "t").url().find("wss://aiplatform.googleapis.com/ws/") == 0);
|
||||
auto x = LiveEndpoint::vertex_express(ctx, "AQ.k");
|
||||
ASSERT_EQ(x.headers().at(0).first, "x-goog-api-key");
|
||||
ASSERT_TRUE(x.url().find("AQ.k") == std::string::npos); // express key never in the URL
|
||||
auto a = LiveEndpoint::api_key("K1");
|
||||
ASSERT_EQ(a.url(), std::string(kLiveApiKeyUrl) + "?key=K1");
|
||||
ASSERT_TRUE(a.headers().empty());
|
||||
ASSERT_EQ(a.model_name("m1"), "models/m1");
|
||||
ASSERT_THROW(a.model_name("../x"), GoogleError);
|
||||
ASSERT_THROW(a.model_name(""), GoogleError);
|
||||
}
|
||||
|
||||
TEST(live_endpoint, validation_before_traffic) {
|
||||
CloudContext ctx;
|
||||
ctx.project = "p1";
|
||||
ASSERT_THROW(LiveEndpoint::api_key("").validate(), NotConfiguredError);
|
||||
ASSERT_THROW(LiveEndpoint::vertex(ctx, "").validate(), NotConfiguredError);
|
||||
ASSERT_THROW(LiveEndpoint::api_key("a&b").validate(), GoogleError);
|
||||
ASSERT_THROW(LiveEndpoint::api_key("a b").validate(), GoogleError);
|
||||
ASSERT_THROW(LiveEndpoint::vertex(ctx, "t\r\nX: y").validate(), GoogleError);
|
||||
ctx.project = "Bad Project";
|
||||
ASSERT_THROW(LiveEndpoint::vertex(ctx, "t").validate(), GoogleError);
|
||||
ctx.project = "p1";
|
||||
ctx.location = "us central";
|
||||
ASSERT_THROW(LiveEndpoint::vertex(ctx, "t").validate(), GoogleError);
|
||||
// connect() without a credential throws before any socket is opened.
|
||||
LiveSession s(LiveEndpoint::api_key(""), LiveConfig{});
|
||||
ASSERT_THROW(s.connect(), NotConfiguredError);
|
||||
}
|
||||
|
||||
TEST(live_config, setup_matches_spec_names) {
|
||||
LiveConfig c;
|
||||
c.system_instruction = "be brief";
|
||||
c.voice_name = "Puck";
|
||||
c.language_code = "nl-NL";
|
||||
c.temperature = 0.5;
|
||||
c.max_output_tokens = 100;
|
||||
c.input_transcription = c.output_transcription = true;
|
||||
c.session_resumption = true;
|
||||
c.context_compression = true;
|
||||
LiveFunctionDeclaration f;
|
||||
f.name = "get_weather";
|
||||
f.description = "weather";
|
||||
f.parameters = Json::parse("{\"type\":\"OBJECT\",\"properties\":{\"city\":{\"type\":\"STRING\"}}}");
|
||||
c.functions.push_back(f);
|
||||
CloudContext ctx;
|
||||
ctx.project = "p";
|
||||
Json j = c.to_setup(LiveEndpoint::vertex(ctx, "t"));
|
||||
ASSERT_TRUE(j.has("setup"));
|
||||
const Json& s = *j.find("setup");
|
||||
ASSERT_EQ(s.find("model")->as_string(),
|
||||
"projects/p/locations/us-central1/publishers/google/models/" + c.model);
|
||||
ASSERT_EQ(s.find("generationConfig")->find("responseModalities")->as_array().at(0).as_string(), "AUDIO");
|
||||
ASSERT_EQ(s.find("generationConfig")->find("speechConfig")->find("voiceConfig")
|
||||
->find("prebuiltVoiceConfig")->find("voiceName")->as_string(), "Puck");
|
||||
ASSERT_EQ(s.find("systemInstruction")->find("parts")->as_array().at(0).find("text")->as_string(), "be brief");
|
||||
ASSERT_TRUE(s.has("inputAudioTranscription") && s.has("outputAudioTranscription"));
|
||||
ASSERT_TRUE(s.find("sessionResumption")->is_object());
|
||||
ASSERT_TRUE(s.find("contextWindowCompression")->find("slidingWindow")->is_object());
|
||||
// Every key anywhere in the message, except user-supplied schema content
|
||||
// under "parameters", is a declared wire name.
|
||||
auto fields = spec_fields();
|
||||
fields.insert("setup");
|
||||
std::set<std::string> keys;
|
||||
Json copy = c.to_setup(LiveEndpoint::api_key("k"));
|
||||
Json& decls = copy.as_object().at("setup").as_object().at("tools").as_array().at(0)
|
||||
.as_object().at("functionDeclarations").as_array().at(0);
|
||||
decls.as_object().erase("parameters");
|
||||
collect_keys(copy, keys);
|
||||
for (const auto& k : keys) ASSERT_TRUE(fields.count(k) == 1 || k == "setup");
|
||||
ASSERT_EQ(copy.find("setup")->find("model")->as_string(), "models/" + c.model);
|
||||
}
|
||||
|
||||
TEST(live_config, validation) {
|
||||
auto ep = LiveEndpoint::api_key("k");
|
||||
auto bad = [&](auto mutate) {
|
||||
LiveConfig c;
|
||||
mutate(c);
|
||||
ASSERT_THROW(c.to_setup(ep), GoogleError);
|
||||
};
|
||||
bad([](LiveConfig& c) { c.model = "a/b"; });
|
||||
bad([](LiveConfig& c) { c.response_modalities = {}; });
|
||||
bad([](LiveConfig& c) { c.response_modalities = {"VIDEO"}; });
|
||||
bad([](LiveConfig& c) { c.temperature = 3.0; });
|
||||
bad([](LiveConfig& c) { c.max_output_tokens = 0; });
|
||||
bad([](LiveConfig& c) { c.voice_name = "bad voice!"; });
|
||||
bad([](LiveConfig& c) { c.language_code = "nl_NL"; });
|
||||
bad([](LiveConfig& c) { c.system_instruction = std::string(LiveCaps::kMaxSystemChars + 1, 'x'); });
|
||||
bad([](LiveConfig& c) { c.resumption_handle = "has space"; });
|
||||
bad([](LiveConfig& c) {
|
||||
c.functions.resize(LiveCaps::kMaxFunctionDecls + 1);
|
||||
for (std::size_t i = 0; i < c.functions.size(); ++i) c.functions[i].name = "f" + std::to_string(i);
|
||||
});
|
||||
bad([](LiveConfig& c) { c.functions.push_back({"1bad", "", Json()}); });
|
||||
bad([](LiveConfig& c) { c.functions.push_back({"ok", "", Json("not an object")}); });
|
||||
}
|
||||
|
||||
TEST(live_requests, shapes_and_caps) {
|
||||
Json t = Json::parse(LiveRequests::text("hi"));
|
||||
ASSERT_EQ(t.find("realtimeInput")->find("text")->as_string(), "hi");
|
||||
Json turn = Json::parse(LiveRequests::turn("hello", false));
|
||||
ASSERT_EQ(turn.find("clientContent")->find("turns")->as_array().at(0).find("role")->as_string(), "user");
|
||||
ASSERT_FALSE(turn.find("clientContent")->find("turnComplete")->as_bool());
|
||||
Json a = Json::parse(LiveRequests::audio(std::string("\x01\x02\x03", 3), "audio/pcm;rate=16000"));
|
||||
const Json* blob = a.find("realtimeInput")->find("audio");
|
||||
ASSERT_EQ(blob->find("mimeType")->as_string(), "audio/pcm;rate=16000");
|
||||
std::string raw;
|
||||
ASSERT_TRUE(Base64::decode(blob->find("data")->as_string(), raw));
|
||||
ASSERT_EQ(raw.size(), (std::size_t)3);
|
||||
Json v = Json::parse(LiveRequests::video("jpegbytes", "image/jpeg"));
|
||||
ASSERT_TRUE(v.find("realtimeInput")->has("video"));
|
||||
ASSERT_TRUE(Json::parse(LiveRequests::audio_stream_end()).find("realtimeInput")->find("audioStreamEnd")->as_bool());
|
||||
Json resp = Json::object();
|
||||
resp.set("temp", 21);
|
||||
Json tr = Json::parse(LiveRequests::tool_responses({{"call-1", "get_weather", resp}}));
|
||||
const Json& fr = tr.find("toolResponse")->find("functionResponses")->as_array().at(0);
|
||||
ASSERT_EQ(fr.find("id")->as_string(), "call-1");
|
||||
ASSERT_EQ(fr.find("name")->as_string(), "get_weather");
|
||||
|
||||
ASSERT_THROW(LiveRequests::text(""), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::text(std::string(LiveCaps::kMaxTextChars + 1, 'x')), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::audio("", "audio/pcm"), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::audio("x", "image/png"), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::audio("x", "audio/pcm\r\n"), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::audio(std::string(LiveCaps::kMaxAudioChunkBytes + 1, 'x'), "audio/pcm"), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::video(std::string(LiveCaps::kMaxVideoChunkBytes + 1, 'x'), "image/jpeg"), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::video("x", "text/plain"), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::tool_responses({}), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::tool_responses({{"", "n", resp}}), GoogleError);
|
||||
ASSERT_THROW(LiveRequests::tool_responses({{"i", "n", Json("str")}}), GoogleError);
|
||||
std::vector<LiveToolResponse> many(LiveCaps::kMaxFunctionResponses + 1, LiveToolResponse{"i", "n", resp});
|
||||
ASSERT_THROW(LiveRequests::tool_responses(many), GoogleError);
|
||||
// Client message envelopes are declared names.
|
||||
auto fields = spec_fields();
|
||||
for (const std::string& m : {LiveRequests::text("x"), LiveRequests::turn("x", true),
|
||||
LiveRequests::audio("x", "audio/pcm"), LiveRequests::video("x", "image/jpeg"),
|
||||
LiveRequests::audio_stream_end(), LiveRequests::tool_responses({{"i", "n", resp}})}) {
|
||||
std::set<std::string> keys;
|
||||
Json j = Json::parse(m);
|
||||
// "response" content is user data.
|
||||
collect_keys(j, keys);
|
||||
for (const auto& k : keys) ASSERT_TRUE(fields.count(k) == 1 || k == "temp");
|
||||
}
|
||||
}
|
||||
|
||||
TEST(live_events, decode_server_messages) {
|
||||
auto one = [](const std::string& json) { return LiveParser::parse(json); };
|
||||
auto ev = one("{\"setupComplete\":{}}");
|
||||
ASSERT_EQ(ev.size(), (std::size_t)1);
|
||||
ASSERT_TRUE(ev[0].kind == LiveEventKind::SetupComplete);
|
||||
|
||||
std::string pcm("\x10\x00\x20\x00", 4);
|
||||
ev = one("{\"serverContent\":{\"modelTurn\":{\"parts\":[{\"text\":\"hi\"},{\"inlineData\":{\"mimeType\":"
|
||||
"\"audio/pcm;rate=24000\",\"data\":\"" + Base64::encode(pcm) + "\"}}]},\"outputTranscription\":"
|
||||
"{\"text\":\"hi\"},\"generationComplete\":true,\"turnComplete\":true}}");
|
||||
ASSERT_EQ(ev.size(), (std::size_t)5);
|
||||
ASSERT_TRUE(ev[0].kind == LiveEventKind::Text);
|
||||
ASSERT_TRUE(ev[1].kind == LiveEventKind::Audio);
|
||||
ASSERT_EQ(ev[1].data, pcm);
|
||||
ASSERT_EQ(ev[1].mime, "audio/pcm;rate=24000");
|
||||
ASSERT_TRUE(ev[2].kind == LiveEventKind::OutputTranscription);
|
||||
ASSERT_TRUE(ev[3].kind == LiveEventKind::GenerationComplete);
|
||||
ASSERT_TRUE(ev[4].kind == LiveEventKind::TurnComplete); // always last
|
||||
|
||||
ev = one("{\"serverContent\":{\"inputTranscription\":{\"text\":\"you\"},\"interrupted\":true}}");
|
||||
ASSERT_TRUE(ev[0].kind == LiveEventKind::InputTranscription);
|
||||
ASSERT_TRUE(ev[1].kind == LiveEventKind::Interrupted);
|
||||
|
||||
ev = one("{\"toolCall\":{\"functionCalls\":[{\"id\":\"c1\",\"name\":\"f\",\"args\":{\"x\":1}}]}}");
|
||||
ASSERT_TRUE(ev[0].kind == LiveEventKind::ToolCall);
|
||||
ASSERT_EQ(ev[0].calls.at(0).id, "c1");
|
||||
ASSERT_EQ(ev[0].calls.at(0).args.find("x")->as_int(), 1L);
|
||||
ev = one("{\"toolCallCancellation\":{\"ids\":[\"c1\",\"c2\"]}}");
|
||||
ASSERT_EQ(ev[0].ids.size(), (std::size_t)2);
|
||||
ev = one("{\"goAway\":{\"timeLeft\":\"12.5s\"}}");
|
||||
ASSERT_TRUE(ev[0].seconds == 12.5);
|
||||
ev = one("{\"sessionResumptionUpdate\":{\"newHandle\":\"h1\",\"resumable\":true}}");
|
||||
ASSERT_EQ(ev[0].handle, "h1");
|
||||
ASSERT_TRUE(ev[0].resumable);
|
||||
ev = one("{\"usageMetadata\":{\"totalTokenCount\":42}}");
|
||||
ASSERT_EQ(ev[0].total_tokens, 42L);
|
||||
|
||||
// Loud on the unexpected.
|
||||
ASSERT_TRUE(one("not json")[0].kind == LiveEventKind::Error);
|
||||
ASSERT_TRUE(one("[1]")[0].kind == LiveEventKind::Error);
|
||||
ASSERT_TRUE(one("{\"somethingNew\":{}}")[0].kind == LiveEventKind::Unknown);
|
||||
ev = one("{\"serverContent\":{\"modelTurn\":{\"parts\":[{\"inlineData\":{\"mimeType\":\"audio/pcm\",\"data\":\"!!\"}}]}}}");
|
||||
ASSERT_TRUE(ev[0].kind == LiveEventKind::Error);
|
||||
ASSERT_TRUE(LiveParser::parse_duration("0.5s") == 0.5);
|
||||
ASSERT_TRUE(LiveParser::parse_duration("5") < 0);
|
||||
ASSERT_TRUE(LiveParser::parse_duration("-1s") < 0);
|
||||
ASSERT_TRUE(LiveParser::parse_duration("xs") < 0);
|
||||
}
|
||||
|
||||
TEST(live_session, full_conversation_over_loopback) {
|
||||
std::string setup_seen, text_seen, audio_seen, tool_seen;
|
||||
LoopbackServer server([&](ServerConn& c) {
|
||||
setup_seen = c.read_message().value_or("");
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
text_seen = c.read_message().value_or("");
|
||||
// Binary frames carry JSON too (as Gemini does).
|
||||
c.send_binary("{\"serverContent\":{\"modelTurn\":{\"parts\":[{\"text\":\"hello\"}]}}}");
|
||||
c.send_text("{\"serverContent\":{\"turnComplete\":true}}");
|
||||
audio_seen = c.read_message().value_or("");
|
||||
c.send_text("{\"toolCall\":{\"functionCalls\":[{\"id\":\"c1\",\"name\":\"f\",\"args\":{}}]}}");
|
||||
tool_seen = c.read_message().value_or("");
|
||||
c.send_text("{\"sessionResumptionUpdate\":{\"newHandle\":\"h-123\",\"resumable\":true}}");
|
||||
c.send_text("{\"goAway\":{\"timeLeft\":\"5s\"}}");
|
||||
c.read_frame(); // the client's close
|
||||
c.send_close(1000);
|
||||
});
|
||||
LiveConfig cfg;
|
||||
cfg.system_instruction = "hi";
|
||||
LiveSession s(local_endpoint(server), cfg);
|
||||
s.connect();
|
||||
ASSERT_TRUE(s.open());
|
||||
ASSERT_TRUE(Json::parse(setup_seen).has("setup") || setup_seen.empty() == false);
|
||||
s.send_text("ping");
|
||||
auto evs = until(s, LiveEventKind::TurnComplete);
|
||||
ASSERT_TRUE(!evs.empty());
|
||||
ASSERT_TRUE(evs.front().kind == LiveEventKind::SetupComplete); // queued during connect
|
||||
bool saw_text = false;
|
||||
for (auto& e : evs) saw_text |= e.kind == LiveEventKind::Text && e.text == "hello";
|
||||
ASSERT_TRUE(saw_text);
|
||||
for (std::size_t i = 1; i < evs.size(); ++i) ASSERT_TRUE(evs[i].seq > evs[i - 1].seq);
|
||||
|
||||
s.send_audio("pcm-bytes");
|
||||
auto tc = until(s, LiveEventKind::ToolCall);
|
||||
ASSERT_TRUE(tc.back().kind == LiveEventKind::ToolCall);
|
||||
Json resp = Json::object();
|
||||
resp.set("ok", true);
|
||||
s.send_tool_responses({{tc.back().calls.at(0).id, "f", resp}});
|
||||
auto rest = until(s, LiveEventKind::GoAway);
|
||||
ASSERT_TRUE(rest.back().kind == LiveEventKind::GoAway);
|
||||
ASSERT_TRUE(rest.back().seconds == 5.0);
|
||||
ASSERT_EQ(s.resumption_handle(), "h-123");
|
||||
s.close();
|
||||
ASSERT_FALSE(s.open());
|
||||
auto closing = until(s, LiveEventKind::Closed, 500);
|
||||
ASSERT_TRUE(!closing.empty() && closing.back().kind == LiveEventKind::Closed);
|
||||
ASSERT_THROW(s.send_text("late"), GoogleError);
|
||||
s.close(); // idempotent
|
||||
|
||||
ASSERT_TRUE(setup_seen.find("\"setup\"") != std::string::npos);
|
||||
ASSERT_TRUE(setup_seen.find("systemInstruction") != std::string::npos);
|
||||
ASSERT_EQ(text_seen, "{\"realtimeInput\":{\"text\":\"ping\"}}");
|
||||
ASSERT_TRUE(audio_seen.find("\"audio\"") != std::string::npos);
|
||||
ASSERT_TRUE(audio_seen.find("audio/pcm;rate=16000") != std::string::npos);
|
||||
ASSERT_TRUE(tool_seen.find("functionResponses") != std::string::npos);
|
||||
auto st = s.stats();
|
||||
ASSERT_EQ(st.sent, (std::uint64_t)3);
|
||||
}
|
||||
|
||||
TEST(live_session, vertex_headers_reach_the_server) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
c.read_frame();
|
||||
});
|
||||
LiveSession s(local_endpoint(server, true), LiveConfig{});
|
||||
s.connect();
|
||||
s.close();
|
||||
ASSERT_TRUE(server.request().find("Authorization: Bearer tok") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(live_session, server_close_before_setup_is_an_error_with_reason) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_close(1008, "Publisher model was not found");
|
||||
});
|
||||
LiveSession s(local_endpoint(server), LiveConfig{});
|
||||
try {
|
||||
s.connect();
|
||||
FAIL("expected failure");
|
||||
} catch (const GoogleError& e) {
|
||||
ASSERT_EQ(e.status(), "FAILED_PRECONDITION");
|
||||
ASSERT_TRUE(e.message().find("1008") != std::string::npos);
|
||||
ASSERT_TRUE(e.message().find("Publisher model was not found") != std::string::npos);
|
||||
}
|
||||
ASSERT_FALSE(s.open());
|
||||
}
|
||||
|
||||
TEST(live_session, handshake_errors_map_to_google_statuses) {
|
||||
struct C { LoopbackServer::Handshake mode; int http; const char* status; };
|
||||
for (C c : {C{LoopbackServer::Handshake::Status403, 403, "PERMISSION_DENIED"},
|
||||
C{LoopbackServer::Handshake::BadAccept, 502, "UNAVAILABLE"},
|
||||
C{LoopbackServer::Handshake::CloseImmediately, 502, "UNAVAILABLE"}}) {
|
||||
LoopbackServer server([](ServerConn&) {}, c.mode);
|
||||
LiveSession s(local_endpoint(server), LiveConfig{});
|
||||
try {
|
||||
s.connect();
|
||||
FAIL("expected failure");
|
||||
} catch (const GoogleError& e) {
|
||||
ASSERT_EQ(e.http_status(), c.http);
|
||||
ASSERT_EQ(e.status(), c.status);
|
||||
ASSERT_TRUE(e.message().find("test-key") == std::string::npos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(live_session, setup_timeout_is_bounded) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(1200)); // never sends setupComplete
|
||||
});
|
||||
LiveOptions opt;
|
||||
opt.setup_timeout_ms = 400;
|
||||
LiveSession s(local_endpoint(server), LiveConfig{}, opt);
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
try {
|
||||
s.connect();
|
||||
FAIL("expected timeout");
|
||||
} catch (const GoogleError& e) {
|
||||
ASSERT_EQ(e.http_status(), 504);
|
||||
}
|
||||
ASSERT_TRUE(std::chrono::steady_clock::now() - t0 < std::chrono::milliseconds(1100));
|
||||
}
|
||||
|
||||
TEST(live_session, event_queue_is_bounded_and_counts_drops) {
|
||||
const int flood = (int)LiveCaps::kMaxQueuedEvents + 300;
|
||||
LoopbackServer server([&](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
for (int i = 0; i < flood; ++i)
|
||||
c.send_text("{\"serverContent\":{\"modelTurn\":{\"parts\":[{\"text\":\"t" + std::to_string(i) + "\"}]}}}");
|
||||
c.send_text("{\"serverContent\":{\"turnComplete\":true}}");
|
||||
c.read_frame();
|
||||
});
|
||||
LiveSession s(local_endpoint(server), LiveConfig{});
|
||||
s.connect();
|
||||
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
|
||||
while (s.stats().received < (std::uint64_t)flood + 1 && std::chrono::steady_clock::now() < deadline)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
ASSERT_TRUE(s.pending() <= LiveCaps::kMaxQueuedEvents);
|
||||
ASSERT_TRUE(s.stats().dropped > 0);
|
||||
// Newest survives: the last event is the turnComplete.
|
||||
auto evs = until(s, LiveEventKind::TurnComplete);
|
||||
ASSERT_TRUE(evs.back().kind == LiveEventKind::TurnComplete);
|
||||
s.close();
|
||||
}
|
||||
|
||||
TEST(live_session, abnormal_disconnect_surfaces_closed_event) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
});
|
||||
LiveSession s(local_endpoint(server), LiveConfig{});
|
||||
s.connect();
|
||||
auto evs = until(s, LiveEventKind::Closed);
|
||||
ASSERT_TRUE(evs.back().kind == LiveEventKind::Closed);
|
||||
ASSERT_EQ(evs.back().code, 1006);
|
||||
ASSERT_FALSE(s.open());
|
||||
}
|
||||
|
||||
TEST(live_session, lifetime_cap_closes_session) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
while (c.read_frame()) {
|
||||
}
|
||||
});
|
||||
LiveOptions opt;
|
||||
opt.max_session_seconds = 1;
|
||||
LiveSession s(local_endpoint(server), LiveConfig{}, opt);
|
||||
s.connect();
|
||||
auto evs = until(s, LiveEventKind::Closed, 4000);
|
||||
ASSERT_TRUE(evs.back().kind == LiveEventKind::Closed);
|
||||
ASSERT_TRUE(evs.back().text.find("lifetime") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(live_session, send_validates_before_the_wire) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
while (c.read_frame()) {
|
||||
}
|
||||
});
|
||||
LiveSession s(local_endpoint(server), LiveConfig{});
|
||||
s.connect();
|
||||
ASSERT_THROW(s.send_text(""), GoogleError);
|
||||
ASSERT_THROW(s.send_audio("x", "video/mp4"), GoogleError);
|
||||
ASSERT_THROW(s.send_video(std::string(LiveCaps::kMaxVideoChunkBytes + 1, 'x')), GoogleError);
|
||||
ASSERT_EQ(s.stats().sent, (std::uint64_t)0);
|
||||
s.close();
|
||||
}
|
||||
|
||||
TEST(live_relay, create_poll_cursor_close_and_caps) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
c.read_message();
|
||||
c.send_text("{\"setupComplete\":{}}");
|
||||
auto m = c.read_message();
|
||||
c.send_text("{\"serverContent\":{\"modelTurn\":{\"parts\":[{\"text\":\"echo\"}]}}}");
|
||||
c.send_text("{\"serverContent\":{\"turnComplete\":true}}");
|
||||
(void)m;
|
||||
while (c.read_frame()) {
|
||||
}
|
||||
});
|
||||
LiveRelay relay(1);
|
||||
std::string id = relay.create(local_endpoint(server), LiveConfig{});
|
||||
ASSERT_TRUE(LiveRelay::valid_id(id));
|
||||
ASSERT_EQ(relay.size(), (std::size_t)1);
|
||||
// Second concurrent session is refused (cap 1).
|
||||
try {
|
||||
relay.create(local_endpoint(server), LiveConfig{});
|
||||
FAIL("expected cap");
|
||||
} catch (const GoogleError& e) {
|
||||
ASSERT_EQ(e.http_status(), 429);
|
||||
}
|
||||
relay.get(id)->send_text("hi");
|
||||
std::vector<LiveEvent> all;
|
||||
std::uint64_t cursor = 0;
|
||||
for (int i = 0; i < 40 && (all.empty() || all.back().kind != LiveEventKind::TurnComplete); ++i) {
|
||||
auto page = relay.poll(id, cursor, 100);
|
||||
for (auto& e : page.events) all.push_back(e);
|
||||
cursor = page.next_cursor;
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
}
|
||||
ASSERT_TRUE(all.back().kind == LiveEventKind::TurnComplete);
|
||||
// Cursor semantics: polling again from the end returns nothing new.
|
||||
ASSERT_TRUE(relay.poll(id, cursor, 100).events.empty());
|
||||
// Page size is capped.
|
||||
ASSERT_TRUE(relay.poll(id, 0, 100000).events.size() <= LiveCaps::kMaxRelayPage);
|
||||
Json j = event_to_json(all.front());
|
||||
ASSERT_TRUE(j.has("seq") && j.has("type"));
|
||||
relay.close(id);
|
||||
ASSERT_EQ(relay.size(), (std::size_t)0);
|
||||
ASSERT_THROW(relay.poll(id, 0, 10), GoogleError);
|
||||
ASSERT_THROW(relay.close(id), GoogleError);
|
||||
ASSERT_THROW(relay.get("../etc"), GoogleError);
|
||||
}
|
||||
|
||||
TEST(live_relay, json_never_leaks_resumption_handle) {
|
||||
LiveEvent e;
|
||||
e.kind = LiveEventKind::SessionResumption;
|
||||
e.handle = "SECRET-HANDLE";
|
||||
e.resumable = true;
|
||||
ASSERT_TRUE(event_to_json(e).dump().find("SECRET-HANDLE") == std::string::npos);
|
||||
}
|
||||
|
||||
// Opt-in real network checks: MOLO_LIVE_NET=1 plus credentials from the
|
||||
// environment (never printed): GOOGLE_CLOUD_PROJECT and either
|
||||
// GOOGLE_API_KEY (express key, x-goog-api-key) or GOOGLE_ACCESS_TOKEN (OAuth
|
||||
// bearer). One handshake, one short text turn, close. Loud SKIP otherwise.
|
||||
namespace {
|
||||
bool live_net_enabled(const char* test, const char* credential_var) {
|
||||
const char* on = std::getenv("MOLO_LIVE_NET");
|
||||
if (!on || std::string(on) != "1" || !std::getenv(credential_var) ||
|
||||
!std::getenv("GOOGLE_CLOUD_PROJECT")) {
|
||||
std::printf(" SKIP %s: set MOLO_LIVE_NET=1, %s and GOOGLE_CLOUD_PROJECT to run against "
|
||||
"the real Vertex Live endpoint\n", test, credential_var);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void live_text_turn(const LiveEndpoint& endpoint) {
|
||||
LiveConfig cfg;
|
||||
cfg.output_transcription = true;
|
||||
LiveSession s(endpoint, cfg);
|
||||
s.connect();
|
||||
s.send_text("Say hello in one short sentence.");
|
||||
auto evs = until(s, LiveEventKind::TurnComplete, 30000);
|
||||
bool audio = false, transcript = false;
|
||||
for (auto& e : evs) {
|
||||
audio |= e.kind == LiveEventKind::Audio && !e.data.empty();
|
||||
transcript |= e.kind == LiveEventKind::OutputTranscription && !e.text.empty();
|
||||
}
|
||||
s.close();
|
||||
ASSERT_TRUE(evs.back().kind == LiveEventKind::TurnComplete);
|
||||
ASSERT_TRUE(audio);
|
||||
ASSERT_TRUE(transcript);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
TEST(live_net, vertex_express_text_turn) {
|
||||
if (!live_net_enabled("live_net.vertex_express_text_turn", "GOOGLE_API_KEY")) return;
|
||||
CloudContext ctx = CloudContext::from_env();
|
||||
live_text_turn(LiveEndpoint::vertex_express(ctx, std::getenv("GOOGLE_API_KEY")));
|
||||
}
|
||||
|
||||
TEST(live_net, vertex_oauth_text_turn) {
|
||||
if (!live_net_enabled("live_net.vertex_oauth_text_turn", "GOOGLE_ACCESS_TOKEN")) return;
|
||||
CloudContext ctx = CloudContext::from_env();
|
||||
live_text_turn(LiveEndpoint::vertex(ctx, std::getenv("GOOGLE_ACCESS_TOKEN")));
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
// RFC 6455 client: framing, handshake, fragmentation, ping/pong, close,
|
||||
// caps, over plain TCP (loopback server) and over the ITlsSession seam.
|
||||
#include <poll.h>
|
||||
|
||||
#include <chrono>
|
||||
|
||||
#include "framework.h"
|
||||
#include "google/live/caps.h"
|
||||
#include "google/live/ws_client.h"
|
||||
#include "google/live/ws_error.h"
|
||||
#include "google/live/ws_stream.h"
|
||||
#include "loopback.h"
|
||||
|
||||
using namespace molo::google::live;
|
||||
using live_test::LoopbackServer;
|
||||
using live_test::ServerConn;
|
||||
|
||||
namespace {
|
||||
|
||||
std::unique_ptr<WsClient> dial(const LoopbackServer& s, const WsHeaders& h = {}) {
|
||||
WsUrl url = WsUrl::parse(s.url());
|
||||
auto c = std::make_unique<WsClient>(open_stream(url, 2000, 2000));
|
||||
c->handshake(url, h, 2000);
|
||||
c->set_read_timeout_ms(200);
|
||||
return c;
|
||||
}
|
||||
|
||||
// Next message within ~2 s.
|
||||
std::optional<WsMessage> recv(WsClient& c) {
|
||||
for (int i = 0; i < 20; ++i)
|
||||
if (auto m = c.receive()) return m;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// A "TLS" session that passes bytes through, with wolfSSL's contract:
|
||||
// recv_some returns 0 for both timeout and EOF.
|
||||
class PassthroughTls : public molo::clients::transports::ITlsSession {
|
||||
public:
|
||||
void handshake(int fd, const std::string& host, bool) override {
|
||||
fd_ = fd;
|
||||
host_seen = host;
|
||||
}
|
||||
void send_all(const char* d, std::size_t n) override {
|
||||
std::size_t s = 0;
|
||||
while (s < n) {
|
||||
ssize_t r = ::send(fd_, d + s, n - s, MSG_NOSIGNAL);
|
||||
if (r <= 0) throw molo::clients::transports::TlsError("write failed");
|
||||
s += (std::size_t)r;
|
||||
}
|
||||
}
|
||||
std::size_t recv_some(char* out, std::size_t max) override {
|
||||
ssize_t r = ::recv(fd_, out, max, 0);
|
||||
return r > 0 ? (std::size_t)r : 0;
|
||||
}
|
||||
std::string negotiated_protocol() const override { return "http/1.1"; }
|
||||
void shutdown() override {}
|
||||
const char* backend() const override { return "passthrough-test"; }
|
||||
int fd_ = -1;
|
||||
std::string host_seen;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(live_ws, rfc_accept_vector) {
|
||||
// RFC 6455 section 1.3 example.
|
||||
ASSERT_EQ(WsHandshake::accept_for("dGhlIHNhbXBsZSBub25jZQ=="), "s3pPLMBiTxaQ9kYGzzhZRbK+xOo=");
|
||||
ASSERT_EQ(WsHandshake::make_key().size(), (std::size_t)24);
|
||||
}
|
||||
|
||||
TEST(live_ws, url_parse_and_redaction) {
|
||||
WsUrl u = WsUrl::parse("wss://h.example.com/ws/x?key=SECRET");
|
||||
ASSERT_TRUE(u.secure);
|
||||
ASSERT_EQ(u.port, 443);
|
||||
ASSERT_EQ(u.target, "/ws/x?key=SECRET");
|
||||
ASSERT_EQ(u.display(), "wss://h.example.com:443/ws/x");
|
||||
WsUrl p = WsUrl::parse("ws://127.0.0.1:8080");
|
||||
ASSERT_EQ(p.target, "/");
|
||||
ASSERT_EQ(p.port, 8080);
|
||||
for (const char* bad : {"http://x/", "ws://", "ws://u@h/", "ws://h:0/", "ws://h:99999/",
|
||||
"ws://h /x", "ws://h/\r\n", "", "ws://h:x/", "ws://a b/"})
|
||||
ASSERT_THROW(WsUrl::parse(bad), WsError);
|
||||
ASSERT_THROW(WsUrl::parse("ws://h/" + std::string(3000, 'a')), WsError);
|
||||
}
|
||||
|
||||
TEST(live_ws, frame_roundtrip_all_length_classes) {
|
||||
std::uint8_t mask[4] = {1, 2, 3, 4};
|
||||
for (std::size_t n : {0u, 5u, 125u, 126u, 200u, 65535u, 65536u, 70000u}) {
|
||||
std::string payload(n, 'x');
|
||||
for (std::size_t i = 0; i < n; ++i) payload[i] = (char)('a' + i % 26);
|
||||
for (bool masked : {false, true}) {
|
||||
FrameDecoder d(1u << 20, masked);
|
||||
std::string wire = encode_frame(true, WsOpcode::Binary, payload, masked ? mask : nullptr);
|
||||
// Feed byte-by-byte for the small ones to exercise incremental parsing.
|
||||
if (n < 300) {
|
||||
for (char c : wire) {
|
||||
ASSERT_FALSE(d.next().has_value());
|
||||
d.feed(&c, 1);
|
||||
}
|
||||
} else {
|
||||
d.feed(wire.data(), wire.size());
|
||||
}
|
||||
auto f = d.next();
|
||||
ASSERT_TRUE(f.has_value());
|
||||
ASSERT_TRUE(f->fin);
|
||||
ASSERT_EQ(f->opcode, (std::uint8_t)2);
|
||||
ASSERT_TRUE(f->payload == payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST(live_ws, decoder_rejects_violations) {
|
||||
auto raw = [](std::initializer_list<int> bytes) {
|
||||
std::string s;
|
||||
for (int b : bytes) s.push_back((char)b);
|
||||
return s;
|
||||
};
|
||||
auto feeds = [](const std::string& wire, bool expect_masked = false, std::size_t cap = 1 << 20) {
|
||||
FrameDecoder d(cap, expect_masked);
|
||||
d.feed(wire.data(), wire.size());
|
||||
return d.next();
|
||||
};
|
||||
ASSERT_THROW(feeds(raw({0xC1, 0x00})), WsError); // RSV1
|
||||
ASSERT_THROW(feeds(raw({0x83, 0x00})), WsError); // reserved opcode 3
|
||||
ASSERT_THROW(feeds(raw({0x81, 0x80, 0, 0, 0, 0})), WsError); // masked server frame
|
||||
ASSERT_THROW(feeds(raw({0x81, 0x00}), true), WsError); // unmasked client frame
|
||||
ASSERT_THROW(feeds(raw({0x09, 0x00})), WsError); // fragmented ping
|
||||
ASSERT_THROW(feeds(raw({0x89, 126, 0, 126})), WsError); // ping over 125
|
||||
ASSERT_THROW(feeds(raw({0x82, 126, 0, 5})), WsError); // non-minimal 16-bit length
|
||||
ASSERT_THROW(feeds(raw({0x82, 127, 0, 0, 0, 0, 0, 0, 1, 0})), WsError); // non-minimal 64-bit
|
||||
ASSERT_THROW(feeds(raw({0x82, 127, 0x80, 0, 0, 0, 0, 0, 0, 0})), WsError); // high bit
|
||||
// Declared length over the cap is refused before any payload arrives.
|
||||
try {
|
||||
feeds(raw({0x82, 127, 0, 0, 0, 0, 0, 0x20, 0, 0}), false, 1024);
|
||||
FAIL("expected TooBig");
|
||||
} catch (const WsError& e) {
|
||||
ASSERT_TRUE(e.kind() == WsError::Kind::TooBig);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(live_ws, utf8_validation) {
|
||||
ASSERT_TRUE(valid_utf8("hello \xC3\xA9 \xE2\x82\xAC \xF0\x9F\x98\x80"));
|
||||
ASSERT_FALSE(valid_utf8("\xC0\xAF")); // overlong
|
||||
ASSERT_FALSE(valid_utf8("\xED\xA0\x80")); // surrogate
|
||||
ASSERT_FALSE(valid_utf8("\xF4\x90\x80\x80")); // > U+10FFFF
|
||||
ASSERT_FALSE(valid_utf8("\xE2\x82")); // truncated
|
||||
ASSERT_FALSE(valid_utf8("\x80")); // stray continuation
|
||||
}
|
||||
|
||||
TEST(live_ws, handshake_masks_and_echoes) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
auto m = c.read_message();
|
||||
if (m) c.send_text("echo:" + *m);
|
||||
c.send_close(1000, "bye");
|
||||
c.read_frame(); // client's close echo
|
||||
});
|
||||
auto c = dial(server, {{"X-Test", "yes"}});
|
||||
c->send_text("hello");
|
||||
auto m = recv(*c);
|
||||
ASSERT_TRUE(m.has_value());
|
||||
ASSERT_TRUE(m->kind == WsMessage::Kind::Text);
|
||||
ASSERT_EQ(m->data, "echo:hello");
|
||||
auto close = recv(*c);
|
||||
ASSERT_TRUE(close.has_value());
|
||||
ASSERT_TRUE(close->kind == WsMessage::Kind::Close);
|
||||
ASSERT_EQ(close->code, (std::uint16_t)1000);
|
||||
ASSERT_EQ(close->data, "bye");
|
||||
ASSERT_TRUE(c->closed());
|
||||
ASSERT_THROW(c->send_text("late"), WsError);
|
||||
std::string req = server.request();
|
||||
ASSERT_TRUE(req.find("Upgrade: websocket") != std::string::npos);
|
||||
ASSERT_TRUE(req.find("Sec-WebSocket-Version: 13") != std::string::npos);
|
||||
ASSERT_TRUE(req.find("X-Test: yes") != std::string::npos);
|
||||
ASSERT_TRUE(req.find("GET /ws HTTP/1.1") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST(live_ws, handshake_failures_are_loud) {
|
||||
{
|
||||
LoopbackServer s([](ServerConn&) {}, LoopbackServer::Handshake::BadAccept);
|
||||
WsUrl url = WsUrl::parse(s.url());
|
||||
WsClient c(open_stream(url, 2000, 2000));
|
||||
try {
|
||||
c.handshake(url, {}, 2000);
|
||||
FAIL("expected accept mismatch");
|
||||
} catch (const WsError& e) {
|
||||
ASSERT_TRUE(e.kind() == WsError::Kind::Handshake);
|
||||
ASSERT_TRUE(std::string(e.what()).find("Accept") != std::string::npos);
|
||||
}
|
||||
}
|
||||
{
|
||||
LoopbackServer s([](ServerConn&) {}, LoopbackServer::Handshake::Status403);
|
||||
WsUrl url = WsUrl::parse(s.url());
|
||||
WsClient c(open_stream(url, 2000, 2000));
|
||||
try {
|
||||
c.handshake(url, {}, 2000);
|
||||
FAIL("expected 403");
|
||||
} catch (const WsError& e) {
|
||||
ASSERT_EQ(e.http_status(), 403);
|
||||
}
|
||||
}
|
||||
{
|
||||
LoopbackServer s([](ServerConn&) {}, LoopbackServer::Handshake::CloseImmediately);
|
||||
WsUrl url = WsUrl::parse(s.url());
|
||||
WsClient c(open_stream(url, 2000, 2000));
|
||||
ASSERT_THROW(c.handshake(url, {}, 2000), WsError);
|
||||
}
|
||||
// Header injection is rejected before anything is written.
|
||||
LoopbackServer s([](ServerConn&) {});
|
||||
WsUrl url = WsUrl::parse(s.url());
|
||||
WsClient c(open_stream(url, 2000, 2000));
|
||||
ASSERT_THROW(c.handshake(url, {{"X-A", "v\r\nEvil: 1"}}, 2000), WsError);
|
||||
// Connection refused is a WsError, not a crash.
|
||||
WsUrl dead = WsUrl::parse("ws://127.0.0.1:1/");
|
||||
ASSERT_THROW(open_stream(dead, 500, 500), WsError);
|
||||
}
|
||||
|
||||
TEST(live_ws, fragmentation_with_interleaved_ping) {
|
||||
std::string pong_payload;
|
||||
std::atomic<bool> got_pong{false};
|
||||
LoopbackServer server([&](ServerConn& c) {
|
||||
c.send_raw(encode_frame(false, WsOpcode::Text, "frag", nullptr));
|
||||
c.send_raw(encode_frame(true, WsOpcode::Ping, "ping-data", nullptr));
|
||||
c.send_raw(encode_frame(false, WsOpcode::Continuation, "ment", nullptr));
|
||||
c.send_raw(encode_frame(true, WsOpcode::Continuation, "ed \xC3\xA9", nullptr));
|
||||
auto f = c.read_frame(); // the pong
|
||||
if (f && f->opcode == 10) {
|
||||
pong_payload = f->payload;
|
||||
got_pong = true;
|
||||
}
|
||||
c.send_binary(std::string("\x01\x02\x00\x03", 4));
|
||||
c.read_frame();
|
||||
});
|
||||
auto c = dial(server);
|
||||
auto m = recv(*c);
|
||||
ASSERT_TRUE(m.has_value());
|
||||
ASSERT_EQ(m->data, "fragmented \xC3\xA9");
|
||||
auto b = recv(*c);
|
||||
ASSERT_TRUE(b.has_value());
|
||||
ASSERT_TRUE(b->kind == WsMessage::Kind::Binary);
|
||||
ASSERT_EQ(b->data.size(), (std::size_t)4);
|
||||
ASSERT_TRUE(got_pong.load());
|
||||
ASSERT_EQ(pong_payload, "ping-data");
|
||||
ASSERT_EQ(c->stats().pings_in, (std::uint64_t)1);
|
||||
}
|
||||
|
||||
TEST(live_ws, protocol_violations_close_with_1002_1007_1009) {
|
||||
struct Case {
|
||||
const char* name;
|
||||
std::function<void(ServerConn&)> script;
|
||||
std::uint16_t want_code;
|
||||
};
|
||||
std::vector<Case> cases = {
|
||||
{"continuation without start",
|
||||
[](ServerConn& c) { c.send_raw(encode_frame(true, WsOpcode::Continuation, "x", nullptr)); }, 1002},
|
||||
{"new message inside fragmented",
|
||||
[](ServerConn& c) {
|
||||
c.send_raw(encode_frame(false, WsOpcode::Text, "a", nullptr));
|
||||
c.send_raw(encode_frame(true, WsOpcode::Text, "b", nullptr));
|
||||
},
|
||||
1002},
|
||||
{"invalid utf8 text",
|
||||
[](ServerConn& c) { c.send_raw(encode_frame(true, WsOpcode::Text, "\xFF\xFE", nullptr)); }, 1007},
|
||||
{"frame over cap",
|
||||
[](ServerConn& c) {
|
||||
c.send_raw(std::string("\x82\x7f\x00\x00\x00\x00\x01\x00\x00\x00", 10)); // 16 MiB declared
|
||||
},
|
||||
1009},
|
||||
};
|
||||
for (auto& tc : cases) {
|
||||
std::uint16_t got = 0;
|
||||
LoopbackServer server([&](ServerConn& c) {
|
||||
tc.script(c);
|
||||
auto f = c.read_frame();
|
||||
if (f && f->opcode == 8 && f->payload.size() >= 2)
|
||||
got = (std::uint16_t)(((std::uint8_t)f->payload[0] << 8) | (std::uint8_t)f->payload[1]);
|
||||
});
|
||||
auto c = dial(server);
|
||||
bool threw = false;
|
||||
for (int i = 0; i < 20 && !threw; ++i) {
|
||||
try {
|
||||
c->receive();
|
||||
} catch (const WsError&) {
|
||||
threw = true;
|
||||
}
|
||||
}
|
||||
ASSERT_TRUE(threw);
|
||||
ASSERT_TRUE(c->closed());
|
||||
c.reset(); // closes the socket so the server thread finishes
|
||||
(void)tc.name;
|
||||
// The server thread joins in the destructor at scope end; read after.
|
||||
// (got is set before the join completes.)
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
ASSERT_EQ(got, tc.want_code);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(live_ws, message_cap_across_fragments) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
std::string chunk(LiveCaps::kMaxFramePayload, 'z');
|
||||
c.send_raw(encode_frame(false, WsOpcode::Binary, chunk, nullptr));
|
||||
c.send_raw(encode_frame(false, WsOpcode::Continuation, chunk, nullptr));
|
||||
c.send_raw(encode_frame(true, WsOpcode::Continuation, chunk, nullptr)); // 12 MiB > 8 MiB
|
||||
c.read_frame();
|
||||
});
|
||||
auto c = dial(server);
|
||||
bool too_big = false;
|
||||
for (int i = 0; i < 50 && !too_big; ++i) {
|
||||
try {
|
||||
c->receive();
|
||||
} catch (const WsError& e) {
|
||||
too_big = e.kind() == WsError::Kind::TooBig;
|
||||
}
|
||||
}
|
||||
ASSERT_TRUE(too_big);
|
||||
}
|
||||
|
||||
TEST(live_ws, abrupt_disconnect_reports_1006) {
|
||||
LoopbackServer server([](ServerConn&) { /* returns: socket closed, no close frame */ });
|
||||
auto c = dial(server);
|
||||
auto m = recv(*c);
|
||||
ASSERT_TRUE(m.has_value());
|
||||
ASSERT_TRUE(m->kind == WsMessage::Kind::Close);
|
||||
ASSERT_EQ(m->code, (std::uint16_t)1006);
|
||||
}
|
||||
|
||||
TEST(live_ws, outbound_caps_and_ping_validation) {
|
||||
LoopbackServer server([](ServerConn& c) { c.read_frame(); });
|
||||
auto c = dial(server);
|
||||
ASSERT_THROW(c->send_text(std::string(LiveCaps::kMaxOutboundMessage + 1, 'a')), WsError);
|
||||
ASSERT_THROW(c->send_ping(std::string(126, 'p')), WsError);
|
||||
c->send_ping("ok");
|
||||
}
|
||||
|
||||
TEST(live_ws, close_is_sent_once) {
|
||||
int closes = 0;
|
||||
LoopbackServer server([&](ServerConn& c) {
|
||||
while (auto f = c.read_frame()) {
|
||||
if (f->opcode == 8) ++closes;
|
||||
}
|
||||
});
|
||||
auto c = dial(server);
|
||||
c->close(1000, "one");
|
||||
c->close(1000, "two");
|
||||
c->shutdown();
|
||||
c.reset();
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(150));
|
||||
ASSERT_EQ(closes, 1);
|
||||
}
|
||||
|
||||
TEST(live_ws, tls_seam_carries_websocket) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
auto m = c.read_message();
|
||||
c.send_text(m ? "tls:" + *m : "none");
|
||||
c.send_close(1000);
|
||||
c.read_frame();
|
||||
});
|
||||
// The wss scheme routes through the injected ITlsSession; the server is
|
||||
// plain TCP, so the passthrough fake stands in for wolfSSL's contract.
|
||||
std::string url = "wss://127.0.0.1:" + std::to_string(server.port()) + "/ws";
|
||||
WsUrl u = WsUrl::parse(url);
|
||||
std::shared_ptr<PassthroughTls> tls;
|
||||
WsClient c(open_stream(u, 2000, 2000, [&] {
|
||||
tls = std::make_shared<PassthroughTls>();
|
||||
return tls;
|
||||
}));
|
||||
ASSERT_EQ(tls->host_seen, "127.0.0.1");
|
||||
c.handshake(u, {}, 2000);
|
||||
c.set_read_timeout_ms(200);
|
||||
c.send_text("ping");
|
||||
auto m = recv(c);
|
||||
ASSERT_TRUE(m.has_value());
|
||||
ASSERT_EQ(m->data, "tls:ping");
|
||||
auto close = recv(c);
|
||||
ASSERT_TRUE(close.has_value());
|
||||
ASSERT_TRUE(close->kind == WsMessage::Kind::Close);
|
||||
}
|
||||
|
||||
TEST(live_ws, tls_read_distinguishes_timeout_from_eof) {
|
||||
LoopbackServer server([](ServerConn& c) {
|
||||
// Stay silent for a while, then drop the connection.
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(700));
|
||||
(void)c;
|
||||
});
|
||||
WsUrl u = WsUrl::parse("wss://127.0.0.1:" + std::to_string(server.port()) + "/ws");
|
||||
WsClient c(open_stream(u, 2000, 2000, [] { return std::make_shared<PassthroughTls>(); }));
|
||||
c.handshake(u, {}, 2000);
|
||||
c.set_read_timeout_ms(200);
|
||||
auto t0 = std::chrono::steady_clock::now();
|
||||
auto first = c.receive(); // silence: timeout, not close
|
||||
ASSERT_FALSE(first.has_value());
|
||||
ASSERT_TRUE(std::chrono::steady_clock::now() - t0 >= std::chrono::milliseconds(100));
|
||||
auto m = recv(c); // then EOF: abnormal close
|
||||
ASSERT_TRUE(m.has_value());
|
||||
ASSERT_EQ(m->code, (std::uint16_t)1006);
|
||||
}
|
||||
Reference in New Issue
Block a user