Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Structure the server #33

Merged
merged 1 commit into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions server/cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package main

import (
"flag"
"log"
userv1 "sabitou-go/user/v1"

config "sabitou/configs"
"sabitou/internal/database"
grpc_server "sabitou/internal/grpc"
"sabitou/internal/services"

"google.golang.org/grpc"
)

func main() {
flag.Parse()

config, err := config.LoadConfig("configs/config.yml")
if err != nil {
log.Fatalf("Failed to load configuration: %v", err)
}
log.Printf("Starting server with configuration: %v", config)
// Use config values
port := config.Server.GRPC.Port
webPort := config.Server.GRPCWeb.Port
dbName := config.Database.DbName

db, err := database.InitDB(dbName)
if err != nil {
log.Fatalf("Failed to initialize database: %v", err)
}
defer db.Close()
grpcServer := grpc.NewServer()

// Register the user services.
userService := services.NewUserService(db)
userv1.RegisterUserServiceServer(grpcServer, userService)

// Start gRPC server
grpc_server.StartGRPCServer(grpcServer, &port, &webPort)

}
48 changes: 48 additions & 0 deletions server/configs/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package config

import (
"os"

"gopkg.in/yaml.v3"
)

type Config struct {
Server struct {
GRPC struct {
Port int `yaml:"port"`
} `yaml:"grpc"`
GRPCWeb struct {
Port int `yaml:"port"`
} `yaml:"grpc_web"`
} `yaml:"server"`
Database struct {
Driver string `yaml:"driver"`
DbName string `yaml:"db_name"`
} `yaml:"database"`
Cors struct {
AllowedOrigins []string `yaml:"allowed_origins"`
AllowedMethods []string `yaml:"allowed_methods"`
AllowedHeaders []string `yaml:"allowed_headers"`
ExposedHeaders []string `yaml:"exposed_headers"`
AllowCredentials bool `yaml:"allow_credentials"`
} `yaml:"cors"`
Auth struct {
Provider string `yaml:"provider"`
} `yaml:"auth"`
}

func LoadConfig(configPath string) (*Config, error) {
config := &Config{}

data, err := os.ReadFile(configPath)
if err != nil {
return nil, err
}

err = yaml.Unmarshal(data, config)
if err != nil {
return nil, err
}

return config, nil
}
31 changes: 31 additions & 0 deletions server/configs/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Server configuration
server:
grpc:
port: 50051
grpc_web:
port: 50052

# Database configuration
database:
driver: "sqlite3"
db_name: "sabitou.db"

# CORS configuration
cors:
allowed_origins:
- "*" # For development. Replace with specific origins in production.
allowed_methods:
- "GET"
- "POST"
- "OPTIONS"
allowed_headers:
- "*"
exposed_headers:
- "grpc-status"
- "grpc-message"
allow_credentials: true

# Authentication configuration (placeholder for Eartho)
auth:
provider: "eartho"
# Add Eartho-specific configurations here when implemented
3 changes: 2 additions & 1 deletion server/go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module server
module sabitou

go 1.23.2

Expand All @@ -23,5 +23,6 @@ require (
google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 // indirect
google.golang.org/grpc v1.67.1 // indirect
google.golang.org/protobuf v1.35.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.6 // indirect
)
2 changes: 2 additions & 0 deletions server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,8 @@ gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
Expand Down
31 changes: 31 additions & 0 deletions server/internal/database/surreal_db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package database

import (
"database/sql"

_ "github.com/mattn/go-sqlite3"
)

