memos/server/server.go

213 lines
5.9 KiB
Go
Raw Normal View History

2022-02-03 15:32:03 +08:00
package server
import (
2023-01-02 23:18:12 +08:00
"context"
2022-02-03 15:32:03 +08:00
"fmt"
2024-04-18 21:41:00 +08:00
"log/slog"
"net"
"net/http"
2023-09-17 19:20:03 +08:00
"strings"
2022-02-04 18:54:24 +08:00
"time"
2022-02-03 15:32:03 +08:00
"github.com/google/uuid"
"github.com/labstack/echo/v4"
2023-01-02 23:18:12 +08:00
"github.com/pkg/errors"
2024-04-18 21:41:00 +08:00
"github.com/soheilhy/cmux"
"google.golang.org/grpc"
2023-09-17 22:55:13 +08:00
storepb "github.com/usememos/memos/proto/gen/store"
2022-06-27 22:09:06 +08:00
"github.com/usememos/memos/server/profile"
2024-04-13 12:07:53 +08:00
"github.com/usememos/memos/server/route/api/auth"
2024-04-28 00:44:29 +08:00
apiv1 "github.com/usememos/memos/server/route/api/v1"
2024-02-29 01:32:59 +08:00
"github.com/usememos/memos/server/route/frontend"
2024-04-13 12:07:53 +08:00
"github.com/usememos/memos/server/route/resource"
"github.com/usememos/memos/server/route/rss"
2023-11-06 20:49:02 +08:00
versionchecker "github.com/usememos/memos/server/service/version_checker"
2022-06-27 22:09:06 +08:00
"github.com/usememos/memos/store"
2022-02-03 15:32:03 +08:00
)
type Server struct {
Secret string
Profile *profile.Profile
Store *store.Store
2024-04-18 21:41:00 +08:00
echoServer *echo.Echo
grpcServer *grpc.Server
2022-02-03 15:32:03 +08:00
}
func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store) (*Server, error) {
2023-02-03 10:30:18 +08:00
s := &Server{
Store: store,
2023-02-03 10:30:18 +08:00
Profile: profile,
}
2024-04-18 21:41:00 +08:00
echoServer := echo.New()
echoServer.Debug = true
echoServer.HideBanner = true
echoServer.HidePort = true
s.echoServer = echoServer
2024-02-29 23:54:43 +08:00
// Register CORS middleware.
2024-04-18 21:41:00 +08:00
echoServer.Use(CORSMiddleware(s.Profile.Origins))
2024-02-04 23:48:26 +08:00
workspaceBasicSetting, err := s.getOrUpsertWorkspaceBasicSetting(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get workspace basic setting")
}
2022-02-03 15:32:03 +08:00
secret := "usememos"
2022-05-02 09:40:25 +08:00
if profile.Mode == "prod" {
secret = workspaceBasicSetting.SecretKey
2022-03-29 07:30:29 +08:00
}
s.Secret = secret
2023-11-26 23:06:50 +08:00
// Register healthz endpoint.
2024-04-18 21:41:00 +08:00
echoServer.GET("/healthz", func(c echo.Context) error {
2023-11-26 23:33:34 +08:00
return c.String(http.StatusOK, "Service ready.")
2023-11-26 23:06:50 +08:00
})
2024-02-29 23:54:43 +08:00
// Only serve frontend when it's enabled.
if profile.Frontend {
frontendService := frontend.NewFrontendService(profile, store)
2024-04-18 21:41:00 +08:00
frontendService.Serve(ctx, echoServer)
2024-02-29 23:54:43 +08:00
}
2024-04-18 21:41:00 +08:00
rootGroup := echoServer.Group("")
2024-04-13 12:07:53 +08:00
// Register public routes.
publicGroup := rootGroup.Group("/o")
publicGroup.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return auth.JWTMiddleware(s.Store, next, s.Secret)
})
// Create and register resource public routes.
resource.NewResourceService(s.Profile, s.Store).RegisterRoutes(publicGroup)
2024-04-13 12:10:57 +08:00
// Create and register RSS routes.
2024-04-13 12:07:53 +08:00
rss.NewRSSService(s.Profile, s.Store).RegisterRoutes(rootGroup)
2024-04-18 21:41:00 +08:00
grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor(
2024-04-28 00:44:29 +08:00
apiv1.NewLoggerInterceptor().LoggerInterceptor,
apiv1.NewGRPCAuthInterceptor(store, secret).AuthenticationInterceptor,
2024-04-18 21:41:00 +08:00
))
s.grpcServer = grpcServer
2024-04-28 00:44:29 +08:00
apiV1Service := apiv1.NewAPIV1Service(s.Secret, profile, store, grpcServer)
// Register gRPC gateway as api v1.
if err := apiV1Service.RegisterGateway(ctx, echoServer); err != nil {
2023-09-17 22:55:13 +08:00
return nil, errors.Wrap(err, "failed to register gRPC gateway")
}
return s, nil
2022-02-03 15:32:03 +08:00
}
2024-04-18 23:34:35 +08:00
func (s *Server) Start(ctx context.Context) error {
2024-04-18 21:41:00 +08:00
address := fmt.Sprintf(":%d", s.Profile.Port)
listener, err := net.Listen("tcp", address)
if err != nil {
return errors.Wrap(err, "failed to listen")
}
muxServer := cmux.New(listener)
go func() {
2024-04-30 10:18:04 +08:00
grpcListener := muxServer.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
2024-04-18 21:41:00 +08:00
if err := s.grpcServer.Serve(grpcListener); err != nil {
slog.Error("failed to serve gRPC", err)
}
}()
go func() {
httpListener := muxServer.Match(cmux.HTTP1Fast(), cmux.Any())
s.echoServer.Listener = httpListener
if err := s.echoServer.Start(address); err != nil {
slog.Error("failed to start echo server", err)
}
}()
2024-04-18 23:34:35 +08:00
s.StartBackgroundRunners(ctx)
2024-04-18 21:41:00 +08:00
return muxServer.Serve()
2023-01-01 21:32:17 +08:00
}
2023-01-02 23:18:12 +08:00
2023-02-03 10:30:18 +08:00
func (s *Server) Shutdown(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
2024-04-29 08:00:37 +08:00
// Shutdown echo server.
2024-04-18 21:41:00 +08:00
if err := s.echoServer.Shutdown(ctx); err != nil {
2023-02-03 10:30:18 +08:00
fmt.Printf("failed to shutdown server, error: %v\n", err)
}
2024-04-29 08:00:37 +08:00
// Close database connection.
if err := s.Store.Close(); err != nil {
2023-02-03 10:30:18 +08:00
fmt.Printf("failed to close database, error: %v\n", err)
}
fmt.Printf("memos stopped properly\n")
}
2024-04-18 23:34:35 +08:00
func (s *Server) StartBackgroundRunners(ctx context.Context) {
2024-04-18 21:41:00 +08:00
go versionchecker.NewVersionChecker(s.Store, s.Profile).Start(ctx)
}
func (s *Server) getOrUpsertWorkspaceBasicSetting(ctx context.Context) (*storepb.WorkspaceBasicSetting, error) {
workspaceBasicSetting, err := s.Store.GetWorkspaceBasicSetting(ctx)
2023-07-06 22:53:38 +08:00
if err != nil {
return nil, errors.Wrap(err, "failed to get workspace basic setting")
}
modified := false
if workspaceBasicSetting.SecretKey == "" {
workspaceBasicSetting.SecretKey = uuid.NewString()
modified = true
}
if modified {
2024-04-17 08:56:52 +08:00
workspaceSetting, err := s.Store.UpsertWorkspaceSetting(ctx, &storepb.WorkspaceSetting{
Key: storepb.WorkspaceSettingKey_WORKSPACE_SETTING_BASIC,
Value: &storepb.WorkspaceSetting_BasicSetting{BasicSetting: workspaceBasicSetting},
})
if err != nil {
return nil, errors.Wrap(err, "failed to upsert workspace setting")
}
workspaceBasicSetting = workspaceSetting.GetBasicSetting()
}
return workspaceBasicSetting, nil
}
2023-09-17 19:20:03 +08:00
func grpcRequestSkipper(c echo.Context) bool {
2024-04-28 00:44:29 +08:00
return strings.HasPrefix(c.Request().URL.Path, "/memos.api.v1.")
}
2024-04-07 22:15:15 +08:00
func CORSMiddleware(origins []string) echo.MiddlewareFunc {
2024-02-04 23:48:26 +08:00
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if grpcRequestSkipper(c) {
return next(c)
}
r := c.Request()
w := c.Response().Writer
2024-04-07 22:15:15 +08:00
requestOrigin := r.Header.Get("Origin")
if len(origins) == 0 {
w.Header().Set("Access-Control-Allow-Origin", requestOrigin)
} else {
for _, origin := range origins {
if origin == requestOrigin {
w.Header().Set("Access-Control-Allow-Origin", origin)
break
}
}
}
2024-02-05 06:10:10 +08:00
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS")
2024-02-04 23:48:26 +08:00
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// If it's preflight request, return immediately.
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return nil
}
2024-02-05 06:10:10 +08:00
return next(c)
2024-02-04 23:48:26 +08:00
}
}
}