diff --git a/Cargo.lock b/Cargo.lock index dcae9e4..fef7adf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1694,7 +1694,7 @@ dependencies = [ "bitflags 2.10.0", "cexpr", "clang-sys", - "itertools 0.13.0", + "itertools 0.12.1", "proc-macro2", "quote", "regex", @@ -3680,15 +3680,6 @@ dependencies = [ "either", ] -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.14.0" @@ -3749,6 +3740,7 @@ dependencies = [ "rand 0.9.2", "ratatui", "spacetimedb", + "spacetimedb-sdk", "strum 0.27.2", "tracing", "tracing-subscriber", @@ -4676,15 +4668,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "ordered-float" -version = "5.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2c1f9f56e534ac6a9b8a4600bdf0f530fb393b5f393e7b4d03489c3cf0c3f01" -dependencies = [ - "num-traits", -] - [[package]] name = "owned_ttf_parser" version = "0.25.1" @@ -6258,7 +6241,7 @@ dependencies = [ "nix 0.29.0", "num-derive", "num-traits", - "ordered-float 4.6.0", + "ordered-float", "pest", "pest_derive", "phf", @@ -7083,7 +7066,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f2ab60e120fd6eaa68d9567f3226e876684639d22a4219b313ff69ec0ccd5ac" dependencies = [ "log", - "ordered-float 4.6.0", + "ordered-float", "strsim", "thiserror 1.0.69", "wezterm-dynamic-derive", @@ -7229,7 +7212,7 @@ dependencies = [ "naga", "ndk-sys 0.6.0+11769913", "objc", - "ordered-float 5.0.0", + "ordered-float", "parking_lot", "portable-atomic", "portable-atomic-util", diff --git a/Cargo.toml b/Cargo.toml index 4c025c7..c283329 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,15 +3,28 @@ resolver = "3" members = ["jong", "jong-types", "spacetimedb"] [workspace.dependencies] +jong = { version = "0.1.0", path = "jong" } +jong-types = { version = "0.1.0", path = "jong-types" } + +bevy.version = "0.17.3" +bevy.default-features = false + +bevy_ratatui = "0.10.0" +bevy_spacetimedb = "0.7" + +spacetimedb = "1.11.*" +spacetimedb-sdk = "1.11.*" + +strum.version = "0.27.2" +strum.features = ["derive"] + clap = "4.5.54" log = "0.4.29" rand = "0.9.2" -strum = "0.27.2" +ratatui = "0.30.0" tracing = "0.1.44" tracing-subscriber = "0.3.22" -jong = { version = "0.1.0", path = "jong" } -jong-types = { version = "0.1.0", path = "jong-types" } -spacetimedb = "1.11.*" +tui-logger = "0.18.0" [profile.dev] opt-level = 1 @@ -21,3 +34,4 @@ opt-level = 3 [patch.crates-io] bevy_ratatui = { path = "/home/tao/clones/bevy_ratatui" } +# bevy_spacetimedb = { path = "/home/tao/clones/bevy_spacetimedb/bevy_spacetimedb" } diff --git a/devenv.nix b/devenv.nix index f7dde90..57c530b 100644 --- a/devenv.nix +++ b/devenv.nix @@ -44,7 +44,7 @@ # https://devenv.sh/processes/ processes.spacetimedb_start.exec = "spacetime start"; processes.spacetimedb_generate_bindings = { - exec = "spacetime dev --module-bindings-path module_bindings jongline"; + exec = "spacetime dev --module-bindings-path jong/src/stdb jongline --delete-data=always"; }; # https://devenv.sh/services/ diff --git a/jong-types/Cargo.toml b/jong-types/Cargo.toml index 216a8df..a32f1b8 100644 --- a/jong-types/Cargo.toml +++ b/jong-types/Cargo.toml @@ -6,8 +6,6 @@ edition = "2024" [lib] [dependencies] -bevy.version = "0.17.3" -bevy.default-features = false +bevy.workspace = true spacetimedb.workspace = true strum.workspace = true -strum.features = ["derive"] diff --git a/jong/Cargo.toml b/jong/Cargo.toml index bf1e58f..a579d2f 100644 --- a/jong/Cargo.toml +++ b/jong/Cargo.toml @@ -10,23 +10,21 @@ readme = false [lib] [dependencies] -# bevy_ratatui = { git = "https://github.com/kenianbei/bevy_ratatui.git", rev = "e4b022308e08ab360ef89eca8e9f8b1c969e9a56" } -# bevy_ratatui = { path = "/home/tao/clones/bevy_ratatui" } -bevy.features = ["dynamic_linking"] -bevy.version = "0.17.3" -bevy_ratatui = "0.10.0" -bevy_spacetimedb = "0.7" +jong-types.workspace = true + +bevy = { workspace = true, features = ["default", "dynamic_linking"] } +bevy_ratatui.workspace = true +bevy_spacetimedb.workspace = true clap = { workspace = true, features = ["derive"] } -jong-types = { version = "0.1.0", path = "../jong-types" } log = { workspace = true, features = [ "release_max_level_error", "max_level_trace", ] } -rand = { workspace = true } -ratatui = "0.30.0" +rand.workspace = true +ratatui.workspace = true +spacetimedb-sdk.workspace = true spacetimedb.workspace = true -strum = { workspace = true, features = ["derive"] } -tracing = { workspace = true } -tracing-subscriber = { workspace = true } -tui-logger.features = ["tracing-support", "crossterm"] -tui-logger.version = "0.18.0" +strum.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +tui-logger = { workspace = true, features = ["tracing-support", "crossterm"] } diff --git a/jong/src/game.rs b/jong/src/game.rs index adeb5fd..759b0ee 100644 --- a/jong/src/game.rs +++ b/jong/src/game.rs @@ -1,4 +1,5 @@ use bevy::prelude::*; +use bevy_spacetimedb::StdbPlugin; use crate::{ game::{ @@ -7,6 +8,7 @@ use crate::{ round::{TurnState, Wind}, wall::Wall, }, + stdb::DbConnection, tile::{self}, }; @@ -43,6 +45,12 @@ impl GameMessage { pub struct Riichi; impl Plugin for Riichi { fn build(&self, app: &mut App) { + // app.add_plugins( + // StdbPlugin::default() + // .with_uri("http://localhost:3000") + // .with_module_name("jongline") + // .with_run_fn(DbConnection::run_threaded), + // ); app // start stopper .init_state::() diff --git a/jong/src/lib.rs b/jong/src/lib.rs index eaa491e..8e711a7 100644 --- a/jong/src/lib.rs +++ b/jong/src/lib.rs @@ -3,15 +3,14 @@ use bevy::prelude::*; use bevy_spacetimedb::StdbConnection; -// mod jongline_bindings; -// use jongline_bindings::*; - pub mod game; pub mod tile; pub mod yakus; +mod stdb; + trait EnumNextCycle { fn next(&self) -> Self; } -// pub type SpacetimeDb<'a> = Res<'a, StdbConnection>; +pub type SpacetimeDB<'a> = Res<'a, StdbConnection>; diff --git a/jong/src/main.rs b/jong/src/main.rs index 53ed662..b29e0e9 100644 --- a/jong/src/main.rs +++ b/jong/src/main.rs @@ -1,5 +1,5 @@ use bevy::{log::LogPlugin, prelude::*}; -use bevy_spacetimedb::{StdbConnection, StdbPlugin, TableMessages}; +use bevy_spacetimedb::{StdbConnection, StdbPlugin}; use clap::{Parser, Subcommand}; use tracing::Level; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -47,14 +47,6 @@ fn main() { } }; - // app.add_plugins( - // StdbPlugin::default() - // .with_uri("http://localhost:3000") - // .with_module_name("jongline") - // .with_run_fn(DbConnection::run_threaded) - // .add_partial_table(RemoteTables::players, TableMessages::no_update()), - // ); - app.add_plugins(jong::game::Riichi); app.run(); diff --git a/module_bindings/add_player_reducer.rs b/jong/src/stdb/add_player_reducer.rs similarity index 100% rename from module_bindings/add_player_reducer.rs rename to jong/src/stdb/add_player_reducer.rs diff --git a/src/module_bindings/say_hello_reducer.rs b/jong/src/stdb/deal_hands_reducer.rs similarity index 55% rename from src/module_bindings/say_hello_reducer.rs rename to jong/src/stdb/deal_hands_reducer.rs index d326602..cb67ec4 100644 --- a/src/module_bindings/say_hello_reducer.rs +++ b/jong/src/stdb/deal_hands_reducer.rs @@ -6,63 +6,63 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; #[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] #[sats(crate = __lib)] -pub(super) struct SayHelloArgs {} +pub(super) struct DealHandsArgs {} -impl From for super::Reducer { - fn from(args: SayHelloArgs) -> Self { - Self::SayHello +impl From for super::Reducer { + fn from(args: DealHandsArgs) -> Self { + Self::DealHands } } -impl __sdk::InModule for SayHelloArgs { +impl __sdk::InModule for DealHandsArgs { type Module = super::RemoteModule; } -pub struct SayHelloCallbackId(__sdk::CallbackId); +pub struct DealHandsCallbackId(__sdk::CallbackId); #[allow(non_camel_case_types)] -/// Extension trait for access to the reducer `say_hello`. +/// Extension trait for access to the reducer `deal_hands`. /// /// Implemented for [`super::RemoteReducers`]. -pub trait say_hello { - /// Request that the remote module invoke the reducer `say_hello` to run as soon as possible. +pub trait deal_hands { + /// Request that the remote module invoke the reducer `deal_hands` to run as soon as possible. /// /// This method returns immediately, and errors only if we are unable to send the request. /// The reducer will run asynchronously in the future, - /// and its status can be observed by listening for [`Self::on_say_hello`] callbacks. - fn say_hello(&self) -> __sdk::Result<()>; - /// Register a callback to run whenever we are notified of an invocation of the reducer `say_hello`. + /// and its status can be observed by listening for [`Self::on_deal_hands`] callbacks. + fn deal_hands(&self) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `deal_hands`. /// /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] /// to determine the reducer's status. /// - /// The returned [`SayHelloCallbackId`] can be passed to [`Self::remove_on_say_hello`] + /// The returned [`DealHandsCallbackId`] can be passed to [`Self::remove_on_deal_hands`] /// to cancel the callback. - fn on_say_hello( + fn on_deal_hands( &self, callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, - ) -> SayHelloCallbackId; - /// Cancel a callback previously registered by [`Self::on_say_hello`], + ) -> DealHandsCallbackId; + /// Cancel a callback previously registered by [`Self::on_deal_hands`], /// causing it not to run in the future. - fn remove_on_say_hello(&self, callback: SayHelloCallbackId); + fn remove_on_deal_hands(&self, callback: DealHandsCallbackId); } -impl say_hello for super::RemoteReducers { - fn say_hello(&self) -> __sdk::Result<()> { - self.imp.call_reducer("say_hello", SayHelloArgs {}) +impl deal_hands for super::RemoteReducers { + fn deal_hands(&self) -> __sdk::Result<()> { + self.imp.call_reducer("deal_hands", DealHandsArgs {}) } - fn on_say_hello( + fn on_deal_hands( &self, mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, - ) -> SayHelloCallbackId { - SayHelloCallbackId(self.imp.on_reducer( - "say_hello", + ) -> DealHandsCallbackId { + DealHandsCallbackId(self.imp.on_reducer( + "deal_hands", Box::new(move |ctx: &super::ReducerEventContext| { #[allow(irrefutable_let_patterns)] let super::ReducerEventContext { event: __sdk::ReducerEvent { - reducer: super::Reducer::SayHello {}, + reducer: super::Reducer::DealHands {}, .. }, .. @@ -74,27 +74,27 @@ impl say_hello for super::RemoteReducers { }), )) } - fn remove_on_say_hello(&self, callback: SayHelloCallbackId) { - self.imp.remove_on_reducer("say_hello", callback.0) + fn remove_on_deal_hands(&self, callback: DealHandsCallbackId) { + self.imp.remove_on_reducer("deal_hands", callback.0) } } #[allow(non_camel_case_types)] #[doc(hidden)] -/// Extension trait for setting the call-flags for the reducer `say_hello`. +/// Extension trait for setting the call-flags for the reducer `deal_hands`. /// /// Implemented for [`super::SetReducerFlags`]. /// /// This type is currently unstable and may be removed without a major version bump. -pub trait set_flags_for_say_hello { - /// Set the call-reducer flags for the reducer `say_hello` to `flags`. +pub trait set_flags_for_deal_hands { + /// Set the call-reducer flags for the reducer `deal_hands` to `flags`. /// /// This type is currently unstable and may be removed without a major version bump. - fn say_hello(&self, flags: __ws::CallReducerFlags); + fn deal_hands(&self, flags: __ws::CallReducerFlags); } -impl set_flags_for_say_hello for super::SetReducerFlags { - fn say_hello(&self, flags: __ws::CallReducerFlags) { - self.imp.set_call_reducer_flags("say_hello", flags); +impl set_flags_for_deal_hands for super::SetReducerFlags { + fn deal_hands(&self, flags: __ws::CallReducerFlags) { + self.imp.set_call_reducer_flags("deal_hands", flags); } } diff --git a/module_bindings/dragon_type.rs b/jong/src/stdb/dragon_type.rs similarity index 100% rename from module_bindings/dragon_type.rs rename to jong/src/stdb/dragon_type.rs diff --git a/module_bindings/hand_table.rs b/jong/src/stdb/hand_table.rs similarity index 62% rename from module_bindings/hand_table.rs rename to jong/src/stdb/hand_table.rs index d648970..905ed76 100644 --- a/module_bindings/hand_table.rs +++ b/jong/src/stdb/hand_table.rs @@ -82,6 +82,23 @@ impl<'ctx> __sdk::Table for HandTableHandle<'ctx> { #[doc(hidden)] pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { let _table = client_cache.get_or_make_table::("hand"); + _table.add_unique_constraint::<__sdk::Identity>("player_ident", |row| &row.player_ident); +} +pub struct HandUpdateCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::TableWithPrimaryKey for HandTableHandle<'ctx> { + type UpdateCallbackId = HandUpdateCallbackId; + + fn on_update( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static, + ) -> HandUpdateCallbackId { + HandUpdateCallbackId(self.imp.on_update(Box::new(callback))) + } + + fn remove_on_update(&self, callback: HandUpdateCallbackId) { + self.imp.remove_on_update(callback.0) + } } #[doc(hidden)] @@ -94,3 +111,35 @@ pub(super) fn parse_table_update( .into() }) } + +/// Access to the `player_ident` unique index on the table `hand`, +/// which allows point queries on the field of the same name +/// via the [`HandPlayerIdentUnique::find`] method. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.hand().player_ident().find(...)`. +pub struct HandPlayerIdentUnique<'ctx> { + imp: __sdk::UniqueConstraintHandle, + phantom: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +impl<'ctx> HandTableHandle<'ctx> { + /// Get a handle on the `player_ident` unique index on the table `hand`. + pub fn player_ident(&self) -> HandPlayerIdentUnique<'ctx> { + HandPlayerIdentUnique { + imp: self + .imp + .get_unique_constraint::<__sdk::Identity>("player_ident"), + phantom: std::marker::PhantomData, + } + } +} + +impl<'ctx> HandPlayerIdentUnique<'ctx> { + /// Find the subscribed row whose `player_ident` column value is equal to `col_val`, + /// if such a row is present in the client cache. + pub fn find(&self, col_val: &__sdk::Identity) -> Option { + self.imp.find(col_val) + } +} diff --git a/module_bindings/hand_type.rs b/jong/src/stdb/hand_type.rs similarity index 92% rename from module_bindings/hand_type.rs rename to jong/src/stdb/hand_type.rs index 0f0dd43..f12c3c9 100644 --- a/module_bindings/hand_type.rs +++ b/jong/src/stdb/hand_type.rs @@ -9,7 +9,7 @@ use super::tile_type::Tile; #[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] #[sats(crate = __lib)] pub struct Hand { - pub player_id: u32, + pub player_ident: __sdk::Identity, pub tiles: Vec, } diff --git a/jong/src/stdb/insert_wall_reducer.rs b/jong/src/stdb/insert_wall_reducer.rs new file mode 100644 index 0000000..2189dae --- /dev/null +++ b/jong/src/stdb/insert_wall_reducer.rs @@ -0,0 +1,105 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct InsertWallArgs { + pub player_ids: Vec, +} + +impl From for super::Reducer { + fn from(args: InsertWallArgs) -> Self { + Self::InsertWall { + player_ids: args.player_ids, + } + } +} + +impl __sdk::InModule for InsertWallArgs { + type Module = super::RemoteModule; +} + +pub struct InsertWallCallbackId(__sdk::CallbackId); + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `insert_wall`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait insert_wall { + /// Request that the remote module invoke the reducer `insert_wall` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed by listening for [`Self::on_insert_wall`] callbacks. + fn insert_wall(&self, player_ids: Vec) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `insert_wall`. + /// + /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] + /// to determine the reducer's status. + /// + /// The returned [`InsertWallCallbackId`] can be passed to [`Self::remove_on_insert_wall`] + /// to cancel the callback. + fn on_insert_wall( + &self, + callback: impl FnMut(&super::ReducerEventContext, &Vec) + Send + 'static, + ) -> InsertWallCallbackId; + /// Cancel a callback previously registered by [`Self::on_insert_wall`], + /// causing it not to run in the future. + fn remove_on_insert_wall(&self, callback: InsertWallCallbackId); +} + +impl insert_wall for super::RemoteReducers { + fn insert_wall(&self, player_ids: Vec) -> __sdk::Result<()> { + self.imp + .call_reducer("insert_wall", InsertWallArgs { player_ids }) + } + fn on_insert_wall( + &self, + mut callback: impl FnMut(&super::ReducerEventContext, &Vec) + Send + 'static, + ) -> InsertWallCallbackId { + InsertWallCallbackId(self.imp.on_reducer( + "insert_wall", + Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] + let super::ReducerEventContext { + event: + __sdk::ReducerEvent { + reducer: super::Reducer::InsertWall { player_ids }, + .. + }, + .. + } = ctx + else { + unreachable!() + }; + callback(ctx, player_ids) + }), + )) + } + fn remove_on_insert_wall(&self, callback: InsertWallCallbackId) { + self.imp.remove_on_reducer("insert_wall", callback.0) + } +} + +#[allow(non_camel_case_types)] +#[doc(hidden)] +/// Extension trait for setting the call-flags for the reducer `insert_wall`. +/// +/// Implemented for [`super::SetReducerFlags`]. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub trait set_flags_for_insert_wall { + /// Set the call-reducer flags for the reducer `insert_wall` to `flags`. + /// + /// This type is currently unstable and may be removed without a major version bump. + fn insert_wall(&self, flags: __ws::CallReducerFlags); +} + +impl set_flags_for_insert_wall for super::SetReducerFlags { + fn insert_wall(&self, flags: __ws::CallReducerFlags) { + self.imp.set_call_reducer_flags("insert_wall", flags); + } +} diff --git a/jong/src/stdb/join_or_create_lobby_reducer.rs b/jong/src/stdb/join_or_create_lobby_reducer.rs new file mode 100644 index 0000000..594b092 --- /dev/null +++ b/jong/src/stdb/join_or_create_lobby_reducer.rs @@ -0,0 +1,105 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub(super) struct JoinOrCreateLobbyArgs { + pub lobby: Option, +} + +impl From for super::Reducer { + fn from(args: JoinOrCreateLobbyArgs) -> Self { + Self::JoinOrCreateLobby { lobby: args.lobby } + } +} + +impl __sdk::InModule for JoinOrCreateLobbyArgs { + type Module = super::RemoteModule; +} + +pub struct JoinOrCreateLobbyCallbackId(__sdk::CallbackId); + +#[allow(non_camel_case_types)] +/// Extension trait for access to the reducer `join_or_create_lobby`. +/// +/// Implemented for [`super::RemoteReducers`]. +pub trait join_or_create_lobby { + /// Request that the remote module invoke the reducer `join_or_create_lobby` to run as soon as possible. + /// + /// This method returns immediately, and errors only if we are unable to send the request. + /// The reducer will run asynchronously in the future, + /// and its status can be observed by listening for [`Self::on_join_or_create_lobby`] callbacks. + fn join_or_create_lobby(&self, lobby: Option) -> __sdk::Result<()>; + /// Register a callback to run whenever we are notified of an invocation of the reducer `join_or_create_lobby`. + /// + /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] + /// to determine the reducer's status. + /// + /// The returned [`JoinOrCreateLobbyCallbackId`] can be passed to [`Self::remove_on_join_or_create_lobby`] + /// to cancel the callback. + fn on_join_or_create_lobby( + &self, + callback: impl FnMut(&super::ReducerEventContext, &Option) + Send + 'static, + ) -> JoinOrCreateLobbyCallbackId; + /// Cancel a callback previously registered by [`Self::on_join_or_create_lobby`], + /// causing it not to run in the future. + fn remove_on_join_or_create_lobby(&self, callback: JoinOrCreateLobbyCallbackId); +} + +impl join_or_create_lobby for super::RemoteReducers { + fn join_or_create_lobby(&self, lobby: Option) -> __sdk::Result<()> { + self.imp + .call_reducer("join_or_create_lobby", JoinOrCreateLobbyArgs { lobby }) + } + fn on_join_or_create_lobby( + &self, + mut callback: impl FnMut(&super::ReducerEventContext, &Option) + Send + 'static, + ) -> JoinOrCreateLobbyCallbackId { + JoinOrCreateLobbyCallbackId(self.imp.on_reducer( + "join_or_create_lobby", + Box::new(move |ctx: &super::ReducerEventContext| { + #[allow(irrefutable_let_patterns)] + let super::ReducerEventContext { + event: + __sdk::ReducerEvent { + reducer: super::Reducer::JoinOrCreateLobby { lobby }, + .. + }, + .. + } = ctx + else { + unreachable!() + }; + callback(ctx, lobby) + }), + )) + } + fn remove_on_join_or_create_lobby(&self, callback: JoinOrCreateLobbyCallbackId) { + self.imp + .remove_on_reducer("join_or_create_lobby", callback.0) + } +} + +#[allow(non_camel_case_types)] +#[doc(hidden)] +/// Extension trait for setting the call-flags for the reducer `join_or_create_lobby`. +/// +/// Implemented for [`super::SetReducerFlags`]. +/// +/// This type is currently unstable and may be removed without a major version bump. +pub trait set_flags_for_join_or_create_lobby { + /// Set the call-reducer flags for the reducer `join_or_create_lobby` to `flags`. + /// + /// This type is currently unstable and may be removed without a major version bump. + fn join_or_create_lobby(&self, flags: __ws::CallReducerFlags); +} + +impl set_flags_for_join_or_create_lobby for super::SetReducerFlags { + fn join_or_create_lobby(&self, flags: __ws::CallReducerFlags) { + self.imp + .set_call_reducer_flags("join_or_create_lobby", flags); + } +} diff --git a/jong/src/stdb/lobby_table.rs b/jong/src/stdb/lobby_table.rs new file mode 100644 index 0000000..53f11a7 --- /dev/null +++ b/jong/src/stdb/lobby_table.rs @@ -0,0 +1,142 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::lobby_type::Lobby; +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +/// Table handle for the table `lobby`. +/// +/// Obtain a handle from the [`LobbyTableAccess::lobby`] method on [`super::RemoteTables`], +/// like `ctx.db.lobby()`. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.lobby().on_insert(...)`. +pub struct LobbyTableHandle<'ctx> { + imp: __sdk::TableHandle, + ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the table `lobby`. +/// +/// Implemented for [`super::RemoteTables`]. +pub trait LobbyTableAccess { + #[allow(non_snake_case)] + /// Obtain a [`LobbyTableHandle`], which mediates access to the table `lobby`. + fn lobby(&self) -> LobbyTableHandle<'_>; +} + +impl LobbyTableAccess for super::RemoteTables { + fn lobby(&self) -> LobbyTableHandle<'_> { + LobbyTableHandle { + imp: self.imp.get_table::("lobby"), + ctx: std::marker::PhantomData, + } + } +} + +pub struct LobbyInsertCallbackId(__sdk::CallbackId); +pub struct LobbyDeleteCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::Table for LobbyTableHandle<'ctx> { + type Row = Lobby; + type EventContext = super::EventContext; + + fn count(&self) -> u64 { + self.imp.count() + } + fn iter(&self) -> impl Iterator + '_ { + self.imp.iter() + } + + type InsertCallbackId = LobbyInsertCallbackId; + + fn on_insert( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> LobbyInsertCallbackId { + LobbyInsertCallbackId(self.imp.on_insert(Box::new(callback))) + } + + fn remove_on_insert(&self, callback: LobbyInsertCallbackId) { + self.imp.remove_on_insert(callback.0) + } + + type DeleteCallbackId = LobbyDeleteCallbackId; + + fn on_delete( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> LobbyDeleteCallbackId { + LobbyDeleteCallbackId(self.imp.on_delete(Box::new(callback))) + } + + fn remove_on_delete(&self, callback: LobbyDeleteCallbackId) { + self.imp.remove_on_delete(callback.0) + } +} + +#[doc(hidden)] +pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { + let _table = client_cache.get_or_make_table::("lobby"); + _table.add_unique_constraint::("id", |row| &row.id); +} +pub struct LobbyUpdateCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::TableWithPrimaryKey for LobbyTableHandle<'ctx> { + type UpdateCallbackId = LobbyUpdateCallbackId; + + fn on_update( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static, + ) -> LobbyUpdateCallbackId { + LobbyUpdateCallbackId(self.imp.on_update(Box::new(callback))) + } + + fn remove_on_update(&self, callback: LobbyUpdateCallbackId) { + self.imp.remove_on_update(callback.0) + } +} + +#[doc(hidden)] +pub(super) fn parse_table_update( + raw_updates: __ws::TableUpdate<__ws::BsatnFormat>, +) -> __sdk::Result<__sdk::TableUpdate> { + __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { + __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") + .with_cause(e) + .into() + }) +} + +/// Access to the `id` unique index on the table `lobby`, +/// which allows point queries on the field of the same name +/// via the [`LobbyIdUnique::find`] method. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.lobby().id().find(...)`. +pub struct LobbyIdUnique<'ctx> { + imp: __sdk::UniqueConstraintHandle, + phantom: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +impl<'ctx> LobbyTableHandle<'ctx> { + /// Get a handle on the `id` unique index on the table `lobby`. + pub fn id(&self) -> LobbyIdUnique<'ctx> { + LobbyIdUnique { + imp: self.imp.get_unique_constraint::("id"), + phantom: std::marker::PhantomData, + } + } +} + +impl<'ctx> LobbyIdUnique<'ctx> { + /// Find the subscribed row whose `id` column value is equal to `col_val`, + /// if such a row is present in the client cache. + pub fn find(&self, col_val: &u32) -> Option { + self.imp.find(col_val) + } +} diff --git a/src/module_bindings/person_type.rs b/jong/src/stdb/lobby_type.rs similarity index 79% rename from src/module_bindings/person_type.rs rename to jong/src/stdb/lobby_type.rs index 56436ae..fcb5045 100644 --- a/src/module_bindings/person_type.rs +++ b/jong/src/stdb/lobby_type.rs @@ -6,10 +6,11 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; #[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] #[sats(crate = __lib)] -pub struct Person { - pub name: String, +pub struct Lobby { + pub id: u32, + pub host: __sdk::Identity, } -impl __sdk::InModule for Person { +impl __sdk::InModule for Lobby { type Module = super::RemoteModule; } diff --git a/module_bindings/mod.rs b/jong/src/stdb/mod.rs similarity index 91% rename from module_bindings/mod.rs rename to jong/src/stdb/mod.rs index 664e7d9..e6d9a19 100644 --- a/module_bindings/mod.rs +++ b/jong/src/stdb/mod.rs @@ -7,11 +7,18 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; pub mod add_player_reducer; +pub mod deal_hands_reducer; pub mod dragon_type; pub mod hand_table; pub mod hand_type; +pub mod insert_wall_reducer; +pub mod join_or_create_lobby_reducer; +pub mod lobby_table; +pub mod lobby_type; pub mod player_table; pub mod player_type; +pub mod pond_table; +pub mod pond_type; pub mod rank_type; pub mod set_name_reducer; pub mod shuffle_wall_reducer; @@ -23,11 +30,20 @@ pub mod wall_type; pub mod wind_type; pub use add_player_reducer::{add_player, set_flags_for_add_player, AddPlayerCallbackId}; +pub use deal_hands_reducer::{deal_hands, set_flags_for_deal_hands, DealHandsCallbackId}; pub use dragon_type::Dragon; pub use hand_table::*; pub use hand_type::Hand; +pub use insert_wall_reducer::{insert_wall, set_flags_for_insert_wall, InsertWallCallbackId}; +pub use join_or_create_lobby_reducer::{ + join_or_create_lobby, set_flags_for_join_or_create_lobby, JoinOrCreateLobbyCallbackId, +}; +pub use lobby_table::*; +pub use lobby_type::Lobby; pub use player_table::*; pub use player_type::Player; +pub use pond_table::*; +pub use pond_type::Pond; pub use rank_type::Rank; pub use set_name_reducer::{set_flags_for_set_name, set_name, SetNameCallbackId}; pub use shuffle_wall_reducer::{set_flags_for_shuffle_wall, shuffle_wall, ShuffleWallCallbackId}; @@ -47,6 +63,9 @@ pub use wind_type::Wind; pub enum Reducer { AddPlayer { name: Option }, + DealHands, + InsertWall { player_ids: Vec }, + JoinOrCreateLobby { lobby: Option }, SetName { name: String }, ShuffleWall, SortHand, @@ -60,6 +79,9 @@ impl __sdk::Reducer for Reducer { fn reducer_name(&self) -> &'static str { match self { Reducer::AddPlayer { .. } => "add_player", + Reducer::DealHands => "deal_hands", + Reducer::InsertWall { .. } => "insert_wall", + Reducer::JoinOrCreateLobby { .. } => "join_or_create_lobby", Reducer::SetName { .. } => "set_name", Reducer::ShuffleWall => "shuffle_wall", Reducer::SortHand => "sort_hand", @@ -78,6 +100,24 @@ impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer { )? .into(), ), + "deal_hands" => Ok( + __sdk::parse_reducer_args::( + "deal_hands", + &value.args, + )? + .into(), + ), + "insert_wall" => Ok( + __sdk::parse_reducer_args::( + "insert_wall", + &value.args, + )? + .into(), + ), + "join_or_create_lobby" => Ok(__sdk::parse_reducer_args::< + join_or_create_lobby_reducer::JoinOrCreateLobbyArgs, + >("join_or_create_lobby", &value.args)? + .into()), "set_name" => Ok(__sdk::parse_reducer_args::( "set_name", &value.args, @@ -112,7 +152,9 @@ impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer { #[doc(hidden)] pub struct DbUpdate { hand: __sdk::TableUpdate, + lobby: __sdk::TableUpdate, player: __sdk::TableUpdate, + pond: __sdk::TableUpdate, wall: __sdk::TableUpdate, } @@ -125,9 +167,15 @@ impl TryFrom<__ws::DatabaseUpdate<__ws::BsatnFormat>> for DbUpdate { "hand" => db_update .hand .append(hand_table::parse_table_update(table_update)?), + "lobby" => db_update + .lobby + .append(lobby_table::parse_table_update(table_update)?), "player" => db_update .player .append(player_table::parse_table_update(table_update)?), + "pond" => db_update + .pond + .append(pond_table::parse_table_update(table_update)?), "wall" => db_update .wall .append(wall_table::parse_table_update(table_update)?), @@ -157,11 +205,19 @@ impl __sdk::DbUpdate for DbUpdate { ) -> AppliedDiff<'_> { let mut diff = AppliedDiff::default(); - diff.hand = cache.apply_diff_to_table::("hand", &self.hand); + diff.hand = cache + .apply_diff_to_table::("hand", &self.hand) + .with_updates_by_pk(|row| &row.player_ident); + diff.lobby = cache + .apply_diff_to_table::("lobby", &self.lobby) + .with_updates_by_pk(|row| &row.id); diff.player = cache .apply_diff_to_table::("player", &self.player) .with_updates_by_pk(|row| &row.identity); - diff.wall = cache.apply_diff_to_table::("wall", &self.wall); + diff.pond = cache.apply_diff_to_table::("pond", &self.pond); + diff.wall = cache + .apply_diff_to_table::("wall", &self.wall) + .with_updates_by_pk(|row| &row.id); diff } @@ -172,7 +228,9 @@ impl __sdk::DbUpdate for DbUpdate { #[doc(hidden)] pub struct AppliedDiff<'r> { hand: __sdk::TableAppliedDiff<'r, Hand>, + lobby: __sdk::TableAppliedDiff<'r, Lobby>, player: __sdk::TableAppliedDiff<'r, Player>, + pond: __sdk::TableAppliedDiff<'r, Pond>, wall: __sdk::TableAppliedDiff<'r, Wall>, __unused: std::marker::PhantomData<&'r ()>, } @@ -188,7 +246,9 @@ impl<'r> __sdk::AppliedDiff<'r> for AppliedDiff<'r> { callbacks: &mut __sdk::DbCallbacks, ) { callbacks.invoke_table_row_callbacks::("hand", &self.hand, event); + callbacks.invoke_table_row_callbacks::("lobby", &self.lobby, event); callbacks.invoke_table_row_callbacks::("player", &self.player, event); + callbacks.invoke_table_row_callbacks::("pond", &self.pond, event); callbacks.invoke_table_row_callbacks::("wall", &self.wall, event); } } @@ -910,7 +970,9 @@ impl __sdk::SpacetimeModule for RemoteModule { fn register_tables(client_cache: &mut __sdk::ClientCache) { hand_table::register_table(client_cache); + lobby_table::register_table(client_cache); player_table::register_table(client_cache); + pond_table::register_table(client_cache); wall_table::register_table(client_cache); } } diff --git a/module_bindings/player_table.rs b/jong/src/stdb/player_table.rs similarity index 100% rename from module_bindings/player_table.rs rename to jong/src/stdb/player_table.rs diff --git a/module_bindings/player_type.rs b/jong/src/stdb/player_type.rs similarity index 93% rename from module_bindings/player_type.rs rename to jong/src/stdb/player_type.rs index 59fa7f6..266df28 100644 --- a/module_bindings/player_type.rs +++ b/jong/src/stdb/player_type.rs @@ -8,9 +8,8 @@ use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; #[sats(crate = __lib)] pub struct Player { pub identity: __sdk::Identity, - pub id: u32, pub name: Option, - pub host: bool, + pub lobby_id: u32, } impl __sdk::InModule for Player { diff --git a/jong/src/stdb/pond_table.rs b/jong/src/stdb/pond_table.rs new file mode 100644 index 0000000..0230d77 --- /dev/null +++ b/jong/src/stdb/pond_table.rs @@ -0,0 +1,96 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use super::pond_type::Pond; +use super::tile_type::Tile; +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +/// Table handle for the table `pond`. +/// +/// Obtain a handle from the [`PondTableAccess::pond`] method on [`super::RemoteTables`], +/// like `ctx.db.pond()`. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.pond().on_insert(...)`. +pub struct PondTableHandle<'ctx> { + imp: __sdk::TableHandle, + ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +#[allow(non_camel_case_types)] +/// Extension trait for access to the table `pond`. +/// +/// Implemented for [`super::RemoteTables`]. +pub trait PondTableAccess { + #[allow(non_snake_case)] + /// Obtain a [`PondTableHandle`], which mediates access to the table `pond`. + fn pond(&self) -> PondTableHandle<'_>; +} + +impl PondTableAccess for super::RemoteTables { + fn pond(&self) -> PondTableHandle<'_> { + PondTableHandle { + imp: self.imp.get_table::("pond"), + ctx: std::marker::PhantomData, + } + } +} + +pub struct PondInsertCallbackId(__sdk::CallbackId); +pub struct PondDeleteCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::Table for PondTableHandle<'ctx> { + type Row = Pond; + type EventContext = super::EventContext; + + fn count(&self) -> u64 { + self.imp.count() + } + fn iter(&self) -> impl Iterator + '_ { + self.imp.iter() + } + + type InsertCallbackId = PondInsertCallbackId; + + fn on_insert( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> PondInsertCallbackId { + PondInsertCallbackId(self.imp.on_insert(Box::new(callback))) + } + + fn remove_on_insert(&self, callback: PondInsertCallbackId) { + self.imp.remove_on_insert(callback.0) + } + + type DeleteCallbackId = PondDeleteCallbackId; + + fn on_delete( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, + ) -> PondDeleteCallbackId { + PondDeleteCallbackId(self.imp.on_delete(Box::new(callback))) + } + + fn remove_on_delete(&self, callback: PondDeleteCallbackId) { + self.imp.remove_on_delete(callback.0) + } +} + +#[doc(hidden)] +pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { + let _table = client_cache.get_or_make_table::("pond"); +} + +#[doc(hidden)] +pub(super) fn parse_table_update( + raw_updates: __ws::TableUpdate<__ws::BsatnFormat>, +) -> __sdk::Result<__sdk::TableUpdate> { + __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { + __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") + .with_cause(e) + .into() + }) +} diff --git a/jong/src/stdb/pond_type.rs b/jong/src/stdb/pond_type.rs new file mode 100644 index 0000000..3cfbd3e --- /dev/null +++ b/jong/src/stdb/pond_type.rs @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +#![allow(unused, clippy::all)] +use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; + +use super::tile_type::Tile; + +#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] +#[sats(crate = __lib)] +pub struct Pond { + pub tiles: Vec, +} + +impl __sdk::InModule for Pond { + type Module = super::RemoteModule; +} diff --git a/module_bindings/rank_type.rs b/jong/src/stdb/rank_type.rs similarity index 100% rename from module_bindings/rank_type.rs rename to jong/src/stdb/rank_type.rs diff --git a/module_bindings/set_name_reducer.rs b/jong/src/stdb/set_name_reducer.rs similarity index 100% rename from module_bindings/set_name_reducer.rs rename to jong/src/stdb/set_name_reducer.rs diff --git a/module_bindings/shuffle_wall_reducer.rs b/jong/src/stdb/shuffle_wall_reducer.rs similarity index 100% rename from module_bindings/shuffle_wall_reducer.rs rename to jong/src/stdb/shuffle_wall_reducer.rs diff --git a/module_bindings/sort_hand_reducer.rs b/jong/src/stdb/sort_hand_reducer.rs similarity index 100% rename from module_bindings/sort_hand_reducer.rs rename to jong/src/stdb/sort_hand_reducer.rs diff --git a/module_bindings/suit_type.rs b/jong/src/stdb/suit_type.rs similarity index 100% rename from module_bindings/suit_type.rs rename to jong/src/stdb/suit_type.rs diff --git a/module_bindings/tile_type.rs b/jong/src/stdb/tile_type.rs similarity index 100% rename from module_bindings/tile_type.rs rename to jong/src/stdb/tile_type.rs diff --git a/module_bindings/wall_table.rs b/jong/src/stdb/wall_table.rs similarity index 64% rename from module_bindings/wall_table.rs rename to jong/src/stdb/wall_table.rs index bd24f06..79cd408 100644 --- a/module_bindings/wall_table.rs +++ b/jong/src/stdb/wall_table.rs @@ -82,6 +82,23 @@ impl<'ctx> __sdk::Table for WallTableHandle<'ctx> { #[doc(hidden)] pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { let _table = client_cache.get_or_make_table::("wall"); + _table.add_unique_constraint::("id", |row| &row.id); +} +pub struct WallUpdateCallbackId(__sdk::CallbackId); + +impl<'ctx> __sdk::TableWithPrimaryKey for WallTableHandle<'ctx> { + type UpdateCallbackId = WallUpdateCallbackId; + + fn on_update( + &self, + callback: impl FnMut(&Self::EventContext, &Self::Row, &Self::Row) + Send + 'static, + ) -> WallUpdateCallbackId { + WallUpdateCallbackId(self.imp.on_update(Box::new(callback))) + } + + fn remove_on_update(&self, callback: WallUpdateCallbackId) { + self.imp.remove_on_update(callback.0) + } } #[doc(hidden)] @@ -94,3 +111,33 @@ pub(super) fn parse_table_update( .into() }) } + +/// Access to the `id` unique index on the table `wall`, +/// which allows point queries on the field of the same name +/// via the [`WallIdUnique::find`] method. +/// +/// Users are encouraged not to explicitly reference this type, +/// but to directly chain method calls, +/// like `ctx.db.wall().id().find(...)`. +pub struct WallIdUnique<'ctx> { + imp: __sdk::UniqueConstraintHandle, + phantom: std::marker::PhantomData<&'ctx super::RemoteTables>, +} + +impl<'ctx> WallTableHandle<'ctx> { + /// Get a handle on the `id` unique index on the table `wall`. + pub fn id(&self) -> WallIdUnique<'ctx> { + WallIdUnique { + imp: self.imp.get_unique_constraint::("id"), + phantom: std::marker::PhantomData, + } + } +} + +impl<'ctx> WallIdUnique<'ctx> { + /// Find the subscribed row whose `id` column value is equal to `col_val`, + /// if such a row is present in the client cache. + pub fn find(&self, col_val: &u32) -> Option { + self.imp.find(col_val) + } +} diff --git a/module_bindings/wall_type.rs b/jong/src/stdb/wall_type.rs similarity index 96% rename from module_bindings/wall_type.rs rename to jong/src/stdb/wall_type.rs index f50341c..88a1e5f 100644 --- a/module_bindings/wall_type.rs +++ b/jong/src/stdb/wall_type.rs @@ -9,6 +9,7 @@ use super::tile_type::Tile; #[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] #[sats(crate = __lib)] pub struct Wall { + pub id: u32, pub tiles: Vec, } diff --git a/module_bindings/wind_type.rs b/jong/src/stdb/wind_type.rs similarity index 100% rename from module_bindings/wind_type.rs rename to jong/src/stdb/wind_type.rs diff --git a/spacetimedb/src/lib.rs b/spacetimedb/src/lib.rs index 134a022..8b21eb3 100644 --- a/spacetimedb/src/lib.rs +++ b/spacetimedb/src/lib.rs @@ -2,29 +2,55 @@ use spacetimedb::{rand::seq::SliceRandom, reducer, table, Identity, ReducerConte use jong_types::*; -#[table(name = player, public)] +#[table(name = player)] pub struct Player { #[primary_key] identity: Identity, + + name: Option, + lobby_id: u32, +} + +#[table(name = lobby, public)] +pub struct Lobby { + #[primary_key] #[auto_inc] id: u32, - name: Option, - host: bool, + + host: Identity, } #[table(name = wall)] pub struct Wall { + #[primary_key] + #[auto_inc] + id: u32, + tiles: Vec, } #[table(name = hand)] pub struct Hand { - player_id: u32, + #[primary_key] + player_ident: Identity, + + tiles: Vec, +} + +#[table(name = pond, public)] +pub struct Pond { tiles: Vec, } #[reducer] -pub fn add_player(ctx: &ReducerContext, name: Option) {} +pub fn add_player(ctx: &ReducerContext, name: Option) { + let identity = ctx.identity(); + ctx.db.player().insert(Player { + identity, + name, + lobby_id: 0, + }); +} #[reducer] pub fn set_name(ctx: &ReducerContext, name: String) -> Result<(), String> { @@ -42,12 +68,27 @@ pub fn set_name(ctx: &ReducerContext, name: String) -> Result<(), String> { } } +#[reducer] +pub fn join_or_create_lobby(ctx: &ReducerContext, lobby: Option) -> Result<(), String> { + let player = ctx.db.player().identity().find(ctx.sender).unwrap(); + + todo!() +} + +#[reducer] +pub fn insert_wall(ctx: &ReducerContext, player_ids: Vec) { + let tiles: Vec = tiles(); + ctx.db.wall().insert(Wall { id: 0, tiles }); +} + #[reducer] pub fn shuffle_wall(ctx: &ReducerContext) { - let mut rng = ctx.rng(); - let mut tiles: Vec = tiles(); - tiles.shuffle(&mut rng); - ctx.db.wall().insert(Wall { tiles }); + todo!() +} + +#[reducer] +pub fn deal_hands(ctx: &ReducerContext) { + todo!() } #[reducer] diff --git a/src/module_bindings/add_reducer.rs b/src/module_bindings/add_reducer.rs deleted file mode 100644 index 5bfecc3..0000000 --- a/src/module_bindings/add_reducer.rs +++ /dev/null @@ -1,102 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -#![allow(unused, clippy::all)] -use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; - -#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] -#[sats(crate = __lib)] -pub(super) struct AddArgs { - pub name: String, -} - -impl From for super::Reducer { - fn from(args: AddArgs) -> Self { - Self::Add { name: args.name } - } -} - -impl __sdk::InModule for AddArgs { - type Module = super::RemoteModule; -} - -pub struct AddCallbackId(__sdk::CallbackId); - -#[allow(non_camel_case_types)] -/// Extension trait for access to the reducer `add`. -/// -/// Implemented for [`super::RemoteReducers`]. -pub trait add { - /// Request that the remote module invoke the reducer `add` to run as soon as possible. - /// - /// This method returns immediately, and errors only if we are unable to send the request. - /// The reducer will run asynchronously in the future, - /// and its status can be observed by listening for [`Self::on_add`] callbacks. - fn add(&self, name: String) -> __sdk::Result<()>; - /// Register a callback to run whenever we are notified of an invocation of the reducer `add`. - /// - /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] - /// to determine the reducer's status. - /// - /// The returned [`AddCallbackId`] can be passed to [`Self::remove_on_add`] - /// to cancel the callback. - fn on_add( - &self, - callback: impl FnMut(&super::ReducerEventContext, &String) + Send + 'static, - ) -> AddCallbackId; - /// Cancel a callback previously registered by [`Self::on_add`], - /// causing it not to run in the future. - fn remove_on_add(&self, callback: AddCallbackId); -} - -impl add for super::RemoteReducers { - fn add(&self, name: String) -> __sdk::Result<()> { - self.imp.call_reducer("add", AddArgs { name }) - } - fn on_add( - &self, - mut callback: impl FnMut(&super::ReducerEventContext, &String) + Send + 'static, - ) -> AddCallbackId { - AddCallbackId(self.imp.on_reducer( - "add", - Box::new(move |ctx: &super::ReducerEventContext| { - #[allow(irrefutable_let_patterns)] - let super::ReducerEventContext { - event: - __sdk::ReducerEvent { - reducer: super::Reducer::Add { name }, - .. - }, - .. - } = ctx - else { - unreachable!() - }; - callback(ctx, name) - }), - )) - } - fn remove_on_add(&self, callback: AddCallbackId) { - self.imp.remove_on_reducer("add", callback.0) - } -} - -#[allow(non_camel_case_types)] -#[doc(hidden)] -/// Extension trait for setting the call-flags for the reducer `add`. -/// -/// Implemented for [`super::SetReducerFlags`]. -/// -/// This type is currently unstable and may be removed without a major version bump. -pub trait set_flags_for_add { - /// Set the call-reducer flags for the reducer `add` to `flags`. - /// - /// This type is currently unstable and may be removed without a major version bump. - fn add(&self, flags: __ws::CallReducerFlags); -} - -impl set_flags_for_add for super::SetReducerFlags { - fn add(&self, flags: __ws::CallReducerFlags) { - self.imp.set_call_reducer_flags("add", flags); - } -} diff --git a/src/module_bindings/identity_connected_reducer.rs b/src/module_bindings/identity_connected_reducer.rs deleted file mode 100644 index 2eaaab0..0000000 --- a/src/module_bindings/identity_connected_reducer.rs +++ /dev/null @@ -1,101 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -#![allow(unused, clippy::all)] -use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; - -#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] -#[sats(crate = __lib)] -pub(super) struct IdentityConnectedArgs {} - -impl From for super::Reducer { - fn from(args: IdentityConnectedArgs) -> Self { - Self::IdentityConnected - } -} - -impl __sdk::InModule for IdentityConnectedArgs { - type Module = super::RemoteModule; -} - -pub struct IdentityConnectedCallbackId(__sdk::CallbackId); - -#[allow(non_camel_case_types)] -/// Extension trait for access to the reducer `identity_connected`. -/// -/// Implemented for [`super::RemoteReducers`]. -pub trait identity_connected { - /// Request that the remote module invoke the reducer `identity_connected` to run as soon as possible. - /// - /// This method returns immediately, and errors only if we are unable to send the request. - /// The reducer will run asynchronously in the future, - /// and its status can be observed by listening for [`Self::on_identity_connected`] callbacks. - fn identity_connected(&self) -> __sdk::Result<()>; - /// Register a callback to run whenever we are notified of an invocation of the reducer `identity_connected`. - /// - /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] - /// to determine the reducer's status. - /// - /// The returned [`IdentityConnectedCallbackId`] can be passed to [`Self::remove_on_identity_connected`] - /// to cancel the callback. - fn on_identity_connected( - &self, - callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, - ) -> IdentityConnectedCallbackId; - /// Cancel a callback previously registered by [`Self::on_identity_connected`], - /// causing it not to run in the future. - fn remove_on_identity_connected(&self, callback: IdentityConnectedCallbackId); -} - -impl identity_connected for super::RemoteReducers { - fn identity_connected(&self) -> __sdk::Result<()> { - self.imp - .call_reducer("identity_connected", IdentityConnectedArgs {}) - } - fn on_identity_connected( - &self, - mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, - ) -> IdentityConnectedCallbackId { - IdentityConnectedCallbackId(self.imp.on_reducer( - "identity_connected", - Box::new(move |ctx: &super::ReducerEventContext| { - #[allow(irrefutable_let_patterns)] - let super::ReducerEventContext { - event: - __sdk::ReducerEvent { - reducer: super::Reducer::IdentityConnected {}, - .. - }, - .. - } = ctx - else { - unreachable!() - }; - callback(ctx) - }), - )) - } - fn remove_on_identity_connected(&self, callback: IdentityConnectedCallbackId) { - self.imp.remove_on_reducer("identity_connected", callback.0) - } -} - -#[allow(non_camel_case_types)] -#[doc(hidden)] -/// Extension trait for setting the call-flags for the reducer `identity_connected`. -/// -/// Implemented for [`super::SetReducerFlags`]. -/// -/// This type is currently unstable and may be removed without a major version bump. -pub trait set_flags_for_identity_connected { - /// Set the call-reducer flags for the reducer `identity_connected` to `flags`. - /// - /// This type is currently unstable and may be removed without a major version bump. - fn identity_connected(&self, flags: __ws::CallReducerFlags); -} - -impl set_flags_for_identity_connected for super::SetReducerFlags { - fn identity_connected(&self, flags: __ws::CallReducerFlags) { - self.imp.set_call_reducer_flags("identity_connected", flags); - } -} diff --git a/src/module_bindings/identity_disconnected_reducer.rs b/src/module_bindings/identity_disconnected_reducer.rs deleted file mode 100644 index c2892ed..0000000 --- a/src/module_bindings/identity_disconnected_reducer.rs +++ /dev/null @@ -1,103 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -#![allow(unused, clippy::all)] -use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; - -#[derive(__lib::ser::Serialize, __lib::de::Deserialize, Clone, PartialEq, Debug)] -#[sats(crate = __lib)] -pub(super) struct IdentityDisconnectedArgs {} - -impl From for super::Reducer { - fn from(args: IdentityDisconnectedArgs) -> Self { - Self::IdentityDisconnected - } -} - -impl __sdk::InModule for IdentityDisconnectedArgs { - type Module = super::RemoteModule; -} - -pub struct IdentityDisconnectedCallbackId(__sdk::CallbackId); - -#[allow(non_camel_case_types)] -/// Extension trait for access to the reducer `identity_disconnected`. -/// -/// Implemented for [`super::RemoteReducers`]. -pub trait identity_disconnected { - /// Request that the remote module invoke the reducer `identity_disconnected` to run as soon as possible. - /// - /// This method returns immediately, and errors only if we are unable to send the request. - /// The reducer will run asynchronously in the future, - /// and its status can be observed by listening for [`Self::on_identity_disconnected`] callbacks. - fn identity_disconnected(&self) -> __sdk::Result<()>; - /// Register a callback to run whenever we are notified of an invocation of the reducer `identity_disconnected`. - /// - /// Callbacks should inspect the [`__sdk::ReducerEvent`] contained in the [`super::ReducerEventContext`] - /// to determine the reducer's status. - /// - /// The returned [`IdentityDisconnectedCallbackId`] can be passed to [`Self::remove_on_identity_disconnected`] - /// to cancel the callback. - fn on_identity_disconnected( - &self, - callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, - ) -> IdentityDisconnectedCallbackId; - /// Cancel a callback previously registered by [`Self::on_identity_disconnected`], - /// causing it not to run in the future. - fn remove_on_identity_disconnected(&self, callback: IdentityDisconnectedCallbackId); -} - -impl identity_disconnected for super::RemoteReducers { - fn identity_disconnected(&self) -> __sdk::Result<()> { - self.imp - .call_reducer("identity_disconnected", IdentityDisconnectedArgs {}) - } - fn on_identity_disconnected( - &self, - mut callback: impl FnMut(&super::ReducerEventContext) + Send + 'static, - ) -> IdentityDisconnectedCallbackId { - IdentityDisconnectedCallbackId(self.imp.on_reducer( - "identity_disconnected", - Box::new(move |ctx: &super::ReducerEventContext| { - #[allow(irrefutable_let_patterns)] - let super::ReducerEventContext { - event: - __sdk::ReducerEvent { - reducer: super::Reducer::IdentityDisconnected {}, - .. - }, - .. - } = ctx - else { - unreachable!() - }; - callback(ctx) - }), - )) - } - fn remove_on_identity_disconnected(&self, callback: IdentityDisconnectedCallbackId) { - self.imp - .remove_on_reducer("identity_disconnected", callback.0) - } -} - -#[allow(non_camel_case_types)] -#[doc(hidden)] -/// Extension trait for setting the call-flags for the reducer `identity_disconnected`. -/// -/// Implemented for [`super::SetReducerFlags`]. -/// -/// This type is currently unstable and may be removed without a major version bump. -pub trait set_flags_for_identity_disconnected { - /// Set the call-reducer flags for the reducer `identity_disconnected` to `flags`. - /// - /// This type is currently unstable and may be removed without a major version bump. - fn identity_disconnected(&self, flags: __ws::CallReducerFlags); -} - -impl set_flags_for_identity_disconnected for super::SetReducerFlags { - fn identity_disconnected(&self, flags: __ws::CallReducerFlags) { - self.imp - .set_call_reducer_flags("identity_disconnected", flags); - } -} diff --git a/src/module_bindings/mod.rs b/src/module_bindings/mod.rs deleted file mode 100644 index e89f725..0000000 --- a/src/module_bindings/mod.rs +++ /dev/null @@ -1,876 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -// This was generated using spacetimedb cli version 1.11.3 (commit 02449737ca3b29e7e39679fccbef541a50f32094). - -#![allow(unused, clippy::all)] -use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; - -pub mod add_reducer; -pub mod identity_connected_reducer; -pub mod identity_disconnected_reducer; -pub mod person_table; -pub mod person_type; -pub mod say_hello_reducer; - -pub use add_reducer::{add, set_flags_for_add, AddCallbackId}; -pub use identity_connected_reducer::{ - identity_connected, set_flags_for_identity_connected, IdentityConnectedCallbackId, -}; -pub use identity_disconnected_reducer::{ - identity_disconnected, set_flags_for_identity_disconnected, IdentityDisconnectedCallbackId, -}; -pub use person_table::*; -pub use person_type::Person; -pub use say_hello_reducer::{say_hello, set_flags_for_say_hello, SayHelloCallbackId}; - -#[derive(Clone, PartialEq, Debug)] - -/// One of the reducers defined by this module. -/// -/// Contained within a [`__sdk::ReducerEvent`] in [`EventContext`]s for reducer events -/// to indicate which reducer caused the event. - -pub enum Reducer { - Add { name: String }, - IdentityConnected, - IdentityDisconnected, - SayHello, -} - -impl __sdk::InModule for Reducer { - type Module = RemoteModule; -} - -impl __sdk::Reducer for Reducer { - fn reducer_name(&self) -> &'static str { - match self { - Reducer::Add { .. } => "add", - Reducer::IdentityConnected => "identity_connected", - Reducer::IdentityDisconnected => "identity_disconnected", - Reducer::SayHello => "say_hello", - _ => unreachable!(), - } - } -} -impl TryFrom<__ws::ReducerCallInfo<__ws::BsatnFormat>> for Reducer { - type Error = __sdk::Error; - fn try_from(value: __ws::ReducerCallInfo<__ws::BsatnFormat>) -> __sdk::Result { - match &value.reducer_name[..] { - "add" => { - Ok(__sdk::parse_reducer_args::("add", &value.args)?.into()) - } - "identity_connected" => Ok(__sdk::parse_reducer_args::< - identity_connected_reducer::IdentityConnectedArgs, - >("identity_connected", &value.args)? - .into()), - "identity_disconnected" => Ok(__sdk::parse_reducer_args::< - identity_disconnected_reducer::IdentityDisconnectedArgs, - >("identity_disconnected", &value.args)? - .into()), - "say_hello" => Ok( - __sdk::parse_reducer_args::( - "say_hello", - &value.args, - )? - .into(), - ), - unknown => { - Err( - __sdk::InternalError::unknown_name("reducer", unknown, "ReducerCallInfo") - .into(), - ) - } - } - } -} - -#[derive(Default)] -#[allow(non_snake_case)] -#[doc(hidden)] -pub struct DbUpdate { - person: __sdk::TableUpdate, -} - -impl TryFrom<__ws::DatabaseUpdate<__ws::BsatnFormat>> for DbUpdate { - type Error = __sdk::Error; - fn try_from(raw: __ws::DatabaseUpdate<__ws::BsatnFormat>) -> Result { - let mut db_update = DbUpdate::default(); - for table_update in raw.tables { - match &table_update.table_name[..] { - "person" => db_update - .person - .append(person_table::parse_table_update(table_update)?), - - unknown => { - return Err(__sdk::InternalError::unknown_name( - "table", - unknown, - "DatabaseUpdate", - ) - .into()); - } - } - } - Ok(db_update) - } -} - -impl __sdk::InModule for DbUpdate { - type Module = RemoteModule; -} - -impl __sdk::DbUpdate for DbUpdate { - fn apply_to_client_cache( - &self, - cache: &mut __sdk::ClientCache, - ) -> AppliedDiff<'_> { - let mut diff = AppliedDiff::default(); - - diff.person = cache.apply_diff_to_table::("person", &self.person); - - diff - } -} - -#[derive(Default)] -#[allow(non_snake_case)] -#[doc(hidden)] -pub struct AppliedDiff<'r> { - person: __sdk::TableAppliedDiff<'r, Person>, - __unused: std::marker::PhantomData<&'r ()>, -} - -impl __sdk::InModule for AppliedDiff<'_> { - type Module = RemoteModule; -} - -impl<'r> __sdk::AppliedDiff<'r> for AppliedDiff<'r> { - fn invoke_row_callbacks( - &self, - event: &EventContext, - callbacks: &mut __sdk::DbCallbacks, - ) { - callbacks.invoke_table_row_callbacks::("person", &self.person, event); - } -} - -#[doc(hidden)] -pub struct RemoteModule; - -impl __sdk::InModule for RemoteModule { - type Module = Self; -} - -/// The `reducers` field of [`EventContext`] and [`DbConnection`], -/// with methods provided by extension traits for each reducer defined by the module. -pub struct RemoteReducers { - imp: __sdk::DbContextImpl, -} - -impl __sdk::InModule for RemoteReducers { - type Module = RemoteModule; -} - -/// The `procedures` field of [`DbConnection`] and other [`DbContext`] types, -/// with methods provided by extension traits for each procedure defined by the module. -pub struct RemoteProcedures { - imp: __sdk::DbContextImpl, -} - -impl __sdk::InModule for RemoteProcedures { - type Module = RemoteModule; -} - -#[doc(hidden)] -/// The `set_reducer_flags` field of [`DbConnection`], -/// with methods provided by extension traits for each reducer defined by the module. -/// Each method sets the flags for the reducer with the same name. -/// -/// This type is currently unstable and may be removed without a major version bump. -pub struct SetReducerFlags { - imp: __sdk::DbContextImpl, -} - -impl __sdk::InModule for SetReducerFlags { - type Module = RemoteModule; -} - -/// The `db` field of [`EventContext`] and [`DbConnection`], -/// with methods provided by extension traits for each table defined by the module. -pub struct RemoteTables { - imp: __sdk::DbContextImpl, -} - -impl __sdk::InModule for RemoteTables { - type Module = RemoteModule; -} - -/// A connection to a remote module, including a materialized view of a subset of the database. -/// -/// Connect to a remote module by calling [`DbConnection::builder`] -/// and using the [`__sdk::DbConnectionBuilder`] builder-pattern constructor. -/// -/// You must explicitly advance the connection by calling any one of: -/// -/// - [`DbConnection::frame_tick`]. -/// - [`DbConnection::run_threaded`]. -/// - [`DbConnection::run_async`]. -/// - [`DbConnection::advance_one_message`]. -/// - [`DbConnection::advance_one_message_blocking`]. -/// - [`DbConnection::advance_one_message_async`]. -/// -/// Which of these methods you should call depends on the specific needs of your application, -/// but you must call one of them, or else the connection will never progress. -pub struct DbConnection { - /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. - pub db: RemoteTables, - /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. - pub reducers: RemoteReducers, - #[doc(hidden)] - /// Access to setting the call-flags of each reducer defined for each reducer defined by the module - /// via extension traits implemented for [`SetReducerFlags`]. - /// - /// This type is currently unstable and may be removed without a major version bump. - pub set_reducer_flags: SetReducerFlags, - - /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. - pub procedures: RemoteProcedures, - - imp: __sdk::DbContextImpl, -} - -impl __sdk::InModule for DbConnection { - type Module = RemoteModule; -} - -impl __sdk::DbContext for DbConnection { - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type Procedures = RemoteProcedures; - type SetReducerFlags = SetReducerFlags; - - fn db(&self) -> &Self::DbView { - &self.db - } - fn reducers(&self) -> &Self::Reducers { - &self.reducers - } - fn procedures(&self) -> &Self::Procedures { - &self.procedures - } - fn set_reducer_flags(&self) -> &Self::SetReducerFlags { - &self.set_reducer_flags - } - - fn is_active(&self) -> bool { - self.imp.is_active() - } - - fn disconnect(&self) -> __sdk::Result<()> { - self.imp.disconnect() - } - - type SubscriptionBuilder = __sdk::SubscriptionBuilder; - - fn subscription_builder(&self) -> Self::SubscriptionBuilder { - __sdk::SubscriptionBuilder::new(&self.imp) - } - - fn try_identity(&self) -> Option<__sdk::Identity> { - self.imp.try_identity() - } - fn connection_id(&self) -> __sdk::ConnectionId { - self.imp.connection_id() - } - fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { - self.imp.try_connection_id() - } -} - -impl DbConnection { - /// Builder-pattern constructor for a connection to a remote module. - /// - /// See [`__sdk::DbConnectionBuilder`] for required and optional configuration for the new connection. - pub fn builder() -> __sdk::DbConnectionBuilder { - __sdk::DbConnectionBuilder::new() - } - - /// If any WebSocket messages are waiting, process one of them. - /// - /// Returns `true` if a message was processed, or `false` if the queue is empty. - /// Callers should invoke this message in a loop until it returns `false` - /// or for as much time is available to process messages. - /// - /// Returns an error if the connection is disconnected. - /// If the disconnection in question was normal, - /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], - /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. - /// - /// This is a low-level primitive exposed for power users who need significant control over scheduling. - /// Most applications should call [`Self::frame_tick`] each frame - /// to fully exhaust the queue whenever time is available. - pub fn advance_one_message(&self) -> __sdk::Result { - self.imp.advance_one_message() - } - - /// Process one WebSocket message, potentially blocking the current thread until one is received. - /// - /// Returns an error if the connection is disconnected. - /// If the disconnection in question was normal, - /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], - /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. - /// - /// This is a low-level primitive exposed for power users who need significant control over scheduling. - /// Most applications should call [`Self::run_threaded`] to spawn a thread - /// which advances the connection automatically. - pub fn advance_one_message_blocking(&self) -> __sdk::Result<()> { - self.imp.advance_one_message_blocking() - } - - /// Process one WebSocket message, `await`ing until one is received. - /// - /// Returns an error if the connection is disconnected. - /// If the disconnection in question was normal, - /// i.e. the result of a call to [`__sdk::DbContext::disconnect`], - /// the returned error will be downcastable to [`__sdk::DisconnectedError`]. - /// - /// This is a low-level primitive exposed for power users who need significant control over scheduling. - /// Most applications should call [`Self::run_async`] to run an `async` loop - /// which advances the connection when polled. - pub async fn advance_one_message_async(&self) -> __sdk::Result<()> { - self.imp.advance_one_message_async().await - } - - /// Process all WebSocket messages waiting in the queue, - /// then return without `await`ing or blocking the current thread. - pub fn frame_tick(&self) -> __sdk::Result<()> { - self.imp.frame_tick() - } - - /// Spawn a thread which processes WebSocket messages as they are received. - pub fn run_threaded(&self) -> std::thread::JoinHandle<()> { - self.imp.run_threaded() - } - - /// Run an `async` loop which processes WebSocket messages when polled. - pub async fn run_async(&self) -> __sdk::Result<()> { - self.imp.run_async().await - } -} - -impl __sdk::DbConnection for DbConnection { - fn new(imp: __sdk::DbContextImpl) -> Self { - Self { - db: RemoteTables { imp: imp.clone() }, - reducers: RemoteReducers { imp: imp.clone() }, - procedures: RemoteProcedures { imp: imp.clone() }, - set_reducer_flags: SetReducerFlags { imp: imp.clone() }, - imp, - } - } -} - -/// A handle on a subscribed query. -// TODO: Document this better after implementing the new subscription API. -#[derive(Clone)] -pub struct SubscriptionHandle { - imp: __sdk::SubscriptionHandleImpl, -} - -impl __sdk::InModule for SubscriptionHandle { - type Module = RemoteModule; -} - -impl __sdk::SubscriptionHandle for SubscriptionHandle { - fn new(imp: __sdk::SubscriptionHandleImpl) -> Self { - Self { imp } - } - - /// Returns true if this subscription has been terminated due to an unsubscribe call or an error. - fn is_ended(&self) -> bool { - self.imp.is_ended() - } - - /// Returns true if this subscription has been applied and has not yet been unsubscribed. - fn is_active(&self) -> bool { - self.imp.is_active() - } - - /// Unsubscribe from the query controlled by this `SubscriptionHandle`, - /// then run `on_end` when its rows are removed from the client cache. - fn unsubscribe_then(self, on_end: __sdk::OnEndedCallback) -> __sdk::Result<()> { - self.imp.unsubscribe_then(Some(on_end)) - } - - fn unsubscribe(self) -> __sdk::Result<()> { - self.imp.unsubscribe_then(None) - } -} - -/// Alias trait for a [`__sdk::DbContext`] connected to this module, -/// with that trait's associated types bounded to this module's concrete types. -/// -/// Users can use this trait as a boundary on definitions which should accept -/// either a [`DbConnection`] or an [`EventContext`] and operate on either. -pub trait RemoteDbContext: - __sdk::DbContext< - DbView = RemoteTables, - Reducers = RemoteReducers, - SetReducerFlags = SetReducerFlags, - SubscriptionBuilder = __sdk::SubscriptionBuilder, -> -{ -} -impl< - Ctx: __sdk::DbContext< - DbView = RemoteTables, - Reducers = RemoteReducers, - SetReducerFlags = SetReducerFlags, - SubscriptionBuilder = __sdk::SubscriptionBuilder, - >, - > RemoteDbContext for Ctx -{ -} - -/// An [`__sdk::DbContext`] augmented with a [`__sdk::Event`], -/// passed to [`__sdk::Table::on_insert`], [`__sdk::Table::on_delete`] and [`__sdk::TableWithPrimaryKey::on_update`] callbacks. -pub struct EventContext { - /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. - pub db: RemoteTables, - /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. - pub reducers: RemoteReducers, - /// Access to setting the call-flags of each reducer defined for each reducer defined by the module - /// via extension traits implemented for [`SetReducerFlags`]. - /// - /// This type is currently unstable and may be removed without a major version bump. - pub set_reducer_flags: SetReducerFlags, - /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. - pub procedures: RemoteProcedures, - /// The event which caused these callbacks to run. - pub event: __sdk::Event, - imp: __sdk::DbContextImpl, -} - -impl __sdk::AbstractEventContext for EventContext { - type Event = __sdk::Event; - fn event(&self) -> &Self::Event { - &self.event - } - fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { - Self { - db: RemoteTables { imp: imp.clone() }, - reducers: RemoteReducers { imp: imp.clone() }, - set_reducer_flags: SetReducerFlags { imp: imp.clone() }, - procedures: RemoteProcedures { imp: imp.clone() }, - event, - imp, - } - } -} - -impl __sdk::InModule for EventContext { - type Module = RemoteModule; -} - -impl __sdk::DbContext for EventContext { - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type Procedures = RemoteProcedures; - type SetReducerFlags = SetReducerFlags; - - fn db(&self) -> &Self::DbView { - &self.db - } - fn reducers(&self) -> &Self::Reducers { - &self.reducers - } - fn procedures(&self) -> &Self::Procedures { - &self.procedures - } - fn set_reducer_flags(&self) -> &Self::SetReducerFlags { - &self.set_reducer_flags - } - - fn is_active(&self) -> bool { - self.imp.is_active() - } - - fn disconnect(&self) -> __sdk::Result<()> { - self.imp.disconnect() - } - - type SubscriptionBuilder = __sdk::SubscriptionBuilder; - - fn subscription_builder(&self) -> Self::SubscriptionBuilder { - __sdk::SubscriptionBuilder::new(&self.imp) - } - - fn try_identity(&self) -> Option<__sdk::Identity> { - self.imp.try_identity() - } - fn connection_id(&self) -> __sdk::ConnectionId { - self.imp.connection_id() - } - fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { - self.imp.try_connection_id() - } -} - -impl __sdk::EventContext for EventContext {} - -/// An [`__sdk::DbContext`] augmented with a [`__sdk::ReducerEvent`], -/// passed to on-reducer callbacks. -pub struct ReducerEventContext { - /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. - pub db: RemoteTables, - /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. - pub reducers: RemoteReducers, - /// Access to setting the call-flags of each reducer defined for each reducer defined by the module - /// via extension traits implemented for [`SetReducerFlags`]. - /// - /// This type is currently unstable and may be removed without a major version bump. - pub set_reducer_flags: SetReducerFlags, - /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. - pub procedures: RemoteProcedures, - /// The event which caused these callbacks to run. - pub event: __sdk::ReducerEvent, - imp: __sdk::DbContextImpl, -} - -impl __sdk::AbstractEventContext for ReducerEventContext { - type Event = __sdk::ReducerEvent; - fn event(&self) -> &Self::Event { - &self.event - } - fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { - Self { - db: RemoteTables { imp: imp.clone() }, - reducers: RemoteReducers { imp: imp.clone() }, - set_reducer_flags: SetReducerFlags { imp: imp.clone() }, - procedures: RemoteProcedures { imp: imp.clone() }, - event, - imp, - } - } -} - -impl __sdk::InModule for ReducerEventContext { - type Module = RemoteModule; -} - -impl __sdk::DbContext for ReducerEventContext { - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type Procedures = RemoteProcedures; - type SetReducerFlags = SetReducerFlags; - - fn db(&self) -> &Self::DbView { - &self.db - } - fn reducers(&self) -> &Self::Reducers { - &self.reducers - } - fn procedures(&self) -> &Self::Procedures { - &self.procedures - } - fn set_reducer_flags(&self) -> &Self::SetReducerFlags { - &self.set_reducer_flags - } - - fn is_active(&self) -> bool { - self.imp.is_active() - } - - fn disconnect(&self) -> __sdk::Result<()> { - self.imp.disconnect() - } - - type SubscriptionBuilder = __sdk::SubscriptionBuilder; - - fn subscription_builder(&self) -> Self::SubscriptionBuilder { - __sdk::SubscriptionBuilder::new(&self.imp) - } - - fn try_identity(&self) -> Option<__sdk::Identity> { - self.imp.try_identity() - } - fn connection_id(&self) -> __sdk::ConnectionId { - self.imp.connection_id() - } - fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { - self.imp.try_connection_id() - } -} - -impl __sdk::ReducerEventContext for ReducerEventContext {} - -/// An [`__sdk::DbContext`] passed to procedure callbacks. -pub struct ProcedureEventContext { - /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. - pub db: RemoteTables, - /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. - pub reducers: RemoteReducers, - /// Access to setting the call-flags of each reducer defined for each reducer defined by the module - /// via extension traits implemented for [`SetReducerFlags`]. - /// - /// This type is currently unstable and may be removed without a major version bump. - pub set_reducer_flags: SetReducerFlags, - /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. - pub procedures: RemoteProcedures, - imp: __sdk::DbContextImpl, -} - -impl __sdk::AbstractEventContext for ProcedureEventContext { - type Event = (); - fn event(&self) -> &Self::Event { - &() - } - fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { - Self { - db: RemoteTables { imp: imp.clone() }, - reducers: RemoteReducers { imp: imp.clone() }, - procedures: RemoteProcedures { imp: imp.clone() }, - set_reducer_flags: SetReducerFlags { imp: imp.clone() }, - imp, - } - } -} - -impl __sdk::InModule for ProcedureEventContext { - type Module = RemoteModule; -} - -impl __sdk::DbContext for ProcedureEventContext { - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type Procedures = RemoteProcedures; - type SetReducerFlags = SetReducerFlags; - - fn db(&self) -> &Self::DbView { - &self.db - } - fn reducers(&self) -> &Self::Reducers { - &self.reducers - } - fn procedures(&self) -> &Self::Procedures { - &self.procedures - } - fn set_reducer_flags(&self) -> &Self::SetReducerFlags { - &self.set_reducer_flags - } - - fn is_active(&self) -> bool { - self.imp.is_active() - } - - fn disconnect(&self) -> __sdk::Result<()> { - self.imp.disconnect() - } - - type SubscriptionBuilder = __sdk::SubscriptionBuilder; - - fn subscription_builder(&self) -> Self::SubscriptionBuilder { - __sdk::SubscriptionBuilder::new(&self.imp) - } - - fn try_identity(&self) -> Option<__sdk::Identity> { - self.imp.try_identity() - } - fn connection_id(&self) -> __sdk::ConnectionId { - self.imp.connection_id() - } - fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { - self.imp.try_connection_id() - } -} - -impl __sdk::ProcedureEventContext for ProcedureEventContext {} - -/// An [`__sdk::DbContext`] passed to [`__sdk::SubscriptionBuilder::on_applied`] and [`SubscriptionHandle::unsubscribe_then`] callbacks. -pub struct SubscriptionEventContext { - /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. - pub db: RemoteTables, - /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. - pub reducers: RemoteReducers, - /// Access to setting the call-flags of each reducer defined for each reducer defined by the module - /// via extension traits implemented for [`SetReducerFlags`]. - /// - /// This type is currently unstable and may be removed without a major version bump. - pub set_reducer_flags: SetReducerFlags, - /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. - pub procedures: RemoteProcedures, - imp: __sdk::DbContextImpl, -} - -impl __sdk::AbstractEventContext for SubscriptionEventContext { - type Event = (); - fn event(&self) -> &Self::Event { - &() - } - fn new(imp: __sdk::DbContextImpl, _event: Self::Event) -> Self { - Self { - db: RemoteTables { imp: imp.clone() }, - reducers: RemoteReducers { imp: imp.clone() }, - procedures: RemoteProcedures { imp: imp.clone() }, - set_reducer_flags: SetReducerFlags { imp: imp.clone() }, - imp, - } - } -} - -impl __sdk::InModule for SubscriptionEventContext { - type Module = RemoteModule; -} - -impl __sdk::DbContext for SubscriptionEventContext { - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type Procedures = RemoteProcedures; - type SetReducerFlags = SetReducerFlags; - - fn db(&self) -> &Self::DbView { - &self.db - } - fn reducers(&self) -> &Self::Reducers { - &self.reducers - } - fn procedures(&self) -> &Self::Procedures { - &self.procedures - } - fn set_reducer_flags(&self) -> &Self::SetReducerFlags { - &self.set_reducer_flags - } - - fn is_active(&self) -> bool { - self.imp.is_active() - } - - fn disconnect(&self) -> __sdk::Result<()> { - self.imp.disconnect() - } - - type SubscriptionBuilder = __sdk::SubscriptionBuilder; - - fn subscription_builder(&self) -> Self::SubscriptionBuilder { - __sdk::SubscriptionBuilder::new(&self.imp) - } - - fn try_identity(&self) -> Option<__sdk::Identity> { - self.imp.try_identity() - } - fn connection_id(&self) -> __sdk::ConnectionId { - self.imp.connection_id() - } - fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { - self.imp.try_connection_id() - } -} - -impl __sdk::SubscriptionEventContext for SubscriptionEventContext {} - -/// An [`__sdk::DbContext`] augmented with a [`__sdk::Error`], -/// passed to [`__sdk::DbConnectionBuilder::on_disconnect`], [`__sdk::DbConnectionBuilder::on_connect_error`] and [`__sdk::SubscriptionBuilder::on_error`] callbacks. -pub struct ErrorContext { - /// Access to tables defined by the module via extension traits implemented for [`RemoteTables`]. - pub db: RemoteTables, - /// Access to reducers defined by the module via extension traits implemented for [`RemoteReducers`]. - pub reducers: RemoteReducers, - /// Access to setting the call-flags of each reducer defined for each reducer defined by the module - /// via extension traits implemented for [`SetReducerFlags`]. - /// - /// This type is currently unstable and may be removed without a major version bump. - pub set_reducer_flags: SetReducerFlags, - /// Access to procedures defined by the module via extension traits implemented for [`RemoteProcedures`]. - pub procedures: RemoteProcedures, - /// The event which caused these callbacks to run. - pub event: Option<__sdk::Error>, - imp: __sdk::DbContextImpl, -} - -impl __sdk::AbstractEventContext for ErrorContext { - type Event = Option<__sdk::Error>; - fn event(&self) -> &Self::Event { - &self.event - } - fn new(imp: __sdk::DbContextImpl, event: Self::Event) -> Self { - Self { - db: RemoteTables { imp: imp.clone() }, - reducers: RemoteReducers { imp: imp.clone() }, - set_reducer_flags: SetReducerFlags { imp: imp.clone() }, - procedures: RemoteProcedures { imp: imp.clone() }, - event, - imp, - } - } -} - -impl __sdk::InModule for ErrorContext { - type Module = RemoteModule; -} - -impl __sdk::DbContext for ErrorContext { - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type Procedures = RemoteProcedures; - type SetReducerFlags = SetReducerFlags; - - fn db(&self) -> &Self::DbView { - &self.db - } - fn reducers(&self) -> &Self::Reducers { - &self.reducers - } - fn procedures(&self) -> &Self::Procedures { - &self.procedures - } - fn set_reducer_flags(&self) -> &Self::SetReducerFlags { - &self.set_reducer_flags - } - - fn is_active(&self) -> bool { - self.imp.is_active() - } - - fn disconnect(&self) -> __sdk::Result<()> { - self.imp.disconnect() - } - - type SubscriptionBuilder = __sdk::SubscriptionBuilder; - - fn subscription_builder(&self) -> Self::SubscriptionBuilder { - __sdk::SubscriptionBuilder::new(&self.imp) - } - - fn try_identity(&self) -> Option<__sdk::Identity> { - self.imp.try_identity() - } - fn connection_id(&self) -> __sdk::ConnectionId { - self.imp.connection_id() - } - fn try_connection_id(&self) -> Option<__sdk::ConnectionId> { - self.imp.try_connection_id() - } -} - -impl __sdk::ErrorContext for ErrorContext {} - -impl __sdk::SpacetimeModule for RemoteModule { - type DbConnection = DbConnection; - type EventContext = EventContext; - type ReducerEventContext = ReducerEventContext; - type ProcedureEventContext = ProcedureEventContext; - type SubscriptionEventContext = SubscriptionEventContext; - type ErrorContext = ErrorContext; - type Reducer = Reducer; - type DbView = RemoteTables; - type Reducers = RemoteReducers; - type SetReducerFlags = SetReducerFlags; - type DbUpdate = DbUpdate; - type AppliedDiff<'r> = AppliedDiff<'r>; - type SubscriptionHandle = SubscriptionHandle; - - fn register_tables(client_cache: &mut __sdk::ClientCache) { - person_table::register_table(client_cache); - } -} diff --git a/src/module_bindings/person_table.rs b/src/module_bindings/person_table.rs deleted file mode 100644 index da3f64b..0000000 --- a/src/module_bindings/person_table.rs +++ /dev/null @@ -1,95 +0,0 @@ -// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE -// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. - -#![allow(unused, clippy::all)] -use super::person_type::Person; -use spacetimedb_sdk::__codegen::{self as __sdk, __lib, __sats, __ws}; - -/// Table handle for the table `person`. -/// -/// Obtain a handle from the [`PersonTableAccess::person`] method on [`super::RemoteTables`], -/// like `ctx.db.person()`. -/// -/// Users are encouraged not to explicitly reference this type, -/// but to directly chain method calls, -/// like `ctx.db.person().on_insert(...)`. -pub struct PersonTableHandle<'ctx> { - imp: __sdk::TableHandle, - ctx: std::marker::PhantomData<&'ctx super::RemoteTables>, -} - -#[allow(non_camel_case_types)] -/// Extension trait for access to the table `person`. -/// -/// Implemented for [`super::RemoteTables`]. -pub trait PersonTableAccess { - #[allow(non_snake_case)] - /// Obtain a [`PersonTableHandle`], which mediates access to the table `person`. - fn person(&self) -> PersonTableHandle<'_>; -} - -impl PersonTableAccess for super::RemoteTables { - fn person(&self) -> PersonTableHandle<'_> { - PersonTableHandle { - imp: self.imp.get_table::("person"), - ctx: std::marker::PhantomData, - } - } -} - -pub struct PersonInsertCallbackId(__sdk::CallbackId); -pub struct PersonDeleteCallbackId(__sdk::CallbackId); - -impl<'ctx> __sdk::Table for PersonTableHandle<'ctx> { - type Row = Person; - type EventContext = super::EventContext; - - fn count(&self) -> u64 { - self.imp.count() - } - fn iter(&self) -> impl Iterator + '_ { - self.imp.iter() - } - - type InsertCallbackId = PersonInsertCallbackId; - - fn on_insert( - &self, - callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, - ) -> PersonInsertCallbackId { - PersonInsertCallbackId(self.imp.on_insert(Box::new(callback))) - } - - fn remove_on_insert(&self, callback: PersonInsertCallbackId) { - self.imp.remove_on_insert(callback.0) - } - - type DeleteCallbackId = PersonDeleteCallbackId; - - fn on_delete( - &self, - callback: impl FnMut(&Self::EventContext, &Self::Row) + Send + 'static, - ) -> PersonDeleteCallbackId { - PersonDeleteCallbackId(self.imp.on_delete(Box::new(callback))) - } - - fn remove_on_delete(&self, callback: PersonDeleteCallbackId) { - self.imp.remove_on_delete(callback.0) - } -} - -#[doc(hidden)] -pub(super) fn register_table(client_cache: &mut __sdk::ClientCache) { - let _table = client_cache.get_or_make_table::("person"); -} - -#[doc(hidden)] -pub(super) fn parse_table_update( - raw_updates: __ws::TableUpdate<__ws::BsatnFormat>, -) -> __sdk::Result<__sdk::TableUpdate> { - __sdk::TableUpdate::parse_table_update(raw_updates).map_err(|e| { - __sdk::InternalError::failed_parse("TableUpdate", "TableUpdate") - .with_cause(e) - .into() - }) -}