func InitDB(dbPath string) (*sql.DB, error) {
db, err := sql.Open("sqlite3", dbPath)
if err != nil {
return nil, err
}

// Initialize database schema
_, err = db.Exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT,
connection_type TEXT NOT NULL
);
`)
if err != nil {
return nil, err
}

return db, nil
}
66 changes: 66 additions & 0 deletions server/internal/grpc/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package grpc_server

import (
"fmt"
"log"
"net"
"net/http"

"github.com/improbable-eng/grpc-web/go/grpcweb"
"github.com/rs/cors"
"google.golang.org/grpc"
)

func StartGRPCServer(grpcServer *grpc.Server, port *int, webPort *int) {
go func() {
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
log.Printf("gRPC server listening at %v", lis.Addr())
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}()

startGRPCWebProxy(grpcServer, webPort)
}

func startGRPCWebProxy(grpcServer *grpc.Server, webPort *int) {
// Create a gRPC-Web wrapper for the gRPC server
wrappedGrpc := grpcweb.WrapServer(grpcServer)

// Create a CORS wrapper
corsWrapper := cors.New(cors.Options{
// [TODO] update the origin for production.
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
AllowedHeaders: []string{"*"},
ExposedHeaders: []string{"grpc-status", "grpc-message"},
AllowCredentials: true,
})

// Set up a gRPC-Web proxy with CORS
handler := http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
if wrappedGrpc.IsGrpcWebRequest(req) {
wrappedGrpc.ServeHTTP(resp, req)
return
}
// Handle normal HTTP traffic
resp.WriteHeader(http.StatusOK)
resp.Write([]byte("gRPC-Web proxy server"))
})

corsHandler := corsWrapper.Handler(handler)

// Start gRPC-Web proxy
httpServer := &http.Server{
Addr: fmt.Sprintf(":%d", *webPort),
Handler: corsHandler,
}

log.Printf("gRPC-Web proxy server listening at :%d", *webPort)
if err := httpServer.ListenAndServe(); err != nil {
log.Fatalf("failed to serve gRPC-Web proxy: %v", err)
}
}
75 changes: 75 additions & 0 deletions server/internal/services/user_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package services

import (
"context"
"database/sql"
"log"

userv1 "sabitou-go/user/v1"

"connectrpc.com/connect"
"github.com/google/uuid"
)

type UserService struct {
db *sql.DB
userv1.UnimplementedUserServiceServer
}

func NewUserService(db *sql.DB) *UserService {
return &UserService{db: db}
}

// GetUser implements userv1connect.UserServiceHandler.
//
// GetUser takes a user ID or an email and a password and returns the
// corresponding user. If the user is not found, it returns a
// connect.Error with code equal to connect.CodeNotFound.
func (s *UserService) GetUser(ctx context.Context, req *userv1.GetUserRequest) (*userv1.User, error) {
var row *sql.Row
if req.Id != nil && *req.Id != "" {
row = s.db.QueryRow("SELECT id, first_name, last_name, email, password, connection_type FROM users WHERE id = ?", *req.Id)
} else {
row = s.db.QueryRow("SELECT id, first_name, last_name, email, password, connection_type FROM users WHERE email = ? AND password = ?",
req.Email, req.Password)
}
var id, firstName, lastName, email, password, connection_type string
if err := row.Scan(&id, &firstName, &lastName, &email, &password, &connection_type); err != nil {
return nil, connect.NewError(connect.CodeNotFound, err)
}
return &userv1.User{
Id: id,
FirstName: firstName,
LastName: lastName,
Email: email,
Password: &password,
ConnectionType: userv1.ConnectionType(userv1.ConnectionType_value[connection_type]),
}, nil
}

// CreateUser implements userv1connect.UserServiceHandler.
//
// CreateUser takes a CreateUserRequest and inserts a new user in the
// database. If the user is already present, it returns a connect.Error
// with code equal to connect.CodeAlreadyExists. If the insert fails, it
// returns a connect.Error with code equal to connect.CodeInternal.
func (s *UserService) CreateUser(ctx context.Context, req *userv1.CreateUserRequest) (*userv1.User, error) {
log.Printf("Received: %v", req.Email)
id := req.Id
if id == "" {
id = uuid.New().String()
}
_, err := s.db.Exec("INSERT INTO users (id, first_name, last_name, email, password, connection_type) VALUES (?, ?, ?, ?, ?, ?)",
id, req.FirstName, req.LastName, req.Email, req.Password, req.ConnectionType.String())
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
return &userv1.User{
Id: id,
FirstName: req.FirstName,
LastName: req.LastName,
Email: req.Email,
Password: req.Password,
ConnectionType: userv1.ConnectionType(req.ConnectionType),
}, nil
}
Loading
Loading