Skip to content

Commit

Permalink
fix up, done
Browse files Browse the repository at this point in the history
  • Loading branch information
hatchan committed Sep 16, 2024
1 parent bcd8163 commit f8e7158
Show file tree
Hide file tree
Showing 19 changed files with 158 additions and 29 deletions.
5 changes: 4 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

53 changes: 53 additions & 0 deletions desktop/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,24 @@ import { useCallback, useEffect, useState } from "react";
import { Button } from "./components/ui/button";
import { Card } from "./components/ui/card";
import { cn } from "./utils";
import { listen } from "@tauri-apps/api/event";

type RecentProjects = Array<string>;

type Idable<T> = {
id: string;
inner: T;
};

type EventMessage = {
type: string;
details: EventMessageDetails;
};

type EventMessageDetails = {
newSpans: Array<[string, string]>;
};

type Project = {
listen_port: number;
};
Expand All @@ -16,6 +31,31 @@ export function App() {
const [error, setError] = useState<string | undefined>();
const [recentProjects, setRecentProjects] = useState<RecentProjects>([]);

const [eventMessage, setEventMessage] = useState<Array<Idable<EventMessage>>>(
[],
);

useEffect(() => {
listen<EventMessage>("api_message", (message) => {
const id_message2: Idable<EventMessage> = {
id: Math.random().toString(36).substring(7),
inner: message.payload,
};
setEventMessage((event_messages) => [...event_messages, id_message2]);
});
}, []);

const handleStart = useCallback(() => {
(async () => {
try {
await invoke("start_server");
} catch (e) {
// TODO: Handle type share
setError(e as string);
}
})();
}, []);

const handleOpen = useCallback((path?: string) => {
(async () => {
const selected =
Expand Down Expand Up @@ -49,6 +89,19 @@ export function App() {
return (
<div className="flex flex-col w-screen h-screen p-4">
{error && <div className="bg-orange-800 rounded p-4">{error}</div>}
<Card className="p-4 flex flex-col gap-8 w-full h-full">
<Button onClick={() => handleStart()}>Start server</Button>
</Card>
<Card className="p-4 flex flex-col gap-8 w-full h-full">
{eventMessage.map((event_message) => (
<p key={event_message.id}>
{event_message.inner.type}:{" "}
{event_message.inner.details.newSpans.map(
([trace_id, span_id]) => trace_id + " - " + span_id,
)}
</p>
))}
</Card>
<Card className="p-4 flex flex-col gap-8 w-full h-full">
<strong>Recent projects</strong>
<div className="flex flex-col gap-4">
Expand Down
6 changes: 5 additions & 1 deletion fpx-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ repository = { workspace = true }

[lib]

[features]
libsql = ["dep:libsql", "dep:include_dir"]

[dependencies]
anyhow = { version = "1.0", default-features = false }
async-trait = { version = "0.1", default-features = false }
Expand All @@ -20,7 +23,8 @@ fpx-macros = { version = "0.1.0", path = "../fpx-macros" }
futures-util = { version = "0.3", default-features = false }
hex = { version = "0.4", default-features = false, features = ["alloc"] }
http = { version = "1.1", default-features = false }
libsql = { version = "0.5", default-features = false, optional = true }
include_dir = { version = "0.7.3", optional = true }
libsql = { version = "0.5", default-features = false, features = ["core", "serde"], optional = true }
opentelemetry = { version = "0.24", default-features = false }
opentelemetry_sdk = { version = "0.24", default-features = false }
opentelemetry-proto = { version = "0.7", default-features = false, features = [
Expand Down
6 changes: 3 additions & 3 deletions fpx-lib/src/data.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
use crate::data::models::HexEncodedId;
use crate::events::ServerEvents;
use async_trait::async_trait;
use std::sync::Arc;
use thiserror::Error;

#[cfg(feature = "libsql")]
pub mod libsql;
pub mod models;
pub mod sql;
pub mod util;

pub type Result<T, E = DbError> = anyhow::Result<T, E>;

pub type BoxedEvents = Arc<dyn ServerEvents>;
pub type BoxedStore = Arc<dyn Store>;

#[derive(Clone, Default, Debug)]
Expand All @@ -35,7 +35,7 @@ pub enum DbError {

#[cfg(feature = "libsql")]
#[error("Internal database error occurred: {0}")]
LibsqlError(#[from] libsql::Error),
LibsqlError(#[from] ::libsql::Error),
}

#[async_trait]
Expand Down
11 changes: 5 additions & 6 deletions fpx/src/data.rs → fpx-lib/src/data/libsql.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::data::models::{HexEncodedId, Span};
use crate::data::sql::SqlBuilder;
use crate::data::{DbError, Result, Store, Transaction};
use anyhow::Context;
use async_trait::async_trait;
use fpx_lib::data::models::{HexEncodedId, Span};
use fpx_lib::data::sql::SqlBuilder;
use fpx_lib::data::{DbError, Result, Store, Transaction};
use libsql::{params, Builder, Connection};
use std::fmt::Display;
use std::path::Path;
Expand All @@ -11,10 +11,9 @@ use tracing::trace;
use util::RowsExt;

mod migrations;
mod util;

#[cfg(test)]
mod tests;
mod util;

pub enum DataPath<'a> {
InMemory,
Expand Down Expand Up @@ -179,7 +178,7 @@ impl Store for LibsqlStore {
&self,
_tx: &Transaction,
// Future improvement could hold sort fields, limits, etc
) -> Result<Vec<fpx_lib::data::models::Trace>> {
) -> Result<Vec<crate::data::models::Trace>> {
let traces = self
.connection
.query(&self.sql_builder.traces_list(None), ())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ use tracing::{debug, trace};

// NOTE: We should probably create our own include, which will store it sorted,
// as an array, and with just the name and sql as the expected types.
static MIGRATIONS: Dir<'_> = include_dir::include_dir!("$CARGO_MANIFEST_DIR/src/data/migrations");
static MIGRATIONS: Dir<'_> =
include_dir::include_dir!("$CARGO_MANIFEST_DIR/src/data/libsql/migrations");

static MIGRATIONS_BOOTSTRAP: &str = "
CREATE TABLE _fpx_migrations (
Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion fpx/src/data/util.rs → fpx-lib/src/data/libsql/util.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use fpx_lib::data::{DbError, Result};
use crate::data::{DbError, Result};
use libsql::{de, Rows};
use serde::de::DeserializeOwned;

Expand Down
5 changes: 5 additions & 0 deletions fpx-lib/src/events.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use crate::api::models::ServerMessage;
use axum::async_trait;
use std::sync::Arc;

pub mod memory;

pub type BoxedEvents = Arc<dyn ServerEvents>;

#[async_trait]
pub trait ServerEvents: Sync + Send {
Expand Down
6 changes: 3 additions & 3 deletions fpx/src/events.rs → fpx-lib/src/events/memory.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::api::models::ServerMessage;
use crate::events::ServerEvents;
use async_trait::async_trait;
use fpx_lib::api::models::ServerMessage;
use fpx_lib::events::ServerEvents;
use tokio::sync::broadcast;
use tracing::trace;

Expand All @@ -15,7 +15,7 @@ impl InMemoryEvents {
Self { sender }
}

pub async fn subscribe(&self) -> broadcast::Receiver<ServerMessage> {
pub fn subscribe(&self) -> broadcast::Receiver<ServerMessage> {
self.sender.subscribe()
}
}
Expand Down
3 changes: 2 additions & 1 deletion fpx-lib/src/service.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::api::models::{Span, SpanAdded};
use crate::data::{BoxedEvents, BoxedStore, DbError};
use crate::data::{BoxedStore, DbError};
use crate::events::BoxedEvents;
use anyhow::Result;
use opentelemetry_proto::tonic::collector::trace::v1::{
ExportTraceServiceRequest, ExportTraceServiceResponse,
Expand Down
11 changes: 10 additions & 1 deletion fpx-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ tauri-build = { version = "1.5.4", features = [] }

[dependencies]
anyhow = { workspace = true }
axum = { workspace = true, default-features = false, features = [
"http1",
"query",
"tokio",
"tracing",
"ws",
] }
fpx-lib = { version = "0.1.0", path = "../fpx-lib", features = ["libsql"] }
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { version = "1.7.2", features = [
Expand All @@ -21,8 +29,9 @@ tauri = { version = "1.7.2", features = [
"http-all",
"shell-all",
] }
tauri-plugin-window-state = "0.1.0"
tauri-plugin-store = { version = "0.0.0", git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" }
tauri-plugin-window-state = "0.1.0"
tokio = { version = "1.40", features = ["rt-multi-thread", "signal", "fs"] }
toml = "0.7.3"

[features]
Expand Down
65 changes: 60 additions & 5 deletions fpx-tauri/src/commands.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use crate::{
models::{AppState, OpenProjectError, Project},
STORE_PATH,
};
use crate::models::{AppState, OpenProjectError, Project};
use crate::STORE_PATH;
use fpx_lib::data::libsql::LibsqlStore;
use fpx_lib::events::memory::InMemoryEvents;
use fpx_lib::service::Service;
use fpx_lib::{api, events};
use serde_json::Value;
use std::{fs::File, io::Read, sync::Mutex};
use std::sync::{Arc, Mutex};
use std::{fs::File, io::Read};
use tauri::async_runtime::spawn;
use tauri::{AppHandle, Runtime, State, Window, WindowBuilder, WindowEvent, WindowUrl};
use tauri_plugin_store::{with_store, StoreCollection};
use tokio::sync::broadcast::error::RecvError;

const RECENT_PROJECTS_STORE_KEY: &str = "recent_projects";

Expand Down Expand Up @@ -92,3 +97,53 @@ pub fn open_project<R: Runtime>(

Ok(project)
}

#[tauri::command]
pub fn start_server(window: Window) -> Result<(), ()> {
spawn(async {
let store: LibsqlStore = LibsqlStore::in_memory().await.unwrap();
LibsqlStore::migrate(&store).await.unwrap();
let store = Arc::new(store);

// Create a shared events struct, which allows events to be send to
// WebSocket connections.
let events = InMemoryEvents::new();
let events = Arc::new(events);

let mut reader = events.subscribe();
spawn(async move {
loop {
match reader.recv().await {
Ok(message) => {
window.emit("api_message", message).expect("emit failed");
}
Err(RecvError::Lagged(i)) => eprintln!("Lagged: {}", i),
Err(RecvError::Closed) => break,
}
}
});

let service = Service::new(store.clone(), events.clone());

let app = api::Builder::new()
.enable_compression()
.build(service.clone(), store.clone());

let listener = tokio::net::TcpListener::bind("127.0.0.1:6767")
.await
.unwrap();

// info!(
// api_listen_address = ?listener.local_addr().context("Failed to get local address")?,
// grpc_listen_address = ?args.grpc_listen_address,
// "Starting server",
// );

let api_server = axum::serve(listener, app);

if let Err(err) = api_server.await {
eprintln!("Server error: {:?}", err);
};
});
Ok(())
}
4 changes: 3 additions & 1 deletion fpx-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use models::AppState;
use std::{env, sync::Mutex};
use std::env;
use std::sync::Mutex;
use tauri::Manager;
use tauri_plugin_store::StoreBuilder;

Expand All @@ -23,6 +24,7 @@ fn main() {
.invoke_handler(tauri::generate_handler![
commands::list_recent_projects,
commands::open_project,
commands::start_server,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
Expand Down
1 change: 0 additions & 1 deletion fpx/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ fpx-lib = { version = "0.1.0", path = "../fpx-lib", features = ["libsql"] }
hex = { version = "0.4" }
http = { version = "1.1" }
http-body-util = { version = "0.1" }
include_dir = { version = "0.7.3" }
libsql = { version = "0.5", default-features = false, features = ["core", "serde"] }
once_cell = { version = "1.19" }
opentelemetry = { version = "0.24" }
Expand Down
4 changes: 2 additions & 2 deletions fpx/src/commands/dev.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::data::LibsqlStore;
use crate::events::InMemoryEvents;
use crate::grpc::GrpcService;
use crate::initialize_fpx_dir;
use anyhow::{Context, Result};
use fpx_lib::data::libsql::LibsqlStore;
use fpx_lib::events::memory::InMemoryEvents;
use fpx_lib::{api, service};
use opentelemetry_proto::tonic::collector::trace::v1::trace_service_server::TraceServiceServer;
use std::future::IntoFuture;
Expand Down
2 changes: 0 additions & 2 deletions fpx/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ use tracing_subscriber::{EnvFilter, Registry};

mod api;
mod commands;
pub mod data;
pub mod events;
pub mod grpc;

#[tokio::main]
Expand Down

0 comments on commit f8e7158

Please sign in to comment.