From 71498785eacd710713da6fbb1db3d377715dfcac Mon Sep 17 00:00:00 2001 From: chashintv Date: Thu, 19 Nov 2026 12:48:34 +0300 Subject: [PATCH 01/13] MSP-8974 add download flow, server migration to http --- assembly/assembly.go | 23 +- assembly/locator.go | 31 +- controller/download.go | 98 +++ domain/download.go | 20 + entity/download.go | 69 ++ entity/user.go | 1 + go.mod | 1 + repository/admin.go | 132 ++++ routes/routes.go | 261 ++++--- service/download.go | 328 +++++++++ .../julienschmidt/httprouter/.travis.yml | 18 + .../julienschmidt/httprouter/LICENSE | 29 + .../julienschmidt/httprouter/README.md | 300 ++++++++ .../julienschmidt/httprouter/path.go | 123 ++++ .../julienschmidt/httprouter/router.go | 452 ++++++++++++ .../julienschmidt/httprouter/tree.go | 666 ++++++++++++++++++ .../txix-open/isp-kit/http/README.md | 81 +++ .../isp-kit/http/apierrors/README.md | 95 +++ .../txix-open/isp-kit/http/apierrors/error.go | 93 +++ .../txix-open/isp-kit/http/common.go | 16 + .../txix-open/isp-kit/http/endpoint/README.md | 257 +++++++ .../isp-kit/http/endpoint/buffer/README.md | 88 +++ .../isp-kit/http/endpoint/buffer/buffer.go | 88 +++ .../isp-kit/http/endpoint/buffer/pool.go | 33 + .../http/endpoint/buffer/request_body.go | 29 + .../txix-open/isp-kit/http/endpoint/caller.go | 123 ++++ .../isp-kit/http/endpoint/codec_middleware.go | 201 ++++++ .../isp-kit/http/endpoint/default.go | 74 ++ .../isp-kit/http/endpoint/httplog/README.md | 89 +++ .../http/endpoint/httplog/log_middleware.go | 215 ++++++ .../isp-kit/http/endpoint/httplog/nop.go | 19 + .../isp-kit/http/endpoint/httplog/options.go | 42 ++ .../isp-kit/http/endpoint/json_request.go | 90 +++ .../isp-kit/http/endpoint/json_response.go | 37 + .../http/endpoint/metrics_middleware.go | 71 ++ .../isp-kit/http/endpoint/middlewares.go | 124 ++++ .../txix-open/isp-kit/http/endpoint/params.go | 39 + .../txix-open/isp-kit/http/endpoint/types.go | 123 ++++ .../isp-kit/http/endpoint/wrapper.go | 133 ++++ .../txix-open/isp-kit/http/router/README.md | 70 ++ .../txix-open/isp-kit/http/router/router.go | 93 +++ .../txix-open/isp-kit/http/server.go | 115 +++ .../tracing/http/server_tracing/README.md | 61 ++ .../tracing/http/server_tracing/middleware.go | 117 +++ .../http/server_tracing/response_writer.go | 48 ++ vendor/modules.txt | 10 + 46 files changed, 5102 insertions(+), 124 deletions(-) create mode 100644 controller/download.go create mode 100644 domain/download.go create mode 100644 entity/download.go create mode 100644 repository/admin.go create mode 100644 service/download.go create mode 100644 vendor/github.com/julienschmidt/httprouter/.travis.yml create mode 100644 vendor/github.com/julienschmidt/httprouter/LICENSE create mode 100644 vendor/github.com/julienschmidt/httprouter/README.md create mode 100644 vendor/github.com/julienschmidt/httprouter/path.go create mode 100644 vendor/github.com/julienschmidt/httprouter/router.go create mode 100644 vendor/github.com/julienschmidt/httprouter/tree.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/http/apierrors/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/http/apierrors/error.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/common.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/buffer.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/pool.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/request_body.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/caller.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/codec_middleware.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/default.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/log_middleware.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/nop.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/options.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/json_request.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/json_response.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/metrics_middleware.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/middlewares.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/params.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/types.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/endpoint/wrapper.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/router/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/http/router/router.go create mode 100644 vendor/github.com/txix-open/isp-kit/http/server.go create mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/middleware.go create mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/response_writer.go diff --git a/assembly/assembly.go b/assembly/assembly.go index e873a9f..3939c95 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -16,7 +16,7 @@ import ( "github.com/txix-open/isp-kit/dbrx" "github.com/txix-open/isp-kit/dbx" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc" + "github.com/txix-open/isp-kit/http" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/httpclix" "github.com/txix-open/isp-kit/log" @@ -24,12 +24,13 @@ import ( ) type Assembly struct { - boot *bootstrap.Bootstrap - db *dbrx.Client - server *grpc.Server - oauthCli *httpcli.Client - logger *log.Adapter - bgjobCli *bgjobx.Client + boot *bootstrap.Bootstrap + db *dbrx.Client + server *http.Server + downloadCli *httpcli.Client + oauthCli *httpcli.Client + logger *log.Adapter + bgjobCli *bgjobx.Client } func New(boot *bootstrap.Bootstrap) (*Assembly, error) { @@ -43,7 +44,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) { return &Assembly{ boot: boot, db: db, - server: grpc.NewServer(), + server: http.NewServer(logger), logger: logger, oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))), bgjobCli: bgjobCli, @@ -73,7 +74,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error } a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl - locator := NewLocator(a.logger, a.oauthCli, a.db) + locator := NewLocator(a.logger, a.oauthCli, a.downloadCli, a.db) config, err := locator.Config(ctx, newCfg, time.Minute) if err != nil { a.logger.Fatal(ctx, errors.WithMessage(err, "locator config")) @@ -109,7 +110,7 @@ func (a *Assembly) Runners() []app.Runner { app.RunnerFunc(func(ctx context.Context) error { err := a.server.ListenAndServe(a.boot.BindingAddress) if err != nil { - return errors.WithMessage(err, "listen ans serve grpc server") + return errors.WithMessage(err, "listen and serve http server") } return nil }), @@ -127,7 +128,7 @@ func (a *Assembly) Closers() []app.Closer { return []app.Closer{ a.boot.ClusterCli, app.CloserFunc(func() error { - a.server.Shutdown() + a.server.Shutdown(context.Background()) return nil }), app.CloserFunc(func() error { diff --git a/assembly/locator.go b/assembly/locator.go index 548ef35..256dd7f 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -18,9 +18,10 @@ import ( "github.com/txix-open/isp-kit/bgjobx" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/endpoint" - "github.com/txix-open/isp-kit/grpc/isp" + httpEndpoint "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/httplog" "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/http/router" "github.com/txix-open/isp-kit/log" ) @@ -30,21 +31,23 @@ type DB interface { } type Locator struct { - logger log.Logger - oauthCli *httpcli.Client - db DB + logger log.Logger + downloadCli *httpcli.Client + oauthCli *httpcli.Client + db DB } -func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator { +func NewLocator(logger log.Logger, oauthCli *httpcli.Client, downloadCli *httpcli.Client, db DB) Locator { return Locator{ - logger: logger, - oauthCli: oauthCli, - db: db, + logger: logger, + downloadCli: downloadCli, + oauthCli: oauthCli, + db: db, } } type Config struct { - Handler isp.BackendServiceServer + Handler *router.Router BgJobCfg []bgjobx.WorkerConfig } @@ -61,9 +64,11 @@ func (l Locator) Config( auditRepo := repository.NewAudit(l.db) auditEventRepo := repository.NewAuditEvent(l.db) userRoleRepo := repository.NewUserRole(l.db) + adminRepo := repository.NewAdmin(l.downloadCli) auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings) tokenService := service.NewToken(tokenRepo, cfg.ExpireSec) + downloadService := service.NewDownload(adminRepo) oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth) oauthService, err := service.NewOauth(oauthSettings, oauthRepo) @@ -106,8 +111,11 @@ func (l Locator) Config( roleController := controller.NewRole(roleService) permissionController := controller.NewPermissions(permissionsService) uiSettingsController := controller.NewUiSettings(uiSettingsService) + downloadController := controller.NewDownload(downloadService) + + wrapper := httpEndpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true)) handler := routes.Handler( - endpoint.DefaultWrapper(l.logger), + wrapper, routes.Controllers{ User: userController, Customization: customizationController, @@ -118,6 +126,7 @@ func (l Locator) Config( Role: roleController, Permissions: permissionController, UiSettings: uiSettingsController, + Download: downloadController, }, ) diff --git a/controller/download.go b/controller/download.go new file mode 100644 index 0000000..e1d4d81 --- /dev/null +++ b/controller/download.go @@ -0,0 +1,98 @@ +package controller + +import ( + "context" + "net/http" + + "isp-admin-service/domain" + + "github.com/txix-open/isp-kit/errors" +) + +type DownloadService interface { + DownloadUsers(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error + DownloadSessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error + DownloadAudit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error + DownloadRoles(ctx context.Context, w http.ResponseWriter) error +} + +type Download struct { + service DownloadService +} + +func NewDownload(service DownloadService) Download { + return Download{ + service: service, + } +} + +// Users +// @Tags Download +// @Summary Скачать список пользователей в csv +// @Accept json +// @Produce json +// @Param body body domain.UsersDownloadRequest true "Тело запроса" +// @Success 200 +// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /user/download [POST] +func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { + err := c.service.DownloadUsers(ctx, req, w) + if err != nil { + return errors.WithMessage(err, "download users") + } + + return nil +} + +// Sessions +// @Tags Download +// @Summary Скачать список сессий в csv +// @Accept json +// @Produce json +// @Param body body domain.SessionDownloadRequest true "Тело запроса" +// @Success 200 +// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /session/download [POST] +func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { + err := c.service.DownloadSessions(ctx, req, w) + if err != nil { + return errors.WithMessage(err, "download sessions") + } + + return nil +} + +// Audit +// @Tags Download +// @Summary Скачать журнал аудита в csv +// @Accept json +// @Produce json +// @Param body body domain.AuditDownloadRequest true "Тело запроса" +// @Success 200 +// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /log/download [POST] +func (c Download) Audit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { + err := c.service.DownloadAudit(ctx, req, w) + if err != nil { + return errors.WithMessage(err, "download audit") + } + + return nil +} + +// Roles +// @Tags Download +// @Summary Скачать матрицу ролей в csv +// @Accept json +// @Produce json +// @Success 200 +// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /role/download [POST] +func (c Download) Roles(ctx context.Context, w http.ResponseWriter) error { + err := c.service.DownloadRoles(ctx, w) + if err != nil { + return errors.WithMessage(err, "download roles") + } + + return nil +} diff --git a/domain/download.go b/domain/download.go new file mode 100644 index 0000000..e137540 --- /dev/null +++ b/domain/download.go @@ -0,0 +1,20 @@ +package domain + +type AuditDownloadRequest struct { + LimitOffestParams + + Order *OrderParams + Query *AuditQuery +} +type SessionDownloadRequest struct { + LimitOffestParams + + Order *OrderParams + Query *SessionQuery +} +type UsersDownloadRequest struct { + LimitOffestParams + + Order *OrderParams + Query *UserQuery +} diff --git a/entity/download.go b/entity/download.go new file mode 100644 index 0000000..01e4679 --- /dev/null +++ b/entity/download.go @@ -0,0 +1,69 @@ +package entity + +import "time" + +const ( + SessionStatusAllowed = "ALLOWED" + SessionStatusAllowedRus = "Активная" + + SessionStatusExpired = "EXPIRED" + SessionStatusExpiredRus = "Истекшая" + + SessionStatusRevoked = "REVOKED" + SessionStatusRevokedRus = "Отмененная" +) + +type AuditResponse struct { + TotalCount int + Items []Audit +} + +type Session struct { + Id int + UserId int + Status string + ExpiredAt time.Time + CreatedAt time.Time +} + +type SessionResponse struct { + TotalCount int + Items []Session +} + +func (s Session) StatusRus() string { + switch s.Status { + case SessionStatusAllowed: + return SessionStatusAllowedRus + case SessionStatusExpired: + return SessionStatusExpiredRus + case SessionStatusRevoked: + return SessionStatusRevokedRus + } + return "" +} + +type UsersResponse struct { + Items []User +} + +type Permission struct { + Key string + Name string +} + +func AuditColumnNames() []string { + return []string{"Пользователь", "Время события", "Действие"} +} + +func SessionColumnNames() []string { + return []string{"Пользователь", "Идентификатор", "Дата начала сессии", "Дата окончания сессии", "Статус"} +} + +func UserColumnNames() []string { + return []string{"id", "Пользователь", "Описание", "Email", "Роль", "Последняя сессия"} +} + +func RoleColumnNames() []string { + return []string{"Действие", "Ключ в системе"} +} diff --git a/entity/user.go b/entity/user.go index 845de4a..1ceba8d 100644 --- a/entity/user.go +++ b/entity/user.go @@ -5,6 +5,7 @@ import "time" type User struct { OauthUserId *string Id int64 + Roles []int FirstName string LastName string FullName string diff --git a/go.mod b/go.mod index bb8f407..064bb57 100644 --- a/go.mod +++ b/go.mod @@ -36,6 +36,7 @@ require ( github.com/jackc/puddle/v2 v2.2.4 // indirect github.com/jmoiron/sqlx v1.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect + github.com/julienschmidt/httprouter v1.3.0 // indirect github.com/klauspost/compress v1.20.4 // indirect github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect diff --git a/repository/admin.go b/repository/admin.go new file mode 100644 index 0000000..818e61a --- /dev/null +++ b/repository/admin.go @@ -0,0 +1,132 @@ +package repository + +import ( + "context" + "isp-admin-service/domain" + "isp-admin-service/entity" + "slices" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/http/httpcli" +) + +const ( + getUserById = "admin/user/get_by_id" + getAllLogs = "admin/log/all" + getAllSessions = "admin/session/all" + getAllUsers = "admin/user/get_users" + getAllRoles = "admin/role/all" + getPermissions = "admin/user/get_permissions" +) + +type ReqGetById struct { + UserId int `json:"userId"` +} + +type getRoleResp struct { + Roles []int `json:"roles"` +} + +type Admin struct { + cli *httpcli.Client +} + +func NewAdmin(cli *httpcli.Client) Admin { + return Admin{cli: cli} +} + +func (r Admin) GetRoleNamesByIds(ctx context.Context, roleIds []int) ([]string, error) { + if len(roleIds) == 0 { + return []string{}, nil + } + resp := make([]entity.Role, 0) + err := r.cli.Post(getAllRoles). + JsonResponseBody(&resp). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "http client request %s", getAllRoles) + } + + roleNames := make([]string, 0) + for _, role := range resp { + if slices.Contains(roleIds, role.Id) { + roleNames = append(roleNames, role.Name) + } + } + + return roleNames, nil +} + +func (r Admin) GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) { + var response entity.AuditResponse + + err := r.cli.Post(getAllLogs). + JsonRequestBody(req). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "http client request %s", getAllLogs) + } + + return &response, nil +} + +func (r Admin) GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) { + var response entity.SessionResponse + + err := r.cli.Post(getAllSessions). + JsonRequestBody(req). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "http client request %s", getAllSessions) + } + + return &response, nil +} + +func (r Admin) GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) { + var response entity.UsersResponse + + err := r.cli.Post(getAllUsers). + JsonRequestBody(req). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "http client request %s", getAllUsers) + } + + return response.Items, nil +} + +func (r Admin) GetRoles(ctx context.Context) ([]entity.Role, error) { + var response []entity.Role + + err := r.cli.Post(getAllRoles). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "http client request %s", getAllRoles) + } + + return response, nil +} + +func (r Admin) GetPermissions(ctx context.Context) ([]entity.Permission, error) { + var response []entity.Permission + + err := r.cli.Post(getPermissions). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "http client request %s", getPermissions) + } + + return response, nil +} diff --git a/routes/routes.go b/routes/routes.go index 54f2e71..1198035 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -3,12 +3,12 @@ package routes import ( "isp-admin-service/controller" "isp-admin-service/docs" + "net/http" "github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/common_endpoints" - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/endpoint" - "github.com/txix-open/isp-kit/grpc/isp" + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/router" ) type Controllers struct { @@ -21,6 +21,7 @@ type Controllers struct { Role controller.Role Permissions controller.Permissions UiSettings controller.UiSettings + Download controller.Download } func EndpointDescriptors() []cluster.EndpointDescriptor { @@ -30,13 +31,13 @@ func EndpointDescriptors() []cluster.EndpointDescriptor { ) } -func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn - muxer := grpc.NewMux() +func Handler(wrapper endpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn + muxer := router.New() for _, descriptor := range endpointDescriptors(c) { - muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) + muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler)) } for _, descriptor := range commonEndpoints() { - muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) + muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler)) } return muxer } @@ -45,153 +46,209 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { return []cluster.EndpointDescriptor{ { - Path: "admin/auth/login", - Inner: false, - Handler: c.Auth.Login, + Path: "admin/auth/login", + Inner: false, + Handler: c.Auth.Login, + HttpMethod: http.MethodPost, }, { - Path: "admin/auth/login_with_oauth", - Inner: false, - Handler: c.Auth.LoginWithOauth, + Path: "admin/auth/login_with_oauth", + Inner: false, + Handler: c.Auth.LoginWithOauth, + HttpMethod: http.MethodPost, }, { - Path: "admin/auth/logout", - Inner: true, - Handler: c.Auth.Logout, + Path: "admin/auth/logout", + Inner: true, + Handler: c.Auth.Logout, + HttpMethod: http.MethodPost, }, { - Path: "admin/auth/logout_with_reason", - Inner: true, - Handler: c.Auth.LogoutWithReason, + Path: "admin/auth/logout_with_reason", + Inner: true, + Handler: c.Auth.LogoutWithReason, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/get_profile", - Inner: true, - Handler: c.User.GetProfile, + Path: "admin/user/get_profile", + Inner: true, + Handler: c.User.GetProfile, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/get_design", - Inner: true, - Handler: c.Customization.GetUIDesign, + Path: "admin/user/get_design", + Inner: true, + Handler: c.Customization.GetUIDesign, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/get_users", - Inner: true, - Handler: c.User.GetUsers, + Path: "admin/user/get_users", + Inner: true, + Handler: c.User.GetUsers, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/get_all_users", - Inner: true, - Handler: c.User.GetAllUsers, + Path: "admin/user/get_all_users", + Inner: true, + Handler: c.User.GetAllUsers, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/create_user", - Inner: true, - Extra: cluster.RequireAdminPermission("user_create"), - Handler: c.User.CreateUser, + Path: "admin/user/create_user", + Inner: true, + Extra: cluster.RequireAdminPermission("user_create"), + Handler: c.User.CreateUser, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/update_user", - Inner: true, - Extra: cluster.RequireAdminPermission("user_update"), - Handler: c.User.UpdateUser, + Path: "admin/user/update_user", + Inner: true, + Extra: cluster.RequireAdminPermission("user_update"), + Handler: c.User.UpdateUser, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/delete_user", - Inner: true, - Extra: cluster.RequireAdminPermission("user_delete"), - Handler: c.User.DeleteUser, + Path: "admin/user/delete_user", + Inner: true, + Extra: cluster.RequireAdminPermission("user_delete"), + Handler: c.User.DeleteUser, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/block_user", - Inner: true, - Extra: cluster.RequireAdminPermission("user_block"), - Handler: c.User.Block, + Path: "admin/user/block_user", + Inner: true, + Extra: cluster.RequireAdminPermission("user_block"), + Handler: c.User.Block, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/get_by_id", - Inner: true, - Handler: c.User.GetById, + Path: "admin/user/get_by_id", + Inner: true, + Handler: c.User.GetById, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/change_password", - Inner: true, - Handler: c.User.ChangePassword, + Path: "admin/user/change_password", + Inner: true, + Handler: c.User.ChangePassword, + HttpMethod: http.MethodPost, }, { - Path: "admin/role/all", - Inner: true, - Extra: cluster.RequireAdminPermission("role_view"), - Handler: c.Role.All, + Path: "admin/role/all", + Inner: true, + Extra: cluster.RequireAdminPermission("role_view"), + Handler: c.Role.All, + HttpMethod: http.MethodPost, }, { - Path: "admin/user/get_permissions", - Inner: true, - Extra: cluster.RequireAdminPermission("role_view"), - Handler: c.Permissions.GetPermissions, + Path: "admin/user/get_permissions", + Inner: true, + Extra: cluster.RequireAdminPermission("role_view"), + Handler: c.Permissions.GetPermissions, + HttpMethod: http.MethodPost, }, { - Path: "admin/role/create", - Inner: true, - Extra: cluster.RequireAdminPermission("role_add"), - Handler: c.Role.CreateRole, + Path: "admin/role/create", + Inner: true, + Extra: cluster.RequireAdminPermission("role_add"), + Handler: c.Role.CreateRole, + HttpMethod: http.MethodPost, }, { - Path: "admin/role/update", - Inner: true, - Extra: cluster.RequireAdminPermission("role_update"), - Handler: c.Role.UpdateRole, + Path: "admin/role/update", + Inner: true, + Extra: cluster.RequireAdminPermission("role_update"), + Handler: c.Role.UpdateRole, + HttpMethod: http.MethodPost, }, { - Path: "admin/role/delete", - Inner: true, - Extra: cluster.RequireAdminPermission("role_delete"), - Handler: c.Role.DeleteRole, + Path: "admin/role/delete", + Inner: true, + Extra: cluster.RequireAdminPermission("role_delete"), + Handler: c.Role.DeleteRole, + HttpMethod: http.MethodPost, }, { - Path: "admin/session/all", - Inner: true, - Extra: cluster.RequireAdminPermission("session_view"), - Handler: c.Session.All, + Path: "admin/session/all", + Inner: true, + Extra: cluster.RequireAdminPermission("session_view"), + Handler: c.Session.All, + HttpMethod: http.MethodPost, }, { - Path: "admin/session/revoke", - Inner: true, - Extra: cluster.RequireAdminPermission("session_revoke"), - Handler: c.Session.Revoke, + Path: "admin/session/revoke", + Inner: true, + Extra: cluster.RequireAdminPermission("session_revoke"), + Handler: c.Session.Revoke, + HttpMethod: http.MethodPost, }, { - Path: "admin/log/all", - Inner: true, - Extra: cluster.RequireAdminPermission("security_log_view"), - Handler: c.Audit.All, + Path: "admin/log/all", + Inner: true, + Extra: cluster.RequireAdminPermission("security_log_view"), + Handler: c.Audit.All, + HttpMethod: http.MethodPost, }, { - Path: "admin/log/events", - Inner: true, - Extra: cluster.RequireAdminPermission("audit_management_view"), - Handler: c.Audit.Events, + Path: "admin/log/events", + Inner: true, + Extra: cluster.RequireAdminPermission("audit_management_view"), + Handler: c.Audit.Events, + HttpMethod: http.MethodPost, }, { - Path: "admin/log/set_events", - Inner: true, - Extra: cluster.RequireAdminPermission("audit_management_view"), - Handler: c.Audit.SetEvents, + Path: "admin/log/set_events", + Inner: true, + Extra: cluster.RequireAdminPermission("audit_management_view"), + Handler: c.Audit.SetEvents, + HttpMethod: http.MethodPost, }, { - Path: "admin/secure/authenticate", - Inner: true, - Handler: c.Secure.Authenticate, + Path: "admin/secure/authenticate", + Inner: true, + Handler: c.Secure.Authenticate, + HttpMethod: http.MethodPost, }, { - Path: "admin/secure/authorize", - Inner: true, - Handler: c.Secure.Authorize, + Path: "admin/secure/authorize", + Inner: true, + Handler: c.Secure.Authorize, + HttpMethod: http.MethodPost, }, { - Path: "admin/ui_settings/oauth", - Inner: false, - Handler: c.UiSettings.OauthSettings, + Path: "admin/ui_settings/oauth", + Inner: false, + Handler: c.UiSettings.OauthSettings, + HttpMethod: http.MethodPost, + }, + // download + { + Path: "/user/download", + Inner: true, + Extra: cluster.RequireAdminPermission("data_download"), + Handler: c.Download.Users, + HttpMethod: http.MethodPost, + }, + { + Path: "/session/download", + Inner: true, + Extra: cluster.RequireAdminPermission("data_download"), + Handler: c.Download.Sessions, + HttpMethod: http.MethodPost, + }, + { + Path: "/log/download", + Inner: true, + Extra: cluster.RequireAdminPermission("data_download"), + Handler: c.Download.Audit, + HttpMethod: http.MethodPost, + }, + { + Path: "/role/download", + Inner: true, + Extra: cluster.RequireAdminPermission("data_download"), + Handler: c.Download.Roles, + HttpMethod: http.MethodPost, }, } } diff --git a/service/download.go b/service/download.go new file mode 100644 index 0000000..dc2d464 --- /dev/null +++ b/service/download.go @@ -0,0 +1,328 @@ +package service + +import ( + "context" + "encoding/csv" + "fmt" + "net/http" + "slices" + "strconv" + "strings" + "time" + + "isp-admin-service/domain" + "isp-admin-service/entity" + + "github.com/txix-open/isp-kit/errors" +) + +const ( + requestLimit = 1000 + foundSymbol = "+" + notFoundSymbol = "-" +) + +type AdminRepo interface { + GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) + GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) + GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) + GetRoles(ctx context.Context) ([]entity.Role, error) + GetRoleNamesByIds(ctx context.Context, roleIds []int) ([]string, error) + GetPermissions(ctx context.Context) ([]entity.Permission, error) +} + +type Download struct { + repo AdminRepo + loc *time.Location +} + +func NewDownload(repo AdminRepo) Download { + loc, _ := time.LoadLocation("Europe/Moscow") + return Download{ + repo: repo, + loc: loc, + } +} + +func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { + req.Limit = requestLimit + req.Offset = 0 + + response, err := s.repo.GetAudit(ctx, req) + if err != nil { + return errors.WithMessage(err, "get audit") + } + + if response.TotalCount == 0 { + return nil + } + + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Audit"))) + w.Header().Set("content-type", "application/octet-stream; charset=utf-8") + w.Header().Set("transfer-encoding", "chunked") + + csvWriter := csv.NewWriter(w) + defer csvWriter.Flush() + + err = writeCsvLine(csvWriter, entity.AuditColumnNames()) + if err != nil { + return errors.WithMessage(err, "write auditColumns to csv") + } + + userById, err := s.getUsersList(ctx) + if err != nil { + return errors.WithMessage(err, "get users list") + } + + itemsCount := len(response.Items) + for { + for _, audit := range response.Items { + username := getUsername(userById, audit.UserId) + + row := []string{username, s.formatTime(&audit.CreatedAt, false), audit.Message} + err = writeCsvLine(csvWriter, row) + if err != nil { + return errors.WithMessage(err, "write audit row to csv") + } + } + + if itemsCount >= response.TotalCount { + break + } + + req.Offset += requestLimit + response, err = s.repo.GetAudit(ctx, req) + if err != nil { + return errors.WithMessage(err, "get audit") + } + + itemsCount += len(response.Items) + } + + return nil +} + +func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { + req.Limit = requestLimit + req.Offset = 0 + + response, err := s.repo.GetSessions(ctx, req) + if err != nil { + return errors.WithMessage(err, "get sessions") + } + + if response.TotalCount == 0 { + return nil + } + + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Sessions"))) + w.Header().Set("content-type", "application/octet-stream; charset=utf-8") + w.Header().Set("transfer-encoding", "chunked") + + csvWriter := csv.NewWriter(w) + defer csvWriter.Flush() + + err = writeCsvLine(csvWriter, entity.SessionColumnNames()) + if err != nil { + return errors.WithMessage(err, "write sessionColumns to csv") + } + + userById, err := s.getUsersList(ctx) + if err != nil { + return errors.WithMessage(err, "get users list") + } + + itemsCount := len(response.Items) + for { + for _, session := range response.Items { + row := []string{ + getUsername(userById, session.UserId), + strconv.Itoa(session.Id), + s.formatTime(&session.CreatedAt, false), + s.formatTime(&session.ExpiredAt, false), + session.StatusRus()} + + err = writeCsvLine(csvWriter, row) + if err != nil { + return errors.WithMessage(err, "write session row to csv") + } + } + + if itemsCount >= response.TotalCount { + break + } + + req.Offset += requestLimit + response, err = s.repo.GetSessions(ctx, req) + if err != nil { + return errors.WithMessage(err, "get sessions") + } + + itemsCount += len(response.Items) + } + + return nil +} + +func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { + req.Limit = requestLimit + req.Offset = 0 + + users, err := s.repo.GetUsers(ctx, req) + if err != nil { + return errors.WithMessage(err, "get users") + } + + roles, err := s.repo.GetRoles(ctx) + if err != nil { + return errors.WithMessage(err, "get roles") + } + + if len(users) == 0 { + return nil + } + + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Users"))) + w.Header().Set("content-type", "application/octet-stream; charset=utf-8") + w.Header().Set("transfer-encoding", "chunked") + + csvWriter := csv.NewWriter(w) + defer csvWriter.Flush() + + err = writeCsvLine(csvWriter, entity.UserColumnNames()) + if err != nil { + return errors.WithMessage(err, "write userColumns to csv") + } + + for _, user := range users { + row := []string{strconv.Itoa(int(user.Id)), + user.FullName, + user.Description, + user.Email, + getRoleNamesByIds(roles, user.Roles), + s.formatTime(user.LastSessionCreatedAt, true)} + + err = writeCsvLine(csvWriter, row) + if err != nil { + return errors.WithMessage(err, "write user row to csv") + } + } + + return nil +} + +func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error { + roles, err := s.repo.GetRoles(ctx) + if err != nil { + return errors.WithMessage(err, "get roles") + } + + perms, err := s.repo.GetPermissions(ctx) + if err != nil { + return errors.WithMessage(err, "get permissions") + } + + if len(perms) == 0 { + return nil + } + + columns := entity.RoleColumnNames() + for _, role := range roles { + columns = append(columns, role.Name) + } + + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Roles"))) + w.Header().Set("content-type", "application/octet-stream; charset=utf-8") + w.Header().Set("transfer-encoding", "chunked") + + csvWriter := csv.NewWriter(w) + defer csvWriter.Flush() + + err = writeCsvLine(csvWriter, columns) + if err != nil { + return errors.WithMessage(err, "write role columns to csv") + } + + for _, perm := range perms { + row := []string{perm.Name, perm.Key} + + for _, role := range roles { + if slices.Contains(role.Permissions, perm.Key) { + row = append(row, foundSymbol) + } else { + row = append(row, notFoundSymbol) + } + } + + err = writeCsvLine(csvWriter, row) + if err != nil { + return errors.WithMessage(err, "write role row to csv") + } + } + + return nil +} + +func (s Download) getUsersList(ctx context.Context) (map[int]entity.User, error) { + users, err := s.repo.GetUsers(ctx, domain.UsersDownloadRequest{ + LimitOffestParams: domain.LimitOffestParams{ + Limit: requestLimit, + Offset: 0, + }, + }) + if err != nil { + return nil, errors.WithMessage(err, "get users") + } + + userById := make(map[int]entity.User) + for _, user := range users { + userById[int(user.Id)] = user + } + + return userById, nil +} + +func getUsername(userById map[int]entity.User, userId int) string { + user, ok := userById[userId] + if !ok { + return "" + } + + return user.FullName +} + +func getRoleNamesByIds(roles []entity.Role, roleIds []int) string { + names := make([]string, 0) + for _, role := range roles { + if slices.Contains(roleIds, role.Id) { + names = append(names, role.Name) + } + } + + return strings.Join(names, ", ") +} + +func writeCsvLine(csvWriter *csv.Writer, line []string) error { + err := csvWriter.Write(line) + if err != nil { + return errors.WithMessage(err, "write line to csv") + } + + return nil +} + +func getCsvFileName(pageName string) string { + return fmt.Sprintf("%s_%s.%s", pageName, time.Now().Format("02-01-2006_15:04:05"), "csv") +} + +func (s Download) formatTime(t *time.Time, onlyDate bool) string { + if t == nil { + return "" + } + + if onlyDate { + return t.In(s.loc).Format("02-01-2006") + } + + return t.In(s.loc).Format("02-01-2006 15:04:05") +} diff --git a/vendor/github.com/julienschmidt/httprouter/.travis.yml b/vendor/github.com/julienschmidt/httprouter/.travis.yml new file mode 100644 index 0000000..ffacfb5 --- /dev/null +++ b/vendor/github.com/julienschmidt/httprouter/.travis.yml @@ -0,0 +1,18 @@ +sudo: false +language: go +go: + - 1.7.x + - 1.8.x + - 1.9.x + - 1.10.x + - 1.11.x + - 1.12.x + - 1.13.x + - master +before_install: + - go get github.com/mattn/goveralls +script: + - go test -v -covermode=count -coverprofile=coverage.out + - go vet ./... + - test -z "$(gofmt -d -s . | tee /dev/stderr)" + - $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci diff --git a/vendor/github.com/julienschmidt/httprouter/LICENSE b/vendor/github.com/julienschmidt/httprouter/LICENSE new file mode 100644 index 0000000..875308f --- /dev/null +++ b/vendor/github.com/julienschmidt/httprouter/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2013, Julien Schmidt +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/julienschmidt/httprouter/README.md b/vendor/github.com/julienschmidt/httprouter/README.md new file mode 100644 index 0000000..d1e68b5 --- /dev/null +++ b/vendor/github.com/julienschmidt/httprouter/README.md @@ -0,0 +1,300 @@ +# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.svg?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage Status](https://coveralls.io/repos/github/julienschmidt/httprouter/badge.svg?branch=master)](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [![GoDoc](https://godoc.org/github.com/julienschmidt/httprouter?status.svg)](http://godoc.org/github.com/julienschmidt/httprouter) + +HttpRouter is a lightweight high performance HTTP request router (also called *multiplexer* or just *mux* for short) for [Go](https://golang.org/). + +In contrast to the [default mux](https://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this router supports variables in the routing pattern and matches against the request method. It also scales better. + +The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching. + +## Features + +**Only explicit matches:** With other routers, like [`http.ServeMux`](https://golang.org/pkg/net/http/#ServeMux), a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like *longest match* or *first registered, first matched*. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience. + +**Stop caring about trailing slashes:** Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can [turn off this behavior](https://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash). + +**Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL. + +**Parameters in your routing pattern:** Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap. + +**Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard `Handler`/`HandlerFunc` API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary. + +**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark). See below for technical details of the implementation. + +**No more server crashes:** You can set a [Panic handler](https://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics occurring during handling a HTTP request. The router then recovers and lets the `PanicHandler` log what happened and deliver a nice error page. + +**Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies. + +Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles). + +## Usage + +This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details. + +Let's start with a trivial example: + +```go +package main + +import ( + "fmt" + "net/http" + "log" + + "github.com/julienschmidt/httprouter" +) + +func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { + fmt.Fprint(w, "Welcome!\n") +} + +func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) +} + +func main() { + router := httprouter.New() + router.GET("/", Index) + router.GET("/hello/:name", Hello) + + log.Fatal(http.ListenAndServe(":8080", router)) +} +``` + +### Named parameters + +As you can see, `:name` is a *named parameter*. The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s. You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method: `:name` can be retrieved by `ByName("name")`. + +When using a `http.Handler` (using `router.Handler` or `http.HandlerFunc`) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the `request.Context`. See more below under [Why doesn't this work with http.Handler?](#why-doesnt-this-work-with-httphandler). + +Named parameters only match a single path segment: + +``` +Pattern: /user/:user + + /user/gordon match + /user/you match + /user/gordon/profile no match + /user/ no match +``` + +**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other. + +### Catch-All parameters + +The second type are *catch-all* parameters and have the form `*name`. Like the name suggests, they match everything. Therefore they must always be at the **end** of the pattern: + +``` +Pattern: /src/*filepath + + /src/ match + /src/somefile.go match + /src/subdir/somefile.go match +``` + +## How does it work? + +The router relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://en.wikipedia.org/wiki/Radix_tree)). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the `GET` request method could look like: + +``` +Priority Path Handle +9 \ *<1> +3 ├s nil +2 |├earch\ *<2> +1 |└upport\ *<3> +2 ├blog\ *<4> +1 | └:post nil +1 | └\ *<5> +2 ├about-us\ *<6> +1 | └team\ *<7> +1 └contact\ *<8> +``` + +Every `*` represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder ([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the `:post` parameter, since we actually match against the routing patterns instead of just comparing hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient. + +Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree. + +For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways: + +1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible. +2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right. + +``` +├------------ +├--------- +├----- +├---- +├-- +├-- +└- +``` + +## Why doesn't this work with `http.Handler`? + +**It does!** The router itself implements the `http.Handler` interface. Moreover the router provides convenient [adapters for `http.Handler`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route. + +Named parameters can be accessed `request.Context`: + +```go +func Hello(w http.ResponseWriter, r *http.Request) { + params := httprouter.ParamsFromContext(r.Context()) + + fmt.Fprintf(w, "hello, %s!\n", params.ByName("name")) +} +``` + +Alternatively, one can also use `params := r.Context().Value(httprouter.ParamsKey)` instead of the helper function. + +Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up. + +## Automatic OPTIONS responses and CORS + +One might wish to modify automatic responses to OPTIONS requests, e.g. to support [CORS preflight requests](https://developer.mozilla.org/en-US/docs/Glossary/preflight_request) or to set other headers. +This can be achieved using the [`Router.GlobalOPTIONS`](https://godoc.org/github.com/julienschmidt/httprouter#Router.GlobalOPTIONS) handler: + +```go +router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Access-Control-Request-Method") != "" { + // Set CORS headers + header := w.Header() + header.Set("Access-Control-Allow-Methods", r.Header.Get("Allow")) + header.Set("Access-Control-Allow-Origin", "*") + } + + // Adjust status code to 204 + w.WriteHeader(http.StatusNoContent) +}) +``` + +## Where can I find Middleware *X*? + +This package just provides a very efficient request router with a few extra features. The router is just a [`http.Handler`](https://golang.org/pkg/net/http/#Handler), you can chain any http.Handler compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](https://justinas.org/writing-http-middleware-in-go/), it's very easy! + +Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter). + +### Multi-domain / Sub-domains + +Here is a quick example: Does your server serve multiple domains / hosts? +You want to use sub-domains? +Define a router per host! + +```go +// We need an object that implements the http.Handler interface. +// Therefore we need a type for which we implement the ServeHTTP method. +// We just use a map here, in which we map host names (with port) to http.Handlers +type HostSwitch map[string]http.Handler + +// Implement the ServeHTTP method on our new type +func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Check if a http.Handler is registered for the given host. + // If yes, use it to handle the request. + if handler := hs[r.Host]; handler != nil { + handler.ServeHTTP(w, r) + } else { + // Handle host names for which no handler is registered + http.Error(w, "Forbidden", 403) // Or Redirect? + } +} + +func main() { + // Initialize a router as usual + router := httprouter.New() + router.GET("/", Index) + router.GET("/hello/:name", Hello) + + // Make a new HostSwitch and insert the router (our http handler) + // for example.com and port 12345 + hs := make(HostSwitch) + hs["example.com:12345"] = router + + // Use the HostSwitch to listen and serve on port 12345 + log.Fatal(http.ListenAndServe(":12345", hs)) +} +``` + +### Basic Authentication + +Another quick example: Basic Authentication (RFC 2617) for handles: + +```go +package main + +import ( + "fmt" + "log" + "net/http" + + "github.com/julienschmidt/httprouter" +) + +func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle { + return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + // Get the Basic Authentication credentials + user, password, hasAuth := r.BasicAuth() + + if hasAuth && user == requiredUser && password == requiredPassword { + // Delegate request to the given handle + h(w, r, ps) + } else { + // Request Basic Authentication otherwise + w.Header().Set("WWW-Authenticate", "Basic realm=Restricted") + http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) + } + } +} + +func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { + fmt.Fprint(w, "Not protected!\n") +} + +func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { + fmt.Fprint(w, "Protected!\n") +} + +func main() { + user := "gordon" + pass := "secret!" + + router := httprouter.New() + router.GET("/", Index) + router.GET("/protected/", BasicAuth(Protected, user, pass)) + + log.Fatal(http.ListenAndServe(":8080", router)) +} +``` + +## Chaining with the NotFound handler + +**NOTE: It might be required to set [`Router.HandleMethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.** + +You can use another [`http.Handler`](https://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [`Router.NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining. + +### Static files + +The `NotFound` handler can for example be used to serve static files from the root path `/` (like an `index.html` file along with other assets): + +```go +// Serve static files from the ./public directory +router.NotFound = http.FileServer(http.Dir("public")) +``` + +But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`. + +## Web Frameworks based on HttpRouter + +If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package: + +* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework +* [api2go](https://github.com/manyminds/api2go): A JSON API Implementation for Go +* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance +* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go +* [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain +* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine +* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow +* [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support +* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context +* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba +* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang +* [pbgo](https://github.com/chai2010/pbgo): pbgo is a mini RPC/REST framework based on Protobuf +* [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server +* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts +* [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware) diff --git a/vendor/github.com/julienschmidt/httprouter/path.go b/vendor/github.com/julienschmidt/httprouter/path.go new file mode 100644 index 0000000..0331c7e --- /dev/null +++ b/vendor/github.com/julienschmidt/httprouter/path.go @@ -0,0 +1,123 @@ +// Copyright 2013 Julien Schmidt. All rights reserved. +// Based on the path package, Copyright 2009 The Go Authors. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +package httprouter + +// CleanPath is the URL version of path.Clean, it returns a canonical URL path +// for p, eliminating . and .. elements. +// +// The following rules are applied iteratively until no further processing can +// be done: +// 1. Replace multiple slashes with a single slash. +// 2. Eliminate each . path name element (the current directory). +// 3. Eliminate each inner .. path name element (the parent directory) +// along with the non-.. element that precedes it. +// 4. Eliminate .. elements that begin a rooted path: +// that is, replace "/.." by "/" at the beginning of a path. +// +// If the result of this process is an empty string, "/" is returned +func CleanPath(p string) string { + // Turn empty string into "/" + if p == "" { + return "/" + } + + n := len(p) + var buf []byte + + // Invariants: + // reading from path; r is index of next byte to process. + // writing to buf; w is index of next byte to write. + + // path must start with '/' + r := 1 + w := 1 + + if p[0] != '/' { + r = 0 + buf = make([]byte, n+1) + buf[0] = '/' + } + + trailing := n > 1 && p[n-1] == '/' + + // A bit more clunky without a 'lazybuf' like the path package, but the loop + // gets completely inlined (bufApp). So in contrast to the path package this + // loop has no expensive function calls (except 1x make) + + for r < n { + switch { + case p[r] == '/': + // empty path element, trailing slash is added after the end + r++ + + case p[r] == '.' && r+1 == n: + trailing = true + r++ + + case p[r] == '.' && p[r+1] == '/': + // . element + r += 2 + + case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'): + // .. element: remove to last / + r += 3 + + if w > 1 { + // can backtrack + w-- + + if buf == nil { + for w > 1 && p[w] != '/' { + w-- + } + } else { + for w > 1 && buf[w] != '/' { + w-- + } + } + } + + default: + // real path element. + // add slash if needed + if w > 1 { + bufApp(&buf, p, w, '/') + w++ + } + + // copy element + for r < n && p[r] != '/' { + bufApp(&buf, p, w, p[r]) + w++ + r++ + } + } + } + + // re-append trailing slash + if trailing && w > 1 { + bufApp(&buf, p, w, '/') + w++ + } + + if buf == nil { + return p[:w] + } + return string(buf[:w]) +} + +// internal helper to lazily create a buffer if necessary +func bufApp(buf *[]byte, s string, w int, c byte) { + if *buf == nil { + if s[w] == c { + return + } + + *buf = make([]byte, len(s)) + copy(*buf, s[:w]) + } + (*buf)[w] = c +} diff --git a/vendor/github.com/julienschmidt/httprouter/router.go b/vendor/github.com/julienschmidt/httprouter/router.go new file mode 100644 index 0000000..599529d --- /dev/null +++ b/vendor/github.com/julienschmidt/httprouter/router.go @@ -0,0 +1,452 @@ +// Copyright 2013 Julien Schmidt. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +// Package httprouter is a trie based high performance HTTP request router. +// +// A trivial example is: +// +// package main +// +// import ( +// "fmt" +// "github.com/julienschmidt/httprouter" +// "net/http" +// "log" +// ) +// +// func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { +// fmt.Fprint(w, "Welcome!\n") +// } +// +// func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { +// fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) +// } +// +// func main() { +// router := httprouter.New() +// router.GET("/", Index) +// router.GET("/hello/:name", Hello) +// +// log.Fatal(http.ListenAndServe(":8080", router)) +// } +// +// The router matches incoming requests by the request method and the path. +// If a handle is registered for this path and method, the router delegates the +// request to that function. +// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to +// register handles, for all other methods router.Handle can be used. +// +// The registered path, against which the router matches incoming requests, can +// contain two types of parameters: +// Syntax Type +// :name named parameter +// *name catch-all parameter +// +// Named parameters are dynamic path segments. They match anything until the +// next '/' or the path end: +// Path: /blog/:category/:post +// +// Requests: +// /blog/go/request-routers match: category="go", post="request-routers" +// /blog/go/request-routers/ no match, but the router would redirect +// /blog/go/ no match +// /blog/go/request-routers/comments no match +// +// Catch-all parameters match anything until the path end, including the +// directory index (the '/' before the catch-all). Since they match anything +// until the end, catch-all parameters must always be the final path element. +// Path: /files/*filepath +// +// Requests: +// /files/ match: filepath="/" +// /files/LICENSE match: filepath="/LICENSE" +// /files/templates/article.html match: filepath="/templates/article.html" +// /files no match, but the router would redirect +// +// The value of parameters is saved as a slice of the Param struct, consisting +// each of a key and a value. The slice is passed to the Handle func as a third +// parameter. +// There are two ways to retrieve the value of a parameter: +// // by the name of the parameter +// user := ps.ByName("user") // defined by :user or *user +// +// // by the index of the parameter. This way you can also get the name (key) +// thirdKey := ps[2].Key // the name of the 3rd parameter +// thirdValue := ps[2].Value // the value of the 3rd parameter +package httprouter + +import ( + "context" + "net/http" + "strings" +) + +// Handle is a function that can be registered to a route to handle HTTP +// requests. Like http.HandlerFunc, but has a third parameter for the values of +// wildcards (variables). +type Handle func(http.ResponseWriter, *http.Request, Params) + +// Param is a single URL parameter, consisting of a key and a value. +type Param struct { + Key string + Value string +} + +// Params is a Param-slice, as returned by the router. +// The slice is ordered, the first URL parameter is also the first slice value. +// It is therefore safe to read values by the index. +type Params []Param + +// ByName returns the value of the first Param which key matches the given name. +// If no matching Param is found, an empty string is returned. +func (ps Params) ByName(name string) string { + for i := range ps { + if ps[i].Key == name { + return ps[i].Value + } + } + return "" +} + +type paramsKey struct{} + +// ParamsKey is the request context key under which URL params are stored. +var ParamsKey = paramsKey{} + +// ParamsFromContext pulls the URL parameters from a request context, +// or returns nil if none are present. +func ParamsFromContext(ctx context.Context) Params { + p, _ := ctx.Value(ParamsKey).(Params) + return p +} + +// Router is a http.Handler which can be used to dispatch requests to different +// handler functions via configurable routes +type Router struct { + trees map[string]*node + + // Enables automatic redirection if the current route can't be matched but a + // handler for the path with (without) the trailing slash exists. + // For example if /foo/ is requested but a route only exists for /foo, the + // client is redirected to /foo with http status code 301 for GET requests + // and 307 for all other request methods. + RedirectTrailingSlash bool + + // If enabled, the router tries to fix the current request path, if no + // handle is registered for it. + // First superfluous path elements like ../ or // are removed. + // Afterwards the router does a case-insensitive lookup of the cleaned path. + // If a handle can be found for this route, the router makes a redirection + // to the corrected path with status code 301 for GET requests and 307 for + // all other request methods. + // For example /FOO and /..//Foo could be redirected to /foo. + // RedirectTrailingSlash is independent of this option. + RedirectFixedPath bool + + // If enabled, the router checks if another method is allowed for the + // current route, if the current request can not be routed. + // If this is the case, the request is answered with 'Method Not Allowed' + // and HTTP status code 405. + // If no other Method is allowed, the request is delegated to the NotFound + // handler. + HandleMethodNotAllowed bool + + // If enabled, the router automatically replies to OPTIONS requests. + // Custom OPTIONS handlers take priority over automatic replies. + HandleOPTIONS bool + + // An optional http.Handler that is called on automatic OPTIONS requests. + // The handler is only called if HandleOPTIONS is true and no OPTIONS + // handler for the specific path was set. + // The "Allowed" header is set before calling the handler. + GlobalOPTIONS http.Handler + + // Cached value of global (*) allowed methods + globalAllowed string + + // Configurable http.Handler which is called when no matching route is + // found. If it is not set, http.NotFound is used. + NotFound http.Handler + + // Configurable http.Handler which is called when a request + // cannot be routed and HandleMethodNotAllowed is true. + // If it is not set, http.Error with http.StatusMethodNotAllowed is used. + // The "Allow" header with allowed request methods is set before the handler + // is called. + MethodNotAllowed http.Handler + + // Function to handle panics recovered from http handlers. + // It should be used to generate a error page and return the http error code + // 500 (Internal Server Error). + // The handler can be used to keep your server from crashing because of + // unrecovered panics. + PanicHandler func(http.ResponseWriter, *http.Request, interface{}) +} + +// Make sure the Router conforms with the http.Handler interface +var _ http.Handler = New() + +// New returns a new initialized Router. +// Path auto-correction, including trailing slashes, is enabled by default. +func New() *Router { + return &Router{ + RedirectTrailingSlash: true, + RedirectFixedPath: true, + HandleMethodNotAllowed: true, + HandleOPTIONS: true, + } +} + +// GET is a shortcut for router.Handle(http.MethodGet, path, handle) +func (r *Router) GET(path string, handle Handle) { + r.Handle(http.MethodGet, path, handle) +} + +// HEAD is a shortcut for router.Handle(http.MethodHead, path, handle) +func (r *Router) HEAD(path string, handle Handle) { + r.Handle(http.MethodHead, path, handle) +} + +// OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle) +func (r *Router) OPTIONS(path string, handle Handle) { + r.Handle(http.MethodOptions, path, handle) +} + +// POST is a shortcut for router.Handle(http.MethodPost, path, handle) +func (r *Router) POST(path string, handle Handle) { + r.Handle(http.MethodPost, path, handle) +} + +// PUT is a shortcut for router.Handle(http.MethodPut, path, handle) +func (r *Router) PUT(path string, handle Handle) { + r.Handle(http.MethodPut, path, handle) +} + +// PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle) +func (r *Router) PATCH(path string, handle Handle) { + r.Handle(http.MethodPatch, path, handle) +} + +// DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle) +func (r *Router) DELETE(path string, handle Handle) { + r.Handle(http.MethodDelete, path, handle) +} + +// Handle registers a new request handle with the given path and method. +// +// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut +// functions can be used. +// +// This function is intended for bulk loading and to allow the usage of less +// frequently used, non-standardized or custom methods (e.g. for internal +// communication with a proxy). +func (r *Router) Handle(method, path string, handle Handle) { + if len(path) < 1 || path[0] != '/' { + panic("path must begin with '/' in path '" + path + "'") + } + + if r.trees == nil { + r.trees = make(map[string]*node) + } + + root := r.trees[method] + if root == nil { + root = new(node) + r.trees[method] = root + + r.globalAllowed = r.allowed("*", "") + } + + root.addRoute(path, handle) +} + +// Handler is an adapter which allows the usage of an http.Handler as a +// request handle. +// The Params are available in the request context under ParamsKey. +func (r *Router) Handler(method, path string, handler http.Handler) { + r.Handle(method, path, + func(w http.ResponseWriter, req *http.Request, p Params) { + if len(p) > 0 { + ctx := req.Context() + ctx = context.WithValue(ctx, ParamsKey, p) + req = req.WithContext(ctx) + } + handler.ServeHTTP(w, req) + }, + ) +} + +// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a +// request handle. +func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) { + r.Handler(method, path, handler) +} + +// ServeFiles serves files from the given file system root. +// The path must end with "/*filepath", files are then served from the local +// path /defined/root/dir/*filepath. +// For example if root is "/etc" and *filepath is "passwd", the local file +// "/etc/passwd" would be served. +// Internally a http.FileServer is used, therefore http.NotFound is used instead +// of the Router's NotFound handler. +// To use the operating system's file system implementation, +// use http.Dir: +// router.ServeFiles("/src/*filepath", http.Dir("/var/www")) +func (r *Router) ServeFiles(path string, root http.FileSystem) { + if len(path) < 10 || path[len(path)-10:] != "/*filepath" { + panic("path must end with /*filepath in path '" + path + "'") + } + + fileServer := http.FileServer(root) + + r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) { + req.URL.Path = ps.ByName("filepath") + fileServer.ServeHTTP(w, req) + }) +} + +func (r *Router) recv(w http.ResponseWriter, req *http.Request) { + if rcv := recover(); rcv != nil { + r.PanicHandler(w, req, rcv) + } +} + +// Lookup allows the manual lookup of a method + path combo. +// This is e.g. useful to build a framework around this router. +// If the path was found, it returns the handle function and the path parameter +// values. Otherwise the third return value indicates whether a redirection to +// the same path with an extra / without the trailing slash should be performed. +func (r *Router) Lookup(method, path string) (Handle, Params, bool) { + if root := r.trees[method]; root != nil { + return root.getValue(path) + } + return nil, nil, false +} + +func (r *Router) allowed(path, reqMethod string) (allow string) { + allowed := make([]string, 0, 9) + + if path == "*" { // server-wide + // empty method is used for internal calls to refresh the cache + if reqMethod == "" { + for method := range r.trees { + if method == http.MethodOptions { + continue + } + // Add request method to list of allowed methods + allowed = append(allowed, method) + } + } else { + return r.globalAllowed + } + } else { // specific path + for method := range r.trees { + // Skip the requested method - we already tried this one + if method == reqMethod || method == http.MethodOptions { + continue + } + + handle, _, _ := r.trees[method].getValue(path) + if handle != nil { + // Add request method to list of allowed methods + allowed = append(allowed, method) + } + } + } + + if len(allowed) > 0 { + // Add request method to list of allowed methods + allowed = append(allowed, http.MethodOptions) + + // Sort allowed methods. + // sort.Strings(allowed) unfortunately causes unnecessary allocations + // due to allowed being moved to the heap and interface conversion + for i, l := 1, len(allowed); i < l; i++ { + for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- { + allowed[j], allowed[j-1] = allowed[j-1], allowed[j] + } + } + + // return as comma separated list + return strings.Join(allowed, ", ") + } + return +} + +// ServeHTTP makes the router implement the http.Handler interface. +func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if r.PanicHandler != nil { + defer r.recv(w, req) + } + + path := req.URL.Path + + if root := r.trees[req.Method]; root != nil { + if handle, ps, tsr := root.getValue(path); handle != nil { + handle(w, req, ps) + return + } else if req.Method != http.MethodConnect && path != "/" { + code := 301 // Permanent redirect, request with GET method + if req.Method != http.MethodGet { + // Temporary redirect, request with same method + // As of Go 1.3, Go does not support status code 308. + code = 307 + } + + if tsr && r.RedirectTrailingSlash { + if len(path) > 1 && path[len(path)-1] == '/' { + req.URL.Path = path[:len(path)-1] + } else { + req.URL.Path = path + "/" + } + http.Redirect(w, req, req.URL.String(), code) + return + } + + // Try to fix the request path + if r.RedirectFixedPath { + fixedPath, found := root.findCaseInsensitivePath( + CleanPath(path), + r.RedirectTrailingSlash, + ) + if found { + req.URL.Path = string(fixedPath) + http.Redirect(w, req, req.URL.String(), code) + return + } + } + } + } + + if req.Method == http.MethodOptions && r.HandleOPTIONS { + // Handle OPTIONS requests + if allow := r.allowed(path, http.MethodOptions); allow != "" { + w.Header().Set("Allow", allow) + if r.GlobalOPTIONS != nil { + r.GlobalOPTIONS.ServeHTTP(w, req) + } + return + } + } else if r.HandleMethodNotAllowed { // Handle 405 + if allow := r.allowed(path, req.Method); allow != "" { + w.Header().Set("Allow", allow) + if r.MethodNotAllowed != nil { + r.MethodNotAllowed.ServeHTTP(w, req) + } else { + http.Error(w, + http.StatusText(http.StatusMethodNotAllowed), + http.StatusMethodNotAllowed, + ) + } + return + } + } + + // Handle 404 + if r.NotFound != nil { + r.NotFound.ServeHTTP(w, req) + } else { + http.NotFound(w, req) + } +} diff --git a/vendor/github.com/julienschmidt/httprouter/tree.go b/vendor/github.com/julienschmidt/httprouter/tree.go new file mode 100644 index 0000000..c9fdf5b --- /dev/null +++ b/vendor/github.com/julienschmidt/httprouter/tree.go @@ -0,0 +1,666 @@ +// Copyright 2013 Julien Schmidt. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file. + +package httprouter + +import ( + "strings" + "unicode" + "unicode/utf8" +) + +func min(a, b int) int { + if a <= b { + return a + } + return b +} + +const maxParamCount uint8 = ^uint8(0) + +func countParams(path string) uint8 { + var n uint + for i := 0; i < len(path); i++ { + if path[i] != ':' && path[i] != '*' { + continue + } + n++ + } + if n >= uint(maxParamCount) { + return maxParamCount + } + + return uint8(n) +} + +type nodeType uint8 + +const ( + static nodeType = iota // default + root + param + catchAll +) + +type node struct { + path string + wildChild bool + nType nodeType + maxParams uint8 + priority uint32 + indices string + children []*node + handle Handle +} + +// increments priority of the given child and reorders if necessary +func (n *node) incrementChildPrio(pos int) int { + n.children[pos].priority++ + prio := n.children[pos].priority + + // adjust position (move to front) + newPos := pos + for newPos > 0 && n.children[newPos-1].priority < prio { + // swap node positions + n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1] + + newPos-- + } + + // build new index char string + if newPos != pos { + n.indices = n.indices[:newPos] + // unchanged prefix, might be empty + n.indices[pos:pos+1] + // the index char we move + n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos' + } + + return newPos +} + +// addRoute adds a node with the given handle to the path. +// Not concurrency-safe! +func (n *node) addRoute(path string, handle Handle) { + fullPath := path + n.priority++ + numParams := countParams(path) + + // non-empty tree + if len(n.path) > 0 || len(n.children) > 0 { + walk: + for { + // Update maxParams of the current node + if numParams > n.maxParams { + n.maxParams = numParams + } + + // Find the longest common prefix. + // This also implies that the common prefix contains no ':' or '*' + // since the existing key can't contain those chars. + i := 0 + max := min(len(path), len(n.path)) + for i < max && path[i] == n.path[i] { + i++ + } + + // Split edge + if i < len(n.path) { + child := node{ + path: n.path[i:], + wildChild: n.wildChild, + nType: static, + indices: n.indices, + children: n.children, + handle: n.handle, + priority: n.priority - 1, + } + + // Update maxParams (max of all children) + for i := range child.children { + if child.children[i].maxParams > child.maxParams { + child.maxParams = child.children[i].maxParams + } + } + + n.children = []*node{&child} + // []byte for proper unicode char conversion, see #65 + n.indices = string([]byte{n.path[i]}) + n.path = path[:i] + n.handle = nil + n.wildChild = false + } + + // Make new node a child of this node + if i < len(path) { + path = path[i:] + + if n.wildChild { + n = n.children[0] + n.priority++ + + // Update maxParams of the child node + if numParams > n.maxParams { + n.maxParams = numParams + } + numParams-- + + // Check if the wildcard matches + if len(path) >= len(n.path) && n.path == path[:len(n.path)] && + // Adding a child to a catchAll is not possible + n.nType != catchAll && + // Check for longer wildcard, e.g. :name and :names + (len(n.path) >= len(path) || path[len(n.path)] == '/') { + continue walk + } else { + // Wildcard conflict + var pathSeg string + if n.nType == catchAll { + pathSeg = path + } else { + pathSeg = strings.SplitN(path, "/", 2)[0] + } + prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path + panic("'" + pathSeg + + "' in new path '" + fullPath + + "' conflicts with existing wildcard '" + n.path + + "' in existing prefix '" + prefix + + "'") + } + } + + c := path[0] + + // slash after param + if n.nType == param && c == '/' && len(n.children) == 1 { + n = n.children[0] + n.priority++ + continue walk + } + + // Check if a child with the next path byte exists + for i := 0; i < len(n.indices); i++ { + if c == n.indices[i] { + i = n.incrementChildPrio(i) + n = n.children[i] + continue walk + } + } + + // Otherwise insert it + if c != ':' && c != '*' { + // []byte for proper unicode char conversion, see #65 + n.indices += string([]byte{c}) + child := &node{ + maxParams: numParams, + } + n.children = append(n.children, child) + n.incrementChildPrio(len(n.indices) - 1) + n = child + } + n.insertChild(numParams, path, fullPath, handle) + return + + } else if i == len(path) { // Make node a (in-path) leaf + if n.handle != nil { + panic("a handle is already registered for path '" + fullPath + "'") + } + n.handle = handle + } + return + } + } else { // Empty tree + n.insertChild(numParams, path, fullPath, handle) + n.nType = root + } +} + +func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) { + var offset int // already handled bytes of the path + + // find prefix until first wildcard (beginning with ':'' or '*'') + for i, max := 0, len(path); numParams > 0; i++ { + c := path[i] + if c != ':' && c != '*' { + continue + } + + // find wildcard end (either '/' or path end) + end := i + 1 + for end < max && path[end] != '/' { + switch path[end] { + // the wildcard name must not contain ':' and '*' + case ':', '*': + panic("only one wildcard per path segment is allowed, has: '" + + path[i:] + "' in path '" + fullPath + "'") + default: + end++ + } + } + + // check if this Node existing children which would be + // unreachable if we insert the wildcard here + if len(n.children) > 0 { + panic("wildcard route '" + path[i:end] + + "' conflicts with existing children in path '" + fullPath + "'") + } + + // check if the wildcard has a name + if end-i < 2 { + panic("wildcards must be named with a non-empty name in path '" + fullPath + "'") + } + + if c == ':' { // param + // split path at the beginning of the wildcard + if i > 0 { + n.path = path[offset:i] + offset = i + } + + child := &node{ + nType: param, + maxParams: numParams, + } + n.children = []*node{child} + n.wildChild = true + n = child + n.priority++ + numParams-- + + // if the path doesn't end with the wildcard, then there + // will be another non-wildcard subpath starting with '/' + if end < max { + n.path = path[offset:end] + offset = end + + child := &node{ + maxParams: numParams, + priority: 1, + } + n.children = []*node{child} + n = child + } + + } else { // catchAll + if end != max || numParams > 1 { + panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'") + } + + if len(n.path) > 0 && n.path[len(n.path)-1] == '/' { + panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'") + } + + // currently fixed width 1 for '/' + i-- + if path[i] != '/' { + panic("no / before catch-all in path '" + fullPath + "'") + } + + n.path = path[offset:i] + + // first node: catchAll node with empty path + child := &node{ + wildChild: true, + nType: catchAll, + maxParams: 1, + } + // update maxParams of the parent node + if n.maxParams < 1 { + n.maxParams = 1 + } + n.children = []*node{child} + n.indices = string(path[i]) + n = child + n.priority++ + + // second node: node holding the variable + child = &node{ + path: path[i:], + nType: catchAll, + maxParams: 1, + handle: handle, + priority: 1, + } + n.children = []*node{child} + + return + } + } + + // insert remaining path part and handle to the leaf + n.path = path[offset:] + n.handle = handle +} + +// Returns the handle registered with the given path (key). The values of +// wildcards are saved to a map. +// If no handle can be found, a TSR (trailing slash redirect) recommendation is +// made if a handle exists with an extra (without the) trailing slash for the +// given path. +func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) { +walk: // outer loop for walking the tree + for { + if len(path) > len(n.path) { + if path[:len(n.path)] == n.path { + path = path[len(n.path):] + // If this node does not have a wildcard (param or catchAll) + // child, we can just look up the next child node and continue + // to walk down the tree + if !n.wildChild { + c := path[0] + for i := 0; i < len(n.indices); i++ { + if c == n.indices[i] { + n = n.children[i] + continue walk + } + } + + // Nothing found. + // We can recommend to redirect to the same URL without a + // trailing slash if a leaf exists for that path. + tsr = (path == "/" && n.handle != nil) + return + + } + + // handle wildcard child + n = n.children[0] + switch n.nType { + case param: + // find param end (either '/' or path end) + end := 0 + for end < len(path) && path[end] != '/' { + end++ + } + + // save param value + if p == nil { + // lazy allocation + p = make(Params, 0, n.maxParams) + } + i := len(p) + p = p[:i+1] // expand slice within preallocated capacity + p[i].Key = n.path[1:] + p[i].Value = path[:end] + + // we need to go deeper! + if end < len(path) { + if len(n.children) > 0 { + path = path[end:] + n = n.children[0] + continue walk + } + + // ... but we can't + tsr = (len(path) == end+1) + return + } + + if handle = n.handle; handle != nil { + return + } else if len(n.children) == 1 { + // No handle found. Check if a handle for this path + a + // trailing slash exists for TSR recommendation + n = n.children[0] + tsr = (n.path == "/" && n.handle != nil) + } + + return + + case catchAll: + // save param value + if p == nil { + // lazy allocation + p = make(Params, 0, n.maxParams) + } + i := len(p) + p = p[:i+1] // expand slice within preallocated capacity + p[i].Key = n.path[2:] + p[i].Value = path + + handle = n.handle + return + + default: + panic("invalid node type") + } + } + } else if path == n.path { + // We should have reached the node containing the handle. + // Check if this node has a handle registered. + if handle = n.handle; handle != nil { + return + } + + if path == "/" && n.wildChild && n.nType != root { + tsr = true + return + } + + // No handle found. Check if a handle for this path + a + // trailing slash exists for trailing slash recommendation + for i := 0; i < len(n.indices); i++ { + if n.indices[i] == '/' { + n = n.children[i] + tsr = (len(n.path) == 1 && n.handle != nil) || + (n.nType == catchAll && n.children[0].handle != nil) + return + } + } + + return + } + + // Nothing found. We can recommend to redirect to the same URL with an + // extra trailing slash if a leaf exists for that path + tsr = (path == "/") || + (len(n.path) == len(path)+1 && n.path[len(path)] == '/' && + path == n.path[:len(n.path)-1] && n.handle != nil) + return + } +} + +// Makes a case-insensitive lookup of the given path and tries to find a handler. +// It can optionally also fix trailing slashes. +// It returns the case-corrected path and a bool indicating whether the lookup +// was successful. +func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) { + return n.findCaseInsensitivePathRec( + path, + make([]byte, 0, len(path)+1), // preallocate enough memory for new path + [4]byte{}, // empty rune buffer + fixTrailingSlash, + ) +} + +// shift bytes in array by n bytes left +func shiftNRuneBytes(rb [4]byte, n int) [4]byte { + switch n { + case 0: + return rb + case 1: + return [4]byte{rb[1], rb[2], rb[3], 0} + case 2: + return [4]byte{rb[2], rb[3]} + case 3: + return [4]byte{rb[3]} + default: + return [4]byte{} + } +} + +// recursive case-insensitive lookup function used by n.findCaseInsensitivePath +func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) { + npLen := len(n.path) + +walk: // outer loop for walking the tree + for len(path) >= npLen && (npLen == 0 || strings.EqualFold(path[1:npLen], n.path[1:])) { + // add common prefix to result + + oldPath := path + path = path[npLen:] + ciPath = append(ciPath, n.path...) + + if len(path) > 0 { + // If this node does not have a wildcard (param or catchAll) child, + // we can just look up the next child node and continue to walk down + // the tree + if !n.wildChild { + // skip rune bytes already processed + rb = shiftNRuneBytes(rb, npLen) + + if rb[0] != 0 { + // old rune not finished + for i := 0; i < len(n.indices); i++ { + if n.indices[i] == rb[0] { + // continue with child node + n = n.children[i] + npLen = len(n.path) + continue walk + } + } + } else { + // process a new rune + var rv rune + + // find rune start + // runes are up to 4 byte long, + // -4 would definitely be another rune + var off int + for max := min(npLen, 3); off < max; off++ { + if i := npLen - off; utf8.RuneStart(oldPath[i]) { + // read rune from cached path + rv, _ = utf8.DecodeRuneInString(oldPath[i:]) + break + } + } + + // calculate lowercase bytes of current rune + lo := unicode.ToLower(rv) + utf8.EncodeRune(rb[:], lo) + + // skip already processed bytes + rb = shiftNRuneBytes(rb, off) + + for i := 0; i < len(n.indices); i++ { + // lowercase matches + if n.indices[i] == rb[0] { + // must use a recursive approach since both the + // uppercase byte and the lowercase byte might exist + // as an index + if out, found := n.children[i].findCaseInsensitivePathRec( + path, ciPath, rb, fixTrailingSlash, + ); found { + return out, true + } + break + } + } + + // if we found no match, the same for the uppercase rune, + // if it differs + if up := unicode.ToUpper(rv); up != lo { + utf8.EncodeRune(rb[:], up) + rb = shiftNRuneBytes(rb, off) + + for i, c := 0, rb[0]; i < len(n.indices); i++ { + // uppercase matches + if n.indices[i] == c { + // continue with child node + n = n.children[i] + npLen = len(n.path) + continue walk + } + } + } + } + + // Nothing found. We can recommend to redirect to the same URL + // without a trailing slash if a leaf exists for that path + return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil) + } + + n = n.children[0] + switch n.nType { + case param: + // find param end (either '/' or path end) + k := 0 + for k < len(path) && path[k] != '/' { + k++ + } + + // add param value to case insensitive path + ciPath = append(ciPath, path[:k]...) + + // we need to go deeper! + if k < len(path) { + if len(n.children) > 0 { + // continue with child node + n = n.children[0] + npLen = len(n.path) + path = path[k:] + continue + } + + // ... but we can't + if fixTrailingSlash && len(path) == k+1 { + return ciPath, true + } + return ciPath, false + } + + if n.handle != nil { + return ciPath, true + } else if fixTrailingSlash && len(n.children) == 1 { + // No handle found. Check if a handle for this path + a + // trailing slash exists + n = n.children[0] + if n.path == "/" && n.handle != nil { + return append(ciPath, '/'), true + } + } + return ciPath, false + + case catchAll: + return append(ciPath, path...), true + + default: + panic("invalid node type") + } + } else { + // We should have reached the node containing the handle. + // Check if this node has a handle registered. + if n.handle != nil { + return ciPath, true + } + + // No handle found. + // Try to fix the path by adding a trailing slash + if fixTrailingSlash { + for i := 0; i < len(n.indices); i++ { + if n.indices[i] == '/' { + n = n.children[i] + if (len(n.path) == 1 && n.handle != nil) || + (n.nType == catchAll && n.children[0].handle != nil) { + return append(ciPath, '/'), true + } + return ciPath, false + } + } + } + return ciPath, false + } + } + + // Nothing found. + // Try to fix the path by adding / removing a trailing slash + if fixTrailingSlash { + if path == "/" { + return ciPath, true + } + if len(path)+1 == npLen && n.path[len(path)] == '/' && + strings.EqualFold(path[1:], n.path[1:len(path)]) && n.handle != nil { + return append(ciPath, n.path...), true + } + } + return ciPath, false +} diff --git a/vendor/github.com/txix-open/isp-kit/http/README.md b/vendor/github.com/txix-open/isp-kit/http/README.md new file mode 100644 index 0000000..eee78cf --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/README.md @@ -0,0 +1,81 @@ +# Package `http` + +Пакет `http` предоставляет инструменты для создания и управления HTTP-сервером с поддержкой middleware, обработки +запросов и гибкой настройки. Интегрируется с системой логирования и обработки ошибок. + +## Types + +### Server + +Структура Server управляет жизненным циклом HTTP-сервера, включая запуск, остановку и динамическое обновление +обработчиков. + +**Methods:** + +#### `NewServer(logger log.Logger, opts ...ServerOption) *Server` + +Конструктор сервера. Дополнительно принимает опции: + +- `WithServer(server *http.Server) ServerOption` – использование объекта предварительно настроенного HTTP-сервера из + стандартной библиотеки `net/http`. + +#### `(s *Server) Upgrade(handler http.Handler)` + +Атомарно заменить текущий обработчик запросов на новый. + +#### `(s *Server) ListenAndServe(address string) error` + +Запустить сервер на указанном адресе. + +#### `(s *Server) Serve(listener net.Listener) error` + +Запустить сервер на существующем listener. + +#### `(s *Server) Shutdown(ctx context.Context) error` + +Остановить сервер, завершив все активные соединения. + +## Usage + +### Default usage flow + +```go +package main + +import ( + "context" + "log" + "net/http" + + http2 "github.com/txix-open/isp-kit/http" + log2 "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/shutdown" +) + +func main() { + logger, err := log2.New() + if err != nil { + log.Fatal(err) + } + + srv := http2.NewServer(logger) + mux := http.NewServeMux() + mux.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("hello world!!")) + }) + + srv.Upgrade(mux) + + shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ + log.Println("shutting down...") + _ = srv.Shutdown(context.Background()) + log.Println("shutdown completed") + }) + + err = srv.ListenAndServe(":8080") + if err != nil { + log.Fatal(err) + } +} + +``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/http/apierrors/README.md b/vendor/github.com/txix-open/isp-kit/http/apierrors/README.md new file mode 100644 index 0000000..094af38 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/apierrors/README.md @@ -0,0 +1,95 @@ +# Package `apierrors` + +Пакет `apierrors` предоставляет инструменты для создания и управления структурированными ошибками HTTP-API. +Ошибки включают код, сообщение, детали и уровень логирования, а также автоматически сериализуются в JSON для ответов +клиентам. + +## Types + +### Error + +Структура для представления ошибки API. Реализует интерфейс `error`. + +**Methods:** + +#### `NewInternalServiceError(err error) Error` + +Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с HTTP-статусом 500, бизнесовым кодом 900 и уровнем +логирования error. + +#### `NewBusinessError(errorCode int, errorMessage string, err error) Error` + +Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с HTTP-статусом 400, указанным +бизнесовым кодом и уровнем логирования warn. + +#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error` + +Создает кастомную ошибку с полным контролем параметров. + +#### `(e Error) Error() string` + +Получить строковое представление ошибки. + +#### `(e Error) WriteError(w http.ResponseWriter) error` + +Сериализует ошибку в JSON и записывает в `http.ResponseWriter`. + +#### `(e Error) WithDetails(details map[string]any) Error` + +Добавить детали информации об ошибке. + +#### `(e Error) WithLogLevel(level log.Level) Error` + +Изменить уровень логирования ошибки. + +#### `(e Error) LogLevel() log.Level` + +Получить текущий уровень логирования ошибки + +## Usage + +### Default usage flow + +```go +package main + +import ( + "context" + "errors" + + "github.com/txix-open/isp-kit/http/apierrors" +) + +type User struct { + Id string + Name string +} + +var ( + ErrUserNotFound = errors.New("user not found") + ErrUserNotFoundCode = 700 +) + +type userService interface { + GetUserById(ctx context.Context, id string) (*User, error) +} + +type userController struct { + svc userService +} + +func (c userController) GetUser(ctx context.Context, userId string) (*User, error) { + result, err := c.svc.GetUserById(ctx, userId) + switch { + case errors.Is(err, ErrUserNotFound): + /* user isn't found so we have to send back specific error code */ + return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err) + case err != nil: + /* got some internal error */ + return nil, apierrors.NewInternalServiceError(err) + default: + return result, nil + } +} + +``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/http/apierrors/error.go b/vendor/github.com/txix-open/isp-kit/http/apierrors/error.go new file mode 100644 index 0000000..b7b756e --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/apierrors/error.go @@ -0,0 +1,93 @@ +// Package apierrors provides HTTP error handling with structured error responses. +// It supports business and internal errors with customizable HTTP status codes, +// error codes, and logging levels. +package apierrors + +import ( + "fmt" + "net/http" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/json" + "github.com/txix-open/isp-kit/log" +) + +const ( + // ErrCodeInternal is the default error code for internal service errors. + ErrCodeInternal = 900 +) + +// Error represents a structured HTTP error with an error code, message, and optional details. +// It supports custom HTTP status codes, logging levels, and error chaining. +type Error struct { + ErrorCode int + ErrorMessage string + Details map[string]any `json:",omitempty"` + + httpStatusCode int + cause error + level log.Level +} + +// NewInternalServiceError creates a new internal service error with HTTP 500 status code. +// It logs at Error level and wraps the provided cause error. +func NewInternalServiceError(err error) Error { + return New(http.StatusInternalServerError, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel) +} + +// NewBusinessError creates a new business error with HTTP 400 status code. +// It logs at Warn level and is used for client-side validation or business logic errors. +func NewBusinessError(errorCode int, errorMessage string, err error) Error { + return New(http.StatusBadRequest, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel) +} + +// New creates a new Error with the specified HTTP status code, error code, message, and cause. +// The default log level is ErrorLevel. +func New( + httpStatusCode int, + errorCode int, + errorMessage string, + err error, +) Error { + return Error{ + ErrorCode: errorCode, + ErrorMessage: errorMessage, + httpStatusCode: httpStatusCode, + cause: err, + level: log.ErrorLevel, + } +} + +// Error returns a formatted string representation of the error. +func (e Error) Error() string { + return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause) +} + +// WriteError writes the error as a JSON response to the http.ResponseWriter. +// It sets the Content-Type header to application/json and the appropriate HTTP status code. +func (e Error) WriteError(w http.ResponseWriter) error { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(e.httpStatusCode) + err := json.NewEncoder(w).Encode(e) + if err != nil { + return errors.WithMessage(err, "json encode error") + } + return nil +} + +// WithDetails adds additional context details to the error. +func (e Error) WithDetails(details map[string]any) Error { + e.Details = details + return e +} + +// WithLogLevel sets the logging level for this error. +func (e Error) WithLogLevel(level log.Level) Error { + e.level = level + return e +} + +// LogLevel returns the logging level associated with this error. +func (e Error) LogLevel() log.Level { + return e.level +} diff --git a/vendor/github.com/txix-open/isp-kit/http/common.go b/vendor/github.com/txix-open/isp-kit/http/common.go new file mode 100644 index 0000000..38d14e3 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/common.go @@ -0,0 +1,16 @@ +// Package http provides core HTTP server functionality and types for building REST and SOAP services. +// It includes a server implementation, handler wrapper, and middleware support for request processing. +package http + +import ( + "context" + "net/http" +) + +// HandlerFunc is the signature for HTTP handlers that process requests in a context-aware manner. +// Handlers should return an error to indicate processing failure. +type HandlerFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request) error + +// Middleware is a function that wraps a HandlerFunc to add cross-cutting concerns +// such as logging, authentication, or metrics collection. +type Middleware func(next HandlerFunc) HandlerFunc diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/README.md b/vendor/github.com/txix-open/isp-kit/http/endpoint/README.md new file mode 100644 index 0000000..cd18454 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/README.md @@ -0,0 +1,257 @@ +# Package `endpoint` + +Пакет `endpoint` предоставляет инструменты для создания HTTP-обработчиков с поддержкой middleware, валидации данных, +логирования и метрик. Упрощает разработку API, автоматизируя рутинные задачи. + +## Types + +### Wrapper + +Структура для создания оберток вокруг обработчиков. Объединяет: + +- Параметры функции (контекст, запрос, тело и т.д.). +- Middleware (логирование, метрики, трейсинг). +- Валидацию и сериализацию данных. + +**Methods:** + +#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, logger log.Logger) Wrapper` + +Конструктор обертки с указанными параметрами. + +#### `(m Wrapper) Endpoint(f any) http.HandlerFunc` + +Преобразовать функцию-обработчик в HTTP-обработчик. + +#### `(m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper` + +Билдер-метод для добавления middleware в обертку. + +### JsonRequestExtractor + +Извлекает JSON из тела запроса и валидирует его с помощью объекта, реализующего интерфейс `Validator`. + +**Methods:** + +#### + +`(j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error)` + +Десериализовать JSON и проверить данные через `Validator`. + +### JsonResponseMapper + +Сериализует ответ в JSON и добавляет заголовки. + +**Methods:** + +#### `(j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error` + +Упаковка результата в JSON-ответ. + +### Caller + +Структура `Caller` предоставляет механизм для вызова функций-обработчиков HTTP-запросов, автоматически преобразуя +параметры запроса в аргументы функции. Интегрируется с валидацией, извлечением данных и middleware. + +**Methods:** + +#### + +`NewCaller(f any, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)` + +Создает экземпляр `Caller` для функции-обработчика. + +#### `(h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error` + +Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса. + + +## Middlewares + +### `MaxRequestBodySize` + +Ограничивает размер тела запроса (по умолчанию 64 МБ). + +### `RequestId` + +Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит. + +### `DecodeRequest` +Декодирует запрос при помощи переданного codec, если заголовок `Content-Encoding` совпадает с типом codec. + +### `LogMiddleware` + +Логирует данные запросов и ответов. + +### `Metrics` + +Собирает метрики: время выполнения, статус-коды, размеры тел. + +### `Tracing` + +Интеграция с трейсингом (OpenTelemetry). + +### `EncodeResponse` + +Кодирует ответ при помощи переданного codec, если заголовок `Accept-Encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах). + +### `ErrorHandler` + +Перехватывает и обрабатывает ошибки. Ошибки типа `HttpError` возвращают структурированный ответ. +Остальные ошибки логируются и возвращаются как 500 Internal Server Error. + +### `Recovery` + +Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку. + +## Functions + +#### `DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper` + +Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами. +Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки". + +Список Middleware: + +- `MaxRequestBodySize` +- `RequestId` +- `LogMiddleware` +- `Metrics` +- `Tracing` +- `ErrorHandler` +- `Recovery` + +#### `DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper` + +Создает предварительно настроенную обертку (`Wrapper`) для HTTP-обработчиков с middleware и параметрами. +Упрощает создание эндпоинтов, включая валидацию, логирование, метрики и обработку ошибок "из коробки". + +Список Middleware: +- `MaxRequestBodySize` +- `RequestId` +- `DecodeRequest` +- `LogMiddleware` +- `Metrics` +- `Tracing` +- `EncodeResponse` +- `ErrorHandler` +- `Recovery` + +## Usage + +### Default usage flow + +```go +package main + +import ( + "context" + "log" + + "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/httplog" + "github.com/txix-open/isp-kit/http/router" + log2 "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/shutdown" +) + +type userRequest struct { + Name string +} + +type userResponse struct { + Id int +} + +func foo(ctx context.Context, req userRequest) (userResponse, error) { + /* put here some business logic */ + return userResponse{Id: 88}, nil +} + +func main() { + logger, err := log2.New() + if err != nil { + log.Fatal(err) + } + + srv := http.NewServer(logger) + + wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true)) + r := router.New() + r.POST("/foo", wrapper.Endpoint(foo)) + + srv.Upgrade(r) + + shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ + log.Println("shutting down...") + _ = srv.Shutdown(context.Background()) + log.Println("shutdown completed") + }) + + err = srv.ListenAndServe(":8080") + if err != nil { + log.Fatal(err) + } +} + +``` + +### Codec usage flow + +```go +package main + +import ( + "context" + "log" + + "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/httplog" + "github.com/txix-open/isp-kit/http/router" + log2 "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/shutdown" +) + +type userRequest struct { + Name string +} + +type userResponse struct { + Id int +} + +func foo(ctx context.Context, req userRequest) (userResponse, error) { + /* put here some business logic */ + return userResponse{Id: 88}, nil +} + +func main() { + logger, err := log2.New() + if err != nil { + log.Fatal(err) + } + + srv := http.NewServer(logger) + + wrapper := endpoint.DefaultCodecWrapper(logger, httplog.Log(logger, true)) + r := router.New() + r.POST("/foo", wrapper.Endpoint(foo)) + + srv.Upgrade(r) + + shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ + log.Println("shutting down...") + _ = srv.Shutdown(context.Background()) + log.Println("shutdown completed") + }) + + err = srv.ListenAndServe(":8080") + if err != nil { + log.Fatal(err) + } +} + +``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/README.md b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/README.md new file mode 100644 index 0000000..18695c8 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/README.md @@ -0,0 +1,88 @@ +# Package `buffer` + +Пакет `buffer` предоставляет инструменты для буферизации HTTP-запросов и ответов. Используется в middleware для +логирования, метрик и других задач, требующих доступа к телам запросов и ответов без их модификации. + +## Types + +### Buffer + +Структура для перехвата и буферизации данных HTTP-ответа. Реализует интерфейс `http.ResponseWriter`. + +**Methods:** + +#### `New() *Buffer` + +Конструктор буфера. Инициализирует внутренние буферы для тела запроса и ответа. + +#### `(m *Buffer) Reset(w http.ResponseWriter)` + +Сбрасывает состояние буфера и привязывает его к новому `http.ResponseWriter`. + +#### `(m *Buffer) Write(b []byte) (int, error)` + +Перехватывает данные, записываемые в ответ, и сохраняет их в буфер. + +#### `(m *Buffer) WriteHeader(statusCode int)` + +Фиксирует статус-код ответа. + +#### `(m *Buffer) ResponseBody() []byte` + +Возвращает тело ответа в виде байтов из буфера. + +#### `(m *Buffer) RequestBody() []byte` + +Возвращает тело запроса в виде байтов из буфера. + +#### `(m *Buffer) ReadRequestBody(r io.Reader) error` + +Читает тело запроса и сохраняет его в буфер. + +#### `(m *Buffer) StatusCode() int` + +Возвращает статус-код ответа. Если статус-код не был еще записан, вернется 200 OK. + +## Functions + +#### `Acquire(w http.ResponseWriter) *Buffer` + +Берет буфер из пула и инициализирует его для работы с указанным `http.ResponseWriter`. + +#### `Release(w *Buffer)` + +Возвращает буфер в пул для повторного использования. + +## Usage + +### Default usage flow + +```go +package main + +import ( + "log" + "net/http" + + "github.com/txix-open/isp-kit/http/endpoint/buffer" +) + +func LoggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + /* get buffer from pool */ + buf := buffer.Acquire(w) + defer buffer.Release(buf) + + /* read request body */ + _ = buf.ReadRequestBody(r.Body) + r.Body = buffer.NewRequestBody(buf.RequestBody()) + + next.ServeHTTP(buf, r) + + /* log response body */ + responseBody := buf.ResponseBody() + log.Printf("Response: %s\n", responseBody) + }) +} + +``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/buffer.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/buffer.go new file mode 100644 index 0000000..b1445c3 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/buffer.go @@ -0,0 +1,88 @@ +// Package buffer provides a ResponseWriter wrapper that buffers request and response bodies. +// It is used for logging and metrics collection in HTTP middleware. +package buffer + +import ( + "bytes" + "io" + "net/http" +) + +const ( + // defaultBufferSize is the initial buffer size in bytes. + defaultBufferSize = 1024 +) + +// Buffer wraps http.ResponseWriter to capture request and response bodies. +// It is commonly used in middleware for logging and metrics collection. +type Buffer struct { + http.ResponseWriter + + requestBuffer *bytes.Buffer + responseBuffer *bytes.Buffer + statusCode int +} + +// New creates a new Buffer with initialized request and response buffers. +func New() *Buffer { + return &Buffer{ + requestBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)), + responseBuffer: bytes.NewBuffer(make([]byte, defaultBufferSize)), + } +} + +// Reset reinitializes the buffer with a new ResponseWriter and clears internal state. +// It should be called before reusing a pooled Buffer. +func (m *Buffer) Reset(w http.ResponseWriter) { + m.ResponseWriter = w + m.statusCode = 0 + m.responseBuffer.Reset() + m.requestBuffer.Reset() +} + +// Write writes data to both the underlying ResponseWriter and the response buffer. +// It returns the number of bytes written and any error encountered. +func (m *Buffer) Write(b []byte) (int, error) { + n, err := m.ResponseWriter.Write(b) + if err != nil { + return n, err + } + + n, err = m.responseBuffer.Write(b) + if err != nil { + return 0, err + } + + return n, nil +} + +// WriteHeader captures the status code and delegates to the underlying ResponseWriter. +func (m *Buffer) WriteHeader(statusCode int) { + m.statusCode = statusCode + m.ResponseWriter.WriteHeader(statusCode) +} + +// ResponseBody returns the captured response body as a byte slice. +func (m *Buffer) ResponseBody() []byte { + return m.responseBuffer.Bytes() +} + +// RequestBody returns the captured request body as a byte slice. +func (m *Buffer) RequestBody() []byte { + return m.requestBuffer.Bytes() +} + +// ReadRequestBody reads the entire request body into the buffer. +// It returns an error if the read operation fails. +func (m *Buffer) ReadRequestBody(r io.Reader) error { + _, err := io.Copy(m.requestBuffer, r) + return err +} + +// StatusCode returns the captured status code, or http.StatusOK if not set. +func (m *Buffer) StatusCode() int { + if m.statusCode == 0 { + return http.StatusOK + } + return m.statusCode +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/pool.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/pool.go new file mode 100644 index 0000000..5cc3ed6 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/pool.go @@ -0,0 +1,33 @@ +package buffer + +import ( + "net/http" + "sync" +) + +// pool is a global sync.Pool for reusing Buffer instances. +// It reduces memory allocation overhead by pooling Buffer objects. +var pool = sync.Pool{ + New: func() any { + return New() + }, +} + +// Acquire retrieves a Buffer from the pool and initializes it with the given ResponseWriter. +// It is safe for concurrent use and should be paired with Release. +func Acquire(w http.ResponseWriter) *Buffer { + var buffer *Buffer + var ok bool + buffer, ok = pool.Get().(*Buffer) + if !ok { + buffer = New() + } + buffer.Reset(w) + return buffer +} + +// Release returns a Buffer to the pool for reuse. +// It should be called after the Buffer is no longer needed. +func Release(w *Buffer) { + pool.Put(w) +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/request_body.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/request_body.go new file mode 100644 index 0000000..a46b278 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/buffer/request_body.go @@ -0,0 +1,29 @@ +package buffer + +import ( + "bytes" +) + +// RequestBody wraps a bytes.Buffer to provide an io.ReadCloser for request body replay. +// It is used when the request body needs to be read multiple times (e.g., for logging). +type RequestBody struct { + body *bytes.Buffer +} + +// NewRequestBody creates a new RequestBody from a byte slice. +func NewRequestBody(body []byte) RequestBody { + return RequestBody{ + body: bytes.NewBuffer(body), + } +} + +// Read reads data from the underlying buffer into p. +// It returns the number of bytes read and any error encountered. +func (r RequestBody) Read(p []byte) (n int, err error) { + return r.body.Read(p) +} + +// Close is a no-op to satisfy the io.ReadCloser interface. +func (r RequestBody) Close() error { + return nil +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/caller.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/caller.go new file mode 100644 index 0000000..437e0c2 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/caller.go @@ -0,0 +1,123 @@ +package endpoint + +import ( + "context" + "net/http" + "reflect" + + "github.com/txix-open/isp-kit/errors" +) + +// param represents a function parameter that can be built from the request context. +type param struct { + index int + builder ParamBuilder +} + +// Caller uses reflection to wrap arbitrary functions as HTTP handlers. +// It automatically extracts request body, builds parameters from the context, +// and maps return values to the response. +type Caller struct { + bodyExtractor RequestBodyExtractor + bodyMapper ResponseBodyMapper + + handler reflect.Value + paramsCount int + params []param + reqBodyIndex int + reqBodyType reflect.Type + + hasResult bool + hasError bool + errorIndex int +} + +// NewCaller creates a new Caller that wraps the provided function. +// It analyzes the function signature and configures parameter extraction and result mapping. +// Returns an error if the provided value is not a function or has invalid parameter types. +func NewCaller( + f any, + bodyExtractor RequestBodyExtractor, + bodyMapper ResponseBodyMapper, + paramMappers map[string]ParamMapper, +) (*Caller, error) { + rt := reflect.TypeOf(f) + if rt.Kind() != reflect.Func { + return nil, errors.New("function expected") + } + + paramsCount := rt.NumIn() + reqBodyIndex := -1 + handler := reflect.ValueOf(f) + var reqBodyType reflect.Type + params := make([]param, 0, paramsCount) + + for i := range paramsCount { + p := rt.In(i) + paramType := p.String() + mapper, ok := paramMappers[paramType] + + if !ok { // maybe it's a request body + if reqBodyIndex != -1 { + return nil, errors.Errorf("param mapper not found for type %s", paramType) + } + reqBodyIndex = i + reqBodyType = p + continue + } + + // it's a simple param + params = append(params, param{index: i, builder: mapper.Builder}) + } + + numOut := rt.NumOut() + hasResult := numOut > 0 && rt.Out(0) != reflect.TypeFor[*error]().Elem() + hasError := numOut > 0 && rt.Out(numOut-1) == reflect.TypeFor[*error]().Elem() + + return &Caller{ + bodyExtractor: bodyExtractor, + bodyMapper: bodyMapper, + handler: handler, + paramsCount: paramsCount, + params: params, + reqBodyIndex: reqBodyIndex, + reqBodyType: reqBodyType, + hasResult: hasResult, + hasError: hasError, + errorIndex: numOut - 1, + }, nil +} + +// Handle invokes the wrapped function with extracted parameters and maps the result. +// It returns an error if parameter extraction fails or the function returns an error. +func (h *Caller) Handle(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + args := make([]reflect.Value, h.paramsCount) + + if h.reqBodyIndex != -1 { + value, err := h.bodyExtractor.Extract(ctx, r.Body, h.reqBodyType) + if err != nil { + return err + } + args[h.reqBodyIndex] = value + } + + for _, p := range h.params { + value, err := p.builder(ctx, w, r) + if err != nil { + return err + } + args[p.index] = reflect.ValueOf(value) + } + + out := h.handler.Call(args) + + if h.hasError && !out[h.errorIndex].IsNil() { + return out[h.errorIndex].Interface().(error) // nolint:forcetypeassert + } + + if h.hasResult { + return h.bodyMapper.Map(ctx, out[0].Interface(), w) + } + + return nil +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/codec_middleware.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/codec_middleware.go new file mode 100644 index 0000000..4f85ee3 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/codec_middleware.go @@ -0,0 +1,201 @@ +package endpoint + +import ( + "bufio" + "bytes" + "context" + "io" + "net" + "net/http" + "strings" + + "github.com/txix-open/isp-kit/codec" + "github.com/txix-open/isp-kit/errors" + http2 "github.com/txix-open/isp-kit/http" +) + +type DecodeCodec interface { + Type() string + Decode(r io.ReadCloser) (io.ReadCloser, error) +} + +const ( + defaultEncodeThreshold = codec.DefaultEncodeThreshold +) + +// DecodeRequest returns middleware that transparently handles encoded requests. +// +// If Content-Encoding matches codec, request body is decoded. +// +// Important: +// - Should be placed before logging middleware if logs must see decoded data. +func DecodeRequest(codec DecodeCodec) http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + if r.Header.Get("Content-Encoding") == codec.Type() { + decoded, err := codec.Decode(r.Body) + if err != nil { + return err + } + + r.Body = decoded + r.Header.Del("Content-Encoding") + r.Header.Del("Content-Length") + } + return next(ctx, w, r) + } + } +} + +type EncodeCodec interface { + Type() string + Encode(w io.Writer) (io.WriteCloser, error) +} + +// EncodeResponse returns middleware that transparently handles response encoding. +// +// If client supports Accept-Encoding and response body size > encodeThresholdBytes, +// the response is encoded using codec. +// +// The middleware finalizes the response after the handler returns. It may +// implicitly call WriteHeader(http.StatusOK) and flush buffered response data +// even if the handler never calls Write or WriteHeader. +// +// Important: +// - Should be placed before logging middleware if logs must see plain data. +func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + if !acceptsEncoding(r.Header.Get("Accept-Encoding"), codec.Type()) { + return next(ctx, w, r) + } + + cw := newEncoderWriter(w, codec, encodeThresholdBytes) + + err := next(ctx, cw, r) + closeErr := cw.Close() + + if err != nil { + return err + } + return closeErr + } + } +} + +type encoderWriter struct { + http.ResponseWriter + + codec EncodeCodec + + buffer bytes.Buffer + encodeThreshold int + + writer io.WriteCloser + status int +} + +func newEncoderWriter(w http.ResponseWriter, codec EncodeCodec, encodeThreshold int) *encoderWriter { + return &encoderWriter{ + ResponseWriter: w, + codec: codec, + encodeThreshold: encodeThreshold, + } +} + +func (w *encoderWriter) WriteHeader(code int) { + if w.status != 0 { + return + } + w.status = code +} + +func (w *encoderWriter) Write(b []byte) (int, error) { + if w.writer != nil { + return w.writer.Write(b) + } + + // fast path: big first write + if w.buffer.Len() == 0 && len(b) > w.encodeThreshold { + return w.startEncoding(b) + } + + n, err := w.buffer.Write(b) + if err != nil { + return n, err + } + + if w.buffer.Len() > w.encodeThreshold { + data := append([]byte(nil), w.buffer.Bytes()...) + w.buffer.Reset() + + return w.startEncoding(data) + } + + return n, nil +} + +func (w *encoderWriter) Close() error { + if w.writer != nil { + return w.writer.Close() + } + + status := w.status + if status == 0 { + status = http.StatusOK + } + w.ResponseWriter.WriteHeader(status) + + _, err := w.ResponseWriter.Write(w.buffer.Bytes()) + return err +} + +// Hijack implements http.Hijacker. +// +// Hijacking is only allowed before the response has started (no buffered or +// encoded data). Once any response data has been written or encoding has been +// triggered, hijacking is disallowed to prevent losing buffered state and to +// preserve response integrity. +func (w *encoderWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + if w.writer != nil || w.buffer.Len() > 0 || w.status != 0 { + return nil, nil, errors.New("encoderWriter: hijack not allowed after response started") + } + + upstream, ok := w.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("encoderWriter: upstream writer doesn't implement Hijack") + } + + return upstream.Hijack() +} + +func (w *encoderWriter) startEncoding(b []byte) (int, error) { + writer, err := w.codec.Encode(w.ResponseWriter) + if err != nil { + return 0, err + } + w.writer = writer + + h := w.Header() + h.Set("Content-Encoding", w.codec.Type()) + h.Add("Vary", "Accept-Encoding") + h.Del("Content-Length") + + status := w.status + if status == 0 { + status = http.StatusOK + } + w.ResponseWriter.WriteHeader(status) + + return w.writer.Write(b) +} + +func acceptsEncoding(header, encoding string) bool { + for part := range strings.SplitSeq(header, ",") { + if strings.TrimSpace(part) == encoding { + return true + } + } + + return false +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/default.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/default.go new file mode 100644 index 0000000..56f86d9 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/default.go @@ -0,0 +1,74 @@ +package endpoint + +import ( + "github.com/txix-open/isp-kit/codec" + "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/metrics" + "github.com/txix-open/isp-kit/metrics/http_metrics" + "github.com/txix-open/isp-kit/observability/tracing/http/server_tracing" + "github.com/txix-open/isp-kit/validator" +) + +// DefaultWrapper creates a pre-configured Wrapper with common middleware and settings. +// It includes request logging, metrics collection, tracing, error handling, and recovery. +// The default maximum request body size is 64MB. +func DefaultWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper { + paramMappers := []ParamMapper{ + ContextParam(), + ResponseWriterParam(), + RequestParam(), + } + middlewares := append( + []http.Middleware{ + MaxRequestBodySize(defaultMaxRequestBodySize), + RequestId(), + http.Middleware(logMiddleware), + Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)), + server_tracing.NewConfig().Middleware(), + ErrorHandler(logger), + Recovery(), + }, + restMiddlewares..., + ) + + return NewWrapper( + paramMappers, + JsonRequestExtractor{Validator: validator.Default}, + JsonResponseMapper{}, + logger, + ).WithMiddlewares(middlewares...) +} + +// DefaultCodecWrapper creates a pre-configured Wrapper with common middleware and settings. +// It includes request logging, encode response, decode request, metrics collection, tracing, error handling, and recovery. +// The default maximum request body size is 64MB. +func DefaultCodecWrapper(logger log.Logger, logMiddleware LogMiddleware, restMiddlewares ...http.Middleware) Wrapper { + paramMappers := []ParamMapper{ + ContextParam(), + ResponseWriterParam(), + RequestParam(), + } + codec := codec.Default + middlewares := append( + []http.Middleware{ + MaxRequestBodySize(defaultMaxRequestBodySize), + RequestId(), + DecodeRequest(codec), + Metrics(http_metrics.NewServerStorage(metrics.DefaultRegistry)), + server_tracing.NewConfig().Middleware(), + EncodeResponse(codec, defaultEncodeThreshold), + http.Middleware(logMiddleware), + ErrorHandler(logger), + Recovery(), + }, + restMiddlewares..., + ) + + return NewWrapper( + paramMappers, + JsonRequestExtractor{Validator: validator.Default}, + JsonResponseMapper{}, + logger, + ).WithMiddlewares(middlewares...) +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/README.md b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/README.md new file mode 100644 index 0000000..3d7e8af --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/README.md @@ -0,0 +1,89 @@ +# Package `httplog` + +Пакет `httplog` предоставляет middleware для логирования HTTP-запросов и ответов. Поддерживает гибкую настройку: выбор +типов контента для логирования тела, управление детализацией и интеграцию с буферизацией данных. + +## Functions + +#### `Log(logger log.Logger, logBody bool) endpoint.LogMiddleware` + +Создает middleware с базовыми настройками: + +- Логирует тело запроса/ответа, если `logBody = true`. +- По умолчанию логирует только для `application/json` и `text/xml`. + +#### `CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware` + +Создает middleware с базовыми настройками: + +- Логирует тело запроса/ответа, если `logBody = true`. +- По умолчанию логирует только для `application/json` и `text/xml`. +- Собирает запрос и ответ в 1 лог. + +#### `LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware` + +Создает middleware с кастомными настройками через опции: + +- `WithContentTypes(logBodyContentTypes []string) Option` – Задает типы контента, для которых логируется тело (например, + `application/json`). +- `WithLogBody(logBody bool) Option` – Включает/отключает логирование тела запроса и ответа. +- `WithLogResponseBody(logResponseBody bool) Option` – Включает/отключает логирование тела ответа. +- `WithLogRequestBody(logRequestBody bool) Option` – Включает/отключает логирование тела запроса. +- `WithCombinedLog(enable bool) Option` – Включает/отключает сборку запроса/ответа в 1 лог. + +## Usage + +### Default log middleware + +```go +package main + +import ( + "log" + + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/httplog" + log2 "github.com/txix-open/isp-kit/log" +) + +func main() { + logger, err := log2.New() + if err != nil { + log.Fatal(err) + } + + /* create wrapper with default logging middleware */ + wrapper := endpoint.DefaultWrapper(logger, httplog.Log(logger, true)) +} + +``` + +### Customize log middleware + +```go +package main + +import ( + "log" + + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/httplog" + log2 "github.com/txix-open/isp-kit/log" +) + +func main() { + logger, err := log2.New() + if err != nil { + log.Fatal(err) + } + + /* create wrapper with custom logging middleware */ + wrapper := endpoint.DefaultWrapper(logger, httplog.LogWithOptions( + logger, + httplog.WithLogRequestBody(true), // enable logging request body + httplog.WithLogResponseBody(false), // disable logging response body + httplog.WithContentTypes([]string{"application/custom"}), // only for `application/custom` content-type + )) +} + +``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/log_middleware.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/log_middleware.go new file mode 100644 index 0000000..78f9314 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/log_middleware.go @@ -0,0 +1,215 @@ +// Package httplog provides HTTP request/response logging middleware. +// It supports separate request and response body logging, combined logging, +// and content-type filtering. +package httplog + +import ( + "context" + "encoding/base64" + "net/http" + "strconv" + "strings" + "time" + + "github.com/txix-open/isp-kit/errors" + http2 "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/buffer" + "github.com/txix-open/isp-kit/log" +) + +const ( + // applicationNameHeader is the HTTP header for base64-encoded application name. + applicationNameHeader = "X-Application-Name" + // applicationIdHeader is the HTTP header for application identity (numeric ID). + applicationIdHeader = "X-Application-Identity" +) + +var ( + // defaultLogBodyContentTypes specifies the content types for which body logging is enabled. + defaultLogBodyContentTypes = []string{ + "application/json", + "text/xml", + } +) + +// logConfig holds the configuration for the logging middleware. +type logConfig struct { + logBodyContentTypes []string + logRequestBody bool + logResponseBody bool + combinedLog bool +} + +// Log creates a logging middleware that logs requests and responses separately. +// If logBody is true, it logs request and response bodies for supported content types. +func Log(logger log.Logger, logBody bool) endpoint.LogMiddleware { + cfg := &logConfig{ + logBodyContentTypes: defaultLogBodyContentTypes, + logRequestBody: logBody, + logResponseBody: logBody, + } + return middleware(logger, cfg) +} + +// CombinedLog creates a logging middleware that logs requests and responses in a single entry. +// If logBody is true, it logs request and response bodies for supported content types. +func CombinedLog(logger log.Logger, logBody bool) endpoint.LogMiddleware { + cfg := &logConfig{ + logBodyContentTypes: defaultLogBodyContentTypes, + logRequestBody: logBody, + logResponseBody: logBody, + } + return combinedLogMiddleware(logger, cfg) +} + +// LogWithOptions creates a logging middleware with custom configuration options. +// By default, body logging is disabled. Use options like WithLogBody, WithCombinedLog +// to customize the behavior. +func LogWithOptions(logger log.Logger, opts ...Option) endpoint.LogMiddleware { + cfg := &logConfig{ + logBodyContentTypes: defaultLogBodyContentTypes, + logRequestBody: false, + logResponseBody: false, + combinedLog: false, + } + for _, opt := range opts { + opt(cfg) + } + + if cfg.combinedLog { + return combinedLogMiddleware(logger, cfg) + } + return middleware(logger, cfg) +} + +// middleware creates a logging middleware that logs requests and responses separately. +func middleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + buf := buffer.Acquire(w) + defer buffer.Release(buf) + + now := time.Now() + requestLogFields := []log.Field{ + log.String("method", r.Method), + log.String("url", r.URL.String()), + } + + requestContentType := r.Header.Get("Content-Type") + if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) { + err := buf.ReadRequestBody(r.Body) + if err != nil { + return errors.WithMessage(err, "read request body for logging") + } + err = r.Body.Close() + if err != nil { + return errors.WithMessage(err, "close request reader") + } + r.Body = buffer.NewRequestBody(buf.RequestBody()) + + requestLogFields = append(requestLogFields, log.ByteString("requestBody", buf.RequestBody())) + } + + logger.Debug(ctx, "http handler: request", requestLogFields...) + + err := next(ctx, buf, r) + + responseLogFields := []log.Field{ + log.Int("statusCode", buf.StatusCode()), + log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()), + } + + responseContentType := buf.Header().Get("Content-Type") + if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) { + responseLogFields = append(responseLogFields, log.ByteString("responseBody", buf.ResponseBody())) + } + + logger.Debug(ctx, "http handler: response", responseLogFields...) + + return err + } + } +} + +// combinedLogMiddleware creates a logging middleware that logs requests and responses in a single entry. +func combinedLogMiddleware(logger log.Logger, cfg *logConfig) endpoint.LogMiddleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + buf := buffer.Acquire(w) + defer buffer.Release(buf) + + now := time.Now() + logFields := []log.Field{ + log.String("method", r.Method), + log.String("url", r.URL.String()), + } + logFields = append(logFields, applicationLogFields(r)...) + + requestContentType := r.Header.Get("Content-Type") + if cfg.logRequestBody && matchContentType(requestContentType, cfg.logBodyContentTypes) { + err := buf.ReadRequestBody(r.Body) + if err != nil { + return errors.WithMessage(err, "read request body for logging") + } + err = r.Body.Close() + if err != nil { + return errors.WithMessage(err, "close request reader") + } + r.Body = buffer.NewRequestBody(buf.RequestBody()) + + logFields = append(logFields, log.ByteString("requestBody", buf.RequestBody())) + } + + err := next(ctx, buf, r) + + logFields = append(logFields, + log.Int("statusCode", buf.StatusCode()), + log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()), + ) + responseContentType := buf.Header().Get("Content-Type") + if cfg.logResponseBody && matchContentType(responseContentType, cfg.logBodyContentTypes) { + logFields = append(logFields, log.ByteString("responseBody", buf.ResponseBody())) + } + + logger.Debug(ctx, "http handler: log", logFields...) + + return err + } + } +} + +// matchContentType checks if the given content type matches any of the available content types. +// It uses prefix matching to handle content types with parameters (e.g., "application/json; charset=utf-8"). +func matchContentType(contentType string, availableContentTypes []string) bool { + for _, content := range availableContentTypes { + if strings.HasPrefix(contentType, content) { + return true + } + } + return false +} + +// applicationLogFields extracts application-related log fields from the request. +// It decodes the base64-encoded application name and parses the application ID. +func applicationLogFields(r *http.Request) []log.Field { + logFields := make([]log.Field, 0) + appName := r.Header.Get(applicationNameHeader) + if appName != "" { + decodedName, err := base64.StdEncoding.DecodeString(appName) + if err == nil { + logFields = append(logFields, log.String("applicationName", string(decodedName))) + } + } + + appId := r.Header.Get(applicationIdHeader) + if appId == "" { + return logFields + } + + intAppId, err := strconv.Atoi(appId) + if err == nil { + logFields = append(logFields, log.Int("applicationId", intAppId)) + } + return logFields +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/nop.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/nop.go new file mode 100644 index 0000000..b677be5 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/nop.go @@ -0,0 +1,19 @@ +package httplog + +import ( + "context" + "net/http" + + http2 "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/endpoint" +) + +// Noop returns a no-operation logging middleware that simply passes through requests. +// It is useful as a placeholder or for testing when logging is not needed. +func Noop() endpoint.LogMiddleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + return next(ctx, w, r) + } + } +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/options.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/options.go new file mode 100644 index 0000000..2430956 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/httplog/options.go @@ -0,0 +1,42 @@ +package httplog + +// Option is a function that configures the logConfig. +type Option func(cfg *logConfig) + +// WithContentTypes sets the content types for which request and response bodies will be logged. +// Content types are matched using prefix comparison (e.g., "application/json" matches "application/json; charset=utf-8"). +func WithContentTypes(logBodyContentTypes []string) Option { + return func(cfg *logConfig) { + cfg.logBodyContentTypes = logBodyContentTypes + } +} + +// WithLogBody is a shortcut to enable both request and response body logging. +func WithLogBody(logBody bool) Option { + return func(cfg *logConfig) { + cfg.logResponseBody = logBody + cfg.logRequestBody = logBody + } +} + +// WithLogResponseBody enables or disables response body logging. +func WithLogResponseBody(logResponseBody bool) Option { + return func(cfg *logConfig) { + cfg.logResponseBody = logResponseBody + } +} + +// WithLogRequestBody enables or disables request body logging. +func WithLogRequestBody(logRequestBody bool) Option { + return func(cfg *logConfig) { + cfg.logRequestBody = logRequestBody + } +} + +// WithCombinedLog enables or disables single combined log entry for request and response. +// When enabled, the middleware logs request and response in a single log entry instead of two separate entries. +func WithCombinedLog(enable bool) Option { + return func(cfg *logConfig) { + cfg.combinedLog = enable + } +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/json_request.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/json_request.go new file mode 100644 index 0000000..057d27e --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/json_request.go @@ -0,0 +1,90 @@ +package endpoint + +import ( + "context" + "io" + "net/http" + "reflect" + "unicode" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/http/apierrors" + "github.com/txix-open/isp-kit/json" +) + +// Validator validates a value and returns whether it's valid along with field-level error details. +type Validator interface { + // Validate returns true if valid and a map of field names to error messages. + Validate(value any) (bool, map[string]string) +} + +// JsonRequestExtractor extracts and validates JSON request bodies. +// It decodes JSON, validates the result, and returns business errors for invalid input. +type JsonRequestExtractor struct { + Validator Validator +} + +// Extract decodes the JSON request body into a reflect.Value of the specified type. +// It validates the decoded value and returns a business error if validation fails. +func (j JsonRequestExtractor) Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error) { + instance := reflect.New(reqBodyType) + err := j.extract(reader, instance.Interface()) + if err != nil { + return reflect.Value{}, err + } + + elem := instance.Elem() + err = j.validate(elem.Interface()) + if err != nil { + return reflect.Value{}, err + } + + return elem, nil +} + +// ExtractV2 decodes the JSON request body into the provided pointer. +// It validates the decoded value and returns a business error if validation fails. +func (j JsonRequestExtractor) ExtractV2(_ context.Context, reader io.Reader, ptr any) error { + err := j.extract(reader, ptr) + if err != nil { + return err + } + return j.validate(ptr) +} + +// extract decodes JSON from the reader into the target pointer. +// It returns a business error with HTTP 400 status for invalid JSON. +func (j JsonRequestExtractor) extract(reader io.Reader, ptr any) error { + err := json.NewDecoder(reader).Decode(ptr) + if err != nil { + err = errors.WithMessage(err, "unmarshal json request body") + return apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err) + } + return nil +} + +// validate validates the decoded value using the configured validator. +// It returns a business error with validation details if validation fails. +func (j JsonRequestExtractor) validate(v any) error { + ok, details := j.Validator.Validate(v) + if ok { + return nil + } + formattedDetails := formatDetails(details) + return apierrors.NewBusinessError( + http.StatusBadRequest, + "invalid request body", + errors.Errorf("validation errors: %v", formattedDetails), + ).WithDetails(formattedDetails) +} + +// formatDetails converts validation error details by lowercasing the first letter of each field name. +func formatDetails(details map[string]string) map[string]any { + result := make(map[string]any, len(details)) + for k, v := range details { + arr := []rune(k) + arr[0] = unicode.ToLower(arr[0]) + result[string(arr)] = v + } + return result +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/json_response.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/json_response.go new file mode 100644 index 0000000..d16a4b4 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/json_response.go @@ -0,0 +1,37 @@ +package endpoint + +import ( + "context" + "net/http" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/json" + "github.com/txix-open/isp-kit/requestid" +) + +// JsonResponseMapper maps response objects to JSON format. +// It sets the Content-Type header to application/json and includes the request ID in response headers. +type JsonResponseMapper struct { +} + +// Map marshals the result to JSON and writes it to the http.ResponseWriter. +// It skips nil results and includes the request ID in the response headers if available. +func (j JsonResponseMapper) Map(ctx context.Context, result any, w http.ResponseWriter) error { + reqId := requestid.FromContext(ctx) + if reqId != "" { + w.Header().Set(requestid.Header, reqId) + } + + if result == nil { + return nil + } + + w.Header().Set("Content-Type", "application/json") + + err := json.EncodeInto(w, result) + if err != nil { + return errors.WithMessage(err, "marshal json") + } + + return nil +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/metrics_middleware.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/metrics_middleware.go new file mode 100644 index 0000000..d80f45f --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/metrics_middleware.go @@ -0,0 +1,71 @@ +package endpoint + +import ( + "context" + "net/http" + "time" + + http2 "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/endpoint/buffer" + "github.com/txix-open/isp-kit/metrics/http_metrics" +) + +// scSource is an interface for retrieving the HTTP status code from a response. +type scSource interface { + StatusCode() int +} + +// writerWrapper wraps http.ResponseWriter to capture the status code. +// It defaults to http.StatusOK if WriteHeader is not called. +type writerWrapper struct { + http.ResponseWriter + + statusCode int +} + +// StatusCode returns the captured status code, or http.StatusOK if not set. +func (w *writerWrapper) StatusCode() int { + if w.statusCode == 0 { + return http.StatusOK + } + return w.statusCode +} + +// WriteHeader captures the status code and delegates to the underlying ResponseWriter. +func (w *writerWrapper) WriteHeader(statusCode int) { + w.statusCode = statusCode + w.ResponseWriter.WriteHeader(statusCode) +} + +// Metrics is a middleware that collects HTTP server metrics for each endpoint. +// It records request duration, status code counts, and request/response body sizes. +// If the endpoint is not available in the context, it skips metrics collection. +func Metrics(storage *http_metrics.ServerStorage) http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + endpoint := http_metrics.ServerEndpoint(r.Context()) + if endpoint == "" { + return next(ctx, w, r) + } + + var scSrc scSource + buf, isBuffer := w.(*buffer.Buffer) + if isBuffer { + scSrc = buf + } else { + scSrc = &writerWrapper{ResponseWriter: w} + } + + start := time.Now() + err := next(ctx, w, r) + storage.ObserveDuration(r.Method, endpoint, time.Since(start)) + storage.CountStatusCode(r.Method, endpoint, scSrc.StatusCode()) + if isBuffer { + storage.ObserveRequestBodySize(r.Method, endpoint, len(buf.RequestBody())) + storage.ObserveResponseBodySize(r.Method, endpoint, len(buf.ResponseBody())) + } + + return err + } + } +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/middlewares.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/middlewares.go new file mode 100644 index 0000000..9a01c6a --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/middlewares.go @@ -0,0 +1,124 @@ +package endpoint + +import ( + "context" + "fmt" + "net/http" + + "github.com/getsentry/sentry-go" + http2 "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/apierrors" + "github.com/txix-open/isp-kit/log/logutil" + sentry2 "github.com/txix-open/isp-kit/observability/sentry" + "github.com/txix-open/isp-kit/panic_recovery" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/requestid" +) + +const ( + // defaultMaxRequestBodySize is the default maximum allowed request body size (64MB). + defaultMaxRequestBodySize = 64 * 1024 * 1024 +) + +// LogMiddleware is an alias for http.Middleware used for request/response logging. +type LogMiddleware http2.Middleware + +// MaxRequestBodySize limits the size of the request body that can be read. +// It wraps the request body with http.MaxBytesReader to enforce the limit. +func MaxRequestBodySize(maxBytes int64) http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + r.Body = http.MaxBytesReader(w, r.Body, maxBytes) + return next(ctx, w, r) + } + } +} + +// Recovery is a middleware that catches panics and converts them to errors. +// It ensures the server remains stable even when handler code panics. +// Safe for concurrent use. +func Recovery() http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) { + defer panic_recovery.Recover(func(panicErr error) { + err = panicErr + }) + + return next(ctx, w, r) + } + } +} + +// ErrorHandler is a middleware that logs errors and writes appropriate HTTP responses. +// It uses the error's logging level and enriches Sentry events with request details. +// For HttpError implementations, it writes the error using WriteError; otherwise, +// it returns a generic internal service error to hide implementation details. +func ErrorHandler(logger log.Logger) http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + err := next(ctx, w, r) + if err == nil { + return nil + } + + logFunc := logutil.LogLevelFuncForError(err, logger) + logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) { + event.Request = sentryRequest(r) + }) + logFunc(logContext, err) + + reqId := requestid.FromContext(ctx) + if reqId != "" { + w.Header().Set(requestid.Header, reqId) + } + + var httpErr HttpError + if errors.As(err, &httpErr) { + err = httpErr.WriteError(w) + return err + } + + // hide error details to prevent potential security leaks + err = apierrors.NewInternalServiceError(err).WriteError(w) + + return err + } + } +} + +// RequestId is a middleware that manages request IDs for tracing and logging. +// It uses the existing request ID from headers if present, or generates a new one. +// The request ID is added to the context and response headers. +func RequestId() http2.Middleware { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + requestId := r.Header.Get(requestid.Header) + if requestId == "" { + requestId = requestid.Next() + } + + ctx = requestid.ToContext(ctx, requestId) + ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId)) + + return next(ctx, w, r) + } + } +} + +// sentryRequest creates a Sentry request object from an http.Request. +// It determines the protocol based on TLS or X-Forwarded-Proto header. +func sentryRequest(r *http.Request) *sentry.Request { + protocol := "https" + if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { + protocol = "http" + } + url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path) + + return &sentry.Request{ + URL: url, + Method: r.Method, + QueryString: r.URL.RawQuery, + } +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/params.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/params.go new file mode 100644 index 0000000..46e100a --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/params.go @@ -0,0 +1,39 @@ +package endpoint + +import ( + "context" + "net/http" +) + +// ContextParam creates a ParamMapper that provides context.Context to endpoint functions. +// This is automatically included in the default wrapper. +func ContextParam() ParamMapper { + return ParamMapper{ + Type: "context.Context", + Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) { + return ctx, nil + }, + } +} + +// ResponseWriterParam creates a ParamMapper that provides http.ResponseWriter to endpoint functions. +// This is automatically included in the default wrapper. +func ResponseWriterParam() ParamMapper { + return ParamMapper{ + Type: "http.ResponseWriter", + Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) { + return w, nil + }, + } +} + +// RequestParam creates a ParamMapper that provides *http.Request to endpoint functions. +// This is automatically included in the default wrapper. +func RequestParam() ParamMapper { + return ParamMapper{ + Type: "*http.Request", + Builder: func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) { + return r, nil + }, + } +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/types.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/types.go new file mode 100644 index 0000000..7aee162 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/types.go @@ -0,0 +1,123 @@ +package endpoint + +import ( + "context" + "net/http" + + http2 "github.com/txix-open/isp-kit/http" +) + +// Wrappable is an interface for types that can be wrapped into an http.HandlerFunc. +// Implementations should handle request extraction and response mapping. +type Wrappable interface { + Wrap(wrapper Wrapper) http2.HandlerFunc +} + +// basic is a generic endpoint function type that accepts a request and returns a response. +type basic[Req any, Res any] func(ctx context.Context, req Req) (Res, error) + +// New creates a new generic endpoint with request and response types. +// The returned endpoint automatically handles JSON body extraction and response mapping. +func New[Req any, Res any](fn func(ctx context.Context, req Req) (Res, error)) basic[Req, Res] { + return fn +} + +// Wrap implements Wrappable for basic endpoints. +// It extracts the request body, calls the endpoint function, and maps the response. +func (fn basic[Req, Res]) Wrap(wrapper Wrapper) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + req, err := extractBody[Req](ctx, wrapper, r) + if err != nil { + return err + } + + resp, err := fn(ctx, req) + if err != nil { + return err + } + + return wrapper.BodyMapper.Map(ctx, resp, w) + } +} + +// withoutResponseBody is an endpoint type that processes a request but returns no response body. +type withoutResponseBody[Req any] func(ctx context.Context, req Req) error + +// NewWithoutResponse creates an endpoint that handles a request without returning a response body. +// Useful for operations like deletions or fire-and-forget actions. +func NewWithoutResponse[Req any](fn func(ctx context.Context, req Req) error) withoutResponseBody[Req] { + return fn +} + +// Wrap implements Wrappable for endpoints without response body. +func (fn withoutResponseBody[Req]) Wrap(wrapper Wrapper) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + req, err := extractBody[Req](ctx, wrapper, r) + if err != nil { + return err + } + return fn(ctx, req) + } +} + +// withRequest is an endpoint type that has direct access to the http.Request. +type withRequest func(ctx context.Context, r *http.Request) error + +// NewWithRequest creates an endpoint that receives the raw http.Request. +// Use this when you need direct access to headers, query parameters, or other request details. +func NewWithRequest(fn func(ctx context.Context, r *http.Request) error) withRequest { + return fn +} + +// Wrap implements Wrappable for withRequest endpoints. +func (fn withRequest) Wrap(wrapper Wrapper) http2.HandlerFunc { + return func(ctx context.Context, _ http.ResponseWriter, r *http.Request) error { + return fn(ctx, r) + } +} + +// withRequestAndResponse is an endpoint type that has direct access to http.Request and returns a typed response. +type withRequestAndResponse[Res any] func(ctx context.Context, r *http.Request) (Res, error) + +// NewWithRequestAndResponse creates an endpoint with direct access to http.Request and automatic response mapping. +// Useful when you need direct access to request details while still returning a typed response. +func NewWithRequestAndResponse[Res any](fn func(ctx context.Context, r *http.Request) (Res, error)) withRequestAndResponse[Res] { + return fn +} + +// Wrap implements Wrappable for withRequestAndResponse endpoints. +func (fn withRequestAndResponse[Res]) Wrap(wrapper Wrapper) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + resp, err := fn(ctx, r) + if err != nil { + return err + } + + return wrapper.BodyMapper.Map(ctx, resp, w) + } +} + +// defaultHttp is an endpoint type that uses the standard http.HandlerFunc signature. +type defaultHttp http2.HandlerFunc + +// NewDefaultHttp creates an endpoint with direct access to ResponseWriter and Request. +// This is the most flexible option but bypasses automatic body extraction and mapping. +func NewDefaultHttp(fn func(ctx context.Context, w http.ResponseWriter, r *http.Request) error) defaultHttp { + return fn +} + +// Wrap implements Wrappable for defaultHttp endpoints. +func (fn defaultHttp) Wrap(wrapper Wrapper) http2.HandlerFunc { + return http2.HandlerFunc(fn) +} + +// extractBody extracts and unmarshals the request body into the target type. +// It uses the wrapper's BodyExtractor to handle the request body. +func extractBody[T any](ctx context.Context, w Wrapper, r *http.Request) (T, error) { + var req T + err := w.BodyExtractor.ExtractV2(ctx, r.Body, &req) + if err != nil { + return *new(T), err + } + return req, nil +} diff --git a/vendor/github.com/txix-open/isp-kit/http/endpoint/wrapper.go b/vendor/github.com/txix-open/isp-kit/http/endpoint/wrapper.go new file mode 100644 index 0000000..7829378 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/endpoint/wrapper.go @@ -0,0 +1,133 @@ +// Package endpoint provides a high-level abstraction for building HTTP endpoints +// with automatic request/response handling, validation, and middleware support. +// It uses Go generics to create type-safe endpoint implementations. +package endpoint + +import ( + "context" + "io" + "net/http" + "reflect" + "slices" + + http2 "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/log" +) + +// HttpError is an interface for errors that can write themselves to an HTTP response. +// Implementations should handle their own HTTP status codes and response formatting. +type HttpError interface { + WriteError(w http.ResponseWriter) error +} + +// RequestBodyExtractor is responsible for extracting and unmarshaling request bodies. +// It supports both reflection-based and direct pointer-based extraction. +type RequestBodyExtractor interface { + // Extract extracts the request body into a reflect.Value of the specified type. + Extract(ctx context.Context, reader io.Reader, reqBodyType reflect.Type) (reflect.Value, error) + // ExtractV2 extracts the request body into a pointer directly. + ExtractV2(ctx context.Context, reader io.Reader, ptr any) error +} + +// ResponseBodyMapper is responsible for marshaling and writing response bodies. +type ResponseBodyMapper interface { + // Map marshals the result and writes it to the http.ResponseWriter. + Map(ctx context.Context, result any, w http.ResponseWriter) error +} + +// ParamBuilder is a function that builds a parameter value from the request context. +type ParamBuilder func(ctx context.Context, w http.ResponseWriter, r *http.Request) (any, error) + +// ParamMapper maps a parameter type to its builder function. +type ParamMapper struct { + // Type is the string representation of the parameter type. + Type string + // Builder creates the parameter value from the request context. + Builder ParamBuilder +} + +// Wrapper is the core component for building HTTP endpoints. +// It combines parameter mapping, body extraction, response mapping, and middleware support. +type Wrapper struct { + ParamMappers map[string]ParamMapper + BodyExtractor RequestBodyExtractor + BodyMapper ResponseBodyMapper + Middlewares []http2.Middleware + Logger log.Logger +} + +// NewWrapper creates a new Wrapper with the specified configuration. +// Parameter mappers are stored in a map for efficient type lookup. +func NewWrapper( + paramMappers []ParamMapper, + bodyExtractor RequestBodyExtractor, + bodyMapper ResponseBodyMapper, + logger log.Logger, +) Wrapper { + mappers := make(map[string]ParamMapper) + for _, mapper := range paramMappers { + mappers[mapper.Type] = mapper + } + return Wrapper{ + ParamMappers: mappers, + BodyExtractor: bodyExtractor, + BodyMapper: bodyMapper, + Logger: logger, + } +} + +// Endpoint wraps a function as an http.HandlerFunc. +// +// Use EndpointV2 with New, NewWithoutResponse, NewWithRequest, or NewDefaultHttp instead. +// EndpointV2 avoids reflection overhead by using the Wrappable interface. +func (m Wrapper) Endpoint(f any) http.HandlerFunc { + w, isWrappable := f.(Wrappable) + if isWrappable { + return m.EndpointV2(w) + } + + caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers) + if err != nil { + panic(err) + } + + handler := caller.Handle + for i := range slices.Backward(m.Middlewares) { + handler = m.Middlewares[i](handler) + } + + return func(w http.ResponseWriter, r *http.Request) { + err := handler(r.Context(), w, r) + if err != nil { + m.Logger.Error(r.Context(), err) + } + } +} + +// EndpointV2 wraps a Wrappable implementation as an http.HandlerFunc. +// It applies middleware in reverse order (last middleware executes first). +// This version avoids reflection overhead and is preferred for production use. +func (m Wrapper) EndpointV2(w Wrappable) http.HandlerFunc { + handler := w.Wrap(m) + for i := range slices.Backward(m.Middlewares) { + handler = m.Middlewares[i](handler) + } + return func(w http.ResponseWriter, r *http.Request) { + err := handler(r.Context(), w, r) + if err != nil { + m.Logger.Error(r.Context(), err) + } + } +} + +// WithMiddlewares returns a new Wrapper with additional middleware appended. +// The original Wrapper remains unchanged (immutable). +func (m Wrapper) WithMiddlewares(middlewares ...http2.Middleware) Wrapper { + return Wrapper{ + ParamMappers: m.ParamMappers, + BodyExtractor: m.BodyExtractor, + BodyMapper: m.BodyMapper, + Middlewares: append(m.Middlewares, middlewares...), + Logger: m.Logger, + } +} diff --git a/vendor/github.com/txix-open/isp-kit/http/router/README.md b/vendor/github.com/txix-open/isp-kit/http/router/README.md new file mode 100644 index 0000000..978a8bd --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/router/README.md @@ -0,0 +1,70 @@ +# Package `router` + +Пакет `router` предоставляет обертку над [`httprouter`](https://github.com/julienschmidt/httprouter) с поддержкой метрик +и удобной регистрацией обработчиков. +Интегрируется с системой мониторинга для отслеживания эндпоинтов. + +## Types + +### Router + +Структура для управления HTTP-маршрутами. Обеспечивает регистрацию обработчиков, сбор метрик и работу с параметрами URL. + +**Methods:** + +#### `New() *Router` + +Конструктор роутера. + +#### `(r *Router) GET(path string, handler http.Handler) *Router` + +Зарегистрировать обработчик для GET-запросов. Аналогичные методы: `POST()`, `PUT()`, `DELETE()`. + +#### `(r *Router) Handler(method string, path string, handler http.Handler) *Router` + +Зарегистрировать обработчик для произвольного HTTP-метода. + +#### `(r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)` + +Обработать HTTP-запрос. + +#### `(r *Router) InternalRouter() *httprouter.Router` + +Возвращает внутренний экземпляр `httprouter.Router` для кастомных настроек. + +## Functions + +#### `ParamsFromRequest(http *http.Request) Params` + +Извлечь URL-параметры из запроса. + +#### `ParamsFromContext(ctx context.Context) Params` + +Извлечь URL-параметры из контекста. + +## Usage + +### Default usage flow + +```go +package main + +import ( + "log" + "net/http" + + "github.com/txix-open/isp-kit/http/router" +) + +func main() { + r := router.New() + r.GET("/users/:id", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + params := router.ParamsFromRequest(r) + userId := params.ByName("id") /* get id param */ + log.Println(userId) + w.WriteHeader(http.StatusOK) + })) + _ = http.ListenAndServe(":8080", r) +} + +``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/http/router/router.go b/vendor/github.com/txix-open/isp-kit/http/router/router.go new file mode 100644 index 0000000..29350d7 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/router/router.go @@ -0,0 +1,93 @@ +// Package router provides HTTP request routing with metrics integration. +// It wraps the julienschmidt/httprouter library and adds automatic endpoint metrics collection. +package router + +import ( + "context" + "fmt" + "net/http" + + "github.com/julienschmidt/httprouter" + "github.com/txix-open/isp-kit/metrics/http_metrics" +) + +// Params is an alias for httprouter.Params, representing URL path parameters. +type Params = httprouter.Params + +// Router wraps httprouter.Router with automatic metrics collection for each endpoint. +// It supports method-based routing (GET, POST, PUT, DELETE) and fluent API for route configuration. +type Router struct { + router *httprouter.Router +} + +// New creates a new Router instance with a fresh httprouter backend. +func New() *Router { + return &Router{ + router: httprouter.New(), + } +} + +// GET registers an HTTP GET handler for the specified path. +// Returns the Router for fluent chaining. +func (r *Router) GET(path string, handler http.Handler) *Router { + return r.Handler(http.MethodGet, path, handler) +} + +// POST registers an HTTP POST handler for the specified path. +// Returns the Router for fluent chaining. +func (r *Router) POST(path string, handler http.Handler) *Router { + return r.Handler(http.MethodPost, path, handler) +} + +// PUT registers an HTTP PUT handler for the specified path. +// Returns the Router for fluent chaining. +func (r *Router) PUT(path string, handler http.Handler) *Router { + return r.Handler(http.MethodPut, path, handler) +} + +// DELETE registers an HTTP DELETE handler for the specified path. +// Returns the Router for fluent chaining. +func (r *Router) DELETE(path string, handler http.Handler) *Router { + return r.Handler(http.MethodDelete, path, handler) +} + +// Handler registers a handler for the specified HTTP method and path. +// It automatically wraps the handler with metrics collection. +// Returns the Router for fluent chaining. +func (r *Router) Handler(method string, path string, handler http.Handler) *Router { + r.router.Handler(method, path, r.withMetricEndpoint(method, path, handler)) + return r +} + +// ServeHTTP implements the http.Handler interface and delegates to the underlying httprouter. +func (r *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request) { + r.router.ServeHTTP(writer, request) +} + +// InternalRouter returns the underlying httprouter instance for advanced configuration. +func (r *Router) InternalRouter() *httprouter.Router { + return r.router +} + +// withMetricEndpoint wraps a handler to add endpoint metrics to the request context. +// The endpoint is formatted as "METHOD /path" for metrics identification. +func (r *Router) withMetricEndpoint(method string, path string, handler http.Handler) http.Handler { + endpoint := fmt.Sprintf("%s %s", method, path) + return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + ctx := http_metrics.ServerEndpointToContext(request.Context(), endpoint) + request = request.WithContext(ctx) + handler.ServeHTTP(writer, request) + }) +} + +// ParamsFromRequest extracts URL path parameters from an http.Request. +// It retrieves the parameters from the request context. +func ParamsFromRequest(http *http.Request) Params { + return ParamsFromContext(http.Context()) +} + +// ParamsFromContext extracts URL path parameters from a context. +// It returns empty params if none are present in the context. +func ParamsFromContext(ctx context.Context) Params { + return httprouter.ParamsFromContext(ctx) +} diff --git a/vendor/github.com/txix-open/isp-kit/http/server.go b/vendor/github.com/txix-open/isp-kit/http/server.go new file mode 100644 index 0000000..8f873d5 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/http/server.go @@ -0,0 +1,115 @@ +// nolint:mnd +package http + +import ( + "context" + "net" + "net/http" + "sync/atomic" + "time" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/http/apierrors" + "github.com/txix-open/isp-kit/log" +) + +// service is an internal wrapper that delegates to the actual HTTP handler. +// It uses atomic.Value for thread-safe handler replacement. +type service struct { + delegate atomic.Value +} + +// ServeHTTP implements the http.Handler interface and delegates to the stored handler. +// It returns an internal service error if the handler is not initialized. +func (s *service) ServeHTTP(w http.ResponseWriter, r *http.Request) { + value, ok := s.delegate.Load().(http.Handler) + if !ok { + _ = apierrors.NewInternalServiceError(errors.New("handler is not initialized")). + WriteError(w) + return + } + + value.ServeHTTP(w, r) +} + +// ServerOption is a function that configures a Server instance. +type ServerOption func(*Server) + +// WithServer allows providing a custom *http.Server for advanced configuration. +func WithServer(server *http.Server) ServerOption { + return func(srv *Server) { + srv.server = server + } +} + +// Server wraps an http.Server with additional functionality for handler management. +// It provides graceful shutdown and handler upgrade capabilities. +type Server struct { + server *http.Server + service *service +} + +// NewServer creates a new HTTP server with the specified logger and options. +// Default timeouts are set: 3 seconds for ReadHeaderTimeout and 120 seconds for IdleTimeout. +// Server is safe for concurrent use. +func NewServer(logger log.Logger, opts ...ServerOption) *Server { + s := &Server{ + server: &http.Server{ + ReadHeaderTimeout: 3 * time.Second, + IdleTimeout: 120 * time.Second, + ErrorLog: log.StdLoggerWithLevel( + logger, + log.WarnLevel, + log.String("worker", "http server"), + ), + }, + service: &service{ + delegate: atomic.Value{}, + }, + } + + for _, opts := range opts { + opts(s) + } + + s.server.Handler = s.service + + return s +} + +// Shutdown gracefully shuts down the server without interrupting any active connections. +// It delegates to the underlying http.Server.Shutdown method. +func (s *Server) Shutdown(ctx context.Context) error { + return s.server.Shutdown(ctx) +} + +// Upgrade replaces the current HTTP handler with a new one. +// This method is safe for concurrent use. +func (s *Server) Upgrade(handler http.Handler) { + s.service.delegate.Store(handler) +} + +// ListenAndServe starts the server on the specified address. +// It creates a TCP listener and delegates to Serve. +func (s *Server) ListenAndServe(address string) error { + var lc net.ListenConfig + listener, err := lc.Listen(context.Background(), "tcp", address) + if err != nil { + return errors.WithMessagef(err, "listen: %s", address) + } + + return s.Serve(listener) +} + +// Serve accepts incoming connections on the specified listener and handles requests. +// It returns nil when the server is gracefully shut down. +func (s *Server) Serve(listener net.Listener) error { + err := s.server.Serve(listener) + if errors.Is(err, http.ErrServerClosed) { + return nil + } + if err != nil { + return errors.WithMessage(err, "serve http") + } + return nil +} diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/README.md b/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/README.md new file mode 100644 index 0000000..4ba282f --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/README.md @@ -0,0 +1,61 @@ +# Package `server_tracing` + +Пакет `server_tracing` предоставляет middleware для серверной части HTTP-приложения, обеспечивая автоматическое создание span'ов OpenTelemetry для обработки входящих HTTP-запросов. + +## Types + +### Config + +Структура `Config` определяет настройки трассировки для входящих HTTP-запросов. + +**Fields:** + +#### `Provider tracing.TracerProvider` + +Провайдер трассировки (по умолчанию `tracing.DefaultProvider`). + +#### `Propagator tracing.Propagator` + +Пропагатор контекста (по умолчанию `tracing.DefaultPropagator`). + +**Methods:** + +#### `NewConfig() Config` + +Создаёт конфигурацию с провайдером и пропагатором по умолчанию: + +#### `func (c Config) Middleware() http2.Middleware` + +Возвращает middleware, который добавляет в контекст обработки запроса OpenTelemetry span с необходимыми атрибутами. При этом: + +- Используется `Propagator` для извлечения контекста трассировки из входящего запроса. +- Определяется имя span'а на основе маршрута или метода + пути. +- В span записываются стандартные HTTP-атрибуты, request ID, а также (если используется `buffer.Buffer`) количество прочитанных и записанных байт. +- Ошибки логируются и, если уровень логирования `Error`, также записываются в span через `RecordError`. + +## Usage + +### Default usage flow + +```go +package main + +import ( + "github.com/txix-open/isp-kit/observability/tracing/http/server_tracing" + "github.com/txix-open/isp-kit/http" +) + +func main(){ + ... + tracingCfg := server_tracing.NewConfig() + mux := http.NewServeMux() + handler := http.WrapHandler(tracingCfg.Middleware())(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + // обработка запроса + return nil + }) + mux.Handle("/example", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = handler(r.Context(), w, r) + })) + ... +} +``` diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/middleware.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/middleware.go new file mode 100644 index 0000000..c8d43f6 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/middleware.go @@ -0,0 +1,117 @@ +// Package server_tracing provides HTTP server middleware for distributed tracing. +package server_tracing + +import ( + "context" + "fmt" + "net/http" + + http2 "github.com/txix-open/isp-kit/http" + "github.com/txix-open/isp-kit/http/endpoint/buffer" + "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/log/logutil" + "github.com/txix-open/isp-kit/metrics/http_metrics" + "github.com/txix-open/isp-kit/observability/tracing" + "github.com/txix-open/isp-kit/observability/tracing/http/semconvutil" + "github.com/txix-open/isp-kit/requestid" + "go.opentelemetry.io/otel/attribute" + "go.opentelemetry.io/otel/propagation" + semconv "go.opentelemetry.io/otel/semconv/v1.21.0" + "go.opentelemetry.io/otel/trace" +) + +// ReadBytesKey is the attribute key for the total number of bytes read from the request body. +var ReadBytesKey = attribute.Key("http.read_bytes") + +// WroteBytesKey is the attribute key for the total number of bytes written to the response. +var WroteBytesKey = attribute.Key("http.wrote_bytes") + +// tracerName identifies the tracer for HTTP server tracing. +const tracerName = "isp-kit/observability/tracing/http" + +// Config holds the configuration for the HTTP server tracing middleware. +type Config struct { + // Provider is the tracer provider used to create tracers. + Provider tracing.TracerProvider + // Propagator is the text map propagator for context propagation. + Propagator tracing.Propagator +} + +// NewConfig creates a new Config with default values. +func NewConfig() Config { + return Config{ + Provider: tracing.DefaultProvider, + Propagator: tracing.DefaultPropagator, + } +} + +// Middleware returns an HTTP server middleware that creates spans for incoming requests. +// It extracts trace context from request headers, creates a server span, and sets +// appropriate attributes including status code and request details. If the provider +// is a no-op, it returns a pass-through middleware. +func (c Config) Middleware() http2.Middleware { + if tracing.IsNoop(c.Provider) { + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + return next(ctx, w, r) + } + } + } + + tracer := c.Provider.Tracer(tracerName) + return func(next http2.HandlerFunc) http2.HandlerFunc { + return func(ctx context.Context, w http.ResponseWriter, r *http.Request) error { + ctx = c.Propagator.Extract(ctx, propagation.HeaderCarrier(r.Header)) + + attributes := semconvutil.HTTPServerRequest("", r) + attributes = append(attributes, tracing.RequestId.String(requestid.FromContext(ctx))) + opts := []trace.SpanStartOption{ + trace.WithSpanKind(trace.SpanKindServer), + } + + var spanName string + serverEndpoint := http_metrics.ServerEndpoint(ctx) + if serverEndpoint != "" { + attributes = append(attributes, semconv.HTTPRouteKey.String(serverEndpoint)) + spanName = serverEndpoint + } else { + spanName = fmt.Sprintf("%s %s", r.Method, r.URL.Path) + } + + ctx, span := tracer.Start(ctx, spanName, opts...) + defer span.End() + + var scSource scSource + buff, isBuffer := w.(*buffer.Buffer) + if isBuffer { + scSource = buff + } else { + scSource = &writerWrapper{ResponseWriter: w} + } + + err := next(ctx, scSource, r) + + if isBuffer { + attributes = append( + attributes, + ReadBytesKey.Int(len(buff.RequestBody())), + WroteBytesKey.Int(len(buff.ResponseBody())), + ) + } + attributes = append( + attributes, + semconv.HTTPStatusCode(scSource.StatusCode()), + ) + if err != nil { + logLevel := logutil.LogLevelForError(err) + if logLevel == log.ErrorLevel { + span.RecordError(err) + } + } + span.SetStatus(semconvutil.HTTPServerStatus(scSource.StatusCode())) + span.SetAttributes(attributes...) + + return err + } + } +} diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/response_writer.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/response_writer.go new file mode 100644 index 0000000..48d275d --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/observability/tracing/http/server_tracing/response_writer.go @@ -0,0 +1,48 @@ +package server_tracing + +import ( + "bufio" + "net" + "net/http" + + "github.com/txix-open/isp-kit/errors" +) + +// scSource is an interface for HTTP response writers that provide status code access. +type scSource interface { + http.ResponseWriter + // StatusCode returns the HTTP status code. + StatusCode() int +} + +// writerWrapper wraps an http.ResponseWriter to capture the status code. +type writerWrapper struct { + http.ResponseWriter + + // statusCode holds the captured HTTP status code. + statusCode int +} + +// Hijack implements the http.Hijacker interface by delegating to the upstream response writer. +// It returns an error if the upstream does not support hijacking. +func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { + upstream, ok := w.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack") + } + return upstream.Hijack() +} + +// StatusCode returns the captured HTTP status code, or http.StatusOK if not yet set. +func (w *writerWrapper) StatusCode() int { + if w.statusCode == 0 { + return http.StatusOK + } + return w.statusCode +} + +// WriteHeader captures the status code and delegates to the upstream response writer. +func (w *writerWrapper) WriteHeader(statusCode int) { + w.statusCode = statusCode + w.ResponseWriter.WriteHeader(statusCode) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index f38f8bb..00ede41 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -114,6 +114,9 @@ github.com/jmoiron/sqlx/reflectx # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go +# github.com/julienschmidt/httprouter v1.3.0 +## explicit; go 1.7 +github.com/julienschmidt/httprouter # github.com/klauspost/compress v1.20.4 ## explicit; go 1.25 github.com/klauspost/compress @@ -241,8 +244,14 @@ github.com/txix-open/isp-kit/grpc/client/request github.com/txix-open/isp-kit/grpc/endpoint github.com/txix-open/isp-kit/grpc/isp github.com/txix-open/isp-kit/healthcheck +github.com/txix-open/isp-kit/http +github.com/txix-open/isp-kit/http/apierrors +github.com/txix-open/isp-kit/http/endpoint +github.com/txix-open/isp-kit/http/endpoint/buffer +github.com/txix-open/isp-kit/http/endpoint/httplog github.com/txix-open/isp-kit/http/httpcli github.com/txix-open/isp-kit/http/httpclix +github.com/txix-open/isp-kit/http/router github.com/txix-open/isp-kit/infra github.com/txix-open/isp-kit/infra/pprof github.com/txix-open/isp-kit/json @@ -264,6 +273,7 @@ github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing github.com/txix-open/isp-kit/observability/tracing/http/client_tracing github.com/txix-open/isp-kit/observability/tracing/http/semconvutil +github.com/txix-open/isp-kit/observability/tracing/http/server_tracing github.com/txix-open/isp-kit/observability/tracing/sql_tracing github.com/txix-open/isp-kit/panic_recovery github.com/txix-open/isp-kit/rc From fa8bc6c1b7168dbe929d6348a96deb26678ec70f Mon Sep 17 00:00:00 2001 From: chashintv Date: Thu, 19 Nov 2026 15:41:50 +0300 Subject: [PATCH 02/13] MSP-8974 fix tests --- assembly/assembly.go | 2 +- domain/audit.go | 2 +- domain/download.go | 6 +- domain/params.go | 2 +- domain/session.go | 2 +- domain/user.go | 2 +- main.go | 2 +- routes/routes.go | 4 +- service/download.go | 2 +- tests/audit_test.go | 53 ++-- tests/auth_test.go | 65 ++--- tests/customization_test.go | 20 +- tests/inactive_test.go | 8 +- tests/secure_test.go | 41 ++- tests/session_test.go | 55 ++-- tests/ui_settings_test.go | 18 +- tests/user_test.go | 157 +++++----- .../txix-open/isp-kit/grpc/client/README.md | 112 -------- .../txix-open/isp-kit/grpc/client/client.go | 210 -------------- .../txix-open/isp-kit/grpc/client/default.go | 39 --- .../isp-kit/grpc/client/middlewares.go | 161 ----------- .../txix-open/isp-kit/grpc/client/options.go | 86 ------ .../isp-kit/grpc/client/request/README.md | 138 --------- .../isp-kit/grpc/client/request/builder.go | 159 ----------- .../isp-kit/grpc/client/request/common.go | 17 -- .../txix-open/isp-kit/grpc/endpoint/README.md | 268 ------------------ .../txix-open/isp-kit/grpc/endpoint/caller.go | 124 -------- .../isp-kit/grpc/endpoint/default.go | 68 ----- .../isp-kit/grpc/endpoint/json_request.go | 69 ----- .../isp-kit/grpc/endpoint/json_response.go | 29 -- .../grpc/endpoint/metrics_middleware.go | 51 ---- .../isp-kit/grpc/endpoint/middlewares.go | 221 --------------- .../txix-open/isp-kit/grpc/endpoint/params.go | 37 --- .../isp-kit/grpc/endpoint/wrapper.go | 107 ------- .../isp-kit/metrics/grpc_metrics/README.md | 112 -------- .../metrics/grpc_metrics/client_storage.go | 33 --- .../isp-kit/metrics/grpc_metrics/doc.go | 15 - .../metrics/grpc_metrics/server_storage.go | 70 ----- .../observability/tracing/grpc/carrier.go | 32 --- .../tracing/grpc/client_tracing/README.md | 62 ---- .../tracing/grpc/client_tracing/middleware.go | 77 ----- .../tracing/grpc/server_tracing/README.md | 95 ------- .../tracing/grpc/server_tracing/middleware.go | 87 ------ .../txix-open/isp-kit/test/grpct/README.md | 74 ----- .../txix-open/isp-kit/test/grpct/test_grpc.go | 69 ----- .../txix-open/isp-kit/test/httpt/README.md | 72 +++++ .../txix-open/isp-kit/test/httpt/server.go | 20 ++ .../txix-open/isp-kit/test/httpt/test_http.go | 72 +++++ .../grpc/resolver/manual/manual.go | 130 --------- vendor/modules.txt | 10 +- 50 files changed, 392 insertions(+), 2975 deletions(-) delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/client.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/default.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/middlewares.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/options.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/request/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/client/request/common.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/default.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/metrics_middleware.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/params.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/endpoint/wrapper.go delete mode 100644 vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/client_storage.go delete mode 100644 vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/doc.go delete mode 100644 vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/server_storage.go delete mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/carrier.go delete mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/middleware.go delete mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/middleware.go delete mode 100644 vendor/github.com/txix-open/isp-kit/test/grpct/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/test/grpct/test_grpc.go create mode 100644 vendor/github.com/txix-open/isp-kit/test/httpt/README.md create mode 100644 vendor/github.com/txix-open/isp-kit/test/httpt/server.go create mode 100644 vendor/github.com/txix-open/isp-kit/test/httpt/test_http.go delete mode 100644 vendor/google.golang.org/grpc/resolver/manual/manual.go diff --git a/assembly/assembly.go b/assembly/assembly.go index 3939c95..66390f6 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -128,7 +128,7 @@ func (a *Assembly) Closers() []app.Closer { return []app.Closer{ a.boot.ClusterCli, app.CloserFunc(func() error { - a.server.Shutdown(context.Background()) + _ = a.server.Shutdown(context.Background()) return nil }), app.CloserFunc(func() error { diff --git a/domain/audit.go b/domain/audit.go index 85fdd77..12fd573 100644 --- a/domain/audit.go +++ b/domain/audit.go @@ -17,7 +17,7 @@ type AuditResponse struct { } type AuditPageRequest struct { - LimitOffestParams + LimitOffsetParams Order *OrderParams // Параметры сортировки Query *AuditQuery // Параметры выборки diff --git a/domain/download.go b/domain/download.go index e137540..4cc34f6 100644 --- a/domain/download.go +++ b/domain/download.go @@ -1,19 +1,19 @@ package domain type AuditDownloadRequest struct { - LimitOffestParams + LimitOffsetParams Order *OrderParams Query *AuditQuery } type SessionDownloadRequest struct { - LimitOffestParams + LimitOffsetParams Order *OrderParams Query *SessionQuery } type UsersDownloadRequest struct { - LimitOffestParams + LimitOffsetParams Order *OrderParams Query *UserQuery diff --git a/domain/params.go b/domain/params.go index 6bc7d2f..e865f5b 100644 --- a/domain/params.go +++ b/domain/params.go @@ -7,7 +7,7 @@ const ( DefaultOrderType = "desc" ) -type LimitOffestParams struct { +type LimitOffsetParams struct { Limit uint64 `validate:"required"` // Максимальное количество записей Offset uint64 // Отступ для выборки } diff --git a/domain/session.go b/domain/session.go index 97248e0..7a6061a 100644 --- a/domain/session.go +++ b/domain/session.go @@ -13,7 +13,7 @@ type Session struct { } type SessionPageRequest struct { - LimitOffestParams + LimitOffsetParams Order *OrderParams // Параметры сортировки Query *SessionQuery // Параметры выборки diff --git a/domain/user.go b/domain/user.go index d3d20d1..d9a402e 100644 --- a/domain/user.go +++ b/domain/user.go @@ -32,7 +32,7 @@ type UserQuery struct { } type UsersPageRequest struct { - LimitOffestParams + LimitOffsetParams Order *OrderParams // Параметры сортировки Query *UserQuery // Параметры выборки diff --git a/main.go b/main.go index e04beb6..8dea5e8 100644 --- a/main.go +++ b/main.go @@ -23,7 +23,7 @@ var version = "1.0.0" //go:generate swag init -pd -ot json -eot json func main() { - boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport) + boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport) app := boot.App logger := app.Logger() diff --git a/routes/routes.go b/routes/routes.go index 1198035..19ed207 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -7,7 +7,7 @@ import ( "github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/common_endpoints" - "github.com/txix-open/isp-kit/http/endpoint" + httpEndpoint "github.com/txix-open/isp-kit/http/endpoint" "github.com/txix-open/isp-kit/http/router" ) @@ -31,7 +31,7 @@ func EndpointDescriptors() []cluster.EndpointDescriptor { ) } -func Handler(wrapper endpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn +func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn muxer := router.New() for _, descriptor := range endpointDescriptors(c) { muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler)) diff --git a/service/download.go b/service/download.go index dc2d464..57b165d 100644 --- a/service/download.go +++ b/service/download.go @@ -265,7 +265,7 @@ func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) erro func (s Download) getUsersList(ctx context.Context) (map[int]entity.User, error) { users, err := s.repo.GetUsers(ctx, domain.UsersDownloadRequest{ - LimitOffestParams: domain.LimitOffestParams{ + LimitOffsetParams: domain.LimitOffsetParams{ Limit: requestLimit, Offset: 0, }, diff --git a/tests/audit_test.go b/tests/audit_test.go index 373ec43..4715805 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -12,11 +12,10 @@ import ( "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" - "github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -31,7 +30,7 @@ type AuditSuite struct { test *test.Test db *dbt.TestDb - grpcCli *client.Client + httpCli *httpcli.Client } func (s *AuditSuite) SetupTest() { @@ -70,25 +69,25 @@ func (s *AuditSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), httpcli.New(), s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) s.insertAuditLogs() - server, apiCli := grpct.TestServer(testInstance, cfg.Handler) - s.grpcCli = apiCli + server, cli := httpt.TestServer(s.test, cfg.Handler) + s.httpCli = cli testInstance.T().Cleanup(func() { - server.Shutdown() + server.Close() }) } func (s *AuditSuite) Test_Events_DefaultEvents() { response := make([]domain.AuditEvent, 0) - err := s.grpcCli. - Invoke("admin/log/events"). + err := s.httpCli. + Post("admin/log/events"). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expectedEventList := map[string]string{ @@ -123,10 +122,10 @@ func (s *AuditSuite) Test_Events_SortEvents() { s.Require().NoError(err) response := make([]domain.AuditEvent, 0) - err = s.grpcCli. - Invoke("admin/log/events"). + err = s.httpCli. + Post("admin/log/events"). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expectedSort := []bool{ @@ -139,13 +138,13 @@ func (s *AuditSuite) Test_Events_SortEvents() { } func (s *AuditSuite) Test_SetEvents_HappyPath() { - err := s.grpcCli. - Invoke("admin/log/set_events"). + err := s.httpCli. + Post("admin/log/set_events"). JsonRequestBody([]domain.SetAuditEvent{ {Event: entity.EventUserChanged, Enabled: true}, {Event: entity.EventRoleChanged, Enabled: false}, }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expectedEventList := map[string]bool{ @@ -169,12 +168,12 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() { } func (s *AuditSuite) Test_SetEvents_InvalidEvent() { - err := s.grpcCli.Invoke("admin/log/set_events"). + err := s.httpCli.Post("admin/log/set_events"). JsonRequestBody([]domain.SetAuditEvent{ {Event: entity.EventUserChanged, Enabled: true}, {Event: "новый#2", Enabled: false}, }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) status, isStatus := status.FromError(err) s.Require().True(isStatus) @@ -183,8 +182,10 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() { func (s *AuditSuite) Test_All_Logs() { request := domain.AuditPageRequest{ - Limit: 3, - Offset: 5, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 3, + Offset: 5, + }, Order: &domain.OrderParams{ Field: "user_id", Type: "desc", @@ -192,11 +193,11 @@ func (s *AuditSuite) Test_All_Logs() { } var response *domain.AuditResponse - err := s.grpcCli. - Invoke("admin/log/all"). + err := s.httpCli. + Post("admin/log/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 3) @@ -210,11 +211,11 @@ func (s *AuditSuite) Test_All_Logs() { request.Limit = 10 request.Offset = 0 - err = s.grpcCli. - Invoke("admin/log/all"). + err = s.httpCli. + Post("admin/log/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 6) diff --git a/tests/auth_test.go b/tests/auth_test.go index 49f5a25..2628fcf 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -18,16 +18,15 @@ import ( "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/test/fake" + "github.com/txix-open/isp-kit/test/httpt" "golang.org/x/sync/errgroup" "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" - "github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -42,7 +41,7 @@ type AuthTestSuite struct { test *test.Test db *dbt.TestDb - grpcCli *client.Client + httpCli *httpcli.Client oauthCli *httpcli.Client oauthClientName string } @@ -77,15 +76,15 @@ func (s *AuthTestSuite) SetupTest() { }, } - cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, httpcli.New(), s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) - server, apiCli := grpct.TestServer(testInstance, cfg.Handler) - s.grpcCli = apiCli + server, cli := httpt.TestServer(s.test, cfg.Handler) + s.httpCli = cli testInstance.T().Cleanup(func() { - server.Shutdown() + server.Close() mocksrv.Close() }) } @@ -99,13 +98,13 @@ func (s *AuthTestSuite) TestLoginHappyPath() { }) response := domain.LoginResponse{} - err := s.grpcCli.Invoke("admin/auth/login"). + err := s.httpCli.Post("admin/auth/login"). JsonRequestBody(domain.LoginRequest{ Email: "a@a.ru", Password: "password", }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) tokenInfo := SelectTokenEntityByToken(s.db, response.Token) @@ -115,12 +114,12 @@ func (s *AuthTestSuite) TestLoginHappyPath() { } func (s *AuthTestSuite) TestLoginNotFound() { - err := s.grpcCli.Invoke("admin/auth/login"). + err := s.httpCli.Post("admin/auth/login"). JsonRequestBody(domain.LoginRequest{ Email: "a1@a.ru", Password: "password", }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -138,12 +137,12 @@ func (s *AuthTestSuite) TestBlockedUser() { Blocked: true, }) - err := s.grpcCli.Invoke("admin/auth/login"). + err := s.httpCli.Post("admin/auth/login"). JsonRequestBody(domain.LoginRequest{ Email: "a@a.ru", Password: "password", }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -160,12 +159,12 @@ func (s *AuthTestSuite) TestLoginWrongPassword() { Password: "password", }) - err := s.grpcCli.Invoke("admin/auth/login"). + err := s.httpCli.Post("admin/auth/login"). JsonRequestBody(domain.LoginRequest{ Email: "a@a.ru", Password: "WrongPassword", }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -177,13 +176,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() { func (s *AuthTestSuite) TestOauthLoginHappyPath() { response := domain.LoginResponse{} - err := s.grpcCli.Invoke("admin/auth/login_with_oauth"). + err := s.httpCli.Post("admin/auth/login_with_oauth"). JsonRequestBody(domain.LoginOauthRequest{ AuthCode: "code", ClientName: s.oauthClientName, }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) user := entity.User{} s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1") @@ -199,13 +198,13 @@ func (s *AuthTestSuite) TestOauthLoginHappyPath() { func (s *AuthTestSuite) TestOauthLogin_UnknownClient() { response := domain.LoginResponse{} - err := s.grpcCli.Invoke("admin/auth/login_with_oauth"). + err := s.httpCli.Post("admin/auth/login_with_oauth"). JsonRequestBody(domain.LoginOauthRequest{ AuthCode: "code", ClientName: s.oauthClientName + fake.It[string](), }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -221,9 +220,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() { CreatedAt: time.Time{}, ExpiredAt: time.Time{}, }) - err := s.grpcCli.Invoke("admin/auth/logout"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). - Do(s.T().Context()) + err := s.httpCli.Post("admin/auth/logout"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213") @@ -233,16 +232,18 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() { } func (s *AuthTestSuite) Test_Logout_NotFound() { - err := s.grpcCli.Invoke("admin/auth/logout"). - AppendMetadata(domain.AdminAuthIdHeader, "0143218411981"). - Do(s.T().Context()) + err := s.httpCli.Post("admin/auth/logout"). + Header(domain.AdminAuthIdHeader, "0143218411981"). + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) time.Sleep(time.Second) audit := repository.NewAudit(s.db) auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{ - Limit: 10, - Offset: 0, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 10, + Offset: 0, + }, Order: &domain.OrderParams{ Field: "created_at", Type: "desc", @@ -264,9 +265,9 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() { CreatedAt: time.Time{}, ExpiredAt: time.Time{}, }) - err := s.grpcCli.Invoke("admin/auth/logout"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). - Do(s.T().Context()) + err := s.httpCli.Post("admin/auth/logout"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462") @@ -290,13 +291,13 @@ func (s *AuthTestSuite) TestBruteForceLogin() { group.Go(func() error { start := time.Now() response := domain.LoginResponse{} - err := s.grpcCli.Invoke("admin/auth/login"). + err := s.httpCli.Post("admin/auth/login"). JsonRequestBody(domain.LoginRequest{ Email: "a@a.ru", Password: fmt.Sprintf("password %s", strconv.Itoa(index)), }). JsonResponseBody(&response). - Do(ctx) + DoWithoutResponse(ctx) s.Require().Error(err) switch status.Code(err) { // nolint:exhaustive diff --git a/tests/customization_test.go b/tests/customization_test.go index a5a1d7e..56c6729 100644 --- a/tests/customization_test.go +++ b/tests/customization_test.go @@ -9,10 +9,10 @@ import ( "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" - "github.com/txix-open/isp-kit/grpc/client" + "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" ) func TestCustomizationTestSuite(t *testing.T) { @@ -25,7 +25,7 @@ type CustomizationTestSuite struct { test *test.Test db *dbt.TestDb - grpcCli *client.Client + httpCli *httpcli.Client } func (s *CustomizationTestSuite) SetupTest() { @@ -40,25 +40,25 @@ func (s *CustomizationTestSuite) SetupTest() { }, ExpireSec: 0, } - cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) - server, apiCli := grpct.TestServer(testInstance, cfg.Handler) - s.grpcCli = apiCli + server, cli := httpt.TestServer(s.test, cfg.Handler) + s.httpCli = cli testInstance.T().Cleanup(func() { - server.Shutdown() + server.Close() }) } func (s *CustomizationTestSuite) TestGetDesign() { response := conf.UIDesign{} - err := s.grpcCli. - Invoke("admin/user/get_design"). + err := s.httpCli. + Post("admin/user/get_design"). JsonRequestBody(struct{}{}). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expected := conf.UIDesign{ Name: "test", diff --git a/tests/inactive_test.go b/tests/inactive_test.go index e96e04a..50d854c 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -27,7 +27,7 @@ func TestInactiveWorker(t *testing.T) { userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)}) InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()}) - config, err := assembly.NewLocator(test.Logger(), nil, db). + config, err := assembly.NewLocator(test.Logger(), nil, nil, db). Config(t.Context(), conf.Remote{ BlockInactiveWorker: conf.BlockInactiveWorker{ DaysThreshold: 1, @@ -49,8 +49,10 @@ func TestInactiveWorker(t *testing.T) { require.True(user.Blocked) list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{ - Limit: 10, - Offset: 0, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 10, + Offset: 0, + }, Order: &domain.OrderParams{ Field: "created_at", Type: "desc", diff --git a/tests/secure_test.go b/tests/secure_test.go index b5b7360..2255a9a 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -12,11 +12,10 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" - "github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" ) func TestSecureSuite(t *testing.T) { @@ -30,7 +29,7 @@ type SecureSuite struct { test *test.Test require *require.Assertions db *dbt.TestDb - grpcCli *client.Client + httpCli *httpcli.Client } func (s *SecureSuite) SetupTest() { @@ -40,15 +39,15 @@ func (s *SecureSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 3600, } - cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, s.db). + cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) - server, apiCli := grpct.TestServer(s.test, cfg.Handler) + server, apiCli := httpt.TestServer(s.test, cfg.Handler) s.test.T().Cleanup(func() { - server.Shutdown() + server.Close() }) - s.grpcCli = apiCli + s.httpCli = apiCli } func (s *SecureSuite) Test_Authenticate_HappyPath() { @@ -61,12 +60,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() { }) result := domain.SecureAuthResponse{} - err := s.grpcCli.Invoke("admin/secure/authenticate"). + err := s.httpCli.Post("admin/secure/authenticate"). JsonRequestBody(domain.SecureAuthRequest{ Token: "happy_path", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: true, @@ -85,12 +84,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() { }) result := domain.SecureAuthResponse{} - err := s.grpcCli.Invoke("admin/secure/authenticate"). + err := s.httpCli.Post("admin/secure/authenticate"). JsonRequestBody(domain.SecureAuthRequest{ Token: "revoked", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: false, @@ -109,12 +108,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() { }) result := domain.SecureAuthResponse{} - err := s.grpcCli.Invoke("admin/secure/authenticate"). + err := s.httpCli.Post("admin/secure/authenticate"). JsonRequestBody(domain.SecureAuthRequest{ Token: "expired", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: false, @@ -125,12 +124,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() { func (s *SecureSuite) Test_Authenticate_NotFound() { result := domain.SecureAuthResponse{} - err := s.grpcCli.Invoke("admin/secure/authenticate"). + err := s.httpCli.Post("admin/secure/authenticate"). JsonRequestBody(domain.SecureAuthRequest{ Token: "not_found", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: false, @@ -165,35 +164,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() { }) result := domain.SecureAuthzResponse{} - err := s.grpcCli.Invoke("admin/secure/authorize"). + err := s.httpCli.Post("admin/secure/authorize"). JsonRequestBody(domain.SecureAuthzRequest{ AdminId: int(userId), Permission: "perm1", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.True(result.Authorized) result = domain.SecureAuthzResponse{} - err = s.grpcCli.Invoke("admin/secure/authorize"). + err = s.httpCli.Post("admin/secure/authorize"). JsonRequestBody(domain.SecureAuthzRequest{ AdminId: int(userId), Permission: "perm2", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.True(result.Authorized) result = domain.SecureAuthzResponse{} - err = s.grpcCli.Invoke("admin/secure/authorize"). + err = s.httpCli.Post("admin/secure/authorize"). JsonRequestBody(domain.SecureAuthzRequest{ AdminId: int(userId), Permission: "perm3", }). JsonResponseBody(&result). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.require.NoError(err) s.require.False(result.Authorized) } diff --git a/tests/session_test.go b/tests/session_test.go index b26680d..36b3913 100644 --- a/tests/session_test.go +++ b/tests/session_test.go @@ -14,11 +14,10 @@ import ( "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/bgjobx" "github.com/txix-open/isp-kit/dbx" - "github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" ) func TestSessionSuite(t *testing.T) { @@ -32,7 +31,7 @@ type SessionSuite struct { test *test.Test db *dbt.TestDb config assembly.Config - grpcCli *client.Client + httpCli *httpcli.Client } func (s *SessionSuite) SetupTest() { @@ -71,17 +70,17 @@ func (s *SessionSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). + config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), nil, s.db). Config(s.T().Context(), remote, 500*time.Millisecond) s.Require().NoError(err) s.config = config - server, apiCli := grpct.TestServer(testInstance, s.config.Handler) - s.grpcCli = apiCli + server, cli := httpt.TestServer(s.test, config.Handler) + s.httpCli = cli testInstance.T().Cleanup(func() { - server.Shutdown() + server.Close() }) } @@ -117,16 +116,18 @@ func (s *SessionSuite) Test_All_Session() { // Дефолт сортировка, лимит и оффсет request := domain.SessionPageRequest{ - Limit: 5, - Offset: 1, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 5, + Offset: 1, + }, } var response *domain.SessionResponse - err := s.grpcCli. - Invoke("admin/session/all"). + err := s.httpCli. + Post("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 2) @@ -142,11 +143,11 @@ func (s *SessionSuite) Test_All_Session() { To: timeNow.Add(24 * time.Hour), }, } - err = s.grpcCli. - Invoke("admin/session/all"). + err = s.httpCli. + Post("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 2) @@ -161,11 +162,11 @@ func (s *SessionSuite) Test_All_Session() { Type: "asc", } - err = s.grpcCli. - Invoke("admin/session/all"). + err = s.httpCli. + Post("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 3) @@ -181,11 +182,11 @@ func (s *SessionSuite) Test_All_Session() { Status: []string{entity.TokenStatusExpired}, } - err = s.grpcCli. - Invoke("admin/session/all"). + err = s.httpCli. + Post("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 1) @@ -206,8 +207,10 @@ func (s *SessionSuite) Test_All_Session() { } request = domain.SessionPageRequest{ - Limit: 5, - Offset: 0, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 5, + Offset: 0, + }, Order: &domain.OrderParams{ Field: "id", Type: "desc", @@ -216,11 +219,11 @@ func (s *SessionSuite) Test_All_Session() { Id: new(2), }, } - err = s.grpcCli. - Invoke("admin/session/all"). + err = s.httpCli. + Post("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 5) diff --git a/tests/ui_settings_test.go b/tests/ui_settings_test.go index 8fca7fd..8f5a407 100644 --- a/tests/ui_settings_test.go +++ b/tests/ui_settings_test.go @@ -8,10 +8,10 @@ import ( "testing" "github.com/stretchr/testify/suite" - "github.com/txix-open/isp-kit/grpc/client" + "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/fake" - "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -20,7 +20,7 @@ type UiSettingsSuite struct { suite.Suite test *test.Test - apiCli *client.Client + apiCli *httpcli.Client oauthClientSetting conf.OauthClientConfig baseOauthUrl string } @@ -50,22 +50,22 @@ func (s *UiSettingsSuite) SetupTest() { Clients: []conf.OauthClientConfig{s.oauthClientSetting}, }, } - cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil). + cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil, nil). Config(s.T().Context(), remote, 0) s.Require().NoError(err) - _, s.apiCli = grpct.TestServer(s.test, cfg.Handler) + _, s.apiCli = httpt.TestServer(s.test, cfg.Handler) } func (s *UiSettingsSuite) Test_HappyPath() { var resp domain.UiOauthSetting - err := s.apiCli.Invoke("admin/ui_settings/oauth"). + err := s.apiCli.Post("admin/ui_settings/oauth"). JsonRequestBody(domain.ClientNameRequest{ ClientName: s.oauthClientSetting.ClientName, }). JsonResponseBody(&resp). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) loginURL, err := url.Parse(resp.LoginUrl) @@ -93,11 +93,11 @@ func (s *UiSettingsSuite) Test_HappyPath() { } func (s *UiSettingsSuite) Test_UnknownClient() { - err := s.apiCli.Invoke("admin/ui_settings/oauth"). + err := s.apiCli.Post("admin/ui_settings/oauth"). JsonRequestBody(domain.ClientNameRequest{ ClientName: s.oauthClientSetting.ClientName + fake.It[string](), }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) diff --git a/tests/user_test.go b/tests/user_test.go index bc0cc26..2e6e84b 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -19,11 +19,10 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" - "github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) @@ -42,7 +41,7 @@ type UserTestSuite struct { test *test.Test db *dbt.TestDb - grpcCli *client.Client + apiCli *httpcli.Client httpCli *httpcli.Client tokenService tokenService } @@ -56,15 +55,15 @@ func (s *UserTestSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 0, } - cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) - server, apiCli := grpct.TestServer(testInstance, cfg.Handler) - s.grpcCli = apiCli + server, apiCli := httpt.TestServer(testInstance, cfg.Handler) + s.apiCli = apiCli testInstance.T().Cleanup(func() { - server.Shutdown() + server.Close() }) tokenRep := repository.NewToken(s.db) @@ -90,10 +89,10 @@ func (s *UserTestSuite) TestGetProfileHappyPath() { }) response := domain.AdminUserShort{} - err := s.grpcCli.Invoke("admin/user/get_profile"). + err := s.httpCli.Post("admin/user/get_profile"). JsonResponseBody(&response). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). - Do(s.T().Context()) + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expected := domain.AdminUserShort{ FirstName: "name", @@ -117,9 +116,9 @@ func (s *UserTestSuite) TestGetProfileNotFound() { Password: "password", }) - err := s.grpcCli.Invoke("admin/user/get_profile"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))). - Do(s.T().Context()) + err := s.httpCli.Post("admin/user/get_profile"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))). + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -145,11 +144,11 @@ func (s *UserTestSuite) TestGetProfileOauth() { }) response := domain.AdminUserShort{} - err := s.grpcCli. - Invoke("admin/user/get_profile"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + err := s.httpCli. + Post("admin/user/get_profile"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expected := domain.AdminUserShort{ FirstName: "name", @@ -184,10 +183,12 @@ func (s *UserTestSuite) TestGetUsers() { email := "a1@" response := domain.UsersResponse{} - err := s.grpcCli.Invoke("admin/user/get_users"). + err := s.httpCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - Limit: 5, - Offset: 1, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 5, + Offset: 1, + }, Order: &domain.OrderParams{ Field: "email", Type: "asc", @@ -198,7 +199,7 @@ func (s *UserTestSuite) TestGetUsers() { }, }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) roles := []int{int(roleId1), int(roleId2)} @@ -210,10 +211,12 @@ func (s *UserTestSuite) TestGetUsers() { s.Require().EqualValues(roles, response.Items[1].Roles) email = "test@mail.ru" - err = s.grpcCli.Invoke("admin/user/get_users"). + err = s.httpCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - Limit: 10, - Offset: 0, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 10, + Offset: 0, + }, Order: &domain.OrderParams{ Field: "id", Type: "asc", @@ -224,7 +227,7 @@ func (s *UserTestSuite) TestGetUsers() { }, }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Empty(response.Items) } @@ -247,7 +250,7 @@ func (s *UserTestSuite) TestAllGetUsers() { InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)}) response := domain.UsersResponse{} - err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(s.T().Context()) + err := s.httpCli.Post("admin/user/get_all_users").JsonResponseBody(&response).DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 7) @@ -292,10 +295,12 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() { }) response := domain.UsersResponse{} - err = s.grpcCli.Invoke("admin/user/get_users"). + err = s.httpCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - Limit: 5, - Offset: 0, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 5, + Offset: 0, + }, Order: &domain.OrderParams{ Field: "lastSessionCreatedAt", Type: "desc", @@ -308,7 +313,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() { }, }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 2) @@ -326,10 +331,12 @@ func (s *UserTestSuite) TestGetUsersSortByName() { userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"}) response := domain.UsersResponse{} - err := s.grpcCli.Invoke("admin/user/get_users"). + err := s.httpCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - Limit: 10, - Offset: 0, + LimitOffsetParams: domain.LimitOffsetParams{ + Limit: 10, + Offset: 0, + }, Order: &domain.OrderParams{ Field: "userId", Type: "asc", @@ -339,7 +346,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() { }, }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 4) @@ -356,9 +363,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() { s.db.Must().SelectRow(&preCount, "select count(*) from users") response := entity.User{} - err := s.grpcCli. - Invoke("admin/user/create_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). + err := s.httpCli. + Post("admin/user/create_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.CreateUserRequest{ FirstName: "name", LastName: "surname", @@ -366,7 +373,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() { Password: "password", }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) postCount := 0 @@ -384,9 +391,9 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() { s.db.Must().SelectRow(&preCount, "select count(*) from users") response := entity.User{} - err := s.grpcCli. - Invoke("admin/user/create_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). + err := s.httpCli. + Post("admin/user/create_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.CreateUserRequest{ FirstName: "name", LastName: "surname", @@ -394,7 +401,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() { Password: "password", }). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) postCount := 0 @@ -407,16 +414,16 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() { func (s *UserTestSuite) TestCreateUserAlreadyExist() { id := InsertUser(s.db, entity.User{Email: "exists@a.ru"}) - err := s.grpcCli. - Invoke("admin/user/create_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + err := s.httpCli. + Post("admin/user/create_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(domain.CreateUserRequest{ FirstName: "name", LastName: "surname", Email: "exists@a.ru", Password: "password", }). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -432,12 +439,12 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() { Email: "update@a.ru", } response := domain.User{} - err := s.grpcCli. - Invoke("admin/user/update_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + err := s.httpCli. + Post("admin/user/update_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(req). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expected := domain.UpdateUserRequest{ Id: response.Id, @@ -459,12 +466,12 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() { Email: "oauth@a.ru", } response := domain.User{} - err := s.grpcCli. - Invoke("admin/user/update_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + err := s.httpCli. + Post("admin/user/update_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(req). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) expected := domain.UpdateUserRequest{ Id: response.Id, @@ -487,11 +494,11 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() { LastName: "surname", Email: "a_exists@a.ru", } - err := s.grpcCli. - Invoke("admin/user/update_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). + err := s.httpCli. + Post("admin/user/update_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(req). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -510,11 +517,11 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() { LastName: "surname", Email: "a_exists@a.ru", } - err := s.grpcCli. - Invoke("admin/user/update_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). + err := s.httpCli. + Post("admin/user/update_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(req). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -528,12 +535,12 @@ func (s *UserTestSuite) TestDeleteUsers() { InsertUser(s.db, entity.User{Email: "a_del@c.ru"}) response := domain.DeleteResponse{} - err := s.grpcCli. - Invoke("admin/user/delete_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). + err := s.httpCli. + Post("admin/user/delete_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}). JsonResponseBody(&response). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Equal(2, response.Deleted) @@ -559,10 +566,10 @@ func (s *UserTestSuite) TestBlockUser() { UpdatedAt: time.Now(), }) - err := s.grpcCli.Invoke("admin/user/block_user"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + err := s.httpCli.Post("admin/user/block_user"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(domain.IdRequest{UserId: int(id)}). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id) @@ -590,20 +597,20 @@ func (s *UserTestSuite) TestChangePasswordUser() { // check for err when invalid data invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"} - err := s.grpcCli.Invoke("admin/user/change_password"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). + err := s.httpCli.Post("admin/user/change_password"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). JsonRequestBody(invalidReq). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().Error(err) err = apierrors.FromError(err) s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword)) // change password changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"} - err = s.grpcCli.Invoke("admin/user/change_password"). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). + err = s.httpCli.Post("admin/user/change_password"). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). JsonRequestBody(changePswReq). - Do(s.T().Context()) + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/README.md b/vendor/github.com/txix-open/isp-kit/grpc/client/README.md deleted file mode 100644 index e6622f5..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/README.md +++ /dev/null @@ -1,112 +0,0 @@ -# Package `client` - -Пакет `client` предоставляет гибкий gRPC-клиент с поддержкой балансировки нагрузки, middleware для логирования, метрик, -трассировки и динамическим обновлением списка хостов. - -## Types - -### Client - -Основная структура клиента для взаимодействия с gRPC-серверами. Поддерживает балансировку нагрузки, цепочки middleware и -динамическое обновление списка хостов. - -**Methods:** - -#### `New(initialHosts []string, opts ...Option) (*Client, error)` - -Создать новый клиент с указанными начальными хостами и опциями: - -- `WithMiddlewares(middlewares ...request.Middleware) Option` – добавить middleware в цепочку обработки запроса. -- `WithDialOptions(dialOptions ...grpc.DialOption) Option` – опция для передачи параметров подключения gRPC (например, - TLS, таймауты) -- `WithCodec(codec Codec) Option` – переопределяет codec для кодирования/декодирования, по умолчанию `zstd` -- `WithEncodeThreshold(threshold int) Option` – переопределяет значение выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest), по умолчанию 128 КБ (параметр в байтах). -- `WithEncodeRequest(encode bool) Option` – переопределить флаг кодирования запроса. Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `x-content-encoding` со значением типа codec и тело запроса будет закодировано, по умолчанию false. -- `WithAcceptEncodedResponse(accept bool) Option` – переопределить флаг флаг приёма закодированных ответов. Если включен, то в заголовки запроса будет добавлен `x-accept-encoding` со значением типа codec + identity (пример `zstd, identity`), по умолчанию true. - -#### `(cli *Client) Invoke(endpoint string) *request.Builder` - -Инициирует запрос к указанному эндпоинту. Возвращает билдер для выполнения запроса. - -#### `(cli *Client) Upgrade(hosts []string)` - -Атомарно обновить список хостов. - -#### `(cli *Client) Close() error` - -Закрыть соединение с сервером. - -#### `(cli *Client) BackendClient() isp.BackendServiceClient` - -Получить низкоуровневый клиент для прямого взаимодействия с gRPC-сервисом. - -## Functions - -#### `Default(restMiddlewares ...request.Middleware) (*Client, error)` - -Создать клиент с настройками по умолчанию: - -- Максимальный размер сообщения 64 МБ. -- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга - -#### `RequestId() request.Middleware` - -Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то -передаваться будет именно он. - -#### `Log(logger log.Logger, logBody bool) request.Middleware` - -Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`. - -#### `Metrics(storage MetricStorage) request.Middleware` - -Middleware для сбора метрик длительности запросов. - -## Usage - -### Default usage flow - -```go -package main - -import ( - "context" - "log" - - "github.com/txix-open/isp-kit/grpc/client" - log2 "github.com/txix-open/isp-kit/log" -) - -type user struct { - Id string - Name string -} - -func main() { - logger, err := log2.New() - if err != nil { - log.Fatal(err) - } - - cli, err := client.Default(client.Log(logger, true)) - if err != nil { - log.Fatal(err) - } - defer cli.Close() - - cli.Upgrade([]string{"host1:8080", "host2:9000"}) - - users := make([]user, 0) - err = cli.Invoke("/get_users"). - JsonResponseBody(&users). - Do(context.Background()) - if err != nil { - log.Fatal(err) - } - - for _, u := range users { - /* handle each user */ - } -} - -``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/client.go b/vendor/github.com/txix-open/isp-kit/grpc/client/client.go deleted file mode 100644 index 99a156e..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/client.go +++ /dev/null @@ -1,210 +0,0 @@ -// Package client provides a gRPC client implementation with built-in load balancing, -// middleware support, and observability features. -// -// The client supports dynamic host updates for service discovery and integrates with -// the ISP kit framework's logging, metrics, and tracing systems. -package client - -import ( - "context" - "slices" - "strings" - "sync/atomic" - - "github.com/txix-open/isp-kit/codec" - "github.com/txix-open/isp-kit/errors" - grpc2 "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/client/request" - "github.com/txix-open/isp-kit/grpc/isp" - - "google.golang.org/grpc" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/resolver" - "google.golang.org/grpc/resolver/manual" -) - -const ( - // resolverScheme defines the custom resolver scheme for host discovery. - resolverScheme = "isp" - // resolverUrl is the target URL for the manual resolver. - resolverUrl = resolverScheme + ":///" - - defaultEncodeThreshold = codec.DefaultEncodeThreshold -) - -type Codec interface { - Type() string - EncodeBytes(b []byte) ([]byte, error) - DecodeBytes(b []byte) ([]byte, error) -} - -// Client is a gRPC client with support for middleware, load balancing, and dynamic host updates. -// It provides a fluent API for building requests and automatically handles connection management. -// Client is safe for concurrent use by multiple goroutines. -type Client struct { - middlewares []request.Middleware - dialOptions []grpc.DialOption - - roundTripper request.RoundTripper - hostsResolver *manual.Resolver - grpcCli *grpc.ClientConn - backendCli isp.BackendServiceClient - - currentHosts atomic.Value - - codec Codec - encodeThreshold int - acceptEncodedResponse bool - encodeRequest bool -} - -// New creates a new Client with the specified initial hosts and options. -// Returns an error if the gRPC client cannot be initialized. -// The client automatically connects to the provided hosts and applies all configured middleware. -func New(initialHosts []string, opts ...Option) (*Client, error) { - cli := &Client{ - codec: codec.Default, - acceptEncodedResponse: true, - encodeRequest: false, - encodeThreshold: defaultEncodeThreshold, - } - for _, opt := range opts { - opt(cli) - } - - hostsResolver := manual.NewBuilderWithScheme(resolverScheme) - hostsResolver.InitialState(resolver.State{ - Addresses: toAddresses(initialHosts), - }) - dialOptions := cli.dialOptions - dialOptions = append( - dialOptions, - grpc.WithResolvers(hostsResolver), - grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`), - ) - - grpcCli, err := grpc.NewClient(resolverUrl, dialOptions...) - if err != nil { - return nil, errors.WithMessage(err, "new grpc client") - } - grpcCli.Connect() - backendCli := isp.NewBackendServiceClient(grpcCli) - - cli.currentHosts = atomic.Value{} - cli.currentHosts.Store(initialHosts) - cli.hostsResolver = hostsResolver - cli.backendCli = backendCli - cli.grpcCli = grpcCli - - roundTripper := cli.do - for _, v := range slices.Backward(cli.middlewares) { - roundTripper = v(roundTripper) - } - cli.roundTripper = roundTripper - - return cli, nil -} - -// Invoke creates a request builder for the specified endpoint. -// The builder provides a fluent API for configuring and executing the request. -func (cli *Client) Invoke(endpoint string) *request.Builder { - return request.NewBuilder( - cli.roundTripper, - endpoint, - request.EncodeSettings{ - EncodeRequest: cli.encodeRequest, - EncodeThreshold: cli.encodeThreshold, - AcceptEncodedResponse: cli.acceptEncodedResponse, - }, - ) -} - -// Upgrade updates the list of backend hosts for load balancing. -// This enables dynamic service discovery without restarting the client. -// Thread-safe for concurrent use. -func (cli *Client) Upgrade(hosts []string) { - cli.currentHosts.Store(hosts) - cli.hostsResolver.UpdateState(resolver.State{ - Addresses: toAddresses(hosts), - }) -} - -// Close closes the gRPC client connection. -// Should be called when the client is no longer needed. -func (cli *Client) Close() error { - return cli.grpcCli.Close() -} - -// BackendClient returns the underlying gRPC BackendServiceClient. -// Useful for direct gRPC calls bypassing the client abstraction. -func (cli *Client) BackendClient() isp.BackendServiceClient { - return cli.backendCli -} - -// do executes the actual gRPC request through the middleware chain. -// Returns an error if the client is not properly initialized or the request fails. -func (cli *Client) do(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - currentHosts := cli.currentHosts.Load().([]string) // nolint:forcetypeassert - if len(currentHosts) == 0 { - return nil, errors.New("grpc client: client is not initialized properly: empty hosts array") - } - - encodeSettings := builder.EncodeSettings - if encodeSettings.AcceptEncodedResponse { - ctx = metadata.AppendToOutgoingContext(ctx, - grpc2.AcceptEncodingHeader, - strings.Join([]string{cli.codec.Type(), "identity"}, ", "), - ) - } - - requestBody := message.GetBytesBody() - if encodeSettings.EncodeRequest && len(requestBody) > encodeSettings.EncodeThreshold { - ctx = metadata.AppendToOutgoingContext(ctx, - grpc2.ContentEncodingHeader, - cli.codec.Type(), - ) - requestBody, err := cli.codec.EncodeBytes(requestBody) - if err != nil { - return nil, err - } - message.Body = &isp.Message_BytesBody{ - BytesBody: requestBody, - } - } - - var header metadata.MD - resp, err := cli.backendCli.Request( - ctx, - message, - grpc.Header(&header), - ) - if err != nil { - return nil, err - } - - contentEncoding, _ := grpc2.StringFromMd(grpc2.ContentEncodingHeader, header) - if contentEncoding != cli.codec.Type() { - return resp, nil - } - - decoded, err := cli.codec.DecodeBytes(resp.GetBytesBody()) - if err != nil { - return nil, err - } - resp.Body = &isp.Message_BytesBody{ - BytesBody: decoded, - } - - return resp, nil -} - -// toAddresses converts a slice of host strings to gRPC resolver addresses. -func toAddresses(hosts []string) []resolver.Address { - addresses := make([]resolver.Address, len(hosts)) - for i, host := range hosts { - addresses[i] = resolver.Address{ - Addr: host, - } - } - return addresses -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/default.go b/vendor/github.com/txix-open/isp-kit/grpc/client/default.go deleted file mode 100644 index fa8ab07..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/default.go +++ /dev/null @@ -1,39 +0,0 @@ -package client - -import ( - ispgrpc "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/client/request" - "github.com/txix-open/isp-kit/metrics" - "github.com/txix-open/isp-kit/metrics/grpc_metrics" - "github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" -) - -// Default creates a Client with pre-configured middleware for observability. -// Includes request ID propagation, metrics collection, and distributed tracing. -// Uses insecure transport by default (suitable for development and testing). -// Accepts additional middleware to be appended after the default ones. -// Returns an error if the client cannot be initialized. -func Default(restMiddlewares ...request.Middleware) (*Client, error) { - middlewares := append( - []request.Middleware{ - RequestId(), - Metrics(grpc_metrics.NewClientStorage(metrics.DefaultRegistry)), - client_tracing.NewConfig().Middleware(), - }, - restMiddlewares..., - ) - return New( - nil, - WithDialOptions( - grpc.WithTransportCredentials(insecure.NewCredentials()), - grpc.WithDefaultCallOptions( - grpc.WaitForReady(true), - grpc.MaxCallSendMsgSize(ispgrpc.DefaultMaxSizeByte), - grpc.MaxCallRecvMsgSize(ispgrpc.DefaultMaxSizeByte), - ), - ), - WithMiddlewares(middlewares...), - ) -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/middlewares.go b/vendor/github.com/txix-open/isp-kit/grpc/client/middlewares.go deleted file mode 100644 index 8ab4d5a..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/middlewares.go +++ /dev/null @@ -1,161 +0,0 @@ -package client - -import ( - "context" - "time" - - "github.com/txix-open/isp-kit/grpc/client/request" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/log" - "github.com/txix-open/isp-kit/requestid" - "google.golang.org/grpc/metadata" -) - -// logConfig holds logging configuration for client middleware. -type logConfig struct { - logRequestBody bool - logResponseBody bool - combinedLog bool -} - -// RequestId is a middleware that propagates request IDs across service boundaries. -// If no request ID is present in the context, it generates a new one. -// The request ID is added to outgoing metadata for tracing purposes. -func RequestId() request.Middleware { - return func(next request.RoundTripper) request.RoundTripper { - return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - requestId := requestid.FromContext(ctx) - if requestId == "" { - requestId = requestid.Next() - } - - ctx = metadata.AppendToOutgoingContext(ctx, requestid.Header, requestId) - return next(ctx, builder, message) - } - } -} - -// Log creates a middleware that logs gRPC client requests and responses. -// When logBody is true, request and response bodies are included in the logs. -// Logs at Debug level for requests and responses. -func Log(logger log.Logger, logBody bool) request.Middleware { - cfg := &logConfig{ - logRequestBody: logBody, - logResponseBody: logBody, - } - return logMiddleware(logger, cfg) -} - -// LogWithOptions creates a middleware that logs gRPC client requests and responses with custom options. -// Provides fine-grained control over what is logged (request body, response body, combined logs). -func LogWithOptions(logger log.Logger, opts ...LogOption) request.Middleware { - cfg := &logConfig{ - logRequestBody: false, - logResponseBody: false, - combinedLog: false, - } - for _, opt := range opts { - opt(cfg) - } - - if cfg.combinedLog { - return logCombinedMiddleware(logger, cfg) - } - return logMiddleware(logger, cfg) -} - -// logMiddleware implements request/response logging with separate log entries. -func logMiddleware(logger log.Logger, cfg *logConfig) request.Middleware { - return func(next request.RoundTripper) request.RoundTripper { - return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - requestFields := []log.Field{ - log.String("endpoint", builder.Endpoint), - } - if cfg.logRequestBody { - requestFields = append(requestFields, log.ByteString("requestBody", message.GetBytesBody())) - } - logger.Debug(ctx, "grpc client: request", requestFields...) - - var responseFields []log.Field - - now := time.Now() - resp, err := next(ctx, builder, message) - if err != nil { - responseFields = append(responseFields, - log.Any("error", err), - log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()), - ) - logger.Debug(ctx, "grpc client: response with error", responseFields...) - - return resp, err - } - - responseFields = append(responseFields, - log.String("endpoint", builder.Endpoint), - log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()), - ) - if cfg.logResponseBody { - responseFields = append(responseFields, log.ByteString("responseBody", resp.GetBytesBody())) - } - - logger.Debug(ctx, "grpc client: response", responseFields...) - - return resp, err - } - } -} - -// logCombinedMiddleware implements logging with a single combined log entry. -func logCombinedMiddleware(logger log.Logger, cfg *logConfig) request.Middleware { - return func(next request.RoundTripper) request.RoundTripper { - return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - logFields := []log.Field{ - log.String("endpoint", builder.Endpoint), - } - if cfg.logRequestBody { - logFields = append(logFields, log.ByteString("requestBody", message.GetBytesBody())) - } - - now := time.Now() - resp, err := next(ctx, builder, message) - - logFields = append(logFields, - log.String("endpoint", builder.Endpoint), - log.Int64("elapsedTimeMs", time.Since(now).Milliseconds()), - ) - - if err != nil { - logFields = append(logFields, log.Any("error", err)) - logger.Debug(ctx, "grpc client: log with error", logFields...) - return resp, err - } - - if cfg.logResponseBody { - logFields = append(logFields, log.ByteString("responseBody", resp.GetBytesBody())) - } - logger.Debug(ctx, "grpc client: log", logFields...) - - return resp, err - } - } -} - -// MetricStorage defines the interface for metric storage implementations. -// Used by the Metrics middleware to collect timing information. -type MetricStorage interface { - // ObserveDuration records the duration of a request for the given endpoint. - ObserveDuration(endpoint string, duration time.Duration) -} - -// Metrics creates a middleware that collects timing metrics for gRPC client requests. -// The storage implementation receives the endpoint name and request duration. -func Metrics(storage MetricStorage) request.Middleware { - return func(next request.RoundTripper) request.RoundTripper { - return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - start := time.Now() - response, err := next(ctx, builder, message) - storage.ObserveDuration(builder.Endpoint, time.Since(start)) - return response, err - } - } -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/options.go b/vendor/github.com/txix-open/isp-kit/grpc/client/options.go deleted file mode 100644 index dae0228..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/options.go +++ /dev/null @@ -1,86 +0,0 @@ -package client - -import ( - "github.com/txix-open/isp-kit/grpc/client/request" - "google.golang.org/grpc" -) - -// Option configures a Client using the functional options pattern. -type Option func(cli *Client) - -// WithMiddlewares adds one or more request middleware to the client. -// Middleware are executed in the order they are provided. -func WithMiddlewares(middlewares ...request.Middleware) Option { - return func(cli *Client) { - cli.middlewares = append(cli.middlewares, middlewares...) - } -} - -// WithDialOptions sets custom gRPC dial options for the client. -// Note: This replaces any previously set dial options. -func WithDialOptions(dialOptions ...grpc.DialOption) Option { - return func(cli *Client) { - cli.dialOptions = dialOptions - } -} - -// WithAcceptEncodedResponse sets acceptEncodedResponse flag. -func WithAcceptEncodedResponse(accept bool) Option { - return func(c *Client) { - c.acceptEncodedResponse = accept - } -} - -// WithEncodeRequest sets encodeRequest flag. -func WithEncodeRequest(encode bool) Option { - return func(c *Client) { - c.encodeRequest = encode - } -} - -// WithEncodeThreshold sets the request encoding threshold in bytes. -func WithEncodeThreshold(thresholdBytes int) Option { - return func(c *Client) { - c.encodeThreshold = thresholdBytes - } -} - -// WithCodec sets codec. -func WithCodec(codec Codec) Option { - return func(c *Client) { - c.codec = codec - } -} - -// LogOption configures logging behavior for request middleware. -type LogOption func(cfg *logConfig) - -// WithLogBody enables logging of both request and response bodies. -func WithLogBody(logBody bool) LogOption { - return func(cfg *logConfig) { - cfg.logResponseBody = logBody - cfg.logRequestBody = logBody - } -} - -// WithLogResponseBody enables or disables logging of response bodies. -func WithLogResponseBody(logResponseBody bool) LogOption { - return func(cfg *logConfig) { - cfg.logResponseBody = logResponseBody - } -} - -// WithLogRequestBody enables or disables logging of request bodies. -func WithLogRequestBody(logRequestBody bool) LogOption { - return func(cfg *logConfig) { - cfg.logRequestBody = logRequestBody - } -} - -// WithCombinedLog enables a single combined log entry for request and response. -// When disabled, requests and responses are logged separately. -func WithCombinedLog(enable bool) LogOption { - return func(cfg *logConfig) { - cfg.combinedLog = enable - } -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/request/README.md b/vendor/github.com/txix-open/isp-kit/grpc/client/request/README.md deleted file mode 100644 index 3b36ffc..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/request/README.md +++ /dev/null @@ -1,138 +0,0 @@ -# Package `request` - -Пакет `request` предоставляет билдер для построения gRPC-запросов с поддержкой JSON-сериализации, таймаутов, метаданных -и цепочек обработки через middleware. Интегрируется с клиентом из пакета [`client`](../client.go). - -## Types - -### Builder - -Структура для пошагового конструирования gRPC-запроса. Обрабатывает сериализацию/десериализацию JSON, управление -контекстом и метаданными. - -**Methods:** - -#### `NewBuilder(roundTripper RoundTripper, endpoint string) *Builder` - -Создать новый билдер для указанного эндпоинта. - -#### `(req *Builder) ApplicationId(appId int) *Builder` - -Установить идентификатор системы в заголовок `x-application-identity`. - -#### `(req *Builder) JsonRequestBody(reqBody any) *Builder` - -Задать тело запроса в формате JSON. Объект будет сериализован автоматически при помощи функций из пакета [ -`json`](../../json) (маршалинг без тэгов в camelCase). - -#### `(req *Builder) JsonResponseBody(respPtr any) *Builder` - -Задать указатель для десериализации тела ответа из JSON. - -#### `(req *Builder) Timeout(timeout time.Duration) *Builder` - -Установить тайм-аут для запроса. По умолчанию: 15 секунд. - -#### `(req *Builder) AppendMetadata(k string, v ...string) *Builder` - -Добавить кастомные метаданные в запрос. - -#### `(b *RequestBuilder) EncodeRequest(encode bool) *RequestBuilder` - -Установить флаг кодирования запроса. -Если включен и запрос по размеру больше заданного threshold, то в заголовки запроса будет добавлен `content-encoding` со значением типа codec и тело запроса будет закодировано. - -#### `(b *RequestBuilder) EncodeThreshold(threshold int) *RequestBuilder` - -Установить threshold в байтах, выше которого будет применяться кодирование запроса (при включённом флаге encodeRequest). - -#### `(b *RequestBuilder) AcceptEncodedResponse(accept bool) *RequestBuilder` - -Установить флаг приёма закодированных ответов. -Если включен, то в заголовки запроса будет добавлен `accept-encoding` со значением типа codec + identity (пример `zstd, identity`). - -#### `(req *Builder) Do(ctx context.Context) error` - -Выполнить запрос. Автоматически: - -1. Сериализует тело запроса в JSON -2. Добавляет системные заголовки (`x-application-identity`, `proxy_method_name`) -3. Обрабатывает цепочку middleware -4. Десериализует ответ (если задан `responsePtr`) - -## Functions - -#### `Default(restMiddlewares ...request.Middleware) (*Client, error)` - -Создать клиент с настройками по умолчанию: - -- Максимальный размер сообщения 64 МБ. -- Middleware для генерации requestId, сбора метрик через `grpc_metrics.ClientStorage` и трейсинга - -#### `RequestId() request.Middleware` - -Middleware для автоматической генерации requestId для передачи в заголовках. Если в контексте будет указан requestId, то -передаваться будет именно он. - -#### `Log(logger log.Logger, logBody bool) request.Middleware` - -Middleware для логирования запросов и ответов. Логирует тело запроса/ответа, если `logBody = true`. - -#### `Metrics(storage MetricStorage) request.Middleware` - -Middleware для сбора метрик длительности запросов. - -## Usage - -### Default usage flow - -```go -package main - -import ( - "context" - "log" - "time" - - "github.com/txix-open/isp-kit/grpc/client" - log2 "github.com/txix-open/isp-kit/log" -) - -type getUserRequest struct { - Id string -} - -type user struct { - Id string - Name string -} - -func main() { - logger, err := log2.New() - if err != nil { - log.Fatal(err) - } - - cli, err := client.Default(client.Log(logger, true)) - if err != nil { - log.Fatal(err) - } - defer cli.Close() - - cli.Upgrade([]string{"host1:8080", "host2:9000"}) - - u := new(user) - err = cli.Invoke("/get_user"). - ApplicationId(88). - JsonRequestBody(getUserRequest{Id: "some-user-id"}). - JsonResponseBody(u). - Timeout(5 * time.Second). - Do(context.Background()) - if err != nil { - log.Fatal(err) - } - - log.Printf("username: %s\n", u.Name) -} - -``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go b/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go deleted file mode 100644 index 014b097..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/request/builder.go +++ /dev/null @@ -1,159 +0,0 @@ -// Package request provides a fluent builder for constructing and executing gRPC requests. -// It handles JSON marshaling/unmarshaling, metadata management, and timeout configuration. -package request - -import ( - "context" - "strconv" - "time" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/json" - "google.golang.org/grpc/metadata" -) - -const ( - // defaultTimeout is the default request timeout when none is specified. - defaultTimeout = 15 * time.Second -) - -type EncodeSettings struct { - EncodeRequest bool - EncodeThreshold int - AcceptEncodedResponse bool -} - -// Builder provides a fluent API for constructing and executing gRPC requests. -// It handles JSON marshaling, metadata management, and timeout configuration. -// Builder is not safe for concurrent use; create a new instance for each request. -type Builder struct { - Endpoint string - MD metadata.MD - EncodeSettings EncodeSettings - - requestBody any - responsePtr any - applicationId int - timeout time.Duration - roundTripper RoundTripper -} - -// NewBuilder creates a new Builder for the specified endpoint. -// Initializes with default timeout and empty metadata. -func NewBuilder( - roundTripper RoundTripper, - endpoint string, - encodeSettings EncodeSettings, -) *Builder { - return &Builder{ - Endpoint: endpoint, - MD: metadata.New(make(map[string]string)), - roundTripper: roundTripper, - timeout: defaultTimeout, - EncodeSettings: encodeSettings, - } -} - -// ApplicationId sets the application identity header for the request. -// Returns the Builder for method chaining. -func (req *Builder) ApplicationId(appId int) *Builder { - req.applicationId = appId - return req -} - -// JsonRequestBody sets the request body as a JSON-encodable value. -// Returns the Builder for method chaining. -func (req *Builder) JsonRequestBody(reqBody any) *Builder { - req.requestBody = reqBody - return req -} - -// JsonResponseBody sets the pointer to unmarshal the JSON response into. -// Returns the Builder for method chaining. -func (req *Builder) JsonResponseBody(respPtr any) *Builder { - req.responsePtr = respPtr - return req -} - -// Timeout sets the request timeout duration. -// A timeout of zero or negative disables the timeout. -// Returns the Builder for method chaining. -func (req *Builder) Timeout(timeout time.Duration) *Builder { - req.timeout = timeout - return req -} - -// AppendMetadata adds one or more values to the metadata key. -// Returns the Builder for method chaining. -func (req *Builder) AppendMetadata(k string, v ...string) *Builder { - req.MD[k] = append(req.MD[k], v...) - return req -} - -// EncodeRequest sets encoding for request body. -// It affects content-encoding and request body serialization. -func (b *Builder) EncodeRequest(encode bool) *Builder { - b.EncodeSettings.EncodeRequest = encode - return b -} - -// AcceptEncodedResponse enables transparent handling of encoded GRPC responses. -// -// When enabled, the client adds "accept-encoding" (e.g. zstd) to request headers, -// allowing the server to return encoded payloads. -func (b *Builder) AcceptEncodedResponse(accept bool) *Builder { - b.EncodeSettings.AcceptEncodedResponse = accept - return b -} - -// EncodeThreshold sets the request encoding threshold in bytes. -func (b *Builder) EncodeThreshold(thresholdBytes int) *Builder { - b.EncodeSettings.EncodeThreshold = thresholdBytes - return b -} - -// Do executes the request and unmarshals the response if a response pointer was provided. -// Returns an error if JSON marshaling, request execution, or response unmarshaling fails. -// Automatically applies the configured timeout to the request context. -func (req *Builder) Do(ctx context.Context) error { - var ( - reqCtx = ctx - cancel context.CancelFunc - ) - if req.timeout > 0 { - reqCtx, cancel = context.WithTimeout(ctx, req.timeout) - defer cancel() - } - - req.MD.Set(grpc.ProxyMethodNameHeader, req.Endpoint) - if req.applicationId != 0 { - req.MD.Set(grpc.ApplicationIdHeader, strconv.Itoa(req.applicationId)) - } - ctx = metadata.NewOutgoingContext(reqCtx, req.MD) - - var body []byte - var err error - if req.requestBody != nil { - body, err = json.Marshal(req.requestBody) - if err != nil { - return errors.WithMessage(err, "marshal to json request body") - } - } - message := &isp.Message{Body: &isp.Message_BytesBody{BytesBody: body}} - - resp, err := req.roundTripper(ctx, req, message) - if err != nil { - return err - } - - if req.responsePtr != nil { - err = json.Unmarshal(resp.GetBytesBody(), req.responsePtr) - if err != nil { - return errors.WithMessage(err, "unmarshal response body") - } - } - - return nil -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/client/request/common.go b/vendor/github.com/txix-open/isp-kit/grpc/client/request/common.go deleted file mode 100644 index 00b7668..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/client/request/common.go +++ /dev/null @@ -1,17 +0,0 @@ -package request - -import ( - "context" - - "github.com/txix-open/isp-kit/grpc/isp" -) - -// RoundTripper defines the interface for executing gRPC requests. -// Receives a context, request builder, and message; returns a response message and optional error. -// Used as the base for middleware chains. -type RoundTripper func(ctx context.Context, builder *Builder, message *isp.Message) (*isp.Message, error) - -// Middleware wraps a RoundTripper to add cross-cutting concerns like logging, -// metrics, authentication, or error handling. -// Middleware functions are typically chained in reverse order of execution. -type Middleware func(next RoundTripper) RoundTripper diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/README.md b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/README.md deleted file mode 100644 index dbf9b7f..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/README.md +++ /dev/null @@ -1,268 +0,0 @@ -# Package `endpoint` - -Пакет `endpoint` предоставляет инструменты для создания gRPC-обработчиков с автоматической сериализацией JSON, -валидацией запросов, middleware-цепочками и интеграцией метрик/логирования. Реализует паттерн "Endpoint" для изоляции -бизнес-логики от транспортного слоя. - -## Types - -### Wrapper - -Основная структура для создания цепочек обработки запросов. Объединяет: - -- Маппинг параметров -- Middleware (логирование, метрики, восстановление после паник) -- Сериализацию/валидацию JSON - -**Methods:** - -#### `NewWrapper(paramMappers []ParamMapper, bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper) Wrapper` - -Создает конфигурацию для обработчиков. -Параметры: - -- `paramMappers` – правила извлечения параметров из контекста/метаданных -- `bodyExtractor` – десериализация и валидация тела запроса -- `bodyMapper` – сериализация ответа - -#### `(m Wrapper) Endpoint(f any) grpc.HandlerFunc` - -Преобразует пользовательскую функцию в gRPC-обработчик. -Функция `f` может содержать параметры: - -- `context.Context` -- `grpc.AuthData` (метаданные аутентификации) -- Пользовательский тип (десериализуется из JSON-тела) - -#### `(m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper` - -Добавляет middleware в цепочку обработки. - -### Caller - -Внутренняя структура для вызова пользовательских обработчиков. Автоматически: - -- Извлекает параметры -- Вызывает middleware -- Обрабатывает ошибки - -**Methods:** - -#### - -`NewCaller(f any,bodyExtractor RequestBodyExtractor, bodyMapper ResponseBodyMapper, paramMappers map[string]ParamMapper) (*Caller, error)` - -Создает экземпляр `Caller` для функции-обработчика. - -#### `(h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error)` - -Вызывает функцию-обработчик, передавая ей аргументы, извлеченные из запроса. - -### JsonRequestExtractor - -Реализация интерфейса `RequestBodyExtractor` для работы с JSON. Валидирует данные с помощью объекта, реализующего -интерфейс `Validator`. - -**Methods:** - -#### - -`(j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error)` - -Десериализует и валидирует JSON-тело запроса через `Validator`. - -### JsonResponseMapper - -Сериализует ответ обработчика в JSON-тело gRPC-сообщения. - -**Methods:** - -#### `(j JsonResponseMapper) Map(result any) (*isp.Message, error)` - -Конвертирует результат обработчика в gRPC-сообщение в формате JSON. - -## Middlewares - -### `MaxRequestBodySize` - -Ограничивает размер тела запроса (по умолчанию 64 МБ). - -### `RequestId` - -Добавляет в контекст requestId, который берет из заголовка x-request-id. Генерирует новый, если не находит. - -### `DecodeRequest` -Декодирует запрос при помощи переданного codec, если заголовок `x-content-encoding` совпадает с типом codec. - -### `Metrics` - -Собирает метрики: время выполнения, статусы, размеры тел. - -### `Tracing` - -Интеграция с трейсингом (OpenTelemetry). - -### `EncodeResponse` - -Кодирует ответ при помощи переданного codec, если заголовок `x-accept-encoding` содержит строку с типом codec (пример значения заголовка `"zstd, identity"`) и размер ответа больше переданного threshold'а, по умолчанию 128 КБ (параметр в байтах). - -### `ErrorHandler` - -Перехватывает и обрабатывает ошибки. Ошибки типа `GrpcError` возвращают структурированный ответ. -Остальные ошибки логируются и возвращаются как Internal Server Error с gRPC-кодом 13. - -### `Recovery` - -Предотвращает падение сервера при панике в обработчике, преобразуя ее в ошибку. - -## Functions - -#### `DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper` - -Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами. -Упрощает создание эндпоинтов, включая валидацию, метрики и обработку ошибок "из коробки". - -Список Middleware: - -- `RequestId` -- `Metrics` -- `Tracing` -- `ErrorHandler` -- `Recovery` - -#### `DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper` - -Создает предварительно настроенную обертку (`Wrapper`) для gRPC-обработчиков с middleware и параметрами. -Упрощает создание эндпоинтов, включая валидацию, декодирование запросов, кодировение ответов, метрики и обработку ошибок "из коробки". - -Список Middleware: - -- `RequestId` -- `DecodeRequest` -- `Metrics` -- `Tracing` -- `EncodeResponse` -- `ErrorHandler` -- `Recovery` - -## Usage - -### Default usage flow - -```go -package main - -import ( - "context" - "log" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/endpoint" - log2 "github.com/txix-open/isp-kit/log" - "github.com/txix-open/isp-kit/shutdown" -) - -type getUserRequest struct { - Id string -} - -type user struct { - Id string - Name string -} - -func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) { - appId, _ := authData.ApplicationId() - log.Printf("Request from app with id %d", appId) - - /* put here business logic */ - - return &user{Id: req.Id, Name: "Alice"}, nil -} - -func main() { - logger, err := log2.New() - if err != nil { - log.Fatal(err) - } - - mux := grpc.NewMux() - wrapper := endpoint.DefaultWrapper(logger) - mux.Handle("/get_user", wrapper.Endpoint(getUser)) - - srv := grpc.DefaultServer() - srv.Upgrade(mux) - - shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ - log.Println("shutting down...") - srv.Shutdown() - log.Println("shutdown completed") - }) - - err = srv.ListenAndServe(":8080") - if err != nil { - log.Fatal(err) - } -} - -``` - -### Codec usage flow - -```go -package main - -import ( - "context" - "log" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/endpoint" - log2 "github.com/txix-open/isp-kit/log" - "github.com/txix-open/isp-kit/shutdown" -) - -type getUserRequest struct { - Id string -} - -type user struct { - Id string - Name string -} - -func getUser(ctx context.Context, authData grpc.AuthData, req getUserRequest) (*user, error) { - appId, _ := authData.ApplicationId() - log.Printf("Request from app with id %d", appId) - - /* put here business logic */ - - return &user{Id: req.Id, Name: "Alice"}, nil -} - -func main() { - logger, err := log2.New() - if err != nil { - log.Fatal(err) - } - - mux := grpc.NewMux() - wrapper := endpoint.DefaultCodecWrapper(logger) - mux.Handle("/get_user", wrapper.Endpoint(getUser)) - - srv := grpc.DefaultServer() - srv.Upgrade(mux) - - shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ - log.Println("shutting down...") - srv.Shutdown() - log.Println("shutdown completed") - }) - - err = srv.ListenAndServe(":8080") - if err != nil { - log.Fatal(err) - } -} - -``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go deleted file mode 100644 index 066c1ba..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/caller.go +++ /dev/null @@ -1,124 +0,0 @@ -package endpoint - -import ( - "context" - "reflect" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/isp" -) - -// param represents a single parameter to be injected into a wrapped function. -type param struct { - index int - builder ParamBuilder -} - -// Caller wraps a function for gRPC invocation using reflection. -// It analyzes the function signature, injects dependencies, and handles -// request/response marshaling automatically. -type Caller struct { - bodyExtractor RequestBodyExtractor - bodyMapper ResponseBodyMapper - - handler reflect.Value - paramsCount int - params []param - reqBodyIndex int - reqBodyType reflect.Type - - hasResult bool - hasError bool - errorIndex int -} - -// NewCaller creates a new Caller for the specified function. -// Analyzes the function signature to determine parameter types and return values. -// Returns an error if the input is not a function or if parameter types cannot be resolved. -func NewCaller( - f any, - bodyExtractor RequestBodyExtractor, - bodyMapper ResponseBodyMapper, - paramMappers map[string]ParamMapper, -) (*Caller, error) { - rt := reflect.TypeOf(f) - if rt.Kind() != reflect.Func { - return nil, errors.New("function expected") - } - - paramsCount := rt.NumIn() - reqBodyIndex := -1 - handler := reflect.ValueOf(f) - var reqBodyType reflect.Type - params := make([]param, 0, paramsCount) - - for i := range paramsCount { - p := rt.In(i) - paramType := p.String() - mapper, ok := paramMappers[paramType] - - if !ok { // maybe it's a request body - if reqBodyIndex != -1 { - return nil, errors.Errorf("param mapper not found for type %s", paramType) - } - reqBodyIndex = i - reqBodyType = p - continue - } - - // it's a simple param - params = append(params, param{index: i, builder: mapper.Builder}) - } - - numOut := rt.NumOut() - hasResult := numOut > 0 && rt.Out(0) != reflect.TypeFor[*error]().Elem() - hasError := numOut > 0 && rt.Out(numOut-1) == reflect.TypeFor[*error]().Elem() - - return &Caller{ - bodyExtractor: bodyExtractor, - bodyMapper: bodyMapper, - handler: handler, - paramsCount: paramsCount, - params: params, - reqBodyIndex: reqBodyIndex, - reqBodyType: reqBodyType, - hasResult: hasResult, - hasError: hasError, - errorIndex: numOut - 1, - }, nil -} - -// Handle executes the wrapped function with the provided context and message. -// Injects parameters, extracts request body, calls the function, and maps the result. -// Returns the response message and any error from the function or parameter extraction. -func (h *Caller) Handle(ctx context.Context, message *isp.Message) (*isp.Message, error) { - args := make([]reflect.Value, h.paramsCount) - - if h.reqBodyIndex != -1 { - value, err := h.bodyExtractor.Extract(ctx, message, h.reqBodyType) - if err != nil { - return nil, err - } - args[h.reqBodyIndex] = value - } - - for _, p := range h.params { - value, err := p.builder(ctx, message) - if err != nil { - return nil, err - } - args[p.index] = reflect.ValueOf(value) - } - - out := h.handler.Call(args) - - if h.hasError && !out[h.errorIndex].IsNil() { - return nil, out[h.errorIndex].Interface().(error) // nolint:forcetypeassert - } - - if h.hasResult { - return h.bodyMapper.Map(out[0].Interface()) - } - - return nil, nil // nolint:nilnil -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/default.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/default.go deleted file mode 100644 index 6410ed1..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/default.go +++ /dev/null @@ -1,68 +0,0 @@ -package endpoint - -import ( - "github.com/txix-open/isp-kit/codec" - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/log" - "github.com/txix-open/isp-kit/metrics" - "github.com/txix-open/isp-kit/metrics/grpc_metrics" - "github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing" - "github.com/txix-open/isp-kit/validator" -) - -// DefaultWrapper creates a Wrapper with pre-configured middleware for observability. -// Includes request ID propagation, metrics collection, distributed tracing, error handling, -// and panic recovery. Uses JSON for request extraction and response mapping. -// Accepts additional middleware to be appended after the default ones. -func DefaultWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper { - paramMappers := []ParamMapper{ - ContextParam(), - AuthDataParam(), - } - metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry) - middlewares := append( - []grpc.Middleware{ - RequestId(), - Metrics(metricStorage), - server_tracing.NewConfig().Middleware(), - ErrorHandler(logger), - Recovery(), - }, - restMiddlewares..., - ) - return NewWrapper( - paramMappers, - JsonRequestExtractor{Validator: validator.Default}, - JsonResponseMapper{}, - ).WithMiddlewares(middlewares...) -} - -// DefaultCodecWrapper creates a Wrapper with pre-configured middleware for observability. -// Includes request ID propagation, metrics collection, distributed tracing, error handling, encode response, decode request, -// and panic recovery. Uses JSON for request extraction and response mapping. -// Accepts additional middleware to be appended after the default ones. -func DefaultCodecWrapper(logger log.Logger, restMiddlewares ...grpc.Middleware) Wrapper { - paramMappers := []ParamMapper{ - ContextParam(), - AuthDataParam(), - } - metricStorage := grpc_metrics.NewServerStorage(metrics.DefaultRegistry) - codec := codec.Default - middlewares := append( - []grpc.Middleware{ - RequestId(), - DecodeRequest(codec), - Metrics(metricStorage), - server_tracing.NewConfig().Middleware(), - EncodeResponse(codec, defaultEncodeThreshold), - ErrorHandler(logger), - Recovery(), - }, - restMiddlewares..., - ) - return NewWrapper( - paramMappers, - JsonRequestExtractor{Validator: validator.Default}, - JsonResponseMapper{}, - ).WithMiddlewares(middlewares...) -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go deleted file mode 100644 index b635e3e..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_request.go +++ /dev/null @@ -1,69 +0,0 @@ -package endpoint - -import ( - "context" - "reflect" - "unicode" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/apierrors" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/json" -) - -const ( - // errCodeBadRequest is the error code for invalid request body errors. - errCodeBadRequest = 400 -) - -// Validator defines the interface for request validation. -// Implementations should validate a value and return whether it's valid -// along with field-specific error details. -type Validator interface { - // Validate checks if the value is valid. - // Returns true if valid, false otherwise, along with a map of field names to error messages. - Validate(value any) (bool, map[string]string) -} - -// JsonRequestExtractor extracts and validates JSON request bodies from gRPC messages. -// Unmarshals the message body into the target type and validates it using the configured validator. -type JsonRequestExtractor struct { - Validator Validator -} - -// Extract unmarshals the message body as JSON and validates it. -// Returns a reflect.Value of the created instance or an error if unmarshaling or validation fails. -// Business validation errors are returned as apierrors.BusinessError with code 400. -func (j JsonRequestExtractor) Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error) { - instance := reflect.New(reqBodyType) - err := json.Unmarshal(message.GetBytesBody(), instance.Interface()) - if err != nil { - err = errors.WithMessage(err, "unmarshal json request body") - return reflect.Value{}, apierrors.NewBusinessError(errCodeBadRequest, err.Error(), err) - } - - elem := instance.Elem() - - ok, details := j.Validator.Validate(elem.Interface()) - if ok { - return elem, nil - } - formattedDetails := formatDetails(details) - return reflect.Value{}, apierrors.NewBusinessError( - errCodeBadRequest, - "invalid request body", - errors.Errorf("validation errors: %v", formattedDetails), - ).WithDetails(formattedDetails) -} - -// formatDetails converts a map of field error messages to a format suitable for API responses. -// Converts field names to lowercase (first character) for consistency. -func formatDetails(details map[string]string) map[string]any { - result := make(map[string]any, len(details)) - for k, v := range details { - arr := []rune(k) - arr[0] = unicode.ToLower(arr[0]) - result[string(arr)] = v - } - return result -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go deleted file mode 100644 index 86a0703..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/json_response.go +++ /dev/null @@ -1,29 +0,0 @@ -package endpoint - -import ( - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/json" -) - -// JsonResponseMapper maps handler results to gRPC messages with JSON-encoded bodies. -// Implements the ResponseBodyMapper interface. -type JsonResponseMapper struct{} - -// Map marshals the result to JSON and creates a gRPC message. -// Returns an empty message body if result is nil. -// Returns an error if JSON marshaling fails. -func (j JsonResponseMapper) Map(result any) (*isp.Message, error) { - if result == nil { - return &isp.Message{Body: &isp.Message_BytesBody{}}, nil - } - data, err := json.Marshal(result) - if err != nil { - return nil, errors.WithMessage(err, "marshal json") - } - return &isp.Message{ - Body: &isp.Message_BytesBody{ - BytesBody: data, - }, - }, nil -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/metrics_middleware.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/metrics_middleware.go deleted file mode 100644 index d9942ad..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/metrics_middleware.go +++ /dev/null @@ -1,51 +0,0 @@ -package endpoint - -import ( - "context" - "time" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -// MetricStorage defines the interface for collecting gRPC server metrics. -// Implementations should record request durations, payload sizes, and response codes. -type MetricStorage interface { - // ObserveDuration records the duration of a request for the given method. - ObserveDuration(method string, duration time.Duration) - // ObserveRequestBodySize records the size of the request body. - ObserveRequestBodySize(method string, size int) - // ObserveResponseBodySize records the size of the response body. - ObserveResponseBodySize(method string, size int) - // CountStatusCode increments the counter for the given endpoint and status code. - CountStatusCode(endpoint string, code codes.Code) -} - -// Metrics creates a middleware that collects metrics for gRPC server requests. -// Records request duration, request/response body sizes, and response status codes. -// The endpoint name is extracted from the ProxyMethodNameHeader in request metadata. -func Metrics(storage MetricStorage) grpc.Middleware { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, message *isp.Message) (*isp.Message, error) { - md, _ := metadata.FromIncomingContext(ctx) - endpoint, err := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md) - if err != nil { - return nil, err - } - - storage.ObserveRequestBodySize(endpoint, len(message.GetBytesBody())) - start := time.Now() - response, err := next(ctx, message) - storage.ObserveDuration(endpoint, time.Since(start)) - storage.CountStatusCode(endpoint, status.Code(err)) - if response != nil { - storage.ObserveResponseBodySize(endpoint, len(response.GetBytesBody())) - } - - return response, err - } - } -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go deleted file mode 100644 index c0d4ab9..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/middlewares.go +++ /dev/null @@ -1,221 +0,0 @@ -package endpoint - -import ( - "context" - "strings" - - "github.com/getsentry/sentry-go" - "github.com/txix-open/isp-kit/codec" - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/log" - "github.com/txix-open/isp-kit/log/logutil" - sentry2 "github.com/txix-open/isp-kit/observability/sentry" - "github.com/txix-open/isp-kit/panic_recovery" - "github.com/txix-open/isp-kit/requestid" - grpc2 "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -const ( - defaultEncodeThreshold = codec.DefaultEncodeThreshold -) - -// Recovery creates a middleware that catches panics and converts them to errors. -// Prevents gRPC server crashes from handler panics by recovering and returning the error. -func Recovery() grpc.Middleware { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, message *isp.Message) (msg *isp.Message, err error) { - defer panic_recovery.Recover(func(panicErr error) { - err = panicErr - }) - return next(ctx, message) - } - } -} - -// ErrorHandler creates a middleware that handles errors from downstream handlers. -// Logs errors at appropriate levels, enriches them with Sentry context, and -// converts custom GrpcError types to gRPC status errors. -// Returns a generic "internal service error" for unknown error types to prevent -// information leakage. -func ErrorHandler(logger log.Logger) grpc.Middleware { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, message *isp.Message) (*isp.Message, error) { - result, err := next(ctx, message) - if err == nil { - return result, nil - } - - logFunc := logutil.LogLevelFuncForError(err, logger) - logContext := sentry2.EnrichEvent(ctx, func(event *sentry.Event) { - event.Request = sentryRequest(ctx) - }) - logFunc(logContext, err) - - var grpcErr GrpcError - if errors.As(err, &grpcErr) { - return result, grpcErr.GrpcStatusError() - } - - // deprecated approach - _, ok := status.FromError(err) - if ok { - return result, err - } - - // hide error details to prevent potential security leaks - return result, status.Error(codes.Internal, "internal service error") - } - } -} - -// RequestId creates a middleware that manages request IDs for tracing. -// Extracts the request ID from incoming metadata, generates a new one if absent, -// and injects it into the context for downstream use. -func RequestId() grpc.Middleware { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, message *isp.Message) (*isp.Message, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, errors.New("metadata is expected in context") - } - values := md.Get(requestid.Header) - requestId := "" - if len(values) > 0 { - requestId = values[0] - } - if requestId == "" { - requestId = requestid.Next() - } - ctx = requestid.ToContext(ctx, requestId) - ctx = log.ToContext(ctx, log.String(requestid.LogKey, requestId)) - - return next(ctx, message) - } - } -} - -type DecodeCodec interface { - Type() string - DecodeBytes(b []byte) ([]byte, error) -} - -// DecodeRequest returns middleware that transparently handles decoded requests. -// -// If x-content-encoding matches codec, request body is decoded. -// -// Important: -// - Should be placed before logging middleware if logs must see decoded data. -func DecodeRequest(codec DecodeCodec) grpc.Middleware { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, errors.New("metadata is expected in context") - } - - contentEncoding, _ := grpc.StringFromMd(grpc.ContentEncodingHeader, md) - reqBody := msg.GetBytesBody() - if contentEncoding == codec.Type() { - decoded, err := codec.DecodeBytes(reqBody) - if err != nil { - return nil, err - } - - msg.Body = &isp.Message_BytesBody{ - BytesBody: decoded, - } - md.Delete(grpc.ContentEncodingHeader) - ctx = metadata.NewIncomingContext(ctx, md) - } - - return next(ctx, msg) - } - } -} - -type EncodeCodec interface { - Type() string - EncodeBytes(b []byte) ([]byte, error) -} - -// EncodeResponse returns middleware that transparently handles response encoding. -// -// If client supports x-accept-encoding and response body size > encodeThresholdBytes, -// the response is encoded using codec. -// -// Important: -// - Should be placed before logging middleware if logs must see plain data. -func EncodeResponse(codec EncodeCodec, encodeThresholdBytes int) grpc.Middleware { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, msg *isp.Message) (*isp.Message, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, errors.New("metadata is expected in context") - } - - resp, err := next(ctx, msg) - if err != nil { - return nil, err - } - - // check accept - acceptEncoding, _ := grpc.StringFromMd(grpc.AcceptEncodingHeader, md) - if !acceptsEncoding(acceptEncoding, codec.Type()) { - return resp, nil - } - - responseBody := resp.GetBytesBody() - if len(responseBody) <= encodeThresholdBytes { - return resp, nil - } - - err = grpc2.SetHeader(ctx, metadata.Pairs( - grpc.ContentEncodingHeader, codec.Type(), - )) - if err != nil { - return nil, err - } - - encoded, err := codec.EncodeBytes(responseBody) - if err != nil { - return nil, err - } - resp.Body = &isp.Message_BytesBody{ - BytesBody: encoded, - } - - return resp, nil - } - } -} - -// acceptsEncoding split header and check contains encoding in it. -func acceptsEncoding(header, encoding string) bool { - for part := range strings.SplitSeq(header, ",") { - if strings.TrimSpace(part) == encoding { - return true - } - } - - return false -} - -// sentryRequest creates a Sentry request object from the gRPC context. -// Extracts endpoint and application ID from metadata for error tracking. -func sentryRequest(ctx context.Context) *sentry.Request { - md, _ := metadata.FromIncomingContext(ctx) - endpoint, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md) - applicationId, _ := grpc.StringFromMd(grpc.ApplicationIdHeader, md) - return &sentry.Request{ - URL: endpoint, - Method: "POST", - Headers: map[string]string{ - grpc.ApplicationIdHeader: applicationId, - }, - } -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/params.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/params.go deleted file mode 100644 index e3c45b9..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/params.go +++ /dev/null @@ -1,37 +0,0 @@ -package endpoint - -import ( - "context" - "errors" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" - "google.golang.org/grpc/metadata" -) - -// ContextParam creates a ParamMapper for injecting context.Context into handlers. -// The context is passed through from the incoming gRPC request context. -func ContextParam() ParamMapper { - return ParamMapper{ - Type: "context.Context", - Builder: func(ctx context.Context, message *isp.Message) (any, error) { - return ctx, nil - }, - } -} - -// AuthDataParam creates a ParamMapper for injecting grpc.AuthData into handlers. -// Extracts authentication and authorization information from the incoming request metadata. -// Returns an error if metadata is not present in the context. -func AuthDataParam() ParamMapper { - return ParamMapper{ - Type: "grpc.AuthData", - Builder: func(ctx context.Context, message *isp.Message) (any, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, errors.New("metadata is expected in context") // nolint:err113 - } - return grpc.AuthData(md), nil - }, - } -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/wrapper.go b/vendor/github.com/txix-open/isp-kit/grpc/endpoint/wrapper.go deleted file mode 100644 index 5a4202c..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/endpoint/wrapper.go +++ /dev/null @@ -1,107 +0,0 @@ -// Package endpoint provides a higher-level abstraction for building gRPC handlers. -// It enables reflection-based function wrapping with automatic request/response -// marshaling, parameter injection, and middleware support. -// -// The package integrates with the ISP kit framework's logging, metrics, and -// validation systems for comprehensive observability and error handling. -package endpoint - -import ( - "context" - "reflect" - "slices" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" -) - -// GrpcError is an interface for errors that can be converted to gRPC status errors. -// Implementations should return a gRPC status error with appropriate details. -type GrpcError interface { - GrpcStatusError() error -} - -// RequestBodyExtractor defines the interface for extracting request bodies from gRPC messages. -// Implementations should unmarshal the message body into the target type and return a reflect.Value. -type RequestBodyExtractor interface { - // Extract unmarshals the message body into an instance of reqBodyType. - // Returns the reflect.Value of the created instance and any unmarshaling or validation errors. - Extract(ctx context.Context, message *isp.Message, reqBodyType reflect.Type) (reflect.Value, error) -} - -// ResponseBodyMapper defines the interface for mapping handler results to gRPC messages. -// Implementations should marshal the result into a gRPC message body. -type ResponseBodyMapper interface { - // Map converts a handler result into a gRPC message. - // Returns the message and any marshaling errors. - Map(result any) (*isp.Message, error) -} - -// ParamBuilder defines a function that builds a parameter value from context and message. -// Used by ParamMapper to inject dependencies like context, auth data, etc. -type ParamBuilder func(ctx context.Context, message *isp.Message) (any, error) - -// ParamMapper maps a parameter type string to a builder function. -// Used to inject dependencies into handler functions automatically. -type ParamMapper struct { - // Type is the string representation of the parameter type. - Type string - // Builder is the function that creates the parameter value. - Builder ParamBuilder -} - -// Wrapper is a high-level handler factory that wraps functions with middleware and -// automatic request/response handling. It uses reflection to analyze function signatures -// and inject dependencies like context and auth data. -type Wrapper struct { - ParamMappers map[string]ParamMapper - BodyExtractor RequestBodyExtractor - BodyMapper ResponseBodyMapper - Middlewares []grpc.Middleware -} - -// NewWrapper creates a new Wrapper with the specified configuration. -// Accepts variadic paramMappers, a body extractor, and a body mapper. -func NewWrapper( - paramMappers []ParamMapper, - bodyExtractor RequestBodyExtractor, - bodyMapper ResponseBodyMapper, -) Wrapper { - mappers := make(map[string]ParamMapper) - for _, mapper := range paramMappers { - mappers[mapper.Type] = mapper - } - return Wrapper{ - ParamMappers: mappers, - BodyExtractor: bodyExtractor, - BodyMapper: bodyMapper, - } -} - -// Endpoint wraps a function to create a gRPC HandlerFunc. -// The function is analyzed via reflection to determine parameter types and return values. -// Middleware is applied in reverse order (last added, first executed). -// Panics if the function signature is invalid or cannot be wrapped. -func (m Wrapper) Endpoint(f any) grpc.HandlerFunc { - caller, err := NewCaller(f, m.BodyExtractor, m.BodyMapper, m.ParamMappers) - if err != nil { - panic(err) - } - - handler := caller.Handle - for i := range slices.Backward(m.Middlewares) { - handler = m.Middlewares[i](handler) - } - return handler -} - -// WithMiddlewares returns a new Wrapper with additional middleware appended. -// The original Wrapper is not modified. -func (m Wrapper) WithMiddlewares(middlewares ...grpc.Middleware) Wrapper { - return Wrapper{ - ParamMappers: m.ParamMappers, - BodyExtractor: m.BodyExtractor, - BodyMapper: m.BodyMapper, - Middlewares: append(m.Middlewares, middlewares...), - } -} diff --git a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/README.md b/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/README.md deleted file mode 100644 index a4d9698..0000000 --- a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/README.md +++ /dev/null @@ -1,112 +0,0 @@ -# Package `grpc_metrics` - -Пакет `grpc_metrics` предоставляет средства для мониторинга метрик GRPC-клиентов и серверов. - -## Types - -### ClientStorage - -Хранилище метрик GRPC-клиента. - -**Metrics:** - -#### `grpc_client_request_duration_ms{endpoint="..."}` - -Продолжительность вызова внешнего GRPC-сервиса. - -**Methods:** - -#### `func NewClientStorage(reg *metrics.Registry) *ClientStorage` - -Создаёт и регистрирует метрику `client_request_duration_ms` с лейблом `endpoint` в переданном реестре. - -#### `func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration)` - -Регистрирует длительность GRPC-вызова для заданного `endpoint`. - -### ServerStorage - -Хранилище метрик GRPC-сервера. - -**Metrics:** - -#### `grpc_request_duration_ms{endpoint="..."}` - -Продолжительность обработки входящего GRPC-запроса. - -#### `grpc_request_body_size{endpoint="..."}` - -Размер тела входящего запроса. - -#### `grpc_response_body_size{endpoint="..."}` - -Размер тела ответа. - -#### `grpc_status_code_count{endpoint="...",code="..."}` - -Количество ответов по статус-кодам (`OK`, `InvalidArgument`, и т.д.). - -**Methods:** - -#### `func NewServerStorage(reg *metrics.Registry) *ServerStorage` - -Создаёт и регистрирует все метрики сервера с нужными лейблами в переданном реестре. - -#### `func (s *ServerStorage) ObserveDuration(endpoint string, duration time.Duration)` - -Регистрирует длительность обработки GRPC-запроса для `endpoint`. - -#### `func (s *ServerStorage) ObserveRequestBodySize(endpoint string, size int)` - -Регистрирует размер тела запроса в байтах. - -#### `func (s *ServerStorage) ObserveResponseBodySize(endpoint string, size int)` - -Регистрирует размер тела ответа в байтах. - -#### `func (s *ServerStorage) CountStatusCode(endpoint string, code codes.Code)` - -Увеличивает счётчик ответов с соответствующим GRPC-кодом. - -## Prometheus metrics example - -``` -# HELP grpc_client_request_duration_ms The latencies of calling external services via GRPC -# TYPE grpc_client_request_duration_ms summary -grpc_client_request_duration_ms{endpoint="UserService.GetUser"} 12.3 - -# HELP grpc_request_duration_ms The latency of the GRPC requests -# TYPE grpc_request_duration_ms summary -grpc_request_duration_ms{endpoint="UserService.GetUser"} 10.5 - -# HELP grpc_request_body_size The size of request body -# TYPE grpc_request_body_size summary -grpc_request_body_size{endpoint="UserService.GetUser"} 512 - -# HELP grpc_response_body_size The size of response body -# TYPE grpc_response_body_size summary -grpc_response_body_size{endpoint="UserService.GetUser"} 1024 - -# HELP grpc_status_code_count Counter of statuses codes -# TYPE grpc_status_code_count counter -grpc_status_code_count{endpoint="UserService.GetUser",code="OK"} 32 -``` - -## Usage - -### Default usage flow - -```go -clientMetrics := grpc_metrics.NewClientStorage(metrics.DefaultRegistry) -defer func(start time.Time) { - clientMetrics.ObserveDuration("UserService.GetUser", time.Since(start)) -}(time.Now()) - -// ... GRPC call - -serverMetrics := grpc_metrics.NewServerStorage(metrics.DefaultRegistry) -serverMetrics.ObserveDuration("UserService.GetUser", 12*time.Millisecond) -serverMetrics.ObserveRequestBodySize("UserService.GetUser", 512) -serverMetrics.ObserveResponseBodySize("UserService.GetUser", 1024) -serverMetrics.CountStatusCode("UserService.GetUser", codes.OK) -``` diff --git a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/client_storage.go b/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/client_storage.go deleted file mode 100644 index 74ee556..0000000 --- a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/client_storage.go +++ /dev/null @@ -1,33 +0,0 @@ -package grpc_metrics - -import ( - "time" - - "github.com/prometheus/client_golang/prometheus" - "github.com/txix-open/isp-kit/metrics" -) - -// ClientStorage collects metrics for gRPC client operations, primarily focusing -// on request latency when calling external gRPC services. -type ClientStorage struct { - duration *prometheus.SummaryVec -} - -// NewClientStorage creates a new ClientStorage instance and registers its metrics -// with the provided registry. Metrics are labeled by the gRPC endpoint. -func NewClientStorage(reg *metrics.Registry) *ClientStorage { - s := &ClientStorage{ - duration: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{ - Subsystem: "grpc", - Name: "client_request_duration_ms", - Help: "The latencies of calling external services via GRPC", - Objectives: metrics.DefaultObjectives, - }, []string{"endpoint"})), - } - return s -} - -// ObserveDuration records the latency of a gRPC client request, labeled by endpoint. -func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration) { - s.duration.WithLabelValues(endpoint).Observe(metrics.Milliseconds(duration)) -} diff --git a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/doc.go b/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/doc.go deleted file mode 100644 index 803e370..0000000 --- a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/doc.go +++ /dev/null @@ -1,15 +0,0 @@ -// Package grpc_metrics provides Prometheus metric collectors for gRPC server and client operations. -// It tracks request latencies, body sizes, and status code counts for both incoming gRPC requests -// and outgoing gRPC client calls. -// -// Example usage for gRPC server: -// -// serverStorage := grpc_metrics.NewServerStorage(reg) -// serverStorage.ObserveDuration(endpoint, duration) -// serverStorage.CountStatusCode(endpoint, code) -// -// Example usage for gRPC client: -// -// clientStorage := grpc_metrics.NewClientStorage(reg) -// clientStorage.ObserveDuration(endpoint, duration) -package grpc_metrics diff --git a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/server_storage.go b/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/server_storage.go deleted file mode 100644 index 1bbda80..0000000 --- a/vendor/github.com/txix-open/isp-kit/metrics/grpc_metrics/server_storage.go +++ /dev/null @@ -1,70 +0,0 @@ -package grpc_metrics - -import ( - "time" - - "github.com/prometheus/client_golang/prometheus" - "github.com/txix-open/isp-kit/metrics" - "google.golang.org/grpc/codes" -) - -// ServerStorage collects metrics for gRPC server operations, including request -// latency, request/response body sizes, and gRPC status code counts. -type ServerStorage struct { - duration *prometheus.SummaryVec - requestBodySize *prometheus.SummaryVec - responseBodySize *prometheus.SummaryVec - statusCounter *prometheus.CounterVec -} - -// NewServerStorage creates a new ServerStorage instance and registers its metrics -// with the provided registry. Metrics are labeled by gRPC endpoint. -func NewServerStorage(reg *metrics.Registry) *ServerStorage { - s := &ServerStorage{ - duration: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{ - Subsystem: "grpc", - Name: "request_duration_ms", - Help: "The latency of the GRPC requests", - Objectives: metrics.DefaultObjectives, - }, []string{"endpoint"})), - requestBodySize: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{ - Subsystem: "grpc", - Name: "request_body_size", - Help: "The size of request body", - Objectives: metrics.DefaultObjectives, - }, []string{"endpoint"})), - responseBodySize: metrics.GetOrRegister(reg, prometheus.NewSummaryVec(prometheus.SummaryOpts{ - Subsystem: "grpc", - Name: "response_body_size", - Help: "The size of response body", - Objectives: metrics.DefaultObjectives, - }, []string{"endpoint"})), - statusCounter: metrics.GetOrRegister(reg, prometheus.NewCounterVec(prometheus.CounterOpts{ - Subsystem: "grpc", - Name: "status_code_count", - Help: "Counter of statuses codes", - }, []string{"endpoint", "code"})), - } - return s -} - -// ObserveDuration records the latency of a gRPC request, labeled by endpoint. -func (s *ServerStorage) ObserveDuration(endpoint string, duration time.Duration) { - s.duration.WithLabelValues(endpoint).Observe(metrics.Milliseconds(duration)) -} - -// ObserveRequestBodySize records the size of a gRPC request payload in bytes. -func (s *ServerStorage) ObserveRequestBodySize(endpoint string, size int) { - s.requestBodySize.WithLabelValues(endpoint).Observe(float64(size)) -} - -// ObserveResponseBodySize records the size of a gRPC response payload in bytes. -func (s *ServerStorage) ObserveResponseBodySize(endpoint string, size int) { - s.responseBodySize.WithLabelValues(endpoint).Observe(float64(size)) -} - -// CountStatusCode increments the counter for a specific gRPC status code, -// labeled by endpoint and status code. -func (s *ServerStorage) CountStatusCode(endpoint string, code codes.Code) { - s.statusCounter.WithLabelValues(endpoint, code.String()).Inc() -} diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/carrier.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/carrier.go deleted file mode 100644 index 43b0b2e..0000000 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/carrier.go +++ /dev/null @@ -1,32 +0,0 @@ -// Package grpc provides utilities for gRPC tracing integration. -package grpc - -import ( - "google.golang.org/grpc/metadata" -) - -// MetadataCarrier implements the TextMapCarrier interface for gRPC metadata. -type MetadataCarrier metadata.MD - -// Get returns the first value associated with the given key. -func (m MetadataCarrier) Get(key string) string { - value := metadata.MD(m).Get(key) - if len(value) == 0 { - return "" - } - return value[0] -} - -// Set associates a key-value pair in the metadata. -func (m MetadataCarrier) Set(key string, value string) { - metadata.MD(m).Set(key, value) -} - -// Keys returns all keys in the metadata. -func (m MetadataCarrier) Keys() []string { - keys := make([]string, 0, len(m)) - for key := range m { - keys = append(keys, key) - } - return keys -} diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/README.md b/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/README.md deleted file mode 100644 index 1811b93..0000000 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# Package `client_tracing` - -Пакет `client_tracing` предназначен для добавления middleware к gRPC-клиенту с поддержкой распределённой трассировки через OpenTelemetry. Позволяет автоматически создавать и передавать span-контекст при выполнении gRPC-запросов, а также записывать статусы и ошибки вызовов в трассировку. - -## Types - -### Config - -Структура `Config` представляет конфигурацию трассировки для gRPC-клиента. - -**Fields:** - -#### `Provider` - -Реализация интерфейса `tracing.TracerProvider`, используемая для создания спанов. - -#### `Propagator` - -Реализация интерфейса `tracing.Propagator`, используемая для инъекции и извлечения контекста трассировки. - -**Methods:** - -#### `func NewConfig() Config` - -Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию. - -#### `func (c Config) Middleware() request.Middleware` - -Возвращает middleware для клиента gRPC, реализующего трассировку запроса. Если трассировка отключена (noop-провайдер), возвращается middleware-заглушка. - -Middleware: - -- Создаёт новый спан для каждого gRPC-вызова с именем `GRPC call `. -- Устанавливает `span kind` в значение `Client`. -- Добавляет `request_id` в атрибуты спана. -- Инъецирует контекст в metadata запроса. -- В случае ошибки записывает её в спан и устанавливает статус `Error`. - -## Usage - -### Default usage flow - -```go -package main - -import ( - "github.com/txix-open/isp-kit/grpc/client" - "github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing" -) -func main() { - ... - cfg := client_tracing.NewConfig() - client := client.New( - client.WithMiddleware( - cfg.Middleware(), - ), - ) - ... -} -``` - -Для корректной работы необходимо, чтобы в контексте присутствовал `request_id`, а также был корректно настроен глобальный TracerProvider и Propagator OpenTelemetry. diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/middleware.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/middleware.go deleted file mode 100644 index 0dd4e6c..0000000 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing/middleware.go +++ /dev/null @@ -1,77 +0,0 @@ -// Package client_tracing provides gRPC client middleware for distributed tracing. -package client_tracing - -import ( - "context" - "fmt" - - "github.com/txix-open/isp-kit/grpc/client/request" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/observability/tracing" - "github.com/txix-open/isp-kit/observability/tracing/grpc" - "github.com/txix-open/isp-kit/requestid" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/codes" - "go.opentelemetry.io/otel/trace" -) - -// tracerName identifies the tracer for gRPC client tracing. -const tracerName = "isp-kit/observability/tracing/grpc" - -// Config holds the configuration for the gRPC client tracing middleware. -type Config struct { - // Provider is the tracer provider used to create tracers. - Provider tracing.TracerProvider - // Propagator is the text map propagator for context propagation. - Propagator tracing.Propagator -} - -// NewConfig creates a new Config with default values. -func NewConfig() Config { - return Config{ - Provider: tracing.DefaultProvider, - Propagator: tracing.DefaultPropagator, - } -} - -// Middleware returns a gRPC client middleware that creates spans for outgoing RPC calls. -// It injects trace context into the request metadata, creates a client span, and records -// errors. If the provider is a no-op, it returns a pass-through middleware. -func (c Config) Middleware() request.Middleware { - if tracing.IsNoop(c.Provider) { - return func(next request.RoundTripper) request.RoundTripper { - return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - return next(ctx, builder, message) - } - } - } - - tracer := c.Provider.Tracer(tracerName) - return func(next request.RoundTripper) request.RoundTripper { - return func(ctx context.Context, builder *request.Builder, message *isp.Message) (*isp.Message, error) { - attributes := []attribute.KeyValue{ - tracing.RequestId.String(requestid.FromContext(ctx)), - } - opts := []trace.SpanStartOption{ - trace.WithSpanKind(trace.SpanKindClient), - trace.WithAttributes(attributes...), - } - - clientEndpoint := builder.Endpoint - spanName := fmt.Sprintf("GRPC call %s", clientEndpoint) - - ctx, span := tracer.Start(ctx, spanName, opts...) - defer span.End() - - c.Propagator.Inject(ctx, grpc.MetadataCarrier(builder.MD)) - - resp, err := next(ctx, builder, message) - if err != nil { - span.RecordError(err) - span.SetStatus(codes.Error, err.Error()) - } - - return resp, err - } - } -} diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/README.md b/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/README.md deleted file mode 100644 index affbe9b..0000000 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/README.md +++ /dev/null @@ -1,95 +0,0 @@ -# Package `server_tracing` - -Пакет `server_tracing` предоставляет middleware для серверов gRPC, реализующих трассировку входящих запросов с использованием OpenTelemetry. - -## Types - -### Config - -Структура `Config` предназначена для конфигурации middleware трассировки gRPC-сервера. Она содержит провайдер трассировки и пропагатор контекста. - -**Fields:** - -#### `Provider tracing.TracerProvider` - -Реализация интерфейса `tracing.TracerProvider`, используемая для создания спанов. - -#### `Propagator tracing.Propagator` - -Реализация интерфейса `tracing.Propagator`, используемая для инъекции и извлечения контекста трассировки. - -**Methods:** - -#### `func NewConfig() Config` - -Создаёт конфигурацию трассировки с `provider` и `propagator` по умолчанию. - -#### `func (c Config) Middleware() grpc.Middleware` - -Создаёт middleware для трассировки gRPC-запросов. Возвращаемый middleware: - -- Извлекает контекст трассировки из входящих метаданных; -- Инициирует span с именем, основанным на методе gRPC-запроса (если доступно); -- Добавляет атрибут `request.id`; -- Фиксирует ошибку в span, если она произошла; -- Завершает span после выполнения запроса. - -Если трассировка отключена (noop-провайдер), возвращается no-op middleware. - -## Usage - -### Default usage flow - -```go -package main - -import ( - "context" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/endpoint" - - "github.com/txix-open/isp-kit/log" - - "github.com/txix-open/isp-kit/validator" - - "github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing" -) - -func main(){ - ... - - tracingCfg := server_tracing.NewConfig() - server := grpc.DefaultServer() - - logger, _ := log.New() - paramMappers := []endpoint.ParamMapper{ - ContextParam(), - AuthDataParam(), - } - middlewares := append( - []grpc.Middleware{ - RequestId(), - server_tracing.NewConfig().Middleware(), - ErrorHandler(logger), - Recovery(), - }, - restMiddlewares..., - ) - wrapper := NewWrapper( - paramMappers, - JsonRequestExtractor{Validator: validator.Default}, - JsonResponseMapper{}, - ).WithMiddlewares(middlewares...) - - mux := grpc.NewMux() - mux.Handle("some_endpoint", wrapper.Endpoint(func(ctx context.Context) error { - // реализация - return nil - })) - - server.Upgrade(mux) - - server.ListenAndServe(":8080") -} -``` diff --git a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/middleware.go b/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/middleware.go deleted file mode 100644 index d471631..0000000 --- a/vendor/github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing/middleware.go +++ /dev/null @@ -1,87 +0,0 @@ -// Package server_tracing provides gRPC server middleware for distributed tracing. -package server_tracing - -import ( - "context" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/log" - "github.com/txix-open/isp-kit/log/logutil" - "github.com/txix-open/isp-kit/observability/tracing" - grpc2 "github.com/txix-open/isp-kit/observability/tracing/grpc" - "github.com/txix-open/isp-kit/requestid" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/trace" - "google.golang.org/grpc/metadata" -) - -// tracerName identifies the tracer for gRPC server tracing. -const tracerName = "isp-kit/observability/tracing/grpc" - -// Config holds the configuration for the gRPC server tracing middleware. -type Config struct { - // Provider is the tracer provider used to create tracers. - Provider tracing.TracerProvider - // Propagator is the text map propagator for context propagation. - Propagator tracing.Propagator -} - -// NewConfig creates a new Config with default values. -func NewConfig() Config { - return Config{ - Provider: tracing.DefaultProvider, - Propagator: tracing.DefaultPropagator, - } -} - -// Middleware returns a gRPC server middleware that creates spans for incoming RPC calls. -// It extracts trace context from request metadata, creates a server span, and records -// errors at the appropriate log level. If the provider is a no-op, it returns a pass-through middleware. -func (c Config) Middleware() grpc.Middleware { - if tracing.IsNoop(c.Provider) { - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, message *isp.Message) (*isp.Message, error) { - return next(ctx, message) - } - } - } - - tracer := c.Provider.Tracer(tracerName) - return func(next grpc.HandlerFunc) grpc.HandlerFunc { - return func(ctx context.Context, message *isp.Message) (*isp.Message, error) { - md, _ := metadata.FromIncomingContext(ctx) - if md == nil { - md = metadata.MD{} - } - spanName, _ := grpc.StringFromMd(grpc.ProxyMethodNameHeader, md) - if spanName == "" { - return next(ctx, message) - } - - ctx = c.Propagator.Extract(ctx, grpc2.MetadataCarrier(md)) - - attributes := []attribute.KeyValue{ - tracing.RequestId.String(requestid.FromContext(ctx)), - } - opts := []trace.SpanStartOption{ - trace.WithSpanKind(trace.SpanKindServer), - trace.WithAttributes(attributes...), - } - - ctx, span := tracer.Start(ctx, spanName, opts...) - defer span.End() - - resp, err := next(ctx, message) - - if err != nil { - logLevel := logutil.LogLevelForError(err) - if logLevel == log.ErrorLevel { - span.RecordError(err) - } - } - - return resp, err - } - } -} diff --git a/vendor/github.com/txix-open/isp-kit/test/grpct/README.md b/vendor/github.com/txix-open/isp-kit/test/grpct/README.md deleted file mode 100644 index 6afae46..0000000 --- a/vendor/github.com/txix-open/isp-kit/test/grpct/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# Package `grpct` - -Пакет `grpct` предназначен для упрощения написания юнит- и интеграционных тестов gRPC-сервисов на базе `isp-kit`. - -## Types - -### MockServer - -Структура `MockServer` представляет собой обёртку над gRPC-сервером, позволяющую удобно мокать отдельные endpoint'ы. - -**Methods:** - -#### `NewMock(t *test.Test) (*MockServer, *client.Client)` - -Создаёт `MockServer` и соответствующий gRPC-клиент. Полезно для юнит-тестов и простых сценариев мокирования. - -#### `(m *MockServer) Mock(endpoint string, handler any) *MockServer` - -Регистрирует указанный `handler` на переданный `endpoint` с использованием `endpoint.Wrapper`. - -## Functions - -### `TestServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, *client.Client)` - -Создаёт полноценный `grpc.Server` с переданным `BackendServiceServer` и возвращает его вместе с клиентом. Подходит для end-to-end тестов. - -Автоматически управляет закрытием ресурсов (`Shutdown` сервера и `Close` клиента) по окончании теста. - -## Usage - -### Create mock gRPC server and mock handler - -```go -package mypkg_test - -import ( - "testing" - - "github.com/txix-open/isp-kit/grpct" - "github.com/txix-open/isp-kit/test" -) - -func TestExample(t *testing.T) { - testCtx := test.New(t) - mockSrv, cli := grpct.NewMock(testCtx) - mockSrv.Mock("/example.Service/Method", handlerFn) - - resp, err := cli.Invoke(testCtx.Context(), "/example.Service/Method", req, &reply) - testCtx.Assert().NoError(err) - testCtx.Assert().Equal(expected, reply) -} -``` - -### Create test gRPC server from implementation - -```go -import ( - "testing" - - "github.com/txix-open/isp-kit/grpct" - "github.com/txix-open/isp-kit/test" -) - -func TestRealService(t *testing.T) { - testCtx := test.New(t) - srv, cli := grpct.TestServer(testCtx, myServiceImpl) - - resp, err := cli.Invoke(testCtx.Context(), "/my.Service/Endpoint", req, &reply) - testCtx.Assert().NoError(err) - testCtx.Assert().Equal(expected, reply) - - _ = srv // используется для дополнительных проверок, если необходимо -} -``` diff --git a/vendor/github.com/txix-open/isp-kit/test/grpct/test_grpc.go b/vendor/github.com/txix-open/isp-kit/test/grpct/test_grpc.go deleted file mode 100644 index 8cec82e..0000000 --- a/vendor/github.com/txix-open/isp-kit/test/grpct/test_grpc.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package grpct provides test helpers for gRPC server and client operations. -// It creates mock gRPC servers on random local ports for testing. -package grpct - -import ( - "net" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/client" - "github.com/txix-open/isp-kit/grpc/endpoint" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/test" -) - -// MockServer provides a mock gRPC server for testing. -// It allows registering handlers for specific endpoints. -type MockServer struct { - Wrapper endpoint.Wrapper - srv *grpc.Server - router *grpc.Mux -} - -// NewMock creates a new mock gRPC server and client pair. -// The server listens on a random local port and is automatically -// shut down when the test completes. -func NewMock(t *test.Test) (*MockServer, *client.Client) { - srv, cli := TestServer(t, grpc.NewMux()) - router := grpc.NewMux() - srv.Upgrade(router) - return &MockServer{ - Wrapper: endpoint.DefaultWrapper(t.Logger()), - srv: srv, - router: router, - }, cli -} - -// Mock registers a handler for the specified endpoint. -// Returns the MockServer for method chaining. -func (m *MockServer) Mock(endpoint string, handler any) *MockServer { - m.router.Handle(endpoint, m.Wrapper.Endpoint(handler)) - return m -} - -// TestServer creates and starts a gRPC server with the provided service, -// returning both the server and a configured client. The server listens -// on a random local port and is automatically shut down when the test completes. -func TestServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, *client.Client) { - assert := t.Assert() - - var lc net.ListenConfig - listener, err := lc.Listen(t.T().Context(), "tcp", "127.0.0.1:") - assert.NoError(err) - srv := grpc.NewServer() - cli, err := client.Default() - assert.NoError(err) - t.T().Cleanup(func() { - err := cli.Close() - assert.NoError(err) - srv.Shutdown() - }) - srv.Upgrade(service) - go func() { - err := srv.Serve(listener) - assert.NoError(err) - }() - - cli.Upgrade([]string{listener.Addr().String()}) - return srv, cli -} diff --git a/vendor/github.com/txix-open/isp-kit/test/httpt/README.md b/vendor/github.com/txix-open/isp-kit/test/httpt/README.md new file mode 100644 index 0000000..6f2e884 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/test/httpt/README.md @@ -0,0 +1,72 @@ +# Package `httpt` + +Пакет `httpt` предназначен для упрощения написания HTTP-тестов (юнит- и интеграционных) с использованием клиента и сервера на базе `isp-kit`. + +## Types + +### MockServer + +Структура `MockServer` представляет собой обёртку над HTTP-сервером, позволяющую удобно мокать отдельные endpoint'ы с использованием `endpoint.Wrapper` и роутера `router.Router`. + +**Methods:** + +#### `NewMock(t *test.Test) *MockServer` + +Создаёт `MockServer`, автоматически запускает сервер и регистрирует его закрытие в `t.Cleanup`. Подходит для юнит-тестов с ручной маршрутизацией и моками. + +#### `(m *MockServer) POST(path string, handler any) *MockServer` + +Регистрирует POST-обработчик на указанный путь. + +#### `(m *MockServer) GET(path string, handler any) *MockServer` + +Регистрирует GET-обработчик на указанный путь. + +#### `(m *MockServer) Mock(method string, path string, handler any) *MockServer` + +Регистрирует обработчик на указанный путь и метод с использованием `Wrapper.Endpoint`. + +#### `(m *MockServer) Client(opts ...httpcli.Option) *httpcli.Client` + +Создаёт HTTP-клиент, настроенный на тестовый сервер. + +#### `(m *MockServer) BaseURL() string` + +Возвращает базовый URL тестового сервера. + +## Functions + +### `TestServer(t *test.Test, handler http.Handler, opts ...httpcli.Option) (*httptest.Server, *httpcli.Client)` + +Создаёт `httptest.Server` с указанным HTTP-обработчиком и возвращает его вместе с клиентом `httpcli.Client`. Подходит для end-to-end тестов. + +Автоматически управляет закрытием ресурсов (`srv.Close`) по окончании теста. + +## Usage + +### Example usage in test + +```go +package mypkg_test + +import ( + "net/http" + "testing" + + "github.com/txix-open/isp-kit/http/httpt" + "github.com/txix-open/isp-kit/test" +) + +func TestExample(t *testing.T) { + testCtx := test.New(t) + srv, cli := httpt.TestServer(testCtx, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("ok")) + })) + + resp, err := cli.Get("/") + testCtx.Assert().NoError(err) + testCtx.Assert().Equal(200, resp.StatusCode) + testCtx.Assert().BodyEqual(resp, "ok") + _ = srv // для дополнительных проверок, если нужно +} +``` diff --git a/vendor/github.com/txix-open/isp-kit/test/httpt/server.go b/vendor/github.com/txix-open/isp-kit/test/httpt/server.go new file mode 100644 index 0000000..9c43b1b --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/test/httpt/server.go @@ -0,0 +1,20 @@ +package httpt + +import ( + "net/http" + "net/http/httptest" + + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/http/httpclix" + "github.com/txix-open/isp-kit/test" +) + +// TestServer creates and starts an HTTP test server with the provided handler, +// returning both the server and a configured client. The server listens on +// a random local port and the client is pre-configured with the server's URL. +func TestServer(t *test.Test, handler http.Handler, opts ...httpcli.Option) (*httptest.Server, *httpcli.Client) { + srv := httptest.NewServer(handler) + cli := httpclix.Default(opts...) + cli.GlobalRequestConfig().BaseUrl = srv.URL + return srv, cli +} diff --git a/vendor/github.com/txix-open/isp-kit/test/httpt/test_http.go b/vendor/github.com/txix-open/isp-kit/test/httpt/test_http.go new file mode 100644 index 0000000..0c65f08 --- /dev/null +++ b/vendor/github.com/txix-open/isp-kit/test/httpt/test_http.go @@ -0,0 +1,72 @@ +// Package httpt provides test helpers for HTTP server and client operations. +// It creates mock HTTP servers on random local ports for testing. +package httpt + +import ( + "net/http" + "net/http/httptest" + + "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint/httplog" + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/http/router" + "github.com/txix-open/isp-kit/test" +) + +// MockServer provides a mock HTTP server for testing. +// It uses httptest.Server and allows registering handlers for specific +// HTTP methods and paths. +type MockServer struct { + Wrapper endpoint.Wrapper + srv *httptest.Server + router *router.Router +} + +// NewMock creates a new mock HTTP server. +// The server listens on a random local port and is automatically +// shut down when the test completes. +func NewMock(t *test.Test) *MockServer { + router := router.New() + srv := httptest.NewServer(router) + t.T().Cleanup(func() { + srv.Close() + }) + wrapper := endpoint.DefaultWrapper(t.Logger(), httplog.Log(t.Logger(), true)) + return &MockServer{ + Wrapper: wrapper, + srv: srv, + router: router, + } +} + +// Client creates a new HTTP client configured to send requests to the +// mock server's base URL. Optional client configuration can be provided. +func (m *MockServer) Client(opts ...httpcli.Option) *httpcli.Client { + cli := httpcli.New(opts...) + cli.GlobalRequestConfig().BaseUrl = m.BaseURL() + return cli +} + +// BaseURL returns the base URL of the mock server. +func (m *MockServer) BaseURL() string { + return m.srv.URL +} + +// POST registers a handler for POST requests at the specified path. +// Returns the MockServer for method chaining. +func (m *MockServer) POST(path string, handler any) *MockServer { + return m.Mock(http.MethodPost, path, handler) +} + +// GET registers a handler for GET requests at the specified path. +// Returns the MockServer for method chaining. +func (m *MockServer) GET(path string, handler any) *MockServer { + return m.Mock(http.MethodGet, path, handler) +} + +// Mock registers a handler for the specified HTTP method and path. +// Returns the MockServer for method chaining. +func (m *MockServer) Mock(method string, path string, handler any) *MockServer { + m.router.Handler(method, path, m.Wrapper.Endpoint(handler)) + return m +} diff --git a/vendor/google.golang.org/grpc/resolver/manual/manual.go b/vendor/google.golang.org/grpc/resolver/manual/manual.go deleted file mode 100644 index 82fcc2e..0000000 --- a/vendor/google.golang.org/grpc/resolver/manual/manual.go +++ /dev/null @@ -1,130 +0,0 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package manual defines a resolver that can be used to manually send resolved -// addresses to ClientConn. -package manual - -import ( - "sync" - - "google.golang.org/grpc/resolver" -) - -// NewBuilderWithScheme creates a new manual resolver builder with the given -// scheme. Every instance of the manual resolver may only ever be used with a -// single grpc.ClientConn. Otherwise, bad things will happen. -func NewBuilderWithScheme(scheme string) *Resolver { - return &Resolver{ - BuildCallback: func(resolver.Target, resolver.ClientConn, resolver.BuildOptions) {}, - UpdateStateCallback: func(error) {}, - ResolveNowCallback: func(resolver.ResolveNowOptions) {}, - CloseCallback: func() {}, - scheme: scheme, - } -} - -// Resolver is also a resolver builder. -// It's build() function always returns itself. -type Resolver struct { - // BuildCallback is called when the Build method is called. Must not be - // nil. Must not be changed after the resolver may be built. - BuildCallback func(resolver.Target, resolver.ClientConn, resolver.BuildOptions) - // UpdateStateCallback is called when the UpdateState method is called on - // the resolver. The value passed as argument to this callback is the value - // returned by the resolver.ClientConn. Must not be nil. Must not be - // changed after the resolver may be built. - UpdateStateCallback func(err error) - // ResolveNowCallback is called when the ResolveNow method is called on the - // resolver. Must not be nil. Must not be changed after the resolver may - // be built. - ResolveNowCallback func(resolver.ResolveNowOptions) - // CloseCallback is called when the Close method is called. Must not be - // nil. Must not be changed after the resolver may be built. - CloseCallback func() - scheme string - - // Fields actually belong to the resolver. - // Guards access to below fields. - mu sync.Mutex - cc resolver.ClientConn - // Storing the most recent state update makes this resolver resilient to - // restarts, which is possible with channel idleness. - lastSeenState *resolver.State -} - -// InitialState adds initial state to the resolver so that UpdateState doesn't -// need to be explicitly called after Dial. -func (r *Resolver) InitialState(s resolver.State) { - r.lastSeenState = &s -} - -// Build returns itself for Resolver, because it's both a builder and a resolver. -func (r *Resolver) Build(target resolver.Target, cc resolver.ClientConn, opts resolver.BuildOptions) (resolver.Resolver, error) { - r.mu.Lock() - defer r.mu.Unlock() - // Call BuildCallback after locking to avoid a race when UpdateState or CC - // is called before Build returns. - r.BuildCallback(target, cc, opts) - r.cc = cc - if r.lastSeenState != nil { - err := r.cc.UpdateState(*r.lastSeenState) - go r.UpdateStateCallback(err) - } - return r, nil -} - -// Scheme returns the manual resolver's scheme. -func (r *Resolver) Scheme() string { - return r.scheme -} - -// ResolveNow is a noop for Resolver. -func (r *Resolver) ResolveNow(o resolver.ResolveNowOptions) { - r.ResolveNowCallback(o) -} - -// Close is a noop for Resolver. -func (r *Resolver) Close() { - r.CloseCallback() -} - -// UpdateState calls UpdateState(s) on the channel. If the resolver has not -// been Built before, this instead sets the initial state of the resolver, like -// InitialState. -func (r *Resolver) UpdateState(s resolver.State) { - r.mu.Lock() - defer r.mu.Unlock() - r.lastSeenState = &s - if r.cc == nil { - return - } - err := r.cc.UpdateState(s) - r.UpdateStateCallback(err) -} - -// CC returns r's ClientConn when r was last Built. Panics if the resolver has -// not been Built before. -func (r *Resolver) CC() resolver.ClientConn { - r.mu.Lock() - defer r.mu.Unlock() - if r.cc == nil { - panic("Manual resolver instance has not yet been built.") - } - return r.cc -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 00ede41..abe0d19 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -239,9 +239,6 @@ github.com/txix-open/isp-kit/dbx/migration github.com/txix-open/isp-kit/errors github.com/txix-open/isp-kit/grpc github.com/txix-open/isp-kit/grpc/apierrors -github.com/txix-open/isp-kit/grpc/client -github.com/txix-open/isp-kit/grpc/client/request -github.com/txix-open/isp-kit/grpc/endpoint github.com/txix-open/isp-kit/grpc/isp github.com/txix-open/isp-kit/healthcheck github.com/txix-open/isp-kit/http @@ -262,15 +259,11 @@ github.com/txix-open/isp-kit/log/logutil github.com/txix-open/isp-kit/metrics github.com/txix-open/isp-kit/metrics/app_metrics github.com/txix-open/isp-kit/metrics/bgjob_metrics -github.com/txix-open/isp-kit/metrics/grpc_metrics github.com/txix-open/isp-kit/metrics/http_metrics github.com/txix-open/isp-kit/metrics/pgx_metrics github.com/txix-open/isp-kit/metrics/sql_metrics github.com/txix-open/isp-kit/observability/sentry github.com/txix-open/isp-kit/observability/tracing -github.com/txix-open/isp-kit/observability/tracing/grpc -github.com/txix-open/isp-kit/observability/tracing/grpc/client_tracing -github.com/txix-open/isp-kit/observability/tracing/grpc/server_tracing github.com/txix-open/isp-kit/observability/tracing/http/client_tracing github.com/txix-open/isp-kit/observability/tracing/http/semconvutil github.com/txix-open/isp-kit/observability/tracing/http/server_tracing @@ -283,7 +276,7 @@ github.com/txix-open/isp-kit/shutdown github.com/txix-open/isp-kit/test github.com/txix-open/isp-kit/test/dbt github.com/txix-open/isp-kit/test/fake -github.com/txix-open/isp-kit/test/grpct +github.com/txix-open/isp-kit/test/httpt github.com/txix-open/isp-kit/test/rct github.com/txix-open/isp-kit/validator # github.com/txix-open/jsonschema v1.3.0 @@ -507,7 +500,6 @@ google.golang.org/grpc/metadata google.golang.org/grpc/peer google.golang.org/grpc/resolver google.golang.org/grpc/resolver/dns -google.golang.org/grpc/resolver/manual google.golang.org/grpc/serviceconfig google.golang.org/grpc/stats google.golang.org/grpc/status From 3e707244dd822dd185746f2add08f2e0f17addf7 Mon Sep 17 00:00:00 2001 From: chashintv Date: Thu, 19 Nov 2026 20:02:12 +0300 Subject: [PATCH 03/13] MSP-8974 fix tests for http --- auth/auth.go | 115 +++++++++ controller/audit.go | 6 +- controller/auth.go | 33 ++- controller/role.go | 23 +- controller/secure.go | 2 +- controller/ui_settings.go | 6 +- controller/user.go | 44 ++-- domain/errors.go | 13 + domain/grpc_error.go | 7 - go.mod | 18 +- tests/audit_test.go | 12 +- tests/auth_test.go | 44 ++-- tests/ui_settings_test.go | 11 +- tests/user_test.go | 97 ++++--- .../txix-open/isp-kit/grpc/README.md | 148 ----------- .../isp-kit/grpc/apierrors/README.md | 102 -------- .../txix-open/isp-kit/grpc/apierrors/error.go | 149 ----------- .../txix-open/isp-kit/grpc/auth_data.go | 115 --------- .../txix-open/isp-kit/grpc/common.go | 16 -- .../txix-open/isp-kit/grpc/encoding.go | 9 - .../isp-kit/grpc/isp/backed_service.pb.go | 241 ------------------ .../isp-kit/grpc/isp/backed_service.proto | 23 -- .../grpc/isp/backed_service_grpc.pb.go | 176 ------------- .../github.com/txix-open/isp-kit/grpc/mux.go | 71 ------ .../txix-open/isp-kit/grpc/server.go | 118 --------- vendor/modules.txt | 3 - 26 files changed, 289 insertions(+), 1313 deletions(-) create mode 100644 auth/auth.go delete mode 100644 domain/grpc_error.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/apierrors/README.md delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/auth_data.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/common.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/encoding.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.pb.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.proto delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service_grpc.pb.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/mux.go delete mode 100644 vendor/github.com/txix-open/isp-kit/grpc/server.go diff --git a/auth/auth.go b/auth/auth.go new file mode 100644 index 0000000..8213e91 --- /dev/null +++ b/auth/auth.go @@ -0,0 +1,115 @@ +package auth + +import ( + "net/http" + "strconv" + + "github.com/txix-open/isp-kit/errors" +) + +const ( + // ApplicationIdHeader is the header key for application identity. + ApplicationIdHeader = "x-application-identity" + // ApplicationNameHeader is the header key for application name. + ApplicationNameHeader = "x-application-name" + // UserIdHeader is the header key for user identity. + UserIdHeader = "x-user-identity" + // DeviceIdHeader is the header key for device identity. + DeviceIdHeader = "x-device-identity" + // ServiceIdHeader is the header key for service identity. + ServiceIdHeader = "x-service-identity" + // DomainIdHeader is the header key for domain identity. + DomainIdHeader = "x-domain-identity" + // SystemIdHeader is the header key for system identity. + SystemIdHeader = "x-system-identity" + // UserTokenHeader is the header key for user token. + UserTokenHeader = "x-user-token" + // DeviceTokenHeader is the header key for device token. + DeviceTokenHeader = "x-device-token" +) + +// AuthData wraps http.Header to provide structured access to authentication +// and authorization information from http request header. +// All methods return an error if the key is not found or cannot be parsed. +type AuthData http.Header + +// SystemId extracts the system identity from header as an integer. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func (i AuthData) SystemId() (int, error) { + return IntFromHeader(SystemIdHeader, http.Header(i)) +} + +// DomainId extracts the domain identity from header as an integer. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func (i AuthData) DomainId() (int, error) { + return IntFromHeader(DomainIdHeader, http.Header(i)) +} + +// ServiceId extracts the service identity from header as an integer. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func (i AuthData) ServiceId() (int, error) { + return IntFromHeader(ServiceIdHeader, http.Header(i)) +} + +// ApplicationId extracts the application identity from header as an integer. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func (i AuthData) ApplicationId() (int, error) { + return IntFromHeader(ApplicationIdHeader, http.Header(i)) +} + +// ApplicationName extracts the application name from header as a string. +// Returns an error if the key is not found. +func (i AuthData) ApplicationName() (string, error) { + return StringFromHeader(ApplicationNameHeader, http.Header(i)) +} + +// UserId extracts the user identity from header as an integer. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func (i AuthData) UserId() (int, error) { + return IntFromHeader(UserIdHeader, http.Header(i)) +} + +// DeviceId extracts the device identity from header as an integer. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func (i AuthData) DeviceId() (int, error) { + return IntFromHeader(DeviceIdHeader, http.Header(i)) +} + +// UserToken extracts the user token from header as a string. +// Returns an error if the key is not found. +func (i AuthData) UserToken() (string, error) { + return StringFromHeader(UserTokenHeader, http.Header(i)) +} + +// DeviceToken extracts the device token from header as a string. +// Returns an error if the key is not found. +func (i AuthData) DeviceToken() (string, error) { + return StringFromHeader(DeviceTokenHeader, http.Header(i)) +} + +// StringFromHeader extracts a string value from header by key. +// Returns an error if header is nil or the key is not found. +func StringFromHeader(key string, h http.Header) (string, error) { + if h == nil { + return "", errors.New("header is nil") + } + values := h.Values(key) + if len(values) == 0 { + return "", errors.Errorf("'%s' is expected in header", key) + } + return values[0], nil +} + +// IntFromHeader extracts an integer value from header by key. +// Returns an error if the key is not found or the value cannot be parsed as an integer. +func IntFromHeader(key string, h http.Header) (int, error) { + value, err := StringFromHeader(key, h) + if err != nil { + return 0, err + } + intValue, err := strconv.Atoi(value) + if err != nil { + return 0, errors.WithMessagef(err, "parse '%s' to int", key) + } + return intValue, nil +} diff --git a/controller/audit.go b/controller/audit.go index 396ce80..c29282f 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -2,12 +2,12 @@ package controller import ( "context" + "net/http" "isp-admin-service/domain" "github.com/txix-open/isp-kit/errors" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + "github.com/txix-open/isp-kit/http/apierrors" ) type AuditService interface { @@ -80,7 +80,7 @@ func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error err := c.service.SetEvents(ctx, req) switch { case errors.As(err, &domain.UnknownAuditEventError{}): - return status.Error(codes.InvalidArgument, err.Error()) + return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err) default: return err } diff --git a/controller/auth.go b/controller/auth.go index d9da2cc..51a0e25 100644 --- a/controller/auth.go +++ b/controller/auth.go @@ -2,16 +2,15 @@ package controller import ( "context" + "net/http" "strconv" + "isp-admin-service/auth" "isp-admin-service/domain" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc" + "github.com/txix-open/isp-kit/http/apierrors" "github.com/txix-open/isp-kit/log" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" ) type authService interface { @@ -43,8 +42,8 @@ func NewAuth(authService authService, logger log.Logger) Auth { // @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Failure 500 {object} domain.GrpcError // @Router /auth/logout [POST] -func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error { - adminId, err := getAdminId(authData) +func (a Auth) Logout(ctx context.Context, r *http.Request) error { + adminId, err := getAdminId(r) if err != nil { return err } @@ -69,8 +68,8 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error { // @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Failure 500 {object} domain.GrpcError // @Router /auth/logout_with_reason [POST] -func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error { - adminId, err := getAdminId(authData) +func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error { + adminId, err := getAdminId(r) if err != nil { return err } @@ -100,12 +99,12 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma switch { case errors.Is(err, domain.ErrOauthAuthorization): - return nil, status.Error(codes.InvalidArgument, "plain auth is not available") + return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err) case errors.Is(err, domain.ErrUnauthenticated): a.logger.Error(ctx, err.Error()) - return nil, status.Error(codes.Unauthenticated, "invalid credential") + return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err) case errors.Is(err, domain.ErrTooManyLoginRequests): - return nil, status.Error(codes.ResourceExhausted, "too many requests") + return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "login") default: @@ -130,9 +129,9 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque switch { case errors.Is(err, domain.ErrOauthIsMissed): - return nil, status.Error(codes.FailedPrecondition, "oauth is not configured") + return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err) case errors.Is(err, domain.ErrUnauthenticated): - return nil, status.Error(codes.Unauthenticated, "invalid code") + return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "login with oauth") default: @@ -140,15 +139,15 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque } } -func getAdminId(authData grpc.AuthData) (int64, error) { - token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData)) +func getAdminId(r *http.Request) (int64, error) { + token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header) if err != nil { - return 0, status.Error(codes.InvalidArgument, err.Error()) + return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err) } adminId, err := strconv.Atoi(token) if err != nil { - return 0, status.Error(codes.InvalidArgument, "admin id is not a number") + return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err) } return int64(adminId), nil diff --git a/controller/role.go b/controller/role.go index e4f8deb..7dbc61c 100644 --- a/controller/role.go +++ b/controller/role.go @@ -2,13 +2,12 @@ package controller import ( "context" + "net/http" "isp-admin-service/domain" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + "github.com/txix-open/isp-kit/http/apierrors" ) type roleService interface { @@ -62,8 +61,8 @@ func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role // @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует" // @Failure 500 {object} domain.GrpcError // @Router /role/create [POST] -func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) { - adminId, err := getAdminId(authData) +func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) { + adminId, err := getAdminId(r) if err != nil { return nil, err } @@ -71,7 +70,7 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain role, err := u.roleService.Create(ctx, req, adminId) switch { case errors.Is(err, domain.ErrAlreadyExists): - return nil, status.Error(codes.AlreadyExists, "role with current name already exists") + return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "create role") default: @@ -92,8 +91,8 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain // @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует" // @Failure 500 {object} domain.GrpcError // @Router /role/update [POST] -func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) { - adminId, err := getAdminId(authData) +func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) { + adminId, err := getAdminId(r) if err != nil { return nil, err } @@ -101,9 +100,9 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain result, err := u.roleService.Update(ctx, req, adminId) switch { case errors.Is(err, domain.ErrNotFound): - return nil, status.Error(codes.NotFound, "role not found") + return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err) case errors.Is(err, domain.ErrAlreadyExists): - return nil, status.Error(codes.AlreadyExists, "role with current name already exists") + return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "update role") default: @@ -123,8 +122,8 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Failure 500 {object} domain.GrpcError // @Router /role/delete [POST] -func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error { - adminId, err := getAdminId(authData) +func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error { + adminId, err := getAdminId(r) if err != nil { return err } diff --git a/controller/secure.go b/controller/secure.go index 0c4907d..3b79e11 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -6,7 +6,7 @@ import ( "isp-admin-service/domain" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/apierrors" + "github.com/txix-open/isp-kit/http/apierrors" ) type SecureService interface { diff --git a/controller/ui_settings.go b/controller/ui_settings.go index 8cf500b..e3c67e4 100644 --- a/controller/ui_settings.go +++ b/controller/ui_settings.go @@ -3,10 +3,10 @@ package controller import ( "context" "isp-admin-service/domain" + "net/http" "github.com/txix-open/isp-kit/errors" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + "github.com/txix-open/isp-kit/http/apierrors" ) type UiSettingsService interface { @@ -39,7 +39,7 @@ func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequ resp, err := c.service.OauthSettings(ctx, req) switch { case errors.Is(err, domain.ErrUnknownClient): - return nil, status.Error(codes.Unauthenticated, "invalid client name") + return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err) case err != nil: return nil, err default: diff --git a/controller/user.go b/controller/user.go index c179af8..4eb8c17 100644 --- a/controller/user.go +++ b/controller/user.go @@ -2,15 +2,13 @@ package controller import ( "context" + "net/http" - "github.com/txix-open/isp-kit/grpc/apierrors" + "github.com/txix-open/isp-kit/http/apierrors" "isp-admin-service/domain" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type userService interface { @@ -47,8 +45,8 @@ func NewUser(userService userService) User { // @Failure 404 {object} domain.GrpcError "Пользователя не существует" // @Failure 500 {object} domain.GrpcError // @Router /user/get_profile [POST] -func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) { - adminId, err := getAdminId(authData) +func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) { + adminId, err := getAdminId(r) if err != nil { return nil, err } @@ -56,9 +54,9 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A profile, err := u.userService.GetProfileById(ctx, adminId) switch { case errors.Is(err, domain.ErrUnauthenticated): - return nil, status.Error(codes.Unauthenticated, "user is blocked") + return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err) case errors.Is(err, domain.ErrNotFound): - return nil, status.Error(codes.NotFound, "user not found") + return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "get profile") default: @@ -127,8 +125,8 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { // @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует" // @Failure 500 {object} domain.GrpcError // @Router /user/create_user [POST] -func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) { - adminId, err := getAdminId(authData) +func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) { + adminId, err := getAdminId(r) if err != nil { return nil, err } @@ -136,7 +134,7 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain user, err := u.userService.CreateUser(ctx, req, adminId) switch { case errors.Is(err, domain.ErrAlreadyExists): - return nil, status.Error(codes.AlreadyExists, "user with the same email already exists") + return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "create user") default: @@ -158,8 +156,8 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain // @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует" // @Failure 500 {object} domain.GrpcError // @Router /user/update_user [POST] -func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) { - adminId, err := getAdminId(authData) +func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) { + adminId, err := getAdminId(r) if err != nil { return nil, err } @@ -167,11 +165,11 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain result, err := u.userService.UpdateUser(ctx, req, adminId) switch { case errors.Is(err, domain.ErrNotFound): - return nil, status.Error(codes.NotFound, "user not found") + return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err) case errors.Is(err, domain.ErrInvalid): - return nil, status.Error(codes.InvalidArgument, "user modification is not available") + return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err) case errors.Is(err, domain.ErrAlreadyExists): - return nil, status.Error(codes.AlreadyExists, "user with the same email already exists") + return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err) case err != nil: return nil, errors.WithMessage(err, "update user") default: @@ -191,8 +189,8 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Failure 500 {object} domain.GrpcError // @Router /user/delete_user [POST] -func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) { - adminId, err := getAdminId(authData) +func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) { + adminId, err := getAdminId(r) if err != nil { return nil, err } @@ -216,8 +214,8 @@ func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities // @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Failure 500 {object} domain.GrpcError // @Router /user/block_user [POST] -func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error { - adminId, err := getAdminId(authData) +func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error { + adminId, err := getAdminId(r) if err != nil { return err } @@ -254,8 +252,8 @@ func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain // @Failure 400 {object} apierrors.Error "Невалидное тело запроса" // @Failure 500 {object} apierrors.Error "внутренняя ошибка" // @Router /user/change_password [POST] -func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error { - adminId, err := getAdminId(authData) +func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error { + adminId, err := getAdminId(r) if err != nil { return err } @@ -263,7 +261,7 @@ func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req do err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword) switch { case errors.Is(err, domain.ErrInvalidPassword): - return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err) + return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err) case err != nil: return apierrors.NewInternalServiceError(err) default: diff --git a/domain/errors.go b/domain/errors.go index 58aef3e..ec89a31 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -26,6 +26,19 @@ var ( ErrUnknownClient = errors.New("unknown client") ) +var ( + UnknownAuditEventErrorCode = 1 + ErrOauthAuthorizationCode = 2 + ErrUnauthenticatedCode = 3 + ErrTooManyLoginRequestsCode = 4 + ErrOauthIsMissedCode = 5 + ErrAlreadyExistsCode = 6 + ErrNotFoundCode = 7 + ErrUnknownClientCode = 8 + ErrInvalidCode = 9 + ErrInvalidPasswordCode = 10 +) + type UnknownAuditEventError struct { Event string } diff --git a/domain/grpc_error.go b/domain/grpc_error.go deleted file mode 100644 index 841bcbe..0000000 --- a/domain/grpc_error.go +++ /dev/null @@ -1,7 +0,0 @@ -package domain - -type GrpcError struct { - ErrorMessage string `json:"errorMessage"` - ErrorCode string `json:"errorCode"` - Details []any `json:"details"` -} diff --git a/go.mod b/go.mod index 064bb57..10c42ba 100644 --- a/go.mod +++ b/go.mod @@ -10,9 +10,8 @@ require ( github.com/txix-open/bgjob v1.6.0 github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/jsonschema v1.3.0 - golang.org/x/crypto v0.59.0 - golang.org/x/sync v0.25.0 - google.golang.org/grpc v1.85.0 + golang.org/x/crypto v0.55.0 + golang.org/x/sync v0.22.0 ) require ( @@ -74,12 +73,13 @@ require ( go.opentelemetry.io/proto/otlp v1.11.1 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect - go.yaml.in/yaml/v3 v3.0.6 // indirect - golang.org/x/net v0.63.0 // indirect - golang.org/x/sys v0.50.0 // indirect - golang.org/x/text v0.44.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect + golang.org/x/net v0.58.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect + google.golang.org/grpc v1.83.2 // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/tests/audit_test.go b/tests/audit_test.go index 4715805..10fc917 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -1,6 +1,7 @@ package tests_test import ( + "net/http" "testing" "time" @@ -16,8 +17,6 @@ import ( "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/httpt" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) func TestAuditSuite(t *testing.T) { @@ -173,11 +172,14 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() { {Event: entity.EventUserChanged, Enabled: true}, {Event: "новый#2", Enabled: false}, }). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - status, isStatus := status.FromError(err) - s.Require().True(isStatus) - s.Require().Equal(codes.InvalidArgument, status.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) // не уверен тут какой код проверять? Статус или внутренний? Коммент чтобы не забыть + } func (s *AuditSuite) Test_All_Logs() { diff --git a/tests/auth_test.go b/tests/auth_test.go index 2628fcf..e11bbc8 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -27,8 +27,6 @@ import ( "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) func TestAuthTestSuite(t *testing.T) { @@ -119,11 +117,13 @@ func (s *AuthTestSuite) TestLoginNotFound() { Email: "a1@a.ru", Password: "password", }). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.Unauthenticated, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode) time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() } @@ -142,11 +142,13 @@ func (s *AuthTestSuite) TestBlockedUser() { Email: "a@a.ru", Password: "password", }). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.Unauthenticated, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode) time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() } @@ -164,11 +166,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() { Email: "a@a.ru", Password: "WrongPassword", }). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.Unauthenticated, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode) time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() } @@ -204,11 +208,13 @@ func (s *AuthTestSuite) TestOauthLogin_UnknownClient() { ClientName: s.oauthClientName + fake.It[string](), }). JsonResponseBody(&response). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.Unauthenticated, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode) } func (s *AuthTestSuite) Test_Logout_HappyPath() { @@ -297,14 +303,18 @@ func (s *AuthTestSuite) TestBruteForceLogin() { Password: fmt.Sprintf("password %s", strconv.Itoa(index)), }). JsonResponseBody(&response). + StatusCodeToError(). DoWithoutResponse(ctx) s.Require().Error(err) - switch status.Code(err) { // nolint:exhaustive - case codes.ResourceExhausted: + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + + switch httpErr.StatusCode { // nolint:exhaustive + case http.StatusTooManyRequests: tooManyRequestsErrorCount.Add(1) s.Require().True(time.Since(start) < time.Second) - case codes.Unauthenticated: + case http.StatusUnauthorized: unauthorizedErrorCount.Add(1) s.Require().True(time.Since(start) > time.Second) default: diff --git a/tests/ui_settings_test.go b/tests/ui_settings_test.go index 8f5a407..a507093 100644 --- a/tests/ui_settings_test.go +++ b/tests/ui_settings_test.go @@ -4,6 +4,7 @@ import ( "isp-admin-service/assembly" "isp-admin-service/conf" "isp-admin-service/domain" + "net/http" "net/url" "testing" @@ -12,8 +13,6 @@ import ( "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/fake" "github.com/txix-open/isp-kit/test/httpt" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type UiSettingsSuite struct { @@ -97,9 +96,11 @@ func (s *UiSettingsSuite) Test_UnknownClient() { JsonRequestBody(domain.ClientNameRequest{ ClientName: s.oauthClientSetting.ClientName + fake.It[string](), }). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.Unauthenticated, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode) } diff --git a/tests/user_test.go b/tests/user_test.go index 2e6e84b..0eea1e9 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -2,11 +2,12 @@ package tests_test import ( "context" + "encoding/json" + "net/http" "strconv" "testing" "time" - "github.com/txix-open/isp-kit/grpc/apierrors" "golang.org/x/crypto/bcrypt" "isp-admin-service/assembly" @@ -23,8 +24,6 @@ import ( "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/httpt" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) type tokenService interface { @@ -89,7 +88,7 @@ func (s *UserTestSuite) TestGetProfileHappyPath() { }) response := domain.AdminUserShort{} - err := s.httpCli.Post("admin/user/get_profile"). + err := s.apiCli.Post("admin/user/get_profile"). JsonResponseBody(&response). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). DoWithoutResponse(s.T().Context()) @@ -116,13 +115,14 @@ func (s *UserTestSuite) TestGetProfileNotFound() { Password: "password", }) - err := s.httpCli.Post("admin/user/get_profile"). + err := s.apiCli.Post("admin/user/get_profile"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.NotFound, st.Code()) + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusNotFound, httpErr.StatusCode) } func (s *UserTestSuite) TestGetProfileOauth() { @@ -144,7 +144,7 @@ func (s *UserTestSuite) TestGetProfileOauth() { }) response := domain.AdminUserShort{} - err := s.httpCli. + err := s.apiCli. Post("admin/user/get_profile"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonResponseBody(&response). @@ -183,7 +183,7 @@ func (s *UserTestSuite) TestGetUsers() { email := "a1@" response := domain.UsersResponse{} - err := s.httpCli.Post("admin/user/get_users"). + err := s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ LimitOffsetParams: domain.LimitOffsetParams{ Limit: 5, @@ -211,7 +211,7 @@ func (s *UserTestSuite) TestGetUsers() { s.Require().EqualValues(roles, response.Items[1].Roles) email = "test@mail.ru" - err = s.httpCli.Post("admin/user/get_users"). + err = s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ LimitOffsetParams: domain.LimitOffsetParams{ Limit: 10, @@ -250,7 +250,10 @@ func (s *UserTestSuite) TestAllGetUsers() { InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)}) response := domain.UsersResponse{} - err := s.httpCli.Post("admin/user/get_all_users").JsonResponseBody(&response).DoWithoutResponse(s.T().Context()) + err := s.apiCli.Post("admin/user/get_all_users"). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 7) @@ -295,7 +298,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() { }) response := domain.UsersResponse{} - err = s.httpCli.Post("admin/user/get_users"). + err = s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ LimitOffsetParams: domain.LimitOffsetParams{ Limit: 5, @@ -331,7 +334,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() { userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"}) response := domain.UsersResponse{} - err := s.httpCli.Post("admin/user/get_users"). + err := s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ LimitOffsetParams: domain.LimitOffsetParams{ Limit: 10, @@ -363,7 +366,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() { s.db.Must().SelectRow(&preCount, "select count(*) from users") response := entity.User{} - err := s.httpCli. + err := s.apiCli. Post("admin/user/create_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.CreateUserRequest{ @@ -391,7 +394,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() { s.db.Must().SelectRow(&preCount, "select count(*) from users") response := entity.User{} - err := s.httpCli. + err := s.apiCli. Post("admin/user/create_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.CreateUserRequest{ @@ -414,7 +417,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() { func (s *UserTestSuite) TestCreateUserAlreadyExist() { id := InsertUser(s.db, entity.User{Email: "exists@a.ru"}) - err := s.httpCli. + err := s.apiCli. Post("admin/user/create_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(domain.CreateUserRequest{ @@ -423,11 +426,13 @@ func (s *UserTestSuite) TestCreateUserAlreadyExist() { Email: "exists@a.ru", Password: "password", }). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.AlreadyExists, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusConflict, httpErr.StatusCode) } func (s *AuthTestSuite) TestUpdateUserHappyPath() { @@ -439,8 +444,7 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() { Email: "update@a.ru", } response := domain.User{} - err := s.httpCli. - Post("admin/user/update_user"). + err := s.httpCli.Post("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(req). JsonResponseBody(&response). @@ -466,8 +470,7 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() { Email: "oauth@a.ru", } response := domain.User{} - err := s.httpCli. - Post("admin/user/update_user"). + err := s.httpCli.Post("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(req). JsonResponseBody(&response). @@ -494,15 +497,16 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() { LastName: "surname", Email: "a_exists@a.ru", } - err := s.httpCli. - Post("admin/user/update_user"). + err := s.httpCli.Post("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(req). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.AlreadyExists, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusConflict, httpErr.StatusCode) } func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() { @@ -517,15 +521,16 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() { LastName: "surname", Email: "a_exists@a.ru", } - err := s.httpCli. - Post("admin/user/update_user"). + err := s.httpCli.Post("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(req). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.AlreadyExists, st.Code()) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusConflict, httpErr.StatusCode) } func (s *UserTestSuite) TestDeleteUsers() { @@ -535,7 +540,7 @@ func (s *UserTestSuite) TestDeleteUsers() { InsertUser(s.db, entity.User{Email: "a_del@c.ru"}) response := domain.DeleteResponse{} - err := s.httpCli. + err := s.apiCli. Post("admin/user/delete_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}). @@ -566,8 +571,9 @@ func (s *UserTestSuite) TestBlockUser() { UpdatedAt: time.Now(), }) - err := s.httpCli.Post("admin/user/block_user"). + err := s.apiCli.Post("admin/user/block_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). + StatusCodeToError(). JsonRequestBody(domain.IdRequest{UserId: int(id)}). DoWithoutResponse(s.T().Context()) s.Require().NoError(err) @@ -597,19 +603,30 @@ func (s *UserTestSuite) TestChangePasswordUser() { // check for err when invalid data invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"} - err := s.httpCli.Post("admin/user/change_password"). + err := s.apiCli.Post("admin/user/change_password"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). JsonRequestBody(invalidReq). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().Error(err) - err = apierrors.FromError(err) - s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword)) + + var httpErr httpcli.ErrorResponse + s.Require().ErrorAs(err, &httpErr) + s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) + + var body struct { + ErrorCode int `json:"errorCode"` + ErrorMessage string `json:"errorMessage"` + } + s.Require().NoError(json.Unmarshal(httpErr.Body, &body)) + s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode) // change password changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"} - err = s.httpCli.Post("admin/user/change_password"). + err = s.apiCli.Post("admin/user/change_password"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). JsonRequestBody(changePswReq). + StatusCodeToError(). DoWithoutResponse(s.T().Context()) s.Require().NoError(err) diff --git a/vendor/github.com/txix-open/isp-kit/grpc/README.md b/vendor/github.com/txix-open/isp-kit/grpc/README.md deleted file mode 100644 index 380bf3c..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/README.md +++ /dev/null @@ -1,148 +0,0 @@ -# Package `grpc` - -Пакет `grpc` предоставляет инструменты для создания и управления gRPC-серверами, включая обработку аутентификации, -маршрутизацию запросов и интеграцию с метаданными. -Поддерживает гибкую настройку обработчиков, безопасное обновление сервисов и работу с заголовками. - -## Types - -### Server - -gRPC-сервер с поддержкой динамического обновления обработчиков. - -**Methods:** - -#### `DefaultServer(restOptions ...grpc.ServerOption) *Server` - -Создать gRPC-сервер с настройками по умолчанию (максимальный размер сообщения 64 МБ). - -#### `NewServer(opts ...grpc.ServerOption) *Server` - -Создать кастомный сервер с указанными опциями gRPC. - -#### `(s *Server) Upgrade(service isp.BackendServiceServer)` - -Атомарно обновить обработчик сервиса без остановки сервера. - -#### `(s *Server) ListenAndServe(address string) error` - -Запустить сервер на указанном адресе. - -#### `(s *Server) Serve(listener net.Listener) error` - -Запустить сервер на существующем listener. - -#### `(s *Server) Shutdown()` - -Остановить сервер - -### Mux - -Мультиплексор для маршрутизации gRPC-запросов. Регистрирует обработчики по имени эндпоинта. - -**Methods:** - -#### `NewMux() *Mux` - -Создать новый мультиплексор. - -#### `(m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux` - -Зарегистрировать обработчик для указанного эндпоинта. - -#### `(m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error)` - -Обрабатывает входящий запрос, определяя эндпоинт через заголовок `ProxyMethodNameHeader`. - -### AuthData - -Структура для работы с метаданными аутентификации в gRPC-запросах. -Оборачивает `metadata.MD` и предоставляет методы для извлечения идентификаторов из заголовков. - -**Methods:** - -#### `(i AuthData) SystemId() (int, error)` - -Получить идентификатор системы из заголовка `x-system-identity`. - -#### `(i AuthData) DomainId() (int, error)` - -Получить идентификатор домена из заголовка `x-domain-identity`. - -#### `(i AuthData) ServiceId() (int, error)` - -Получить идентификатор сервиса из заголовка `x-service-identity`. - -#### `(i AuthData) ApplicationId() (int, error)` - -Получить идентификатор системы из заголовка `x-application-identity`. - -#### `(i AuthData) ApplicationName() (int, error)` - -Получить название системы из заголовка `x-application-name`. - -#### `(i AuthData) UserId() (int, error)` - -Получить идентификатор пользователя из заголовка `x-user-identity`. - -#### `(i AuthData) DeviceId() (int, error)` - -Получить идентификатор устройства из заголовка `x-device-identity`. - -#### `(i AuthData) UserToken() (string, error)` - -Получить токен пользователя из заголовка `x-user-token`. - -#### `(i AuthData) DeviceToken() (string, error)` - -Получить токен устройства из заголовка `x-device-token`. - -## Functions - -#### `StringFromMd(key string, md metadata.MD) (string, error)` - -Извлекает строковое значение из метаданных по ключу. - -#### `IntFromMd(key string, md metadata.MD) (int, error)` - -Извлекает целочисленное значение из метаданных по ключу. - -## Usage - -### Default usage flow - -```go -package main - -import ( - "context" - "log" - - "github.com/txix-open/isp-kit/grpc" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/shutdown" -) - -func main() { - mux := grpc.NewMux() - mux.Handle("/get_users", func(ctx context.Context, msg *isp.Message) (*isp.Message, error) { - /* put here business logic */ - return new(isp.Message), nil - }) - - srv := grpc.DefaultServer() - srv.Upgrade(mux) - - shutdown.On(func() { /* waiting for SIGINT & SIGTERM signals */ - log.Println("shutting down...") - srv.Shutdown() - log.Println("shutdown completed") - }) - - err := srv.ListenAndServe(":8080") - if err != nil { - log.Fatal(err) - } -} - -``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/grpc/apierrors/README.md b/vendor/github.com/txix-open/isp-kit/grpc/apierrors/README.md deleted file mode 100644 index 4ab3236..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/apierrors/README.md +++ /dev/null @@ -1,102 +0,0 @@ -# Package `apierrors` - -Пакет `apierrors` предоставляет структурированный формат ошибок для gRPC-сервисов с поддержкой кодов ошибок, деталей, -уровней логирования и интеграции с gRPC-статусами. Позволяет единообразно обрабатывать бизнес-ошибки и технические сбои. - -## Types - -### Error - -Структура для представления ошибки API. Реализует интерфейс `error`. - -**Methods:** - -#### `NewInternalServiceError(err error) Error` - -Создает ошибку для внутренних сбоев сервера. Возвращает ошибку с gRPC-статусом 13 (internal), бизнесовым кодом 900 и -уровнем -логирования error. - -#### `NewBusinessError(errorCode int, errorMessage string, err error) Error` - -Создает бизнес-ошибку (например, невалидные данные от клиента). Возвращает ошибку с gRPC-статусом 3 (invalid argument), -указанным -бизнесовым кодом и уровнем логирования warn. - -#### `New(httpStatusCode int, errorCode int, errorMessage string, err error) Error` - -Создает кастомную ошибку с полным контролем параметров. - -#### `(e Error) Error() string` - -Получить строковое представление ошибки. - -#### `(e Error) GrpcStatusError() error` - -Конвертирует ошибку в gRPC-сообщение с сериализованными деталями об ошибке в формате JSON. - -#### `(e Error) WithDetails(details map[string]any) Error` - -Добавить детали информации об ошибке. - -#### `(e Error) WithLogLevel(level log.Level) Error` - -Изменить уровень логирования ошибки. - -#### `(e Error) LogLevel() log.Level` - -Получить текущий уровень логирования ошибки - -## Functions - -#### `FromError(err error) *Error` - -Извлекает структурированную бизнесовую ошибку из gRPC-сообщения спрятанного под интерфейс `error`. - -## Usage - -### Default usage flow - -```go -package main - -import ( - "context" - "errors" - - "github.com/txix-open/isp-kit/grpc/apierrors" -) - -type User struct { - Id string - Name string -} - -var ( - ErrUserNotFound = errors.New("user not found") - ErrUserNotFoundCode = 700 -) - -type userService interface { - GetUserById(ctx context.Context, id string) (*User, error) -} - -type userController struct { - svc userService -} - -func (c userController) GetUser(ctx context.Context, userId string) (*User, error) { - result, err := c.svc.GetUserById(ctx, userId) - switch { - case errors.Is(err, ErrUserNotFound): - /* user isn't found so we have to send back specific error code */ - return nil, apierrors.NewBusinessError(ErrUserNotFoundCode, ErrUserNotFound.Error(), err) - case err != nil: - /* got some internal error */ - return nil, apierrors.NewInternalServiceError(err) - default: - return result, nil - } -} - -``` \ No newline at end of file diff --git a/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go b/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go deleted file mode 100644 index 5bfafe2..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/apierrors/error.go +++ /dev/null @@ -1,149 +0,0 @@ -// Package apierrors provides structured error handling for gRPC services. -// It defines custom error types with business error codes, gRPC status codes, -// and structured details for comprehensive error reporting. -// -// Errors can be converted to gRPC status errors with JSON-encoded details, -// enabling rich error information to be transmitted across service boundaries. -package apierrors - -import ( - "fmt" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/json" - "github.com/txix-open/isp-kit/log" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -const ( - // ErrCodeInternal is the default error code for internal service errors. - ErrCodeInternal = 900 -) - -// Error represents a structured error with business and gRPC status codes. -// Includes optional details for field-specific errors and a configurable log level. -// Implements the GrpcError interface for conversion to gRPC status errors. -// -// Fields: -// - ErrorCode: Business-level error code (e.g., 400 for bad request) -// - ErrorMessage: Human-readable error message -// - Details: Optional map of field-specific error details -// - grpcStatusCode: gRPC status code (e.g., codes.InvalidArgument) -// - cause: Underlying error cause -// - level: Log level for error logging -type Error struct { - ErrorCode int - ErrorMessage string - Details map[string]any `json:",omitempty"` - - grpcStatusCode codes.Code - cause error - level log.Level -} - -// NewInternalServiceError creates a new internal service error. -// Uses gRPC status code Internal and business error code 900. -// Sets log level to Error. -func NewInternalServiceError(err error) Error { - return New(codes.Internal, ErrCodeInternal, "internal service error", err).WithLogLevel(log.ErrorLevel) -} - -// NewBusinessError creates a new business validation error. -// Uses gRPC status code InvalidArgument and the specified error code. -// Sets log level to Warn. -func NewBusinessError(errorCode int, errorMessage string, err error) Error { - return New(codes.InvalidArgument, errorCode, errorMessage, err).WithLogLevel(log.WarnLevel) -} - -// New creates a new Error with the specified parameters. -// Sets default log level to Error. -func New( - grpcStatusCode codes.Code, - errorCode int, - errorMessage string, - err error, -) Error { - return Error{ - ErrorCode: errorCode, - ErrorMessage: errorMessage, - grpcStatusCode: grpcStatusCode, - cause: err, - level: log.ErrorLevel, - } -} - -// Error returns a string representation of the error. -// Includes error code, message, and underlying cause. -func (e Error) Error() string { - return fmt.Sprintf("errorCode: %d, errorMessage: %s, cause: %v", e.ErrorCode, e.ErrorMessage, e.cause) -} - -// GrpcStatusError converts the Error to a gRPC status error. -// Serializes the error to JSON and attaches it as gRPC status details. -// Returns an error if JSON marshaling or status creation fails. -func (e Error) GrpcStatusError() error { - data, err := json.Marshal(e) - if err != nil { - return errors.WithMessage(err, "marshal json") - } - - msg := &isp.Message{ - Body: &isp.Message_BytesBody{ - BytesBody: data, - }, - } - s, err := status.New(e.grpcStatusCode, e.ErrorMessage).WithDetails(msg) - if err != nil { - return errors.WithMessage(err, "set status details") - } - return s.Err() -} - -// WithDetails sets the error details map. -// Returns the Error for method chaining. -func (e Error) WithDetails(details map[string]any) Error { - e.Details = details - return e -} - -// WithLogLevel sets the log level for this error. -// Returns the Error for method chaining. -func (e Error) WithLogLevel(level log.Level) Error { - e.level = level - return e -} - -// LogLevel returns the log level for this error. -func (e Error) LogLevel() log.Level { - return e.level -} - -// FromError extracts an Error from a gRPC status error. -// Returns nil if the error is not a gRPC status error or if the details cannot be parsed. -// Useful for checking if an error originated from a remote service. -func FromError(err error) *Error { - s, ok := status.FromError(err) - if !ok { - return nil - } - - for _, detail := range s.Details() { - typedDetail, ok := detail.(*isp.Message) - if ok { - errData := Error{} - err := json.Unmarshal(typedDetail.GetBytesBody(), &errData) - // not an error - if err != nil { - return nil // nolint:nilerr - } - if errData.ErrorCode == 0 { - return nil - } - return &errData - } - } - - return nil -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go b/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go deleted file mode 100644 index ed868be..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/auth_data.go +++ /dev/null @@ -1,115 +0,0 @@ -package grpc - -import ( - "strconv" - - "github.com/txix-open/isp-kit/errors" - "google.golang.org/grpc/metadata" -) - -const ( - // ApplicationIdHeader is the metadata key for application identity. - ApplicationIdHeader = "x-application-identity" - // ApplicationNameHeader is the metadata key for application name. - ApplicationNameHeader = "x-application-name" - // UserIdHeader is the metadata key for user identity. - UserIdHeader = "x-user-identity" - // DeviceIdHeader is the metadata key for device identity. - DeviceIdHeader = "x-device-identity" - // ServiceIdHeader is the metadata key for service identity. - ServiceIdHeader = "x-service-identity" - // DomainIdHeader is the metadata key for domain identity. - DomainIdHeader = "x-domain-identity" - // SystemIdHeader is the metadata key for system identity. - SystemIdHeader = "x-system-identity" - // UserTokenHeader is the metadata key for user token. - UserTokenHeader = "x-user-token" - // DeviceTokenHeader is the metadata key for device token. - DeviceTokenHeader = "x-device-token" -) - -// AuthData wraps metadata.MD to provide structured access to authentication -// and authorization information from gRPC request metadata. -// All methods return an error if the key is not found or cannot be parsed. -type AuthData metadata.MD - -// SystemId extracts the system identity from metadata as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) SystemId() (int, error) { - return IntFromMd(SystemIdHeader, metadata.MD(i)) -} - -// DomainId extracts the domain identity from metadata as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) DomainId() (int, error) { - return IntFromMd(DomainIdHeader, metadata.MD(i)) -} - -// ServiceId extracts the service identity from metadata as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) ServiceId() (int, error) { - return IntFromMd(ServiceIdHeader, metadata.MD(i)) -} - -// ApplicationId extracts the application identity from metadata as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) ApplicationId() (int, error) { - return IntFromMd(ApplicationIdHeader, metadata.MD(i)) -} - -// ApplicationName extracts the application name from metadata as a string. -// Returns an error if the key is not found. -func (i AuthData) ApplicationName() (string, error) { - return StringFromMd(ApplicationNameHeader, metadata.MD(i)) -} - -// UserId extracts the user identity from metadata as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) UserId() (int, error) { - return IntFromMd(UserIdHeader, metadata.MD(i)) -} - -// DeviceId extracts the device identity from metadata as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) DeviceId() (int, error) { - return IntFromMd(DeviceIdHeader, metadata.MD(i)) -} - -// UserToken extracts the user token from metadata as a string. -// Returns an error if the key is not found. -func (i AuthData) UserToken() (string, error) { - return StringFromMd(UserTokenHeader, metadata.MD(i)) -} - -// DeviceToken extracts the device token from metadata as a string. -// Returns an error if the key is not found. -func (i AuthData) DeviceToken() (string, error) { - return StringFromMd(DeviceTokenHeader, metadata.MD(i)) -} - -// StringFromMd extracts a string value from metadata by key. -// Returns an error if metadata is nil or the key is not found. -func StringFromMd(key string, md metadata.MD) (string, error) { - if md == nil { - return "", errors.New("metadata is nil") - } - values := md[key] - if len(values) == 0 { - return "", errors.Errorf("'%s' is expected in metadata", key) - } - return values[0], nil -} - -// IntFromMd extracts an integer value from metadata by key. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func IntFromMd(key string, md metadata.MD) (int, error) { - value, err := StringFromMd(key, md) - if err != nil { - return 0, err - } - intValue, err := strconv.Atoi(value) - if err != nil { - return 0, errors.WithMessagef(err, "parse '%s' to int", key) - } - return intValue, nil -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/common.go b/vendor/github.com/txix-open/isp-kit/grpc/common.go deleted file mode 100644 index f577361..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/common.go +++ /dev/null @@ -1,16 +0,0 @@ -package grpc - -import ( - "context" - - "github.com/txix-open/isp-kit/grpc/isp" -) - -// HandlerFunc defines the signature for gRPC request handlers. -// Receives a context and message, returns a response message and optional error. -type HandlerFunc func(ctx context.Context, message *isp.Message) (*isp.Message, error) - -// Middleware wraps a HandlerFunc to add cross-cutting concerns like logging, -// metrics, authentication, or error handling. -// Middleware functions are typically chained in reverse order of execution. -type Middleware func(next HandlerFunc) HandlerFunc diff --git a/vendor/github.com/txix-open/isp-kit/grpc/encoding.go b/vendor/github.com/txix-open/isp-kit/grpc/encoding.go deleted file mode 100644 index 84ec7c2..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/encoding.go +++ /dev/null @@ -1,9 +0,0 @@ -package grpc - -const ( - // AcceptEncodingHeader is the metadata key for accept encoding. - AcceptEncodingHeader = "x-accept-encoding" - - // ContentEncodingHeader is the metadata key for content encoding. - ContentEncodingHeader = "x-content-encoding" -) diff --git a/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.pb.go b/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.pb.go deleted file mode 100644 index 5b895ef..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.pb.go +++ /dev/null @@ -1,241 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.31.0 -// protoc v3.21.12 -// source: backed_service.proto - -package isp - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - structpb "google.golang.org/protobuf/types/known/structpb" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type Message struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // Types that are assignable to Body: - // - // *Message_StructBody - // *Message_ListBody - // *Message_NullBody - // *Message_BytesBody - Body isMessage_Body `protobuf_oneof:"body"` -} - -func (x *Message) Reset() { - *x = Message{} - if protoimpl.UnsafeEnabled { - mi := &file_backed_service_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *Message) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Message) ProtoMessage() {} - -func (x *Message) ProtoReflect() protoreflect.Message { - mi := &file_backed_service_proto_msgTypes[0] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Message.ProtoReflect.Descriptor instead. -func (*Message) Descriptor() ([]byte, []int) { - return file_backed_service_proto_rawDescGZIP(), []int{0} -} - -func (m *Message) GetBody() isMessage_Body { - if m != nil { - return m.Body - } - return nil -} - -func (x *Message) GetStructBody() *structpb.Struct { - if x, ok := x.GetBody().(*Message_StructBody); ok { - return x.StructBody - } - return nil -} - -func (x *Message) GetListBody() *structpb.ListValue { - if x, ok := x.GetBody().(*Message_ListBody); ok { - return x.ListBody - } - return nil -} - -func (x *Message) GetNullBody() structpb.NullValue { - if x, ok := x.GetBody().(*Message_NullBody); ok { - return x.NullBody - } - return structpb.NullValue(0) -} - -func (x *Message) GetBytesBody() []byte { - if x, ok := x.GetBody().(*Message_BytesBody); ok { - return x.BytesBody - } - return nil -} - -type isMessage_Body interface { - isMessage_Body() -} - -type Message_StructBody struct { - StructBody *structpb.Struct `protobuf:"bytes,1,opt,name=structBody,proto3,oneof"` -} - -type Message_ListBody struct { - ListBody *structpb.ListValue `protobuf:"bytes,2,opt,name=listBody,proto3,oneof"` -} - -type Message_NullBody struct { - NullBody structpb.NullValue `protobuf:"varint,3,opt,name=NullBody,proto3,enum=google.protobuf.NullValue,oneof"` -} - -type Message_BytesBody struct { - BytesBody []byte `protobuf:"bytes,4,opt,name=BytesBody,proto3,oneof"` -} - -func (*Message_StructBody) isMessage_Body() {} - -func (*Message_ListBody) isMessage_Body() {} - -func (*Message_NullBody) isMessage_Body() {} - -func (*Message_BytesBody) isMessage_Body() {} - -var File_backed_service_proto protoreflect.FileDescriptor - -var file_backed_service_proto_rawDesc = []byte{ - 0x0a, 0x14, 0x62, 0x61, 0x63, 0x6b, 0x65, 0x64, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, - 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03, 0x69, 0x73, 0x70, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x73, 0x74, 0x72, - 0x75, 0x63, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0xe0, 0x01, 0x0a, 0x07, 0x4d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x39, 0x0a, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, - 0x6f, 0x64, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x53, 0x74, 0x72, 0x75, - 0x63, 0x74, 0x48, 0x00, 0x52, 0x0a, 0x73, 0x74, 0x72, 0x75, 0x63, 0x74, 0x42, 0x6f, 0x64, 0x79, - 0x12, 0x38, 0x0a, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00, - 0x52, 0x08, 0x6c, 0x69, 0x73, 0x74, 0x42, 0x6f, 0x64, 0x79, 0x12, 0x38, 0x0a, 0x08, 0x4e, 0x75, - 0x6c, 0x6c, 0x42, 0x6f, 0x64, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1a, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x4e, - 0x75, 0x6c, 0x6c, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00, 0x52, 0x08, 0x4e, 0x75, 0x6c, 0x6c, - 0x42, 0x6f, 0x64, 0x79, 0x12, 0x1e, 0x0a, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73, 0x42, 0x6f, 0x64, - 0x79, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00, 0x52, 0x09, 0x42, 0x79, 0x74, 0x65, 0x73, - 0x42, 0x6f, 0x64, 0x79, 0x42, 0x06, 0x0a, 0x04, 0x62, 0x6f, 0x64, 0x79, 0x32, 0x6c, 0x0a, 0x0e, - 0x42, 0x61, 0x63, 0x6b, 0x65, 0x6e, 0x64, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x27, - 0x0a, 0x07, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, - 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x0d, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, - 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x1a, 0x0c, 0x2e, 0x69, 0x73, 0x70, 0x2e, 0x4d, 0x65, 0x73, - 0x73, 0x61, 0x67, 0x65, 0x22, 0x00, 0x28, 0x01, 0x30, 0x01, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x3b, - 0x69, 0x73, 0x70, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_backed_service_proto_rawDescOnce sync.Once - file_backed_service_proto_rawDescData = file_backed_service_proto_rawDesc -) - -func file_backed_service_proto_rawDescGZIP() []byte { - file_backed_service_proto_rawDescOnce.Do(func() { - file_backed_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_backed_service_proto_rawDescData) - }) - return file_backed_service_proto_rawDescData -} - -var file_backed_service_proto_msgTypes = make([]protoimpl.MessageInfo, 1) -var file_backed_service_proto_goTypes = []interface{}{ - (*Message)(nil), // 0: isp.Message - (*structpb.Struct)(nil), // 1: google.protobuf.Struct - (*structpb.ListValue)(nil), // 2: google.protobuf.ListValue - (structpb.NullValue)(0), // 3: google.protobuf.NullValue -} -var file_backed_service_proto_depIdxs = []int32{ - 1, // 0: isp.Message.structBody:type_name -> google.protobuf.Struct - 2, // 1: isp.Message.listBody:type_name -> google.protobuf.ListValue - 3, // 2: isp.Message.NullBody:type_name -> google.protobuf.NullValue - 0, // 3: isp.BackendService.Request:input_type -> isp.Message - 0, // 4: isp.BackendService.RequestStream:input_type -> isp.Message - 0, // 5: isp.BackendService.Request:output_type -> isp.Message - 0, // 6: isp.BackendService.RequestStream:output_type -> isp.Message - 5, // [5:7] is the sub-list for method output_type - 3, // [3:5] is the sub-list for method input_type - 3, // [3:3] is the sub-list for extension type_name - 3, // [3:3] is the sub-list for extension extendee - 0, // [0:3] is the sub-list for field type_name -} - -func init() { file_backed_service_proto_init() } -func file_backed_service_proto_init() { - if File_backed_service_proto != nil { - return - } - if !protoimpl.UnsafeEnabled { - file_backed_service_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Message); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - } - file_backed_service_proto_msgTypes[0].OneofWrappers = []interface{}{ - (*Message_StructBody)(nil), - (*Message_ListBody)(nil), - (*Message_NullBody)(nil), - (*Message_BytesBody)(nil), - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_backed_service_proto_rawDesc, - NumEnums: 0, - NumMessages: 1, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_backed_service_proto_goTypes, - DependencyIndexes: file_backed_service_proto_depIdxs, - MessageInfos: file_backed_service_proto_msgTypes, - }.Build() - File_backed_service_proto = out.File - file_backed_service_proto_rawDesc = nil - file_backed_service_proto_goTypes = nil - file_backed_service_proto_depIdxs = nil -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.proto b/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.proto deleted file mode 100644 index a696a1f..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service.proto +++ /dev/null @@ -1,23 +0,0 @@ -syntax = "proto3"; -package isp; -// protoc --go_out=plugins=grpc:. *.proto - -option go_package = ".;isp"; - -import "google/protobuf/struct.proto"; - -message Message { - oneof body { - google.protobuf.Struct structBody = 1; - google.protobuf.ListValue listBody = 2; - google.protobuf.NullValue NullBody = 3; - bytes BytesBody = 4; - } -} - -service BackendService { - // ===== SYSTEM ===== - rpc Request (Message) returns (Message) {} - - rpc RequestStream(stream Message) returns (stream Message) {} -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service_grpc.pb.go b/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service_grpc.pb.go deleted file mode 100644 index 3ab400c..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/isp/backed_service_grpc.pb.go +++ /dev/null @@ -1,176 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.2.0 -// - protoc v3.21.12 -// source: backed_service.proto - -package isp - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.32.0 or later. -const _ = grpc.SupportPackageIsVersion7 - -// BackendServiceClient is the client API for BackendService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -type BackendServiceClient interface { - // ===== SYSTEM ===== - Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) - RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error) -} - -type backendServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewBackendServiceClient(cc grpc.ClientConnInterface) BackendServiceClient { - return &backendServiceClient{cc} -} - -func (c *backendServiceClient) Request(ctx context.Context, in *Message, opts ...grpc.CallOption) (*Message, error) { - out := new(Message) - err := c.cc.Invoke(ctx, "/isp.BackendService/Request", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *backendServiceClient) RequestStream(ctx context.Context, opts ...grpc.CallOption) (BackendService_RequestStreamClient, error) { - stream, err := c.cc.NewStream(ctx, &BackendService_ServiceDesc.Streams[0], "/isp.BackendService/RequestStream", opts...) - if err != nil { - return nil, err - } - x := &backendServiceRequestStreamClient{stream} - return x, nil -} - -type BackendService_RequestStreamClient interface { - Send(*Message) error - Recv() (*Message, error) - grpc.ClientStream -} - -type backendServiceRequestStreamClient struct { - grpc.ClientStream -} - -func (x *backendServiceRequestStreamClient) Send(m *Message) error { - return x.ClientStream.SendMsg(m) -} - -func (x *backendServiceRequestStreamClient) Recv() (*Message, error) { - m := new(Message) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// BackendServiceServer is the server API for BackendService service. -// All implementations must embed UnimplementedBackendServiceServer -// for forward compatibility -type BackendServiceServer interface { - // ===== SYSTEM ===== - Request(context.Context, *Message) (*Message, error) - RequestStream(BackendService_RequestStreamServer) error - mustEmbedUnimplementedBackendServiceServer() -} - -// UnimplementedBackendServiceServer must be embedded to have forward compatible implementations. -type UnimplementedBackendServiceServer struct { -} - -func (UnimplementedBackendServiceServer) Request(context.Context, *Message) (*Message, error) { - return nil, status.Errorf(codes.Unimplemented, "method Request not implemented") -} -func (UnimplementedBackendServiceServer) RequestStream(BackendService_RequestStreamServer) error { - return status.Errorf(codes.Unimplemented, "method RequestStream not implemented") -} -func (UnimplementedBackendServiceServer) mustEmbedUnimplementedBackendServiceServer() {} - -// UnsafeBackendServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to BackendServiceServer will -// result in compilation errors. -type UnsafeBackendServiceServer interface { - mustEmbedUnimplementedBackendServiceServer() -} - -func RegisterBackendServiceServer(s grpc.ServiceRegistrar, srv BackendServiceServer) { - s.RegisterService(&BackendService_ServiceDesc, srv) -} - -func _BackendService_Request_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Message) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BackendServiceServer).Request(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/isp.BackendService/Request", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BackendServiceServer).Request(ctx, req.(*Message)) - } - return interceptor(ctx, in, info, handler) -} - -func _BackendService_RequestStream_Handler(srv interface{}, stream grpc.ServerStream) error { - return srv.(BackendServiceServer).RequestStream(&backendServiceRequestStreamServer{stream}) -} - -type BackendService_RequestStreamServer interface { - Send(*Message) error - Recv() (*Message, error) - grpc.ServerStream -} - -type backendServiceRequestStreamServer struct { - grpc.ServerStream -} - -func (x *backendServiceRequestStreamServer) Send(m *Message) error { - return x.ServerStream.SendMsg(m) -} - -func (x *backendServiceRequestStreamServer) Recv() (*Message, error) { - m := new(Message) - if err := x.ServerStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -// BackendService_ServiceDesc is the grpc.ServiceDesc for BackendService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var BackendService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "isp.BackendService", - HandlerType: (*BackendServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Request", - Handler: _BackendService_Request_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "RequestStream", - Handler: _BackendService_RequestStream_Handler, - ServerStreams: true, - ClientStreams: true, - }, - }, - Metadata: "backed_service.proto", -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/mux.go b/vendor/github.com/txix-open/isp-kit/grpc/mux.go deleted file mode 100644 index 213b23b..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/mux.go +++ /dev/null @@ -1,71 +0,0 @@ -package grpc - -import ( - "context" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/isp" - "github.com/txix-open/isp-kit/log" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/grpc/status" -) - -const ( - // ProxyMethodNameHeader is the metadata key used to specify the target endpoint. - ProxyMethodNameHeader = "proxy_method_name" -) - -// Mux is a request router that dispatches gRPC requests to registered handlers based on endpoint name. -// It extracts the endpoint from request metadata and invokes the corresponding HandlerFunc. -// Mux implements the BackendServiceServer interface but does not support streaming RPCs. -type Mux struct { - isp.UnimplementedBackendServiceServer - - unaryHandlers map[string]HandlerFunc -} - -// NewMux creates a new Mux with an empty handler registry. -func NewMux() *Mux { - return &Mux{ - unaryHandlers: make(map[string]HandlerFunc), - } -} - -// Handle registers a HandlerFunc for the specified endpoint. -// Panics if a handler is already registered for the endpoint. -// Returns the Mux for method chaining. -func (m *Mux) Handle(endpoint string, handler HandlerFunc) *Mux { - _, ok := m.unaryHandlers[endpoint] - if ok { - panic(errors.Errorf("handler for endpoint %v is already provided", endpoint)) - } - m.unaryHandlers[endpoint] = handler - return m -} - -// Request handles unary gRPC requests by routing to the registered handler for the endpoint. -// The endpoint is extracted from the ProxyMethodNameHeader in request metadata. -// Returns an error if metadata is missing, endpoint is not found, or handler fails. -func (m *Mux) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) { - md, ok := metadata.FromIncomingContext(ctx) - if !ok { - return nil, errors.New("metadata is expected in context") - } - endpoint, err := StringFromMd(ProxyMethodNameHeader, md) - if err != nil { - return nil, err - } - handler, ok := m.unaryHandlers[endpoint] - if !ok { - return nil, status.Errorf(codes.NotFound, "handler not found for endpoint %s", endpoint) - } - ctx = log.ToContext(ctx, log.String("endpoint", endpoint)) - return handler(ctx, message) -} - -// RequestStream returns an unimplemented error for streaming RPCs. -// Mux does not support streaming; use a custom implementation for streaming support. -func (m *Mux) RequestStream(_ isp.BackendService_RequestStreamServer) error { - return status.Errorf(codes.Unimplemented, "service does not support streaming RPC") -} diff --git a/vendor/github.com/txix-open/isp-kit/grpc/server.go b/vendor/github.com/txix-open/isp-kit/grpc/server.go deleted file mode 100644 index 39d4340..0000000 --- a/vendor/github.com/txix-open/isp-kit/grpc/server.go +++ /dev/null @@ -1,118 +0,0 @@ -// Package grpc provides a gRPC server and client implementation for the ISP kit framework. -// It enables building scalable microservices with support for hot-swappable handlers, -// middleware integration, and structured authentication via metadata. -// -// The package supports both unary and streaming RPCs, with built-in features for -// request/response logging, metrics collection, and distributed tracing. -package grpc - -import ( - "context" - "net" - "sync/atomic" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/isp" - "google.golang.org/grpc" -) - -const ( - // DefaultMaxSizeByte defines the default maximum message size in bytes (64MB). - DefaultMaxSizeByte = 64 * 1024 * 1024 -) - -// service implements the BackendServiceServer interface with hot-swappable handler support. -// It uses atomic.Value for thread-safe handler replacement without interrupting in-flight requests. -type service struct { - isp.UnimplementedBackendServiceServer - - delegate atomic.Value -} - -// Request handles unary gRPC requests by delegating to the registered BackendServiceServer. -// Returns an error if the handler is not initialized. -func (s *service) Request(ctx context.Context, message *isp.Message) (*isp.Message, error) { - delegate, ok := s.delegate.Load().(isp.BackendServiceServer) - if !ok { - return nil, errors.New("handler is not initialized") - } - return delegate.Request(ctx, message) -} - -// RequestStream handles streaming gRPC requests by delegating to the registered BackendServiceServer. -// Returns an error if the handler is not initialized. -func (s *service) RequestStream(server isp.BackendService_RequestStreamServer) error { - delegate, ok := s.delegate.Load().(isp.BackendServiceServer) - if !ok { - return errors.New("handler is not initialized") - } - return delegate.RequestStream(server) -} - -// Server wraps a gRPC server with hot-swappable handler support. -// It provides a clean interface for starting, stopping, and upgrading gRPC services -// without requiring server restart. -type Server struct { - server *grpc.Server - service *service -} - -// DefaultServer creates a new Server with default configuration including 64MB message size limits. -// Accepts additional grpc.ServerOption for further customization. -// Thread-safe for concurrent use. -func DefaultServer(restOptions ...grpc.ServerOption) *Server { - opts := append([]grpc.ServerOption{ - grpc.MaxRecvMsgSize(DefaultMaxSizeByte), - grpc.MaxSendMsgSize(DefaultMaxSizeByte), - }, restOptions...) - return NewServer(opts...) -} - -// NewServer creates a new Server with custom gRPC options. -// Accepts variadic grpc.ServerOption for full configuration control. -// Thread-safe for concurrent use. -func NewServer(opts ...grpc.ServerOption) *Server { - s := &Server{ - server: grpc.NewServer(opts...), - service: &service{ - delegate: atomic.Value{}, - }, - } - isp.RegisterBackendServiceServer(s.server, s.service) - return s -} - -// Shutdown gracefully stops the server, waiting for in-flight requests to complete. -// Thread-safe for concurrent use. -func (s *Server) Shutdown() { - s.server.GracefulStop() -} - -// Upgrade atomically replaces the backend service handler without interrupting in-flight requests. -// This enables hot-reload of business logic without server restart. -// Thread-safe for concurrent use. -func (s *Server) Upgrade(service isp.BackendServiceServer) { - s.service.delegate.Store(service) -} - -// ListenAndServe binds the server to the specified TCP address and starts serving. -// Returns an error if binding fails or serving encounters a fatal error. -func (s *Server) ListenAndServe(address string) error { - var lc net.ListenConfig - listener, err := lc.Listen(context.Background(), "tcp", address) - if err != nil { - return errors.WithMessagef(err, "listen: %s", address) - } - return s.Serve(listener) -} - -// Serve starts serving gRPC requests on the provided listener. -// Blocks until the server is stopped or an error occurs. -// Returns an error if serving encounters a fatal error. -func (s *Server) Serve(listener net.Listener) error { - err := s.server.Serve(listener) - if err != nil { - return errors.WithMessage(err, "serve grpc") - } - return nil -} diff --git a/vendor/modules.txt b/vendor/modules.txt index abe0d19..0fe31c6 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -237,9 +237,6 @@ github.com/txix-open/isp-kit/dbrx github.com/txix-open/isp-kit/dbx github.com/txix-open/isp-kit/dbx/migration github.com/txix-open/isp-kit/errors -github.com/txix-open/isp-kit/grpc -github.com/txix-open/isp-kit/grpc/apierrors -github.com/txix-open/isp-kit/grpc/isp github.com/txix-open/isp-kit/healthcheck github.com/txix-open/isp-kit/http github.com/txix-open/isp-kit/http/apierrors From 2f29af5e76cc4fe998a934a55f82defda4883c4b Mon Sep 17 00:00:00 2001 From: chashintv Date: Thu, 19 Nov 2026 20:31:51 +0300 Subject: [PATCH 04/13] MSP-8974 update doc --- controller/audit.go | 25 +-- controller/auth.go | 29 +-- controller/customization.go | 4 +- controller/download.go | 8 +- controller/permissions.go | 5 +- controller/role.go | 24 +- controller/secure.go | 4 +- controller/session.go | 8 +- controller/ui_settings.go | 6 +- controller/user.go | 44 ++-- docs/swagger.json | 432 ++++++++++++++++++++++++++---------- 11 files changed, 395 insertions(+), 194 deletions(-) diff --git a/controller/audit.go b/controller/audit.go index c29282f..e658865 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -29,13 +29,14 @@ func NewAudit(service AuditService) Audit { // All // @Tags log // @Summary Получение списка логов +// @Description `errorCode: 400` - если тело запроса невалидно // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.AuditPageRequest true "Тело запроса" +// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)" // @Success 200 {object} domain.AuditResponse -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /log/all [POST] func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) { if req.Order == nil { @@ -50,15 +51,13 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au // Events // @Tags log -// @Summary Получение списка логов +// @Summary Получение списка событий аудита // @Description Возвращает полный список доступных событий аудита // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.AuditResponse true "Тело запроса" // @Success 200 {array} domain.AuditEvent -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /log/events [POST] func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) { return c.service.Events(ctx) @@ -66,15 +65,15 @@ func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) { // SetEvents // @Tags log -// @Summary Получение списка логов -// @Description Всегда возвращает полный список доступных событий аудита +// @Summary Установить события аудита +// @Description Устанавливает (обновляет) набор активных событий аудита. `errorCode: ` - если передано неизвестное событие аудита // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.SetAuditEvent true "Тело запроса" -// @Success 200 -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки" +// @Success 200 {object} map[string]interface{} "События успешно установлены" +// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита" +// @Failure 500 {object} apierrors.Error // @Router /log/set_events [POST] func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error { err := c.service.SetEvents(ctx, req) diff --git a/controller/auth.go b/controller/auth.go index 51a0e25..7ca2801 100644 --- a/controller/auth.go +++ b/controller/auth.go @@ -38,9 +38,9 @@ func NewAuth(authService authService, logger log.Logger) Auth { // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 -// @Failure 400 {object} domain.GrpcError "Невалидный токен" -// @Failure 500 {object} domain.GrpcError +// @Success 200 {object} map[string]interface{} "Успешный выход" +// @Failure 400 {object} apierrors.Error "Невалидный токен" +// @Failure 500 {object} apierrors.Error // @Router /auth/logout [POST] func (a Auth) Logout(ctx context.Context, r *http.Request) error { adminId, err := getAdminId(r) @@ -62,11 +62,11 @@ func (a Auth) Logout(ctx context.Context, r *http.Request) error { // @Description Выход по бездействию из авторизованной сессии администрирования // @Accept json // @Produce json -// @Param body body domain.LogoutRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 -// @Failure 400 {object} domain.GrpcError "Невалидный токен" -// @Failure 500 {object} domain.GrpcError +// @Param body body domain.LogoutRequest true "Тело запроса" +// @Success 200 {object} map[string]interface{} "Успешный выход" +// @Failure 400 {object} apierrors.Error "Невалидный токен" +// @Failure 500 {object} apierrors.Error // @Router /auth/logout_with_reason [POST] func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error { adminId, err := getAdminId(r) @@ -90,9 +90,10 @@ func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutR // @Produce json // @Param body body domain.LoginRequest true "Тело запроса" // @Success 200 {object} domain.LoginResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны" +// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию" +// @Failure 500 {object} apierrors.Error // @Router /auth/login [POST] func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) { auth, err := a.authService.Login(ctx, authRequest) @@ -115,14 +116,14 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma // LoginWithOauth // @Tags auth // @Summary Авторизация по авторизационному коду от OAuth -// @Description Авторизация с получением токена администратора +// @Description Авторизация с получением токена администратора. `errorCode: ` - OAuth не настроен, `` - неверный код или неизвестный клиент // @Accept json // @Produce json // @Param body body domain.LoginOauthRequest true "Тело запроса" // @Success 200 {object} domain.LoginResponse -// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента" -// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере" +// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента" +// @Failure 500 {object} apierrors.Error // @Router /auth/login_with_oauth [POST] func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) { auth, err := a.authService.LoginWithOauth(ctx, request) diff --git a/controller/customization.go b/controller/customization.go index 3c5492b..3681fe7 100644 --- a/controller/customization.go +++ b/controller/customization.go @@ -26,8 +26,8 @@ func NewCustomization(uiCfg conf.UIDesign) Customization { // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Success 200 {object} domain.UIDesign -// @Failure 400 {object} domain.GrpcError "Невалидный токен" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидный токен" +// @Failure 500 {object} apierrors.Error // @Router /user/get_design [POST] func (c Customization) GetUIDesign() (domain.UIDesign, error) { return c.uiCfg, nil diff --git a/controller/download.go b/controller/download.go index e1d4d81..7cabac1 100644 --- a/controller/download.go +++ b/controller/download.go @@ -33,7 +33,7 @@ func NewDownload(service DownloadService) Download { // @Produce json // @Param body body domain.UsersDownloadRequest true "Тело запроса" // @Success 200 -// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /user/download [POST] func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { err := c.service.DownloadUsers(ctx, req, w) @@ -51,7 +51,7 @@ func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w // @Produce json // @Param body body domain.SessionDownloadRequest true "Тело запроса" // @Success 200 -// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /session/download [POST] func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { err := c.service.DownloadSessions(ctx, req, w) @@ -69,7 +69,7 @@ func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadReques // @Produce json // @Param body body domain.AuditDownloadRequest true "Тело запроса" // @Success 200 -// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /log/download [POST] func (c Download) Audit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { err := c.service.DownloadAudit(ctx, req, w) @@ -86,7 +86,7 @@ func (c Download) Audit(ctx context.Context, req domain.AuditDownloadRequest, w // @Accept json // @Produce json // @Success 200 -// @Failure 500 {object} domain.BusinessError "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /role/download [POST] func (c Download) Roles(ctx context.Context, w http.ResponseWriter) error { err := c.service.DownloadRoles(ctx, w) diff --git a/controller/permissions.go b/controller/permissions.go index 61f7c21..e8afb81 100644 --- a/controller/permissions.go +++ b/controller/permissions.go @@ -22,11 +22,12 @@ func NewPermissions(permissionsService permissionsService) Permissions { // GetPermissions // @Tags user -// @Summary Получить все разрашения -// @Description Получить все разрашения +// @Summary Получить все разрешения +// @Description Получить все разрешения // @Accept json // @Produce json // @Success 200 {array} domain.Permission +// @Failure 500 {object} apierrors.Error // @Router /user/get_permissions [POST] func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission { return u.permissionsService.All(ctx) diff --git a/controller/role.go b/controller/role.go index 7dbc61c..876bacf 100644 --- a/controller/role.go +++ b/controller/role.go @@ -36,8 +36,8 @@ func NewRole(roleService roleService) Role { // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.RoleAllRequest true "Тело запроса" // @Success 200 {array} domain.Role -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /role/all [POST] func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) { users, err := u.roleService.All(ctx, req) @@ -49,17 +49,17 @@ func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role } // CreateRole -// @Tags user +// @Tags role // @Summary Создать роль // @Description Создать роль // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.CreateRoleRequest true "Тело запроса" -// @Success 200 {object} domain.User -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует" -// @Failure 500 {object} domain.GrpcError +// @Success 200 {object} domain.Role +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" +// @Failure 500 {object} apierrors.Error // @Router /role/create [POST] func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) { adminId, err := getAdminId(r) @@ -87,9 +87,9 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.UpdateRoleRequest true "Тело запроса" // @Success 200 {object} domain.Role -// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует" -// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует" -// @Failure 500 {object} domain.GrpcError +// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует" +// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" +// @Failure 500 {object} apierrors.Error // @Router /role/update [POST] func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) { adminId, err := getAdminId(r) @@ -119,8 +119,8 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.DeleteRoleRequest true "Тело запроса" // @Success 200 -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /role/delete [POST] func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error { adminId, err := getAdminId(r) diff --git a/controller/secure.go b/controller/secure.go index 3b79e11..4b78e0a 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -32,7 +32,7 @@ func NewSecure(service SecureService) Secure { // @Produce json // @Param body body domain.SecureAuthRequest true "Тело запроса" // @Success 200 {object} domain.SecureAuthResponse -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /secure/authenticate [POST] func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) { adminId, err := s.service.Authenticate(ctx, req.Token) @@ -68,7 +68,7 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) // @Produce json // @Param body body domain.SecureAuthzRequest true "Тело запроса" // @Success 200 {object} domain.SecureAuthzResponse -// @Failure 500 {object} domain.GrpcError +// @Failure 500 {object} apierrors.Error // @Router /secure/authorize [POST] func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) { ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission) diff --git a/controller/session.go b/controller/session.go index b96027e..eb0fda6 100644 --- a/controller/session.go +++ b/controller/session.go @@ -29,8 +29,8 @@ func NewSession(service SessionService) Session { // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.SessionPageRequest true "Тело запроса" // @Success 200 {object} domain.SessionResponse -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /session/all [POST] func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) { if req.Order == nil { @@ -51,8 +51,8 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.RevokeRequest true "Тело запроса" // @Success 200 -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /session/revoke [POST] func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error { return c.service.Revoke(ctx, req.Id) diff --git a/controller/ui_settings.go b/controller/ui_settings.go index e3c67e4..b2e1e2b 100644 --- a/controller/ui_settings.go +++ b/controller/ui_settings.go @@ -31,9 +31,9 @@ func NewUiSettings(service UiSettingsService) UiSettings { // @Produce json // @Param body body domain.ClientNameRequest true "Тело запроса" // @Success 200 {object} domain.UiOauthSetting -// @Failure 400 {object} domain.GrpcError -// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 401 {object} apierrors.Error "Неизвестное название клиента" +// @Failure 500 {object} apierrors.Error // @Router /ui_settings/oauth [POST] func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) { resp, err := c.service.OauthSettings(ctx, req) diff --git a/controller/user.go b/controller/user.go index 4eb8c17..4234993 100644 --- a/controller/user.go +++ b/controller/user.go @@ -41,9 +41,9 @@ func NewUser(userService userService) User { // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Success 200 {object} domain.AdminUserShort -// @Failure 400 {object} domain.GrpcError "Невалидный токен" -// @Failure 404 {object} domain.GrpcError "Пользователя не существует" -// @Failure 500 {object} domain.GrpcError +// @Failure 401 {object} apierrors.Error "Невалидный токен" +// @Failure 404 {object} apierrors.Error "Пользователя не существует" +// @Failure 500 {object} apierrors.Error // @Router /user/get_profile [POST] func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) { adminId, err := getAdminId(r) @@ -73,8 +73,8 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.UsersPageRequest true "Тело запроса" // @Success 200 {object} domain.UsersResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /user/get_users [POST] func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) { if req.Order == nil { @@ -100,8 +100,8 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Success 200 {object} domain.UsersResponse -// @Failure 400 {object} domain.GrpcError -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error // @Router /user/get_all_users [POST] func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { users, err := u.userService.GetAllUsers(ctx) @@ -121,9 +121,9 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.CreateUserRequest true "Тело запроса" // @Success 200 {object} domain.User -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" +// @Failure 500 {object} apierrors.Error // @Router /user/create_user [POST] func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) { adminId, err := getAdminId(r) @@ -151,10 +151,10 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.UpdateUserRequest true "Тело запроса" // @Success 200 {object} domain.User -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует" -// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует" +// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" +// @Failure 500 {object} apierrors.Error // @Router /user/update_user [POST] func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) { adminId, err := getAdminId(r) @@ -186,8 +186,8 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.IdentitiesRequest true "Тело запроса" // @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /user/delete_user [POST] func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) { adminId, err := getAdminId(r) @@ -211,8 +211,8 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.IdRequest true "Тело запроса" // @Success 200 -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /user/block_user [POST] func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error { adminId, err := getAdminId(r) @@ -234,8 +234,8 @@ func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Re // @Produce json // @Param body body domain.IdRequest true "Тело запроса" // @Success 200 {object} domain.User -// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" -// @Failure 500 {object} domain.GrpcError +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error // @Router /user/get_by_id [POST] func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) { return u.userService.GetById(ctx, identities.UserId) @@ -249,8 +249,8 @@ func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain // @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param body body domain.ChangePasswordRequest true "Тело запроса" // @Success 200 -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error "внутренняя ошибка" +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль" +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка" // @Router /user/change_password [POST] func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error { adminId, err := getAdminId(r) diff --git a/docs/swagger.json b/docs/swagger.json index e1543c0..ffff79f 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -46,19 +46,25 @@ "400": { "description": "Bad Request", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "401": { "description": "Данные для авторизации не верны", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" + } + }, + "429": { + "description": "Слишком много запросов на авторизацию", + "schema": { + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -66,7 +72,7 @@ }, "/auth/login_with_oauth": { "post": { - "description": "Авторизация с получением токена администратора", + "description": "Авторизация с получением токена администратора. `errorCode: \u003cErrOauthIsMissedCode\u003e` - OAuth не настроен, `\u003cErrUnauthenticatedCode\u003e` - неверный код или неизвестный клиент", "consumes": [ "application/json" ], @@ -95,22 +101,22 @@ "$ref": "#/definitions/domain.LoginResponse" } }, + "400": { + "description": "Авторизация OAuth не настроена на сервере", + "schema": { + "$ref": "#/definitions/apierrors.Error" + } + }, "401": { "description": "Некорректный код для авторизации или неизвестное название клиента", "schema": { - "$ref": "#/definitions/domain.GrpcError" - } - }, - "412": { - "description": "Авторизация OAuth не настроена на сервере", - "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -140,18 +146,22 @@ ], "responses": { "200": { - "description": "OK" + "description": "Успешный выход", + "schema": { + "type": "object", + "additionalProperties": true + } }, "400": { "description": "Невалидный токен", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -171,6 +181,13 @@ ], "summary": "Выход по бездействию из авторизованной сессии", "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, { "description": "Тело запроса", "name": "body", @@ -179,29 +196,26 @@ "schema": { "$ref": "#/definitions/domain.LogoutRequest" } - }, - { - "type": "string", - "description": "Токен администратора", - "name": "X-AUTH-ADMIN", - "in": "header", - "required": true } ], "responses": { "200": { - "description": "OK" + "description": "Успешный выход", + "schema": { + "type": "object", + "additionalProperties": true + } }, "400": { "description": "Невалидный токен", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -209,6 +223,7 @@ }, "/log/all": { "post": { + "description": "`errorCode: 400` - если тело запроса невалидно", "consumes": [ "application/json" ], @@ -228,7 +243,7 @@ "required": true }, { - "description": "Тело запроса", + "description": "Тело запроса (пагинация, сортировка, фильтры)", "name": "body", "in": "body", "required": true, @@ -247,13 +262,49 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" + } + } + } + } + }, + "/log/download": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Download" + ], + "summary": "Скачать журнал аудита в csv", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.AuditDownloadRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "500": { + "description": "Внутренняя ошибка сервиса ```{errorCode: -1}```", + "schema": { + "$ref": "#/definitions/apierrors.Error" } } } @@ -271,7 +322,7 @@ "tags": [ "log" ], - "summary": "Получение списка логов", + "summary": "Получение списка событий аудита", "parameters": [ { "type": "string", @@ -279,15 +330,6 @@ "name": "X-AUTH-ADMIN", "in": "header", "required": true - }, - { - "description": "Тело запроса", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.AuditResponse" - } } ], "responses": { @@ -300,16 +342,10 @@ } } }, - "400": { - "description": "Невалидное тело запроса", - "schema": { - "$ref": "#/definitions/domain.GrpcError" - } - }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -317,7 +353,7 @@ }, "/log/set_events": { "post": { - "description": "Всегда возвращает полный список доступных событий аудита", + "description": "Устанавливает (обновляет) набор активных событий аудита. `errorCode: \u003cUnknownAuditEventErrorCode\u003e` - если передано неизвестное событие аудита", "consumes": [ "application/json" ], @@ -327,7 +363,7 @@ "tags": [ "log" ], - "summary": "Получение списка логов", + "summary": "Установить события аудита", "parameters": [ { "type": "string", @@ -337,29 +373,36 @@ "required": true }, { - "description": "Тело запроса", + "description": "Список событий аудита для установки", "name": "body", "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.SetAuditEvent" + "type": "array", + "items": { + "$ref": "#/definitions/domain.SetAuditEvent" + } } } ], "responses": { "200": { - "description": "OK" + "description": "События успешно установлены", + "schema": { + "type": "object", + "additionalProperties": true + } }, "400": { - "description": "Невалидное тело запроса", + "description": "Неизвестное событие аудита", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -409,13 +452,13 @@ "400": { "description": "Bad Request", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -431,7 +474,7 @@ "application/json" ], "tags": [ - "user" + "role" ], "summary": "Создать роль", "parameters": [ @@ -456,25 +499,25 @@ "200": { "description": "OK", "schema": { - "$ref": "#/definitions/domain.User" + "$ref": "#/definitions/domain.Role" } }, "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "409": { "description": "Роль с указанным именем уже существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -518,13 +561,38 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" + } + } + } + } + }, + "/role/download": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Download" + ], + "summary": "Скачать матрицу ролей в csv", + "responses": { + "200": { + "description": "OK" + }, + "500": { + "description": "Внутренняя ошибка сервиса ```{errorCode: -1}```", + "schema": { + "$ref": "#/definitions/apierrors.Error" } } } @@ -571,19 +639,19 @@ "404": { "description": "Роль с указанным id не существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "409": { "description": "Роль с указанным именем уже существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -623,7 +691,7 @@ "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -663,7 +731,7 @@ "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -709,13 +777,49 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" + } + } + } + } + }, + "/session/download": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Download" + ], + "summary": "Скачать список сессий в csv", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.SessionDownloadRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "500": { + "description": "Внутренняя ошибка сервиса ```{errorCode: -1}```", + "schema": { + "$ref": "#/definitions/apierrors.Error" } } } @@ -758,13 +862,13 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -804,19 +908,19 @@ "400": { "description": "Bad Request", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "401": { "description": "Неизвестное название клиента", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -859,13 +963,13 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -906,13 +1010,13 @@ "description": "OK" }, "400": { - "description": "Невалидное тело запроса", + "description": "Невалидное тело запроса или неверный старый пароль", "schema": { "$ref": "#/definitions/apierrors.Error" } }, "500": { - "description": "внутренняя ошибка", + "description": "Внутренняя ошибка", "schema": { "$ref": "#/definitions/apierrors.Error" } @@ -961,19 +1065,19 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "409": { "description": "Пользователь с указанным email уже существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1020,13 +1124,49 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" + } + } + } + } + }, + "/user/download": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "Download" + ], + "summary": "Скачать список пользователей в csv", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UsersDownloadRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "500": { + "description": "Внутренняя ошибка сервиса ```{errorCode: -1}```", + "schema": { + "$ref": "#/definitions/apierrors.Error" } } } @@ -1064,13 +1204,13 @@ "400": { "description": "Bad Request", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1109,13 +1249,13 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1153,13 +1293,13 @@ "400": { "description": "Невалидный токен", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1167,7 +1307,7 @@ }, "/user/get_permissions": { "post": { - "description": "Получить все разрашения", + "description": "Получить все разрешения", "consumes": [ "application/json" ], @@ -1177,7 +1317,7 @@ "tags": [ "user" ], - "summary": "Получить все разрашения", + "summary": "Получить все разрешения", "responses": { "200": { "description": "OK", @@ -1187,6 +1327,12 @@ "$ref": "#/definitions/domain.Permission" } } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/apierrors.Error" + } } } } @@ -1220,22 +1366,22 @@ "$ref": "#/definitions/domain.AdminUserShort" } }, - "400": { + "401": { "description": "Невалидный токен", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "404": { "description": "Пользователя не существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1282,13 +1428,13 @@ "400": { "description": "Bad Request", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1335,25 +1481,25 @@ "400": { "description": "Невалидное тело запроса", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "404": { "description": "Пользователь с указанным id не существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "409": { "description": "Пользователь с указанным email уже существует", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } }, "500": { "description": "Internal Server Error", "schema": { - "$ref": "#/definitions/domain.GrpcError" + "$ref": "#/definitions/apierrors.Error" } } } @@ -1450,6 +1596,29 @@ } } }, + "domain.AuditDownloadRequest": { + "type": "object", + "required": [ + "limit" + ], + "properties": { + "limit": { + "description": "Максимальное количество записей", + "type": "integer" + }, + "offset": { + "description": "Отступ для выборки", + "type": "integer", + "format": "int64" + }, + "order": { + "$ref": "#/definitions/domain.OrderParams" + }, + "query": { + "$ref": "#/definitions/domain.AuditQuery" + } + } + }, "domain.AuditEvent": { "type": "object", "properties": { @@ -1669,21 +1838,6 @@ } } }, - "domain.GrpcError": { - "type": "object", - "properties": { - "details": { - "type": "array", - "items": {} - }, - "errorCode": { - "type": "string" - }, - "errorMessage": { - "type": "string" - } - } - }, "domain.IdRequest": { "type": "object", "required": [ @@ -1944,6 +2098,29 @@ } } }, + "domain.SessionDownloadRequest": { + "type": "object", + "required": [ + "limit" + ], + "properties": { + "limit": { + "description": "Максимальное количество записей", + "type": "integer" + }, + "offset": { + "description": "Отступ для выборки", + "type": "integer", + "format": "int64" + }, + "order": { + "$ref": "#/definitions/domain.OrderParams" + }, + "query": { + "$ref": "#/definitions/domain.SessionQuery" + } + } + }, "domain.SessionPageRequest": { "type": "object", "required": [ @@ -2235,6 +2412,29 @@ } } }, + "domain.UsersDownloadRequest": { + "type": "object", + "required": [ + "limit" + ], + "properties": { + "limit": { + "description": "Максимальное количество записей", + "type": "integer" + }, + "offset": { + "description": "Отступ для выборки", + "type": "integer", + "format": "int64" + }, + "order": { + "$ref": "#/definitions/domain.OrderParams" + }, + "query": { + "$ref": "#/definitions/domain.UserQuery" + } + } + }, "domain.UsersPageRequest": { "type": "object", "required": [ From 06acaba5b3f8d857b2d449837577a67feb3f0bcd Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 10:32:52 +0300 Subject: [PATCH 05/13] MSP-8974 add download flow test --- repository/admin.go | 35 +----- routes/routes.go | 8 +- service/download.go | 1 - tests/download_test.go | 280 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 289 insertions(+), 35 deletions(-) create mode 100644 tests/download_test.go diff --git a/repository/admin.go b/repository/admin.go index 818e61a..63025e9 100644 --- a/repository/admin.go +++ b/repository/admin.go @@ -4,19 +4,17 @@ import ( "context" "isp-admin-service/domain" "isp-admin-service/entity" - "slices" "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/http/httpcli" ) const ( - getUserById = "admin/user/get_by_id" - getAllLogs = "admin/log/all" - getAllSessions = "admin/session/all" - getAllUsers = "admin/user/get_users" - getAllRoles = "admin/role/all" - getPermissions = "admin/user/get_permissions" + getAllLogs = "/admin/log/all" + getAllSessions = "/admin/session/all" + getAllUsers = "/admin/user/get_users" + getAllRoles = "/admin/role/all" + getPermissions = "/admin/user/get_permissions" ) type ReqGetById struct { @@ -35,29 +33,6 @@ func NewAdmin(cli *httpcli.Client) Admin { return Admin{cli: cli} } -func (r Admin) GetRoleNamesByIds(ctx context.Context, roleIds []int) ([]string, error) { - if len(roleIds) == 0 { - return []string{}, nil - } - resp := make([]entity.Role, 0) - err := r.cli.Post(getAllRoles). - JsonResponseBody(&resp). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllRoles) - } - - roleNames := make([]string, 0) - for _, role := range resp { - if slices.Contains(roleIds, role.Id) { - roleNames = append(roleNames, role.Name) - } - } - - return roleNames, nil -} - func (r Admin) GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) { var response entity.AuditResponse diff --git a/routes/routes.go b/routes/routes.go index 19ed207..996bbbc 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -223,28 +223,28 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { }, // download { - Path: "/user/download", + Path: "user/download", Inner: true, Extra: cluster.RequireAdminPermission("data_download"), Handler: c.Download.Users, HttpMethod: http.MethodPost, }, { - Path: "/session/download", + Path: "session/download", Inner: true, Extra: cluster.RequireAdminPermission("data_download"), Handler: c.Download.Sessions, HttpMethod: http.MethodPost, }, { - Path: "/log/download", + Path: "log/download", Inner: true, Extra: cluster.RequireAdminPermission("data_download"), Handler: c.Download.Audit, HttpMethod: http.MethodPost, }, { - Path: "/role/download", + Path: "role/download", Inner: true, Extra: cluster.RequireAdminPermission("data_download"), Handler: c.Download.Roles, diff --git a/service/download.go b/service/download.go index 57b165d..6262d44 100644 --- a/service/download.go +++ b/service/download.go @@ -27,7 +27,6 @@ type AdminRepo interface { GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) GetRoles(ctx context.Context) ([]entity.Role, error) - GetRoleNamesByIds(ctx context.Context, roleIds []int) ([]string, error) GetPermissions(ctx context.Context) ([]entity.Permission, error) } diff --git a/tests/download_test.go b/tests/download_test.go new file mode 100644 index 0000000..ca2d0b3 --- /dev/null +++ b/tests/download_test.go @@ -0,0 +1,280 @@ +package tests_test + +import ( + "encoding/csv" + "encoding/json" + "net/http" + "testing" + "time" + + "isp-admin-service/assembly" + "isp-admin-service/conf" + "isp-admin-service/domain" + "isp-admin-service/entity" + + "github.com/stretchr/testify/suite" + + "github.com/txix-open/isp-kit/dbx" + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/test" + "github.com/txix-open/isp-kit/test/dbt" + "github.com/txix-open/isp-kit/test/httpt" +) + +func TestDownloadSuite(t *testing.T) { + t.Parallel() + suite.Run(t, &DownloadSuite{}) +} + +type DownloadSuite struct { + suite.Suite + + test *test.Test + db *dbt.TestDb + httpCli *httpcli.Client + downloadCli *httpcli.Client + permissions entity.PermList +} + +func (s *DownloadSuite) SetupTest() { + testInstance, _ := test.New(s.T()) + s.test = testInstance + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) + + remote := conf.Remote{ + Permissions: []conf.Permission{ + { + Key: "data_download", + Name: "123", + }, + }, + } + s.initMockDownload() + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.downloadCli, s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) + + server, cli := httpt.TestServer(s.test, cfg.Handler) + s.httpCli = cli + + s.permissions = entity.PermList{ + "data_download", + } + + testInstance.T().Cleanup(func() { + server.Close() + }) +} + +func (s *DownloadSuite) TestUsersHappyPath() { + id1 := InsertUser(s.db, entity.User{ + FirstName: "Alice", + LastName: "Bob", + FullName: "Bob Alice", + Email: "alice@a.ru", + Password: "password", + }) + roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + + resp, err := s.httpCli.Post("user/download"). + JsonRequestBody(domain.UsersDownloadRequest{ + LimitOffsetParams: domain.LimitOffsetParams{Limit: 1000, Offset: 0}, + }). + Do(s.T().Context()) + s.Require().NoError(err) + defer resp.Raw.Body.Close() + s.Require().Equal(http.StatusOK, resp.StatusCode()) + + records, err := csv.NewReader(resp.Raw.Body).ReadAll() + s.Require().NoError(err) + s.Require().NotEmpty(records) + + header := records[0] + col := make(map[string]int, len(header)) + for i, name := range header { + col[name] = i + } + + idIdx, ok := col["id"] + s.Require().True(ok) + emailIdx, ok := col["Email"] + s.Require().True(ok) + fullNameIdx, ok := col["Пользователь"] + s.Require().True(ok) + + s.Require().Len(records, 2) + + row := records[1] + s.Require().EqualValues("1", row[idIdx]) + s.Require().EqualValues("alice@a.ru", row[emailIdx]) + s.Require().EqualValues("Bob Alice", row[fullNameIdx]) +} + +func (s *DownloadSuite) TestSessionsHappyPath() { + id1 := InsertUser(s.db, entity.User{Email: "sess1@a.ru"}) + roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + + resp, err := s.httpCli.Post("/session/download"). + JsonRequestBody(domain.SessionDownloadRequest{ + LimitOffsetParams: domain.LimitOffsetParams{Limit: 1000, Offset: 0}, + }). + Do(s.T().Context()) + s.Require().NoError(err) + defer resp.Raw.Body.Close() + s.Require().Equal(http.StatusOK, resp.StatusCode()) + + records, err := csv.NewReader(resp.Raw.Body).ReadAll() + s.Require().NoError(err) + s.Require().NotEmpty(records) + + header := records[0] + col := make(map[string]int, len(header)) + for i, name := range header { + col[name] = i + } + + userIdx, ok := col["Пользователь"] + s.Require().True(ok) + idIdx, ok := col["Идентификатор"] + s.Require().True(ok) + + s.Require().Len(records, 2) + row := records[1] + s.Require().EqualValues("Bob Alice", row[userIdx]) + s.Require().EqualValues("1", row[idIdx]) +} + +func (s *DownloadSuite) TestAuditHappyPath() { + id1 := InsertUser(s.db, entity.User{Email: "audit1@a.ru"}) + roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + + resp, err := s.httpCli.Post("log/download"). + JsonRequestBody(domain.AuditDownloadRequest{ + LimitOffsetParams: domain.LimitOffsetParams{Limit: 1000, Offset: 0}, + }). + StatusCodeToError(). + Do(s.T().Context()) + s.Require().NoError(err) + + records, err := csv.NewReader(resp.Raw.Body).ReadAll() + s.Require().NoError(err) + s.Require().NotEmpty(records) + + header := records[0] + col := make(map[string]int, len(header)) + for i, name := range header { + col[name] = i + } + + idIdx, ok := col["Пользователь"] + s.Require().True(ok) + moveIdx, ok := col["Действие"] // уточнить + s.Require().True(ok) + + s.Require().Len(records, 2) + row := records[1] + s.Require().EqualValues("Bob Alice", row[idIdx]) + s.Require().EqualValues("audit1@a.ru", row[moveIdx]) +} + +func (s *DownloadSuite) TestRolesHappyPath() { + err := s.httpCli.Post("role/download"). + StatusCodeToError(). + DoWithoutResponse(s.T().Context()) + s.Require().NoError(err) +} + +func (s *DownloadSuite) initMockDownload() { + mocksrv := httpt.NewMock(s.test) + mocksrv.POST("/user/download", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "Items": []domain.User{{Id: 0, FullName: "Bob Alice", Email: "alice@a.ru"}}, + }) + }) + mocksrv.POST("/session/download", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "Items": []domain.User{{Id: 0, FullName: "Sess1", Email: "sess1@a.ru"}}, + }) + }) + mocksrv.POST("/log/download", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "TotalCount": 1, + "Items": []domain.Audit{{Id: 0, UserId: 0, Message: "audit1@a.ru"}}, + }) + }) + mocksrv.POST("/role/download", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "Items": []domain.User{{Id: 0, Roles: []int{0}, Email: "admin@a.ru"}}, + }) + }) + + mocksrv.POST("/admin/user/get_users", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "Items": []domain.User{{ + Id: 1, + FullName: "Bob Alice", + Email: "alice@a.ru", + }}, + "TotalCount": 1, + }) + }) + + mocksrv.POST("/admin/user/get_permissions", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode([]domain.Permission{{ + Key: "data_download", + Name: "123", + }}) + + }) + + mocksrv.POST("/admin/session/all", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "Items": []domain.Session{{ + Id: 1, + UserId: 1, + }}, + "TotalCount": 1, + }) + }) + + mocksrv.POST("/admin/log/all", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]any{ + "Items": []domain.Audit{{ + Id: 1, + UserId: 1, + Message: "audit1@a.ru", + }}, + "TotalCount": 1, + }) + }) + + mocksrv.POST("/admin/role/all", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode([]domain.Role{{ + Id: 1, + Name: "admin", + }}) + }) + + s.downloadCli = mocksrv.Client() +} From 5263e1504dcf25c114b6017b42da0ed5f9377b2c Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 10:34:18 +0300 Subject: [PATCH 06/13] MSP-8974 Bump version to 7.2.0 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c38cb79..eaccf2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ * Добавлено поле `application_group` в таблицу `roles` * Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен * Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации +* Добавлена возможность скачивания и формирования CSV ### v7.1.0 * переименование авторизации через SUDIR в OAuth: * Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth` From 11ef48bbebe20ceff33bcd56c0d7d7a5a385d88c Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 10:42:39 +0300 Subject: [PATCH 07/13] MSP-8974 up deps --- go.mod | 18 +++++----- go.sum | 105 ++++++--------------------------------------------------- 2 files changed, 20 insertions(+), 103 deletions(-) diff --git a/go.mod b/go.mod index 10c42ba..d7326e4 100644 --- a/go.mod +++ b/go.mod @@ -10,8 +10,8 @@ require ( github.com/txix-open/bgjob v1.6.0 github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/jsonschema v1.3.0 - golang.org/x/crypto v0.55.0 - golang.org/x/sync v0.22.0 + golang.org/x/crypto v0.59.0 + golang.org/x/sync v0.25.0 ) require ( @@ -73,13 +73,13 @@ require ( go.opentelemetry.io/proto/otlp v1.11.1 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect - go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/net v0.58.0 // indirect - golang.org/x/sys v0.47.0 // indirect - golang.org/x/text v0.41.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect - google.golang.org/grpc v1.83.2 // indirect + go.yaml.in/yaml/v3 v3.0.6 // indirect + golang.org/x/net v0.63.0 // indirect + golang.org/x/sys v0.50.0 // indirect + golang.org/x/text v0.44.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect + google.golang.org/grpc v1.85.0 // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 8cb1bed..9f9f2f1 100644 --- a/go.sum +++ b/go.sum @@ -19,23 +19,16 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= -github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= +github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= -github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= -github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= -github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s= -github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI= github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g= github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= -github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120= -github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg= github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k= github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -45,20 +38,13 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY= github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= -github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk= -github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= -github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= -github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME= +github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -66,8 +52,6 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk= github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= @@ -76,12 +60,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= -github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= -github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4= github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds= -github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= -github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8= github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= @@ -90,8 +70,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= -github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -110,13 +88,10 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M= github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= -github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ= -github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= -github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= -github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg= github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= @@ -128,9 +103,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= -github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= +github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM= github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= @@ -138,37 +112,24 @@ github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTw github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= -github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE= github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= -github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= -github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= -github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= -github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI= github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA= -github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= -github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4= github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= -github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek= -github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ= +github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= -github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -192,14 +153,10 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM= github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y= github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE= -github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw= -github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78= github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg= github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M= github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4= github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= -github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0= -github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA= github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs= github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw= github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc= @@ -213,44 +170,26 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17 github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE= -go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= -go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= -go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw= go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss= -go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38= go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= -go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= -go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= -go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= -go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= -go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= -go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= -go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= -go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= -go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= -go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw= go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -259,45 +198,26 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= -go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= -go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI= -go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= -go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= -golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= -golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= -golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= -golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0= golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig= -golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= -golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= -golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= -golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU= -google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0= google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY= google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA= google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g= google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= -google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= -google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= @@ -310,14 +230,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws= -modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4= modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A= +modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= -modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= -modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g= -modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog= -modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= +modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g= +modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE= From 1d1c5dbde6dc781ac61206a790de75ddede17ffa Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 10:51:17 +0300 Subject: [PATCH 08/13] MSP-8974 lint fixes --- .golangci.yml | 1 + controller/audit.go | 2 +- controller/auth.go | 2 +- domain/errors.go | 1 + repository/admin.go | 4 ---- service/download.go | 6 ++---- tests/audit_test.go | 7 ++----- tests/auth_test.go | 6 ++---- tests/download_test.go | 26 +++++++++++++------------- tests/inactive_test.go | 6 ++---- tests/session_test.go | 12 ++++-------- tests/user_test.go | 24 ++++++++---------------- 12 files changed, 37 insertions(+), 60 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 575b423..8f84c93 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -81,3 +81,4 @@ formatters: - third_party$ - builtin$ - examples$ + diff --git a/controller/audit.go b/controller/audit.go index e658865..c228e76 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -66,7 +66,7 @@ func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) { // SetEvents // @Tags log // @Summary Установить события аудита -// @Description Устанавливает (обновляет) набор активных событий аудита. `errorCode: ` - если передано неизвестное событие аудита +// @Description Устанавливает (обновляет) набор активных событий аудита. // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" diff --git a/controller/auth.go b/controller/auth.go index 7ca2801..a849497 100644 --- a/controller/auth.go +++ b/controller/auth.go @@ -116,7 +116,7 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma // LoginWithOauth // @Tags auth // @Summary Авторизация по авторизационному коду от OAuth -// @Description Авторизация с получением токена администратора. `errorCode: ` - OAuth не настроен, `` - неверный код или неизвестный клиент +// @Description Авторизация с получением токена администратора. // @Accept json // @Produce json // @Param body body domain.LoginOauthRequest true "Тело запроса" diff --git a/domain/errors.go b/domain/errors.go index ec89a31..8572df3 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -26,6 +26,7 @@ var ( ErrUnknownClient = errors.New("unknown client") ) +// nolint:gochecknoglobals var ( UnknownAuditEventErrorCode = 1 ErrOauthAuthorizationCode = 2 diff --git a/repository/admin.go b/repository/admin.go index 63025e9..411ea8d 100644 --- a/repository/admin.go +++ b/repository/admin.go @@ -21,10 +21,6 @@ type ReqGetById struct { UserId int `json:"userId"` } -type getRoleResp struct { - Roles []int `json:"roles"` -} - type Admin struct { cli *httpcli.Client } diff --git a/service/download.go b/service/download.go index 6262d44..f65409a 100644 --- a/service/download.go +++ b/service/download.go @@ -264,10 +264,8 @@ func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) erro func (s Download) getUsersList(ctx context.Context) (map[int]entity.User, error) { users, err := s.repo.GetUsers(ctx, domain.UsersDownloadRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: requestLimit, - Offset: 0, - }, + Limit: requestLimit, + Offset: 0, }) if err != nil { return nil, errors.WithMessage(err, "get users") diff --git a/tests/audit_test.go b/tests/audit_test.go index 10fc917..9681942 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -179,15 +179,12 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() { var httpErr httpcli.ErrorResponse s.Require().ErrorAs(err, &httpErr) s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) // не уверен тут какой код проверять? Статус или внутренний? Коммент чтобы не забыть - } func (s *AuditSuite) Test_All_Logs() { request := domain.AuditPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 3, - Offset: 5, - }, + Limit: 3, + Offset: 5, Order: &domain.OrderParams{ Field: "user_id", Type: "desc", diff --git a/tests/auth_test.go b/tests/auth_test.go index e11bbc8..61b23bb 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -246,10 +246,8 @@ func (s *AuthTestSuite) Test_Logout_NotFound() { time.Sleep(time.Second) audit := repository.NewAudit(s.db) auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 10, - Offset: 0, - }, + Limit: 10, + Offset: 0, Order: &domain.OrderParams{ Field: "created_at", Type: "desc", diff --git a/tests/download_test.go b/tests/download_test.go index ca2d0b3..e6beb36 100644 --- a/tests/download_test.go +++ b/tests/download_test.go @@ -1,3 +1,4 @@ +// nolint: funlen package tests_test import ( @@ -79,7 +80,7 @@ func (s *DownloadSuite) TestUsersHappyPath() { resp, err := s.httpCli.Post("user/download"). JsonRequestBody(domain.UsersDownloadRequest{ - LimitOffsetParams: domain.LimitOffsetParams{Limit: 1000, Offset: 0}, + Limit: 1000, Offset: 0, }). Do(s.T().Context()) s.Require().NoError(err) @@ -118,7 +119,7 @@ func (s *DownloadSuite) TestSessionsHappyPath() { resp, err := s.httpCli.Post("/session/download"). JsonRequestBody(domain.SessionDownloadRequest{ - LimitOffsetParams: domain.LimitOffsetParams{Limit: 1000, Offset: 0}, + Limit: 1000, Offset: 0, }). Do(s.T().Context()) s.Require().NoError(err) @@ -153,7 +154,7 @@ func (s *DownloadSuite) TestAuditHappyPath() { resp, err := s.httpCli.Post("log/download"). JsonRequestBody(domain.AuditDownloadRequest{ - LimitOffsetParams: domain.LimitOffsetParams{Limit: 1000, Offset: 0}, + Limit: 1000, Offset: 0, }). StatusCodeToError(). Do(s.T().Context()) @@ -192,21 +193,21 @@ func (s *DownloadSuite) initMockDownload() { mocksrv.POST("/user/download", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "Items": []domain.User{{Id: 0, FullName: "Bob Alice", Email: "alice@a.ru"}}, }) }) mocksrv.POST("/session/download", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "Items": []domain.User{{Id: 0, FullName: "Sess1", Email: "sess1@a.ru"}}, }) }) mocksrv.POST("/log/download", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "TotalCount": 1, "Items": []domain.Audit{{Id: 0, UserId: 0, Message: "audit1@a.ru"}}, }) @@ -214,7 +215,7 @@ func (s *DownloadSuite) initMockDownload() { mocksrv.POST("/role/download", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "Items": []domain.User{{Id: 0, Roles: []int{0}, Email: "admin@a.ru"}}, }) }) @@ -222,7 +223,7 @@ func (s *DownloadSuite) initMockDownload() { mocksrv.POST("/admin/user/get_users", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "Items": []domain.User{{ Id: 1, FullName: "Bob Alice", @@ -235,17 +236,16 @@ func (s *DownloadSuite) initMockDownload() { mocksrv.POST("/admin/user/get_permissions", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode([]domain.Permission{{ + _ = json.NewEncoder(w).Encode([]domain.Permission{{ Key: "data_download", Name: "123", }}) - }) mocksrv.POST("/admin/session/all", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "Items": []domain.Session{{ Id: 1, UserId: 1, @@ -257,7 +257,7 @@ func (s *DownloadSuite) initMockDownload() { mocksrv.POST("/admin/log/all", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode(map[string]any{ + _ = json.NewEncoder(w).Encode(map[string]any{ "Items": []domain.Audit{{ Id: 1, UserId: 1, @@ -270,7 +270,7 @@ func (s *DownloadSuite) initMockDownload() { mocksrv.POST("/admin/role/all", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) - json.NewEncoder(w).Encode([]domain.Role{{ + _ = json.NewEncoder(w).Encode([]domain.Role{{ Id: 1, Name: "admin", }}) diff --git a/tests/inactive_test.go b/tests/inactive_test.go index 50d854c..a0f01be 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -49,10 +49,8 @@ func TestInactiveWorker(t *testing.T) { require.True(user.Blocked) list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 10, - Offset: 0, - }, + Limit: 10, + Offset: 0, Order: &domain.OrderParams{ Field: "created_at", Type: "desc", diff --git a/tests/session_test.go b/tests/session_test.go index 36b3913..474bba3 100644 --- a/tests/session_test.go +++ b/tests/session_test.go @@ -116,10 +116,8 @@ func (s *SessionSuite) Test_All_Session() { // Дефолт сортировка, лимит и оффсет request := domain.SessionPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 5, - Offset: 1, - }, + Limit: 5, + Offset: 1, } var response *domain.SessionResponse @@ -207,10 +205,8 @@ func (s *SessionSuite) Test_All_Session() { } request = domain.SessionPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 5, - Offset: 0, - }, + Limit: 5, + Offset: 0, Order: &domain.OrderParams{ Field: "id", Type: "desc", diff --git a/tests/user_test.go b/tests/user_test.go index 0eea1e9..77e22d2 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -185,10 +185,8 @@ func (s *UserTestSuite) TestGetUsers() { response := domain.UsersResponse{} err := s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 5, - Offset: 1, - }, + Limit: 5, + Offset: 1, Order: &domain.OrderParams{ Field: "email", Type: "asc", @@ -213,10 +211,8 @@ func (s *UserTestSuite) TestGetUsers() { email = "test@mail.ru" err = s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 10, - Offset: 0, - }, + Limit: 10, + Offset: 0, Order: &domain.OrderParams{ Field: "id", Type: "asc", @@ -300,10 +296,8 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() { response := domain.UsersResponse{} err = s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 5, - Offset: 0, - }, + Limit: 5, + Offset: 0, Order: &domain.OrderParams{ Field: "lastSessionCreatedAt", Type: "desc", @@ -336,10 +330,8 @@ func (s *UserTestSuite) TestGetUsersSortByName() { response := domain.UsersResponse{} err := s.apiCli.Post("admin/user/get_users"). JsonRequestBody(domain.UsersPageRequest{ - LimitOffsetParams: domain.LimitOffsetParams{ - Limit: 10, - Offset: 0, - }, + Limit: 10, + Offset: 0, Order: &domain.OrderParams{ Field: "userId", Type: "asc", From 1ea3ef186c2280778698ba0d73002d9a78081b97 Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 10:51:42 +0300 Subject: [PATCH 09/13] MSP-8974 up swagger --- docs/swagger.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/swagger.json b/docs/swagger.json index ffff79f..d6ed766 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -72,7 +72,7 @@ }, "/auth/login_with_oauth": { "post": { - "description": "Авторизация с получением токена администратора. `errorCode: \u003cErrOauthIsMissedCode\u003e` - OAuth не настроен, `\u003cErrUnauthenticatedCode\u003e` - неверный код или неизвестный клиент", + "description": "Авторизация с получением токена администратора.", "consumes": [ "application/json" ], @@ -353,7 +353,7 @@ }, "/log/set_events": { "post": { - "description": "Устанавливает (обновляет) набор активных событий аудита. `errorCode: \u003cUnknownAuditEventErrorCode\u003e` - если передано неизвестное событие аудита", + "description": "Устанавливает (обновляет) набор активных событий аудита.", "consumes": [ "application/json" ], From 7bac2e403f94f2afe3380e5d63c4fd5b767d423c Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 15:41:28 +0300 Subject: [PATCH 10/13] MSP-8974 review fixes --- assembly/assembly.go | 15 ++- assembly/locator.go | 30 +++--- auth/auth.go | 80 ---------------- controller/audit.go | 1 - controller/download.go | 18 ++-- docs/swagger.json | 76 +-------------- domain/errors.go | 20 ++-- domain/session.go | 23 +++++ entity/download.go | 12 --- repository/admin.go | 103 -------------------- service/download.go | 76 +++++++-------- tests/audit_test.go | 4 +- tests/auth_test.go | 2 +- tests/customization_test.go | 2 +- tests/download_test.go | 183 ++++++++++++++---------------------- tests/inactive_test.go | 2 +- tests/secure_test.go | 2 +- tests/session_test.go | 2 +- tests/ui_settings_test.go | 2 +- tests/user_test.go | 2 +- 20 files changed, 189 insertions(+), 466 deletions(-) delete mode 100644 repository/admin.go diff --git a/assembly/assembly.go b/assembly/assembly.go index 66390f6..e249b8b 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -24,13 +24,12 @@ import ( ) type Assembly struct { - boot *bootstrap.Bootstrap - db *dbrx.Client - server *http.Server - downloadCli *httpcli.Client - oauthCli *httpcli.Client - logger *log.Adapter - bgjobCli *bgjobx.Client + boot *bootstrap.Bootstrap + db *dbrx.Client + server *http.Server + oauthCli *httpcli.Client + logger *log.Adapter + bgjobCli *bgjobx.Client } func New(boot *bootstrap.Bootstrap) (*Assembly, error) { @@ -74,7 +73,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error } a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl - locator := NewLocator(a.logger, a.oauthCli, a.downloadCli, a.db) + locator := NewLocator(a.logger, a.oauthCli, a.db) config, err := locator.Config(ctx, newCfg, time.Minute) if err != nil { a.logger.Fatal(ctx, errors.WithMessage(err, "locator config")) diff --git a/assembly/locator.go b/assembly/locator.go index 256dd7f..0e3cbae 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -18,7 +18,7 @@ import ( "github.com/txix-open/isp-kit/bgjobx" "github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/errors" - httpEndpoint "github.com/txix-open/isp-kit/http/endpoint" + "github.com/txix-open/isp-kit/http/endpoint" "github.com/txix-open/isp-kit/http/endpoint/httplog" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/router" @@ -31,18 +31,16 @@ type DB interface { } type Locator struct { - logger log.Logger - downloadCli *httpcli.Client - oauthCli *httpcli.Client - db DB + logger log.Logger + oauthCli *httpcli.Client + db DB } -func NewLocator(logger log.Logger, oauthCli *httpcli.Client, downloadCli *httpcli.Client, db DB) Locator { +func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator { return Locator{ - logger: logger, - downloadCli: downloadCli, - oauthCli: oauthCli, - db: db, + logger: logger, + oauthCli: oauthCli, + db: db, } } @@ -64,11 +62,9 @@ func (l Locator) Config( auditRepo := repository.NewAudit(l.db) auditEventRepo := repository.NewAuditEvent(l.db) userRoleRepo := repository.NewUserRole(l.db) - adminRepo := repository.NewAdmin(l.downloadCli) auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings) tokenService := service.NewToken(tokenRepo, cfg.ExpireSec) - downloadService := service.NewDownload(adminRepo) oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth) oauthService, err := service.NewOauth(oauthSettings, oauthRepo) @@ -102,6 +98,14 @@ func (l Locator) Config( uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings) + downloadService := service.NewDownload( + auditService, + userService, + tokenService, + roleService, + *permissionsService, + ) + userController := controller.NewUser(userService) customizationController := controller.NewCustomization(cfg.UiDesign) authController := controller.NewAuth(authService, l.logger) @@ -113,7 +117,7 @@ func (l Locator) Config( uiSettingsController := controller.NewUiSettings(uiSettingsService) downloadController := controller.NewDownload(downloadService) - wrapper := httpEndpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true)) + wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true)) handler := routes.Handler( wrapper, routes.Controllers{ diff --git a/auth/auth.go b/auth/auth.go index 8213e91..498eecd 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -7,86 +7,6 @@ import ( "github.com/txix-open/isp-kit/errors" ) -const ( - // ApplicationIdHeader is the header key for application identity. - ApplicationIdHeader = "x-application-identity" - // ApplicationNameHeader is the header key for application name. - ApplicationNameHeader = "x-application-name" - // UserIdHeader is the header key for user identity. - UserIdHeader = "x-user-identity" - // DeviceIdHeader is the header key for device identity. - DeviceIdHeader = "x-device-identity" - // ServiceIdHeader is the header key for service identity. - ServiceIdHeader = "x-service-identity" - // DomainIdHeader is the header key for domain identity. - DomainIdHeader = "x-domain-identity" - // SystemIdHeader is the header key for system identity. - SystemIdHeader = "x-system-identity" - // UserTokenHeader is the header key for user token. - UserTokenHeader = "x-user-token" - // DeviceTokenHeader is the header key for device token. - DeviceTokenHeader = "x-device-token" -) - -// AuthData wraps http.Header to provide structured access to authentication -// and authorization information from http request header. -// All methods return an error if the key is not found or cannot be parsed. -type AuthData http.Header - -// SystemId extracts the system identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) SystemId() (int, error) { - return IntFromHeader(SystemIdHeader, http.Header(i)) -} - -// DomainId extracts the domain identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) DomainId() (int, error) { - return IntFromHeader(DomainIdHeader, http.Header(i)) -} - -// ServiceId extracts the service identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) ServiceId() (int, error) { - return IntFromHeader(ServiceIdHeader, http.Header(i)) -} - -// ApplicationId extracts the application identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) ApplicationId() (int, error) { - return IntFromHeader(ApplicationIdHeader, http.Header(i)) -} - -// ApplicationName extracts the application name from header as a string. -// Returns an error if the key is not found. -func (i AuthData) ApplicationName() (string, error) { - return StringFromHeader(ApplicationNameHeader, http.Header(i)) -} - -// UserId extracts the user identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) UserId() (int, error) { - return IntFromHeader(UserIdHeader, http.Header(i)) -} - -// DeviceId extracts the device identity from header as an integer. -// Returns an error if the key is not found or the value cannot be parsed as an integer. -func (i AuthData) DeviceId() (int, error) { - return IntFromHeader(DeviceIdHeader, http.Header(i)) -} - -// UserToken extracts the user token from header as a string. -// Returns an error if the key is not found. -func (i AuthData) UserToken() (string, error) { - return StringFromHeader(UserTokenHeader, http.Header(i)) -} - -// DeviceToken extracts the device token from header as a string. -// Returns an error if the key is not found. -func (i AuthData) DeviceToken() (string, error) { - return StringFromHeader(DeviceTokenHeader, http.Header(i)) -} - // StringFromHeader extracts a string value from header by key. // Returns an error if header is nil or the key is not found. func StringFromHeader(key string, h http.Header) (string, error) { diff --git a/controller/audit.go b/controller/audit.go index c228e76..3650203 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -29,7 +29,6 @@ func NewAudit(service AuditService) Audit { // All // @Tags log // @Summary Получение списка логов -// @Description `errorCode: 400` - если тело запроса невалидно // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" diff --git a/controller/download.go b/controller/download.go index 7cabac1..6b10796 100644 --- a/controller/download.go +++ b/controller/download.go @@ -10,9 +10,9 @@ import ( ) type DownloadService interface { - DownloadUsers(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error - DownloadSessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error - DownloadAudit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error + DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error + DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error + DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error DownloadRoles(ctx context.Context, w http.ResponseWriter) error } @@ -31,11 +31,11 @@ func NewDownload(service DownloadService) Download { // @Summary Скачать список пользователей в csv // @Accept json // @Produce json -// @Param body body domain.UsersDownloadRequest true "Тело запроса" +// @Param body body domain.UsersPageRequest true "Тело запроса" // @Success 200 // @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /user/download [POST] -func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { +func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error { err := c.service.DownloadUsers(ctx, req, w) if err != nil { return errors.WithMessage(err, "download users") @@ -49,11 +49,11 @@ func (c Download) Users(ctx context.Context, req domain.UsersDownloadRequest, w // @Summary Скачать список сессий в csv // @Accept json // @Produce json -// @Param body body domain.SessionDownloadRequest true "Тело запроса" +// @Param body body domain.SessionPageRequest true "Тело запроса" // @Success 200 // @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /session/download [POST] -func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { +func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error { err := c.service.DownloadSessions(ctx, req, w) if err != nil { return errors.WithMessage(err, "download sessions") @@ -67,11 +67,11 @@ func (c Download) Sessions(ctx context.Context, req domain.SessionDownloadReques // @Summary Скачать журнал аудита в csv // @Accept json // @Produce json -// @Param body body domain.AuditDownloadRequest true "Тело запроса" +// @Param body body domain.AuditPageRequest true "Тело запроса" // @Success 200 // @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" // @Router /log/download [POST] -func (c Download) Audit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { +func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error { err := c.service.DownloadAudit(ctx, req, w) if err != nil { return errors.WithMessage(err, "download audit") diff --git a/docs/swagger.json b/docs/swagger.json index d6ed766..2c2b503 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -223,7 +223,6 @@ }, "/log/all": { "post": { - "description": "`errorCode: 400` - если тело запроса невалидно", "consumes": [ "application/json" ], @@ -293,7 +292,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.AuditDownloadRequest" + "$ref": "#/definitions/domain.AuditPageRequest" } } ], @@ -808,7 +807,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.SessionDownloadRequest" + "$ref": "#/definitions/domain.SessionPageRequest" } } ], @@ -1155,7 +1154,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/domain.UsersDownloadRequest" + "$ref": "#/definitions/domain.UsersPageRequest" } } ], @@ -1596,29 +1595,6 @@ } } }, - "domain.AuditDownloadRequest": { - "type": "object", - "required": [ - "limit" - ], - "properties": { - "limit": { - "description": "Максимальное количество записей", - "type": "integer" - }, - "offset": { - "description": "Отступ для выборки", - "type": "integer", - "format": "int64" - }, - "order": { - "$ref": "#/definitions/domain.OrderParams" - }, - "query": { - "$ref": "#/definitions/domain.AuditQuery" - } - } - }, "domain.AuditEvent": { "type": "object", "properties": { @@ -2098,29 +2074,6 @@ } } }, - "domain.SessionDownloadRequest": { - "type": "object", - "required": [ - "limit" - ], - "properties": { - "limit": { - "description": "Максимальное количество записей", - "type": "integer" - }, - "offset": { - "description": "Отступ для выборки", - "type": "integer", - "format": "int64" - }, - "order": { - "$ref": "#/definitions/domain.OrderParams" - }, - "query": { - "$ref": "#/definitions/domain.SessionQuery" - } - } - }, "domain.SessionPageRequest": { "type": "object", "required": [ @@ -2412,29 +2365,6 @@ } } }, - "domain.UsersDownloadRequest": { - "type": "object", - "required": [ - "limit" - ], - "properties": { - "limit": { - "description": "Максимальное количество записей", - "type": "integer" - }, - "offset": { - "description": "Отступ для выборки", - "type": "integer", - "format": "int64" - }, - "order": { - "$ref": "#/definitions/domain.OrderParams" - }, - "query": { - "$ref": "#/definitions/domain.UserQuery" - } - } - }, "domain.UsersPageRequest": { "type": "object", "required": [ diff --git a/domain/errors.go b/domain/errors.go index 8572df3..416c46d 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -28,16 +28,16 @@ var ( // nolint:gochecknoglobals var ( - UnknownAuditEventErrorCode = 1 - ErrOauthAuthorizationCode = 2 - ErrUnauthenticatedCode = 3 - ErrTooManyLoginRequestsCode = 4 - ErrOauthIsMissedCode = 5 - ErrAlreadyExistsCode = 6 - ErrNotFoundCode = 7 - ErrUnknownClientCode = 8 - ErrInvalidCode = 9 - ErrInvalidPasswordCode = 10 + UnknownAuditEventErrorCode = 601 + ErrOauthAuthorizationCode = 602 + ErrUnauthenticatedCode = 603 + ErrTooManyLoginRequestsCode = 604 + ErrOauthIsMissedCode = 605 + ErrAlreadyExistsCode = 606 + ErrNotFoundCode = 607 + ErrUnknownClientCode = 608 + ErrInvalidCode = 609 + ErrInvalidPasswordCode = 610 ) type UnknownAuditEventError struct { diff --git a/domain/session.go b/domain/session.go index 7a6061a..bc76be9 100644 --- a/domain/session.go +++ b/domain/session.go @@ -4,6 +4,17 @@ import ( "time" ) +const ( + SessionStatusAllowed = "ALLOWED" + SessionStatusAllowedRus = "Активная" + + SessionStatusExpired = "EXPIRED" + SessionStatusExpiredRus = "Истекшая" + + SessionStatusRevoked = "REVOKED" + SessionStatusRevokedRus = "Отмененная" +) + type Session struct { Id int // Идентификатор сессии UserId int // Идентификатор пользоватеккля @@ -35,3 +46,15 @@ type SessionResponse struct { type RevokeRequest struct { Id int `validate:"required"` // Идентификатор сессии } + +func (s Session) StatusRus() string { + switch s.Status { + case SessionStatusAllowed: + return SessionStatusAllowedRus + case SessionStatusExpired: + return SessionStatusExpiredRus + case SessionStatusRevoked: + return SessionStatusRevokedRus + } + return "" +} diff --git a/entity/download.go b/entity/download.go index 01e4679..0565765 100644 --- a/entity/download.go +++ b/entity/download.go @@ -31,18 +31,6 @@ type SessionResponse struct { Items []Session } -func (s Session) StatusRus() string { - switch s.Status { - case SessionStatusAllowed: - return SessionStatusAllowedRus - case SessionStatusExpired: - return SessionStatusExpiredRus - case SessionStatusRevoked: - return SessionStatusRevokedRus - } - return "" -} - type UsersResponse struct { Items []User } diff --git a/repository/admin.go b/repository/admin.go deleted file mode 100644 index 411ea8d..0000000 --- a/repository/admin.go +++ /dev/null @@ -1,103 +0,0 @@ -package repository - -import ( - "context" - "isp-admin-service/domain" - "isp-admin-service/entity" - - "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/http/httpcli" -) - -const ( - getAllLogs = "/admin/log/all" - getAllSessions = "/admin/session/all" - getAllUsers = "/admin/user/get_users" - getAllRoles = "/admin/role/all" - getPermissions = "/admin/user/get_permissions" -) - -type ReqGetById struct { - UserId int `json:"userId"` -} - -type Admin struct { - cli *httpcli.Client -} - -func NewAdmin(cli *httpcli.Client) Admin { - return Admin{cli: cli} -} - -func (r Admin) GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) { - var response entity.AuditResponse - - err := r.cli.Post(getAllLogs). - JsonRequestBody(req). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllLogs) - } - - return &response, nil -} - -func (r Admin) GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) { - var response entity.SessionResponse - - err := r.cli.Post(getAllSessions). - JsonRequestBody(req). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllSessions) - } - - return &response, nil -} - -func (r Admin) GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) { - var response entity.UsersResponse - - err := r.cli.Post(getAllUsers). - JsonRequestBody(req). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllUsers) - } - - return response.Items, nil -} - -func (r Admin) GetRoles(ctx context.Context) ([]entity.Role, error) { - var response []entity.Role - - err := r.cli.Post(getAllRoles). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getAllRoles) - } - - return response, nil -} - -func (r Admin) GetPermissions(ctx context.Context) ([]entity.Permission, error) { - var response []entity.Permission - - err := r.cli.Post(getPermissions). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessagef(err, "http client request %s", getPermissions) - } - - return response, nil -} diff --git a/service/download.go b/service/download.go index f65409a..d6a68ad 100644 --- a/service/download.go +++ b/service/download.go @@ -22,32 +22,38 @@ const ( notFoundSymbol = "-" ) -type AdminRepo interface { - GetAudit(ctx context.Context, req domain.AuditDownloadRequest) (*entity.AuditResponse, error) - GetSessions(ctx context.Context, req domain.SessionDownloadRequest) (*entity.SessionResponse, error) - GetUsers(ctx context.Context, req domain.UsersDownloadRequest) ([]entity.User, error) - GetRoles(ctx context.Context) ([]entity.Role, error) - GetPermissions(ctx context.Context) ([]entity.Permission, error) -} - type Download struct { - repo AdminRepo - loc *time.Location + auditService Audit + userService User + tokenService Token + roleService Role + permissionService Permission + loc *time.Location } -func NewDownload(repo AdminRepo) Download { +func NewDownload( + auditService Audit, + userService User, + tokenService Token, + roleService Role, + permissionService Permission, +) Download { loc, _ := time.LoadLocation("Europe/Moscow") return Download{ - repo: repo, - loc: loc, + auditService: auditService, + userService: userService, + tokenService: tokenService, + roleService: roleService, + permissionService: permissionService, + loc: loc, } } -func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadRequest, w http.ResponseWriter) error { +func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error { req.Limit = requestLimit req.Offset = 0 - response, err := s.repo.GetAudit(ctx, req) + response, err := s.auditService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get audit") } @@ -90,7 +96,7 @@ func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadReq } req.Offset += requestLimit - response, err = s.repo.GetAudit(ctx, req) + response, err = s.auditService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get audit") } @@ -101,11 +107,11 @@ func (s Download) DownloadAudit(ctx context.Context, req domain.AuditDownloadReq return nil } -func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownloadRequest, w http.ResponseWriter) error { +func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error { req.Limit = requestLimit req.Offset = 0 - response, err := s.repo.GetSessions(ctx, req) + response, err := s.tokenService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get sessions") } @@ -152,7 +158,7 @@ func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownlo } req.Offset += requestLimit - response, err = s.repo.GetSessions(ctx, req) + response, err = s.tokenService.All(ctx, req) if err != nil { return errors.WithMessage(err, "get sessions") } @@ -163,21 +169,21 @@ func (s Download) DownloadSessions(ctx context.Context, req domain.SessionDownlo return nil } -func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadRequest, w http.ResponseWriter) error { +func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error { req.Limit = requestLimit req.Offset = 0 - users, err := s.repo.GetUsers(ctx, req) + users, err := s.userService.GetUsers(ctx, req) if err != nil { return errors.WithMessage(err, "get users") } - roles, err := s.repo.GetRoles(ctx) + roles, err := s.roleService.All(ctx) if err != nil { return errors.WithMessage(err, "get roles") } - if len(users) == 0 { + if len(users.Items) == 0 { return nil } @@ -193,7 +199,7 @@ func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadReq return errors.WithMessage(err, "write userColumns to csv") } - for _, user := range users { + for _, user := range users.Items { row := []string{strconv.Itoa(int(user.Id)), user.FullName, user.Description, @@ -211,15 +217,12 @@ func (s Download) DownloadUsers(ctx context.Context, req domain.UsersDownloadReq } func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error { - roles, err := s.repo.GetRoles(ctx) + roles, err := s.roleService.All(ctx) if err != nil { return errors.WithMessage(err, "get roles") } - perms, err := s.repo.GetPermissions(ctx) - if err != nil { - return errors.WithMessage(err, "get permissions") - } + perms := s.permissionService.All(ctx) if len(perms) == 0 { return nil @@ -262,24 +265,21 @@ func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) erro return nil } -func (s Download) getUsersList(ctx context.Context) (map[int]entity.User, error) { - users, err := s.repo.GetUsers(ctx, domain.UsersDownloadRequest{ - Limit: requestLimit, - Offset: 0, - }) +func (s Download) getUsersList(ctx context.Context) (map[int]domain.User, error) { + users, err := s.userService.GetAllUsers(ctx) if err != nil { return nil, errors.WithMessage(err, "get users") } - userById := make(map[int]entity.User) - for _, user := range users { + userById := make(map[int]domain.User) + for _, user := range users.Items { userById[int(user.Id)] = user } return userById, nil } -func getUsername(userById map[int]entity.User, userId int) string { +func getUsername(userById map[int]domain.User, userId int) string { user, ok := userById[userId] if !ok { return "" @@ -288,7 +288,7 @@ func getUsername(userById map[int]entity.User, userId int) string { return user.FullName } -func getRoleNamesByIds(roles []entity.Role, roleIds []int) string { +func getRoleNamesByIds(roles []domain.Role, roleIds []int) string { names := make([]string, 0) for _, role := range roles { if slices.Contains(roleIds, role.Id) { diff --git a/tests/audit_test.go b/tests/audit_test.go index 9681942..883a75a 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -68,7 +68,7 @@ func (s *AuditSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), httpcli.New(), s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) s.insertAuditLogs() @@ -178,7 +178,7 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() { var httpErr httpcli.ErrorResponse s.Require().ErrorAs(err, &httpErr) - s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) // не уверен тут какой код проверять? Статус или внутренний? Коммент чтобы не забыть + s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode) } func (s *AuditSuite) Test_All_Logs() { diff --git a/tests/auth_test.go b/tests/auth_test.go index 61b23bb..9549cd7 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -74,7 +74,7 @@ func (s *AuthTestSuite) SetupTest() { }, } - cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, httpcli.New(), s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) diff --git a/tests/customization_test.go b/tests/customization_test.go index 56c6729..734fa7a 100644 --- a/tests/customization_test.go +++ b/tests/customization_test.go @@ -40,7 +40,7 @@ func (s *CustomizationTestSuite) SetupTest() { }, ExpireSec: 0, } - cfg, err := assembly.NewLocator(testInstance.Logger(), nil, nil, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) diff --git a/tests/download_test.go b/tests/download_test.go index e6beb36..29ea6e9 100644 --- a/tests/download_test.go +++ b/tests/download_test.go @@ -3,7 +3,6 @@ package tests_test import ( "encoding/csv" - "encoding/json" "net/http" "testing" "time" @@ -12,6 +11,7 @@ import ( "isp-admin-service/conf" "isp-admin-service/domain" "isp-admin-service/entity" + "isp-admin-service/repository" "github.com/stretchr/testify/suite" @@ -33,7 +33,6 @@ type DownloadSuite struct { test *test.Test db *dbt.TestDb httpCli *httpcli.Client - downloadCli *httpcli.Client permissions entity.PermList } @@ -50,8 +49,7 @@ func (s *DownloadSuite) SetupTest() { }, }, } - s.initMockDownload() - cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.downloadCli, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) @@ -79,8 +77,13 @@ func (s *DownloadSuite) TestUsersHappyPath() { InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) resp, err := s.httpCli.Post("user/download"). - JsonRequestBody(domain.UsersDownloadRequest{ - Limit: 1000, Offset: 0, + JsonRequestBody(domain.UsersPageRequest{ + Limit: 1000, + Offset: 0, + Order: &domain.OrderParams{ + Field: "id", + Type: "desc", + }, }). Do(s.T().Context()) s.Require().NoError(err) @@ -104,22 +107,53 @@ func (s *DownloadSuite) TestUsersHappyPath() { fullNameIdx, ok := col["Пользователь"] s.Require().True(ok) - s.Require().Len(records, 2) + s.Require().Len(records, 4) row := records[1] - s.Require().EqualValues("1", row[idIdx]) + s.Require().EqualValues("3", row[idIdx]) s.Require().EqualValues("alice@a.ru", row[emailIdx]) s.Require().EqualValues("Bob Alice", row[fullNameIdx]) } func (s *DownloadSuite) TestSessionsHappyPath() { - id1 := InsertUser(s.db, entity.User{Email: "sess1@a.ru"}) + timeNow := time.Now().UTC() + userId := InsertUser(s.db, entity.User{Email: "sess1@a.ru", FullName: "Bob Alice"}) roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) - InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)}) + + InsertTokenEntity(s.db, entity.Token{ + Token: "test_token_1", + UserId: userId, + Status: entity.TokenStatusAllowed, + ExpiredAt: timeNow.Add(1 * time.Hour), + CreatedAt: timeNow.Add(-1 * time.Hour), + UpdatedAt: timeNow, + }) + InsertTokenEntity(s.db, entity.Token{ + Token: "test_token_2", + UserId: userId, + Status: entity.TokenStatusRevoked, + ExpiredAt: timeNow.Add(1 * time.Hour), + CreatedAt: timeNow.Add(-2 * time.Hour), + UpdatedAt: timeNow, + }) + InsertTokenEntity(s.db, entity.Token{ + Token: "test_token_3", + UserId: userId, + Status: entity.TokenStatusExpired, + ExpiredAt: timeNow.Add(-1 * time.Hour), + CreatedAt: timeNow.Add(-3 * time.Hour), + UpdatedAt: timeNow, + }) resp, err := s.httpCli.Post("/session/download"). - JsonRequestBody(domain.SessionDownloadRequest{ - Limit: 1000, Offset: 0, + JsonRequestBody(domain.SessionPageRequest{ + Limit: 1000, + Offset: 0, + Order: &domain.OrderParams{ + Field: "user_id", + Type: "desc", + }, }). Do(s.T().Context()) s.Require().NoError(err) @@ -141,20 +175,36 @@ func (s *DownloadSuite) TestSessionsHappyPath() { idIdx, ok := col["Идентификатор"] s.Require().True(ok) - s.Require().Len(records, 2) + s.Require().Len(records, 4) row := records[1] s.Require().EqualValues("Bob Alice", row[userIdx]) s.Require().EqualValues("1", row[idIdx]) } func (s *DownloadSuite) TestAuditHappyPath() { - id1 := InsertUser(s.db, entity.User{Email: "audit1@a.ru"}) + timeNow := time.Now().UTC() + userId := InsertUser(s.db, entity.User{Email: "audit1@a.ru", FullName: "Bob Alice"}) roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions}) - InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)}) + InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)}) + + auditRepo := repository.NewAudit(s.db) + _, err := auditRepo.Insert(s.T().Context(), entity.Audit{ + Id: 1, + UserId: int(userId), + Message: "audit1@a.ru", + Event: "123456", + CreatedAt: timeNow, + }) + s.Require().NoError(err) resp, err := s.httpCli.Post("log/download"). - JsonRequestBody(domain.AuditDownloadRequest{ - Limit: 1000, Offset: 0, + JsonRequestBody(domain.AuditPageRequest{ + Limit: 1000, + Offset: 0, + Order: &domain.OrderParams{ + Field: "user_id", + Type: "desc", + }, }). StatusCodeToError(). Do(s.T().Context()) @@ -172,7 +222,7 @@ func (s *DownloadSuite) TestAuditHappyPath() { idIdx, ok := col["Пользователь"] s.Require().True(ok) - moveIdx, ok := col["Действие"] // уточнить + moveIdx, ok := col["Действие"] s.Require().True(ok) s.Require().Len(records, 2) @@ -182,99 +232,12 @@ func (s *DownloadSuite) TestAuditHappyPath() { } func (s *DownloadSuite) TestRolesHappyPath() { - err := s.httpCli.Post("role/download"). + resp, err := s.httpCli.Post("role/download"). StatusCodeToError(). - DoWithoutResponse(s.T().Context()) + Do(s.T().Context()) s.Require().NoError(err) -} -func (s *DownloadSuite) initMockDownload() { - mocksrv := httpt.NewMock(s.test) - mocksrv.POST("/user/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{Id: 0, FullName: "Bob Alice", Email: "alice@a.ru"}}, - }) - }) - mocksrv.POST("/session/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{Id: 0, FullName: "Sess1", Email: "sess1@a.ru"}}, - }) - }) - mocksrv.POST("/log/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "TotalCount": 1, - "Items": []domain.Audit{{Id: 0, UserId: 0, Message: "audit1@a.ru"}}, - }) - }) - mocksrv.POST("/role/download", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{Id: 0, Roles: []int{0}, Email: "admin@a.ru"}}, - }) - }) - - mocksrv.POST("/admin/user/get_users", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.User{{ - Id: 1, - FullName: "Bob Alice", - Email: "alice@a.ru", - }}, - "TotalCount": 1, - }) - }) - - mocksrv.POST("/admin/user/get_permissions", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode([]domain.Permission{{ - Key: "data_download", - Name: "123", - }}) - }) - - mocksrv.POST("/admin/session/all", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.Session{{ - Id: 1, - UserId: 1, - }}, - "TotalCount": 1, - }) - }) - - mocksrv.POST("/admin/log/all", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode(map[string]any{ - "Items": []domain.Audit{{ - Id: 1, - UserId: 1, - Message: "audit1@a.ru", - }}, - "TotalCount": 1, - }) - }) - - mocksrv.POST("/admin/role/all", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _ = json.NewEncoder(w).Encode([]domain.Role{{ - Id: 1, - Name: "admin", - }}) - }) - - s.downloadCli = mocksrv.Client() + records, err := csv.NewReader(resp.Raw.Body).ReadAll() + s.Require().NoError(err) + s.Require().NotEmpty(records) } diff --git a/tests/inactive_test.go b/tests/inactive_test.go index a0f01be..e96e04a 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -27,7 +27,7 @@ func TestInactiveWorker(t *testing.T) { userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)}) InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()}) - config, err := assembly.NewLocator(test.Logger(), nil, nil, db). + config, err := assembly.NewLocator(test.Logger(), nil, db). Config(t.Context(), conf.Remote{ BlockInactiveWorker: conf.BlockInactiveWorker{ DaysThreshold: 1, diff --git a/tests/secure_test.go b/tests/secure_test.go index 2255a9a..7327d31 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -39,7 +39,7 @@ func (s *SecureSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 3600, } - cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, nil, s.db). + cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) diff --git a/tests/session_test.go b/tests/session_test.go index 474bba3..f8a23b7 100644 --- a/tests/session_test.go +++ b/tests/session_test.go @@ -70,7 +70,7 @@ func (s *SessionSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), nil, s.db). + config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). Config(s.T().Context(), remote, 500*time.Millisecond) s.Require().NoError(err) diff --git a/tests/ui_settings_test.go b/tests/ui_settings_test.go index a507093..740007b 100644 --- a/tests/ui_settings_test.go +++ b/tests/ui_settings_test.go @@ -49,7 +49,7 @@ func (s *UiSettingsSuite) SetupTest() { Clients: []conf.OauthClientConfig{s.oauthClientSetting}, }, } - cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil, nil). + cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil). Config(s.T().Context(), remote, 0) s.Require().NoError(err) diff --git a/tests/user_test.go b/tests/user_test.go index 77e22d2..ed0d529 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -54,7 +54,7 @@ func (s *UserTestSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 0, } - cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, nil, s.db). + cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db). Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) From ebc99c6ae4289657c1a2e1fa1076d1951c508a4b Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 18:21:29 +0300 Subject: [PATCH 11/13] MSP-8974 remove unused structs --- domain/download.go | 20 -------------------- entity/download.go | 29 ----------------------------- 2 files changed, 49 deletions(-) delete mode 100644 domain/download.go diff --git a/domain/download.go b/domain/download.go deleted file mode 100644 index 4cc34f6..0000000 --- a/domain/download.go +++ /dev/null @@ -1,20 +0,0 @@ -package domain - -type AuditDownloadRequest struct { - LimitOffsetParams - - Order *OrderParams - Query *AuditQuery -} -type SessionDownloadRequest struct { - LimitOffsetParams - - Order *OrderParams - Query *SessionQuery -} -type UsersDownloadRequest struct { - LimitOffsetParams - - Order *OrderParams - Query *UserQuery -} diff --git a/entity/download.go b/entity/download.go index 0565765..6d2ecd5 100644 --- a/entity/download.go +++ b/entity/download.go @@ -1,7 +1,5 @@ package entity -import "time" - const ( SessionStatusAllowed = "ALLOWED" SessionStatusAllowedRus = "Активная" @@ -13,33 +11,6 @@ const ( SessionStatusRevokedRus = "Отмененная" ) -type AuditResponse struct { - TotalCount int - Items []Audit -} - -type Session struct { - Id int - UserId int - Status string - ExpiredAt time.Time - CreatedAt time.Time -} - -type SessionResponse struct { - TotalCount int - Items []Session -} - -type UsersResponse struct { - Items []User -} - -type Permission struct { - Key string - Name string -} - func AuditColumnNames() []string { return []string{"Пользователь", "Время события", "Действие"} } From 24a8ea2578195350ed65c7b61547073757f8cf3d Mon Sep 17 00:00:00 2001 From: chashintv Date: Fri, 20 Nov 2026 18:43:43 +0300 Subject: [PATCH 12/13] MSP-8974 fix --- assembly/locator.go | 2 +- controller/audit.go | 63 +++++------ controller/auth.go | 92 ++++++++-------- controller/customization.go | 21 ++-- controller/download.go | 66 ++++++------ controller/permissions.go | 17 +-- controller/role.go | 99 +++++++++--------- controller/secure.go | 38 +++---- controller/session.go | 42 ++++---- controller/ui_settings.go | 23 ++-- controller/user.go | 203 +++++++++++++++++++----------------- docs/swagger.json | 8 +- domain/errors.go | 3 +- main.go | 12 +-- service/permission.go | 6 +- 15 files changed, 362 insertions(+), 333 deletions(-) diff --git a/assembly/locator.go b/assembly/locator.go index 0e3cbae..e5a1421 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -103,7 +103,7 @@ func (l Locator) Config( userService, tokenService, roleService, - *permissionsService, + permissionsService, ) userController := controller.NewUser(userService) diff --git a/controller/audit.go b/controller/audit.go index 3650203..c93d1b2 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -27,16 +27,17 @@ func NewAudit(service AuditService) Audit { } // All -// @Tags log -// @Summary Получение списка логов -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)" -// @Success 200 {object} domain.AuditResponse -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /log/all [POST] +// +// @Tags log +// @Summary Получение списка логов +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)" +// @Success 200 {object} domain.AuditResponse +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /log/all [POST] func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) { if req.Order == nil { req.Order = &domain.OrderParams{ @@ -49,31 +50,33 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au } // Events -// @Tags log -// @Summary Получение списка событий аудита -// @Description Возвращает полный список доступных событий аудита -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 {array} domain.AuditEvent -// @Failure 500 {object} apierrors.Error -// @Router /log/events [POST] +// +// @Tags log +// @Summary Получение списка событий аудита +// @Description Возвращает полный список доступных событий аудита +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Success 200 {array} domain.AuditEvent +// @Failure 500 {object} apierrors.Error +// @Router /log/events [POST] func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) { return c.service.Events(ctx) } // SetEvents -// @Tags log -// @Summary Установить события аудита -// @Description Устанавливает (обновляет) набор активных событий аудита. -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки" -// @Success 200 {object} map[string]interface{} "События успешно установлены" -// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита" -// @Failure 500 {object} apierrors.Error -// @Router /log/set_events [POST] +// +// @Tags log +// @Summary Установить события аудита +// @Description Устанавливает (обновляет) набор активных событий аудита. +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки" +// @Success 200 {object} map[string]interface{} "События успешно установлены" +// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита" +// @Failure 500 {object} apierrors.Error +// @Router /log/set_events [POST] func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error { err := c.service.SetEvents(ctx, req) switch { diff --git a/controller/auth.go b/controller/auth.go index a849497..6f900fd 100644 --- a/controller/auth.go +++ b/controller/auth.go @@ -32,16 +32,17 @@ func NewAuth(authService authService, logger log.Logger) Auth { } // Logout -// @Tags auth -// @Summary Выход из авторизованной сессии -// @Description Выход из авторизованной сессии администрирования -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 {object} map[string]interface{} "Успешный выход" -// @Failure 400 {object} apierrors.Error "Невалидный токен" -// @Failure 500 {object} apierrors.Error -// @Router /auth/logout [POST] +// +// @Tags auth +// @Summary Выход из авторизованной сессии +// @Description Выход из авторизованной сессии администрирования +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Success 200 {object} map[string]interface{} "Успешный выход" +// @Failure 400 {object} apierrors.Error "Невалидный токен" +// @Failure 500 {object} apierrors.Error +// @Router /auth/logout [POST] func (a Auth) Logout(ctx context.Context, r *http.Request) error { adminId, err := getAdminId(r) if err != nil { @@ -57,17 +58,18 @@ func (a Auth) Logout(ctx context.Context, r *http.Request) error { } // LogoutWithReason -// @Tags auth -// @Summary Выход по бездействию из авторизованной сессии -// @Description Выход по бездействию из авторизованной сессии администрирования -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.LogoutRequest true "Тело запроса" -// @Success 200 {object} map[string]interface{} "Успешный выход" -// @Failure 400 {object} apierrors.Error "Невалидный токен" -// @Failure 500 {object} apierrors.Error -// @Router /auth/logout_with_reason [POST] +// +// @Tags auth +// @Summary Выход по бездействию из авторизованной сессии +// @Description Выход по бездействию из авторизованной сессии администрирования +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.LogoutRequest true "Тело запроса" +// @Success 200 {object} map[string]interface{} "Успешный выход" +// @Failure 400 {object} apierrors.Error "Невалидный токен" +// @Failure 500 {object} apierrors.Error +// @Router /auth/logout_with_reason [POST] func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error { adminId, err := getAdminId(r) if err != nil { @@ -83,18 +85,19 @@ func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutR } // Login -// @Tags auth -// @Summary Авторизация по логину и паролю -// @Description Авторизация с получением токена администратора -// @Accept json -// @Produce json -// @Param body body domain.LoginRequest true "Тело запроса" -// @Success 200 {object} domain.LoginResponse -// @Failure 400 {object} apierrors.Error -// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны" -// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию" -// @Failure 500 {object} apierrors.Error -// @Router /auth/login [POST] +// +// @Tags auth +// @Summary Авторизация по логину и паролю +// @Description Авторизация с получением токена администратора +// @Accept json +// @Produce json +// @Param body body domain.LoginRequest true "Тело запроса" +// @Success 200 {object} domain.LoginResponse +// @Failure 400 {object} apierrors.Error +// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны" +// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию" +// @Failure 500 {object} apierrors.Error +// @Router /auth/login [POST] func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) { auth, err := a.authService.Login(ctx, authRequest) @@ -114,17 +117,18 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma } // LoginWithOauth -// @Tags auth -// @Summary Авторизация по авторизационному коду от OAuth -// @Description Авторизация с получением токена администратора. -// @Accept json -// @Produce json -// @Param body body domain.LoginOauthRequest true "Тело запроса" -// @Success 200 {object} domain.LoginResponse -// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере" -// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента" -// @Failure 500 {object} apierrors.Error -// @Router /auth/login_with_oauth [POST] +// +// @Tags auth +// @Summary Авторизация по авторизационному коду от OAuth +// @Description Авторизация с получением токена администратора. +// @Accept json +// @Produce json +// @Param body body domain.LoginOauthRequest true "Тело запроса" +// @Success 200 {object} domain.LoginResponse +// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере" +// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента" +// @Failure 500 {object} apierrors.Error +// @Router /auth/login_with_oauth [POST] func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) { auth, err := a.authService.LoginWithOauth(ctx, request) diff --git a/controller/customization.go b/controller/customization.go index 3681fe7..89bc0c4 100644 --- a/controller/customization.go +++ b/controller/customization.go @@ -19,16 +19,17 @@ func NewCustomization(uiCfg conf.UIDesign) Customization { } // GetUIDesign -// @Tags user -// @Summary Получение внешнего вида -// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 {object} domain.UIDesign -// @Failure 400 {object} apierrors.Error "Невалидный токен" -// @Failure 500 {object} apierrors.Error -// @Router /user/get_design [POST] +// +// @Tags user +// @Summary Получение внешнего вида +// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Success 200 {object} domain.UIDesign +// @Failure 400 {object} apierrors.Error "Невалидный токен" +// @Failure 500 {object} apierrors.Error +// @Router /user/get_design [POST] func (c Customization) GetUIDesign() (domain.UIDesign, error) { return c.uiCfg, nil } diff --git a/controller/download.go b/controller/download.go index 6b10796..b2a3929 100644 --- a/controller/download.go +++ b/controller/download.go @@ -27,14 +27,15 @@ func NewDownload(service DownloadService) Download { } // Users -// @Tags Download -// @Summary Скачать список пользователей в csv -// @Accept json -// @Produce json -// @Param body body domain.UsersPageRequest true "Тело запроса" -// @Success 200 -// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" -// @Router /user/download [POST] +// +// @Tags Download +// @Summary Скачать список пользователей в csv +// @Accept json +// @Produce text/csv +// @Param body body domain.UsersPageRequest true "Тело запроса" +// @Success 200 +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /user/download [POST] func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error { err := c.service.DownloadUsers(ctx, req, w) if err != nil { @@ -45,14 +46,15 @@ func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http } // Sessions -// @Tags Download -// @Summary Скачать список сессий в csv -// @Accept json -// @Produce json -// @Param body body domain.SessionPageRequest true "Тело запроса" -// @Success 200 -// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" -// @Router /session/download [POST] +// +// @Tags Download +// @Summary Скачать список сессий в csv +// @Accept json +// @Produce text/csv +// @Param body body domain.SessionPageRequest true "Тело запроса" +// @Success 200 +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /session/download [POST] func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error { err := c.service.DownloadSessions(ctx, req, w) if err != nil { @@ -63,14 +65,15 @@ func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w } // Audit -// @Tags Download -// @Summary Скачать журнал аудита в csv -// @Accept json -// @Produce json -// @Param body body domain.AuditPageRequest true "Тело запроса" -// @Success 200 -// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" -// @Router /log/download [POST] +// +// @Tags Download +// @Summary Скачать журнал аудита в csv +// @Accept json +// @Produce text/csv +// @Param body body domain.AuditPageRequest true "Тело запроса" +// @Success 200 +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /log/download [POST] func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error { err := c.service.DownloadAudit(ctx, req, w) if err != nil { @@ -81,13 +84,14 @@ func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http } // Roles -// @Tags Download -// @Summary Скачать матрицу ролей в csv -// @Accept json -// @Produce json -// @Success 200 -// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" -// @Router /role/download [POST] +// +// @Tags Download +// @Summary Скачать матрицу ролей в csv +// @Accept json +// @Produce text/csv +// @Success 200 +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```" +// @Router /role/download [POST] func (c Download) Roles(ctx context.Context, w http.ResponseWriter) error { err := c.service.DownloadRoles(ctx, w) if err != nil { diff --git a/controller/permissions.go b/controller/permissions.go index e8afb81..9a69671 100644 --- a/controller/permissions.go +++ b/controller/permissions.go @@ -21,14 +21,15 @@ func NewPermissions(permissionsService permissionsService) Permissions { } // GetPermissions -// @Tags user -// @Summary Получить все разрешения -// @Description Получить все разрешения -// @Accept json -// @Produce json -// @Success 200 {array} domain.Permission -// @Failure 500 {object} apierrors.Error -// @Router /user/get_permissions [POST] +// +// @Tags user +// @Summary Получить все разрешения +// @Description Получить все разрешения +// @Accept json +// @Produce json +// @Success 200 {array} domain.Permission +// @Failure 500 {object} apierrors.Error +// @Router /user/get_permissions [POST] func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission { return u.permissionsService.All(ctx) } diff --git a/controller/role.go b/controller/role.go index 876bacf..fd0fa6b 100644 --- a/controller/role.go +++ b/controller/role.go @@ -28,19 +28,19 @@ func NewRole(roleService roleService) Role { } // All -// @Tags role -// @Summary Список ролей -// @Description Получить список ролей -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.RoleAllRequest true "Тело запроса" -// @Success 200 {array} domain.Role -// @Failure 400 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /role/all [POST] -func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) { - users, err := u.roleService.All(ctx, req) +// +// @Tags role +// @Summary Список ролей +// @Description Получить список ролей +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Success 200 {array} domain.Role +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error +// @Router /role/all [POST] +func (u Role) All(ctx context.Context) ([]domain.Role, error) { + users, err := u.roleService.All(ctx) if err != nil { return nil, errors.WithMessage(err, "get roles") } @@ -49,18 +49,19 @@ func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role } // CreateRole -// @Tags role -// @Summary Создать роль -// @Description Создать роль -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.CreateRoleRequest true "Тело запроса" -// @Success 200 {object} domain.Role -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" -// @Failure 500 {object} apierrors.Error -// @Router /role/create [POST] +// +// @Tags role +// @Summary Создать роль +// @Description Создать роль +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.CreateRoleRequest true "Тело запроса" +// @Success 200 {object} domain.Role +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" +// @Failure 500 {object} apierrors.Error +// @Router /role/create [POST] func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) { adminId, err := getAdminId(r) if err != nil { @@ -79,18 +80,19 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h } // UpdateRole -// @Tags role -// @Summary Обновить роль -// @Description Обновить данные существующую роль -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.UpdateRoleRequest true "Тело запроса" -// @Success 200 {object} domain.Role -// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует" -// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" -// @Failure 500 {object} apierrors.Error -// @Router /role/update [POST] +// +// @Tags role +// @Summary Обновить роль +// @Description Обновить данные существующую роль +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.UpdateRoleRequest true "Тело запроса" +// @Success 200 {object} domain.Role +// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует" +// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует" +// @Failure 500 {object} apierrors.Error +// @Router /role/update [POST] func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) { adminId, err := getAdminId(r) if err != nil { @@ -111,17 +113,18 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h } // DeleteRole -// @Tags role -// @Summary Удалить роль -// @Description Удалить существующую роль -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.DeleteRoleRequest true "Тело запроса" -// @Success 200 -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /role/delete [POST] +// +// @Tags role +// @Summary Удалить роль +// @Description Удалить существующую роль +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.DeleteRoleRequest true "Тело запроса" +// @Success 200 +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /role/delete [POST] func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error { adminId, err := getAdminId(r) if err != nil { diff --git a/controller/secure.go b/controller/secure.go index 4b78e0a..f804902 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -25,15 +25,16 @@ func NewSecure(service SecureService) Secure { } // Authenticate -// @Tags secure -// @Summary Метод аутентификации токена -// @Description Проверяет токен и возвращает идентификатор администратора -// @Accept json -// @Produce json -// @Param body body domain.SecureAuthRequest true "Тело запроса" -// @Success 200 {object} domain.SecureAuthResponse -// @Failure 500 {object} apierrors.Error -// @Router /secure/authenticate [POST] +// +// @Tags secure +// @Summary Метод аутентификации токена +// @Description Проверяет токен и возвращает идентификатор администратора +// @Accept json +// @Produce json +// @Param body body domain.SecureAuthRequest true "Тело запроса" +// @Success 200 {object} domain.SecureAuthResponse +// @Failure 500 {object} apierrors.Error +// @Router /secure/authenticate [POST] func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) { adminId, err := s.service.Authenticate(ctx, req.Token) switch { @@ -61,15 +62,16 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) } // Authorize -// @Tags secure -// @Summary Метод авторизации для администратора -// @Description Проверяет наличие у администратора необходимого разрешения -// @Accept json -// @Produce json -// @Param body body domain.SecureAuthzRequest true "Тело запроса" -// @Success 200 {object} domain.SecureAuthzResponse -// @Failure 500 {object} apierrors.Error -// @Router /secure/authorize [POST] +// +// @Tags secure +// @Summary Метод авторизации для администратора +// @Description Проверяет наличие у администратора необходимого разрешения +// @Accept json +// @Produce json +// @Param body body domain.SecureAuthzRequest true "Тело запроса" +// @Success 200 {object} domain.SecureAuthzResponse +// @Failure 500 {object} apierrors.Error +// @Router /secure/authorize [POST] func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) { ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission) if err != nil { diff --git a/controller/session.go b/controller/session.go index eb0fda6..bd89666 100644 --- a/controller/session.go +++ b/controller/session.go @@ -22,16 +22,17 @@ func NewSession(service SessionService) Session { } // All -// @Tags session -// @Summary Получение списка сессий -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.SessionPageRequest true "Тело запроса" -// @Success 200 {object} domain.SessionResponse -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /session/all [POST] +// +// @Tags session +// @Summary Получение списка сессий +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.SessionPageRequest true "Тело запроса" +// @Success 200 {object} domain.SessionResponse +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /session/all [POST] func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) { if req.Order == nil { req.Order = &domain.OrderParams{ @@ -44,16 +45,17 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai } // Revoke -// @Tags session -// @Summary Отзыв сессии -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.RevokeRequest true "Тело запроса" -// @Success 200 -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /session/revoke [POST] +// +// @Tags session +// @Summary Отзыв сессии +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.RevokeRequest true "Тело запроса" +// @Success 200 +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /session/revoke [POST] func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error { return c.service.Revoke(ctx, req.Id) } diff --git a/controller/ui_settings.go b/controller/ui_settings.go index b2e1e2b..bc13f2b 100644 --- a/controller/ui_settings.go +++ b/controller/ui_settings.go @@ -24,17 +24,18 @@ func NewUiSettings(service UiSettingsService) UiSettings { } // UiOauthSettings -// @Tags ui_settings -// @Summary Получение настроек для ui для авторизации через OAuth -// @Description Получение настроек для ui для авторизации через OAuth -// @Accept json -// @Produce json -// @Param body body domain.ClientNameRequest true "Тело запроса" -// @Success 200 {object} domain.UiOauthSetting -// @Failure 400 {object} apierrors.Error -// @Failure 401 {object} apierrors.Error "Неизвестное название клиента" -// @Failure 500 {object} apierrors.Error -// @Router /ui_settings/oauth [POST] +// +// @Tags ui_settings +// @Summary Получение настроек для ui для авторизации через OAuth +// @Description Получение настроек для ui для авторизации через OAuth +// @Accept json +// @Produce json +// @Param body body domain.ClientNameRequest true "Тело запроса" +// @Success 200 {object} domain.UiOauthSetting +// @Failure 400 {object} apierrors.Error +// @Failure 401 {object} apierrors.Error "Неизвестное название клиента" +// @Failure 500 {object} apierrors.Error +// @Router /ui_settings/oauth [POST] func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) { resp, err := c.service.OauthSettings(ctx, req) switch { diff --git a/controller/user.go b/controller/user.go index 4234993..4834b02 100644 --- a/controller/user.go +++ b/controller/user.go @@ -34,17 +34,18 @@ func NewUser(userService userService) User { } // GetProfile -// @Tags user -// @Summary Получить профиль -// @Description Получить данные профиля -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 {object} domain.AdminUserShort -// @Failure 401 {object} apierrors.Error "Невалидный токен" -// @Failure 404 {object} apierrors.Error "Пользователя не существует" -// @Failure 500 {object} apierrors.Error -// @Router /user/get_profile [POST] +// +// @Tags user +// @Summary Получить профиль +// @Description Получить данные профиля +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Success 200 {object} domain.AdminUserShort +// @Failure 401 {object} apierrors.Error "Невалидный токен" +// @Failure 404 {object} apierrors.Error "Пользователя не существует" +// @Failure 500 {object} apierrors.Error +// @Router /user/get_profile [POST] func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) { adminId, err := getAdminId(r) if err != nil { @@ -65,17 +66,18 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse } // GetUsers -// @Tags user -// @Summary Список пользователей -// @Description Получить список пользователей -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.UsersPageRequest true "Тело запроса" -// @Success 200 {object} domain.UsersResponse -// @Failure 400 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /user/get_users [POST] +// +// @Tags user +// @Summary Список пользователей +// @Description Получить список пользователей +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.UsersPageRequest true "Тело запроса" +// @Success 200 {object} domain.UsersResponse +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error +// @Router /user/get_users [POST] func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) { if req.Order == nil { req.Order = &domain.OrderParams{ @@ -93,16 +95,17 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai } // GetAllUsers -// @Tags user -// @Summary Список пользователей -// @Description Получить список пользователей -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 {object} domain.UsersResponse -// @Failure 400 {object} apierrors.Error -// @Failure 500 {object} apierrors.Error -// @Router /user/get_all_users [POST] +// +// @Tags user +// @Summary Список пользователей +// @Description Получить список пользователей +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Success 200 {object} domain.UsersResponse +// @Failure 400 {object} apierrors.Error +// @Failure 500 {object} apierrors.Error +// @Router /user/get_all_users [POST] func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { users, err := u.userService.GetAllUsers(ctx) if err != nil { @@ -113,18 +116,19 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { } // CreateUser -// @Tags user -// @Summary Создать пользователя -// @Description Создать пользователя -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.CreateUserRequest true "Тело запроса" -// @Success 200 {object} domain.User -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" -// @Failure 500 {object} apierrors.Error -// @Router /user/create_user [POST] +// +// @Tags user +// @Summary Создать пользователя +// @Description Создать пользователя +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.CreateUserRequest true "Тело запроса" +// @Success 200 {object} domain.User +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" +// @Failure 500 {object} apierrors.Error +// @Router /user/create_user [POST] func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) { adminId, err := getAdminId(r) if err != nil { @@ -143,19 +147,20 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h } // UpdateUser -// @Tags user -// @Summary Обновить пользователя -// @Description Обновить данные существующего пользователя -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.UpdateUserRequest true "Тело запроса" -// @Success 200 {object} domain.User -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует" -// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" -// @Failure 500 {object} apierrors.Error -// @Router /user/update_user [POST] +// +// @Tags user +// @Summary Обновить пользователя +// @Description Обновить данные существующего пользователя +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.UpdateUserRequest true "Тело запроса" +// @Success 200 {object} domain.User +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует" +// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует" +// @Failure 500 {object} apierrors.Error +// @Router /user/update_user [POST] func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) { adminId, err := getAdminId(r) if err != nil { @@ -178,17 +183,18 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h } // DeleteUser -// @Tags user -// @Summary Удалить пользователя -// @Description Удалить существующего пользователя -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.IdentitiesRequest true "Тело запроса" -// @Success 200 {object} domain.DeleteResponse -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /user/delete_user [POST] +// +// @Tags user +// @Summary Удалить пользователя +// @Description Удалить существующего пользователя +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.IdentitiesRequest true "Тело запроса" +// @Success 200 {object} domain.DeleteResponse +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /user/delete_user [POST] func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) { adminId, err := getAdminId(r) if err != nil { @@ -204,16 +210,17 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques } // Block -// @Tags user -// @Summary Метод блокировки/разблокировки пользователя -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.IdRequest true "Тело запроса" -// @Success 200 -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /user/block_user [POST] +// +// @Tags user +// @Summary Метод блокировки/разблокировки пользователя +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.IdRequest true "Тело запроса" +// @Success 200 +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /user/block_user [POST] func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error { adminId, err := getAdminId(r) if err != nil { @@ -228,30 +235,32 @@ func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Re } // GetById -// @Tags user -// @Summary Метод получения данных по пользователю -// @Accept json -// @Produce json -// @Param body body domain.IdRequest true "Тело запроса" -// @Success 200 {object} domain.User -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" -// @Failure 500 {object} apierrors.Error -// @Router /user/get_by_id [POST] +// +// @Tags user +// @Summary Метод получения данных по пользователю +// @Accept json +// @Produce json +// @Param body body domain.IdRequest true "Тело запроса" +// @Success 200 {object} domain.User +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" +// @Failure 500 {object} apierrors.Error +// @Router /user/get_by_id [POST] func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) { return u.userService.GetById(ctx, identities.UserId) } // ChangePassword -// @Tags user -// @Summary Метод изменения пароля пользователя -// @Accept json -// @Produce json -// @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Param body body domain.ChangePasswordRequest true "Тело запроса" -// @Success 200 -// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль" -// @Failure 500 {object} apierrors.Error "Внутренняя ошибка" -// @Router /user/change_password [POST] +// +// @Tags user +// @Summary Метод изменения пароля пользователя +// @Accept json +// @Produce json +// @Param X-AUTH-ADMIN header string true "Токен администратора" +// @Param body body domain.ChangePasswordRequest true "Тело запроса" +// @Success 200 +// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль" +// @Failure 500 {object} apierrors.Error "Внутренняя ошибка" +// @Router /user/change_password [POST] func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error { adminId, err := getAdminId(r) if err != nil { diff --git a/docs/swagger.json b/docs/swagger.json index 2c2b503..a13951b 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -279,7 +279,7 @@ "application/json" ], "produces": [ - "application/json" + "text/csv" ], "tags": [ "Download" @@ -578,7 +578,7 @@ "application/json" ], "produces": [ - "application/json" + "text/csv" ], "tags": [ "Download" @@ -794,7 +794,7 @@ "application/json" ], "produces": [ - "application/json" + "text/csv" ], "tags": [ "Download" @@ -1141,7 +1141,7 @@ "application/json" ], "produces": [ - "application/json" + "text/csv" ], "tags": [ "Download" diff --git a/domain/errors.go b/domain/errors.go index 416c46d..fe5d62b 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -26,8 +26,7 @@ var ( ErrUnknownClient = errors.New("unknown client") ) -// nolint:gochecknoglobals -var ( +const ( UnknownAuditEventErrorCode = 601 ErrOauthAuthorizationCode = 602 ErrUnauthenticatedCode = 603 diff --git a/main.go b/main.go index 8dea5e8..e868859 100644 --- a/main.go +++ b/main.go @@ -12,14 +12,14 @@ import ( var version = "1.0.0" -// @title isp-admin-service -// @version 1.0.0 -// @description сервис управления администраторами +// @title isp-admin-service +// @version 1.0.0 +// @description сервис управления администраторами -// @license.name GNU GPL v3.0 +// @license.name GNU GPL v3.0 -// @host localhost:9000 -// @BasePath /api/admin +// @host localhost:9000 +// @BasePath /api/admin //go:generate swag init -pd -ot json -eot json func main() { diff --git a/service/permission.go b/service/permission.go index 1d2a79d..63a3bf9 100644 --- a/service/permission.go +++ b/service/permission.go @@ -11,12 +11,12 @@ type Permission struct { permissions []domain.Permission } -func NewPermission(permissions []conf.Permission) *Permission { - return &Permission{ +func NewPermission(permissions []conf.Permission) Permission { + return Permission{ permissions: toDomain(permissions), } } -func (s *Permission) All(_ context.Context) []domain.Permission { +func (s Permission) All(_ context.Context) []domain.Permission { return s.permissions } From e2af9c4978197eaadd8dccc5cd979d3aadcbcf1b Mon Sep 17 00:00:00 2001 From: chashintv Date: Mon, 23 Nov 2026 13:26:29 +0300 Subject: [PATCH 13/13] MSP-8974 fix --- controller/role.go | 4 +-- docs/swagger.json | 18 ------------ service/download.go | 4 +-- tests/role_filter_test.go | 58 ++++++++++++++++++++------------------- 4 files changed, 34 insertions(+), 50 deletions(-) diff --git a/controller/role.go b/controller/role.go index fd0fa6b..f2753b4 100644 --- a/controller/role.go +++ b/controller/role.go @@ -39,8 +39,8 @@ func NewRole(roleService roleService) Role { // @Failure 400 {object} apierrors.Error // @Failure 500 {object} apierrors.Error // @Router /role/all [POST] -func (u Role) All(ctx context.Context) ([]domain.Role, error) { - users, err := u.roleService.All(ctx) +func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) { + users, err := u.roleService.All(ctx, req) if err != nil { return nil, errors.WithMessage(err, "get roles") } diff --git a/docs/swagger.json b/docs/swagger.json index a13951b..06357ff 100644 --- a/docs/swagger.json +++ b/docs/swagger.json @@ -427,15 +427,6 @@ "name": "X-AUTH-ADMIN", "in": "header", "required": true - }, - { - "description": "Тело запроса", - "name": "body", - "in": "body", - "required": true, - "schema": { - "$ref": "#/definitions/domain.RoleAllRequest" - } } ], "responses": { @@ -1991,15 +1982,6 @@ } } }, - "domain.RoleAllRequest": { - "type": "object", - "properties": { - "applicationGroup": { - "description": "Фильтр по группе приложений", - "type": "string" - } - } - }, "domain.SecureAuthRequest": { "type": "object", "properties": { diff --git a/service/download.go b/service/download.go index d6a68ad..5273650 100644 --- a/service/download.go +++ b/service/download.go @@ -178,7 +178,7 @@ func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest return errors.WithMessage(err, "get users") } - roles, err := s.roleService.All(ctx) + roles, err := s.roleService.All(ctx, domain.RoleAllRequest{}) if err != nil { return errors.WithMessage(err, "get roles") } @@ -217,7 +217,7 @@ func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest } func (s Download) DownloadRoles(ctx context.Context, w http.ResponseWriter) error { - roles, err := s.roleService.All(ctx) + roles, err := s.roleService.All(ctx, domain.RoleAllRequest{}) if err != nil { return errors.WithMessage(err, "get roles") } diff --git a/tests/role_filter_test.go b/tests/role_filter_test.go index 5c6147a..a878fd2 100644 --- a/tests/role_filter_test.go +++ b/tests/role_filter_test.go @@ -1,6 +1,7 @@ package tests_test import ( + "net/http" "strconv" "testing" "time" @@ -13,13 +14,10 @@ import ( "github.com/stretchr/testify/suite" "github.com/txix-open/isp-kit/dbx" "github.com/txix-open/isp-kit/errors" - "github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test/dbt" - "github.com/txix-open/isp-kit/test/grpct" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" + "github.com/txix-open/isp-kit/test/httpt" ) func TestRoleTestSuite(t *testing.T) { @@ -32,7 +30,7 @@ type RoleTestSuite struct { test *test.Test db *dbt.TestDb - grpcCli *client.Client + httpCli *httpcli.Client adminId int64 } @@ -48,11 +46,11 @@ func (s *RoleTestSuite) SetupTest() { Config(s.T().Context(), remote, time.Minute) s.Require().NoError(err) - server, apiCli := grpct.TestServer(testInstance, cfg.Handler) - s.grpcCli = apiCli + server, apiCli := httpt.TestServer(testInstance, cfg.Handler) + s.httpCli = apiCli testInstance.T().Cleanup(func() { - server.Shutdown() + server.Close() }) roleId := InsertRole(s.db, entity.Role{ @@ -79,7 +77,8 @@ func (s *RoleTestSuite) TestAllRolesWithoutFilter() { InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"}) roles := []domain.Role{} - s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{}, &roles)) + _, err := s.request("admin/role/all", domain.RoleAllRequest{}, &roles) + s.Require().NoError(err) groups := make(map[string]string, len(roles)) for _, role := range roles { @@ -94,12 +93,10 @@ func (s *RoleTestSuite) TestAllRolesWithoutFilter() { func (s *RoleTestSuite) TestAllRolesInvalidArgument() { roles := []domain.Role{} - err := s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles) + statusCode, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles) s.Require().Error(err) - st, ok := status.FromError(err) - s.Require().True(ok) - s.Require().Equal(codes.InvalidArgument, st.Code()) + s.Require().Equal(http.StatusBadRequest, statusCode) s.Require().Empty(roles) } @@ -108,30 +105,34 @@ func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() { InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"}) roles := []domain.Role{} - s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)) + _, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles) + s.Require().NoError(err) s.Require().Len(roles, 1) s.Require().Equal("groupA", roles[0].ApplicationGroup) roles = []domain.Role{} - s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)) + _, err = s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles) + s.Require().NoError(err) s.Require().Empty(roles) } func (s *RoleTestSuite) TestCreateRoleApplicationGroup() { role := domain.Role{} - s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{ + _, err := s.request("admin/role/create", domain.CreateRoleRequest{ Name: "role_new", ApplicationGroup: "group", Permissions: []string{}, - }, &role)) + }, &role) + s.Require().NoError(err) roleEmpty := domain.Role{} - s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{ + _, err = s.request("admin/role/create", domain.CreateRoleRequest{ Name: "role_empty", Permissions: []string{}, - }, &roleEmpty)) + }, &roleEmpty) + s.Require().NoError(err) s.Require().Equal("role_new", role.Name) s.Require().Equal("group", role.ApplicationGroup) @@ -146,26 +147,27 @@ func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() { }) role := domain.Role{} - s.Require().NoError(s.invoke("admin/role/update", domain.UpdateRoleRequest{ + _, err := s.request("admin/role/update", domain.UpdateRoleRequest{ Id: int(roleId), Name: "role_new", ApplicationGroup: "group_new", Permissions: []string{}, - }, &role)) - + }, &role) + s.Require().NoError(err) s.Require().Equal("role_new", role.Name) s.Require().Equal("group_new", role.ApplicationGroup) } -func (s *RoleTestSuite) invoke(path string, req, resp any) error { - err := s.grpcCli.Invoke(path). +func (s *RoleTestSuite) request(path string, req, resp any) (int, error) { + err := s.httpCli.Post(path). JsonRequestBody(req). JsonResponseBody(resp). - AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))). - Do(s.T().Context()) + StatusCodeToError(). + Header(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))). + DoWithoutResponse(s.T().Context()) if err != nil { - return errors.WithMessagef(err, "invoke %s", path) + return http.StatusBadRequest, errors.WithMessagef(err, "request %s", path) } - return nil + return http.StatusOK, nil }