From fa8bc6c1b7168dbe929d6348a96deb26678ec70f Mon Sep 17 00:00:00 2001 From: chashintv Date: Thu, 19 Nov 2026 15:41:50 +0300 Subject: [PATCH] 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