Compare commits

...

3 Commits

Author SHA1 Message Date
Giulio De Pasquale
27aea7d0c1 svelte + rollup + tailwind initial config 2021-02-17 18:49:32 +00:00
Giulio De Pasquale
b8f239ec31 merge rust 2021-02-17 17:19:49 +00:00
Giulio De Pasquale
7014917acb initial support for websockets 2021-02-12 15:00:22 +00:00
13 changed files with 2698 additions and 81 deletions

98
rustybot/Cargo.lock generated
View File

@ -87,12 +87,6 @@ dependencies = [
"rustc-demangle",
]
[[package]]
name = "base64"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff"
[[package]]
name = "base64"
version = "0.13.0"
@ -114,8 +108,8 @@ dependencies = [
"serde",
"serde_derive",
"serde_json",
"tokio 1.1.0",
"tungstenite 0.12.0",
"tokio",
"tungstenite",
"url",
]
@ -152,12 +146,6 @@ version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e4cec68f03f32e44924783795810fa50a7035d8c8ebe78580ad7e6c703fba38"
[[package]]
name = "bytes"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0dcbc35f504eb6fc275a6d20e4ebcda18cf50d40ba6fabff8c711fa16cb3b16"
[[package]]
name = "bytes"
version = "1.0.1"
@ -237,12 +225,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "dotenv"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f"
[[package]]
name = "dyn-clone"
version = "1.0.4"
@ -386,7 +368,7 @@ checksum = "fde5a672a61f96552aa5ed9fd9c81c3fbdae4be9b1e205d6eaf17c83705adc0f"
dependencies = [
"futures",
"pin-project-lite",
"tokio 1.1.0",
"tokio",
]
[[package]]
@ -476,7 +458,7 @@ dependencies = [
"http",
"indexmap",
"slab",
"tokio 1.1.0",
"tokio",
"tokio-util",
"tracing",
"tracing-futures",
@ -554,7 +536,7 @@ dependencies = [
"itoa",
"pin-project 1.0.2",
"socket2",
"tokio 1.1.0",
"tokio",
"tower-service",
"tracing",
"want",
@ -569,7 +551,7 @@ dependencies = [
"bytes 1.0.1",
"hyper",
"native-tls",
"tokio 1.1.0",
"tokio",
"tokio-native-tls",
]
@ -594,15 +576,6 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "input_buffer"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19a8a95243d5a0398cae618ec29477c6e3cb631152be5c19481f80bc71559754"
dependencies = [
"bytes 0.5.6",
]
[[package]]
name = "input_buffer"
version = "0.4.0"
@ -1130,7 +1103,7 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd281b1030aa675fb90aa994d07187645bb3c8fc756ca766e7c3070b439de9de"
dependencies = [
"base64 0.13.0",
"base64",
"bytes 1.0.1",
"encoding_rs",
"futures-core",
@ -1149,7 +1122,7 @@ dependencies = [
"pin-project-lite",
"serde",
"serde_urlencoded",
"tokio 1.1.0",
"tokio",
"tokio-native-tls",
"url",
"wasm-bindgen",
@ -1187,7 +1160,6 @@ dependencies = [
"bitfinex",
"byteorder",
"chrono",
"dotenv",
"dyn-clone",
"fern",
"float-cmp",
@ -1196,8 +1168,9 @@ dependencies = [
"log 0.4.11",
"merge",
"regex",
"tokio 1.1.0",
"tokio",
"tokio-tungstenite",
"tungstenite",
]
[[package]]
@ -1396,20 +1369,6 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "tokio"
version = "0.3.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "720ba21c25078711bf456d607987d95bce90f7c3bea5abe1db587862e7a1e87c"
dependencies = [
"autocfg",
"bytes 0.6.0",
"libc",
"memchr",
"mio",
"pin-project-lite",
]
[[package]]
name = "tokio"
version = "1.1.0"
@ -1448,7 +1407,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b"
dependencies = [
"native-tls",
"tokio 1.1.0",
"tokio",
]
[[package]]
@ -1459,20 +1418,20 @@ checksum = "76066865172052eb8796c686f0b441a93df8b08d40a950b062ffb9a426f00edd"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio 1.1.0",
"tokio",
]
[[package]]
name = "tokio-tungstenite"
version = "0.12.0"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0381c1e6e08908317cee104781ca48afe03f37cc857792b85f01f9828fb55ba3"
checksum = "e1a5f475f1b9d077ea1017ecbc60890fda8e54942d680ca0b1d2b47cfa2d861b"
dependencies = [
"futures-util",
"log 0.4.11",
"pin-project 1.0.2",
"tokio 0.3.6",
"tungstenite 0.11.1",
"tokio",
"tungstenite",
]
[[package]]
@ -1487,7 +1446,7 @@ dependencies = [
"futures-sink",
"log 0.4.11",
"pin-project-lite",
"tokio 1.1.0",
"tokio",
"tokio-stream",
]
@ -1533,37 +1492,18 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
[[package]]
name = "tungstenite"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0308d80d86700c5878b9ef6321f020f29b1bb9d5ff3cab25e75e23f3a492a23"
dependencies = [
"base64 0.12.3",
"byteorder",
"bytes 0.5.6",
"http",
"httparse",
"input_buffer 0.3.1",
"log 0.4.11",
"rand 0.7.3",
"sha-1",
"url",
"utf-8",
]
[[package]]
name = "tungstenite"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ada8297e8d70872fa9a551d93250a9f407beb9f37ef86494eb20012a2ff7c24"
dependencies = [
"base64 0.13.0",
"base64",
"byteorder",
"bytes 1.0.1",
"http",
"httparse",
"input_buffer 0.4.0",
"input_buffer",
"log 0.4.11",
"native-tls",
"rand 0.8.2",

View File

@ -9,7 +9,6 @@ edition = "2018"
[dependencies]
bitfinex = { path= "/home/giulio/dev/bitfinex-rs" }
tokio = { version = "1", features=["full"]}
tokio-tungstenite = "*"
futures-util = { version = "0.3", default-features = false, features = ["async-await", "sink", "std"] }
async-trait = "0.1"
regex = "1"
@ -21,4 +20,5 @@ byteorder = "1"
float-cmp = "0.8"
merge = "0.1"
futures-retry = "0.6"
dotenv = "0.15"
tungstenite = "0.12"
tokio-tungstenite = "0.13"

View File

@ -5,6 +5,7 @@ use tokio::time::sleep;
use crate::connectors::ExchangeDetails;
use crate::currency::{Symbol, SymbolPair};
use crate::frontend::FrontendManagerHandle;
use crate::managers::ExchangeManager;
use crate::ticker::Ticker;
use crate::BoxError;
@ -12,6 +13,7 @@ use crate::BoxError;
pub struct BfxBot {
ticker: Ticker,
exchange_managers: Vec<ExchangeManager>,
frontend_connector: FrontendManagerHandle,
}
impl BfxBot {
@ -34,6 +36,7 @@ impl BfxBot {
BfxBot {
ticker: Ticker::new(tick_duration),
exchange_managers,
frontend_connector: FrontendManagerHandle::new(),
}
}

90
rustybot/src/frontend.rs Normal file
View File

@ -0,0 +1,90 @@
use log::info;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use crate::events::{ActorMessage, Message};
use crate::BoxError;
use futures_util::stream::TryStreamExt;
use futures_util::StreamExt;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::{TcpListener, TcpStream};
use tokio_tungstenite::accept_async;
#[derive(Debug)]
pub struct FrontendManager {
receiver: Receiver<ActorMessage>,
}
impl FrontendManager {
pub fn new(receiver: Receiver<ActorMessage>) -> Self {
Self { receiver }
}
async fn handle_ws_connection(stream: TcpStream, addr: SocketAddr) -> Result<(), BoxError> {
let mut websocket = accept_async(stream).await?;
info!("Received WebSocket connection <{:?}>", addr);
let (ws_out, ws_in) = websocket.split();
let on_received = ws_in.try_for_each(move |msg| {
info!(
"Received a message from {:?}: {}",
addr,
msg.to_text().unwrap()
);
futures_util::future::ok(())
});
tokio::spawn(on_received);
Ok(())
}
pub async fn websocket() -> Result<(), BoxError> {
let server = TcpListener::bind("127.0.0.1:3012").await?;
while let Ok((stream, addr)) = server.accept().await {
tokio::spawn(FrontendManager::handle_ws_connection(stream, addr));
}
Ok(())
}
pub async fn handle_message(&mut self, message: ActorMessage) -> Result<(), BoxError> {
match message.message {
_ => {}
}
Ok(message
.respond_to
.send((None, None))
.map_err(|_| BoxError::from("Could not send message."))?)
}
}
pub struct FrontendManagerHandle {
sender: Sender<ActorMessage>,
}
impl FrontendManagerHandle {
async fn run_frontend_manager(mut manager: FrontendManager) {
info!("Frontend handler ready");
while let Some(msg) = manager.receiver.recv().await {
manager.handle_message(msg).await.unwrap();
}
}
pub fn new() -> Self {
let (sender, receiver) = channel(1);
let frontend = FrontendManager::new(receiver);
tokio::spawn(FrontendManager::websocket());
tokio::spawn(FrontendManagerHandle::run_frontend_manager(frontend));
Self { sender }
}
}

7
svelte/.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
.vscode/
/node_modules/
/public/*
src/*.ts
.DS_Store

105
svelte/README.md Normal file
View File

@ -0,0 +1,105 @@
*Looking for a shareable component template? Go here --> [sveltejs/component-template](https://github.com/sveltejs/component-template)*
---
# svelte app
This is a project template for [Svelte](https://svelte.dev) apps. It lives at https://github.com/sveltejs/template.
To create a new project based on this template using [degit](https://github.com/Rich-Harris/degit):
```bash
npx degit sveltejs/template svelte-app
cd svelte-app
```
*Note that you will need to have [Node.js](https://nodejs.org) installed.*
## Get started
Install the dependencies...
```bash
cd svelte-app
npm install
```
...then start [Rollup](https://rollupjs.org):
```bash
npm run dev
```
Navigate to [localhost:5000](http://localhost:5000). You should see your app running. Edit a component file in `src`, save it, and reload the page to see your changes.
By default, the server will only respond to requests from localhost. To allow connections from other computers, edit the `sirv` commands in package.json to include the option `--host 0.0.0.0`.
If you're using [Visual Studio Code](https://code.visualstudio.com/) we recommend installing the official extension [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode). If you are using other editors you may need to install a plugin in order to get syntax highlighting and intellisense.
## Building and running in production mode
To create an optimised version of the app:
```bash
npm run build
```
You can run the newly built app with `npm run start`. This uses [sirv](https://github.com/lukeed/sirv), which is included in your package.json's `dependencies` so that the app will work when you deploy to platforms like [Heroku](https://heroku.com).
## Single-page app mode
By default, sirv will only respond to requests that match files in `public`. This is to maximise compatibility with static fileservers, allowing you to deploy your app anywhere.
If you're building a single-page app (SPA) with multiple routes, sirv needs to be able to respond to requests for *any* path. You can make it so by editing the `"start"` command in package.json:
```js
"start": "sirv public --single"
```
## Using TypeScript
This template comes with a script to set up a TypeScript development environment, you can run it immediately after cloning the template with:
```bash
node scripts/setupTypeScript.js
```
Or remove the script via:
```bash
rm scripts/setupTypeScript.js
```
## Deploying to the web
### With [Vercel](https://vercel.com)
Install `vercel` if you haven't already:
```bash
npm install -g vercel
```
Then, from within your project folder:
```bash
cd public
vercel deploy --name my-project
```
### With [surge](https://surge.sh/)
Install `surge` if you haven't already:
```bash
npm install -g surge
```
Then, from within your project folder:
```bash
npm run build
surge public my-project.surge.sh
```

34
svelte/package.json Normal file
View File

@ -0,0 +1,34 @@
{
"name": "rustico-ui",
"version": "1.0.0",
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public",
"validate": "svelte-check"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^17.0.0",
"@rollup/plugin-node-resolve": "^11.0.0",
"@rollup/plugin-typescript": "^6.0.0",
"@tsconfig/svelte": "^1.0.0",
"postcss": "^8.2.6",
"rollup": "^2.3.4",
"rollup-plugin-css-only": "^3.1.0",
"rollup-plugin-livereload": "^2.0.0",
"rollup-plugin-postcss": "^4.0.0",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"svelte": "^3.0.0",
"svelte-check": "^1.0.0",
"svelte-preprocess": "^4.0.0",
"tslib": "^2.0.0",
"typescript": "^3.9.3"
},
"dependencies": {
"@rollup/plugin-typescript": "^8.2.0",
"autoprefixer": "^10.2.4",
"sirv-cli": "^1.0.0",
"tailwindcss": "^2.0.3"
}
}

6
svelte/postcss.config.js Normal file
View File

@ -0,0 +1,6 @@
module.exports = {
plugins: [
require("tailwindcss"),
require("autoprefixer")
],
};

83
svelte/rollup.config.js Normal file
View File

@ -0,0 +1,83 @@
import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import sveltePreprocess from 'svelte-preprocess';
import typescript from '@rollup/plugin-typescript';
import css from 'rollup-plugin-css-only';
const production = !process.env.ROLLUP_WATCH;
function serve() {
let server;
function toExit() {
if (server) server.kill(0);
}
return {
writeBundle() {
if (server) return;
server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
stdio: ['ignore', 'inherit', 'inherit'],
shell: true
});
process.on('SIGTERM', toExit);
process.on('exit', toExit);
}
};
}
export default {
input: 'src/main.ts',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
preprocess: sveltePreprocess({ sourceMap: !production, postcss: true }),
compilerOptions: {
// enable run-time checks when not in production
dev: !production,
}
}),
typescript({ sourceMap: !production }),
// we'll extract any component CSS out into
// a separate file - better for performance
css({ output: 'bundle.css' }),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration -
// consult the documentation for details:
// https://github.com/rollup/plugins/tree/master/packages/commonjs
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
typescript({
sourceMap: !production,
inlineSources: !production
}),
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
watch: {
clearScreen: false
}
};

23
svelte/src/App.svelte Normal file
View File

@ -0,0 +1,23 @@
<script lang="ts">
export let name: string;
</script>
<main>
<h1 class="bg-gray-400">Hello {name}!</h1>
<p>
Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
<style global lang="postcss">
/* only apply purgecss on utilities, per Tailwind docs */
/* purgecss start ignore */
@tailwind base;
@tailwind components;
/* purgecss end ignore */
@tailwind utilities;
</style>

30
svelte/tailwind.config.js Normal file
View File

@ -0,0 +1,30 @@
const isProduction = !process.env.ROLLUP_WATCH; // or some other env var like NODE_ENV
module.exports = {
// only needed in Tailwind 1.0 for tailwind 2.0 compat
// future: {
// purgeLayersByDefault: true,
// removeDeprecatedGapUtilities: true,
// },
plugins: [
// for tailwind UI users only
// require('@tailwindcss/ui'),
// other plugins here
],
purge: {
content: [
"./src/**/*.svelte",
// may also want to include HTML files
// "./src/**/*.html"
],
// this is for extracting Svelte `class:` syntax but is not perfect yet, see below
defaultExtractor: content => {
const broadMatches = content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || []
const broadMatchesWithoutTrailingSlash = broadMatches.map(match => _.trimEnd(match, '\\'))
const matches = broadMatches
.concat(broadMatchesWithoutTrailingSlash)
return matches
},
enabled: isProduction // disable purge in dev
},
};

6
svelte/tsconfig.json Normal file
View File

@ -0,0 +1,6 @@
{
"extends": "@tsconfig/svelte/tsconfig.json",
"include": ["src/**/*"],
"exclude": ["node_modules/*", "__sapper__/*", "public/*"]
}

2290
svelte/yarn.lock Normal file

File diff suppressed because it is too large Load Diff