-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathmodule_host.rs
More file actions
2526 lines (2288 loc) · 88.5 KB
/
module_host.rs
File metadata and controls
2526 lines (2288 loc) · 88.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::{
ArgsTuple, FunctionArgs, InvalidProcedureArguments, InvalidReducerArguments, ReducerCallResult, ReducerId,
ReducerOutcome, Scheduler,
};
use crate::client::messages::{OneOffQueryResponseMessage, SerializableMessage};
use crate::client::{ClientActorId, ClientConnectionSender};
use crate::database_logger::{DatabaseLogger, LogLevel, Record};
use crate::db::relational_db::RelationalDB;
use crate::energy::EnergyQuanta;
use crate::error::DBError;
use crate::estimation::estimate_rows_scanned;
use crate::hash::Hash;
use crate::host::host_controller::CallProcedureReturn;
use crate::host::scheduler::{CallScheduledFunctionResult, ScheduledFunctionParams};
use crate::host::v8::JsInstance;
pub use crate::host::wasm_common::module_host_actor::{InstanceCommon, WasmInstance};
use crate::host::wasmtime::ModuleInstance;
use crate::host::{InvalidFunctionArguments, InvalidViewArguments};
use crate::identity::Identity;
use crate::messages::control_db::{Database, HostType};
use crate::replica_context::ReplicaContext;
use crate::sql::ast::SchemaViewer;
use crate::sql::execute::SqlResult;
use crate::sql::parser::RowLevelExpr;
use crate::subscription::module_subscription_actor::ModuleSubscriptions;
use crate::subscription::tx::DeltaTx;
use crate::subscription::websocket_building::{BuildableWebsocketFormat, RowListBuilderSource};
use crate::subscription::{execute_plan, execute_plan_for_view};
use crate::util::jobs::SingleCoreExecutor;
use crate::vm::check_row_limit;
use crate::worker_metrics::WORKER_METRICS;
use anyhow::Context;
use bytes::Bytes;
use derive_more::From;
use futures::lock::Mutex;
use indexmap::IndexSet;
use itertools::Itertools;
use prometheus::{Histogram, IntGauge};
use scopeguard::ScopeGuard;
use smallvec::SmallVec;
use spacetimedb_auth::identity::ConnectionAuthCtx;
use spacetimedb_client_api_messages::energy::FunctionBudget;
use spacetimedb_client_api_messages::websocket::common::{ByteListLen as _, RowListLen as _};
use spacetimedb_client_api_messages::websocket::v1::{self as ws_v1};
use spacetimedb_client_api_messages::websocket::v2::{self as ws_v2};
use spacetimedb_data_structures::error_stream::ErrorStream;
use spacetimedb_data_structures::map::{HashCollectionExt as _, HashSet};
use spacetimedb_datastore::error::DatastoreError;
use spacetimedb_datastore::execution_context::{Workload, WorkloadType};
use spacetimedb_datastore::locking_tx_datastore::{MutTxId, ViewCallInfo};
use spacetimedb_datastore::traits::{IsolationLevel, Program, TxData};
use spacetimedb_durability::DurableOffset;
use spacetimedb_execution::pipelined::{PipelinedProject, ViewProject};
use spacetimedb_expr::expr::CollectViews;
use spacetimedb_lib::db::raw_def::v9::Lifecycle;
use spacetimedb_lib::identity::{AuthCtx, RequestId};
use spacetimedb_lib::metrics::ExecutionMetrics;
use spacetimedb_lib::{ConnectionId, Timestamp};
use spacetimedb_primitives::{ArgId, ProcedureId, TableId, ViewFnPtr, ViewId};
use spacetimedb_query::compile_subscription;
use spacetimedb_sats::raw_identifier::RawIdentifier;
use spacetimedb_sats::{AlgebraicType, AlgebraicTypeRef, ProductValue};
use spacetimedb_schema::auto_migrate::{AutoMigrateError, MigrationPolicy};
use spacetimedb_schema::def::{ModuleDef, ProcedureDef, ReducerDef, TableDef, ViewDef};
use spacetimedb_schema::identifier::Identifier;
use spacetimedb_schema::reducer_name::ReducerName;
use spacetimedb_schema::schema::{Schema, TableSchema};
use spacetimedb_schema::table_name::TableName;
use spacetimedb_vm::relation::RelValue;
use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Weak};
use std::time::{Duration, Instant};
use tokio::sync::oneshot;
#[derive(Debug, Default, Clone, From)]
pub struct DatabaseUpdate {
pub tables: SmallVec<[DatabaseTableUpdate; 1]>,
}
impl FromIterator<DatabaseTableUpdate> for DatabaseUpdate {
fn from_iter<T: IntoIterator<Item = DatabaseTableUpdate>>(iter: T) -> Self {
DatabaseUpdate {
tables: iter.into_iter().collect(),
}
}
}
impl DatabaseUpdate {
pub fn is_empty(&self) -> bool {
if self.tables.len() == 0 {
return true;
}
false
}
pub fn from_writes(tx_data: &TxData) -> Self {
let entries = tx_data.iter_table_entries();
let mut tables = SmallVec::with_capacity(entries.len());
tables.extend(entries.map(|(table_id, e)| DatabaseTableUpdate {
table_id,
table_name: e.table_name.clone(),
inserts: e.inserts.clone(),
deletes: e.deletes.clone(),
}));
DatabaseUpdate { tables }
}
/// The number of rows in the payload
pub fn num_rows(&self) -> usize {
self.tables.iter().map(|t| t.inserts.len() + t.deletes.len()).sum()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DatabaseTableUpdate {
pub table_id: TableId,
pub table_name: TableName,
// Note: `Arc<[ProductValue]>` allows to cheaply
// use the values from `TxData` without cloning the
// contained `ProductValue`s.
pub inserts: Arc<[ProductValue]>,
pub deletes: Arc<[ProductValue]>,
}
#[derive(Debug)]
pub struct DatabaseUpdateRelValue<'a> {
pub tables: Vec<DatabaseTableUpdateRelValue<'a>>,
}
#[derive(PartialEq, Debug)]
pub struct DatabaseTableUpdateRelValue<'a> {
pub table_id: TableId,
pub table_name: TableName,
pub updates: UpdatesRelValue<'a>,
}
#[derive(Default, PartialEq, Debug)]
pub struct UpdatesRelValue<'a> {
pub deletes: Vec<RelValue<'a>>,
pub inserts: Vec<RelValue<'a>>,
}
impl UpdatesRelValue<'_> {
/// Returns whether there are any updates.
pub fn has_updates(&self) -> bool {
!(self.deletes.is_empty() && self.inserts.is_empty())
}
pub fn encode<F: BuildableWebsocketFormat>(
&self,
rlb_pool: &impl RowListBuilderSource<F>,
) -> (F::QueryUpdate, u64, usize) {
let (deletes, nr_del) = F::encode_list(rlb_pool.take_row_list_builder(), self.deletes.iter());
let (inserts, nr_ins) = F::encode_list(rlb_pool.take_row_list_builder(), self.inserts.iter());
let num_rows = nr_del + nr_ins;
let num_bytes = deletes.num_bytes() + inserts.num_bytes();
let qu = ws_v1::QueryUpdate { deletes, inserts };
// We don't compress individual table updates.
// Previously we were, but the benefits, if any, were unclear.
// Note, each message is still compressed before being sent to clients,
// but we no longer have to hold a tx lock when doing so.
let cqu = F::into_query_update(qu, ws_v1::Compression::None);
(cqu, num_rows, num_bytes)
}
}
#[derive(Debug, Clone)]
pub enum EventStatus {
Committed(DatabaseUpdate),
FailedUser(String),
FailedInternal(String),
OutOfEnergy,
}
impl EventStatus {
pub fn database_update(&self) -> Option<&DatabaseUpdate> {
match self {
EventStatus::Committed(upd) => Some(upd),
_ => None,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct ModuleFunctionCall {
pub reducer: Option<ReducerName>,
pub reducer_id: ReducerId,
pub args: ArgsTuple,
}
impl ModuleFunctionCall {
pub fn update() -> Self {
Self {
reducer: None,
reducer_id: u32::MAX.into(),
args: ArgsTuple::nullary(),
}
}
}
#[derive(Debug, Clone)]
pub struct ModuleEvent {
pub timestamp: Timestamp,
pub caller_identity: Identity,
pub caller_connection_id: Option<ConnectionId>,
pub function_call: ModuleFunctionCall,
pub status: EventStatus,
pub reducer_return_value: Option<Bytes>,
pub energy_quanta_used: EnergyQuanta,
pub host_execution_duration: Duration,
pub request_id: Option<RequestId>,
pub timer: Option<Instant>,
}
/// Information about a running module.
pub struct ModuleInfo {
/// The definition of the module.
/// Loaded by loading the module's program from the system tables, extracting its definition,
/// and validating.
pub module_def: Arc<ModuleDef>,
/// The identity of the module.
pub owner_identity: Identity,
/// The identity of the database.
pub database_identity: Identity,
/// The hash of the module.
pub module_hash: Hash,
/// Subscriptions to this module.
pub subscriptions: ModuleSubscriptions,
/// Metrics handles for this module.
pub metrics: ModuleMetrics,
}
impl fmt::Debug for ModuleInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModuleInfo")
.field("module_def", &self.module_def)
.field("owner_identity", &self.owner_identity)
.field("database_identity", &self.database_identity)
.field("module_hash", &self.module_hash)
.finish()
}
}
#[derive(Debug)]
pub struct ModuleMetrics {
pub connected_clients: IntGauge,
pub ws_clients_spawned: IntGauge,
pub ws_clients_aborted: IntGauge,
pub request_round_trip_subscribe: Histogram,
pub request_round_trip_unsubscribe: Histogram,
pub request_round_trip_sql: Histogram,
}
impl ModuleMetrics {
fn new(db: &Identity) -> Self {
let connected_clients = WORKER_METRICS.connected_clients.with_label_values(db);
let ws_clients_spawned = WORKER_METRICS.ws_clients_spawned.with_label_values(db);
let ws_clients_aborted = WORKER_METRICS.ws_clients_aborted.with_label_values(db);
let request_round_trip_subscribe =
WORKER_METRICS
.request_round_trip
.with_label_values(&WorkloadType::Subscribe, db, "");
let request_round_trip_unsubscribe =
WORKER_METRICS
.request_round_trip
.with_label_values(&WorkloadType::Unsubscribe, db, "");
let request_round_trip_sql = WORKER_METRICS
.request_round_trip
.with_label_values(&WorkloadType::Sql, db, "");
Self {
connected_clients,
ws_clients_spawned,
ws_clients_aborted,
request_round_trip_subscribe,
request_round_trip_unsubscribe,
request_round_trip_sql,
}
}
}
impl ModuleInfo {
/// Create a new `ModuleInfo`.
/// Reducers are sorted alphabetically by name and assigned IDs.
pub fn new(
module_def: ModuleDef,
owner_identity: Identity,
database_identity: Identity,
module_hash: Hash,
subscriptions: ModuleSubscriptions,
) -> Arc<Self> {
let metrics = ModuleMetrics::new(&database_identity);
Arc::new(ModuleInfo {
module_def: Arc::new(module_def),
owner_identity,
database_identity,
module_hash,
subscriptions,
metrics,
})
}
pub fn relational_db(&self) -> &Arc<RelationalDB> {
self.subscriptions.relational_db()
}
}
/// A bidirectional map between `Identifiers` (reducer names) and `ReducerId`s.
/// Invariant: the reducer names are in the same order as they were declared in the `ModuleDef`.
pub struct ReducersMap(IndexSet<Box<str>>);
impl<'a> FromIterator<&'a str> for ReducersMap {
fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
Self(iter.into_iter().map_into().collect())
}
}
impl fmt::Debug for ReducersMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl ReducersMap {
/// Lookup the ID for a reducer name.
pub fn lookup_id(&self, reducer_name: &str) -> Option<ReducerId> {
self.0.get_index_of(reducer_name).map(ReducerId::from)
}
/// Lookup the name for a reducer ID.
pub fn lookup_name(&self, reducer_id: ReducerId) -> Option<&str> {
let result = self.0.get_index(reducer_id.0 as _)?;
Some(&**result)
}
}
pub enum ModuleWithInstance {
Wasm {
module: super::wasmtime::Module,
executor: SingleCoreExecutor,
init_inst: Box<super::wasmtime::ModuleInstance>,
},
Js {
module: super::v8::JsModule,
init_inst: super::v8::JsInstance,
},
}
enum ModuleHostInner {
Wasm(WasmtimeModuleHost),
Js(V8ModuleHost),
}
struct WasmtimeModuleHost {
executor: SingleCoreExecutor,
instance_manager: ModuleInstanceManager<super::wasmtime::Module>,
}
struct V8ModuleHost {
instance_manager: ModuleInstanceManager<super::v8::JsModule>,
}
/// A module; used as a bound on `InstanceManager`.
trait GenericModule {
type Instance: GenericModuleInstance;
async fn create_instance(&self) -> Self::Instance;
fn host_type(&self) -> HostType;
}
trait GenericModuleInstance {
fn trapped(&self) -> bool;
}
impl<T: WasmInstance> GenericModuleInstance for super::wasm_common::module_host_actor::WasmModuleInstance<T> {
fn trapped(&self) -> bool {
self.trapped()
}
}
impl<T: GenericModuleInstance + ?Sized> GenericModuleInstance for Box<T> {
fn trapped(&self) -> bool {
(**self).trapped()
}
}
impl GenericModule for super::wasmtime::Module {
type Instance = Box<super::wasmtime::ModuleInstance>;
async fn create_instance(&self) -> Self::Instance {
Box::new(self.create_instance())
}
fn host_type(&self) -> HostType {
HostType::Wasm
}
}
impl GenericModule for super::v8::JsModule {
type Instance = super::v8::JsInstance;
async fn create_instance(&self) -> Self::Instance {
self.create_instance().await
}
fn host_type(&self) -> HostType {
HostType::Js
}
}
impl GenericModuleInstance for super::v8::JsInstance {
fn trapped(&self) -> bool {
self.trapped()
}
}
/// Creates the table for `table_def` in `stdb`.
pub fn create_table_from_def(
stdb: &RelationalDB,
tx: &mut MutTxId,
module_def: &ModuleDef,
table_def: &TableDef,
) -> anyhow::Result<()> {
let schema = TableSchema::from_module_def(module_def, table_def, (), TableId::SENTINEL);
stdb.create_table(tx, schema)
.with_context(|| format!("failed to create table {}", &table_def.name))?;
Ok(())
}
/// Creates the table for `view_def` in `stdb`.
pub fn create_table_from_view_def(
stdb: &RelationalDB,
tx: &mut MutTxId,
module_def: &ModuleDef,
view_def: &ViewDef,
) -> anyhow::Result<()> {
stdb.create_view(tx, module_def, view_def)
.with_context(|| format!("failed to create table for view {}", &view_def.name))?;
Ok(())
}
/// Moves out the `trapped: bool` from `res`.
fn extract_trapped<T, E>(res: Result<(T, bool), E>) -> (Result<T, E>, bool) {
match res {
Ok((x, t)) => (Ok(x), t),
Err(x) => (Err(x), false),
}
}
/// If the module instance's `replica_ctx` is uninitialized, initialize it.
pub(crate) fn init_database(
replica_ctx: &ReplicaContext,
module_def: &ModuleDef,
program: Program,
call_reducer: impl FnOnce(Option<MutTxId>, CallReducerParams) -> (ReducerCallResult, bool),
) -> (anyhow::Result<Option<ReducerCallResult>>, bool) {
extract_trapped(init_database_inner(replica_ctx, module_def, program, call_reducer))
}
fn init_database_inner(
replica_ctx: &ReplicaContext,
module_def: &ModuleDef,
program: Program,
call_reducer: impl FnOnce(Option<MutTxId>, CallReducerParams) -> (ReducerCallResult, bool),
) -> anyhow::Result<(Option<ReducerCallResult>, bool)> {
log::debug!("init database");
let timestamp = Timestamp::now();
let stdb = &*replica_ctx.relational_db;
let logger = replica_ctx.logger.system_logger();
let owner_identity = replica_ctx.database.owner_identity;
let tx = stdb.begin_mut_tx(IsolationLevel::Serializable, Workload::Internal);
let auth_ctx = AuthCtx::for_current(owner_identity);
let (tx, ()) = stdb
.with_auto_rollback(tx, |tx| {
// Create all in-memory tables defined by the module,
// with IDs ordered lexicographically by the table names.
let mut table_defs: Vec<_> = module_def.tables().collect();
table_defs.sort_by_key(|x| &x.name);
for def in table_defs {
logger.info(&format!("Creating table `{}`", &def.name));
create_table_from_def(stdb, tx, module_def, def)?;
}
// Create all in-memory views defined by the module.
let mut view_defs: Vec<_> = module_def.views().collect();
view_defs.sort_by_key(|x| &x.name);
for def in view_defs {
logger.info(&format!("Creating table for view `{}`", &def.name));
create_table_from_view_def(stdb, tx, module_def, def)?;
}
// Insert the late-bound row-level security expressions.
for rls in module_def.row_level_security() {
logger.info(&format!("Creating row level security `{}`", rls.sql));
let rls = RowLevelExpr::build_row_level_expr(tx, &auth_ctx, rls)
.with_context(|| format!("failed to create row-level security: `{}`", rls.sql))?;
let table_id = rls.def.table_id;
let sql = rls.def.sql.clone();
stdb.create_row_level_security(tx, rls.def)
.with_context(|| format!("failed to create row-level security for table `{table_id}`: `{sql}`",))?;
}
stdb.set_initialized(tx, program)?;
anyhow::Ok(())
})
.inspect_err(|e| log::error!("{e:?}"))?;
let rcr = match module_def.lifecycle_reducer(Lifecycle::Init) {
None => {
if let Some((_tx_offset, tx_data, tx_metrics, reducer)) = stdb.commit_tx(tx)? {
stdb.report_mut_tx_metrics(reducer, tx_metrics, Some(tx_data));
}
(None, false)
}
Some((reducer_id, _)) => {
logger.info("Invoking `init` reducer");
let params = CallReducerParams::from_system(timestamp, owner_identity, reducer_id, ArgsTuple::nullary());
let (res, trapped) = call_reducer(Some(tx), params);
(Some(res), trapped)
}
};
logger.info("Database initialized");
Ok(rcr)
}
pub fn call_identity_connected(
caller_auth: ConnectionAuthCtx,
caller_connection_id: ConnectionId,
module: &ModuleInfo,
call_reducer: impl FnOnce(Option<MutTxId>, CallReducerParams) -> (ReducerCallResult, bool),
trapped_slot: &mut bool,
) -> Result<(), ClientConnectedError> {
let reducer_lookup = module.module_def.lifecycle_reducer(Lifecycle::OnConnect);
let stdb = module.relational_db();
let workload = Workload::reducer_no_args(
ReducerName::new(Identifier::new_assume_valid("call_identity_connected".into())),
caller_auth.claims.identity,
caller_connection_id,
);
let mut_tx = stdb.begin_mut_tx(IsolationLevel::Serializable, workload);
let mut mut_tx = scopeguard::guard(mut_tx, |mut_tx| {
// If we crash before committing, we need to ensure that the transaction is rolled back.
// This is necessary to avoid leaving the database in an inconsistent state.
log::debug!("call_identity_connected: rolling back transaction");
let (_, metrics, reducer_name) = mut_tx.rollback();
stdb.report_mut_tx_metrics(reducer_name, metrics, None);
});
mut_tx
.insert_st_client(
caller_auth.claims.identity,
caller_connection_id,
&caller_auth.jwt_payload,
)
.map_err(DBError::from)
.map_err(Box::new)?;
if let Some((reducer_id, reducer_def)) = reducer_lookup {
// The module defined a lifecycle reducer to handle new connections.
// Call this reducer.
// If the call fails (as in, something unexpectedly goes wrong with guest execution),
// abort the connection: we can't really recover.
let tx = Some(ScopeGuard::into_inner(mut_tx));
let params = ModuleHost::call_reducer_params(
module,
caller_auth.claims.identity,
Some(caller_connection_id),
None,
None,
None,
reducer_id,
reducer_def,
FunctionArgs::Nullary,
)
.map_err(ReducerCallError::from)?;
let (reducer_outcome, trapped) = call_reducer(tx, params);
*trapped_slot = trapped;
match reducer_outcome.outcome {
// If the reducer committed successfully, we're done.
// `WasmModuleInstance::call_reducer_with_tx` has already ensured
// that `st_client` is updated appropriately.
//
// It's necessary to spread out the responsibility for updating `st_client` in this way
// because it's important that `call_identity_connected` commit at most one transaction.
// A naive implementation of this method would just run the reducer first,
// then insert into `st_client`,
// but if we crashed in between, we'd be left in an inconsistent state
// where the reducer had run but `st_client` was not yet updated.
ReducerOutcome::Committed => Ok(()),
// If the reducer returned an error or couldn't run due to insufficient energy,
// abort the connection: the module code has decided it doesn't want this client.
ReducerOutcome::Failed(message) => Err(ClientConnectedError::Rejected(*message)),
ReducerOutcome::BudgetExceeded => Err(ClientConnectedError::OutOfEnergy),
}
} else {
// The module doesn't define a client_connected reducer.
// We need to commit the transaction to update st_clients and st_connection_credentials.
//
// This is necessary to be able to disconnect clients after a server crash.
// TODO: Is this being broadcast? Does it need to be, or are st_client table subscriptions
// not allowed?
// I (jsdt) don't think it was being broadcast previously. See:
// https://github.com/clockworklabs/SpacetimeDB/issues/3130
stdb.finish_tx(ScopeGuard::into_inner(mut_tx), Ok(()))
.map_err(|e: DBError| {
log::error!("`call_identity_connected`: finish transaction failed: {e:#?}");
ClientConnectedError::DBError(e.into())
})?;
Ok(())
}
}
pub struct CallReducerParams {
pub timestamp: Timestamp,
pub caller_identity: Identity,
pub caller_connection_id: ConnectionId,
pub client: Option<Arc<ClientConnectionSender>>,
pub request_id: Option<RequestId>,
pub timer: Option<Instant>,
pub reducer_id: ReducerId,
pub args: ArgsTuple,
}
impl CallReducerParams {
/// Returns a set of parameters for an internal call
/// without a client/caller/request_id.
pub fn from_system(
timestamp: Timestamp,
caller_identity: Identity,
reducer_id: ReducerId,
args: ArgsTuple,
) -> Self {
Self {
timestamp,
caller_identity,
caller_connection_id: ConnectionId::ZERO,
client: None,
request_id: None,
timer: None,
reducer_id,
args,
}
}
}
pub enum ViewCommand {
AddSingleSubscription {
sender: Arc<ClientConnectionSender>,
auth: AuthCtx,
request: ws_v1::SubscribeSingle,
_timer: Instant,
},
AddMultiSubscription {
sender: Arc<ClientConnectionSender>,
auth: AuthCtx,
request: ws_v1::SubscribeMulti,
_timer: Instant,
},
AddLegacySubscription {
sender: Arc<ClientConnectionSender>,
auth: AuthCtx,
subscribe: ws_v1::Subscribe,
_timer: Instant,
},
AddSubscriptionV2 {
sender: Arc<ClientConnectionSender>,
auth: AuthCtx,
request: ws_v2::Subscribe,
_timer: Instant,
},
RemoveSubscriptionV2 {
sender: Arc<ClientConnectionSender>,
auth: AuthCtx,
request: ws_v2::Unsubscribe,
timer: Instant,
},
Sql {
db: Arc<RelationalDB>,
sql_text: String,
auth: AuthCtx,
subs: Option<ModuleSubscriptions>,
},
}
#[derive(Debug)]
pub enum ViewCommandResult {
Subscription {
result: Result<Option<ExecutionMetrics>, DBError>,
},
Sql {
result: Result<SqlResult, DBError>,
head: Vec<(RawIdentifier, AlgebraicType)>,
},
}
pub struct CallViewParams {
pub view_name: Identifier,
pub view_id: ViewId,
pub table_id: TableId,
pub fn_ptr: ViewFnPtr,
/// This is not always the same identity as `sender`.
/// For subscribe and sql calls it will be.
/// However for atomic view update after a reducer call,
/// this will be the caller of the reducer.
pub caller: Identity,
pub sender: Option<Identity>,
pub args: ArgsTuple,
pub row_type: AlgebraicTypeRef,
pub timestamp: Timestamp,
}
pub struct CallProcedureParams {
pub timestamp: Timestamp,
pub caller_identity: Identity,
pub caller_connection_id: ConnectionId,
pub timer: Option<Instant>,
pub procedure_id: ProcedureId,
pub args: ArgsTuple,
}
impl CallProcedureParams {
/// Returns a set of parameters for an internal call
/// without a client/caller/request_id.
pub fn from_system(
timestamp: Timestamp,
caller_identity: Identity,
procedure_id: ProcedureId,
args: ArgsTuple,
) -> Self {
Self {
timestamp,
caller_identity,
caller_connection_id: ConnectionId::ZERO,
timer: None,
procedure_id,
args,
}
}
}
/// Holds a [`Module`] and a set of [`Instance`]s from it,
/// and allocates the [`Instance`]s to be used for function calls.
///
/// Capable of managing and allocating multiple instances of the same module,
/// but this functionality is currently unused, as only one reducer runs at a time.
/// When we introduce procedures, it will be necessary to have multiple instances,
/// as each procedure invocation will have its own sandboxed instance,
/// and multiple procedures can run concurrently with up to one reducer.
struct ModuleInstanceManager<M: GenericModule> {
instances: Mutex<VecDeque<M::Instance>>,
module: M,
create_instance_time_metric: CreateInstanceTimeMetric,
}
/// Handle on the `spacetime_module_create_instance_time_seconds` label for a particular database
/// which calls `remove_label_values` to clean up on drop.
struct CreateInstanceTimeMetric {
metric: Histogram,
host_type: HostType,
database_identity: Identity,
}
impl Drop for CreateInstanceTimeMetric {
fn drop(&mut self) {
let _ = WORKER_METRICS
.module_create_instance_time_seconds
.remove_label_values(&self.database_identity, &self.host_type);
}
}
impl CreateInstanceTimeMetric {
fn observe(&self, duration: std::time::Duration) {
self.metric.observe(duration.as_secs_f64());
}
}
impl<M: GenericModule> ModuleInstanceManager<M> {
fn new(module: M, init_inst: M::Instance, database_identity: Identity) -> Self {
let host_type = module.host_type();
let create_instance_time_metric = CreateInstanceTimeMetric {
metric: WORKER_METRICS
.module_create_instance_time_seconds
.with_label_values(&database_identity, &host_type),
host_type,
database_identity,
};
// Add the first instance.
let mut instances = VecDeque::new();
instances.push_front(init_inst);
Self {
instances: Mutex::new(instances),
module,
create_instance_time_metric,
}
}
async fn with_instance<R>(&self, f: impl AsyncFnOnce(M::Instance) -> (R, M::Instance)) -> R {
let inst = self.get_instance().await;
let (res, inst) = f(inst).await;
self.return_instance(inst).await;
res
}
async fn get_instance(&self) -> M::Instance {
let inst = self.instances.lock().await.pop_back();
if let Some(inst) = inst {
inst
} else {
let start_time = std::time::Instant::now();
let res = self.module.create_instance().await;
let elapsed_time = start_time.elapsed();
self.create_instance_time_metric.observe(elapsed_time);
res
}
}
async fn return_instance(&self, inst: M::Instance) {
if inst.trapped() {
// Don't return trapped instances;
// they may have left internal data structures in the guest `Instance`
// (WASM linear memory, V8 global scope) in a bad state.
return;
}
self.instances.lock().await.push_front(inst);
}
}
#[derive(Clone)]
pub struct ModuleHost {
pub info: Arc<ModuleInfo>,
inner: Arc<ModuleHostInner>,
/// Called whenever a reducer call on this host panics.
on_panic: Arc<dyn Fn() + Send + Sync + 'static>,
/// Marks whether this module has been closed by [`Self::exit`].
///
/// When this is true, most operations will fail with [`NoSuchModule`].
closed: Arc<AtomicBool>,
}
impl fmt::Debug for ModuleHost {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModuleHost")
.field("info", &self.info)
.field("inner", &Arc::as_ptr(&self.inner))
.finish()
}
}
pub struct WeakModuleHost {
info: Arc<ModuleInfo>,
inner: Weak<ModuleHostInner>,
on_panic: Weak<dyn Fn() + Send + Sync + 'static>,
closed: Weak<AtomicBool>,
}
#[derive(Debug)]
pub enum UpdateDatabaseResult {
NoUpdateNeeded,
UpdatePerformed,
UpdatePerformedWithClientDisconnect,
AutoMigrateError(Box<ErrorStream<AutoMigrateError>>),
ErrorExecutingMigration(anyhow::Error),
}
impl UpdateDatabaseResult {
/// Check if a database update was successful.
pub fn was_successful(&self) -> bool {
matches!(
self,
UpdateDatabaseResult::UpdatePerformed
| UpdateDatabaseResult::NoUpdateNeeded
| UpdateDatabaseResult::UpdatePerformedWithClientDisconnect
)
}
}
#[derive(thiserror::Error, Debug)]
#[error("no such module")]
pub struct NoSuchModule;
#[derive(thiserror::Error, Debug)]
pub enum ReducerCallError {
#[error(transparent)]
Args(#[from] InvalidReducerArguments),
#[error(transparent)]
NoSuchModule(#[from] NoSuchModule),
#[error("no such reducer")]
NoSuchReducer,
#[error("no such scheduled reducer")]
ScheduleReducerNotFound,
#[error("can't directly call special {0:?} lifecycle reducer")]
LifecycleReducer(Lifecycle),
}
#[derive(Debug, PartialEq, Eq)]
pub enum ViewOutcome {
Success,
Failed(String),
BudgetExceeded,
}
impl From<EventStatus> for ViewOutcome {
fn from(status: EventStatus) -> Self {
match status {
EventStatus::Committed(_) => ViewOutcome::Success,
EventStatus::FailedUser(e) | EventStatus::FailedInternal(e) => ViewOutcome::Failed(e),
EventStatus::OutOfEnergy => ViewOutcome::BudgetExceeded,
}
}
}
pub struct ViewCallResult {
pub outcome: ViewOutcome,
pub tx: MutTxId,
pub energy_used: FunctionBudget,
pub total_duration: Duration,
pub abi_duration: Duration,
}
impl fmt::Debug for ViewCallResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ViewCallResult")
.field("outcome", &self.outcome)
.field("energy_used", &self.energy_used)
.field("total_duration", &self.total_duration)
.field("abi_duration", &self.abi_duration)
.finish()
}
}
impl ViewCallResult {
pub fn default(tx: MutTxId) -> Self {
Self {
outcome: ViewOutcome::Success,
energy_used: FunctionBudget::ZERO,
total_duration: Duration::ZERO,
abi_duration: Duration::ZERO,
tx,
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum ViewCallError {
#[error(transparent)]
Args(#[from] InvalidViewArguments),
#[error(transparent)]
NoSuchModule(#[from] NoSuchModule),
#[error("no such view")]
NoSuchView,
#[error("Table does not exist for view `{0}`")]
TableDoesNotExist(ViewId),
#[error("missing client connection for view call trigged by subscription")]
MissingClientConnection,
#[error("DB error during view call: {0}")]
DatastoreError(#[from] DatastoreError),
#[error("The module instance encountered a fatal error: {0}")]
InternalError(String),
}
#[derive(thiserror::Error, Debug)]
pub enum ProcedureCallError {
#[error(transparent)]
Args(#[from] InvalidProcedureArguments),
#[error(transparent)]
NoSuchModule(#[from] NoSuchModule),
#[error("No such procedure")]
NoSuchProcedure,
#[error("Procedure terminated due to insufficient budget")]
OutOfEnergy,
#[error("The module instance encountered a fatal error: {0}")]
InternalError(String),
}
#[derive(thiserror::Error, Debug)]
pub enum InitDatabaseError {
#[error(transparent)]
Args(#[from] InvalidReducerArguments),
#[error(transparent)]
NoSuchModule(#[from] NoSuchModule),
#[error(transparent)]
Other(anyhow::Error),
}
#[derive(thiserror::Error, Debug)]
pub enum ClientConnectedError {
#[error(transparent)]
ReducerCall(#[from] ReducerCallError),
#[error("Failed to insert `st_client` row for module without client_connected reducer: {0}")]
DBError(#[from] Box<DBError>),
#[error("Connection rejected by `client_connected` reducer: {0}")]
Rejected(Box<str>),
#[error("Insufficient energy balance to run `client_connected` reducer")]