memos/server/server.go

226 lines
5.8 KiB
Go
Raw Normal View History

2022-02-03 10:32:03 +03:00
package server
import (
2023-01-02 18:18:12 +03:00
"context"
"encoding/json"
2022-02-03 10:32:03 +03:00
"fmt"
"net"
"net/http"
2022-02-04 13:54:24 +03:00
"time"
2022-02-03 10:32:03 +03:00
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
2023-01-02 18:18:12 +03:00
"github.com/pkg/errors"
apiv1 "github.com/usememos/memos/api/v1"
apiv2 "github.com/usememos/memos/api/v2"
"github.com/usememos/memos/common/log"
2023-07-06 17:53:38 +03:00
"github.com/usememos/memos/common/util"
"github.com/usememos/memos/plugin/telegram"
2022-06-27 17:09:06 +03:00
"github.com/usememos/memos/server/profile"
"github.com/usememos/memos/store"
"go.uber.org/zap"
"google.golang.org/grpc"
2022-02-03 10:32:03 +03:00
)
type Server struct {
e *echo.Echo
grpcServer *grpc.Server
2022-02-03 10:32:03 +03:00
ID string
Secret string
Profile *profile.Profile
Store *store.Store
2023-07-30 04:53:24 +03:00
// Asynchronous runners.
backupRunner *BackupRunner
telegramBot *telegram.Bot
2022-02-03 10:32:03 +03:00
}
func NewServer(ctx context.Context, profile *profile.Profile, store *store.Store) (*Server, error) {
2022-02-03 10:32:03 +03:00
e := echo.New()
e.Debug = true
e.HideBanner = true
2022-05-20 17:48:36 +03:00
e.HidePort = true
2022-02-03 10:32:03 +03:00
2023-02-03 05:30:18 +03:00
s := &Server{
e: e,
Store: store,
2023-02-03 05:30:18 +03:00
Profile: profile,
2023-07-30 04:53:24 +03:00
// Asynchronous runners.
backupRunner: NewBackupRunner(store),
telegramBot: telegram.NewBotWithHandler(newTelegramHandler(store)),
}
2022-02-04 13:54:24 +03:00
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
2022-08-18 19:45:02 +03:00
Format: `{"time":"${time_rfc3339}",` +
`"method":"${method}","uri":"${uri}",` +
`"status":${status},"error":"${error}"}` + "\n",
2022-02-04 13:54:24 +03:00
}))
e.Use(middleware.Gzip())
2022-07-30 09:52:37 +03:00
e.Use(middleware.CORS())
2023-01-07 05:51:34 +03:00
e.Use(middleware.SecureWithConfig(middleware.SecureConfig{
2023-02-12 12:29:23 +03:00
Skipper: defaultGetRequestSkipper,
2023-01-07 05:51:34 +03:00
XSSProtection: "1; mode=block",
ContentTypeNosniff: "nosniff",
XFrameOptions: "SAMEORIGIN",
HSTSPreloadEnabled: false,
}))
2022-02-04 13:54:24 +03:00
e.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{
Skipper: func(c echo.Context) bool {
// this is a hack to skip timeout for openai chat streaming
// because streaming require to flush response. But the timeout middleware will break it.
return c.Request().URL.Path == "/api/v1/openai/chat-streaming"
},
2022-02-04 13:54:24 +03:00
ErrorMessage: "Request timeout",
Timeout: 30 * time.Second,
}))
serverID, err := s.getSystemServerID(ctx)
if err != nil {
return nil, fmt.Errorf("failed to retrieve system server ID: %w", err)
}
s.ID = serverID
2022-02-03 10:32:03 +03:00
embedFrontend(e)
secret := "usememos"
2022-05-02 04:40:25 +03:00
if profile.Mode == "prod" {
secret, err = s.getSystemSecretSessionName(ctx)
if err != nil {
return nil, fmt.Errorf("failed to retrieve system secret session name: %w", err)
}
2022-03-29 02:30:29 +03:00
}
s.Secret = secret
rootGroup := e.Group("")
apiV1Service := apiv1.NewAPIV1Service(s.Secret, profile, store)
apiV1Service.Register(rootGroup)
// Register gPRC server services.
s.grpcServer = apiv2.NewGRPCServer(store)
// Register gRPC gateway as api v2.
if err := apiv2.RegisterGateway(ctx, e, s.Profile.Port+1); err != nil {
return nil, fmt.Errorf("failed to register gRPC gateway: %w", err)
}
return s, nil
2022-02-03 10:32:03 +03:00
}
func (s *Server) Start(ctx context.Context) error {
2023-01-02 18:18:12 +03:00
if err := s.createServerStartActivity(ctx); err != nil {
return errors.Wrap(err, "failed to create activity")
}
go s.telegramBot.Start(ctx)
2023-07-30 04:53:24 +03:00
go s.backupRunner.Run(ctx)
// Start gRPC server.
listen, err := net.Listen("tcp", fmt.Sprintf(":%d", s.Profile.Port+1))
if err != nil {
return err
}
go func() {
if err := s.grpcServer.Serve(listen); err != nil {
log.Error("grpc server listen error", zap.Error(err))
}
}()
return s.e.Start(fmt.Sprintf(":%d", s.Profile.Port))
2023-01-01 16:32:17 +03:00
}
2023-01-02 18:18:12 +03:00
2023-02-03 05:30:18 +03:00
func (s *Server) Shutdown(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
// Shutdown echo server
if err := s.e.Shutdown(ctx); err != nil {
fmt.Printf("failed to shutdown server, error: %v\n", err)
}
// Close database connection
if err := s.Store.GetDB().Close(); err != nil {
2023-02-03 05:30:18 +03:00
fmt.Printf("failed to close database, error: %v\n", err)
}
fmt.Printf("memos stopped properly\n")
}
func (s *Server) GetEcho() *echo.Echo {
return s.e
}
func (s *Server) getSystemServerID(ctx context.Context) (string, error) {
serverIDSetting, err := s.Store.GetSystemSetting(ctx, &store.FindSystemSetting{
Name: apiv1.SystemSettingServerIDName.String(),
})
2023-07-06 17:53:38 +03:00
if err != nil {
return "", err
}
if serverIDSetting == nil || serverIDSetting.Value == "" {
serverIDSetting, err = s.Store.UpsertSystemSetting(ctx, &store.SystemSetting{
Name: apiv1.SystemSettingServerIDName.String(),
Value: uuid.NewString(),
})
if err != nil {
return "", err
}
}
return serverIDSetting.Value, nil
}
func (s *Server) getSystemSecretSessionName(ctx context.Context) (string, error) {
secretSessionNameValue, err := s.Store.GetSystemSetting(ctx, &store.FindSystemSetting{
Name: apiv1.SystemSettingSecretSessionName.String(),
})
2023-07-06 17:53:38 +03:00
if err != nil {
return "", err
}
if secretSessionNameValue == nil || secretSessionNameValue.Value == "" {
secretSessionNameValue, err = s.Store.UpsertSystemSetting(ctx, &store.SystemSetting{
Name: apiv1.SystemSettingSecretSessionName.String(),
Value: uuid.NewString(),
})
if err != nil {
return "", err
}
}
return secretSessionNameValue.Value, nil
}
2023-01-02 18:18:12 +03:00
func (s *Server) createServerStartActivity(ctx context.Context) error {
payload := apiv1.ActivityServerStartPayload{
2023-01-03 15:05:37 +03:00
ServerID: s.ID,
Profile: s.Profile,
2023-01-02 18:18:12 +03:00
}
payloadBytes, err := json.Marshal(payload)
2023-01-02 18:18:12 +03:00
if err != nil {
return errors.Wrap(err, "failed to marshal activity payload")
}
activity, err := s.Store.CreateActivity(ctx, &store.Activity{
CreatorID: apiv1.UnknownID,
Type: apiv1.ActivityServerStart.String(),
Level: apiv1.ActivityInfo.String(),
Payload: string(payloadBytes),
2023-01-02 18:18:12 +03:00
})
2023-01-07 06:49:58 +03:00
if err != nil || activity == nil {
return errors.Wrap(err, "failed to create activity")
}
2023-01-02 18:18:12 +03:00
return err
}
func defaultGetRequestSkipper(c echo.Context) bool {
return c.Request().Method == http.MethodGet
}
func defaultAPIRequestSkipper(c echo.Context) bool {
path := c.Path()
2023-07-06 17:53:38 +03:00
return util.HasPrefixes(path, "/api", "/api/v1")
}