mirror of
https://github.com/fluencelabs/fluent-pad
synced 2025-04-25 00:42:14 +00:00
fmt, delete old projects
This commit is contained in:
parent
11d222275d
commit
3c490c3a44
@ -15,8 +15,8 @@
|
||||
*/
|
||||
|
||||
use crate::message::Message;
|
||||
use crate::service_api::{AddServiceResult, EmptyResult};
|
||||
use crate::service_api::GetMessagesServiceResult;
|
||||
use crate::service_api::{AddServiceResult, EmptyResult};
|
||||
use crate::Result;
|
||||
|
||||
use std::convert::From;
|
||||
|
@ -17,9 +17,9 @@
|
||||
use crate::message::Message;
|
||||
use crate::storage_api::*;
|
||||
|
||||
use fluence::{fce, CallParameters, SecurityTetraplet};
|
||||
use crate::Result;
|
||||
use crate::utils::u64_to_usize;
|
||||
use crate::Result;
|
||||
use fluence::{fce, CallParameters, SecurityTetraplet};
|
||||
|
||||
pub const SUCCESS_CODE: i32 = 0;
|
||||
|
||||
@ -70,7 +70,12 @@ pub fn get_current_tetraplet(auth: bool) -> Vec<Vec<SecurityTetraplet>> {
|
||||
}
|
||||
|
||||
#[fce]
|
||||
pub fn set_tetraplet(peer_id: String, service_id: String, fn_name: String, path: String) -> EmptyResult {
|
||||
pub fn set_tetraplet(
|
||||
peer_id: String,
|
||||
service_id: String,
|
||||
fn_name: String,
|
||||
path: String,
|
||||
) -> EmptyResult {
|
||||
fn set_impl(peer_id: String, service_id: String, fn_name: String, path: String) -> Result<()> {
|
||||
is_owner()?;
|
||||
Ok(store_tetraplet(peer_id, service_id, fn_name, path))
|
||||
@ -86,7 +91,8 @@ pub fn is_owner() -> Result<()> {
|
||||
let call_parameters: CallParameters = fluence::get_call_parameters();
|
||||
let init_peer_id = call_parameters.init_peer_id;
|
||||
|
||||
(init_peer_id == call_parameters.service_creator_peer_id).ok_or_else(|| Unauthorized("This operation could be processed only by owner.".to_string()))
|
||||
(init_peer_id == call_parameters.service_creator_peer_id)
|
||||
.ok_or_else(|| Unauthorized("This operation could be processed only by owner.".to_string()))
|
||||
}
|
||||
|
||||
pub fn is_authenticated(auth: bool, index: u64) -> Result<()> {
|
||||
@ -100,10 +106,17 @@ pub fn is_authenticated(auth: bool, index: u64) -> Result<()> {
|
||||
let index = u64_to_usize(index)?;
|
||||
let st = &call_parameters.tetraplets[index][0];
|
||||
|
||||
(st.peer_pk == t.peer_pk && st.function_name == t.fn_name
|
||||
&& st.service_id == t.service_id &&
|
||||
st.json_path == t.json_path && auth)
|
||||
.ok_or_else(|| Unauthorized(format!("Tetraplet did not pass the check. Expected: {:?}, actual: {:?}", t, st)))
|
||||
(st.peer_pk == t.peer_pk
|
||||
&& st.function_name == t.fn_name
|
||||
&& st.service_id == t.service_id
|
||||
&& st.json_path == t.json_path
|
||||
&& auth)
|
||||
.ok_or_else(|| {
|
||||
Unauthorized(format!(
|
||||
"Tetraplet did not pass the check. Expected: {:?}, actual: {:?}",
|
||||
t, st
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
@ -17,9 +17,9 @@
|
||||
use crate::message::Message;
|
||||
use crate::Result;
|
||||
|
||||
use once_cell::sync::{OnceCell};
|
||||
use crate::utils::{u64_to_usize, usize_to_u64};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use crate::utils::{usize_to_u64, u64_to_usize};
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Tetraplet {
|
||||
@ -32,7 +32,7 @@ pub struct Tetraplet {
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Data {
|
||||
messages: Vec<Message>,
|
||||
tetraplet: Option<Tetraplet>
|
||||
tetraplet: Option<Tetraplet>,
|
||||
}
|
||||
|
||||
static INSTANCE: OnceCell<Mutex<Data>> = OnceCell::new();
|
||||
@ -42,9 +42,7 @@ pub fn init() -> Result<()> {
|
||||
}
|
||||
|
||||
fn get_data() -> &'static Mutex<Data> {
|
||||
INSTANCE.get_or_init(|| {
|
||||
<_>::default()
|
||||
})
|
||||
INSTANCE.get_or_init(|| <_>::default())
|
||||
}
|
||||
|
||||
pub fn add_message(msg: String) -> Result<u64> {
|
||||
@ -54,15 +52,21 @@ pub fn add_message(msg: String) -> Result<u64> {
|
||||
|
||||
data.messages.push(Message { id, body: msg });
|
||||
|
||||
return Ok(id)
|
||||
|
||||
return Ok(id);
|
||||
}
|
||||
|
||||
pub fn get_messages_with_limit(limit: u64) -> Result<Vec<Message>> {
|
||||
let data = get_data().lock();
|
||||
let limit = u64_to_usize(limit)?;
|
||||
|
||||
let msgs: Vec<Message> = data.messages.to_vec().iter().rev().take(limit).map(|msg| msg.clone()).collect();
|
||||
let msgs: Vec<Message> = data
|
||||
.messages
|
||||
.to_vec()
|
||||
.iter()
|
||||
.rev()
|
||||
.take(limit)
|
||||
.map(|msg| msg.clone())
|
||||
.collect();
|
||||
|
||||
Ok(msgs)
|
||||
}
|
||||
|
296
services/history/Cargo.lock
generated
296
services/history/Cargo.lock
generated
@ -1,296 +0,0 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
[[package]]
|
||||
name = "anyhow"
|
||||
version = "1.0.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bf8dcb5b4bbaa28653b647d8c77bd4ed40183b48882e130c1f1ffb73de069fd7"
|
||||
|
||||
[[package]]
|
||||
name = "boolinator"
|
||||
version = "2.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cfa8873f51c92e232f9bac4065cddef41b714152812bfc5f7672ba16d6ef8cd9"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "0.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
|
||||
|
||||
[[package]]
|
||||
name = "fce-sqlite-connector"
|
||||
version = "0.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8165090ee52453a5c14bd42212bfc6516860c4aaa2315fd568c0198b46b52901"
|
||||
dependencies = [
|
||||
"fluence 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1099731bb64286758969fb8dd6f903d1e4a7398d8e63bdec1be6387576f4d8ab"
|
||||
dependencies = [
|
||||
"fluence-sdk-macro 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"fluence-sdk-main 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence"
|
||||
version = "0.2.9"
|
||||
source = "git+https://github.com/fluencelabs/rust-sdk#fd9672636e8d7a91275e5e0b8b88a34494336e5a"
|
||||
dependencies = [
|
||||
"fluence-sdk-macro 0.2.9 (git+https://github.com/fluencelabs/rust-sdk)",
|
||||
"fluence-sdk-main 0.2.9 (git+https://github.com/fluencelabs/rust-sdk)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence-sdk-macro"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca5ffdf0ccf817b1e4e8438f6da7e8fa024679c706a69bde7aa8cad8b43e90ee"
|
||||
dependencies = [
|
||||
"fluence-sdk-wit 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence-sdk-macro"
|
||||
version = "0.2.9"
|
||||
source = "git+https://github.com/fluencelabs/rust-sdk#fd9672636e8d7a91275e5e0b8b88a34494336e5a"
|
||||
dependencies = [
|
||||
"fluence-sdk-wit 0.2.9 (git+https://github.com/fluencelabs/rust-sdk)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence-sdk-main"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4f81c3778c18d372fec6d96049f25e29fc4ff7ba4ab65ef4c2285f971e8670a"
|
||||
dependencies = [
|
||||
"fluence-sdk-macro 0.2.9 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence-sdk-main"
|
||||
version = "0.2.9"
|
||||
source = "git+https://github.com/fluencelabs/rust-sdk#fd9672636e8d7a91275e5e0b8b88a34494336e5a"
|
||||
dependencies = [
|
||||
"fluence-sdk-macro 0.2.9 (git+https://github.com/fluencelabs/rust-sdk)",
|
||||
"log",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence-sdk-wit"
|
||||
version = "0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9c68c4d07e821e1be23b01c278acdae4e825d03c46879f453426ea3160b3e25"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"syn",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fluence-sdk-wit"
|
||||
version = "0.2.9"
|
||||
source = "git+https://github.com/fluencelabs/rust-sdk#fd9672636e8d7a91275e5e0b8b88a34494336e5a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"syn",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc587bc0ec293155d5bfa6b9891ec18a1e330c234f896ea47fbada4cadbe47e6"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "history"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"boolinator",
|
||||
"fce-sqlite-connector",
|
||||
"fluence 0.2.9 (git+https://github.com/fluencelabs/rust-sdk)",
|
||||
"log",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "0.4.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc6f3ad7b9d11a0c00842ff8de1b60ee58661048eb8049ed33c73594f359d7e6"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.80"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4d58d1b70b004888f764dfbf6a26a3b0342a1632d33968e4a179d8011c760614"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "260e51e7efe62b592207e9e13a68e43692a7a279171d6ba57abd208bf23645ad"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
|
||||
dependencies = [
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.7.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"libc",
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
"rand_hc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_hc"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b88fa983de7720629c9387e9f517353ed404164b1e482c970a90c1a4aaf7dc1a"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cbd1ae72adb44aab48f325a02444a5fc079349a8d804c1fc922aed3f7454c74e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.59"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dcac07dbffa1c65e7f816ab9eba78eb142c6d44410f4eeba1e26e4f5dfa56b95"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"ryu",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.48"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc371affeffc477f42a221a1e4297aedcea33d47d19b61455588bd9d8f6b19ac"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-xid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-xid"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
|
||||
|
||||
[[package]]
|
||||
name = "uuid"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fde2f6a4bea1d6e007c4ad38c6839fa71cbb63b6dbf5b595aa38dc9b1093c11"
|
||||
dependencies = [
|
||||
"rand",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.9.0+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
|
@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "history"
|
||||
version = "0.1.0"
|
||||
authors = ["Fluence Labs"]
|
||||
edition = "2018"
|
||||
|
||||
[[bin]]
|
||||
name = "history"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
fluence = { git = "https://github.com/fluencelabs/rust-sdk", features = ["logger"] }
|
||||
fce-sqlite-connector = "=0.1.3"
|
||||
|
||||
anyhow = "1.0.31"
|
||||
boolinator = "2.4.0"
|
||||
log = "0.4.8"
|
||||
once_cell = "1.4.1"
|
@ -1,131 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::message::Message;
|
||||
use crate::service_api::AddServiceResult;
|
||||
use crate::service_api::CountServiceResult;
|
||||
use crate::service_api::GetMessagesServiceResult;
|
||||
use crate::Result;
|
||||
|
||||
use fce_sqlite_connector::Error as SqliteConnectorError;
|
||||
use fce_sqlite_connector::Value;
|
||||
|
||||
use std::convert::From;
|
||||
use std::error::Error;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum HistoryError {
|
||||
SqliteConnectorError(SqliteConnectorError),
|
||||
CorruptedMessage(Vec<Value>),
|
||||
InternalError(String),
|
||||
InvalidArgument(String),
|
||||
UnexpectedValueType(Value, &'static str),
|
||||
}
|
||||
|
||||
impl Error for HistoryError {}
|
||||
|
||||
impl std::fmt::Display for HistoryError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
match self {
|
||||
Self::SqliteConnectorError(err) => writeln!(f, "{:?}", err),
|
||||
Self::CorruptedMessage(values) => writeln!(
|
||||
f,
|
||||
"message can't be constructed from returned values: {:?}",
|
||||
values
|
||||
),
|
||||
Self::InternalError(err_msg) => writeln!(f, "{}", err_msg),
|
||||
Self::InvalidArgument(err_msg) => writeln!(f, "{}", err_msg),
|
||||
Self::UnexpectedValueType(value, expected_type) => writeln!(
|
||||
f,
|
||||
"expected type {}, but value {:?} received",
|
||||
expected_type, value
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SqliteConnectorError> for HistoryError {
|
||||
fn from(err: SqliteConnectorError) -> Self {
|
||||
HistoryError::SqliteConnectorError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::convert::Infallible> for HistoryError {
|
||||
fn from(_: std::convert::Infallible) -> Self {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
fn to_error_core(err: &HistoryError) -> i32 {
|
||||
match err {
|
||||
HistoryError::SqliteConnectorError(_) => 0,
|
||||
HistoryError::CorruptedMessage(_) => 1,
|
||||
HistoryError::InternalError(_) => 2,
|
||||
HistoryError::InvalidArgument(_) => 3,
|
||||
HistoryError::UnexpectedValueType(..) => 4,
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Result<i64>> for AddServiceResult {
|
||||
fn from(result: Result<i64>) -> Self {
|
||||
match result {
|
||||
Ok(msg_id) => Self {
|
||||
ret_code: crate::service_api::SUCCESS_CODE,
|
||||
err_msg: String::new(),
|
||||
msg_id: msg_id as u64,
|
||||
},
|
||||
Err(err) => Self {
|
||||
ret_code: to_error_core(&err),
|
||||
err_msg: format!("{}", err),
|
||||
msg_id: u64::max_value(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Result<Vec<Message>>> for GetMessagesServiceResult {
|
||||
fn from(result: Result<Vec<Message>>) -> Self {
|
||||
match result {
|
||||
Ok(messages) => Self {
|
||||
ret_code: crate::service_api::SUCCESS_CODE,
|
||||
err_msg: String::new(),
|
||||
messages,
|
||||
},
|
||||
Err(err) => Self {
|
||||
ret_code: to_error_core(&err),
|
||||
err_msg: format!("{}", err),
|
||||
messages: vec![],
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Result<i64>> for CountServiceResult {
|
||||
fn from(result: Result<i64>) -> Self {
|
||||
match result {
|
||||
Ok(messages_count) => Self {
|
||||
ret_code: crate::service_api::SUCCESS_CODE,
|
||||
err_msg: String::new(),
|
||||
messages_count: messages_count as u64,
|
||||
},
|
||||
Err(err) => Self {
|
||||
ret_code: to_error_core(&err),
|
||||
err_msg: format!("{}", err),
|
||||
messages_count: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
mod errors;
|
||||
mod message;
|
||||
mod service_api;
|
||||
mod storage_api;
|
||||
|
||||
use fluence::WasmLogger;
|
||||
use storage_api::init;
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, errors::HistoryError>;
|
||||
|
||||
pub fn main() {
|
||||
WasmLogger::new()
|
||||
.with_log_level(log::Level::Info)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
match init() {
|
||||
Ok(_) => log::info!("db created"),
|
||||
Err(e) => log::error!("sqlite db creation failed: {}", e),
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use fluence::fce;
|
||||
|
||||
#[fce]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
|
||||
pub struct Message {
|
||||
pub id: i64,
|
||||
pub author: String,
|
||||
pub body: String,
|
||||
pub reply_to: i64,
|
||||
}
|
||||
|
||||
pub(crate) const MESSAGE_FIELDS_COUNT: usize = 4;
|
@ -1,68 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::message::Message;
|
||||
use crate::storage_api::*;
|
||||
|
||||
use fluence::fce;
|
||||
|
||||
pub const SUCCESS_CODE: i32 = 0;
|
||||
|
||||
#[fce]
|
||||
pub struct AddServiceResult {
|
||||
pub ret_code: i32,
|
||||
pub err_msg: String,
|
||||
pub msg_id: u64,
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn add(author: String, msg: String, reply_to: i64) -> AddServiceResult {
|
||||
add_message(msg, author, reply_to).into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
pub struct GetMessagesServiceResult {
|
||||
pub ret_code: i32,
|
||||
pub err_msg: String,
|
||||
pub messages: Vec<Message>,
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn get_all() -> GetMessagesServiceResult {
|
||||
get_all_messages().into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn get_last(last: u64) -> GetMessagesServiceResult {
|
||||
get_messages_with_limit(last).into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn get_by_reply_to(reply_to: u64) -> GetMessagesServiceResult {
|
||||
get_messages_by_reply_to(reply_to).into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
pub struct CountServiceResult {
|
||||
pub ret_code: i32,
|
||||
pub err_msg: String,
|
||||
pub messages_count: u64,
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn count_by_reply_to(reply_to: u64) -> CountServiceResult {
|
||||
count_messages_by_reply_to(reply_to).into()
|
||||
}
|
@ -1,124 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
mod utils;
|
||||
|
||||
use crate::message::Message;
|
||||
use crate::Result;
|
||||
use utils::*;
|
||||
|
||||
use fce_sqlite_connector::Connection;
|
||||
use fce_sqlite_connector::Value;
|
||||
use fce_sqlite_connector::Value::Integer as VInteger;
|
||||
use fce_sqlite_connector::Value::String as VString;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
static SQLITE: Lazy<Connection> = Lazy::new(|| Connection::open(":memory:").unwrap());
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
let init_sql = "CREATE TABLE IF NOT EXISTS history(\
|
||||
msg_id INTEGER PRIMARY KEY,\
|
||||
msg TEXT NOT NULL,\
|
||||
author TEXT NOT NULL,\
|
||||
reply_to INTEGER\
|
||||
);";
|
||||
|
||||
SQLITE.execute(init_sql).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn add_message(msg: String, author: String, reply_to: i64) -> Result<i64> {
|
||||
use crate::errors::HistoryError::InternalError;
|
||||
|
||||
let add_msg_sql = "INSERT INTO history (msg, author, reply_to) VALUES (?, ?, ?)";
|
||||
let mut cursor = SQLITE.prepare(add_msg_sql)?.cursor();
|
||||
cursor.bind(&[VString(msg), VString(author), VInteger(reply_to)])?;
|
||||
cursor.next()?;
|
||||
|
||||
let last_rowid_sql = "SELECT last_insert_rowid()";
|
||||
let mut cursor = SQLITE.prepare(last_rowid_sql)?.cursor();
|
||||
let raw_id = cursor
|
||||
.next()?
|
||||
.ok_or_else(|| InternalError(String::from("last_insert_rowid didn't return any value")))?
|
||||
.first()
|
||||
.unwrap();
|
||||
|
||||
value_to_integer(raw_id)
|
||||
}
|
||||
|
||||
pub fn get_messages_with_limit(limit: u64) -> Result<Vec<Message>> {
|
||||
let get_messages_with_limit_sql = "SELECT * FROM history ORDER BY msg_id DESC LIMIT ?";
|
||||
let limit = u64_to_i64(limit)?;
|
||||
|
||||
get_messages(get_messages_with_limit_sql, &[VInteger(limit)])
|
||||
}
|
||||
|
||||
pub fn get_messages_by_reply_to(reply_to: u64) -> Result<Vec<Message>> {
|
||||
let get_messages_by_reply_to_sql = "SELECT * FROM history WHERE reply_to = ?";
|
||||
let reply_to = u64_to_i64(reply_to)?;
|
||||
|
||||
get_messages(get_messages_by_reply_to_sql, &[VInteger(reply_to)])
|
||||
}
|
||||
|
||||
pub fn get_all_messages() -> Result<Vec<Message>> {
|
||||
let get_all_messages_sql = "SELECT * FROM history";
|
||||
|
||||
get_messages(get_all_messages_sql, &[])
|
||||
}
|
||||
|
||||
pub fn count_messages_by_reply_to(reply_to: u64) -> Result<i64> {
|
||||
use crate::errors::HistoryError::InternalError;
|
||||
|
||||
let get_messages_count_by_reply_to_sql = "SELECT COUNT(*) FROM history WHERE reply_to = ?";
|
||||
let mut cursor = SQLITE.prepare(get_messages_count_by_reply_to_sql)?.cursor();
|
||||
|
||||
let reply_to = u64_to_i64(reply_to)?;
|
||||
cursor.bind(&[VInteger(reply_to)])?;
|
||||
|
||||
let messages_count = cursor
|
||||
.next()?
|
||||
.ok_or_else(|| InternalError(String::from("count didn't return any value")))?
|
||||
.first()
|
||||
.unwrap();
|
||||
|
||||
value_to_integer(messages_count)
|
||||
}
|
||||
|
||||
fn get_messages(sql: &str, bind_values: &[Value]) -> Result<Vec<Message>> {
|
||||
use crate::errors::HistoryError::CorruptedMessage;
|
||||
use crate::message::MESSAGE_FIELDS_COUNT;
|
||||
|
||||
let mut get_msgs_cursor = SQLITE.prepare(sql)?.cursor();
|
||||
get_msgs_cursor.bind(bind_values)?;
|
||||
|
||||
let mut messages = Vec::new();
|
||||
while let Some(raw_message) = get_msgs_cursor.next()? {
|
||||
if raw_message.len() != MESSAGE_FIELDS_COUNT {
|
||||
return Err(CorruptedMessage(raw_message.into()));
|
||||
}
|
||||
|
||||
let message = Message {
|
||||
id: value_to_integer(&raw_message[0])?,
|
||||
author: value_to_string(&raw_message[2])?,
|
||||
body: value_to_string(&raw_message[1])?,
|
||||
reply_to: value_to_integer(&raw_message[3])?,
|
||||
};
|
||||
|
||||
messages.push(message);
|
||||
}
|
||||
|
||||
Ok(messages)
|
||||
}
|
@ -1,45 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::Result;
|
||||
|
||||
use fce_sqlite_connector::Value;
|
||||
|
||||
pub(super) fn value_to_string(value: &Value) -> Result<String> {
|
||||
use crate::errors::HistoryError::UnexpectedValueType;
|
||||
|
||||
value
|
||||
.as_string()
|
||||
.ok_or_else(|| UnexpectedValueType(value.clone(), "string"))
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
pub(super) fn value_to_integer(value: &Value) -> Result<i64> {
|
||||
use crate::errors::HistoryError::UnexpectedValueType;
|
||||
|
||||
value
|
||||
.as_integer()
|
||||
.ok_or_else(|| UnexpectedValueType(value.clone(), "integer"))
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
pub(super) fn u64_to_i64(value: u64) -> Result<i64> {
|
||||
use crate::errors::HistoryError::InvalidArgument;
|
||||
use std::convert::TryFrom;
|
||||
|
||||
i64::try_from(value)
|
||||
.map_err(|_| InvalidArgument(format!("limit should be less than {}", i64::max_value())))
|
||||
}
|
@ -14,9 +14,9 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::service_api::{EmptyServiceResult, AuthResult};
|
||||
use crate::service_api::ExistsServiceResult;
|
||||
use crate::service_api::GetUsersServiceResult;
|
||||
use crate::service_api::{AuthResult, EmptyServiceResult};
|
||||
use crate::user::User;
|
||||
use crate::Result;
|
||||
|
||||
|
@ -14,11 +14,11 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::errors::UserListError;
|
||||
use crate::storage_api::*;
|
||||
use crate::user::User;
|
||||
use crate::Result;
|
||||
use fluence::{fce, CallParameters};
|
||||
use crate::errors::UserListError;
|
||||
|
||||
pub const SUCCESS_CODE: i32 = 0;
|
||||
|
||||
@ -99,6 +99,12 @@ fn check_auth() -> Result<()> {
|
||||
|
||||
let existed = get_user_by_peer_id(init_peer_id.clone())?.pop();
|
||||
|
||||
(init_peer_id == call_parameters.service_creator_peer_id || existed.is_some())
|
||||
.ok_or_else(|| UserNotExist(format!("init_peer_id is {:?} and it is not existed or an owner. Owner: {:?}", &init_peer_id, &call_parameters.service_creator_peer_id)))
|
||||
(init_peer_id == call_parameters.service_creator_peer_id || existed.is_some()).ok_or_else(
|
||||
|| {
|
||||
UserNotExist(format!(
|
||||
"init_peer_id is {:?} and it is not existed or an owner. Owner: {:?}",
|
||||
&init_peer_id, &call_parameters.service_creator_peer_id
|
||||
))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
@ -17,11 +17,10 @@
|
||||
use crate::user::User;
|
||||
use crate::Result;
|
||||
|
||||
use once_cell::sync::{OnceCell};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
|
||||
|
||||
static INSTANCE: OnceCell<Mutex<HashMap<String, User>>> = OnceCell::new();
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
@ -29,9 +28,7 @@ pub fn init() -> Result<()> {
|
||||
}
|
||||
|
||||
fn get_data() -> &'static Mutex<HashMap<String, User>> {
|
||||
INSTANCE.get_or_init(|| {
|
||||
<_>::default()
|
||||
})
|
||||
INSTANCE.get_or_init(|| <_>::default())
|
||||
}
|
||||
|
||||
pub fn user_exists(peer_id: String) -> Result<bool> {
|
||||
@ -51,7 +48,7 @@ pub fn get_user_by_peer_id(peer_id: String) -> Result<Vec<User>> {
|
||||
|
||||
match data.get(&peer_id) {
|
||||
None => Ok(vec![]),
|
||||
Some(user) => Ok(vec![user.clone()])
|
||||
Some(user) => Ok(vec![user.clone()]),
|
||||
}
|
||||
}
|
||||
|
||||
|
1438
services/user-list/Cargo.lock
generated
1438
services/user-list/Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,23 +0,0 @@
|
||||
[package]
|
||||
name = "user-list"
|
||||
version = "0.1.0"
|
||||
authors = ["Fluence Labs"]
|
||||
edition = "2018"
|
||||
|
||||
[[bin]]
|
||||
name = "user-list"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
fluence = { git = "https://github.com/fluencelabs/rust-sdk", features = ["logger"] }
|
||||
fce-sqlite-connector = "=0.1.3"
|
||||
|
||||
anyhow = "1.0.31"
|
||||
boolinator = "2.4.0"
|
||||
log = "0.4.8"
|
||||
once_cell = "1.4.1"
|
||||
|
||||
[dev-dependencies]
|
||||
fluence-app-service = "0.1.19"
|
||||
uuid = { version = "0.8.1", features = ["v4"] }
|
||||
serde_json = "1.0.59"
|
@ -1,135 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::service_api::EmptyServiceResult;
|
||||
use crate::service_api::ExistsServiceResult;
|
||||
use crate::service_api::GetUsersServiceResult;
|
||||
use crate::user::User;
|
||||
use crate::Result;
|
||||
|
||||
use fce_sqlite_connector::Error as SqliteConnectorError;
|
||||
use fce_sqlite_connector::Value;
|
||||
|
||||
use std::convert::From;
|
||||
use std::error::Error;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UserListError {
|
||||
SqliteConnectorError(SqliteConnectorError),
|
||||
CorruptedUser(Vec<Value>),
|
||||
UnexpectedValueType(Value, &'static str),
|
||||
InvalidSignature(String, String),
|
||||
UserNotExist(String),
|
||||
}
|
||||
|
||||
impl Error for UserListError {}
|
||||
|
||||
impl std::fmt::Display for UserListError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
||||
match self {
|
||||
Self::SqliteConnectorError(err) => writeln!(f, "{:?}", err),
|
||||
Self::CorruptedUser(values) => writeln!(
|
||||
f,
|
||||
"user can't be constructed from returned values: {:?}",
|
||||
values
|
||||
),
|
||||
Self::UnexpectedValueType(value, expected_type) => writeln!(
|
||||
f,
|
||||
"expected type {}, but value {:?} received",
|
||||
expected_type, value
|
||||
),
|
||||
Self::InvalidSignature(user_name, signature) => writeln!(
|
||||
f,
|
||||
"invalid signature '{}' provided for user '{}'",
|
||||
signature, user_name
|
||||
),
|
||||
Self::UserNotExist(user_name) => {
|
||||
writeln!(f, "user with name '{}' does not exist", user_name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<SqliteConnectorError> for UserListError {
|
||||
fn from(err: SqliteConnectorError) -> Self {
|
||||
UserListError::SqliteConnectorError(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<std::convert::Infallible> for UserListError {
|
||||
fn from(_: std::convert::Infallible) -> Self {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
|
||||
fn to_error_core(err: &UserListError) -> i32 {
|
||||
match err {
|
||||
UserListError::SqliteConnectorError(_) => 0,
|
||||
UserListError::CorruptedUser(_) => 1,
|
||||
UserListError::UnexpectedValueType(..) => 2,
|
||||
UserListError::InvalidSignature(..) => 3,
|
||||
UserListError::UserNotExist(_) => 4,
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Result<()>> for EmptyServiceResult {
|
||||
fn from(result: Result<()>) -> Self {
|
||||
match result {
|
||||
Ok(_) => Self {
|
||||
ret_code: crate::service_api::SUCCESS_CODE,
|
||||
err_msg: String::new(),
|
||||
},
|
||||
Err(err) => Self {
|
||||
ret_code: to_error_core(&err),
|
||||
err_msg: format!("{}", err),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Result<Vec<User>>> for GetUsersServiceResult {
|
||||
fn from(result: Result<Vec<User>>) -> Self {
|
||||
match result {
|
||||
Ok(users) => Self {
|
||||
ret_code: crate::service_api::SUCCESS_CODE,
|
||||
err_msg: String::new(),
|
||||
users,
|
||||
},
|
||||
Err(err) => Self {
|
||||
ret_code: to_error_core(&err),
|
||||
err_msg: format!("{}", err),
|
||||
users: vec![],
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Result<bool>> for ExistsServiceResult {
|
||||
fn from(result: Result<bool>) -> Self {
|
||||
match result {
|
||||
Ok(is_exists) => Self {
|
||||
ret_code: crate::service_api::SUCCESS_CODE,
|
||||
err_msg: String::new(),
|
||||
is_exists,
|
||||
},
|
||||
Err(err) => Self {
|
||||
ret_code: to_error_core(&err),
|
||||
err_msg: format!("{}", err),
|
||||
is_exists: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
mod errors;
|
||||
mod service_api;
|
||||
mod storage_api;
|
||||
mod user;
|
||||
|
||||
use fluence::WasmLogger;
|
||||
use storage_api::init;
|
||||
|
||||
pub(crate) type Result<T> = std::result::Result<T, errors::UserListError>;
|
||||
|
||||
pub fn main() {
|
||||
WasmLogger::new()
|
||||
.with_log_level(log::Level::Info)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
match init() {
|
||||
Ok(_) => log::info!("db created"),
|
||||
Err(e) => log::error!("sqlite db creation failed: {}", e),
|
||||
}
|
||||
}
|
@ -1,90 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::storage_api::*;
|
||||
use crate::user::User;
|
||||
use crate::Result;
|
||||
use fluence::{fce, CallParameters};
|
||||
|
||||
pub const SUCCESS_CODE: i32 = 0;
|
||||
|
||||
#[fce]
|
||||
pub struct GetUsersServiceResult {
|
||||
pub ret_code: i32,
|
||||
pub err_msg: String,
|
||||
pub users: Vec<User>,
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn get_users() -> GetUsersServiceResult {
|
||||
get_all_users().into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn get_user(peer_id: String) -> GetUsersServiceResult {
|
||||
get_user_by_peer_id(peer_id).into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
pub struct EmptyServiceResult {
|
||||
pub ret_code: i32,
|
||||
pub err_msg: String,
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn join(user: User) -> EmptyServiceResult {
|
||||
fn add_impl(user: User) -> Result<()> {
|
||||
is_authenticated()?;
|
||||
add_user(user)
|
||||
}
|
||||
|
||||
add_impl(user).into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn delete(peer_id: String) -> EmptyServiceResult {
|
||||
fn delete_impl(peer_id: String) -> Result<()> {
|
||||
is_authenticated()?;
|
||||
|
||||
delete_user(peer_id)
|
||||
};
|
||||
|
||||
delete_impl(peer_id).into()
|
||||
}
|
||||
|
||||
#[fce]
|
||||
pub struct ExistsServiceResult {
|
||||
pub ret_code: i32,
|
||||
pub err_msg: String,
|
||||
pub is_exists: bool,
|
||||
}
|
||||
|
||||
#[fce]
|
||||
fn is_exists(user_name: String) -> ExistsServiceResult {
|
||||
user_exists(user_name).into()
|
||||
}
|
||||
|
||||
fn is_authenticated() -> Result<()> {
|
||||
use crate::errors::UserListError::UserNotExist;
|
||||
use boolinator::Boolinator;
|
||||
|
||||
let call_parameters: CallParameters = fluence::get_call_parameters();
|
||||
let init_peer_id = call_parameters.init_peer_id;
|
||||
|
||||
let existed = get_user_by_peer_id(init_peer_id)?.pop();
|
||||
|
||||
(init_peer_id == call_parameters.service_creator_peer_id || existed.is_some()).ok_or_else(|| UserNotExist(user_name.clone()))
|
||||
}
|
@ -1,115 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use crate::user::User;
|
||||
use crate::Result;
|
||||
|
||||
use fce_sqlite_connector::Connection;
|
||||
use fce_sqlite_connector::Value;
|
||||
use fce_sqlite_connector::Value::String as VString;
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
|
||||
static SQLITE: Lazy<Connection> = Lazy::new(|| Connection::open(":memory:").unwrap());
|
||||
|
||||
macro_rules! non_return_sql {
|
||||
($SQLITE:expr, $sql:expr, $bind_values:expr) => {{
|
||||
let mut cursor = $SQLITE.prepare($sql)?.cursor();
|
||||
cursor.bind($bind_values)?;
|
||||
cursor.next().map(|_| ()).map_err(Into::into)
|
||||
}};
|
||||
}
|
||||
|
||||
pub fn init() -> Result<()> {
|
||||
let init_sql = "CREATE TABLE IF NOT EXISTS users(\
|
||||
peer_id TEXT PRIMARY KEY,\
|
||||
relay TEXT NOT NULL,\
|
||||
name TEXT NOT NULL\
|
||||
);";
|
||||
|
||||
SQLITE.execute(init_sql).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn user_exists(peer_id: String) -> Result<bool> {
|
||||
let prepare_sql = "SELECT * FROM users WHERE peer_id = ?";
|
||||
let mut cursor = SQLITE.prepare(prepare_sql)?.cursor();
|
||||
cursor.bind(&[VString(peer_id)])?;
|
||||
|
||||
let user = cursor.next()?;
|
||||
Ok(user.is_some())
|
||||
}
|
||||
|
||||
pub fn get_all_users() -> Result<Vec<User>> {
|
||||
let get_all_users_sql = "SELECT * FROM users";
|
||||
|
||||
get_users(get_all_users_sql, &[])
|
||||
}
|
||||
|
||||
pub fn get_user_by_peer_id(peer_id: String) -> Result<Vec<User>> {
|
||||
let get_user_by_peer_id_sql = "SELECT * FROM users WHERE peer_id = ?";
|
||||
|
||||
get_users(get_user_by_peer_id_sql, &[VString(peer_id)])
|
||||
}
|
||||
|
||||
fn get_users(sql: &str, bind_values: &[Value]) -> Result<Vec<User>> {
|
||||
use crate::errors::UserListError::CorruptedUser;
|
||||
use crate::user::USER_FIELDS_COUNT;
|
||||
|
||||
fn value_to_string(value: &Value) -> Result<String> {
|
||||
use crate::errors::UserListError::UnexpectedValueType;
|
||||
|
||||
value
|
||||
.as_string()
|
||||
.ok_or_else(|| UnexpectedValueType(value.clone(), "string"))
|
||||
.map(Into::into)
|
||||
}
|
||||
|
||||
let mut get_users_cursor = SQLITE.prepare(sql)?.cursor();
|
||||
get_users_cursor.bind(bind_values)?;
|
||||
|
||||
let mut users = Vec::new();
|
||||
while let Some(raw_user) = get_users_cursor.next()? {
|
||||
if raw_user.len() != USER_FIELDS_COUNT {
|
||||
return Err(CorruptedUser(raw_user.into()));
|
||||
}
|
||||
|
||||
let user = User {
|
||||
peer_id: value_to_string(&raw_user[0])?,
|
||||
relay_id: value_to_string(&raw_user[1])?,
|
||||
name: value_to_string(&raw_user[2])?,
|
||||
};
|
||||
|
||||
users.push(user);
|
||||
}
|
||||
|
||||
Ok(users)
|
||||
}
|
||||
|
||||
pub fn add_user(user: User) -> Result<()> {
|
||||
// TODO: do we really need replace here?
|
||||
let add_user_sql = "REPLACE INTO users (peer_id,relay,name) VALUES (?, ?, ?)";
|
||||
let raw_user = &[
|
||||
VString(user.peer_id),
|
||||
VString(user.relay_id),
|
||||
VString(user.name),
|
||||
];
|
||||
non_return_sql!(SQLITE, add_user_sql, raw_user)
|
||||
}
|
||||
|
||||
pub fn delete_user(peer_id: String) -> Result<()> {
|
||||
let delete_user_sql = "DELETE FROM users WHERE peer_id = ?";
|
||||
non_return_sql!(SQLITE, delete_user_sql, &[VString(peer_id),])
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
/*
|
||||
* Copyright 2020 Fluence Labs Limited
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
use fluence::fce;
|
||||
|
||||
#[fce]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
|
||||
pub struct User {
|
||||
pub peer_id: String,
|
||||
pub relay_id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub(crate) const USER_FIELDS_COUNT: usize = 3;
|
Loading…
x
Reference in New Issue
Block a user