use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::error::{Error, Result};
use crate::hlc::Hlc;
pub const PROTOCOL_VERSION: u32 = 1;
pub const PROTOCOL_V2: u32 = 2;
pub const USERS_TABLE: &str = "_users";
pub const QUERY_ALL: &str = "*";
pub const MAX_FRAME_BYTES: usize = 8 << 20;
pub const MAX_MUTATIONS_PER_FRAME: usize = 500;
pub type JsonMap = Map<String, Value>;
fn is_false(b: &bool) -> bool {
!*b
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ColumnDef {
#[serde(rename = "type")]
pub ty: String,
#[serde(default, skip_serializing_if = "is_false")]
pub optional: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ref_table: Option<String>,
#[serde(flatten)]
pub extra: JsonMap,
}
impl ColumnDef {
pub fn new(ty: &str) -> ColumnDef {
ColumnDef { ty: ty.to_string(), optional: false, ref_table: None, extra: Map::new() }
}
pub fn optional(mut self) -> ColumnDef {
self.optional = true;
self
}
}
pub const COLUMN_TYPES: &[&str] = &["string", "number", "boolean", "datetime", "json", "ref", "file_ref"];
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TableSchema {
pub columns: BTreeMap<String, ColumnDef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub order: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<i64>,
#[serde(flatten)]
pub extra: JsonMap,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileMeta {
pub path: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub sha256: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size_bytes: Option<u64>,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub mime_type: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mutation {
pub mutation_id: String,
pub hlc: String,
pub kind: String,
pub op: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub table: Option<String>,
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fields: Option<JsonMap>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<FileMeta>,
}
impl Mutation {
pub fn entity_key(&self) -> String {
if self.kind == "file" {
format!("file\u{0}{}", self.id)
} else {
format!("record\u{0}{}\u{0}{}", self.table.as_deref().unwrap_or(""), self.id)
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Actor {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub user_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub machine_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub app_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FileState {
pub id: String,
pub path: String,
#[serde(default)]
pub sha256: String,
#[serde(default)]
pub size_bytes: u64,
#[serde(default)]
pub mime_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hlc: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seq: Option<i64>,
#[serde(default, skip_serializing_if = "is_false")]
pub deleted: bool,
#[serde(flatten)]
pub extra: JsonMap,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecordState {
pub table: String,
pub id: String,
pub fields: JsonMap,
#[serde(default)]
pub hlcs: BTreeMap<String, String>,
#[serde(default, skip_serializing_if = "is_false")]
pub deleted: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deleted_hlc: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seq: Option<i64>,
#[serde(flatten)]
pub extra: JsonMap,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Op {
pub seq: i64,
#[serde(default)]
pub mutation_id: String,
pub hlc: String,
pub at: String,
#[serde(default)]
pub by: Actor,
pub kind: String,
pub op: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub table: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub fields: Option<JsonMap>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub file: Option<FileState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<TableSchema>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ClientInfo {
pub name: String,
pub version: String,
pub platform: String,
}
impl ClientInfo {
pub fn current() -> ClientInfo {
ClientInfo { name: "kovlet-rs".into(), version: env!("CARGO_PKG_VERSION").into(), platform: platform().into() }
}
}
pub fn platform() -> &'static str {
if cfg!(target_os = "ios") {
"ios"
} else if cfg!(target_os = "android") {
"android"
} else if cfg!(target_os = "macos") {
"macos"
} else if cfg!(target_os = "windows") {
"windows"
} else if cfg!(target_os = "linux") {
"linux"
} else {
"other"
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Hello {
pub protocol: u32,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub space_id: String,
#[serde(default)]
pub since_seq: i64,
pub token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_proof: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<BTreeMap<String, TableSchema>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client: Option<ClientInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub as_end_user: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Mutate {
pub space_id: String,
pub mutations: Vec<Mutation>,
#[serde(default, skip_serializing_if = "is_false")]
pub atomic: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub batch_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<JsonMap>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct FilesScope {
#[serde(default, skip_serializing_if = "String::is_empty")]
pub prefix: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Subscribe {
pub sub: String,
pub space_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub query: Option<Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub files: Option<FilesScope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<JsonMap>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resume: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<BTreeMap<String, TableSchema>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Unsubscribe {
pub sub: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ping {
pub nonce: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientFrame {
Hello(Hello),
Mutate(Mutate),
Ping(Ping),
Subscribe(Subscribe),
Unsubscribe(Unsubscribe),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Snapshot {
pub space_id: String,
pub head_seq: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tables: Option<BTreeMap<String, TableSchema>>,
#[serde(default)]
pub records: Vec<RecordState>,
#[serde(default)]
pub files: Vec<FileState>,
#[serde(default)]
pub complete: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<Vec<Value>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Delta {
pub space_id: String,
pub head_seq: i64,
#[serde(default)]
pub complete: bool,
pub ops: Vec<Op>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<Vec<Value>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Broadcast {
pub space_id: String,
pub head_seq: i64,
pub ops: Vec<Op>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorBody {
pub code: String,
#[serde(default)]
pub message: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<JsonMap>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MutationResult {
pub mutation_id: String,
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seq: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorBody>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Ack {
pub space_id: String,
pub head_seq: i64,
pub results: Vec<MutationResult>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<Value>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub batch: Option<BatchResult>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BatchResult {
pub id: String,
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed_index: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorBody>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ErrorFrame {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub space_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sub: Option<String>,
pub code: String,
#[serde(default)]
pub message: String,
#[serde(default)]
pub retryable: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub details: Option<JsonMap>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Pong {
pub nonce: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct PrincipalInfo {
pub kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub end_user_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct Limits {
#[serde(default)]
pub max_frame_bytes: u64,
#[serde(default)]
pub max_mutations: u64,
#[serde(default)]
pub max_subscriptions: u64,
#[serde(default)]
pub max_rows_per_subscription: u64,
#[serde(default)]
pub ping_interval_ms: u64,
#[serde(default)]
pub write_timeout_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Welcome {
pub protocol: u32,
pub principal: PrincipalInfo,
#[serde(default)]
pub limits: Limits,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub features: Option<JsonMap>,
}
impl Welcome {
pub fn atomic(&self) -> bool {
self.features.as_ref().is_some_and(|f| f.get("atomic").is_some_and(|v| !v.is_null()))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RemovedRow {
pub table: String,
pub id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResultFrame {
pub sub: String,
pub space_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tables: Option<BTreeMap<String, TableSchema>>,
#[serde(default)]
pub rows: Vec<RecordState>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub files: Vec<FileState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ids: Option<BTreeMap<String, Vec<String>>>,
#[serde(default, skip_serializing_if = "is_false")]
pub resumed: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub more: Option<BTreeMap<String, bool>>,
pub through_seq: i64,
#[serde(default)]
pub cursor: String,
#[serde(default)]
pub complete: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub usage: Option<Vec<Value>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Changes {
pub sub: String,
pub space_id: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ops: Vec<Op>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub added: Vec<RecordState>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub removed: Vec<RemovedRow>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub more: Option<BTreeMap<String, bool>>,
pub through_seq: i64,
#[serde(default)]
pub cursor: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerFrame {
Snapshot(Snapshot),
Delta(Delta),
Broadcast(Broadcast),
Ack(Ack),
Error(ErrorFrame),
Pong(Pong),
Welcome(Welcome),
Result(ResultFrame),
Changes(Changes),
}
impl<'de> Deserialize<'de> for ServerFrame {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<ServerFrame, D::Error> {
use serde::de::Error as _;
let mut v = Map::<String, Value>::deserialize(d)?;
let ty = match v.remove("type") {
Some(Value::String(t)) => t,
_ => return Err(D::Error::missing_field("type")),
};
fn de<T: serde::de::DeserializeOwned, E: serde::de::Error>(v: Map<String, Value>) -> std::result::Result<T, E> {
serde_json::from_value(Value::Object(v)).map_err(E::custom)
}
Ok(match ty.as_str() {
"snapshot" => ServerFrame::Snapshot(de(v)?),
"delta" => ServerFrame::Delta(de(v)?),
"broadcast" => ServerFrame::Broadcast(de(v)?),
"ack" => ServerFrame::Ack(de(v)?),
"error" => ServerFrame::Error(de(v)?),
"pong" => ServerFrame::Pong(de(v)?),
"welcome" => ServerFrame::Welcome(de(v)?),
"result" => ServerFrame::Result(de(v)?),
"changes" => ServerFrame::Changes(de(v)?),
t => {
return Err(D::Error::unknown_variant(
t,
&["snapshot", "delta", "broadcast", "ack", "error", "pong", "welcome", "result", "changes"],
))
}
})
}
}
fn invalid(msg: impl Into<String>) -> Error {
Error::new("invalid_frame", msg)
}
pub fn valid_entity_id(s: &str) -> bool {
!s.is_empty() && s.len() <= 128 && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
pub fn valid_record_id(s: &str) -> bool {
!s.is_empty() && s.len() <= 256 && !s.chars().any(|c| (c as u32) < 0x20 || (0x7f..=0x9f).contains(&(c as u32)))
}
pub fn valid_record_table(s: &str) -> bool {
valid_identifier(s) || s == USERS_TABLE
}
pub fn valid_identifier(s: &str) -> bool {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 63
&& b[0].is_ascii_alphabetic()
&& b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
}
pub fn valid_file_path(p: &str) -> bool {
!p.is_empty()
&& p.len() <= 1024
&& !p.contains('\0')
&& !p.contains('\\')
&& p.split('/').all(|s| !s.is_empty() && s != "." && s != "..")
}
fn valid_sha256(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
impl TableSchema {
pub fn validate(&self, table: &str) -> Result<()> {
if !valid_identifier(table) {
return Err(invalid(format!("bad table name {table:?}")));
}
for (name, col) in &self.columns {
if !valid_identifier(name) {
return Err(invalid(format!("bad column name {table}.{name}")));
}
if !COLUMN_TYPES.contains(&col.ty.as_str()) {
return Err(invalid(format!("unknown column type {:?} for {table}.{name}", col.ty)));
}
}
if let Some(order) = &self.order {
let mut seen = std::collections::BTreeSet::new();
for c in order {
if !self.columns.contains_key(c) || !seen.insert(c) {
return Err(invalid(format!("{table}.order must name every column exactly once")));
}
}
if seen.len() != self.columns.len() {
return Err(invalid(format!("{table}.order must name every column exactly once")));
}
}
Ok(())
}
}
fn check_hlc(h: &str) -> Result<()> {
Hlc::parse(h).map(|_| ()).map_err(|_| invalid(format!("bad hlc {h:?}")))
}
impl RecordState {
pub fn validate(&self) -> Result<()> {
if !valid_record_table(&self.table) || !valid_record_id(&self.id) {
return Err(invalid(format!("row {}/{} needs a valid table and id", self.table, self.id)));
}
for k in self.fields.keys() {
if !valid_identifier(k) {
return Err(invalid(format!("bad field name {}.{k}", self.table)));
}
match self.hlcs.get(k) {
Some(h) => check_hlc(h)?,
None => return Err(invalid(format!("field {}.{k} has no stamp", self.table))),
}
}
if let Some(d) = &self.deleted_hlc {
check_hlc(d)?;
}
Ok(())
}
}
fn check_tables(tables: Option<&BTreeMap<String, TableSchema>>) -> Result<()> {
for (name, ts) in tables.into_iter().flatten() {
ts.validate(name)?;
}
Ok(())
}
impl Op {
pub fn validate(&self) -> Result<()> {
if self.seq < 1 {
return Err(invalid("op.seq must be at least 1"));
}
check_hlc(&self.hlc)?;
match (self.kind.as_str(), self.op.as_str()) {
("record", "upsert" | "delete" | "restore") => {
let ok = self.table.as_deref().is_some_and(valid_record_table)
&& self.id.as_deref().is_some_and(valid_record_id);
if !ok {
return Err(invalid("record ops need a valid table and id"));
}
}
("file", "put" | "move" | "delete" | "restore") => {
if self.file.is_none() {
return Err(invalid("file op without file"));
}
}
("schema", "put" | "delete") => {
if self.table.is_none() {
return Err(invalid("schema op without table"));
}
}
(k, o) => return Err(invalid(format!("bad op kind/op {k}/{o}"))),
}
Ok(())
}
}
impl Mutation {
pub fn validate(&self) -> Result<()> {
let bad = |code: &str, m: String| Err(Error::new(code, m));
if !valid_entity_id(&self.mutation_id) {
return bad("invalid_mutation", format!("bad mutation_id {:?}", self.mutation_id));
}
if Hlc::parse(&self.hlc).is_err() {
return bad("invalid_mutation", format!("bad hlc {:?}", self.hlc));
}
match (self.kind.as_str(), self.op.as_str()) {
("record", op) => {
if !valid_record_id(&self.id) {
return bad("invalid_id", "record ids are 1–256 bytes of UTF-8 with no control characters".into());
}
let Some(t) = &self.table else {
return bad("invalid_mutation", "record mutation without table".into());
};
if !valid_identifier(t) {
return bad("invalid_mutation", format!("bad table name {t:?}"));
}
match op {
"upsert" => {
let Some(f) = &self.fields else {
return bad("invalid_mutation", "upsert without fields".into());
};
if f.is_empty() {
return bad("invalid_mutation", "upsert needs at least one field".into());
}
for k in f.keys() {
if !valid_identifier(k) {
return bad("invalid_mutation", format!("bad field name {k:?}"));
}
}
}
"delete" | "restore" => {
if self.fields.is_some() {
return bad("invalid_mutation", format!("{op} carries no fields"));
}
}
_ => return bad("invalid_mutation", format!("bad record op {op}")),
}
}
("file", op) => {
if !valid_entity_id(&self.id) {
return bad("invalid_id", "file ids are 1–128 characters of [A-Za-z0-9_-]".into());
}
match op {
"put" => {
let Some(f) = &self.file else {
return bad("invalid_mutation", "file put without file".into());
};
if !valid_file_path(&f.path) || !valid_sha256(&f.sha256) || f.mime_type.is_empty() {
return bad("invalid_mutation", "file put needs a valid path, sha256 and mime_type".into());
}
}
"move" => {
let ok = self.file.as_ref().is_some_and(|f| valid_file_path(&f.path));
if !ok {
return bad("invalid_mutation", "file move needs a valid path".into());
}
}
"delete" | "restore" => {}
_ => return bad("invalid_mutation", format!("bad file op {op}")),
}
}
(k, _) => return bad("invalid_mutation", format!("bad mutation kind {k}")),
}
Ok(())
}
}
impl ServerFrame {
pub fn decode(text: &str) -> Result<ServerFrame> {
let v: Value = serde_json::from_str(text).map_err(|e| invalid(format!("not JSON: {e}")))?;
let f: ServerFrame = serde_json::from_value(v).map_err(|e| invalid(format!("bad frame: {e}")))?;
f.validate()?;
Ok(f)
}
pub fn validate(&self) -> Result<()> {
match self {
ServerFrame::Snapshot(s) => {
for r in &s.records {
for k in r.fields.keys() {
if !r.hlcs.contains_key(k) {
return Err(invalid(format!("snapshot field {}.{} has no stamp", r.table, k)));
}
}
for h in r.hlcs.values() {
check_hlc(h)?;
}
}
if let Some(t) = &s.tables {
for (name, ts) in t {
ts.validate(name)?;
}
}
}
ServerFrame::Delta(d) => {
for op in &d.ops {
op.validate()?;
}
}
ServerFrame::Broadcast(b) => {
if b.ops.is_empty() {
return Err(invalid("broadcast without ops"));
}
for op in &b.ops {
op.validate()?;
}
}
ServerFrame::Ack(a) => {
for r in &a.results {
match r.status.as_str() {
"applied" | "duplicate" | "aborted" => {}
"rejected" if r.error.is_some() => {}
"rejected" => return Err(invalid("rejected result without error")),
s => return Err(invalid(format!("bad ack status {s}"))),
}
}
if let Some(b) = &a.batch {
if !matches!(b.status.as_str(), "applied" | "rejected" | "duplicate") {
return Err(invalid(format!("bad batch status {}", b.status)));
}
}
}
ServerFrame::Welcome(w) => {
if w.protocol < PROTOCOL_V2 {
return Err(invalid("welcome.protocol must be >= 2"));
}
if w.principal.kind.is_empty() {
return Err(invalid("welcome.principal.kind is required"));
}
}
ServerFrame::Result(r) => {
if !valid_entity_id(&r.sub) || !valid_entity_id(&r.space_id) || r.through_seq < 0 {
return Err(invalid("result needs a valid sub, space_id and through_seq"));
}
check_tables(r.tables.as_ref())?;
for row in &r.rows {
row.validate()?;
}
for (table, ids) in r.ids.iter().flatten() {
if !valid_record_table(table) || !ids.iter().all(|id| valid_record_id(id)) {
return Err(invalid(format!("result.ids[{table}] is invalid")));
}
}
}
ServerFrame::Changes(c) => {
if !valid_entity_id(&c.sub) || !valid_entity_id(&c.space_id) || c.through_seq < 0 {
return Err(invalid("changes needs a valid sub, space_id and through_seq"));
}
for op in &c.ops {
op.validate()?;
}
for row in &c.added {
row.validate()?;
}
for r in &c.removed {
if !valid_record_table(&r.table) || !valid_record_id(&r.id) {
return Err(invalid("changes.removed needs a valid table and id"));
}
}
}
ServerFrame::Error(e) => {
if e.code.is_empty() {
return Err(invalid("error frame without code"));
}
}
ServerFrame::Pong(p) => {
if !valid_entity_id(&p.nonce) {
return Err(invalid("bad pong nonce"));
}
if p.region.as_ref().is_some_and(|r| r.len() > 64) {
return Err(invalid("pong region over 64 bytes"));
}
}
}
Ok(())
}
}
impl ClientFrame {
pub fn encode(&self) -> String {
serde_json::to_string(self).expect("frames serialize")
}
pub fn decode(text: &str) -> Result<ClientFrame> {
let f: ClientFrame = serde_json::from_str(text).map_err(|e| invalid(format!("bad frame: {e}")))?;
match &f {
ClientFrame::Hello(h) => {
if h.protocol >= PROTOCOL_V2 {
if h.token.is_empty() || !h.space_id.is_empty() || h.since_seq != 0 || h.schema.is_some() {
return Err(invalid("a protocol 2 hello carries a token and no space_id, since_seq or schema"));
}
} else if h.protocol < 1 || h.since_seq < 0 || h.space_id.is_empty() || h.token.is_empty() {
return Err(invalid("bad hello"));
}
for (name, t) in h.schema.iter().flatten() {
t.validate(name)?;
}
}
ClientFrame::Mutate(m) => {
if m.mutations.is_empty() || m.mutations.len() > MAX_MUTATIONS_PER_FRAME {
return Err(invalid("a mutate frame holds 1 to 500 mutations"));
}
for mu in &m.mutations {
if !valid_entity_id(&mu.mutation_id) {
return Err(invalid("bad mutation_id"));
}
}
if m.batch_id.as_deref().is_some_and(|b| !valid_entity_id(b)) || (m.atomic && m.batch_id.is_none()) {
return Err(invalid("an atomic mutate needs a valid batch_id"));
}
}
ClientFrame::Subscribe(sb) => {
let declare = sb.query.is_none() && sb.files.is_none();
if !valid_entity_id(&sb.sub) || !valid_entity_id(&sb.space_id) {
return Err(invalid("subscribe needs a valid sub and space_id"));
}
if declare && sb.schema.as_ref().is_none_or(|s| s.is_empty()) {
return Err(invalid("a subscription needs a query, files or schema"));
}
if declare && (sb.params.is_some() || sb.resume.is_some()) {
return Err(invalid("a schema declaration takes no params or resume"));
}
if sb.query.is_some() && sb.files.is_some() {
return Err(invalid("give a query or files, not both"));
}
match &sb.query {
None | Some(Value::Object(_)) => {}
Some(Value::String(q)) if q == QUERY_ALL => {}
Some(_) => return Err(invalid(r#"query must be an object or "*""#)),
}
check_tables(sb.schema.as_ref())?;
}
ClientFrame::Unsubscribe(u) => {
if !valid_entity_id(&u.sub) {
return Err(invalid("unsubscribe needs a valid sub"));
}
}
ClientFrame::Ping(p) => {
if !valid_entity_id(&p.nonce) {
return Err(invalid("bad ping nonce"));
}
}
}
Ok(f)
}
}