From f6b6cd7d6c87f190ecf115de3385aaa41a03cd94 Mon Sep 17 00:00:00 2001 From: "boweian@creditease.cn" Date: Wed, 5 Jun 2024 18:25:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E7=94=A8=E6=88=B7=E7=AE=A1?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/service/service_start.go | 23 +- src/pkg/auth/endpoint.go | 389 ++++++++++++++++-------- src/pkg/auth/http.go | 502 +++++++++++++++++++++++++++---- src/pkg/auth/logging.go | 187 ++++++++++-- src/pkg/auth/service.go | 184 ++++++++--- src/pkg/auth/tracing.go | 216 +++++++++++-- src/pkg/auth/types.go | 115 +++++++ src/repository/auth/logging.go | 215 ++++++++++--- src/repository/auth/service.go | 61 ++-- src/repository/auth/tracing.go | 246 ++++++++++++--- src/repository/model/logging.go | 456 ++++++++++++++++++++-------- src/repository/model/service.go | 11 +- src/repository/model/tracing.go | 425 +++++++++++++++++++++----- src/repository/tenant/logging.go | 90 +++++- src/repository/tenant/service.go | 9 + src/repository/tenant/tracing.go | 89 +++++- 16 files changed, 2616 insertions(+), 602 deletions(-) create mode 100644 src/pkg/auth/types.go diff --git a/cmd/service/service_start.go b/cmd/service/service_start.go index dd43252..3aca50c 100644 --- a/cmd/service/service_start.go +++ b/cmd/service/service_start.go @@ -4,6 +4,17 @@ import ( "context" "embed" "fmt" + "io/fs" + "net" + "net/http" + "net/http/httputil" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" + tiktoken2 "github.com/IceBearAI/aigc/src/helpers/tiktoken" "github.com/IceBearAI/aigc/src/pkg/assistants" "github.com/IceBearAI/aigc/src/pkg/auth" @@ -22,16 +33,6 @@ import ( "github.com/igm/sockjs-go/v3/sockjs" "github.com/pkoukk/tiktoken-go" "github.com/tmc/langchaingo/llms/openai" - "io/fs" - "net" - "net/http" - "net/http/httputil" - "os" - "os/signal" - "strconv" - "strings" - "syscall" - "time" "github.com/go-kit/kit/tracing/opentracing" @@ -66,9 +67,9 @@ aigc-server start -p :8080 return err } - _ = generateTable() // 判断是否需要初始化数据,如果没有则初始化数据 if !gormDB.Migrator().HasTable(types.Accounts{}) { + _ = generateTable() if err = initData(); err != nil { _ = level.Error(logger).Log("cmd.start.PreRunE", "initData", "err", err.Error()) return err diff --git a/src/pkg/auth/endpoint.go b/src/pkg/auth/endpoint.go index 394b472..869e46c 100644 --- a/src/pkg/auth/endpoint.go +++ b/src/pkg/auth/endpoint.go @@ -1,197 +1,330 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" + "github.com/IceBearAI/aigc/src/encode" - "github.com/IceBearAI/aigc/src/middleware" - "github.com/go-kit/kit/endpoint" - "time" + endpoint "github.com/go-kit/kit/endpoint" ) -type ( - loginRequest struct { - // Username 登陆用户的邮箱或邮箱前缀 - Username string `json:"username" validate:"required"` - // Username 登陆用户的邮箱密码 - Password string `json:"password" validate:"required"` - } - - loginResult struct { - // Token jwt token - Token string `json:"token"` - // Username 登陆用户的姓名 - Username string `json:"username"` - // Avatar 登陆用户的头像地址 - Avatar string `json:"avatar,omitempty"` - } - accountRequest struct { - Email string `json:"email"` - } - tenant struct { - // TenantId 租户ID - Id string `json:"id"` - // TenantName 租户名称 - Name string `json:"name"` - } - accountResult struct { - // Tenant 租户信息 - Tenants []tenant `json:"tenants"` - Email string `json:"email"` - Nickname string `json:"nickname"` - Language string `json:"language"` - } +const ( + AccountMethodName = "Account" - TenantDetail struct { - Id uint `json:"id"` - Name string `json:"name"` - PublicTenantID string `json:"publicTenantId"` - ContactEmail string `json:"contactEmail"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - } + CreateAccountMethodName = "CreateAccount" - ListTenantRequest struct { - Page int `json:"page"` - PageSize int `json:"pageSize"` - Name string `json:"name"` - } + CreateTenantMethodName = "CreateTenant" - ListTenantResponse struct { - Tenants []TenantDetail `json:"list"` - Total int64 `json:"total"` - } + DeleteAccountMethodName = "DeleteAccount" - CreateAccountRequest struct { - Nickname string `json:"nickname" validate:"required"` - Email string `json:"email" validate:"required"` - IsLdap bool `json:"isLdap"` - Password string `json:"password"` - TenantId uint `json:"tenantId"` - Language string `json:"language" validate:"required"` - } + DeleteTenantMethodName = "DeleteTenant" - Account struct { - Id uint `json:"id"` - Email string `json:"email"` - Nickname string `json:"nickname"` - Status bool `json:"status"` - IsLdap bool `json:"isLdap"` - Language string `json:"language"` - CreatedAt time.Time `json:"createdAt"` - UpdatedAt time.Time `json:"updatedAt"` - } + ListAccountMethodName = "ListAccount" - ListAccountRequest struct { - Page int `json:"page"` - PageSize int `json:"pageSize"` - Email string `json:"email"` - Nickname string `json:"nickname"` - IsLdap *bool `json:"isLdap,omitempty"` - Status *bool `json:"status,omitempty"` - } + ListTenantsMethodName = "ListTenants" - ListAccountResponse struct { - Accounts []Account `json:"list"` - Total int64 `json:"total"` - } + LoginMethodName = "Login" - CreateTenantRequest struct { - Name string `json:"name" validate:"required"` - ContactEmail string `json:"contactEmail" validate:"required"` - } + UpdateAccountMethodName = "UpdateAccount" - UpdateAccountRequest struct { - Id uint `json:"id" validate:"required"` - Nickname string `json:"nickname"` - Email string `json:"email"` - IsLdap *bool `json:"isLdap"` - Language string `json:"language"` - Status *bool `json:"status,omitempty"` - Password string `json:"password"` - } + UpdateTenantMethodName = "UpdateTenant" ) type Endpoints struct { - LoginEndpoint endpoint.Endpoint - AccountEndpoint endpoint.Endpoint + AccountEndpoint endpoint.Endpoint + CreateAccountEndpoint endpoint.Endpoint - ListTenantsEndpoint endpoint.Endpoint - CreateTenantEndpoint endpoint.Endpoint + + CreateTenantEndpoint endpoint.Endpoint + + DeleteAccountEndpoint endpoint.Endpoint + + DeleteTenantEndpoint endpoint.Endpoint + + ListAccountEndpoint endpoint.Endpoint + + ListTenantsEndpoint endpoint.Endpoint + + LoginEndpoint endpoint.Endpoint + + UpdateAccountEndpoint endpoint.Endpoint + + UpdateTenantEndpoint endpoint.Endpoint } func NewEndpoint(s Service, dmw map[string][]endpoint.Middleware) Endpoints { eps := Endpoints{ - LoginEndpoint: makeLoginEndpoint(s), - AccountEndpoint: makeAccountEndpoint(s), + + AccountEndpoint: makeAccountEndpoint(s), + CreateAccountEndpoint: makeCreateAccountEndpoint(s), - ListTenantsEndpoint: makeListTenantsEndpoint(s), - CreateTenantEndpoint: makeCreateTenantEndpoint(s), + + CreateTenantEndpoint: makeCreateTenantEndpoint(s), + + DeleteAccountEndpoint: makeDeleteAccountEndpoint(s), + + DeleteTenantEndpoint: makeDeleteTenantEndpoint(s), + + ListAccountEndpoint: makeListAccountEndpoint(s), + + ListTenantsEndpoint: makeListTenantsEndpoint(s), + + LoginEndpoint: makeLoginEndpoint(s), + + UpdateAccountEndpoint: makeUpdateAccountEndpoint(s), + + UpdateTenantEndpoint: makeUpdateTenantEndpoint(s), } - for _, m := range dmw["Auth"] { - eps.LoginEndpoint = m(eps.LoginEndpoint) + for _, m := range dmw[AccountMethodName] { eps.AccountEndpoint = m(eps.AccountEndpoint) + } + + for _, m := range dmw[CreateAccountMethodName] { eps.CreateAccountEndpoint = m(eps.CreateAccountEndpoint) - eps.ListTenantsEndpoint = m(eps.ListTenantsEndpoint) + } + + for _, m := range dmw[CreateTenantMethodName] { eps.CreateTenantEndpoint = m(eps.CreateTenantEndpoint) } + + for _, m := range dmw[DeleteAccountMethodName] { + eps.DeleteAccountEndpoint = m(eps.DeleteAccountEndpoint) + } + + for _, m := range dmw[DeleteTenantMethodName] { + eps.DeleteTenantEndpoint = m(eps.DeleteTenantEndpoint) + } + + for _, m := range dmw[ListAccountMethodName] { + eps.ListAccountEndpoint = m(eps.ListAccountEndpoint) + } + + for _, m := range dmw[ListTenantsMethodName] { + eps.ListTenantsEndpoint = m(eps.ListTenantsEndpoint) + } + + for _, m := range dmw[LoginMethodName] { + eps.LoginEndpoint = m(eps.LoginEndpoint) + } + + for _, m := range dmw[UpdateAccountMethodName] { + eps.UpdateAccountEndpoint = m(eps.UpdateAccountEndpoint) + } + + for _, m := range dmw[UpdateTenantMethodName] { + eps.UpdateTenantEndpoint = m(eps.UpdateTenantEndpoint) + } + return eps } -func makeLoginEndpoint(s Service) endpoint.Endpoint { +func makeAccountEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(loginRequest) - res, err := s.Login(ctx, req.Username, req.Password) + + req := request.(AccountRequest) + + var res AccountResult + + res, err = s.Account( + ctx, + + req.Email, + ) + return encode.Response{ Data: res, Error: err, - }, err + }, nil + } } -func makeAccountEndpoint(s Service) endpoint.Endpoint { +func makeCreateAccountEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { - email, _ := middleware.GetEmail(ctx) - res, err := s.Account(ctx, email) + + req := request.(CreateAccountRequest) + + var res Account + + res, err = s.CreateAccount( + ctx, + + req, + ) + return encode.Response{ Data: res, Error: err, - }, err + }, nil + } } -func makeCreateAccountEndpoint(s Service) endpoint.Endpoint { +func makeCreateTenantEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(CreateAccountRequest) - if req.TenantId == 0 { - req.TenantId, _ = middleware.GetTenantId(ctx) - } - res, err := s.CreateAccount(ctx, req) + + req := request.(CreateTenantRequest) + + var res TenantDetail + + res, err = s.CreateTenant( + ctx, + + req, + ) + return encode.Response{ Data: res, Error: err, - }, err + }, nil + + } +} + +func makeDeleteAccountEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(DeleteAccountRequest) + + err = s.DeleteAccount( + ctx, + + req.Id, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} + +func makeDeleteTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(DeleteTenantRequest) + + err = s.DeleteTenant( + ctx, + + req.Id, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + + } +} + +func makeListAccountEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(ListAccountRequest) + + var list []Account + + var total int64 + + list, total, err = s.ListAccount( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{ + "list": list, + "total": total}, + Error: err, + }, nil + } } func makeListTenantsEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { + req := request.(ListTenantRequest) - res, err := s.ListTenants(ctx, req) + + var list []TenantDetail + + var total int64 + + list, total, err = s.ListTenants( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{ + "list": list, + "total": total}, + Error: err, + }, nil + + } +} + +func makeLoginEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(LoginRequest) + + var res LoginResult + + res, err = s.Login( + ctx, + + req, + ) + return encode.Response{ Data: res, Error: err, - }, err + }, nil + } } -func makeCreateTenantEndpoint(s Service) endpoint.Endpoint { +func makeUpdateAccountEndpoint(s Service) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (response interface{}, err error) { - req := request.(CreateTenantRequest) - resp, err := s.CreateTenant(ctx, req) + + req := request.(UpdateAccountRequest) + + err = s.UpdateAccount( + ctx, + + req, + ) + return encode.Response{ - Data: resp, + Data: map[string]interface{}{}, Error: err, - }, err + }, nil + + } +} + +func makeUpdateTenantEndpoint(s Service) endpoint.Endpoint { + return func(ctx context.Context, request interface{}) (response interface{}, err error) { + + req := request.(UpdateTenantRequest) + + err = s.UpdateTenant( + ctx, + + req, + ) + + return encode.Response{ + Data: map[string]interface{}{}, + Error: err, + }, nil + } } diff --git a/src/pkg/auth/http.go b/src/pkg/auth/http.go index 0503c14..ada25b7 100644 --- a/src/pkg/auth/http.go +++ b/src/pkg/auth/http.go @@ -1,124 +1,504 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" "encoding/json" + "net/http" + "github.com/IceBearAI/aigc/src/encode" - "github.com/IceBearAI/aigc/src/helpers/page" - "github.com/IceBearAI/aigc/src/middleware" - "github.com/go-kit/kit/endpoint" + endpoint "github.com/go-kit/kit/endpoint" kithttp "github.com/go-kit/kit/transport/http" "github.com/go-playground/validator/v10" "github.com/gorilla/mux" "github.com/pkg/errors" - "net/http" + "github.com/spf13/cast" ) var validate = validator.New() - func MakeHTTPHandler(s Service, dmw []endpoint.Middleware, opts []kithttp.ServerOption) http.Handler { var ems []endpoint.Middleware + + opts = append(opts, kithttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context { + return ctx + })) + ems = append(ems, dmw...) - var kitopts = []kithttp.ServerOption{ - kithttp.ServerBefore(func(ctx context.Context, request *http.Request) context.Context { - return ctx - }), - kithttp.ServerAfter(func(ctx context.Context, response http.ResponseWriter) context.Context { - return ctx - }), - } - kitopts = append(opts, kitopts...) eps := NewEndpoint(s, map[string][]endpoint.Middleware{ - "Auth": ems, + + AccountMethodName: ems, + + CreateAccountMethodName: ems, + + CreateTenantMethodName: ems, + + DeleteAccountMethodName: ems, + + DeleteTenantMethodName: ems, + + ListAccountMethodName: ems, + + ListTenantsMethodName: ems, + + LoginMethodName: ems, + + UpdateAccountMethodName: ems, + + UpdateTenantMethodName: ems, }) r := mux.NewRouter() - r.Handle("/login", kithttp.NewServer( - eps.LoginEndpoint, - decodeLoginRequest, - encode.JsonResponse, - kitopts..., - )).Methods(http.MethodPost) r.Handle("/account", kithttp.NewServer( eps.AccountEndpoint, - kithttp.NopRequestDecoder, + decodeAccountRequest, encode.JsonResponse, - kitopts..., - )).Methods(http.MethodGet) + opts..., + )).Methods("GET") + r.Handle("/account", kithttp.NewServer( eps.CreateAccountEndpoint, decodeCreateAccountRequest, encode.JsonResponse, - kitopts..., - )).Methods(http.MethodPost) + opts..., + )).Methods("POST") + + r.Handle("/tenants", kithttp.NewServer( + eps.CreateTenantEndpoint, + decodeCreateTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + r.Handle("/account/{id}", kithttp.NewServer( + eps.DeleteAccountEndpoint, + decodeDeleteAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("DELETE") + + r.Handle("/tenant/{id}", kithttp.NewServer( + eps.DeleteTenantEndpoint, + decodeDeleteTenantRequest, + encode.JsonResponse, + opts..., + )).Methods("DELETE") + + r.Handle("/accounts", kithttp.NewServer( + eps.ListAccountEndpoint, + decodeListAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("GET") + r.Handle("/tenants", kithttp.NewServer( eps.ListTenantsEndpoint, decodeListTenantsRequest, encode.JsonResponse, - kitopts..., - )).Methods(http.MethodGet) - r.Handle("/tenants", kithttp.NewServer( - eps.CreateTenantEndpoint, - decodeCreateTenantRequest, + opts..., + )).Methods("GET") + + r.Handle("/login", kithttp.NewServer( + eps.LoginEndpoint, + decodeLoginRequest, + encode.JsonResponse, + opts..., + )).Methods("POST") + + r.Handle("/account/{id}", kithttp.NewServer( + eps.UpdateAccountEndpoint, + decodeUpdateAccountRequest, + encode.JsonResponse, + opts..., + )).Methods("PUT") + + r.Handle("/tenant/{id}", kithttp.NewServer( + eps.UpdateTenantEndpoint, + decodeUpdateTenantRequest, encode.JsonResponse, - kitopts..., - )).Methods(http.MethodPost) + opts..., + )).Methods("PUT") + return r } -func decodeLoginRequest(_ context.Context, r *http.Request) (interface{}, error) { - var req loginRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { +// Account +// @Summary 获取账号信息 +// @Description 获取账号信息 +// @tags Account +// @Accept json +// @Produce json +// @Success 200 {object} encode.Response{data=AccountResult} +// @Router /account [GET] +func decodeAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := AccountRequest{} + +err = validate.Struct(req) + if err != nil { return nil, encode.InvalidParams.Wrap(err) } - err := validate.Struct(req) + return req, err +} + +// CreateAccount +// @Summary 创建账号 +// @Description 创建账号 +// @tags Account +// @Accept json +// @Produce json +// @Param CreateAccountRequest body CreateAccountRequest true "http request body" +// @Success 200 {object} encode.Response{data=Account} +// @Router /account [POST] +func decodeCreateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := CreateAccountRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) if err != nil { return nil, encode.InvalidParams.Wrap(err) } - return req, nil + return req, err } -func decodeAccountRequest(ctx context.Context, r *http.Request) (interface{}, error) { - email, _ := middleware.GetEmail(ctx) - return accountRequest{ - Email: email, - }, nil +// CreateTenant +// @Summary 创建租户 +// @Description 创建租户 +// @tags Account +// @Accept json +// @Produce json +// @Param CreateTenantRequest body CreateTenantRequest true "http request body" +// @Success 200 {object} encode.Response{data=TenantDetail} +// @Router /tenants [POST] +func decodeCreateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := CreateTenantRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err } -func decodeCreateAccountRequest(ctx context.Context, r *http.Request) (interface{}, error) { - var req CreateAccountRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { +// DeleteAccount +// @Summary 删除账号 +// @Description 删除账号 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Success 200 {object} encode.Response{} +// @Router /account/{id} [DELETE] +func decodeDeleteAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := DeleteAccountRequest{} + + var _id uint + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { return nil, encode.InvalidParams.Wrap(err) } - err := validate.Struct(req) + return req, err +} + +// DeleteTenant +// @Summary 删除租户 +// @Description 删除租户 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Success 200 {object} encode.Response{} +// @Router /tenant/{id} [DELETE] +func decodeDeleteTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := DeleteTenantRequest{} + + var _id uint + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) if err != nil { return nil, encode.InvalidParams.Wrap(err) } - if !req.IsLdap && req.Password == "" { - return nil, encode.InvalidParams.Wrap(errors.New("创建非LDAP账户,密码不能为空")) + return req, err +} + +// ListAccount +// @Summary 获取账号列表 +// @Description 获取账号列表 +// @tags Account +// @Accept json +// @Produce json +// @Param email query string false " " +// @Param isLdap query string false " " +// @Param nickname query string false " " +// @Param page query string false " " +// @Param pageSize query string false " " +// @Success 200 {object} encode.Response{data.list=[]Account,data.total=int64} +// @Router /accounts [GET] +func decodeListAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := ListAccountRequest{} + + var _email string + + var _isLdap bool + + var _nickname string + + var _page int + + var _pageSize int + + _email = r.URL.Query().Get("email") + + _isLdapStr := r.URL.Query().Get("isLdap") + + if _isLdapStr != "" { + _isLdap, err = cast.ToBoolE(_isLdapStr) + + if err != nil { + return + } + } + + _nickname = r.URL.Query().Get("nickname") + + _pageStr := r.URL.Query().Get("page") + + if _pageStr != "" { + _page, err = cast.ToIntE(_pageStr) + + if err != nil { + return + } + } + + _pageSizeStr := r.URL.Query().Get("pageSize") + + if _pageSizeStr != "" { + _pageSize, err = cast.ToIntE(_pageSizeStr) + + if err != nil { + return + } + } + + req.Email = _email + + if _isLdapStr != "" { + req.IsLdap = &_isLdap + } + + req.Nickname = _nickname + + req.Page = _page + + req.PageSize = _pageSize + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err +} + +// ListTenants +// @Summary 获取租户列表 +// @Description 获取租户列表 +// @tags Account +// @Accept json +// @Produce json +// @Param name query string false " " +// @Param page query string false " " +// @Param pageSize query string false " " +// @Success 200 {object} encode.Response{data.list=[]TenantDetail,data.total=int64} +// @Router /tenants [GET] +func decodeListTenantsRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := ListTenantRequest{} + + var _name string + + var _page int + + var _pageSize int + + _name = r.URL.Query().Get("name") + + _pageStr := r.URL.Query().Get("page") + + if _pageStr != "" { + _page, err = cast.ToIntE(_pageStr) + + if err != nil { + return + } + } + + _pageSizeStr := r.URL.Query().Get("pageSize") + + if _pageSizeStr != "" { + _pageSize, err = cast.ToIntE(_pageSizeStr) + + if err != nil { + return + } } - return req, nil + + req.Name = _name + + req.Page = _page + + req.PageSize = _pageSize + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) + } + return req, err } -func decodeListTenantsRequest(ctx context.Context, r *http.Request) (interface{}, error) { - req := ListTenantRequest{ - Name: r.URL.Query().Get("name"), - Page: page.GetPage(r), - PageSize: page.GetPageSize(r), +// Login +// @Summary 平台授权登陆 +// @Description 平台授权登陆 +// @tags Account +// @Accept json +// @Produce json +// @Param LoginRequest body LoginRequest true "http request body" +// @Success 200 {object} encode.Response{data=LoginResult} +// @Router /login [POST] +func decodeLoginRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := LoginRequest{} + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + +err = validate.Struct(req) + if err != nil { + return nil, encode.InvalidParams.Wrap(err) } - return req, nil + return req, err } -func decodeCreateTenantRequest(ctx context.Context, r *http.Request) (interface{}, error) { - var req CreateTenantRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { +// UpdateAccount +// @Summary 更新账号 +// @Description 更新账号 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Param UpdateAccountRequest body UpdateAccountRequest true "http request body" +// @Success 200 {object} encode.Response{} +// @Router /account/{id} [PUT] +func decodeUpdateAccountRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := UpdateAccountRequest{} + + var _id uint + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) + if err != nil { return nil, encode.InvalidParams.Wrap(err) } - err := validate.Struct(req) + return req, err +} + +// UpdateTenant +// @Summary 更新租户 +// @Description 更新租户 +// @tags Account +// @Accept json +// @Produce json +// @Param id path string true " " +// @Param UpdateTenantRequest body UpdateTenantRequest true "http request body" +// @Success 200 {object} encode.Response{} +// @Router /tenant/{id} [PUT] +func decodeUpdateTenantRequest(ctx context.Context, r *http.Request) (res interface{}, err error) { + + req := UpdateTenantRequest{} + + var _id uint + + err = json.NewDecoder(r.Body).Decode(&req) + + if err != nil { + err = encode.Invalid.Wrap(errors.Wrap(err, "decode body")) + return + } + + vars := mux.Vars(r) + + _id, err = cast.ToUintE(vars["id"]) + + if err != nil { + return + } + + req.Id = _id + +err = validate.Struct(req) if err != nil { return nil, encode.InvalidParams.Wrap(err) } - return req, nil + return req, err } diff --git a/src/pkg/auth/logging.go b/src/pkg/auth/logging.go index f1cf0de..65f45a0 100644 --- a/src/pkg/auth/logging.go +++ b/src/pkg/auth/logging.go @@ -1,11 +1,13 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" - "fmt" - "github.com/go-kit/log" - "github.com/go-kit/log/level" + "encoding/json" "time" + + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -14,88 +16,225 @@ type logging struct { traceId string } -func (s *logging) UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) { +func (s *logging) Account(ctx context.Context, email string) (res AccountResult, err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "UpdateAccount", "request", fmt.Sprintf("%+v", request), + "method", "Account", + + "email", email, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.UpdateAccount(ctx, request) + + return s.next.Account(ctx, email) + } -func (s *logging) ListAccount(ctx context.Context, request ListAccountRequest) (res ListAccountResponse, err error) { +func (s *logging) CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) { + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "ListAccount", "request", fmt.Sprintf("%+v", request), + "method", "CreateAccount", + + "req", reqJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.ListAccount(ctx, request) + + return s.next.CreateAccount(ctx, req) + } -func (s *logging) CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) { +func (s *logging) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "CreateTenant", "request", fmt.Sprintf("%+v", request), + "method", "CreateTenant", + + "req", reqJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.CreateTenant(ctx, request) + + return s.next.CreateTenant(ctx, req) + } -func (s *logging) ListTenants(ctx context.Context, request ListTenantRequest) (res ListTenantResponse, err error) { +func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "ListTenants", "request", fmt.Sprintf("%+v", request), + "method", "DeleteAccount", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.ListTenants(ctx, request) + + return s.next.DeleteAccount(ctx, id) + } -func (s *logging) CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) { +func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "CreateAccount", "request", fmt.Sprintf("%+v", request), + "method", "DeleteTenant", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.CreateAccount(ctx, request) + + return s.next.DeleteTenant(ctx, id) + } -func (s *logging) Account(ctx context.Context, email string) (res accountResult, err error) { +func (s *logging) ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) { + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "Account", "email", email, + "method", "ListAccount", + + "req", reqJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.Account(ctx, email) + + return s.next.ListAccount(ctx, req) + } -func (s *logging) Login(ctx context.Context, username, password string) (res loginResult, err error) { +func (s *logging) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "Login", "username", username, + "method", "ListTenants", + + "req", reqJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.Login(ctx, username, password) + + return s.next.ListTenants(ctx, req) + +} + +func (s *logging) Login(ctx context.Context, req LoginRequest) (res LoginResult, err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "Login", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.Login(ctx, req) + +} + +func (s *logging) UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateAccount", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.UpdateAccount(ctx, req) + +} + +func (s *logging) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + + defer func(begin time.Time) { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateTenant", + + "req", reqJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.UpdateTenant(ctx, req) + } func NewLogging(logger log.Logger, traceId string) Middleware { diff --git a/src/pkg/auth/service.go b/src/pkg/auth/service.go index 543516e..9beb702 100644 --- a/src/pkg/auth/service.go +++ b/src/pkg/auth/service.go @@ -2,8 +2,11 @@ package auth import ( "context" + "time" + "github.com/IceBearAI/aigc/src/encode" authjwt "github.com/IceBearAI/aigc/src/jwt" + "github.com/IceBearAI/aigc/src/middleware" "github.com/IceBearAI/aigc/src/repository" "github.com/IceBearAI/aigc/src/repository/auth" "github.com/IceBearAI/aigc/src/repository/types" @@ -15,25 +18,54 @@ import ( "github.com/pkg/errors" "golang.org/x/crypto/bcrypt" "gorm.io/gorm" - "time" ) +// 用户管理 +// @tags Account type Service interface { // Login 平台授权登陆 // username, password: 用户名密码 - Login(ctx context.Context, username, password string) (res loginResult, err error) + // @kit-http /login POST + // @kit-http-request LoginRequest true + Login(ctx context.Context, req LoginRequest) (res LoginResult, err error) // Account 获取账号信息 - Account(ctx context.Context, email string) (res accountResult, err error) + // @kit-http /account GET + // @kit-http-request AccountRequest + Account(ctx context.Context, email string) (res AccountResult, err error) // ListTenants 获取租户列表 - ListTenants(ctx context.Context, request ListTenantRequest) (res ListTenantResponse, err error) - // CreateAccount 创建账号 - CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) + // @kit-http /tenants GET + // @kit-http-request ListTenantRequest + ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) + + // UpdateTenant 更新租户 + // @kit-http /tenant/{id} PUT + // @kit-http-request UpdateTenantRequest true + UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) // CreateTenant 创建租户 - CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) + // @kit-http /tenants POST + // @kit-http-request CreateTenantRequest true + CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) + // DeleteTenant 删除租户 + // @kit-http /tenant/{id} DELETE + // @kit-http-request DeleteTenantRequest + DeleteTenant(ctx context.Context, id uint) (err error) + // CreateAccount 创建账号 + // @kit-http /account POST + // @kit-http-request CreateAccountRequest true + CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) // ListAccount 获取账号列表 - ListAccount(ctx context.Context, request ListAccountRequest) (res ListAccountResponse, err error) + // @kit-http /accounts GET + // @kit-http-request ListAccountRequest + ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) // UpdateAccount 更新账号 - UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) + // @kit-http /account/{id} PUT + // @kit-http-request UpdateAccountRequest true + UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) + + // DeleteAccount 删除账号 + // @kit-http /account/{id} DELETE + // @kit-http-request DeleteAccountRequest + DeleteAccount(ctx context.Context, id uint) (err error) } type service struct { @@ -44,6 +76,48 @@ type service struct { apiSvc services.Service } +// UpdateTenant implements Service. +func (s *service) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + t, err := s.store.Auth().GetTenantById(ctx, req.Id) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + } + + t.Name = req.Name + t.ContactEmail = req.ContactEmail + t.Models, err = s.store.Model().FindByModelNames(ctx, req.ModelNames) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) + } + + err = s.store.Auth().UpdateTenant(ctx, &t) + if err != nil { + return encode.ErrSystem.Wrap(errors.Wrap(err, "更新租户失败")) + } + + return +} + +// DeleteTenant implements Service. +func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { + err = s.store.Auth().DeleteTenant(ctx, id) + if err != nil { + err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除租户失败")) + return + } + return +} + +// DeleteAccount implements Service. +func (s *service) DeleteAccount(ctx context.Context, id uint) (err error) { + err = s.store.Auth().DeleteAccount(ctx, id) + if err != nil { + err = encode.ErrSystem.Wrap(errors.Wrap(err, "删除账号失败")) + return + } + return +} + func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) { logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "UpdateAccount") data, err := s.store.Auth().GetAccountById(ctx, request.Id) @@ -52,13 +126,13 @@ func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountReques if errors.Is(err, gorm.ErrRecordNotFound) { return encode.ErrAccountNotFound.Error() } - return encode.ErrSystem.Wrap(errors.New("查询账号失败")) + return encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) } if request.Email != "" { res, err := s.store.Auth().GetAccountByEmail(ctx, request.Email) if err == nil && res.ID != data.ID { _ = level.Error(logger).Log("auth", "UpdateAccount", "err", "邮箱账号已存在") - return encode.InvalidParams.Wrap(errors.New("要更新邮箱账号已存在")) + return encode.InvalidParams.Wrap(errors.Wrap(err, "要更新邮箱账号已存在")) } data.Email = request.Email } @@ -81,10 +155,18 @@ func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountReques hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) if err != nil { _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) - return encode.ErrSystem.Wrap(errors.New("更新账号失败,请联系管理员")) + return encode.ErrSystem.Wrap(errors.Wrap(err, "更新账号失败,请联系管理员")) } data.PasswordHash = string(hash) } + + data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) + if err != nil { + _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + err = s.store.Auth().UpdateAccount(ctx, &data) if err != nil { _ = level.Error(logger).Log("auth", "UpdateAccount", "err", err.Error()) @@ -93,24 +175,24 @@ func (s *service) UpdateAccount(ctx context.Context, request UpdateAccountReques return nil } -func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) (res ListAccountResponse, err error) { +func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) (list []Account, total int64, err error) { logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListAccount") req := auth.ListAccountRequest{ Page: request.Page, PageSize: request.PageSize, Email: request.Email, + IsLdap: request.IsLdap, } accounts, total, err := s.store.Auth().ListAccount(ctx, req) if err != nil { _ = level.Error(logger).Log("auth", "ListAccount", "err", err.Error()) - return res, err + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询账号失败")) + return } - res.Total = total - res.Accounts = make([]Account, 0) for _, a := range accounts { - res.Accounts = append(res.Accounts, convertAccount(&a)) + list = append(list, convertAccount(&a)) } - return res, nil + return } func (s *service) CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) { @@ -120,6 +202,14 @@ func (s *service) CreateTenant(ctx context.Context, request CreateTenantRequest) PublicTenantID: uuid.New().String(), ContactEmail: request.ContactEmail, } + + models, err := s.store.Model().FindByModelNames(ctx, request.ModelNames) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询模型失败")) + return res, err + } + data.Models = models err = s.store.Auth().CreateTenant(ctx, &data) if err != nil { _ = level.Error(logger).Log("auth", "CreateTenant", "err", err.Error()) @@ -129,7 +219,7 @@ func (s *service) CreateTenant(ctx context.Context, request CreateTenantRequest) return res, nil } -func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (res ListTenantResponse, err error) { +func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (list []TenantDetail, total int64, err error) { logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId), "method", "ListTenants") req := auth.ListTenantRequest{ Page: request.Page, @@ -139,14 +229,13 @@ func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (r tenants, total, err := s.store.Auth().ListTenants(ctx, req) if err != nil { _ = level.Error(logger).Log("auth", "ListTenants", "err", err.Error()) - return res, err + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return } - res.Total = total - res.Tenants = make([]TenantDetail, 0) for _, t := range tenants { - res.Tenants = append(res.Tenants, convertTenant(&t)) + list = append(list, convertTenant(&t)) } - return res, nil + return } func (s *service) CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) { @@ -162,11 +251,18 @@ func (s *service) CreateAccount(ctx context.Context, request CreateAccountReques hash, err := bcrypt.GenerateFromPassword([]byte(request.Password), bcrypt.DefaultCost) if err != nil { _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) - return res, encode.ErrSystem.Wrap(errors.New("创建账号失败,请联系管理员")) + return res, encode.ErrSystem.Wrap(errors.Wrap(err, "创建账号失败,请联系管理员")) } data.PasswordHash = string(hash) } - err = s.store.Auth().CreateAccount(ctx, &data, request.TenantId) + data.Tenants, err = s.store.Tenants().FindByPublicTenantIdItems(ctx, request.TenantPublicTenantIdItems) + if err != nil { + _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) + err = encode.ErrSystem.Wrap(errors.Wrap(err, "查询租户失败")) + return + } + + err = s.store.Auth().CreateAccount(ctx, &data) if err != nil { _ = level.Error(logger).Log("auth", "CreateAccount", "err", err.Error()) return res, err @@ -175,7 +271,12 @@ func (s *service) CreateAccount(ctx context.Context, request CreateAccountReques return res, nil } -func (s *service) Account(ctx context.Context, email string) (res accountResult, err error) { +func (s *service) Account(ctx context.Context, email string) (res AccountResult, err error) { + email, ok := middleware.GetEmail(ctx) + if !ok { + _ = level.Error(s.logger).Log("auth", "Account, GetEmail error", "email", email) + return res, encode.ErrAccountNotFound.Error() + } account, err := s.store.Auth().GetAccountByEmail(ctx, email, "Tenants") if err != nil { _ = level.Error(s.logger).Log("auth", "account, GetAccountByEmail error", "email", email, "err", err.Error()) @@ -184,9 +285,9 @@ func (s *service) Account(ctx context.Context, email string) (res accountResult, res.Email = account.Email res.Nickname = account.Nickname res.Language = account.Language - res.Tenants = make([]tenant, 0) + res.Tenants = make([]Tenant, 0) for _, t := range account.Tenants { - res.Tenants = append(res.Tenants, tenant{ + res.Tenants = append(res.Tenants, Tenant{ Id: t.PublicTenantID, Name: t.Name, }) @@ -194,8 +295,10 @@ func (s *service) Account(ctx context.Context, email string) (res accountResult, return res, nil } -func (s *service) Login(ctx context.Context, username, password string) (res loginResult, err error) { +func (s *service) Login(ctx context.Context, req LoginRequest) (res LoginResult, err error) { logger := log.With(s.logger, s.traceId, ctx.Value(s.traceId)) + username := req.Username + password := req.Password if username == "" || password == "" { _ = level.Error(logger).Log("auth", "login, username or password is empty", "username", username, "password", password) return res, encode.ErrAccountLogin.Error() @@ -215,7 +318,7 @@ func (s *service) Login(ctx context.Context, username, password string) (res log //errNum, err := s.rdb.Get(ctx, errLoginKey).Int() //if err != nil && !errors.Is(err, redis.Nil) { // _ = level.Error(logger).Log("auth", "login, redis get errLoginKey error", "username", username, "err", err.Error()) - // return res, encode.ErrSystem.Wrap(errors.New("登录失败,请联系管理员")) + // return res, encode.ErrSystem.Wrap(errors.Wrap(err,"登录失败,请联系管理员")) //} //if errNum >= 5 { // _ = level.Error(logger).Log("auth", "login too many error times", "username", username, "err", encode.ErrLimiter.Error()) @@ -223,7 +326,7 @@ func (s *service) Login(ctx context.Context, username, password string) (res log //} // 获取账号信息 - account, err := s.store.Auth().GetAccountByEmail(ctx, username) + account, err := s.store.Auth().GetAccountByEmail(ctx, req.Username) if err != nil { _ = level.Error(logger).Log("auth", "login, GetAccountByEmail error", "username", username, "err", err.Error()) return res, encode.ErrAccountNotFound.Error() @@ -258,7 +361,7 @@ func (s *service) Login(ctx context.Context, username, password string) (res log tk, err := s.jwtToken(ctx, authjwt.TokenSourceNd, time.Duration(168)*time.Hour, username, "", account.ID) if err != nil { _ = level.Error(logger).Log("auth", "login, jwtToken error", "username", username, "err", err.Error()) - return res, encode.ErrSystem.Wrap(errors.New("登录失败,请联系管理员")) + return res, encode.ErrSystem.Wrap(errors.Wrap(err, "登录失败,请联系管理员")) } res.Token = tk res.Username = username @@ -293,7 +396,7 @@ func (s *service) jwtToken(ctx context.Context, source authjwt.TokenSource, time return } func convertTenant(data *types.Tenants) TenantDetail { - return TenantDetail{ + td := TenantDetail{ Id: data.ID, Name: data.Name, PublicTenantID: data.PublicTenantID, @@ -301,10 +404,15 @@ func convertTenant(data *types.Tenants) TenantDetail { CreatedAt: data.CreatedAt, UpdatedAt: data.UpdatedAt, } + + for _, v := range data.Models { + td.ModelNames = append(td.ModelNames, v.ModelName) + } + return td } func convertAccount(data *types.Accounts) Account { - return Account{ + res := Account{ Id: data.ID, Email: data.Email, IsLdap: data.IsLdap, @@ -314,6 +422,12 @@ func convertAccount(data *types.Accounts) Account { CreatedAt: data.CreatedAt, UpdatedAt: data.UpdatedAt, } + + for _, v := range data.Tenants { + res.Tenants = append(res.Tenants, convertTenant(&v)) + } + return res + } func New(logger log.Logger, traceId string, diff --git a/src/pkg/auth/tracing.go b/src/pkg/auth/tracing.go index f177d99..214b24f 100644 --- a/src/pkg/auth/tracing.go +++ b/src/pkg/auth/tracing.go @@ -1,8 +1,10 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" - "fmt" + "encoding/json" + "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) @@ -12,95 +14,255 @@ type tracing struct { tracer opentracing.Tracer } -func (s *tracing) UpdateAccount(ctx context.Context, request UpdateAccountRequest) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ +func (s *tracing) Account(ctx context.Context, email string) (res AccountResult, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "Account", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + span.LogKV( + "email", email, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.UpdateAccount(ctx, request) + + return s.next.Account(ctx, email) + } -func (s *tracing) ListAccount(ctx context.Context, request ListAccountRequest) (res ListAccountResponse, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ +func (s *tracing) CreateAccount(ctx context.Context, req CreateAccountRequest) (res Account, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "res", res, "err", err) + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.ListAccount(ctx, request) + + return s.next.CreateAccount(ctx, req) + } -func (s *tracing) CreateTenant(ctx context.Context, request CreateTenantRequest) (res TenantDetail, err error) { +func (s *tracing) CreateTenant(ctx context.Context, req CreateTenantRequest) (res TenantDetail, err error) { + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.CreateTenant(ctx, request) + + return s.next.CreateTenant(ctx, req) + } -func (s *tracing) ListTenants(ctx context.Context, request ListTenantRequest) (res ListTenantResponse, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ +func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.ListTenants(ctx, request) + + return s.next.DeleteAccount(ctx, id) + } -func (s *tracing) CreateAccount(ctx context.Context, request CreateAccountRequest) (res Account, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ +func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.CreateAccount(ctx, request) + + return s.next.DeleteTenant(ctx, id) + } -func (s *tracing) Account(ctx context.Context, email string) (res accountResult, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "Account", opentracing.Tag{ +func (s *tracing) ListAccount(ctx context.Context, req ListAccountRequest) (list []Account, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("email", email, "err", err) + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.Account(ctx, email) + + return s.next.ListAccount(ctx, req) + } -func (s *tracing) Login(ctx context.Context, username, password string) (res loginResult, err error) { +func (s *tracing) ListTenants(ctx context.Context, req ListTenantRequest) (list []TenantDetail, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.ListTenants(ctx, req) + +} + +func (s *tracing) Login(ctx context.Context, req LoginRequest) (res LoginResult, err error) { + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "Login", opentracing.Tag{ Key: string(ext.Component), Value: "pkg.auth", }) defer func() { - span.LogKV("username", username, "err", err) + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.Login(ctx, req) + +} + +func (s *tracing) UpdateAccount(ctx context.Context, req UpdateAccountRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.Login(ctx, username, password) + + return s.next.UpdateAccount(ctx, req) + +} + +func (s *tracing) UpdateTenant(ctx context.Context, req UpdateTenantRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ + Key: string(ext.Component), + Value: "pkg.auth", + }) + defer func() { + + reqByte, _ := json.Marshal(req) + reqJson := string(reqByte) + + span.LogKV( + "req", reqJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.UpdateTenant(ctx, req) + } func NewTracing(otTracer opentracing.Tracer) Middleware { diff --git a/src/pkg/auth/types.go b/src/pkg/auth/types.go new file mode 100644 index 0000000..edbe0fd --- /dev/null +++ b/src/pkg/auth/types.go @@ -0,0 +1,115 @@ +package auth + +import "time" + +type LoginRequest struct { + // Username 登陆用户的邮箱或邮箱前缀 + Username string `json:"username" validate:"required" param:",username"` + // Username 登陆用户的邮箱密码 + Password string `json:"password" validate:"required" param:",password"` +} + +type LoginResult struct { + // Token jwt token + Token string `json:"token"` + // Username 登陆用户的姓名 + Username string `json:"username"` + // Avatar 登陆用户的头像地址 + Avatar string `json:"avatar,omitempty"` +} +type AccountRequest struct { + Email string `json:"email" param:",email"` +} +type Tenant struct { + // TenantId 租户ID + Id string `json:"id"` + // TenantName 租户名称 + Name string `json:"name"` +} +type AccountResult struct { + // Tenant 租户信息 + Tenants []Tenant `json:"tenants"` + Email string `json:"email"` + Nickname string `json:"nickname"` + Language string `json:"language"` +} + +type TenantDetail struct { + Id uint `json:"id"` + Name string `json:"name"` + PublicTenantID string `json:"publicTenantId"` + ContactEmail string `json:"contactEmail"` + ModelNames []string `json:"modelNames"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} + +type ListTenantRequest struct { + Page int `json:"page" param:"query,page"` + PageSize int `json:"pageSize" param:"query,pageSize"` + Name string `json:"name" param:"query,name"` +} + +type CreateAccountRequest struct { + Nickname string `json:"nickname" validate:"required"` + Email string `json:"email" validate:"required"` + IsLdap bool `json:"isLdap"` + Password string `json:"password"` + Language string `json:"language" validate:"required"` + + TenantPublicTenantIdItems []string `json:"tenantPublicTenantIdItems"` +} + +type Account struct { + Id uint `json:"id"` + Email string `json:"email"` + Nickname string `json:"nickname"` + Status bool `json:"status"` + IsLdap bool `json:"isLdap"` + Language string `json:"language"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + + Tenants []TenantDetail `json:"tenants"` +} + +type ListAccountRequest struct { + Page int `json:"page" param:"query,page"` + PageSize int `json:"pageSize" param:"query,pageSize"` + Email string `json:"email" param:"query,email"` + Nickname string `json:"nickname" param:"query,nickname"` + IsLdap *bool `json:"isLdap,omitempty" param:"query,isLdap"` + Status *bool `json:"status,omitempty"` +} + +type CreateTenantRequest struct { + Name string `json:"name" validate:"required"` + ContactEmail string `json:"contactEmail" validate:"required"` + ModelNames []string `json:"modelNames"` +} + +type UpdateAccountRequest struct { + Id uint `json:"id" param:"path,id" validate:"required"` + Nickname string `json:"nickname"` + Email string `json:"email"` + IsLdap *bool `json:"isLdap"` + Language string `json:"language"` + Status *bool `json:"status,omitempty"` + Password string `json:"password"` + TenantPublicTenantIdItems []string `json:"tenantPublicTenantIdItems"` +} + +type DeleteAccountRequest struct { + Id uint `json:"id" validate:"required" param:"path,id"` +} + +type DeleteTenantRequest struct { + Id uint `json:"publicTenantId" validate:"required" param:"path,id"` +} + +type UpdateTenantRequest struct { + Id uint `json:"id" param:"path,id" validate:"required"` + Name string `json:"name" validate:"required"` + ContactEmail string `json:"contactEmail" validate:"required"` + ModelNames []string `json:"modelNames"` +} diff --git a/src/repository/auth/logging.go b/src/repository/auth/logging.go index 5e98d09..f108e3f 100644 --- a/src/repository/auth/logging.go +++ b/src/repository/auth/logging.go @@ -1,12 +1,14 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" - "fmt" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/go-kit/log" - "github.com/go-kit/log/level" + "encoding/json" "time" + + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -15,134 +17,277 @@ type logging struct { traceId string } -func (s *logging) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { +func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "UpdateTenant", "data", fmt.Sprintf("%+v", data), + "method", "CreateAccount", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.UpdateTenant(ctx, data) + + return s.next.CreateAccount(ctx, data) + } -func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { +func (s *logging) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "DeleteTenant", "id", id, + "method", "CreateTenant", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.DeleteTenant(ctx, id) + + return s.next.CreateTenant(ctx, data) + } -func (s *logging) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { +func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "ListAccount", "request", fmt.Sprintf("%+v", request), + "method", "DeleteAccount", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.ListAccount(ctx, request) + + return s.next.DeleteAccount(ctx, id) + } -func (s *logging) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { +func (s *logging) DeleteTenant(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "UpdateAccount", "data", fmt.Sprintf("%+v", data), + "method", "DeleteTenant", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.UpdateAccount(ctx, data) + + return s.next.DeleteTenant(ctx, id) + +} + +func (s *logging) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { + + defer func(begin time.Time) { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "GetAccountByEmail", + + "email", email, + + "preload", preloadJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.GetAccountByEmail(ctx, email, preload...) + } func (s *logging) GetAccountById(ctx context.Context, id uint) (res types.Accounts, err error) { + defer func(begin time.Time) { + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "GetAccountById", "id", id, + "method", "GetAccountById", + + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) + return s.next.GetAccountById(ctx, id) + } -func (s *logging) DeleteAccount(ctx context.Context, id uint) (err error) { +func (s *logging) GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) { + defer func(begin time.Time) { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), "method", "DeleteAccount", "id", id, + s.traceId, ctx.Value(s.traceId), + "method", "GetTenantById", + + "id", id, + + "preload", preloadJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.DeleteAccount(ctx, id) + + return s.next.GetTenantById(ctx, id, preload...) + } -func (s *logging) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { +func (s *logging) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { + defer func(begin time.Time) { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "CreateTenant", "data", fmt.Sprintf("%+v", data), + "method", "GetTenantByUuid", + + "uuid", uuid, + + "preload", preloadJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.CreateTenant(ctx, data) + + return s.next.GetTenantByUuid(ctx, uuid, preload...) + } -func (s *logging) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { +func (s *logging) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { + defer func(begin time.Time) { + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "ListTenants", "request", fmt.Sprintf("%+v", request), + "method", "ListAccount", + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.ListTenants(ctx, request) + + return s.next.ListAccount(ctx, request) + } -func (s *logging) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { +func (s *logging) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { + defer func(begin time.Time) { + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "CreateAccount", "data", fmt.Sprintf("%+v", data), + "method", "ListTenants", + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.CreateAccount(ctx, data, tenantId) + + return s.next.ListTenants(ctx, request) + } -func (s *logging) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { +func (s *logging) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "GetTenantByUuid", "uuid", uuid, + "method", "UpdateAccount", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.GetTenantByUuid(ctx, uuid, preload...) + + return s.next.UpdateAccount(ctx, data) + } -func (s *logging) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { +func (s *logging) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { + defer func(begin time.Time) { + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + _ = s.logger.Log( - s.traceId, ctx.Value(s.traceId), "method", "GetAccountByEmail", "email", email, + s.traceId, ctx.Value(s.traceId), + "method", "UpdateTenant", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.GetAccountByEmail(ctx, email, preload...) + + return s.next.UpdateTenant(ctx, data) + } func NewLogging(logger log.Logger, traceId string) Middleware { diff --git a/src/repository/auth/service.go b/src/repository/auth/service.go index ac21d10..2553898 100644 --- a/src/repository/auth/service.go +++ b/src/repository/auth/service.go @@ -2,14 +2,18 @@ package auth import ( "context" + "github.com/IceBearAI/aigc/src/helpers/page" "github.com/IceBearAI/aigc/src/repository/types" + "github.com/pkg/errors" "gorm.io/gorm" ) type Middleware func(Service) Service type Service interface { + // GetTenantById 根据id获取租户信息 + GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) // GetTenantByUuid 根据uuid获取租户信息 GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) // GetAccountByEmail 根据email获取账号信息 @@ -23,7 +27,7 @@ type Service interface { // ListTenants 租户列表 ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) // CreateAccount 创建账号 - CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) + CreateAccount(ctx context.Context, data *types.Accounts) (err error) // ListAccount 获取账号列表 ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) // UpdateAccount 更新账号 @@ -52,11 +56,27 @@ type service struct { db *gorm.DB } -func (s *service) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { - err = s.db.WithContext(ctx).Save(data).Error +// GetTenantById implements Service. +func (s *service) GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) { + db := s.db.WithContext(ctx).Where("id = ?", id) + for _, v := range preload { + db = db.Preload(v) + } + err = db.First(&res).Error return } +func (s *service) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { + return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + if err = tx.Model(&types.Tenants{Model: data.Model}).Association("Models").Clear(); err != nil { + err = errors.Wrap(err, "取消关联模型失败") + return err + } + return tx.Save(data).Error + }) + +} + func (s *service) DeleteTenant(ctx context.Context, id uint) (err error) { err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { if err = tx.Delete(&types.Tenants{}, id).Error; err != nil { @@ -82,12 +102,28 @@ func (s *service) ListAccount(ctx context.Context, request ListAccountRequest) ( query = query.Where("status = ?", request.Status) } limit, offset := page.Limit(request.Page, request.PageSize) - err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Find(&res).Error + err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Preload("Tenants").Find(&res).Error return } func (s *service) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { - err = s.db.WithContext(ctx).Save(data).Error + db := s.db.WithContext(ctx) + + err = db.Transaction(func(tx *gorm.DB) (err error) { + err = tx.Model(&types.Accounts{Model: data.Model}).Association("Tenants").Clear() + if err != nil { + err = errors.Wrap(err, "取消关联租户失败") + return + } + + err = tx.Save(data).Error + if err != nil { + err = errors.Wrap(err, "更新账号信息失败") + return + } + + return nil + }) return } @@ -117,21 +153,12 @@ func (s *service) ListTenants(ctx context.Context, request ListTenantRequest) (r query = query.Where("name LIKE ?", "%"+request.Name+"%") } limit, offset := page.Limit(request.Page, request.PageSize) - err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Find(&res).Error + err = query.Count(&total).Order("id DESC").Limit(limit).Offset(offset).Preload("Models").Find(&res).Error return } -func (s *service) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { - err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { - if err = tx.Create(data).Error; err != nil { - return err - } - return tx.Create(&types.TenantAccountAssociations{ - TenantID: tenantId, - AccountID: data.ID, - }).Error - }) - return +func (s *service) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { + return s.db.WithContext(ctx).Save(data).Error } func (s *service) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { diff --git a/src/repository/auth/tracing.go b/src/repository/auth/tracing.go index f8d214a..1770829 100644 --- a/src/repository/auth/tracing.go +++ b/src/repository/auth/tracing.go @@ -1,8 +1,10 @@ +// Code generated . DO NOT EDIT. package auth import ( "context" - "fmt" + "encoding/json" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" @@ -13,147 +15,307 @@ type tracing struct { tracer opentracing.Tracer } -func (s *tracing) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ +func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.UpdateTenant(ctx, data) + + return s.next.CreateAccount(ctx, data) + } -func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ +func (s *tracing) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("id", id, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.DeleteTenant(ctx, id) + + return s.next.CreateTenant(ctx, data) + } -func (s *tracing) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ +func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "res", res, "total", total, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.ListAccount(ctx, request) + + return s.next.DeleteAccount(ctx, id) + } -func (s *tracing) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ +func (s *tracing) DeleteTenant(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.UpdateAccount(ctx, data) + + return s.next.DeleteTenant(ctx, id) + +} + +func (s *tracing) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetAccountByEmail", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.auth", + }) + defer func() { + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "email", email, "preload", preloadJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.GetAccountByEmail(ctx, email, preload...) + } func (s *tracing) GetAccountById(ctx context.Context, id uint) (res types.Accounts, err error) { + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetAccountById", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("id", id, "res", res, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() + return s.next.GetAccountById(ctx, id) + } -func (s *tracing) DeleteAccount(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteAccount", opentracing.Tag{ +func (s *tracing) GetTenantById(ctx context.Context, id uint, preload ...string) (res types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetTenantById", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("id", id, "err", err) + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "id", id, "preload", preloadJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.DeleteAccount(ctx, id) + + return s.next.GetTenantById(ctx, id, preload...) + } -func (s *tracing) CreateTenant(ctx context.Context, data *types.Tenants) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateTenant", opentracing.Tag{ +func (s *tracing) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetTenantByUuid", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "uuid", uuid, "preload", preloadJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.CreateTenant(ctx, data) + + return s.next.GetTenantByUuid(ctx, uuid, preload...) + } -func (s *tracing) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ +func (s *tracing) ListAccount(ctx context.Context, request ListAccountRequest) (res []types.Accounts, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.ListTenants(ctx, request) + + return s.next.ListAccount(ctx, request) + } -func (s *tracing) CreateAccount(ctx context.Context, data *types.Accounts, tenantId uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateAccount", opentracing.Tag{ +func (s *tracing) ListTenants(ctx context.Context, request ListTenantRequest) (res []types.Tenants, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListTenants", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.CreateAccount(ctx, data, tenantId) + + return s.next.ListTenants(ctx, request) + } -func (s *tracing) GetTenantByUuid(ctx context.Context, uuid string, preload ...string) (res types.Tenants, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetTenantByUuid", opentracing.Tag{ +func (s *tracing) UpdateAccount(ctx context.Context, data *types.Accounts) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateAccount", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("uuid", uuid, "res", res, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.GetTenantByUuid(ctx, uuid, preload...) + + return s.next.UpdateAccount(ctx, data) + } -func (s *tracing) GetAccountByEmail(ctx context.Context, email string, preload ...string) (res types.Accounts, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetAccountByEmail", opentracing.Tag{ +func (s *tracing) UpdateTenant(ctx context.Context, data *types.Tenants) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.auth", }) defer func() { - span.LogKV("email", email, "res", res, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.GetAccountByEmail(ctx, email, preload...) + + return s.next.UpdateTenant(ctx, data) + } func NewTracing(otTracer opentracing.Tracer) Middleware { diff --git a/src/repository/model/logging.go b/src/repository/model/logging.go index 2f073cd..8078f45 100644 --- a/src/repository/model/logging.go +++ b/src/repository/model/logging.go @@ -1,11 +1,14 @@ +// Code generated . DO NOT EDIT. package model import ( "context" - "fmt" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/go-kit/log" + "encoding/json" "time" + + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -14,265 +17,478 @@ type logging struct { traceId string } -func (l *logging) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { +func (s *logging) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CancelModelDeploy", + "modelId", modelId, - "method", "FindByModelId", + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindByModelId(ctx, modelId, preloads...) + + return s.next.CancelModelDeploy(ctx, modelId) + } -func (l *logging) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { +func (s *logging) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "FindDeployPendingModels", + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateEval", + + "data", dataJson, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindDeployPendingModels(ctx) + + return s.next.CreateEval(ctx, data) + } -func (l *logging) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { +func (s *logging) CreateModel(ctx context.Context, data *types.Models) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "UpdateDeployStatus", - "modelId", modelId, - "status", status, + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "CreateModel", + + "data", dataJson, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.UpdateDeployStatus(ctx, modelId, status) + + return s.next.CreateModel(ctx, data) + } -func (l *logging) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { +func (s *logging) DeleteEval(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "SetModelEnabled", - "modelId", modelId, - "enabled", enabled, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteEval", + + "id", id, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.SetModelEnabled(ctx, modelId, enabled) + + return s.next.DeleteEval(ctx, id) + } -func (l *logging) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { +func (s *logging) DeleteModel(ctx context.Context, id uint) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "FindModelDeployByModeId", - "modelId", modelId, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "DeleteModel", + + "id", id, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindModelDeployByModeId(ctx, modelId) + + return s.next.DeleteModel(ctx, id) + } -func (l *logging) SaveModel(ctx context.Context, model *types.Models) (err error) { +func (s *logging) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "SaveModel", - "model", model, + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindByModelId", + + "modelId", modelId, + + "preloads", preloadsJson, + + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.SaveModel(ctx, model) + + return s.next.FindByModelId(ctx, modelId, preloads...) + } -func (l *logging) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { +func (s *logging) FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "", "modelId", modelId, + + modelNamesByte, _ := json.Marshal(modelNames) + modelNamesJson := string(modelNamesByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindByModelNames", + + "modelNames", modelNamesJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.CancelModelDeploy(ctx, modelId) + + return s.next.FindByModelNames(ctx, modelNames) + } -func (l *logging) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { +func (s *logging) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "", "data", data, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindDeployPendingModels", + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.SaveModelDeploy(ctx, data) + + return s.next.FindDeployPendingModels(ctx) + } -func (l *logging) DeleteEval(ctx context.Context, id uint) (err error) { +func (s *logging) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "DeleteEval", - "id", id, + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindModelDeployByModeId", + + "modelId", modelId, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.DeleteEval(ctx, id) + + return s.next.FindModelDeployByModeId(ctx, modelId) + } -func (l *logging) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { +func (s *logging) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "UpdateEval", - "data", fmt.Sprintf("%+v", data), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindModelsByTenantId", + + "tenantId", tenantId, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.UpdateEval(ctx, data) + + return s.next.FindModelsByTenantId(ctx, tenantId) + } -func (l *logging) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { +func (s *logging) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), "method", "GetEval", + "id", id, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.GetEval(ctx, id) + + return s.next.GetEval(ctx, id) + } -func (l *logging) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { +func (s *logging) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "CreateEval", - "data", fmt.Sprintf("%+v", data), + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "GetModel", + + "id", id, + + "preload", preloadJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.CreateEval(ctx, data) + + return s.next.GetModel(ctx, id, preload...) + } -func (l *logging) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { +func (s *logging) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "GetModelByModelName", + + "modelName", modelName, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.GetModelByModelName(ctx, modelName) + +} + +func (s *logging) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { + + defer func(begin time.Time) { + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), "method", "ListEval", - "request", fmt.Sprintf("%+v", request), - "total", total, + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.ListEval(ctx, request) + + return s.next.ListEval(ctx, request) + } -func (l *logging) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { +func (s *logging) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), "method", "ListModels", - "request", fmt.Sprintf("%+v", request), - "preloads", fmt.Sprintf("%+v", preloads), + + "request", requestJson, + + "preloads", preloadsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.ListModels(ctx, request, preloads...) + + return s.next.ListModels(ctx, request, preloads...) + } -func (l *logging) CreateModel(ctx context.Context, data *types.Models) (err error) { +func (s *logging) SaveModel(ctx context.Context, model *types.Models) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "CreateModel", - "data", fmt.Sprintf("%+v", data), + + modelByte, _ := json.Marshal(model) + modelJson := string(modelByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "SaveModel", + + "model", modelJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.CreateModel(ctx, data) + + return s.next.SaveModel(ctx, model) + } -func (l *logging) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { +func (s *logging) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "GetModel", - "id", id, + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "SaveModelDeploy", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.GetModel(ctx, id, preload...) + + return s.next.SaveModelDeploy(ctx, data) + } -func (l *logging) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { +func (s *logging) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "UpdateModel", - "request", fmt.Sprintf("%+v", request), + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "SetModelEnabled", + + "modelId", modelId, + + "enabled", enabled, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.UpdateModel(ctx, request) + + return s.next.SetModelEnabled(ctx, modelId, enabled) + } -func (l *logging) DeleteModel(ctx context.Context, id uint) (err error) { +func (s *logging) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "DeleteModel", - "id", id, + + statusByte, _ := json.Marshal(status) + statusJson := string(statusByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateDeployStatus", + + "modelId", modelId, + + "status", statusJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.DeleteModel(ctx, id) + + return s.next.UpdateDeployStatus(ctx, modelId, status) + } -func (l *logging) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { +func (s *logging) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "FindModelsByTenantId", - "tenantId", tenantId, + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateEval", + + "data", dataJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.FindModelsByTenantId(ctx, tenantId) + + return s.next.UpdateEval(ctx, data) + } -func (l *logging) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { +func (s *logging) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { + defer func(begin time.Time) { - _ = l.logger.Log( - l.traceId, ctx.Value(l.traceId), - "method", "GetModelByModelName", - "modelName", modelName, + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "UpdateModel", + + "request", requestJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return l.next.GetModelByModelName(ctx, modelName) + + return s.next.UpdateModel(ctx, request) + } func NewLogging(logger log.Logger, traceId string) Middleware { + logger = log.With(logger, "repository.model", "logging") return func(next Service) Service { return &logging{ - logger: logger, + logger: level.Info(logger), next: next, traceId: traceId, } diff --git a/src/repository/model/service.go b/src/repository/model/service.go index 1edb29e..9e84e23 100644 --- a/src/repository/model/service.go +++ b/src/repository/model/service.go @@ -2,10 +2,11 @@ package model import ( "context" + "time" + "github.com/IceBearAI/aigc/src/helpers/page" "github.com/IceBearAI/aigc/src/repository/types" "gorm.io/gorm" - "time" ) type Middleware func(Service) Service @@ -72,12 +73,20 @@ type Service interface { SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) // FindByModelId 根据id查询模型 FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) + // 根据模型名字列表查模型 + FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) } type service struct { db *gorm.DB } +// FindByModelNames implements Service. +func (s *service) FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) { + err = s.db.WithContext(ctx).Where("model_name IN ?", modelNames).Find(&models).Error + return +} + func (s *service) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { db := s.db.WithContext(ctx) for _, preload := range preloads { diff --git a/src/repository/model/tracing.go b/src/repository/model/tracing.go index e87c5ef..a506c92 100644 --- a/src/repository/model/tracing.go +++ b/src/repository/model/tracing.go @@ -1,8 +1,10 @@ +// Code generated . DO NOT EDIT. package model import ( "context" - "fmt" + "encoding/json" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" @@ -13,264 +15,525 @@ type tracing struct { tracer opentracing.Tracer } -func (t *tracing) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindByModelId", opentracing.Tag{ +func (s *tracing) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CancelModelDeploy", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "err", err) + + span.LogKV( + "modelId", modelId, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindByModelId(ctx, modelId, preloads...) + + return s.next.CancelModelDeploy(ctx, modelId) + } -func (t *tracing) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindDeployPendingModels", opentracing.Tag{ +func (s *tracing) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindDeployPendingModels(ctx) + + return s.next.CreateEval(ctx, data) + } -func (t *tracing) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "UpdateDeployStatus", opentracing.Tag{ +func (s *tracing) CreateModel(ctx context.Context, data *types.Models) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "CreateModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "status", status, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.UpdateDeployStatus(ctx, modelId, status) + + return s.next.CreateModel(ctx, data) + } -func (t *tracing) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "SetModelEnabled", opentracing.Tag{ +func (s *tracing) DeleteEval(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "enabled", enabled, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.SetModelEnabled(ctx, modelId, enabled) + + return s.next.DeleteEval(ctx, id) + } -func (t *tracing) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindModelDeployByModeId", opentracing.Tag{ +func (s *tracing) DeleteModel(ctx context.Context, id uint) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "DeleteModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindModelDeployByModeId(ctx, modelId) + + return s.next.DeleteModel(ctx, id) + } -func (t *tracing) SaveModel(ctx context.Context, model *types.Models) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "SaveModel", opentracing.Tag{ +func (s *tracing) FindByModelId(ctx context.Context, modelId string, preloads ...string) (model types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindByModelId", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("model", model, "err", err) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "modelId", modelId, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.SaveModel(ctx, model) + + return s.next.FindByModelId(ctx, modelId, preloads...) + } -func (t *tracing) CancelModelDeploy(ctx context.Context, modelId uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "CancelModelDeploy", opentracing.Tag{ +func (s *tracing) FindByModelNames(ctx context.Context, modelNames []string) (models []types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindByModelNames", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.model", + }) + defer func() { + + modelNamesByte, _ := json.Marshal(modelNames) + modelNamesJson := string(modelNamesByte) + + span.LogKV( + "modelNames", modelNamesJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.FindByModelNames(ctx, modelNames) + +} + +func (s *tracing) FindDeployPendingModels(ctx context.Context) (models []types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindDeployPendingModels", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelId", modelId, "err", err) + + span.LogKV( + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.CancelModelDeploy(ctx, modelId) + + return s.next.FindDeployPendingModels(ctx) + } -func (t *tracing) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "SaveModelDeploy", opentracing.Tag{ +func (s *tracing) FindModelDeployByModeId(ctx context.Context, modelId uint) (res types.ModelDeploy, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindModelDeployByModeId", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", data, "err", err) + + span.LogKV( + "modelId", modelId, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.SaveModelDeploy(ctx, data) + + return s.next.FindModelDeployByModeId(ctx, modelId) + } -func (t *tracing) DeleteEval(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "DeleteEval", opentracing.Tag{ +func (s *tracing) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindModelsByTenantId", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + span.LogKV( + "tenantId", tenantId, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.DeleteEval(ctx, id) + + return s.next.FindModelsByTenantId(ctx, tenantId) + } -func (t *tracing) CreateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "CreateEval", opentracing.Tag{ +func (s *tracing) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + span.LogKV( + "id", id, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.CreateEval(ctx, data) + + return s.next.GetEval(ctx, id) + } -func (t *tracing) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "ListEval", opentracing.Tag{ +func (s *tracing) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + preloadByte, _ := json.Marshal(preload) + preloadJson := string(preloadByte) + + span.LogKV( + "id", id, "preload", preloadJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.ListEval(ctx, request) + + return s.next.GetModel(ctx, id, preload...) + } -func (t *tracing) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "UpdateEval", opentracing.Tag{ +func (s *tracing) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "GetModelByModelName", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", fmt.Sprintf("%+v", data), "err", err) + + span.LogKV( + "modelName", modelName, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.UpdateEval(ctx, data) + + return s.next.GetModelByModelName(ctx, modelName) + } -func (t *tracing) GetEval(ctx context.Context, id uint) (res types.LLMEvalResults, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "GetEval", opentracing.Tag{ +func (s *tracing) ListEval(ctx context.Context, request ListEvalRequest) (res []types.LLMEvalResults, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.GetEval(ctx, id) + + return s.next.ListEval(ctx, request) + } -func (t *tracing) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "ListModels", opentracing.Tag{ +func (s *tracing) ListModels(ctx context.Context, request ListModelRequest, preloads ...string) (res []types.Models, total int64, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "ListModels", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "preloads", preloads, "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "request", requestJson, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.ListModels(ctx, request, preloads...) + + return s.next.ListModels(ctx, request, preloads...) + } -func (t *tracing) CreateModel(ctx context.Context, data *types.Models) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "CreateModel", opentracing.Tag{ +func (s *tracing) SaveModel(ctx context.Context, model *types.Models) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "SaveModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("data", data, "err", err) + + modelByte, _ := json.Marshal(model) + modelJson := string(modelByte) + + span.LogKV( + "model", modelJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.CreateModel(ctx, data) + + return s.next.SaveModel(ctx, model) + } -func (t *tracing) GetModel(ctx context.Context, id uint, preload ...string) (res types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "GetModel", opentracing.Tag{ +func (s *tracing) SaveModelDeploy(ctx context.Context, data *types.ModelDeploy) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "SaveModelDeploy", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.GetModel(ctx, id, preload...) + + return s.next.SaveModelDeploy(ctx, data) + } -func (t *tracing) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "UpdateModel", opentracing.Tag{ +func (s *tracing) SetModelEnabled(ctx context.Context, modelId string, enabled bool) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "SetModelEnabled", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("request", fmt.Sprintf("%+v", request), "err", err) + + span.LogKV( + "modelId", modelId, "enabled", enabled, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.UpdateModel(ctx, request) + + return s.next.SetModelEnabled(ctx, modelId, enabled) + } -func (t *tracing) DeleteModel(ctx context.Context, id uint) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "DeleteModel", opentracing.Tag{ +func (s *tracing) UpdateDeployStatus(ctx context.Context, modelId uint, status types.ModelDeployStatus) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateDeployStatus", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("id", id, "err", err) + + statusByte, _ := json.Marshal(status) + statusJson := string(statusByte) + + span.LogKV( + "modelId", modelId, "status", statusJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.DeleteModel(ctx, id) + + return s.next.UpdateDeployStatus(ctx, modelId, status) + } -func (t *tracing) FindModelsByTenantId(ctx context.Context, tenantId uint) (res []types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "FindModelsByTenantId", opentracing.Tag{ +func (s *tracing) UpdateEval(ctx context.Context, data *types.LLMEvalResults) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateEval", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("tenantId", tenantId, "err", err) + + dataByte, _ := json.Marshal(data) + dataJson := string(dataByte) + + span.LogKV( + "data", dataJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.FindModelsByTenantId(ctx, tenantId) + + return s.next.UpdateEval(ctx, data) + } -func (t *tracing) GetModelByModelName(ctx context.Context, modelName string) (res types.Models, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, t.tracer, "GetModelByModelName", opentracing.Tag{ +func (s *tracing) UpdateModel(ctx context.Context, request UpdateModelRequest) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "UpdateModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.model", }) defer func() { - span.LogKV("modelName", modelName, "err", err) + + requestByte, _ := json.Marshal(request) + requestJson := string(requestByte) + + span.LogKV( + "request", requestJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return t.next.GetModelByModelName(ctx, modelName) + + return s.next.UpdateModel(ctx, request) + } func NewTracing(otTracer opentracing.Tracer) Middleware { diff --git a/src/repository/tenant/logging.go b/src/repository/tenant/logging.go index fcc174c..3800af9 100644 --- a/src/repository/tenant/logging.go +++ b/src/repository/tenant/logging.go @@ -1,10 +1,14 @@ +// Code generated . DO NOT EDIT. package tenant import ( "context" - "github.com/IceBearAI/aigc/src/repository/types" - "github.com/go-kit/log" + "encoding/json" "time" + + "github.com/IceBearAI/aigc/src/repository/types" + "github.com/go-kit/kit/log" + "github.com/go-kit/kit/log/level" ) type logging struct { @@ -13,50 +17,114 @@ type logging struct { traceId string } -func (s *logging) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { +func (s *logging) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { + defer func(begin time.Time) { + + modelsByte, _ := json.Marshal(models) + modelsJson := string(modelsByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "FindTenantByTenantId", - "tenantId", tenantId, + "method", "AddModel", + + "id", id, + + "models", modelsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + + return s.next.AddModel(ctx, id, models...) + } -func (s *logging) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { +func (s *logging) FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) { + defer func(begin time.Time) { + + publicTenantIdItemsByte, _ := json.Marshal(publicTenantIdItems) + publicTenantIdItemsJson := string(publicTenantIdItemsByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), - "method", "AddModel", - "id", id, + "method", "FindByPublicTenantIdItems", + + "publicTenantIdItems", publicTenantIdItemsJson, + + "preloads", preloadsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) - return s.next.AddModel(ctx, id, models...) + + return s.next.FindByPublicTenantIdItems(ctx, publicTenantIdItems, preloads...) + } func (s *logging) FindTenant(ctx context.Context, id uint, preloads ...string) (res types.Tenants, err error) { + defer func(begin time.Time) { + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + _ = s.logger.Log( s.traceId, ctx.Value(s.traceId), "method", "FindTenant", + "id", id, + + "preloads", preloadsJson, + "took", time.Since(begin), + "err", err, ) }(time.Now()) + return s.next.FindTenant(ctx, id, preloads...) + +} + +func (s *logging) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { + + defer func(begin time.Time) { + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + _ = s.logger.Log( + s.traceId, ctx.Value(s.traceId), + "method", "FindTenantByTenantId", + + "tenantId", tenantId, + + "preloads", preloadsJson, + + "took", time.Since(begin), + + "err", err, + ) + }(time.Now()) + + return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + } func NewLogging(logger log.Logger, traceId string) Middleware { logger = log.With(logger, "repository.tenant", "logging") return func(next Service) Service { return &logging{ - logger: logger, + logger: level.Info(logger), next: next, traceId: traceId, } diff --git a/src/repository/tenant/service.go b/src/repository/tenant/service.go index 794c55e..8595f92 100644 --- a/src/repository/tenant/service.go +++ b/src/repository/tenant/service.go @@ -2,6 +2,7 @@ package tenant import ( "context" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/pkg/errors" "gorm.io/gorm" @@ -16,12 +17,20 @@ type Service interface { AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) // FindTenantByTenantId 通过租户ID获取租户信息 FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) + // FindByPublicTenantIdItems 通过公共租户ID获取租户信息 + FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) } type service struct { db *gorm.DB } +// FindByPublicTenantIdItems implements Service. +func (s *service) FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) { + err = s.db.WithContext(ctx).Where("public_tenant_id IN ?", publicTenantIdItems).Find(&res).Error + return +} + func (s service) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { db := s.db.WithContext(ctx) for _, preload := range preloads { diff --git a/src/repository/tenant/tracing.go b/src/repository/tenant/tracing.go index 32f0a86..1f1d647 100644 --- a/src/repository/tenant/tracing.go +++ b/src/repository/tenant/tracing.go @@ -1,7 +1,10 @@ +// Code generated . DO NOT EDIT. package tenant import ( "context" + "encoding/json" + "github.com/IceBearAI/aigc/src/repository/types" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" @@ -12,43 +15,111 @@ type tracing struct { tracer opentracing.Tracer } -func (s *tracing) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindTenantByTenantId", opentracing.Tag{ +func (s *tracing) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "AddModel", opentracing.Tag{ Key: string(ext.Component), Value: "repository.tenant", }) defer func() { - span.LogKV("tenantId", tenantId, "err", err) + + modelsByte, _ := json.Marshal(models) + modelsJson := string(modelsByte) + + span.LogKV( + "id", id, "models", modelsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + + return s.next.AddModel(ctx, id, models...) + } -func (s *tracing) AddModel(ctx context.Context, id uint, models ...*types.Models) (err error) { - span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "AddModel", opentracing.Tag{ +func (s *tracing) FindByPublicTenantIdItems(ctx context.Context, publicTenantIdItems []string, preloads ...string) (res []types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindByPublicTenantIdItems", opentracing.Tag{ Key: string(ext.Component), Value: "repository.tenant", }) defer func() { - span.LogKV("id", id, "err", err) + + publicTenantIdItemsByte, _ := json.Marshal(publicTenantIdItems) + publicTenantIdItemsJson := string(publicTenantIdItemsByte) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "publicTenantIdItems", publicTenantIdItemsJson, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() - return s.next.AddModel(ctx, id, models...) + + return s.next.FindByPublicTenantIdItems(ctx, publicTenantIdItems, preloads...) + } func (s *tracing) FindTenant(ctx context.Context, id uint, preloads ...string) (res types.Tenants, err error) { + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindTenant", opentracing.Tag{ Key: string(ext.Component), Value: "repository.tenant", }) defer func() { - span.LogKV("id", id, "err", err) + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "id", id, "preloads", preloadsJson, + + "err", err, + ) + span.SetTag(string(ext.Error), err != nil) + span.Finish() }() + return s.next.FindTenant(ctx, id, preloads...) + +} + +func (s *tracing) FindTenantByTenantId(ctx context.Context, tenantId string, preloads ...string) (res types.Tenants, err error) { + + span, ctx := opentracing.StartSpanFromContextWithTracer(ctx, s.tracer, "FindTenantByTenantId", opentracing.Tag{ + Key: string(ext.Component), + Value: "repository.tenant", + }) + defer func() { + + preloadsByte, _ := json.Marshal(preloads) + preloadsJson := string(preloadsByte) + + span.LogKV( + "tenantId", tenantId, "preloads", preloadsJson, + + "err", err, + ) + + span.SetTag(string(ext.Error), err != nil) + + span.Finish() + }() + + return s.next.FindTenantByTenantId(ctx, tenantId, preloads...) + } func NewTracing(otTracer opentracing.Tracer) Middleware {